/*
  SpeedTestView.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  dashboard.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/**
 * KineticJS JavaScript Framework v4.3.3
 * http://www.kineticjs.com/
 * Copyright 2013, Eric Rowell
 * Licensed under the MIT or GPL Version 2 licenses.
 * Date: Feb 12 2013
 *
 * Copyright (C) 2011 - 2013 by Eric Rowell
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/** @license
 * RequireJS plugin for async dependency load like JSONP and Google Maps
 * Author: Miller Medeiros
 * Version: 0.1.1 (2011/11/17)
 * Released under the MIT license
 */

/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version: 3.1.6
 *
 * Requires: jQuery 1.2.2+
 */

/*
 * heatmap.js v2.0.0 | JavaScript Heatmap Library
 *
 * Copyright 2008-2014 Patrick Wied <heatmapjs@patrick-wied.at> - All rights reserved.
 * Dual licensed under MIT and Beerware license 
 *
 * :: 2014-10-31 21:16
 */

/*
* heatmap.js gmaps overlay
*
* Copyright (c) 2014, Patrick Wied (http://www.patrick-wied.at)
* Dual-licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and the Beerware (http://en.wikipedia.org/wiki/Beerware) license.
*/

/*!
 * jQuery Validation Plugin 1.12.0pre
 *
 * http://jqueryvalidation.org//
 *
 * Copyright 2013 Jörn Zaefferer
 * Released under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 */

/*
  map.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  devices.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  FormView.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  gateways.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  switches.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  phones.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  AddDeviceView.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  devices/IndexView.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  clients.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  calls.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  app.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  statistics.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  insights.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  switchstatsview.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  remoteuservpnstats.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  support.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

/*
  ubnt.layout.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 
  To be used to add draggable handles to each layout panel and
  also to resize a panel manually. Each panel can be dragged
  from one or more directions (north, south, east or west) and
  can trigger the resize of other panels at the same time (eg. if
  one panel should expand while another collapses).
 
  Usage:
    //initialize the east column to have a handler on the west to change its width
    $('#columnEast').layout({
      'directions': {
        'west': {                                            //add a handle to the west side
          'draggable': true,                                 //allow the panel to be dragged to resize
          'property': 'width',                               //resize the panel's width attribute
          'also': [{
            'element': $('#columnMain > .content'),          //also resize this element
            'property': 'margin-right',                      //resize this element's margin-right
            'inverse': false                                 //don't resize inversely to the main panel
          }]
        }
      }
    });
 
    //resize the east column (using the west handler config) to be 30 pixels wider
    $('#columnEast').layout('resize', 'west', 30, true);
 
    //resize the west column (using the east handler config) to a dynamic value and animate the transition
    $('#columnWest').layout('resize', 'east', function() {
      var left = $('#columnEast').offset().left;
      return left ? left : $(window).width();
    }, false, { duration: 350 });
 */

/*
  ubnt.panel.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 
  An extenstion of the ubnt.layout.js plugin that treats each
  layout element as a panel that can be toggled on or off using
  one or more buttons. A panel toggled to off is completely
  gone, not just minimized.
 
  Usage:
    //initialize the east column to have a handler on the west to change its width
    $('#columnEast').layout({
      'duration': 350,                                       //the duration for the panel show/hide animation
      'directions': {
        'west': {                                            //add a handle to the west side
          'draggable': true,                                 //allow the panel to be dragged to resize
          'property': 'width',                               //resize the panel's width attribute
          'also': [{
            'element': $('#columnMain > .content'),          //also resize this element
            'property': 'margin-right',                      //resize this element's margin-right
            'inverse': false                                 //don't resize inversely to the main panel
          }],
          buttons: [                                         //the button(s) to toggle the east column
            $('#toggleEast')
          ]
        }
      }
    });
 */

/*
  store.js
  Copyright 2015 Ubiquiti Networks, Inc. All rights reserved.
 */

define("text!includes/dashboard/dashboardTableItemTemplate.html",[],function(){return'<div class="unknown <%- subsystem %> table-item">\n    <div class="header">\n        <div class="icon <%- icon %>"></div>\n        <%- subsystem.toUpperCase() %>\n    </div>\n    <div class="current-state">\n        <div class="state">\n            <%- msg.G_DashboardNoDataAvailable %>\n        </div>\n    </div>\n    <div class="stats"></div>\n    <div class="no-data"><%- msg.G_DashboardNoDataAvailable %></div>\n    <div class="footer">\n        <% if(statsLink) { %>\n        <div class="link left btn-stats">\n            <div class="button-hover sprite-button-hover"></div>\n            <div class="icon ubnt-icon-histogram"></div>\n        </div>\n        <% } %>\n        <% if(configureLink) { %>\n            <div class="link right btn-configure">\n                <div class="button-hover sprite-button-hover"></div>\n                <div class="icon ubnt-icon-wrench"></div>\n            </div>\n        <% } %>\n    </div>\n</div>\n'}),define("text!includes/dashboard/dashboardStatRowTemplate.html",[],function(){return'<div class="row">\n    <div class="stat-name"><%- name %></div>\n    <div class="stat-value stat-value-<%- name.replace(/\\s/g, \'-\') %>"><%- value %></div>\n</div>'}),define("unifi/model/Subsystem",["unifi/model/Model","underscore","jquery","ubnt/backgrid"],function(e,t,n,r){"use strict";return e.extend({notifications:0,possibleStates:["ok","unknown","warning","error"],state:function(){return this.get("status")},icon:function(){switch(this.get("subsystem")){case"www":return"ubnt-icon-globe";case"wan":return"ubnt-icon-lock";case"lan":return"ubnt-icon-files";case"wlan":return"ubnt-icon-wifi";case"voip":return"ubnt-icon-dial"}},stats:function(){var e=[],t=[],i=[],s,o,u,a,f,l;switch(this.get("subsystem")){case"www":var c=this.get("ip"),h=this.get("nameservers"),p=this.get("uptime");l=this.get("gateways"),c&&i.push({name:"IP",value:this.get("ip")}),n.isArray(l)&&l.length>0&&i.push({name:"GATEWAY",value:this.get("gateways").join(" ")}),n.isArray(h)&&h.length>0&&i.push({name:"DNS",value:this.get("nameservers").join(" ")});if(p){if(this.has("latency")){var d=this.get("latency");i.push({name:"LATENCY",value:(d<=1?"<1":d)+" ms"})}i.push({name:"UPTIME",value:r.Formatters.Seconds.fromRaw(p)})}return i;case"wan":var v=this.get("num_gateway"),m=this.get("num_sta");u=this.get("tx_bytes-r"),a=this.get("rx_bytes-r");if(v!==undefined||m!==undefined||a!==undefined||u!==undefined)return[{name:"LAN IP",value:this.get("lan_ip")},{name:"CLIENTS",value:m},{name:"DOWN",value:r.Formatters.BytesPerSecond.fromRaw(a)||0},{name:"UP",value:r.Formatters.BytesPerSecond.fromRaw(u)||0}];return null;case"lan":var g=this.get("num_sw");f=this.get("num_adopted"),l=this.get("gateways"),s=this.get("num_user"),o=this.get("num_guest"),a=this.get("tx_bytes-r"),u=this.get("rx_bytes-r");if(g!==undefined||o!==undefined||a!==undefined||u!==undefined)return i=[{name:"SWITCHES",value:g==f?g:g+" / "+f},{name:"USERS",value:s},{name:"GUESTS",value:o}],n.isArray(l)&&l.length>0&&i.push({name:"DOWN",value:r.Formatters.BytesPerSecond.fromRaw(a)||0},{name:"UP",value:r.Formatters.BytesPerSecond.fromRaw(u)||0}),i;return null;case"wlan":var y=this.get("num_ap");f=this.get("num_adopted"),s=this.get("num_user"),o=this.get("num_guest"),a=this.get("tx_bytes-r"),u=this.get("rx_bytes-r");if(y!==undefined||s!==undefined||o!==undefined||a!==undefined||u!==undefined)return[{name:"APS",value:y==f?y:y+" / "+f},{name:"USERS",value:s},{name:"GUESTS",value:o},{name:"DOWN",value:r.Formatters.BytesPerSecond.fromRaw(a)||0},{name:"UP",value:r.Formatters.BytesPerSecond.fromRaw(u)||0}];return null;case"voip":var b=this.get("num_phone");return f=this.get("num_adopted"),[{name:"PHONES",value:b==f?b:b+" / "+f},{name:"EXTENSIONS",value:this.get("num_extension")||0}]}}})}),define("unifi/view/dashboard/LayerView",["unifi/view/dashboard/LayerView","backbone","underscore","jquery","text!includes/dashboard/dashboardTableItemTemplate.html","text!includes/dashboard/dashboardStatRowTemplate.html","msg/Msg","unifi/model/Subsystem"],function(e,t,n,r,i,s,o,u){"use strict";return t.View.extend({initialize:function(e){n.bindAll(this),this.dashboardTable=r("#dashboardTable"),this.tableItemTemplate=n.template(i),this.model=e.model,this.app=e.app,this.$notifications=this.$(".drop-count").on("click",this.viewNotifications),this.$el.on("mouseover",this.mouseoverLayer),this.$el.on("mouseout",this.mouseoutLayer),this.render()},render:function(){var e=this.model.get("subsystem");return!this.rendered&&(this.rendered=!0)&&(this.dashboardTable.append(this.tableItemTemplate(n.extend(this.model.toJSON(),{icon:this.model.icon(),stats:this.model.stats(),state:this.model.state(),configureLink:n.isFunction(this.model.get("configureLink")),statsLink:n.isFunction(this.model.get("statsLink")),msg:o}))),this.configureLink=this.model.get("configureLink"),this.statsLink=this.model.get("statsLink"),this.$tableItem=this.dashboardTable.find(".table-item."+e),this.$tableItem.on("mouseover",this.mouseoverLayer),this.$tableItem.on("mouseout",this.mouseoutLayer),this.$tableItem.find(".btn-stats").on("click",this.clickStats),this.$tableItem.find(".btn-configure").on("click",this.clickConfigure),this.updateNotifications(),this.updateState()),this},update:function(e){this.model&&e&&(this.model.clear({silent:!0}),this.model=new u(e.toJSON())),this.updateState(),this.updateStats(),this.updateNotifications()},updateState:function(){var e=this.model.state(),t=this.model.possibleStates;this.$el.removeClass(t.join(" ")).addClass(e),this.$tableItem.removeClass(t.join(" ")).addClass(e);var n=this.$tableItem.find(".state");n.removeClass(t.join(" ")).addClass(e),n.text(o[this.model.get("status_text")])},updateStats:function(){var e=this.model.stats(),t=this.$tableItem.find(".stats"),r=this.$tableItem.find(".no-data");e?(t.empty().removeClass("hidden"),r.addClass("hidden"),n.each(e,function(e){t.append(n.template(s,e))},this)):(t.empty().addClass("hidden"),r.removeClass("hidden"));if(this.model.get("subsystem")==="wan"){var i=this.model.get("gw_mac")?!0:!1;this.$tableItem.find(".btn-configure").toggle(i)}},updateNotifications:function(){var e=n.size(this.model.get("notifications"));e>0?this.showNotifications():this.hideNotifications();var t=this.$notifications.find(".count");parseInt(t.text(),10)<e&&this.$notifications.effect("shake",{direction:"up",times:1,distance:5},300),t.text(e)},showNotifications:function(){this.$notifications.show()},hideNotifications:function(){this.$notifications.hide()},viewNotifications:function(){var e=this.model.get("subsystem"),t=r("#panelAlerts"),n=t.is(":visible");n||r("#toggleAlerts").click(),t.find(".data-filters").find('input[value="'+e+'"]').click()},mouseoverLayer:function(){this.$el.addClass("over"),this.$tableItem.addClass("over")},mouseoutLayer:function(){this.$el.removeClass("over"),this.$tableItem.removeClass("over")},clickStats:function(){return this.statsLink&&this.statsLink.call(this),!1},clickConfigure:function(){return this.configureLink&&this.configureLink.call(this),!1},remove:function(){this.$(".drop-count").off("click",this.viewNotifications),this.$el.off("mouseover",this.mouseoverLayer),this.$el.off("mouseout",this.mouseoutLayer),this.rendered=!1,t.View.prototype.remove.apply(this,arguments)}})}),define("unifi/collection/Subsystems",["unifi/collection/Collection","backbone","unifi/model/Subsystem","ubnt/backgrid"],function(e,t,n,r){"use strict";return e.extend({model:n,bySite:!0,possibleSubsystems:["www","wan","lan","wlan","voip"],url:function(){return"/api/s/"+SITE.name+"/stat/health"},getSubsystem:function(e){return this.findWhere({subsystem:e})}})}),define("unifi/model/SpeedTest",["unifi/model/Model","backbone","underscore","msg/Msg","libs/moment"],function(e,t,n,r,i){"use strict";return e.extend({isTesting:!1,speedtestIndex:1,speedtestMaxIndex:11,download_id:0,upload_id:0,download_array:[],upload_array:[],download_arrayIndex:0,upload_arrayIndex:0,download_value:0,upload_value:0,sync:function(e,n,r){var i=this,s=[];r=r||{},r._method&&(e=r._method,delete r._method);switch(e){case"read":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/cmd/devmgr",this.isTesting&&(r.url="/data/speedtest/"+this.speedtestIndex+".json"),r.type="POST",r.data=JSON.stringify({cmd:"speedtest-status"});if(this.getStatus("download")===1){if(this.download_arrayIndex<this.download_array.length){s=this.download_array[this.download_arrayIndex];if(s===undefined){this._increaseTestIndex();break}this.download_value=s[1]/100,this.set("xput_download",this.download_value),this.download_arrayIndex++;return}this._increaseTestIndex();break}if(this.getStatus("upload")===1){if(this.upload_arrayIndex<this.upload_array.length){s=this.upload_array[this.upload_arrayIndex];if(s===undefined){this._increaseTestIndex();break}this.upload_value=s[1]/100,this.set("xput_upload",this.upload_value),this.upload_arrayIndex++;return}this._increaseTestIndex();break}this._increaseTestIndex();break;case"start":this.initializeProgressRecords(),r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/cmd/devmgr",r.type="POST",r.data=JSON.stringify({cmd:"speedtest"})}return t.sync.call(this,e,n,r)},_increaseTestIndex:function(){this.isTesting&&(this.speedtestIndex++,this.speedtestIndex>this.speedtestMaxIndex&&(this.speedtestIndex=1))},clearArray:function(e){while(e.length)e.pop()},initializeProgressRecords:function(){var e=this;n.each(["download","upload"],function(t){e[t+"_id"]=0,e[t+"_value"]=0,e[t+"_arrayIndex"]=0,e.clearArray(e[t+"_array"])})},getStatus:function(e){return e?this.get("status_"+e):this.get("summary_status")},getResult:function(e){switch(e){case"ping":return this.getPing();case"download":return this.getDownloadSpeed();case"upload":return this.getUploadSpeed()}},getPing:function(){return parseInt(this.get("latency")||0,10)},getUploadSpeed:function(){return parseFloat(this.upload_value||this.get("xput_upload")||0).toFixed(2)},getDownloadSpeed:function(){return parseFloat(this.download_value||this.get("xput_download")||0).toFixed(2)},getLastRun:function(){return i(this.get("rundate"),"X").format("YYYY/MM/DD HH:mm:ss")},getProgressRecords:function(){var e=this,t=[];n.each(["download","upload"],function(r){t=e.get(r+"-progress"),n.each(t,function(t){t.id>e[r+"_id"]&&(e[r+"_id"]=t.id,e[r+"_array"]=e[r+"_array"].concat(t.records))})})},convertToMbps:function(e){return e/100},convertMbpsToPercentage:function(e,t){var n=this.convertToMbps(e);return n>t&&(n=t),n/t*100}})}),define("unifi/model/Event",["unifi/model/Model","underscore"],function(e,t){"use strict";return e.extend({toSearch:function(){var e={},n,r;return(n=this.attributes.msg.match(/([a-z0-9\-]{2,})/gi))&&t.each(n,function(t,n){e["word"+n]=t}),(r=this.attributes.msg.match(/(([0-9A-F]{2}:){5}([0-9A-F]{2}))/gi))&&t.each(r,function(t,n){e["mac"+n]=t}),e}})}),define("unifi/model/Alert",["unifi/model/Event","backbone"],function(e,t){"use strict";return e.extend({archive:function(e){return this.sync("archive",this,e)},sync:function(e,n,r){r=r||{};switch(e){case"archive":r.url="/api/s/"+SITE.name+"/cmd/evtmgr",r.contentType="application/json; charset=utf-8",r.type="POST",r.data=JSON.stringify({_id:n.id,cmd:"archive-alarm"})}return t.sync.call(this,e,n,r)}})}),define("unifi/collection/Alerts",["unifi/collection/Collection","backbone","unifi/model/Alert","libs/moment","underscore"],function(e,t,n,r,i){"use strict";return e.extend({model:n,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/list/alarm"},comparator:function(e){return-r(e.get("datetime"))},parse:function(t,n){return i.filter(e.prototype.parse.call(this,t,n),function(e){return!!e.msg})},archiveAll:function(e){return this.sync("archive-all",this,e)},archived:function(e){return this.fetch(i.extend(e,{_method:"read-archived"}))},unarchived:function(e){return this.fetch(i.extend(e,{_method:"read-unarchived"}))},sync:function(e,n,r){r=r||{},r._method&&(e=r._method,delete r._method);switch(e){case"read":r.url="/api/s/"+SITE.name+"/list/alarm",r.contentType="application/json; charset=utf-8",r.type="POST",r.data=JSON.stringify({_sort:"-time"});break;case"read-archived":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/list/alarm",r.type="POST",r.data=JSON.stringify({_sort:"-time",archived:!0});break;case"read-unarchived":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/list/alarm",r.type="POST",r.data=JSON.stringify({_sort:"-time",archived:!1});break;case"archive-all":r.url="/api/s/"+SITE.name+"/cmd/evtmgr",r.contentType="application/json; charset=utf-8",r.type="POST",r.data=JSON.stringify({cmd:"archive-all-alarms"})}return t.sync.call(this,e,n,r)}})}),define("unifi/model/PortModel",["unifi/model/Model","underscore","backbone","msg/Msg","app","ubnt/backgrid"],function(e,t,n,r,i,s){"use strict";return e.extend({diagramClasses:function(){var e=[];return this.get("poe_enable")&&e.push("poe"),this.get("op_mode")=="mirror"&&e.push("mirror"),this.get("enable")||e.push("shutdown"),this.get("up")&&(e.push("up"),this.get("speed")==1e3?e.push("green"):(this.get("speed")==100||this.get("speed")==10)&&e.push("orange"),this.get("stp_state")=="discarding"&&e.push("block")),e.join(" ")},diagramTooltip:function(){var e="<table>",t=this.portIdxText(),n=this.get("name"),i=this.statusText(),o=this.get("tx_bytes")&&s.Formatters.Bytes.fromRaw(this.get("tx_bytes")),u=this.get("rx_bytes")&&s.Formatters.Bytes.fromRaw(this.get("rx_bytes")),a=this.poeModeText(),f=this.networksVlansText(),l='<tr class="table-row"><td class="column-name">{1}</td><td class="column-value">{2}</td></tr>';return t&&(e+=r.localize(l,r.G_Port,t)),n&&(e+=r.localize(l,r.G_Name,n)),i&&(e+=r.localize(l,r.G_Status,i)),o&&(e+=r.localize(l,r.G_DevicesTX,o)),u&&(e+=r.localize(l,r.G_DevicesRX,u)),a&&(e+=r.localize(l,r.G_PropertiesPoE,a)),f&&(e+=r.localize(l,r.G_PropertiesNetworksVLANs,f)),e+="</table>",e},portIdxText:function(){var e=this.get("port_idx");return this.get("masked")?"":(this.get("op_mode")=="aggregate"&&(e+="-"+(parseInt(e,10)+parseInt(this.get("aggregate_num_ports")-1,10))),e)},statusText:function(){if(this.get("up")){var e=this.get("speed");return e+=" ",e+=this.get("full_duplex")?r.G_PropertiesFullDuplexAbbrv:r.G_PropertiesHalfDuplexAbbrv,this.get("is_uplink")&&(e+=" ("+r.G_PropertiesUplink+")"),this.get("stp_state")=="discarding"&&(e+=" ("+r.G_PropertiesBlocked+")"),e}return""},poeModeText:function(){if(!this.get("port_poe"))return"";if(this.get("op_mode")!=="switch"||this.get("masked"))return"";var e=this.get("poe_mode");return e==="auto"&&this.get("poe_enable")?this.get("poe_power")+"w":e==="auto"?r.G_PropertiesPoEModePoEPlus:e==="pasv24"?r.G_PropertiesPoEModePassive:e},networksVlansText:function(){if(this.get("aggregated_by"))return r.G_PropertiesAggregatedByPort+" "+this.get("aggregated_by");if(this.get("op_mode")=="mirror")return r.G_PropertiesMirroringPort+" "+this.get("mirror_port_idx");var e=this.get("portconf_id");if(e){var t=i.collection("PortConf").get(e);if(t)return t.get("name")}}})}),define("unifi/model/Device",["unifi/model/Model","unifi/model/PortModel","jquery","backbone","ubnt/backgrid","msg/Msg","underscore","libs/moment","ubnt/ubnt.ip"],function(e,t,n,r,i,s,o,u){"use strict";return e.extend({typeMap:{gateway:"ugw","switch":"usw",ap:"uap",phone:"uph"},copyConfigMap:{US24:["US24P250","US24P500"],US24P250:["US24","US24P500"],US24P500:["US24","US24P250"],US48:["US48P500","US48P750"],US48P500:["US48","US48P750"],US48P750:["US48","US48P500"]},initialize:function(){this.collections={},this.listenTo(this,"change:port_table",this.syncPortTable),this.listenTo(this,"change:port_overrides",this.syncPortTable),(this.attributes.port_table||this.attributes.type=="usw")&&this.syncPortTable()},validate:function(e,t){var n={},r=t?t.partial:null;r=="advance-adopt"&&(e.username||(n.username=s.localize(s.E_CannotBeEmpty,s.G_UN)),e.password||(n.password=s.localize(s.E_CannotBeEmpty,s.G_PW)));if(e.port_overrides&&t.extra&&t.extra.portidx){var i=o.findWhere(e.port_overrides,{port_idx:t.extra.portidx});if(i){if(i.op_mode=="aggregate"&&(!r||r=="aggregate_num_ports")){var u=t.extra.portidx+1,a=t.extra.portidx+3,f=this.numPorts(),l=4,c=this.get("port_table"),h=c.length;for(var p=t.extra.portidx;p<a;p++)if(p<a){var d=c[p];if(d&&d.op_mode!=="switch"){a=p,l=a-t.extra.portidx+1;break}}a>f&&(a=f,l=a-t.extra.portidx+1),this.validator.range(i.aggregate_num_ports,2,l)||(n.aggregate_num_ports=s.localize(s.E_IncorrectNumberRange,s.G_PropertiesAggregatePorts,u,a))}i.op_mode=="mirror"&&(!r||r=="mirror_port_idx")&&(i.mirror_port_idx==t.extra.portidx||!this.validator.range(i.mirror_port_idx,1,this.numPorts()))&&(n.mirror_port_idx=s.localize(s.E_InvalidMirroringPort,i.mirror_port_idx))}}(!r||r=="config_network_wan")&&e.config_network_wan&&(o.size(n.config_network_wan=this.validateNetwork(e,"config_network_wan"))||delete n.config_network_wan),(!r||r=="config_network")&&e.config_network&&(o.size(n.config_network=this.validateNetwork(e,"config_network"))||delete n.config_network),(!r||r=="wlan_overrides")&&e.wlan_overrides&&(n.wlan_overrides={},o.each(e.wlan_overrides,function(t,r){n.wlan_overrides[r]={};var i;if(e.hasOwnProperty("wlanconf")){var u=e.wlanconf.attributes.vlan_enabled;i=t.hasOwnProperty("vlan_enabled")?t.vlan_enabled:u}else i=t.vlan_enabled;i&&t.vlan===""?n.wlan_overrides[r].vlan=s.localize(s.E_CannotBeEmpty,s.G_PropertiesVLAN):t.vlan&&!this.validator.range(t.vlan,2,4095)&&(n.wlan_overrides[r].vlan=s.localize(s.E_IncorrectNumberRange,s.G_PropertiesVLAN,2,4095)),t.x_passphrase&&!this.validator.password(t.x_passphrase)&&(n.wlan_overrides[r].x_passphrase=s.localize(s.E_InvalidPassphrase,s.G_PropertiesPSK)),o.size(n.wlan_overrides[r])||delete n.wlan_overrides[r]},this),o.size(n.wlan_overrides)||delete n.wlan_overrides),e.name&&!this.validator.name(e.name)&&e.name.toLowerCase()!==e.mac.toLowerCase()&&(n.name=s.localize(s.E_InvalidName,s.G_PropertiesAlias));if(o.size(n))return n},validateNetwork:function(e,t){var n={};switch(e[t].type){case"dhcp":e[t].dns1&&!this.validator.ip(e[t].dns1)&&(n.dns1=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesPreferredDNS)),e[t].dns2&&!this.validator.ip(e[t].dns2)&&(n.dns2=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesAlternateDNS));break;case"pppoe":e[t].username||(n.username=s.localize(s.E_CannotBeEmpty,s.G_UN)),e[t].x_password||(n.x_password=s.localize(s.E_CannotBeEmpty,s.G_PW)),e[t].dns1&&!this.validator.ip(e[t].dns1)&&(n.dns1=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesPreferredDNS)),e[t].dns2&&!this.validator.ip(e[t].dns2)&&(n.dns2=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesAlternateDNS));break;case"static":e[t].ip?this.validator.ip(e[t].ip)||(n.ip=s.localize(s.E_IncorrectIPAddress,s.G_IPAddress)):n.ip=s.localize(s.E_CannotBeEmpty,s.G_IPAddress),e[t].netmask?this.validator.netmask(e[t].netmask,e[t].ip)||(n.netmask=s.localize(s.E_IncorrectNetmask,s.G_Netmask)):n.netmask=s.localize(s.E_CannotBeEmpty,s.G_Netmask),e[t].gateway&&!this.validator.ip(e[t].gateway)&&(n.gateway=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesGateway)),e[t].dns1&&!this.validator.ip(e[t].dns1)&&(n.dns1=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesPreferredDNS)),e[t].dns2&&!this.validator.ip(e[t].dns2)&&(n.dns2=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesAlternateDNS))}return n},parse:function(t,n){return t=e.prototype.parse.call(this,t,n),t&&parseInt(t.state,10)!==0&&(t.restarting=!1),t&&(t.uptime?t.uptime=parseInt(t.uptime,10):t.uptime=0),t},toSearch:function(){var e={name:this.attributes.name,mac:this.attributes.mac,ip:this.attributes.ip,status:this.status(),model:this.apModel(),version:this.attributes.version};return this.attributes.vap_table&&o.each(this.attributes.vap_table,function(t,n){e["bssid_"+n]=t.bssid}),e},name:function(){return this.get("name")||this.get("mac")},ip2long:function(){return n.ip2long(this.get("ip"))},getMacNoColons:function(){return this.get("mac").replace(/:/g,"")},apModel:function(){var e=this.get("model")||"";switch(e){case"BZ2":return"UniFi AP";case"BZ2LR":return"UniFi AP-LR";case"U2S48":return"UniFi AP";case"U2L48":return"UniFi AP-LR";case"U2HSR":return"UniFi AP-Outdoor+";case"U2O":return"UniFi AP-Outdoor";case"U5O":return"UniFi AP-Outdoor 5G";case"U7P":return"UniFi AP-Pro";case"U2M":return"UniFi AP-Mini";case"U7E":return"UniFi AP-AC";case"U7Ev2":return"UniFi AP-AC v2";case"U2Sv2":return"UniFi AP v2";case"U2Lv2":return"UniFi AP-LR v2";case"U7O":return"UniFi AP-AC Outdoor";case"p2N":return"PicoStation M2";case"US24":return"UniFi Switch 24";case"US24P250":return"UniFi Switch 24 POE-250W";case"US24P500":return"UniFi Switch 24 POE-500W";case"US48":return"UniFi Switch 48";case"US48P500":return"UniFi Switch 48 POE-500W";case"US48P750":return"UniFi Switch 48 POE-750W";case"UGW3":return"UniFi Security Gateway 3P";case"UGW8":return"UniFi Security Gateway 8P";case"UP5":return"UniFi Phone";case"UP5t":return"UniFi Phone-Pro";case"UP7":return"UniFi Phone-Executive";case"UP5c":return"UniFi Phone";case"UP5tc":return"UniFi Phone-Pro";case"UP7c":return"UniFi Phone-Executive"}return"UniFi "+e},isAntennaGainEditable:function(){var e=this.get("model")||"",t=["U2O","U5O","U2HSR"];return o.indexOf(t,e)!==-1?!0:!1},apIcon:function(){var e=this.get("model")||"";switch(e){case"U7P":return"ap-pro-icon";default:return"ap-icon"}},numPorts:function(){switch(this.get("model")){case"US24":case"US24P250":case"US24P500":return 26;case"US48":case"US48P500":case"US48P750":return 52;case"UGW3":return 3;case"UGW8":return 8}},txPower:function(){var e=this.transmitPower("ng"),t=this.transmitPower("na");return!o.isUndefined(t)&&!o.isUndefined(e)?e>t?e:t:o.isUndefined(t)?o.isUndefined(e)?undefined:e:t},transmitFrequency:function(e){if(e=="ng"){var t=this.transmitPower("ng"),n=this.get("ng-channel"),r={1:2412,2:2417,3:2422,4:2427,5:2432,6:2437,7:2442,8:2447,9:2452,10:2457,11:2462,12:2467,13:2472,14:2484};if(!o.isUndefined(t))return r[n]}if(e=="na"){var i=this.transmitPower("na"),s=this.get("na-channel"),u={7:5035,8:5040,9:5045,11:5055,12:5060,16:5080,34:5170,36:5180,38:5190,40:5200,42:5210,44:5220,46:5230,48:5240,52:5260,56:5280,60:5300,64:5320,100:5500,104:5520,108:5540,112:5560,116:5580,120:5600,124:5620,128:5640,132:5660,136:5680,140:5700,149:5745,153:5765,157:5785,161:5805,165:5825,183:4915,184:4920,185:4925,187:4935,188:4940,189:4945,192:4960,196:4980};if(!o.isUndefined(i))return u[s]}return undefined},uptime:function(e){return e=e||this.get("uptime"),e>0?i.Formatters.Duration.fromRaw(e||0):""},power:function(){var e=0;return o.each(this.get("port_table"),function(t,n){e+=parseFloat(t.poe_power||0,10)}),e.toFixed(2)},uplink:function(){return this.isConnected()?this.get("uplink"):this.get("last_uplink")||this.get("uplink")},uplinks:function(){return this.get("uplink_table")||{}},uplinkDeviceMac:function(){var e=this.uplink();if(e){var t;e.hasOwnProperty("uplink_mac")?t=e.uplink_mac:e.type==="wireless"&&e.hasOwnProperty("ap_mac")&&(t=e.ap_mac);if(t)return t}return""},uplinkDeviceText:function(){var e=this.uplink();if(e){var t=this.uplinkDeviceMac(),n=this.collection.findWhere({mac:t});return n?n.name()+(e.uplink_remote_port?" #"+e.uplink_remote_port:""):t}return""},uplinkRemotePort:function(){var e=this.uplink();if(e){var t=this.uplinkDeviceMac(),n=this.collection.findWhere({mac:t});if(n&&e.uplink_remote_port)return e.uplink_remote_port}return null},uplinkRssi:function(){var e=this.uplink();if(e)return this.calcRssi(e.rssi)},calcRssi:function(e){return e===undefined&&(e=this.get("rssi")),e=parseFloat(e),e?(e>45?e=45:e<5&&(e=5),e=(e-5)/40*99,(e===0?"0":e.toPrecision(2))+"%"):""},apXRate:function(e){return isNaN(e)?"":parseInt(e,10)/1e3+"M"},uplinkTxRate:function(){var e=this.uplink();return e?this.apXRate(e.tx_rate):""},uplinkRxRate:function(){var e=this.uplink();return e?this.apXRate(e.rx_rate):""},uplinkSpeed:function(){var e=this.uplink();return e?e.speed:"Unknown"},uplinkDuplex:function(){var e=this.uplink();return e&&e.full_duplex?"Full Duplex":"Half Duplex"},uplinkDownPackets:function(){var e=this.uplink();return e&&e.rx_packets&&e.rx_bytes?i.Formatters.Bytes.fromRaw(e.rx_packets)+"/"+i.Formatters.Bytes.fromRaw(e.rx_bytes):"0.00 / 0.00"},uplinkUpPackets:function(){var e=this.uplink();return e&&e.tx_packets&&e.tx_bytes?i.Formatters.Bytes.fromRaw(e.tx_packets)+"/"+i.Formatters.Bytes.fromRaw(e.tx_bytes):"0.00 / 0.00"},uplinkActivity:function(){var e=this.uplink(),t=e?e["tx_bytes-r"]:0,n=e?e["rx_bytes-r"]:0,r=t+n,s=0;return r&&(s=i.Formatters.Bytes.fromRaw(r)),s+"B / sec"},uplinkActivityDown:function(){var e=this.uplink(),t=e?e["rx_bytes-r"]:0,n=0;return t&&(n=i.Formatters.Bytes.fromRaw(t)),n+"B / sec"},uplinkActivityUp:function(){var e=this.uplink(),t=e?e["tx_bytes-r"]:0,n=0;return t&&(n=i.Formatters.Bytes.fromRaw(t)),n+"B / sec"},adoptIp:function(){return this.get("adopt_ip")||this.get("ip")},adoptUrl:function(){return this.get("adopt_url")||this.get("inform_url")||"http://unifi:8080/inform"},downlinks:function(){return this.get("downlink_table")||[]},networks:function(){return this.get("network_table")||[]},getChannel:function(){var e=this.get("ng-channel"),t=this.get("na-channel"),n=[];return e&&n.push(e+" (2G)"),t&&n.push(t+" (5G)"),n.length?n.join(", "):""},apChannel:function(){if(!this.get("vap_table"))return"";var e=[],t,r,i;return i=this.get("model"),o.each(this.get("vap_table"),function(s,o){if(s.channel===0)return!0;if((s.state||"RUN")!="RUN")return!0;r=s.radio,r=="na"&&(i=="U7E"||i=="U7O"||i=="U7Ev2")&&(r="ac"),t=s.channel+" ("+r+")",n.inArray(t,e)<0&&(s.radio=="ng"?e=[t].concat(e):e.push(t))}),e.join(", ")},getRadio:function(e){return o.find(this.get("radio_table"),function(t){if(t.hasOwnProperty("radio"))return t.radio===e})},hasRadio:function(e){return this.getRadio(e)===undefined?!1:!0},channel:function(e){var t=this.get(e+"-state")||"INIT",n=this.get(e+"-extchannel")||0,r=n>0?",+1":n<0?",-1":"",i=this.get(e+"-channel")+r;return"INIT"==t?i="":"DFS_WAIT"==t&&(i+=" (DFS Waiting)"),i},transmitPower:function(e){var t=this.get(e+"-state")||"INIT";if("INIT"==t)return undefined;var n=Math.min(this.get(e+"-tx_power"),30),r=this.get(e+"-gain")||0,i=this.get(e+"-eirp")||parseInt(n,10)+r;return i},packetsPerBytes:function(e,t){var n=this.get("stat"),r=n?n[e+"-"+t+"_packets"]:0,s=n?n[e+"-"+t+"_bytes"]:0;return r=r||0,s=s||0,i.Formatters.Bytes.fromRaw(r)+" / "+i.Formatters.Bytes.fromRaw(s)},errorPercentage:function(e,t){var n=this.get("stat"),r=n?n[e+"-"+t+"_retries"]:0,s=n?n[e+"-"+t+"_packets"]:0,o=n?n[e+"-"+t+"_dropped"]:0,u;return r=r||0,s=s||0,o=o||0,u=s+o,i.Formatters.Percentage.fromRaw(r,u)+" / "+i.Formatters.Percentage.fromRaw(o,u)},getOverride:function(e,t){var n=null,r=this.get("wlan_overrides")||[];return o.each(r,function(r){if(r.wlan_id==e&&r.radio==t)return n=r,!1}),n},hasOverrides:function(e,t){var n=!1,r=this.get("wlan_overrides")||[];return o.each(r,function(e){if(e.radio==t)return n=!0,!1}),n},wlan2G:function(e){return this.wlangroup(this.get("wlangroup_id_ng"),"ng",e)},wlan5G:function(e){return this.wlangroup(this.get("wlangroup_id_na"),"na",e)},wlangroup:function(e,t,n){if(!this.get("adopted")||!this.get("radio_"+t)||!n||!o.size(n))return"";var r=n.findWhere({_id:e})||n.findWhere({attr_hidden_id:"Default"}),i=r.get("name");return r.get("roam_enabled")?i+=" (ZH)":this.hasOverrides(r.get("id"),t)&&(i+=" (*)"),i},radio2G:function(){return this.radioChannelAndPower(this.get("radio_ng"))},radio5G:function(){return this.radioChannelAndPower(this.get("radio_na"))},radioChannelAndPower:function(e){if(!this.get("adopted")||!e)return"";var t=e.channel&&!isNaN(e.channel)?parseInt(e.channel,10):"auto",n=e.tx_power_mode||"auto";return n==="custom"&&(n=parseInt(e.tx_power,10)+parseInt(e.antenna_gain,10)+" dBm"),t===0&&(t="auto"),t+" / "+n},clientName:function(e){return e.hostname||e.mac},deviceName:function(e){return e.essid||e.mac},status:function(){var e,t=this.uplink()||{};switch(parseInt(this.get("state"),10)||0){case 0:e=this.get("restarting")?s.G_APRestarting:s.G_APDisconnected;break;case 1:e=s.G_APConnected,this.get("isolated")?e+=" (limited)":t.type=="wire"?this.get("type")!=="ugw"&&(t.max_speed!=t.speed||!t.full_duplex)&&(e+=" ("+t.speed+" "+(t.full_duplex?"FDX":"HDX")+")"):t.type=="wireless"&&(e+=" (wireless)"),this.get("version_incompatible")&&(e+=" (needs upgrade)");break;case 2:this.get("default")?this.get("discovered_via")=="scan"?e=s.G_APIsolatedPending:e=s.G_APPending:e=s.G_APManagedByOthers;break;case 3:e=s.G_APFirmwareMismatch;break;case 4:e=s.G_APUpgrading;break;case 5:e=s.G_APProvisioning;break;case 6:e=s.G_APHeartbeatMissed;break;case 7:e=s.G_APAdopting,t.type=="wireless"&&(e+=" (wireless)");break;case 8:e=s.G_APDeleting;break;case 9:e=s.G_APDisconnected;break;case 10:e=s.G_APAdoptFailed;break;case 11:e=s.G_APIsolated}return e},statusType:function(){switch(parseInt(this.get("state"),10)||0){case 1:case 4:case 5:return"ok";case 2:case 7:case 13:return"pending";case 0:case 3:case 9:case 10:case 11:return"error";default:return"error"}},isConnected:function(){return this.statusType()==="ok"},is11ac:function(){return n.inArray(this.get("model"),["U7E","U7O","U7Ev2"])!==-1},lastSeen:function(){var e=this.get("last_seen"),t;return e?(t=(new Date).getTime()/1e3-parseInt(e,10),isNaN(t)?"":t<86400?i.Formatters.Duration.fromRaw(t)+" ago":u(e+"","X").format("YYYY/MM/DD HH:mm:ss")):s.G_Never},absoluteLastSeen:function(){var e=this.get("last_seen");return e?u(e+"","X").format("YYYY/MM/DD HH:mm:ss"):""},syncPortTable:function(e,i){this.collections.portTable||(this.collections.portTable=new(r.Collection.extend({model:t.extend({idAttribute:"port_idx"})}))),o.each(this.attributes.port_table,n.proxy(function(e){var t=o.filter(this.attributes.port_overrides,function(t){return t.port_idx==e.port_idx});t.length&&(e=o.extend(e,t[0])),e.device=this.get("mac"),this.collections.portTable.add(e,{merge:!0})},this)),this.trigger("syncPortTable")},upgrade:function(e){return this.sync("upgrade",this,e)},adopt:function(e){return this.sync("adopt",this,e)},advanceAdopt:function(e){return this.validationError=this.validate(e.data,o.extend({partial:"advance-adopt"},e)),this.validationError?!1:this.sync("advance-adopt",this,e)},forget:function(e){return this.sync("forget",this,e)},restart:function(e){return this.sync("restart",this,e)},powerCyclePort:function(e){return this.sync("power-cycle",this,e)},clearSwitchCounters:function(e){return this.sync("clear-switch-counters",this,e)},clearPortCounters:function(e){return this.sync("clear-switch-port-counters",this,e)},setVwireUplink:function(e){return this.sync("set-vwire-uplink",this,e)},unsetVwireUplink:function(e){return this.sync("unset-vwire-uplink",this,e)},move:function(e){return this.sync("move",this,e)},copyConfig:function(e){return this.sync("copy-config",this,e)},update:function(e){return this.sync("update",this,e)},locate:function(e){return this.sync("locate",this,e)},updateWlanGroup:function(e,t){var n={};return n["wlangroup_id_"+e]=t.wlangroup_id,n.wlan_overrides=o.reject(this.get("wlan_overrides"),function(t){return t.radio==e}),this.save(n,o.extend(t,{_method:"update-wlangroup-"+e}))},sync:function(e,t,n,i){n=n||{},n._method&&(e=n._method,delete n._method);switch(e){case"read":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/stat/device/"+t.get("mac"),n.type="GET";break;case"update":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/upd/device/"+t.id,n.type="POST",n.data=n.data?JSON.stringify(n.data):JSON.stringify(t.changed);break;case"adopt":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"adopt"}));break;case"advance-adopt":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"adv-adopt"}));break;case"power-cycle":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"power-cycle"}));break;case"clear-switch-counters":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"clear-switch-counters"}));break;case"clear-switch-port-counters":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"clear-switch-port-counters"}));break;case"set-vwire-uplink":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{cmd:"set-vwire-uplink"}));break;case"unset-vwire-uplink":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{cmd:"unset-vwire-uplink"}));break;case"forget":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/sitemgr",n.type="POST",n.data=JSON.stringify({mac:t.get("mac"),cmd:"delete-device"});break;case"restart":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify({mac:t.get("mac"),cmd:"restart"});break;case"upgrade":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify({mac:t.get("mac"),cmd:"upgrade"});break;case"move":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/sitemgr/",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"move-device"}));break;case"copy-config":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr/",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"clone-config",origin:n.selectedMac}));break;case"add-device":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/sitemgr/",n.type="POST",n.data=JSON.stringify({macid:n.macidqr,cmd:"add-device"});break;case"locate":t.get("adopted")?t.set({locating:!t.get("locating")}):t.set({locating:!1}),n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify({mac:t.get("mac"),cmd:t.get("adopted")?t.get("locating")?"set-locate":"unset-locate":"locate"});break;case"update-wlangroup-ng":n.contentType="application/json",n.url="/api/s/"+SITE.name+"/upd/device/"+t.id,n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{wlangroup_id_ng:t.get("wlangroup_id_ng"),wlan_overrides:t.get("wlan_overrides")}));break;case"update-wlangroup-na":n.contentType="application/json",n.url="/api/s/"+SITE.name+"/upd/device/"+t.id,n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{wlangroup_id_na:t.get("wlangroup_id_na"),wlan_overrides:t.get("wlan_overrides")}))}return r.sync.call(this,e,t,n)}})}),define("unifi/collection/Devices",["unifi/collection/Collection","underscore","backbone","unifi/model/Device"],function(e,t,n,r){"use strict";return e.extend({model:r,bySite:!0,initialize:function(t){e.prototype.initialize.call(this,t),this.typeMap=(new this.model).typeMap},get:function(n){var r=e.prototype.get.call(this,n);return!r&&t.isObject(n)&&!n.id&&n.get("mac")&&(r=this.getDeviceFromMac(n.get("mac"))),r},getInformIP:function(){var e=this.find(function(e){return e.get("adopted")&&e.get("state")==1&&e.get("inform_ip")});return e===undefined?"":e.get("inform_ip")},hasUpgradableAP:function(){var e=this.find(function(e){return e.get("type")=="uap"&&e.get("state")==1&&e.get("upgradable")});return e?!0:!1},hasUpgradablePhone:function(){var e=this.find(function(e){return e.get("type")=="uph"&&e.get("state")==1&&e.get("upgradable")});return e?!0:!1},isUpgradingDevices:function(){var e=this.find(function(e){return e.get("rollupgrade")});return e?!0:!1},getDeviceFromMac:function(e){return this.find(function(t){return t.get("mac")==e})},sortByBytes:function(){var e=this.sortBy(function(e){return-1*(e.get("bytes")||0)});return e},sortByBytesOnlyAps:function(){var e=this.sortByBytes();return t.filter(e,function(e){return e.get("type")==="uap"})},url:function(){return"/api/s/"+SITE.name+"/stat/device"},all:function(e){return this.fetch(t.extend(e,{_method:"read-all"}))},discover:function(){return this.fetch({_method:"discover"})},scanUplink:function(e){return this.sync("scan-uplink",this,e)},upgradeAPs:function(e){return this.sync("upgrade-aps",this,e)},upgradePhones:function(e){return this.sync("upgrade-phones",this,e)},sync:function(e,r,i){i=i||{},i._method&&(e=i._method,delete i._method);switch(e){case"read-all":i.contentType="application/json; charset=utf-8",i.url="/api/stat/device",i.type="POST",i.data=JSON.stringify(i.data||{});break;case"discover":i.contentType="application/json; charset=utf-8",i.url="/api/stat/device",i.type="POST",i.data=JSON.stringify({state:2,"default":!0});break;case"read":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/stat/device",i.type="GET";break;case"scan-uplink":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/cmd/devmgr",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{},{cmd:"scan-uplink"}));break;case"upgrade-aps":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/cmd/devmgr",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{},{cmd:this.isUpgradingDevices()?"unset-rollupgrade":"set-rollupgrade"}));break;case"upgrade-phones":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/cmd/devmgr",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{},{cmd:"upgrade-all",type:"uph"}))}return n.sync.call(this,e,r,i)}})}),define("text!includes/dashboard/dashboardIndexTemplate.html",[],function(){return'<h1><%-msg.G_DashboardNetworkHealth %></h1>\n\n<div class="diagram">\n    <div class="nodes">\n        <div class="unknown www layer">\n            <div id="speedtest">\n                <div class="speedtest-inner">\n                    <div class="mini">\n                        <h2><span class="speedtest-icon"></span> <%- msg.G_Speedtest %></h2>\n                        <a href="#" class="button button-test"><%- msg.G_StartNow %></a>\n                        <div class="speedtest-download">\n                            <div class="result">\n                                <span class="arrow sprite-arrow-down-gray"></span>\n                                <span class="value">&nbsp;?&nbsp;</span>\n                                <span class="unit">Mbps</span>\n                            </div>\n                        </div>\n                        <div class="speedtest-upload">\n                            <div class="result">\n                                <span class="arrow sprite-arrow-up-gray"></span>\n                                <span class="value">&nbsp;?&nbsp;</span>\n                                <span class="unit">Mbps</span>\n                            </div>\n                        </div>\n                        <div class="speedtest-lastrun">\n                            <div class="result">\n                                <span class="unit">Last run:</span>\n                                <span class="value"></span>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n            <div class="drop-count hidden">\n                <div class="ubnt-icon-drop"></div>\n                <div class="count"></div>\n            </div>\n            <div class="inner">\n                <div class="image ubnt-icon-globe"></div>\n                <div class="title"><%-msg.G_DashboardDiagramWWW %></div>\n            </div>\n            <div class="ubnt-icon-arrow-right"></div>\n            <div class="connector right"><span></span></div>\n        </div>\n        <div class="unknown wan layer">\n            <div class="drop-count hidden">\n                <div class="ubnt-icon-drop"></div>\n                <div class="count"></div>\n            </div>\n            <div class="inner">\n                <div class="image ubnt-icon-lock"></div>\n                <div class="title"><%-msg.G_DashboardDiagramWAN %></div>\n            </div>\n            <div class="ubnt-icon-arrow-left"></div>\n            <div class="connector left"><span></span></div>\n            <div class="ubnt-icon-arrow-right"></div>\n            <div class="connector right"><span></span></div>\n        </div>\n        <div class="unknown lan layer">\n            <div class="drop-count hidden">\n                <div class="ubnt-icon-drop"></div>\n                <div class="count"></div>\n            </div>\n            <div class="inner">\n                <div class="image ubnt-icon-files"></div>\n                <div class="title"><%-msg.G_DashboardDiagramLAN %></div>\n            </div>\n            <div class="ubnt-icon-arrow-left"></div>\n            <div class="connector left"><span></span></div>\n            <div class="ubnt-icon-arrow-right top"></div>\n            <div class="connector right top"><span></span></div>\n            <div class="ubnt-icon-arrow-right bottom"></div>\n            <div class="connector right bottom"><span></span></div>\n        </div>\n        <div class="unknown wlan layer">\n            <div class="drop-count hidden">\n                <div class="ubnt-icon-drop"></div>\n                <div class="count"></div>\n            </div>\n            <div class="inner">\n                <div class="image ubnt-icon-wifi"></div>\n                <div class="title"><%-msg.G_DashboardDiagramWLAN %></div>\n            </div>\n            <div class="ubnt-icon-arrow-left"></div>\n            <div class="connector left"><span></span></div>\n        </div>\n        <div class="unknown voip layer">\n            <div class="drop-count hidden">\n                <div class="ubnt-icon-drop"></div>\n                <div class="count"></div>\n            </div>\n            <div class="inner">\n                <div class="image ubnt-icon-dial"></div>\n                <div class="title"><%-msg.G_DashboardDiagramVOIP %></div>\n            </div>\n            <div class="ubnt-icon-arrow-left"></div>\n            <div class="connector left"><span></span></div>\n        </div>\n    </div>\n    <div id="dashboardTable" class="table"></div>\n</div>\n'}),define("text!includes/dashboard/speedTestTemplate.html",[],function(){return'<div class="speedometer">\n    <div class="speedometer-tachring speedometer-ring--grey"></div>\n    <div class="speedometer-tachring speedometer-ring--glow"></div>\n    <div class="speedometer-tachring speedometer-tach--grey"></div>\n    <div class="speedometer-tachring">\n        <span class="speedometer-tach-icon speedometer-tach-icon-1"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-2"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-3"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-4"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-5"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-6"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-7"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-8"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-9"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-10"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-11"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-12"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-13"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-14"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-15"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-16"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-17"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-18"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-19"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-20"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-21"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-22"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-23"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-24"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-25"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-26"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-27"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-28"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-29"></span>\n        <span class="speedometer-tach-icon speedometer-tach-icon-30"></span>\n    </div>\n    \n    <div class="speedometer-stats">\n        <span class="testing-ping"><%- msg.G_TestingPing %></span>\n        <div class="speedtest-error-message"><%- msg.E_Retest %></div>\n        <a href="#" class="button button-test"><%- msg.G_Retest %></a>\n        <div class="result">\n            <span class="value"></span>\n            <span class="unit">Mbps</span>\n        </div>\n    </div>\n</div>\n\n<div class="speedtest-progress">\n    <div class="icon icon-globe"></div>\n    <div id="speedtest-progress-bars" class="speedtest-progress-bars"></div>\n    <div class="icon icon-shield"></div>\n</div>\n\n<div class="speedtest-results">\n    <div class="speedtest-result speedtest-ping">\n        <div class="appSpinner"></div>\n        <div class="result">\n            <span class="value"></span>\n            <span class="unit">ms</span>\n        </div>\n        <h4><%- msg.G_Ping %></h4>\n    </div>\n    <div class="speedtest-result speedtest-download">\n        <div class="appSpinner"></div>\n        <div class="result">\n            <span class="value"></span>\n            <span class="unit">Mbps</span>\n        </div>\n        <h4><%- msg.G_Download %></h4>\n    </div>\n    <div class="speedtest-result speedtest-upload">\n        <div class="appSpinner"></div>\n        <div class="result">\n            <span class="value"></span>\n            <span class="unit">Mbps</span>\n        </div>\n        <h4><%- msg.G_Upload %></h4>\n    </div>\n</div>\n'}),define("libs/fixedqueue",["jquery","underscore","backbone","msg/Msg"],function(e,t,n,r){"use strict";function i(e,t){t=t||[];var n=Array.apply(null,t);return n.fixedSize=e,n.push=i.push,n.splice=i.splice,n.unshift=i.unshift,n.setAll=i.setAll,i.trimTail.call(n),n}return i.trimHead=function(){if(this.length<=this.fixedSize)return;Array.prototype.splice.call(this,0,this.length-this.fixedSize)},i.trimTail=function(){if(this.length<=this.fixedSize)return;Array.prototype.splice.call(this,this.fixedSize,this.length-this.fixedSize)},i.wrapMethod=function(e,t){var n=function(){var n=Array.prototype[e],r=n.apply(this,arguments);return t.call(this),r};return n},i.push=i.wrapMethod("push",i.trimHead),i.splice=i.wrapMethod("splice",i.trimTail),i.unshift=i.wrapMethod("unshift",i.trimTail),i.setAll=function(e){for(var t=0;t<this.fixedSize;t++)this.push(e)},i}),define("unifi/view/dashboard/SpeedTestView",["unifi/view/app/DialogView","text!includes/dashboard/speedTestTemplate.html","msg/Msg","backbone","underscore","jquery","libs/fixedqueue"],function(e,t,n,r,i,s,o){"use strict";return e.extend({fastInterval:50,slowInterval:3e3,pollingIntervalms:3e3,uploadInitialized:!1,progressBarCount:66,tachIconCount:30,tachDelayInterval:35,tachFadeSpeed:80,maxMbps:100,dialogOptions:{width:430,height:435,modal:!0,resizable:!1,draggable:!1,dialogClass:"dialog-speedtest"},initialize:function(e){i.bindAll(this),this.app=e.app,this.model=e.model,this.progressBars=new o(this.progressBarCount)},render:function(){this.$el.html(i.template(t,{msg:n})),this.$speedometerGlow=this.$(".speedometer-ring--glow"),this.$testingPing=this.$(".testing-ping"),this.$buttonTest=this.$(".button-test"),this.$errorMessage=this.$(".speedtest-error-message"),this.$speedometerStatsResult=this.$(".speedometer-stats").find(".result"),this.$speedometerStatsValue=this.$speedometerStatsResult.find(".value"),this.$(".ui-icon-closethick").removeClass("ui-icon-closethick"),this.$tachRing=this.$(".speedometer-tachring"),this.$tachSegments=this.$(".speedometer-tach-icon"),this.currentTachSegmentsGlowing=0,this.$progressBars=this.$("#speedtest-progress-bars"),this.$pingWrapper=this.$(".speedtest-ping"),this.$pingResult=this.$(".speedtest-ping.speedtest-result").find(".result"),this.$pingValue=this.$pingResult.find(".value"),this.$downloadWrapper=this.$(".speedtest-download"),this.$downloadResult=this.$(".speedtest-download.speedtest-result").find(".result"),this.$downloadValue=this.$downloadResult.find(".value"),this.$uploadWrapper=this.$(".speedtest-upload"),this.$uploadResult=this.$(".speedtest-upload.speedtest-result").find(".result"),this.$uploadValue=this.$uploadResult.find(".value"),this.generateSpeedTestProgressBarHTML(),this.bindEventListeners()},bindEventListeners:function(){this.listenTo(this.model,"sync",this.onTestProgress),this.listenTo(this.model,"change:xput_download",this.onDownloadStatusChange),this.listenTo(this.model,"change:xput_upload",this.onUploadStatusChange),this.listenTo(this.model,"change:status_ping",this.onPingStatusChange),this.listenTo(this.model,"change:status_download",this.onDownloadStatusChange),this.listenTo(this.model,"change:status_upload",this.onUploadStatusChange),this.listenTo(this.model,"change:status_summary",this.onSummaryStatusChange),this.listenTo(this.model,"change:timestamp",this.onUpdateFromServer),this.$buttonTest.on("click",this.startTest)},open:function(){e.prototype.open.call(this),s.Window.on("resize.speedTestDialog",i.debounce(this.onResizeWindow,250)),this.onResizeWindow(),this.startTest(),this.removeTooltips()},close:function(){e.prototype.close.call(this),s.Window.off("resize.speedTestDialog"),this.removeTooltips()},removeTooltips:function(){s(".ui-tooltip-content").parents("div").remove()},onResizeWindow:function(){this.center()},generateSpeedTestProgressBarHTML:function(){var e="",t=[];for(var n=0;n<this.progressBarCount;n++)t.push('<span class="speedtest-progress-bar speedtest-progress-bar-'+n+'"><span class="value"></span></span>');this.$progressBars.html(t.join(""))},polling:function(){var e=this;this.pollingInterval&&this.stopPolling(),this.model.getStatus("download")===1||this.model.getStatus("upload")===1?this.pollingIntervalms=this.fastInterval:this.pollingIntervalms=this.slowInterval,this.pollingInterval=window.setInterval(function(){e.model.fetch()},this.pollingIntervalms)},stopPolling:function(){window.clearInterval(this.pollingInterval)},startTest:function(e){e&&e.preventDefault(),this.uploadInitialized=!1,this.progressBars.setAll(0),this.model.clear(),this.model.sync("start",this.model,{}),this.onTestStart()},onTestStart:function(){this.$speedometerGlow.show(),this.$testingPing.show(),this.$speedometerStatsResult.hide(),this.$buttonTest.hide(),this.hideErrorMessage(),this.hideResults(),this.onTestProgress()},hideResults:function(){this.$pingResult.addClass("hide"),this.$downloadResult.addClass("hide"),this.$uploadResult.addClass("hide")},hideStatuses:function(){this.$testingPing.hide(),this.$speedometerStatsResult.hide()},onTestProgress:function(){this.onPingStatusChange(),this.onDownloadStatusChange(),this.onUploadStatusChange(),this.onSummaryStatusChange()},onTestComplete:function(){this.stopPolling(),this.$speedometerGlow.hide(),this.$speedometerStatsResult.hide(),this.resetProgressBars(),this.resetTachRing(),this.$buttonTest.show()},onPingStatusChange:function(){this.updateStatus("ping",this.$pingResult,this.$pingValue,this.$pingWrapper)},onDownloadStatusChange:function(){this.updateStatus("download",this.$downloadResult,this.$downloadValue,this.$downloadWrapper)},onUploadStatusChange:function(){this.updateStatus("upload",this.$uploadResult,this.$uploadValue,this.$uploadWrapper)},onSummaryStatusChange:function(){this.updateStatus("summary")},onUpdateFromServer:function(){this.model.getProgressRecords()},updateStatusTitle:function(e,t){var n=this.model.getStatus(e);e==="ping"&&n<2||n===1?t.addClass("running"):t.removeClass("running")},updateStatus:function(e,t,n,r){var i=!1;e!=="summary"&&this.updateStatusTitle(e,r);switch(this.model.getStatus(e)){case 0:break;case 1:if(e==="download"||e==="upload")e==="upload"&&this.uploadInitialized===!1&&(this.progressBars.setAll(0),this.resetProgressBars(),this.resetTachRing(),this.uploadInitialized=!0),this.updateTachRing(e),this.updateProgressBars(e);break;case 2:e==="summary"?i=!0:(e==="ping"&&this.$testingPing.hide(),r.removeClass("running"),this.showResult(this.model.getResult(e),t,n));break;case 3:i=!0,this.hideStatuses(),this.showErrorMessage()}i?this.onTestComplete():this.polling()},showResult:function(e,t,n){n.text(e),t.removeClass("hide")},updateTachRing:function(e){var t=this.model.getResult(e)*100,n=this.model.convertMbpsToPercentage(t,this.maxMbps),r=Math.ceil(this.tachIconCount*(n/100)),i,s,o;i=r-this.currentTachSegmentsGlowing;if(i!==0){this.removeFlickeringTachSegment(this.currentTachSegmentsGlowing-1);if(i>0)for(s=0;s<i;s++)this._fadeTachSegment(this.currentTachSegmentsGlowing+s,s*this.tachDelayInterval,!0);else if(i<0)for(s=-1,o=1;s>=i;s--,o++)this._fadeTachSegment(this.currentTachSegmentsGlowing+s,o*this.tachDelayInterval,!1);this.flickerTachSegment(r-1),this.currentTachSegmentsGlowing=r}this.$speedometerStatsResult.show(),this.$speedometerStatsValue.text(this.model.convertToMbps(t).toFixed(2))},flickerTachSegment:function(e){e>-1&&e<this.tachIconCount&&this.$tachSegments.eq(e).addClass("flicker")},removeFlickeringTachSegment:function(e){e>-1&&e<this.tachIconCount&&this.$tachSegments.eq(e).removeClass("flicker")},_fadeTachSegment:function(e,t,n){e>-1&&e<this.tachIconCount&&this.$tachSegments.eq(e).delay(t).stop(!0,!0)[n?"fadeIn":"fadeOut"](this.tachFadeSpeed)},resetTachRing:function(){this.removeFlickeringTachSegment(this.currentTachSegmentsGlowing);for(var e=0,t=1;e>=-this.currentTachSegmentsGlowing;e--,t++)this.tachIconCount+e>-1&&this.$tachSegments.eq(this.currentTachSegmentsGlowing+e).delay(t*this.tachDelayInterval).fadeOut(this.tachFadeSpeed);this.currentTachSegmentsGlowing=0},updateProgressBars:function(e){var t=this.model.getResult(e)*100,n=100,r,s;e==="download"?this.progressBars.push(t):this.progressBars.unshift(t),i.each(this.progressBars,function(e,t){r=this.model.convertMbpsToPercentage(e,this.maxMbps),s=(100-r).toFixed(2),this.$progressBars.find(".speedtest-progress-bar-"+t).find(".value").height(s+"%")},this)},resetProgressBars:function(){this.$progressBars.find(".speedtest-progress-bar").find(".value").height("100%")},showErrorMessage:function(){this.$errorMessage.show()},hideErrorMessage:function(){this.$errorMessage.hide()},remove:function(){this.stopListening(this.model,"sync",this.onTestProgress),this.stopListening(this.model,"change:xput_download",this.onDownloadStatusChange),this.stopListening(this.model,"change:xput_upload",this.onUploadStatusChange),this.stopListening(this.model,"change:status_ping",this.onPingStatusChange),this.stopListening(this.model,"change:status_download",this.onDownloadStatusChange),this.stopListening(this.model,"change:status_upload",this.onUploadStatusChange),this.stopListening(this.model,"change:status_summary",this.onSummaryStatusChange),this.stopListening(this.model,"change:timestamp",this.onUpdateFromServer),this.$buttonTest.off("click",this.startTest),s.Window.off("resize.speedTestDialog"),e.prototype.remove.apply(this,arguments)}})}),define("unifi/view/dashboard/IndexView",["unifi/view/app/ContentView","unifi/view/dashboard/LayerView","unifi/collection/Subsystems","unifi/model/Subsystem","unifi/model/SpeedTest","ubnt/backgrid","underscore","jquery","unifi/collection/Alerts","unifi/collection/Devices","text!includes/dashboard/dashboardIndexTemplate.html","unifi/view/dashboard/SpeedTestView","ubnt/view/dialogs/ErrorDialogView","msg/Msg"],function(e,t,n,r,i,s,o,u,a,f,l,c,h,p){"use strict";return e.extend({id:"dashboardIndex",layers:{},speedtest_status:"",pollingSpeedtestInterval:null,initialize:function(t){e.prototype.initialize.call(this,t),this.layers={},this.template=o.template(l),u.when(this._rendered=u.Deferred(),this._dependencies=u.Deferred()).then(this.populate,this.failed),this.dependencies(),this.render()},dependencies:function(){var e={Subsystems:n,Alerts:a,Devices:f},t=[],r={},i=this,s;o.each(e,function(e,n){t.push(r[n]=u.Deferred())},this),u.when.apply(u,t).then(function(){i._dependencies.resolve()},function(){i._dependencies.reject()}),o.each(e,function(e,t){s={fetch:{reload:!1,deferred:r[t]}},t==="Alerts"&&(s.fetch.method="unarchived"),this.options.app.collection(t,s,e)},this)},failed:function(){(new h).open(p.E_DataLoad)},onAlertsChange:function(){o.each(this.subsystems.possibleSubsystems,function(e){this.layers[e.toUpperCase()].model.set("notifications",this.alerts.where({system:e,archived:!1}))},this)},render:function(){e.prototype.render.call(this);if(!this.rendered&&(this.rendered=!0)){var n=this,s,a,f;this.$el.html(this.template({msg:p})),this.speedTestModel=new i,this.speedTestModel.fetch(),this.speedTestView=new c({app:this.app,model:this.speedTestModel}),this.subsystems=this.options.app.collection("Subsystems"),this.alerts=this.options.app.collection("Alerts"),this.devices=this.options.app.collection("Devices"),this.listenTo(this.alerts,"change",o.debounce(this.onAlertsChange,500)),this.listenTo(this.alerts,"add",o.debounce(this.onAlertsChange,500)),this.listenTo(this.alerts,"remove",o.debounce(this.onAlertsChange,500)),this.listenTo(this.alerts,"reset",o.debounce(this.onAlertsChange,500)),this.listenTo(this.subsystems,"reset change sync",o.debounce(this.populate,500)),this.$speedTest=u("#speedtest"),this.$speedTestButton=this.$speedTest.find(".button-test").on("click",this.triggerSpeedTest),this.$speedTestUploadResult=this.$speedTest.find(".speedtest-upload .result"),this.$speedTestUploadValue=this.$speedTestUploadResult.find(".value"),this.$speedTestDownloadResult=this.$speedTest.find(".speedtest-download .result"),this.$speedTestDownloadValue=this.$speedTestDownloadResult.find(".value"),this.$speedLastRunResult=this.$speedTest.find(".speedtest-lastrun .result"),this.$speedLastRunValue=this.$speedLastRunResult.find(".value"),this.listenTo(this.speedTestModel,"change:status_download change:status_upload change:timestamp",this.onSpeedTestChangeStatus),f=u("#navSettings").find("a"),o.each(this.subsystems.possibleSubsystems,function(e,i){s=!1,a=function(){n.app.routers.statistics.forward()};switch(e){case"www":a=!1;break;case"wan":s=function(){var t=n.subsystems.findWhere({subsystem:e}),r=n.devices.findWhere({mac:t.get("gw_mac")});u("#devicesIndex").find(".mac-"+r.getMacNoColons()+" .column-name").click()},a=!1;break;case"lan":s=function(){f.click(),u("#navSettingsNetworks").find("a").click()},a=!1;break;case"wlan":s=function(){f.click(),u("#navSettingsWirelessNetworks").find("a").click()};break;case"voip":a=!1}n.layers[e.toUpperCase()]=new t({model:new r({subsystem:e,configureLink:s,statsLink:a}),$tableItem:n.$(".table-item."+e),el:".layer."+e,app:n.app})}),this.$nodeWWW=u(".nodes .www"),this._rendered.state()==="resolved"&&this._dependencies.state()=="resolved"?this.populate():this._rendered.state()==="pending"&&this._rendered.resolve()}},populate:function(){var e;o.each(this.subsystems.possibleSubsystems,function(t){e=this.subsystems.findWhere({subsystem:t}),this.layers[t.toUpperCase()].update(e)},this),this.$nodeWWW.hasClass("ok")?this.addSpeedTestEvents():this.removeSpeedTestEvents(),this.speedTestModel.isTesting&&this.addSpeedTestEvents()},showSpeedTest:function(){this.$speedTest.show()},hideSpeedTest:function(){this.$speedTest.hide()},closeSpeedTest:function(){return this.hideSpeedTest(),this.addSpeedTestEvents(),!1},addSpeedTestEvents:function(){this.$nodeWWW.on("mouseenter",this.showSpeedTest).on("mouseleave",this.hideSpeedTest)},removeSpeedTestEvents:function(){this.$nodeWWW.off("mouseenter",this.showSpeedTest).off("mouseleave",this.hideSpeedTest)},triggerSpeedTest:function(){return this.speedTestView.open(),this.$speedTestButton.text(p.localize(p.G_Retest)),!1},onSpeedTestChangeStatus:function(){var e=!1,t=!1,n=!1;this.speedTestModel.getStatus("download")===2&&(this.$speedTestDownloadValue.text(this.speedTestModel.getDownloadSpeed()),this.$speedTestDownloadResult.show(),e=!0),this.speedTestModel.getStatus("upload")===2&&(this.$speedTestUploadValue.text(this.speedTestModel.getUploadSpeed()),this.$speedTestUploadResult.show(),t=!0),this.speedTestModel.get("rundate")&&(this.$speedLastRunValue.text(this.speedTestModel.getLastRun()),this.$speedLastRunResult.show(),n=!0),e&&t&&n?this.$speedTest.removeClass("notrun"):(this.$speedTest.addClass("notrun"),this.$speedTestDownloadValue.text(""),this.$speedTestUploadValue.text(""),this.$speedLastRunValue.text(""),this.$speedTestDownloadResult.hide(),this.$speedTestUploadResult.hide(),this.$speedLastRunResult.hide())},remove:function(){this.stopListening(this.alerts),this.stopListening(this.subsystems),this.$speedTest.find(".button-test").off("click",this.triggerSpeedTest),this.removeSpeedTestEvents(),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/router/DashboardRouter",["unifi/router/Router","unifi/view/dashboard/IndexView","unifi/view/dashboard/LayerView"],function(e,t,n){"use strict";return e.extend({_fullyQualifiedName:"UNIFI.Routers.Dashboard",_associatedViews:{Index:t,Layer:n},routes:{dashboard:"index"}})}),define("text!includes/map/mapIndexTemplate.html",[],function(){return'<div id="Map" class="tab-content">\n    <div class="toolbar">\n        <div class="map-configuration-items">\n            <div class="buttonset left coverage">\n                <input type="radio" id="mapFilterCoverage2G" name="coverageFilter" value="2G" checked="checked"/>\n                <label for="mapFilterCoverage2G"><%- msg.G_2G %></label>\n                <input type="radio" id="mapFilterCoverage5G" name="coverageFilter" value="5G" />\n                <label for="mapFilterCoverage5G"><%- msg.G_5G %></label>\n            </div>\n            <div class="buttonset left mainToggles">\n                <input type="checkbox" id="mapFilterDetails" name="filter" value="details" />\n                <label for="mapFilterDetails"><%- msg.G_MapDetails %></label>\n                <input type="checkbox" id="mapFilterCoverage" name="filter" value="coverage" />\n                <label for="mapFilterCoverage"><%- msg.G_MapCoverage %></label>\n                <input type="checkbox" id="mapFilterTopology" name="filter" value="topology" />\n                <label for="mapFilterTopology"><%- msg.G_MapTopology %></label>\n            </div>\n            <div class="right">\n                <select name="mapSelect" class="mapSelect"></select>\n            </div>\n        </div>\n        <div class="zoom-controls">\n            <div class="ir zoom-icon plus"><div class="plus-icon ubnt-icon-plus"></div></div>\n            <div class="zoom-slider"></div>\n            <div class="ir zoom-icon minus"><div class="minus-icon ubnt-icon-minus"></div></div>\n        </div>\n        <div class="ruler is-admin">\n            <div class="ruler-icon ubnt-icon-scale"></div>\n            <div class="sub-section">\n                <div class="sub-section-title"><%- msg.G_MapSetMapScale %></div>\n                <div class="ubnt-icon-close close handle"></div>\n                <div class="tip"><%- msg.G_MapDrawLine %></div>\n                <form action="#" class="frm-map-scale">\n                    <input name="distance" type="text" maxlength="4" placeholder="distance" class="input distance left disabled" disabled/>\n                    <div>\n                        <select name="units" class="input units right">\n                            <option value="m"><%- msg.G_MapMeters %></option>\n                            <option value="f"><%- msg.G_MapFeet %></option>\n                        </select>\n                    </div>\n                    <button type="submit" class="button submit right disabled" disabled>\n                        <span class="icon ubnt-icon-check"></span>\n                        <%- msg.G_MapSetScale %>\n                    </button>\n                </form>\n            </div>\n        </div>\n    </div>\n\n    <div class="ubnt-map-widget">\n        <div class="image-map-container map-container">\n            <div class="image-map-coverage-layer"></div>\n            <div class="image-drag-layer">\n                <div class="image-map-layer">\n                    <canvas class="map-canvas"></canvas>\n                </div>\n                <div class="sub-marker-layer"></div>\n                <div class="marker-layer"></div>\n            </div>\n        </div>\n        <div class="google-map-container map-container">\n            <div class="loading"></div>\n        </div>\n    </div>\n\n    <div class="scale">\n        <div class="scale-icon"></div>\n        <div class="scale-measurement"></div>\n    </div>\n\n    <div class="marker-drawer">\n        <button class="button header handle is-admin"><span class="unplaced-markers-count"></span> <%- msg.G_MapUnplacedDevices %></button>\n        <div class="unplaced-devices">\n            <h3 class="sub-section-title"><%- msg.G_MapUnplacedDevices %></h3>\n            <div class="ubnt-icon-close close handle"></div>\n            <ul class="marker-list draggable-list"></ul>\n        </div>\n    </div>\n</div>'}),define("text!includes/map/mapMarkerTemplate.html",[],function(){return'<div class="marker connected disconnected expand">\n    <div class="marker-button">\n        <div class="marker-icon device-icons access-point ir forceRetina"></div>\n    </div>\n\n    <div class="status-icon">\n        <div class="disconnected sprite-status-disconnected"></div>\n        <div class="isolated sprite-status-isolated"></div>\n        <div class="vwireless sprite-status-vwireless"></div>\n    </div>\n    <div class="title"></div>\n    <div class="details">\n        <div class="detail"><div class="ap-name"></div></div>\n        <div class="detail mac-text"><span></span> <div class="mac"></div></div>\n        <div class="detail channel-text"><span></span> <div class="channel"></div></div>\n        <div class="detail users-text"><span></span> <div class="users"></div></div>\n        <div class="detail guests-text"><span></span> <div class="guests"></div></div>\n    </div>\n    <div class="halo"></div>\n    <div class="ir move"></div>\n    <div class="sub-buttons">\n        <div class="button-container lock">\n            <div class="button"><div class="icon ubnt-icon-unlock"></div></div>\n        </div>\n\n        <div class="button-container config">\n            <div class="button"><div class="icon ubnt-icon-gear"></div></div>\n        </div>\n\n        <div class="button-container remove">\n            <div class="button"><div class="icon ubnt-icon-close"></div></div>\n        </div>\n    </div>\n</div>'}),define("text!includes/map/mapUnplacedMarkerTemplate.html",[],function(){return'<li class="device-list-item">\n    <a href="#">\n    	<span class="ui-icon device-icons access-point half"></span>\n    	<span class="item-label"></span>\n    </a>\n</li>'}),define("text!includes/map/mapUnplacedMarkerDraggableTemplate.html",[],function(){return'<div class="map-widget-marker helper marker expand">\n    <div class="marker-button">\n        <div class="marker-icon device-icons access-point ir ui-icon"></div>\n    </div>\n</div>'});var Kinetic={};(function(){Kinetic.version="4.3.3",Kinetic.Filters={},Kinetic.Plugins={},Kinetic.Global={stages:[],idCounter:0,ids:{},names:{},shapes:{},warn:function(e){window.console&&console.warn&&console.warn("Kinetic warning: "+e)},extend:function(e,t){for(var n in t.prototype)n in e.prototype||(e.prototype[n]=t.prototype[n])},_addId:function(e,t){t!==undefined&&(this.ids[t]=e)},_removeId:function(e){e!==undefined&&delete this.ids[e]},_addName:function(e,t){t!==undefined&&(this.names[t]===undefined&&(this.names[t]=[]),this.names[t].push(e))},_removeName:function(e,t){if(e!==undefined){var n=this.names[e];if(n!==undefined){for(var r=0;r<n.length;r++){var i=n[r];i._id===t&&n.splice(r,1)}n.length===0&&delete this.names[e]}}}}})(),function(e,t){typeof exports=="object"?module.exports=t():typeof define=="function"&&define.amd?define("libs/kinetic",t):e.returnExports=t()}(this,function(){return Kinetic}),function(){Kinetic.Type={_isElement:function(e){return!!e&&e.nodeType==1},_isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},_isObject:function(e){return!!e&&e.constructor==Object},_isArray:function(e){return Object.prototype.toString.call(e)=="[object Array]"},_isNumber:function(e){return Object.prototype.toString.call(e)=="[object Number]"},_isString:function(e){return Object.prototype.toString.call(e)=="[object String]"},_hasMethods:function(e){var t=[];for(var n in e)this._isFunction(e[n])&&t.push(n);return t.length>0},_isInDocument:function(e){while(e=e.parentNode)if(e==document)return!0;return!1},_getXY:function(e){if(this._isNumber(e))return{x:e,y:e};if(this._isArray(e)){if(e.length===1){var t=e[0];if(this._isNumber(t))return{x:t,y:t};if(this._isArray(t))return{x:t[0],y:t[1]};if(this._isObject(t))return t}else if(e.length>=2)return{x:e[0],y:e[1]}}else if(this._isObject(e))return e;return null},_getSize:function(e){if(this._isNumber(e))return{width:e,height:e};if(this._isArray(e))if(e.length===1){var t=e[0];if(this._isNumber(t))return{width:t,height:t};if(this._isArray(t)){if(t.length>=4)return{width:t[2],height:t[3]};if(t.length>=2)return{width:t[0],height:t[1]}}else if(this._isObject(t))return t}else{if(e.length>=4)return{width:e[2],height:e[3]};if(e.length>=2)return{width:e[0],height:e[1]}}else if(this._isObject(e))return e;return null},_getPoints:function(e){if(e===undefined)return[];if(this._isArray(e[0])){var t=[];for(var n=0;n<e.length;n++)t.push({x:e[n][0],y:e[n][1]});return t}if(this._isObject(e[0]))return e;var t=[];for(var n=0;n<e.length;n+=2)t.push({x:e[n],y:e[n+1]});return t},_getImage:function(e,t){if(!e)t(null);else if(this._isElement(e))t(e);else if(this._isString(e)){var n=new Image;n.onload=function(){t(n)},n.src=e}else if(e.data){var r=document.createElement("canvas");r.width=e.width,r.height=e.height;var i=r.getContext("2d");i.putImageData(e,0,0);var s=r.toDataURL(),n=new Image;n.onload=function(){t(n)},n.src=s}else t(null)},_rgbToHex:function(e,t,n){return((1<<24)+(e<<16)+(t<<8)+n).toString(16).slice(1)},_hexToRgb:function(e){var t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}},_getRandomColorKey:function(){var e=Math.round(Math.random()*255),t=Math.round(Math.random()*255),n=Math.round(Math.random()*255);return this._rgbToHex(e,t,n)},_merge:function(e,t){var n=this._clone(t);for(var r in e)this._isObject(e[r])?n[r]=this._merge(e[r],n[r]):n[r]=e[r];return n},_clone:function(e){var t={};for(var n in e)this._isObject(e[n])?t[n]=this._clone(e[n]):t[n]=e[n];return t},_degToRad:function(e){return e*Math.PI/180},_radToDeg:function(e){return e*180/Math.PI}}}(),function(){var e=document.createElement("canvas"),t=e.getContext("2d"),n=window.devicePixelRatio||1,r=t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1,i=n/r;Kinetic.Canvas=function(e,t,n){this.pixelRatio=n||i,this.width=e,this.height=t,this.element=document.createElement("canvas"),this.context=this.element.getContext("2d"),this.setSize(e||0,t||0)},Kinetic.Canvas.prototype={clear:function(){var e=this.getContext(),t=this.getElement();e.clearRect(0,0,t.width,t.height)},getElement:function(){return this.element},getContext:function(){return this.context},setWidth:function(e){this.width=e,this.element.width=e*this.pixelRatio,this.element.style.width=e+"px"},setHeight:function(e){this.height=e,this.element.height=e*this.pixelRatio,this.element.style.height=e+"px"},getWidth:function(){return this.width},getHeight:function(){return this.height},setSize:function(e,t){this.setWidth(e),this.setHeight(t)},toDataURL:function(e,t){try{return this.element.toDataURL(e,t)}catch(n){try{return this.element.toDataURL()}catch(n){return Kinetic.Global.warn("Unable to get data URL. "+n.message),""}}},fill:function(e){e.getFillEnabled()&&this._fill(e)},stroke:function(e){e.getStrokeEnabled()&&this._stroke(e)},fillStroke:function(e){var t=e.getFillEnabled();t&&this._fill(e),e.getStrokeEnabled()&&this._stroke(e,e.hasShadow()&&e.hasFill()&&t)},applyShadow:function(e,t){var n=this.context;n.save(),this._applyShadow(e),t(),n.restore(),t()},_applyLineCap:function(e){var t=e.getLineCap();t&&(this.context.lineCap=t)},_applyOpacity:function(e){var t=e.getAbsoluteOpacity();t!==1&&(this.context.globalAlpha=t)},_applyLineJoin:function(e){var t=e.getLineJoin();t&&(this.context.lineJoin=t)},_applyAncestorTransforms:function(e){var t=this.context;e._eachAncestorReverse(function(e){var n=e.getTransform(),r=n.getMatrix();t.transform(r[0],r[1],r[2],r[3],r[4],r[5])},!0)}},Kinetic.SceneCanvas=function(e,t,n){Kinetic.Canvas.call(this,e,t,n)},Kinetic.SceneCanvas.prototype={setWidth:function(e){var t=this.pixelRatio;Kinetic.Canvas.prototype.setWidth.call(this,e),this.context.scale(t,t)},setHeight:function(e){var t=this.pixelRatio;Kinetic.Canvas.prototype.setHeight.call(this,e),this.context.scale(t,t)},_fillColor:function(e){var t=this.context,n=e.getFill();t.fillStyle=n,e._fillFunc(t)},_fillPattern:function(e){var t=this.context,n=e.getFillPatternImage(),r=e.getFillPatternX(),i=e.getFillPatternY(),s=e.getFillPatternScale(),o=e.getFillPatternRotation(),u=e.getFillPatternOffset(),a=e.getFillPatternRepeat();(r||i)&&t.translate(r||0,i||0),o&&t.rotate(o),s&&t.scale(s.x,s.y),u&&t.translate(-1*u.x,-1*u.y),t.fillStyle=t.createPattern(n,a||"repeat"),t.fill()},_fillLinearGradient:function(e){var t=this.context,n=e.getFillLinearGradientStartPoint(),r=e.getFillLinearGradientEndPoint(),i=e.getFillLinearGradientColorStops(),s=t.createLinearGradient(n.x,n.y,r.x,r.y);for(var o=0;o<i.length;o+=2)s.addColorStop(i[o],i[o+1]);t.fillStyle=s,t.fill()},_fillRadialGradient:function(e){var t=this.context,n=e.getFillRadialGradientStartPoint(),r=e.getFillRadialGradientEndPoint(),i=e.getFillRadialGradientStartRadius(),s=e.getFillRadialGradientEndRadius(),o=e.getFillRadialGradientColorStops(),u=t.createRadialGradient(n.x,n.y,i,r.x,r.y,s);for(var a=0;a<o.length;a+=2)u.addColorStop(o[a],o[a+1]);t.fillStyle=u,t.fill()},_fill:function(e,t){var n=this.context,r=e.getFill(),i=e.getFillPatternImage(),s=e.getFillLinearGradientStartPoint(),o=e.getFillRadialGradientStartPoint(),u=e.getFillPriority();n.save(),!t&&e.hasShadow()&&this._applyShadow(e),r&&u==="color"?this._fillColor(e):i&&u==="pattern"?this._fillPattern(e):s&&u==="linear-gradient"?this._fillLinearGradient(e):o&&u==="radial-gradient"?this._fillRadialGradient(e):r?this._fillColor(e):i?this._fillPattern(e):s?this._fillLinearGradient(e):o&&this._fillRadialGradient(e),n.restore(),!t&&e.hasShadow()&&this._fill(e,!0)},_stroke:function(e,t){var n=this.context,r=e.getStroke(),i=e.getStrokeWidth(),s=e.getDashArray();if(r||i)n.save(),this._applyLineCap(e),s&&e.getDashArrayEnabled()&&(n.setLineDash?n.setLineDash(s):"mozDash"in n?n.mozDash=s:"webkitLineDash"in n&&(n.webkitLineDash=s)),!t&&e.hasShadow()&&this._applyShadow(e),n.lineWidth=i||2,n.strokeStyle=r||"black",e._strokeFunc(n),n.restore(),!t&&e.hasShadow()&&this._stroke(e,!0)},_applyShadow:function(e){var t=this.context;if(e.hasShadow()&&e.getShadowEnabled()){var n=e.getAbsoluteOpacity(),r=e.getShadowColor()||"black",i=e.getShadowBlur()||5,s=e.getShadowOffset()||{x:0,y:0};e.getShadowOpacity()&&(t.globalAlpha=e.getShadowOpacity()*n),t.shadowColor=r,t.shadowBlur=i,t.shadowOffsetX=s.x,t.shadowOffsetY=s.y}}},Kinetic.Global.extend(Kinetic.SceneCanvas,Kinetic.Canvas),Kinetic.HitCanvas=function(e,t,n){Kinetic.Canvas.call(this,e,t,n)},Kinetic.HitCanvas.prototype={_fill:function(e){var t=this.context;t.save(),t.fillStyle="#"+e.colorKey,e._fillFuncHit(t),t.restore()},_stroke:function(e){var t=this.context,n=e.getStroke(),r=e.getStrokeWidth();if(n||r)this._applyLineCap(e),t.save(),t.lineWidth=r||2,t.strokeStyle="#"+e.colorKey,e._strokeFuncHit(t),t.restore()}},Kinetic.Global.extend(Kinetic.HitCanvas,Kinetic.Canvas)}(),function(){Kinetic.Tween=function(e,t,n,r,i,s){this._listeners=[],this.addListener(this),this.obj=e,this.propFunc=t,this.begin=r,this._pos=r,this.setDuration(s),this.isPlaying=!1,this._change=0,this.prevTime=0,this.prevPos=0,this.looping=!1,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.name="",this.func=n,this.setFinish(i)},Kinetic.Tween.prototype={setTime:function(e){this.prevTime=this._time,e>this.getDuration()?this.looping?(this.rewind(e-this._duration),this.update(),this.broadcastMessage("onLooped",{target:this,type:"onLooped"})):(this._time=this._duration,this.update(),this.stop(),this.broadcastMessage("onFinished",{target:this,type:"onFinished"})):e<0?(this.rewind(),this.update()):(this._time=e,this.update())},getTime:function(){return this._time},setDuration:function(e){this._duration=e===null||e<=0?1e5:e},getDuration:function(){return this._duration},setPosition:function(e){this.prevPos=this._pos,this.propFunc(e),this._pos=e,this.broadcastMessage("onChanged",{target:this,type:"onChanged"})},getPosition:function(e){return e===undefined&&(e=this._time),this.func(e,this.begin,this._change,this._duration)},setFinish:function(e){this._change=e-this.begin},getFinish:function(){return this.begin+this._change},start:function(){this.rewind(),this.startEnterFrame(),this.broadcastMessage("onStarted",{target:this,type:"onStarted"})},rewind:function(e){this.stop(),this._time=e===undefined?0:e,this.fixTime(),this.update()},fforward:function(){this._time=this._duration,this.fixTime(),this.update()},update:function(){this.setPosition(this.getPosition(this._time))},startEnterFrame:function(){this.stopEnterFrame(),this.isPlaying=!0,this.onEnterFrame()},onEnterFrame:function(){this.isPlaying&&this.nextFrame()},nextFrame:function(){this.setTime((this.getTimer()-this._startTime)/1e3)},stop:function(){this.stopEnterFrame(),this.broadcastMessage("onStopped",{target:this,type:"onStopped"})},stopEnterFrame:function(){this.isPlaying=!1},continueTo:function(e,t){this.begin=this._pos,this.setFinish(e),this._duration!==undefined&&this.setDuration(t),this.start()},resume:function(){this.fixTime(),this.startEnterFrame(),this.broadcastMessage("onResumed",{target:this,type:"onResumed"})},yoyo:function(){this.continueTo(this.begin,this._time)},addListener:function(e){return this.removeListener(e),this._listeners.push(e)},removeListener:function(e){var t=this._listeners,n=t.length;while(n--)if(t[n]==e)return t.splice(n,1),!0;return!1},broadcastMessage:function(){var e=[];for(var t=0;t<arguments.length;t++)e.push(arguments[t]);var n=e.shift(),r=this._listeners,i=r.length;for(var t=0;t<i;t++)r[t][n]&&r[t][n].apply(r[t],e)},fixTime:function(){this._startTime=this.getTimer()-this._time*1e3},getTimer:function(){return(new Date).getTime()-this._time}},Kinetic.Tweens={"back-ease-in":function(e,t,n,r,i,s){var o=1.70158;return n*(e/=r)*e*((o+1)*e-o)+t},"back-ease-out":function(e,t,n,r,i,s){var o=1.70158;return n*((e=e/r-1)*e*((o+1)*e+o)+1)+t},"back-ease-in-out":function(e,t,n,r,i,s){var o=1.70158;return(e/=r/2)<1?n/2*e*e*(((o*=1.525)+1)*e-o)+t:n/2*((e-=2)*e*(((o*=1.525)+1)*e+o)+2)+t},"elastic-ease-in":function(e,t,n,r,i,s){var o=0;return e===0?t:(e/=r)==1?t+n:(s||(s=r*.3),!i||i<Math.abs(n)?(i=n,o=s/4):o=s/(2*Math.PI)*Math.asin(n/i),-(i*Math.pow(2,10*(e-=1))*Math.sin((e*r-o)*2*Math.PI/s))+t)},"elastic-ease-out":function(e,t,n,r,i,s){var o=0;return e===0?t:(e/=r)==1?t+n:(s||(s=r*.3),!i||i<Math.abs(n)?(i=n,o=s/4):o=s/(2*Math.PI)*Math.asin(n/i),i*Math.pow(2,-10*e)*Math.sin((e*r-o)*2*Math.PI/s)+n+t)},"elastic-ease-in-out":function(e,t,n,r,i,s){var o=0;return e===0?t:(e/=r/2)==2?t+n:(s||(s=r*.3*1.5),!i||i<Math.abs(n)?(i=n,o=s/4):o=s/(2*Math.PI)*Math.asin(n/i),e<1?-0.5*i*Math.pow(2,10*(e-=1))*Math.sin((e*r-o)*2*Math.PI/s)+t:i*Math.pow(2,-10*(e-=1))*Math.sin((e*r-o)*2*Math.PI/s)*.5+n+t)},"bounce-ease-out":function(e,t,n,r){return(e/=r)<1/2.75?n*7.5625*e*e+t:e<2/2.75?n*(7.5625*(e-=1.5/2.75)*e+.75)+t:e<2.5/2.75?n*(7.5625*(e-=2.25/2.75)*e+.9375)+t:n*(7.5625*(e-=2.625/2.75)*e+.984375)+t},"bounce-ease-in":function(e,t,n,r){return n-Kinetic.Tweens["bounce-ease-out"](r-e,0,n,r)+t},"bounce-ease-in-out":function(e,t,n,r){return e<r/2?Kinetic.Tweens["bounce-ease-in"](e*2,0,n,r)*.5+t:Kinetic.Tweens["bounce-ease-out"](e*2-r,0,n,r)*.5+n*.5+t},"ease-in":function(e,t,n,r){return n*(e/=r)*e+t},"ease-out":function(e,t,n,r){return-n*(e/=r)*(e-2)+t},"ease-in-out":function(e,t,n,r){return(e/=r/2)<1?n/2*e*e+t:-n/2*(--e*(e-2)-1)+t},"strong-ease-in":function(e,t,n,r){return n*(e/=r)*e*e*e*e+t},"strong-ease-out":function(e,t,n,r){return n*((e=e/r-1)*e*e*e*e+1)+t},"strong-ease-in-out":function(e,t,n,r){return(e/=r/2)<1?n/2*e*e*e*e*e+t:n/2*((e-=2)*e*e*e*e+2)+t},linear:function(e,t,n,r){return n*e/r+t}}}(),function(){Kinetic.Transform=function(){this.m=[1,0,0,1,0,0]},Kinetic.Transform.prototype={translate:function(e,t){this.m[4]+=this.m[0]*e+this.m[2]*t,this.m[5]+=this.m[1]*e+this.m[3]*t},scale:function(e,t){this.m[0]*=e,this.m[1]*=e,this.m[2]*=t,this.m[3]*=t},rotate:function(e){var t=Math.cos(e),n=Math.sin(e),r=this.m[0]*t+this.m[2]*n,i=this.m[1]*t+this.m[3]*n,s=this.m[0]*-n+this.m[2]*t,o=this.m[1]*-n+this.m[3]*t;this.m[0]=r,this.m[1]=i,this.m[2]=s,this.m[3]=o},getTranslation:function(){return{x:this.m[4],y:this.m[5]}},multiply:function(e){var t=this.m[0]*e.m[0]+this.m[2]*e.m[1],n=this.m[1]*e.m[0]+this.m[3]*e.m[1],r=this.m[0]*e.m[2]+this.m[2]*e.m[3],i=this.m[1]*e.m[2]+this.m[3]*e.m[3],s=this.m[0]*e.m[4]+this.m[2]*e.m[5]+this.m[4],o=this.m[1]*e.m[4]+this.m[3]*e.m[5]+this.m[5];this.m[0]=t,this.m[1]=n,this.m[2]=r,this.m[3]=i,this.m[4]=s,this.m[5]=o},invert:function(){var e=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),t=this.m[3]*e,n=-this.m[1]*e,r=-this.m[2]*e,i=this.m[0]*e,s=e*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=e*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);this.m[0]=t,this.m[1]=n,this.m[2]=r,this.m[3]=i,this.m[4]=s,this.m[5]=o},getMatrix:function(){return this.m}}}(),function(){Kinetic.Collection=function(){var e=[].slice.call(arguments),t=e.length,n=0;this.length=t;for(;n<t;n++)this[n]=e[n];return this},Kinetic.Collection.prototype=new Array,Kinetic.Collection.prototype.apply=function(e){args=[].slice.call(arguments),args.shift();for(var t=0;t<this.length;t++)Kinetic.Type._isFunction(this[t][e])&&this[t][e].apply(this[t],args)},Kinetic.Collection.prototype.each=function(e){for(var t=0;t<this.length;t++)e.call(this[t],t,this[t])}}(),function(){Kinetic.Filters.Grayscale=function(e,t){var n=e.data;for(var r=0;r<n.length;r+=4){var i=.34*n[r]+.5*n[r+1]+.16*n[r+2];n[r]=i,n[r+1]=i,n[r+2]=i}}}(),function(){Kinetic.Filters.Brighten=function(e,t){var n=t.val||0,r=e.data;for(var i=0;i<r.length;i+=4)r[i]+=n,r[i+1]+=n,r[i+2]+=n}}(),function(){Kinetic.Filters.Invert=function(e,t){var n=e.data;for(var r=0;r<n.length;r+=4)n[r]=255-n[r],n[r+1]=255-n[r+1],n[r+2]=255-n[r+2]}}(),function(){Kinetic.Node=function(e){this._nodeInit(e)},Kinetic.Node.prototype={_nodeInit:function(e){this._id=Kinetic.Global.idCounter++,this.defaultNodeAttrs={visible:!0,listening:!0,name:undefined,opacity:1,x:0,y:0,scale:{x:1,y:1},rotation:0,offset:{x:0,y:0},draggable:!1,dragOnTop:!0},this.setDefaultAttrs(this.defaultNodeAttrs),this.eventListeners={},this.setAttrs(e)},on:function(e,t){var n=e.split(" "),r=n.length;for(var i=0;i<r;i++){var s=n[i],o=s,u=o.split("."),a=u[0],f=u.length>1?u[1]:"";this.eventListeners[a]||(this.eventListeners[a]=[]),this.eventListeners[a].push({name:f,handler:t})}},off:function(e){var t=e.split(" "),n=t.length;for(var r=0;r<n;r++){var i=t[r],s=i,o=s.split("."),u=o[0];if(o.length>1)if(u)this.eventListeners[u]&&this._off(u,o[1]);else for(var i in this.eventListeners)this._off(i,o[1]);else delete this.eventListeners[u]}},remove:function(){var e=this.getParent();e&&e.children&&(e.children.splice(this.index,1),e._setChildrenIndices()),delete this.parent},destroy:function(){var e=this.getParent(),t=this.getStage(),n=Kinetic.DD,r=Kinetic.Global;while(this.children&&this.children.length>0)this.children[0].destroy();r._removeId(this.getId()),r._removeName(this.getName(),this._id),n&&n.node&&n.node._id===this._id&&node._endDrag(),this.trans&&this.trans.stop(),this.remove()},getAttrs:function(){return this.attrs},setDefaultAttrs:function(e){this.attrs===undefined&&(this.attrs={});if(e)for(var t in e)this.attrs[t]===undefined&&(this.attrs[t]=e[t])},setAttrs:function(e){if(e)for(var t in e){var n="set"+t.charAt(0).toUpperCase()+t.slice(1);Kinetic.Type._isFunction(this[n])?this[n](e[t]):this.setAttr(t,e[t])}},getVisible:function(){var e=this.attrs.visible,t=this.getParent();return e&&t&&!t.getVisible()?!1:e},getListening:function(){var e=this.attrs.listening,t=this.getParent();return e&&t&&!t.getListening()?!1:e},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},getZIndex:function(){return this.index},getAbsoluteZIndex:function(){function i(t){var s=[],o=t.length;for(var u=0;u<o;u++){var a=t[u];r++,a.nodeType!=="Shape"&&(s=s.concat(a.getChildren())),a._id===n._id&&(u=o)}s.length>0&&s[0].getLevel()<=e&&i(s)}var e=this.getLevel(),t=this.getStage(),n=this,r=0;return n.nodeType!=="Stage"&&i(n.getStage().getChildren()),r},getLevel:function(){var e=0,t=this.parent;while(t)e++,t=t.parent;return e},setPosition:function(){var e=Kinetic.Type._getXY([].slice.call(arguments));this.setAttr("x",e.x),this.setAttr("y",e.y)},getPosition:function(){var e=this.attrs;return{x:e.x,y:e.y}},getAbsolutePosition:function(){var e=this.getAbsoluteTransform(),t=this.getOffset();return e.translate(t.x,t.y),e.getTranslation()},setAbsolutePosition:function(){var e=Kinetic.Type._getXY([].slice.call(arguments)),t=this._clearTransform();this.attrs.x=t.x,this.attrs.y=t.y,delete t.x,delete t.y;var n=this.getAbsoluteTransform();n.invert(),n.translate(e.x,e.y),e={x:this.attrs.x+n.getTranslation().x,y:this.attrs.y+n.getTranslation().y},this.setPosition(e.x,e.y),this._setTransform(t)},move:function(){var e=Kinetic.Type._getXY([].slice.call(arguments)),t=this.getX(),n=this.getY();e.x!==undefined&&(t+=e.x),e.y!==undefined&&(n+=e.y),this.setPosition(t,n)},_eachAncestorReverse:function(e,t){var n=[],r=this.getParent();t&&n.unshift(this);while(r)n.unshift(r),r=r.parent;var i=n.length;for(var s=0;s<i;s++)e(n[s])},rotate:function(e){this.setRotation(this.getRotation()+e)},rotateDeg:function(e){this.setRotation(this.getRotation()+Kinetic.Type._degToRad(e))},moveToTop:function(){var e=this.index;return this.parent.children.splice(e,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0},moveUp:function(){var e=this.index,t=this.parent.getChildren().length;if(e<t-1)return this.parent.children.splice(e,1),this.parent.children.splice(e+1,0,this),this.parent._setChildrenIndices(),!0},moveDown:function(){var e=this.index;if(e>0)return this.parent.children.splice(e,1),this.parent.children.splice(e-1,0,this),this.parent._setChildrenIndices(),!0},moveToBottom:function(){var e=this.index;if(e>0)return this.parent.children.splice(e,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0},setZIndex:function(e){var t=this.index;this.parent.children.splice(t,1),this.parent.children.splice(e,0,this),this.parent._setChildrenIndices()},getAbsoluteOpacity:function(){var e=this.getOpacity();return this.getParent()&&(e*=this.getParent().getAbsoluteOpacity()),e},moveTo:function(e){Kinetic.Node.prototype.remove.call(this),e.add(this)},toObject:function(){var e=Kinetic.Type,t={},n=this.attrs;t.attrs={};for(var r in n){var i=n[r];!e._isFunction(i)&&!e._isElement(i)&&(!e._isObject(i)||!e._hasMethods(i))&&(t.attrs[r]=i)}return t.nodeType=this.nodeType,t.shapeType=this.shapeType,t},toJSON:function(){return JSON.stringify(this.toObject())},getParent:function(){return this.parent},getLayer:function(){return this.getParent().getLayer()},getStage:function(){return this.getParent()?this.getParent().getStage():undefined},simulate:function(e,t){this._handleEvent(e,t||{})},fire:function(e,t){this._executeHandlers(e,t||{})},getAbsoluteTransform:function(){var e=new Kinetic.Transform;return this._eachAncestorReverse(function(t){var n=t.getTransform();e.multiply(n)},!0),e},getTransform:function(){var e=new Kinetic.Transform,t=this.attrs,n=t.x,r=t.y,i=t.rotation,s=t.scale,o=s.x,u=s.y,a=t.offset,f=a.x,l=a.y;return(n!==0||r!==0)&&e.translate(n,r),i!==0&&e.rotate(i),(o!==1||u!==1)&&e.scale(o,u),(f!==0||l!==0)&&e.translate(-1*f,-1*l),e},clone:function(e){var t=this.shapeType||this.nodeType,n=new Kinetic[t](this.attrs);for(var r in this.eventListeners){var i=this.eventListeners[r],s=i.length;for(var o=0;o<s;o++){var u=i[o];u.name.indexOf("kinetic")<0&&(n.eventListeners[r]||(n.eventListeners[r]=[]),n.eventListeners[r].push(u))}}return n.setAttrs(e),n},toDataURL:function(e){e=e||{};var t=e.mimeType||null,n=e.quality||null,r,i,s=e.x||0,o=e.y||0;return e.width&&e.height?r=new Kinetic.SceneCanvas(e.width,e.height,1):(r=this.getStage().bufferCanvas,r.clear()),i=r.getContext(),i.save(),(s||o)&&i.translate(-1*s,-1*o),this.drawScene(r),i.restore(),r.toDataURL(t,n)},toImage:function(e){Kinetic.Type._getImage(this.toDataURL(e),function(t){e.callback(t)})},setSize:function(){var e=Kinetic.Type._getSize(Array.prototype.slice.call(arguments));this.setWidth(e.width),this.setHeight(e.height)},getSize:function(){return{width:this.getWidth(),height:this.getHeight()}},getWidth:function(){return this.attrs.width||0},getHeight:function(){return this.attrs.height||0},_get:function(e){return this.nodeType===e?[this]:[]},_off:function(e,t){for(var n=0;n<this.eventListeners[e].length;n++)if(this.eventListeners[e][n].name===t){this.eventListeners[e].splice(n,1);if(this.eventListeners[e].length===0){delete this.eventListeners[e];break}n--}},_clearTransform:function(){var e=this.attrs,t=e.scale,n=e.offset,r={x:e.x,y:e.y,rotation:e.rotation,scale:{x:t.x,y:t.y},offset:{x:n.x,y:n.y}};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scale={x:1,y:1},this.attrs.offset={x:0,y:0},r},_setTransform:function(e){for(var t in e)this.attrs[t]=e[t]},_fireBeforeChangeEvent:function(e,t,n){this._handleEvent("before"+e.toUpperCase()+"Change",{oldVal:t,newVal:n})},_fireChangeEvent:function(e,t,n){this._handleEvent(e+"Change",{oldVal:t,newVal:n})},setId:function(e){var t=this.getId(),n=this.getStage(),r=Kinetic.Global;r._removeId(t),r._addId(this,e),this.setAttr("id",e)},setName:function(e){var t=this.getName(),n=this.getStage(),r=Kinetic.Global;r._removeName(t,this._id),r._addName(this,e),this.setAttr("name",e)},setAttr:function(e,t){if(t!==undefined){var n=this.attrs[e];this._fireBeforeChangeEvent(e,n,t),this.attrs[e]=t,this._fireChangeEvent(e,n,t)}},_handleEvent:function(e,t,n){t&&this.nodeType==="Shape"&&(t.shape=this);var r=this.getStage(),i=this.eventListeners,s=!0;e==="mouseenter"&&n&&this._id===n._id?s=!1:e==="mouseleave"&&n&&this._id===n._id&&(s=!1),s&&(i[e]&&this.fire(e,t),t&&!t.cancelBubble&&this.parent&&(n&&n.parent?this._handleEvent.call(this.parent,e,t,n.parent):this._handleEvent.call(this.parent,e,t)))},_executeHandlers:function(e,t){var n=this.eventListeners[e],r=n.length;for(var i=0;i<r;i++)n[i].handler.apply(this,[t])}},Kinetic.Node.addSetters=function(e,t){var n=t.length;for(var r=0;r<n;r++){var i=t[r];this._addSetter(e,i)}},Kinetic.Node.addPointSetters=function(e,t){var n=t.length;for(var r=0;r<n;r++){var i=t[r];this._addPointSetter(e,i)}},Kinetic.Node.addRotationSetters=function(e,t){var n=t.length;for(var r=0;r<n;r++){var i=t[r];this._addRotationSetter(e,i)}},Kinetic.Node.addGetters=function(e,t){var n=t.length;for(var r=0;r<n;r++){var i=t[r];this._addGetter(e,i)}},Kinetic.Node.addRotationGetters=function(e,t){var n=t.length;for(var r=0;r<n;r++){var i=t[r];this._addRotationGetter(e,i)}},Kinetic.Node.addGettersSetters=function(e,t){this.addSetters(e,t),this.addGetters(e,t)},Kinetic.Node.addPointGettersSetters=function(e,t){this.addPointSetters(e,t),this.addGetters(e,t)},Kinetic.Node.addRotationGettersSetters=function(e,t){this.addRotationSetters(e,t),this.addRotationGetters(e,t)},Kinetic.Node._addSetter=function(e,t){var n=this,r="set"+t.charAt(0).toUpperCase()+t.slice(1);e.prototype[r]=function(e){this.setAttr(t,e)}},Kinetic.Node._addPointSetter=function(e,t){var n=this,r="set"+t.charAt(0).toUpperCase()+t.slice(1);e.prototype[r]=function(){var e=Kinetic.Type._getXY([].slice.call(arguments));e&&e.x===undefined&&(e.x=this.attrs[t].x),e&&e.y===undefined&&(e.y=this.attrs[t].y),this.setAttr(t,e)}},Kinetic.Node._addRotationSetter=function(e,t){var n=this,r="set"+t.charAt(0).toUpperCase()+t.slice(1);e.prototype[r]=function(e){this.setAttr(t,e)},e.prototype[r+"Deg"]=function(e){this.setAttr(t,Kinetic.Type._degToRad(e))}},Kinetic.Node._addGetter=function(e,t){var n=this,r="get"+t.charAt(0).toUpperCase()+t.slice(1);e.prototype[r]=function(e){return this.attrs[t]}},Kinetic.Node._addRotationGetter=function(e,t){var n=this,r="get"+t.charAt(0).toUpperCase()+t.slice(1);e.prototype[r]=function(){return this.attrs[t]},e.prototype[r+"Deg"]=function(){return Kinetic.Type._radToDeg(this.attrs[t])}},Kinetic.Node.create=function(e,t){return this._createNode(JSON.parse(e),t)},Kinetic.Node._createNode=function(e,t){var n;e.nodeType==="Shape"?e.shapeType===undefined?n="Shape":n=e.shapeType:n=e.nodeType,t&&(e.attrs.container=t);var r=new Kinetic[n](e.attrs);if(e.children){var i=e.children.length;for(var s=0;s<i;s++)r.add(this._createNode(e.children[s]))}return r},Kinetic.Node.addGettersSetters(Kinetic.Node,["x","y","opacity"]),Kinetic.Node.addGetters(Kinetic.Node,["name","id"]),Kinetic.Node.addRotationGettersSetters(Kinetic.Node,["rotation"]),Kinetic.Node.addPointGettersSetters(Kinetic.Node,["scale","offset"]),Kinetic.Node.addSetters(Kinetic.Node,["width","height","listening","visible"]),Kinetic.Node.prototype.isListening=Kinetic.Node.prototype.getListening,Kinetic.Node.prototype.isVisible=Kinetic.Node.prototype.getVisible;var e=["on","off"];for(var t=0;t<2;t++)(function(t){var n=e[t];Kinetic.Collection.prototype[n]=function(){var e=[].slice.call(arguments);e.unshift(n),this.apply.apply(this,e)}})(t)}(),function(){Kinetic.Animation=function(e,t){this.func=e,this.node=t,this.id=Kinetic.Animation.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:(new Date).getTime()}},Kinetic.Animation.prototype={isRunning:function(){var e=Kinetic.Animation,t=e.animations;for(var n=0;n<t.length;n++)if(t[n].id===this.id)return!0;return!1},start:function(){this.stop(),this.frame.timeDiff=0,this.frame.lastTime=(new Date).getTime(),Kinetic.Animation._addAnimation(this)},stop:function(){Kinetic.Animation._removeAnimation(this)},_updateFrameObject:function(e){this.frame.timeDiff=e-this.frame.lastTime,this.frame.lastTime=e,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1e3/this.frame.timeDiff}},Kinetic.Animation.animations=[],Kinetic.Animation.animIdCounter=0,Kinetic.Animation.animRunning=!1,Kinetic.Animation.fixedRequestAnimFrame=function(e){window.setTimeout(e,1e3/60)},Kinetic.Animation._addAnimation=function(e){this.animations.push(e),this._handleAnimation()},Kinetic.Animation._removeAnimation=function(e){var t=e.id,n=this.animations,r=n.length;for(var i=0;i<r;i++)if(n[i].id===t){this.animations.splice(i,1);break}},Kinetic.Animation._runFrames=function(){var e={},t=this.animations;for(var n=0;n<t.length;n++){var r=t[n],i=r.node,s=r.func;r._updateFrameObject((new Date).getTime()),i&&i._id!==undefined&&(e[i._id]=i),s&&s(r.frame)}for(var o in e)e[o].draw()},Kinetic.Animation._animationLoop=function(){var e=this;this.animations.length>0?(this._runFrames(),Kinetic.Animation.requestAnimFrame(function(){e._animationLoop()})):this.animRunning=!1},Kinetic.Animation._handleAnimation=function(){var e=this;this.animRunning||(this.animRunning=!0,e._animationLoop())},RAF=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||Kinetic.Animation.fixedRequestAnimFrame}(),Kinetic.Animation.requestAnimFrame=function(e){var t=Kinetic.DD&&Kinetic.DD.moving?this.fixedRequestAnimFrame:RAF;t(e)};var e=Kinetic.Node.prototype.moveTo;Kinetic.Node.prototype.moveTo=function(t){e.call(this,t)}}(),function(){Kinetic.DD={anim:new Kinetic.Animation,moving:!1,offset:{x:0,y:0}},Kinetic.getNodeDragging=function(){return Kinetic.DD.node},Kinetic.DD._setupDragLayerAndGetContainer=function(e){var t=e.getStage(),n=e.nodeType,r,i;return e._eachAncestorReverse(function(e){e.nodeType==="Layer"?(t.dragLayer.setAttrs(e.getAttrs()),r=t.dragLayer,t.add(t.dragLayer)):e.nodeType==="Group"&&(i=new Kinetic.Group(e.getAttrs()),r.add(i),r=i)}),r},Kinetic.DD._initDragLayer=function(e){e.dragLayer=new Kinetic.Layer,e.dragLayer.getCanvas().getElement().className="kinetic-drag-and-drop-layer"},Kinetic.DD._drag=function(e){var t=Kinetic.DD,n=t.node;if(n){var r=n.getStage().getUserPosition(),i=n.attrs.dragBoundFunc,s={x:r.x-t.offset.x,y:r.y-t.offset.y};i!==undefined&&(s=i.call(n,s,e)),n.setAbsolutePosition(s),t.moving||(t.moving=!0,n.setListening(!1),n._handleEvent("dragstart",e)),n._handleEvent("dragmove",e)}},Kinetic.DD._endDrag=function(e){var t=Kinetic.DD,n=t.node;if(n){var r=n.nodeType,i=n.getStage();n.setListening(!0),r==="Stage"?n.draw():((r==="Group"||r==="Shape")&&n.getDragOnTop()&&t.prevParent&&(n.moveTo(t.prevParent),n.getStage().dragLayer.remove(),t.prevParent=null),n.getLayer().draw()),delete t.node,t.anim.stop(),t.moving&&(t.moving=!1,n._handleEvent("dragend",e))}},Kinetic.Node.prototype._startDrag=function(e){var t=Kinetic.DD,n=this,r=this.getStage(),i=r.getUserPosition();if(i){var s=this.getTransform().getTranslation(),o=this.getAbsolutePosition(),u=this.nodeType,a;t.node=this,t.offset.x=i.x-o.x,t.offset.y=i.y-o.y,u==="Stage"||u==="Layer"?(t.anim.node=this,t.anim.start()):this.getDragOnTop()?(a=t._setupDragLayerAndGetContainer(this),t.anim.node=r.dragLayer,t.prevParent=this.getParent(),setTimeout(function(){t.node&&(n.moveTo(a),t.prevParent.getLayer().draw(),r.dragLayer.draw(),t.anim.start())},0)):(t.anim.node=this.getLayer(),t.anim.start())}},Kinetic.Node.prototype.setDraggable=function(e){this.setAttr("draggable",e),this._dragChange()},Kinetic.Node.prototype.getDraggable=function(){return this.attrs.draggable},Kinetic.Node.prototype.isDragging=function(){var e=Kinetic.DD;return e.node&&e.node._id===this._id&&e.moving},Kinetic.Node.prototype._listenDrag=function(){this._dragCleanup();var e=this;this.on("mousedown.kinetic touchstart.kinetic",function(t){Kinetic.getNodeDragging()||e._startDrag(t)})},Kinetic.Node.prototype._dragChange=function(){if(this.attrs.draggable)this._listenDrag();else{this._dragCleanup();var e=this.getStage(),t=Kinetic.DD;e&&t.node&&t.node._id===this._id&&t._endDrag()}},Kinetic.Node.prototype._dragCleanup=function(){this.off("mousedown.kinetic"),this.off("touchstart.kinetic")},Kinetic.Node.prototype.isDraggable=Kinetic.Node.prototype.getDraggable,Kinetic.Node.addGettersSetters(Kinetic.Node,["dragBoundFunc","dragOnTop"]);var e=document.getElementsByTagName("html")[0];e.addEventListener("mouseup",Kinetic.DD._endDrag,!0),e.addEventListener("touchend",Kinetic.DD._endDrag,!0)}(),function(){Kinetic.Transition=function(e,t){function i(e,t,r,s){for(var o in e)o!=="duration"&&o!=="easing"&&o!=="callback"&&(Kinetic.Type._isObject(e[o])?(r[o]={},i(e[o],t[o],r[o],s)):n._add(n._getTween(t,o,e[o],r,s)))}var n=this,r={};this.node=e,this.config=t,this.tweens=[],i(t,e.attrs,r,r),this.tweens[0].onStarted=function(){},this.tweens[0].onStopped=function(){e.transAnim.stop()},this.tweens[0].onResumed=function(){e.transAnim.start()},this.tweens[0].onLooped=function(){},this.tweens[0].onChanged=function(){},this.tweens[0].onFinished=function(){var n={};for(var r in t)r!=="duration"&&r!=="easing"&&r!=="callback"&&(n[r]=t[r]);e.transAnim.stop(),e.setAttrs(n),t.callback&&t.callback()}},Kinetic.Transition.prototype={start:function(){for(var e=0;e<this.tweens.length;e++)this.tweens[e].start()},stop:function(){for(var e=0;e<this.tweens.length;e++)this.tweens[e].stop()},resume:function(){for(var e=0;e<this.tweens.length;e++)this.tweens[e].resume()},_onEnterFrame:function(){for(var e=0;e<this.tweens.length;e++)this.tweens[e].onEnterFrame()},_add:function(e){this.tweens.push(e)},_getTween:function(e,t,n,r,i){var s=this.config,o=this.node,u=s.easing;u===undefined&&(u="linear");var a=new Kinetic.Tween(o,function(e){r[t]=e,o.setAttrs(i)},Kinetic.Tweens[u],e[t],n,s.duration);return a}},Kinetic.Node.prototype.transitionTo=function(e){var t=this,n=new Kinetic.Transition(this,e);return this.transAnim||(this.transAnim=new Kinetic.Animation),this.transAnim.func=function(){n._onEnterFrame()},this.transAnim.node=this.nodeType==="Stage"?this:this.getLayer(),n.start(),this.transAnim.start(),this.trans=n,n}}(),function(){Kinetic.Container=function(e){this._containerInit(e)},Kinetic.Container.prototype={_containerInit:function(e){this.children=[],Kinetic.Node.call(this,e)},getChildren:function(){return this.children},removeChildren:function(){while(this.children.length>0)this.children[0].remove()},add:function(e){var t=Kinetic.Global,n=this.children;return e.index=n.length,e.parent=this,n.push(e),this},get:function(e){var t=new Kinetic.Collection;if(e.charAt(0)==="#"){var n=this._getNodeById(e.slice(1));n&&t.push(n)}else if(e.charAt(0)==="."){var r=this._getNodesByName(e.slice(1));Kinetic.Collection.apply(t,r)}else{var i=[],s=this.getChildren(),o=s.length;for(var u=0;u<o;u++)i=i.concat(s[u]._get(e));Kinetic.Collection.apply(t,i)}return t},_getNodeById:function(e){var t=this.getStage(),n=Kinetic.Global,r=n.ids[e];return r!==undefined&&this.isAncestorOf(r)?r:null},_getNodesByName:function(e){var t=Kinetic.Global,n=t.names[e]||[];return this._getDescendants(n)},_get:function(e){var t=Kinetic.Node.prototype._get.call(this,e),n=this.getChildren(),r=n.length;for(var i=0;i<r;i++)t=t.concat(n[i]._get(e));return t},toObject:function(){var e=Kinetic.Node.prototype.toObject.call(this);e.children=[];var t=this.getChildren(),n=t.length;for(var r=0;r<n;r++){var i=t[r];e.children.push(i.toObject())}return e},_getDescendants:function(e){var t=[],n=e.length;for(var r=0;r<n;r++){var i=e[r];this.isAncestorOf(i)&&t.push(i)}return t},isAncestorOf:function(e){var t=e.getParent();while(t){if(t._id===this._id)return!0;t=t.getParent()}return!1},clone:function(e){var t=Kinetic.Node.prototype.clone.call(this,e);for(var n in this.children)t.add(this.children[n].clone());return t},getIntersections:function(){var e=Kinetic.Type._getXY(Array.prototype.slice.call(arguments)),t=[],n=this.get("Shape"),r=n.length;for(var i=0;i<r;i++){var s=n[i];s.isVisible()&&s.intersects(e)&&t.push(s)}return t},_setChildrenIndices:function(){var e=this.children,t=e.length;for(var n=0;n<t;n++)e[n].index=n},draw:function(){this.drawScene(),this.drawHit()},drawScene:function(e){if(this.isVisible()){var t=this.children,n=t.length;for(var r=0;r<n;r++)t[r].drawScene(e)}},drawHit:function(){if(this.isVisible()&&this.isListening()){var e=this.children,t=e.length;for(var n=0;n<t;n++)e[n].drawHit()}}},Kinetic.Global.extend(Kinetic.Container,Kinetic.Node)}(),function(){function e(e){e.fill()}function t(e){e.stroke()}function n(e){e.fill()}function r(e){e.stroke()}Kinetic.Shape=function(e){this._initShape(e)},Kinetic.Shape.prototype={_initShape:function(i){this.setDefaultAttrs({fillEnabled:!0,strokeEnabled:!0,shadowEnabled:!0,dashArrayEnabled:!0,fillPriority:"color"}),this.nodeType="Shape",this._fillFunc=e,this._strokeFunc=t,this._fillFuncHit=n,this._strokeFuncHit=r;var s=Kinetic.Global.shapes,o;for(;;){o=Kinetic.Type._getRandomColorKey();if(o&&!(o in s))break}this.colorKey=o,s[o]=this,Kinetic.Node.call(this,i)},getContext:function(){return this.getLayer().getContext()},getCanvas:function(){return this.getLayer().getCanvas()},hasShadow:function(){return!!(this.getShadowColor()||this.getShadowBlur()||this.getShadowOffset())},hasFill:function(){return!!(this.getFill()||this.getFillPatternImage()||this.getFillLinearGradientStartPoint()||this.getFillRadialGradientStartPoint())},_get:function(e){return this.nodeType===e||this.shapeType===e?[this]:[]},intersects:function(){var e=Kinetic.Type._getXY(Array.prototype.slice.call(arguments)),t=this.getStage(),n=t.hitCanvas;n.clear(),this.drawScene(n);var r=n.context.getImageData(Math.round(e.x),Math.round(e.y),1,1).data;return r[3]>0},enableFill:function(){this.setAttr("fillEnabled",!0)},disableFill:function(){this.setAttr("fillEnabled",!1)},enableStroke:function(){this.setAttr("strokeEnabled",!0)},disableStroke:function(){this.setAttr("strokeEnabled",!1)},enableShadow:function(){this.setAttr("shadowEnabled",!0)},disableShadow:function(){this.setAttr("shadowEnabled",!1)},enableDashArray:function(){this.setAttr("dashArrayEnabled",!0)},disableDashArray:function(){this.setAttr("dashArrayEnabled",!1)},remove:function(){Kinetic.Node.prototype.remove.call(this),delete Kinetic.Global.shapes[this.colorKey]},drawScene:function(e){var t=this.attrs,n=t.drawFunc,e=e||this.getLayer().getCanvas(),r=e.getContext();n&&this.isVisible()&&(r.save(),e._applyOpacity(this),e._applyLineJoin(this),e._applyAncestorTransforms(this),n.call(this,e),r.restore())},drawHit:function(){var e=this.attrs,t=e.drawHitFunc||e.drawFunc,n=this.getLayer().hitCanvas,r=n.getContext();t&&this.isVisible()&&this.isListening()&&(r.save(),n._applyLineJoin(this),n._applyAncestorTransforms(this),t.call(this,n),r.restore())},_setDrawFuncs:function(){!this.attrs.drawFunc&&this.drawFunc&&this.setDrawFunc(this.drawFunc),!this.attrs.drawHitFunc&&this.drawHitFunc&&this.setDrawHitFunc(this.drawHitFunc)}},Kinetic.Global.extend(Kinetic.Shape,Kinetic.Node),Kinetic.Node.addGettersSetters(Kinetic.Shape,["stroke","lineJoin","lineCap","strokeWidth","drawFunc","drawHitFunc","dashArray","shadowColor","shadowBlur","shadowOpacity","fillPatternImage","fill","fillPatternX","fillPatternY","fillLinearGradientColorStops","fillRadialGradientStartRadius","fillRadialGradientEndRadius","fillRadialGradientColorStops","fillPatternRepeat","fillEnabled","strokeEnabled","shadowEnabled","dashArrayEnabled","fillPriority"]),Kinetic.Node.addPointGettersSetters(Kinetic.Shape,["fillPatternOffset","fillPatternScale","fillLinearGradientStartPoint","fillLinearGradientEndPoint","fillRadialGradientStartPoint","fillRadialGradientEndPoint","shadowOffset"]),Kinetic.Node.addRotationGettersSetters(Kinetic.Shape,["fillPatternRotation"])}(),function(){Kinetic.Stage=function(e){this._initStage(e)},Kinetic.Stage.prototype={_initStage:function(e){var t=Kinetic.DD;this.setDefaultAttrs({width:400,height:200}),Kinetic.Container.call(this,e),this._setStageDefaultProperties(),this._id=Kinetic.Global.idCounter++,this._buildDOM(),this._bindContentEvents(),Kinetic.Global.stages.push(this),t&&t._initDragLayer(this)},setContainer:function(e){typeof e=="string"&&(e=document.getElementById(e)),this.setAttr("container",e)},setHeight:function(e){Kinetic.Node.prototype.setHeight.call(this,e),this._resizeDOM()},setWidth:function(e){Kinetic.Node.prototype.setWidth.call(this,e),this._resizeDOM()},clear:function(){var e=this.children;for(var t=0;t<e.length;t++)e[t].clear()},remove:function(){var e=this.content;Kinetic.Node.prototype.remove.call(this),e&&Kinetic.Type._isInDocument(e)&&this.attrs.container.removeChild(e)},reset:function(){this.removeChildren(),this._setStageDefaultProperties(),this.setAttrs(this.defaultNodeAttrs)},getMousePosition:function(){return this.mousePos},getTouchPosition:function(){return this.touchPos},getUserPosition:function(){return this.getTouchPosition()||this.getMousePosition()},getStage:function(){return this},getContent:function(){return this.content},toDataURL:function(e){function a(r){var i=u[r],f=i.toDataURL(),l=new Image;l.onload=function(){o.drawImage(l,0,0),r<u.length-1?a(r+1):e.callback(s.toDataURL(t,n))},l.src=f}e=e||{};var t=e.mimeType||null,n=e.quality||null,r=e.x||0,i=e.y||0,s=new Kinetic.SceneCanvas(e.width||this.getWidth(),e.height||this.getHeight()),o=s.getContext(),u=this.children;(r||i)&&o.translate(-1*r,-1*i),a(0)},toImage:function(e){var t=e.callback;e.callback=function(e){Kinetic.Type._getImage(e,function(e){t(e)})},this.toDataURL(e)},getIntersection:function(e){var t,n=this.getChildren();for(var r=n.length-1;r>=0;r--){var i=n[r];if(i.isVisible()&&i.isListening()){var s=i.hitCanvas.context.getImageData(Math.round(e.x),Math.round(e.y),1,1).data;if(s[3]===255){var o=Kinetic.Type._rgbToHex(s[0],s[1],s[2]);return t=Kinetic.Global.shapes[o],{shape:t,pixel:s}}if(s[0]>0||s[1]>0||s[2]>0||s[3]>0)return{pixel:s}}}return null},_resizeDOM:function(){if(this.content){var e=this.attrs.width,t=this.attrs.height;this.content.style.width=e+"px",this.content.style.height=t+"px",this.bufferCanvas.setSize(e,t,1),this.hitCanvas.setSize(e,t);var n=this.children;for(var r=0;r<n.length;r++){var i=n[r];i.getCanvas().setSize(e,t),i.hitCanvas.setSize(e,t),i.draw()}}},add:function(e){return Kinetic.Container.prototype.add.call(this,e),e.canvas.setSize(this.attrs.width,this.attrs.height),e.hitCanvas.setSize(this.attrs.width,this.attrs.height),e.draw(),this.content.appendChild(e.canvas.element),this},getDragLayer:function(){return this.dragLayer},_setUserPosition:function(e){e||(e=window.event),this._setMousePosition(e),this._setTouchPosition(e)},_bindContentEvents:function(){var e=Kinetic.Global,t=this,n=["mousedown","mousemove","mouseup","mouseout","touchstart","touchmove","touchend"];for(var r=0;r<n.length;r++){var i=n[r];(function(){var e=i;t.content.addEventListener(e,function(n){t["_"+e](n)},!1)})()}},_mouseout:function(e){this._setUserPosition(e);var t=Kinetic.DD,n=this.targetShape;n&&(!t||!t.moving)&&(n._handleEvent("mouseout",e),n._handleEvent("mouseleave",e),this.targetShape=null),this.mousePos=undefined},_mousemove:function(e){this._setUserPosition(e);var t=Kinetic.DD,n=this.getIntersection(this.getUserPosition());if(n){var r=n.shape;r&&(!!t&&!!t.moving||n.pixel[3]!==255||!!this.targetShape&&this.targetShape._id===r._id?r._handleEvent("mousemove",e):(this.targetShape&&(this.targetShape._handleEvent("mouseout",e,r),this.targetShape._handleEvent("mouseleave",e,r)),r._handleEvent("mouseover",e,this.targetShape),r._handleEvent("mouseenter",e,this.targetShape),this.targetShape=r))}else this.targetShape&&(!t||!t.moving)&&(this.targetShape._handleEvent("mouseout",e),this.targetShape._handleEvent("mouseleave",e),this.targetShape=null);t&&t._drag(e)},_mousedown:function(e){var t,n=Kinetic.DD;this._setUserPosition(e),t=this.getIntersection(this.getUserPosition());if(t&&t.shape){var r=t.shape;this.clickStart=!0,r._handleEvent("mousedown",e)}n&&this.attrs.draggable&&!n.node&&this._startDrag(e)},_mouseup:function(e){this._setUserPosition(e);var t=this,n=Kinetic.DD,r=this.getIntersection(this.getUserPosition());if(r&&r.shape){var i=r.shape;i._handleEvent("mouseup",e),this.clickStart&&(!n||!n.moving||!n.node)&&(i._handleEvent("click",e),this.inDoubleClickWindow&&i._handleEvent("dblclick",e),this.inDoubleClickWindow=!0,setTimeout(function(){t.inDoubleClickWindow=!1},this.dblClickWindow))}this.clickStart=!1},_touchstart:function(e){var t,n=Kinetic.DD;this._setUserPosition(e),e.preventDefault(),t=this.getIntersection(this.getUserPosition());if(t&&t.shape){var r=t.shape;this.tapStart=!0,r._handleEvent("touchstart",e)}n&&this.attrs.draggable&&!n.node&&this._startDrag(e)},_touchend:function(e){this._setUserPosition(e);var t=this,n=Kinetic.DD,r=this.getIntersection(this.getUserPosition());if(r&&r.shape){var i=r.shape;i._handleEvent("touchend",e),this.tapStart&&(!n||!n.moving||!n.node)&&(i._handleEvent("tap",e),this.inDoubleClickWindow&&i._handleEvent("dbltap",e),this.inDoubleClickWindow=!0,setTimeout(function(){t.inDoubleClickWindow=!1},this.dblClickWindow))}this.tapStart=!1},_touchmove:function(e){this._setUserPosition(e);var t=Kinetic.DD;e.preventDefault();var n=this.getIntersection(this.getUserPosition());if(n&&n.shape){var r=n.shape;r._handleEvent("touchmove",e)}t&&t._drag(e)},_setMousePosition:function(e){var t=e.clientX-this._getContentPosition().left,n=e.clientY-this._getContentPosition().top;this.mousePos={x:t,y:n}},_setTouchPosition:function(e){if(e.touches!==undefined&&e.touches.length===1){var t=e.touches[0],n=t.clientX-this._getContentPosition().left,r=t.clientY-this._getContentPosition().top;this.touchPos={x:n,y:r}}},_getContentPosition:function(){var e=this.content.getBoundingClientRect();return{top:e.top,left:e.left}},_buildDOM:function(){this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.display="inline-block",this.content.className="kineticjs-content",this.attrs.container.appendChild(this.content),this.bufferCanvas=new Kinetic.SceneCanvas,this.hitCanvas=new Kinetic.HitCanvas,this._resizeDOM()},_onContent:function(e,t){var n=e.split(" ");for(var r=0;r<n.length;r++){var i=n[r];this.content.addEventListener(i,t,!1)}},_setStageDefaultProperties:function(){this.nodeType="Stage",this.dblClickWindow=400,this.targetShape=null,this.mousePos=undefined,this.clickStart=!1,this.touchPos=undefined,this.tapStart=!1}},Kinetic.Global.extend(Kinetic.Stage,Kinetic.Container),Kinetic.Node.addGetters(Kinetic.Stage,["container"])}(),function(){Kinetic.Layer=function(e){this._initLayer(e)},Kinetic.Layer.prototype={_initLayer:function(e){this.setDefaultAttrs({clearBeforeDraw:!0}),this.nodeType="Layer",this.beforeDrawFunc=undefined,this.afterDrawFunc=undefined,this.canvas=new Kinetic.SceneCanvas,this.canvas.getElement().style.position="absolute",this.hitCanvas=new Kinetic.HitCanvas,Kinetic.Container.call(this,e)},draw:function(){var e=this.getContext();this.beforeDrawFunc!==undefined&&this.beforeDrawFunc.call(this),Kinetic.Container.prototype.draw.call(this),this.afterDrawFunc!==undefined&&this.afterDrawFunc.call(this)},drawHit:function(){this.hitCanvas.clear(),Kinetic.Container.prototype.drawHit.call(this)},drawScene:function(e){e=e||this.getCanvas(),this.attrs.clearBeforeDraw&&e.clear(),Kinetic.Container.prototype.drawScene.call(this,e)},toDataURL:function(e){e=e||{};var t=e.mimeType||null,n=e.quality||null,r,i,s=e.x||0,o=e.y||0;return e.width||e.height||e.x||e.y?Kinetic.Node.prototype.toDataURL.call(this,e):this.getCanvas().toDataURL(t,n)},beforeDraw:function(e){this.beforeDrawFunc=e},afterDraw:function(e){this.afterDrawFunc=e},getCanvas:function(){return this.canvas},getContext:function(){return this.canvas.context},clear:function(){this.getCanvas().clear()},setVisible:function(e){Kinetic.Node.prototype.setVisible.call(this,e),e?(this.canvas.element.style.display="block",this.hitCanvas.element.style.display="block"):(this.canvas.element.style.display="none",this.hitCanvas.element.style.display="none")},setZIndex:function(e){Kinetic.Node.prototype.setZIndex.call(this,e);var t=this.getStage();t&&(t.content.removeChild(this.canvas.element),e<t.getChildren().length-1?t.content.insertBefore(this.canvas.element,t.getChildren()[e+1].canvas.element):t.content.appendChild(this.canvas.element))},moveToTop:function(){Kinetic.Node.prototype.moveToTop.call(this);var e=this.getStage();e&&(e.content.removeChild(this.canvas.element),e.content.appendChild(this.canvas.element))},moveUp:function(){if(Kinetic.Node.prototype.moveUp.call(this)){var e=this.getStage();e&&(e.content.removeChild(this.canvas.element),this.index<e.getChildren().length-1?e.content.insertBefore(this.canvas.element,e.getChildren()[this.index+1].canvas.element):e.content.appendChild(this.canvas.element))}},moveDown:function(){if(Kinetic.Node.prototype.moveDown.call(this)){var e=this.getStage();if(e){var t=e.getChildren();e.content.removeChild(this.canvas.element),e.content.insertBefore(this.canvas.element,t[this.index+1].canvas.element)}}},moveToBottom:function(){if(Kinetic.Node.prototype.moveToBottom.call(this)){var e=this.getStage();if(e){var t=e.getChildren();e.content.removeChild(this.canvas.element),e.content.insertBefore(this.canvas.element,t[1].canvas.element)}}},getLayer:function(){return this},remove:function(){var e=this.getStage(),t=this.canvas,n=t.element;Kinetic.Node.prototype.remove.call(this),e&&t&&Kinetic.Type._isInDocument(n)&&e.content.removeChild(n)}},Kinetic.Global.extend(Kinetic.Layer,Kinetic.Container),Kinetic.Node.addGettersSetters(Kinetic.Layer,["clearBeforeDraw"])}(),function(){Kinetic.Group=function(e){this._initGroup(e)},Kinetic.Group.prototype={_initGroup:function(e){this.nodeType="Group",Kinetic.Container.call(this,e)}},Kinetic.Global.extend(Kinetic.Group,Kinetic.Container)}(),function(){Kinetic.Rect=function(e){this._initRect(e)},Kinetic.Rect.prototype={_initRect:function(e){this.setDefaultAttrs({width:0,height:0,cornerRadius:0}),Kinetic.Shape.call(this,e),this.shapeType="Rect",this._setDrawFuncs()},drawFunc:function(e){var t=e.getContext();t.beginPath();var n=this.getCornerRadius(),r=this.getWidth(),i=this.getHeight();n===0?t.rect(0,0,r,i):(t.moveTo(n,0),t.lineTo(r-n,0),t.arc(r-n,n,n,Math.PI*3/2,0,!1),t.lineTo(r,i-n),t.arc(r-n,i-n,n,0,Math.PI/2,!1),t.lineTo(n,i),t.arc(n,i-n,n,Math.PI/2,Math.PI,!1),t.lineTo(0,n),t.arc(n,n,n,Math.PI,Math.PI*3/2,!1)),t.closePath(),e.fillStroke(this)}},Kinetic.Global.extend(Kinetic.Rect,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Rect,["cornerRadius"])}(),function(){Kinetic.Circle=function(e){this._initCircle(e)},Kinetic.Circle.prototype={_initCircle:function(e){this.setDefaultAttrs({radius:0}),Kinetic.Shape.call(this,e),this.shapeType="Circle",this._setDrawFuncs()},drawFunc:function(e){var t=e.getContext();t.beginPath(),t.arc(0,0,this.getRadius(),0,Math.PI*2,!0),t.closePath(),e.fillStroke(this)},getWidth:function(){return this.getRadius()*2},getHeight:function(){return this.getRadius()*2},setWidth:function(e){Kinetic.Node.prototype.setWidth.call(this,e),this.setRadius(e/2)},setHeight:function(e){Kinetic.Node.prototype.setHeight.call(this,e),this.setRadius(e/2)}},Kinetic.Global.extend(Kinetic.Circle,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Circle,["radius"])}(),function(){Kinetic.Wedge=function(e){this._initWedge(e)},Kinetic.Wedge.prototype={_initWedge:function(e){this.setDefaultAttrs({radius:0,angle:0,clockwise:!1}),Kinetic.Shape.call(this,e),this.shapeType="Wedge",this._setDrawFuncs()},drawFunc:function(e){var t=e.getContext();t.beginPath(),t.arc(0,0,this.getRadius(),0,this.getAngle(),this.getClockwise()),t.lineTo(0,0),t.closePath(),e.fillStroke(this)},setAngleDeg:function(e){this.setAngle(Kinetic.Type._degToRad(e))},getAngleDeg:function(){return Kinetic.Type._radToDeg(this.getAngle())}},Kinetic.Global.extend(Kinetic.Wedge,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Wedge,["radius","angle","clockwise"])}(),function(){Kinetic.Ellipse=function(e){this._initEllipse(e)},Kinetic.Ellipse.prototype={_initEllipse:function(e){this.setDefaultAttrs({radius:{x:0,y:0}}),Kinetic.Shape.call(this,e),this.shapeType="Ellipse",this._setDrawFuncs()},drawFunc:function(e){var t=e.getContext(),n=this.getRadius();t.beginPath(),t.save(),n.x!==n.y&&t.scale(1,n.y/n.x),t.arc(0,0,n.x,0,Math.PI*2,!0),t.restore(),t.closePath(),e.fillStroke(this)},getWidth:function(){return this.getRadius().x*2},getHeight:function(){return this.getRadius().y*2},setWidth:function(e){Kinetic.Node.prototype.setWidth.call(this,e),this.setRadius({x:e/2})},setHeight:function(e){Kinetic.Node.prototype.setHeight.call(this,e),this.setRadius({y:e/2})}},Kinetic.Global.extend(Kinetic.Ellipse,Kinetic.Shape),Kinetic.Node.addPointGettersSetters(Kinetic.Ellipse,["radius"])}(),function(){Kinetic.Image=function(e){this._initImage(e)},Kinetic.Image.prototype={_initImage:function(e){Kinetic.Shape.call(this,e),this.shapeType="Image",this._setDrawFuncs();var t=this;this.on("imageChange",function(e){t._syncSize()}),this._syncSize()},drawFunc:function(e){var t=this.getWidth(),n=this.getHeight(),r,i=this,s=e.getContext();s.beginPath(),s.rect(0,0,t,n),s.closePath(),e.fillStroke(this);if(this.attrs.image){if(this.attrs.crop&&this.attrs.crop.width&&this.attrs.crop.height){var o=this.attrs.crop.x||0,u=this.attrs.crop.y||0,a=this.attrs.crop.width,f=this.attrs.crop.height;r=[this.attrs.image,o,u,a,f,0,0,t,n]}else r=[this.attrs.image,0,0,t,n];this.hasShadow()?e.applyShadow(this,function(){i._drawImage(s,r)}):this._drawImage(s,r)}},drawHitFunc:function(e){var t=this.getWidth(),n=this.getHeight(),r=this.imageHitRegion,i=!1,s=e.getContext();r?(s.drawImage(r,0,0,t,n),s.beginPath(),s.rect(0,0,t,n),s.closePath(),e.stroke(this)):(s.beginPath(),s.rect(0,0,t,n),s.closePath(),e.fillStroke(this))},applyFilter:function(e,t,n){var r=new Kinetic.Canvas(this.attrs.image.width,this.attrs.image.height),i=r.getContext();i.drawImage(this.attrs.image,0,0);try{var s=i.getImageData(0,0,r.getWidth(),r.getHeight());e(s,t);var o=this;Kinetic.Type._getImage(s,function(e){o.setImage(e),n&&n()})}catch(u){Kinetic.Global.warn("Unable to apply filter. "+u.message)}},setCrop:function(){var e=[].slice.call(arguments),t=Kinetic.Type._getXY(e),n=Kinetic.Type._getSize(e),r=Kinetic.Type._merge(t,n);this.setAttr("crop",Kinetic.Type._merge(r,this.getCrop()))},createImageHitRegion:function(e){var t=new Kinetic.Canvas(this.attrs.width,this.attrs.height),n=t.getContext();n.drawImage(this.attrs.image,0,0);try{var r=n.getImageData(0,0,t.getWidth(),t.getHeight()),i=r.data,s=Kinetic.Type._hexToRgb(this.colorKey);for(var o=0,u=i.length;o<u;o+=4)i[o]=s.r,i[o+1]=s.g,i[o+2]=s.b;var a=this;Kinetic.Type._getImage(r,function(t){a.imageHitRegion=t,e&&e()})}catch(f){Kinetic.Global.warn("Unable to create image hit region. "+f.message)}},clearImageHitRegion:function(){delete this.imageHitRegion},_syncSize:function(){this.attrs.image&&(this.attrs.width||this.setWidth(this.attrs.image.width),this.attrs.height||this.setHeight(this.attrs.image.height))},_drawImage:function(e,t){t.length===5?e.drawImage(t[0],t[1],t[2],t[3],t[4]):t.length===9&&e.drawImage(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])}},Kinetic.Global.extend(Kinetic.Image,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Image,["image"]),Kinetic.Node.addGetters(Kinetic.Image,["crop"])}(),function(){Kinetic.Polygon=function(e){this._initPolygon(e)},Kinetic.Polygon.prototype={_initPolygon:function(e){this.setDefaultAttrs({points:[]}),Kinetic.Shape.call(this,e),this.shapeType="Polygon",this._setDrawFuncs()},drawFunc:function(e){var t=e.getContext(),n=this.getPoints(),r=n.length;t.beginPath(),t.moveTo(n[0].x,n[0].y);for(var i=1;i<r;i++)t.lineTo(n[i].x,n[i].y);t.closePath(),e.fillStroke(this)},setPoints:function(e){this.setAttr("points",Kinetic.Type._getPoints(e))}},Kinetic.Global.extend(Kinetic.Polygon,Kinetic.Shape),Kinetic.Node.addGetters(Kinetic.Polygon,["points"])}(),function(){function E(e){e.fillText(this.partialText,0,0)}function S(e){e.strokeText(this.partialText,0,0)}var e="auto",t="Calibri",r="canvas",i="center",s="Change.kinetic",o="2d",u="\n",a="",f="left",l="\n",c="text",h="Text",p="top",d="middle",v="normal",m="px ",g=" ",y="right",b=["fontFamily","fontSize","fontStyle","padding","align","lineHeight","text","width","height"],w=b.length;Kinetic.Text=function(e){this._initText(e)},Kinetic.Text.prototype={_initText:function(n){var i=this;this.setDefaultAttrs({fontFamily:t,text:a,fontSize:12,align:f,verticalAlign:p,fontStyle:v,padding:0,width:e,height:e,lineHeight:1}),this.dummyCanvas=document.createElement(r),Kinetic.Shape.call(this,n),this._fillFunc=E,this._strokeFunc=S,this.shapeType=h,this._setDrawFuncs();for(var o=0;o<w;o++)this.on(b[o]+s,i._setTextData);this._setTextData()},drawFunc:function(e){var t=e.getContext(),n=this.getPadding(),r=this.getFontStyle(),s=this.getFontSize(),o=this.getFontFamily(),u=this.getTextHeight(),a=this.getLineHeight()*u,l=this.textArr,c=l.length,h=this.getWidth();t.font=r+g+s+m+o,t.textBaseline=d,t.textAlign=f,t.save(),t.translate(n,0),t.translate(0,n+u/2);for(var p=0;p<c;p++){var v=l[p],b=v.text,w=v.width;t.save(),this.getAlign()===y?t.translate(h-w-n*2,0):this.getAlign()===i&&t.translate((h-w-n*2)/2,0),this.partialText=b,e.fillStroke(this),t.restore(),t.translate(0,a)}t.restore()},drawHitFunc:function(e){var t=e.getContext(),n=this.getWidth(),r=this.getHeight();t.beginPath(),t.rect(0,0,n,r),t.closePath(),e.fillStroke(this)},setText:function(e){var t=Kinetic.Type._isString(e)?e:e.toString();this.setAttr(c,t)},getWidth:function(){return this.attrs.width===e?this.getTextWidth()+this.getPadding()*2:this.attrs.width},getHeight:function(){return this.attrs.height===e?this.getTextHeight()*this.textArr.length*this.attrs.lineHeight+this.attrs.padding*2:this.attrs.height},getTextWidth:function(){return this.textWidth},getTextHeight:function(){return this.textHeight},_getTextSize:function(e){var t=this.dummyCanvas,n=t.getContext(o),r=this.getFontSize(),i;return n.save(),n.font=this.getFontStyle()+g+r+m+this.getFontFamily(),i=n.measureText(e),n.restore(),{width:i.width,height:parseInt(r,10)}},_expandTextData:function(e){var t=e.length;n=0,text=a,newArr=[];for(n=0;n<t;n++)text=e[n],newArr.push({text:text,width:this._getTextSize(text).width});return newArr},_setTextData:function(){var t=this.getText().split(a),n=[],r=0;addLine=!0,lineHeightPx=0,padding=this.getPadding(),this.textWidth=0,this.textHeight=this._getTextSize(this.getText()).height,lineHeightPx=this.getLineHeight()*this.textHeight;while(t.length>0&&addLine&&(this.attrs.height===e||lineHeightPx*(r+1)<this.attrs.height-padding*2)){var i=0,s=undefined;addLine=!1;while(i<t.length){if(t.indexOf(l)===i){t.splice(i,1),s=t.splice(0,i).join(a);break}var o=t.slice(0,i);if(this.attrs.width!==e&&this._getTextSize(o.join(a)).width>this.attrs.width-padding*2){if(i==0)break;var f=o.lastIndexOf(g),c=o.lastIndexOf(u),h=Math.max(f,c);if(h>=0){s=t.splice(0,1+h).join(a);break}s=t.splice(0,i).join(a);break}i++,i===t.length&&(s=t.splice(0,i).join(a))}this.textWidth=Math.max(this.textWidth,this._getTextSize(s).width),s!==undefined&&(n.push(s),addLine=!0),r++}this.textArr=this._expandTextData(n)}},Kinetic.Global.extend(Kinetic.Text,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Text,["fontFamily","fontSize","fontStyle","padding","align","lineHeight"]),Kinetic.Node.addGetters(Kinetic.Text,[c])}(),function(){Kinetic.Line=function(e){this._initLine(e)},Kinetic.Line.prototype={_initLine:function(e){this.setDefaultAttrs({points:[],lineCap:"butt"}),Kinetic.Shape.call(this,e),this.shapeType="Line",this._setDrawFuncs()},drawFunc:function(e){var t=this.getPoints(),n=t.length,r=e.getContext();r.beginPath(),r.moveTo(t[0].x,t[0].y);for(var i=1;i<n;i++){var s=t[i];r.lineTo(s.x,s.y)}e.stroke(this)},setPoints:function(e){this.setAttr("points",Kinetic.Type._getPoints(e))}},Kinetic.Global.extend(Kinetic.Line,Kinetic.Shape),Kinetic.Node.addGetters(Kinetic.Line,["points"])}(),function(){Kinetic.Spline=function(e){this._initSpline(e)},Kinetic.Spline._getControlPoints=function(e,t,n,r){var i=e.x,s=e.y,o=t.x,u=t.y,a=n.x,f=n.y,l=Math.sqrt(Math.pow(o-i,2)+Math.pow(u-s,2)),c=Math.sqrt(Math.pow(a-o,2)+Math.pow(f-u,2)),h=r*l/(l+c),p=r*c/(l+c),d=o-h*(a-i),v=u-h*(f-s),m=o+p*(a-i),g=u+p*(f-s);return[{x:d,y:v},{x:m,y:g}]},Kinetic.Spline.prototype={_initSpline:function(e){this.setDefaultAttrs({tension:1}),Kinetic.Line.call(this,e),this.shapeType="Spline"},drawFunc:function(e){var t=this.getPoints(),n=t.length,r=e.getContext(),i=this.getTension();r.beginPath(),r.moveTo(t[0].x,t[0].y);if(i!==0&&n>2){var s=this.allPoints,o=s.length;r.quadraticCurveTo(s[0].x,s[0].y,s[1].x,s[1].y);var u=2;while(u<o-1)r.bezierCurveTo(s[u].x,s[u++].y,s[u].x,s[u++].y,s[u].x,s[u++].y);r.quadraticCurveTo(s[o-1].x,s[o-1].y,t[n-1].x,t[n-1].y)}else for(var u=1;u<n;u++){var a=t[u];r.lineTo(a.x,a.y)}e.stroke(this)},setPoints:function(e){Kinetic.Line.prototype.setPoints.call(this,e),this._setAllPoints()},setTension:function(e){this.setAttr("tension",e),this._setAllPoints()},_setAllPoints:function(){var e=this.getPoints(),t=e.length,n=this.getTension(),r=[];for(var i=1;i<t-1;i++){var s=Kinetic.Spline._getControlPoints(e[i-1],e[i],e[i+1],n);r.push(s[0]),r.push(e[i]),r.push(s[1])}this.allPoints=r}},Kinetic.Global.extend(Kinetic.Spline,Kinetic.Line),Kinetic.Node.addGetters(Kinetic.Spline,["tension"])}(),function(){Kinetic.Blob=function(e){this._initBlob(e)},Kinetic.Blob.prototype={_initBlob:function(e){Kinetic.Spline.call(this,e),this.shapeType="Blob"},drawFunc:function(e){var t=this.getPoints(),n=t.length,r=e.getContext(),i=this.getTension();r.beginPath(),r.moveTo(t[0].x,t[0].y);if(i!==0&&n>2){var s=this.allPoints,o=s.length,u=0;while(u<o-1)r.bezierCurveTo(s[u].x,s[u++].y,s[u].x,s[u++].y,s[u].x,s[u++].y)}else for(var u=1;u<n;u++){var a=t[u];r.lineTo(a.x,a.y)}r.closePath(),e.fillStroke(this)},_setAllPoints:function(){var e=this.getPoints(),t=e.length,n=this.getTension(),r=Kinetic.Spline._getControlPoints(e[t-1],e[0],e[1],n),i=Kinetic.Spline._getControlPoints(e[t-2],e[t-1],e[0],n);Kinetic.Spline.prototype._setAllPoints.call(this),this.allPoints.unshift(r[1]),this.allPoints.push(i[0]),this.allPoints.push(e[t-1]),this.allPoints.push(i[1]),this.allPoints.push(r[0]),this.allPoints.push(e[0])}},Kinetic.Global.extend(Kinetic.Blob,Kinetic.Spline)}(),function(){Kinetic.Sprite=function(e){this._initSprite(e)},Kinetic.Sprite.prototype={_initSprite:function(e){this.setDefaultAttrs({index:0,frameRate:17}),Kinetic.Shape.call(this,e),this.shapeType="Sprite",this._setDrawFuncs(),this.anim=new Kinetic.Animation;var t=this;this.on("animationChange",function(){t.setIndex(0)})},drawFunc:function(e){var t=this.attrs.animation,n=this.attrs.index,r=this.attrs.animations[t][n],i=e.getContext(),s=this.attrs.image;s&&i.drawImage(s,r.x,r.y,r.width,r.height,0,0,r.width,r.height)},drawHitFunc:function(e){var t=this.attrs.animation,n=this.attrs.index,r=this.attrs.animations[t][n],i=e.getContext();i.beginPath(),i.rect(0,0,r.width,r.height),i.closePath(),e.fill(this)},start:function(){var e=this,t=this.getLayer();this.anim.node=t,this.interval=setInterval(function(){var t=e.attrs.index;e._updateIndex(),e.afterFrameFunc&&t===e.afterFrameIndex&&(e.afterFrameFunc(),delete e.afterFrameFunc,delete e.afterFrameIndex)},1e3/this.attrs.frameRate),this.anim.start()},stop:function(){this.anim.stop(),clearInterval(this.interval)},afterFrame:function(e,t){this.afterFrameIndex=e,this.afterFrameFunc=t},_updateIndex:function(){var e=this.attrs.index,t=this.attrs.animation;e<this.attrs.animations[t].length-1?this.attrs.index++:this.attrs.index=0}},Kinetic.Global.extend(Kinetic.Sprite,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Sprite,["animation","animations","index"])}(),function(){Kinetic.Star=function(e){this._initStar(e)},Kinetic.Star.prototype={_initStar:function(e){this.setDefaultAttrs({numPoints:0,innerRadius:0,outerRadius:0}),Kinetic.Shape.call(this,e),this.shapeType="Star",this._setDrawFuncs()},drawFunc:function(e){var t=e.getContext(),n=this.attrs.innerRadius,r=this.attrs.outerRadius,i=this.attrs.numPoints;t.beginPath(),t.moveTo(0,0-this.attrs.outerRadius);for(var s=1;s<i*2;s++){var o=s%2===0?r:n,u=o*Math.sin(s*Math.PI/i),a=-1*o*Math.cos(s*Math.PI/i);t.lineTo(u,a)}t.closePath(),e.fillStroke(this)}},Kinetic.Global.extend(Kinetic.Star,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Star,["numPoints","innerRadius","outerRadius"])}(),function(){Kinetic.RegularPolygon=function(e){this._initRegularPolygon(e)},Kinetic.RegularPolygon.prototype={_initRegularPolygon:function(e){this.setDefaultAttrs({radius:0,sides:0}),Kinetic.Shape.call(this,e),this.shapeType="RegularPolygon",this._setDrawFuncs()},drawFunc:function(e){var t=e.getContext(),n=this.attrs.sides,r=this.attrs.radius;t.beginPath(),t.moveTo(0,0-r);for(var i=1;i<n;i++){var s=r*Math.sin(i*2*Math.PI/n),o=-1*r*Math.cos(i*2*Math.PI/n);t.lineTo(s,o)}t.closePath(),e.fillStroke(this)}},Kinetic.Global.extend(Kinetic.RegularPolygon,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.RegularPolygon,["radius","sides"])}(),function(){Kinetic.Path=function(e){this._initPath(e)},Kinetic.Path.prototype={_initPath:function(e){this.dataArray=[];var t=this;Kinetic.Shape.call(this,e),this.shapeType="Path",this._setDrawFuncs(),this.dataArray=Kinetic.Path.parsePathData(this.attrs.data),this.on("dataChange",function(){t.dataArray=Kinetic.Path.parsePathData(t.attrs.data)})},drawFunc:function(e){var t=this.dataArray,n=e.getContext();n.beginPath();for(var r=0;r<t.length;r++){var i=t[r].command,s=t[r].points;switch(i){case"L":n.lineTo(s[0],s[1]);break;case"M":n.moveTo(s[0],s[1]);break;case"C":n.bezierCurveTo(s[0],s[1],s[2],s[3],s[4],s[5]);break;case"Q":n.quadraticCurveTo(s[0],s[1],s[2],s[3]);break;case"A":var o=s[0],u=s[1],a=s[2],f=s[3],l=s[4],c=s[5],h=s[6],p=s[7],d=a>f?a:f,v=a>f?1:a/f,m=a>f?f/a:1;n.translate(o,u),n.rotate(h),n.scale(v,m),n.arc(0,0,d,l,l+c,1-p),n.scale(1/v,1/m),n.rotate(-h),n.translate(-o,-u);break;case"z":n.closePath()}}e.fillStroke(this)}},Kinetic.Global.extend(Kinetic.Path,Kinetic.Shape),Kinetic.Path.getLineLength=function(e,t,n,r){return Math.sqrt((n-e)*(n-e)+(r-t)*(r-t))},Kinetic.Path.getPointOnLine=function(e,t,n,r,i,s,o){s===undefined&&(s=t),o===undefined&&(o=n);var u=(i-n)/(r-t+1e-8),a=Math.sqrt(e*e/(1+u*u));r<t&&(a*=-1);var f=u*a,l;if((o-n)/(s-t+1e-8)===u)l={x:s+a,y:o+f};else{var c,h,p=this.getLineLength(t,n,r,i);if(p<1e-8)return undefined;var d=(s-t)*(r-t)+(o-n)*(i-n);d/=p*p,c=t+d*(r-t),h=n+d*(i-n);var v=this.getLineLength(s,o,c,h),m=Math.sqrt(e*e-v*v);a=Math.sqrt(m*m/(1+u*u)),r<t&&(a*=-1),f=u*a,l={x:c+a,y:h+f}}return l},Kinetic.Path.getPointOnCubicBezier=function(e,t,n,r,i,s,o,u,a){function f(e){return e*e*e}function l(e){return 3*e*e*(1-e)}function c(e){return 3*e*(1-e)*(1-e)}function h(e){return(1-e)*(1-e)*(1-e)}var p=u*f(e)+s*l(e)+r*c(e)+t*h(e),d=a*f(e)+o*l(e)+i*c(e)+n*h(e);return{x:p,y:d}},Kinetic.Path.getPointOnQuadraticBezier=function(e,t,n,r,i,s,o){function u(e){return e*e}function a(e){return 2*e*(1-e)}function f(e){return(1-e)*(1-e)}var l=s*u(e)+r*a(e)+t*f(e),c=o*u(e)+i*a(e)+n*f(e);return{x:l,y:c}},Kinetic.Path.getPointOnEllipticalArc=function(e,t,n,r,i,s){var o=Math.cos(s),u=Math.sin(s),a={x:n*Math.cos(i),y:r*Math.sin(i)};return{x:e+(a.x*o-a.y*u),y:t+(a.x*u+a.y*o)}},Kinetic.Path.parsePathData=function(e){if(!e)return[];var t=e,n=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];t=t.replace(new RegExp(" ","g"),",");for(var r=0;r<n.length;r++)t=t.replace(new RegExp(n[r],"g"),"|"+n[r]);var i=t.split("|"),s=[],o=0,u=0;for(var r=1;r<i.length;r++){var a=i[r],f=a.charAt(0);a=a.slice(1),a=a.replace(new RegExp(",-","g"),"-"),a=a.replace(new RegExp("-","g"),",-"),a=a.replace(new RegExp("e,-","g"),"e-");var l=a.split(",");l.length>0&&l[0]===""&&l.shift();for(var c=0;c<l.length;c++)l[c]=parseFloat(l[c]);while(l.length>0){if(isNaN(l[0]))break;var h=null,p=[],d=o,v=u;switch(f){case"l":o+=l.shift(),u+=l.shift(),h="L",p.push(o,u);break;case"L":o=l.shift(),u=l.shift(),p.push(o,u);break;case"m":o+=l.shift(),u+=l.shift(),h="M",p.push(o,u),f="l";break;case"M":o=l.shift(),u=l.shift(),h="M",p.push(o,u),f="L";break;case"h":o+=l.shift(),h="L",p.push(o,u);break;case"H":o=l.shift(),h="L",p.push(o,u);break;case"v":u+=l.shift(),h="L",p.push(o,u);break;case"V":u=l.shift(),h="L",p.push(o,u);break;case"C":p.push(l.shift(),l.shift(),l.shift(),l.shift()),o=l.shift(),u=l.shift(),p.push(o,u);break;case"c":p.push(o+l.shift(),u+l.shift(),o+l.shift(),u+l.shift()),o+=l.shift(),u+=l.shift(),h="C",p.push(o,u);break;case"S":var m=o,g=u,y=s[s.length-1];y.command==="C"&&(m=o+(o-y.points[2]),g=u+(u-y.points[3])),p.push(m,g,l.shift(),l.shift()),o=l.shift(),u=l.shift(),h="C",p.push(o,u);break;case"s":var m=o,g=u,y=s[s.length-1];y.command==="C"&&(m=o+(o-y.points[2]),g=u+(u-y.points[3])),p.push(m,g,o+l.shift(),u+l.shift()),o+=l.shift(),u+=l.shift(),h="C",p.push(o,u);break;case"Q":p.push(l.shift(),l.shift()),o=l.shift(),u=l.shift(),p.push(o,u);break;case"q":p.push(o+l.shift(),u+l.shift()),o+=l.shift(),u+=l.shift(),h="Q",p.push(o,u);break;case"T":var m=o,g=u,y=s[s.length-1];y.command==="Q"&&(m=o+(o-y.points[0]),g=u+(u-y.points[1])),o=l.shift(),u=l.shift(),h="Q",p.push(m,g,o,u);break;case"t":var m=o,g=u,y=s[s.length-1];y.command==="Q"&&(m=o+(o-y.points[0]),g=u+(u-y.points[1])),o+=l.shift(),u+=l.shift(),h="Q",p.push(m,g,o,u);break;case"A":var b=l.shift(),w=l.shift(),E=l.shift(),S=l.shift(),x=l.shift(),T=o,N=u;o=l.shift(),u=l.shift(),h="A",p=this.convertEndpointToCenterParameterization(T,N,o,u,S,x,b,w,E);break;case"a":var b=l.shift(),w=l.shift(),E=l.shift(),S=l.shift(),x=l.shift(),T=o,N=u;o+=l.shift(),u+=l.shift(),h="A",p=this.convertEndpointToCenterParameterization(T,N,o,u,S,x,b,w,E)}s.push({command:h||f,points:p,start:{x:d,y:v},pathLength:this.calcLength(d,v,h||f,p)})}(f==="z"||f==="Z")&&s.push({command:"z",points:[],start:undefined,pathLength:0})}return s},Kinetic.Path.calcLength=function(e,n,r,i){var s,o,u,a=Kinetic.Path;switch(r){case"L":return a.getLineLength(e,n,i[0],i[1]);case"C":s=0,o=a.getPointOnCubicBezier(0,e,n,i[0],i[1],i[2],i[3],i[4],i[5]);for(t=.01;t<=1;t+=.01)u=a.getPointOnCubicBezier(t,e,n,i[0],i[1],i[2],i[3],i[4],i[5]),s+=a.getLineLength(o.x,o.y,u.x,u.y),o=u;return s;case"Q":s=0,o=a.getPointOnQuadraticBezier(0,e,n,i[0],i[1],i[2],i[3]);for(t=.01;t<=1;t+=.01)u=a.getPointOnQuadraticBezier(t,e,n,i[0],i[1],i[2],i[3]),s+=a.getLineLength(o.x,o.y,u.x,u.y),o=u;return s;case"A":s=0;var f=i[4],l=i[5],c=i[4]+l,h=Math.PI/180;Math.abs(f-c)<h&&(h=Math.abs(f-c)),o=a.getPointOnEllipticalArc(i[0],i[1],i[2],i[3],f,0);if(l<0)for(t=f-h;t>c;t-=h)u=a.getPointOnEllipticalArc(i[0],i[1],i[2],i[3],t,0),s+=a.getLineLength(o.x,o.y,u.x,u.y),o=u;else for(t=f+h;t<c;t+=h)u=a.getPointOnEllipticalArc(i[0],i[1],i[2],i[3],t,0),s+=a.getLineLength(o.x,o.y,u.x,u.y),o=u;return u=a.getPointOnEllipticalArc(i[0],i[1],i[2],i[3],c,0),s+=a.getLineLength(o.x,o.y,u.x,u.y),s}return 0},Kinetic.Path.convertEndpointToCenterParameterization=function(e,t,n,r,i,s,o,u,a){var f=a*(Math.PI/180),l=Math.cos(f)*(e-n)/2+Math.sin(f)*(t-r)/2,c=-1*Math.sin(f)*(e-n)/2+Math.cos(f)*(t-r)/2,h=l*l/(o*o)+c*c/(u*u);h>1&&(o*=Math.sqrt(h),u*=Math.sqrt(h));var p=Math.sqrt((o*o*u*u-o*o*c*c-u*u*l*l)/(o*o*c*c+u*u*l*l));i==s&&(p*=-1),isNaN(p)&&(p=0);var d=p*o*c/u,v=p*-u*l/o,m=(e+n)/2+Math.cos(f)*d-Math.sin(f)*v,g=(t+r)/2+Math.sin(f)*d+Math.cos(f)*v,y=function(e){return Math.sqrt(e[0]*e[0]+e[1]*e[1])},b=function(e,t){return(e[0]*t[0]+e[1]*t[1])/(y(e)*y(t))},w=function(e,t){return(e[0]*t[1]<e[1]*t[0]?-1:1)*Math.acos(b(e,t))},E=w([1,0],[(l-d)/o,(c-v)/u]),S=[(l-d)/o,(c-v)/u],x=[(-1*l-d)/o,(-1*c-v)/u],T=w(S,x);return b(S,x)<=-1&&(T=Math.PI),b(S,x)>=1&&(T=0),s===0&&T>0&&(T-=2*Math.PI),s==1&&T<0&&(T+=2*Math.PI),[m,g,o,u,E,T,f,s]},Kinetic.Node.addGettersSetters(Kinetic.Path,["data"])}(),function(){function e(e){e.fillText(this.partialText,0,0)}function t(e){e.strokeText(this.partialText,0,0)}Kinetic.TextPath=function(e){this._initTextPath(e)},Kinetic.TextPath.prototype={_initTextPath:function(n){this.setDefaultAttrs({fontFamily:"Calibri",fontSize:12,fontStyle:"normal",text:""}),this.dummyCanvas=document.createElement("canvas"),this.dataArray=[];var r=this;Kinetic.Shape.call(this,n),this._fillFunc=e,this._strokeFunc=t,this.shapeType="TextPath",this._setDrawFuncs(),this.dataArray=Kinetic.Path.parsePathData(this.attrs.data),this.on("dataChange",function(){r.dataArray=Kinetic.Path.parsePathData(this.attrs.data)});var i=["text","textStroke","textStrokeWidth"];for(var s=0;s<i.length;s++){var o=i[s];this.on(o+"Change",r._setTextData)}r._setTextData()},drawFunc:function(e){var t=this.charArr,n=e.getContext();n.font=this.attrs.fontStyle+" "+this.attrs.fontSize+"pt "+this.attrs.fontFamily,n.textBaseline="middle",n.textAlign="left",n.save();var r=this.glyphInfo;for(var i=0;i<r.length;i++){n.save();var s=r[i].p0,o=r[i].p1,u=parseFloat(this.attrs.fontSize);n.translate(s.x,s.y),n.rotate(r[i].rotation),this.partialText=r[i].text,e.fillStroke(this),n.restore()}n.restore()},getTextWidth:function(){return this.textWidth},getTextHeight:function(){return this.textHeight},setText:function(e){Kinetic.Text.prototype.setText.call(this,e)},_getTextSize:function(e){var t=this.dummyCanvas,n=t.getContext("2d");n.save(),n.font=this.attrs.fontStyle+" "+this.attrs.fontSize+"pt "+this.attrs.fontFamily;var r=n.measureText(e);return n.restore(),{width:r.width,height:parseInt(this.attrs.fontSize,10)}},_setTextData:function(){var e=this,t=this._getTextSize(this.attrs.text);this.textWidth=t.width,this.textHeight=t.height,this.glyphInfo=[];var n=this.attrs.text.split(""),r,i,s,o=-1,u=0,a=function(){u=0;var t=e.dataArray;for(var n=o+1;n<t.length;n++){if(t[n].pathLength>0)return o=n,t[n];t[n].command=="M"&&(r={x:t[n].points[0],y:t[n].points[1]})}return{}},f=function(t,n){var o=e._getTextSize(t).width,f=0,l=0,c=!1;i=undefined;while(Math.abs(o-f)/o>.01&&l<25){l++;var h=f;while(s===undefined)s=a(),s&&h+s.pathLength<o&&(h+=s.pathLength,s=undefined);if(s==={}||r===undefined)return undefined;var p=!1;switch(s.command){case"L":Kinetic.Path.getLineLength(r.x,r.y,s.points[0],s.points[1])>o?i=Kinetic.Path.getPointOnLine(o,r.x,r.y,s.points[0],s.points[1],r.x,r.y):s=undefined;break;case"A":var d=s.points[4],v=s.points[5],m=s.points[4]+v;u===0?u=d+1e-8:o>f?u+=Math.PI/180*v/Math.abs(v):u-=Math.PI/360*v/Math.abs(v),Math.abs(u)>Math.abs(m)&&(u=m,p=!0),i=Kinetic.Path.getPointOnEllipticalArc(s.points[0],s.points[1],s.points[2],s.points[3],u,s.points[6]);break;case"C":u===0?o>s.pathLength?u=1e-8:u=o/s.pathLength:o>f?u+=(o-f)/s.pathLength:u-=(f-o)/s.pathLength,u>1&&(u=1,p=!0),i=Kinetic.Path.getPointOnCubicBezier(u,s.start.x,s.start.y,s.points[0],s.points[1],s.points[2],s.points[3],s.points[4],s.points[5]);break;case"Q":u===0?u=o/s.pathLength:o>f?u+=(o-f)/s.pathLength:u-=(f-o)/s.pathLength,u>1&&(u=1,p=!0),i=Kinetic.Path.getPointOnQuadraticBezier(u,s.start.x,s.start.y,s.points[0],s.points[1],s.points[2],s.points[3])}i!==undefined&&(f=Kinetic.Path.getLineLength(r.x,r.y,i.x,i.y)),p&&(p=!1,s=undefined)}};for(var l=0;l<n.length;l++){f(n[l]);if(r===undefined||i===undefined)break;var c=Kinetic.Path.getLineLength(r.x,r.y,i.x,i.y),h=0,p=Kinetic.Path.getPointOnLine(h+c/2,r.x,r.y,i.x,i.y),d=Math.atan2(i.y-r.y,i.x-r.x);this.glyphInfo.push({transposeX:p.x,transposeY:p.y,text:n[l],rotation:d,p0:r,p1:i}),r=i}}},Kinetic.Global.extend(Kinetic.TextPath,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.TextPath,["fontFamily","fontSize","fontStyle"]),Kinetic.Node.addGetters(Kinetic.TextPath,["text"])}(),define("ubnt/view/map/RulerView",["backbone","underscore","libs/kinetic","jquery"],function(e,t,n,r){"use strict";return e.View.extend({_fullyQualifiedName:"UBNT.views.map.Ruler",events:{click:"onRulerClick","click .close":"onCloseClick","click .submit":"onFormSubmit"},initialize:function(){t.bindAll(this),this.distance=0,this.measuredDistance=0,this.scale=0,this.render()},render:function(){!this.rendered&&(this.rendered=!0)&&(this.$distance=this.$(".distance"),this.$units=this.$(".units"),this.$submit=this.$(".submit"))},setupStage:function(){var e=r("#Map");this.layer=new n.Layer,this.stage=new n.Stage({container:"Map",width:e.width(),height:e.height()}),this.background=new n.Rect({x:0,y:0,width:this.stage.getWidth(),height:this.stage.getHeight(),fill:"#1292c5",opacity:.1}),this.line=new n.Line({points:[0,0,0,0],stroke:"red"}),this.moving=!1,this.layer.add(this.background),this.layer.add(this.line),this.stage.add(this.layer)},destroyStage:function(){this.line.destroy(),this.background.destroy(),this.layer.destroy(),this.stage.destroy()},bindStageEvents:function(){this.stage.on("mousedown",this.onStageMouseDown),this.stage.on("mousemove",this.onStageMouseMove),this.stage.on("mouseup",this.onStageMouseUp)},unbindStageEvents:function(){this.stage.off("mousedown",this.onStageMouseDown),this.stage.off("mousemove",this.onStageMouseMove),this.stage.off("mouseup",this.onStageMouseUp)},onStageMouseDown:function(){if(this.moving)this.moving=!1,this.layer.draw();else{var e=this.stage.getMousePosition();this.line.getPoints()[0].x=e.x,this.line.getPoints()[0].y=e.y,this.line.getPoints()[1].x=e.x,this.line.getPoints()[1].y=e.y,this.moving=!0,this.layer.drawScene()}},onStageMouseMove:function(){if(this.moving){var e=this.stage.getMousePosition(),t=e.x,n=e.y;this.line.getPoints()[1].x=e.x,this.line.getPoints()[1].y=e.y,this.moving=!0,this.layer.drawScene()}},onStageMouseUp:function(){var e=this.line.getPoints();this.measuredDistance=this.getDistance(e[0],e[1]),this.moving=!1,this.measuredDistance>0&&(this.$distance.prop("disabled",!1).removeClass("disabled").focus(),this.$submit.prop("disabled",!1).removeClass("disabled"))},onRulerClick:function(e){this.$el.hasClass("is-open")||(this.$el.addClass("is-open"),this.setupStage(),this.bindStageEvents()),e.preventDefault()},onCloseClick:function(e){return this.$el.removeClass("is-open"),this.unbindStageEvents(),this.destroyStage(),e.preventDefault(),e.stopPropagation(),!1},onFormSubmit:function(e){var t=parseFloat(this.$distance.val(),10),n=t/this.measuredDistance,r=this.$units.val();t&&(this.onCloseClick(e),this.$el.trigger("scaled",[n,r]),this.$distance.val(""))},getDistance:function(e,t){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))},remove:function(){this.unbindStageEvents(),this.rendered=!1,e.View.prototype.remove.apply(this,arguments)}})}),define("ubnt/EventDispatcher",{bind:function(e,t,n){"use strict";var r=this._callbacks||(this._callbacks={}),i=r[e]||(r[e]=[]);return i.push([t,n]),this},unbind:function(e,t){"use strict";var n;if(!e)this._callbacks={};else if(n=this._callbacks)if(!t)n[e]=[];else{var r=n[e];if(!r)return this;for(var i=0,s=r.length;i<s;i++)if(r[i]&&t===r[i][0]){r[i]=null;break}}return this},trigger:function(e){"use strict";var t,n,r,i,s,o=2;if(!(n=this._callbacks))return this;while(o--){r=o?e:"all";if(t=n[r])for(var u=0,a=t.length;u<a;u++)(i=t[u])?(s=o?Array.prototype.slice.call(arguments,1):arguments,i[0].apply(i[1]||this,s)):(t.splice(u,1),u--,a--)}return this}}),define("ubnt/TimerEvent",{TIMER_COMPLETE:"timer complete",TIMER:"timer"}),define("ubnt/Timer",["underscore","ubnt/EventDispatcher","ubnt/TimerEvent"],function(e,t,n){"use strict";var r=function(t,n){e.bindAll(this),this._delay=t,this._repeatCount=n||0,this._interval=undefined,this._currentCount=0,this._isRunning=!1};return e.extend(r.prototype,t,{setRunning:function(){throw new Error("running is read-only")},setCurrentCount:function(){throw new Error("currentCount is read-only")},setDelay:function(e){this._delay=e},setRepeatCount:function(e){this._repeatCount=e||0},reset:function(){this.stop(),this._currentCount=0},start:function(){if(this._interval)return;if(this._repeatCount&&this._currentCount>=this._repeatCount)return;this._interval=setTimeout(this.tick,this._delay)},stop:function(){this._interval&&clearTimeout(this._interval),this._interval=undefined},tick:function(){this._currentCount+=1;if(this._repeatCount&&this._currentCount>=this._repeatCount){this.reset(),this.trigger(n.TIMER_COMPLETE,{target:this});return}this._interval=setTimeout(this.tick,this._delay),this.trigger(n.TIMER)}}),r}),define("ubnt/view/map/MarkerView",["backbone","underscore","ubnt/Timer","ubnt/TimerEvent","jquery"],function(e,t,n,r,i){"use strict";return e.View.extend({_fullyQualifiedName:"UBNT.views.map.Marker",initialize:function(e){t.bindAll(this),this.isHoldToDrag=!1,this.isMoving=!1,this.el=this.template({}),this.$el=i(this.el),this.$el.draggable({}).data("view",this),this.$marker=this.$(".marker-button"),this.$el.removeClass("expand"),this.$el.addClass("ap-model-"+this.model.get("model")),this.initHandlers(),this.render()},initHandlers:function(){this.isHoldToDrag&&(this.holdTimer=new n(500,1),this.holdTimer.bind(r.TIMER_COMPLETE,this.enableMove)),this.$el.on("drag",this.dragHandler),this.$el.on("dragstop",this.dragStopHandler),this.bindHandlers()},bindHandlers:function(){this.$marker.on("mousedown",this.markerMouseDownHandler),this.isHoldToDrag&&this.$marker.on("mouseout",this.holdTimer.reset)},dragHandler:function(){return this.isMoving?(this.trigger("markerchange"),!0):!1},dragStopHandler:function(e,t){this.trigger("dragstop",e,t)},render:function(){},show:function(){this.$el.show()},hide:function(){this.$el.hide()},pulse:function(){this.$el.addClass("show-halo")},enableMove:function(){this.isMoving=!0,this.isHoldToDrag&&(this.$el.addClass("show-move"),this.$el.removeClass("expand")),this.trigger("dragstart",this)},disableMove:function(){this.$el.removeClass("show-move"),this.isMoving=!1,this.trigger("dragstop",this)},setPosition:function(e,t){this.x=e,this.y=t,this.$el.css({left:this.x,top:this.y})},setExpanded:function(e){e?this.isExpanded||(this.$el.addClass("expand"),this.trigger("markerselect",this)):this.isExpanded&&(this.$el.removeClass("expand"),this.trigger("markerdeselect",this))},markerMouseDownHandler:function(e){this.isHoldToDrag&&this.holdTimer.start(),this.$el.toggleClass("expand"),this.isExpanded()?this.trigger("markerselect",this):this.trigger("markerdeselect",this),this.trigger("markerchange",this),this.isHoldToDrag||this.enableMove(),i("body").bind("mouseup",this.markerMouseUpHandler)},isExpanded:function(){return this.$el.hasClass("expand")},markerMouseUpHandler:function(e){this.isHoldToDrag&&this.holdTimer.reset(),this.disableMove(),i("body").unbind("mouseup",this.markerMouseUpHandler)},handleRemoveClick:function(){this.save({map_id:"",x:"",y:""})},remove:function(){this.$el.off("drag",this.dragHandler),this.$el.off("dragstop",this.dragStopHandler),this.$marker.off("mousedown",this.markerMouseDownHandler),i("body").unbind("mouseup",this.markerMouseUpHandler),e.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/map/MarkerView",["ubnt/view/map/MarkerView","underscore","jquery","msg/Msg"],function(e,t,n,r){"use strict";return e.extend({initialize:function(n){t.bindAll(this),this.template=this.options.template,this.map=this.options.map,e.prototype.initialize.apply(this,[n]),this.updateState(),this.updateUplink()},initHandlers:function(){e.prototype.initHandlers.apply(this,[]),this.$lockButton=this.$(".lock"),this.$configButton=this.$(".config"),this.$removeButton=this.$(".remove"),this.$lockButtonIcon=this.$lockButton.find(".icon"),this.$lockButton.on("click",this.lockClickHandler),this.$configButton.on("click",this.configClickHandler),this.$removeButton.on("click",this.handleRemoveClick),this.listenTo(this.model,"change:name",this.updateName),this.listenTo(this.model,"change:mac",this.updateMac),this.listenTo(this.model,"change:ng-channel change:na-channel",this.updateChannel),this.listenTo(this.model,"change:user-num_sta",this.updateUsers),this.listenTo(this.model,"change:guest-num_sta",this.updateGuests),this.listenTo(this.model,"change:state",this.updateState),this.listenTo(this.model,"change:uplink",this.updateUplink),this.listenTo(this.model,"change:locked",this.updateLocked),this.updateLocked()},updateLocked:function(){this.model.get("locked")?(this.$el.toggleClass("locked",!0),this.$el.draggable("disable"),this.$lockButtonIcon.removeClass("ubnt-icon-unlock").addClass("ubnt-icon-lock")):(this.$el.toggleClass("locked",!1),this.$el.draggable("enable"),this.$lockButtonIcon.removeClass("ubnt-icon-lock").addClass("ubnt-icon-unlock"))},enableMove:function(){this.model.get("locked")||e.prototype.enableMove.apply(this,arguments)},lockClickHandler:function(e){var t=!this.model.get("locked");this.$el.toggleClass("locked",t),this.$el.draggable(t?"disable":"enable"),t?this.$lockButtonIcon.removeClass("ubnt-icon-unlock").addClass("ubnt-icon-lock"):this.$lockButtonIcon.removeClass("ubnt-icon-lock").addClass("ubnt-icon-unlock"),this.app.isReadOnly?this.model.set({locked:t}):this.model.save({locked:t})},configClickHandler:function(e){this.model.get("locked")||this.app.routers.devices.views.index.property(this.model)},handleRemoveClick:function(t){this.model.get("locked")||e.prototype.handleRemoveClick.apply(this,arguments)},render:function(){e.prototype.render.apply(this,[]),this.$details=this.$(".details"),this.updateName(),this.updateMac(),this.updateChannel(),this.updateUsers(),this.updateGuests(),this.$(".marker-icon").addClass(this.model.apIcon()),n(".ruler").on("scaled",this.updateRulerScale)},updateName:function(){this.$(".title").text(this.model.name());var e="";switch(this.model.get("type")){case this.model.typeMap.ap:e="AP";break;case this.model.typeMap.gateway:e="Gateway";break;case this.model.typeMap["switch"]:e="Switch";break;case this.model.typeMap.phone:e="Phone"}this.$details.find(".ap-name").text(this.model.get("name")||"Unnamed "+e)},updateMac:function(){this.$details.find(".mac").text(this.model.get("mac"))},updateChannel:function(){this.model.get("type")===this.model.typeMap.ap?this.$details.find(".channel").text(this.model.getChannel()):this.$details.find(".channel").parent().hide()},updateUsers:function(){this.model.get("type")===this.model.typeMap.phone?this.$details.find(".users").parent().hide():this.$details.find(".users").text(this.model.get("user-num_sta")||0)},updateGuests:function(){this.model.get("type")===this.model.typeMap.phone?this.$details.find(".guests").parent().hide():this.$details.find(".guests").text(this.model.get("guest-num_sta")||0)},updateState:function(){this.model.isConnected()?this.$el.addClass("ap-connected").removeClass("ap-disconnected"):this.$el.addClass("ap-disconnected").removeClass("ap-connected"),parseInt(this.model.get("state"),10)===11?this.$el.addClass("ap-isolated"):this.$el.removeClass("ap-isolated")},updateUplink:function(){var e=this.model.uplink();e&&e.name=="ath0"?this.$el.addClass("ap-vwireless"):this.$el.removeClass("ap-vwireless")},updateRulerScale:function(e,t,n){this.map.model.set({upp:t,unit:n}),this.map.$el.click()},save:function(e){this.app.isReadOnly?this.model.set({map_id:e.map_id!==undefined?e.map_id:this.model.get("map_id"),x:e.x!==undefined?e.x:this.model.get("x"),y:e.y!==undefined?e.y:this.model.get("y"),locked:e.locked!==undefined?e.locked:this.model.get("locked")}):(this.model.unset("x",{silent:!0}),this.model.unset("y",{silent:!0}),this.model.unset("map_id",{silent:!0}),this.model.unset("locked",{silent:!0}),this.model.save({map_id:e.map_id!==undefined?e.map_id:this.model.get("map_id"),x:e.x!==undefined?e.x:this.model.get("x"),y:e.y!==undefined?e.y:this.model.get("y"),locked:e.locked!==undefined?e.locked:this.model.get("locked")}))},pulse:function(){this.$el.stop().effect("pulsate",{times:2},2500)},remove:function(){this.$lockButton.off("click",this.lockClickHandler),this.$configButton.off("click",this.configClickHandler),this.$removeButton.off("click",this.handleRemoveClick),this.stopListening(this.model,"change:name",this.updateName),this.stopListening(this.model,"change:mac",this.updateMac),this.stopListening(this.model,"change:ng-channel change:na-channel",this.updateChannel),this.stopListening(this.model,"change:user-num_sta",this.updateUsers),this.stopListening(this.model,"change:guest-num_sta",this.updateGuests),this.stopListening(this.model,"change:state",this.updateState),this.stopListening(this.model,"change:uplink",this.updateUplink),n(".ruler").off("scaled",this.updateRulerScale),e.prototype.remove.apply(this,arguments)}})}),define("ubnt/view/map/UnplacedMarkerView",["backbone","underscore","jquery"],function(e,t,n){"use strict";return e.View.extend({initialize:function(){var e=this;t.bindAll(this),this.el=this.template({}),this.$el=n(this.el),this.draggableTemplate=this.options.draggableTemplate||this.draggableTemplate,this.$draggableHelper=n(this.draggableTemplate({})),this.$draggableHelper.addClass("ap-model-"+this.model.get("model")),this.$el.addClass("unplaced-marker ap-model-"+this.model.get("model")).draggable({appendTo:"#Map",helper:function(){return e.$draggableHelper.get(0)},cursorAt:{right:0,bottom:0}}),this.$draggableHelper.data("view",this),this.model.bind("change",this.updateMarker),this.model.bind("remove",this.removeMarker),this.updateMarker(this.model)},updateMarker:function(e){e.isConnected()?(this.$el.addClass("ap-connected").removeClass("ap-disconnected"),this.$draggableHelper.addClass("ap-connected").removeClass("ap-disconnected")):(this.$el.addClass("ap-disconnected").removeClass("ap-connected"),this.$draggableHelper.addClass("ap-disconnected").removeClass("ap-connected"))},remove:function(){this.model.unbind("change",this.updateMarker),this.model.unbind("remove",this.removeMarker),e.View.prototype.remove.apply(this,arguments)}})}),define("ubnt/view/map/MarkerDrawerView",["backbone","underscore","ubnt/view/map/UnplacedMarkerView","jquery"],function(e,t,n,r){"use strict";return e.View.extend({_fullyQualifiedName:"UBNT.views.map.MarkerDrawer",initialize:function(){t.bindAll(this),this.$markerList=this.$(".marker-list"),this.markerViews={},this.markerView=this.options.markerView||n,this.unplacedMarkerTemplate=this.options.unplacedMarkerTemplate,this.unplacedMarkerDraggableTemplate=this.options.unplacedMarkerDraggableTemplate,this.collections={},this.collections.markers=this.options.markers,this.collections.maps=this.options.maps,this.listenTo(this.collections.markers,"add",this.addMarker),this.listenTo(this.collections.markers,"change",this.updateMarker),this.listenTo(this.collections.markers,"reset",this.resetMarkers),this.listenTo(this.collections.markers,"remove",this.removeMarker),this.$unplacedMarkerCountElt=this.$(".unplaced-markers-count")},render:function(){return this.isRendered||(this.isRendered=!0,this.resetMarkers()),this.$el},isMarkerMappable:function(e){return e.id&&e.get("adopted")},addMultipleMarkers:function(e){var t=this,n=e.length,r=document.createDocumentFragment(),i,s,o,u;for(u=0;u<n;u++)i=e[u],s=i.get("map_id"),!s&&!t.collections.maps.get(s)&&t.isMarkerMappable(i)&&(o=new t.markerView({model:i,template:t.unplacedMarkerTemplate,draggableTemplate:t.unplacedMarkerDraggableTemplate}),o.render(),r.appendChild(o.$el[0]),t.markerViews[i.id]=o);t.$markerList.append(r),t.updateUnplacedMarkerCount()},addMarker:function(e){if(e.get("map_id")&&this.collections.maps.get(e.get("map_id"))&&!this.isMarkerMappable(e))return;if(e.id){var t=new this.markerView({model:e,template:this.unplacedMarkerTemplate,draggableTemplate:this.unplacedMarkerDraggableTemplate});t.render(),this.$markerList.append(t.$el),this.markerViews[e.id]=t,this.updateUnplacedMarkerCount()}},updateMarker:function(e){var t=e.changedAttributes();this.isMarkerMappable(e)&&(!e.get("map_id")&&!this.collections.maps.get(e.get("map_id"))?(this.markerViews[e.id]===null||this.markerViews[e.id]===undefined)&&this.addMarker(e):this.removeMarker(e))},resetMarkers:function(){r.each(this.markerViews,function(e,t){t.remove()}),this.markerViews={},this.addMultipleMarkers(this.collections.markers.models),this.updateUnplacedMarkerCount()},removeMarker:function(e){this.markerViews[e.id]&&(this.markerViews[e.id].remove(),delete this.markerViews[e.id],this.updateUnplacedMarkerCount())},hasUnplacedMarkers:function(){return r.isEmptyObject(this.markerViews)?!1:!0},updateUnplacedMarkerCount:function(){var e=this,n=t.size(this.markerViews);this.$unplacedMarkerCountElt.text(n),n?this.show():this.hide()},show:function(){this.$el.show()},hide:function(){this.$el.hide()},remove:function(){this.stopListening(this.collections.markers,"add",this.addMarker),this.stopListening(this.collections.markers,"change",this.updateMarker),this.stopListening(this.collections.markers,"reset",this.resetMarkers),this.stopListening(this.collections.markers,"remove",this.removeMarker),this.isRendered=!1,e.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/map/UnplacedMarkerView",["ubnt/view/map/UnplacedMarkerView","underscore"],function(e,t){"use strict";return e.extend({initialize:function(t){this.template=this.options.template,this.listenTo(this.model,"change:name",this.updateName),e.prototype.initialize.apply(this,[t]),this.$itemLabel=this.$(".item-label"),this.$UIicon=this.$(".ui-icon"),this.$draggableHelperUIicon=this.$draggableHelper.find(".ui-icon")},render:function(){this.updateName(),this.$UIicon.addClass(this.model.apIcon()),this.$draggableHelperUIicon.addClass(this.model.apIcon()).text(this.model.name()),this.listenTo(this.model,"change:state",this.updateState),this.updateState()},updateName:function(){this.$itemLabel.html(t.escape(this.model.name()))},updateState:function(){this.model.isConnected()?this.$el.addClass("ap-connected"):this.$el.addClass("ap-disconnected"),parseInt(this.model.get("state"),10)===11?this.$el.addClass("ap-isolated"):this.$el.removeClass("ap-isolated")},remove:function(){this.stopListening(this.model,"change:name",this.updateName),this.stopListening(this.model,"change:state",this.updateState),e.prototype.remove.apply(this,arguments)}})}),define("ubnt/view/map/MapBase",["backbone","underscore","jquery","msg/Msg"],function(e,t,n,r){"use strict";return e.View.extend({_fullyQualifiedName:"UBNT.views.map.MapBase",initialize:function(){t.bindAll(this),this.collections={},this.collections.markers=this.options.markers,this.MarkerView=this.options.markerView,this.markerTemplate=this.options.markerTemplate,this.markerViews={},this.layers={},this.layerItems={},this.layerZ=1},bindHandlers:function(){this.collections.markers.on("add",this.addMarker),this.collections.markers.on("change",this.updateMarker),this.collections.markers.on("reset",this.resetMarkers),this.collections.markers.on("remove",this.removeMarker),t.each(this.layers,function(e){e.bindHandlers()},this)},unbindHandlers:function(){this.collections.markers.off("add",this.addMarker),this.collections.markers.off("change",this.updateMarker),this.collections.markers.off("reset",this.resetMarkers),this.collections.markers.off("remove",this.removeMarker),t.each(this.layers,function(e){e.unbindHandlers()},this)},getMap:function(){return this.model},show:function(){this.$el.show()},hide:function(){this.$el.hide()},resize:function(){},mapChangeHandler:function(){},toggleLabels:function(){n.each(this.markers,function(e,t){t.toggleLabel()})},toggleDetails:function(){n.each(this.markers,function(e,t){t.toggleDetail()})},bringLayerItemToTop:function(e){var t=this.layerItems[e.cid];t&&(t.$el.css("zIndex",this.layerZ),this.layerZ++)},addMarker:function(e,t){var n=e.get("map_id"),i=e.id;if(!this.model||!t||n!=this.model.id)return;if(this.markerViews[i]===null||this.markerViews[i]===undefined){var s=new this.MarkerView({model:e,map:this,template:this.markerTemplate});s.bind("markerselect",this.markerSelectHandler),s.bind("markerdeselect",this.markerDeselectHandler),this.markerViews[i]=s;var o=s.$(".detail.mac-text"),u=s.$(".detail.channel-text"),a=s.$(".detail.users-text"),f=s.$(".detail.guests-text");o.find("span").text(r.G_MapMAC),u.find("span").text(r.G_MapChannel),a.find("span").text(r.G_MapUsers),f.find("span").text(r.G_MapGuests)}},updateMarker:function(){throw"updateMarker: You must override this function."},resetMarkers:function(){t.each(this.markerViews,function(e){this.removeMarker(e.model)},this),this.markerViews={},this.collections.markers.each(function(e){this.addMarker(e)},this)},removeMarker:function(e){var t=this.markerViews[e.id];t&&(this.markerViews[e.id].remove(),delete this.markerViews[e.id],this.trigger("mapremovemarker",t))},getMarkers:function(){return this.markerViews},addLayerItem:function(){throw"addLayerItem: You must override this function."},removeLayerItem:function(){throw"removeLayerItem: You must override this function."},dropHandler:function(){throw"dropHandler: You must override this function."},enableMapDrag:function(){throw"enableMapDrag: You must override this function."},disableMapDrag:function(){throw"disableMapDrag: You must override this function."},computeDistanceBetween:function(){throw"computeDistanceBetween: You must override this function."},computeOffset:function(){throw"computeOffset: You must override this function."},translateToPixelCoordinates:function(){throw"translateToPixelCoordinates: You must override this function."},translateToMapCoordinates:function(){throw"translateToMapCoordinates: You must override this function."},markerSelectHandler:function(e){t.each(this.markerViews,function(t){t!==e&&t.setExpanded(!1)},this)},markerDeselectHandler:function(){},remove:function(){this.unbindHandlers(),t.each(this.markerViews,function(e){e.unbind("markerselect",this.markerSelectHandler),e.unbind("markerdeselect",this.markerDeselectHandler)},this),e.View.prototype.remove.apply(this,arguments)}},{MAP_PANE:"mapPane",OVERLAY_LAYER:"overlayLayer",OVERLAY_SHADOW:"overlayShadow",OVERLAY_IMAGE:"overlayImage",FLOAT_SHADOW:"floatShadow",OVERLAY_MOUSE_TARGET:"overlayMouseTarget",FLOAT_PANE:"floatPane"})}),define("ubnt/view/map/GoogleMapOverlayWrapperView",[],function(){"use strict";return{Overlay:function(e,t){return this.view=e,this},initialize:function(){this.Overlay.prototype=new google.maps.OverlayView,this.Overlay.prototype.onAdd=function(){var e=this.getPanes();e[this.view.getPane()].appendChild(this.view.$el.get(0))},this.Overlay.prototype.onRemove=function(){this.view.$el.hide()},this.Overlay.prototype.draw=function(){this.view.trigger("layeritemadded"),this.view.$el.show()},this.Overlay.prototype.hide=function(){this.view.$el.hide()},this.Overlay.prototype.show=function(){this.draw(),this.view.$el.show()},this.Overlay.prototype.toggle=function(){this.view.$el.toggle()}}}}),define("ubnt/view/map/GoogleMapMarkerWrapperView",[],function(){"use strict";return{Overlay:function(e,t){return this.markerView=e,this},initialize:function(){this.Overlay.prototype=new google.maps.OverlayView,this.Overlay.prototype.onAdd=function(){var e=this.getPanes();e.floatPane.appendChild(this.markerView.$el.get(0))},this.Overlay.prototype.onRemove=function(){this.markerView.$el.hide()},this.Overlay.prototype.draw=function(){var e=this.getProjection(),t=e.fromLatLngToDivPixel(new google.maps.LatLng(this.markerView.model.get("x"),this.markerView.model.get("y")));this.markerView.$el.css("position","absolute"),this.markerView.$el.css("top",t.y+"px"),this.markerView.$el.css("left",t.x+"px"),this.markerView.$el.show()},this.Overlay.prototype.hide=function(){this.container.hide()},this.Overlay.prototype.show=function(){this.draw(),this.container.show()},this.Overlay.prototype.toggle=function(){this.container.toggle()}}}}),define("async",[],function(){function n(e){var t,n;t=document.createElement("script"),t.type="text/javascript",t.async=!0,t.src=e,n=document.getElementsByTagName("script")[0],n.parentNode.insertBefore(t,n)}function r(t,n){var r=/!(.+)/,i=t.replace(r,""),s=r.test(t)?t.replace(/.+!/,""):e;return i+=i.indexOf("?")<0?"?":"&",i+s+"="+n}function i(){return t+=1,"__async_req_"+t+"__"}var e="callback",t=0;return{load:function(e,t,s,o){if(o.isBuild)s(null);else{var u=i();window[u]=s,n(r(e,u))}}}}),define("gmaps",["jquery"],function(e){"use strict";if(window.google&&window.google.maps)return window.google;var t=e.Deferred();return require(["async!//maps.google.com/maps/api/js?libraries=geometry&sensor=false!callback"],function(){t.resolve(window.google)},function(e){window.googleMapsNotLoaded(),t.reject()}),t.promise()}),define("ubnt/view/map/GoogleMapView",["underscore","ubnt/view/map/MapBase","ubnt/view/map/GoogleMapOverlayWrapperView","ubnt/view/map/GoogleMapMarkerWrapperView","ubnt/Timer","ubnt/TimerEvent","jquery","msg/Msg","gmaps"],function(e,t,n,r,i,s,o,u,a){"use strict";return t.extend({_fullyQualifiedName:"UBNT.views.map.GoogleMap",initialize:function(n){e.bindAll(this),this.app=n.app,this.loaded=!1,a.maps?o("body").hasClass("googlemaps-notLoaded")||(this.loaded=!0):a.done(o.proxy(function(e){a=e,this.onLoad()},this)).fail(function(){o("body").addClass("googlemaps-notLoaded")}),this.mapBaseType="google",t.prototype.initialize.apply(this,[n]),this.markerViewOverlays={},this.layerItemOverlays={},this.layerQueue=[]},onLoad:function(){this.loaded=!0,r.initialize(),n.initialize(),this.trigger("googlemaps-loaded")},setMap:function(e){this.model&&(this.model.off("change:zoom",this.mapZoomHandler),this.model.off("change:lat",this.mapOffsetHandler),this.model.off("change:lng",this.mapOffsetHandler),this.model.off("change:mapTypeId",this.mapTypeHandler)),this.model=e,this.model.on("change:zoom",this.mapZoomHandler),this.model.on("change:lat",this.mapOffsetHandler),this.model.on("change:lng",this.mapOffsetHandler),this.model.on("change:mapTypeId",this.mapTypeHandler),this.zoomLevel=this.model.get("zoom"),o("body").hasClass("googlemaps-notLoaded")?window.googleMapsNotLoaded():this.renderMap()},mapChangeHandler:function(){this.renderMap()},getMap:function(){return this.model},render:function(){return this.model&&this.setOffset(this.model.get("lat")||0,this.model.get("lng")||0,!0),this.$el},renderMap:function(){if(!this.loaded)return this.renderOnLoad=!0;this.calculateScale();var t=this,n={zoom:this.model?this.model.get("zoom"):1,center:new a.maps.LatLng(this.model.get("lat"),this.model.get("lng")),mapTypeId:a.maps.MapTypeId[this.model.get("mapTypeId").toUpperCase()],tilt:0,disableDoubleClickZoom:!0,zoomControl:!1,streetViewControl:!1,panControl:!1,scaleControl:!0};this.googleMap?this.googleMap.setOptions(n):(this.googleMap=new a.maps.Map(this.$el.get(0),n),a.maps.event.addListener(this.googleMap,"zoom_changed",function(){var e=t.googleMap.getZoom();e>20&&(e=20),e<1&&(e=1),t.setZoom(e)}),a.maps.event.addListener(this.googleMap,"center_changed",function(){t.setOffset(t.googleMap.center.lat(),t.googleMap.center.lng())}),a.maps.event.addListener(this.googleMap,"maptypeid_changed",function(){t.setMapType(t.googleMap.getMapTypeId())}),this.googleMapOverlay=new a.maps.OverlayView,this.googleMapOverlay.onAdd=function(){},this.googleMapOverlay.draw=function(){},this.googleMapOverlay.onRemove=function(){},this.googleMapOverlay.setMap(this.googleMap),e.each(this.layerQueue,function(e){this.layers[e.cid]=e,e.bindHandlers()},this),this.layerQueue=[],this.loaded=!0),this.previousMapZoom=n.zoom,this.googleMapOverlay&&this.resetMarkers()},addLayer:function(t,n){var r=e.extend(n,{mapBase:this}),i=new t(r);this.googleMap===null||this.googleMap===undefined?this.layerQueue.push(i):this.layers[i.cid]=t},addLayerItem:function(e){if(this.googleMap){var t=new n.Overlay(e,this.googleMap);t.setMap(this.googleMap),this.layerItems[e.cid]=e,this.layerItemOverlays[e.cid]=t,e.$el.css("zIndex",this.layerZ),this.layerZ++,e.trigger("layeritemadded")}},removeLayerItem:function(e){var t=this.layerItemOverlays[e.cid];t&&t.setMap(null)},positionMarker:function(e){this.googleMap&&this.markerViewOverlays[e.model.id]&&(e.model.attributes.map_id==this.model.id?this.markerViewOverlays[e.model.id].setMap(this.googleMap):this.markerViewOverlays[e.model.id].setMap(null))},updateMarkerPositions:function(){e.each(this.markerViews,this.positionMarker)},addMarker:function(e){t.prototype.addMarker.apply(this,[e,this.model]);var n=this.markerViews[e.id];if(n){if(this.markerViewOverlays[e.id]===null||this.markerViewOverlays[e.id]===undefined)this.markerViewOverlays[e.id]=new r.Overlay(n,this.googleMap);var i=this.markerViewOverlays[e.id];this.model&&this.model.id==e.attributes.map_id&&i.setMap(this.googleMap),n.unbind("dragstart",this.markerDragStartHandler).bind("dragstart",this.markerDragStartHandler),n.unbind("dragstop",this.markerDragStopHandler).bind("dragstop",this.markerDragStopHandler),this.trigger("mapaddmarker",n)}},updateMarker:function(e){e.get("map_id")!==undefined&&(this.model&&e.get("map_id")==this.model.id?this.addMarker(e):this.removeMarker(e))},removeMarker:function(e){var n=this.markerViewOverlays[e.id];this.markerViewOverlays[e.id]&&(this.markerViewOverlays[e.id].setMap(null),delete this.markerViewOverlays[e.id]),t.prototype.removeMarker.apply(this,[e])},resize:function(){this.loaded&&this.googleMap&&a.maps.event.trigger(this.googleMap,"resize")},markerDragStartHandler:function(){this.isMarkerDragging=!0,this.disableMapDrag()},markerDragStopHandler:function(e,t){this.isMarkerDragging=!1,this.enableMapDrag();if(t&&t.position){var n=this.googleMapOverlay.getProjection().fromDivPixelToLatLng(new a.maps.Point(t.position.left,t.position.top)),r=t.helper.data("view"),i=r.model;this.app.isReadOnly?i.set({x:Number(n.lat().toFixed(5)),y:Number(n.lng().toFixed(5))}):i.save({x:Number(n.lat().toFixed(5)),y:Number(n.lng().toFixed(5))})}},dropHandler:function(e,t){var n=this.googleMapOverlay.getProjection().fromContainerPixelToLatLng(new a.maps.Point(t.position.left,t.position.top-42)),r=t.helper.data("view"),i=r.model;this.app.isReadOnly?i.set({x:Number(n.lat().toFixed(5)),y:Number(n.lng().toFixed(5)),map_id:this.model.id}):i.save({x:Number(n.lat().toFixed(5)),y:Number(n.lng().toFixed(5)),map_id:this.model.id})},enableMapDrag:function(){this.googleMap&&this.googleMap.setOptions({draggable:!0})},disableMapDrag:function(){this.googleMap&&this.googleMap.setOptions({draggable:!1})},calculateScale:function(){this.scale=1/Math.pow(2,20-this.zoomLevel)/5},mapTypeHandler:function(e){this.setMapType(e.get("mapTypeId"),!0)},setMapType:function(e,t){this.model.set({mapTypeId:e}),!t&&!this.app.isReadOnly&&this.saveMapType(e)},saveMapType:e.debounce(function(e){this.model.unset("mapTypeId",{silent:!0}),this.model.save({mapTypeId:e},{silent:!0})},250),mapOffsetHandler:function(e){this.setOffset(e.get("lat")||0,e.get("lng")||0,!0)},setOffset:function(e,t,n){this.model.set({lat:e,lng:t}),!n&&!this.app.isReadOnly&&this.saveOffset(e,t)},saveOffset:e.debounce(function(e,t){this.model.unset("lat",{silent:!0}),this.model.unset("lng",{silent:!0}),this.model.save({lat:e,lng:t},{silent:!0})},250),mapZoomHandler:function(e){this.setZoom(e.get("zoom")||this.zoomLevel,!0),this.renderMap(),this.updateMarkerPositions()},setZoom:function(e,t){if(this.zoomLevel==e)return;this.zoomLevel=e,this.model.set({zoom:e}),!t&&!this.app.isReadOnly&&this.saveZoom(e)},saveZoom:e.debounce(function(e){this.model.unset("zoom",{silent:!0}),this.model.save({zoom:e},{silent:!0})},250),computeDistanceBetween:function(e,t,n,r){var i=this.googleMapOverlay.getProjection().fromDivPixelToLatLng(new a.maps.Point(e,t)),s=this.googleMapOverlay.getProjection().fromDivPixelToLatLng(new a.maps.Point(n,r));return a.maps.geometry.spherical.computeDistanceBetween(i,s)},computeOffset:function(e,t,n,r){var i=this.googleMapOverlay.getProjection().fromDivPixelToLatLng(new a.maps.Point(e,t)),s=a.maps.geometry.spherical.computeOffset(i,n,(r+Math.PI)*(180/Math.PI)),o=this.googleMapOverlay.getProjection().fromLatLngToDivPixel(s);return{x:Math.round(o.x),y:Math.round(o.y)}},translateToPixelCoordinates:function(e,t){var n=this.googleMapOverlay.getProjection().fromLatLngToDivPixel(new a.maps.LatLng(e,t));return n},translateToMapCoordinates:function(e,t){var n=this.googleMapOverlay.getProjection().fromDivPixelToLatLng(new a.maps.Point(e,t));return{x:n.lat(),y:n.lng()}},remove:function(){this.model.off("change",this.mapChangeHandler),e.each(this.markerViews,function(e){e.unbind("dragstart",this.markerDragStartHandler),e.unbind("dragstop",this.markerDragStopHandler)},this),this.googleMap&&(a.maps.event.removeListener(this.googleMap,"zoom_changed"),a.maps.event.removeListener(this.googleMap,"center_changed"),a.maps.event.removeListener(this.googleMap,"bounds_changed"),a.maps.event.removeListener(this.googleMap,"maptypeid_changed")),this.model&&(this.model.off("change:zoom",this.mapZoomHandler),this.model.off("change:lat",this.mapOffsetHandler),this.model.off("change:lng",this.mapOffsetHandler),this.model.off("change:mapTypeId",this.mapTypeHandler)),t.prototype.remove.apply(this,arguments)}})}),function(e){typeof define=="function"&&define.amd?define("libs/jquery.mousewheel",["jquery"],e):typeof exports=="object"?module.exports=e:e(jQuery)}(function(e){function u(t){var n=t||window.event,o=r.call(arguments,1),u=0,f=0,l=0,c=0;t=e.event.fix(n),t.type="mousewheel","detail"in n&&(l=n.detail*-1),"wheelDelta"in n&&(l=n.wheelDelta),"wheelDeltaY"in n&&(l=n.wheelDeltaY),"wheelDeltaX"in n&&(f=n.wheelDeltaX*-1),"axis"in n&&n.axis===n.HORIZONTAL_AXIS&&(f=l*-1,l=0),u=l===0?f:l,"deltaY"in n&&(l=n.deltaY*-1,u=l),"deltaX"in n&&(f=n.deltaX,l===0&&(u=f*-1));if(l===0&&f===0)return;c=Math.max(Math.abs(l),Math.abs(f));if(!s||c<s)s=c;return u=Math[u>=1?"floor":"ceil"](u/s),f=Math[f>=1?"floor":"ceil"](f/s),l=Math[l>=1?"floor":"ceil"](l/s),t.deltaX=f,t.deltaY=l,t.deltaFactor=s,o.unshift(t,u,f,l),i&&clearTimeout(i),i=setTimeout(a,200),(e.event.dispatch||e.event.handle).apply(this,o)}function a(){s=null}var t=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],n="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],r=Array.prototype.slice,i,s;if(e.event.fixHooks)for(var o=t.length;o;)e.event.fixHooks[t[--o]]=e.event.mouseHooks;e.event.special.mousewheel={version:"3.1.6",setup:function(){if(this.addEventListener)for(var e=n.length;e;)this.addEventListener(n[--e],u,!1);else this.onmousewheel=u},teardown:function(){if(this.removeEventListener)for(var e=n.length;e;)this.removeEventListener(n[--e],u,!1);else this.onmousewheel=null}},e.fn.extend({mousewheel:function(e){return e?this.bind("mousewheel",e):this.trigger("mousewheel")},unmousewheel:function(e){return this.unbind("mousewheel",e)}})}),define("ubnt/view/map/ImageMapView",["ubnt/view/map/MapBase","underscore","jquery","libs/jquery.mousewheel"],function(e,t,n){"use strict";return e.extend({_fullyQualifiedName:"UBNT.views.map.ImageMap",initialize:function(n){t.bindAll(this),this.mapBaseType="image",this.app=n.app,e.prototype.initialize.apply(this,[n]),this.zoom=1,this.scale=1,this.$dragLayer=this.$(".image-drag-layer"),this.$subMarkerLayer=this.$(".sub-marker-layer"),this.$markerLayer=this.$(".marker-layer"),this.mapImages=[],this.initHandlers()},initHandlers:function(){this.$el.bind("mousedown",this.mouseDownHandler),this.$el.bind("mousewheel",this.mouseWheelHandler)},setMap:function(e){this.model&&(this.model.off("change:zoom",this.mapZoomHandler),this.model.off("change:offset_left",this.mapOffsetHandler),this.model.off("change:offset_right",this.mapOffsetHandler),this.model.off("change:url",this.loadMap)),this.model=e,this.$img=this.mapImages[this.model.id],this.$(".image-map-layer").empty();if(this.$img===undefined)this.loadMap();else{var t=this.$el.width(),n=this.$el.height();this.imgWidth=this.$img[0].width,this.imgHeight=this.$img[0].height,this.scale=1,this.imgWidth/this.imgHeight>t/n?(this.$img.height(t/this.imgWidth*this.imgHeight),this.$img.width(t)):(this.$img.width(n/this.imgHeight*this.imgWidth),this.$img.height(n)),this.$dragLayer.css("top",(n-this.imgHeight)/2+"px"),this.$dragLayer.css("left",(t-this.imgWidth)/2+"px"),this.$(".image-map-layer").append(this.$img),this.resetMarkers(),this.model.on("change:zoom",this.mapZoomHandler),this.model.on("change:offset_left",this.mapOffsetHandler),this.model.on("change:offset_right",this.mapOffsetHandler),this.model.on("change:url",this.loadMap),this.mapZoomHandler(this.model),this.mapOffsetHandler(this.model)}},mapZoomHandler:function(e){this.setZoom(e.get("zoom"),!0)},mapOffsetHandler:function(e){this.setOffset(e.get("offset_top")||0,e.get("offset_left")||0,!0)},loadMap:function(e,t,r){var i=this;this.$img=n(new Image),this.$img.load(function(){i.mapImages[i.model.id]=n(this),i.$img.unbind("load"),i.setMap(i.model)}),this.$img.attr("src",this.model.get("url"))},render:function(){return this.updateMarkerPositions(),this.model&&this.setOffset(this.model.get("offset_top")||0,this.model.get("offset_left")||0,!0),this.$el},preventEventPropagationFunc:function(e){e.stopPropagation()},addMarker:function(t){var n=this;e.prototype.addMarker.apply(this,[t,this.model]);var r=this.markerViews[t.id];r&&(r.$el.unbind("mousedown",this.preventEventPropagationFunc).bind("mousedown",this.preventEventPropagationFunc),r.unbind("dragstart",this.markerDragStartHandler).bind("dragstart",this.markerDragStartHandler),r.unbind("dragstop",this.markerDragStopHandler).bind("dragstop",this.markerDragStopHandler),this.positionMarker(r),this.$markerLayer.append(r.$el))},updateMarker:function(e){e.get("map_id")!==undefined&&(this.model&&e.get("map_id")==this.model.id?this.addMarker(e):this.removeMarker(e))},positionMarker:function(e){if(this.model&&e.model.attributes.map_id==this.model.id){var t=e.model.get("x")*this.zoom,n=e.model.get("y")*this.zoom;e.setPosition(t,n),e.show()}else e.hide()},updateMarkerPositions:function(){t.each(this.markerViews,this.positionMarker)},addLayer:function(e,n){var r=t.extend(n,{mapBase:this}),i=new e(r);this.layers[i.cid]=i},addLayerItem:function(e){this.$subMarkerLayer.append(e.$el),e.trigger("layeritemadded")},removeLayerItem:function(e){e.$el.remove()},markerDragStartHandler:function(e){this.isMarkerDragging=!0},markerDragStopHandler:function(e,t){this.isMarkerDragging=!1;if(t&&t.helper){var n=t.helper.data("view"),r=n.model;this.app.isReadOnly?r.set({x:t.position.left/this.zoom,y:t.position.top/this.zoom}):r.save({x:t.position.left/this.zoom,y:t.position.top/this.zoom})}},mouseDownHandler:function(e){return e.button==2?(e.preventDefault(),e.stopPropagation(),!1):(this.startPageX=e.pageX,this.startPageY=e.pageY,n("body").bind("mouseup",this.mouseUpHandler),this.$el.bind("mousemove",this.mouseMoveHandler),!1)},mouseWheelHandler:function(e,t,n,r){},mouseUpHandler:function(){n("body").unbind("mouseup",this.mouseUpHandler),this.$el.unbind("mousemove",this.mouseMoveHandler)},mouseMoveHandler:function(e){if(!this.isMarkerDragging){this.deltaX=e.pageX-this.startPageX,this.deltaY=e.pageY-this.startPageY,this.startPageX=e.pageX,this.startPageY=e.pageY;var t=this.$dragLayer.offset(),n=t.top+this.deltaY,r=t.left+this.deltaX;this.setOffset(n,r)}},clickHandler:function(e){var t=n(e.target);t.hasClass("phone-icon")&&(t.parent().css("z-index",this.currentZIndex),this.currentZIndex++)},dropHandler:function(e,t){var n=t.helper.data("view"),r=n.model,i=this.$dragLayer.position(),s=(t.position.left-i.left)/this.zoom,o=(t.position.top-i.top-42)/this.zoom;this.app.isReadOnly?r.set({x:s,y:o,map_id:this.model.id}):r.save({x:s,y:o,map_id:this.model.id})},setOffset:function(e,t,n){this.$dragLayer.offset({top:e,left:t}),this.model.set({offset_top:e,offset_left:t}),!n&&!this.app.isReadOnly&&this.saveOffset(e,t)},saveOffset:t.debounce(function(e,t){this.model.unset("offset_top",{silent:!0}),this.model.unset("offset_left",{silent:!0}),this.model.save({offset_top:e,offset_left:t},{silent:!0})},250),setZoom:function(e){var t=this.$dragLayer.position(),n=this.$el.width(),r=this.$el.height();this.zoom=e/10,this.$img.width(this.scale*this.imgWidth*this.zoom),this.$img.height(this.scale*this.imgHeight*this.zoom),this.updateMarkerPositions()},setFocus:function(e,t,n){var r=this.translateToPixelCoordinates(e,t),i=this.$el.width(),s=this.$el.height(),o=i/2-r.x,u=s/2-r.y;n||(this.$dragLayer.css("top",u+"px"),this.$dragLayer.css("left",o+"px"))},enableMapDrag:function(){this.$el.on("mousedown",this.mouseDownHandler)},disableMapDrag:function(){this.$el.off("mousedown",this.mouseDownHandler)},translateToPixelCoordinates:function(e,t){return{x:e*this.scale*this.zoom,y:t*this.scale*this.zoom}},translateToMapCoordinates:function(e,t){return{x:e/this.scale/this.zoom,y:t/this.scale/this.zoom}},computeOffset:function(e,t,n,r){return{x:e+Math.sin(r)*n*this.scale*this.zoom,y:t-Math.cos(r)*n*this.scale*this.zoom}},computeDistanceBetween:function(e,t,n,r){var i=this.translateToMapCoordinates(e,t),s=this.translateToMapCoordinates(n,r);return Math.sqrt((s.x-i.x)*(s.x-i.x)+(s.y-i.y)*(s.y-i.y))},remove:function(){this.$el.unbind("mousedown",this.mouseDownHandler),this.$el.unbind("mousewheel",this.mouseWheelHandler),t.each(this.markerViews,function(e){e.$el.unbind("mousedown"),e.unbind("dragstart",this.markerDragStartHandler),e.unbind("dragstop",this.markerDragStopHandler)},this),n("body").unbind("mouseup",this.mouseUpHandler),this.$el.unbind("mousemove",this.mouseMoveHandler),this.$el.off("mousedown",this.mouseDownHandler),this.model&&(this.model.off("change:zoom",this.mapZoomHandler),this.model.off("change:offset_left",this.mapOffsetHandler),this.model.off("change:offset_right",this.mapOffsetHandler),this.model.off("change:url",this.loadMap)),e.prototype.remove.apply(this,arguments)}})}),define("ubnt/view/uicomponents/DroppableItemView",["backbone","jquery"],function(e,t){"use strict";return e.View.extend({_fullyQualifiedName:"UBNT.views.uicomponents.DroppableItem",initialize:function(){this.scope=this.options.scope||"global",this.accept=this.options.accept,this.drop=this.options.drop,this._greedy=this.options.greedy||!0;var e=this;this.$el.droppable({tolerance:"pointer",accept:this.accept,greedy:this._greedy,activeClass:"droppable",drop:function(n,r){t(this).removeClass("ui-state-highlight"),e.trigger("drop",n,r)},over:function(n,r){t(this).addClass("ui-state-highlight"),e.trigger("over",n,r)},out:function(n,r){t(this).removeClass("ui-state-highlight"),e.trigger("out",n,r)}})},destroy:function(){this.$el.droppable("destroy")},setScope:function(e){this.$el.droppable("option","scope",e)},setAccept:function(e){this.$el.droppable("option","accept",e)}})}),define("ubnt/view/map/MapWidgetView",["backbone","jquery","underscore","ubnt/view/map/MarkerView","ubnt/view/map/GoogleMapView","ubnt/view/map/ImageMapView","ubnt/view/uicomponents/DroppableItemView","libs/jquery.mousewheel"],function(e,t,n,r,i,s,o){"use strict";return e.View.extend({_fullyQualifiedName:"UBNT.views.map.MapWidget",initialize:function(){n.bindAll(this),this.markerView=this.options.markerView||r,this.markerTemplate=this.options.markerTemplate,this.layers={},this.maps=this.options.maps,this.markers=this.options.markers,this.app=this.options.app,this.zoomLevel=1,this.$googleMapContainer=this.$(".google-map-container"),this.googleMap=new i({app:this.app,el:this.$googleMapContainer,collection:this.maps,markers:this.markers,markerView:this.markerView,markerTemplate:this.markerTemplate}),this.$imageMapContainer=this.$(".image-map-container"),this.imageMap=new s({app:this.app,el:this.$imageMapContainer,collection:this.maps,markers:this.markers,markerView:this.markerView,markerTemplate:this.markerTemplate}),this.initHandlers(),this.initDroppable()},initHandlers:function(){var e=this;this.$el.bind("mousewheel",this.mouseWheelHandler)},bindHandlers:function(){this.googleMap.bindHandlers(),this.imageMap.bindHandlers()},unbindHandlers:function(){this.googleMap.unbindHandlers(),this.imageMap.unbindHandlers()},render:function(){this.$googleMap=this.googleMap.render(),this.$imageMap=this.imageMap.render(),this.isRendered||(this.isRendered=!0)},locateDevice:function(e){if(this.isRendered){if(this.markers.get(e)&&this.model.id==e.get("map_id")){var t;this.model.get("type")==="googleMap"?t=this.googleMap.markerViews[e.id]:t=this.imageMap.markerViews[e.id];if(t){if(this.model.get("type")==="imageMap"){var r=t.$el.position(),i=this.imageMap.translateToMapCoordinates(r.left,r.top);this.imageMap.setFocus(i.x,i.y)}t.pulse()}else n.delay(this.locateDevice,50,e)}}else n.delay(this.locateDevice,50,e)},addLayer:function(e,t){this.googleMap.addLayer(e,t),this.imageMap.addLayer(e,t)},setMap:function(e){e&&(this.model&&this.model.off("change:type",this.setMap),this.model=e,this.model.on("change:type",this.setMap),e.get("type")==="googleMap"?(this.googleMap.show(),this.googleMap.setMap(e),this.imageMap.hide(),t("#Map").addClass("isGoogleMap")):(this.imageMap.show(),this.imageMap.setMap(e),this.googleMap.hide(),t("#Map").removeClass("isGoogleMap")),this.zoomLevel=e.get("zoom"))},initDroppable:function(){this.droppable=new o({el:this.el,accept:".unplaced-marker"}),this.droppable.bind("drop",this.dropHandler)},dropHandler:function(e,t){this.model.attributes.type=="googleMap"?this.googleMap.dropHandler(e,t):this.imageMap.dropHandler(e,t)},mouseWheelHandler:function(e,t,n,r){r=r||e.originalEvent.wheelDeltaY;var i=this.zoomLevel;if(r>0){if(!(this.zoomLevel<20))return;i+=1}else{if(!(this.zoomLevel>1))return;i-=1}this.setZoom(i)},setZoom:function(e,t){if(this.zoomLevel==e)return;this.zoomLevel=e,this.model.set({zoom:e}),!t&&!this.app.isReadOnly&&this.saveZoom(e)},saveZoom:n.debounce(function(e){this.model.unset("zoom",{silent:!0}),this.model.save({zoom:e},{silent:!0})},250),resize:function(){this.imageMap&&this.imageMap.resize(),this.googleMap&&this.googleMap.resize()},remove:function(){this.unbindHandlers(),this.model.off("change:type",this.setMap),this.$el.unbind("mousewheel",this.mouseWheelHandler),this.droppable.unbind("drop",this.dropHandler),this.model.off("change:type",this.setMap),this.isRendered=!1,e.View.prototype.remove.apply(this,arguments)}})}),define("ubnt/view/map/MapView",["backbone","underscore","jquery","ubnt/view/map/MapWidgetView","msg/Msg","libs/jquery.cookie"],function(e,t,n,r,i){"use strict";return e.View.extend({_fullyQualifiedName:"UBNT.views.map.Map",initialize:function(){this.markers=this.options.markers,this.maps=this.options.maps,this.markerView=this.options.markerView,this.markerTemplate=this.options.markerTemplate,this.app=this.options.app,this.mapWidget=new r({app:this.app,el:this.$(".ubnt-map-widget"),maps:this.maps,markers:this.markers,markerView:this.markerView,markerTemplate:this.markerTemplate})},setMap:function(e){this.model=e,this.mapWidget.setMap(e)},tabShowHandler:function(e,t){n("#Map:visible").length?(this.visible=!0,this.mapWidget.resize()):this.visible===!0&&(this.visible=!1)},render:function(){!this.rendered&&(this.rendered=!0)&&this.mapWidget.bindHandlers(),this.mapWidget.render(),this.tabShowHandler()},locateDevice:function(e){this.rendered?this.markers.get(e)&&this.mapWidget.locateDevice(e):t.delay(this.locateDevice,50,e)},remove:function(){this.rendered=!1,e.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/map/TopologyView",["backbone","underscore","jquery","libs/kinetic"],function(e,t,n,r){"use strict";return e.View.extend({LINK_COLOR:[{value:45,color:"#57c23e"},{value:30,color:"#f78100"},{value:20,color:"#ff0000"}],DISCONNECTED_COLOR:"#CCCCCC",initialize:function(e){t.bindAll(this),this.indexView=e.indexView,this.markers=this.indexView.app.collection("Devices"),this.linkLines=[],this.isMoving=!1,this.isVisible=!1},setMap:function(e){this.model&&(this.model.off("change:zoom",this.mapChangeHandler),this.model.off("change:offset_left",this.mapChangeHandler),this.model.off("change:offset_top",this.mapChangeHandler),this.model.off("change:lng",this.mapChangeHandler),this.model.off("change:lat",this.mapChangeHandler),this.model.off("change:upp",this.mapChangeHandler),this.model.off("change:unit",this.mapChangeHandler)),this.isVisible&&this.destroyStage(),this.model=e,this.isVisible&&(this.setupStage(),this.rebuildUplinks()),this.model.on("change:zoom",this.mapChangeHandler),this.model.on("change:offset_left",this.mapChangeHandler),this.model.on("change:offset_top",this.mapChangeHandler),this.model.on("change:lng",this.mapChangeHandler),this.model.on("change:lat",this.mapChangeHandler),this.model.on("change:upp",this.mapChangeHandler),this.model.on("change:unit",this.mapChangeHandler),this.mapChangeHandler()},bindListeners:function(){this.markers.on("add",this.mapChangeHandler),this.markers.on("remove",this.mapChangeHandler),this.markers.on("change:map_id",this.mapChangeHandler),this.markers.on("change:x",this.mapChangeHandler),this.markers.on("change:y",this.mapChangeHandler)},unbindListeners:function(){this.markers.off("add",this.mapChangeHandler),this.markers.off("remove",this.mapChangeHandler),this.markers.off("change:map_id",this.mapChangeHandler),this.markers.off("change:x",this.mapChangeHandler),this.markers.off("change:y",this.mapChangeHandler)},mapChangeHandler:function(){this.destroyStage(),this.isVisible&&(this.setupStage(),this.rebuildUplinks())},show:function(){this.isVisible||(this.isVisible=!0,this.bindListeners(),this.setupStage(),this.rebuildUplinks(),this.markers.on("change",this.rebuildUplinks))},hide:function(){this.isVisible&&(this.isVisible=!1,this.unbindListeners(),this.markers.off("change",this.rebuildUplinks),this.destroyStage())},setupStage:function(){var e=n(".marker-layer");this.layer=new r.Layer,this.stage=new r.Stage({container:e[0],width:e.width(),height:e.parent().height()}),this.stage.add(this.layer)},destroyStage:function(){this.layer&&(this.layer.destroy(),this.stage.destroy())},getMarkerPosition:function(e){var t=this.markers.get(e),n=this.model.get("zoom");if(this.model.get("type")==="googleMap"){var r=this.indexView.getActiveMap().googleMapOverlay.getProjection(),i=r.fromLatLngToDivPixel(new google.maps.LatLng(t.get("x"),t.get("y")));return{left:i.x,top:i.y}}return{left:t.get("x")*n/10,top:t.get("y")*n/10}},rebuildUplinks:function(){if(this.model.get("type")==="googleMap")return;var e,n,r;this.model&&(e=this.markers.filter(function(e){return e.get("map_id")===this.model.get("_id")},this),t.each(this.linkLines,function(e){e.line.destroy()}),t.each(e,function(e){n=e.uplinks(),t.each(n,function(t){t.configured&&(r=this.markers.findWhere({mac:t.mac}),r&&r.get("map_id")===this.model.get("_id")&&this.setTopologyLink(e,r,t))},this)},this))},setTopologyLink:function(e,n,r){var i=.8,s=this.getMarkerPosition(e.id),o=this.getMarkerPosition(n.id),u,a,f;r.configured?(r.up?(u=!0,a=this.LINK_COLOR[0].color,t.each(this.LINK_COLOR,function(e){r.rssi<e.value&&(a=e.color)},this)):(u=!0,a=this.DISCONNECTED_COLOR),i=1):i=.25,f=this._createLine(s.left,s.top,o.left,o.top,a,i),this.linkLines.push({line:f,islandDevice:e,uplinkDevice:n}),this.layer.add(f),this.layer.drawScene()},_createLine:function(e,t,n,i,s,o){var u=new r.Line({points:this._getArrowPoints(e,t,n,i),stroke:s,opacity:o,dashArray:[10,10]});return u},_getArrowPoints:function(e,t,n,r){return[e,t,n,r]},remove:function(){this.unbindListeners(),this.model.off("change:zoom",this.mapChangeHandler),this.model.off("change:offset_left",this.mapChangeHandler),this.model.off("change:offset_top",this.mapChangeHandler),this.model.off("change:lng",this.mapChangeHandler),this.model.off("change:lat",this.mapChangeHandler),this.model.off("change:upp",this.mapChangeHandler),this.model.off("change:unit",this.mapChangeHandler),this.markers.off("change",this.rebuildUplinks),e.View.prototype.remove.apply(this,arguments)}})}),function(e,t,n){typeof module!="undefined"&&module.exports?module.exports=n():typeof define=="function"&&define.amd?define("heatmap",n):t[e]=n()}("h337",this,function(){var e={defaultRadius:40,defaultRenderer:"canvas2d",defaultGradient:{.25:"rgb(0,0,255)",.55:"rgb(0,255,0)",.85:"yellow",1:"rgb(255,0,0)"},defaultMaxOpacity:1,defaultMinOpacity:0,defaultBlur:.85,defaultXField:"x",defaultYField:"y",defaultValueField:"value",plugins:{}},t=function(){var n=function(t){this._coordinator={},this._data=[],this._radi=[],this._min=0,this._max=1,this._xField=t.xField||t.defaultXField,this._yField=t.yField||t.defaultYField,this._valueField=t.valueField||t.defaultValueField,t.radius&&(this._cfgRadius=t.radius)},r=e.defaultRadius;return n.prototype={_organiseData:function(e,t){var n=e[this._xField],i=e[this._yField],s=this._radi,o=this._data,u=this._max,a=this._min,f=e[this._valueField]||1,l=e.radius||this._cfgRadius||r;return o[n]||(o[n]=[],s[n]=[]),o[n][i]?o[n][i]+=f:(o[n][i]=f,s[n][i]=l),o[n][i]>u?(t?this.setDataMax(o[n][i]):this._max=o[n][i],!1):{x:n,y:i,value:f,radius:l,min:a,max:u}},_unOrganizeData:function(){var e=[],t=this._data,n=this._radi;for(var r in t)for(var i in t[r])e.push({x:r,y:i,radius:n[r][i],value:t[r][i]});return{min:this._min,max:this._max,data:e}},_onExtremaChange:function(){this._coordinator.emit("extremachange",{min:this._min,max:this._max})},addData:function(){if(arguments[0].length>0){var e=arguments[0],t=e.length;while(t--)this.addData.call(this,e[t])}else{var n=this._organiseData(arguments[0],!0);n&&this._coordinator.emit("renderpartial",{min:this._min,max:this._max,data:[n]})}return this},setData:function(e){var t=e.data,n=t.length;this._data=[],this._radi=[];for(var r=0;r<n;r++)this._organiseData(t[r],!1);return this._max=e.max,this._min=e.min||0,this._onExtremaChange(),this._coordinator.emit("renderall",this._getInternalData()),this},removeData:function(){},setDataMax:function(e){return this._max=e,this._onExtremaChange(),this._coordinator.emit("renderall",this._getInternalData()),this},setDataMin:function(e){return this._min=e,this._onExtremaChange(),this._coordinator.emit("renderall",this._getInternalData()),this},setCoordinator:function(e){this._coordinator=e},_getInternalData:function(){return{max:this._max,min:this._min,data:this._data,radi:this._radi}},getData:function(){return this._unOrganizeData()}},n}(),n=function(){function i(e){var n=e.container,r=this.shadowCanvas=document.createElement("canvas"),i=this.canvas=e.canvas||document.createElement("canvas"),s=this._renderBoundaries=[1e4,1e4,0,0],o=getComputedStyle(e.container)||{};i.className="heatmap-canvas",this._width=i.width=r.width=+o.width.replace(/px/,""),this._height=i.height=r.height=+o.height.replace(/px/,""),this.shadowCtx=r.getContext("2d"),this.ctx=i.getContext("2d"),i.style.cssText=r.style.cssText="position:absolute;left:0;top:0;",n.style.position="relative",n.appendChild(i),this._palette=t(e),this._templates={},this._setStyles(e)}var t=function(e){var t=e.gradient||e.defaultGradient,n=document.createElement("canvas"),r=n.getContext("2d");n.width=256,n.height=1;var i=r.createLinearGradient(0,0,256,1);for(var s in t)i.addColorStop(s,t[s]);return r.fillStyle=i,r.fillRect(0,0,256,1),r.getImageData(0,0,256,1).data},n=function(e,t){var n=document.createElement("canvas"),r=n.getContext("2d"),i=e,s=e;n.width=n.height=e*2;if(t==1)r.beginPath(),r.arc(i,s,e,0,2*Math.PI,!1),r.fillStyle="rgba(0,0,0,1)",r.fill();else{var o=r.createRadialGradient(i,s,e*t,i,s,e);o.addColorStop(0,"rgba(0,0,0,1)"),o.addColorStop(1,"rgba(0,0,0,0)"),r.fillStyle=o,r.fillRect(0,0,2*e,2*e)}return n},r=function(e){var t=[],n=e.min,r=e.max,i=e.radi,e=e.data,s=Object.keys(e),o=s.length;while(o--){var u=s[o],a=Object.keys(e[u]),f=a.length;while(f--){var l=a[f],c=e[u][l],h=i[u][l];t.push({x:u,y:l,value:c,radius:h})}}return{min:n,max:r,data:t}};return i.prototype={renderPartial:function(e){this._drawAlpha(e),this._colorize()},renderAll:function(e){this._clear(),this._drawAlpha(r(e)),this._colorize()},_updateGradient:function(e){this._palette=t(e)},updateConfig:function(e){e.gradient&&this._updateGradient(e),this._setStyles(e)},setDimensions:function(e,t){this._width=e,this._height=t,this.canvas.width=this.shadowCanvas.width=e,this.canvas.height=this.shadowCanvas.height=t},_clear:function(){this.shadowCtx.clearRect(0,0,this._width,this._height),this.ctx.clearRect(0,0,this._width,this._height)},_setStyles:function(e){this._blur=e.blur==0?0:e.blur||e.defaultBlur,e.backgroundColor&&(this.canvas.style.backgroundColor=e.backgroundColor),this._opacity=(e.opacity||0)*255,this._maxOpacity=(e.maxOpacity||e.defaultMaxOpacity)*255,this._minOpacity=(e.minOpacity||e.defaultMinOpacity)*255,this._useGradientOpacity=!!e.useGradientOpacity},_drawAlpha:function(e){var t=this._min=e.min,r=this._max=e.max,e=e.data||[],i=e.length,s=1-this._blur;while(i--){var o=e[i],u=o.x,a=o.y,f=o.radius,l=Math.min(o.value,r),c=u-f,h=a-f,p=this.shadowCtx,d;this._templates[f]?d=this._templates[f]:this._templates[f]=d=n(f,s),p.globalAlpha=(l-t)/(r-t),p.drawImage(d,c,h),c<this._renderBoundaries[0]&&(this._renderBoundaries[0]=c),h<this._renderBoundaries[1]&&(this._renderBoundaries[1]=h),c+2*f>this._renderBoundaries[2]&&(this._renderBoundaries[2]=c+2*f),h+2*f>this._renderBoundaries[3]&&(this._renderBoundaries[3]=h+2*f)}},_colorize:function(){var e=this._renderBoundaries[0],t=this._renderBoundaries[1],n=this._renderBoundaries[2]-e,r=this._renderBoundaries[3]-t,i=this._width,s=this._height,o=this._opacity,u=this._maxOpacity,a=this._minOpacity,f=this._useGradientOpacity;e<0&&(e=0),t<0&&(t=0),e+n>i&&(n=i-e),t+r>s&&(r=s-t);var l=this.shadowCtx.getImageData(e,t,n,r),c=l.data,h=c.length,p=this._palette;for(var d=3;d<h;d+=4){var v=c[d],m=v*4;if(!m)continue;var g;o>0?g=o:v<u?v<a?g=a:g=v:g=u,c[d-3]=p[m],c[d-2]=p[m+1],c[d-1]=p[m+2],c[d]=f?p[m+3]:g}l.data=c,this.ctx.putImageData(l,e,t),this._renderBoundaries=[1e3,1e3,0,0]},getValueAt:function(e){var t,n=this.shadowCtx,r=n.getImageData(e.x,e.y,1,1),i=r.data[3],s=this._max,o=this._min;return t=Math.abs(s-o)*(i/255)>>0,t},getDataURL:function(){return this.canvas.toDataURL()}},i}(),r=function(){var r=!1;return e.defaultRenderer==="canvas2d"&&(r=n),r}(),i={merge:function(){var e={},t=arguments.length;for(var n=0;n<t;n++){var r=arguments[n];for(var i in r)e[i]=r[i]}return e}},s=function(){function u(){var n=this._config=i.merge(e,arguments[0]||{});this._coordinator=new s;if(n.plugin){var u=n.plugin;if(!e.plugins[u])throw new Error("Plugin '"+u+"' not found. Maybe it was not registered.");var a=e.plugins[u];this._renderer=new a.renderer(n),this._store=new a.store(n)}else this._renderer=new r(n),this._store=new t(n);o(this)}var s=function(){function t(){this.cStore={}}return t.prototype={on:function(e,t,n){var r=this.cStore;r[e]||(r[e]=[]),r[e].push(function(e){return t.call(n,e)})},emit:function(e,t){var n=this.cStore;if(n[e]){var r=n[e].length;for(var i=0;i<r;i++){var s=n[e][i];s(t)}}}},t}(),o=function(e){var t=e._renderer,n=e._coordinator,r=e._store;n.on("renderpartial",t.renderPartial,t),n.on("renderall",t.renderAll,t),n.on("extremachange",function(t){e._config.onExtremaChange&&e._config.onExtremaChange({min:t.min,max:t.max,gradient:e._config.gradient||e._config.defaultGradient})}),r.setCoordinator(n)};return u.prototype={addData:function(){return this._store.addData.apply(this._store,arguments),this},removeData:function(){return this._store.removeData&&this._store.removeData.apply(this._store,arguments),this},setData:function(){return this._store.setData.apply(this._store,arguments),this},setDataMax:function(){return this._store.setDataMax.apply(this._store,arguments),this},setDataMin:function(){return this._store.setDataMin.apply(this._store,arguments),this},configure:function(e){return this._config=i.merge(this._config,e),this._renderer.updateConfig(this._config),this._coordinator.emit("renderall",this._store._getInternalData()),this},repaint:function(){return this._coordinator.emit("renderall",this._store._getInternalData()),this},getData:function(){return this._store.getData()},getDataURL:function(){return this._renderer.getDataURL()},getValueAt:function(e){return this._store.getValueAt?this._store.getValueAt(e):this._renderer.getValueAt?this._renderer.getValueAt(e):null}},u}(),o={create:function(e){return new s(e)},register:function(t,n){e.plugins[t]=n}};return o}),function(e,t,n){typeof module!="undefined"&&module.exports?module.exports=n(require("jquery"),require("heatmap"),require("gmaps")):typeof define=="function"&&define.amd?define("heatmap-gmaps",["jquery","heatmap","gmaps"],n):t[e]=n($,h337,google)}("HeatmapOverlay",this,function(e,t,n){if(window.HeatmapOverlay)return window.HeatmapOverlay;var r=e.Deferred(),i=function(e){var n=function(e,t){this.setMap(e),this.initialize(t||{})};return n.prototype=new e.maps.OverlayView,n.CSS_TRANSFORM=function(){var e=document.createElement("div"),t=["transform","WebkitTransform","MozTransform","OTransform","msTransform"];for(var n=0;n<t.length;n++){var r=t[n];if(e.style[r]!==undefined)return r}return t[0]}(),n.prototype.initialize=function(e){this.cfg=e;var t=this.map=this.getMap(),n=this.container=document.createElement("div"),r=t.getDiv(),i=this.width=r.clientWidth,s=this.height=r.clientHeight;n.style.cssText="width:"+i+"px;height:"+s+"px;",this.data=[],this.max=1,this.min=0,e.container=n},n.prototype.onAdd=function(){this.getPanes().overlayLayer.appendChild(this.container),this.changeHandler=e.maps.event.addListener(this.map,"bounds_changed",this.draw),this.heatmap||(this.heatmap=t.create(this.cfg)),this.draw()},n.prototype.onRemove=function(){if(!this.map)return;this.map=null,this.container.parentElement.removeChild(this.container),this.container=null,this.changeHandler&&(e.maps.event.removeListener(this.changeHandler),this.changeHandler=null)},n.prototype.draw=function(){if(!this.map)return;var t=this.map.getBounds(),r=new e.maps.LatLng(t.getNorthEast().lat(),t.getSouthWest().lng()),i=this.getProjection(),s=i.fromLatLngToDivPixel(r);this.container.style[n.CSS_TRANSFORM]="translate("+Math.round(s.x)+"px,"+Math.round(s.y)+"px)",this.update()},n.prototype.resize=function(){if(!this.map)return;var e=this.map.getDiv(),t=e.clientWidth,n=e.clientHeight;if(t==this.width&&n==this.height)return;this.width=t,this.height=n,this.heatmap._renderer.setDimensions(t,n),this.update()},n.prototype.update=function(){var t=this.map.getProjection(),n,r,i,s;if(!t)return;i=this.map.getBounds(),s=new e.maps.LatLng(i.getNorthEast().lat(),i.getSouthWest().lng()),n=this.map.getZoom(),r=Math.pow(2,n),this.resize();if(this.data.length==0)return;var o={max:this.max,min:this.min},u=[],a=this.data.length,f=this.getProjection(),l=f.fromLatLngToDivPixel(s),c=this.cfg.scaleRadius?r:1,h=0,p=0,d=this.cfg.valueField||"value";while(a--){var v=this.data[a],m=v[d],g=v.latlng;if(!i.contains(g))continue;h=Math.max(m,h),p=Math.min(m,p);var y=f.fromLatLngToDivPixel(g),b={x:Math.round(y.x-l.x),y:Math.round(y.y-l.y)};b[d]=m;var w;v.radius?w=v.radius*c:w=(this.cfg.radius||2)*c,b.radius=w,u.push(b)}this.cfg.useLocalExtrema&&(o.max=h,o.min=p),o.data=u,this.heatmap.setData(o)},n.prototype.setData=function(t){this.max=t.max,this.min=t.min;var n=this.cfg.latField||"lat",r=this.cfg.lngField||"lng",i=this.cfg.valueField||"value",t=t.data,s=t.length,o=[];while(s--){var u=t[s],a=new e.maps.LatLng(u[n],u[r]),f={latlng:a};f[i]=u[i],u.radius&&(f.radius=u.radius),o.push(f)}this.data=o,this.update()},n.prototype.addData=function(t){if(t.length>0){var n=t.length;while(n--)this.addData(t[n])}else{var r=this.cfg.latField||"lat",i=this.cfg.lngField||"lng",s=this.cfg.valueField||"value",o=t,u=new e.maps.LatLng(o[r],o[i]),a={latlng:u};a[s]=o[s],o.radius&&(a.radius=o.radius),this.max=Math.max(this.max,a[s]),this.min=Math.min(this.min,a[s]),this.data.push(a),this.update()}},n};return n.maps?i(n):(n.done(e.proxy(function(e){n=e;var t=i(n);t.isResolved=!0,r.resolve(t)},this)).fail(function(){r.reject()}),r.promise())}),define("unifi/view/map/CoverageView",["backbone","underscore","jquery","heatmap","heatmap-gmaps"],function(e,t,n,r,i){"use strict";return e.View.extend({el:".image-map-coverage-layer",initialize:function(e){t.bindAll(this);var r=this;this.indexView=e.indexView,this.markers=this.indexView.app.collection("Devices"),this.isVisible=!1,this.dataSetMax=10,this.dataSetMin=0,this.markerHeatmapCount=9,this.coverageFilter="2G",this.heatmapOptions={radius:200,maxOpacity:.7,useLocalExtrema:!0,latField:"lat",lngField:"lng",gradient:{0:"rgba(000,000,255,0)",.2:"rgba(000,000,255,1)",.4:"rgba(000,255,255,1)",.6:"rgba(000,255,000,1)",.8:"rgba(255,255,000,1)",1:"rgba(255,000,000,1)"}},this.$heatmapElt=this.$el,this.heatmapElt=this.$heatmapElt[0],n(window).on("resize",this.resize)},setCoverageFilter:function(e){this.coverageFilter=e,this.mapChangeHandler()},setMap:function(e){this.model&&(this.model.off("change:zoom",this.mapChangeHandler),this.model.off("change:offset_left",this.mapChangeHandler),this.model.off("change:offset_top",this.mapChangeHandler),this.model.off("change:lng",this.mapChangeHandler),this.model.off("change:lat",this.mapChangeHandler),this.model.off("change:upp",this.mapChangeHandler),this.model.off("change:unit",this.mapChangeHandler)),this.model=e,this.model.on("change:zoom",this.mapChangeHandler),this.model.on("change:offset_left",this.mapChangeHandler),this.model.on("change:offset_top",this.mapChangeHandler),this.model.on("change:lng",this.mapChangeHandler),this.model.on("change:lat",this.mapChangeHandler),this.model.on("change:upp",this.mapChangeHandler),this.model.on("change:unit",this.mapChangeHandler),this.mapChangeHandler()},mapChangeHandler:function(){this.isVisible&&this.updateCoverage()},show:function(){this.isVisible||(this.bindListeners(),this.isVisible=!0,this.updateCoverage())},hide:function(){this.isVisible&&(this.unbindListeners(),this.$el.empty(),this.isVisible=!1,this.googleHeatmap&&(this.googleHeatmap.onRemove(),this.googleHeatmap=null))},bindListeners:function(){this.markers.on("add",this.mapChangeHandler),this.markers.on("remove",this.mapChangeHandler),this.markers.on("change:map_id",this.mapChangeHandler),this.markers.on("change:x",this.mapChangeHandler),this.markers.on("change:y",this.mapChangeHandler),this.markers.on("change:ng-tx_power",this.mapChangeHandler),this.markers.on("change:ng-gain",this.mapChangeHandler),this.markers.on("change:ng-eirp",this.mapChangeHandler),this.markers.on("change:na-tx_power",this.mapChangeHandler),this.markers.on("change:na-gain",this.mapChangeHandler),this.markers.on("change:na-eirp",this.mapChangeHandler)},unbindListeners:function(){this.markers.off("add",this.mapChangeHandler),this.markers.off("remove",this.mapChangeHandler),this.markers.off("change:map_id",this.mapChangeHandler),this.markers.off("change:x",this.mapChangeHandler),this.markers.off("change:y",this.mapChangeHandler),this.markers.off("change:ng-tx_power",this.mapChangeHandler),this.markers.off("change:ng-gain",this.mapChangeHandler),this.markers.off("change:ng-eirp",this.mapChangeHandler),this.markers.off("change:na-tx_power",this.mapChangeHandler),this.markers.off("change:na-gain",this.mapChangeHandler),this.markers.off("change:na-eirp",this.mapChangeHandler)},resize:function(){var e=n(".image-map-container");if(e.length){var t=n(".ubnt-map-widget").outerWidth(),r=n(".ubnt-map-widget").outerHeight();this.$heatmapElt.css({width:t,height:r});var i=this.$heatmapElt.find("canvas");if(i.length){var s=i[0].getContext("2d");s.canvas.style.width=t+"px",s.canvas.style.height=r+"px",s.canvas.width=t,s.canvas.height=r}this.updateCoverage(!0)}},updateCoverage:t.debounce(function(t){if(e.history.fragment!=="map")return;if(this.model&&this.isVisible){if(!t){this.resize();return}this.model.get("type")==="googleMap"?this.updateGoogleMapCoverage():this.updateImageMapCoverage()}},100),updateGoogleMapCoverage:function(){var e=this;if(!e.HeatmapOverlay){if(e.HeatmapOverlayLoading)return;e.HeatmapOverlayLoading=!0,i.isResolved?(e.HeatmapOverlay=i,e._updateGoogleMapCoverage()):i.done(n.proxy(function(t){e.HeatmapOverlay=t,e._updateGoogleMapCoverage()},this))}else e._updateGoogleMapCoverage()},_updateGoogleMapCoverage:function(){var e=this,n=this.indexView.map.mapWidget.googleMap,r=n.googleMap;if(window.google.maps.hasOwnProperty("OverlayView")&&n.loaded&&google.maps){this.googleHeatmap&&(this.googleHeatmap.onRemove(),this.googleHeatmap=null),this.googleHeatmap=new this.HeatmapOverlay(r,this.heatmapOptions);var i=function(){if(!this.googleHeatmap.heatmap){t.delay(t.bind(i,this),50);return}this.googleData=[],t.each(n.markerViews,function(e){var t=this.calculateCoverage(e.model);t>=0&&this.googleData.push({lat:e.model.get("x"),lng:e.model.get("y"),value:this.markerHeatmapCount,radius:t})},this),this.googleData.length?this.googleHeatmap.setData({max:this.dataSetMax,min:this.dataSetMin,data:this.googleData}):this.googleHeatmap.heatmap.setData({data:[]})};t.delay(t.bind(i,this),50)}},updateImageMapCoverage:function(){var e=this,i=n(".image-map-container"),s=i.find(".marker"),o=n(".image-drag-layer").position(),u=[],a,f,l;this.$el.empty(),this.heatmap=r.create(t.extend(this.heatmapOptions,{container:this.heatmapElt})),window.heatmap=this.heatmap;var c=function(){s.each(function(t){a=n(this),f=a.position(),l=a.find(".mac").text();var r=e.calculateCoverage(e.markers.findWhere({mac:l}));r>=0&&u.push({x:f.left+o.left,y:f.top+o.top,value:e.markerHeatmapCount,radius:r})}),this.heatmap.setData({max:this.dataSetMax,min:this.dataSetMin,data:u})};t.delay(t.bind(c,this),50)},calculateCoverage:function(e){var t=100,n=1,r=this.coverageFilter=="2G"?e.transmitPower("ng"):e.transmitPower("na"),i=this.coverageFilter=="2G"?e.transmitFrequency("ng"):e.transmitFrequency("na"),s=this.model.get("unit")||"m",o=this.model.get("upp")||10,u=this.model.get("zoom")||1,a=this.indexView.getActiveMap().scale||1,f,l,c,h;o>0?(n=1,s==="m"?o/=1:o/=3.2808399,n=10/o*u*a):n=15*u*a;if(e.get("state")==1&&r>=0)return l=n,c=r,h=Math.pow(10,c/20)/(i/3e5),l*=Math.sqrt(h/200),l<1&&(l=1),l=Math.floor(l),t=l,t},remove:function(){n(window).off("resize",this.resize),this.model&&(this.model.off("change:zoom",this.mapChangeHandler),this.model.off("change:offset_left",this.mapChangeHandler),this.model.off("change:offset_top",this.mapChangeHandler),this.model.off("change:lng",this.mapChangeHandler),this.model.off("change:lat",this.mapChangeHandler),this.model.off("change:upp",this.mapChangeHandler),this.model.off("change:unit",this.mapChangeHandler)),this.unbindListeners(),this.googleHeatmap&&(this.googleHeatmap.onRemove(),this.googleHeatmap=null),e.View.prototype.remove.apply(this,arguments)}})}),define("unifi/model/Map",["unifi/model/Model","backbone"],function(e,t){"use strict";return e.extend({defaults:{upp:.5,unit:"m",offset_top:130,offset_left:200,zoom:10},sync:function(e,n,r){r=r||{};switch(e){case"update":r.contentType="application/json; charset=utf-8",this.get("type")==="googleMap"?(r.url="/api/s/"+SITE.name+"/rest/map/"+n.id,r.type="PUT",r.data=JSON.stringify(n.attributes)):(r.url="/api/s/"+SITE.name+"/rest/map/"+n.id,r.type="PUT",r.data=JSON.stringify(n.changed));break;case"delete":r.url="/api/s/"+SITE.name+"/rest/map/"+n.id}return t.sync.call(this,e,n,r)}})}),define("unifi/collection/Maps",["unifi/collection/Collection","unifi/model/Map","underscore"],function(e,t,n){"use strict";return e.extend({model:t,bySite:!0,url:function(e,t){return e?t?"/api/s/"+SITE.name+"/rest/map/":"/upload/map/s/"+SITE.name:"/api/s/"+SITE.name+"/list/map"},createGoogleMapModel:function(e,t){return t=t||{data:null},t.url=this.url(!0,!0),t.data=JSON.stringify(e),this.create(e,t)}})}),define("text!includes/map/addEditMapDialogTemplate.html",[],function(){return'<div class="dialog-content add-map-dialog-content">\n    <div class="content-area">\n        <form name="addEditMapForm" class="side-by-side ui-form clearfix">\n            <fieldset class="fieldset">\n                <div class="row">\n                    <input name="name" type="text" placeholder="Enter new map name" class="input map-name" tabindex="1" />\n                    <div class="buttonset map-type-select">\n                        <input type="radio" id="mapTypeImage" name="type" value="imageMap" class="image-map-radio" />\n                        <label for="mapTypeImage"> </label>\n                        <input type="radio" id="mapTypeGoogleMaps" name="type" value="googleMap" class="google-map-radio" />\n                        <label for="mapTypeGoogleMaps"></label>\n                    </div>\n                    <input name="Filedata" type="file" style="position: absolute; left: -9999px;" accept="image/x-png, image/png, image/jpg, image/jpe, image/jpeg, image/pjpeg, image/gif" />\n                </div>\n            </fieldset>\n        </form>\n        <div class="map-container">\n            <img class="image-map" />\n            <div class="google-map-container"></div>\n            <div class="select-a-different-map">\n                <span class="not-map-text"></span>\n                <a href="#"></a>\n            </div>\n            <div class="set-location">\n                <form name="setLocation" class="ui-form clearfix">\n                    <fieldset>\n                        <p>\n                            <input name="location" type="text" placeholder="Enter location" class="set-location-input input" tabindex="2" />\n                            <button name="searchButton" type="submit" value="Locate" class="button set-location-button" tabindex="3">\n                                <span class="ubnt-icon-location ui-button-icon"></span>\n                                <span class="copy"></span>\n                            </button>\n                        </p>\n                    </fieldset>\n                </form>\n            </div>\n        </div>\n    </div>\n</div>'}),function(e){e.extend(e.fn,{validate:function(t){if(!this.length){t&&t.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing.");return}var n=e.data(this[0],"validator");return n?n:(this.attr("novalidate","novalidate"),n=new e.validator(t,this[0]),e.data(this[0],"validator",n),n.settings.onsubmit&&(this.validateDelegate(":submit","click",function(t){n.settings.submitHandler&&(n.submitButton=t.target),e(t.target).hasClass("cancel")&&(n.cancelSubmit=!0),e(t.target).attr("formnovalidate")!==undefined&&(n.cancelSubmit=!0)}),this.submit(function(t){function r(){var r;return n.settings.submitHandler?(n.submitButton&&(r=e("<input type='hidden'/>").attr("name",n.submitButton.name).val(e(n.submitButton).val()).appendTo(n.currentForm)),n.settings.submitHandler.call(n,n.currentForm,t),n.submitButton&&r.remove(),!1):!0}return n.settings.debug&&t.preventDefault(),n.cancelSubmit?(n.cancelSubmit=!1,r()):n.form()?n.pendingRequest?(n.formSubmitted=!0,!1):r():(n.focusInvalid(),!1)})),n)},valid:function(){if(e(this[0]).is("form"))return this.validate().form();var t=!0,n=e(this[0].form).validate();return this.each(function(){t=t&&n.element(this)}),t},removeAttrs:function(t){var n={},r=this;return e.each(t.split(/\s/),function(e,t){n[t]=r.attr(t),r.removeAttr(t)}),n},rules:function(t,n){var r=this[0];if(t){var i=e.data(r.form,"validator").settings,s=i.rules,o=e.validator.staticRules(r);switch(t){case"add":e.extend(o,e.validator.normalizeRule(n)),delete o.messages,s[r.name]=o,n.messages&&(i.messages[r.name]=e.extend(i.messages[r.name],n.messages));break;case"remove":if(!n)return delete s[r.name],o;var u={};return e.each(n.split(/\s/),function(e,t){u[t]=o[t],delete o[t]}),u}}var a=e.validator.normalizeRules(e.extend({},e.validator.classRules(r),e.validator.attributeRules(r),e.validator.dataRules(r),e.validator.staticRules(r)),r);if(a.required){var f=a.required;delete a.required,a=e.extend({required:f},a)}return a}}),e.extend(e.expr[":"],{blank:function(t){return!e.trim(""+e(t).val())},filled:function(t){return!!e.trim(""+e(t).val())},unchecked:function(t){return!e(t).prop("checked")}}),e.validator=function(t,n){this.settings=e.extend(!0,{},e.validator.defaults,t),this.currentForm=n,this.init()},e.validator.format=function(t,n){return arguments.length===1?function(){var n=e.makeArray(arguments);return n.unshift(t),e.validator.format.apply(this,n)}:(arguments.length>2&&n.constructor!==Array&&(n=e.makeArray(arguments).slice(1)),n.constructor!==Array&&(n=[n]),e.each(n,function(e,n){t=t.replace(new RegExp("\\{"+e+"\\}","g"),function(){return n})}),t)},e.extend(e.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:!0,errorContainer:e([]),errorLabelContainer:e([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(e,t){this.lastActive=e,this.settings.focusCleanup&&!this.blockFocusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,e,this.settings.errorClass,this.settings.validClass),this.addWrapper(this.errorsFor(e)).hide())},onfocusout:function(e,t){!this.checkable(e)&&(e.name in this.submitted||!this.optional(e))&&this.element(e)},onkeyup:function(e,t){if(t.which===9&&this.elementValue(e)==="")return;(e.name in this.submitted||e===this.lastElement)&&this.element(e)},onclick:function(e,t){e.name in this.submitted?this.element(e):e.parentNode.name in this.submitted&&this.element(e.parentNode)},highlight:function(t,n,r){t.type==="radio"?this.findByName(t.name).addClass(n).removeClass(r):e(t).addClass(n).removeClass(r)},unhighlight:function(t,n,r){t.type==="radio"?this.findByName(t.name).removeClass(n).addClass(r):e(t).removeClass(n).addClass(r)}},setDefaults:function(t){e.extend(e.validator.defaults,t)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",maxlength:e.validator.format("Please enter no more than {0} characters."),minlength:e.validator.format("Please enter at least {0} characters."),rangelength:e.validator.format("Please enter a value between {0} and {1} characters long."),range:e.validator.format("Please enter a value between {0} and {1}."),max:e.validator.format("Please enter a value less than or equal to {0}."),min:e.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:!1,prototype:{init:function(){function r(t){var n=e.data(this[0].form,"validator"),r="on"+t.type.replace(/^validate/,"");n.settings[r]&&n.settings[r].call(n,this[0],t)}this.labelContainer=e(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||e(this.currentForm),this.containers=e(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var t=this.groups={};e.each(this.settings.groups,function(n,r){typeof r=="string"&&(r=r.split(/\s/)),e.each(r,function(e,r){t[r]=n})});var n=this.settings.rules;e.each(n,function(t,r){n[t]=e.validator.normalizeRule(r)}),e(this.currentForm).validateDelegate(":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'] ,[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'] ","focusin focusout keyup",r).validateDelegate("[type='radio'], [type='checkbox'], select, option","click",r),this.settings.invalidHandler&&e(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){return this.checkForm(),e.extend(this.submitted,this.errorMap),this.invalid=e.extend({},this.errorMap),this.valid()||e(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var e=0,t=this.currentElements=this.elements();t[e];e++)this.check(t[e]);return this.valid()},element:function(t){t=this.validationTargetFor(this.clean(t)),this.lastElement=t,this.prepareElement(t),this.currentElements=e(t);var n=this.check(t)!==!1;return n?delete this.invalid[t.name]:this.invalid[t.name]=!0,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),n},showErrors:function(t){if(t){e.extend(this.errorMap,t),this.errorList=[];for(var n in t)this.errorList.push({message:t[n],element:this.findByName(n)[0]});this.successList=e.grep(this.successList,function(e){return!(e.name in t)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){e.fn.resetForm&&e(this.currentForm).resetForm(),this.submitted={},this.lastElement=null,this.prepareForm(),this.hideErrors(),this.elements().removeClass(this.settings.errorClass).removeData("previousValue")},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(e){var t=0;for(var n in e)t++;return t},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return this.size()===0},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{e(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(t){}},findLastActive:function(){var t=this.lastActive;return t&&e.grep(this.errorList,function(e){return e.element.name===t.name}).length===1&&t},elements:function(){var t=this,n={};return e(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){return!this.name&&t.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.name in n||!t.objectLength(e(this).rules())?!1:(n[this.name]=!0,!0)})},clean:function(t){return e(t)[0]},errors:function(){var t=this.settings.errorClass.replace(" ",".");return e(this.settings.errorElement+"."+t,this.errorContext)},reset:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=e([]),this.toHide=e([]),this.currentElements=e([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(e){this.reset(),this.toHide=this.errorsFor(e)},elementValue:function(t){var n=e(t).attr("type"),r=e(t).val();return n==="radio"||n==="checkbox"?e("input[name='"+e(t).attr("name")+"']:checked").val():typeof r=="string"?r.replace(/\r/g,""):r},check:function(t){t=this.validationTargetFor(this.clean(t));var n=e(t).rules(),r=!1,i=this.elementValue(t),s;for(var o in n){var u={method:o,parameters:n[o]};try{s=e.validator.methods[o].call(this,i,t,u.parameters);if(s==="dependency-mismatch"){r=!0;continue}r=!1;if(s==="pending"){this.toHide=this.toHide.not(this.errorsFor(t));return}if(!s)return this.formatAndAdd(t,u),!1}catch(a){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+t.id+", check the '"+u.method+"' method.",a),a}}if(r)return;return this.objectLength(n)&&this.successList.push(t),!0},customDataMessage:function(t,n){return e(t).data("msg-"+n.toLowerCase())||t.attributes&&e(t).attr("data-msg-"+n.toLowerCase())},customMessage:function(e,t){var n=this.settings.messages[e];return n&&(n.constructor===String?n:n[t])},findDefined:function(){for(var e=0;e<arguments.length;e++)if(arguments[e]!==undefined)return arguments[e];return undefined},defaultMessage:function(t,n){return this.findDefined(this.customMessage(t.name,n),this.customDataMessage(t,n),!this.settings.ignoreTitle&&t.title||undefined,e.validator.messages[n],"<strong>Warning: No message defined for "+t.name+"</strong>")},formatAndAdd:function(t,n){var r=this.defaultMessage(t,n.method),i=/\$?\{(\d+)\}/g;typeof r=="function"?r=r.call(this,n.parameters,t):i.test(r)&&(r=e.validator.format(r.replace(i,"{$1}"),n.parameters)),this.errorList.push({message:r,element:t}),this.errorMap[t.name]=r,this.submitted[t.name]=r},addWrapper:function(e){return this.settings.wrapper&&(e=e.add(e.parent(this.settings.wrapper))),e},defaultShowErrors:function(){var e,t;for(e=0;this.errorList[e];e++){var n=this.errorList[e];this.settings.highlight&&this.settings.highlight.call(this,n.element,this.settings.errorClass,this.settings.validClass),this.showLabel(n.element,n.message)}this.errorList.length&&(this.toShow=this.toShow.add(this.containers));if(this.settings.success)for(e=0;this.successList[e];e++)this.showLabel(this.successList[e]);if(this.settings.unhighlight)for(e=0,t=this.validElements();t[e];e++)this.settings.unhighlight.call(this,t[e],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return e(this.errorList).map(function(){return this.element})},showLabel:function(t,n){var r=this.errorsFor(t);r.length?(r.removeClass(this.settings.validClass).addClass(this.settings.errorClass),r.html(n)):(r=e("<"+this.settings.errorElement+">").attr("for",this.idOrName(t)).addClass(this.settings.errorClass).html(n||""),this.settings.wrapper&&(r=r.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.append(r).length||(this.settings.errorPlacement?this.settings.errorPlacement(r,e(t)):r.insertAfter(t))),!n&&this.settings.success&&(r.text(""),typeof this.settings.success=="string"?r.addClass(this.settings.success):this.settings.success(r,t)),this.toShow=this.toShow.add(r)},errorsFor:function(t){var n=this.idOrName(t);return this.errors().filter(function(){return e(this).attr("for")===n})},idOrName:function(e){return this.groups[e.name]||(this.checkable(e)?e.name:e.id||e.name)},validationTargetFor:function(e){return this.checkable(e)&&(e=this.findByName(e.name).not(this.settings.ignore)[0]),e},checkable:function(e){return/radio|checkbox/i.test(e.type)},findByName:function(t){return e(this.currentForm).find("[name='"+t+"']")},getLength:function(t,n){switch(n.nodeName.toLowerCase()){case"select":return e("option:selected",n).length;case"input":if(this.checkable(n))return this.findByName(n.name).filter(":checked").length}return t.length},depend:function(e,t){return this.dependTypes[typeof e]?this.dependTypes[typeof e](e,t):!0},dependTypes:{"boolean":function(e,t){return e},string:function(t,n){return!!e(t,n.form).length},"function":function(e,t){return e(t)}},optional:function(t){var n=this.elementValue(t);return!e.validator.methods.required.call(this,n,t)&&"dependency-mismatch"},startRequest:function(e){this.pending[e.name]||(this.pendingRequest++,this.pending[e.name]=!0)},stopRequest:function(t,n){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[t.name],n&&this.pendingRequest===0&&this.formSubmitted&&this.form()?(e(this.currentForm).submit(),this.formSubmitted=!1):!n&&this.pendingRequest===0&&this.formSubmitted&&(e(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(t){return e.data(t,"previousValue")||e.data(t,"previousValue",{old:null,valid:!0,message:this.defaultMessage(t,"remote")})}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(t,n){t.constructor===String?this.classRuleSettings[t]=n:e.extend(this.classRuleSettings,t)},classRules:function(t){var n={},r=e(t).attr("class");return r&&e.each(r.split(" "),function(){this in e.validator.classRuleSettings&&e.extend(n,e.validator.classRuleSettings[this])}),n},attributeRules:function(t){var n={},r=e(t),i=r[0].getAttribute("type");for(var s in e.validator.methods){var o;s==="required"?(o=r.get(0).getAttribute(s),o===""&&(o=!0),o=!!o):o=r.attr(s),/min|max/.test(s)&&(i===null||/number|range|text/.test(i))&&(o=Number(o)),o?n[s]=o:i===s&&i!=="range"&&(n[s]=!0)}return n.maxlength&&/-1|2147483647|524288/.test(n.maxlength)&&delete n.maxlength,n},dataRules:function(t){var n,r,i={},s=e(t);for(n in e.validator.methods)r=s.data("rule-"+n.toLowerCase()),r!==undefined&&(i[n]=r);return i},staticRules:function(t){var n={},r=e.data(t.form,"validator");return r.settings.rules&&(n=e.validator.normalizeRule(r.settings.rules[t.name])||{}),n},normalizeRules:function(t,n){return e.each(t,function(r,i){if(i===!1){delete t[r];return}if(i.param||i.depends){var s=!0;switch(typeof i.depends){case"string":s=!!e(i.depends,n.form).length;break;case"function":s=i.depends.call(n,n)}s?t[r]=i.param!==undefined?i.param:!0:delete t[r]}}),e.each(t,function(r,i){t[r]=e.isFunction(i)?i(n):i}),e.each(["minlength","maxlength"],function(){t[this]&&(t[this]=Number(t[this]))}),e.each(["rangelength","range"],function(){var n;t[this]&&(e.isArray(t[this])?t[this]=[Number(t[this][0]),Number(t[this][1])]:typeof t[this]=="string"&&(n=t[this].split(/[\s,]+/),t[this]=[Number(n[0]),Number(n[1])]))}),e.validator.autoCreateRanges&&(t.min&&t.max&&(t.range=[t.min,t.max],delete t.min,delete t.max),t.minlength&&t.maxlength&&(t.rangelength=[t.minlength,t.maxlength],delete t.minlength,delete t.maxlength)),t},normalizeRule:function(t){if(typeof t=="string"){var n={};e.each(t.split(/\s/),function(){n[this]=!0}),t=n}return t},addMethod:function(t,n,r){e.validator.methods[t]=n,e.validator.messages[t]=r!==undefined?r:e.validator.messages[t],n.length<3&&e.validator.addClassRules(t,e.validator.normalizeRule(t))},methods:{required:function(t,n,r){if(!this.depend(r,n))return"dependency-mismatch";if(n.nodeName.toLowerCase()==="select"){var i=e(n).val();return i&&i.length>0}return this.checkable(n)?this.getLength(t,n)>0:e.trim(t).length>0},email:function(e,t){return this.optional(t)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(e)},url:function(e,t){return this.optional(t)||/^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(e)},date:function(e,t){return this.optional(t)||!/Invalid|NaN/.test((new Date(e)).toString())},dateISO:function(e,t){return this.optional(t)||/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(e)},number:function(e,t){return this.optional(t)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(e)},digits:function(e,t){return this.optional(t)||/^\d+$/.test(e)},creditcard:function(e,t){if(this.optional(t))return"dependency-mismatch";if(/[^0-9 \-]+/.test(e))return!1;var n=0,r=0,i=!1;e=e.replace(/\D/g,"");for(var s=e.length-1;s>=0;s--){var o=e.charAt(s);r=parseInt(o,10),i&&(r*=2)>9&&(r-=9),n+=r,i=!i}return n%10===0},minlength:function(t,n,r){var i=e.isArray(t)?t.length:this.getLength(e.trim(t),n);return this.optional(n)||i>=r},maxlength:function(t,n,r){var i=e.isArray(t)?t.length:this.getLength(e.trim(t),n);return this.optional(n)||i<=r},rangelength:function(t,n,r){var i=e.isArray(t)?t.length:this.getLength(e.trim(t),n);return this.optional(n)||i>=r[0]&&i<=r[1]},min:function(e,t,n){return this.optional(t)||e>=n},max:function(e,t,n){return this.optional(t)||e<=n},range:function(e,t,n){return this.optional(t)||e>=n[0]&&e<=n[1]},equalTo:function(t,n,r){var i=e(r);return this.settings.onfocusout&&i.unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){e(n).valid()}),t===i.val()},remote:function(t,n,r){if(this.optional(n))return"dependency-mismatch";var i=this.previousValue(n);this.settings.messages[n.name]||(this.settings.messages[n.name]={}),i.originalMessage=this.settings.messages[n.name].remote,this.settings.messages[n.name].remote=i.message,r=typeof r=="string"&&{url:r}||r;if(i.old===t)return i.valid;i.old=t;var s=this;this.startRequest(n);var o={};return o[n.name]=t,e.ajax(e.extend(!0,{url:r,mode:"abort",port:"validate"+n.name,dataType:"json",data:o,success:function(r){s.settings.messages[n.name].remote=i.originalMessage;var o=r===!0||r==="true";if(o){var u=s.formSubmitted;s.prepareElement(n),s.formSubmitted=u,s.successList.push(n),delete s.invalid[n.name],s.showErrors()}else{var a={},f=r||s.defaultMessage(n,"remote");a[n.name]=i.message=e.isFunction(f)?f(t):f,s.invalid[n.name]=!0,s.showErrors(a)}i.valid=o,s.stopRequest(n,o)}},r)),"pending"}}}),e.format=e.validator.format}(jQuery),function(e){var t={};if(e.ajaxPrefilter)e.ajaxPrefilter(function(e,n,r){var i=e.port;e.mode==="abort"&&(t[i]&&t[i].abort(),t[i]=r)});else{var n=e.ajax;e.ajax=function(r){var i=("mode"in r?r:e.ajaxSettings).mode,s=("port"in r?r:e.ajaxSettings).port;return i==="abort"?(t[s]&&t[s].abort(),t[s]=n.apply(this,arguments),t[s]):n.apply(this,arguments)}}}(jQuery),function(e){e.extend(e.fn,{validateDelegate:function(t,n,r){return this.bind(n,function(n){var i=e(n.target);if(i.is(t))return r.apply(i,arguments)})}})}(jQuery),define("libs/jquery.validate",function(){}),define("ubnt/view/map/AddEditMapDialogView",["underscore","ubnt/view/dialogs/DialogView","ubnt/view/dialogs/ErrorDialogView","msg/Msg","jquery","xregexp","ubnt/view/map/GoogleMapView","ubnt/view/map/GoogleMapOverlayWrapperView","ubnt/view/map/GoogleMapMarkerWrapperView","text!includes/map/addEditMapDialogTemplate.html","libs/jquery.validate"],function(e,t,n,r,i,s,o,u,a,f){"use strict";return t.extend({_fullyQualifiedName:"UBNT.views.map.AddEditMapDialog",initialize:function(n){e.bindAll(this);var i=this;this.template=e.template(f),this.mapIndexView=n.mapIndexView;var s={title:r.G_MapAddMapHeader,autoOpen:!0,width:640,resizable:!1,draggable:!1,modal:!0,dialogClass:"ubnt-map-add-map-dialog",CancelButton:{buttonClass:"ui-button-cancel button tall auto",handler:function(){i.mapIndexView.addMapPending=!1,i.destroy(),i.mapIndexView.configureMapsHandler()}},DoneButton:{buttonClass:"ui-button-positive button tall auto green",handler:this.addMapHandler},buttons:{},close:this.destroy};s.buttons[r.G_Cancel]=s.CancelButton,s.buttons[r.G_Done]=s.DoneButton,n.dialogOptions=e.extend(s,n.dialogOptions||{}),t.prototype.initialize.apply(this,[n])},initElements:function(){this.$mapTypeSelect=this.$('input[name="type"]'),this.$mapImageBrowser=this.$('input[name="Filedata"]'),this.$googleMapContainer=this.$(".google-map-container"),this.$form=this.$('form[name="addEditMapForm"]'),this.$setLocationForm=this.$('form[name="setLocation"]'),this.$mapLabel=this.$('input[name="name"]'),this.$imageMapContainer=this.$(".map-container"),this.$mapImage=this.$("img.image-map"),this.$selectMapLink=this.$(".select-a-different-map"),this.$setLocation=this.$(".set-location"),this.$setLocation.find('input[type="button"]'),this.$searchButton=this.$el.find('input[name="searchButton"]'),this.$addMapButtonText=this.$el.parent().find(".ui-dialog-buttonpane button:first-child span"),this.$uploadImageLabel=this.$('label[for="mapTypeImage"]'),this.$mapTypeLabel=this.$('label[for="mapTypeGoogleMaps"]'),this.$notMap=this.$(".select-a-different-map").find(".not-map-text"),this.$selectDiffMap=this.$(".select-a-different-map").find("a"),this.$buttonLocate=this.$('button[name="searchButton"]'),this.$el.find(".buttonset").buttonset()},initHandlers:function(){this.$selectMapLink.find("a").on("click",this.showMapImageBrowser),this.$mapImageBrowser.on("change",this.setImageMap),this.$mapTypeSelect.on("change",this.mapTypeChangeHandler),this.$mapImage.on("load",this.imageMapLoadHandler)},initValidation:function(){i.validator.addMethod("regex",function(e,t,n){return this.optional(t)||n.test(e)},""),i.validator.addMethod("custom_xregex",function(e,t){var n=new s("^[\\p{L}\\p{Z}\\p{P}\\p{S}\\p{N}]{0,}$");return this.optional(t)||n.test(e)},""),this.$form.validate({rules:{name:{required:!0,custom_xregex:!0}},submitHandler:this.saveMap}),this.$setLocationForm.validate({rules:{location:{required:!0}},submitHandler:this.setLocation})},setLocation:function(){var e=this;return this.geocoder.geocode({address:i('input[name="location"]').val()},function(t,i){if(i===google.maps.GeocoderStatus.OK)e.googleMap.setOptions({center:t[0].geometry.location});else{e.errorDialog||(e.errorDialog=new n);switch(i){case"ZERO_RESULTS":e.errorDialog.open(r.E_GoogleNotFound);break;default:e.errorDialog.open(i)}}}),!1},setImageMap:function(){var e=this.$mapImageBrowser.get(0).files[0],t=new FileReader,n=this;t.onload=function(e){n.$mapImage.attr("src",e.target.result)},t.readAsDataURL(e)},showMapImageBrowser:function(){return this.$mapImageBrowser.val(""),this.$mapImage.removeAttr("src"),this.$mapImage.hide(),this.$mapImageBrowser.click(),this.$setLocation.hide(),!1},showImageMap:function(){this.$mapImage.show(),this.$selectMapLink.show(),this.$setLocation.hide(),this.$googleMapContainer.hide()},showGoogleMap:function(){var e=this,t=i("body");this.$mapImage.hide(),this.$selectMapLink.hide(),this.$setLocation.show(),this.$googleMapContainer.show();if(t.hasClass("googlemaps-notLoaded"))window.googleMapsNotLoaded();else{o.loaded||i("body").bind("googleMapsLoaded.AddMapDialog",this.googleMapLoadedHandler),!o.loading&&!o.loaded&&(window.UBNTMapGoogleMapCallback=function(){o.loaded=!0,a.initialize(),u.initialize(),i("body").trigger("googleMapsLoaded")},o.loading=!0,window.google&&window.google.maps&&window.UBNTMapGoogleMapCallback());if(o.loaded){var n=new google.maps.LatLng(37.411146,-121.943083),r={};this.model&&this.model.get("type")==="googleMap"?r={zoom:this.model.get("zoom"),center:new google.maps.LatLng(this.model.get("lat"),this.model.get("lng")),mapTypeId:this.model.get("mapTypeId"),tilt:this.model.get("tilt")}:r={zoom:14,center:n,mapTypeId:google.maps.MapTypeId.SATELLITE,tilt:0},this.googleMap===null||this.googleMap===undefined?(this.googleMap=new google.maps.Map(this.$googleMapContainer.get(0),r),this.geocoder=new google.maps.Geocoder):this.googleMap.setOptions(r)}}},setModel:function(e){this.model=e,this.render()},removeMarkers:function(){var t=this,n=e.filter(this.mapIndexView.markers.models,function(e){return t.model&&e.get("map_id")==t.model.id});e.each(n,function(e){e.save({map_id:"",x:"",y:""})})},saveMap:function(){var e=this,t={name:this.$mapLabel.val(),type:this.$('input[type="radio"]:checked').val()},i=!1;switch(t.type){case"imageMap":var s=this.$mapImageBrowser.get(0).files[0];if(s){this.mapIndexView.addMapPending=!0,this.removeMarkers();var o=new XMLHttpRequest,u=new FormData(this.$form.get(0));o.upload.addEventListener("progress",this.handleUploadProgress,!1),o.addEventListener("load",this.handleUploadComplete,!1),o.addEventListener("error",this.handleUploadFailed,!1),o.addEventListener("abort",this.handleUploadCanceled,!1),o.open("POST","/upload/s/"+SITE.name+"/map"+(this.model===null?"":"/"+this.model.get("_id"))),o.setRequestHeader("X-Requested-With","XMLHttpRequest"),o.send(u)}else this.model&&this.$mapImage.attr("src")?this.model.save(t,{success:this.destroy}):(this.errorDialog||(this.errorDialog=new n),this.errorDialog.open(r.E_NoImageSpecified));break;case"googleMap":t.lat=this.googleMap.getCenter().lat(),t.lng=this.googleMap.getCenter().lng(),t.zoom=this.googleMap.getZoom(),t.tilt=this.googleMap.getTilt(),t.mapTypeId=this.googleMap.getMapTypeId(),this.model?(this.removeMarkers(),this.model.save(t,{wait:!0,success:e.destroy})):(this.mapIndexView.addMapPending=!0,this.collection.createGoogleMapModel(t,{wait:!0,success:e.destroy}))}},render:function(){t.prototype.render.apply(this,[]),this.isRenderedd||(this.isRenderedd=!0,this.initElements(),this.initHandlers(),this.initValidation(),this.$searchButton.button(),i(".ui-button-cancel").attr("tabindex",4).button({icons:{primary:"ubnt-icon-close"}}),i(".ui-button-positive").attr("tabindex",5).button({icons:{primary:"ubnt-icon-check"}}),this.$uploadImageLabel.find(".ui-button-text").text(r.G_MapUploadImage),this.$mapTypeLabel.find(".ui-button-text").text(r.G_MapGoogleMaps),this.$notMap.text(r.G_MapNotWhatYouLookingFor),this.$selectDiffMap.text(r.G_MapSelectDiffMap),this.$buttonLocate.find("span.copy").text(r.G_Locate)),this.$mapLabel.val(""),this.$mapImage.hide();if(this.model){this.$el.dialog("option",{title:r.G_MapEditMapHeader}),this.$mapLabel.val(this.model.get("name"));var e=this.model.get("type")||"imageMap";e==="imageMap"?(this.$("input.image-map-radio").click(),this.$mapImage.attr("src",this.model.get("url"))):(this.$("input.google-map-radio").click(),this.showGoogleMap()),this.$mapTypeSelect.find(i('input[value="'+e+'"]'))}else this.$el.dialog("option",{title:r.G_MapAddMapHeader}),this.$addMapButtonText.text("Add Map"),this.$googleMapContainer.hide(),this.setDefaultMapType||(this.$("input.image-map-radio").click(),this.showMapImageBrowser(),this.setDefaultMapType=!0);this.$('input[name="key"]').val(i.cookie("unifises"))},imageMapLoadHandler:function(e){this.$mapImage.css("width","auto"),this.$mapImage.css("height","auto");var t=e.target.width,n=e.target.height,r=this.$imageMapContainer.width(),i=this.$imageMapContainer.height();t/n>r/i?(this.$mapImage.height(r/t*n),this.$mapImage.width(r),this.$mapImage.css("margin-top",(i-this.$mapImage.height())/2+"px"),this.$mapImage.css("margin-left","0px")):(this.$mapImage.width(i/n*t),this.$mapImage.height(i),this.$mapImage.css("margin-left",(r-this.$mapImage.width())/2+"px"),this.$mapImage.css("margin-top","0px")),this.$googleMapContainer.hide(),this.$setLocation.hide(),this.$selectMapLink.show(),this.$mapImage.show()},mapTypeChangeHandler:function(e){var t=i(e.target).val();switch(t){case"imageMap":this.showImageMap();break;case"googleMap":this.showGoogleMap()}},googleMapLoadedHandler:function(){i("body").unbind("googleMapsLoaded.AddMapDialog"),this.showGoogleMap()},addMapHandler:function(){this.$form.submit()},handleUploadProgress:function(e){},handleUploadComplete:function(e){var n=i.parseJSON(e.currentTarget.response).data[0],r=this.collection.get(n._id);r?r.set(n,{silent:!1}):this.collection.add(n),t.prototype.destroy.apply(this,arguments),this.$mapImageBrowser.val("")},handleUploadFailed:function(e){},handleUploadCanceled:function(e){},dialogOpenHandler:function(e,t){this.model&&this.model.get("type")==="googleMap"?(this.$("input.image-map-radio").removeAttr("checked"),this.$("input.image-map-radio").next("label").removeClass("ui-state-active"),this.$("input.google-map-radio").attr("checked","checked"),this.$("input.google-map-radio").next("label").addClass("ui-state-active")):(this.$("input.image-map-radio").attr("checked","checked"),this.$("input.image-map-radio").next("label").addClass("ui-state-active"),this.$("input.google-map-radio").removeAttr("checked"),this.$("input.google-map-radio").next("label").removeClass("ui-state-active"))},dialogCloseHandler:function(e,n){t.prototype.dialogCloseHandler.apply(this,arguments),this.setDefaultMapType=null},hide:function(){t.prototype.hide.apply(this,arguments)},destroy:function(){t.prototype.destroy.apply(this,arguments)},remove:function(){this.$selectMapLink.find("a").off("click",this.showMapImageBrowser),this.$mapImageBrowser.off("change",this.setImageMap),this.$mapTypeSelect.off("change",this.mapTypeChangeHandler),this.$mapImage.off("load",this.imageMapLoadHandler),i("body").unbind("googleMapsLoaded.AddMapDialog",this.googleMapLoadedHandler),this.isRenderedd=!1,t.prototype.remove.apply(this,arguments)}})}),define("text!includes/map/confirmRemoveDialogTemplate.html",[],function(){return'<div class="dialog-content configure-maps-dialog">\n    <div class="content-area">\n        <img class="image" src="/lib/4.6.6/images/1x1.gif" alt="" />\n        <div class="confirmation">\n            \n            <div class="map-name"></div>\n        </div>\n    </div>\n</div>'}),define("ubnt/view/map/ConfirmRemoveMapDialogView",["underscore","ubnt/view/dialogs/DialogView","msg/Msg","jquery","text!includes/map/confirmRemoveDialogTemplate.html"],function(e,t,n,r,i){"use strict";return t.extend({_fullyQualifiedName:"UBNT.views.dialogs.ConfirmRemoveDialog",initialize:function(){e.bindAll(this),this.template=e.template(i);var r={title:n.G_PleaseConfirm,autoOpen:!0,width:430,height:265,resizable:!1,draggable:!1,modal:!0,dialogClass:"confirm-dialog confirm-remove-dialog",CancelButton:{buttonClass:"button tall auto ui-button-cancel",handler:this.cancelHandler},ConfirmButton:{buttonClass:"button tall auto red",handler:this.confirmHandler},buttons:{}};r.buttons[n.G_Cancel]=r.CancelButton,r.buttons[n.G_Confirm]=r.ConfirmButton,this.options.dialogOptions=e.extend(r,this.options.dialogOptions||{}),t.prototype.initialize.apply(this,[this.options])},render:function(){t.prototype.render.apply(this,[]),r(".ui-button-cancel").button({icons:{primary:"ubnt-icon-close"}}),this.$image=this.$el.find(".image"),this.$mapName=this.$el.find(".map-name"),this.image?this.$el.removeClass("no-image"):(this.image="/lib/4.6.6/images/1x1.gif",this.$el.addClass("no-image")),this.$confirmation=this.$el.find(".confirmation"),this.$confirmation.find("div").before(n.G_RemoveMap),this.$image.attr("src",this.image),this.$mapName.text(this.mapName)},show:function(e){this.map=e,this.map.get("type")==="imageMap"&&(this.image=this.map.get("url")),this.mapName=this.map.get("name"),this.open()},confirmHandler:function(){this.options.confirmHandler.call(this.context,this.map),this.destroy()},cancelHandler:function(){this.options.cancelHandler.call(this.context,this.map),this.destroy()}})}),define("text!includes/map/configureMapsDialogTemplate.html",[],function(){return'<div class="dialog-content configure-maps-dialog">\n    <% if(items.length > 0) { %>\n        <table class="table maps">\n            <thead class="thead">\n                <tr class="table-row">\n                    <td class="table-cell table-cell-map-name"></td>\n                    <td class="table-cell table-cell-actions"></td>\n                </tr>\n            </thead>\n            <tbody class="tbody">\n                <% for(var key in items) { %>\n                <tr class="table-row map-<%- items[key]._id %>" data-id="<%- items[key]._id %>">\n                    <td class="table-cell table-cell-map-name"><%- items[key].name %></td>\n                    <td class="table-cell table-cell-actions">\n                        <button class="button edit skinny"><span class="ui-icon ubnt-icon-edit"></span></button>\n                        <button class="button remove skinny" \n                            <% if (items[key].attr_no_delete) { %>disabled="disabled"<% } %>><span class="ui-icon ubnt-icon-trash"></span></button>\n                    </td>\n                </tr>\n                <% } %>\n            </tbody>\n        </table>\n    <% } else { %>\n        <div class="no-maps"></div>\n    <% } %>\n</div>'}),define("ubnt/view/map/ConfigureMapsDialogView",["underscore","ubnt/view/dialogs/DialogView","msg/Msg","jquery","text!includes/map/configureMapsDialogTemplate.html"],function(e,t,n,r,i){"use strict";return t.extend({_fullyQualifiedName:"UBNT.views.map.ConfigureMapsDialog",initialize:function(r){e.bindAll(this),this.mapIndexView=r.mapIndexView,this.template=e.template(i);var s={title:n.G_ConfigureMaps,autoOpen:!0,width:430,resizable:!1,draggable:!1,modal:!0,dialogClass:"ubnt-map-configure-maps-dialog",AddMapButton:{buttonClass:"ui-button-positive button tall green add-a-map",handler:this.addMapHandler},DoneButton:{buttonClass:"ui-button-cancel button tall right",handler:this.destroy},buttons:{},close:this.destroy};s.buttons[n.G_MapAddMap]=s.AddMapButton,s.buttons[n.G_Done]=s.DoneButton,r.dialogOptions=e.extend(s,r.dialogOptions||{}),t.prototype.initialize.apply(this,[r]),this.collection.on("change",this.updateMapNames)},render:function(){var e={items:this.collection.toJSON(),length:this.collection.length};t.prototype.render.apply(this,[{template_json:e}]),this.$tableCellMapName=r("thead .table-cell-map-name"),this.$tableCellActions=r("thead .table-cell-actions"),this.$noMaps=r(".no-maps"),this.$edit=r(".edit span"),this.$remove=r(".remove span"),this.$tableCellMapName.text(n.G_Name),this.$tableCellActions.text(n.G_Actions),this.$noMaps.text(n.G_MapNoMaps),this.$edit.after(n.G_Edit),this.$remove.after(n.G_Delete),this.isRenderedd||(r(".ui-button-cancel").button({icons:{primary:"ubnt-icon-close"}}),r(".ui-button-positive").button({icons:{primary:"ubnt-icon-check"}}),this.$el.one("click",".edit",this.editMapHandler),this.$el.one("click",".remove",this.removeMapHandler)),this.isRendered=!1},updateMapNames:function(){var t=this;e.each(this.collection.models,function(e){t.$(".map-"+e.get("_id")).find(".table-cell-map-name").text(e.get("name"))})},setModel:function(e){this.model=e},editMapHandler:function(e){this.destroy(),this.mapIndexView.editMapClickHandler(e)},removeMapHandler:function(e){this.destroy();var t=r(e.target).parents(".table-row").data("id"),n=this.collection.findWhere({_id:t});this.mapIndexView.removeMapClickHandler(n)},addMapHandler:function(){this.destroy(),this.mapIndexView.addMapClickHandler()},remove:function(){this.collection.off("change",this.updateMapNames),this.isRendered=!1,t.prototype.remove.apply(this,arguments)}})}),define("unifi/view/map/IndexView",["backbone","underscore","jquery","msg/Msg","unifi/view/app/ContentView","text!includes/map/mapIndexTemplate.html","text!includes/map/mapMarkerTemplate.html","text!includes/map/mapUnplacedMarkerTemplate.html","text!includes/map/mapUnplacedMarkerDraggableTemplate.html","ubnt/view/map/RulerView","unifi/view/map/MarkerView","ubnt/view/map/MarkerDrawerView","unifi/view/map/UnplacedMarkerView","ubnt/view/map/MapView","unifi/view/map/TopologyView","unifi/view/map/CoverageView","unifi/collection/Maps","ubnt/view/uicomponents/SelectMenuView","ubnt/view/map/AddEditMapDialogView","ubnt/view/map/ConfirmRemoveMapDialogView","ubnt/view/map/ConfigureMapsDialogView","ubnt/view/dialogs/ErrorDialogView"],function(e,t,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y,b,w,E){"use strict";return i.extend({template:t.template(s),id:"mapIndex",initialize:function(e){i.prototype.initialize.call(this,e),this._dependencies=n.Deferred(),this.drawerHidden=!0,n.when(this._dependencies).then(this.render,this.failed),this.dependencies()},render:function(){if(this._dependencies.state()==="pending")return;var e=this;i.prototype.render.call(this);if(!this.rendered&&(this.rendered=!0)){this.maps=this.app.collection("Maps"),this.markers=this.options.app.collection("Devices"),this.$el.html(this.template({msg:r})),this.$el.find("select").each(function(){var e=n(this),t=e.parent();e.attr("name")!="mapSelect"&&e.selectmenu({parent:t,appendTo:t,icons:{button:"ubnt-icon-arrow-down secondary-color"},position:{at:"left bottom"}})}),this.$mapSelect=this.$el.find('select[name="mapSelect"]'),this.$drawerHandle=this.$el.find(".marker-drawer").find(".handle"),this.mapSelector=new g({el:this.$mapSelect,collection:this.maps,width:200,create:function(t,i){i.menuWrap.append(n('<div class="ui-menu-item configure-maps is-admin"><span class="ubnt-icon-gear gear"></span>'+r.G_ConfigureMaps+"</div>").on("click",function(t){e.configureMapsHandler()}).on("mouseover",function(e){i.menu.find(".ui-state-focus").removeClass("ui-state-focus")}))}}),this.$slider=this.$el.find(".zoom-slider").slider({min:1,max:20,value:10,step:1,slide:this.slideHandler,orientation:"vertical",range:"min"}),this.$zoomOut=this.$el.find(".zoom-controls").find(".minus").click(this.zoomOut),this.$zoomIn=this.$el.find(".zoom-controls").find(".plus").click(this.zoomIn),this.markerDrawer=new c({el:this.$("div.marker-drawer"),markers:this.markers,maps:this.maps,markerView:h,unplacedMarkerTemplate:t.template(u),unplacedMarkerDraggableTemplate:t.template(a)}),this.$markerDrawer=this.markerDrawer.render();if(this.maps.models[0]){var s=n.cookie?n.cookie("default-map"):null,m=this.maps.get(s)||this.maps.models[0];m&&(this.mapSelector.set(m.id),this.mapSelector.$el.trigger("change"),this.mapSelector.$el.selectmenu("close"))}this.$drawerHandle.on("click",this.toggleDrawer),this.$mapSelect.on("change",this.mapSelectHandler),this.map=new p({app:this.options.app,el:"#Map",maps:this.maps,markers:this.markers,markerView:l.extend({app:this.options.app}),markerTemplate:t.template(o)}),this.coverageView=new v({indexView:this}),this.topologyView=new d({indexView:this}),this.$(".buttonset").buttonset(),this.$(".buttonset.mainToggles input").on("click",this.mapViewClick),this.mapViewClick(),this.$(".buttonset.coverage input").on("click",this.mapCoverageViewClick),this.$(".buttonset.coverage").hide(),this.$ruler=new f({el:".ruler"}),this.$ruler.$el.on("scaled",this.setUpp),this.$scale=this.$(".scale"),this.$scaleMeasurement=this.$scale.find(".scale-measurement"),this.$scaleIcon=this.$scale.find(".scale-icon"),this.setMap(this.maps.findWhere({_id:this.$mapSelect.val()})),this.markers.bind("add",this.addDevice),this.markers.bind("change",this.updateDevice),this.markers.bind("remove",this.removeDevice),this.markers.bind("reset",this.resetDevices),this.maps.bind("add",this.addMap),this.maps.bind("change",this.updateMap),this.maps.bind("remove",this.removeMap),this.maps.bind("reset",this.resetMaps)}this.map.render(),this.coverageView.updateCoverage()},addDevice:function(e,t){this.markerDrawer.hasUnplacedMarkers()&&this.showDrawer()},updateDevice:function(e,t){var n=e.changedAttributes();if(n.map_id!==undefined||n.provisioned!==undefined)this.markerDrawer.hasUnplacedMarkers()?this.showDrawer():this.hideDrawer()},removeDevice:function(e,t){this.markerDrawer.hasUnplacedMarkers()?this.showDrawer():this.hideDrawer()},resetDevices:function(){},configureMapsHandler:function(){var e=new w({mapIndexView:this,collection:this.maps});e.render()},toggleDrawer:function(){this.drawerHidden?this.showDrawer():this.hideDrawer()},showDrawer:function(e){this.markerDrawer.$el.addClass("is-open"),this.drawerHidden=!1},hideDrawer:function(e){this.markerDrawer.$el.removeClass("is-open"),this.drawerHidden=!0},mapSelectHandler:function(){var e=this.$mapSelect.val();n.cookie&&n.cookie("default-map",e);var t=this.maps.findWhere({_id:e});this.setMap(t)},setMap:function(e){this.model&&this.model.off("change:zoom",this.mapZoomHandler),this.model=e,this.model.on("change:zoom",this.mapZoomHandler),this.map.setMap(e),this.coverageView.setMap(e),this.topologyView.setMap(e),this.setZoom(this.model.get("zoom"),!0)},getActiveMap:function(){var e=this.model;return e?e.get("type")==="googleMap"?this.map.mapWidget.googleMap:this.map.mapWidget.imageMap:null},setScaleBar:function(){var e=this.getActiveMap(),t=1,n,r;e&&(r=this.model.get("upp")||.5,n=1*e.scale*e.zoomLevel*r,n>1e4||Math.abs(n-1e4)<Math.abs(n-5e3)?t=1e4:n>5e3||Math.abs(n-5e3)<Math.abs(n-1e3)?t=5e3:n>1e3||Math.abs(n-1e3)<Math.abs(n-500)?t=1e3:n>500||Math.abs(n-500)<Math.abs(n-100)?t=500:n>100||Math.abs(n-100)<Math.abs(n-50)?t=100:Math.abs(n-50)<Math.abs(n-20)?t=50:Math.abs(n-20)<Math.abs(n-10)?t=20:Math.abs(n-10)<Math.abs(n-5)?t=10:Math.abs(n-5)<Math.abs(n-1)?t=5:t=1,this.$scaleMeasurement.text(t+" "+(this.model.get("unit")||"m")),this.$scaleIcon.width(t*e.scale*this.model.get("zoom")/r),this.$scale.show())},setUpp:function(e,t,n){var r=this.getActiveMap(),i;return r&&(i=t*r.scale*this.model.get("zoom"),this.app.isReadOnly?r.model.set({upp:i,unit:n}):r.model.save({upp:i,unit:n}),this.setScaleBar()),!1},mapViewClick:function(){var e=this.$('input[name="filter"]:checked'),r=[];e.each(function(){r.push(n(this).val())}),this.mapView||(this.mapView=[]),this.map.$el.removeClass(this.mapView.join(" ")).addClass(r.join(" ")),this.mapView=r,t.contains(this.mapView,"details")?(n("#mapFilterDetails").next("label:first").addClass("ui-state-active"),this.map.$el.removeClass("labels")):this.map.$el.addClass("labels"),t.contains(this.mapView,"coverage")?(n("#mapFilterCoverage").next("label:first").addClass("ui-state-active"),this.coverageView.show(),this.$(".buttonset.coverage").show()):(this.coverageView.hide(),this.$(".buttonset.coverage").hide()),t.contains(this.mapView,"topology")?(n("#mapFilterTopology").next("label:first").addClass("ui-state-active"),this.topologyView.show()):this.topologyView.hide()},mapCoverageViewClick:function(){var e=this.$('input[name="coverageFilter"]:checked'),r=[];e.each(function(){r.push(n(this).val())}),this.mapViewCoverageType||(this.mapViewCoverageType=[]),this.map.$el.removeClass(this.mapViewCoverageType.join(" ")).addClass(r.join(" ")),this.mapViewCoverageType=r,t.contains(this.mapViewCoverageType,"2G")&&(n("#mapFilterCoverage2G").next("label:first").addClass("ui-state-active"),n("#mapFilterCoverage5G").prop("checked",!1).next("label:first").removeClass("ui-state-active"),this.coverageView.setCoverageFilter("2G")),t.contains(this.mapViewCoverageType,"5G")&&(n("#mapFilterCoverage5G").next("label:first").addClass("ui-state-active"),n("#mapFilterCoverage2G").prop("checked",!1).next("label:first").removeClass("ui-state-active"),this.coverageView.setCoverageFilter("5G"))},slideHandler:function(e,t){var n=t.value;this.setZoom(n,!1,!0)},zoomOut:function(){var e=this.$slider.slider("value"),t=this.$slider.slider("option","min"),n=e-1;return n>=t&&this.setZoom(n),!1},zoomIn:function(){var e=this.$slider.slider("value"),t=this.$slider.slider("option","max"),n=e+1;return n<=t&&this.setZoom(n),!1},mapZoomHandler:function(e){this.setZoom(e.get("zoom"),!0)},setZoom:function(e,t,n){n||this.$slider.slider("option","value",e),this.model.set({zoom:e}),this.setScaleBar(),!t&&!this.app.isReadOnly&&this.saveZoom(e)},saveZoom:t.debounce(function(e){this.model.unset("zoom",{silent:!0}),this.model.save({zoom:e},{silent:!0})},250),addMapClickHandler:function(){this.addEditMapDialog=new y({collection:this.maps,mapIndexView:this}),this.$addEditMapDialog=this.addEditMapDialog.render(),this.addEditMapDialog.setModel(null),this.addEditMapDialog.show()},editMapClickHandler:function(e){var t=this.maps.get(n(e.target).parents(".table-row:first").data("id"));t&&(this.addEditMapDialog=new y({collection:this.maps,model:t,mapIndexView:this}),this.$addEditMapDialog=this.addEditMapDialog.render(),this.addEditMapDialog.setModel(t),this.addEditMapDialog.show())},removeMapClickHandler:function(e){var t=this,n=new b({cancelHandler:this.cancelRemoveMapHandler,confirmHandler:this.confirmRemoveMapHandler});n.show(e)},cancelRemoveMapHandler:function(){this.configureMapsHandler(),this.removeMapPending=!1},confirmRemoveMapHandler:function(e){var t=this;e&&(this.maps.remove(e),e.destroy({success:function(){var e=t.maps.at(0);e&&(t.setMap(e),t.mapSelector.set(e.id))}})),this.configureMapsHandler()},addMap:function(e,t){this.addMapPending&&(this.addMapPending=!1,n(".ui-dialog").is(":visible")||this.configureMapsHandler(),this.setMap(e),this.mapSelector.set(e.id))},updateMap:function(e,t){},removeMap:function(e,t){if(this.model.id===e.id){var n=this.maps.at(0);n&&(this.setMap(n),this.mapSelector.set(n.id))}this.removeMapPending&&(this.removeMapPending=!1,this.configureMapsHandler())},resetMaps:function(){},dependencies:function(){var e={Maps:m},r=[],i={},s=this,o;t.each(e,function(e,t){r.push(i[t]=n.Deferred())},this),n.when.apply(n,r).then(function(){s._dependencies.resolve()},function(){s._dependencies.reject()}),t.each(e,function(e,t){this.app.collection(t,{fetch:{reload:!1,deferred:i[t]}},e)},this)},failed:function(){(new E).open(r.E_DataLoad)},locateDevice:function(e){this.rendered?(this.$mapSelect.val(e.get("map_id")),this.mapSelectHandler(),this.markers.get(e)&&this.map.locateDevice(e)):t.delay(this.locateDevice,50,e)},remove:function(){this.$ruler.$el.off("scaled",this.setUpp),this.$(".buttonset input").off("click",this.mapViewClick),this.$drawerHandle.off("click",this.toggleDrawer),this.$mapSelect.off("change",this.mapSelectHandler),this.markers.unbind("add",this.addDevice),this.markers.unbind("change",this.updateDevice),this.markers.unbind("remove",this.removeDevice),this.markers.unbind("reset",this.resetDevices),this.maps.unbind("add",this.addMap),this.maps.unbind("change",this.updateMap),this.maps.unbind("remove",this.removeMap),this.maps.unbind("reset",this.resetMaps),this.rendered=!1,i.prototype.remove.apply(this,arguments)}})}),define("unifi/router/MapRouter",["unifi/router/Router","unifi/view/map/IndexView","unifi/view/map/MarkerView","unifi/view/map/UnplacedMarkerView"],function(e,t,n,r){"use strict";return e.extend({_fullyQualifiedName:"UNIFI.Routers.Map",_associatedViews:{Index:t,Marker:n,UnplacedMarker:r},routes:{map:"index"}})}),define("unifi/view/app/PropertyView",["backbone","underscore","jquery","ubnt/backgrid","ubnt/view/dialogs/ErrorDialogView","msg/Msg"],function(e,t,n,r,i,s){"use strict";return e.View.extend({tagName:"div",className:"properties accordion",templateId:null,_autoRender:!1,_detached:!1,initialize:function(e){if(!this.templateId)throw"Missing templateId";t.bindAll(this),this.template=t.template(this.templateId),this.properties=e.properties,this.parent=e.parent,this.app=this.parent.app,this.id=e.count,this.$container=this.properties.$el,this.grids={},this.collections={},this.model.on("change:name",this.render,!0),this.model.on("remove",this.remove),n(window).bind("resize",this.position),this._autoRender&&this.render()},render:function(e){return!this.rendered&&(this.rendered=!0)?(this.$el.html(this.template(t.extend(this.args(),this.model))),this.$tabs=this.$(".tabs"),this.$statusSaved=this.$(".status-success"),this.$statusError=this.$(".status-error"),this.$overflow=this.$(".properties-container.overflow"),this.$el.find(".accordion").andSelf().accordion({header:"> .accordion-header",heightStyle:"content",collapsible:!0,animate:200,beforeActivate:function(e,t){if(n(this).hasClass("ui-dragging-stopped"))return!1},activate:n.proxy(function(e,t){this.position()},this)}),this.$el.find(".accordion .accordion-header").on("click",this.renderSelects),this.$el.find(".accordion-header .remove").on("click",n.proxy(function(e){e.stopPropagation(),e.preventDefault(),this.remove()},this)),this.$el.find(".accordion-header .detach").on("click",n.proxy(function(e){e.stopPropagation(),e.preventDefault(),this._detached?this.attach():this.detach()},this)),this.$tabs.tabs({activate:n.proxy(function(e,t){this.position(),this.$tabs.trigger("change")},this)}),this.$tabs.find("a").on("click",this.renderSelects),this.$container.prepend(this.$el.hide().fadeIn()),this.attach(!0)):(e||(this._detached?this.detach():this.attach()),this.$el.find(".accordion-header .title-text").text(this.model.get("name"))),this.$container.scrollTop(0),this.position(),this},renderSelects:function(){this.$("select:visible").each(function(){var e=n(this),t=e.parent(),r=e.data("selectRendered"),i=e.data("myposition")||"left top",s=e.data("atposition")||"left bottom";r||(e.selectmenu({parent:t,appendTo:t,icons:{button:"ubnt-icon-arrow-down secondary-color"},position:{my:i,at:s,collision:"flip"},change:function(t,n){var r=n.item.element.parents(".row:first"),i=r.next(".custom:first");n.item.value==="custom"?i.show():i.hide(),e.trigger("change")}}),e.data("selectRendered",!0).trigger("change",!0))})},args:function(){return{_id:this.id,msg:s}},remove:function(){this.rendered=!1,this.model.off("change:name",this.render,!0),this.model.off("remove",this.remove),n(window).unbind("resize",this.position),this.$el.find(".accordion-header .remove").off(),this.$el.find(".accordion .accordion-header").off(),this.$el.find(".accordion-header .detach").off(),this.$tabs.find("a").off(),t.each(this.grids,function(e){e.remove()}),this.grids={},this.removeTooltips(),this.$el.fadeOut(n.proxy(function(){e.View.prototype.remove.apply(this,arguments),this.$container.trigger("property:remove")},this))},attach:function(e){this.removeTooltips(),e||this.$container.prepend(this.$el.detach()),this.$el.accordion("option","active",0),this.$el.is(".ui-draggable")&&this.$el.draggable("destroy"),this.$el.is(".ui-resizable")&&(this.$el.resizable("destroy"),this.$el.css("width","")),this.$el.css({position:"static",top:0,left:0,"z-index":""}).find(".accordion-header .detach").attr("title",s.G_Detach).tooltip({show:!1,hide:!1,track:!0,close:n.proxy(function(e,t){this.$el.find(".accordion-header .detach").attr("title",this._detached?s.G_Attach:s.G_Detach)},this)}),this.overflow(!1),this._detached=!1,this.$container.trigger("property:render")},detach:function(e){var t=this.properties.$detached.find("> div.properties").size();this.removeTooltips(),e||this.properties.$detached.append(this.$el.detach()),this.$el.accordion("option","animate",!1).accordion("option","active",0).draggable({handle:".accordion-header",stack:".properties",containment:"window",opacity:.95,stop:function(e){n(e.target).addClass("ui-dragging-stopped").delay(300).queue(function(e){n(this).removeClass("ui-dragging-stopped"),e()})}}).resizable({handles:"e"}).css("width","").css("position","absolute").position({my:"center+"+10*t+" center+"+10*t,of:n.Window}).accordion("option","animate",200).trigger("click").find(".accordion-header .detach").attr("title",s.G_Attach).tooltip({show:!1,hide:!1,track:!0,close:n.proxy(function(e,t){this.$el.find(".accordion-header .detach").attr("title",this._detached?s.G_Attach:s.G_Detach)},this)}),this._detached=!0,this.position(),this.$container.trigger("property:remove")},removeTooltips:function(){n(".ui-tooltip-content").parents("div").remove()},overflow:function(e){this.$overflow.css("max-height","");if(e){var t=n(window).height(),r=this.$el.outerHeight(!0)-this.$overflow.height();this.$overflow.css("max-height",Math.max(0,t-r)+"px")}},position:function(){if(this._detached){this.overflow(!1);var e=this.$el.offset().top;e<0&&this.$el.css("top",e=0);var t=e+this.$el.outerHeight(!0),r=t-n(window).height(),i;if(r>0){if(i=(e-=r)<0)e=0;this.$el.css("top",e),i&&this.overflow(!0)}}},grid:function(e,n,i,s,o){if(n){var u=new r.Grid(o=t.extend({columns:e,collection:n,pageable:!0,footer:r.Paginators.Mini,noRows:s},o||{}));return i.html(u.render().$el),o.pageable&&u.paginate(1,5),u}s&&i.html(s)},failed:function(){(new i).open(s.E_DataLoad)},showSavedState:function(){this.$statusSaved.stop().fadeIn().delay(2e3).fadeOut()},showErrorState:function(){this.$statusError.stop().fadeIn().delay(2e3).fadeOut()}})}),function(e){Backbone.Stickit={_handlers:[],addHandler:function(e){e=_.map(_.flatten([e]),function(e){return _.extend({updateModel:!0,updateView:!0,updateMethod:"text"},e)}),this._handlers=this._handlers.concat(e)}},_.extend(Backbone.View.prototype,{_modelBindings:null,unstickit:function(e){_.each(this._modelBindings,_.bind(function(t,n){if(e&&t.model!==e)return!1;t.model.off(t.event,t.fn),delete this._modelBindings[n]},this)),this._modelBindings=_.compact(this._modelBindings),this.$el.off(".stickit"+(e?"."+e.cid:""))},stickit:function(e,t){var r=this,h=e||this.model,p=".stickit."+h.cid,d=t||this.bindings||{};this._modelBindings||(this._modelBindings=[]),this.unstickit(h),_.each(_.keys(d),function(e){var t,v,m,g,y=d[e]||{},b=_.uniqueId();e!=":el"?t=r.$(e):(t=r.$el,e="");if(!t.length)return;_.isString(y)&&(y={observe:y}),g=a(t,y),m=g.observe,v=_.extend({bindKey:b},g.setOptions||{}),f(r,t,g,h,m),l(r,t,g,h,m),m&&(_.each(g.events||[],function(n){var s=n+p,u=function(e){var n=g.getVal.call(r,t,e,g);i(r,g.updateModel,n,g)&&o(h,m,n,v,r,g)};e===""?r.$el.on(s,u):r.$el.on(s,e,u)}),_.each(_.flatten([m]),function(e){s(h,r,"change:"+e,function(e,n,i){(i==null||i.bindKey!=b)&&c(r,t,g,u(e,m,g,r),e)})}),c(r,t,g,u(h,m,g,r),h,!0)),n(r,g.initialize,t,h,g)}),this.remove=_.wrap(this.remove,function(e){r.unstickit(),e&&e.call(r)})}});var t=function(e,t){var n=(t||"").split("."),r=_.reduce(n,function(e,t){return e[t]},e);return r==null?e:r},n=function(e,t){if(t)return(_.isString(t)?e[t]:t).apply(e,_.toArray(arguments).slice(2))},r=function(e){return e.find("option").not(function(){return!this.selected})},i=function(e,t){return _.isBoolean(t)?t:_.isFunction(t)||_.isString(t)?n.apply(this,_.toArray(arguments)):!1},s=function(e,t,n,r){e.on(n,r,t),t._modelBindings.push({model:e,event:n,fn:r})},o=function(e,t,r,i,s,o){o.onSet&&(r=n(s,o.onSet,r,o)),e.set(t,r,i)},u=function(e,t,r,i){var s,o=function(t){var n=r.escape?e.escape(t):e.get(t);return _.isUndefined(n)?"":n};return s=_.isArray(t)?_.map(t,o):o(t),r.onGet?n(i,r.onGet,s,r):s},a=function(e,t){var n=[{updateModel:!1,updateView:!0,updateMethod:"text",update:function(e,t,n,r){e[r.updateMethod](t)},getVal:function(e,t,n){return e[n.updateMethod]()}}];_.each(Backbone.Stickit._handlers,function(t){e.is(t.selector)&&n.push(t)}),n.push(t);var r=_.extend.apply(_,n);return delete r.selector,r},f=function(e,t,n,r,i){var o=["autofocus","autoplay","async","checked","controls","defer","disabled","hidden","loop","multiple","open","readonly","required","scoped","selected"];_.each(n.attributes||[],function(n){var a="",f=n.observe||(n.observe=i),l=function(){var i=_.indexOf(o,n.name,!0)>-1?"prop":"attr",s=u(r,f,n,e);n.name=="class"?(t.removeClass(a).addClass(s),a=s):t[i](n.name,s)};_.each(_.flatten([f]),function(t){s(r,e,"change:"+t,l)}),l()})},l=function(e,t,r,i,o){if(r.visible==null)return;var a=function(){var s=r.visible,a=r.visibleFn,f=u(i,o,r,e),l=!!f;if(_.isFunction(s)||_.isString(s))l=n(e,s,f,r);a?n(e,a,t,l,r):l?t.show():t.hide()};_.each(_.flatten([o]),function(t){s(i,e,"change:"+t,a)}),a()},c=function(e,t,r,s,o,u){if(!i(e,r.updateView,s,r))return;r.update.call(e,t,s,o,r),u||n(e,r.afterUpdate,t,s,r)};Backbone.Stickit.addHandler([{selector:'[contenteditable="true"]',updateMethod:"html",events:["keyup","change","paste","cut"]},{selector:"input",events:["keyup","change","paste","cut"],update:function(e,t){e.val(t)},getVal:function(e){var t=e.val();return e.is('[type="number"]')?t==null?t:Number(t):t}},{selector:"textarea",events:["keyup","change","paste","cut"],update:function(e,t){e.val(t)},getVal:function(e){return e.val()}},{selector:'input[type="radio"]',events:["change"],update:function(e,t){e.filter('[value="'+t+'"]').prop("checked",!0)},getVal:function(e){return e.filter(":checked").val()}},{selector:'input[type="checkbox"]',events:["change"],update:function(t,n,r,i){t.length>1?(n||(n=[]),_.each(t,function(t){_.indexOf(n,e(t).val())>-1?e(t).prop("checked",!0):e(t).prop("checked",!1)})):_.isBoolean(n)?t.prop("checked",n):t.prop("checked",n==t.val())},getVal:function(t){var n;if(t.length>1)n=_.reduce(t,function(t,n){return e(n).prop("checked")&&t.push(e(n).val()),t},[]);else{n=t.prop("checked");var r=t.val();r!="on"&&r!=null&&(n?n=t.val():n=null)}return n}},{selector:"select",events:["change"],update:function(r,i,s,o){var u,a=o.selectOptions,f=a&&a.collection||undefined,l=r.prop("multiple");if(!a){a={};var c=function(e){return e.find("option").map(function(){return{value:this.value,label:this.text}}).get()};r.find("optgroup").length?(f={opt_labels:[]},_.each(r.find("optgroup"),function(t){var n=e(t).attr("label");f.opt_labels.push(n),f[n]=c(e(t))})):f=c(r)}a.valuePath=a.valuePath||"value",a.labelPath=a.labelPath||"label";var h=function(n,r,i){a.defaultOption&&(n=_.clone(n),n.unshift("__default__")),_.each(n,function(n){var s=e("<option/>"),o=n,u=function(e,t){s.text(e),o=t,s.data("stickit_bind_val",o),!_.isArray(o)&&!_.isObject(o)&&s.val(o)};n==="__default__"?u(a.defaultOption.label,a.defaultOption.value):u(t(n,a.labelPath),t(n,a.valuePath)),!l&&o!=null&&i!=null&&o==i||_.isObject(i)&&_.isEqual(o,i)?s.prop("selected",!0):l&&_.isArray(i)&&_.each(i,function(e){_.isObject(e)&&(e=t(e,a.valuePath)),(e==o||_.isObject(e)&&_.isEqual(o,e))&&s.prop("selected",!0)}),r.append(s)})};r.html("");var p=function(e,n){var r=window;return n.indexOf("this.")===0&&(r=e),n=n.replace(/^[a-z]*\.(.+)$/,"$1"),t(r,n)};_.isString(f)?u=p(this,f):_.isFunction(f)?u=n(this,f,r,o):u=f,u instanceof Backbone.Collection&&(u=u.toJSON()),_.isArray(u)?h(u,r,i):_.each(u.opt_labels,function(t){var n=e("<optgroup/>").attr("label",t);h(u[t],n,i),r.append(n)})},getVal:function(t){var n;return t.prop("multiple")?n=e(r(t).map(function(){return e(this).data("stickit_bind_val")})).get():n=r(t).data("stickit_bind_val"),n}}])}(window.jQuery||window.Zepto),define("stickit",function(){}),define("unifi/view/devices/PropertyView",["unifi/view/app/PropertyView","ubnt/backgrid","underscore","backbone","jquery","msg/Msg","ubnt/view/dialogs/ConfirmDialogView","stickit"],function(e,t,n,r,i,s,o){"use strict";return e.extend({initialize:function(t){e.prototype.initialize.call(this,t),this.model.on("change",this.populate),i.when(this._rendered=i.Deferred(),this._dependencies=i.Deferred()).then(this.populate,this.failed),this.dependencies(),this.render()},bindings:function(){return{".button-locate":{observe:["state","map_id","default","upgradable","locating"],onGet:function(){this.model.get("state")==1?this.$btnLocate.show():this.$btnLocate.hide(),this.model.get("adopted")&&(this.$btnLocate.removeClass("on"),this.model.get("locating")?this.$btnLocate.addClass("locating"):this.$btnLocate.removeClass("locating")),this.model.get("state")==1?this.$btnRestart.show():this.$btnRestart.hide(),this.model.get("state")!=2&&this.model.get("state")!=12||!this.model.get("default")?this.$btnAdopt.hide():this.$btnAdopt.show(),this.model.get("state")==5&&this.$btnAdopt.hide(),this.model.get("state")==1&&this.model.get("upgradable")===!0?this.$btnUpdate.show():this.$btnUpdate.hide()}},".bind-status":{observe:"state",onGet:function(){this.$statusBar.removeClass("ok pending error").addClass(this.model.statusType()).text(this.model.status())}},".bind-version":"version",".bind-ip":"ip",".bind-uptime":{observe:"uptime",onGet:function(){this.$bindUptime.text(this.model.uptime())}},".bind-adopt-ip":{observe:["adopt_ip","ip"],onGet:function(){return this.model.adoptIp()}},".bind-adopt-url":{observe:["adopt_url","inform_url"],onGet:function(){return this.model.adoptUrl()}}}},dependencies:function(){this._dependencies.resolve()},render:function(t){var n=this.rendered;return e.prototype.render.call(this,t),n||(this.$statusBar=this.$(".device-status"),this.$bindUptime=this.$(".bind-uptime"),this.$aliasForm=this.$(".aliasForm"),this.$forget=this.$(".forget"),this.$moveDropdown=this.$(".move-dropdown"),this.$copyConfigDropdown=this.$(".copyConfig-dropdown"),this.$btnUpdate=this.$(".button-update"),this.$btnAdopt=this.$(".button-adopt"),this.$btnLocate=this.$(".button-locate"),this.$btnRestart=this.$(".button-restart"),this.$aliasForm.on("submit",this.updateAlias),this.$forget.on("click",this.forget),this.$moveDropdown.on("change",this.moveDropdownChange),this.$copyConfigDropdown.on("change",this.copyConfigDropdownChange),this.$btnAdopt.on("click",this.adopt),this.$btnUpdate.on("click",this.upgrade),this.$btnLocate.on("click",this.locate),this.$btnRestart.on("click",this.restart)),this},populate:function(){if(this._dependencies&&this._dependencies.state()=="resolved"){this.$el.find(".property-content .loading").remove(),this.$el.removeClass("ap-connected ap-disconnected ap-upgradable ap-adopted ap-pending ap-adoptfailed ap-adopting ap-unmanaged has-uplink-dev"),this.$el.addClass("device-properties"),this.$el.addClass("mac-"+this.model.get("mac").replace(/:/g,"")),this.$el.addClass("ap-model-"+this.model.get("model")),this.model.isConnected()?(this.$el.addClass("ap-connected"),this.model.get("upgradable")&&this.$el.addClass("ap-upgradable")):this.$el.addClass("ap-disconnected"),this.model.get("adopted")?(this.$el.addClass("ap-adopted"),parseInt(this.model.get("state"),10)==10&&this.$el.addClass("ap-adoptfailed")):(this.$el.addClass("ap-pending"),this.model.get("default")||this.$el.addClass("ap-unmanaged")),this.model.status()==="Adopting"&&(this.$el.addClass("ap-adopting"),this.$el.find(".basic-overview").show());var e=this.model.uplinkDeviceMac();e!==""&&this.$el.addClass("has-uplink-dev"),this.setupMoveDropdown(),this.setupCopyConfigDropdown()}},populateNetworkForm:function(e,t){e[0].reset(),t.type=="pppoe"?(this.$connectionType.val("pppoe").trigger("change"),e.find("input[name=username]").val(t.username),e.find("input[name=x_password]").val(t.x_password),e.find("input[name=dns1]").val(t.dns1),e.find("input[name=dns2]").val(t.dns2),e.find("input[name=dnssuffix]").val(t.dnssuffix)):t.type=="static"?(this.$connectionType.val("static").trigger("change"),e.find("input[name=ip]").val(t.ip),e.find("input[name=netmask]").val(t.netmask),e.find("input[name=gateway]").val(t.gateway),e.find("input[name=dns1]").val(t.dns1),e.find("input[name=dns2]").val(t.dns2),e.find("input[name=dnssuffix]").val(t.dnssuffix)):(this.$connectionType.val("dhcp").trigger("change"),e.find("input[name=dns1]").val(t.dns1),e.find("input[name=dns2]").val(t.dns2),e.find("input[name=dnssuffix]").val(t.dnssuffix))},setupMoveDropdown:function(){this.$moveDropdown.empty().append(i('<option value=""></option>').text(s.G_MoveTo)),this.app.collection("Sites").each(function(e){if(!e.get("attr_hidden")){var t=e.get("desc");e.get("_id")==SITE.id&&(t+=" (current)"),this.$moveDropdown.append(i('<option value="'+e.get("_id")+'"></option>').text(t))}},this)},setupCopyConfigDropdown:function(){this.$copyConfigDropdown.empty().append(i('<option value=""></option>').text(s.G_CopyFrom)),this.app.collection("Devices").each(function(e){var t=e.get("mac"),n=e.get("type"),r=e.get("model");if(n===this.model.typeMap["switch"]&&t!==this.model.get("mac")&&(this.model.copyConfigMap[this.model.get("model")]&&this.model.copyConfigMap[this.model.get("model")].indexOf(r)>-1||r===this.model.get("model"))){var s=e.get("name");this.$copyConfigDropdown.append(i('<option value="'+t+'"></option>').text(s?s+" ("+t+")":t))}},this)},moveDropdownChange:function(){var e=this.$moveDropdown.val(),t=this.$moveDropdown.find("option:selected").text(),n=this,r=s.localize(s.G_PropertiesMoveDeviceConfirmTxt,t,t);if(e&&e!=SITE.id){var u=new o;u.options.dialogOptions.title=s.G_PropertiesMoveDeviceConfirmTitle,u.show(r,i.proxy(function(){n.model.move({data:{site:e},success:function(e,t){i("#header .refresh-status").click()},error:i.proxy(function(e){n.app.views.app.flash("error","Error",s.apiError(e))},n)})},n)),u.closeDialog(function(){n.$moveDropdown.val("").trigger("change")},n)}},copyConfigDropdownChange:function(){var e=this,t=this.$copyConfigDropdown.val();if(t){var n=this.$copyConfigDropdown.find("option:selected").text(),r=s.localize(s.G_PropertiesCopyDeviceConfigConfirmTxt,n),u=new o;u.options.dialogOptions.title=s.G_PropertiesCopyDeviceConfigConfirmTitle,u.show(r,i.proxy(function(){e.model.copyConfig({selectedMac:t,success:function(e,t){i("#header .refresh-status").click()},error:i.proxy(function(t){e.app.views.app.flash("error","Error",s.apiError(t))},e)})})),u.closeDialog(function(){e.$copyConfigDropdown.val("").trigger("change")},e)}},updateAlias:function(){var e=this,t=this.$aliasForm.find('input[name="name"]'),n=t.val(),r=!1,s,o;return this.$aliasForm.find(".error").removeClass("error"),this.$aliasForm.find(".row-error").remove(),n===""?(r=!0,n=this.model.get("mac"),s={name:n}):s=this.$aliasForm.serializeObject(),o=this.model.save(s,{wait:!0,data:s,success:function(i,s){s.meta.rc==="ok"?(e.showSavedState(),t.val(r?"":n)):e.showErrorState()},error:function(){e.showErrorState()}}),!o&&this.model.validationError&&this.model.validationError.name&&(t.addClass("error"),this.$aliasForm.find(".row").after(i('<div class="row row-error"></div>').text(this.model.validationError.name))),!1},updateNetwork:function(e,t){var r={};switch(this.$connectionType.val()){case"pppoe":r[t]={type:"pppoe",username:e.find("input[name=username]").val(),x_password:e.find("input[name=x_password]").val(),dns1:e.find("input[name=dns1]").val(),dns2:e.find("input[name=dns2]").val(),dnssuffix:e.find("input[name=dnssuffix]").val()},r[t].dns1||delete r[t].dns1,r[t].dns2||delete r[t].dns2,r[t].dnssuffix||delete r[t].dnssuffix;break;case"static":r[t]={type:"static",ip:e.find("input[name=ip]").val(),netmask:e.find("input[name=netmask]").val(),gateway:e.find("input[name=gateway]").val(),dns1:e.find("input[name=dns1]").val(),dns2:e.find("input[name=dns2]").val(),dnssuffix:e.find("input[name=dnssuffix]").val()},r[t].gateway||delete r[t].gateway,r[t].dns1||delete r[t].dns1,r[t].dns2||delete r[t].dns2,r[t].dnssuffix||delete r[t].dnssuffix;break;case"dhcp":r[t]={type:"dhcp",dns1:e.find("input[name=dns1]").val(),dns2:e.find("input[name=dns2]").val(),dnssuffix:e.find("input[name=dnssuffix]").val()},r[t].dns1||delete r[t].dns1,r[t].dns2||delete r[t].dns2,r[t].dnssuffix||delete r[t].dnssuffix}e.find(".error").removeClass("error");var s=this.model.save(r,{success:i.proxy(function(e,t){t.meta.rc==="ok"?this.showSavedState():this.showErrorState()},this),error:i.proxy(function(){this.showErrorState()},this)});!s&&this.model.validationError&&this.model.validationError[t]&&n.each(this.model.validationError[t],function(t,n){switch(n){case"username":case"x_password":case"ip":case"netmask":case"gateway":case"dns1":case"dns2":case"dnssuffix":e.find('input[name="'+n+'"]').addClass("error")}},this)},forget:function(){var e=new o;return e.options.dialogOptions.title=s.G_PropertiesForgetDeviceConfirmTitle,e.show(s.G_PropertiesForgetDeviceConfirmTxt,i.proxy(function(){this.model.forget({success:i.proxy(function(){this.app.collection("Devices").remove(this.model),this.remove()},this),error:i.proxy(function(e){this.app.views.app.flash("error","Error",s.apiError(e))},this)})},this)),!1},adopt:function(){return this.parent.rowAdopt(this.model),!1},upgrade:function(){return this.parent.rowUpgrade(this.model),!1},locate:function(){return this.parent.rowLocate(this.model),!1},restart:function(){return this.parent.rowRestart(this.model),!1},remove:function(){this.model.off("change",this.populate),this.$aliasForm.off(),this.$forget.off(),this.$moveDropdown.off(),this.$btnAdopt.off(),this.$btnUpdate.off(),this.$btnLocate.off(),this.$btnRestart.off(),this.rendered=!1,e.prototype.remove.call(this)}})}),define("text!includes/aps/apPropertiesTemplate.html",[],function(){return'<div class="accordion-header">\n    <div class="accordion-title">\n        <span class="device-icons access-point half"></span>\n        <span class="title-text"><%- name() %></span>\n        <div class="ubnt-icon-arrow-down sidebar-icons minmax minimize"></div>\n    </div>\n    <div class="right">\n        <div class="ubnt-icon-new-window sidebar-icons detach" title="Detach"></div>\n        <div class="ubnt-icon-close sidebar-icons remove" title="Close"></div>\n    </div>\n</div>\n<div class="property-content">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n\n    <div class="device-status-wrapper">\n        <div class="device-status bind-status"></div>\n    </div>\n    <div class="status-alert status-success"><span class="ubnt-icon-check checkmark"></span><%- msg.G_Saved %></div>\n    <div class="status-alert status-error"><span class="ubnt-icon-warning alert"></span><%- msg.E_Error %></div>\n    <div class="tabs">\n        <ul>\n            <li class="tab-nav-list-item">\n                <a class="tab-button" href="#deviceDetails<%- _id %>"><%- msg.G_PropertiesDetails %></a>\n            </li>\n            <li class="tab-nav-list-item station-details">\n                <a class="tab-button" href="#deviceUsers<%- _id %>"><%- msg.G_Users %></a>\n            </li>\n            <li class="tab-nav-list-item station-details">\n                <a class="tab-button" href="#deviceGuests<%- _id %>"><%- msg.G_Guests %></a>\n            </li>\n            <li class="tab-nav-list-item ap-configs">\n                <a class="tab-button" href="#deviceConfig<%- _id %>"><%- msg.G_PropertiesConfiguration %></a>\n            </li>\n        </ul>\n        <div class="properties-container overflow">\n            <div id="deviceDetails<%- _id %>" class="tab-content">\n                <div class="accordion">\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_DevicesOverview %></div>\n                    </div>\n                    <div class="basic-overview">\n                        <table>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesMACAddress %></td>\n                                <td class="column-value"><%- get(\'mac\') %></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_DevicesModel %></td>\n                                <td class="column-value"><%- apModel() %></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Version %></td>\n                                <td class="column-value bind-version"></td>\n                            </tr>\n                        </table>\n                        <hr />\n                        <table>\n                            <tr class="table-row ip-address">\n                                <td class="column-name"><%- msg.G_IPAddress %></td>\n                                <td class="column-value bind-ip"></td>\n                            </tr>\n                            <tr class="table-row uptime">\n                                <td class="column-name"><%- msg.G_Uptime %></td>\n                                <td class="column-value bind-uptime"></td>\n                            </tr>\n                            <tr class="table-row last-uplink">\n                                <td class="column-name"><%- msg.G_LastUplink %></td>\n                                <td class="column-value">\n                                    <a class="bind-lastuplink button-uplink-device" href="#"></a>\n                                </td>\n                            </tr>\n                            <tr class="table-row last-seen">\n                                <td class="column-name"><%- msg.G_LastSeen %></td>\n                                <td class="column-value bind-lastseen"></td>\n                            </tr>\n                        </table>\n                        <hr class="station-details" />\n                        <table class="station-details">\n                            <tr class="table-row">\n                                <td class="column-name"># <%- msg.G_Users %></td>\n                                <td class="column-value bind-num-users"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"># <%- msg.G_Guests %></td>\n                                <td class="column-value bind-num-guests"></td>\n                            </tr>\n                        </table>\n                    </div>\n                    <div class="accordion-header ap-uplink-details">\n                        <div class="accordion-title"><%- msg.G_PropertiesUplink %> <span class="uplink-type"></span></div>\n                    </div>\n                    <div class="ap-uplink-details">\n                        <table class="wireless">\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesUplinkAP %></td>\n                                <td class="column-value">\n                                    <a class="bind-uplink-device button-uplink-device" href="#"></a>\n                                </td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesSignal %></td>\n                                <td class="column-value bind-uplink-rssi"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesTXRate %></td>\n                                <td class="column-value bind-uplink-tx-rate"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesRXRate %></td>\n                                <td class="column-value bind-uplink-rx-rate"></td>\n                            </tr>\n                        </table>\n                        <table class="wire">\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Speed %></td>\n                                <td class="column-value bind-uplink-speed"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesDuplex %></td>\n                                <td class="column-value bind-uplink-duplex"></td>\n                            </tr>\n                            <tr class="table-row uplink-device">\n                                <td class="column-name"><%- msg.G_PropertiesUplink %></td>\n                                <td class="column-value">\n                                    <a class="bind-uplink-device button-uplink-device" href="#"></a>\n                                </td>\n                            </tr>\n                        </table>\n                        <hr />\n                        <table>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesDownPktsBytes %></td>\n                                <td class="column-value bind-uplink-down-packets"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesUpPktsBytes %></td>\n                                <td class="column-value bind-uplink-up-packets"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Activity %></td>\n                                <td class="column-value bind-uplink-activity"></td>\n                            </tr>\n                        </table>\n                    </div>\n                    <div class="accordion-header ap-adv-adopt">\n                        <div class="accordion-title"><%- msg.G_PropertiesAdvancedOpts %></div>\n                    </div>\n                    <div class="ap-adv-adopt">\n                        <form action="" class="advAdoptForm ap-adv-adopt">\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_IP %></label>\n                                <input class="input inline medium bind-adopt-ip" type="text" value="" name="ip" />\n                                <span class="colon">:</span>\n                                <input class="input inline small" type="text" value="22" name="port" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_UN %></label>\n                                <input class="input inline" type="text" value="" name="username" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_PW %></label>\n                                <input class="input inline" type="password" value="" name="password" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_PropertiesInformURL %></label>\n                                <input class="input inline bind-adopt-url" type="text" value="" name="url" />\n                            </div>\n                            <button class="button is-admin" type="submit"><%- msg.G_Adopt %></button>\n                        </form>\n                    </div>\n                    <div class="accordion-header ap-downlink-details">\n                        <div class="accordion-title"><%- msg.G_PropertiesDownlinks %></div>\n                    </div>\n                    <div class="ap-downlink-details ap-downlink-content">\n                        <div class="data-table data-table-downlinks bind-downlinks"></div>\n                    </div>\n                    <div class="accordion-header radio-ng ap-ng-details">\n                        <div class="accordion-title"><%- msg.G_PropertiesRadio11NBG %></div>\n                    </div>\n                    <div class="radio-ng ap-ng-details">\n                        <table>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Channel %></td>\n                                <td class="column-value bind-ng-channel"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesTransmitPower %></td>\n                                <td class="column-value"><span class="bind-ng-transmit-power"></span></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesTXPktsBytes %></td>\n                                <td class="column-value bind-ng-tx-packets"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesRXPktsBytes %></td>\n                                <td class="column-value bind-ng-rx-packets"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesTXRetryDropped %></td>\n                                <td class="column-value bind-ng-tx-retry"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesRXRetryDropped %></td>\n                                <td class="column-value bind-ng-rx-retry"></td>\n                            </tr>\n                        </table>\n                        <hr />\n                        <table>\n                            <tr class="table-row">\n                                <td class="column-name"># <%- msg.G_Users %></td>\n                                <td class="column-value bind-ng-users"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"># <%- msg.G_Guests %></td>\n                                <td class="column-value bind-ng-guests"></td>\n                            </tr>\n                        </table>\n                    </div>\n                    <div class="accordion-header radio-na ap-na-details">\n                        <div class="accordion-title"><%- msg.G_PropertiesRadio11NA %></div>\n                    </div>\n                    <div class="radio-na ap-na-details">\n                        <table>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Channel %></td>\n                                <td class="column-value bind-na-channel"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesTransmitPower %></td>\n                                <td class="column-value"><span class="bind-na-transmit-power"></span></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesTXPktsBytes %></td>\n                                <td class="column-value bind-na-tx-packets"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesRXPktsBytes %></td>\n                                <td class="column-value bind-na-rx-packets"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesTXRetryDropped %></td>\n                                <td class="column-value bind-na-tx-retry"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesRXRetryDropped %></td>\n                                <td class="column-value bind-na-rx-retry"></td>\n                            </tr>\n                        </table>\n                        <hr />\n                        <table>\n                            <tr class="table-row">\n                                <td class="column-name"># <%- msg.G_Users %></td>\n                                <td class="column-value bind-na-users"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"># <%- msg.G_Guests %></td>\n                                <td class="column-value bind-na-guests"></td>\n                            </tr>\n                        </table>\n                    </div>\n                </div>\n            </div>\n            <div id="deviceUsers<%- _id %>" class="tab-content minigrid">\n                <div class="data-table data-table-users"><%- msg.G_PropertiesNoUsersConnected %></div>\n            </div>\n            <div id="deviceGuests<%- _id %>" class="tab-content minigrid">\n                <div class="data-table data-table-guests"><%- msg.G_PropertiesNoGuestsConnected %></div>\n            </div>\n            <div id="deviceConfig<%- _id %>" class="tab-content ap-configs">\n                <div class="accordion">\n                    <div class="accordion-header ap-configs">\n                        <div class="accordion-title"><%- msg.G_Config %></div>\n                    </div>\n                    <div class="ap-configs">\n                        <form action="" class="aliasForm">\n                            <div class="row">\n                                <label for="aliasName<%- _id %>" class="label"><%- msg.G_PropertiesAlias %></label>\n                                <input name="name" id="aliasName<%- _id %>" type="text" class="input" value="<%- get(\'name\') %>" />\n                            </div>\n                            <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n                        </form>\n                    </div>\n\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_PropertiesRadios %></div>\n                    </div>\n                    <div>\n                        <form action="" class="radiosForm">\n                            <fieldset class="fieldset radio-ng ap-ng-configs">\n                                <legend class="legend"><%- msg.G_PropertiesRadio2G11NBG %></legend>\n                                <div class="row">\n                                    <input type="hidden" class="hidden" name="ng.radio" value="ng" />\n                                    <label for="channel-radio-nbg<%- _id %>" class="label label-selectmenu"><%- msg.G_Channel %></label>\n                                    <div class="selectmenu-group">\n                                        <div>\n                                            <select name="ng.channel" id="channel-radio-nbg<%- _id %>" class="radio-channel inline"></select>\n                                        </div>\n                                        <div>\n                                            <select name="ng.ht" class="inline radio-ht" data-radio="ng">\n                                                <option value="20"><%- msg.G_PropertiesHT20 %></option>\n                                                <option value="40"><%- msg.G_PropertiesHT40 %></option>\n                                            </select>\n                                        </div>\n                                    </div>\n                                </div>\n\n                                <div class="row">\n                                    <label for="txPower-radio-nbg<%- _id %>" class="label label-selectmenu"><%- msg.G_PropertiesTXPower %></label>\n                                    <select name="ng.tx_power_mode" id="txPower-radio-nbg<%- _id %>" class="inline">\n                                        <option value="auto"><%- msg.G_Auto %></option>\n                                        <option value="high"><%- msg.G_High %></option>\n                                        <option value="medium"><%- msg.G_Medium %></option>\n                                        <option value="low"><%- msg.G_Low %></option>\n                                        <option value="custom"><%- msg.G_Custom %></option>\n                                    </select>\n                                </div>\n                                <div class="custom">\n                                    <div class="row">\n                                        <input class="input no-label" type="text" name="ng.tx_power" size="2" value="<%- get(\'ng.tx_power\') || \'0\' %>" />\n                                        <label class="label unit"><%- msg.G_PropertiesDBM %></label>\n                                    </div>\n                                    <div class="row antenna-gain">\n                                        <label class="label custom-label" for="antenna-gain<%- _id %>"><%- msg.G_PropertiesAntennaGain %></label>\n                                        <input class="custom input" id="antenna-gain<%- _id %>" type="text" size="2" name="ng.antenna_gain" value="<%- get(\'ng.antenna_gain\') || \'6\' %>" />\n                                        <label class="label unit"><%- msg.G_PropertiesDBI %></label>\n                                    </div>\n                                </div>\n                            </fieldset>\n                            <fieldset class="fieldset radio-na ap-na-configs">\n                                <legend class="legend"><%- msg.G_PropertiesRadio5G11NA %></legend>\n                                <div class="row">\n                                    <input type="hidden" class="hidden" name="na.radio" value="na" />\n                                    <label for="channel-radio-na<%- _id %>" class="label label-selectmenu"><%- msg.G_Channel %></label>\n                                    <div class="selectmenu-group">\n                                        <div>\n                                            <select name="na.channel" id="channel-radio-na<%- _id %>" class="radio-channel inline"></select>\n                                        </div>\n                                        <div>\n                                            <select name="na.ht" class="radio-ht inline" data-radio="na">\n                                                <option value="20"><%- msg.G_PropertiesHT20 %></option>\n                                                <option value="40"><%- msg.G_PropertiesHT40 %></option>\n                                                <option value="80"><%- msg.G_PropertiesHT80 %></option>\n                                            </select>\n                                        </div>\n                                    </div>\n                                </div>\n                                <div class="row">\n                                    <label for="txPower-radio-na<%- _id %>" class="label label-selectmenu"><%- msg.G_PropertiesTXPower %></label>\n                                    <select name="na.tx_power_mode" id="txPower-radio-na<%- _id %>" class="inline">\n                                        <option value="auto"><%- msg.G_Auto %></option>\n                                        <option value="high"><%- msg.G_High %></option>\n                                        <option value="medium"><%- msg.G_Medium %></option>\n                                        <option value="low"><%- msg.G_Low %></option>\n                                        <option value="custom"><%- msg.G_Custom %></option>\n                                    </select>\n                                </div>\n                                <div class="custom">\n                                    <div class="row">\n                                        <input class="input no-label" type="text" name="na.tx_power" size="2" value="<%- get(\'na.tx_power\') || \'0\' %>" />\n                                        <label class="label unit"><%- msg.G_PropertiesDBM %></label>\n                                    </div>\n                                    <div class="row antenna-gain">\n                                        <label class="label custom-label" for="antenna-gain-na<%- _id %>"><%- msg.G_PropertiesAntennaGain %></label>\n                                        <input class="custom input" id="antenna-gain-na<%- _id %>" type="text" size="2" name="na.antenna_gain" value="<%- get(\'na.antenna_gain\') || \'6\' %>" />\n                                        <label class="label unit"><%- msg.G_PropertiesDBI %></label>\n                                    </div>\n                                </div>\n                            </fieldset>\n                            <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n                        </form>\n                    </div>\n\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_PropertiesWLANS %></div>\n                    </div>\n                    <div>\n                        <fieldset class="fieldset ap-ng-configs radio-ng fieldset-wlan">\n                            <div class="settings-list">\n                                <legend class="legend"><%- msg.G_PropertiesWLANS2G11NBG %></legend>\n                                <div class="row">\n                                    <label for="wlan-group-ng<%- _id %>" class="label label-selectmenu wide"><%- msg.G_PropertiesWLANGroup %></label>\n                                    <div class="is-admin bind-wlan-group-ng">\n                                        <select name="wlan-group-ng" id="wlan-group-ng<%- _id %>" data-radio="ng" class="inline select-wlan wlan-group-ng"></select>\n                                    </div>\n                                    <div class="table-wlans table-wlans-ng data-table data-table-wlans-ng"></div>\n                            </div>\n                        </fieldset>\n                        <fieldset class="fieldset ap-na-configs radio-na fieldset-wlan">\n                            <div class="settings-list">\n                                <legend class="legend"><%- msg.G_PropertiesWLANS5G11NA %></legend>\n                                <div class="row">\n                                    <label for="wlan-group-na<%- _id %>" class="label label-selectmenu wide"><%- msg.G_PropertiesWLANGroup %></label>\n                                    <div class="is-admin bind-wlan-group-na">\n                                        <select name="wlan-group-na" id="wlan-group-na<%- _id %>" data-radio="na" class="inline select-wlan wlan-group-na"></select>\n                                    </div>\n                                    <div class="table-wlans table-wlans-na data-table data-table-wlans-na"></div>\n                                    <div class=\'WLANSDisabled\'><%- msg.G_5GWLANSDisabled %></div>\n                                </div>\n                            </div>\n                        </fieldset>\n                        <fieldset class="fieldset override-form">\n                            <form>\n                                <legend class="legend"><%- msg.G_Override %></legend>\n                                <div class="row">\n                                    <label class="label" for="override-enabled<%- _id %>"><%- msg.G_Enabled %></label>\n                                    <input class="input checkbox" type="checkbox" name="wlanEnabled" id="override-enabled<%- _id %>" />\n                                    <span><%- msg.G_PropertiesEnblOnAP %></span>\n                                </div>\n                                <div class="row">\n                                    <label class="label" for="override-vlan<%- _id %>"><%- msg.G_PropertiesVLAN %></label>\n                                    <input class="input checkbox" type="checkbox" name="vlanEnabled" id="override-vlan<%- _id %>" />\n                                    <span><%- msg.G_PropertiesUseVLANId %></span>\n                                    <input class="input small" type="text" name="vlan" maxlength="4" size="3" />\n                                </div>\n                                <div class="row ssid-row">\n                                    <label class="label inline" for="override-ssid<%- _id %>"><%- msg.G_PropertiesSSID %></label>\n                                    <input class="input inline" type="text" name="name" id="override-ssid<%- _id %>" />\n                                </div>\n                                <div class="row wpapsk">\n                                    <label class="label inline" for="override-psk<%- _id %>"><%- msg.G_PropertiesPSK %></label>\n                                    <input class="input inline" type="text" name="passphrase" id="override-psk<%- _id %>" />\n                                </div>\n                                <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n                                <button class="button is-admin" name="restore" value="Restore" type="button"><%- msg.G_PropertiesRestore %></button>\n                                <button class="button" name="cancel" value="Cancel" type="button"><%- msg.G_Cancel %></button>\n                            </form>\n                        </fieldset>\n                    </div>\n\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_Network %></div>\n                    </div>\n                    <div>\n                        <form action="" class="networkForm bind-network">\n                            <div class="clearfix">\n                                <div class="side-by-side">\n                                    <div class="row">\n                                        <label for="configure-ip<%- _id %>" class="label inline"><%- msg.G_PropertiesConfigIP %></label>\n                                        <select name="type" class="configure-ip" id="configure-ip<%- _id %>">\n                                            <option value="dhcp"><%- msg.G_PropertiesUsingDHCP %></option>\n                                            <option value="static"><%- msg.G_PropertiesStaticIP %></option>\n                                        </select>\n                                    </div>\n                                </div>\n                            </div>\n\n                            <div class="clearfix">\n                                <div class="side-by-side">\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_IPAddress %></label>\n                                        <input type="text" class="input inline" name="ip" size="17" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesSubnetMask %></label>\n                                        <input type="text" class="input inline" name="netmask" size="17" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesGateway %></label>\n                                        <input type="text" class="input inline" name="gateway" size="17" value="" />\n                                    </div>\n                                </div>\n\n                                <div class="side-by-side">\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesPreferredDNS %></label>\n                                        <input type="text" class="input inline" name="dns1" size="17" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesAlternateDNS %></label>\n                                        <input type="text" class="input inline" name="dns2" size="17" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesDNSSuffix %></label>\n                                        <input type="text" class="input inline" name="dnssuffix" size="17" value="" />\n                                    </div>\n                                </div>\n                            </div>\n                            <button class="button is-admin"><%- msg.G_Apply %></button>\n                        </form>\n                    </div>\n\n                    <div class="accordion-header ap-uplinks-select">\n                        <div class="accordion-title"><%- msg.G_PropertiesWirelessUplinks %></div>\n                    </div>\n                    <div class="ap-uplinks-select ap-uplinks-content">\n                        <div class="data-table-uplinks-none"><%- msg.G_PropertiesNoWirelssUplnks %></div>\n                        <div class="data-table data-table-uplinks"></div>\n                    </div>\n\n                    <div class="accordion-header is-admin">\n                        <div class="accordion-title"><%- msg.G_PropertiesForgetAP %></div>\n                    </div>\n                    <div class="is-admin">\n                        <div class="row">\n                            <%- msg.G_PropertiesForgetAPTxt %>\n                        </div>\n                        <button class="button forget left">\n                            <span class="ui-button-icon-primary ubnt-icon-forget-this-network"></span>\n                            <span class="nav-text"><%- msg.G_PropertiesForget %></span>\n                        </button>\n                        <div class="left">\n                            <select name="move" class="move-dropdown" data-myposition="left bottom" data-atposition="left top"></select>\n                        </div>\n                        <!--<button class="button shell">Shell</button>-->\n                    </div>\n                </div>\n            </div>\n        </div>\n        <div class="dialog-controls is-admin clearfix">\n            <button class="button button-locate left">\n                <span class="ui-button-icon-primary ubnt-icon-location sidebar-icons locate"></span>\n                <span class="nav-text"><%- msg.G_Locate %></span>\n            </button>\n            <button class="button button-restart left">\n                <span class="ui-button-icon-primary ubnt-icon-rotate sidebar-icons restart"></span>\n                <span class="nav-text"><%- msg.G_Restart %></span>\n            </button>\n            <button class="button button-update left">\n                <span class="ui-button-icon-primary ubnt-icon-download sidebar-icons update"></span>\n                <span class="nav-text"><%- msg.G_Upgrade %></span>\n            </button>\n            <button class="button button-adopt left">\n                <span class="ui-button-icon-primary ubnt-icon-plus sidebar-icons adopt"></span>\n                <span class="nav-text"><%- msg.G_Adopt %></span>\n            </button>\n        </div>\n    </div>\n</div>\n'}),define("unifi/view/aps/PropertyView",["unifi/view/devices/PropertyView","ubnt/backgrid","underscore","backbone","jquery","msg/Msg","unifi/model/Device","unifi/collection/SystemInfos","unifi/collection/WlanGroups","unifi/collection/Wlans","unifi/collection/Sites","text!includes/aps/apPropertiesTemplate.html","ubnt/view/dialogs/AlertDialogView","stickit"],function(e,t,n,r,i,s,o,u,a,f,l,c,h){"use strict";return e.extend({templateId:c,initialize:function(t){this.configuredRadios=!1,e.prototype.initialize.call(this,t),this.listenTo(this.app.collection("Wlans"),"add remove destroy change",this.setupWlanPanel),this.listenTo(this.model,"change:radio_na change:radio_ng",i.proxy("updateRadiosForm",this))},bindings:function(){return n.extend({},e.prototype.bindings.call(this),{".bind-lastseen":{observe:"last_seen",onGet:function(){this.$bindLastseen.text(this.model.lastSeen())}},".bind-lastuplink":{observe:["last_uplink","uplink"],onGet:function(){this.$bindLastUplink.text(this.model.uplinkDeviceText())}},".bind-num-users":{observe:"user-num_sta",onGet:function(e){this.$bindNumUsers.text(e||0)}},".bind-num-guests":{observe:"guest-num_sta",onGet:function(e){this.$bindNumGuests.text(e||0)}},".bind-uplink-device":{observe:"uplink",onGet:function(){this.$bindUplinkDevice.text(this.model.uplinkDeviceText()),this.$bindUplinkRssi.text(this.model.uplinkRssi()),this.$bindUplinkTxRate.text(this.model.uplinkTxRate()),this.$bindUplinkRxRate.text(this.model.uplinkRxRate()),this.$bindUplinkSpeed.text(this.model.uplinkSpeed()),this.$bindUplinkDuplex.text(this.model.uplinkDuplex()),this.$bindUplinkDownPackets.text(this.model.uplinkDownPackets()),this.$bindUplinkUpPackets.text(this.model.uplinkUpPackets()),this.$bindUplinkActivity.text(this.model.uplinkActivity()),this.$statusBar.removeClass("ok pending error").addClass(this.model.statusType()).text(this.model.status())}},".bind-ng-channel":{observe:["ng-state","ng-extchannel","ng-channel","na-state","na-extchannel","na-channel"],onGet:function(){this.$bindNgChannel.text(this.model.channel("ng")),this.$bindNaChannel.text(this.model.channel("na"))}},".bind-ng-transmit-power":{observe:["ng-tx_power","ng-gain","ng-eirp","na-tx_power","na-gain","na-eirp"],onGet:function(){var e=this.model.transmitPower("ng"),t=this.model.transmitPower("na"),r=" "+s.G_PropertiesDBM+" ("+s.G_PropertiesEIRP+")";this.$bindNgTransmitPower.text(n.isUndefined(e)?"":e+r),this.$bindNaTransmitPower.text(n.isUndefined(t)?"":t+r)}},".bind-ng-tx-packets":{observe:"stat",onGet:function(){this.$bindNgTxPackets.text(this.model.packetsPerBytes("ng","tx")),this.$bindNgRxPackets.text(this.model.packetsPerBytes("ng","rx")),this.$bindNgTxRetry.text(this.model.errorPercentage("ng","tx")),this.$bindNgRxRetry.text(this.model.errorPercentage("ng","rx")),this.$bindNaTxPackets.text(this.model.packetsPerBytes("na","tx")),this.$bindNaRxPackets.text(this.model.packetsPerBytes("na","rx")),this.$bindNaTxRetry.text(this.model.errorPercentage("na","tx")),this.$bindNaRxRetry.text(this.model.errorPercentage("na","rx"))}},".bind-na-users":{observe:["na-user-num_sta"],onGet:function(){this.$bindNaUsers.text(this.model.get("na-user-num_sta")||0)}},".bind-ng-users":{observe:["ng-user-num_sta"],onGet:function(){this.$bindNgUsers.text(this.model.get("ng-user-num_sta")||0)}},".bind-na-guests":{observe:["na-guest-num_sta"],onGet:function(){this.$bindNaGuests.text(this.model.get("na-guest-num_sta")||0)}},".bind-ng-guests":{observe:["ng-guest-num_sta"],onGet:function(){this.$bindNgGuests.text(this.model.get("ng-guest-num_sta")||0)}},".bind-wlan-group-ng":{observe:"wlangroup_id_ng",updateView:!1,onGet:function(e){this.$bindWlanGroupNg.find("select").val(e).trigger("change",!0),this.setupWlanTable("ng")}},".bind-wlan-group-na":{observe:"wlangroup_id_na",updateView:!1,onGet:function(e){this.$bindWlanGroupNa.find("select").val(e).trigger("change",!0),this.setupWlanTable("na")}},".bind-network":{observe:"config_network",onGet:function(e){this.populateNetworkForm(this.$networkForm,e)}}})},dependencies:function(){var e={SystemInfos:u,WlanGroups:a,Wlans:f,Sites:l},t=[],r={},s=this;n.each(e,function(e,n){t.push(r[n]=i.Deferred())},this),i.when.apply(i,t).then(function(){s._dependencies.resolve()},function(){s._dependencies.reject()}),n.each(e,function(e,t){this.app.collection(t,{fetch:{reload:!1,deferred:r[t]}},e)},this)},render:function(t){var n=this.rendered;return e.prototype.render.call(this,t),n||(this.$advAdoptForm=this.$(".advAdoptForm"),this.$radiosForm=this.$(".radiosForm"),this.$networkForm=this.$(".networkForm"),this.$shell=this.$(".shell"),this.$connectionType=this.$(".configure-ip"),this.$btnLocate=this.$(".button-locate"),this.$btnRestart=this.$(".button-restart"),this.$btnUpdate=this.$(".button-update"),this.$btnAdopt=this.$(".button-adopt"),this.$overrideFieldset=this.$(".override-form"),this.$overrideForm=this.$overrideFieldset.find("form"),this.$fieldsetWlans=this.$(".fieldset-wlan"),this.$uplinkDevice=this.$(".button-uplink-device"),this.$bindUptime=this.$(".bind-uptime"),this.$bindLastseen=this.$(".bind-lastseen"),this.$bindLastUplink=this.$(".bind-lastuplink"),this.$bindNumUsers=this.$(".bind-num-users"),this.$bindNumGuests=this.$(".bind-num-guests"),this.$bindUplinkDevice=this.$(".bind-uplink-device"),this.$bindUplinkRssi=this.$(".bind-uplink-rssi"),this.$bindUplinkTxRate=this.$(".bind-uplink-tx-rate"),this.$bindUplinkRxRate=this.$(".bind-uplink-rx-rate"),this.$bindUplinkSpeed=this.$(".bind-uplink-speed"),this.$bindUplinkDuplex=this.$(".bind-uplink-duplex"),this.$bindUplinkDownPackets=this.$(".bind-uplink-down-packets"),this.$bindUplinkUpPackets=this.$(".bind-uplink-up-packets"),this.$bindUplinkActivity=this.$(".bind-uplink-activity"),this.$bindAdoptIp=this.$(".bind-adopt-ip"),this.$bindAdoptUrl=this.$(".bind-adopt-url"),this.$bindDownlinks=this.$(".bind-downlinks"),this.$bindNgChannel=this.$(".bind-ng-channel"),this.$bindNgTransmitPower=this.$(".bind-ng-transmit-power"),this.$bindNgTxPackets=this.$(".bind-ng-tx-packets"),this.$bindNgRxPackets=this.$(".bind-ng-rx-packets"),this.$bindNgTxRetry=this.$(".bind-ng-tx-retry"),this.$bindNgRxRetry=this.$(".bind-ng-rx-retry"),this.$bindNgUsers=this.$(".bind-ng-users"),this.$bindNgGuests=this.$(".bind-ng-guests"),this.$bindNaChannel=this.$(".bind-na-channel"),this.$bindNaTransmitPower=this.$(".bind-na-transmit-power"),this.$bindNaTxPackets=this.$(".bind-na-tx-packets"),this.$bindNaRxPackets=this.$(".bind-na-rx-packets"),this.$bindNaTxRetry=this.$(".bind-na-tx-retry"),this.$bindNaRxRetry=this.$(".bind-na-rx-retry"),this.$bindNaUsers=this.$(".bind-na-users"),this.$bindNaGuests=this.$(".bind-na-guests"),this.$bindWlanGroupNg=this.$(".bind-wlan-group-ng"),this.$bindWlanGroupNa=this.$(".bind-wlan-group-na"),this.noUserRows=this.$(".data-table-users").html(),this.noGuestRows=this.$(".data-table-guests").html(),this.noDownlinkRows=this.$(".data-table-downlinks").html(),this.noUplinkRows=this.$(".data-table-uplinks").html(),this.noWlanRows_ng=this.$(".data-table-wlans-ng").html(),this.noWlanRows_na=this.$(".data-table-wlans-na").html(),this.wLanOverrideModel=null,this.wLanOverrideRadio=null,this.$advAdoptForm.on("submit",this.onAdvAdoptFormSubmit),this.$networkForm.on("submit",i.proxy(function(e){e.preventDefault(),this.updateNetwork(this.$networkForm,"config_network")},this)),this.$radiosForm.on("submit",this.updateRadios),this.$shell.on("click",this.shell),this.$(".button-block").on("click",this.blockUser),this.$(".button-reconnect").on("click",this.reconnectUser),this.$uplinkDevice.on("click",this.displayUplinkDevice),this.$connectionType.on("change",i.proxy(function(e){var t=i(e.target).val();this.$networkForm.find(".connection-toggled").hide().filter(".connection-"+t).show()},this)).trigger("change"),this.$overrideForm.on("submit",this.onOverrideFormSubmit),this.$overrideForm.find('button[name="restore"]').on("click",this.onOverrideFormRestore),this.$overrideForm.find('button[name="cancel"]').on("click",this.onOverrideFormCancel),this.$("select.wlan-group-ng").on("change",this.updateWlan),this.$("select.wlan-group-na").on("change",this.updateWlan),this.$("select.radio-ht").on("change",this.updateChannelSelect),this._rendered.state()==="resolved"&&this._dependencies.state()=="resolved"?(this.configuredRadios=!1,this.populate()):this._rendered.state()==="pending"&&this._rendered.resolve(),this.stickit(this.model,this.bindings())),this},populate:function(){e.prototype.populate.call(this);if(this._dependencies&&this._dependencies.state()=="resolved"){var t=this.model.isConnected(),r=this.model.uplink(),i=r?r.type==="wireless":!1,s=!1;this.$el.removeClass("ap-uplink-wire ap-uplink-wireless ap-has-downlinks ap-needs-uplinks ap-ng-radio ap-na-radio"),this.model.get("adopted")&&(this.model.get("locating")?this.$btnLocate.addClass("locating"):this.$btnLocate.removeClass("locating")),this.setupAP(),n.each(this.model.uplinks(),function(e,t){t.configured&&(s=!0)}),this.model.get("vwireEnabled")&&(i||s||!t)&&(this.$el.addClass("ap-needs-uplinks"),t||this.setupUplinksTable()),this.position()}},setupAP:function(){var e=this,t=this.model.hasRadio("ng"),r=this.model.hasRadio("na"),o=n.size(this.model.downlinks())>0,u=this.model.uplink()||{},a=this.model.downlinks(),f,l,c,h,p=this.model.is11ac();u.name=="eth0"||u.name=="eth1"?(this.$el.addClass("ap-uplink-wire"),this.$(".uplink-type").text("("+s.G_Wire+")")):u.name=="ath0"&&(this.$el.addClass("ap-uplink-wireless"),this.$(".uplink-type").text("("+s.G_Wireless+")")),this.setupUplinksTable(),this.setupDownlinksTable(),this.systemInfo=this.app.collection("SystemInfos").at(0),this.currentCCode=this.systemInfo.get("cur_ccode"),this.currentCountryKey=this.currentCCode.key,this.currentCCode.ht40_ng||this.$('select[name="ng.ht"] option[value=40]').remove(),this.currentCCode.ht40_na||this.$('select[name="na.ht"] option[value=40]').remove(),(!this.currentCCode.channels_na_80||this.currentCCode.channels_na_80.length===0||!this.model.is11ac())&&this.$('select[name="na.ht"] option[value=80]').remove(),o&&this.$el.addClass("ap-has-downlinks"),t&&this.$el.addClass("ap-ng-radio"),r&&(this.$el.addClass("ap-na-radio"),p&&(this.$("fieldset.ap-na-configs legend").text(s.G_PropertiesRadio5G11AC),this.$("fieldset.ap-na-configs.fieldset-wlan legend").text(s.G_PropertiesWLANS5G11AC),this.$("div.radio-na").find("div.accordion-title").text(s.G_PropertiesRadio11AC))),this.configuredRadios||this.updateRadiosForm(),this.userTable(),this.guestTable(),this.$("select.radio-ht").each(function(){i(this).trigger("change")}),this.setupWlanPanel()},onAdvAdoptFormSubmit:function(e){e.preventDefault();var t=this,r=this.model,s=i(e.target).find("button");this.$advAdoptForm.find(".error").removeClass("error"),s.attr("disabled","disabled");var o=r.advanceAdopt({data:{ip:this.$advAdoptForm.find('input[name="ip"]').val(),port:this.$advAdoptForm.find('input[name="port"]').val(),username:this.$advAdoptForm.find('input[name="username"]').val(),password:this.$advAdoptForm.find('input[name="password"]').val(),url:this.$advAdoptForm.find('input[name="url"]').val()},success:function(e){e.meta.rc==="ok"?r.fetch({success:function(e,n,r){n.meta.rc==="ok"&&t.parent.property(e)},complete:function(){s.removeAttr("disabled")}}):(t.showErrorState(),s.removeAttr("disabled"))},error:function(){t.showErrorState(),s.removeAttr("disabled")}});!o&&this.model.validationError&&n.each(this.model.validationError,function(e,t){switch(t){case"username":case"password":this.$advAdoptForm.find('input[name="'+t+'"]').addClass("error"),s.removeAttr("disabled")}},this)},displayUplinkDevice:function(){var e=this.app.routers.devices.views.index,t=e.collection.getDeviceFromMac(this.model.uplinkDeviceMac()),r=t&&e.property(t),i=this.model.uplinkRemotePort();return i&&(r.$el.find(".switchPorts-anchor").click(),n.delay(function(){r.$el.find(".port-"+i).click()},100)),!1},userAndGuestColumns:function(){var e=this;return[{name:"hostname",label:s.G_Name,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:t.Cells.ModelCell.extend({callback:"name"}),callback:function(t){var n=e.app.routers.clients.views.index,r=n.collection.getClientFromMac(t.get("mac"));n.property(r)}},{name:"essid",label:s.G_Wlan,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:"string"},{name:"signal",label:s.G_DevicesSignal,editable:!1,cell:t.Cells.ModelCell.extend({callback:"signalWithDbm"})},{name:"tx_rate",label:s.G_DevicesTX,editable:!1,cell:t.Cells.ModelCell.extend({callback:"txRateInM"})}]},userTable:function(){if(!this.rendered)return!1;var e=this.app.collection("Clients"),t=e.where({ap_mac:this.model.get("mac"),is_guest:!1});this.grids.users?this.grids.users.collection.set(t):this.grids.users=this.grid(this.userAndGuestColumns(),new r.Collection(t),this.$(".data-table-users"),this.noUserRows)},guestTable:function(){if(!this.rendered)return!1;var e=this.app.collection("Clients"),t=e.where({ap_mac:this.model.get("mac"),is_guest:!0});this.grids.guests?this.grids.guests.collection.set(t):this.grids.guests=this.grid(this.userAndGuestColumns(),new r.Collection(t),this.$(".data-table-guests"),this.noGuestRows)},updateRadioTable:function(e){var t=this,r;n.each(e,function(e){r=t.model.getRadio(e.radio);if(r===undefined)return;for(var n in e)e.hasOwnProperty(n)&&(r[n]=e[n])})},updateRadiosForm:function(){var e=this,t,r;n.each(this.model.get("radio_table"),function(n){r=n.radio,t=e.$("fieldset.radio-"+r),t.find('select[name="'+r+'.ht"]').val(n.ht||(r=="ng"?20:40)).change(),t.find('select[name="'+r+'.tx_power_mode"]').val(n.tx_power_mode||"auto").change(),t.find('input[name="'+r+'.tx_power"]').val(n.tx_power||"0"),t.find('input[name="'+r+'.antenna_gain"]').val(n.antenna_gain||"6"),n.builtin_antenna===!0&&t.find("div.custom .antenna-gain").remove(),n.tx_power_mode==="custom"?t.find("div.custom").show():t.find("div.custom").hide(),this.configuredRadios=!0},this),this.configuredRadios&&this.renderSelects()},updateRadios:function(){var e=this,t=this.$radiosForm.serializeObject(),r={},i={},o=[],u=0,a=0,f="",l=!0,c={};return n.each(t,function(e,t){t.indexOf("ng.")===0?r[t.replace("ng.","")]=e:t.indexOf("na.")===0&&(i[t.replace("na.","")]=e)}),r&&this.model.hasRadio("ng")&&o.push(r),i&&this.model.hasRadio("na")&&o.push(i),n.each(o,function(t){f=t.radio;if(t.tx_power_mode==="custom"){u=e.model.get("radio_"+f).max_txpower||"0",a=e.model.get("radio_"+f).min_txpower||"0";if(t.tx_power>u||t.tx_power<a){(new h).open(s.localize(s.E_IncorrectNumberRange,(f==="ng"?s.G_2G:s.G_5G)+" "+s.G_PropertiesTransmitPower,a,u)),l=!1;return}}}),l?(this.model.update({data:{radio_table:o},success:function(t){t.meta.rc==="ok"?(c=n.find(t.data,function(t){return t.mac===e.model.get("mac")}),c!==undefined&&e.updateRadioTable(c.radio_table),e.updateRadiosForm(),e.showSavedState()):e.showErrorState()},error:function(){e.showErrorState()}}),!1):!1},shell:function(){return window.open("/shell?mac="+this.model.get("mac")+"&name="+this.model.name(),"_blank","toolbar=no,menubar=0,status=0,copyhistory=0,scrollbars=yes,resizable=1,location=0,Width=800,Height=600"),!1},blockUser:function(e){var t=i(e.target),n=t.data("mac"),r=this.app.collection("Clients"),s=r.getClientFromMac(n);s.block()},reconnectUser:function(){var e=i(event.target),t=e.data("mac"),n=this.app.collection("Clients"),r=n.getClientFromMac(t);r.reconnect()},updateChannelSelect:function(e){var t=i(e.target),r=t.val()||20,o=t.data("radio"),u=this.$('select[name="'+o+'.channel"]'),a=u.val()||(this.model.get("radio_"+o)||{}).channel,f=this.model.is11ac(),l;u.empty().append(i('<option value="auto" />').text(s.G_Auto)),n.each(this.currentCCode["channels_"+o+(r==20?"":"_"+r)],i.proxy(function(e){var t=i("<option />").attr("value",e).text(e);if(o=="na"){var r=i.inArray(e,this.currentCCode.channels_na_dfs)!==-1;if(r){if(f)return;t.text(function(e,t){return t+" (dfs)"})}t.attr("band",n.escape(e<52?1:e<149?2:3))}u.append(t)},this));if(o=="na")if(this.currentCountryKey=="US"||this.currentCountryKey=="CA")switch(this.model.get("model")){case"U5O":u.find("[band=1]").remove(),u.find("[band=2]").remove();break;case"U7P":u.find("[band=2]").remove()}l=u.find("option[value="+a+"]"),l.length||(l=u.find("option[value=auto]")),l.attr("selected",!0).trigger("change")},updateWlan:function(e,t){var n=i(e.target),r=n.data("radio"),s=n.val(),o=this.app.collection("WlanGroups"),u=o.findWhere({_id:s}),a=this.app.collection("Wlans"),f=a.findWhere({wlangroup_id:s}),l;n.data("wlangroup",u),l=this.$radiosForm.find(".radio-"+r);if(u&&u.get("roam_enabled")){l.find('select[name="'+r+'.channel"]').val(r=="ng"?u.get("roam_channel_ng"):u.get("roam_channel_na")).disable(),l.find('select[name="'+r+'.ht"]').disable(),this._rendered.state()==="resolved"&&this._dependencies.state()=="resolved"&&l.find('select[name="'+r+'.ht"]').val("20").change();try{l.find('select[name="'+r+'.channel"]').selectmenu("disable"),l.find('select[name="'+r+'.ht"]').selectmenu("disable")}catch(c){}}else{l.find('select[name="'+r+'.channel"]').enable(),l.find('select[name="'+r+'.ht"]').enable();try{l.find('select[name="'+r+'.channel"]').selectmenu("enable"),l.find('select[name="'+r+'.ht"]').selectmenu("enable")}catch(c){}}t||this.model.get("_id")&&this.model.get("wlangroup_id_"+r)!=s&&this.model.updateWlanGroup(r,{wait:!0,wlangroup_id:s,success:i.proxy(function(){this.showSavedState(),this.setupWlanTable(r)},this),error:i.proxy(function(){this.showErrorState()},this)})},setupWlanPanel:function(){var e=this,t=["ng","na"],r=this.app.collection("WlanGroups");n.each(t,function(t,s){var o=e.$("select.wlan-group-"+t);o.empty(),n.each(r.models,function(r,s){var u=i('<option value="'+n.escape(r.get("_id"))+'"></option>');if(r.get("roam_enabled")){if(t!=r.get("roam_radio"))return null;u.addClass("roam"),u.text(r.get("name")+" (Zero-Handoff)")}else u.text(r.get("name"));u.hasClass("roam")&&(e.$el.hasClass("ap-uplink-wireless")||i.inArray(e.model.get("model"),["U7E","U7O","U7Ev2"])!==-1)?u=null:o.append(u)});try{o.selectmenu("refresh")}catch(u){}var a=e.model.get("wlangroup_id_"+t);a&&(o.val(a).trigger("change",!0),e.setupWlanTable(t,a))})},fillWlanForm:function(e){this.$overrideForm.find(".error").removeClass("error"),this.$overrideForm.find(".row-error").remove();if(this.wLanOverrideModel){var t=this.wLanOverrideModel.get("_id"),n=this.wLanOverrideRadio,r=this.model.getOverride(t,n),i=this.wLanOverrideModel.toJSON();if(!r||e)r=this.wLanOverrideModel.toJSON();this.$overrideForm.find('input[name="name"]').val(r.hasOwnProperty("name")?r.name:i.name),this.$overrideForm.find('input[name="wlanEnabled"]').prop("checked",r.hasOwnProperty("enabled")?r.enabled===!0:i.enabled===!0),this.$overrideForm.find('input[name="vlanEnabled"]').prop("checked",r.hasOwnProperty("vlan_enabled")?r.vlan_enabled===!0:i.vlan_enabled===!0),this.$overrideForm.find('input[name="vlan"]').val(r.hasOwnProperty("vlan")?r.vlan>1?r.vlan:"":i.vlan>1?i.vlan:""),this.$overrideForm.find(".wpapsk").attr("display",r.hasOwnProperty("security")?r.security=="wpapsk"?"block":"none":i.security=="wpapsk"?"block":"none"),this.$overrideForm.find('input[name="passphrase"]').val(r.hasOwnProperty("x_passphrase")?r.x_passphrase:i.x_passphrase),this.wLanOverrideModel.get("security")=="wpapsk"?this.$overrideForm.find("div.row.wpapsk").show():this.$overrideForm.find("div.row.wpapsk").hide()}var s=this.$overrideForm.find('input[name="vlanEnabled"]'),o=this.$overrideForm.find('input[name="vlan"]');s.prop("checked")===!0?o.prop("disabled",!1):o.prop("disabled",!0),s.click(function(){s.is(":checked")?o.prop("disabled",!1):o.prop("disabled",!0)})},onOverrideFormSubmit:function(e){e&&e.preventDefault(),this.submitOverride(!1)},submitOverride:function(e){this.$overrideForm.find(".error").removeClass("error"),this.$overrideForm.find(".row-error").remove();if(!this.wLanOverrideModel)return;var t=this,r=this.model.get("wlan_overrides")||[],s=this.wLanOverrideModel.get("_id"),o=this.wLanOverrideRadio,u=this.model.getOverride(s,o)||this.wLanOverrideModel.toJSON(),a=!0;r=i.grep(r,function(e){return e!=u});if(!e){var f=["enabled","name","radio","vlan","vlan_enabled","wlan_id","x_passphrase"];u=n.pick(u,f),u.wlan_id=s,u.radio=o,u.name=this.$overrideForm.find('input[name="name"]').val(),u.enabled=this.$overrideForm.find('input[name="wlanEnabled"]').is(":checked");var l=u.vlan_enabled=this.$overrideForm.find('input[name="vlanEnabled"]').is(":checked");u.vlan=this.$overrideForm.find('input[name="vlan"]').val(),u.x_passphrase=this.$overrideForm.find('input[name="passphrase"]').val();var c=this.wLanOverrideModel;u.name!=c.get("name")?a=!1:delete u.name,u.enabled!=c.get("enabled")?a=!1:delete u.enabled,u.vlan_enabled!=c.get("vlan_enabled")?a=!1:delete u.vlan_enabled,u.vlan===""?l?a=!1:delete u.vlan:u.vlan!=c.get("vlan")?a=!1:delete u.vlan,u.x_passphrase!=c.get("x_passphrase")?a=!1:delete u.x_passphrase,a||r.push(u)}var h=this.model.save({wlan_overrides:r,wlanconf:this.app.collection("Wlans").findWhere({_id:s})},{wait:!0,data:{wlan_overrides:r},success:function(e,n){n.meta.rc==="ok"?(t.setupWlanTable(o),t.$el.removeClass("ap-show-override"),t.showSavedState()):t.showErrorState()},error:function(){t.showErrorState()}});!h&&this.model.validationError&&this.model.validationError.wlan_overrides&&n.each(this.model.validationError.wlan_overrides,function(e,t){n.each(e,function(e,t){var n;switch(t){case"name":case"vlan":n=this.$overrideForm.find('input[name="'+t+'"]').addClass("error");break;case"x_passphrase":n=this.$overrideForm.find('input[name="passphrase"]').addClass("error")}n.parents(".row").after(i('<div class="row row-error"></div>').text(e))},this)},this)},onOverrideFormRestore:function(e,t){return this.fillWlanForm(!0),!t&&this.submitOverride(!0),!1},onOverrideFormCancel:function(e){return this.onOverrideFormRestore(null,!0),this.$el.removeClass("ap-show-override"),!1},setupWlanTable:function(e,r){if(!this.rendered)return!1;var i=this,o=i.$("select.wlan-group-"+e),u=r||o.val(),a=this.app.collection("Wlans").filter(function(e){return e.get("wlangroup_id")==u}),l=this.$(".data-table-wlans-"+e);l.next(".WLANSDisabled").hide();if(!this.grids["wlan_"+e]){var c=[{name:"name",label:s.G_Name,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:t.Cells.ComplexCell.extend({className:"string-cell",formatter:{fromRaw:function(e){var t=e.get("enabled")||!1,n=e.get("name");return n},toRaw:function(e){return e}}})},{name:"essid",label:s.G_Overrides,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:t.Cells.ComplexCell.extend({className:"string-cell",formatter:{fromRaw:function(t){var n=[],r=i.model.getOverride(t.get("_id"),e);if(!r)return"";if(r.hasOwnProperty("enabled")&&r.enabled!=t.get("enabled")){if(r.enabled===!0)return s.G_Enabled;if(r.enabled===!1)return s.G_Disabled}r.hasOwnProperty("name")&&r.name!=t.get("name")&&n.push("SSID:"+r.name),r.hasOwnProperty("vlan_enabled")&&(t.get("vlan_enabled")&&!r.vlan_enabled?n.push("VLAN:"+s.G_Disabled):!t.get("vlan_enabled")&&r.vlan_enabled&&n.push("VLAN:"+s.G_Enabled));var o=t.get("vlan_enabled")===!0&&r.vlan_enabled!==!1||t.get("vlan_enabled")===!1&&r.vlan_enabled===!0;return r.hasOwnProperty("vlan")&&o&&t.get("vlan")!=r.vlan&&n.push("VLAN:"+r.vlan),r.hasOwnProperty("x_passphrase")&&t.get("security")=="wpapsk"&&r.x_passphrase!=t.get("x_passphrase")&&n.push("PSK"),n.join(", ")},toRaw:function(e){return e}}})},{name:"_id",label:s.G_Actions,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:t.Cells.ActionsCell.extend({actions:{override:{render:function(e){var t=i.app.collection("WlanGroups"),n=t.findWhere({_id:e.get("wlangroup_id")});return n&&n.get("roam_enabled")?!1:!0},callback:function(t){i.wLanOverrideModel=t,i.wLanOverrideRadio=e,i.$el.addClass("ap-show-override"),i.fillWlanForm()}}}})}];this.grids["wlan_"+e]=this.grid(c,new f(a),l,this["noWlanRows_"+e])}else this.grids["wlan_"+e].collection.reset(),this.grids["wlan_"+e].collection.set(a);n.size(a)?l.show():l.hide();try{o.selectmenu("refresh")}catch(h){}},setupUplinksTable:function(){if(!this.rendered)return!1;var e=this,u=this.app.routers.devices.views.index,a=this.model.uplinks(),f=this.$(".data-table-uplinks"),l=this.$(".data-table-uplinks-none");n.size(a)?(f.show(),l.hide()):(f.hide(),l.show());if(!this.grids.uplinks){var c=[{name:"mac",label:s.G_AP,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:t.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var t=u.collection.getDeviceFromMac(e.get("mac"));return t||(t=e),t.name()},toRaw:function(e){return e}}}),callback:function(e){var t=u.collection.getDeviceFromMac(e.get("mac"));t&&u.property(t)},title:"mac"},{name:"channel",label:s.G_ChannelAbbrev,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:"string"},{name:"rssi",label:s.G_DevicesSignal,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:t.Cells.ModelCell.extend({callback:"calcRssi"})},{name:"configured",label:s.G_Actions,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:t.Cells.ActionsCell.extend({actions:{select:{buttonClasses:"narrow",render:function(e){return!e.get("configured")},callback:function(t,n){var r=i(n.currentTarget);r.prop("disabled",!0),e.model.setVwireUplink({data:{uplink:t.get("mac"),mac:e.model.get("mac")},success:function(){(new h).open(s.G_DevicesTopologyChanged)},complete:function(){r.prop("disabled",!1)}})}},remove:{buttonClasses:"narrow",render:function(e){return e.get("configured")},callback:function(t,n){var r=i(n.currentTarget);r.prop("disabled",!0),e.model.unsetVwireUplink({data:{uplink:t.get("mac"),mac:e.model.get("mac")},success:function(){(new h).open(s.G_DevicesTopologyChanged)},complete:function(){r.prop("disabled",!1)}})}}}})}];this.grids.uplinks=this.grid(c,new r.Collection(a,{model:o}),this.$(".data-table-uplinks"),this.noUplinkRows)}else this.grids.uplinks.collection.set(a)},setupDownlinksTable:function(){if(!this.rendered)return!1;var e=this,n=this.app.routers.devices.views.index;if(!this.grids.downlinks){var u=[{name:"ap_mac",label:s.G_AP,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:t.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var t=n.collection.getDeviceFromMac(e.get("ap_mac"));return t||(t=e),t.name()},toRaw:function(e){return e}}}),callback:function(e){var t=e.get("ap_mac"),r=n.collection.getDeviceFromMac(t);n.property(r)},title:"ap_mac"},{name:"rssi",label:s.G_DevicesSignal,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:t.Cells.ModelCell.extend({callback:"calcRssi"})},{name:"_id",label:s.G_Actions,editable:!1,sortable:!1,headerCell:t.Headers.noSortHeader,cell:t.Cells.ActionsCell.extend({actions:{remove:{buttonClasses:"narrow",callback:function(t,n){var r=i(n.currentTarget);r.prop("disabled",!0),e.model.unsetVwireUplink({data:{mac:t.get("ap_mac"),uplink:e.model.get("mac")},success:function(){(new h).open(s.G_DevicesTopologyChanged)},complete:function(){r.prop("disabled",!1)}})}}}})}];this.grids.downlinks=this.grid(u,new r.Collection(this.model.downlinks(),{model:o}),this.$(".data-table-downlinks"),this.noDownlinkRows)}else this.grids.downlinks.collection.set(this.model.downlinks())},remove:function(){this.onOverrideFormCancel(),this.stopListening(this.app.collection("Wlans"),"add remove destroy change",this.setupWlanPanel),this.stopListening(this.model,"change:radio_na change:radio_ng"),this.$advAdoptForm.off("submit"),this.$networkForm.off("submit"),this.$radiosForm.off("submit"),this.$shell.off("click"),this.$(".button-block").off("click"),this.$(".button-reconnect").off("click"),this.$uplinkDevice.off("click"),this.$connectionType.off("change"),this.$overrideForm.off("submit"),this.$overrideForm.find('button[name="restore"]').off("click"),this.$overrideForm.find('button[name="cancel"]').off("click"),this.$("select.wlan-group-ng").off("change"),this.$("select.wlan-group-na").off("change"),this.$("select.radio-ht").off("change"),this.unstickit(this.model),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("text!includes/gateway/gatewayPortForwardFormTemplate.html",[],function(){return'<form>\n    <fieldset class="fieldset">\n        <div class="row">\n            <label class="label inline"><%- msg.G_Name %></label>\n            <input type="text" class="input inline" name="name" value="" />\n        </div>\n        <div class="row source">\n            <label class="label inline"><%- msg.G_PortForwardSource %></label>\n            \n            <div class="radio-group left">\n                <label><input type="radio" name="src_type" value="any" /> <%- msg.G_PropertiesPortFwdSrcAnywhere %></label>\n                <label><input type="radio" name="src_type" value="limited" /> <%- msg.G_PropertiesPortFwdSrcLimited %></label>\n            </div>\n            \n            <input type="text" class="input inline" name="src" value="" />\n        </div>\n        <div class="row">\n            <label class="label inline"><%- msg.G_Port %></label>\n            <input type="text" class="input inline" name="dst_port" value="" />\n            <label class="tip inline">(1000,1002-1004,...)\n        </div>\n        <div class="row">\n            <label class="label inline"><%- msg.G_PortForwardDestIp %></label>\n            <input type="text" class="input inline" name="fwd" value="" />\n        </div>\n        <div class="row">\n            <label class="label inline"><%- msg.G_PortForwardDestPort %></label>\n            <input type="text" class="input inline" name="fwd_port" value="" />\n        </div>\n    </fieldset>\n    \n    <fieldset class="fieldset">\n        <legend class="legend"><%- msg.G_SettingsAdvancedOpts %></legend>\n        \n        <div class="row">\n            <label class="label inline"><%- msg.G_PropertiesProtocol %></label>\n            \n            <div class="radio-group">\n                <label><input type="radio" name="proto" value="tcp_udp" /> <%- msg.G_Both %></label>\n                <label><input type="radio" name="proto" value="tcp" /> <%- msg.G_PropertiesTcp %></label>\n                <label><input type="radio" name="proto" value="udp" /> <%- msg.G_PropertiesUdp %></label>\n            </div>\n        </div>\n    </fieldset>\n    \n    <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n    <button class="button" name="cancel" value="Cancel" type="button"><%- msg.G_Cancel %></button>\n</form>'}),define("unifi/view/gateway/PortForwardFormView",["unifi/view/app/FormView","jquery","underscore","msg/Msg","text!includes/gateway/gatewayPortForwardFormTemplate.html"],function(e,t,n,r,i){"use strict";return e.extend({_templateId:n.template(i,{msg:r}),_prevalidate:{name:{input:"text"},src:{input:"text"},dst_port:{input:"text"},fwd:{input:"text"},fwd_port:{input:"text"}},events:{"click button[name=cancel]":"remove"},render:function(){var t=this.rendered;e.prototype.render.call(this);var n=this.$container.parents(".portfwd-config");n.addClass("show-form");if(!t){this.on("remove",function(){n.removeClass("show-form")});var r=this.$("input[name=fwd_port]"),i=this.$("input[name=dst_port]");this.$("input[name=dst_port]").on("change",function(e){var t=i.val().indexOf("-")>=0||i.val().indexOf(",")>=0;r.val(i.val()),r.enable(),t&&t&&r.disable()}),this.$("input[name=fwd_port]").on("change",function(e){var t=r.val().indexOf("-")>=0||r.val().indexOf(",")>=0;r.enable(),t&&(i.val(r.val()),t&&r.disable())}),this.app.isReadOnly||this.prevalidator()}},populate:function(){var e=this.model.get("src"),t=!e||e=="any";this.model&&(this.$el.find("input[name=name]").val(this.model.get("name")),this.$el.find("input[name=src_type][value="+(t?"any":"limited")+"]").prop("checked",!0),this.$el.find("input[name=src]").val(t?"":e),this.$el.find("input[name=dst_port]").val(this.model.get("dst_port")),this.$el.find("input[name=fwd]").val(this.model.get("fwd")),this.$el.find("input[name=fwd_port]").val(this.model.get("fwd_port")),this.$el.find("input[name=proto][value="+(this.model.get("proto")||"tcp_udp")+"]").prop("checked",!0))},gather:function(){var e=this.$el.find("input[name=src]").val(),t=this.$el.find("input[name=src_type]:checked").val()=="any";return{name:this.$el.find("input[name=name]").val(),src:e&&!t?e:"any",dst_port:this.$el.find("input[name=dst_port]").val(),fwd:this.$el.find("input[name=fwd]").val(),fwd_port:this.$el.find("input[name=fwd_port]").val(),proto:this.$el.find("input[name=proto]:checked").val()}},success:function(){this.remove()},error:function(e,t){this.options.app.views.app.flash("error","Error",r.apiError(t))},remove:function(){this.$("input[name=dst_port]").off(),e.prototype.remove.apply(this,arguments)}})}),define("text!includes/gateway/gatewayDynamicDNSFormTemplate.html",[],function(){return'<form>\n    <fieldset class="fieldset">\n        <div class="row">\n            <label class="label inline"><%- msg.G_PropertiesDDNSService %></label>\n            <select name="service" class="input inline">\n                <option value="afraid" selected="selected"><%- msg.G_PropertiesDDNSServiceAfraid %></option>\n                <option value="dnspark"><%- msg.G_PropertiesDDNSServiceDnspark %></option>\n                <option value="dslreports"><%- msg.G_PropertiesDDNSServiceDslreports %></option>\n                <option value="dyndns"><%- msg.G_PropertiesDDNSServiceDyndns %></option>\n                <option value="easydns"><%- msg.G_PropertiesDDNSServiceEasydns %></option>\n                <option value="namecheap"><%- msg.G_PropertiesDDNSServiceNamecheap %></option>\n                <option value="sitelutions"><%- msg.G_PropertiesDDNSServiceSitelutions %></option>\n                <option value="zoneedit"><%- msg.G_PropertiesDDNSServiceZoneedit %></option>\n            </select>\n        </div>\n        <div class="row">\n            <label class="label inline"><%- msg.G_PropertiesDDNSHostname %></label>\n            <input type="text" class="input inline" name="host_name" value="" />\n        </div>\n        <div class="row">\n            <label class="label inline"><%- msg.G_PropertiesDDNSUsername %></label>\n            <input type="text" class="input inline" name="login" value="" />\n        </div>\n        <div class="row">\n            <label class="label inline"><%- msg.G_PropertiesDDNSPassword %></label>\n            <input type="password" class="input inline" name="x_password" value="" />\n        </div>\n        <div class="row">\n            <label class="label inline"><%- msg.G_PropertiesDDNSServer %></label>\n            <input type="text" class="input inline" name="server" value="" />\n        </div>\n    </fieldset>\n\n    <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n    <button class="button" name="cancel" value="Cancel" type="button"><%- msg.G_Cancel %></button>\n</form>\n'}),define("unifi/view/gateway/DynamicDNSFormView",["unifi/view/app/FormView","jquery","underscore","msg/Msg","text!includes/gateway/gatewayDynamicDNSFormTemplate.html"],function(e,t,n,r,i){"use strict";return e.extend({_templateId:n.template(i,{msg:r}),_prevalidate:{login:{input:"text"},x_password:{input:"password"},host_name:{input:"text"},server:{input:"text"}},events:{"click button[name=cancel]":"remove"},render:function(){var t=this.rendered;e.prototype.render.call(this);var n=this.$container.parents(".dynamicdns-config");n.addClass("show-form"),this.$el.find("input[name=x_password-text]").addClass("input inline"),t||(this.on("remove",function(){n.removeClass("show-form")}),this.app.isReadOnly||this.prevalidator())},populate:function(){this.model&&(this.$el.find("select[name=service]").val(this.model.get("service")||"afraid").trigger("change"),this.$el.find("input[name=host_name]").val(this.model.get("host_name")),this.$el.find("input[name=login]").val(this.model.get("login")),this.$el.find("input[name=x_password]").val(this.model.get("x_password")),this.$el.find("input[name=server]").val(this.model.get("server")))},gather:function(){var e={service:this.$el.find("select[name=service] option:selected").val(),host_name:this.$el.find("input[name=host_name]").val(),login:this.$el.find("input[name=login]").val(),x_password:this.$el.find("input[name=x_password]").val(),server:this.$el.find("input[name=server]").val()};return e},success:function(){this.remove()},error:function(e,t){this.options.app.views.app.flash("error","Error",r.apiError(t))},remove:function(){e.prototype.remove.apply(this,arguments)}})}),define("unifi/model/PortForward",["unifi/model/Model","underscore","backbone","msg/Msg"],function(e,t,n,r){"use strict";return e.extend({validate:function(e,n){var i={},s=n?n.partial:null;(!s||s=="name")&&e.name&&(this.validator.name(e.name)||(i.name=r.localize(r.E_InvalidName,r.G_Name))),(!s||s=="src")&&e.src&&e.src!="any"&&!this.validator.ip(e.src)&&!this.validator.iprange(e.src)&&!this.validator.subnet(e.src)&&(e.src.charAt(0)!=="!"||!(this.validator.ip(e.src.substring(1))||this.validator.iprange(e.src.substring(1))||this.validator.subnet(e.src.substring(1))))&&(i.src=r.localize(r.E_IncorrectIPRangeSubnet,r.G_PortForwardSource)),(!s||s=="dst_port")&&e.dst_port&&(this.validator.rangeList(e.dst_port,",-",15,1,65535)||(i.dst_port=r.localize(r.E_IncorrectNumberRangeList,r.G_Port,15,1,65535))),(!s||s=="fwd")&&e.fwd&&(this.validator.ip(e.fwd)||(i.fwd=r.localize(r.E_IncorrectIPAddress,r.G_PortForwardDestIp))),(!s||s=="fwd_port")&&e.fwd_port&&(this.validator.rangeList(e.fwd_port,",-",15,1,65535)||(i.fwd_port=r.localize(r.E_IncorrectNumberRangeList,r.G_PortForwardDestPort,15,1,65535)));if(t.size(i))return i},sync:function(e,t,r){r=r||{};switch(e){case"create":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/add/portforward",r.type="POST";break;case"update":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/upd/portforward/"+t.id,r.type="POST",r.data=JSON.stringify(t.toJSON({exclude:["_id","site_id"]}));break;case"delete":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/del/portforward/"+t.id,r.type="POST"}return n.sync.call(this,e,t,r)}})}),define("unifi/collection/PortForward",["unifi/collection/Collection","underscore","unifi/model/PortForward"],function(e,t,n){"use strict";return e.extend({model:n,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/list/portforward"}})}),define("unifi/model/DynamicDNS",["unifi/model/Model","underscore","backbone","msg/Msg"],function(e,t,n,r){"use strict";return e.extend({validate:function(e,n){var i={},s=n?n.partial:null;if(!s||s=="login")e.login||(i.login=r.localize(r.E_CannotBeEmpty,r.G_PropertiesDDNSUsername));if(!s||s=="x_password")e.x_password||(i.x_password=r.localize(r.E_CannotBeEmpty,r.G_PropertiesDDNSPassword));if(!s||s=="host_name")e.host_name||(i.host_name=r.localize(r.E_CannotBeEmpty,r.G_PropertiesDDNSHostname));if(t.size(i))return i},service:function(){return this.get("service")},hostname:function(){return this.get("host_name")},server:function(){return this.get("server")},username:function(){return this.get("login")},sync:function(e,t,r){r=r||{};switch(e){case"create":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/add/dynamicdns",r.type="POST";break;case"update":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/upd/dynamicdns/"+t.id,r.type="POST",r.data=JSON.stringify(t.toJSON({exclude:["_id","site_id"]}));break;case"delete":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/del/dynamicdns/"+t.id,r.type="POST"}return n.sync.call(this,e,t,r)}})}),define("unifi/collection/DynamicDNS",["unifi/collection/Collection","underscore","unifi/model/DynamicDNS"],function(e,t,n){"use strict";return e.extend({model:n,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/list/dynamicdns"}})}),define("text!includes/gateway/gatewayPropertiesTemplate.html",[],function(){return'<div class="accordion-header">\n    <div class="accordion-title">\n        <span class="device-icons access-point half"></span>\n        <span class="title-text"><%- name() %></span>\n        <div class="ubnt-icon-arrow-down sidebar-icons minmax minimize"></div>\n    </div>\n    <div class="right">\n        <div class="ubnt-icon-new-window sidebar-icons detach" title="Detach"></div>\n        <div class="ubnt-icon-close sidebar-icons remove" title="Close"></div>\n    </div>\n</div>\n<div class="property-content">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n\n    <%= diagram %>\n\n    <div class="status-alert status-success"><span class="ubnt-icon-check checkmark"></span><%- msg.G_Saved %></div>\n    <div class="status-alert status-error"><span class="ubnt-icon-warning alert"></span><%- msg.E_Error %></div>\n\n    <div class="tabs">\n        <ul>\n            <li class="tab-nav-list-item">\n                <a class="tab-button" href="#gatewayDetails<%- _id %>"><%- msg.G_PropertiesDetails %></a>\n            </li>\n            <li class="tab-nav-list-item">\n                <a class="tab-button" href="#gatewayNetworks<%- _id %>"><%- msg.G_PropertiesNetworks %></a>\n            </li>\n            <li class="tab-nav-list-item ap-configs">\n                <a class="tab-button" href="#gatewayConfig<%- _id %>"><%- msg.G_PropertiesConfiguration %></a>\n            </li>\n        </ul>\n        <div class="properties-container overflow">\n            <div id="gatewayDetails<%- _id %>" class="gateway-details tab-content">\n                <div class="accordion">\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_DevicesOverview %></div>\n                    </div>\n                    <div class="basic-overview">\n                        <table>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesMACAddress %></td>\n                                <td class="column-value"><%- get(\'mac\') %></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_DevicesModel %></td>\n                                <td class="column-value"><%- apModel() %></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Version %></td>\n                                <td class="column-value bind-version"></td>\n                            </tr>\n                        </table>\n                        <hr />\n                        <table>\n                            <tr class="table-row ip-address">\n                                <td class="column-name"><%- msg.G_PropertiesLANIPAddress %></td>\n                                <td class="column-value bind-lan-ip"></td>\n                            </tr>\n                            <tr class="table-row uptime">\n                                <td class="column-name"><%- msg.G_Uptime %></td>\n                                <td class="column-value bind-uptime"></td>\n                            </tr>\n                        </table>\n                    </div>\n                    <div class="accordion-header gw-wan-details">\n                        <div class="accordion-title"><%- msg.G_DevicesWan %></div>\n                    </div>\n                    <div class="devices-wan gw-wan-details">\n                        <table class="side-by-side">\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_IPAddress %></td>\n                                <td class="column-value bind-wan-ip"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Speed %></td>\n                                <td class="column-value bind-uplink-speed"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesDuplex %></td>\n                                <td class="column-value bind-uplink-duplex"></td>\n                            </tr>\n                        </table>\n\n                        <table class="side-by-side">\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesDownPktsBytes %></td>\n                                <td class="column-value bind-uplink-down-packets"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesUpPktsBytes %></td>\n                                <td class="column-value bind-uplink-up-packets"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesDownActivity %></td>\n                                <td class="column-value bind-uplink-down-rate"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesUpActivity %></td>\n                                <td class="column-value bind-uplink-up-rate"></td>\n                            </tr>\n                        </table>\n                    </div>\n                    <div class="accordion-header gw-adv-adopt">\n                        <div class="accordion-title"><%- msg.G_PropertiesAdvancedOpts %></div>\n                    </div>\n                    <div class="gw-adv-adopt">\n                        <form action="" class="advAdoptForm gw-adv-adopt">\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_IP %></label>\n                                <input class="input inline medium bind-adopt-ip" type="text" value="" name="ip" />\n                                <span class="colon">:</span>\n                                <input class="input inline small" type="text" value="22" name="port" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_UN %></label>\n                                <input class="input inline" type="text" value="" name="username" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_PW %></label>\n                                <input class="input inline" type="password" value="" name="password" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_PropertiesInformURL %></label>\n                                <input class="input inline bind-adopt-url" type="text" value="" name="url" />\n                            </div>\n                            <button class="button is-admin" type="submit"><%- msg.G_Adopt %></button>\n                        </form>\n                    </div>\n                    <div class="accordion-header gw-voip-details">\n                        <div class="accordion-title"><%- msg.G_DevicesVoip %></div>\n                    </div>\n                    <div class="devices-voice gw-voip-details">\n                        <table>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesNumPhones %></td>\n                                <td class="column-value bind-num-phones"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesNumCalls %></td>\n                                <td class="column-value bind-num-calls"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesActiveCalls %></td>\n                                <td class="column-value bind-active-calls"></td>\n                            </tr>\n                        </table>\n                    </div>\n                </div>\n            </div>\n            <div id="gatewayNetworks<%- _id %>" class="tab-content minigrid">\n                <div class="data-table data-table-networks bind-networks"><%- msg.G_PropertiesNoNetworksConfigured %></div>\n            </div>\n            <div id="gatewayConfig<%- _id %>" class="tab-content ap-configs">\n                <div class="accordion">\n                    <div class="accordion-header ap-configs">\n                        <div class="accordion-title"><%- msg.G_Config %></div>\n                    </div>\n                    <div class="ap-configs">\n                        <form action="" class="aliasForm">\n                            <div class="row">\n                                <label for="aliasName<%- _id %>" class="label"><%- msg.G_PropertiesAlias %></label>\n                                <input name="name" id="aliasName<%- _id %>" type="text" class="input" value="<%- get(\'name\') %>" />\n                            </div>\n                            <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n                        </form>\n                    </div>\n                    <div class="accordion-header wan-config">\n                        <div class="accordion-title"><%- msg.G_DevicesWan %></div>\n                    </div>\n                    <div class="wan-config">\n                        <form class="wanForm bind-wan">\n                            <div class="clearfix">\n                                <div class="row">\n                                   <label for="connectionnType<%- _id %>" class="label inline"><%- msg.G_PropertiesConnectionType %></label>\n                                   <select name="connectionType" class="connection-type" id="connectionnType<%- _id %>">\n                                       <option value="dhcp"><%- msg.G_PropertiesUsingDHCP %></option>\n                                       <option value="static"><%- msg.G_PropertiesStaticIP %></option>\n                                       <option value="pppoe"><%- msg.G_PropertiesPPPoE %></option>\n                                   </select>\n                                </div>\n\n                                <div class="side-by-side">\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_IPAddress %></label>\n                                        <input type="text" class="input inline" name="ip" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesSubnetMask %></label>\n                                        <input type="text" class="input inline" name="netmask" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-static">\n                                        <label for="gateway<%- _id %>" class="label inline"><%- msg.G_PropertiesRouter %></label>\n                                        <input type="text" class="input inline" name="gateway" id="gateway<%- _id %>" value="" />\n                                    </div>\n\n                                    <div class="row connection-toggled connection-pppoe">\n                                        <label class="label inline"><%- msg.G_UN %></label>\n                                        <input type="text" class="input inline" name="username" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-pppoe">\n                                        <label class="label inline"><%- msg.G_PW %></label>\n                                        <input type="text" class="input inline" name="x_password" value="" />\n                                    </div>\n                                </div>\n\n                                <div class="side-by-side">\n                                    <div class="row">\n                                        <label class="label inline"><%- msg.G_PropertiesPreferredDNS %></label>\n                                        <input type="text" class="input inline" name="dns1" value="" />\n                                    </div>\n                                    <div class="row">\n                                        <label class="label inline"><%- msg.G_PropertiesAlternateDNS %></label>\n                                        <input type="text" class="input inline" name="dns2" value="" />\n                                    </div>\n                                </div>\n                            </div>\n\n                            <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n                        </form>\n                    </div>\n                    <div class="accordion-header portfwd-config">\n                        <div class="accordion-title"><%- msg.G_PropertiesPortForward %></div>\n                    </div>\n                    <div class="portfwd-config">\n                        <button class="button portfwd-create is-admin" name="create">\n                            <span class="ui-button-icon-primary ubnt-icon-plus"></span>\n                            <span class="nav-text"><%- msg.G_Create %></span>\n                        </button>\n\n                        <div class="portfwd-list">\n                            <div class="data-table data-table-portfwd data-table-fit"><%- msg.G_PropertiesNoPortForwardingConfigured %></div>\n                        </div>\n\n                        <div class="portfwd-form"></div>\n                    </div>\n                    <div class="accordion-header dynamicdns-config">\n                        <div class="accordion-title"><%- msg.G_PropertiesDynamicDNS %></div>\n                    </div>\n                    <div class="dynamicdns-config">\n                        <button class="button dynamicdns-create is-admin" name="create">\n                            <span class="ui-button-icon-primary ubnt-icon-plus"></span>\n                            <span class="nav-text"><%- msg.G_Create %></span>\n                        </button>\n                        <div class="dynamicdns-list">\n                            <div class="data-table data-table-dynamicdns data-table-fit"><%- msg.G_PropertiesNoDynamicDNSConfigured %></div>\n                        </div>\n                        <div class="dynamicdns-form"></div>\n                    </div>\n                    <div class="accordion-header is-admin">\n                        <div class="accordion-title"><%- msg.G_PropertiesForgetGateway %></div>\n                    </div>\n                    <div class="is-admin">\n                        <div class="row">\n                            <%- msg.G_PropertiesForgetGatewayTxt %>\n                        </div>\n                        <button class="button forget left">\n                            <span class="ui-button-icon-primary ubnt-icon-forget-this-network"></span>\n                            <span class="nav-text"><%- msg.G_PropertiesForget %></span>\n                        </button>\n                        <div class="left">\n                            <select name="move" class="move-dropdown" data-myposition="left bottom" data-atposition="left top"></select>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </div>\n        <div class="dialog-controls is-admin clearfix">\n            <button class="button button-locate left">\n                <span class="ui-button-icon-primary ubnt-icon-location sidebar-icons locate"></span>\n                <span class="nav-text"><%- msg.G_Locate %></span>\n            </button>\n            <button class="button button-restart left">\n                <span class="ui-button-icon-primary ubnt-icon-rotate sidebar-icons restart"></span>\n                <span class="nav-text"><%- msg.G_Restart %></span>\n            </button>\n            <button class="button button-update left">\n                <span class="ui-button-icon-primary ubnt-icon-download sidebar-icons update"></span>\n                <span class="nav-text"><%- msg.G_Upgrade %></span>\n            </button>\n            <button class="button button-adopt left">\n                <span class="ui-button-icon-primary ubnt-icon-plus sidebar-icons adopt"></span>\n                <span class="nav-text"><%- msg.G_Adopt %></span>\n            </button>\n        </div>\n    </div>\n</div>'}),define("text!includes/gateway/gatewayDiagramUGW3Template.html",[],function(){return'<div class="diagram gateway port3 bind-state">\n    <div class="port wan"><div class="status"></div><div class="name"><%- msg.G_DevicesWan %></div></div>\n    <div class="port lan"><div class="status"></div><div class="name"><%- msg.G_DevicesLan %></div></div>\n    <div class="port voip"><div class="status"></div><div class="name"><%- msg.G_DevicesVoip %></div></div>\n</div>'}),define("text!includes/gateway/gatewayDiagramUGW8Template.html",[],function(){return'<div class="diagram gateway port8 bind-state">\n    <div class="port lan lan1"><div class="status"></div><div class="name"><%- msg.G_DevicesLan %>1</div></div>\n    <div class="port lan lan2"><div class="status"></div><div class="name"><%- msg.G_DevicesLan %>2</div></div>\n    <div class="port lan lan3"><div class="status"></div><div class="name"><%- msg.G_DevicesLan %>3</div></div>\n    <div class="port lan lan4"><div class="status"></div><div class="name"><%- msg.G_DevicesLan %>4</div></div>\n    <div class="port lan lan5"><div class="status"></div><div class="name"><%- msg.G_DevicesLan %>5</div></div>\n    <div class="port voip"><div class="status"></div><div class="name"><%- msg.G_DevicesVoip %></div></div>\n    <div class="port wan wan1"><div class="status"></div><div class="name"><%- msg.G_DevicesWan %>1</div></div>\n    <div class="port wan wan2"><div class="status"></div><div class="name"><%- msg.G_DevicesWan %>2</div></div>\n</div>'}),define("unifi/view/gateway/PropertyView",["unifi/view/devices/PropertyView","unifi/view/gateway/PortForwardFormView","unifi/view/gateway/DynamicDNSFormView","ubnt/backgrid","libs/backgrid","underscore","backbone","jquery","msg/Msg","unifi/collection/PortForward","unifi/collection/DynamicDNS","text!includes/gateway/gatewayPropertiesTemplate.html","text!includes/gateway/gatewayDiagramUGW3Template.html","text!includes/gateway/gatewayDiagramUGW8Template.html","ubnt/view/dialogs/AlertDialogView","ubnt/view/dialogs/ConfirmDialogView","stickit"],function(e,t,n,r,i,s,o,u,a,f,l,c,h,p,d,v){"use strict";return e.extend({templateId:c,diagramTemplate:null,bindings:function(){return s.extend({},e.prototype.bindings.call(this),{".bind-wan-ip":{observe:"uplink",onGet:function(e){this.$bindWanIp.text(e.ip),this.$bindUplinkSpeed.text(this.model.uplinkSpeed()),this.$bindUplinkDuplex.text(this.model.uplinkDuplex()),this.$bindUplinkDownPackets.text(this.model.uplinkDownPackets()),this.$bindUplinkUpPackets.text(this.model.uplinkUpPackets()),this.$bindUplinkDownRate.text(this.model.uplinkActivityDown()),this.$bindUplinkUpRate.text(this.model.uplinkActivityUp())}},".bind-wan":{observe:"config_network_wan",onGet:function(e){this.populateNetworkForm(this.$wanForm,e)}},".bind-networks":{observe:"network_table",onGet:function(e){this.networkTable()}},".bind-state":{observe:["uplink","port_table"],onGet:function(){this.populateStates()}},".bind-lan-ip":{observe:"port_table",onGet:function(e){var t=s.findWhere(e,{name:"lan"});t&&this.$bindLanIp.text(t.ip||"")}}})},initialize:function(t){switch(this.model.get("model")){case"UGW3":this.diagramTemplate=s.template(h,{msg:a});break;case"UGW8":this.diagramTemplate=s.template(p,{msg:a})}e.prototype.initialize.call(this,t)},dependencies:function(){var e={PortForward:f,DynamicDNS:l},t=[],n={},r=this;s.each(e,function(e,r){t.push(n[r]=u.Deferred())},this),u.when.apply(u,t).then(function(){r._dependencies.resolve()},function(){r._dependencies.reject()}),s.each(e,function(e,t){this.app.collection(t,{fetch:{reload:!1,deferred:n[t]}},e)},this)},render:function(t){var n=this.rendered;return e.prototype.render.call(this,t),n||(this.forms={},this.listenTo(this.app.collection("PortForward"),"add remove",this.portForwardTable),this.listenTo(this.app.collection("DynamicDNS"),"add remove",this.dynamicDNSTable),this.noPortFwdRows=this.$(".data-table-portfwd").html(),this.noDynamicDNSRows=this.$(".data-table-dynamicdns").html(),this.noNetworkRows=this.$(".data-table-networks").html(),this.$advAdoptForm=this.$(".advAdoptForm"),this.$gatewayDetails=this.$(".gateway-details"),this.$gatewayConfig=this.$(".ap-configs"),this.$wanForm=this.$(".wanForm"),this.$connectionType=this.$wanForm.find("select[name=connectionType]"),this.$bindWanIp=this.$(".bind-wan-ip"),this.$bindUplinkSpeed=this.$(".bind-uplink-speed"),this.$bindUplinkDuplex=this.$(".bind-uplink-duplex"),this.$bindUplinkDownPackets=this.$(".bind-uplink-down-packets"),this.$bindUplinkUpPackets=this.$(".bind-uplink-up-packets"),this.$bindUplinkDownRate=this.$(".bind-uplink-down-rate"),this.$bindUplinkUpRate=this.$(".bind-uplink-up-rate"),this.$bindLanIp=this.$(".bind-lan-ip"),this.$bindNumPhones=this.$(".bind-num-phones"),this.$bindNumCalls=this.$(".bind-num-calls"),this.$bindActiveCalls=this.$(".bind-active-calls"),this.$portFwdCreate=this.$('.portfwd-config button[name="create"]'),this.$portFwdList=this.$(".portfwd-list"),this.$portFwdForm=this.$(".portfwd-form"),this.$advAdoptForm.on("submit",this.onAdvAdoptFormSubmit),this.$portFwdCreate.on("click",u.proxy(function(){this.portForwardForm()},this)),this.$portFwdForm.hide(),this.$dynamicDNSCreate=this.$('.dynamicdns-config button[name="create"]'),this.$dynamicDNSList=this.$(".dynamicdns-list"),this.$dynamicDNSForm=this.$(".dynamicdns-form"),this.$dynamicDNSCreate.on("click",u.proxy(function(){this.dynamicDNSForm()},this)),this.$dynamicDNSForm.hide(),this.$connectionType.on("change",u.proxy(function(e){var t=u(e.target).val();this.$wanForm.find(".connection-toggled").hide().filter(".connection-"+t).show()},this)).trigger("change"),this.$wanForm.on("submit",u.proxy(function(e){e.preventDefault(),this.updateNetwork(this.$wanForm,"config_network_wan")},this)),this.renderDiagram(),this._rendered.state()==="resolved"&&this._dependencies.state()=="resolved"?this.populate():this._rendered.state()==="pending"&&this._rendered.resolve(),this.stickit(this.model,this.bindings())),this.populateStates(),this.networkTable(),this.portForwardTable(),this.dynamicDNSTable(),n||this.detach(),this.options.options&&this.options.options.port=="lan"&&this.$diagramLan.click(),this},renderDiagram:function(){this.$diagram=this.$(".diagram"),this.$diagramWan=this.$(".diagram .port.wan"),this.$diagramLan=this.$(".diagram .port.lan"),this.$diagramVoice=this.$(".diagram .port.voice"),this.$diagramWan.on("click",u.proxy(function(){var e=s.findWhere(this.model.get("port_table"),{name:"wan"}),t=e&&e.up?e.up:!1;this.$tabs.tabs("option","active",0),t&&this.$gatewayDetails.find(".accordion").accordion("option","active",1)},this)),this.$diagramLan.on("click",u.proxy(function(){this.$tabs.tabs("option","active",1)},this)),this.$diagramVoice.on("click",u.proxy(function(){this.$el.hasClass("gw-has-voice")&&(this.$tabs.tabs("option","active",0),this.$gatewayDetails.find(".accordion").accordion("option","active",2))},this))},args:function(){return{_id:this.id,diagram:this.diagramTemplate,msg:a}},onAdvAdoptFormSubmit:function(e){e.preventDefault();var t=this,n=this.model,r=u(e.target).find("button");this.$advAdoptForm.find(".error").removeClass("error"),r.attr("disabled","disabled");var i=n.advanceAdopt({data:{ip:this.$advAdoptForm.find('input[name="ip"]').val(),port:this.$advAdoptForm.find('input[name="port"]').val(),username:this.$advAdoptForm.find('input[name="username"]').val(),password:this.$advAdoptForm.find('input[name="password"]').val(),url:this.$advAdoptForm.find('input[name="url"]').val()},success:function(e){e.meta.rc==="ok"?n.fetch({success:function(e,n,r){n.meta.rc==="ok"&&t.parent.property(e)},complete:function(){r.removeAttr("disabled")}}):(t.showErrorState(),r.removeAttr("disabled"))},error:function(){t.showErrorState(),r.removeAttr("disabled")}});!i&&this.model.validationError&&s.each(this.model.validationError,function(e,t){switch(t){case"username":case"password":this.$advAdoptForm.find('input[name="'+t+'"]').addClass("error"),r.removeAttr("disabled")}},this)},populate:function(){this.$el.addClass("gateway-properties"),e.prototype.populate.call(this),this._dependencies&&this._dependencies.state()=="resolved"&&this.position()},populateStates:function(){this.$el.removeClass("gw-has-wan gw-has-lan gw-has-voice"),s.each(this.model.get("port_table")||[],u.proxy(function(e){var t=this.$diagram.find(".port."+e.name);t.removeClass("shutdown up green orange"),e.enable||t.addClass("shutdown"),e.up&&(this.$el.addClass("gw-has-"+e.name.replace(/[^a-z]/,"")),t.addClass("up"),e.speed==1e3?t.addClass("green"):(e.speed==100||e.speed==10)&&t.addClass("orange"))},this))},networkTable:function(){if(!this.rendered)return!1;if(!this.grids.networks){var e=[{name:"name",label:a.G_Network,editable:!1,cell:"string"},{name:"ip",label:a.G_IP,editable:!1,cell:"string"},{name:"tx_bytes",label:a.G_DevicesTX,editable:!1,cell:i.StringCell.extend({formatter:r.Formatters.Bytes})},{name:"rx_bytes",label:a.G_DevicesRX,editable:!1,cell:i.StringCell.extend({formatter:r.Formatters.Bytes})},{name:"num_sta",label:a.G_PropertiesNumClients,editable:!1,cell:"integer"}];this.grids.networks=this.grid(e,new o.Collection(this.model.networks()),this.$(".data-table-networks"),this.noNetworkRows)}else this.grids.networks.collection.set(this.model.networks())},portForwardTable:function(){if(!this.rendered)return!1;if(!this.grids.portfwd){var e=[{name:"name",label:a.G_Name,editable:!1,cell:"string"},{name:"src",label:a.G_PortForwardSource,editable:!1,cell:i.StringCell.extend({formatter:{fromRaw:function(e){return!e||e=="any"?"*":e},toRaw:function(e){return e}}})},{name:"dst_port",label:a.G_Port,customClass:"detached-only",editable:!1,cell:"string"},{name:"fwd",label:a.G_PortForwardDest,customClass:"detached-only",editable:!1,cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){return s.filter([e.get("fwd"),e.get("fwd_port")],function(e){return e}).join(":")},toRaw:function(e){return e}}})},{name:"_id",label:a.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.ActionsCell.extend({actions:{edit:{icon:"ubnt-icon-edit",iconOnly:!0,requiresAdminPrivilege:!0,callback:this.portForwardForm},remove:{icon:"ubnt-icon-trash",iconOnly:!0,requiresAdminPrivilege:!0,callback:u.proxy(function(e){(new v).show(a.G_PropertiesPortForwardDeleteConfirm,u.proxy(function(){e.destroy({success:u.proxy(function(e,t){t.meta.rc==="ok"?this.showSavedState():this.showErrorState()},this),error:u.proxy(function(){this.showErrorState()},this)})},this))},this)}}})}];this.grids.portfwd=this.grid(e,this.app.collection("PortForward"),this.$(".data-table-portfwd"),this.noPortFwdRows,{paginateToAddedModel:!0}),this.grids.portfwd&&this.grids.portfwd.setFilter("name")}},portForwardForm:function(e){var n=this.app.collection("PortForward");this.forms.PortForward=new t({app:this.app,container:this.$portFwdForm,collection:n,model:e||new n.model}),this.listenTo(this.forms.PortForward,"remove",u.proxy(function(){this.forms.PortForward=null},this)),this.forms.PortForward.render(),this.position()},dynamicDNSTable:function(){if(!this.rendered)return!1;if(!this.grids.dynamicdns){var e=[{name:"service",label:a.G_PropertiesDDNSService,editable:!1,cell:"string"},{name:"host_name",label:a.G_PropertiesDDNSHostname,editable:!1,cell:"string"},{name:"login",label:a.G_PropertiesDDNSUsername,customClass:"detached-only",editable:!1,cell:"string"},{name:"x_password",label:a.G_PropertiesDDNSPassword,customClass:"detached-only",editable:!1,cell:"string"},{name:"server",label:a.G_PropertiesDDNSServer,customClass:"detached-only",editable:!1,cell:"string"},{name:"_id",label:a.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.ActionsCell.extend({actions:{edit:{icon:"ubnt-icon-edit",iconOnly:!0,requiresAdminPrivilege:!0,callback:this.dynamicDNSForm},remove:{icon:"ubnt-icon-trash",iconOnly:!0,requiresAdminPrivilege:!0,callback:u.proxy(function(e){(new v).show(a.G_PropertiesDDNSDynamicDNSDeleteConfirm,u.proxy(function(){e.destroy({success:u.proxy(function(e,t){t.meta.rc==="ok"?this.showSavedState():this.showErrorState()},this),error:u.proxy(function(){this.showErrorState()},this)})},this))},this)}}})}];this.grids.dynamicdns=this.grid(e,this.app.collection("DynamicDNS"),this.$(".data-table-dynamicdns"),this.noDynamicDNSRows,{paginateToAddedModel:!0}),this.grids.dynamicdns&&this.grids.dynamicdns.setFilter("service")}},dynamicDNSForm:function(e){var t=this.app.collection("DynamicDNS");this.forms.DynamicDNS=new n({app:this.app,container:this.$dynamicDNSForm,collection:t,model:e||new t.model}),this.listenTo(this.forms.DynamicDNS,"remove",u.proxy(function(){this.forms.DynamicDNS=null},this)),this.forms.DynamicDNS.render(),this.position()},statsDynamicDNSForm:function(e,t){this.$tabs.tabs("option","active",2),this.$gatewayConfig.find(".accordion").accordion("option","active",3),t&&this.dynamicDNSForm(e)},remove:function(){this.listenTo(this.app.collection("PortForward"),"add remove",this.portForwardTable),this.$portFwdCreate.off("click"),this.$connectionType.off("change"),this.$wanForm.off("submit"),this.$diagramWan.off("click"),this.$diagramLan.off("click"),this.$diagramVoice.off("click"),this.stopListening(this.forms.PortForward,"remove"),this.forms.PortForward&&this.forms.PortForward.remove(),this.unstickit(this.model),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("text!includes/switches/switchNetworksVlanFormTemplate.html",[],function(){return'<form>\n    <fieldset class="fieldset">\n        <div class="row">\n            <label class="label inline"><%- msg.G_Name %></label>\n            <input type="text" class="input inline" name="name" value="" />\n        </div>\n        <div class="row forward-native forward-customize">\n            <label class="label inline"><%- msg.G_NativeNetwork %></label>\n            <select id="network" name="network" class="input inline"></select>\n        </div>\n        <div class="row forward-customize">\n            <label class="label inline"><%- msg.G_PropertiesTaggedNetworks %></label>\n\n            <div class="networks checkbox-group left"></div>\n        </div>\n    </fieldset>\n\n    <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n    <button class="button" name="cancel" value="Cancel" type="button"><%- msg.G_Cancel %></button>\n</form>\n'}),define("unifi/view/switches/NetworksVlanFormView",["unifi/view/app/FormView","jquery","underscore","msg/Msg","text!includes/switches/switchNetworksVlanFormTemplate.html","ubnt/ubnt.radiotoggle"],function(e,t,n,r,i){"use strict";return e.extend({_templateId:n.template(i,{msg:r}),_prevalidate:{name:{input:"text"}},events:{"change #network":"onNetworkChange","click button[name=cancel]":"remove",'click input[name="networks"]':"onTaggedNetworkChange"},onNetworkChange:function(e){var t=this.$el.find("input[type=checkbox][name=networks]");t.prop("disabled",!1),t.filter(":checkbox[value="+e.target.value+"]").prop("checked",!1).prop("disabled",!0)},onTaggedNetworkChange:function(e){var n=t(e.target),r=this.$el.find("select[name=network]"),i=r.find('option[value="'+n.val()+'"]');n.is(":checked")&&(i.prop("selected",!1),r.val()==n.val()&&(i=r.find("option:first"),i.prop("selected",!0))),r.selectmenu("refresh")},render:function(){var t=this.rendered;e.prototype.render.call(this);var n=this.$container.parents(".networks-vlan-config");n.addClass("show-form"),t||(this.listenTo(this.app.collection("Networks"),"add remove",this.renderNetworks),this.on("remove",function(){n.removeClass("show-form")}),this.renderNetworks(),this.app.isReadOnly||this.prevalidator())},renderNetworks:function(){var e=this.app.collection("Networks").filterByPurpose(["corporate","guest","voip","vlan-only"]),i=this.$("select[name=network]"),s=this.$(".networks");s.empty(),i.empty(),i.append(t('<option value=""></option>').text(r.G_None)),n.each(e,function(e){s.append(t('<label><input type="checkbox" name="networks" value="'+e.id+'" /> '+e.get("name")+"</label>")),i.append(t('<option value="'+e.id+'"></option>').text(e.get("name")))}),i.selectmenu("refresh"),this.populate()},populate:function(){if(this.model){this.$el.find("input[name=name]").val(this.model.get("name")),this.$el.find("select[name=network]").val(this.model.get("native_networkconf_id")).trigger("change");var e=this.$el.find("input[type=checkbox][name=networks]");e.prop("checked",!1),n.each(this.model.get("tagged_networkconf_ids")||[],function(t){e.filter(":checkbox[value="+t+"]").prop("checked",!0)})}},gather:function(){var e={name:this.$el.find("input[name=name]").val()};return e.native_networkconf_id=this.$el.find("select[name=network] option:selected").val(),e.tagged_networkconf_ids=this.$el.find("input[name=networks]:checked").map(function(){return t(this).val()}).get(),e.native_networkconf_id&&n.isEmpty(e.tagged_networkconf_ids)?e.forward="native":e.forward="customize",e},success:function(){this.remove()},error:function(e,t){this.options.app.views.app.flash("error","Error",r.apiError(t))},remove:function(){this.stopListening(this.app.collection("Networks"),"add remove"),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("text!includes/switches/switchPortFormTemplate.html",[],function(){return'<form class="tab-form">\n    <fieldset>\n        <div class="row">\n            <span class="label inline"><%- msg.G_Port %></span>\n            <span class="label inline label-fit label-light portidx"></span>\n        </div>\n        <div class="name">\n            <div class="row">\n                <label class="label inline"><%- msg.G_Name %></label>\n                <input type="text" class="input inline" name="name" value="" />\n            </div>\n        </div>\n        <div class="poe">\n            <div class="row op_mode-toggled op_mode-switch">\n                <label class="label inline"><%- msg.G_PropertiesPoE %></label>\n\n                <div class="radio-group left">\n                    <label><input type="radio" name="poe_mode" value="off" /> <%- msg.G_SettingsOff %></label>\n                    <label><input type="radio" name="poe_mode" value="pasv24" /> <%- msg.G_PropertiesPoEModePassive %></label>\n                    <label><input type="radio" name="poe_mode" value="auto" /> <%- msg.G_PropertiesPoEModePoEPlus %></label>\n                </div>\n            </div>\n        </div>\n        <div class="row op_mode-toggled op_mode-switch op_mode-aggregate">\n            <label class="label inline"><%- msg.G_PropertiesNetworksVLANs %></label>\n            <select name="portconf_id" class="input inline"></select>\n        </div>\n    </fieldset>\n\n    <fieldset class="advanced">\n        <legend class="toggle"><%- msg.G_SettingsAdvancedOpts %> <span class="ubnt-icon-arrow-down secondary-color"></span></legend>\n\n        <div class="advanced">\n            <div class="row">\n                <label class="label inline"><%- msg.G_PropertiesOperation %></label>\n                <div class="radio-group left">\n                    <label><input type="radio" name="op_mode" value="switch" /> <%- msg.G_PropertiesSwitching %></label>\n                    <label><input type="radio" name="op_mode" value="mirror" /> <%- msg.G_PropertiesMirroring %></label>\n                    <label><input type="radio" name="op_mode" value="aggregate" /> <%- msg.G_PropertiesAggregate %></label>\n                </div>\n            </div>\n            <div class="row op_mode-toggled op_mode-mirror">\n                <label class="label inline"><%- msg.G_PropertiesMirroringPort %></label>\n                <input type="text" class="input inline" name="mirror_port_idx" value="" />\n            </div>\n            <div class="row op_mode-toggled op_mode-aggregate">\n                <label class="label inline"><%- msg.G_PropertiesAggregatePorts %></label>\n                <input type="text" class="input inline small" name="aggregate_start" value="" disabled="disabled" />\n                <span class="label inline label-fit label-light"><%- msg.G_To %></span>\n                <input type="text" class="input inline small" name="aggregate_num_ports" value="" />\n                <span class="aggregate-limits tip inline"></span>\n            </div>\n            <div class="row autoneg">\n                <label class="label inline"><%- msg.G_PropertiesAutoneg %></label>\n                <div class="radio-group left">\n                    <label><input type="radio" name="portconf_autoneg" value="auto" /><%- msg.G_PropertiesAuto %></label>\n                    <label><input type="radio" name="portconf_autoneg" value="manual" /><%- msg.G_PropertiesManual %></label>\n                </div>\n            </div>\n            <div class="row autoneg-disable autoneg">\n                <label class="label inline"><%- msg.G_PropertiesFullDuplex %></label>\n                <div class="radio-group left">\n                    <label><input type="checkbox" name="portconf_fullduplex"><%- msg.G_PropertiesEnable %></label>\n                </div>\n            </div>\n            <div class="row autoneg-disable autoneg">\n                <label class="label inline"><%- msg.G_PropertiesSpeed %></label>\n                <div class="radio-group left">\n                    <select id="test" class="input inline" name="portconf_speed">\n                        <option value="1000"><%- msg.G_Properties1000Mbps %></option>\n                        <option value="100"><%- msg.G_Properties100Mbps %></option>\n                        <option value="10"><%- msg.G_Properties10Mbps %></option>\n                    </select>\n                </div>\n            </div>\n        </div>\n    </fieldset>\n\n    <div class="form-controls">\n        <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n        <button class="button" name="cancel" value="Cancel" type="button"><%- msg.G_Cancel %></button>\n    </div>\n</form>\n'}),define("unifi/view/switches/PortFormView",["unifi/view/app/FormView","ubnt/view/dialogs/ConfirmDialogView","jquery","underscore","msg/Msg","text!includes/switches/switchPortFormTemplate.html"],function(e,t,n,r,i,s){"use strict";return e.extend({_templateId:r.template(s,{msg:i}),_prevalidate:{aggregate_num_ports:{input:"text",complex:!0,extra:{portidx:"tbd"}},mirror_port_idx:{input:"text",complex:!0,extra:{portidx:"tbd"}}},events:{"click button[name=cancel]":"remove"},render:function(){var t=this.rendered;this.formResult="",this.selection={},this.selection.count=this.options.overrides.length,this.selection.firstIdx=this.options.overrides[0].get("port_idx"),this.selection.lastIdx=this.options.overrides[this.selection.count-1].get("port_idx");var i=[],s=null,o=!1;r.each(this.options.overrides,function(e){var t=e.get("port_idx");o||(o=e.get("port_poe")),e.get("op_mode")=="aggregate"?(i.push(t+"-"+(t+e.get("aggregate_num_ports")-1)),s=null):t===this.selection.firstIdx?i.push(t):t!==s+1?(i[i.length-1]!==s&&(i[i.length-1]+="-"+s),i.push(t)):t===this.selection.lastIdx&&(t===s+1?i[i.length-1]+="-"+t:i.push(t)),s=t},this),this.selection.indexesLabel=i.join(", "),this.selection.supportsPoe=o,e.prototype.render.call(this);var u=this.$container.parents(".port-list-config");u.addClass("show-form");var a=this.$el;if(!t){this.on("remove",function(){u.removeClass("show-form")}),this.$el.find("input[name=op_mode]").radiotoggle({container:this.$el});var f=this.selection.count===1?this.options.overrides[0]:null;f?f.get("media")&&f.get("media")!=="SFP"&&f.get("media")!=="SFP+"?(n(".autoneg").show(),this.$el.find("input[name=portconf_autoneg]").change(function(){n(this).val()==="auto"?n(".autoneg-disable").hide():n(".autoneg-disable").show()})):n(".autoneg").hide():n(".autoneg").hide(),this.renderPortConf(),this.app.isReadOnly||this.prevalidator()}},renderPortConf:function(){var e=this.$el.find("select[name=portconf_id]");e.empty(),this.selection.count>1&&e.append(n('<option value=""></option>').text("(Keep existing)")),this.app.collection("PortConf").each(function(t){e.append(n('<option value="'+t.id+'"></option>').text(t.get("name")))}),this.portidx=parseInt(this.selection.firstIdx,10),this.$el.find(".portidx").text(this.selection.indexesLabel),this.$el.find("div.poe").toggle(this.selection.supportsPoe),e.selectmenu("refresh"),this.populate()},populate:function(){var e=this.selection.count===1?this.options.overrides[0]:null,t=e?e.get("poe_mode")||"auto":"auto",n=e?e.get("op_mode")||"switch":"switch",s={};r.each(this.model.get("port_overrides"),function(e){s[e.port_idx]=!0},this);if(e){this.$el.find("input[name=name]").val(e.get("name")),this.$el.find("input[name=poe_mode][value="+t+"]").prop("checked",!0).trigger("change"),this.$el.find("select[name=portconf_id]").val(e.get("portconf_id")||"").trigger("change"),this.$el.find("input[name=op_mode][value="+n+"]").prop("checked",!0).trigger("change"),this.$el.find("input[name=mirror_port_idx]").val(e.get("mirror_port_idx")),this.$el.find("input[name=aggregate_num_ports]").val(e.get("aggregate_num_ports")?parseInt(e.get("port_idx"),10)+parseInt(e.get("aggregate_num_ports"),10)-1:"");var o,u,a;s[e.get("port_idx")]?(o=e.get("autoneg")?"auto":"manual",u=e.get("full_duplex"),a=e.get("speed")):(o="auto",u=!0,a="1000"),this.$el.find("input[name=portconf_autoneg][value="+o+"]").prop("checked",!0).trigger("change"),this.$el.find("input[name=portconf_fullduplex]").prop("checked",u).trigger("change"),this.$el.find("select[name=portconf_speed]").val(a).trigger("change"),n!="switch"&&this.$el.find("legend.toggle").trigger("click",!1)}else this.$el.find("input[name=name]").val("(Keep existing)"),this.$el.find("input[name=poe_mode][value=auto]").prop("checked",!0).trigger("change"),this.$el.find("input[name=op_mode][value=switch]").prop("checked",!0).trigger("change");if(this.selection.count===1){this.$el.find("fieldset.advanced input").prop("disabled",!1),this.$el.find("input[name=aggregate_start]").val(e.get("port_idx")).disable();var f=this.selection.firstIdx+1,l=this.selection.firstIdx+3,c=this.model.numPorts(),h=this.$el.find("input[name=aggregate_num_ports]"),p=this.model.get("port_table"),d=p.length;for(var v=this.selection.firstIdx;v<l;v++)if(v<l){var m=p[v];if(m&&m.op_mode!=="switch"){l=v;break}}l>c&&(l=c),this.$el.find('input[name=op_mode][value="aggregate"]').parents("label:first").css("display",f>c||f>l?"none":"inline-block"),l-f>0?(this.$el.find(".aggregate-limits").text("("+i.localize(i.G_BetweenXandY,f,l)+")"),h.enable()):(h.val(f),h.disable()),this._prevalidate.aggregate_num_ports.extra.portidx=this.selection.firstIdx,this._prevalidate.mirror_port_idx.extra.portidx=this.selection.firstIdx}else this.$el.find("fieldset.advanced").prop("disabled",!0)},gather:function(){var e=r.clone(this.model.get("port_overrides")),t=[],i=this.$el.find("input[name=name]").val(),s=this.$el.find("input[name=poe_mode]:checked").val(),o=this.$el.find("select[name=portconf_id]").val(),u=this.$el.find("input[name=op_mode]:checked").val();r.each(this.options.overrides,function(e){var r={port_idx:e.get("port_idx"),name:i==="(Keep existing)"?e.get("name"):i,portconf_id:o||e.get("portconf_id"),op_mode:u};this.selection.supportsPoe&&e.get("media")!=="SFP"&&e.get("media")!=="SFP+"&&(r.poe_mode=s);if(!r.name){r.name="Port "+e.get("port_idx");switch(this.model.get("model")){case"US24":case"US24P250":case"US24P500":r.port_idx>24&&(r.name="SFP "+(r.port_idx-24));break;case"US48":case"US48P500":case"US48P750":r.port_idx>50?r.name="SFP "+(r.port_idx-50):r.port_idx>48&&(r.name="SFP+ "+(r.port_idx-48))}}r.op_mode=="mirror"?r.mirror_port_idx=this.$el.find("input[name=mirror_port_idx]").val():r.op_mode=="aggregate"&&(r.aggregate_num_ports=this.$el.find("input[name=aggregate_num_ports]").val()-this.selection.firstIdx+1),n(".autoneg").is(":visible")&&(r.autoneg=this.$el.find("input[name=portconf_autoneg]:checked").val()==="auto"?!0:!1,r.autoneg||(r.full_duplex=this.$el.find("input[name=portconf_fullduplex]:checked").is(":checked"),r.speed=this.$el.find("select[name=portconf_speed]").val())),t.push(r)},this);var a=t.map(function(e){return e.port_idx});return e?e=r.reject(e,function(e){return a.indexOf(e.port_idx)>-1}):e=[],e=e.concat(t),{port_overrides:e}},save:function(e){e&&e.preventDefault();var r=n.proxy(function(){this.clear(),this.$submit.trigger("saving");var e=this._save(this.model,null,{wait:!0,data:this.gather(),extra:{portidx:this.selection.firstIdx}});e?this.formResult="success":this.$submit.trigger("error",!0)},this),s=this.model.get("inform_ip"),o=this.app.collection("Clients").getUserFromIp(s);typeof o!="undefined"&&this.model.get("mac")===o.get("sw_mac")&&this.portidx==o.get("sw_port")?(new t).show(i.localize(i.N_ConfirmPortConfigApply,this.portidx,s),r):r()},success:function(){this.model.fetch(),this.remove()},error:function(e,t){this.options.app.views.app.flash("error","Error",i.apiError(t,!0))},remove:function(){this.rendered=!1,this.$el.find("input[name=portconf_autoneg]").off(),e.prototype.remove.apply(this,arguments)}})}),define("unifi/model/PortConf",["unifi/model/Model","underscore","backbone","msg/Msg"],function(e,t,n,r){"use strict";return e.extend({validate:function(e,n){var i={},s=n?n.partial:null;if(!s||s=="name")e.name?this.validator.name(e.name)||(i.name=r.localize(r.E_InvalidName,r.G_Name)):s||(i.name=r.localize(r.E_CannotBeEmpty,r.G_Name));if(t.size(i))return i},sync:function(e,t,r){r=r||{};switch(e){case"create":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/add/portconf",r.type="POST";break;case"update":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/upd/portconf/"+t.id,r.type="POST",r.data=JSON.stringify(t.toJSON({exclude:["_id","site_id"]}));break;case"delete":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/del/portconf/"+t.id,r.type="POST"}return n.sync.call(this,e,t,r)}})}),define("unifi/collection/PortConf",["unifi/collection/Collection","underscore","unifi/model/PortConf"],function(e,t,n){"use strict";return e.extend({model:n,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/list/portconf"}})}),define("text!includes/switches/switchPropertiesTemplate.html",[],function(){return'<div class="accordion-header">\n    <div class="accordion-title">\n        <span class="device-icons access-point half"></span>\n        <span class="title-text"><%- name() %></span>\n        <div class="ubnt-icon-arrow-down sidebar-icons minmax minimize"></div>\n    </div>\n    <div class="right">\n        <div class="ubnt-icon-new-window sidebar-icons detach" title="Detach"></div>\n        <div class="ubnt-icon-close sidebar-icons remove" title="Close"></div>\n    </div>\n</div>\n<div class="property-content">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n\n    <div class="device-status-wrapper">\n        <div class="device-status bind-status"></div>\n    </div>\n\n    <%= diagram %>\n\n    <div class="status-alert status-success"><span class="ubnt-icon-check checkmark"></span><%- msg.G_Saved %></div>\n    <div class="status-alert status-error"><span class="ubnt-icon-warning alert"></span><%- msg.E_Error %></div>\n    <div class="tabs">\n        <ul>\n            <li class="tab-nav-list-item">\n                <a class="tab-button" href="#switchDetails<%- _id %>"><%- msg.G_PropertiesDetails %></a>\n            </li>\n            <li class="tab-nav-list-item ap-configs">\n                <a class="tab-button switchPorts-anchor" href="#switchPorts<%- _id %>"><%- msg.G_Ports %></a>\n            </li>\n            <li class="tab-nav-list-item ap-configs">\n                <a class="tab-button" href="#switchConfig<%- _id %>"><%- msg.G_PropertiesConfiguration %></a>\n            </li>\n        </ul>\n        <div class="properties-container overflow">\n            <div id="switchDetails<%- _id %>" class="tab-content">\n                <div class="accordion">\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_DevicesOverview %></div>\n                    </div>\n                    <div class="basic-overview">\n                        <table>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesMACAddress %></td>\n                                <td class="column-value"><%- get(\'mac\') %></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_DevicesModel %></td>\n                                <td class="column-value"><%- apModel() %></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Version %></td>\n                                <td class="column-value bind-version"></td>\n                            </tr>\n                        </table>\n                        <hr />\n                        <table>\n                            <tr class="table-row ip-address">\n                                <td class="column-name"><%- msg.G_IPAddress %></td>\n                                <td class="column-value bind-ip"></td>\n                            </tr>\n                            <tr class="table-row power-consumption">\n                                <td class="column-name"><%- msg.G_PowerConsumption %></td>\n                                <td class="column-value bind-power-consumption"></td>\n                            </tr>\n                            <tr class="table-row uptime">\n                                <td class="column-name"><%- msg.G_Uptime %></td>\n                                <td class="column-value bind-uptime"></td>\n                            </tr>\n                            <tr class="table-row last-uplink">\n                                <td class="column-name"><%- msg.G_LastUplink %></td>\n                                <td class="column-value">\n                                    <a class="bind-lastuplink button-uplink-device" href="#"></a>\n                                </td>\n                            </tr>\n                            <tr class="table-row last-seen">\n                                <td class="column-name"><%- msg.G_LastSeen %></td>\n                                <td class="column-value bind-lastseen"></td>\n                            </tr>\n                        </table>\n                    </div>\n\n                    <div class="accordion-header sw-uplink-details">\n                        <div class="accordion-title"><%- msg.G_PropertiesUplink %></div>\n                    </div>\n                    <div class="uplinks bind-uplink sw-uplink-details">\n                        <table class="side-by-side">\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Port %></td>\n                                <td class="column-value bind-uplink-port"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesUplink %></td>\n                                <td class="column-value column-callback bind-uplink-device button-uplink-device"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Speed %></td>\n                                <td class="column-value bind-uplink-speed"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesDuplex %></td>\n                                <td class="column-value bind-uplink-duplex"></td>\n                            </tr>\n                        </table>\n\n                        <table class="side-by-side">\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesDownPktsBytes %></td>\n                                <td class="column-value bind-uplink-down-packets"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesUpPktsBytes %></td>\n                                <td class="column-value bind-uplink-up-packets"></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Activity %></td>\n                                <td class="column-value bind-uplink-activity"></td>\n                            </tr>\n                        </table>\n                    </div>\n\n                    <div class="accordion-header sw-adv-adopt">\n                        <div class="accordion-title"><%- msg.G_PropertiesAdvancedOpts %></div>\n                    </div>\n                    <div class="sw-adv-adopt">\n                        <form action="" class="advAdoptForm sw-adv-adopt">\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_IP %></label>\n                                <input class="input inline medium bind-adopt-ip" type="text" value="" name="ip" />\n                                <span class="colon">:</span>\n                                <input class="input inline small" type="text" value="22" name="port" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_UN %></label>\n                                <input class="input inline" type="text" value="" name="username" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_PW %></label>\n                                <input class="input inline" type="password" value="" name="password" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_PropertiesInformURL %></label>\n                                <input class="input inline bind-adopt-url" type="text" value="" name="url" />\n                            </div>\n                            <button class="button is-admin" type="submit"><%- msg.G_Adopt %></button>\n                        </form>\n                    </div>\n\n                    <div class="accordion-header sw-downlink-details">\n                        <div class="accordion-title"><%- msg.G_PropertiesDownlinks %></div>\n                    </div>\n                    <div class="downlinks sw-downlink-details minigrid">\n                        <div class="data-table data-table-downlinks data-table-fit bind-downlinks"><%- msg.G_PropertiesNoDownlinksConnected %></div>\n                    </div>\n                </div>\n            </div>\n            <div id="switchPorts<%- _id %>" class="tab-content minigrid port-list-config ap-configs">\n                <div class="data-table data-table-ports data-table-fit bind-ports port-list"><%- msg.G_PropertiesNoPorts %></div>\n                <div class="port-form"></div>\n            </div>\n            <div id="switchConfig<%- _id %>" class="tab-content ap-configs">\n                <div class="accordion">\n                    <div class="accordion-header ap-configs">\n                        <div class="accordion-title"><%- msg.G_Config %></div>\n                    </div>\n                    <div class="ap-configs">\n                        <form action="" class="aliasForm">\n                            <div class="row">\n                                <label for="aliasName<%- _id %>" class="label"><%- msg.G_PropertiesAlias %></label>\n                                <input name="name" id="aliasName<%- _id %>" type="text" class="input" value="<%- get(\'name\') %>" />\n                            </div>\n                            <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n                        </form>\n                    </div>\n\n                    <div class="accordion-header" class="networks-vlan-config">\n                        <div class="accordion-title"><%- msg.G_PropertiesNetworksVLANs %></div>\n                    </div>\n                    <div class="networks-vlan-config">\n                        <button class="button networks-vlan-create is-admin" name="create">\n                            <span class="ui-button-icon-primary ubnt-icon-plus"></span>\n                            <span class="nav-text"><%- msg.G_Create %></span>\n                        </button>\n\n                        <div class="networks-vlan-list">\n                            <div class="data-table data-table-networks-vlan data-table-fit"><%- msg.G_PropertiesNoNetworksVLANsConfigured %></div>\n                        </div>\n\n                        <div class="networks-vlan-form"></div>\n                    </div>\n\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_Services %></div>\n                    </div>\n                    <div>\n                        <form action="" class="servicesForm">\n                            <div class="clearfix">\n                                <div class="side-by-side">\n                                    <div class="row">\n                                        <label class="label inline"><%- msg.G_PropertiesManagementVLAN %></label>\n                                        <select name="networkgroup" id="networkgroup<%- _id %>">\n                                            <option value="LAN"><%- msg.G_DevicesLan %></option>\n                                            <option value="VOIP"><%- msg.G_DevicesVoip %></option>\n                                        </select>\n                                    </div>\n                                </div>\n                            </div>\n\n                            <div class="row">\n                                <label class="wrapper"><input type="checkbox" name="jumboframe_enabled" value="1" /><%- msg.G_PropertiesEnableJumboFrame %></label>\n                            </div>\n                            <div class="row">\n                                <label class="wrapper"><input type="checkbox" name="flowctrl_enabled" value="1" /><%- msg.G_PropertiesEnableFlowControl %></label>\n                            </div>\n\n                            <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n                        </form>\n                    </div>\n\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_Network %></div>\n                    </div>\n                    <div>\n                        <form action="" class="networkForm bind-network">\n                            <div class="clearfix">\n                                <div class="side-by-side">\n                                    <div class="row">\n                                        <label for="configure-ip<%- _id %>" class="label inline"><%- msg.G_PropertiesConfigIP %></label>\n                                        <select name="type" class="configure-ip" id="configure-ip<%- _id %>">\n                                            <option value="dhcp"><%- msg.G_PropertiesUsingDHCP %></option>\n                                            <option value="static"><%- msg.G_PropertiesStaticIP %></option>\n                                        </select>\n                                    </div>\n                                </div>\n                            </div>\n\n                            <div class="clearfix">\n                                <div class="side-by-side">\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_IPAddress %></label>\n                                        <input type="text" class="input inline" name="ip" size="17" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesSubnetMask %></label>\n                                        <input type="text" class="input inline" name="netmask" size="17" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesGateway %></label>\n                                        <input type="text" class="input inline" name="gateway" size="17" value="" />\n                                    </div>\n                                </div>\n\n                                <div class="side-by-side">\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesPreferredDNS %></label>\n                                        <input type="text" class="input inline" name="dns1" size="17" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesAlternateDNS %></label>\n                                        <input type="text" class="input inline" name="dns2" size="17" value="" />\n                                    </div>\n                                    <div class="row connection-toggled connection-static">\n                                        <label class="label inline"><%- msg.G_PropertiesDNSSuffix %></label>\n                                        <input type="text" class="input inline" name="dnssuffix" size="17" value="" />\n                                    </div>\n                                </div>\n                            </div>\n                            <button class="button is-admin"><%- msg.G_Apply %></button>\n                        </form>\n                    </div>\n\n                    <div class="accordion-header is-admin">\n                        <div class="accordion-title"><%- msg.G_PropertiesCopySwitchConfig %></div>\n                    </div>\n                    <div class="is-admin">\n                        <div class="row">\n                            <%- msg.G_PropertiesCopySwitchConfigTxt %>\n                        </div>\n                        <div class="left">\n                            <select name="copyConfig" class="copyConfig-dropdown" data-myposition="left bottom" data-atposition="left top"></select>\n                        </div>\n                    </div>\n\n                    <div class="accordion-header is-admin">\n                        <div class="accordion-title"><%- msg.G_PropertiesForgetSwitch %></div>\n                    </div>\n                    <div class="is-admin">\n                        <div class="row">\n                            <%- msg.G_PropertiesForgetSwitchTxt %>\n                        </div>\n                        <button class="button forget left">\n                            <span class="ui-button-icon-primary ubnt-icon-forget-this-network"></span>\n                            <span class="nav-text"><%- msg.G_PropertiesForget %></span>\n                        </button>\n                        <div class="left">\n                            <select name="move" class="move-dropdown" data-myposition="left bottom" data-atposition="left top"></select>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </div>\n        <div class="dialog-controls is-admin clearfix">\n            <button class="button button-locate left">\n                <span class="ui-button-icon-primary ubnt-icon-location sidebar-icons locate"></span>\n                <span class="nav-text"><%- msg.G_Locate %></span>\n            </button>\n            <button class="button button-restart left">\n                <span class="ui-button-icon-primary ubnt-icon-rotate sidebar-icons restart"></span>\n                <span class="nav-text"><%- msg.G_Restart %></span>\n            </button>\n            <button class="button button-update left">\n                <span class="ui-button-icon-primary ubnt-icon-download sidebar-icons update"></span>\n                <span class="nav-text"><%- msg.G_Upgrade %></span>\n            </button>\n            <button class="button button-adopt left">\n                <span class="ui-button-icon-primary ubnt-icon-plus sidebar-icons adopt"></span>\n                <span class="nav-text"><%- msg.G_Adopt %></span>\n            </button>\n            <button class="button button-edit right disabled">\n                <span class="ui-button-icon-primary ubnt-icon-edit sidebar-icons edit"></span>\n                <span class="nav-text"><%- msg.G_EditSelected %></span>\n            </button>\n        </div>\n    </div>\n</div>\n'}),define("text!includes/switches/switchDiagramUS24PTemplate.html",[],function(){return'<div class="diagram switch port24 bind-state">\n    <div class="detached">\n        <div class="top">\n            <% for (var i = 1; i <= 24; i+=2) { %>\n            <div class="port port-<%= i %>" data-port="<%= i %>">\n                <div class="num"><%= i %></div>\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n            <% } %>\n\n            <div class="port sfp port-25" data-port="25">\n                <div class="num">SFP1</div>\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n        </div>\n\n        <div class="bottom">\n            <% for (var i = 2; i <= 24; i+=2) { %>\n            <div class="port port-<%= i %>" data-port="<%= i %>">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n                <div class="num"><%= i %></div>\n            </div>\n            <% } %>\n\n            <div class="port sfp port-26" data-port="26">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n                <div class="num">SFP2</div>\n            </div>\n        </div>\n    </div>\n    <div class="attached">\n        <div class="top">\n            <% for (var i = 1; i <= 24; i+=2) { %>\n            <div class="port port-<%= i %>" data-port="<%= i %>">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n            <% } %>\n\n            <div class="port sfp port-25" data-port="25">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n        </div>\n\n        <div class="bottom">\n            <% for (var i = 2; i <= 24; i+=2) { %>\n            <div class="port port-<%= i %>" data-port="<%= i %>">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n            <% } %>\n\n            <div class="port sfp port-26" data-port="26">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n        </div>\n    </div>\n</div>\n'}),define("text!includes/switches/switchDiagramUS48PTemplate.html",[],function(){return'<div class="diagram switch port48 bind-state">\n    <div class="detached">\n        <div class="top">\n            <% for (var i = 1; i <= 48; i+=2) { %>\n                <div class="port port-<%= i %>" data-port="<%= i %>">\n                    <div class="num"><%= i %></div>\n                    <div class="status">\n                        <div class="poe"></div>\n                        <div class="mirror"></div>\n                        <div class="block"></div>\n                    </div>\n                </div>\n            <% } %>\n\n            <div class="port sfp port-49" data-port="49">\n                <div class="num">SFP+1</div>\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n\n            <div class="port sfp port-51" data-port="51">\n                <div class="num">SFP1</div>\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n        </div>\n\n        <div class="bottom">\n            <% for (var i = 2; i <= 48; i+=2) { %>\n                <div class="port port-<%= i %>" data-port="<%= i %>">\n                    <div class="status">\n                        <div class="poe"></div>\n                        <div class="mirror"></div>\n                        <div class="block"></div>\n                    </div>\n                    <div class="num"><%= i %></div>\n                </div>\n            <% } %>\n\n            <div class="port sfp port-50" data-port="50">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n                <div class="num">SFP+2</div>\n            </div>\n            <div class="port sfp port-52" data-port="52">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n                <div class="num">SFP2</div>\n            </div>\n        </div>\n    </div>\n    <div class="attached">\n        <div class="top">\n            <% for (var i = 1; i <= 48; i+=2) { %>\n                <div class="port port-<%= i %>" data-port="<%= i %>">\n                    <div class="status">\n                        <div class="poe"></div>\n                        <div class="mirror"></div>\n                        <div class="block"></div>\n                    </div>\n                </div>\n            <% } %>\n\n            <div class="port sfp port-49" data-port="49">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n\n            <div class="port sfp port-51" data-port="51">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n        </div>\n\n        <div class="bottom">\n            <% for (var i = 2; i <= 48; i+=2) { %>\n                <div class="port port-<%= i %>" data-port="<%= i %>">\n                    <div class="status">\n                        <div class="poe"></div>\n                        <div class="mirror"></div>\n                        <div class="block"></div>\n                    </div>\n                </div>\n            <% } %>\n\n            <div class="port sfp port-50" data-port="50">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n            <div class="port sfp port-52" data-port="52">\n                <div class="status">\n                    <div class="poe"></div>\n                    <div class="mirror"></div>\n                    <div class="block"></div>\n                </div>\n            </div>\n        </div>\n    </div>\n</div>\n'}),define("unifi/view/switches/PropertyView",["unifi/view/devices/PropertyView","unifi/view/switches/NetworksVlanFormView","unifi/view/switches/PortFormView","ubnt/backgrid","libs/backgrid","underscore","backbone","jquery","msg/Msg","unifi/collection/PortConf","unifi/collection/Networks","text!includes/switches/switchPropertiesTemplate.html","text!includes/switches/switchDiagramUS24PTemplate.html","text!includes/switches/switchDiagramUS48PTemplate.html","ubnt/view/dialogs/AlertDialogView","ubnt/view/dialogs/ConfirmDialogView","stickit"],function(e,t,n,r,i,s,o,u,a,f,l,c,h,p,d,v){"use strict";return e.extend({templateId:c,diagramTemplate:null,bindings:function(){return s.extend({},e.prototype.bindings.call(this),{".bind-uplink":{observe:"uplink",onGet:function(e){if(e){var t=this.parent.options.app.collection("Devices").getDeviceFromMac(e.uplink_mac);t&&this.$bindUplinkDevice.text(t.name()).data("mac",t.get("mac")||""),this.$bindUplinkPort.text(e.port_idx),this.$bindUplinkSpeed.text(this.model.uplinkSpeed()),this.$bindUplinkDuplex.text(this.model.uplinkDuplex()),this.$bindUplinkDownPackets.text(this.model.uplinkDownPackets()),this.$bindUplinkUpPackets.text(this.model.uplinkUpPackets()),this.$bindUplinkActivity.text(this.model.uplinkActivity())}}},".bind-lastseen":{observe:"last_seen",onGet:function(){this.$bindLastseen.text(this.model.lastSeen())}},".bind-lastuplink":{observe:["last_uplink","uplink"],onGet:function(){this.$bindLastUplink.text(this.model.uplinkDeviceText())}},".bind-state":{observe:"uplink",onGet:function(){this.populateStates()}},".bind-downlinks":{observe:"downlink_table",onGet:function(e){this.downlinksTable()}},".bind-ports":{observe:"port_table",onGet:function(e){this.portsTable(!0)}},".bind-power-consumption":{observe:"port_table",onGet:function(e){this.$bindPowerConsumption.text(this.model.power()+" "+a.G_Watt)}},".bind-network":{observe:"config_network",onGet:function(e){this.populateNetworkForm(this.$networkForm,e)}},".button-edit":{observe:["state","map_id","default","upgradable","locating"],onGet:function(){var e=this.model.get("state");e==1?this.$btnEdit.show():this.$btnEdit.hide(),e!==this.lastPortState&&(this.position(),this.lastPortState=e)}}})},initialize:function(t){this.portConfCollection=t.parent.options.app.collection("PortConf");switch(this.model.get("model")){case"US24":case"US24P250":case"US24P500":this.diagramTemplate=s.template(h,{msg:a});break;case"US48":case"US48P500":case"US48P750":this.diagramTemplate=s.template(p,{msg:a})}this.listenTo(this.portConfCollection,"add remove change",u.proxy(function(){this.networksVlanTable(),this.portsTable()},this)),e.prototype.initialize.call(this,t)},dependencies:function(){var e={PortConf:f,Networks:l},t=[],n={},r=this;s.each(e,function(e,r){t.push(n[r]=u.Deferred())},this),u.when.apply(u,t).then(function(){r._dependencies.resolve()},function(){r._dependencies.reject()}),s.each(e,function(e,t){this.options.parent.app.collection(t,{fetch:{reload:!1,deferred:n[t]}},e)},this)},render:function(t){var n=this.rendered;return e.prototype.render.call(this,t),n||(this.forms={},this.noDownlinksRows=this.$(".data-table-downlinks").html(),this.noPortsRows=this.$(".data-table-ports").html(),this.noNetworksVlanRows=this.$(".data-table-networks-vlan").html(),this.$advAdoptForm=this.$(".advAdoptForm"),this.$btnEdit=this.$(".button-edit"),this.$diagram=this.$(".diagram"),this.$portList=this.$(".port-list"),this.$portForm=this.$(".port-form"),this.$bindLastseen=this.$(".bind-lastseen"),this.$bindLastUplink=this.$(".bind-lastuplink"),this.$bindPowerConsumption=this.$(".bind-power-consumption"),this.$bindUplinkPort=this.$(".bind-uplink-port"),this.$bindUplinkDevice=this.$(".bind-uplink-device"),this.$bindUplinkSpeed=this.$(".bind-uplink-speed"),this.$bindUplinkDuplex=this.$(".bind-uplink-duplex"),this.$bindUplinkDownPackets=this.$(".bind-uplink-down-packets"),this.$bindUplinkUpPackets=this.$(".bind-uplink-up-packets"),this.$bindUplinkActivity=this.$(".bind-uplink-activity"),this.$uplinkDevice=this.$(".button-uplink-device"),this.$servicesForm=this.$(".servicesForm"),this.$networkForm=this.$(".networkForm"),this.$connectionType=this.$(".configure-ip"),this.$networksVlanCreate=this.$('.networks-vlan-config button[name="create"]'),this.$networksVlanList=this.$(".networks-vlan-list"),this.$networksVlanForm=this.$(".networks-vlan-form"),this.$advAdoptForm.on("submit",this.onAdvAdoptFormSubmit),this.$btnEdit.on("click",this.edit),this.$uplinkDevice.on("click",this.displayUplinkDevice),this.$servicesForm.on("submit",u.proxy(function(e){e.preventDefault(),this.updateServices()},this)),this.$networkForm.on("submit",u.proxy(function(e){e.preventDefault(),this.updateNetwork(this.$networkForm,"config_network")},this)),this.$connectionType.on("change",u.proxy(function(e){var t=u(e.target).val();this.$networkForm.find(".connection-toggled").hide().filter(".connection-"+t).show()},this)).trigger("change"),this.$networksVlanCreate.on("click",u.proxy(function(){this.networksVlanForm()},this)),this.$networksVlanForm.hide(),this.$portList.on("click","tr",u.proxy(function(e){var t=u(e.target).closest("tr"),n;if(e.metaKey||e.ctrlKey){var r=t.closest("tr").find(".column-checkboxes input:not([disabled])"),i=r.is(":checked");window.getSelection?window.getSelection().removeAllRanges():document.selection&&document.selection.empty(),r.trigger("click"),this.highlightPort(n,!1)}else t.parent().prop("tagName").toLowerCase()=="tbody"&&(n=t.attr("class").replace("port-","")),this.highlightPort(n)},this)),this.$diagram.on("click",".port",u.proxy(function(e){e.preventDefault();if(this.forms.Port)return;var t=u(e.target).closest(".port"),n=t.data("port");if(e.metaKey||e.ctrlKey){var r=this.$portList.find("tr.port-"+n).find(".column-checkboxes input:not([disabled])");r.trigger("click"),this.highlightPort(n,!1)}else this.highlightPort(n)},this)),this._rendered.state()==="resolved"&&this._dependencies.state()==="resolved"?this.populate():this._rendered.state()==="pending"&&this._rendered.resolve(),this.adjustData&&this.adjustData(),this.stickit(this.model,this.bindings()),this.$tabs.on("change",u.proxy(function(e){this.toggleEditButton()},this)),this.toggleEditButton()),this.networksVlanTable(),this.portsTable(),n||this.detach(),this.options.options&&this.options.options.port&&this.highlightPort(this.options.options.port),this},toggleEditButton:function(){this.$tabs.tabs("option","active")===1&&!this.forms.Port?this.$tabs.find(".dialog-controls .button-edit").show():this.$tabs.find(".dialog-controls .button-edit").hide();var e=this.model.get("state");e!==this.lastPortState&&(this.position(),this.lastPortState=e)},edit:function(e){var t=u(e.target),n=t.hasClass("disabled"),r=this.$portList.find('.checkbox-cell input[type="checkbox"]:checked'),i=s.map(r,function(e){return e.id}),o=s.filter(this.model.collections.portTable.models,function(e){return i.indexOf(""+e.id)!==-1});if(n||!r.length)return;this.portForm(o,null,!0),this.toggleEditButton()},args:function(){return{_id:this.id,diagram:this.diagramTemplate,msg:a}},adjustData:function(){},onAdvAdoptFormSubmit:function(e){e.preventDefault();var t=this,n=this.model,r=u(e.target).find("button");this.$advAdoptForm.find(".error").removeClass("error"),r.attr("disabled","disabled");var i=n.advanceAdopt({data:{ip:this.$advAdoptForm.find('input[name="ip"]').val(),port:this.$advAdoptForm.find('input[name="port"]').val(),username:this.$advAdoptForm.find('input[name="username"]').val(),password:this.$advAdoptForm.find('input[name="password"]').val(),url:this.$advAdoptForm.find('input[name="url"]').val()},success:function(e){e.meta.rc==="ok"?n.fetch({success:function(e,n,r){n.meta.rc==="ok"&&t.parent.property(e)},complete:function(){r.removeAttr("disabled")}}):(t.showErrorState(),r.removeAttr("disabled"))},error:function(){t.showErrorState(),r.removeAttr("disabled")}});!i&&this.model.validationError&&s.each(this.model.validationError,function(e,t){switch(t){case"username":case"password":this.$advAdoptForm.find('input[name="'+t+'"]').addClass("error"),r.removeAttr("disabled")}},this)},populate:function(){var t=this,n=this.$(".properties-container"),r=n.scrollTop();this.$el.addClass("switch-properties"),e.prototype.populate.call(this),this._dependencies&&this._dependencies.state()=="resolved"&&(this.$servicesForm.find("select").val(this.model.get("networkgroup")||"LAN"),this.$servicesForm.find("input[name=jumboframe_enabled]").prop("checked",this.model.get("jumboframe_enabled")),this.$servicesForm.find("input[name=flowctrl_enabled]").prop("checked",this.model.get("flowctrl_enabled")),s.each(this.model.collections.portTable.models||[],u.proxy(function(e){var t=this.$diagram.find(".port-"+e.id);t.removeClass("shutdown up green orange poe mirror block").addClass(e.diagramClasses()).attr("title","Port "+e.get("port_idx")).tooltip({show:!1,hide:!1,track:!0,content:function(){return e.diagramTooltip()}})},this)),this.position(),s.delay(function(){n.scrollTop(r)},0))},populateStates:function(){this.$el.removeClass("sw-has-uplink, sw-has-downlinks"),this.model.get("uplink")&&this.$el.addClass("sw-has-uplink"),this.model.get("downlink_table")&&this.$el.addClass("sw-has-downlinks")},downlinksTable:function(){if(!this.rendered)return!1;if(!this.grids.downlinks){var e=[{name:"port_idx",label:a.G_Port,editable:!1,cell:"integer"},{name:"mac",label:a.G_PropertiesDevice,editable:!1,cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:u.proxy(function(e){var t=this.parent.options.app.collection("Devices"),n=e.get("mac")?t.getDeviceFromMac(e.get("mac")):null;return n?n.name():e.get("mac")},this),toRaw:function(e){return e}}}),callback:u.proxy(function(e){var t=this.parent.options.app.routers.devices.views.index,n=t.collection.getDeviceFromMac(e.get("mac"));t.property(n)},this)},{name:"model",label:a.G_DevicesModel,editable:!1,headerCell:r.Headers.customSortHeader,sortValue:u.proxy(function(e){var t=this.parent.options.app.collection("Devices"),n=e.get("mac")?t.getDeviceFromMac(e.get("mac")):null;return n?n.apModel():""},this),cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:u.proxy(function(e){var t=this.parent.options.app.collection("Devices"),n=e.get("mac")?t.getDeviceFromMac(e.get("mac")):null;return n?n.apModel():""},this),toRaw:function(e){return e}}})},{name:"status",label:a.G_Status,editable:!1,headerCell:r.Headers.customSortHeader,sortValue:u.proxy(function(e){var t=e.get("speed")+" ";return t+=e.get("full_duplex")?a.G_PropertiesFullDuplexAbbrv:a.G_PropertiesHalfDuplexAbbrv,t},this),cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var t=e.get("speed")+" ";return t+=e.get("full_duplex")?a.G_PropertiesFullDuplexAbbrv:a.G_PropertiesHalfDuplexAbbrv,t},toRaw:function(e){return e}}})}];this.grids.downlinks=this.grid(e,new o.Collection(this.model.get("downlink_table")),this.$(".data-table-downlinks"),this.noDownlinksRows)}else this.grids.downlinks.collection.set(this.model.get("downlink_table"))},displayUplinkDevice:function(){var e=this.app.routers.devices.views.index,t=e.collection.getDeviceFromMac(this.model.uplinkDeviceMac());return t&&e.property(t),!1},portsTable:function(e){this.lastPortState=null;if(!this.rendered)return!1;if(!this.grids.ports){var t=[{name:"_checkboxes",customClass:"column-checkboxes",editable:!1,sortable:!1,headerCell:r.Headers.CheckboxHeader,cell:r.Cells.CheckboxCell.extend({config:{callback:this.portSelectionChanged},render:function(){var e=!!this.$checkbox;if(!e){this.$checkbox=this.$el.find('input[type="checkbox"]'),this.$el.empty();var t=this.config,n=t.callback||u.noop,r=this.model,i=t.options;(!t.render||t.render(r,i))&&this.$el.append(u('<input type="checkbox" id="'+r.id+'">').on("click",function(e){var t=u(e.target),i=t.is(":checked");i?(t.closest("tr").addClass("select"),t.closest(".property-content").find(".diagram div.port-"+r.id).addClass("select")):(t.closest("tr").removeClass("select"),t.closest(".property-content").find(".diagram div.port-"+r.id).removeClass("select")),e.stopPropagation(),n(r,e)}))}return this.model.get("aggregated_by")||this.model.get("op_mode")!=="switch"?this.$el.find('input[type="checkbox"]').prop("checked",!1).prop("disabled",!0).addClass("disabled"):this.$el.find('input[type="checkbox"]').prop("disabled",!1).removeClass("disabled"),this}})},{name:"port_idx",label:a.G_Port,editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){return e.portIdxText()},toRaw:function(e){return e}}})},{name:"name",label:a.G_Name,editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:"string"},{name:"speed",label:a.G_Status,customClass:"detached-only",editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){return e.statusText()},toRaw:function(e){return e}}})},{name:"tx_bytes",label:a.G_DevicesTX,customClass:"detached-only",editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:i.StringCell.extend({formatter:r.Formatters.Bytes})},{name:"rx_bytes",label:a.G_DevicesRX,customClass:"detached-only",editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:i.StringCell.extend({formatter:r.Formatters.Bytes})},{name:"poe_mode",label:a.G_PropertiesPoE,editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:u.proxy(function(e){return e.poeModeText()},this),toRaw:function(e){return e}}})},{name:"portconf_id",label:a.G_PropertiesNetworksVLANs,customClass:"detached-only",editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:u.proxy(function(e){return e.networksVlansText()},this),toRaw:function(e){return e}}})},{name:"_id",label:a.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.ActionsCell.extend({actions:{edit:{icon:"ubnt-icon-edit",iconOnly:!0,requiresAdminPrivilege:!0,callback:this.portForm,render:function(e){return!e.get("masked")}},restart:{icon:"ubnt-icon-rotate",iconOnly:!0,callback:this.rowPowerCycle,requiresAdminPrivilege:!0,render:function(e){return e.get("poe_enable")}}}})}],n={pageable:!1,rowClassName:function(e){return"port-"+e.get("port_idx")}};this.grids.ports=this.grid(t,this.model.collections.portTable,this.$(".data-table-ports"),this.noPortsRows,n)}else this.grids.ports.refresh();if(this.grids.ports){var s,o;(s=this.$diagram.find("div.highlight"))&&(o=s.data("port"))&&this.highlightPort(o,!0,e)}},statsPortForm:function(e,t){this.$tabs.tabs("option","active",1);var n=e.get("port_idx");this.highlightPort(n),t&&(this.forms.Port&&this.forms.Port.remove(),this.portForm(e))},portForm:function(e,t,r){t&&t.stopPropagation();var i=this,o=this.parent.options.app.collection("PortConf"),a=this.$(".properties-container"),f=a.scrollTop();this.forms.Port=new n({app:this.parent.options.app,container:this.$portForm,model:this.model,overrides:r?e:[e]}),this.forms.Port.render(),this.position(),r||(this.$diagram.find("div.port.select").removeClass("select"),this.highlightPort(e.id)),this.listenTo(this.forms.Port,"remove",u.proxy(function(){this.position();var e=this.$portList.find('.checkbox-cell input[type="checkbox"]:checked'),t=s.map(e,function(e){return e.id}),n=this.forms.Port.formResult&&this.forms.Port.formResult==="success"||!1,r=this.$diagram.find("div.port.highlight"),i=this.$portList.find("tr.highlight");t.length&&(r.removeClass("highlight"),i.removeClass("highlight"),s.each(t,function(e){this.$diagram.find("div.port.port-"+e).addClass("select")},this),!i.length&&n&&this.$portList.find('thead .column-checkboxes input[type="checkbox"]').prop("checked",!1).trigger("change")),this.forms.Port=null},this)),this.forms.Port.$el.one("remove",function(){s.delay(function(){a.scrollTop(f),i.toggleEditButton()},0)})},portSelectionChanged:s.debounce(function(e){var t=this.$portList.find('.checkbox-cell input[type="checkbox"]:checked');t.length?this.$tabs.find(".dialog-controls .button-edit").removeClass("disabled"):this.$tabs.find(".dialog-controls .button-edit").addClass("disabled")},100),networksVlanTable:function(){var e=this;if(!this.rendered)return!1;if(!this.grids.networks){var t=[{name:"name",label:a.G_Name,editable:!1,cell:"string"},{name:"forward",label:a.G_Config,editable:!1,cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n="",r=e.app.collection("Networks"),i=r.filterByPurpose(["corporate","guest","voip","vlan-only"]),o=s.findWhere(i,{id:t.get("native_networkconf_id")});switch(t.get("forward")){case"customize":n+=a.G_PropertiesCustomized;break;case"native":n+=a.G_PropertiesNative,o&&(n+=" ("+o.get("name")+")")}return n},toRaw:function(e){return e}}})},{name:"_id",label:a.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.ActionsCell.extend({actions:{edit:{icon:"ubnt-icon-edit",iconOnly:!0,requiresAdminPrivilege:!0,callback:this.networksVlanForm},remove:{icon:"ubnt-icon-trash",iconOnly:!0,requiresAdminPrivilege:!0,callback:u.proxy(function(e){(new v).show(a.G_PropertiesNetworkDeleteConfirm,u.proxy(function(){e.destroy({success:u.proxy(function(e,t){t.meta.rc==="ok"?this.showSavedState():this.showErrorState()},this),error:u.proxy(function(){this.showErrorState()},this)})},this))},this)}}})}];this.grids.networks=this.grid(t,this.parent.options.app.collection("PortConf"),this.$(".data-table-networks-vlan"),this.noNetworksVlanRows,{paginateToAddedModel:!0})}this.grids.networks&&this.grids.networks.setFilter("forward",["native","customize"],1)},networksVlanForm:function(e){var n=this.parent.options.app.collection("PortConf");this.forms.NetworksVlan=new t({app:this.parent.options.app,container:this.$networksVlanForm,collection:n,model:e||new n.model}),this.listenTo(this.forms.NetworksVlan,"remove",u.proxy(function(){this.forms.NetworksVlan=null},this)),this.forms.NetworksVlan.render(),this.position()},updateServices:function(){var e={networkgroup:this.$servicesForm.find("select").val(),jumboframe_enabled:this.$servicesForm.find("input[name=jumboframe_enabled]").is(":checked"),flowctrl_enabled:this.$servicesForm.find("input[name=flowctrl_enabled]").is(":checked")};return this.model.save(e,{success:u.proxy(function(e,t){t.meta.rc==="ok"?this.showSavedState():this.showErrorState()},this),error:u.proxy(function(){this.showErrorState()},this)}),!1},highlightPort:function(e,t,n){var r=this.$portList.find("tr.port-"+e),i=this.$diagram.find("div.port-"+e),o=s.isUndefined(t)?i.hasClass("highlight"):!t,u=this.$diagram.find("div.port.select").length>0;this.$portList.find("tr.highlight").removeClass("highlight"),this.$diagram.find("div.port.highlight").removeClass("highlight"),o||(u||i.addClass("highlight"),n||this.$tabs.tabs("option","active",1),r.length&&(u||r.addClass("highlight"))),r.length&&this.$(".properties-container").scrollTop(r.position().top)},rowPowerCycle:function(e){var t=this,n=function(){t.model.powerCyclePort({data:{port_idx:e.get("port_idx")},success:function(e,n,r){t.model.fetch()},error:function(e,n,r){t.app.views.app.flash("error","Error",a.apiError(e))}})};(new v).show(a.localize(a.N_ConfirmPowerCyclePort,e.get("port_idx")),n)},remove:function(){this.stopListening(this.portConfCollection,"add remove change"),this.stopListening(this.forms.Port,"remove"),this.stopListening(this.forms.NetworksVlan,"remove"),this.$bindUplinkDevice.off(),this.$connectionType.off(),this.$servicesForm.off(),this.$networkForm.off(),this.$networksVlanCreate.off(),this.$portList.off(),this.$diagram.off(),this.unstickit(this.model),this.$btnEdit.off("click",this.edit),this.$uplinkDevice.off("click",this.displayUplinkDevice),this.unstickit(this.model),this.$tabs.off("change"),this.forms.Port&&this.forms.Port.$el.off(),this.forms.Port&&this.forms.Port.remove(),this.forms.NetworksVlan&&this.forms.NetworksVlan.remove(),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/view/app/CallsMixin",["jquery","underscore","msg/Msg"],function(e,t,n){"use strict";return{formatNumber:function(e,r){if(e.get(r+"_type")=="external"){var i=e.get(r+"_number");return!i||i=="unknown"?n.G_CallsUnknown:i}var s=e.get(r+"_extension"),o=e.get(r+"_branch"),u,a,f;return e.get(r+"_name")?a=e.get(r+"_name"):(u=this.app.collection("Extensions").filterByExtension(s),a=u?u.get("name"):null),f=s?'<span class="ext">'+(o||"")+s+"</span>":"",a?t.escape(a)+(f?" ("+f+")":""):f}}}),define("text!includes/phones/phonePropertiesTemplate.html",[],function(){return'<div class="accordion-header">\n    <div class="accordion-title">\n        <span class="device-icons access-point half"></span>\n        <span class="title-text"><%- name() %></span>\n        <div class="ubnt-icon-arrow-down sidebar-icons minmax minimize"></div>\n    </div>\n    <div class="right">\n        <div class="ubnt-icon-new-window sidebar-icons detach" title="Detach"></div>\n        <div class="ubnt-icon-close sidebar-icons remove" title="Close"></div>\n    </div>\n</div>\n<div class="property-content">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n\n    <div class="device-status-wrapper">\n        <div class="device-status bind-status"></div>\n    </div>\n    <div class="status-alert status-success"><span class="ubnt-icon-check checkmark"></span><%- msg.G_Saved %></div>\n    <div class="status-alert status-error"><span class="ubnt-icon-warning alert"></span><%- msg.E_Error %></div>\n    <div class="tabs">\n        <ul>\n            <li class="tab-nav-list-item">\n                <a class="tab-button" href="#deviceDetails<%- _id %>"><%- msg.G_PropertiesDetails %></a>\n            </li>\n            <li class="tab-nav-list-item ap-configs">\n                <a class="tab-button" href="#deviceConfig<%- _id %>"><%- msg.G_PropertiesConfiguration %></a>\n            </li>\n        </ul>\n        <div class="properties-container overflow">\n            <div id="deviceDetails<%- _id %>" class="tab-content">\n                <div class="accordion">\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_DevicesOverview %></div>\n                    </div>\n                    <div class="basic-overview">\n                        <table>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_PropertiesMACAddress %></td>\n                                <td class="column-value"><%- get(\'mac\') %></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_DevicesModel %></td>\n                                <td class="column-value"><%- apModel() %></td>\n                            </tr>\n                            <tr class="table-row">\n                                <td class="column-name"><%- msg.G_Version %></td>\n                                <td class="column-value bind-version"></td>\n                            </tr>\n                        </table>\n                        <hr />\n                        <table>\n                            <tr class="table-row ip-address">\n                                <td class="column-name"><%- msg.G_IPAddress %></td>\n                                <td class="column-value bind-ip"></td>\n                            </tr>\n                            <tr class="table-row uptime">\n                                <td class="column-name"><%- msg.G_Uptime %></td>\n                                <td class="column-value bind-uptime"></td>\n                            </tr>\n                        </table>\n                    </div>\n                    <div class="accordion-header sw-adv-adopt">\n                        <div class="accordion-title"><%- msg.G_PropertiesAdvancedOpts %></div>\n                    </div>\n                    <div class="sw-adv-adopt">\n                        <form action="" class="advAdoptForm ph-adv-adopt">\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_IP %></label>\n                                <input class="input inline medium bind-adopt-ip" type="text" value="" name="ip" />\n                                <span class="colon">:</span>\n                                <input class="input inline small" type="text" value="22" name="port" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_UN %></label>\n                                <input class="input inline" type="text" value="" name="username" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_PW %></label>\n                                <input class="input inline" type="password" value="" name="password" />\n                            </div>\n                            <div class="row">\n                                <label class="label inline"><%- msg.G_PropertiesInformURL %></label>\n                                <input class="input inline bind-adopt-url" type="text" value="" name="url" />\n                            </div>\n                            <button class="button is-admin" type="submit"><%- msg.G_Adopt %></button>\n                        </form>\n                    </div>\n                </div>\n            </div>\n            <div id="deviceConfig<%- _id %>" class="tab-content ap-configs">\n                <div class="accordion">\n                    <div class="accordion-header is-admin">\n                        <div class="accordion-title"><%- msg.G_PropertiesForgetPhone %></div>\n                    </div>\n                    <div class="is-admin">\n                        <div class="row">\n                            <%- msg.G_PropertiesForgetPhoneTxt %>\n                        </div>\n                        <button class="button forget left is-admin">\n                            <span class="ui-button-icon-primary ubnt-icon-forget-this-network"></span>\n                            <span class="nav-text"><%- msg.G_PropertiesForget %></span>\n                        </button>\n                        <div class="left">\n                            <select name="move" class="move-dropdown" data-myposition="left bottom" data-atposition="left top"></select>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </div>\n        <div class="dialog-controls is-admin clearfix">\n            <button class="button button-locate left">\n                <span class="ui-button-icon-primary ubnt-icon-location sidebar-icons locate"></span>\n                <span class="nav-text"><%- msg.G_Locate %></span>\n            </button>\n            <button class="button button-restart left">\n                <span class="ui-button-icon-primary ubnt-icon-rotate sidebar-icons restart"></span>\n                <span class="nav-text"><%- msg.G_Restart %></span>\n            </button>\n            <button class="button button-update left">\n                <span class="ui-button-icon-primary ubnt-icon-download sidebar-icons update"></span>\n                <span class="nav-text"><%- msg.G_Upgrade %></span>\n            </button>\n            <button class="button button-adopt left">\n                <span class="ui-button-icon-primary ubnt-icon-plus sidebar-icons adopt"></span>\n                <span class="nav-text"><%- msg.G_Adopt %></span>\n            </button>\n        </div>\n    </div>\n</div>\n'}),define("unifi/view/phones/PropertyView",["unifi/view/devices/PropertyView","unifi/view/app/CallsMixin","ubnt/backgrid","underscore","backbone","libs/backgrid","jquery","msg/Msg","unifi/model/Device","text!includes/phones/phonePropertiesTemplate.html","ubnt/view/dialogs/AlertDialogView","stickit"],function(e,t,n,r,i,s,o,u,a,f,l){"use strict";return e.extend(r.extend({},t,{templateId:f,render:function(t){var n=this.rendered;return e.prototype.render.call(this,t),n||(this.$advAdoptForm=this.$(".advAdoptForm"),this.$advAdoptForm.on("submit",this.onAdvAdoptFormSubmit),this._rendered.state()==="resolved"&&this._dependencies.state()=="resolved"?this.populate():this._rendered.state()==="pending"&&this._rendered.resolve(),this.stickit(this.model,this.bindings())),this},onAdvAdoptFormSubmit:function(e){e.preventDefault();var t=this,n=this.model,i=o(e.target).find("button");this.$advAdoptForm.find(".error").removeClass("error"),i.attr("disabled","disabled");var s=n.advanceAdopt({data:{ip:this.$advAdoptForm.find('input[name="ip"]').val(),port:this.$advAdoptForm.find('input[name="port"]').val(),username:this.$advAdoptForm.find('input[name="username"]').val(),password:this.$advAdoptForm.find('input[name="password"]').val(),url:this.$advAdoptForm.find('input[name="url"]').val()},success:function(e){e.meta.rc==="ok"?n.fetch({success:function(e,n,r){n.meta.rc==="ok"&&t.parent.property(e)},complete:function(){i.removeAttr("disabled")}}):(t.showErrorState(),i.removeAttr("disabled"))},error:function(){t.showErrorState(),i.removeAttr("disabled")}});!s&&this.model.validationError&&r.each(this.model.validationError,function(e,t){switch(t){case"username":case"password":this.$advAdoptForm.find('input[name="'+t+'"]').addClass("error"),i.removeAttr("disabled")}},this)},populate:function(){e.prototype.populate.call(this),this._dependencies&&this._dependencies.state()=="resolved"&&this.position()},remove:function(){this.rendered=!1,this.unstickit(this.model),e.prototype.remove.apply(this,arguments)}}))}),define("text!includes/devices/devicesAddDeviceDialog.html",[],function(){return'<div id="add-device" class="dialog-simple-form">\n    <div class="content left">\n        <div class="errors" style="display:none"></div>\n        <div class="success" style="display:none"></div>\n\n        <form id="addDeviceForm" action="" class="left">\n            <div class="row">\n\n                <input id="deviceAddress" \n                       name="device-address" \n                       type="text" \n                       placeholder="<%- msg.G_PropertiesMACAddress %>" \n                       class="input device-address"\n                       maxlength="17" />\n\n                <input id="deviceCode" \n                       name="device-code" \n                       type="text" \n                       placeholder="<%- msg.G_DeviceCode %>" \n                       class="input device-code"\n                       maxlength="6" />\n            </div>\n\n            <div class="footer">\n                <button class="button button-submit right tall green" type="submit">\n                    <span class="ubnt-icon-check ui-button-icon button-check-icon"></span>\n                    <%- msg.G_Submit %>\n                </button>\n            </div>\n        </form>\n    </div>\n</div>\n'}),define("unifi/view/devices/AddDeviceView",["unifi/view/app/DialogView","text!includes/devices/devicesAddDeviceDialog.html","unifi/model/Device","msg/Msg","backbone","underscore","jquery"],function(e,t,n,r,i,s,o){"use strict";return e.extend({events:{"keyup input[name=device-address]":"validateInputs","keyup input[name=device-code]":"validateInputs","click .button-submit":"onSubmit","submit #addSiteForm":"onSubmit"},dialogOptions:{title:r.G_DevicesAddNewDevice,width:"auto",height:"auto",modal:!0,resizable:!1,draggable:!1,dialogClass:"dialog-add-device dialog-simple"},initialize:function(e){s.bindAll(this),this.app=e.app,this.device=new n},render:function(){this.$el.html(s.template(t,{msg:r})),this.$deviceAddressInput=this.$("input[name=device-address]").focus(),this.$deviceCodeInput=this.$("input[name=device-code]").focus(),this.$submitButton=this.$(".button-submit"),this.$errors=this.$(".errors"),this.$success=this.$(".success")},open:function(){e.prototype.open.call(this),o.Window.on("resize.addDeviceDialog",s.debounce(this.onResizeWindow,250)),this.$submitButton.prop("disabled",!0),this.onResizeWindow()},close:function(){e.prototype.close.call(this),o.Window.off("resize.addDeviceDialog")},onResizeWindow:function(){this.center()},validateInputs:function(){var e=0,t=[this.$deviceAddressInput];s.each(t,function(t){t.val()||e++},this),this.$submitButton.prop("disabled",!!e)},onSubmit:function(e){e.preventDefault();var t=this,n=this.$deviceAddressInput.val(),i=this.$deviceCodeInput.val(),s=n+i,o={macidqr:s,success:function(e){e.meta.rc==="ok"&&(t.$errors.hide(),t.$success.show(),t.$success.text(r.G_DevicesAddSuccess),t.app.refresh(),setTimeout(function(){t.close()},1e3))},error:function(e){e.statusText==="Bad Request"&&(t.$errors.show(),t.$errors.text(r.E_InvalidDevice))}};return this.device.sync("add-device",this,o)},remove:function(){o.Window.off("resize.addDeviceDialog"),e.prototype.remove.apply(this,arguments)}})}),define("text!includes/devices/devicesIndexTemplate.html",[],function(){return'<div class="section section-main">\n    <h1><%- msg.G_Devices %></h1>\n    <form class="data-filters clearfix">\n        <span class="ubnt-icon-search"></span>\n        <input type="text" name="search" class="search left" />\n        \n        <div class="buttonset type-filters">\n            <input type="radio" id="devicesFilterAll" name="type-filter" value="all" checked="checked" /><label for="devicesFilterAll"><%- msg.G_All %></label>\n            <input type="radio" id="devicesFilterGatewaySwitch" name="type-filter" value="gateway-switch" /><label for="devicesFilterGatewaySwitch"><%- msg.G_DevicesGatewaySwitches %></label>\n            <input type="radio" id="devicesFilterAccessPoints" name="type-filter" value="ap" /><label for="devicesFilterAccessPoints"><%- msg.G_DevicesAPs %></label>\n            <input type="radio" id="devicesFilterPhones" name="type-filter" value="phone" /><label for="devicesFilterPhones"><%- msg.G_DevicesPhones %></label>\n        </div>\n        \n        <div class="buttonset ap-filters">\n            <input type="radio" id="devicesFilterOverview" name="ap-filter" value="overview" checked="checked" /><label for="devicesFilterOverview"><%- msg.G_DevicesOverview %></label>\n            <input type="radio" id="devicesFilterConfig" name="ap-filter" value="config" /><label for="devicesFilterConfig"><%- msg.G_Config %></label>\n            <input type="radio" id="devicesFilterPerformance" name="ap-filter" value="performance" /><label for="devicesFilterPerformance"><%- msg.G_DevicesPerformance %></label>\n        </div>\n        \n        <div class="right">\n            <select name="items-per-page" data-label="<%- msg.G_FilterItemsPerPage %>">\n                <option value="10">10</option>\n                <option value="50" selected="selected">50</option>\n                <option value="100">100</option>\n                <option value="200">200</option>\n            </select>\n        </div>\n    </form>\n    \n    <div class="global-actions">\n        <button type="button" class="button lighter auto is-admin" style="display:none" id="addDevice">\n            <span class="ui-button-icon-primary ubnt-icon-plus"></span>\n            <%- msg.G_AddDevice %>\n        </button>\n        <button type="button" class="button lighter auto is-admin" id="upgradeAPs">\n            <span class="ubnt-icon-download"></span>\n            <span class="copy"><%- msg.G_DevicesStartRollingUpgrade %></span>\n        </button>\n        <button type="button" class="button lighter auto is-admin" id="upgradePhones">\n            <span class="ubnt-icon-download"></span>\n            <span class="copy"><%- msg.G_UpgradeAll %></span>\n        </button>\n    </div>\n\n    <div class="data-table untitled">\n        <div class="loading"><span><%- msg.N_Loading %></span></div>\n    </div>\n</div>\n'}),define("unifi/view/devices/IndexView",["unifi/view/app/ListContentView","unifi/view/aps/PropertyView","unifi/view/gateway/PropertyView","unifi/view/switches/PropertyView","unifi/view/phones/PropertyView","unifi/view/devices/AddDeviceView","ubnt/view/dialogs/ConfirmDialogView","underscore","libs/backgrid","ubnt/backgrid","msg/Msg","jquery","unifi/collection/Devices","unifi/collection/WlanGroups","unifi/collection/Extensions","ubnt/GoogleAnalytics","text!includes/devices/devicesIndexTemplate.html","ubnt/view/dialogs/AlertDialogView"],function(e,t,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g){"use strict";return e.extend({id:"devicesIndex",_templateId:m,_collectionType:{name:"Devices",Class:h},_pageable:!0,_filterMinimum:.1,initialize:function(t){this.properties={},this.locateTimer=null,this.locateLit=!1,e.prototype.initialize.call(this,t),this.listenTo(this.collection,"change:upgradable change:rollupgrade add remove sync",u.debounce(this.changeUpgradeButtonStatus,250)),this.listenTo(this.collection,"remove",u.debounce(this.removeProperty,250)),this.listenTo(this.collection,"change:locating",u.debounce(this.toggleLocating,250)),this.listenTo(this.collection,"sync",u.debounce(this.enableLocateTimerIfNeeded,250))},render:function(){var t=this.rendered;e.prototype.render.call(this,!0),t||(this.$btnAddDevice=c("#addDevice"),this.$btnAddDevice.on("click",this.addDevice),this.$btnUpgradeAPs=c("#upgradeAPs"),this.$btnUpgradeAPsCopy=this.$btnUpgradeAPs.find(".copy"),this.$btnUpgradeAPs.on("click",this.upgradeAPs),this.changeUpgradeAPsStatus(),this.$btnUpgradePhones=c("#upgradePhones"),this.$btnUpgradePhones.on("click",this.upgradePhones),this.changeUpgradePhonesStatus(),this._rendered.resolve())},dependencies:function(){this._dependencies.resolve(),this.wlanGroups=this.app.collection("WlanGroups",{fetch:{reload:!1}},p),this.listenTo(this.wlanGroups,"sync",c.proxy(function(){this.grids.content&&this.grids.content.reset()},this)),this.extensions=this.app.collection("Extensions",{fetch:{reload:!1}},d)},columns:function(){var e=this;return[{name:"state",customClass:"column-name",editable:!1,sortable:!1,headerCell:f.Headers.emptyHeader,cell:f.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(e){return c("<div />").addClass("ap-model-"+e.get("model")).addClass(e.isConnected()?"ap-connected":"ap-disconnected").append(c('<div class="device-icons access-point half"></div>'))},toRaw:function(e){return e}}})},{name:"name",label:l.G_DevicesNameMACAddress,customClass:"column-name",editable:!1,sortValue:"name",sortFormatter:"toLowerCase",headerCell:f.Headers.customSortHeader,cell:f.Cells.ModelCell.extend({callback:"name"}),callback:this.property,title:"mac"},{name:"mac",label:l.G_NameMACAddress,customClass:"column-mac",editable:!1,cell:"string"},{name:"ip",label:l.G_IPAddress,customClass:"column-ip",editable:!1,sortValue:"ip2long",headerCell:f.Headers.customSortHeader,cell:f.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){if(e.get("type")===e.typeMap.gateway){var t=u.findWhere(e.get("port_table"),{name:"lan"});if(t&&t.ip)return t.ip}return e.get("ip")},toRaw:function(e){return e}}})},{name:"state",label:l.G_Status,customClass:"column-state",editable:!1,sortValue:"status",headerCell:f.Headers.customSortHeader,cell:f.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(e){return c("<span />").addClass(e.statusType()).text(e.status())},toRaw:function(e){return e}}})},{name:"model",label:l.G_DevicesModel,customClass:"column-model",editable:!1,sortValue:"apModel",headerCell:f.Headers.customSortHeader,cell:f.Cells.ModelCell.extend({callback:"apModel"})},{name:"version",label:l.G_Version,customClass:"column-version",editable:!1,cell:"string",title:function(e){return e.get("type")===e.typeMap.phone?e.get("version")+" / "+e.get("platform_version"):""}},{name:"num_sta",label:l.G_DevicesClients,customClass:"column-num_sta",editable:!1,cell:"integer"},{name:"ng-num_sta",label:l.G_Devices2GClients,customClass:"column-ng-num_sta",editable:!1,cell:"string"},{name:"na-num_sta",label:l.G_Devices5GClients,customClass:"column-na-num_sta",editable:!1,cell:"string"},{name:"tx_bytes",label:l.G_DevicesDown,customClass:"column-tx_bytes",editable:!1,cell:a.StringCell.extend({formatter:f.Formatters.Bytes})},{name:"rx_bytes",label:l.G_DevicesUp,customClass:"column-rx_bytes",editable:!1,cell:a.StringCell.extend({formatter:f.Formatters.Bytes})},{name:"tx_bytes-d",label:l.G_DevicesTX,customClass:"column-tx_bytes-d",editable:!1,cell:a.StringCell.extend({formatter:f.Formatters.Bytes})},{name:"rx_bytes-d",label:l.G_DevicesRX,customClass:"column-rx_bytes-d",editable:!1,cell:a.StringCell.extend({formatter:f.Formatters.Bytes})},{name:"tx_bytes_2g",label:l.G_DevicesTX2G,customClass:"column-tx_bytes_2g",editable:!1,cell:f.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:c.proxy(function(e){return this.radioBar("ng",e)},this)}})},{name:"tx_bytes_5g",label:l.G_DevicesTX5G,customClass:"column-tx_bytes_5g",editable:!1,cell:f.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:c.proxy(function(e){return this.radioBar("na",e)},this)}})},{name:"ng-channel",label:l.G_DevicesChannel,customClass:"column-ng-channel",editable:!1,cell:f.Cells.ModelCell.extend({callback:"apChannel"})},{name:"wlangroup_id_na",label:l.G_DevicesWLAN2G,customClass:"column-wlangroup_id_na",editable:!1,cell:f.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){return t.wlan2G(e.app.collection("WlanGroups"))},toRaw:function(e){return e}}})},{name:"wlangroup_id_ng",label:l.G_DevicesWLAN5G,customClass:"column-wlangroup_id_ng",editable:!1,cell:f.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){return t.wlan5G(e.app.collection("WlanGroups"))},toRaw:function(e){return e}}})},{name:"radio_ng",label:l.G_DevicesRadio2G,customClass:"column-radio_ng",editable:!1,cell:f.Cells.ModelCell.extend({callback:"radio2G"})},{name:"radio_na",label:l.G_DevicesRadio5G,customClass:"column-radio_na",editable:!1,cell:f.Cells.ModelCell.extend({callback:"radio5G"})},{name:"extension",label:l.G_DevicesExtension,customClass:"column-extension",editable:!1,cell:f.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){return e.get("extension")},toRaw:function(e){return e}}}),callback:function(t){var n=e.app.collection("Extensions").filterByExtension(t.get("extension"));n&&e.options.app.views.app.openSettings("extensions",n.id)}},{name:"num_calls",label:l.G_DevicesNumCalls,customClass:"column-num_calls",editable:!1,cell:"string"},{name:"minutes",label:l.G_DevicesMinutes,customClass:"column-minutes",editable:!1,cell:"string"},{name:"uptime",label:l.G_Uptime,customClass:"column-uptime",editable:!1,cell:f.Cells.ModelCell.extend({callback:"uptime"})},{name:"_id",label:l.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:f.Headers.noSortHeader,cell:f.Cells.ActionsCell.extend({actions:{locate:{icon:"ubnt-icon-location",callback:this.rowLocate,requiresAdminPrivilege:!0,classCallback:function(e){return e.get("locating")?"locating":""},render:function(e){return e.get("state")==1}},restart:{icon:"ubnt-icon-rotate",callback:this.rowRestart,requiresAdminPrivilege:!0,render:function(e){return e.get("state")==1}},adopt:{icon:"ubnt-icon-plus",callback:this.rowAdopt,requiresAdminPrivilege:!0,render:function(e){return(e.get("state")==2||e.get("state")==12)&&e.get("default")}},upgrade:{icon:"ubnt-icon-download",callback:this.rowUpgrade,requiresAdminPrivilege:!0,render:function(e){if(e.get("upgradable")===!0){if(e.get("state")==1)return!0;if(e.get("state")==2)return e.get("uplink")&&e.get("uplink").type==="wireless"?!1:!0}return!1}}}})}]},grid:function(){this._gridRowClassName=this.gridRowClassName,e.prototype.grid.call(this);var t=this.grids.content,n=this.$el.find(".buttonset.type-filters"),r=n.find("input[name=type-filter]"),i=this.$el.find(".buttonset.ap-filters"),s=i.find("input[name=ap-filter]"),o=[],a=[],f=this.collection.typeMap,l=this.$btnUpgradeAPs,h=this.$btnUpgradePhones;return r.filter('[value="all"]').click(),s.filter('[value="overview"]').click(),u.each(r,function(e,t){o.push(e.value)}),u.each(s,function(e,t){a.push(e.value)}),r.on("change",function(e){var n=c(this).val(),r=n?n.split("-"):null,a=[];r&&u.each(r,function(e,t){f[e]&&a.push(f[e])}),a&&a.length?t.setFilter("type",a.length>1?a:a[0],1):t.removeFilter("type"),t.$el.removeClass(o.join(" ")).addClass(n||o[0]),n=="ap"?(i.show(),l.show(),h.hide()):n=="phone"?(i.hide(),l.hide(),h.show()):(i.hide(),l.hide(),h.hide()),s.filter(":checked").trigger("change"),c.cookie("filterDeviceType",n)}).filter(":checked").trigger("change"),s.on("change",function(e){var n=c(this),r=n.val();t.$el.removeClass(a.join(" ")).addClass(n.is(":visible")?r||a[0]:""),c.cookie("filterDeviceAp",r)}).filter(":checked").trigger("change"),this},gridRowClassName:function(e){return"mac-"+e.getMacNoColons()},property:function(e,s){if(!e)throw"Missing model";var o=e.get("mac"),a;if(this.properties[o])this.properties[o].render();else{switch(e.get("type")){case e.typeMap.ap:a=t;break;case e.typeMap.gateway:a=n;break;case e.typeMap["switch"]:a=r;break;case e.typeMap.phone:a=i}a&&(this.properties[o]=new a({properties:this.app.views.app.views.properties,parent:this,model:e,count:u.size(this.properties)+1,show:!0,options:s}))}return this.properties[o]},removeProperty:function(e){var t=e.get("mac");this.properties[t]&&delete this.properties[t]},rowLocate:function(e){e.locate(),e.get("state")===1&&e.get("map_id")&&(this.app.routers.map.forward(),this.app.routers.map.views.index.locateDevice(e))},toggleLocating:function(e){e.get("state")===1&&e.get("locating")?this.getLocateButtons(e).addClass("locating"):this.getLocateButtons(e).removeClass("locating"),this.enableLocateTimerIfNeeded()},enableLocateTimerIfNeeded:function(){var e=this,t=this.collection.findWhere({locating:!0});t?this.locateTimer||(e.locateLit=!0,this.locateTimer=window.setInterval(function(){c(".button-locate.locating").toggleClass("on",e.locateLit),e.locateLit=!e.locateLit},500)):(this.locateTimer&&(clearTimeout(this.locateTimer),delete this.locateTimer),this.locateTimer=null)},getLocateButtons:function(e){return c("."+this.gridRowClassName(e)).find(".button-locate")},rowRestart:function(e){var t=this,n=function(){e.restart({success:function(n,r,i){n.meta.rc==="ok"?(e.fetch(),e.set({restarting:!0})):t.app.views.app.flash("error")},error:function(e,n,r){t.app.views.app.flash("error","Error",l.apiError(e))}})};e.get("type")===e.typeMap.gateway||e.get("type")===e.typeMap["switch"]?(new o).show(l.N_ConfirmRestartDevice,n):n()},rowAdopt:function(e){var t=this;e.adopt({success:function(n,r,i){n.meta.rc==="ok"?e.fetch({success:function(){},error:function(){t.app.views.app.flash("error")}}):t.app.views.app.flash("error")},error:function(e,n,r){t.app.views.app.flash("error","Error",l.apiError(e))}})},rowUpgrade:function(e){var t=this,n=function(){e.upgrade({success:function(n,r,i){n.meta.rc==="ok"?e.fetch({success:function(){n.meta.rc==="ok"&&t.app.views.app.flash("success")}}):t.app.views.app.flash("error")},error:function(e,n,r){t.app.views.app.flash("error","Error",l.apiError(e))}})};e.get("type")===e.typeMap.gateway||e.get("type")===e.typeMap["switch"]?(new o).show(l.N_ConfirmUpgradeDevice,n):n()},changeUpgradeButtonStatus:function(){this.changeUpgradeAPsStatus(),this.changeUpgradePhonesStatus()},changeUpgradeAPsStatus:function(){this.collection.hasUpgradableAP()?this.$btnUpgradeAPs.removeAttr("disabled"):this.$btnUpgradeAPs.attr("disabled","disabled"),this.changeUpgradeAPsText()},changeUpgradeAPsText:function(){this.collection.isUpgradingDevices()?this.$btnUpgradeAPsCopy.text(l.G_DevicesRollingUpgradeInProgress):this.$btnUpgradeAPsCopy.text(l.G_DevicesStartRollingUpgrade)},upgradeAPs:function(){var e=this;this.collection.upgradeAPs({success:function(){e.collection.isUpgradingDevices()?(new g).open(l.G_DevicesRollingUpgradeCancelled):(new g).open(l.G_APRollingUpgrade),e.app.refresh(),e.changeUpgradeAPsStatus()}})},changeUpgradePhonesStatus:function(){this.collection.hasUpgradablePhone()?this.$btnUpgradePhones.removeAttr("disabled"):this.$btnUpgradePhones.attr("disabled","disabled"),this.changeUpgradeAPsText()},upgradePhones:function(){var e=this;this.collection.upgradePhones({success:function(){e.app.refresh(),e.changeUpgradePhonesStatus()}})},addDevice:function(){var e=new s({app:this.app});e.open()},radioBar:function(e,t){if(!t.get("adopted")||t.get("state")!=1||!t.get("radio_"+e))return"";var n=(parseInt(t.get(e+"_ast_txto"),10)||0)+(parseInt(t.get(e+"_ast_cst"),10)||0),r=parseInt(t.get(e+"_tx_retries"),10)||0,i=(parseInt(t.get(e+"_ast_be_xmit"),10)||0)+(parseInt(t.get(e+"_tx_packets"),10)||0),s=[n,r,i],o=["red","yellow","green"],a=100,f,l;if(!(f=u.reduce(s,function(e,t){return e+t},0)))return"";var h=c('<ul class="ratio-bar"></ul>');return u.each(s,function(e,t){l=Math.ceil(e*100/f),l>a&&(l=a),c("<li></li>",{"class":o[t],width:(t+1==s.length?a:l)+"%"}).appendTo(h),a-=l}),h.attr("title",s.join(" / ")),h},remove:function(){this.stopListening(this.collection),this.$btnAddDevice.off("click",this.addDevice),this.$btnUpgradeAPs.off("click",this.upgradeAPs),this.$btnUpgradePhones.off("click",this.upgradePhones);var t=this.$el.find(".buttonset.type-filters"),n=t.find("input[name=type-filter]"),r=this.$el.find(".buttonset.ap-filters"),i=r.find("input[name=ap-filter]");n.off("change"),i.off("change"),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/router/DevicesRouter",["unifi/router/Router","unifi/view/devices/IndexView","unifi/view/devices/PropertyView"],function(e,t,n){"use strict";return e.extend({_fullyQualifiedName:"UNIFI.Routers.Devices",_associatedViews:{Index:t,Property:n},routes:{devices:"index"}})}),define("unifi/model/ClientHistory",["unifi/model/Model"],function(e){"use strict";return e.extend()}),define("unifi/collection/ClientHistory",["unifi/collection/Collection","backbone","underscore","unifi/model/ClientHistory"],function(e,t,n,r){"use strict";return e.extend({model:r,bySite:!0,initialize:function(t){this.mac=t.mac,e.prototype.initialize.call(this,t)},url:function(){return"/api/s/"+SITE.name+"/stat/session"},sync:function(e,n,r){r=r||{};switch(e){case"read":r.contentType="application/json; charset=utf-8",r.type="POST",r.data=JSON.stringify({mac:this.mac,_limit:5,_sort:"-assoc_time"})}return t.sync.call(this,e,n,r)},parse:function(e){var t=e.data;return n.where(t,{mac:this.mac})}})}),define("unifi/model/User",["unifi/model/Model","jquery","underscore","backbone","msg/Msg","ubnt/ubnt.ip"],function(e,t,n,r,i){"use strict";return e.extend({validate:function(e,r){var s={},o=r?r.partial:null;(!o||o=="fixed_ip")&&e.use_fixedip&&(this.validator.ip(e.fixed_ip)?r.extra&&r.extra.subnet&&!t.ipsubnet_hasip(r.extra.subnet,e.fixed_ip)&&(s.fixed_ip=i.localize(i.E_IncorrectIPSubnet,e.fixed_ip,r.extra.subnet)):s.fixed_ip=i.localize(i.E_IncorrectIPAddress,i.G_ClientsFixedIP));if(n.size(s))return s},sync:function(e,t,n){n=n||{};switch(e){case"read":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/rest/user/"+t.id,n.type="GET";break;case"create":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/rest/user",n.type="PUT";break;case"update":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/rest/user/"+t.id,n.type="PUT",n.data=JSON.stringify(t.toJSON({exclude:["_id","site_id","first_seen","is_guest","is_wired","mac","oui"]}));break;case"delete":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/rest/user/"+t.id,n.type="DELETE"}return r.sync.call(this,e,t,n)}})}),define("text!includes/clients/clientsPropertiesTemplate.html",[],function(){return'<div class="accordion-header">\n    <div class="accordion-title">\n        <span class="device-icons station"></span>\n        <span class="title-text"><%- name() %></span>\n        <div class="ubnt-icon-arrow-down sidebar-icons minmax minimize"></div>\n    </div>\n    <div class="right">\n        <div class="ubnt-icon-new-window sidebar-icons detach" title="Detach"></div>\n        <div class="ubnt-icon-close sidebar-icons remove" title="Close"></div>\n    </div>\n</div>\n<div class="property-content">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n    \n    <div class="status-alert status-success"><span class="ubnt-icon-check checkmark"></span> <%- msg.G_Saved %></div>\n    <div class="status-alert status-error"><span class="ubnt-icon-warning alert"></span> <%- msg.E_Error %></div>\n    <div class="tabs">\n        <ul>\n            <li class="tab-nav-list-item">\n                <a class="tab-button" href="#clientDetails<%- _id %>"><%- msg.G_PropertiesDetails %></a>\n            </li>\n            <li class="tab-nav-list-item statistics-tab">\n                <a class="tab-button" href="#clientStatistics<%- _id %>"><%- msg.G_Stats %></a>\n            </li>\n            <li class="tab-nav-list-item">\n                <a class="tab-button" href="#clientHistory<%- _id %>"><%- msg.G_PropertiesHistory %></a>\n            </li>\n            <li class="tab-nav-list-item">\n                <a class="tab-button" href="#clientConfig<%- _id %>"><%- msg.G_Configuration %></a>\n            </li>\n        </ul>\n        <div class="properties-container overflow">\n            <div id="clientDetails<%- _id %>" class="tab-content">\n                <div class="table-basic">\n                    <table>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_PropertiesMACAddress %></td>\n                            <td class="column-value"><%- get(\'mac\') %></td>\n                        </tr>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_Hostname %></td>\n                            <td class="column-value hostname bind-hostname"></td>\n                        </tr>\n                    </table>\n                    <hr />\n                    <table>\n                        <tr class="table-row ip-address">\n                            <td class="column-name"><%- msg.G_IPAddress %></td>\n                            <td class="column-value bind-ip"></td>\n                        </tr>\n                        <tr class="table-row uptime">\n                            <td class="column-name"><%- msg.G_Uptime %></td>\n                            <td class="column-value bind-uptime"></td>\n                        </tr>\n                        <tr class="table-row connected-ap wireless-only">\n                            <td class="column-name"><%- msg.G_PropertiesConnectedAP %></td>\n                            <td class="column-value">\n                                <a class="bind-connected-ap" href="#"></a>\n                            </td>\n                        </tr>\n                        <tr class="table-row connected-network wired-only">\n                            <td class="column-name"><%- msg.G_Network %></td>\n                            <td class="column-value bind-connected-network"></td>\n                        </tr>\n                        <tr class="table-row connected-port wired-only">\n                            <td class="column-name"><%- msg.G_Port %></td>\n                            <td class="column-value">\n                                <a class="bind-connected-port" href="#"></a>\n                            </td>\n                        </tr>\n                        <tr class="table-row last-seen">\n                            <td class="column-name"><%- msg.G_LastSeen %></td>\n                            <td class="column-value bind-last-seen"></td>\n                        </tr>\n                    </table>\n                </div>\n            </div>\n            <div id="clientStatistics<%- _id %>" class="tab-content">\n                <div class="table-basic">\n                    <table class="wireless-only">\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_PropertiesESSID %></td>\n                            <td class="column-value bind-essid"></td>\n                        </tr>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_PropertiesConnectedAP %></td>\n                            <td class="column-value">\n                                <a class="bind-connected-ap" href="#"></a>\n                            </td>\n                        </tr>\n                    </table>\n                    <table class="wired-only">\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_Network %></td>\n                            <td class="column-value bind-connected-network"></td>\n                        </tr>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_Port %></td>\n                            <td class="column-value">\n                                <a class="bind-connected-port" href="#"></a>\n                            </td>\n                        </tr>\n                    </table>\n                    <hr />\n                    <table class="wireless-only">\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_Channel %></td>\n                            <td class="column-value"><span class="bind-channel"></span> (11<span class="bind-radio-type"></span>)</td>\n                        </tr>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_PropertiesSignal %></td>\n                            <td class="column-value"><span class="bind-rssi"></span> (<span class="bind-signal-with-dbm"></span>)</td>\n                        </tr>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_PropertiesTXRate %></td>\n                            <td class="column-value bind-tx-rate"></td>\n                        </tr>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_PropertiesRXRate %></td>\n                            <td class="column-value bind-rx-rate"></td>\n                        </tr>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_PropertiesPowerSave %></td>\n                            <td class="column-value bind-powersave"></td>\n                        </tr>\n                    </table>\n                    <hr class="wireless-only" />\n                    <table>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_Activity %></td>\n                            <td class="column-value bind-activity"></td>\n                        </tr>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_PropertiesDownPktsBytes %></td>\n                            <td class="column-value bind-sent-packets"></td>\n                        </tr>\n                        <tr class="table-row">\n                            <td class="column-name"><%- msg.G_PropertiesUpPktsBytes %></td>\n                            <td class="column-value bind-received-packets"></td>\n                        </tr>\n                    </table>\n                </div>\n            </div>\n            <div id="clientHistory<%- _id %>" class="tab-content minigrid">\n                <div class="data-table data-table-clients-history"><%- msg.G_PropertiesNoHistory %></div>\n            </div>\n            <div id="clientConfig<%- _id %>" class="tab-content">\n                <div class="accordion">\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_Config %></div>\n                    </div>\n                    <div>\n                        <form action="" class="configForm">\n                            <div class="row">\n                                <label for="aliasName<%- _id %>" class="label"><%- msg.G_PropertiesAlias %></label>\n                                <input name="name" id="aliasName<%- _id %>" type="text" class="input" value="<%- get(\'name\') %>" />\n                            </div>\n                            <div class="row">\n                                <label for="note<%- _id %>" class="label"><%- msg.G_Note %></label>\n								<textarea id="note<%- _id %>" name="note" class="textarea"><%- get(\'note\') %></textarea>\n                            </div>\n                            <div class="row">\n                                <label for="usergroups<%- _id %>" class="label label-selectmenu"><%- msg.G_PropertiesUsergroups %></label>\n                                <select id="usergroups<%- _id %>" name="usergroup_id" class="bind-usergroups">\n                                    <option value="null"><%- msg.G_PropertiesAutomatic %></option>\n                                    <option value="default"><%- msg.G_Default %></option>\n                                </select>\n                            </div>\n                            <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n                        </form>\n                    </div>\n                    <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_ClientsIPConfig %></div>\n                    </div>\n                    <div>\n                        <form action="" class="configIpForm">\n                            <fieldset>\n                                <div class="row">\n                                    <label for="useFixedIp<%- _id %>" class="label inline"><%- msg.G_ClientsFixedIP %></label>\n                                    <label class="label inline wrapper label-fit label-light"><input type="checkbox" class="checkbox" id="useFixedIp<%- _id %>" name="use_fixedip" value="1" /> <%- msg.G_ClientsUseFixedIP %></label>\n                                </div>\n                                <div class="row">\n                                    <label for="fixedNetwork<%- _id %>" class="label inline"><%- msg.G_Network %></label>\n                                    <select id="fixedNetwork<%- _id %>" name="network_id" class="bind-networks"></select>\n                                </div>\n                                <div class="row">\n                                    <label for="fixedIp<%- _id %>" class="label inline"><%- msg.G_IP %></label>\n                                    <input id="fixedIp<%- _id %>" type="text" class="input inline" name="fixed_ip" />\n                                </div>\n                            </fieldset>\n                            <button class="button is-admin" type="submit"><%- msg.G_Apply %></button>\n                        </form>\n                    </div>\n                    <div class="accordion-header is-admin">\n                        <div class="accordion-title"><%- msg.G_PropertiesDebug %></div>\n                    </div>\n                    <div class="is-admin">\n                        <div class="row">\n                            <table>\n                                <tr class="table-row">\n                                    <td class="column-name"><%- msg.G_PropertiesDeviceType %></td>\n                                    <td class="column-value"><%- get(\'oui\') %></td>\n                                </tr>\n                            </table>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </div>\n        <div class="dialog-controls is-admin clearfix">\n            <button class="button button-block left auto">\n                <span class="ui-button-icon-primary ubnt-icon-close sidebar-icons block bind-block"></span>\n                <span class="nav-text"><%- msg.G_Block %></span>\n            </button>\n            <button class="button button-unblock left auto">\n                <span class="ui-button-icon-primary ubnt-icon-close sidebar-icons unblock bind-unblock"></span>\n                <span class="nav-text"><%- msg.G_Unblock %></span>\n            </button>\n            <button class="button button-reconnect left narrow wireless-only">\n                <span class="ui-button-icon-primary ubnt-icon-reconnect sidebar-icons restart"></span>\n                <span class="nav-text"><%- msg.G_PropertiesReconnect %></span>\n            </button>\n            <button class="button button-unauthorize left narrow">\n                <span class="ui-button-icon-primary ubnt-icon-close sidebar-icons block"></span>\n                <span class="nav-text"><%- msg.G_PropertiesUnauthorize %></span>\n            </button>\n            <button class="button button-authorize left narrow">\n                <span class="ui-button-icon-primary ubnt-icon-close sidebar-icons block"></span>\n                <span class="nav-text"><%- msg.G_PropertiesAuthorize %></span>\n            </button>\n        </div>\n    </div>\n</div>\n'}),define("unifi/view/clients/PropertyView",["unifi/view/app/PropertyView","unifi/collection/ClientHistory","unifi/collection/UserGroups","unifi/collection/Networks","unifi/model/User","jquery","underscore","msg/Msg","libs/backgrid","ubnt/backgrid","text!includes/clients/clientsPropertiesTemplate.html"],function(e,t,n,r,i,s,o,u,a,f,l){"use strict";return e.extend({templateId:l,initialize:function(t){e.prototype.initialize.call(this,t),s.when(this._rendered=s.Deferred(),this._dependencies=s.Deferred()).then(this.populate,this.failed),this.user=new i,this.user.id=this.model.id,this.listenTo(this.user,"change",this.populateConfigIp),this.dependencies(),this.render()},bindings:function(){return{".bind-hostname":{observe:["name","hostname"],onGet:function(){this.$bindHostname.text(this.model.name()),this.$titleText.text(this.model.name())}},".bind-ip":"ip",".bind-uptime":{observe:"uptime",onGet:function(){this.$bindUptime.text(this.model.uptime())}},".bind-connected-ap":{observe:"ap_mac",onGet:this.populateDeviceName},".bind-connected-network":{observe:"network_id",onGet:function(e){if(e){var t=this.networks.get(e);this.$bindConnectedNetwork.text(t.get("name")),this.$selectNetwork.val(t.get("_id"))}}},".bind-connected-port":{observe:["gw_mac","sw_mac","sw_port"],onGet:this.populateDeviceName},".bind-last-seen":{observe:"last_seen",onGet:function(){this.$bindLastSeen.text(this.model.lastSeen())}},".bind-essid":"essid",".bind-channel":"channel",".bind-radio-type":{observe:["radio","radio_proto"],onGet:function(){this.$bindRadioType.text(this.model.radioType())}},".bind-rssi":{observe:"rssi",onGet:function(){this.$bindRssi.text(this.model.rssi())}},".bind-signal-with-dbm":{observe:"signal",onGet:function(){this.$bindSignalWithDbm.text(this.model.signalWithDbm())}},".bind-tx-rate":{observe:"tx_rate",onGet:function(){this.$bindTxRate.text(this.model.txRateInM())}},".bind-rx-rate":{observe:"rx_rate",onGet:function(){this.$bindRxRate.text(this.model.rxRateInM())}},".bind-activity":{observe:["tx_bytes-r","rx_bytes-r"],onGet:function(){this.$bindActivity.text(this.model.activity())}},".bind-powersave":{observe:"powersave_enabled",onGet:function(){this.$bindPowersave.text(this.model.powersave())}},".bind-received-packets":{observe:["rx_packets","rx_bytes"],onGet:function(){this.$bindReceivedPackets.text(this.model.receivedPacketsOverBytes())}},".bind-sent-packets":{observe:["tx_packets","tx_bytes"],onGet:function(){this.$bindSentPackets.text(this.model.sentPacketsOverBytes())}},".bind-oui":"oui"}},dependencies:function(){var e={UserGroups:n,Networks:r},t=[],i={},u=this;o.each(e,function(e,n){t.push(i[n]=s.Deferred())},this),t.push(i.user=s.Deferred()),s.when.apply(s,t).then(function(){u._dependencies.resolve()},function(){u._dependencies.reject()}),o.each(e,function(e,t){this.app.collection(t,{fetch:{reload:!1,deferred:i[t]}},e)},this),this.user.fetch({complete:function(){i.user.resolve()}})},render:function(r){var i=this.rendered;return e.prototype.render.call(this,r),i||(this.$titleText=this.$(".title-text"),this.$configForm=this.$(".configForm"),this.$configIpForm=this.$(".configIpForm"),this.$bindHostname=this.$(".bind-hostname"),this.$bindUptime=this.$(".bind-uptime"),this.$bindConnectedAP=this.$(".bind-connected-ap"),this.$bindConnectedNetwork=this.$(".bind-connected-network"),this.$bindConnectedPort=this.$(".bind-connected-port"),this.$bindLastSeen=this.$(".bind-last-seen"),this.$bindRadioType=this.$(".bind-radio-type"),this.$bindRssi=this.$(".bind-rssi"),this.$bindSignalWithDbm=this.$(".bind-signal-with-dbm"),this.$bindTxRate=this.$(".bind-tx-rate"),this.$bindRxRate=this.$(".bind-rx-rate"),this.$bindActivity=this.$(".bind-activity"),this.$bindPowersave=this.$(".bind-powersave"),this.$bindReceivedPackets=this.$(".bind-received-packets"),this.$bindSentPackets=this.$(".bind-sent-packets"),this.$bindUserGroups=this.$(".bind-usergroups"),this.$useFixedIp=this.$("input[name=use_fixedip]"),this.$fixedIp=this.$("input[name=fixed_ip]"),this.$selectNetwork=this.$("select[name=network_id]"),this.$buttonBlock=this.$(".button-block"),this.$buttonUnblock=this.$(".button-unblock"),this.$buttonBlock.on("click",this.block),this.$buttonUnblock.on("click",this.unblock),this.$(".button-reconnect").on("click",this.reconnect),this.$(".button-unauthorize").on("click",this.unauthorize),this.$(".button-authorize").on("click",this.authorize),this.$configForm.on("submit",this.updateConfig),this.$configIpForm.on("submit",this.updateConfigIp),this.$bindConnectedAP.on("click",this.displayConnectedAP),this.$bindConnectedPort.on("click",this.displayConnectedPort),this.$useFixedIp.on("change",s.proxy(function(e){var t=s(e.target);t.parents(".row").siblings().toggle(t.is(":checked")),t.is(":checked")&&this.renderSelects()},this)).trigger("change"),this.collections.history=new t({mac:this.model.get("mac")}),this.noClientHistoryRows=this.$(".data-table-clients-history").html(),this.model.on("change:name",this.onChangeName),this.model.on("change",this.populate),this.devices=this.app.collection("Devices"),this.devices.on("change",this.populateDeviceName),this.networks=this.app.collection("Networks"),this.listenTo(this.networks,"add remove change",this.setupNetworks),this.setupNetworks(),this.devices.on("change",this.toggleFixedIP),this.toggleFixedIP(),this.userGroups=this.app.collection("UserGroups",{},n),this.listenTo(this.userGroups,"add remove change",this.setupUserGroups),this._rendered.state()==="resolved"&&this._dependencies.state()=="resolved"?this.populate():this._rendered.state()==="pending"&&this._rendered.resolve(),this.stickit(this.model,this.bindings())),this},populate:function(){if(this._dependencies&&this._dependencies.state()=="resolved"){this.$el.find(".property-content .loading").remove();var e=this.model.isConnected(),t=this.model.get("is_wired"),n=this.model.get("is_guest"),r=this.model.get("blocked"),i=this.model.get("authorized");this.$el.removeClass("sta-connected sta-disconnected sta-isguest sta-authorized sta-blocked sta-wired sta-wireless"),this.$el.addClass("client-properties"),e?(this.$el.addClass("sta-connected"),n&&this.$el.addClass("sta-isguest"),i&&this.$el.addClass("sta-authorized")):this.$el.addClass("sta-disconnected"),t?this.$el.addClass("sta-wired"):this.$el.addClass("sta-wireless"),r&&this.$el.addClass("sta-blocked"),this.populateConfigIp(),this.setupUserGroups(),this.collections.history.fetch().done(this.historyTableGrid),this.position()}},populateConfigIp:function(){this.$useFixedIp.prop("checked",this.user.get("use_fixedip")).trigger("change"),this.$fixedIp.val(this.user.get("fixed_ip")||this.model.get("ip")),this.user.get("network_id")&&this.$selectNetwork.val(this.user.get("network_id"))},populateDeviceName:function(){var e,t="";this.model.get("is_wired")?(this.model.get("sw_mac")?(e=this.devices.getDeviceFromMac(this.model.get("sw_mac")))?t=e.name()+(this.model.get("sw_port")?" #"+this.model.get("sw_port"):""):t=this.model.get("sw_mac"):this.model.get("gw_mac")&&((e=this.devices.getDeviceFromMac(this.model.get("gw_mac")))?t=e.name():t=this.model.get("gw_mac")),this.$bindConnectedPort.text(t)):((e=this.model.get("ap_mac")?this.devices.getDeviceFromMac(this.model.get("ap_mac")):null)?t=e.name():t=this.model.get("ap_mac"),this.$bindConnectedAP.text(t))},onChangeName:function(){this.$(".hostname").text(this.model.get("name"))},block:function(){this.parent.rowBlock(this.model)},unblock:function(){this.parent.rowUnblock(this.model)},reconnect:function(){this.parent.rowReconnect(this.model,{success:s.proxy(function(){this.remove()},this)})},unauthorize:function(){var e=this;return this.model.unauthorize({success:function(){e.$el.removeClass("sta-authorized")}}),!1},authorize:function(){var e=this;return this.model.authorize({success:function(){}}),!1},updateConfig:function(e){e&&e.preventDefault();var t=this,n=this.$configForm.serializeObject(),r=this.$configForm.find('input[name="name"]'),i;return this.$configForm.find(".error").removeClass("error"),this.$configForm.find(".row-error").remove(),!this.model.get("name")&&n.name===""&&delete n.name,n.noted=n.note?!0:!1,i=this.model.save(n,{data:n,success:function(e,n){n.meta.rc==="ok"?t.showSavedState():t.showErrorState()},error:function(){t.showErrorState()}}),!i&&this.model.validationError&&this.model.validationError.name&&(r.addClass("error"),this.$configForm.find(".row").after(s('<div class="row row-error"></div>').text(this.model.validationError.name))),!1},toggleFixedIP:function(){var e=this.devices.where({type:"ugw",adopted:!0}),t=this.networks.where({dhcpd_enabled:!0}),n=e.length&&t.length;n?this.$useFixedIp.removeAttr("disabled"):this.$useFixedIp.attr("disabled","disabled")},updateConfigIp:function(e){e&&e.preventDefault(),this.$configIpForm.find(".error").removeClass("error"),this.$configIpForm.find(".error-msg").remove();var t=this,n=this.$configIpForm.find("input[name=use_fixedip]").is(":checked"),r={use_fixedip:n},i,a;n&&(r.network_id=this.$configIpForm.find("select[name=network_id]").val(),r.fixed_ip=this.$configIpForm.find("input[name=fixed_ip]").val(),r.network_id&&(i=this.networks.get(r.network_id))&&(a=i.get("ip_subnet")));var f=this.user.save(r,{extra:{subnet:a},success:function(e,n){n.meta.rc==="ok"?t.showSavedState():t.showErrorState()},error:function(e,n){t.app.views.app.flash("error","Error",u.apiError(n,!0))}});return!f&&this.user.validationError&&o.each(this.user.validationError,s.proxy(function(e,t){this.$configIpForm.find("[name="+t+"]").addClass("error").parent().append('<div class="error-msg">'+e+"</div>")},this)),!1},displayConnectedAP:function(){var e=this.app.routers.devices.views.index,t=e.collection.getDeviceFromMac(this.model.get("ap_mac"));return e.property(t),!1},displayConnectedPort:function(){var e=this.app.routers.devices.views.index,t=e.collection.getDeviceFromMac(this.model.get("sw_mac")?this.model.get("sw_mac"):this.model.get("gw_mac"));return e.property(t,{port:this.model.get("sw_mac")?this.model.get("sw_port"):"lan"}),!1},historyTableGrid:function(){if(!this.rendered)return!1;if(!this.grids.history){var e=[{name:"assoc_time",label:u.G_DateTime,editable:!1,cell:a.StringCell.extend({formatter:f.Formatters.Moment,className:"time-cell"})},{name:"duration",label:u.G_Duration,editable:!1,cell:a.StringCell.extend({formatter:f.Formatters.Duration,className:"duration-cell"})},{name:"tx_bytes",label:u.G_Down,editable:!1,cell:a.StringCell.extend({formatter:f.Formatters.Bytes,className:"down-cell"})},{name:"rx_bytes",label:u.G_Up,editable:!1,cell:a.StringCell.extend({formatter:f.Formatters.Bytes,className:"up-cell"})}];this.grids.history=this.grid(e,this.collections.history,this.$(".data-table-clients-history"),this.noClientHistoryRows)}},setupUserGroups:function(){var e=this,t=this.app.collection("UserGroups");this.$bindUserGroups.empty(),this.$bindUserGroups.append(s('<option value=""></option>').text(u.G_PropertiesAutomatic)),t.each(function(e){e.get("site_id")===SITE.id&&this.$bindUserGroups.append(s('<option value="'+e.get("_id")+'"></option>').text(e.get("name")))},this);if(this.model.get("usergroup_id")){this.$bindUserGroups.val(this.model.get("usergroup_id"));try{this.$bindUserGroups.selectmenu("refresh")}catch(n){}}},setupNetworks:function(){this.$selectNetwork.empty(),o.each(this.networks.filterByPurpose(["corporate","guest","voip"]),s.proxy(function(e){this.$selectNetwork.append(s('<option value="'+e.get("_id")+'"></option>').text(e.get("name")))},this));if(this.user.get("network_id")){this.$selectNetwork.val(this.user.get("network_id"));try{this.$selectNetwork.selectmenu("refresh")}catch(e){}}},remove:function(){this.stopListening(this.user,"change",this.populateConfigIp),this.$buttonBlock.off("click",this.block),this.$buttonUnblock.off("click",this.unblock),this.$(".button-reconnect").off("click",this.reconnect),this.$(".button-unauthorize").off("click",this.unauthorize),this.$(".button-authorize").off("click",this.authorize),this.$configForm.off("submit",this.updateConfig),this.$configIpForm.off("submit",this.updateConfigIp),this.$bindConnectedAP.off("click",this.displayConnectedAP),this.$bindConnectedPort.off("click",this.displayConnectedPort),this.$useFixedIp.off("change"),this.model.off("change:name",this.onChangeName),this.model.off("change",this.populate),this.devices.off("change",this.populateDeviceName),this.stopListening(this.networks,"add remove change",this.setupNetworks),this.devices.off("change",this.toggleFixedIP),this.stopListening(this.userGroups,"add remove change",this.setupUserGroups),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("text!includes/clients/clientsIndexTemplate.html",[],function(){return'<div class="section section-main">\n    <h1><%- msg.G_Clients %></h1>\n\n    <form class="data-filters clearfix">\n        <span class="ubnt-icon-search"></span>\n        <input type="text" name="search" class="search left" />\n        <div class="buttonset conn-filters">\n            <input type="radio" id="clientsFilterConnAll" name="conn-filter" value="conn-all" checked="checked" /><label for="clientsFilterConnAll"><%- msg.G_All %></label>\n            <input type="radio" id="clientsFilterConnWireless" name="conn-filter" value="wireless" /><label for="clientsFilterConnWireless"><%- msg.G_Wireless %></label>\n            <input type="radio" id="clientsFilterConnWired" name="conn-filter" value="wired" /><label for="clientsFilterConnWired"><%- msg.G_Wired %></label>\n        </div>\n        \n        <div class="buttonset wireless-filters">\n            <input type="radio" id="clientsFilterWirelessAll" name="wireless-filter" value="wireless-all" checked="checked" /><label for="clientsFilterWirelessAll"><%- msg.G_All %></label>\n            <input type="radio" id="clientsFilterWireless2g" name="wireless-filter" value="ng" /><label for="clientsFilterWireless2g"><%- msg.G_2G %></label>\n            <input type="radio" id="clientsFilterWireless5g" name="wireless-filter" value="na" /><label for="clientsFilterWireless5g"><%- msg.G_5G %></label>\n        </div>\n\n        <div class="buttonset access-filters">\n            <input type="radio" id="clientsFilterAccessAll" name="access-filter" value="access-all" /><label for="clientsFilterAccessAll"><%- msg.G_All %></label>\n            <input type="radio" id="clientsFilterAccessUsers" name="access-filter" value="users" checked="checked" /><label for="clientsFilterAccessUsers"><%- msg.G_Users %></label>\n            <input type="radio" id="clientsFilterAccessGuests" name="access-filter" value="guests" /><label for="clientsFilterAccessGuests"><%- msg.G_Guests %></label>\n        </div>\n\n        <div class="network-filters">\n            <div class="ap-filter">\n                <select name="ap-filter" data-label="AP: "></select>\n            </div>\n            <div class="network-filter">\n                <select name="network-filter" data-label="Network: "></select>\n            </div>\n        </div>\n\n        <div class="right">\n            <select name="items-per-page" data-label="<%- msg.G_FilterItemsPerPage %>">\n                <option value="10">10</option>\n                <option value="50" selected="selected">50</option>\n                <option value="100">100</option>\n                <option value="200">200</option>\n            </select>\n        </div>\n    </form>\n\n    <div class="data-table untitled">\n        <div class="loading"><span><%- msg.N_Loading %></span></div>\n    </div>\n</div>'}),define("unifi/view/clients/IndexView",["unifi/view/app/ListContentView","unifi/view/clients/PropertyView","ubnt/view/dialogs/ConfirmDialogView","libs/backgrid","ubnt/backgrid","underscore","jquery","msg/Msg","unifi/collection/Clients","unifi/collection/insights/KnownClients","unifi/collection/Networks","text!includes/clients/clientsIndexTemplate.html","libs/jquery.cookie"],function(e,t,n,r,i,s,o,u,a,f,l,c){"use strict";return e.extend({id:"clientsIndex",_templateId:c,_collectionType:{name:"Clients",Class:a},_pageable:!0,initialize:function(t){this.properties={},e.prototype.initialize.call(this,t)},render:function(){var t=this.rendered;e.prototype.render.call(this,!0),t||(this.$apFilter=this.$el.find("select[name=ap-filter]"),this.$networkFilter=this.$el.find("select[name=network-filter]"),this._rendered.resolve())},columns:function(){var e=this;return[{name:"hostname",label:u.G_ClientsNameMACAddress,customClass:"column-name",editable:!1,sortValue:"name",sortFormatter:"toLowerCase",headerCell:i.Headers.customSortHeader,cell:i.Cells.ModelCell.extend({callback:"name"}),callback:this.property,title:"mac"},{name:"ip",label:u.G_IPAddress,customClass:"column-ip",editable:!1,sortValue:"ip2long",headerCell:i.Headers.customSortHeader,cell:"string"},{name:"status",label:u.G_Status,customClass:"column-status",editable:!1,cell:i.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(e){if(!e.get("is_wired"))return e.get("authorized")?o('<span class="ok">'+u.G_ClientsAuthorized+"</span>"):o('<span class="pending">'+u.G_ClientsPending+"</span>")},toRaw:function(e){return e}}})},{name:"network",label:u.G_ClientsConnection,customClass:"column-connection",editable:!1,sortValue:"connection",headerCell:i.Headers.customSortHeader,cell:i.Cells.ModelCell.extend({callback:"connection"})},{name:"network",label:u.G_Network,customClass:"column-network",editable:!1,cell:"string"},{name:"essid",label:u.G_ClientsWLAN,customClass:"column-wlan",editable:!1,cell:"string"},{name:"sw_port",label:u.G_Port,customClass:"column-port",editable:!1,sortValue:"wired_connection",headerCell:i.Headers.customSortHeader,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.app.collection("Devices"),r;if(t.get("sw_mac"))return(r=n.getDeviceFromMac(t.get("sw_mac")))?r.name()+t.switch_port_suffix(!1):t.get("sw_mac");if(t.get("gw_mac"))return(r=n.getDeviceFromMac(t.get("gw_mac")))?r.name():t.get("gw_mac")},toRaw:function(e){return e}}}),callback:function(t){var n=e.app.routers.devices.views.index,r=n.collection.getDeviceFromMac(t.get("sw_mac")?t.get("sw_mac"):t.get("gw_mac"));n.property(r,{port:t.get("sw_mac")?t.get("sw_port"):"lan"})},title:function(e){return e.get("sw_mac")||e.get("gw_mac")}},{name:"ap_mac",label:u.G_ClientsAP,customClass:"column-ap",editable:!1,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.app.collection("Devices"),r=t.get("ap_mac")?n.getDeviceFromMac(t.get("ap_mac")):null;return r?r.name():t.get("ap_mac")},toRaw:function(e){return e}}}),callback:function(t){var n=e.app.routers.devices.views.index,r=n.collection.getDeviceFromMac(t.get("ap_mac"));n.property(r)},title:"ap_mac"},{name:"sw_mac",label:u.G_ClientsAPPort,customClass:"column-apport",editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.app.collection("Devices"),r;if(!t.get("is_wired"))return r=t.get("ap_mac")?n.getDeviceFromMac(t.get("ap_mac")):null,r?r.name():t.get("ap_mac");if(t.get("sw_mac"))return(r=n.getDeviceFromMac(t.get("sw_mac")))?r.name()+t.switch_port_suffix(!1):t.get("sw_mac");if(t.get("gw_mac"))return(r=n.getDeviceFromMac(t.get("gw_mac")))?r.name():t.get("gw_mac")},toRaw:function(e){return e}}}),callback:function(t){var n=e.app.routers.devices.views.index,r;t.get("is_wired")?(r=n.collection.getDeviceFromMac(t.get("sw_mac")?t.get("sw_mac"):t.get("gw_mac")),n.property(r,{port:t.get("sw_mac")?t.get("sw_port"):"lan"})):(r=n.collection.getDeviceFromMac(t.get("ap_mac")),n.property(r))},title:"ap_mac"},{name:"rssi",label:u.G_Signal,customClass:"column-signal",editable:!1,cell:i.Cells.ComplexHtmlCell.extend({className:"rssiWithRadio",formatter:{fromRaw:function(e){var t=e.rssi(),n="sprite-";return n+=e.radioType(),n+="-"+(e.is5g()?"5g":"2g"),n+=e.get("powersave_enabled")?"-powersave":"",'<span class="signal-value">'+t+'</span><span class="signal-icon '+n+'"></span>'},toRaw:function(e){return e}}})},{name:"tx_bytes",label:u.G_Down,customClass:"column-down",editable:!1,cell:r.StringCell.extend({formatter:i.Formatters.Bytes})},{name:"rx_bytes",label:u.G_Up,customClass:"column-up",editable:!1,cell:r.StringCell.extend({formatter:i.Formatters.Bytes})},{name:"bytes-r",label:u.G_Activity,customClass:"column-activity",editable:!1,cell:i.Cells.HtmlCell.extend({formatter:s.extend({},i.Formatters.Grid,{className:"green-cells",levels:[2048e3,512e3,64e3,8e3,500]})})},{name:"uptime",label:u.G_Uptime,customClass:"column-uptime",editable:!1,cell:r.StringCell.extend({formatter:i.Formatters.Seconds})},{name:"_id",label:u.G_Actions,customClass:"column-actions is-admin",editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ActionsCell.extend({actions:{block:{icon:"ubnt-icon-close",callback:this.rowBlock,requiresAdminPrivilege:!0,render:function(e){return!e.get("blocked")}},unblock:{icon:"ubnt-icon-close",callback:this.rowUnblock,requiresAdminPrivilege:!0,render:function(e){return e.get("blocked")}},reconnect:{icon:"ubnt-icon-reconnect",callback:this.rowReconnect,requiresAdminPrivilege:!0,buttonClasses:"narrow",render:function(e){return!e.get("is_wired")}},authorize:{icon:"ubnt-icon-authrize",callback:this.rowAuthorize,requiresAdminPrivilege:!0,buttonClasses:"narrow",render:function(e){return!e.get("is_wired")&&e.get("is_guest")&&!e.get("authorized")}},unauthorize:{icon:"ubnt-icon-unauthrize",callback:this.rowUnauthorize,requiresAdminPrivilege:!0,buttonClasses:"narrow",render:function(e){return!e.get("is_wired")&&e.get("is_guest")&&e.get("authorized")}}}})}]},load:function(t,n){return n=n||{},n.reset=!0,e.prototype.load.call(this,t,n)},grid:function(){this._gridRowClassName=this.gridRowClassName,e.prototype.grid.call(this);var t=this.grids.content,n=this.$el.find(".network-filters .ap-filter"),r=this.$el.find(".network-filters .network-filter"),i=this.$el.find(".buttonset.conn-filters"),u=i.find("input[name=conn-filter]"),a=this.$el.find(".buttonset.wireless-filters"),f=a.find("input[name=wireless-filter]"),c=this.$el.find(".buttonset.access-filters"),h=c.find("input[name=access-filter]"),p=[],d=[],v=[];return this.devices=this.app.collection("Devices"),this.listenTo(this.devices,"add remove change",s.debounce(this.setupApFilter,250)),this.setupApFilter(),this.networks=this.app.collection("Networks",{fetch:{reload:!1}},l),this.listenTo(this.networks,"add remove change",this.setupNetworkFilter),this.setupNetworkFilter(),this.$el.find('.buttonset input[name=conn-filter][value="conn-all"]').click(),this.$el.find('.buttonset input[name=wireless-filter][value="wireless-all"]').click(),this.$el.find('.buttonset input[name=access-filter][value="access-all"]').click(),s.each(u,function(e,t){p.push(e.value)}),s.each(f,function(e,t){d.push(e.value)}),s.each(h,function(e,t){v.push(e.value)}),u.on("change",function(e){var i=o(this).val();i=="wired"?(t.setFilter("is_wired",!0,1),n.hide(),r.show()):i=="wireless"?(t.setFilter("is_wired",!0,-1),n.show(),r.hide()):(t.removeFilter("is_wired"),n.hide(),r.hide()),i=="wireless"?a.show():a.hide(),t.$el.removeClass(p.join(" ")).addClass(i||p[0]),f.filter(":checked").trigger("change"),n.trigger("change"),r.trigger("change"),o.cookie("filterClientConn",i)}).filter(":checked").trigger("change"),f.on("change",function(){var e=o(this),n=e.val(),r=e.is(":visible");!r||n!="na"&&n!="ng"?t.removeFilter("radio"):t.setFilter("radio",n,1),t.$el.removeClass(d.join(" ")).addClass(r?n||d[0]:""),o.cookie("filterClientWireless",n)}).filter(":checked").trigger("change"),h.on("change",function(){var e=o(this).val();e=="users"?t.setFilter("is_guest",!1,1):e=="guests"?t.setFilter("is_guest",!0,1):t.removeFilter("is_guest"),t.$el.removeClass(v.join(" ")).addClass(e||v[0]),o.cookie("filterClientAccess",e)}).filter(":checked").trigger("change"),n.on("change",function(){var e=o(this),n=e.find("option:selected").val(),r=e.is(":visible");r&&n?t.setFilter("ap_mac",n,1):t.removeFilter("ap_mac")}),r.on("change",function(){var e=o(this),n=e.find("option:selected").val(),r=e.is(":visible");r&&n?t.setFilter("network",n,1):t.removeFilter("network")}),this},gridRowClassName:function(e){return"id-"+e.id},property:function(e){if(!e)throw"Missing model";var n=e.get("mac")||e.id;this.properties[n]?(this.properties[n].model=e,this.properties[n].render()):this.properties[n]=new t({properties:this.app.views.app.views.properties,parent:this,model:e,count:s.size(this.properties)+1,show:!0})},updateBlocked:function(e,t){var n=this.app.collection("Clients",{},a),r=this.grids.content;s.each(n.where({mac:e}),function(e){e.set({blocked:t})});var i=this.app.collection("KnownClients",{},f);s.each(i.where({mac:e}),function(e){e.set({blocked:t})})},rowUnblock:function(e){var t=this;e.unblock({success:function(n,r,i){t.updateBlocked(e.get("mac"),!1)},error:function(e,n,r){t.app.views.app.flash("error","Error",u.apiError(e,!0))}})},rowBlock:function(e){var t=this,r=t.app.collection("Devices").getInformIP(),i=function(){e.block({success:function(n,r,i){t.updateBlocked(e.get("mac"),!0)},error:function(e,n,r){t.app.views.app.flash("error","Error",u.apiError(e,!0))}})};e.get("ip")===r?(new n).show(u.localize(u.N_ConfirmBlockController,e.get("mac")),i):i()},rowReconnect:function(e,t){var n=this;e.reconnect({success:function(e,r,i){n.app.refresh(),t&&t.success&&t.success()},error:function(e,t,r){n.app.views.app.flash("error","Error",u.apiError(e))}})},updateAuthorized:function(e,t){var n=this.app.collection("Clients",{},a);s.each(n.where({mac:e}),function(e){e.set({authorized:t})})},rowAuthorize:function(e,t){var n=this;e.authorize({success:function(t,r,i){n.updateAuthorized(e.get("mac"),!0)},error:function(e,t,r){n.app.views.app.flash("error","Error",u.apiError(e))}})},rowUnauthorize:function(e,t){var n=this;e.unauthorize({success:function(e,t,r){n.app.refresh()},error:function(e,t,r){n.app.views.app.flash("error","Error",u.apiError(e))}})},setupApFilter:function(){var e=this.$apFilter.find("option:selected").val();this.$apFilter.empty(),this.$apFilter.append(o('<option value=""></option>').text(u.G_All)),this.devices&&s.each(this.devices.where({type:this.devices.typeMap.ap}),o.proxy(function(e){e.isConnected()&&this.$apFilter.append(o("<option />").attr("value",e.get("mac")).text(e.name()))},this)),this.$apFilter.val(e),this.$apFilter.selectmenu("refresh")},setupNetworkFilter:function(){var e=this.$networkFilter.find("option:selected").val();this.$networkFilter.empty(),this.$networkFilter.append(o('<option value=""></option>').text(u.G_All)),this.networks&&s.each(this.networks.filterByPurpose(["corporate","guest","voip","vlan-only"]),o.proxy(function(e){this.$networkFilter.append(o("<option />").attr("value",e.get("name")).text(e.get("name")))},this)),this.$networkFilter.val(e),this.$networkFilter.selectmenu("refresh")},remove:function(){this.rendered=!1,this.stopListening(this.devices),this.stopListening(this.networks),this.$el.find(".buttonset.conn-filters input[name=conn-filter]").off("change"),e.prototype.remove.apply(this,arguments)}})}),define("unifi/router/ClientsRouter",["unifi/router/Router","unifi/view/clients/IndexView","unifi/view/clients/PropertyView"],function(e,t,n){"use strict";return e.extend({_fullyQualifiedName:"UNIFI.Routers.Clients",_associatedViews:{Index:t,Property:n},routes:{clients:"index"}})}),define("unifi/model/Call",["unifi/model/Model","jquery","backbone","msg/Msg"],function(e,t,n,r){"use strict";return e.extend({terminate:function(e){this.sync("terminate",this,e)},toName:function(){return this.get("to_number")},fromName:function(){return this.get("from_number")},sync:function(e,t,r){r=r||{};switch(e){case"terminate":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/cmd/unitel",r.type="POST",r.data=JSON.stringify({id:t.id,cmd:"terminate"})}return n.sync.call(this,e,t,r)}})}),define("unifi/collection/Calls",["unifi/collection/Collection","unifi/model/Call"],function(e,t){"use strict";return e.extend({model:t,bySite:!0,filterByToExtension:function(e){return this.find({to_extension:e})},filterByFromExtension:function(e){return this.find({from_extension:e})},filterByExtension:function(e){return this.filter(function(t){return t.get("to_type")=="extension"&&t.get("to_extension")==e||t.get("to_type")=="branch_extension"&&t.get("to_extension")==e||t.get("from_type")=="extension"&&t.get("from_extension")==e||t.get("from_type")=="branch_extension"&&t.get("from_extension")==e})},url:function(){return"/api/s/"+SITE.name+"/stat/calls"}})}),define("unifi/model/Branch",["unifi/model/Model","jquery","backbone","underscore","msg/Msg"],function(e,t,n,r,i){"use strict";return e.extend({url:function(){return"/api/s/"+SITE.name+"/cmd/unitel"},sync:function(e,t,i){switch(e){case"create":i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify(r.extend(t.toJSON(i),{cmd:"add-branch"}));break;case"delete":i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify({admin:t.id,cmd:"del-branch"})}return n.sync.call(this,e,t,i)}})}),define("unifi/collection/Branches",["unifi/collection/Collection","unifi/model/Branch","backbone"],function(e,t,n){"use strict";return e.extend({model:t,bySite:!0,url:function(){return"/data/branches.json"},sync:function(e,t,r){switch(e){case"read":r.type="POST",r.data=JSON.stringify({cmd:"get-branches"})}return n.sync.call(this,e,t,r)}})}),define("text!includes/calls/callsIndexTemplate.html",[],function(){return'<div class="section section-main">\n    <h1><%- msg.G_Calls %></h1>\n\n    <form class="data-filters clearfix">\n        <span class="ubnt-icon-search"></span>\n        <input type="text" name="search" class="search left" />\n        <div class="buttonset direction-filters">\n            <input type="radio" id="callsFilterDirAll" name="direction-filter" value="direction-all" checked="checked" /><label for="callsFilterDirAll"><%- msg.G_All %></label>\n            <input type="radio" id="callsFilterDirIncoming" name="direction-filter" value="incoming" /><label for="callsFilterDirIncoming"><%- msg.G_Incoming %></label>\n            <input type="radio" id="callsFilterDirOutgoing" name="direction-filter" value="outgoing" /><label for="callsFilterDirOutgoing"><%- msg.G_Outgoing %></label>\n            <input type="radio" id="callsFilterDirInternal" name="direction-filter" value="internal" /><label for="callsFilterDirInternal"><%- msg.G_Internal %></label>\n        </div>\n        \n        <div class="select left">\n            <select name="time-filter" id="callsTimeframe">\n                <option value="1" selected="selected">1 <%- msg.G_Hour %></option>\n                <option value="8">8 <%- msg.G_Hours %></option>\n                <option value="24">24 <%- msg.G_Hours %></option>\n                <option value="48">2 <%- msg.G_Days %></option>\n                <option value="168">7 <%- msg.G_Days %></option>\n                <option value="336">2 <%- msg.G_Weeks %></option>\n                <option value="720">1 <%- msg.G_Month %></option>\n            </select>\n        </div>\n        \n        <div class="right">\n            <div class="select left">\n                <select name="items-per-page" data-label="<%- msg.G_FilterItemsPerPage %>">\n                    <option value="10">10</option>\n                    <option value="50" selected="selected">50</option>\n                    <option value="100">100</option>\n                    <option value="200">200</option>\n                </select>\n            </div>\n            \n            <button id="manageExtensions" class="button auto narrow"><%- msg.G_CallsManageExtensions %></button>\n        </div>\n    </form>\n\n    <div class="data-table untitled">\n        <div class="loading"><span><%- msg.N_Loading %></span></div>\n    </div>\n</div>\n'}),define("unifi/view/calls/IndexView",["unifi/view/app/ListContentView","unifi/view/app/CallsMixin","libs/backgrid","ubnt/backgrid","underscore","jquery","msg/Msg","unifi/collection/Calls","unifi/collection/Extensions","unifi/collection/Branches","text!includes/calls/callsIndexTemplate.html","libs/jquery.cookie"],function(e,t,n,r,i,s,o,u,a,f,l){"use strict";return e.extend(i.extend({},t,{id:"callsIndex",_templateId:l,_collectionType:{name:"Calls",Class:u},_pageable:!0,_limitTimeframe:1,columns:function(){var e=this;return[{name:"direction",customClass:"column-icon",editable:!1,sortable:!1,headerCell:r.Headers.emptyHeader,cell:r.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(e){var t=e.get("direction"),n=s("<div />");return t==="incoming"?n.addClass("ubnt-icon-enter"):t==="outgoing"&&n.addClass("ubnt-icon-exit"),n},toRaw:function(e){return e}}})},{name:"direction",label:o.G_CallsDirection,customClass:"column-direction",editable:!1,cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var t=e.get("direction");return t==="incoming"?o.G_Incoming:t==="outgoing"?o.G_Outgoing:t==="internal"?o.G_Internal:o.G_Uknown},toRaw:function(e){return e}}})},{name:"from_number",label:o.G_CallsOrigin,customClass:"column-origin",editable:!1,sortValue:"fromName",headerCell:r.Headers.customSortHeader,cell:r.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(e){return e.get("from_number")},toRaw:function(e){return e}}})},{name:"to_number",label:o.G_CallsRecipient,customClass:"column-recipient",editable:!1,sortValue:"toName",headerCell:r.Headers.customSortHeader,cell:r.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(e){return e.get("to_number")+(e.get("is_international")?o.G_CallIsInternational:"")},toRaw:function(e){return e}}})},{name:"status",label:o.G_Status,customClass:"column-status",editable:!1,cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var t=e.get("status");switch(t){case"answer":return o.G_CallsStatusAnswered;case"no_answer":return e.get("is_group")?o.G_CallsStatusGroupNoAnswer:o.G_CallsStatusNoAnswer;case"rejected":return o.G_CallsStatusRejected;case"voicemail":return o.G_CallsStatusVoicemail;case"transfer":return o.G_CallsStatusTransferTo+e.get("transfer_to");case"conference":return o.G_CallsStatusConference}},toRaw:function(e){return e}}})},{name:"start_time",label:o.G_CallsStartTime,customClass:"column-start_time",editable:!1,cell:n.StringCell.extend({formatter:r.Formatters.Moment,className:"time-cell"})},{name:"duration",label:o.G_Duration,customClass:"column-duration",editable:!1,cell:n.StringCell.extend({formatter:r.Formatters.Duration,className:"time-cell"})}]},load:function(t){t=t||!this.collection;if(!this.collection||t)this.collection&&this.collection.reset(),e.prototype.load.call(this,t,{data:{within:this._limitTimeframe}})},dependencies:function(){var e={Extensions:a},t=[],n={},r=this;i.each(e,function(e,r){t.push(n[r]=s.Deferred())},this),s.when.apply(s,t).then(function(){r._dependencies.resolve()},function(){r._dependencies.reject()}),i.each(e,function(e,t){this.app.collection(t,{fetch:{reload:!1,deferred:n[t]}},e)},this)},render:function(t){var n=this.rendered;e.prototype.render.call(this,t),n||(this.$el.on("click","td .ext",s.proxy(function(e){e.preventDefault()},this)),this.$("#manageExtensions").button().on("click",s.proxy(function(){this.app.views.app.openSettings("extensions")},this)))},grid:function(){var t=this.app.collection("Extensions");this.listenTo(t,"add remove reset sync change",this.addNamesToCalls),this.listenTo(this.collection,"reset sync",this.addNamesToCalls),this.listenTo(this.collection,"add remove sync change",this.addNamesToCall),this.addNamesToCalls(),this._gridRowClassName=this.gridRowClassName,e.prototype.grid.call(this);var n=this.grids.content,r=this.$el.find(".buttonset.direction-filters"),o=r.find("input[name=direction-filter]"),u=[];return this.$el.find('.buttonset input[name=direction-filter][value="direction-all"]').click(),i.each(o,function(e,t){u.push(e.value)}),o.on("change",function(e){var t=s(this).val();"direction-all"===t?n.removeFilter("direction"):n.setFilter("direction",t,1),n.$el.removeClass(u.join(" ")).addClass(t||u[0]),s.cookie("filterCallsDirection",t)}).filter(":checked").trigger("change"),this.$el.find('select[name="time-filter"]').on("change",s.proxy(function(e){this._limitTimeframe=s(e.target).find("option:selected").val(),this.load(!0)},this)),this},gridRowClassName:function(e){return"id-"+e.id},addNamesToCalls:i.throttle(s.proxy(function(){if(!this.collection)return;this.collection.each(this.addNameToCall)},this),1e3),addNameToCall:function(e){var t=this.app.collection("Extensions"),n;(n=t.findWhere({extension:e.get("to_number")}))&&e.set({to_name:n.get("name")}),(n=t.findWhere({extension:e.get("from_number")}))&&e.set({from_name:n.get("name")})},rowExtension:function(e){var t=this.app.collection("Extensions").filterByExtension(e);t&&this.options.app.views.app.openSettings("extensions",t.id)},rowTerminate:function(e,t){var n=this;e.terminate({success:function(e,r,i){n.app.refresh(),t&&t.success&&t.success()},error:function(e,t,r){n.app.views.app.flash("error","Error",o.apiError(e))}})},remove:function(){this.rendered=!1,this.$el.off("click","td .ext"),this.$("#manageExtensions").off("click"),this.stopListening(this.app.collection("Extensions")),this.stopListening(this.collection),this.$el.find(".buttonset.direction-filters input[name=direction-filter]").off("change"),this.$el.find('select[name="time-filter"]').off("change"),e.prototype.remove.apply(this,arguments)}}))}),define("unifi/router/CallsRouter",["unifi/router/Router","unifi/view/calls/IndexView"],function(e,t){"use strict";return e.extend({_fullyQualifiedName:"UNIFI.Routers.Calls",_associatedViews:{Index:t},routes:{calls:"index"}})}),d3=function(){function p(e){return e!=null&&!isNaN(e)}function v(e){return e.length}function g(e){var t=1;while(e*t%1)t*=10;return t}function y(e,t){try{for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}catch(r){e.prototype=t}}function b(){}function S(){}function x(e,t,n){return function(){var r=n.apply(t,arguments);return r===t?e:r}}function T(e,t){if(t in e)return t;t=t.charAt(0).toUpperCase()+t.substring(1);for(var n=0,r=N.length;n<r;++n){var i=N[n]+t;if(i in e)return i}}function C(){}function k(){}function L(e){function r(){var n=t,r=-1,i=n.length,s;while(++r<i)(s=n[r].on)&&s.apply(this,arguments);return e}var t=[],n=new b;return r.on=function(r,i){var s=n.get(r),o;return arguments.length<2?s&&s.on:(s&&(s.on=null,t=t.slice(0,o=t.indexOf(s)).concat(t.slice(o+1)),n.remove(r)),i&&t.push(n.set(r,{on:i})),e)},r}function A(){e.event.preventDefault()}function O(){var t=e.event,n;while(n=t.sourceEvent)t=n;return t}function M(t){var n=new k,r=0,i=arguments.length;while(++r<i)n[arguments[r]]=L(n);return n.of=function(r,i){return function(s){try{var o=s.sourceEvent=e.event;s.target=t,e.event=s,n[s.type].apply(r,i)}finally{e.event=o}}},n}function P(e){return D(e,I),e}function q(e){return typeof e=="function"?e:function(){return H(e,this)}}function R(e){return typeof e=="function"?e:function(){return B(e,this)}}function z(t,n){function r(){this.removeAttribute(t)}function i(){this.removeAttributeNS(t.space,t.local)}function s(){this.setAttribute(t,n)}function o(){this.setAttributeNS(t.space,t.local,n)}function u(){var e=n.apply(this,arguments);e==null?this.removeAttribute(t):this.setAttribute(t,e)}function a(){var e=n.apply(this,arguments);e==null?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}return t=e.ns.qualify(t),n==null?t.local?i:r:typeof n=="function"?t.local?a:u:t.local?o:s}function W(e){return e.trim().replace(/\s+/g," ")}function X(t){return new RegExp("(?:^|\\s+)"+e.requote(t)+"(?:\\s+|$)","g")}function V(e,t){function r(){var r=-1;while(++r<n)e[r](this,t)}function i(){var r=-1,i=t.apply(this,arguments);while(++r<n)e[r](this,i)}e=e.trim().split(/\s+/).map($);var n=e.length;return typeof t=="function"?i:r}function $(e){var t=X(e);return function(n,r){if(i=n.classList)return r?i.add(e):i.remove(e);var i=n.getAttribute("class")||"";r?(t.lastIndex=0,t.test(i)||n.setAttribute("class",W(i+" "+e))):n.setAttribute("class",W(i.replace(t," ")))}}function J(e,t,n){function r(){this.style.removeProperty(e)}function i(){this.style.setProperty(e,t,n)}function s(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}return t==null?r:typeof t=="function"?s:i}function K(e,t){function n(){delete this[e]}function r(){this[e]=t}function i(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}return t==null?n:typeof t=="function"?i:r}function Q(t){return typeof t=="function"?t:(t=e.ns.qualify(t)).local?function(){return this.ownerDocument.createElementNS(t.space,t.local)}:function(){return this.ownerDocument.createElementNS(this.namespaceURI,t)}}function G(e){return{__data__:e}}function Y(e){return function(){return F(this,e)}}function Z(t){return arguments.length||(t=e.ascending),function(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}}function et(e,t){for(var n=0,r=e.length;n<r;n++)for(var i=e[n],s=0,o=i.length,u;s<o;s++)(u=i[s])&&t(u,s,n);return e}function tt(e){return D(e,nt),e}function rt(e){var t,n;return function(r,i,s){var o=e[s].update,u=o.length,a;s!=n&&(n=s,t=0),i>=t&&(t=i+1);while(!(a=o[t])&&++t<u);return a}}function it(){var e=this.__transition__;e&&++e.active}function ot(t,r,i){function f(){var e=this[s];e&&(this.removeEventListener(t,e,e.$),delete this[s])}function l(){var e=u(r,n(arguments));f.call(this),this.addEventListener(t,this[s]=e,e.$=i),e._=r}function c(){var n=new RegExp("^__on([^.]+)"+e.requote(t)+"$"),r;for(var i in this)if(r=i.match(n)){var s=this[i];this.removeEventListener(r[1],s,s.$),delete this[i]}}var s="__on"+t,o=t.indexOf("."),u=at;o>0&&(t=t.substring(0,o));var a=ut.get(t);return a&&(t=a,u=ft),o?r?l:f:r?C:c}function at(t,n){return function(r){var i=e.event;e.event=r,n[0]=this.__data__;try{t.apply(this,n)}finally{e.event=i}}}function ft(e,t){var n=at(e,t);return function(e){var t=this,r=e.relatedTarget;(!r||r!==t&&!(r.compareDocumentPosition(t)&8))&&n.call(t,e)}}function ht(){var t=".dragsuppress-"+ ++ct,n="click"+t,r=e.select(s).on("touchmove"+t,A).on("dragstart"+t,A).on("selectstart"+t,A);if(lt){var o=i.style,u=o[lt];o[lt]="none"}return function(e){r.on(t,null),lt&&(o[lt]=u);if(e){function i(){r.on(n,null)}r.on(n,function(){A(),i()},!0),setTimeout(i,0)}}}function dt(t,n){n.changedTouches&&(n=n.changedTouches[0]);var r=t.ownerSVGElement||t;if(r.createSVGPoint){var i=r.createSVGPoint();if(pt<0&&(s.scrollX||s.scrollY)){r=e.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();pt=!o.f&&!o.e,r.remove()}return pt?(i.x=n.pageX,i.y=n.pageY):(i.x=n.clientX,i.y=n.clientY),i=i.matrixTransform(t.getScreenCTM().inverse()),[i.x,i.y]}var u=t.getBoundingClientRect();return[n.clientX-u.left-t.clientLeft,n.clientY-u.top-t.clientTop]}function St(e){return e>0?1:e<0?-1:0}function xt(e){return e>1?0:e<-1?vt:Math.acos(e)}function Tt(e){return e>1?gt:e<-1?-gt:Math.asin(e)}function Nt(e){return((e=Math.exp(e))-1/e)/2}function Ct(e){return((e=Math.exp(e))+1/e)/2}function kt(e){return((e=Math.exp(2*e))-1)/(e+1)}function Lt(e){return(e=Math.sin(e/2))*e}function Ht(){}function Bt(e,t,n){return new jt(e,t,n)}function jt(e,t,n){this.h=e,this.s=t,this.l=n}function It(e,t,n){function s(e){return e>360?e-=360:e<0&&(e+=360),e<60?r+(i-r)*e/60:e<180?i:e<240?r+(i-r)*(240-e)/60:r}function o(e){return Math.round(s(e)*255)}var r,i;return e=isNaN(e)?0:(e%=360)<0?e+360:e,t=isNaN(t)?0:t<0?0:t>1?1:t,n=n<0?0:n>1?1:n,i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i,sn(o(e+120),o(e),o(e-120))}function qt(e,t,n){return new Rt(e,t,n)}function Rt(e,t,n){this.h=e,this.c=t,this.l=n}function zt(e,t,n){return isNaN(e)&&(e=0),isNaN(t)&&(t=0),Wt(n,Math.cos(e*=wt)*t,Math.sin(e)*t)}function Wt(e,t,n){return new Xt(e,t,n)}function Xt(e,t,n){this.l=e,this.a=t,this.b=n}function Gt(e,t,n){var r=(e+16)/116,i=r+t/500,s=r-n/200;return i=Zt(i)*$t,r=Zt(r)*Jt,s=Zt(s)*Kt,sn(tn(3.2404542*i-1.5371385*r-.4985314*s),tn(-0.969266*i+1.8760108*r+.041556*s),tn(.0556434*i-.2040259*r+1.0572252*s))}function Yt(e,t,n){return e>0?qt(Math.atan2(n,t)*Et,Math.sqrt(t*t+n*n),e):qt(NaN,NaN,e)}function Zt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function en(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function tn(e){return Math.round(255*(e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function nn(e){return sn(e>>16,e>>8&255,e&255)}function rn(e){return nn(e)+""}function sn(e,t,n){return new on(e,t,n)}function on(e,t,n){this.r=e,this.g=t,this.b=n}function an(e){return e<16?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function fn(e,t,n){var r=0,i=0,s=0,o,u,a;o=/([a-z]+)\((.*)\)/i.exec(e);if(o){u=o[2].split(",");switch(o[1]){case"hsl":return n(parseFloat(u[0]),parseFloat(u[1])/100,parseFloat(u[2])/100);case"rgb":return t(pn(u[0]),pn(u[1]),pn(u[2]))}}return(a=dn.get(e))?t(a.r,a.g,a.b):(e!=null&&e.charAt(0)==="#"&&(e.length===4?(r=e.charAt(1),r+=r,i=e.charAt(2),i+=i,s=e.charAt(3),s+=s):e.length===7&&(r=e.substring(1,3),i=e.substring(3,5),s=e.substring(5,7)),r=parseInt(r,16),i=parseInt(i,16),s=parseInt(s,16)),t(r,i,s))}function ln(e,t,n){var r=Math.min(e/=255,t/=255,n/=255),i=Math.max(e,t,n),s=i-r,o,u,a=(i+r)/2;return s?(u=a<.5?s/(i+r):s/(2-i-r),e==i?o=(t-n)/s+(t<n?6:0):t==i?o=(n-e)/s+2:o=(e-t)/s+4,o*=60):(o=NaN,u=a>0&&a<1?0:o),Bt(o,u,a)}function cn(e,t,n){e=hn(e),t=hn(t),n=hn(n);var r=en((.4124564*e+.3575761*t+.1804375*n)/$t),i=en((.2126729*e+.7151522*t+.072175*n)/Jt),s=en((.0193339*e+.119192*t+.9503041*n)/Kt);return Wt(116*i-16,500*(r-i),200*(i-s))}function hn(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function pn(e){var t=parseFloat(e);return e.charAt(e.length-1)==="%"?Math.round(t*2.55):t}function vn(e){return typeof e=="function"?e:function(){return e}}function mn(e){return e}function gn(e){return function(t,n,r){return arguments.length===2&&typeof n=="function"&&(r=n,n=null),yn(t,n,e,r)}}function yn(t,r,i,o){function h(){var e=l.status,t;if(!e&&l.responseText||e>=200&&e<300||e===304){try{t=i.call(u,l)}catch(n){a.error.call(u,n);return}a.load.call(u,t)}else a.error.call(u,l)}var u={},a=e.dispatch("beforesend","progress","load","error"),f={},l=new XMLHttpRequest,c=null;return s.XDomainRequest&&!("withCredentials"in l)&&/^(http(s)?:)?\/\//.test(t)&&(l=new XDomainRequest),"onload"in l?l.onload=l.onerror=h:l.onreadystatechange=function(){l.readyState>3&&h()},l.onprogress=function(t){var n=e.event;e.event=t;try{a.progress.call(u,l)}finally{e.event=n}},u.header=function(e,t){return e=(e+"").toLowerCase(),arguments.length<2?f[e]:(t==null?delete f[e]:f[e]=t+"",u)},u.mimeType=function(e){return arguments.length?(r=e==null?null:e+"",u):r},u.responseType=function(e){return arguments.length?(c=e,u):c},u.response=function(e){return i=e,u},["get","post"].forEach(function(e){u[e]=function(){return u.send.apply(u,[e].concat(n(arguments)))}}),u.send=function(e,n,i){arguments.length===2&&typeof n=="function"&&(i=n,n=null),l.open(e,t,!0),r!=null&&!("accept"in f)&&(f.accept=r+",*/*");if(l.setRequestHeader)for(var s in f)l.setRequestHeader(s,f[s]);return r!=null&&l.overrideMimeType&&l.overrideMimeType(r),c!=null&&(l.responseType=c),i!=null&&u.on("error",i).on("load",function(e){i(null,e)}),a.beforesend.call(u,l),l.send(n==null?null:n),u},u.abort=function(){return l.abort(),u},e.rebind(u,a,"on"),o==null?u:u.get(bn(o))}function bn(e){return e.length===1?function(t,n){e(t==null?n:null)}:e}function Cn(){var e=kn(),t=Ln()-e;t>24?(isFinite(t)&&(clearTimeout(xn),xn=setTimeout(Cn,t)),Sn=0):(Sn=1,Nn(Cn))}function kn(){var e=Date.now();Tn=wn;while(Tn)e>=Tn.t&&(Tn.f=Tn.c(e-Tn.t)),Tn=Tn.n;return e}function Ln(){var e,t=wn,n=Infinity;while(t)t.f?t=e?e.n=t.n:wn=t.n:(t.t<n&&(n=t.t),t=(e=t).n);return En=e,n}function Pn(e,t){var n=Math.pow(10,m(8-t)*3);return{scale:t>8?function(e){return e/n}:function(e){return e*n},symbol:e}}function jn(e,t){return t-(e?Math.ceil(Math.log(e)/Math.LN10):1)}function Fn(e){return e+""}function Rn(){}function zn(e,t,n){var r=n.s=e+t,i=r-e,s=r-i;n.t=e-s+(t-i)}function Wn(e,t){e&&Vn.hasOwnProperty(e.type)&&Vn[e.type](e,t)}function $n(e,t,n){var r=-1,i=e.length-n,s;t.lineStart();while(++r<i)s=e[r],t.point(s[0],s[1],s[2]);t.lineEnd()}function Jn(e,t){var n=-1,r=e.length;t.polygonStart();while(++n<r)$n(e[n],t,1);t.polygonEnd()}function Yn(){function s(e,t){e*=wt,t=t*wt/2+vt/4;var s=e-n,o=Math.cos(t),u=Math.sin(t),a=i*u,f=r*o+a*Math.cos(s),l=a*Math.sin(s);Qn.add(Math.atan2(l,f)),n=e,r=o,i=u}var e,t,n,r,i;Gn.point=function(o,u){Gn.point=s,n=(e=o)*wt,r=Math.cos(u=(t=u)*wt/2+vt/4),i=Math.sin(u)},Gn.lineEnd=function(){s(e,t)}}function Zn(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function er(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function tr(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function nr(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function rr(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function ir(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function sr(e){return[Math.atan2(e[1],e[0]),Tt(e[2])]}function or(e,t){return m(e[0]-t[0])<yt&&m(e[1]-t[1])<yt}function br(e,t){e*=wt;var n=Math.cos(t*=wt);wr(n*Math.cos(e),n*Math.sin(e),Math.sin(t))}function wr(e,t,n){++ur,fr+=(e-fr)/ur,lr+=(t-lr)/ur,cr+=(n-cr)/ur}function Er(){function r(r,i){r*=wt;var s=Math.cos(i*=wt),o=s*Math.cos(r),u=s*Math.sin(r),a=Math.sin(i),f=Math.atan2(Math.sqrt((f=t*a-n*u)*f+(f=n*o-e*a)*f+(f=e*u-t*o)*f),e*o+t*u+n*a);ar+=f,hr+=f*(e+(e=o)),pr+=f*(t+(t=u)),dr+=f*(n+(n=a)),wr(e,t,n)}var e,t,n;yr.point=function(i,s){i*=wt;var o=Math.cos(s*=wt);e=o*Math.cos(i),t=o*Math.sin(i),n=Math.sin(s),yr.point=r,wr(e,t,n)}}function Sr(){yr.point=br}function xr(){function s(e,t){e*=wt;var s=Math.cos(t*=wt),o=s*Math.cos(e),u=s*Math.sin(e),a=Math.sin(t),f=r*a-i*u,l=i*o-n*a,c=n*u-r*o,h=Math.sqrt(f*f+l*l+c*c),p=n*o+r*u+i*a,d=h&&-xt(p)/h,v=Math.atan2(h,p);vr+=d*f,mr+=d*l,gr+=d*c,ar+=v,hr+=v*(n+(n=o)),pr+=v*(r+(r=u)),dr+=v*(i+(i=a)),wr(n,r,i)}var e,t,n,r,i;yr.point=function(o,u){e=o,t=u,yr.point=s,o*=wt;var a=Math.cos(u*=wt);n=a*Math.cos(o),r=a*Math.sin(o),i=Math.sin(u),wr(n,r,i)},yr.lineEnd=function(){s(e,t),yr.lineEnd=Sr,yr.point=br}}function Tr(){return!0}function Nr(e,t,n,r,i){var s=[],o=[];e.forEach(function(e){if((t=e.length-1)<=0)return;var t,n=e[0],r=e[t];if(or(n,r)){i.lineStart();for(var u=0;u<t;++u)i.point((n=e[u])[0],n[1]);i.lineEnd();return}var a=new kr(n,e,null,!0),f=new kr(n,null,a,!1);a.o=f,s.push(a),o.push(f),a=new kr(r,e,null,!1),f=new kr(r,null,a,!0),a.o=f,s.push(a),o.push(f)}),o.sort(t),Cr(s),Cr(o);if(!s.length)return;for(var u=0,a=n,f=o.length;u<f;++u)o[u].e=a=!a;var l=s[0],c,h;for(;;){var p=l,d=!0;while(p.v)if((p=p.n)===l)return;c=p.z,i.lineStart();do{p.v=p.o.v=!0;if(p.e){if(d)for(var u=0,f=c.length;u<f;++u)i.point((h=c[u])[0],h[1]);else r(p.x,p.n.x,1,i);p=p.n}else{if(d){c=p.p.z;for(var u=c.length-1;u>=0;--u)i.point((h=c[u])[0],h[1])}else r(p.x,p.p.x,-1,i);p=p.p}p=p.o,c=p.z,d=!d}while(!p.v);i.lineEnd()}}function Cr(e){if(!(t=e.length))return;var t,n=0,r=e[0],i;while(++n<t)r.n=i=e[n],i.p=r,r=i;r.n=i=e[0],i.p=r}function kr(e,t,n,r){this.x=e,this.z=t,this.o=n,this.e=r,this.v=!1,this.n=this.p=null}function Lr(t,n,r,i){return function(s,o){function l(e,n){var r=s(e,n);t(e=r[0],n=r[1])&&o.point(e,n)}function c(e,t){var n=s(e,t);u.point(n[0],n[1])}function h(){f.point=c,u.lineStart()}function p(){f.point=l,u.lineEnd()}function b(e,t){y.push([e,t]);var n=s(e,t);m.point(n[0],n[1])}function w(){m.lineStart(),y=[]}function E(){b(y[0][0],y[0][1]),m.lineEnd();var e=m.clean(),t=v.buffer(),n,r=t.length;y.pop(),g.push(y),y=null;if(!r)return;if(e&1){n=t[0];var r=n.length-1,i=-1,s;o.lineStart();while(++i<r)o.point((s=n[i])[0],s[1]);o.lineEnd();return}r>1&&e&2&&t.push(t.pop().concat(t.shift())),d.push(t.filter(Ar))}var u=n(o),a=s.invert(i[0],i[1]),f={point:l,lineStart:h,lineEnd:p,polygonStart:function(){f.point=b,f.lineStart=w,f.lineEnd=E,d=[],g=[],o.polygonStart()},polygonEnd:function(){f.point=l,f.lineStart=h,f.lineEnd=p,d=e.merge(d);var t=_r(a,g);d.length?Nr(d,Mr,t,r,o):t&&(o.lineStart(),r(null,null,1,o),o.lineEnd()),o.polygonEnd(),d=g=null},sphere:function(){o.polygonStart(),o.lineStart(),r(null,null,1,o),o.lineEnd(),o.polygonEnd()}},d,v=Or(),m=n(v),g,y;return f}}function Ar(e){return e.length>1}function Or(){var e=[],t;return{lineStart:function(){e.push(t=[])},point:function(e,n){t.push([e,n])},lineEnd:C,buffer:function(){var n=e;return e=[],t=null,n},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Mr(e,t){return((e=e.x)[0]<0?e[1]-gt-yt:gt-e[1])-((t=t.x)[0]<0?t[1]-gt-yt:gt-t[1])}function _r(e,t){var n=e[0],r=e[1],i=[Math.sin(n),-Math.cos(n),0],s=0,o=0;Qn.reset();for(var u=0,a=t.length;u<a;++u){var f=t[u],l=f.length;if(!l)continue;var c=f[0],h=c[0],p=c[1]/2+vt/4,d=Math.sin(p),v=Math.cos(p),g=1;for(;;){g===l&&(g=0),e=f[g];var y=e[0],b=e[1]/2+vt/4,w=Math.sin(b),E=Math.cos(b),S=y-h,x=m(S)>vt,T=d*w;Qn.add(Math.atan2(T*Math.sin(S),v*E+T*Math.cos(S))),s+=x?S+(S>=0?mt:-mt):S;if(x^h>=n^y>=n){var N=tr(Zn(c),Zn(e));ir(N);var C=tr(i,N);ir(C);var k=(x^S>=0?-1:1)*Tt(C[2]);if(r>k||r===k&&(N[0]||N[1]))o+=x^S>=0?1:-1}if(!(g++))break;h=y,d=w,v=E,c=e}}return(s<-yt||s<yt&&Qn<0)^o&1}function Pr(e){var t=NaN,n=NaN,r=NaN,i;return{lineStart:function(){e.lineStart(),i=1},point:function(s,o){var u=s>0?vt:-vt,a=m(s-t);m(a-vt)<yt?(e.point(t,n=(n+o)/2>0?gt:-gt),e.point(r,n),e.lineEnd(),e.lineStart(),e.point(u,n),e.point(s,n),i=0):r!==u&&a>=vt&&(m(t-r)<yt&&(t-=r*yt),m(s-u)<yt&&(s-=u*yt),n=Hr(t,n,s,o),e.point(r,n),e.lineEnd(),e.lineStart(),e.point(u,n),i=0),e.point(t=s,n=o),r=u},lineEnd:function(){e.lineEnd(),t=n=NaN},clean:function(){return 2-i}}}function Hr(e,t,n,r){var i,s,o=Math.sin(e-n);return m(o)>yt?Math.atan((Math.sin(t)*(s=Math.cos(r))*Math.sin(n)-Math.sin(r)*(i=Math.cos(t))*Math.sin(e))/(i*s*o)):(t+r)/2}function Br(e,t,n,r){var i;if(e==null)i=n*gt,r.point(-vt,i),r.point(0,i),r.point(vt,i),r.point(vt,0),r.point(vt,-i),r.point(0,-i),r.point(-vt,-i),r.point(-vt,0),r.point(-vt,i);else if(m(e[0]-t[0])>yt){var s=e[0]<t[0]?vt:-vt;i=n*s/2,r.point(-s,i),r.point(0,i),r.point(s,i)}else r.point(t[0],t[1])}function jr(e){function s(e,n){return Math.cos(e)*Math.cos(n)>t}function o(e){var t,i,o,f,l;return{lineStart:function(){f=o=!1,l=1},point:function(c,h){var p=[c,h],d,v=s(c,h),m=n?v?0:a(c,h):v?a(c+(c<0?vt:-vt),h):0;!t&&(f=o=v)&&e.lineStart();if(v!==o){d=u(t,p);if(or(t,d)||or(p,d))p[0]+=yt,p[1]+=yt,v=s(p[0],p[1])}if(v!==o)l=0,v?(e.lineStart(),d=u(p,t),e.point(d[0],d[1])):(d=u(t,p),e.point(d[0],d[1]),e.lineEnd()),t=d;else if(r&&t&&n^v){var g;!(m&i)&&(g=u(p,t,!0))&&(l=0,n?(e.lineStart(),e.point(g[0][0],g[0][1]),e.point(g[1][0],g[1][1]),e.lineEnd()):(e.point(g[1][0],g[1][1]),e.lineEnd(),e.lineStart(),e.point(g[0][0],g[0][1])))}v&&(!t||!or(t,p))&&e.point(p[0],p[1]),t=p,o=v,i=m},lineEnd:function(){o&&e.lineEnd(),t=null},clean:function(){return l|(f&&o)<<1}}}function u(e,n,r){var i=Zn(e),s=Zn(n),o=[1,0,0],u=tr(i,s),a=er(u,u),f=u[0],l=a-f*f;if(!l)return!r&&e;var c=t*a/l,h=-t*f/l,p=tr(o,u),d=rr(o,c),v=rr(u,h);nr(d,v);var g=p,y=er(d,g),b=er(g,g),w=y*y-b*(er(d,d)-1);if(w<0)return;var E=Math.sqrt(w),S=rr(g,(-y-E)/b);nr(S,d),S=sr(S);if(!r)return S;var x=e[0],T=n[0],N=e[1],C=n[1],k;T<x&&(k=x,x=T,T=k);var L=T-x,A=m(L-vt)<yt,O=A||L<yt;!A&&C<N&&(k=N,N=C,C=k);if(O?A?N+C>0^S[1]<(m(S[0]-x)<yt?N:C):N<=S[1]&&S[1]<=C:L>vt^(x<=S[0]&&S[0]<=T)){var M=rr(g,(-y+E)/b);return nr(M,d),[S,sr(M)]}}function a(t,r){var i=n?e:vt-e,s=0;return t<-i?s|=1:t>i&&(s|=2),r<-i?s|=4:r>i&&(s|=8),s}var t=Math.cos(e),n=t>0,r=m(t)>yt,i=Ei(e,6*wt);return Lr(s,o,i,n?[0,-e]:[-vt,e-vt])}function Fr(e,t,n,r){return function(i){var s=i.a,o=i.b,u=s.x,a=s.y,f=o.x,l=o.y,c=0,h=1,p=f-u,d=l-a,v;v=e-u;if(!p&&v>0)return;v/=p;if(p<0){if(v<c)return;v<h&&(h=v)}else if(p>0){if(v>h)return;v>c&&(c=v)}v=n-u;if(!p&&v<0)return;v/=p;if(p<0){if(v>h)return;v>c&&(c=v)}else if(p>0){if(v<c)return;v<h&&(h=v)}v=t-a;if(!d&&v>0)return;v/=d;if(d<0){if(v<c)return;v<h&&(h=v)}else if(d>0){if(v>h)return;v>c&&(c=v)}v=r-a;if(!d&&v<0)return;v/=d;if(d<0){if(v>h)return;v>c&&(c=v)}else if(d>0){if(v<c)return;v<h&&(h=v)}return c>0&&(i.a={x:u+c*p,y:a+c*d}),h<1&&(i.b={x:u+h*p,y:a+h*d}),i}}function qr(t,n,r,i){function s(e,i){return m(e[0]-t)<yt?i>0?0:3:m(e[0]-r)<yt?i>0?2:1:m(e[1]-n)<yt?i>0?1:0:i>0?3:2}function o(e,t){return u(e.x,t.x)}function u(e,t){var n=s(e,1),r=s(t,1);return n!==r?n-r:n===0?t[1]-e[1]:n===1?e[0]-t[0]:n===2?e[1]-t[1]:t[0]-e[0]}return function(a){function m(e){var t=0,n=p.length,r=e[1];for(var i=0;i<n;++i)for(var s=1,o=p[i],u=o.length,a=o[0],f;s<u;++s)f=o[s],a[1]<=r?f[1]>r&&g(a,f,e)>0&&++t:f[1]<=r&&g(a,f,e)<0&&--t,a=f;return t!==0}function g(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(n[0]-e[0])*(t[1]-e[1])}function y(e,o,a,f){var l=0,c=0;if(e==null||(l=s(e,a))!==(c=s(o,a))||u(e,o)<0^a>0){do f.point(l===0||l===3?t:r,l>1?i:n);while((l=(l+a+4)%4)!==c)}else f.point(o[0],o[1])}function b(e,s){return t<=e&&e<=r&&n<=s&&s<=i}function w(e,t){b(e,t)&&a.point(e,t)}function A(){v.point=M,p&&p.push(d=[]),k=!0,C=!1,T=N=NaN}function O(){h&&(M(E,S),x&&C&&l.rejoin(),h.push(l.buffer())),v.point=w,C&&a.lineEnd()}function M(e,t){e=Math.max(-Ir,Math.min(Ir,e)),t=Math.max(-Ir,Math.min(Ir,t));var n=b(e,t);p&&d.push([e,t]);if(k)E=e,S=t,x=n,k=!1,n&&(a.lineStart(),a.point(e,t));else if(n&&C)a.point(e,t);else{var r={a:{x:T,y:N},b:{x:e,y:t}};c(r)?(C||(a.lineStart(),a.point(r.a.x,r.a.y)),a.point(r.b.x,r.b.y),n||a.lineEnd(),L=!1):n&&(a.lineStart(),a.point(e,t),L=!1)}T=e,N=t,C=n}var f=a,l=Or(),c=Fr(t,n,r,i),h,p,d,v={point:w,lineStart:A,lineEnd:O,polygonStart:function(){a=l,h=[],p=[],L=!0},polygonEnd:function(){a=f,h=e.merge(h);var n=m([t,i]),r=L&&n,s=h.length;if(r||s)a.polygonStart(),r&&(a.lineStart(),y(null,null,1,a),a.lineEnd()),s&&Nr(h,o,n,y,a),a.polygonEnd();h=p=d=null}},E,S,x,T,N,C,k,L;return v}}function Rr(e,t){function n(n,r){return n=e(n,r),t(n[0],n[1])}return e.invert&&t.invert&&(n.invert=function(n,r){return n=t.invert(n,r),n&&e.invert(n[0],n[1])}),n}function Ur(e){var t=0,n=vt/3,r=pi(e),i=r(t,n);return i.parallels=function(e){return arguments.length?r(t=e[0]*vt/180,n=e[1]*vt/180):[t/vt*180,n/vt*180]},i}function zr(e,t){function o(e,t){var n=Math.sqrt(i-2*r*Math.sin(t))/r;return[n*Math.sin(e*=r),s-n*Math.cos(e)]}var n=Math.sin(e),r=(n+Math.sin(t))/2,i=1+n*(2*r-n),s=Math.sqrt(i)/r;return o.invert=function(e,t){var n=s-t;return[Math.atan2(e,n)/r,Tt((i-(e*e+n*n)*r*r)/(2*r))]},o}function $r(){function i(e,t){Xr+=r*e-n*t,n=e,r=t}var e,t,n,r;Vr.point=function(s,o){Vr.point=i,e=n=s,t=r=o},Vr.lineEnd=function(){i(e,t)}}function Zr(e,t){e<Jr&&(Jr=e),e>Qr&&(Qr=e),t<Kr&&(Kr=t),t>Gr&&(Gr=t)}function ei(){function r(n,r){t.push("M",n,",",r,e)}function i(e,r){t.push("M",e,",",r),n.point=s}function s(e,n){t.push("L",e,",",n)}function o(){n.point=r}function u(){t.push("Z")}var e=ti(4.5),t=[],n={point:r,lineStart:function(){n.point=i},lineEnd:o,polygonStart:function(){n.lineEnd=u},polygonEnd:function(){n.lineEnd=o,n.point=r},pointRadius:function(t){return e=ti(t),n},result:function(){if(t.length){var e=t.join("");return t=[],e}}};return n}function ti(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+ -2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}function ri(e,t){fr+=e,lr+=t,++cr}function ii(){function n(n,r){var i=n-e,s=r-t,o=Math.sqrt(i*i+s*s);hr+=o*(e+n)/2,pr+=o*(t+r)/2,dr+=o,ri(e=n,t=r)}var e,t;ni.point=function(r,i){ni.point=n,ri(e=r,t=i)}}function si(){ni.point=ri}function oi(){function i(e,t){var i=e-n,s=t-r,o=Math.sqrt(i*i+s*s);hr+=o*(n+e)/2,pr+=o*(r+t)/2,dr+=o,o=r*e-n*t,vr+=o*(n+e),mr+=o*(r+t),gr+=o*3,ri(n=e,r=t)}var e,t,n,r;ni.point=function(s,o){ni.point=i,ri(e=n=s,t=r=o)},ni.lineEnd=function(){i(e,t)}}function ui(e){function r(n,r){e.moveTo(n,r),e.arc(n,r,t,0,mt)}function i(t,r){e.moveTo(t,r),n.point=s}function s(t,n){e.lineTo(t,n)}function o(){n.point=r}function u(){e.closePath()}var t=4.5,n={point:r,lineStart:function(){n.point=i},lineEnd:o,polygonStart:function(){n.lineEnd=u},polygonEnd:function(){n.lineEnd=o,n.point=r},pointRadius:function(e){return t=e,n},result:C};return n}function ai(e){function i(e){return(r?o:s)(e)}function s(t){return ci(t,function(n,r){n=e(n,r),t.point(n[0],n[1])})}function o(t){function y(n,r){n=e(n,r),t.point(n[0],n[1])}function b(){h=NaN,g.point=w,t.lineStart()}function w(n,i){var s=Zn([n,i]),o=e(n,i);u(h,p,c,d,v,m,h=o[0],p=o[1],c=n,d=s[0],v=s[1],m=s[2],r,t),t.point(h,p)}function E(){g.point=y,t.lineEnd()}function S(){b(),g.point=x,g.lineEnd=T}function x(e,t){w(n=e,i=t),s=h,o=p,a=d,f=v,l=m,g.point=w}function T(){u(h,p,c,d,v,m,s,o,n,a,f,l,r,t),g.lineEnd=E,E()}var n,i,s,o,a,f,l,c,h,p,d,v,m,g={point:y,lineStart:b,lineEnd:E,polygonStart:function(){t.polygonStart(),g.lineStart=S},polygonEnd:function(){t.polygonEnd(),g.lineStart=b}};return g}function u(r,i,s,o,a,f,l,c,h,p,d,v,g,y){var b=l-r,w=c-i,E=b*b+w*w;if(E>4*t&&g--){var S=o+p,x=a+d,T=f+v,N=Math.sqrt(S*S+x*x+T*T),C=Math.asin(T/=N),k=m(m(T)-1)<yt||m(s-h)<yt?(s+h)/2:Math.atan2(x,S),L=e(k,C),A=L[0],O=L[1],M=A-r,_=O-i,D=w*M-b*_;if(D*D/E>t||m((b*M+w*_)/E-.5)>.3||o*p+a*d+f*v<n)u(r,i,s,o,a,f,A,O,k,S/=N,x/=N,T,g,y),y.point(A,O),u(A,O,k,S,x,T,l,c,h,p,d,v,g,y)}}var t=.5,n=Math.cos(30*wt),r=16;return i.precision=function(e){return arguments.length?(r=(t=e*e)>0&&16,i):Math.sqrt(t)},i}function fi(e){var t=ai(function(t,n){return e([t*Et,n*Et])});return function(e){return di(t(e))}}function li(e){this.stream=e}function ci(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function hi(e){return pi(function(){return e})()}function pi(t){function E(e){return e=i(e[0]*wt,e[1]*wt),[e[0]*o+d,v-e[1]*o]}function S(e){return e=i.invert((e[0]-d)/o,(v-e[1])/o),e&&[e[0]*Et,e[1]*Et]}function x(){i=Rr(r=gi(c,h,p),n);var e=n(f,l);return d=u-e[0]*o,v=a+e[1]*o,T()}function T(){return w&&(w.valid=!1,w=null),E}var n,r,i,s=ai(function(e,t){return e=n(e,t),[e[0]*o+d,v-e[1]*o]}),o=150,u=480,a=250,f=0,l=0,c=0,h=0,p=0,d,v,m=Dr,g=mn,y=null,b=null,w;return E.stream=function(e){return w&&(w.valid=!1),w=di(m(r,s(g(e)))),w.valid=!0,w},E.clipAngle=function(e){return arguments.length?(m=e==null?(y=e,Dr):jr((y=+e)*wt),T()):y},E.clipExtent=function(e){return arguments.length?(b=e,g=e?qr(e[0][0],e[0][1],e[1][0],e[1][1]):mn,T()):b},E.scale=function(e){return arguments.length?(o=+e,x()):o},E.translate=function(e){return arguments.length?(u=+e[0],a=+e[1],x()):[u,a]},E.center=function(e){return arguments.length?(f=e[0]%360*wt,l=e[1]%360*wt,x()):[f*Et,l*Et]},E.rotate=function(e){return arguments.length?(c=e[0]%360*wt,h=e[1]%360*wt,p=e.length>2?e[2]%360*wt:0,x()):[c*Et,h*Et,p*Et]},e.rebind(E,s,"precision"),function(){return n=t.apply(this,arguments),E.invert=n.invert&&S,x()}}function di(e){return ci(e,function(t,n){e.point(t*wt,n*wt)})}function vi(e,t){return[e,t]}function mi(e,t){return[e>vt?e-mt:e<-vt?e+mt:e,t]}function gi(e,t,n){return e?t||n?Rr(bi(e),wi(t,n)):bi(e):t||n?wi(t,n):mi}function yi(e){return function(t,n){return t+=e,[t>vt?t-mt:t<-vt?t+mt:t,n]}}function bi(e){var t=yi(e);return t.invert=yi(-e),t}function wi(e,t){function o(e,t){var o=Math.cos(t),u=Math.cos(e)*o,a=Math.sin(e)*o,f=Math.sin(t),l=f*n+u*r;return[Math.atan2(a*i-l*s,u*n-f*r),Tt(l*i+a*s)]}var n=Math.cos(e),r=Math.sin(e),i=Math.cos(t),s=Math.sin(t);return o.invert=function(e,t){var o=Math.cos(t),u=Math.cos(e)*o,a=Math.sin(e)*o,f=Math.sin(t),l=f*i-a*s;return[Math.atan2(a*i+f*s,u*n+l*r),Tt(l*n-u*r)]},o}function Ei(e,t){var n=Math.cos(e),r=Math.sin(e);return function(i,s,o,u){var a=o*t;if(i!=null){i=Si(n,i),s=Si(n,s);if(o>0?i<s:i>s)i+=o*mt}else i=e+o*mt,s=e-.5*a;for(var f,l=i;o>0?l>s:l<s;l-=a)u.point((f=sr([n,-r*Math.cos(l),-r*Math.sin(l)]))[0],f[1])}}function Si(e,t){var n=Zn(t);n[0]-=e,ir(n);var r=xt(-n[1]);return((-n[2]<0?-r:r)+2*Math.PI-yt)%(2*Math.PI)}function xi(t,n,r){var i=e.range(t,n-yt,r).concat(n);return function(e){return i.map(function(t){return[e,t]})}}function Ti(t,n,r){var i=e.range(t,n-yt,r).concat(n);return function(e){return i.map(function(t){return[t,e]})}}function Ni(e){return e.source}function Ci(e){return e.target}function ki(e,t,n,r){var i=Math.cos(t),s=Math.sin(t),o=Math.cos(r),u=Math.sin(r),a=i*Math.cos(e),f=i*Math.sin(e),l=o*Math.cos(n),c=o*Math.sin(n),h=2*Math.asin(Math.sqrt(Lt(r-t)+i*o*Lt(n-e))),p=1/Math.sin(h),d=h?function(e){var t=Math.sin(e*=h)*p,n=Math.sin(h-e)*p,r=n*a+t*l,i=n*f+t*c,o=n*s+t*u;return[Math.atan2(i,r)*Et,Math.atan2(o,Math.sqrt(r*r+i*i))*Et]}:function(){return[e*Et,t*Et]};return d.distance=h,d}function Oi(){function r(r,i){var s=Math.sin(i*=wt),o=Math.cos(i),u=m((r*=wt)-e),a=Math.cos(u);Li+=Math.atan2(Math.sqrt((u=o*Math.sin(u))*u+(u=n*s-t*o*a)*u),t*s+n*o*a),e=r,t=s,n=o}var e,t,n;Ai.point=function(i,s){e=i*wt,t=Math.sin(s*=wt),n=Math.cos(s),Ai.point=r},Ai.lineEnd=function(){Ai.point=Ai.lineEnd=C}}function Mi(e,t){function n(t,n){var r=Math.cos(t),i=Math.cos(n),s=e(r*i);return[s*i*Math.sin(t),s*Math.sin(n)]}return n.invert=function(e,n){var r=Math.sqrt(e*e+n*n),i=t(r),s=Math.sin(i),o=Math.cos(i);return[Math.atan2(e*s,r*o),Math.asin(r&&n*s/r)]},n}function Pi(e,t){function o(e,t){var n=m(m(t)-gt)<yt?0:s/Math.pow(r(t),i);return[n*Math.sin(i*e),s-n*Math.cos(i*e)]}var n=Math.cos(e),r=function(e){return Math.tan(vt/4+e/2)},i=e===t?Math.sin(e):Math.log(n/Math.cos(t))/Math.log(r(t)/r(e)),s=n*Math.pow(r(e),i)/i;return i?(o.invert=function(e,t){var n=s-t,r=St(i)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/i,2*Math.atan(Math.pow(s/r,1/i))-gt]},o):ji}function Hi(e,t){function s(e,t){var n=i-t;return[n*Math.sin(r*e),i-n*Math.cos(r*e)]}var n=Math.cos(e),r=e===t?Math.sin(e):(n-Math.cos(t))/(t-e),i=n/r+e;return m(r)<yt?vi:(s.invert=function(e,t){var n=i-t;return[Math.atan2(e,n)/r,i-St(r)*Math.sqrt(e*e+n*n)]},s)}function ji(e,t){return[e,Math.log(Math.tan(vt/4+t/2))]}function Fi(e){var t=hi(e),n=t.scale,r=t.translate,i=t.clipExtent,s;return t.scale=function(){var e=n.apply(t,arguments);return e===t?s?t.clipExtent(null):t:e},t.translate=function(){var e=r.apply(t,arguments);return e===t?s?t.clipExtent(null):t:e},t.clipExtent=function(e){var o=i.apply(t,arguments);if(o===t){if(s=e==null){var u=vt*n(),a=r();i([[a[0]-u,a[1]-u],[a[0]+u,a[1]+u]])}}else s&&(o=null);return o},t.clipExtent(null)}function Ri(e,t){var n=Math.cos(t)*Math.sin(e);return[Math.log((1+n)/(1-n))/2,Math.atan2(Math.tan(t),Math.cos(e))]}function Ui(e){return e[0]}function zi(e){return e[1]}function Wi(e,t,n,r){var i,s,o,u,a,f,l;return i=r[e],s=i[0],o=i[1],i=r[t],u=i[0],a=i[1],i=r[n],f=i[0],l=i[1],(l-o)*(u-s)-(a-o)*(f-s)>0}function Vi(e,t,n){return(n[0]-t[0])*(e[1]-t[1])<(n[1]-t[1])*(e[0]-t[0])}function $i(e,t,n,r){var i=e[0],s=n[0],o=t[0]-i,u=r[0]-s,a=e[1],f=n[1],l=t[1]-a,c=r[1]-f,h=(u*(a-f)-c*(i-s))/(c*o-u*l);return[i+h*o,a+h*l]}function Ji(e){var t=e[0],n=e[e.length-1];return!(t[0]-n[0]||t[1]-n[1])}function ns(){xs(this),this.edge=this.site=this.circle=null}function rs(e){var t=Yi.pop()||new ns;return t.site=e,t}function is(e){ds(e),Gi.remove(e),Yi.push(e),xs(e)}function ss(e){var t=e.circle,n=t.x,r=t.cy,i={x:n,y:r},s=e.P,o=e.N,u=[e];is(e);var a=s;while(a.circle&&m(n-a.circle.x)<yt&&m(r-a.circle.cy)<yt)s=a.P,u.unshift(a),is(a),a=s;u.unshift(a),ds(a);var f=o;while(f.circle&&m(n-f.circle.x)<yt&&m(r-f.circle.cy)<yt)o=f.N,u.push(f),is(f),f=o;u.push(f),ds(f);var l=u.length,c;for(c=1;c<l;++c)f=u[c],a=u[c-1],ws(f.edge,a.site,f.site,i);a=u[0],f=u[l-1],f.edge=ys(a.site,f.site,null,i),ps(a),ps(f)}function os(e){var t=e.x,n=e.y,r,i,s,o,u=Gi._;while(u){s=us(u,n)-t;if(s>yt)u=u.L;else{o=t-as(u,n);if(!(o>yt)){s>-yt?(r=u.P,i=u):o>-yt?(r=u,i=u.N):r=i=u;break}if(!u.R){r=u;break}u=u.R}}var a=rs(e);Gi.insert(r,a);if(!r&&!i)return;if(r===i){ds(r),i=rs(r.site),Gi.insert(a,i),a.edge=i.edge=ys(r.site,a.site),ps(r),ps(i);return}if(!i){a.edge=ys(r.site,a.site);return}ds(r),ds(i);var f=r.site,l=f.x,c=f.y,h=e.x-l,p=e.y-c,d=i.site,v=d.x-l,m=d.y-c,g=2*(h*m-p*v),y=h*h+p*p,b=v*v+m*m,w={x:(m*y-p*b)/g+l,y:(h*b-v*y)/g+c};ws(i.edge,f,d,w),a.edge=ys(f,e,null,w),i.edge=ys(e,d,null,w),ps(r),ps(i)}function us(e,t){var n=e.site,r=n.x,i=n.y,s=i-t;if(!s)return r;var o=e.P;if(!o)return-Infinity;n=o.site;var u=n.x,a=n.y,f=a-t;if(!f)return u;var l=u-r,c=1/s-1/f,h=l/f;return c?(-h+Math.sqrt(h*h-2*c*(l*l/(-2*f)-a+f/2+i-s/2)))/c+r:(r+u)/2}function as(e,t){var n=e.N;if(n)return us(n,t);var r=e.site;return r.y===t?r.x:Infinity}function fs(e){this.site=e,this.edges=[]}function ls(e){var t=e[0][0],n=e[1][0],r=e[0][1],i=e[1][1],s,o,u,a,f=Qi,l=f.length,c,h,p,d,v,g;while(l--){c=f[l];if(!c||!c.prepare())continue;p=c.edges,d=p.length,h=0;while(h<d){g=p[h].end(),u=g.x,a=g.y,v=p[++h%d].start(),s=v.x,o=v.y;if(m(u-s)>yt||m(a-o)>yt)p.splice(h,0,new Es(bs(c.site,g,m(u-t)<yt&&i-a>yt?{x:t,y:m(s-t)<yt?o:i}:m(a-i)<yt&&n-u>yt?{x:m(o-i)<yt?s:n,y:i}:m(u-n)<yt&&a-r>yt?{x:n,y:m(s-n)<yt?o:r}:m(a-r)<yt&&u-t>yt?{x:m(o-r)<yt?s:t,y:r}:null),c.site,null)),++d}}}function cs(e,t){return t.angle-e.angle}function hs(){xs(this),this.x=this.y=this.arc=this.site=this.cy=null}function ps(e){var t=e.P,n=e.N;if(!t||!n)return;var r=t.site,i=e.site,s=n.site;if(r===s)return;var o=i.x,u=i.y,a=r.x-o,f=r.y-u,l=s.x-o,c=s.y-u,h=2*(a*c-f*l);if(h>=-bt)return;var p=a*a+f*f,d=l*l+c*c,v=(c*p-f*d)/h,m=(a*d-l*p)/h,c=m+u,g=ts.pop()||new hs;g.arc=e,g.site=i,g.x=v+o,g.y=c+Math.sqrt(v*v+m*m),g.cy=c,e.circle=g;var y=null,b=es._;while(b)if(g.y<b.y||g.y===b.y&&g.x<=b.x){if(!b.L){y=b.P;break}b=b.L}else{if(!b.R){y=b;break}b=b.R}es.insert(y,g),y||(Zi=g)}function ds(e){var t=e.circle;t&&(t.P||(Zi=t.N),es.remove(t),ts.push(t),xs(t),e.circle=null)}function vs(e){var t=Ki,n=Fr(e[0][0],e[0][1],e[1][0],e[1][1]),r=t.length,i;while(r--){i=t[r];if(!ms(i,e)||!n(i)||m(i.a.x-i.b.x)<yt&&m(i.a.y-i.b.y)<yt)i.a=i.b=null,t.splice(r,1)}}function ms(e,t){var n=e.b;if(n)return!0;var r=e.a,i=t[0][0],s=t[1][0],o=t[0][1],u=t[1][1],a=e.l,f=e.r,l=a.x,c=a.y,h=f.x,p=f.y,d=(l+h)/2,v=(c+p)/2,m,g;if(p===c){if(d<i||d>=s)return;if(l>h){if(!r)r={x:d,y:o};else if(r.y>=u)return;n={x:d,y:u}}else{if(!r)r={x:d,y:u};else if(r.y<o)return;n={x:d,y:o}}}else{m=(l-h)/(p-c),g=v-m*d;if(m<-1||m>1)if(l>h){if(!r)r={x:(o-g)/m,y:o};else if(r.y>=u)return;n={x:(u-g)/m,y:u}}else{if(!r)r={x:(u-g)/m,y:u};else if(r.y<o)return;n={x:(o-g)/m,y:o}}else if(c<p){if(!r)r={x:i,y:m*i+g};else if(r.x>=s)return;n={x:s,y:m*s+g}}else{if(!r)r={x:s,y:m*s+g};else if(r.x<i)return;n={x:i,y:m*i+g}}}return e.a=r,e.b=n,!0}function gs(e,t){this.l=e,this.r=t,this.a=this.b=null}function ys(e,t,n,r){var i=new gs(e,t);return Ki.push(i),n&&ws(i,e,t,n),r&&ws(i,t,e,r),Qi[e.i].edges.push(new Es(i,e,t)),Qi[t.i].edges.push(new Es(i,t,e)),i}function bs(e,t,n){var r=new gs(e,null);return r.a=t,r.b=n,Ki.push(r),r}function ws(e,t,n,r){!e.a&&!e.b?(e.a=r,e.l=t,e.r=n):e.l===n?e.b=r:e.a=r}function Es(e,t,n){var r=e.a,i=e.b;this.edge=e,this.site=t,this.angle=n?Math.atan2(n.y-t.y,n.x-t.x):e.l===t?Math.atan2(i.x-r.x,r.y-i.y):Math.atan2(r.x-i.x,i.y-r.y)}function Ss(){this._=null}function xs(e){e.U=e.C=e.L=e.R=e.P=e.N=null}function Ts(e,t){var n=t,r=t.R,i=n.U;i?i.L===n?i.L=r:i.R=r:e._=r,r.U=i,n.U=r,n.R=r.L,n.R&&(n.R.U=n),r.L=n}function Ns(e,t){var n=t,r=t.L,i=n.U;i?i.L===n?i.L=r:i.R=r:e._=r,r.U=i,n.U=r,n.L=r.R,n.L&&(n.L.U=n),r.R=n}function Cs(e){while(e.L)e=e.L;return e}function ks(e,t){var n=e.sort(Ls).pop(),r,i,s;Ki=[],Qi=new Array(e.length),Gi=new Ss,es=new Ss;for(;;){s=Zi;if(n&&(!s||n.y<s.y||n.y===s.y&&n.x<s.x)){if(n.x!==r||n.y!==i)Qi[n.i]=new fs(n),os(n),r=n.x,i=n.y;n=e.pop()}else{if(!s)break;ss(s.arc)}}t&&(vs(t),ls(t));var o={cells:Qi,edges:Ki};return Gi=es=Ki=Qi=null,o}function Ls(e,t){return t.y-e.y||t.x-e.x}function Os(e,t,n){return(e.x-n.x)*(t.y-e.y)-(e.x-t.x)*(n.y-e.y)}function Ms(e){return e.x}function _s(e){return e.y}function Ds(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function Ps(e,t,n,r,i,s){if(!e(t,n,r,i,s)){var o=(n+i)*.5,u=(r+s)*.5,a=t.nodes;a[0]&&Ps(e,a[0],n,r,o,u),a[1]&&Ps(e,a[1],o,r,i,u),a[2]&&Ps(e,a[2],n,u,o,s),a[3]&&Ps(e,a[3],o,u,i,s)}}function Hs(t,n){t=e.rgb(t),n=e.rgb(n);var r=t.r,i=t.g,s=t.b,o=n.r-r,u=n.g-i,a=n.b-s;return function(e){return"#"+an(Math.round(r+o*e))+an(Math.round(i+u*e))+an(Math.round(s+a*e))}}function Bs(e,t){var n={},r={},i;for(i in e)i in t?n[i]=qs(e[i],t[i]):r[i]=e[i];for(i in t)i in e||(r[i]=t[i]);return function(e){for(i in n)r[i]=n[i](e);return r}}function js(e,t){return t-=e=+e,function(n){return e+t*n}}function Fs(e,t){var n,r,i,s=0,o=0,u=[],a=[],f,l;e+="",t+="",Is.lastIndex=0;for(r=0;n=Is.exec(t);++r)n.index&&u.push(t.substring(s,o=n.index)),a.push({i:u.length,x:n[0]}),u.push(null),s=Is.lastIndex;s<t.length&&u.push(t.substring(s));for(r=0,f=a.length;(n=Is.exec(e))&&r<f;++r){l=a[r];if(l.x==n[0]){if(l.i)if(u[l.i+1]==null){u[l.i-1]+=l.x,u.splice(l.i,1);for(i=r+1;i<f;++i)a[i].i--}else{u[l.i-1]+=l.x+u[l.i+1],u.splice(l.i,2);for(i=r+1;i<f;++i)a[i].i-=2}else if(u[l.i+1]==null)u[l.i]=l.x;else{u[l.i]=l.x+u[l.i+1],u.splice(l.i+1,1);for(i=r+1;i<f;++i)a[i].i--}a.splice(r,1),f--,r--}else l.x=js(parseFloat(n[0]),parseFloat(l.x))}while(r<f)l=a.pop(),u[l.i+1]==null?u[l.i]=l.x:(u[l.i]=l.x+u[l.i+1],u.splice(l.i+1,1)),f--;return u.length===1?u[0]==null?(l=a[0].x,function(e){return l(e)+""}):function(){return t}:function(e){for(r=0;r<f;++r)u[(l=a[r]).i]=l.x(e);return u.join("")}}function qs(t,n){var r=e.interpolators.length,i;while(--r>=0&&!(i=e.interpolators[r](t,n)));return i}function Rs(e,t){var n=[],r=[],i=e.length,s=t.length,o=Math.min(e.length,t.length),u;for(u=0;u<o;++u)n.push(qs(e[u],t[u]));for(;u<i;++u)r[u]=e[u];for(;u<s;++u)r[u]=t[u];return function(e){for(u=0;u<o;++u)r[u]=n[u](e);return r}}function Xs(e){return function(t){return t<=0?0:t>=1?1:e(t)}}function Vs(e){return function(t){return 1-e(1-t)}}function $s(e){return function(t){return.5*(t<.5?e(2*t):2-e(2-2*t))}}function Js(e){return e*e}function Ks(e){return e*e*e}function Qs(e){if(e<=0)return 0;if(e>=1)return 1;var t=e*e,n=t*e;return 4*(e<.5?n:3*(e-t)+n-.75)}function Gs(e){return function(t){return Math.pow(t,e)}}function Ys(e){return 1-Math.cos(e*gt)}function Zs(e){return Math.pow(2,10*(e-1))}function eo(e){return 1-Math.sqrt(1-e*e)}function to(e,t){var n;return arguments.length<2&&(t=.45),arguments.length?n=t/mt*Math.asin(1/e):(e=1,n=t/4),function(r){return 1+e*Math.pow(2,-10*r)*Math.sin((r-n)*mt/t)}}function no(e){return e||(e=1.70158),function(t){return t*t*((e+1)*t-e)}}function ro(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function io(t,n){t=e.hcl(t),n=e.hcl(n);var r=t.h,i=t.c,s=t.l,o=n.h-r,u=n.c-i,a=n.l-s;return isNaN(u)&&(u=0,i=isNaN(i)?n.c:i),isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360),function(e){return zt(r+o*e,i+u*e,s+a*e)+""}}function so(t,n){t=e.hsl(t),n=e.hsl(n);var r=t.h,i=t.s,s=t.l,o=n.h-r,u=n.s-i,a=n.l-s;return isNaN(u)&&(u=0,i=isNaN(i)?n.s:i),isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360),function(e){return It(r+o*e,i+u*e,s+a*e)+""}}function oo(t,n){t=e.lab(t),n=e.lab(n);var r=t.l,i=t.a,s=t.b,o=n.l-r,u=n.a-i,a=n.b-s;return function(e){return Gt(r+o*e,i+u*e,s+a*e)+""}}function uo(e,t){return t-=e,function(n){return Math.round(e+t*n)}}function ao(e){var t=[e.a,e.b],n=[e.c,e.d],r=lo(t),i=fo(t,n),s=lo(co(n,t,-i))||0;t[0]*n[1]<n[0]*t[1]&&(t[0]*=-1,t[1]*=-1,r*=-1,i*=-1),this.rotate=(r?Math.atan2(t[1],t[0]):Math.atan2(-n[0],n[1]))*Et,this.translate=[e.e,e.f],this.scale=[r,s],this.skew=s?Math.atan2(i,s)*Et:0}function fo(e,t){return e[0]*t[0]+e[1]*t[1]}function lo(e){var t=Math.sqrt(fo(e,e));return t&&(e[0]/=t,e[1]/=t),t}function co(e,t,n){return e[0]+=n*t[0],e[1]+=n*t[1],e}function po(t,n){var r=[],i=[],s,o=e.transform(t),u=e.transform(n),a=o.translate,f=u.translate,l=o.rotate,c=u.rotate,h=o.skew,p=u.skew,d=o.scale,v=u.scale;return a[0]!=f[0]||a[1]!=f[1]?(r.push("translate(",null,",",null,")"),i.push({i:1,x:js(a[0],f[0])},{i:3,x:js(a[1],f[1])})):f[0]||f[1]?r.push("translate("+f+")"):r.push(""),l!=c?(l-c>180?c+=360:c-l>180&&(l+=360),i.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:js(l,c)})):c&&r.push(r.pop()+"rotate("+c+")"),h!=p?i.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:js(h,p)}):p&&r.push(r.pop()+"skewX("+p+")"),d[0]!=v[0]||d[1]!=v[1]?(s=r.push(r.pop()+"scale(",null,",",null,")"),i.push({i:s-4,x:js(d[0],v[0])},{i:s-2,x:js(d[1],v[1])})):(v[0]!=1||v[1]!=1)&&r.push(r.pop()+"scale("+v+")"),s=i.length,function(e){var t=-1,n;while(++t<s)r[(n=i[t]).i]=n.x(e);return r.join("")}}function vo(e,t){return t=t-(e=+e)?1/(t-e):0,function(n){return(n-e)*t}}function mo(e,t){return t=t-(e=+e)?1/(t-e):0,function(n){return Math.max(0,Math.min(1,(n-e)*t))}}function go(e){var t=e.source,n=e.target,r=bo(t,n),i=[t];while(t!==r)t=t.parent,i.push(t);var s=i.length;while(n!==r)i.splice(s,0,n),n=n.parent;return i}function yo(e){var t=[],n=e.parent;while(n!=null)t.push(e),e=n,n=n.parent;return t.push(e),t}function bo(e,t){if(e===t)return e;var n=yo(e),r=yo(t),i=n.pop(),s=r.pop(),o=null;while(i===s)o=i,i=n.pop(),s=r.pop();return o}function wo(e){e.fixed|=2}function Eo(e){e.fixed&=-7}function So(e){e.fixed|=4,e.px=e.x,e.py=e.y}function xo(e){e.fixed&=-5}function To(e,t,n){var r=0,i=0;e.charge=0;if(!e.leaf){var s=e.nodes,o=s.length,u=-1,a;while(++u<o){a=s[u];if(a==null)continue;To(a,t,n),e.charge+=a.charge,r+=a.charge*a.cx,i+=a.charge*a.cy}}if(e.point){e.leaf||(e.point.x+=Math.random()-.5,e.point.y+=Math.random()-.5);var f=t*n[e.point.index];e.charge+=e.pointCharge=f,r+=f*e.point.x,i+=f*e.point.y}e.cx=r/e.charge,e.cy=i/e.charge}function ko(t,n){return e.rebind(t,n,"sort","children","value"),t.nodes=t,t.links=Mo,t}function Lo(e){return e.children}function Ao(e){return e.value}function Oo(e,t){return t.value-e.value}function Mo(t){return e.merge(t.map(function(e){return(e.children||[]).map(function(t){return{source:e,target:t}})}))}function Do(e){return e.x}function Po(e){return e.y}function Ho(e,t,n){e.y0=t,e.y=n}function Fo(t){return e.range(t.length)}function Io(e){var t=-1,n=e[0].length,r=[];while(++t<n)r[t]=0;return r}function qo(e){var t=1,n=0,r=e[0][1],i,s=e.length;for(;t<s;++t)(i=e[t][1])>r&&(n=t,r=i);return n}function Ro(e){return e.reduce(Uo,0)}function Uo(e,t){return e+t[1]}function zo(e,t){return Wo(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function Wo(e,t){var n=-1,r=+e[0],i=(e[1]-r)/t,s=[];while(++n<=t)s[n]=i*n+r;return s}function Xo(t){return[e.min(t),e.max(t)]}function Vo(e,t){return e.parent==t.parent?1:2}function $o(e){var t=e.children;return t&&t.length?t[0]:e._tree.thread}function Jo(e){var t=e.children,n;return t&&(n=t.length)?t[n-1]:e._tree.thread}function Ko(e,t){var n=e.children;if(n&&(i=n.length)){var r,i,s=-1;while(++s<i)t(r=Ko(n[s],t),e)>0&&(e=r)}return e}function Qo(e,t){return e.x-t.x}function Go(e,t){return t.x-e.x}function Yo(e,t){return e.depth-t.depth}function Zo(e,t){function n(e,r){var i=e.children;if(i&&(a=i.length)){var s,o=null,u=-1,a;while(++u<a)s=i[u],n(s,o),o=s}t(e,r)}n(e,null)}function eu(e){var t=0,n=0,r=e.children,i=r.length,s;while(--i>=0)s=r[i]._tree,s.prelim+=t,s.mod+=t,t+=s.shift+(n+=s.change)}function tu(e,t,n){e=e._tree,t=t._tree;var r=n/(t.number-e.number);e.change+=r,t.change-=r,t.shift+=n,t.prelim+=n,t.mod+=n}function nu(e,t,n){return e._tree.ancestor.parent==t.parent?e._tree.ancestor:n}function ru(e,t){return e.value-t.value}function iu(e,t){var n=e._pack_next;e._pack_next=t,t._pack_prev=e,t._pack_next=n,n._pack_prev=t}function su(e,t){e._pack_next=t,t._pack_prev=e}function ou(e,t){var n=t.x-e.x,r=t.y-e.y,i=e.r+t.r;return.999*i*i>n*n+r*r}function uu(e){function p(e){n=Math.min(e.x-e.r,n),r=Math.max(e.x+e.r,r),i=Math.min(e.y-e.r,i),s=Math.max(e.y+e.r,s)}if(!(t=e.children)||!(h=t.length))return;var t,n=Infinity,r=-Infinity,i=Infinity,s=-Infinity,o,u,a,f,l,c,h;t.forEach(au),o=t[0],o.x=-o.r,o.y=0,p(o);if(h>1){u=t[1],u.x=u.r,u.y=0,p(u);if(h>2){a=t[2],cu(o,u,a),p(a),iu(o,a),o._pack_prev=a,iu(a,u),u=o._pack_next;for(f=3;f<h;f++){cu(o,u,a=t[f]);var d=0,v=1,m=1;for(l=u._pack_next;l!==u;l=l._pack_next,v++)if(ou(l,a)){d=1;break}if(d==1)for(c=o._pack_prev;c!==l._pack_prev;c=c._pack_prev,m++)if(ou(c,a))break;d?(v<m||v==m&&u.r<o.r?su(o,u=l):su(o=c,u),f--):(iu(o,a),u=a,p(a))}}}var g=(n+r)/2,y=(i+s)/2,b=0;for(f=0;f<h;f++)a=t[f],a.x-=g,a.y-=y,b=Math.max(b,a.r+Math.sqrt(a.x*a.x+a.y*a.y));e.r=b,t.forEach(fu)}function au(e){e._pack_next=e._pack_prev=e}function fu(e){delete e._pack_next,delete e._pack_prev}function lu(e,t,n,r){var i=e.children;e.x=t+=r*e.x,e.y=n+=r*e.y,e.r*=r;if(i){var s=-1,o=i.length;while(++s<o)lu(i[s],t,n,r)}}function cu(e,t,n){var r=e.r+n.r,i=t.x-e.x,s=t.y-e.y;if(r&&(i||s)){var o=t.r+n.r,u=i*i+s*s;o*=o,r*=r;var a=.5+(r-o)/(2*u),f=Math.sqrt(Math.max(0,2*o*(r+u)-(r-=u)*r-o*o))/(2*u);n.x=e.x+a*i+f*s,n.y=e.y+a*s-f*i}else n.x=e.x+r,n.y=e.y}function hu(t){return 1+e.max(t,function(e){return e.y})}function pu(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}function du(e){var t=e.children;return t&&t.length?du(t[0]):e}function vu(e){var t=e.children,n;return t&&(n=t.length)?vu(t[n-1]):e}function mu(e){return{x:e.x,y:e.y,dx:e.dx,dy:e.dy}}function gu(e,t){var n=e.x+t[3],r=e.y+t[0],i=e.dx-t[1]-t[3],s=e.dy-t[0]-t[2];return i<0&&(n+=i/2,i=0),s<0&&(r+=s/2,s=0),{x:n,y:r,dx:i,dy:s}}function yu(e){var t=e[0],n=e[e.length-1];return t<n?[t,n]:[n,t]}function bu(e){return e.rangeExtent?e.rangeExtent():yu(e.range())}function wu(e,t,n,r){var i=n(e[0],e[1]),s=r(t[0],t[1]);return function(e){return s(i(e))}}function Eu(e,t){var n=0,r=e.length-1,i=e[n],s=e[r],o;return s<i&&(o=n,n=r,r=o,o=i,i=s,s=o),e[n]=t.floor(i),e[r]=t.ceil(s),e}function Su(e){return e?{floor:function(t){return Math.floor(t/e)*e},ceil:function(t){return Math.ceil(t/e)*e}}:xu}function Tu(t,n,r,i){var s=[],o=[],u=0,a=Math.min(t.length,n.length)-1;t[a]<t[0]&&(t=t.slice().reverse(),n=n.slice().reverse());while(++u<=a)s.push(r(t[u-1],t[u])),o.push(i(n[u-1],n[u]));return function(n){var r=e.bisect(t,n,1,a)-1;return o[r](s[r](n))}}function Nu(e,t,n,r){function o(){var o=Math.min(e.length,t.length)>2?Tu:wu,a=r?mo:vo;return i=o(e,t,a,n),s=o(t,e,a,qs),u}function u(e){return i(e)}var i,s;return u.invert=function(e){return s(e)},u.domain=function(t){return arguments.length?(e=t.map(Number),o()):e},u.range=function(e){return arguments.length?(t=e,o()):t},u.rangeRound=function(e){return u.range(e).interpolate(uo)},u.clamp=function(e){return arguments.length?(r=e,o()):r},u.interpolate=function(e){return arguments.length?(n=e,o()):n},u.ticks=function(t){return Au(e,t)},u.tickFormat=function(t,n){return Ou(e,t,n)},u.nice=function(t){return ku(e,t),o()},u.copy=function(){return Nu(e,t,n,r)},o()}function Cu(t,n){return e.rebind(t,n,"range","rangeRound","interpolate","clamp")}function ku(e,t){return Eu(e,Su(Lu(e,t)[2]))}function Lu(e,t){t==null&&(t=10);var n=yu(e),r=n[1]-n[0],i=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),s=t/r*i;return s<=.15?i*=10:s<=.35?i*=5:s<=.75&&(i*=2),n[0]=Math.ceil(n[0]/i)*i,n[1]=Math.floor(n[1]/i)*i+i*.5,n[2]=i,n}function Au(t,n){return e.range.apply(e,Lu(t,n))}function Ou(t,n,r){var i=Lu(t,n);return e.format(r?r.replace(Hn,function(e,t,n,r,s,o,u,a,f,l){return[t,n,r,s,o,u,a,f||"."+Du(l,i),l].join("")}):",."+_u(i[2])+"f")}function _u(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}function Du(e,t){var n=_u(t[2]);return e in Mu?Math.abs(n-_u(Math.max(Math.abs(t[0]),Math.abs(t[1]))))+ +(e!=="e"):n-(e==="%")*2}function Pu(t,n,r,i){function s(e){return(r?Math.log(e<0?0:e):-Math.log(e>0?0:-e))/Math.log(n)}function o(e){return r?Math.pow(n,e):-Math.pow(n,-e)}function u(e){return t(s(e))}return u.invert=function(e){return o(t.invert(e))},u.domain=function(e){return arguments.length?(r=e[0]>=0,t.domain((i=e.map(Number)).map(s)),u):i},u.base=function(e){return arguments.length?(n=+e,t.domain(i.map(s)),u):n},u.nice=function(){var e=Eu(i.map(s),r?Math:Bu);return t.domain(e),i=e.map(o),u},u.ticks=function(){var e=yu(i),t=[],u=e[0],a=e[1],f=Math.floor(s(u)),l=Math.ceil(s(a)),c=n%1?2:n;if(isFinite(l-f)){if(r){for(;f<l;f++)for(var h=1;h<c;h++)t.push(o(f)*h);t.push(o(f))}else{t.push(o(f));for(;f++<l;)for(var h=c-1;h>0;h--)t.push(o(f)*h)}for(f=0;t[f]<u;f++);for(l=t.length;t[l-1]>a;l--);t=t.slice(f,l)}return t},u.tickFormat=function(t,n){if(!arguments.length)return Hu;arguments.length<2?n=Hu:typeof n!="function"&&(n=e.format(n));var i=Math.max(.1,t/u.ticks().length),a=r?(f=1e-12,Math.ceil):(f=-1e-12,Math.floor),f;return function(e){return e/o(a(s(e)+f))<=i?n(e):""}},u.copy=function(){return Pu(t.copy(),n,r,i)},Cu(u,t)}function ju(e,t,n){function s(t){return e(r(t))}var r=Fu(t),i=Fu(1/t);return s.invert=function(t){return i(e.invert(t))},s.domain=function(t){return arguments.length?(e.domain((n=t.map(Number)).map(r)),s):n},s.ticks=function(e){return Au(n,e)},s.tickFormat=function(e,t){return Ou(n,e,t)},s.nice=function(e){return s.domain(ku(n,e))},s.exponent=function(o){return arguments.length?(r=Fu(t=o),i=Fu(1/t),e.domain(n.map(r)),s):t},s.copy=function(){return ju(e.copy(),t,n)},Cu(s,e)}function Fu(e){return function(t){return t<0?-Math.pow(-t,e):Math.pow(t,e)}}function Iu(t,n){function o(e){return i[((r.get(e)||n.t==="range"&&r.set(e,t.push(e)))-1)%i.length]}function u(n,r){return e.range(t.length).map(function(e){return n+r*e})}var r,i,s;return o.domain=function(e){if(!arguments.length)return t;t=[],r=new b;var i=-1,s=e.length,u;while(++i<s)r.has(u=e[i])||r.set(u,t.push(u));return o[n.t].apply(o,n.a)},o.range=function(e){return arguments.length?(i=e,s=0,n={t:"range",a:arguments},o):i},o.rangePoints=function(e,r){arguments.length<2&&(r=0);var a=e[0],f=e[1],l=(f-a)/(Math.max(1,t.length-1)+r);return i=u(t.length<2?(a+f)/2:a+l*r/2,l),s=0,n={t:"rangePoints",a:arguments},o},o.rangeBands=function(e,r,a){arguments.length<2&&(r=0),arguments.length<3&&(a=r);var f=e[1]<e[0],l=e[f-0],c=e[1-f],h=(c-l)/(t.length-r+2*a);return i=u(l+h*a,h),f&&i.reverse(),s=h*(1-r),n={t:"rangeBands",a:arguments},o},o.rangeRoundBands=function(e,r,a){arguments.length<2&&(r=0),arguments.length<3&&(a=r);var f=e[1]<e[0],l=e[f-0],c=e[1-f],h=Math.floor((c-l)/(t.length-r+2*a)),p=c-l-(t.length-r)*h;return i=u(l+Math.round(p/2),h),f&&i.reverse(),s=Math.round(h*(1-r)),n={t:"rangeRoundBands",a:arguments},o},o.rangeBand=function(){return s},o.rangeExtent=function(){return yu(n.a[0])},o.copy=function(){return Iu(t,n)},o.domain(t)}function Wu(t,n){function i(){var i=0,o=n.length;r=[];while(++i<o)r[i-1]=e.quantile(t,i/o);return s}function s(t){if(!isNaN(t=+t))return n[e.bisect(r,t)]}var r;return s.domain=function(n){return arguments.length?(t=n.filter(function(e){return!isNaN(e)}).sort(e.ascending),i()):t},s.range=function(e){return arguments.length?(n=e,i()):n},s.quantiles=function(){return r},s.invertExtent=function(e){return e=n.indexOf(e),e<0?[NaN,NaN]:[e>0?r[e-1]:t[0],e<r.length?r[e]:t[t.length-1]]},s.copy=function(){return Wu(t,n)},i()}function Xu(e,t,n){function s(t){return n[Math.max(0,Math.min(i,Math.floor(r*(t-e))))]}function o(){return r=n.length/(t-e),i=n.length-1,s}var r,i;return s.domain=function(n){return arguments.length?(e=+n[0],t=+n[n.length-1],o()):[e,t]},s.range=function(e){return arguments.length?(n=e,o()):n},s.invertExtent=function(t){return t=n.indexOf(t),t=t<0?NaN:t/r+e,[t,t+1/r]},s.copy=function(){return Xu(e,t,n)},o()}function Vu(t,n){function r(r){if(r<=r)return n[e.bisect(t,r)]}return r.domain=function(e){return arguments.length?(t=e,r):t},r.range=function(e){return arguments.length?(n=e,r):n},r.invertExtent=function(e){return e=n.indexOf(e),[t[e-1],t[e]]},r.copy=function(){return Vu(t,n)},r}function $u(e){function t(e){return+e}return t.invert=t,t.domain=t.range=function(n){return arguments.length?(e=n.map(t),t):e},t.ticks=function(t){return Au(e,t)},t.tickFormat=function(t,n){return Ou(e,t,n)},t.copy=function(){return $u(e)},t}function Qu(e){return e.innerRadius}function Gu(e){return e.outerRadius}function Yu(e){return e.startAngle}function Zu(e){return e.endAngle}function ea(e){function u(s){function d(){u.push("M",i(e(a),o))}var u=[],a=[],f=-1,l=s.length,c,h=vn(t),p=vn(n);while(++f<l)r.call(this,c=s[f],f)?a.push([+h.call(this,c,f),+p.call(this,c,f)]):a.length&&(d(),a=[]);return a.length&&d(),u.length?u.join(""):null}var t=Ui,n=zi,r=Tr,i=na,s=i.key,o=.7;return u.x=function(e){return arguments.length?(t=e,u):t},u.y=function(e){return arguments.length?(n=e,u):n},u.defined=function(e){return arguments.length?(r=e,u):r},u.interpolate=function(e){return arguments.length?(typeof e=="function"?s=i=e:s=(i=ta.get(e)||na).key,u):s},u.tension=function(e){return arguments.length?(o=e,u):o},u}function na(e){return e.join("L")}function ra(e){return na(e)+"Z"}function ia(e){var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];while(++t<n)i.push("H",(r[0]+(r=e[t])[0])/2,"V",r[1]);return n>1&&i.push("H",r[0]),i.join("")}function sa(e){var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];while(++t<n)i.push("V",(r=e[t])[1],"H",r[0]);return i.join("")}function oa(e){var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];while(++t<n)i.push("H",(r=e[t])[0],"V",r[1]);return i.join("")}function ua(e,t){return e.length<4?na(e):e[1]+la(e.slice(1,e.length-1),ca(e,t))}function aa(e,t){return e.length<3?na(e):e[0]+la((e.push(e[0]),e),ca([e[e.length-2]].concat(e,[e[1]]),t))}function fa(e,t){return e.length<3?na(e):e[0]+la(e,ca(e,t))}function la(e,t){if(t.length<1||e.length!=t.length&&e.length!=t.length+2)return na(e);var n=e.length!=t.length,r="",i=e[0],s=e[1],o=t[0],u=o,a=1;n&&(r+="Q"+(s[0]-o[0]*2/3)+","+(s[1]-o[1]*2/3)+","+s[0]+","+s[1],i=e[1],a=2);if(t.length>1){u=t[1],s=e[a],a++,r+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(s[0]-u[0])+","+(s[1]-u[1])+","+s[0]+","+s[1];for(var f=2;f<t.length;f++,a++)s=e[a],u=t[f],r+="S"+(s[0]-u[0])+","+(s[1]-u[1])+","+s[0]+","+s[1]}if(n){var l=e[a];r+="Q"+(s[0]+u[0]*2/3)+","+(s[1]+u[1]*2/3)+","+l[0]+","+l[1]}return r}function ca(e,t){var n=[],r=(1-t)/2,i,s=e[0],o=e[1],u=1,a=e.length;while(++u<a)i=s,s=o,o=e[u],n.push([r*(o[0]-i[0]),r*(o[1]-i[1])]);return n}function ha(e){if(e.length<3)return na(e);var t=1,n=e.length,r=e[0],i=r[0],s=r[1],o=[i,i,i,(r=e[1])[0]],u=[s,s,s,r[1]],a=[i,",",s,"L",ma(ba,o),",",ma(ba,u)];e.push(e[n-1]);while(++t<=n)r=e[t],o.shift(),o.push(r[0]),u.shift(),u.push(r[1]),wa(a,o,u);return e.pop(),a.push("L",r),a.join("")}function pa(e){if(e.length<4)return na(e);var t=[],n=-1,r=e.length,i,s=[0],o=[0];while(++n<3)i=e[n],s.push(i[0]),o.push(i[1]);t.push(ma(ba,s)+","+ma(ba,o)),--n;while(++n<r)i=e[n],s.shift(),s.push(i[0]),o.shift(),o.push(i[1]),wa(t,s,o);return t.join("")}function da(e){var t,n=-1,r=e.length,i=r+4,s,o=[],u=[];while(++n<4)s=e[n%r],o.push(s[0]),u.push(s[1]);t=[ma(ba,o),",",ma(ba,u)],--n;while(++n<i)s=e[n%r],o.shift(),o.push(s[0]),u.shift(),u.push(s[1]),wa(t,o,u);return t.join("")}function va(e,t){var n=e.length-1;if(n){var r=e[0][0],i=e[0][1],s=e[n][0]-r,o=e[n][1]-i,u=-1,a,f;while(++u<=n)a=e[u],f=u/n,a[0]=t*a[0]+(1-t)*(r+f*s),a[1]=t*a[1]+(1-t)*(i+f*o)}return ha(e)}function ma(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]}function wa(e,t,n){e.push("C",ma(ga,t),",",ma(ga,n),",",ma(ya,t),",",ma(ya,n),",",ma(ba,t),",",ma(ba,n))}function Ea(e,t){return(t[1]-e[1])/(t[0]-e[0])}function Sa(e){var t=0,n=e.length-1,r=[],i=e[0],s=e[1],o=r[0]=Ea(i,s);while(++t<n)r[t]=(o+(o=Ea(i=s,s=e[t+1])))/2;return r[t]=o,r}function xa(e){var t=[],n,r,i,s,o=Sa(e),u=-1,a=e.length-1;while(++u<a)n=Ea(e[u],e[u+1]),m(n)<yt?o[u]=o[u+1]=0:(r=o[u]/n,i=o[u+1]/n,s=r*r+i*i,s>9&&(s=n*3/Math.sqrt(s),o[u]=s*r,o[u+1]=s*i));u=-1;while(++u<=a)s=(e[Math.min(a,u+1)][0]-e[Math.max(0,u-1)][0])/(6*(1+o[u]*o[u])),t.push([s||0,o[u]*s||0]);return t}function Ta(e){return e.length<3?na(e):e[0]+la(e,xa(e))}function Na(e){var t,n=-1,r=e.length,i,s;while(++n<r)t=e[n],i=t[0],s=t[1]+Ju,t[0]=i*Math.cos(s),t[1]=i*Math.sin(s);return e}function Ca(e){function c(u){function x(){c.push("M",o(e(p),l),f,a(e(h.reverse()),l),"Z")}var c=[],h=[],p=[],d=-1,v=u.length,m,g=vn(t),y=vn(r),b=t===n?function(){return E}:vn(n),w=r===i?function(){return S}:vn(i),E,S;while(++d<v)s.call(this,m=u[d],d)?(h.push([E=+g.call(this,m,d),S=+y.call(this,m,d)]),p.push([+b.call(this,m,d),+w.call(this,m,d)])):h.length&&(x(),h=[],p=[]);return h.length&&x(),c.length?c.join(""):null}var t=Ui,n=Ui,r=0,i=zi,s=Tr,o=na,u=o.key,a=o,f="L",l=.7;return c.x=function(e){return arguments.length?(t=n=e,c):n},c.x0=function(e){return arguments.length?(t=e,c):t},c.x1=function(e){return arguments.length?(n=e,c):n},c.y=function(e){return arguments.length?(r=i=e,c):i},c.y0=function(e){return arguments.length?(r=e,c):r},c.y1=function(e){return arguments.length?(i=e,c):i},c.defined=function(e){return arguments.length?(s=e,c):s},c.interpolate=function(e){return arguments.length?(typeof e=="function"?u=o=e:u=(o=ta.get(e)||na).key,a=o.reverse||o,f=o.closed?"M":"L",c):u},c.tension=function(e){return arguments.length?(l=e,c):l},c}function ka(e){return e.radius}function La(e){return[e.x,e.y]}function Aa(e){return function(){var t=e.apply(this,arguments),n=t[0],r=t[1]+Ju;return[n*Math.cos(r),n*Math.sin(r)]}}function Oa(){return 64}function Ma(){return"circle"}function _a(e){var t=Math.sqrt(e/vt);return"M0,"+t+"A"+t+","+t+" 0 1,1 0,"+ -t+"A"+t+","+t+" 0 1,1 0,"+t+"Z"}function Ba(e,t){return D(e,ja),e.id=t,e}function Ra(e,t,n,r){var i=e.id;return et(e,typeof n=="function"?function(e,s,o){e.__transition__[i].tween.set(t,r(n.call(e,e.__data__,s,o)))}:(n=r(n),function(e){e.__transition__[i].tween.set(t,n)}))}function Ua(e){return e==null&&(e=""),function(){this.textContent=e}}function za(t,n,r,i){var s=t.__transition__||(t.__transition__={active:0,count:0}),o=s[r];if(!o){var u=i.time;o=s[r]={tween:new b,time:u,ease:i.ease,delay:i.delay,duration:i.duration},++s.count,e.timer(function(i){function d(i){if(s.active>r)return m();s.active=r,o.event&&o.event.start.call(t,a,n),o.tween.forEach(function(e,r){(r=r.call(t,a,n))&&p.push(r)}),e.timer(function(){return h.c=v(i||1)?Tr:v,1},0,u)}function v(e){if(s.active!==r)return m();var i=e/c,u=f(i),l=p.length;while(l>0)p[--l].call(t,u);if(i>=1)return o.event&&o.event.end.call(t,a,n),m()}function m(){return--s.count?delete s[r]:delete t.__transition__,1}var a=t.__data__,f=o.ease,l=o.delay,c=o.duration,h=Tn,p=[];h.t=l+u;if(l<=i)return d(i-l);h.c=d},0,u)}}function Va(e,t){e.attr("transform",function(e){return"translate("+t(e)+",0)"})}function $a(e,t){e.attr("transform",function(e){return"translate(0,"+t(e)+")"})}function Za(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function ff(e,t,n){function r(t){var n=e(t),r=s(n,1);return t-n<r-t?n:r}function i(n){return t(n=e(new Ga(n-1)),1),n}function s(e,n){return t(e=new Ga(+e),n),e}function o(e,r,s){var o=i(e),u=[];if(s>1)while(o<r)n(o)%s||u.push(new Date(+o)),t(o,1);else while(o<r)u.push(new Date(+o)),t(o,1);return u}function u(e,t,n){try{Ga=Za;var r=new Za;return r._=e,o(r,t,n)}finally{Ga=Date}}e.floor=e,e.round=r,e.ceil=i,e.offset=s,e.range=o;var a=e.utc=lf(e);return a.floor=a,a.round=lf(r),a.ceil=lf(i),a.offset=lf(s),a.range=u,e}function lf(e){return function(t,n){try{Ga=Za;var r=new Za;return r._=t,e(r,n)._}finally{Ga=Date}}}function cf(e){function n(n){var r=[],i=-1,s=0,o,u,a;while(++i<t)if(e.charCodeAt(i)===37){r.push(e.substring(s,i)),(u=Nf[o=e.charAt(++i)])!=null&&(o=e.charAt(++i));if(a=Cf[o])o=a(n,u==null?o==="e"?" ":"0":u);r.push(o),s=i+1}return r.push(e.substring(s,i)),r.join("")}var t=e.length;return n.parse=function(t){var n={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},r=hf(n,e,t,0);if(r!=t.length)return null;"p"in n&&(n.H=n.H%12+n.p*12);var i=n.Z!=null&&Ga!==Za,s=new(i?Za:Ga);return"j"in n?s.setFullYear(n.y,0,n.j):"w"in n&&("W"in n||"U"in n)?(s.setFullYear(n.y,0,1),s.setFullYear(n.y,0,"W"in n?(n.w+6)%7+n.W*7-(s.getDay()+5)%7:n.w+n.U*7-(s.getDay()+6)%7)):s.setFullYear(n.y,n.m,n.d),s.setHours(n.H+Math.floor(n.Z/100),n.M+n.Z%100,n.S,n.L),i?s._:s},n.toString=function(){return e},n}function hf(e,t,n,r){var i,s,o,u=0,a=t.length,f=n.length;while(u<a){if(r>=f)return-1;i=t.charCodeAt(u++);if(i===37){o=t.charAt(u++),s=kf[o in Nf?t.charAt(u++):o];if(!s||(r=s(e,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}function pf(t){return new RegExp("^(?:"+t.map(e.requote).join("|")+")","i")}function df(e){var t=new b,n=-1,r=e.length;while(++n<r)t.set(e[n].toLowerCase(),n);return t}function vf(e,t,n){var r=e<0?"-":"",i=(r?-e:e)+"",s=i.length;return r+(s<n?(new Array(n-s+1)).join(t)+i:i)}function Lf(e,t,n){yf.lastIndex=0;var r=yf.exec(t.substring(n));return r?(e.w=bf.get(r[0].toLowerCase()),n+r[0].length):-1}function Af(e,t,n){mf.lastIndex=0;var r=mf.exec(t.substring(n));return r?(e.w=gf.get(r[0].toLowerCase()),n+r[0].length):-1}function Of(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function Mf(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n));return r?(e.U=+r[0],n+r[0].length):-1}function _f(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n));return r?(e.W=+r[0],n+r[0].length):-1}function Df(e,t,n){Sf.lastIndex=0;var r=Sf.exec(t.substring(n));return r?(e.m=xf.get(r[0].toLowerCase()),n+r[0].length):-1}function Pf(e,t,n){wf.lastIndex=0;var r=wf.exec(t.substring(n));return r?(e.m=Ef.get(r[0].toLowerCase()),n+r[0].length):-1}function Hf(e,t,n){return hf(e,Cf.c.toString(),t,n)}function Bf(e,t,n){return hf(e,Cf.x.toString(),t,n)}function jf(e,t,n){return hf(e,Cf.X.toString(),t,n)}function Ff(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function If(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n,n+2));return r?(e.y=Rf(+r[0]),n+r[0].length):-1}function qf(e,t,n){return/^[+-]\d{4}$/.test(t=t.substring(n,n+5))?(e.Z=+t,n+5):-1}function Rf(e){return e+(e>68?1900:2e3)}function Uf(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function zf(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function Wf(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function Xf(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function Vf(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function $f(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function Jf(e,t,n){Kf.lastIndex=0;var r=Kf.exec(t.substring(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function Qf(e,t,n){var r=Gf.get(t.substring(n,n+=2).toLowerCase());return r==null?-1:(e.p=r,n)}function Yf(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=~~(m(t)/60),i=m(t)%60;return n+vf(r,"0",2)+vf(i,"0",2)}function Zf(e,t,n){Tf.lastIndex=0;var r=Tf.exec(t.substring(n,n+1));return r?n+r[0].length:-1}function el(e){function n(e){try{Ga=Za;var n=new Ga;return n._=e,t(n)}finally{Ga=Date}}var t=cf(e);return n.parse=function(e){try{Ga=Za;var n=t.parse(e);return n&&n._}finally{Ga=Date}},n.toString=t.toString,n}function nl(e){return e.toISOString()}function rl(t,n,r){function i(e){return t(e)}function s(t,r){var i=t[1]-t[0],s=i/r,o=e.bisect(ol,s);return o==ol.length?[n.year,Lu(t.map(function(e){return e/31536e6}),r)[2]]:o?n[s/ol[o-1]<ol[o]/s?o-1:o]:[ll,Lu(t,r)[2]]}return i.invert=function(e){return il(t.invert(e))},i.domain=function(e){return arguments.length?(t.domain(e),i):t.domain().map(il)},i.nice=function(e,t){function u(n){return!isNaN(n)&&!e.range(n,il(+n+1),t).length}var n=i.domain(),r=yu(n),o=e==null?s(r,10):typeof e=="number"&&s(r,e);return o&&(e=o[0],t=o[1]),i.domain(Eu(n,t>1?{floor:function(t){while(u(t=e.floor(t)))t=il(t-1);return t},ceil:function(t){while(u(t=e.ceil(t)))t=il(+t+1);return t}}:e))},i.ticks=function(e,t){var n=yu(i.domain()),r=e==null?s(n,10):typeof e=="number"?s(n,e):!e.range&&[{range:e},t];return r&&(e=r[0],t=r[1]),e.range(n[0],il(+n[1]+1),t<1?1:t)},i.tickFormat=function(){return r},i.copy=function(){return rl(t.copy(),n,r)},Cu(i,t)}function il(e){return new Date(e)}function sl(e){return function(t){var n=e.length-1,r=e[n];while(!r[1](t))r=e[--n];return r[0](t)}}function dl(e){return JSON.parse(e.responseText)}function vl(e){var t=r.createRange();return t.selectNode(r.body),t.createContextualFragment(e.responseText)}var e={version:"3.3.10"};Date.now||(Date.now=function(){return+(new Date)});var t=[].slice,n=function(e){return t.call(e)},r=document,i=r.documentElement,s=window;try{n(i.childNodes)[0].nodeType}catch(o){n=function(e){var t=e.length,n=new Array(t);while(t--)n[t]=e[t];return n}}try{r.createElement("div").style.setProperty("opacity",0,"")}catch(u){var a=s.Element.prototype,f=a.setAttribute,l=a.setAttributeNS,c=s.CSSStyleDeclaration.prototype,h=c.setProperty;a.setAttribute=function(e,t){f.call(this,e,t+"")},a.setAttributeNS=function(e,t,n){l.call(this,e,t,n+"")},c.setProperty=function(e,t,n){h.call(this,e,t+"",n)}}e.ascending=function(e,t){return e<t?-1:e>t?1:e>=t?0:NaN},e.descending=function(e,t){return t<e?-1:t>e?1:t>=e?0:NaN},e.min=function(e,t){var n=-1,r=e.length,i,s;if(arguments.length===1){while(++n<r&&!((i=e[n])!=null&&i<=i))i=undefined;while(++n<r)(s=e[n])!=null&&i>s&&(i=s)}else{while(++n<r&&!((i=t.call(e,e[n],n))!=null&&i<=i))i=undefined;while(++n<r)(s=t.call(e,e[n],n))!=null&&i>s&&(i=s)}return i},e.max=function(e,t){var n=-1,r=e.length,i,s;if(arguments.length===1){while(++n<r&&!((i=e[n])!=null&&i<=i))i=undefined;while(++n<r)(s=e[n])!=null&&s>i&&(i=s)}else{while(++n<r&&!((i=t.call(e,e[n],n))!=null&&i<=i))i=undefined;while(++n<r)(s=t.call(e,e[n],n))!=null&&s>i&&(i=s)}return i},e.extent=function(e,t){var n=-1,r=e.length,i,s,o;if(arguments.length===1){while(++n<r&&!((i=o=e[n])!=null&&i<=i))i=o=undefined;while(++n<r)(s=e[n])!=null&&(i>s&&(i=s),o<s&&(o=s))}else{while(++n<r&&!((i=o=t.call(e,e[n],n))!=null&&i<=i))i=undefined;while(++n<r)(s=t.call(e,e[n],n))!=null&&(i>s&&(i=s),o<s&&(o=s))}return[i,o]},e.sum=function(e,t){var n=0,r=e.length,i,s=-1;if(arguments.length===1)while(++s<r)isNaN(i=+e[s])||(n+=i);else while(++s<r)isNaN(i=+t.call(e,e[s],s))||(n+=i);return n},e.mean=function(e,t){var n=e.length,r,i=0,s=-1,o=0;if(arguments.length===1)while(++s<n)p(r=e[s])&&(i+=(r-i)/++o);else while(++s<n)p(r=t.call(e,e[s],s))&&(i+=(r-i)/++o);return o?i:undefined},e.quantile=function(e,t){var n=(e.length-1)*t+1,r=Math.floor(n),i=+e[r-1],s=n-r;return s?i+s*(e[r]-i):i},e.median=function(t,n){return arguments.length>1&&(t=t.map(n)),t=t.filter(p),t.length?e.quantile(t.sort(e.ascending),.5):undefined},e.bisector=function(e){return{left:function(t,n,r,i){arguments.length<3&&(r=0),arguments.length<4&&(i=t.length);while(r<i){var s=r+i>>>1;e.call(t,t[s],s)<n?r=s+1:i=s}return r},right:function(t,n,r,i){arguments.length<3&&(r=0),arguments.length<4&&(i=t.length);while(r<i){var s=r+i>>>1;n<e.call(t,t[s],s)?i=s:r=s+1}return r}}};var d=e.bisector(function(e){return e});e.bisectLeft=d.left,e.bisect=e.bisectRight=d.right,e.shuffle=function(e){var t=e.length,n,r;while(t)r=Math.random()*t--|0,n=e[t],e[t]=e[r],e[r]=n;return e},e.permute=function(e,t){var n=t.length,r=new Array(n);while(n--)r[n]=e[t[n]];return r},e.pairs=function(e){var t=0,n=e.length-1,r,i=e[0],s=new Array(n<0?0:n);while(t<n)s[t]=[r=i,i=e[++t]];return s},e.zip=function(){if(!(s=arguments.length))return[];for(var t=-1,n=e.min(arguments,v),r=new Array(n);++t<n;)for(var i=-1,s,o=r[t]=new Array(s);++i<s;)o[i]=arguments[i][t];return r},e.transpose=function(t){return e.zip.apply(e,t)},e.keys=function(e){var t=[];for(var n in e)t.push(n);return t},e.values=function(e){var t=[];for(var n in e)t.push(e[n]);return t},e.entries=function(e){var t=[];for(var n in e)t.push({key:n,value:e[n]});return t},e.merge=function(e){var t=e.length,n,r=-1,i=0,s,o;while(++r<t)i+=e[r].length;s=new Array(i);while(--t>=0){o=e[t],n=o.length;while(--n>=0)s[--i]=o[n]}return s};var m=Math.abs;e.range=function(e,t,n){arguments.length<3&&(n=1,arguments.length<2&&(t=e,e=0));if((t-e)/n===Infinity)throw new Error("infinite range");var r=[],i=g(m(n)),s=-1,o;e*=i,t*=i,n*=i;if(n<0)while((o=e+n*++s)>t)r.push(o/i);else while((o=e+n*++s)<t)r.push(o/i);return r},e.map=function(e){var t=new b;if(e instanceof b)e.forEach(function(e,n){t.set(e,n)});else for(var n in e)t.set(n,e[n]);return t},y(b,{has:function(e){return w+e in this},get:function(e){return this[w+e]},set:function(e,t){return this[w+e]=t},remove:function(e){return e=w+e,e in this&&delete this[e]},keys:function(){var e=[];return this.forEach(function(t){e.push(t)}),e},values:function(){var e=[];return this.forEach(function(t,n){e.push(n)}),e},entries:function(){var e=[];return this.forEach(function(t,n){e.push({key:t,value:n})}),e},forEach:function(e){for(var t in this)t.charCodeAt(0)===E&&e.call(this,t.substring(1),this[t])}});var w="\0",E=w.charCodeAt(0);e.nest=function(){function o(e,r,u){if(u>=n.length)return s?s.call(t,r):i?r.sort(i):r;var a=-1,f=r.length,l=n[u++],c,h,p,d=new b,v;while(++a<f)(v=d.get(c=l(h=r[a])))?v.push(h):d.set(c,[h]);return e?(h=e(),p=function(t,n){h.set(t,o(e,n,u))}):(h={},p=function(t,n){h[t]=o(e,n,u)}),d.forEach(p),h}function u(e,t){if(t>=n.length)return e;var i=[],s=r[t++];return e.forEach(function(e,n){i.push({key:e,values:u(n,t)})}),s?i.sort(function(e,t){return s(e.key,t.key)}):i}var t={},n=[],r=[],i,s;return t.map=function(e,t){return o(t,e,0)},t.entries=function(t){return u(o(e.map,t,0),0)},t.key=function(e){return n.push(e),t},t.sortKeys=function(e){return r[n.length-1]=e,t},t.sortValues=function(e){return i=e,t},t.rollup=function(e){return s=e,t},t},e.set=function(e){var t=new S;if(e)for(var n=0,r=e.length;n<r;++n)t.add(e[n]);return t},y(S,{has:function(e){return w+e in this},add:function(e){return this[w+e]=!0,e},remove:function(e){return e=w+e,e in this&&delete this[e]},values:function(){var e=[];return this.forEach(function(t){e.push(t)}),e},forEach:function(e){for(var t in this)t.charCodeAt(0)===E&&e.call(this,t.substring(1))}}),e.behavior={},e.rebind=function(e,t){var n=1,r=arguments.length,i;while(++n<r)e[i=arguments[n]]=x(e,t,t[i]);return e};var N=["webkit","ms","moz","Moz","o","O"];e.dispatch=function(){var e=new k,t=-1,n=arguments.length;while(++t<n)e[arguments[t]]=L(e);return e},k.prototype.on=function(e,t){var n=e.indexOf("."),r="";n>=0&&(r=e.substring(n+1),e=e.substring(0,n));if(e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(arguments.length===2){if(t==null)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null);return this}},e.event=null,e.requote=function(e){return e.replace(_,"\\$&")};var _=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,D={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]},H=function(e,t){return t.querySelector(e)},B=function(e,t){return t.querySelectorAll(e)},j=i[T(i,"matchesSelector")],F=function(e,t){return j.call(e,t)};typeof Sizzle=="function"&&(H=function(e,t){return Sizzle(e,t)[0]||null},B=function(e,t){return Sizzle.uniqueSort(Sizzle(e,t))},F=Sizzle.matchesSelector),e.selection=function(){return st};var I=e.selection.prototype=[];I.select=function(e){var t=[],n,r,i,s;e=q(e);for(var o=-1,u=this.length;++o<u;){t.push(n=[]),n.parentNode=(i=this[o]).parentNode;for(var a=-1,f=i.length;++a<f;)(s=i[a])?(n.push(r=e.call(s,s.__data__,a,o)),r&&"__data__"in s&&(r.__data__=s.__data__)):n.push(null)}return P(t)},I.selectAll=function(e){var t=[],r,i;e=R(e);for(var s=-1,o=this.length;++s<o;)for(var u=this[s],a=-1,f=u.length;++a<f;)if(i=u[a])t.push(r=n(e.call(i,i.__data__,a,s))),r.parentNode=i;return P(t)};var U={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};e.ns={prefix:U,qualify:function(e){var t=e.indexOf(":"),n=e;return t>=0&&(n=e.substring(0,t),e=e.substring(t+1)),U.hasOwnProperty(n)?{space:U[n],local:e}:e}},I.attr=function(t,n){if(arguments.length<2){if(typeof t=="string"){var r=this.node();return t=e.ns.qualify(t),t.local?r.getAttributeNS(t.space,t.local):r.getAttribute(t)}for(n in t)this.each(z(n,t[n]));return this}return this.each(z(t,n))},I.classed=function(e,t){if(arguments.length<2){if(typeof e=="string"){var n=this.node(),r=(e=e.trim().split(/^|\s+/g)).length,i=-1;if(t=n.classList){while(++i<r)if(!t.contains(e[i]))return!1}else{t=n.getAttribute("class");while(++i<r)if(!X(e[i]).test(t))return!1}return!0}for(t in e)this.each(V(t,e[t]));return this}return this.each(V(e,t))},I.style=function(e,t,n){var r=arguments.length;if(r<3){if(typeof e!="string"){r<2&&(t="");for(n in e)this.each(J(n,e[n],t));return this}if(r<2)return s.getComputedStyle(this.node(),null).getPropertyValue(e);n=""}return this.each(J(e,t,n))},I.property=function(e,t){if(arguments.length<2){if(typeof e=="string")return this.node()[e];for(t in e)this.each(K(t,e[t]));return this}return this.each(K(e,t))},I.text=function(e){return arguments.length?this.each(typeof e=="function"?function(){var t=e.apply(this,arguments);this.textContent=t==null?"":t}:e==null?function(){this.textContent=""}:function(){this.textContent=e}):this.node().textContent},I.html=function(e){return arguments.length?this.each(typeof e=="function"?function(){var t=e.apply(this,arguments);this.innerHTML=t==null?"":t}:e==null?function(){this.innerHTML=""}:function(){this.innerHTML=e}):this.node().innerHTML},I.append=function(e){return e=Q(e),this.select(function(){return this.appendChild(e.apply(this,arguments))})},I.insert=function(e,t){return e=Q(e),t=q(t),this.select(function(){return this.insertBefore(e.apply(this,arguments),t.apply(this,arguments)||null)})},I.remove=function(){return this.each(function(){var e=this.parentNode;e&&e.removeChild(this)})},I.data=function(e,t){function o(e,n){var r,i=e.length,s=n.length,o=Math.min(i,s),l=new Array(s),c=new Array(s),h=new Array(i),p,d;if(t){var v=new b,m=new b,g=[],y;for(r=-1;++r<i;)y=t.call(p=e[r],p.__data__,r),v.has(y)?h[r]=p:v.set(y,p),g.push(y);for(r=-1;++r<s;)y=t.call(n,d=n[r],r),(p=v.get(y))?(l[r]=p,p.__data__=d):m.has(y)||(c[r]=G(d)),m.set(y,d),v.remove(y);for(r=-1;++r<i;)v.has(g[r])&&(h[r]=e[r])}else{for(r=-1;++r<o;)p=e[r],d=n[r],p?(p.__data__=d,l[r]=p):c[r]=G(d);for(;r<s;++r)c[r]=G(n[r]);for(;r<i;++r)h[r]=e[r]}c.update=l,c.parentNode=l.parentNode=h.parentNode=e.parentNode,u.push(c),a.push(l),f.push(h)}var n=-1,r=this.length,i,s;if(!arguments.length){e=new Array(r=(i=this[0]).length);while(++n<r)if(s=i[n])e[n]=s.__data__;return e}var u=tt([]),a=P([]),f=P([]);if(typeof e=="function")while(++n<r)o(i=this[n],e.call(i,i.parentNode.__data__,n));else while(++n<r)o(i=this[n],e);return a.enter=function(){return u},a.exit=function(){return f},a},I.datum=function(e){return arguments.length?this.property("__data__",e):this.property("__data__")},I.filter=function(e){var t=[],n,r,i;typeof e!="function"&&(e=Y(e));for(var s=0,o=this.length;s<o;s++){t.push(n=[]),n.parentNode=(r=this[s]).parentNode;for(var u=0,a=r.length;u<a;u++)(i=r[u])&&e.call(i,i.__data__,u,s)&&n.push(i)}return P(t)},I.order=function(){for(var e=-1,t=this.length;++e<t;)for(var n=this[e],r=n.length-1,i=n[r],s;--r>=0;)if(s=n[r])i&&i!==s.nextSibling&&i.parentNode.insertBefore(s,i),i=s;return this},I.sort=function(e){e=Z.apply(this,arguments);for(var t=-1,n=this.length;++t<n;)this[t].sort(e);return this.order()},I.each=function(e){return et(this,function(t,n,r){e.call(t,t.__data__,n,r)})},I.call=function(e){var t=n(arguments);return e.apply(t[0]=this,t),this},I.empty=function(){return!this.node()},I.node=function(){for(var e=0,t=this.length;e<t;e++)for(var n=this[e],r=0,i=n.length;r<i;r++){var s=n[r];if(s)return s}return null},I.size=function(){var e=0;return this.each(function(){++e}),e};var nt=[];e.selection.enter=tt,e.selection.enter.prototype=nt,nt.append=I.append,nt.empty=I.empty,nt.node=I.node,nt.call=I.call,nt.size=I.size,nt.select=function(e){var t=[],n,r,i,s,o;for(var u=-1,a=this.length;++u<a;){i=(s=this[u]).update,t.push(n=[]),n.parentNode=s.parentNode;for(var f=-1,l=s.length;++f<l;)(o=s[f])?(n.push(i[f]=r=e.call(s.parentNode,o.__data__,f,u)),r.__data__=o.__data__):n.push(null)}return P(t)},nt.insert=function(e,t){return arguments.length<2&&(t=rt(this)),I.insert.call(this,e,t)},I.transition=function(){var e=Ia||++Fa,t=[],n,r,i=qa||{time:Date.now(),ease:Qs,delay:0,duration:250};for(var s=-1,o=this.length;++s<o;){t.push(n=[]);for(var u=this[s],a=-1,f=u.length;++a<f;)(r=u[a])&&za(r,a,e,i),n.push(r)}return Ba(t,e)},I.interrupt=function(){return this.each(it)},e.select=function(e){var t=[typeof e=="string"?H(e,r):e];return t.parentNode=i,P([t])},e.selectAll=function(e){var t=n(typeof e=="string"?B(e,r):e);return t.parentNode=i,P([t])};var st=e.select(i);I.on=function(e,t,n){var r=arguments.length;if(r<3){if(typeof e!="string"){r<2&&(t=!1);for(n in e)this.each(ot(n,e[n],t));return this}if(r<2)return(r=this.node()["__on"+e])&&r._;n=!1}return this.each(ot(e,t,n))};var ut=e.map({mouseenter:"mouseover",mouseleave:"mouseout"});ut.forEach(function(e){"on"+e in r&&ut.remove(e)});var lt="onselectstart"in r?null:T(i.style,"userSelect"),ct=0;e.mouse=function(e){return dt(e,O())};var pt=/WebKit/.test(s.navigator.userAgent)?-1:0;e.touches=function(e,t){return arguments.length<2&&(t=O().touches),t?n(t).map(function(t){var n=dt(e,t);return n.identifier=t.identifier,n}):[]},e.behavior.drag=function(){function o(){this.on("mousedown.drag",r).on("touchstart.drag",i)}function u(){return e.event.changedTouches[0].identifier}function a(t,n){return e.touches(t).filter(function(e){return e.identifier===n})[0]}function f(r,i,o,u){return function(){function b(){var e=i(f,h),t=e[0]-d[0],n=e[1]-d[1];v|=t|n,d=e,l({type:"drag",x:e[0]+m[0],y:e[1]+m[1],dx:t,dy:n})}function w(){g.on(o+"."+p,null).on(u+"."+p,null),y(v&&e.event.target===c),l({type:"dragend"})}var a=this,f=a.parentNode,l=t.of(a,arguments),c=e.event.target,h=r(),p=h==null?"drag":"drag-"+h,d=i(f,h),v=0,m,g=e.select(s).on(o+"."+p,b).on(u+"."+p,w),y=ht();n?(m=n.apply(a,arguments),m=[m.x-d[0],m.y-d[1]]):m=[0,0],l({type:"dragstart"})}}var t=M(o,"drag","dragstart","dragend"),n=null,r=f(C,e.mouse,"mousemove","mouseup"),i=f(u,a,"touchmove","touchend");return o.origin=function(e){return arguments.length?(n=e,o):n},e.rebind(o,t,"on")};var vt=Math.PI,mt=2*vt,gt=vt/2,yt=1e-6,bt=yt*yt,wt=vt/180,Et=180/vt,At=Math.SQRT2,Ot=2,Mt=4;e.interpolateZoom=function(e,t){function y(e){var t=e*g;if(m){var s=Ct(d),o=i/(Ot*c)*(s*kt(At*t+d)-Nt(d));return[n+o*a,r+o*f,i*s/Ct(At*t+d)]}return[n+e*a,r+e*f,i*Math.exp(At*t)]}var n=e[0],r=e[1],i=e[2],s=t[0],o=t[1],u=t[2],a=s-n,f=o-r,l=a*a+f*f,c=Math.sqrt(l),h=(u*u-i*i+Mt*l)/(2*i*Ot*c),p=(u*u-i*i-Mt*l)/(2*u*Ot*c),d=Math.log(Math.sqrt(h*h+1)-h),v=Math.log(Math.sqrt(p*p+1)-p),m=v-d,g=(m||Math.log(u/i))/At;return y.duration=g*1e3,y},e.behavior.zoom=function(){function y(e){e.on(u,k).on(Pt+".zoom",O).on(a,_).on("dblclick.zoom",D).on(c,L)}function b(e){return[(e[0]-t.x)/t.k,(e[1]-t.y)/t.k]}function w(e){return[e[0]*t.k+t.x,e[1]*t.k+t.y]}function E(e){t.k=Math.max(o[0],Math.min(o[1],e))}function S(e,n){n=w(n),t.x+=e[0]-n[0],t.y+=e[1]-n[1]}function x(){v&&v.domain(d.range().map(function(e){return(e-t.x)/t.k}).map(d.invert)),g&&g.domain(m.range().map(function(e){return(e-t.y)/t.k}).map(m.invert))}function T(e){e({type:"zoomstart"})}function N(e){x(),e({type:"zoom",scale:t.k,translate:[t.x,t.y]})}function C(e){e({type:"zoomend"})}function k(){function c(){i=1,S(e.mouse(t),u),N(n)}function h(){o.on(a,s===t?_:null).on(f,null),l(i&&e.event.target===r),C(n)}var t=this,n=p.of(t,arguments),r=e.event.target,i=0,o=e.select(s).on(a,c).on(f,h),u=b(e.mouse(t)),l=ht();it.call(t),T(n)}function L(){function y(){var r=e.touches(n);return a=t.k,r.forEach(function(e){e.identifier in i&&(i[e.identifier]=b(e))}),r}function w(){var n=e.event.changedTouches;for(var s=0,u=n.length;s<u;++s)i[n[s].identifier]=null;var a=y(),f=Date.now();if(a.length===1){if(f-h<500){var l=a[0],c=i[l.identifier];E(t.k*2),S(l,c),A(),N(r)}h=f}else if(a.length>1){var l=a[0],p=a[1],d=l[0]-p[0],v=l[1]-p[1];o=d*d+v*v}}function x(){var t=e.touches(n),s,u,f,l;for(var c=0,p=t.length;c<p;++c,l=null){f=t[c];if(l=i[f.identifier]){if(u)break;s=f,u=l}}if(l){var d=(d=f[0]-s[0])*d+(d=f[1]-s[1])*d,v=o&&Math.sqrt(d/o);s=[(s[0]+f[0])/2,(s[1]+f[1])/2],u=[(u[0]+l[0])/2,(u[1]+l[1])/2],E(v*a)}h=null,S(s,u),N(r)}function O(){if(e.event.touches.length){var t=e.event.changedTouches;for(var n=0,s=t.length;n<s;++n)delete i[t[n].identifier];for(var o in i)return void y()}v.on(l,null).on(d,null),m.on(u,k).on(c,L),g(),C(r)}var n=this,r=p.of(n,arguments),i={},o=0,a,f=e.event.changedTouches[0].identifier,l="touchmove.zoom-"+f,d="touchend.zoom-"+f,v=e.select(s).on(l,x).on(d,O),m=e.select(n).on(u,null).on(c,w),g=ht();it.call(n),w(),T(r)}function O(){var i=p.of(this,arguments);l?clearTimeout(l):(it.call(this),T(i)),l=setTimeout(function(){l=null,C(i)},50),A();var s=r||e.mouse(this);n||(n=b(s)),E(Math.pow(2,Dt()*.002)*t.k),S(s,n),N(i)}function _(){n=null}function D(){var n=p.of(this,arguments),r=e.mouse(this),i=b(r),s=Math.log(t.k)/Math.LN2;T(n),E(Math.pow(2,e.event.shiftKey?Math.ceil(s)-1:Math.floor(s)+1)),S(r,i),N(n),C(n)}var t={x:0,y:0,k:1},n,r,i=[960,500],o=_t,u="mousedown.zoom",a="mousemove.zoom",f="mouseup.zoom",l,c="touchstart.zoom",h,p=M(y,"zoomstart","zoom","zoomend"),d,v,m,g;return y.event=function(n){n.each(function(){var n=p.of(this,arguments),r=t;Ia?e.select(this).transition().each("start.zoom",function(){t=this.__chart__||{x:0,y:0,k:1},T(n)}).tween("zoom:zoom",function(){var s=i[0],o=i[1],u=s/2,a=o/2,f=e.interpolateZoom([(u-t.x)/t.k,(a-t.y)/t.k,s/t.k],[(u-r.x)/r.k,(a-r.y)/r.k,s/r.k]);return function(e){var r=f(e),i=s/r[2];this.__chart__=t={x:u-r[0]*i,y:a-r[1]*i,k:i},N(n)}}).each("end.zoom",function(){C(n)}):(this.__chart__=t,T(n),N(n),C(n))})},y.translate=function(e){return arguments.length?(t={x:+e[0],y:+e[1],k:t.k},x(),y):[t.x,t.y]},y.scale=function(e){return arguments.length?(t={x:t.x,y:t.y,k:+e},x(),y):t.k},y.scaleExtent=function(e){return arguments.length?(o=e==null?_t:[+e[0],+e[1]],y):o},y.center=function(e){return arguments.length?(r=e&&[+e[0],+e[1]],y):r},y.size=function(e){return arguments.length?(i=e&&[+e[0],+e[1]],y):i},y.x=function(e){return arguments.length?(v=e,d=e.copy(),t={x:0,y:0,k:1},y):v},y.y=function(e){return arguments.length?(g=e,m=e.copy(),t={x:0,y:0,k:1},y):g},e.rebind(y,p,"on")};var _t=[0,Infinity],Dt,Pt="onwheel"in r?(Dt=function(){return-e.event.deltaY*(e.event.deltaMode?120:1)},"wheel"):"onmousewheel"in r?(Dt=function(){return e.event.wheelDelta},"mousewheel"):(Dt=function(){return-e.event.detail},"MozMousePixelScroll");Ht.prototype.toString=function(){return this.rgb()+""},e.hsl=function(e,t,n){return arguments.length===1?e instanceof jt?Bt(e.h,e.s,e.l):fn(""+e,ln,Bt):Bt(+e,+t,+n)};var Ft=jt.prototype=new Ht;Ft.brighter=function(e){return e=Math.pow(.7,arguments.length?e:1),Bt(this.h,this.s,this.l/e)},Ft.darker=function(e){return e=Math.pow(.7,arguments.length?e:1),Bt(this.h,this.s,e*this.l)},Ft.rgb=function(){return It(this.h,this.s,this.l)},e.hcl=function(t,n,r){return arguments.length===1?t instanceof Rt?qt(t.h,t.c,t.l):t instanceof Xt?Yt(t.l,t.a,t.b):Yt((t=cn((t=e.rgb(t)).r,t.g,t.b)).l,t.a,t.b):qt(+t,+n,+r)};var Ut=Rt.prototype=new Ht;Ut.brighter=function(e){return qt(this.h,this.c,Math.min(100,this.l+Vt*(arguments.length?e:1)))},Ut.darker=function(e){return qt(this.h,this.c,Math.max(0,this.l-Vt*(arguments.length?e:1)))},Ut.rgb=function(){return zt(this.h,this.c,this.l).rgb()},e.lab=function(t,n,r){return arguments.length===1?t instanceof Xt?Wt(t.l,t.a,t.b):t instanceof Rt?zt(t.l,t.c,t.h):cn((t=e.rgb(t)).r,t.g,t.b):Wt(+t,+n,+r)};var Vt=18,$t=.95047,Jt=1,Kt=1.08883,Qt=Xt.prototype=new Ht;Qt.brighter=function(e){return Wt(Math.min(100,this.l+Vt*(arguments.length?e:1)),this.a,this.b)},Qt.darker=function(e){return Wt(Math.max(0,this.l-Vt*(arguments.length?e:1)),this.a,this.b)},Qt.rgb=function(){return Gt(this.l,this.a,this.b)},e.rgb=function(e,t,n){return arguments.length===1?e instanceof on?sn(e.r,e.g,e.b):fn(""+e,sn,It):sn(~~e,~~t,~~n)};var un=on.prototype=new Ht;un.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,n=this.g,r=this.b,i=30;return!t&&!n&&!r?sn(i,i,i):(t&&t<i&&(t=i),n&&n<i&&(n=i),r&&r<i&&(r=i),sn(Math.min(255,~~(t/e)),Math.min(255,~~(n/e)),Math.min(255,~~(r/e))))},un.darker=function(e){return e=Math.pow(.7,arguments.length?e:1),sn(~~(e*this.r),~~(e*this.g),~~(e*this.b))},un.hsl=function(){return ln(this.r,this.g,this.b)},un.toString=function(){return"#"+an(this.r)+an(this.g)+an(this.b)};var dn=e.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});dn.forEach(function(e,t){dn.set(e,nn(t))}),e.functor=vn,e.xhr=gn(mn),e.dsv=function(t,n){function s(t,r,i){arguments.length<3&&(i=r,r=null);var s=e.xhr(t,n,i);return s.row=function(e){return arguments.length?s.response((r=e)==null?o:u(e)):r},s.row(r)}function o(e){return s.parse(e.responseText)}function u(e){return function(t){return s.parse(t.responseText,e)}}function a(e){return e.map(f).join(t)}function f(e){return r.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}var r=new RegExp('["'+t+"\n]"),i=t.charCodeAt(0);return s.parse=function(e,t){var n;return s.parseRows(e,function(e,r){if(n)return n(e,r-1);var i=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");n=t?function(e,n){return t(i(e),n)}:i})},s.parseRows=function(e,t){function c(){if(u>=o)return r;if(l)return l=!1,n;var t=u;if(e.charCodeAt(t)===34){var s=t;while(s++<o)if(e.charCodeAt(s)===34){if(e.charCodeAt(s+1)!==34)break;++s}u=s+2;var a=e.charCodeAt(s+1);return a===13?(l=!0,e.charCodeAt(s+2)===10&&++u):a===10&&(l=!0),e.substring(t+1,s).replace(/""/g,'"')}while(u<o){var a=e.charCodeAt(u++),f=1;if(a===10)l=!0;else if(a===13)l=!0,e.charCodeAt(u)===10&&(++u,++f);else if(a!==i)continue;return e.substring(t,u-f)}return e.substring(t)}var n={},r={},s=[],o=e.length,u=0,a=0,f,l;while((f=c())!==r){var h=[];while(f!==n&&f!==r)h.push(f),f=c();if(t&&!(h=t(h,a++)))continue;s.push(h)}return s},s.format=function(e){if(Array.isArray(e[0]))return s.formatRows(e);var n=new S,r=[];return e.forEach(function(e){for(var t in e)n.has(t)||r.push(n.add(t))}),[r.map(f).join(t)].concat(e.map(function(e){return r.map(function(t){return f(e[t])}).join(t)})).join("\n")},s.formatRows=function(e){return e.map(a).join("\n")},s},e.csv=e.dsv(",","text/csv"),e.tsv=e.dsv("	","text/tab-separated-values");var wn,En,Sn,xn,Tn,Nn=s[T(s,"requestAnimationFrame")]||function(e){setTimeout(e,17)};e.timer=function(e,t,n){var r=arguments.length;r<2&&(t=0),r<3&&(n=Date.now());var i=n+t,s={c:e,t:i,f:!1,n:null};En?En.n=s:wn=s,En=s,Sn||(xn=clearTimeout(xn),Sn=1,Nn(Cn))},e.timer.flush=function(){kn(),Ln()};var An=".",On=",",Mn=[3,3],_n="$",Dn=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"].map(Pn);e.formatPrefix=function(t,n){var r=0;return t&&(t<0&&(t*=-1),n&&(t=e.round(t,jn(t,n))),r=1+Math.floor(1e-12+Math.log(t)/Math.LN10),r=Math.max(-24,Math.min(24,Math.floor((r<=0?r+1:r-1)/3)*3))),Dn[8+r/3]},e.round=function(e,t){return t?Math.round(e*(t=Math.pow(10,t)))/t:Math.round(e)},e.format=function(t){var n=Hn.exec(t),r=n[1]||" ",i=n[2]||">",s=n[3]||"",o=n[4]||"",u=n[5],a=+n[6],f=n[7],l=n[8],c=n[9],h=1,p="",d=!1;l&&(l=+l.substring(1));if(u||r==="0"&&i==="=")u=r="0",i="=",f&&(a-=Math.floor((a-1)/4));switch(c){case"n":f=!0,c="g";break;case"%":h=100,p="%",c="f";break;case"p":h=100,p="%",c="r";break;case"b":case"o":case"x":case"X":o==="#"&&(o="0"+c.toLowerCase());case"c":case"d":d=!0,l=0;break;case"s":h=-1,c="r"}o==="#"?o="":o==="$"&&(o=_n),c=="r"&&!l&&(c="g");if(l!=null)if(c=="g")l=Math.max(1,Math.min(21,l));else if(c=="e"||c=="f")l=Math.max(0,Math.min(20,l));c=Bn.get(c)||Fn;var v=u&&f;return function(t){if(d&&t%1)return"";var n=t<0||t===0&&1/t<0?(t=-t,"-"):s;if(h<0){var m=e.formatPrefix(t,l);t=m.scale(t),p=m.symbol}else t*=h;t=c(t,l);var g=t.lastIndexOf("."),y=g<0?t:t.substring(0,g),b=g<0?"":An+t.substring(g+1);!u&&f&&(y=In(y));var w=o.length+y.length+b.length+(v?0:n.length),E=w<a?(new Array(w=a-w+1)).join(r):"";return v&&(y=In(E+y)),n+=o,t=y+b,(i==="<"?n+t+E:i===">"?E+n+t:i==="^"?E.substring(0,w>>=1)+n+t+E.substring(w):n+(v?t:E+t))+p}};var Hn=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Bn=e.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(t,n){return(t=e.round(t,jn(t,n))).toFixed(Math.max(0,Math.min(20,jn(t*(1+1e-15),n))))}}),In=mn;if(Mn){var qn=Mn.length;In=function(e){var t=e.length,n=[],r=0,i=Mn[0];while(t>0&&i>0)n.push(e.substring(t-=i,t+i)),i=Mn[r=(r+1)%qn];return n.reverse().join(On)}}e.geo={},Rn.prototype={s:0,t:0,add:function(e){zn(e,this.t,Un),zn(Un.s,this.s,this),this.s?this.t+=Un.t:this.s=Un.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var Un=new Rn;e.geo.stream=function(e,t){e&&Xn.hasOwnProperty(e.type)?Xn[e.type](e,t):Wn(e,t)};var Xn={Feature:function(e,t){Wn(e.geometry,t)},FeatureCollection:function(e,t){var n=e.features,r=-1,i=n.length;while(++r<i)Wn(n[r].geometry,t)}},Vn={Sphere:function(e,t){t.sphere()},Point:function(e,t){e=e.coordinates,t.point(e[0],e[1],e[2])},MultiPoint:function(e,t){var n=e.coordinates,r=-1,i=n.length;while(++r<i)e=n[r],t.point(e[0],e[1],e[2])},LineString:function(e,t){$n(e.coordinates,t,0)},MultiLineString:function(e,t){var n=e.coordinates,r=-1,i=n.length;while(++r<i)$n(n[r],t,0)},Polygon:function(e,t){Jn(e.coordinates,t)},MultiPolygon:function(e,t){var n=e.coordinates,r=-1,i=n.length;while(++r<i)Jn(n[r],t)},GeometryCollection:function(e,t){var n=e.geometries,r=-1,i=n.length;while(++r<i)Wn(n[r],t)}};e.geo.area=function(t){return Kn=0,e.geo.stream(t,Gn),Kn};var Kn,Qn=new Rn,Gn={sphere:function(){Kn+=4*vt},point:C,lineStart:C,lineEnd:C,polygonStart:function(){Qn.reset(),Gn.lineStart=Yn},polygonEnd:function(){var e=2*Qn;Kn+=e<0?4*vt+e:e,Gn.lineStart=Gn.lineEnd=Gn.point=C}};e.geo.bounds=function(){function p(e,s){l.push(c=[t=e,r=e]),s<n&&(n=s),s>i&&(i=s)}function d(e,o){var u=Zn([e*wt,o*wt]);if(a){var f=tr(a,u),l=[f[1],-f[0],0],c=tr(l,f);ir(c),c=sr(c);var h=e-s,d=h>0?1:-1,v=c[0]*Et*d,g=m(h)>180;if(g^(d*s<v&&v<d*e)){var y=c[1]*Et;y>i&&(i=y)}else if(v=(v+360)%360-180,g^(d*s<v&&v<d*e)){var y=-c[1]*Et;y<n&&(n=y)}else o<n&&(n=o),o>i&&(i=o);g?e<s?E(t,e)>E(t,r)&&(r=e):E(e,r)>E(t,r)&&(t=e):r>=t?(e<t&&(t=e),e>r&&(r=e)):e>s?E(t,e)>E(t,r)&&(r=e):E(e,r)>E(t,r)&&(t=e)}else p(e,o);a=u,s=e}function v(){h.point=d}function g(){c[0]=t,c[1]=r,h.point=p,a=null}function y(e,t){if(a){var n=e-s;f+=m(n)>180?n+(n>0?360:-360):n}else o=e,u=t;Gn.point(e,t),d(e,t)}function b(){Gn.lineStart()}function w(){y(o,u),Gn.lineEnd(),m(f)>yt&&(t=-(r=180)),c[0]=t,c[1]=r,a=null}function E(e,t){return(t-=e)<0?t+360:t}function S(e,t){return e[0]-t[0]}function x(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e<t[0]||t[1]<e}var t,n,r,i,s,o,u,a,f,l,c,h={point:p,lineStart:v,lineEnd:g,polygonStart:function(){h.point=y,h.lineStart=b,h.lineEnd=w,f=0,Gn.polygonStart()},polygonEnd:function(){Gn.polygonEnd(),h.point=p,h.lineStart=v,h.lineEnd=g,Qn<0?(t=-(r=180),n=-(i=90)):f>yt?i=90:f<-yt&&(n=-90),c[0]=t,c[1]=r}};return function(s){i=r=-(t=n=Infinity),l=[],e.geo.stream(s,h);var o=l.length;if(o){l.sort(S);for(var u=1,a=l[0],f,p=[a];u<o;++u)f=l[u],x(f[0],a)||x(f[1],a)?(E(a[0],f[1])>E(a[0],a[1])&&(a[1]=f[1]),E(f[0],a[1])>E(a[0],a[1])&&(a[0]=f[0])):p.push(a=f);var d=-Infinity,v;for(var o=p.length-1,u=0,a=p[o],f;u<=o;a=f,++u)f=p[u],(v=E(a[1],f[0]))>d&&(d=v,t=f[0],r=a[1])}return l=c=null,t===Infinity||n===Infinity?[[NaN,NaN],[NaN,NaN]]:[[t,n],[r,i]]}}(),e.geo.centroid=function(t){ur=ar=fr=lr=cr=hr=pr=dr=vr=mr=gr=0,e.geo.stream(t,yr);var n=vr,r=mr,i=gr,s=n*n+r*r+i*i;if(s<bt){n=hr,r=pr,i=dr,ar<yt&&(n=fr,r=lr,i=cr),s=n*n+r*r+i*i;if(s<bt)return[NaN,NaN]}return[Math.atan2(r,n)*Et,Tt(i/Math.sqrt(s))*Et]};var ur,ar,fr,lr,cr,hr,pr,dr,vr,mr,gr,yr={sphere:C,point:br,lineStart:Er,lineEnd:Sr,polygonStart:function(){yr.lineStart=xr},polygonEnd:function(){yr.lineStart=Er}},Dr=Lr(Tr,Pr,Br,[-vt,-vt/2]),Ir=1e9;e.geo.clipExtent=function(){var e,t,n,r,i,s,o={stream:function(e){return i&&(i.valid=!1),i=s(e),i.valid=!0,i},extent:function(u){return arguments.length?(s=qr(e=+u[0][0],t=+u[0][1],n=+u[1][0],r=+u[1][1]),i&&(i.valid=!1,i=null),o):[[e,t],[n,r]]}};return o.extent([[0,0],[960,500]])},(e.geo.conicEqualArea=function(){return Ur(zr)}).raw=zr,e.geo.albers=function(){return e.geo.conicEqualArea().rotate([96,0]).center([-0.6,38.7]).parallels([29.5,45.5]).scale(1070)},e.geo.albersUsa=function(){function f(e){var t=e[0],n=e[1];return i=null,(o(t,n),i)||(u(t,n),i)||a(t,n),i}var t=e.geo.albers(),n=e.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),r=e.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),i,s={point:function(e,t){i=[e,t]}},o,u,a;return f.invert=function(e){var i=t.scale(),s=t.translate(),o=(e[0]-s[0])/i,u=(e[1]-s[1])/i;return(u>=.12&&u<.234&&o>=-0.425&&o<-0.214?n:u>=.166&&u<.234&&o>=-0.214&&o<-0.115?r:t).invert(e)},f.stream=function(e){var i=t.stream(e),s=n.stream(e),o=r.stream(e);return{point:function(e,t){i.point(e,t),s.point(e,t),o.point(e,t)},sphere:function(){i.sphere(),s.sphere(),o.sphere()},lineStart:function(){i.lineStart(),s.lineStart(),o.lineStart()},lineEnd:function(){i.lineEnd(),s.lineEnd(),o.lineEnd()},polygonStart:function(){i.polygonStart(),s.polygonStart(),o.polygonStart()},polygonEnd:function(){i.polygonEnd(),s.polygonEnd(),o.polygonEnd()}}},f.precision=function(e){return arguments.length?(t.precision(e),n.precision(e),r.precision(e),f):t.precision()},f.scale=function(e){return arguments.length?(t.scale(e),n.scale(e*.35),r.scale(e),f.translate(t.translate())):t.scale()},f.translate=function(e){if(!arguments.length)return t.translate();var i=t.scale(),l=+e[0],c=+e[1];return o=t.translate(e).clipExtent([[l-.455*i,c-.238*i],[l+.455*i,c+.238*i]]).stream(s).point,u=n.translate([l-.307*i,c+.201*i]).clipExtent([[l-.425*i+yt,c+.12*i+yt],[l-.214*i-yt,c+.234*i-yt]]).stream(s).point,a=r.translate([l-.205*i,c+.212*i]).clipExtent([[l-.214*i+yt,c+.166*i+yt],[l-.115*i-yt,c+.234*i-yt]]).stream(s).point,f},f.scale(1070)};var Wr,Xr,Vr={point:C,lineStart:C,lineEnd:C,polygonStart:function(){Xr=0,Vr.lineStart=$r},polygonEnd:function(){Vr.lineStart=Vr.lineEnd=Vr.point=C,Wr+=m(Xr/2)}},Jr,Kr,Qr,Gr,Yr={point:Zr,lineStart:C,lineEnd:C,polygonStart:C,polygonEnd:C},ni={point:ri,lineStart:ii,lineEnd:si,polygonStart:function(){ni.lineStart=oi},polygonEnd:function(){ni.point=ri,ni.lineStart=ii,ni.lineEnd=si}};e.geo.path=function(){function u(n){if(n){typeof t=="function"&&s.pointRadius(+t.apply(this,arguments));if(!o||!o.valid)o=i(s);e.geo.stream(n,o)}return s.result()}function a(){return o=null,u}var t=4.5,n,r,i,s,o;return u.area=function(t){return Wr=0,e.geo.stream(t,i(Vr)),Wr},u.centroid=function(t){return fr=lr=cr=hr=pr=dr=vr=mr=gr=0,e.geo.stream(t,i(ni)),gr?[vr/gr,mr/gr]:dr?[hr/dr,pr/dr]:cr?[fr/cr,lr/cr]:[NaN,NaN]},u.bounds=function(t){return Qr=Gr=-(Jr=Kr=Infinity),e.geo.stream(t,i(Yr)),[[Jr,Kr],[Qr,Gr]]},u.projection=function(e){return arguments.length?(i=(n=e)?e.stream||fi(e):mn,a()):n},u.context=function(e){return arguments.length?(s=(r=e)==null?new ei:new ui(e),typeof t!="function"&&s.pointRadius(t),a()):r},u.pointRadius=function(e){return arguments.length?(t=typeof e=="function"?e:(s.pointRadius(+e),+e),u):t},u.projection(e.geo.albersUsa()).context(null)},e.geo.transform=function(e){return{stream:function(t){var n=new li(t);for(var r in e)n[r]=e[r];return n}}},li.prototype={point:function(e,t){this.stream.point(e,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},e.geo.projection=hi,e.geo.projectionMutator=pi,(e.geo.equirectangular=function(){return hi(vi)}).raw=vi.invert=vi,e.geo.rotation=function(e){function t(t){return t=e(t[0]*wt,t[1]*wt),t[0]*=Et,t[1]*=Et,t}return e=gi(e[0]%360*wt,e[1]*wt,e.length>2?e[2]*wt:0),t.invert=function(t){return t=e.invert(t[0]*wt,t[1]*wt),t[0]*=Et,t[1]*=Et,t},t},mi.invert=vi,e.geo.circle=function(){function i(){var t=typeof e=="function"?e.apply(this,arguments):e,n=gi(-t[0]*wt,-t[1]*wt,0).invert,i=[];return r(null,null,1,{point:function(e,t){i.push(e=n(e,t)),e[0]*=Et,e[1]*=Et}}),{type:"Polygon",coordinates:[i]}}var e=[0,0],t,n=6,r;return i.origin=function(t){return arguments.length?(e=t,i):e},i.angle=function(e){return arguments.length?(r=Ei((t=+e)*wt,n*wt),i):t},i.precision=function(e){return arguments.length?(r=Ei(t*wt,(n=+e)*wt),i):n},i.angle(90)},e.geo.distance=function(e,t){var n=(t[0]-e[0])*wt,r=e[1]*wt,i=t[1]*wt,s=Math.sin(n),o=Math.cos(n),u=Math.sin(r),a=Math.cos(r),f=Math.sin(i),l=Math.cos(i),c;return Math.atan2(Math.sqrt((c=l*s)*c+(c=a*f-u*l*o)*c),u*f+a*l*o)},e.geo.graticule=function(){function b(){return{type:"MultiLineString",coordinates:w()}}function w(){return e.range(Math.ceil(i/c)*c,r,c).map(v).concat(e.range(Math.ceil(a/h)*h,u,h).map(g)).concat(e.range(Math.ceil(n/f)*f,t,f).filter(function(e){return m(e%c)>yt}).map(p)).concat(e.range(Math.ceil(o/l)*l,s,l).filter(function(e){return m(e%h)>yt}).map(d))}var t,n,r,i,s,o,u,a,f=10,l=f,c=90,h=360,p,d,v,g,y=2.5;return b.lines=function(){return w().map(function(e){return{type:"LineString",coordinates:e}})},b.outline=function(){return{type:"Polygon",coordinates:[v(i).concat(g(u).slice(1),v(r).reverse().slice(1),g(a).reverse().slice(1))]}},b.extent=function(e){return arguments.length?b.majorExtent(e).minorExtent(e):b.minorExtent()},b.majorExtent=function(e){return arguments.length?(i=+e[0][0],r=+e[1][0],a=+e[0][1],u=+e[1][1],i>r&&(e=i,i=r,r=e),a>u&&(e=a,a=u,u=e),b.precision(y)):[[i,a],[r,u]]},b.minorExtent=function(e){return arguments.length?(n=+e[0][0],t=+e[1][0],o=+e[0][1],s=+e[1][1],n>t&&(e=n,n=t,t=e),o>s&&(e=o,o=s,s=e),b.precision(y)):[[n,o],[t,s]]},b.step=function(e){return arguments.length?b.majorStep(e).minorStep(e):b.minorStep()},b.majorStep=function(e){return arguments.length?(c=+e[0],h=+e[1],b):[c,h]},b.minorStep=function(e){return arguments.length?(f=+e[0],l=+e[1],b):[f,l]},b.precision=function(e){return arguments.length?(y=+e,p=xi(o,s,90),d=Ti(n,t,y),v=xi(a,u,90),g=Ti(i,r,y),b):y},b.majorExtent([[-180,-90+yt],[180,90-yt]]).minorExtent([[-180,-80-yt],[180,80+yt]])},e.geo.greatArc=function(){function s(){return{type:"LineString",coordinates:[n||t.apply(this,arguments),i||r.apply(this,arguments)]}}var t=Ni,n,r=Ci,i;return s.distance=function(){return e.geo.distance(n||t.apply(this,arguments),i||r.apply(this,arguments))},s.source=function(e){return arguments.length?(t=e,n=typeof e=="function"?null:e,s):t},s.target=function(e){return arguments.length?(r=e,i=typeof e=="function"?null:e,s):r},s.precision=function(){return arguments.length?s:0},s},e.geo.interpolate=function(e,t){return ki(e[0]*wt,e[1]*wt,t[0]*wt,t[1]*wt)},e.geo.length=function(t){return Li=0,e.geo.stream(t,Ai),Li};var Li,Ai={sphere:C,point:C,lineStart:Oi,lineEnd:C,polygonStart:C,polygonEnd:C},_i=Mi(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(e.geo.azimuthalEqualArea=function(){return hi(_i)}).raw=_i;var Di=Mi(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},mn);(e.geo.azimuthalEquidistant=function(){return hi(Di)}).raw=Di,(e.geo.conicConformal=function(){return Ur(Pi)}).raw=Pi,(e.geo.conicEquidistant=function(){return Ur(Hi)}).raw=Hi;var Bi=Mi(function(e){return 1/e},Math.atan);(e.geo.gnomonic=function(){return hi(Bi)}).raw=Bi,ji.invert=function(e,t){return[e,2*Math.atan(Math.exp(t))-gt]},(e.geo.mercator=function(){return Fi(ji)}).raw=ji;var Ii=Mi(function(){return 1},Math.asin);(e.geo.orthographic=function(){return hi(Ii)}).raw=Ii;var qi=Mi(function(e){return 1/(1+e)},function(e){return 2*Math.atan(e)});(e.geo.stereographic=function(){return hi(qi)}).raw=qi,Ri.invert=function(e,t){return[Math.atan2(Nt(e),Math.cos(t)),Tt(Math.sin(t)/Ct(e))]},(e.geo.transverseMercator=function(){return Fi(Ri)}).raw=Ri,e.geom={},e.geom.hull=function(e){function r(e){if(e.length<3)return[];var r=vn(t),i=vn(n),s=e.length,o,u=s-1,a=[],f=[],l,c,h,p=0,d,v,m,g,y,b,w,E;if(r===Ui&&n===zi)o=e;else for(c=0,o=[];c<s;++c)o.push([+r.call(this,l=e[c],c),+i.call(this,l,c)]);for(c=1;c<s;++c)if(o[c][1]<o[p][1]||o[c][1]==o[p][1]&&o[c][0]<o[p][0])p=c;for(c=0;c<s;++c){if(c===p)continue;v=o[c][1]-o[p][1],d=o[c][0]-o[p][0],a.push({angle:Math.atan2(v,d),index:c})}a.sort(function(e,t){return e.angle-t.angle}),w=a[0].angle,b=a[0].index,y=0;for(c=1;c<u;++c){h=a[c].index;if(w==a[c].angle){d=o[b][0]-o[p][0],v=o[b][1]-o[p][1],m=o[h][0]-o[p][0],g=o[h][1]-o[p][1];if(d*d+v*v>=m*m+g*g){a[c].index=-1;continue}a[y].index=-1}w=a[c].angle,y=c,b=h}f.push(p);for(c=0,h=0;c<2;++h)a[h].index>-1&&(f.push(a[h].index),c++);E=f.length;for(;h<u;++h){if(a[h].index<0)continue;while(!Wi(f[E-2],f[E-1],a[h].index,o))--E;f[E++]=a[h].index}var S=[];for(c=E-1;c>=0;--c)S.push(e[f[c]]);return S}var t=Ui,n=zi;return arguments.length?r(e):(r.x=function(e){return arguments.length?(t=e,r):t},r.y=function(e){return arguments.length?(n=e,r):n},r)},e.geom.polygon=function(e){return D(e,Xi),e};var Xi=e.geom.polygon.prototype=[];Xi.area=function(){var e=-1,t=this.length,n,r=this[t-1],i=0;while(++e<t)n=r,r=this[e],i+=n[1]*r[0]-n[0]*r[1];return i*.5},Xi.centroid=function(e){var t=-1,n=this.length,r=0,i=0,s,o=this[n-1],u;arguments.length||(e=-1/(6*this.area()));while(++t<n)s=o,o=this[t],u=s[0]*o[1]-o[0]*s[1],r+=(s[0]+o[0])*u,i+=(s[1]+o[1])*u;return[r*e,i*e]},Xi.clip=function(e){var t,n=Ji(e),r=-1,i=this.length-Ji(this),s,o,u=this[i-1],a,f,l;while(++r<i){t=e.slice(),e.length=0,a=this[r],f=t[(o=t.length-n)-1],s=-1;while(++s<o)l=t[s],Vi(l,u,a)?(Vi(f,u,a)||e.push($i(f,l,u,a)),e.push(l)):Vi(f,u,a)&&e.push($i(f,l,u,a)),f=l;n&&e.push(e[0]),u=a}return e};var Ki,Qi,Gi,Yi=[],Zi,es,ts=[];fs.prototype.prepare=function(){var e=this.edges,t=e.length,n;while(t--)n=e[t].edge,(!n.b||!n.a)&&e.splice(t,1);return e.sort(cs),e.length},Es.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}},Ss.prototype={insert:function(e,t){var n,r,i;if(e){t.P=e,t.N=e.N,e.N&&(e.N.P=t),e.N=t;if(e.R){e=e.R;while(e.L)e=e.L;e.L=t}else e.R=t;n=e}else this._?(e=Cs(this._),t.P=null,t.N=e,e.P=e.L=t,n=e):(t.P=t.N=null,this._=t,n=null);t.L=t.R=null,t.U=n,t.C=!0,e=t;while(n&&n.C)r=n.U,n===r.L?(i=r.R,i&&i.C?(n.C=i.C=!1,r.C=!0,e=r):(e===n.R&&(Ts(this,n),e=n,n=e.U),n.C=!1,r.C=!0,Ns(this,r))):(i=r.L,i&&i.C?(n.C=i.C=!1,r.C=!0,e=r):(e===n.L&&(Ns(this,n),e=n,n=e.U),n.C=!1,r.C=!0,Ts(this,r))),n=e.U;this._.C=!1},remove:function(e){e.N&&(e.N.P=e.P),e.P&&(e.P.N=e.N),e.N=e.P=null;var t=e.U,n,r=e.L,i=e.R,s,o;r?i?s=Cs(i):s=r:s=i,t?t.L===e?t.L=s:t.R=s:this._=s,r&&i?(o=s.C,s.C=e.C,s.L=r,r.U=s,s!==i?(t=s.U,s.U=e.U,e=s.R,t.L=e,s.R=i,i.U=s):(s.U=t,t=s,e=s.R)):(o=e.C,e=s),e&&(e.U=t);if(o)return;if(e&&e.C){e.C=!1;return}do{if(e===this._)break;if(e===t.L){n=t.R,n.C&&(n.C=!1,t.C=!0,Ts(this,t),n=t.R);if(n.L&&n.L.C||n.R&&n.R.C){if(!n.R||!n.R.C)n.L.C=!1,n.C=!0,Ns(this,n),n=t.R;n.C=t.C,t.C=n.R.C=!1,Ts(this,t),e=this._;break}}else{n=t.L,n.C&&(n.C=!1,t.C=!0,Ns(this,t),n=t.L);if(n.L&&n.L.C||n.R&&n.R.C){if(!n.L||!n.L.C)n.R.C=!1,n.C=!0,Ts(this,n),n=t.L;n.C=t.C,t.C=n.L.C=!1,Ns(this,t),e=this._;break}}n.C=!0,e=t,t=t.U}while(!e.C);e&&(e.C=!1)}},e.geom.voronoi=function(e){function o(e){var t=new Array(e.length),n=s[0][0],r=s[0][1],i=s[1][0],o=s[1][1];return ks(u(e),s).cells.forEach(function(s,u){var a=s.edges,f=s.site,l=t[u]=a.length?a.map(function(e){var t=e.start();return[t.x,t.y]}):f.x>=n&&f.x<=i&&f.y>=r&&f.y<=o?[[n,o],[i,o],[i,r],[n,r]]:[];l.point=e[u]}),t}function u(e){return e.map(function(e,t){return{x:Math.round(r(e,t)/yt)*yt,y:Math.round(i(e,t)/yt)*yt,i:t}})}var t=Ui,n=zi,r=t,i=n,s=As;return e?o(e):(o.links=function(e){return ks(u(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},o.triangles=function(e){var t=[];return ks(u(e)).cells.forEach(function(n,r){var i=n.site,s=n.edges.sort(cs),o=-1,u=s.length,a,f,l=s[u-1].edge,c=l.l===i?l.r:l.l;while(++o<u)a=l,f=c,l=s[o].edge,c=l.l===i?l.r:l.l,r<f.i&&r<c.i&&Os(i,f,c)<0&&t.push([e[r],e[f.i],e[c.i]])}),t},o.x=function(e){return arguments.length?(r=vn(t=e),o):t},o.y=function(e){return arguments.length?(i=vn(n=e),o):n},o.clipExtent=function(e){return arguments.length?(s=e==null?As:e,o):s===As?null:s},o.size=function(e){return arguments.length?o.clipExtent(e&&[[0,0],e]):s===As?null:s&&s[1]},o)};var As=[[-1e6,-1e6],[1e6,1e6]];e.geom.delaunay=function(t){return e.geom.voronoi().triangles(t)},e.geom.quadtree=function(e,t,n,r,i){function a(e){function T(e,t,n,r,i,s,o,u){if(isNaN(n)||isNaN(r))return;if(e.leaf){var a=e.x,f=e.y;if(a!=null)if(m(a-n)+m(f-r)<.01)N(e,t,n,r,i,s,o,u);else{var l=e.point;e.x=e.y=e.point=null,N(e,l,a,f,i,s,o,u),N(e,t,n,r,i,s,o,u)}else e.x=n,e.y=r,e.point=t}else N(e,t,n,r,i,s,o,u)}function N(e,t,n,r,i,s,o,u){var a=(i+o)*.5,f=(s+u)*.5,l=n>=a,c=r>=f,h=(c<<1)+l;e.leaf=!1,e=e.nodes[h]||(e.nodes[h]=Ds()),l?i=a:o=a,c?s=f:u=f,T(e,t,n,r,i,s,o,u)}var a,f=vn(s),l=vn(o),c,h,p,d,v,g,y,b;if(t!=null)v=t,g=n,y=r,b=i;else{y=b=-(v=g=Infinity),c=[],h=[],d=e.length;if(u)for(p=0;p<d;++p)a=e[p],a.x<v&&(v=a.x),a.y<g&&(g=a.y),a.x>y&&(y=a.x),a.y>b&&(b=a.y),c.push(a.x),h.push(a.y);else for(p=0;p<d;++p){var w=+f(a=e[p],p),E=+l(a,p);w<v&&(v=w),E<g&&(g=E),w>y&&(y=w),E>b&&(b=E),c.push(w),h.push(E)}}var S=y-v,x=b-g;S>x?b=g+S:y=v+x;var C=Ds();C.add=function(e){T(C,e,+f(e,++p),+l(e,p),v,g,y,b)},C.visit=function(e){Ps(e,C,v,g,y,b)},p=-1;if(t==null){while(++p<d)T(C,e[p],c[p],h[p],v,g,y,b);--p}else e.forEach(C.add);return c=h=e=a=null,C}var s=Ui,o=zi,u;return(u=arguments.length)?(s=Ms,o=_s,u===3&&(i=n,r=t,n=t=0),a(e)):(a.x=function(e){return arguments.length?(s=e,a):s},a.y=function(e){return arguments.length?(o=e,a):o},a.extent=function(e){return arguments.length?(e==null?t=n=r=i=null:(t=+e[0][0],n=+e[0][1],r=+e[1][0],i=+e[1][1]),a):t==null?null:[[t,n],[r,i]]},a.size=function(e){return arguments.length?(e==null?t=n=r=i=null:(t=n=0,r=+e[0],i=+e[1]),a):t==null?null:[r-t,i-n]},a)},e.interpolateRgb=Hs,e.interpolateObject=Bs,e.interpolateNumber=js,e.interpolateString=Fs;var Is=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;e.interpolate=qs,e.interpolators=[function(e,t){var n=typeof t;return(n==="string"?dn.has(t)||/^(#|rgb\(|hsl\()/.test(t)?Hs:Fs:t instanceof Ht?Hs:n==="object"?Array.isArray(t)?Rs:Bs:js)(e,t)}],e.interpolateArray=Rs;var Us=function(){return mn},zs=e.map({linear:Us,poly:Gs,quad:function(){return Js},cubic:function(){return Ks},sin:function(){return Ys},exp:function(){return Zs},circle:function(){return eo},elastic:to,back:no,bounce:function(){return ro}}),Ws=e.map({"in":mn,out:Vs,"in-out":$s,"out-in":function(e){return $s(Vs(e))}});e.ease=function(e){var n=e.indexOf("-"),r=n>=0?e.substring(0,n):e,i=n>=0?e.substring(n+1):"in";return r=zs.get(r)||Us,i=Ws.get(i)||mn,Xs(i(r.apply(null,t.call(arguments,1))))},e.interpolateHcl=io,e.interpolateHsl=so,e.interpolateLab=oo,e.interpolateRound=uo,e.transform=function(t){var n=r.createElementNS(e.ns.prefix.svg,"g");return(e.transform=function(e){if(e!=null){n.setAttribute("transform",e);var t=n.transform.baseVal.consolidate()}return new ao(t?t.matrix:ho)})(t)},ao.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ho={a:1,b:0,c:0,d:1,e:0,f:0};e.interpolateTransform=po,e.layout={},e.layout.bundle=function(){return function(e){var t=[],n=-1,r=e.length;while(++n<r)t.push(go(e[n]));return t}},e.layout.chord=function(){function l(){var t={},l=[],h=e.range(s),p=[],d,v,m,g,y;n=[],r=[],d=0,g=-1;while(++g<s){v=0,y=-1;while(++y<s)v+=i[g][y];l.push(v),p.push(e.range(s)),d+=v}u&&h.sort(function(e,t){return u(l[e],l[t])}),a&&p.forEach(function(e,t){e.sort(function(e,n){return a(i[t][e],i[t][n])})}),d=(mt-o*s)/d,v=0,g=-1;while(++g<s){m=v,y=-1;while(++y<s){var b=h[g],w=p[b][y],E=i[b][w],S=v,x=v+=E*d;t[b+"-"+w]={index:b,subindex:w,startAngle:S,endAngle:x,value:E}}r[b]={index:b,startAngle:m,endAngle:v,value:(v-m)/d},v+=o}g=-1;while(++g<s){y=g-1;while(++y<s){var T=t[g+"-"+y],N=t[y+"-"+g];(T.value||N.value)&&n.push(T.value<N.value?{source:N,target:T}:{source:T,target:N})}}f&&c()}function c(){n.sort(function(e,t){return f((e.source.value+e.target.value)/2,(t.source.value+t.target.value)/2)})}var t={},n,r,i,s,o=0,u,a,f;return t.matrix=function(e){return arguments.length?(s=(i=e)&&i.length,n=r=null,t):i},t.padding=function(e){return arguments.length?(o=e,n=r=null,t):o},t.sortGroups=function(e){return arguments.length?(u=e,n=r=null,t):u},t.sortSubgroups=function(e){return arguments.length?(a=e,n=null,t):a},t.sortChords=function(e){return arguments.length?(f=e,n&&c(),t):f},t.chords=function(){return n||l(),n},t.groups=function(){return r||l(),r},t},e.layout.force=function(){function g(e){return function(t,n,r,i){if(t.point!==e){var s=t.cx-e.x,o=t.cy-e.y,u=1/Math.sqrt(s*s+o*o);if((i-n)*u<c){var a=t.charge*u*u;return e.px-=s*a,e.py-=o*a,!0}if(t.point&&isFinite(u)){var a=t.pointCharge*u*u;e.px-=s*a,e.py-=o*a}}return!t.charge}}function y(n){n.px=e.event.x,n.py=e.event.y,t.resume()}var t={},n=e.dispatch("start","tick","end"),r=[1,1],i,s,o=.9,u=No,a=Co,f=-30,l=.1,c=.8,h=[],p=[],d,v,m;return t.tick=function(){if((s*=.99)<.005)return n.end({type:"end",alpha:s=0}),!0;var t=h.length,i=p.length,u,a,c,y,b,w,E,S,x;for(a=0;a<i;++a){c=p[a],y=c.source,b=c.target,S=b.x-y.x,x=b.y-y.y;if(w=S*S+x*x)w=s*v[a]*((w=Math.sqrt(w))-d[a])/w,S*=w,x*=w,b.x-=S*(E=y.weight/(b.weight+y.weight)),b.y-=x*E,y.x+=S*(E=1-E),y.y+=x*E}if(E=s*l){S=r[0]/2,x=r[1]/2,a=-1;if(E)while(++a<t)c=h[a],c.x+=(S-c.x)*E,c.y+=(x-c.y)*E}if(f){To(u=e.geom.quadtree(h),s,m),a=-1;while(++a<t)(c=h[a]).fixed||u.visit(g(c))}a=-1;while(++a<t)c=h[a],c.fixed?(c.x=c.px,c.y=c.py):(c.x-=(c.px-(c.px=c.x))*o,c.y-=(c.py-(c.py=c.y))*o);n.tick({type:"tick",alpha:s})},t.nodes=function(e){return arguments.length?(h=e,t):h},t.links=function(e){return arguments.length?(p=e,t):p},t.size=function(e){return arguments.length?(r=e,t):r},t.linkDistance=function(e){return arguments.length?(u=typeof e=="function"?e:+e,t):u},t.distance=t.linkDistance,t.linkStrength=function(e){return arguments.length?(a=typeof e=="function"?e:+e,t):a},t.friction=function(e){return arguments.length?(o=+e,t):o},t.charge=function(e){return arguments.length?(f=typeof e=="function"?e:+e,t):f},t.gravity=function(e){return arguments.length?(l=+e,t):l},t.theta=function(e){return arguments.length?(c=+e,t):c},t.alpha=function(r){return arguments.length?(r=+r,s?r>0?s=r:s=0:r>0&&(n.start({type:"start",alpha:s=r}),e.timer(t.tick)),t):s},t.start=function(){function g(t,r){if(!l){l=new Array(n);for(o=0;o<n;++o)l[o]=[];for(o=0;o<u;++o){var i=p[o];l[i.source.index].push(i.target),l[i.target.index].push(i.source)}}var s=l[e],o=-1,u=s.length,a;while(++o<u)if(!isNaN(a=s[o][t]))return a;return Math.random()*r}var e,n=h.length,i=p.length,s=r[0],o=r[1],l,c;for(e=0;e<n;++e)(c=h[e]).index=e,c.weight=0;for(e=0;e<i;++e)c=p[e],typeof c.source=="number"&&(c.source=h[c.source]),typeof c.target=="number"&&(c.target=h[c.target]),++c.source.weight,++c.target.weight;for(e=0;e<n;++e)c=h[e],isNaN(c.x)&&(c.x=g("x",s)),isNaN(c.y)&&(c.y=g("y",o)),isNaN(c.px)&&(c.px=c.x),isNaN(c.py)&&(c.py=c.y);d=[];if(typeof u=="function")for(e=0;e<i;++e)d[e]=+u.call(this,p[e],e);else for(e=0;e<i;++e)d[e]=u;v=[];if(typeof a=="function")for(e=0;e<i;++e)v[e]=+a.call(this,p[e],e);else for(e=0;e<i;++e)v[e]=a;m=[];if(typeof f=="function")for(e=0;e<n;++e)m[e]=+f.call(this,h[e],e);else for(e=0;e<n;++e)m[e]=f;return t.resume()},t.resume=function(){return t.alpha(.1)},t.stop=function(){return t.alpha(0)},t.drag=function(){i||(i=e.behavior.drag().origin(mn).on("dragstart.force",wo).on("drag.force",y).on("dragend.force",Eo));if(!arguments.length)return i;this.on("mouseover.force",So).on("mouseout.force",xo).call(i)},e.rebind(t,n,"on")};var No=20,Co=1;e.layout.hierarchy=function(){function r(i,o,u){var a=t.call(s,i,o);i.depth=o,u.push(i);if(a&&(l=a.length)){var f=-1,l,c=i.children=new Array(l),h=0,p=o+1,d;while(++f<l)d=c[f]=r(a[f],p,u),d.parent=i,h+=d.value;e&&c.sort(e),n&&(i.value=h)}else delete i.children,n&&(i.value=+n.call(s,i,o)||0);return i}function i(e,t){var r=e.children,o=0;if(r&&(a=r.length)){var u=-1,a,f=t+1;while(++u<a)o+=i(r[u],f)}else n&&(o=+n.call(s,e,t)||0);return n&&(e.value=o),o}function s(e){var t=[];return r(e,0,t),t}var e=Oo,t=Lo,n=Ao;return s.sort=function(t){return arguments.length?(e=t,s):e},s.children=function(e){return arguments.length?(t=e,s):t},s.value=function(e){return arguments.length?(n=e,s):n},s.revalue=function(e){return i(e,0),e},s},e.layout.partition=function(){function r(e,t,n,i){var s=e.children;e.x=t,e.y=e.depth*i,e.dx=n,e.dy=i;if(s&&(u=s.length)){var o=-1,u,a,f;n=e.value?n/e.value:0;while(++o<u)r(a=s[o],t,f=a.value*n,i),t+=f}}function i(e){var t=e.children,n=0;if(t&&(s=t.length)){var r=-1,s;while(++r<s)n=Math.max(n,i(t[r]))}return 1+n}function s(e,s){var o=t.call(this,e,s);return r(o[0],0,n[0],n[1]/i(o[0])),o}var t=e.layout.hierarchy(),n=[1,1];return s.size=function(e){return arguments.length?(n=e,s):n},ko(s,t)},e.layout.pie=function(){function s(o){var u=o.map(function(e,n){return+t.call(s,e,n)}),a=+(typeof r=="function"?r.apply(this,arguments):r),f=((typeof i=="function"?i.apply(this,arguments):i)-a)/e.sum(u),l=e.range(o.length);n!=null&&l.sort(n===_o?function(e,t){return u[t]-u[e]}:function(e,t){return n(o[e],o[t])});var c=[];return l.forEach(function(e){var t;c[e]={data:o[e],value:t=u[e],startAngle:a,endAngle:a+=t*f}}),c}var t=Number,n=_o,r=0,i=mt;return s.value=function(e){return arguments.length?(t=e,s):t},s.sort=function(e){return arguments.length?(n=e,s):n},s.startAngle=function(e){return arguments.length?(r=e,s):r},s.endAngle=function(e){return arguments.length?(i=e,s):i},s};var _o={};e.layout.stack=function(){function u(a,f){var l=a.map(function(e,n){return t.call(u,e,n)}),c=l.map(function(e){return e.map(function(e,t){return[s.call(u,e,t),o.call(u,e,t)]})}),h=n.call(u,c,f);l=e.permute(l,h),c=e.permute(c,h);var p=r.call(u,c,f),d=l.length,v=l[0].length,m,g,y;for(g=0;g<v;++g){i.call(u,l[0][g],y=p[g],c[0][g][1]);for(m=1;m<d;++m)i.call(u,l[m][g],y+=c[m-1][g][1],c[m][g][1])}return a}var t=mn,n=Fo,r=Io,i=Ho,s=Do,o=Po;return u.values=function(e){return arguments.length?(t=e,u):t},u.order=function(e){return arguments.length?(n=typeof e=="function"?e:Bo.get(e)||Fo,u):n},u.offset=function(e){return arguments.length?(r=typeof e=="function"?e:jo.get(e)||Io,u):r},u.x=function(e){return arguments.length?(s=e,u):s},u.y=function(e){return arguments.length?(o=e,u):o},u.out=function(e){return arguments.length?(i=e,u):i},u};var Bo=e.map({"inside-out":function(t){var n=t.length,r,i,s=t.map(qo),o=t.map(Ro),u=e.range(n).sort(function(e,t){return s[e]-s[t]}),a=0,f=0,l=[],c=[];for(r=0;r<n;++r)i=u[r],a<f?(a+=o[i],l.push(i)):(f+=o[i],c.push(i));return c.reverse().concat(l)},reverse:function(t){return e.range(t.length).reverse()},"default":Fo}),jo=e.map({silhouette:function(e){var t=e.length,n=e[0].length,r=[],i=0,s,o,u,a=[];for(o=0;o<n;++o){for(s=0,u=0;s<t;s++)u+=e[s][o][1];u>i&&(i=u),r.push(u)}for(o=0;o<n;++o)a[o]=(i-r[o])/2;return a},wiggle:function(e){var t=e.length,n=e[0],r=n.length,i,s,o,u,a,f,l,c,h,p=[];p[0]=c=h=0;for(s=1;s<r;++s){for(i=0,u=0;i<t;++i)u+=e[i][s][1];for(i=0,a=0,l=n[s][0]-n[s-1][0];i<t;++i){for(o=0,f=(e[i][s][1]-e[i][s-1][1])/(2*l);o<i;++o)f+=(e[o][s][1]-e[o][s-1][1])/l;a+=f*e[i][s][1]}p[s]=c-=u?a/u*l:0,c<h&&(h=c)}for(s=0;s<r;++s)p[s]-=h;return p},expand:function(e){var t=e.length,n=e[0].length,r=1/t,i,s,o,u=[];for(s=0;s<n;++s){for(i=0,o=0;i<t;i++)o+=e[i][s][1];if(o)for(i=0;i<t;i++)e[i][s][1]/=o;else for(i=0;i<t;i++)e[i][s][1]=r}for(s=0;s<n;++s)u[s]=0;return u},zero:Io});e.layout.histogram=function(){function s(s,o){var u=[],a=s.map(n,this),f=r.call(this,a,o),l=i.call(this,f,a,o),c,o=-1,h=a.length,p=l.length-1,d=t?1:1/h,v;while(++o<p)c=u[o]=[],c.dx=l[o+1]-(c.x=l[o]),c.y=0;if(p>0){o=-1;while(++o<h)v=a[o],v>=f[0]&&v<=f[1]&&(c=u[e.bisect(l,v,1,p)-1],c.y+=d,c.push(s[o]))}return u}var t=!0,n=Number,r=Xo,i=zo;return s.value=function(e){return arguments.length?(n=e,s):n},s.range=function(e){return arguments.length?(r=vn(e),s):r},s.bins=function(e){return arguments.length?(i=typeof e=="number"?function(t){return Wo(t,e)}:vn(e),s):i},s.frequency=function(e){return arguments.length?(t=!!e,s):t},s},e.layout.tree=function(){function s(e,s){function a(e,t){var r=e.children,i=e._tree;if(r&&(s=r.length)){var s,o=r[0],u,f=o,c,h=-1;while(++h<s)c=r[h],a(c,u),f=l(c,u,f),u=c;eu(e);var p=.5*(o._tree.prelim+c._tree.prelim);t?(i.prelim=t._tree.prelim+n(e,t),i.mod=i.prelim-p):i.prelim=p}else t&&(i.prelim=t._tree.prelim+n(e,t))}function f(e,t){e.x=e._tree.prelim+t;var n=e.children;if(n&&(i=n.length)){var r=-1,i;t+=e._tree.mod;while(++r<i)f(n[r],t)}}function l(e,t,r){if(t){var i=e,s=e,o=t,u=e.parent.children[0],a=i._tree.mod,f=s._tree.mod,l=o._tree.mod,c=u._tree.mod,h;while(o=Jo(o),i=$o(i),o&&i)u=$o(u),s=Jo(s),s._tree.ancestor=e,h=o._tree.prelim+l-i._tree.prelim-a+n(o,i),h>0&&(tu(nu(o,e,r),e,h),a+=h,f+=h),l+=o._tree.mod,a+=i._tree.mod,c+=u._tree.mod,f+=s._tree.mod;o&&!Jo(s)&&(s._tree.thread=o,s._tree.mod+=l-f),i&&!$o(u)&&(u._tree.thread=i,u._tree.mod+=a-c,r=e)}return r}var o=t.call(this,e,s),u=o[0];Zo(u,function(e,t){e._tree={ancestor:e,prelim:0,mod:0,change:0,shift:0,number:t?t._tree.number+1:0}}),a(u),f(u,-u._tree.prelim);var c=Ko(u,Go),h=Ko(u,Qo),p=Ko(u,Yo),d=c.x-n(c,h)/2,v=h.x+n(h,c)/2,m=p.depth||1;return Zo(u,i?function(e){e.x*=r[0],e.y=e.depth*r[1],delete e._tree}:function(e){e.x=(e.x-d)/(v-d)*r[0],e.y=e.depth/m*r[1],delete e._tree}),o}var t=e.layout.hierarchy().sort(null).value(null),n=Vo,r=[1,1],i=!1;return s.separation=function(e){return arguments.length?(n=e,s):n},s.size=function(e){return arguments.length?(i=(r=e)==null,s):i?null:r},s.nodeSize=function(e){return arguments.length?(i=(r=e)!=null,s):i?r:null},ko(s,t)},e.layout.pack=function(){function s(e,s){var o=t.call(this,e,s),u=o[0],a=r[0],f=r[1],l=i==null?Math.sqrt:typeof i=="function"?i:function(){return i};u.x=u.y=0,Zo(u,function(e){e.r=+l(e.value)}),Zo(u,uu);if(n){var c=n*(i?1:Math.max(2*u.r/a,2*u.r/f))/2;Zo(u,function(e){e.r+=c}),Zo(u,uu),Zo(u,function(e){e.r-=c})}return lu(u,a/2,f/2,i?1:1/Math.max(2*u.r/a,2*u.r/f)),o}var t=e.layout.hierarchy().sort(ru),n=0,r=[1,1],i;return s.size=function(e){return arguments.length?(r=e,s):r},s.radius=function(e){return arguments.length?(i=e==null||typeof e=="function"?e:+e,s):i},s.padding=function(e){return arguments.length?(n=+e,s):n},ko(s,t)},e.layout.cluster=function(){function s(e,s){var o=t.call(this,e,s),u=o[0],a,f=0;Zo(u,function(e){var t=e.children;t&&t.length?(e.x=pu(t),e.y=hu(t)):(e.x=a?f+=n(e,a):0,e.y=0,a=e)});var l=du(u),c=vu(u),h=l.x-n(l,c)/2,p=c.x+n(c,l)/2;return Zo(u,i?function(e){e.x=(e.x-u.x)*r[0],e.y=(u.y-e.y)*r[1]}:function(e){e.x=(e.x-h)/(p-h)*r[0],e.y=(1-(u.y?e.y/u.y:1))*r[1]}),o}var t=e.layout.hierarchy().sort(null).value(null),n=Vo,r=[1,1],i=!1;return s.separation=function(e){return arguments.length?(n=e,s):n},s.size=function(e){return arguments.length?(i=(r=e)==null,s):i?null:r},s.nodeSize=function(e){return arguments.length?(i=(r=e)!=null,s):i?r:null},ko(s,t)},e.layout.treemap=function(){function l(e,t){var n=-1,r=e.length,i,s;while(++n<r)s=(i=e[n]).value*(t<0?0:t),i.area=isNaN(s)||s<=0?0:s}function c(e){var t=e.children;if(t&&t.length){var n=s(e),r=[],i=t.slice(),o,u=Infinity,f,h=a==="slice"?n.dx:a==="dice"?n.dy:a==="slice-dice"?e.depth&1?n.dy:n.dx:Math.min(n.dx,n.dy),v;l(i,n.dx*n.dy/e.value),r.area=0;while((v=i.length)>0)r.push(o=i[v-1]),r.area+=o.area,a!=="squarify"||(f=p(r,h))<=u?(i.pop(),u=f):(r.area-=r.pop().area,d(r,h,n,!1),h=Math.min(n.dx,n.dy),r.length=r.area=0,u=Infinity);r.length&&(d(r,h,n,!0),r.length=r.area=0),t.forEach(c)}}function h(e){var t=e.children;if(t&&t.length){var n=s(e),r=t.slice(),i,o=[];l(r,n.dx*n.dy/e.value),o.area=0;while(i=r.pop())o.push(i),o.area+=i.area,i.z!=null&&(d(o,i.z?n.dx:n.dy,n,!r.length),o.length=o.area=0);t.forEach(h)}}function p(e,t){var n=e.area,r,i=0,s=Infinity,o=-1,u=e.length;while(++o<u){if(!(r=e[o].area))continue;r<s&&(s=r),r>i&&(i=r)}return n*=n,t*=t,n?Math.max(t*i*f/n,n/(t*s*f)):Infinity}function d(e,t,r,i){var s=-1,o=e.length,u=r.x,a=r.y,f=t?n(e.area/t):0,l;if(t==r.dx){if(i||f>r.dy)f=r.dy;while(++s<o)l=e[s],l.x=u,l.y=a,l.dy=f,u+=l.dx=Math.min(r.x+r.dx-u,f?n(l.area/f):0);l.z=!0,l.dx+=r.x+r.dx-u,r.y+=f,r.dy-=f}else{if(i||f>r.dx)f=r.dx;while(++s<o)l=e[s],l.x=u,l.y=a,l.dx=f,a+=l.dy=Math.min(r.y+r.dy-a,f?n(l.area/f):0);l.z=!1,l.dy+=r.y+r.dy-a,r.x+=f,r.dx-=f}}function v(e){var n=u||t(e),i=n[0];return i.x=0,i.y=0,i.dx=r[0],i.dy=r[1],u&&t.revalue(i),l([i],i.dx*i.dy/i.value),(u?h:c)(i),o&&(u=n),n}var t=e.layout.hierarchy(),n=Math.round,r=[1,1],i=null,s=mu,o=!1,u,a="squarify",f=.5*(1+Math.sqrt(5));return v.size=function(e){return arguments.length?(r=e,v):r},v.padding=function(e){function t(t){var n=e.call(v,t,t.depth);return n==null?mu(t):gu(t,typeof n=="number"?[n,n,n,n]:n)}function n(t){return gu(t,e)}if(!arguments.length)return i;var r;return s=(i=e)==null?mu:(r=typeof e)==="function"?t:r==="number"?(e=[e,e,e,e],n):n,v},v.round=function(e){return arguments.length?(n=e?Math.round:Number,v):n!=Number},v.sticky=function(e){return arguments.length?(o=e,u=null,v):o},v.ratio=function(e){return arguments.length?(f=e,v):f},v.mode=function(e){return arguments.length?(a=e+"",v):a},ko(v,t)},e.random={normal:function(e,t){var n=arguments.length;return n<2&&(t=1),n<1&&(e=0),function(){var n,r,i;do n=Math.random()*2-1,r=Math.random()*2-1,i=n*n+r*r;while(!i||i>1);return e+t*n*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=e.random.normal.apply(e,arguments);return function(){return Math.exp(t())}},irwinHall:function(e){return function(){for(var t=0,n=0;n<e;n++)t+=Math.random();return t/e}}},e.scale={};var xu={floor:mn,ceil:mn};e.scale.linear=function(){return Nu([0,1],[0,1],qs,!1)};var Mu={s:1,g:1,p:1,r:1,e:1};e.scale.log=function(){return Pu(e.scale.linear().domain([0,1]),10,!0,[1,10])};var Hu=e.format(".0e"),Bu={floor:function(e){return-Math.ceil(-e)},ceil:function(e){return-Math.floor(-e)}};e.scale.pow=function(){return ju(e.scale.linear(),1,[0,1])},e.scale.sqrt=function(){return e.scale.pow().exponent(.5)},e.scale.ordinal=function(){return Iu([],{t:"range",a:[[]]})},e.scale.category10=function(){return e.scale.ordinal().range(qu)},e.scale.category20=function(){return e.scale.ordinal().range(Ru)},e.scale.category20b=function(){return e.scale.ordinal().range(Uu)},e.scale.category20c=function(){return e.scale.ordinal().range(zu)};var qu=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(rn),Ru=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(rn),Uu=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(rn),zu=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(rn);e.scale.quantile=function(){return Wu([],[])},e.scale.quantize=function(){return Xu(0,1,[0,1])},e.scale.threshold=function(){return Vu([.5],[0,1])},e.scale.identity=function(){return $u([0,1])},e.svg={},e.svg.arc=function(){function i(){var i=e.apply(this,arguments),s=t.apply(this,arguments),o=n.apply(this,arguments)+Ju,u=r.apply(this,arguments)+Ju,a=(u<o&&(a=o,o=u,u=a),u-o),f=a<vt?"0":"1",l=Math.cos(o),c=Math.sin(o),h=Math.cos(u),p=Math.sin(u);return a>=Ku?i?"M0,"+s+"A"+s+","+s+" 0 1,1 0,"+ -s+"A"+s+","+s+" 0 1,1 0,"+s+"M0,"+i+"A"+i+","+i+" 0 1,0 0,"+ -i+"A"+i+","+i+" 0 1,0 0,"+i+"Z":"M0,"+s+"A"+s+","+s+" 0 1,1 0,"+ -s+"A"+s+","+s+" 0 1,1 0,"+s+"Z":i?"M"+s*l+","+s*c+"A"+s+","+s+" 0 "+f+",1 "+s*h+","+s*p+"L"+i*h+","+i*p+"A"+i+","+i+" 0 "+f+",0 "+i*l+","+i*c+"Z":"M"+s*l+","+s*c+"A"+s+","+s+" 0 "+f+",1 "+s*h+","+s*p+"L0,0"+"Z"}var e=Qu,t=Gu,n=Yu,r=Zu;return i.innerRadius=function(t){return arguments.length?(e=vn(t),i):e},i.outerRadius=function(e){return arguments.length?(t=vn(e),i):t},i.startAngle=function(e){return arguments.length?(n=vn(e),i):n},i.endAngle=function(e){return arguments.length?(r=vn(e),i):r},i.centroid=function(){var i=(e.apply(this,arguments)+t.apply(this,arguments))/2,s=(n.apply(this,arguments)+r.apply(this,arguments))/2+Ju;return[Math.cos(s)*i,Math.sin(s)*i]},i};var Ju=-gt,Ku=mt-yt;e.svg.line=function(){return ea(mn)};var ta=e.map({linear:na,"linear-closed":ra,step:ia,"step-before":sa,"step-after":oa,basis:ha,"basis-open":pa,"basis-closed":da,bundle:va,cardinal:fa,"cardinal-open":ua,"cardinal-closed":aa,monotone:Ta});ta.forEach(function(e,t){t.key=e,t.closed=/-closed$/.test(e)});var ga=[0,2/3,1/3,0],ya=[0,1/3,2/3,0],ba=[0,1/6,2/3,1/6];e.svg.line.radial=function(){var e=ea(Na);return e.radius=e.x,delete e.x,e.angle=e.y,delete e.y,e},sa.reverse=oa,oa.reverse=sa,e.svg.area=function(){return Ca(mn)},e.svg.area.radial=function(){var e=Ca(Na);return e.radius=e.x,delete e.x,e.innerRadius=e.x0,delete e.x0,e.outerRadius=e.x1,delete e.x1,e.angle=e.y,delete e.y,e.startAngle=e.y0,delete e.y0,e.endAngle=e.y1,delete e.y1,e},e.svg.chord=function(){function s(n,r){var i=o(this,e,n,r),s=o(this,t,n,r);return"M"+i.p0+a(i.r,i.p1,i.a1-i.a0)+(u(i,s)?f(i.r,i.p1,i.r,i.p0):f(i.r,i.p1,s.r,s.p0)+a(s.r,s.p1,s.a1-s.a0)+f(s.r,s.p1,i.r,i.p0))+"Z"}function o(e,t,s,o){var u=t.call(e,s,o),a=n.call(e,u,o),f=r.call(e,u,o)+Ju,l=i.call(e,u,o)+Ju;return{r:a,a0:f,a1:l,p0:[a*Math.cos(f),a*Math.sin(f)],p1:[a*Math.cos(l),a*Math.sin(l)]}}function u(e,t){return e.a0==t.a0&&e.a1==t.a1}function a(e,t,n){return"A"+e+","+e+" 0 "+ +(n>vt)+",1 "+t}function f(e,t,n,r){return"Q 0,0 "+r}var e=Ni,t=Ci,n=ka,r=Yu,i=Zu;return s.radius=function(e){return arguments.length?(n=vn(e),s):n},s.source=function(t){return arguments.length?(e=vn(t),s):e},s.target=function(e){return arguments.length?(t=vn(e),s):t},s.startAngle=function(e){return arguments.length?(r=vn(e),s):r},s.endAngle=function(e){return arguments.length?(i=vn(e),s):i},s},e.svg.diagonal=function(){function r(r,i){var s=e.call(this,r,i),o=t.call(this,r,i),u=(s.y+o.y)/2,a=[s,{x:s.x,y:u},{x:o.x,y:u},o];return a=a.map(n),"M"+a[0]+"C"+a[1]+" "+a[2]+" "+a[3]}var e=Ni,t=Ci,n=La;return r.source=function(t){return arguments.length?(e=vn(t),r):e},r.target=function(e){return arguments.length?(t=vn(e),r):t},r.projection=function(e){return arguments.length?(n=e,r):n},r},e.svg.diagonal.radial=function(){var t=e.svg.diagonal(),n=La,r=t.projection;return t.projection=function(e){return arguments.length?r(Aa(n=e)):n},t},e.svg.symbol=function(){function n(n,r){return(Da.get(e.call(this,n,r))||_a)(t.call(this,n,r))}var e=Ma,t=Oa;return n.type=function(t){return arguments.length?(e=vn(t),n):e},n.size=function(e){return arguments.length?(t=vn(e),n):t},n};var Da=e.map({circle:_a,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+ -3*t+","+ -t+"H"+ -t+"V"+ -3*t+"H"+t+"V"+ -t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+ -t+"V"+t+"H"+ -3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*Ha)),n=t*Ha;return"M0,"+ -t+"L"+n+",0"+" 0,"+t+" "+ -n+",0"+"Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+ -t+","+ -t+"L"+t+","+ -t+" "+t+","+t+" "+ -t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/Pa),n=t*Pa/2;return"M0,"+n+"L"+t+","+ -n+" "+ -t+","+ -n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/Pa),n=t*Pa/2;return"M0,"+ -n+"L"+t+","+n+" "+ -t+","+n+"Z"}});e.svg.symbolTypes=Da.keys();var Pa=Math.sqrt(3),Ha=Math.tan(30*wt),ja=[],Fa=0,Ia,qa;ja.call=I.call,ja.empty=I.empty,ja.node=I.node,ja.size=I.size,e.transition=function(e){return arguments.length?Ia?e.transition():e:st.transition()},e.transition.prototype=ja,ja.select=function(e){var t=this.id,n=[],r,i,s;e=q(e);for(var o=-1,u=this.length;++o<u;){n.push(r=[]);for(var a=this[o],f=-1,l=a.length;++f<l;)(s=a[f])&&(i=e.call(s,s.__data__,f,o))?("__data__"in s&&(i.__data__=s.__data__),za(i,f,t,s.__transition__[t]),r.push(i)):r.push(null)}return Ba(n,t)},ja.selectAll=function(e){var t=this.id,n=[],r,i,s,o,u;e=R(e);for(var a=-1,f=this.length;++a<f;)for(var l=this[a],c=-1,h=l.length;++c<h;)if(s=l[c]){u=s.__transition__[t],i=e.call(s,s.__data__,c,a),n.push(r=[]);for(var p=-1,d=i.length;++p<d;)(o=i[p])&&za(o,p,t,u),r.push(o)}return Ba(n,t)},ja.filter=function(e){var t=[],n,r,i;typeof e!="function"&&(e=Y(e));for(var s=0,o=this.length;s<o;s++){t.push(n=[]);for(var r=this[s],u=0,a=r.length;u<a;u++)(i=r[u])&&e.call(i,i.__data__,u,s)&&n.push(i)}return Ba(t,this.id)},ja.tween=function(e,t){var n=this.id;return arguments.length<2?this.node().__transition__[n].tween.get(e):et(this,t==null?function(t){t.__transition__[n].tween.remove(e)}:function(r){r.__transition__[n].tween.set(e,t)})},ja.attr=function(t,n){function s(){this.removeAttribute(i)}function o(){this.removeAttributeNS(i.space,i.local)}function u(e){return e==null?s:(e+="",function(){var t=this.getAttribute(i),n;return t!==e&&(n=r(t,e),function(e){this.setAttribute(i,n(e))})})}function a(e){return e==null?o:(e+="",function(){var t=this.getAttributeNS(i.space,i.local),n;return t!==e&&(n=r(t,e),function(e){this.setAttributeNS(i.space,i.local,n(e))})})}if(arguments.length<2){for(n in t)this.attr(n,t[n]);return this}var r=t=="transform"?po:qs,i=e.ns.qualify(t);return Ra(this,"attr."+t,n,i.local?a:u)},ja.attrTween=function(t,n){function i(e,t){var i=n.call(this,e,t,this.getAttribute(r));return i&&function(e){this.setAttribute(r,i(e))}}function s(e,t){var i=n.call(this,e,t,this.getAttributeNS(r.space,r.local));return i&&function(e){this.setAttributeNS(r.space,r.local,i(e))}}var r=e.ns.qualify(t);return this.tween("attr."+t,r.local?s:i)},ja.style=function(e,t,n){function i(){this.style.removeProperty(e)}function o(t){return t==null?i:(t+="",function(){var r=s.getComputedStyle(this,null).getPropertyValue(e),i;return r!==t&&(i=qs(r,t),function(t){this.style.setProperty(e,i(t),n)})})}var r=arguments.length;if(r<3){if(typeof e!="string"){r<2&&(t="");for(n in e)this.style(n,e[n],t);return this}n=""}return Ra(this,"style."+e,t,o)},ja.styleTween=function(e,t,n){function r(r,i){var o=t.call(this,r,i,s.getComputedStyle(this,null).getPropertyValue(e));return o&&function(t){this.style.setProperty(e,o(t),n)}}return arguments.length<3&&(n=""),this.tween("style."+e,r)},ja.text=function(e){return Ra(this,"text",e,Ua)},ja.remove=function(){return this.each("end.transition",function(){var e;this.__transition__.count<2&&(e=this.parentNode)&&e.removeChild(this)})},ja.ease=function(t){var n=this.id;return arguments.length<1?this.node().__transition__[n].ease:(typeof t!="function"&&(t=e.ease.apply(e,arguments)),et(this,function(e){e.__transition__[n].ease=t}))},ja.delay=function(e){var t=this.id;return et(this,typeof e=="function"?function(n,r,i){n.__transition__[t].delay=+e.call(n,n.__data__,r,i)}:(e=+e,function(n){n.__transition__[t].delay=e}))},ja.duration=function(e){var t=this.id;return et(this,typeof e=="function"?function(n,r,i){n.__transition__[t].duration=Math.max(1,e.call(n,n.__data__,r,i))}:(e=Math.max(1,e),function(n){n.__transition__[t].duration=e}))},ja.each=function(t,n){var r=this.id;if(arguments.length<2){var i=qa,s=Ia;Ia=r,et(this,function(e,n,i){qa=e.__transition__[r],t.call(e,e.__data__,n,i)}),qa=i,Ia=s}else et(this,function(i){var s=i.__transition__[r];(s.event||(s.event=e.dispatch("start","end"))).on(t,n)});return this},ja.transition=function(){var e=this.id,t=++Fa,n=[],r,i,s,o;for(var u=0,a=this.length;u<a;u++){n.push(r=[]);for(var i=this[u],f=0,l=i.length;f<l;f++){if(s=i[f])o=Object.create(s.__transition__[e]),o.delay+=o.duration,za(s,f,t,o);r.push(s)}}return Ba(n,t)},e.svg.axis=function(){function f(f){f.each(function(){var f=e.select(this),l=this.__chart__||t,c=this.__chart__=t.copy(),h=u==null?c.ticks?c.ticks.apply(c,o):c.domain():u,p=a==null?c.tickFormat?c.tickFormat.apply(c,o):mn:a,d=f.selectAll(".tick").data(h,c),v=d.enter().insert("g",".domain").attr("class","tick").style("opacity",yt),m=e.transition(d.exit()).style("opacity",yt).remove(),g=e.transition(d).style("opacity",1),y,b=bu(c),w=f.selectAll(".domain").data([0]),E=(w.enter().append("path").attr("class","domain"),e.transition(w));v.append("line"),v.append("text");var S=v.select("line"),x=g.select("line"),T=d.select("text").text(p),N=v.select("text"),C=g.select("text");switch(n){case"bottom":y=Va,S.attr("y2",r),N.attr("y",Math.max(r,0)+s),x.attr("x2",0).attr("y2",r),C.attr("x",0).attr("y",Math.max(r,0)+s),T.attr("dy",".71em").style("text-anchor","middle"),E.attr("d","M"+b[0]+","+i+"V0H"+b[1]+"V"+i);break;case"top":y=Va,S.attr("y2",-r),N.attr("y",-(Math.max(r,0)+s)),x.attr("x2",0).attr("y2",-r),C.attr("x",0).attr("y",-(Math.max(r,0)+s)),T.attr("dy","0em").style("text-anchor","middle"),E.attr("d","M"+b[0]+","+ -i+"V0H"+b[1]+"V"+ -i);break;case"left":y=$a,S.attr("x2",-r),N.attr("x",-(Math.max(r,0)+s)),x.attr("x2",-r).attr("y2",0),C.attr("x",-(Math.max(r,0)+s)).attr("y",0),T.attr("dy",".32em").style("text-anchor","end"),E.attr("d","M"+ -i+","+b[0]+"H0V"+b[1]+"H"+ -i);break;case"right":y=$a,S.attr("x2",r),N.attr("x",Math.max(r,0)+s),x.attr("x2",r).attr("y2",0),C.attr("x",Math.max(r,0)+s).attr("y",0),T.attr("dy",".32em").style("text-anchor","start"),E.attr("d","M"+i+","+b[0]+"H0V"+b[1]+"H"+i)}if(c.rangeBand){var k=c,L=k.rangeBand()/2;l=c=function(e){return k(e)+L}}else l.rangeBand?l=c:m.call(y,c);v.call(y,l),g.call(y,c)})}var t=e.scale.linear(),n=Wa,r=6,i=6,s=3,o=[10],u=null,a;return f.scale=function(e){return arguments.length?(t=e,f):t},f.orient=function(e){return arguments.length?(n=e in Xa?e+"":Wa,f):n},f.ticks=function(){return arguments.length?(o=arguments,f):o},f.tickValues=function(e){return arguments.length?(u=e,f):u},f.tickFormat=function(e){return arguments.length?(a=e,f):a},f.tickSize=function(e){var t=arguments.length;return t?(r=+e,i=+arguments[t-1],f):r},f.innerTickSize=function(e){return arguments.length?(r=+e,f):r},f.outerTickSize=function(e){return arguments.length?(i=+e,f):i},f.tickPadding=function(e){return arguments.length?(s=+e,f):s},f.tickSubdivide=function(){return arguments.length&&f},f};var Wa="bottom",Xa={top:1,right:1,bottom:1,left:1};e.svg.brush=function(){function h(t){t.each(function(){var t=e.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",m).on("touchstart.brush",m),i=t.selectAll(".background").data([0]);i.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),t.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var s=t.selectAll(".resize").data(c,mn);s.exit().remove(),s.enter().append("g").attr("class",function(e){return"resize "+e}).style("cursor",function(e){return Ja[e]}).append("rect").attr("x",function(e){return/[ew]$/.test(e)?-3:null}).attr("y",function(e){return/^[ns]/.test(e)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),s.style("display",h.empty()?"none":null);var o=e.transition(t),u=e.transition(i),a;n&&(a=bu(n),u.attr("x",a[0]).attr("width",a[1]-a[0]),d(o)),r&&(a=bu(r),u.attr("y",a[0]).attr("height",a[1]-a[0]),v(o)),p(o)})}function p(e){e.selectAll(".resize").attr("transform",function(e){return"translate("+i[+/e$/.test(e)]+","+o[+/^s/.test(e)]+")"})}function d(e){e.select(".extent").attr("x",i[0]),e.selectAll(".extent,.n>rect,.s>rect").attr("width",i[1]-i[0])}function v(e){e.select(".extent").attr("y",o[0]),e.selectAll(".extent,.e>rect,.w>rect").attr("height",o[1]-o[0])}function m(){function M(){e.event.keyCode==32&&(S||(T=null,N[0]-=i[1],N[1]-=o[1],S=2),A())}function _(){e.event.keyCode==32&&S==2&&(N[0]+=i[1],N[1]+=o[1],S=0,A())}function D(){var t=e.mouse(c),s=!1;C&&(t[0]+=C[0],t[1]+=C[1]),S||(e.event.altKey?(T||(T=[(i[0]+i[1])/2,(o[0]+o[1])/2]),N[0]=i[+(t[0]<T[0])],N[1]=o[+(t[1]<T[1])]):T=null),w&&P(t,n,0)&&(d(y),s=!0),E&&P(t,r,1)&&(v(y),s=!0),s&&(p(y),g({type:"brush",mode:S?"move":"resize"}))}function P(e,t,n){var r=bu(t),s=r[0],c=r[1],h=N[n],p=n?o:i,d=p[1]-p[0],v,m;S&&(s-=h,c-=d+h),v=(n?l:f)?Math.max(s,Math.min(c,e[n])):e[n],S?m=(v+=h)+d:(T&&(h=Math.max(s,Math.min(c,2*T[n]-v))),h<v?(m=v,v=h):m=h);if(p[0]!=v||p[1]!=m)return n?a=null:u=null,p[0]=v,p[1]=m,!0}function H(){D(),y.style("pointer-events","all").selectAll(".resize").style("display",h.empty()?"none":null),e.select("body").style("cursor",null),k.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),x(),g({type:"brushend"})}var c=this,m=e.select(e.event.target),g=t.of(c,arguments),y=e.select(c),b=m.datum(),w=!/^(n|s)$/.test(b)&&n,E=!/^(e|w)$/.test(b)&&r,S=m.classed("extent"),x=ht(),T,N=e.mouse(c),C,k=e.select(s).on("keydown.brush",M).on("keyup.brush",_);e.event.changedTouches?k.on("touchmove.brush",D).on("touchend.brush",H):k.on("mousemove.brush",D).on("mouseup.brush",H),y.interrupt().selectAll("*").interrupt();if(S)N[0]=i[0]-N[0],N[1]=o[0]-N[1];else if(b){var L=+/w$/.test(b),O=+/^n/.test(b);C=[i[1-L]-N[0],o[1-O]-N[1]],N[0]=i[L],N[1]=o[O]}else e.event.altKey&&(T=N.slice());y.style("pointer-events","none").selectAll(".resize").style("display",null),e.select("body").style("cursor",m.style("cursor")),g({type:"brushstart"}),D()}var t=M(h,"brushstart","brush","brushend"),n=null,r=null,i=[0,0],o=[0,0],u,a,f=!0,l=!0,c=Ka[0];return h.event=function(n){n.each(function(){var n=t.of(this,arguments),r={x:i,y:o,i:u,j:a},s=this.__chart__||r;this.__chart__=r,Ia?e.select(this).transition().each("start.brush",function(){u=s.i,a=s.j,i=s.x,o=s.y,n({type:"brushstart"})}).tween("brush:brush",function(){var e=Rs(i,r.x),t=Rs(o,r.y);return u=a=null,function(s){i=r.x=e(s),o=r.y=t(s),n({type:"brush",mode:"resize"})}}).each("end.brush",function(){u=r.i,a=r.j,n({type:"brush",mode:"resize"}),n({type:"brushend"})}):(n({type:"brushstart"}),n({type:"brush",mode:"resize"}),n({type:"brushend"}))})},h.x=function(e){return arguments.length?(n=e,c=Ka[!n<<1|!r],h):n},h.y=function(e){return arguments.length?(r=e,c=Ka[!n<<1|!r],h):r},h.clamp=function(e){return arguments.length?(n&&r?(f=!!e[0],l=!!e[1]):n?f=!!e:r&&(l=!!e),h):n&&r?[f,l]:n?f:r?l:null},h.extent=function(e){var t,s,f,l,c;if(!arguments.length)return n&&(u?(t=u[0],s=u[1]):(t=i[0],s=i[1],n.invert&&(t=n.invert(t),s=n.invert(s)),s<t&&(c=t,t=s,s=c))),r&&(a?(f=a[0],l=a[1]):(f=o[0],l=o[1],r.invert&&(f=r.invert(f),l=r.invert(l)),l<f&&(c=f,f=l,l=c))),n&&r?[[t,f],[s,l]]:n?[t,s]:r&&[f,l];if(n){t=e[0],s=e[1],r&&(t=t[0],s=s[0]),u=[t,s],n.invert&&(t=n(t),s=n(s)),s<t&&(c=t,t=s,s=c);if(t!=i[0]||s!=i[1])i=[t,s]}if(r){f=e[0],l=e[1],n&&(f=f[1],l=l[1]),a=[f,l],r.invert&&(f=r(f),l=r(l)),l<f&&(c=f,f=l,l=c);if(f!=o[0]||l!=o[1])o=[f,l]}return h},h.clear=function(){return h.empty()||(i=[0,0],o=[0,0],u=a=null),h},h.empty=function(){return!!n&&i[0]==i[1]||!!r&&o[0]==o[1]},e.rebind(h,t,"on")};var Ja={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Ka=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Qa=e.time={},Ga=Date,Ya=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];Za.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ef.setUTCDate.apply(this._,arguments)},setDay:function(){ef.setUTCDay.apply(this._,arguments)},setFullYear:function(){ef.setUTCFullYear.apply(this._,arguments)},setHours:function(){ef.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ef.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ef.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ef.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ef.setUTCSeconds.apply(this._,arguments)},setTime:function(){ef.setTime.apply(this._,arguments)}};var ef=Date.prototype,tf="%a %b %e %X %Y",nf="%m/%d/%Y",rf="%H:%M:%S",sf=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],of=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],uf=["January","February","March","April","May","June","July","August","September","October","November","December"],af=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];Qa.year=ff(function(e){return e=Qa.day(e),e.setMonth(0,1),e},function(e,t){e.setFullYear(e.getFullYear()+t)},function(e){return e.getFullYear()}),Qa.years=Qa.year.range,Qa.years.utc=Qa.year.utc.range,Qa.day=ff(function(e){var t=new Ga(2e3,0);return t.setFullYear(e.getFullYear(),e.getMonth(),e.getDate()),t},function(e,t){e.setDate(e.getDate()+t)},function(e){return e.getDate()-1}),Qa.days=Qa.day.range,Qa.days.utc=Qa.day.utc.range,Qa.dayOfYear=function(e){var t=Qa.year(e);return Math.floor((e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/864e5)},Ya.forEach(function(e,t){e=e.toLowerCase(),t=7-t;var n=Qa[e]=ff(function(e){return(e=Qa.day(e)).setDate(e.getDate()-(e.getDay()+t)%7),e},function(e,t){e.setDate(e.getDate()+Math.floor(t)*7)},function(e){var n=Qa.year(e).getDay();return Math.floor((Qa.dayOfYear(e)+(n+t)%7)/7)-(n!==t)});Qa[e+"s"]=n.range,Qa[e+"s"].utc=n.utc.range,Qa[e+"OfYear"]=function(e){var n=Qa.year(e).getDay();return Math.floor((Qa.dayOfYear(e)+(n+t)%7)/7)}}),Qa.week=Qa.sunday,Qa.weeks=Qa.sunday.range,Qa.weeks.utc=Qa.sunday.utc.range,Qa.weekOfYear=Qa.sundayOfYear,Qa.format=cf;var mf=pf(sf),gf=df(sf),yf=pf(of),bf=df(of),wf=pf(uf),Ef=df(uf),Sf=pf(af),xf=df(af),Tf=/^%/,Nf={"-":"",_:" ",0:"0"},Cf={a:function(e){return of[e.getDay()]},A:function(e){return sf[e.getDay()]},b:function(e){return af[e.getMonth()]},B:function(e){return uf[e.getMonth()]},c:cf(tf),d:function(e,t){return vf(e.getDate(),t,2)},e:function(e,t){return vf(e.getDate(),t,2)},H:function(e,t){return vf(e.getHours(),t,2)},I:function(e,t){return vf(e.getHours()%12||12,t,2)},j:function(e,t){return vf(1+Qa.dayOfYear(e),t,3)},L:function(e,t){return vf(e.getMilliseconds(),t,3)},m:function(e,t){return vf(e.getMonth()+1,t,2)},M:function(e,t){return vf(e.getMinutes(),t,2)},p:function(e){return e.getHours()>=12?"PM":"AM"},S:function(e,t){return vf(e.getSeconds(),t,2)},U:function(e,t){return vf(Qa.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return vf(Qa.mondayOfYear(e),t,2)},x:cf(nf),X:cf(rf),y:function(e,t){return vf(e.getFullYear()%100,t,2)},Y:function(e,t){return vf(e.getFullYear()%1e4,t,4)},Z:Yf,"%":function(){return"%"}},kf={a:Lf,A:Af,b:Df,B:Pf,c:Hf,d:zf,e:zf,H:Xf,I:Xf,j:Wf,L:Jf,m:Uf,M:Vf,p:Qf,S:$f,U:Mf,w:Of,W:_f,x:Bf,X:jf,y:If,Y:Ff,Z:qf,"%":Zf},Kf=/^\s*\d+/,Gf=e.map({am:0,pm:1});cf.utc=el;var tl=el("%Y-%m-%dT%H:%M:%S.%LZ");cf.iso=Date.prototype.toISOString&&+(new Date("2000-01-01T00:00:00.000Z"))?nl:tl,nl.parse=function(e){var t=new Date(e);return isNaN(t)?null:t},nl.toString=tl.toString,Qa.second=ff(function(e){return new Ga(Math.floor(e/1e3)*1e3)},function(e,t){e.setTime(e.getTime()+Math.floor(t)*1e3)},function(e){return e.getSeconds()}),Qa.seconds=Qa.second.range,Qa.seconds.utc=Qa.second.utc.range,Qa.minute=ff(function(e){return new Ga(Math.floor(e/6e4)*6e4)},function(e,t){e.setTime(e.getTime()+Math.floor(t)*6e4)},function(e){return e.getMinutes()}),Qa.minutes=Qa.minute.range,Qa.minutes.utc=Qa.minute.utc.range,Qa.hour=ff(function(e){var t=e.getTimezoneOffset()/60;return new Ga((Math.floor(e/36e5-t)+t)*36e5)},function(e,t){e.setTime(e.getTime()+Math.floor(t)*36e5)},function(e){return e.getHours()}),Qa.hours=Qa.hour.range,Qa.hours.utc=Qa.hour.utc.range,Qa.month=ff(function(e){return e=Qa.day(e),e.setDate(1),e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()}),Qa.months=Qa.month.range,Qa.months.utc=Qa.month.utc.range;var ol=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],ul=[[Qa.second,1],[Qa.second,5],[Qa.second,15],[Qa.second,30],[Qa.minute,1],[Qa.minute,5],[Qa.minute,15],[Qa.minute,30],[Qa.hour,1],[Qa.hour,3],[Qa.hour,6],[Qa.hour,12],[Qa.day,1],[Qa.day,2],[Qa.week,1],[Qa.month,1],[Qa.month,3],[Qa.year,1]],al=[[cf("%Y"),Tr],[cf("%B"),function(e){return e.getMonth()}],[cf("%b %d"),function(e){return e.getDate()!=1}],[cf("%a %d"),function(e){return e.getDay()&&e.getDate()!=1}],[cf("%I %p"),function(e){return e.getHours()}],[cf("%I:%M"),function(e){return e.getMinutes()}],[cf(":%S"),function(e){return e.getSeconds()}],[cf(".%L"),function(e){return e.getMilliseconds()}]],fl=sl(al);ul.year=Qa.year,Qa.scale=function(){return rl(e.scale.linear(),ul,fl)};var ll={range:function(t,n,r){return e.range(+t,+n,r).map(il)}},cl=ul.map(function(e){return[e[0].utc,e[1]]}),hl=[[el("%Y"),Tr],[el("%B"),function(e){return e.getUTCMonth()}],[el("%b %d"),function(e){return e.getUTCDate()!=1}],[el("%a %d"),function(e){return e.getUTCDay()&&e.getUTCDate()!=1}],[el("%I %p"),function(e){return e.getUTCHours()}],[el("%I:%M"),function(e){return e.getUTCMinutes()}],[el(":%S"),function(e){return e.getUTCSeconds()}],[el(".%L"),function(e){return e.getUTCMilliseconds()}]],pl=sl(hl);return cl.year=Qa.year.utc,Qa.scale.utc=function(){return rl(e.scale.linear(),cl,pl)},e.text=gn(function(e){return e.responseText}),e.json=function(e,t){return yn(e,"application/json",dl,t)},e.html=function(e,t){return yn(e,"text/html",vl,t)},e.xml=gn(function(e){return e.responseXML}),e}(),define("libs/d3",function(e){return function(){var t,n;return t||e.d3}}(this)),define("unifi/model/StatisticsColors",["backbone","underscore"],function(e,t){"use strict";return e.Model.extend({initialize:function(){this.colors=["#23B1E6","#EE6B79","#52CC74","#EE472B","#F7931E","#52C1C4","#D2C485","#50B748","#F071A6","#3186C1","#C3DFB0","#F15A24","#159653","#F6C2D9","#E60688","#045AA6","#B8B34B","#8C2473","#B66BA5","#BFD637"],this.index=0,this.numColors=this.colors.length},first:function(){return t.first(this.colors)},getAllButFirst:function(){return t.rest(this.colors)},getNext:function(){return this.index++,this.getCurrent()},getIndex:function(){return this.index%this.numColors},getCurrent:function(){return this.colors[this.getIndex()]},getAtIndex:function(e){return this.colors[e%this.numColors]}})}),define("unifi/collection/stats/Stats",["unifi/collection/Collection","backbone","unifi/model/Model","libs/moment","underscore"],function(e,t,n,r,i){"use strict";return e.extend({model:n,bySite:!0,_o:null,_type:null,toGraph:function(e){var t=this,n=i.compact(t.chain().filter(function(n){return e&&e.filter?n.get(t._o)==e.filter:!0}).map(function(e){if(e.get("o")==t._o){var n=e.toJSON();return n.datetime=new Date(e.get("time")),n}}).value()),r=i.max(n,function(e){return e.bytes}).bytes,s,o;r>(s=Math.pow(1e3,3))?o="GB":r>(s=Math.pow(1e3,2))?o="MB":r>(s=1e3)?o="KB":o="B";if(e.fill===!0&&e.interval){var u=i.pluck(n,"time"),a=i.min(u),f=i.max(u);for(var l=a;l<f;l+=e.interval*1e3)u.indexOf(l)===-1&&n.push({bytes:null,num_sta:null,datetime:new Date(l)});n=i.sortBy(n,function(e){return e.datetime})}return n.map(function(e){return delete e.time,delete e.o,delete e.site,e.bytesFmt=e.bytes?+(e.bytes/s).toPrecision(2):null,e.bytesLbl=o,e})},validatePointsHasProp:function(e,t){for(var n=0,r=e.length;n<r;n++)if(i.has(e[n],t)&&!i.isNull(e[n][t]))return!0;return!1},orderByBytes:function(){var e=this,t=this.sortBy(function(e){return e.get("bytes")});return t=t.reverse(),t=i.uniq(t,!1,function(t){return t.attributes[e._o]}),t},comparator:function(e){return-r(e.get("time"))},hourly:function(e){return this.fetch(i.extend(e,{_method:"read-hourly"}))},daily:function(e){return this.fetch(i.extend(e,{_method:"read-daily"}))},clearStats:function(e){this.sync("clear",this,e)},sync:function(e,n,r){r=r||{},r._method&&(e=r._method,delete r._method);switch(e){case"read-hourly":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/stat/report/hourly."+this._type,r.type="POST",r.data=JSON.stringify(i.extend({attrs:["bytes","num_sta","time"]},r.data||{}));break;case"read-daily":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/stat/report/daily."+this._type,r.type="POST",r.data=JSON.stringify(i.extend({attrs:["bytes","num_sta","time"]},r.data||{}));break;case"clear":r.contentType="application/json; charset=utf-8",r.url="/api/s/"+SITE.name+"/cmd/stat",r.type="POST",r.data=JSON.stringify(i.extend({cmd:"reset-current"},r.data||{}))}return t.sync.call(this,e,n,r)}})}),define("unifi/collection/stats/SiteStats",["unifi/collection/stats/Stats"],function(e){"use strict";return e.extend({_o:"site",_type:"site"})}),define("unifi/collection/stats/ClientStats",["unifi/collection/stats/Stats"],function(e){"use strict";return e.extend({_o:"user",_type:"user"})}),define("unifi/collection/stats/DeviceStats",["unifi/collection/stats/Stats"],function(e){"use strict";return e.extend({_o:"ap",_type:"ap"})}),define("unifi/view/statistics/LineChartView",["backbone","underscore","msg/Msg","jquery","libs/d3"],function(e,t,n,r,i){"use strict";return e.View.extend({initialize:function(e){this.config=e.config,this.data=e.data,this.plottable=!1,this.components={},this.mouse=[0,0],this.xpos,this.render()},render:function(){var e=this.config,t=this.data,n=this.components;!this.rendered&&(this.rendered=!0)&&(this.renderChart(),e.overlays.databox&&this.renderDatabox(),e.overlays.ticktip&&this.renderTicktip(),this.hideOverlays(!0),n.overlays.style("visibility","visible")),t.points.length&&this.update(!0)},renderChart:function(){var e=this.config,t=this.data,r=this.components;r.xScale=i.time.scale().domain([0,24]).range([0,e.width()]),r.yScale=i.scale.linear().domain([e.height,0]).range([0,e.height]),r.xAxis=i.svg.axis().scale(r.xScale).orient("bottom").ticks(24).tickSize.apply(null,e.ticksize).tickFormat(""),r.yAxis=i.svg.axis().scale(r.yScale).orient("right").ticks(6).tickSize(-e.width(),0,0).tickPadding(5),r.container=i.select(this.$el[0]).append("svg").attr("width",e.width()+e.margin.left+e.margin.right).attr("height",e.height+e.margin.top+e.margin.bottom),r.title=r.container.append("text").attr("x",e.margin.left).attr("y",e.margin.top/2).attr("class","title").text(e.title),r.chart=r.container.append("g").attr("class","chart").attr("transform","translate("+e.margin.left+","+e.margin.top+")"),r.border=r.chart.append("rect").attr("height",e.height).attr("width",e.width()).attr("class","border");var s=r.chart.append("svg:defs");s.append("svg:pattern").attr("id","hatched").attr("patternUnits","userSpaceOnUse").attr("x","0").attr("y","0").attr("width","4").attr("height","4").attr("patternTransform","rotate(-45)").append("svg:path").attr("d","M 0 1 L 4 1").style("fill","none").style("stroke-width",1).style("stroke","#ccc").style("stroke-opacity",".5"),s.append("clipPath").attr("id","clip").append("rect").attr("width",e.width()).attr("height",e.height),r.chart.append("g").attr("class","x axis").attr("transform","translate(0,"+e.height+")"),r.chart.append("g").attr("class","y axis").attr("transform","translate("+e.width()+",0)"),r.chart.append("g").attr("clip-path","url(#clip)").attr("class","x grid").attr("width",e.width()).attr("height",e.height),r.datasets=r.chart.append("g").attr("class","datasets"),r.overlays=r.chart.append("g").attr("class","overlays").style("visibility","hidden"),r.line=i.svg.line().defined(function(e){return e[t.yprop]!==null}).x(function(e){return r.xScale(e[t.xprop])}).y(function(e){return r.yScale(e[t.yprop]||0)}),r.moreDataNeeded=r.container.append("text").attr("class","more-data-needed").text(n.G_StatsMoreDataPoints);var o=r.moreDataNeeded[0][0].getBBox();r.moreDataNeededBBox=o,r.moreDataNeeded.attr("x",(e.width()-o.width)/2).attr("y",(e.height+o.height)/2),r.moreDataNeeded.style("visibility","hidden")},renderDatabox:function(){var e=this.config,t=this.components;t.databox=t.overlays.append("g").attr("width",e.overlays.databox.width).attr("height",e.height+e.overlays.databox.heightDiff).attr("class","databox");var n=t.databox.append("svg:defs").append("svg:filter").attr("id","blur");n.append("svg:feGaussianBlur").attr("in","SourceAlpha").attr("stdDeviation",2),n.append("svg:feOffset").attr("dx",0).attr("dy",0).attr("result","offsetblur"),n.append("svg:feComponentTransfer").append("svg:feFuncA").attr("type","linear").attr("slope",".13");var r=n.append("svg:feMerge");r.append("svg:feMergeNode"),r.append("svg:feMergeNode").attr("in","SourceGraphic"),t.databox.append("rect").attr("y",-e.overlays.databox.heightDiff/2).attr("width",e.overlays.databox.width).attr("height",e.height+e.overlays.databox.heightDiff).attr("filter","url(#blur)"),t.databox.append("g").attr("class","labels").attr("transform","translate(0,20)")},renderTicktip:function(){var e=this.config,t=this.components;t.ticktip=t.overlays.append("g").attr("class","ticktip"),t.ticktip.append("rect").attr("width",e.overlays.ticktip.width.min).attr("height",e.overlays.ticktip.height).attr("rx","3"),t.ticktip.append("text"),t.ticktip.style("visibility","hidden")},update:function(e){var n=this.config,r=this.data,s=this.components,o=i.merge(r.points);o=t.filter(o,function(e){return e[r.yprop]!==null}),s.xScale.domain(r.xDomain||i.extent(o,function(e){return e[r.xprop]})),s.yScale.domain([i.max(o,function(e){return e[r.yprop]||0}),i.min(o,function(e){return e[r.yprop]||0})]),e===!0&&s.datasets.selectAll(".dataset").remove(),this.updateChart(),this.updateSections(),this.updateOverlays(!0)},updateChart:function(){var e=this.config,t=this.data,n=this.components;this.plottable=t.points.length&&t.points[0]&&(t.points[0].length||t.points[1]&&t.points[1].length),n.container.attr("width",e.width()+e.margin.left+e.margin.right),n.border.attr("width",e.width()),n.xScale.range([0,e.width()]),n.chart.select("#clip rect").attr("width",e.width()),n.chart.select(".y.axis").attr("transform","translate("+e.width()+",0)"),n.chart.select(".x.grid").attr("width",e.width()),n.container.select(".more-data-needed").attr("x",(e.width()-n.moreDataNeededBBox.width)/2);if(!this.plottable){n.moreDataNeeded.style("visibility","visible"),this.hideOverlays(!0);return}n.moreDataNeeded.style("visibility","hidden"),n.chart.select(".x.axis").call(n.xAxis),n.chart.select(".y.axis").call(n.yAxis),n.data=n.datasets.selectAll(".dataset").data(t.points),n.data.enter().append("g").attr("class",function(e,t){return"dataset dataset-"+t}),n.data.exit().remove(),n.paths=n.data.selectAll("path").data(function(e){return[e]}).attr("d",n.line),n.paths.enter().append("path").attr("d",n.line).attr("class","line").attr("clip-path","url(#clip)").style("stroke",function(t,n,r){return e.colors[r]}),n.paths.exit().remove(),n.circles=n.data.selectAll("circle").data(function(e){return e.filter(function(e){return e[t.yprop]!==null})},function(e){return e[t.idprop]}).attr("cx",n.line.x()).attr("cy",n.line.y()||0),n.circles.enter().append("circle").attr("cx",n.line.x()).attr("cy",n.line.y()||0).attr("r",e.points.off).attr("class","point").attr("fill",function(t,n,r){return e.colors[r]}),n.circles.exit().remove()},updateSections:function(){var e=this.config,t=this.components,n=t.chart.selectAll(".x.grid"),r=t.chart.selectAll(".x.axis .tick"),s=4,o=Math.round(r[0].length/s),u=e.width()/(r[0].length-1)*s,a=[];n.selectAll("rect").remove(),a=r[0].map(function(e){return parseFloat(i.select(e).attr("transform").match(/translate\(\s*([^\s,)]+)[ ,]([^\s,)]+)/)[1])}).sort(function(e,t){return e-t}),u=a[s]-a[0]||u;for(var f=0;f<o;f++)f%2&&n.insert("svg:rect").attr("transform","translate("+a[f*s]+",0)").attr("height",e.height).attr("width",u).style("fill","url(#hatched)")},updateOverlays:function(e){var n=this.config,r=this.data,s=this.components,o;o=Math.max(Math.min(this.mouse[0]-10,n.width()),0);var u=[],a=[];s.data&&t.each(s.data.selectAll("circle"),function(e,r){var s,f;t.each(e,function(e){e=i.select(e);var r=e.attr("cx")-o;r>=0&&(t.isUndefined(s)||r<s)&&(f=e,s=r),e.attr("r",n.points.off)},this),f&&(f.attr("r",n.points.on),u[r]=f,a[r]=s)},this),t.each(a,function(e,n){e>t.min(a)&&delete u[n]});if(u.length){o=t.first(t.compact(u)).attr("cx");if(e||o!=this.xpos){if(n.overlays.databox){s.databox.selectAll("circle").remove(),t.each(u,function(e,t){e.attr("cx")>n.overlays.databox.width&&s.databox.append("circle").attr("cx",n.overlays.databox.width).attr("cy",e.attr("cy")).attr("r",n.points.on).attr("class","point").attr("fill",n.colors[t])});var f=s.databox.select(".labels");f.selectAll("g").remove(),t.each(r.labels,function(e,t){if(u[t]){var i=f.append("g").attr("transform","translate(0,"+30*t+")").style("fill",n.colors[t]),s=u[t].datum();i.append("text").attr("x",n.overlays.databox.valueWidth).attr("width",n.overlays.databox.valueWidth).attr("class","value").text(s[r.yprop]||0),i.append("text").attr("x",n.overlays.databox.valueWidth+5).text((r.labelprop?s[r.labelprop]+" ":"")+e)}}),s.databox.attr("transform","translate("+Math.max(0,o-n.overlays.databox.width)+",0)")}if(n.overlays.ticktip){var l=t.first(t.values(u)).datum()[r.xprop],c=s.ticktip.select("text");c.text(n.overlays.ticktip.format?n.overlays.ticktip.format(l,this.config.range):l);var h=Math.max(n.overlays.ticktip.width.min,Math.min(c.node().getComputedTextLength()+n.overlays.ticktip.width.padding*2,n.overlays.ticktip.width.max));c.attr("transform","translate("+(h-n.overlays.ticktip.width.padding)+",17)"),s.ticktip.attr("transform","translate("+Math.max(n.overlays.databox.width-h,o-h)+","+(n.height+n.overlays.ticktip.bottom)+")").select("rect").attr("width",h),s.ticktip.style("visibility","visible")}}}this.xpos=o},hideOverlays:function(e){var t=this,n=this.config,r=this.components;r.data&&r.data.selectAll("circle").transition().duration(e?0:600).attr("r",n.points.off),r.overlays&&r.overlays.transition().duration(e?0:600).style("opacity",0).each("end",function(){t._overlaysVisible=!1})},showOverlays:function(){if(this.plottable){var e=this.components;this._overlaysVisible=!0,e.overlays.transition().duration(0).style("opacity",null)}},remove:function(){this.rendered=!1,e.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/statistics/PieChartView",["backbone","underscore","msg/Msg","jquery","libs/d3","ubnt/backgrid"],function(e,t,n,r,i,s){"use strict";return e.View.extend({initialize:function(e){this.config=e.config,this.data=e.data,this.components={},this.render()},render:function(){var e=this,t=this.config,n=this.data,i=this.components;!this.rendered&&(this.rendered=!0)&&(this.renderChart(),this.$el.on("mouseover",".arc",function(t){var n=r(this),i=n.data("arc");e.$(".tooltip-"+i).css({visibility:"visible"}),e.$(".piechart-item-"+i).addClass("over"),e.tooltipIndex=i}).on("mouseout",".arc",function(t){var n=r(this),i=r(this).data("arc");e.$(".tooltip-"+i).css({visibility:"hidden"}),e.$(".piechart-item-"+i).removeClass("over")})),n.points.length&&this.update()},renderChart:function(){var e=this.config,t=this.data,n=this.components;n.pie=i.layout.pie().sort(null).value(function(e){return e.get(t.prop)||0}),n.arc=i.svg.arc().innerRadius(0).outerRadius(this.config.radius-10),n.svg=i.select(this.$(e.pieChart)[0]).append("svg").attr("width",e.width).attr("height",e.height).append("g").attr("transform","translate("+e.width/2+","+e.height/2+")"),e.legend&&this.renderLegend()},renderLegend:function(){var e=this.config,n=this.data,r;e.legend&&(this.$legend=this.$legend||this.$(".piechart-legend"),this.$legend.empty(),t.each(n.points,function(t,n){r=typeof t.name=="function"?t.name():t.get("name"),this.$legend.append('<div class="piechart-legend-item piechart-item-'+n+'"><div class="piechart-legend-color" style="background-color:'+e.colors[n]+'"></div>'+r+"</div>")},this))},update:function(){var e=this.config,t=this.data,n=this.components;t.points&&(n.g=n.svg.selectAll(".arc").data(n.pie(t.points)),n.g.enter().append("g").attr("class","arc").attr("data-arc",function(e,t,n){return t}),n.g.enter().append("text").attr("class",function(e,t,n){return"tooltip tooltip-"+t}).attr("data-arc",function(e,t,n){return t}).attr("transform",function(t){var r=n.arc.centroid(t),i=r[0],s=r[1],o=Math.sqrt(i*i+s*s);return"translate("+i/o*(e.radius-3)+","+s/o*(e.radius-3)+")"}).attr("dy",".35em").style("text-anchor",function(e){return(e.endAngle+e.startAngle)/2>Math.PI?"end":"start"}).style("visibility","hidden").text(function(e){var n=e.data.get(t.prop)||0;return t.formatBytes&&(n=s.Formatters.Bytes.fromRaw(n)),n}),n.g.selectAll("path").remove(),n.g.append("path").attr("d",n.arc).attr("fill",function(t,n,r){return e.colors[n]}),n.g.exit().remove(),this.renderLegend())},remove:function(){this.$el.off("mouseover",".arc").off("mouseout",".arc"),this.rendered=!1,e.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/statistics/DatetimeNavView",["backbone","underscore","msg/Msg","libs/moment","jquery","jquery-ui"],function(e,t,n,r,i){"use strict";return e.View.extend({initialize:function(e){t.bindAll(this),this.RANGE_1HOUR=i(".dateRange1HourBtn").val(),this.RANGE_24HOUR=i(".dateRange24HourBtn").val(),this.RANGE_MONTH=i(".dateRangeMonthBtn").val(),this.RANGE_7DAY=i(".dateRange7DayBtn").val(),this.useCurrentTimeForRange=!1,e.useCurrentTimeForRange&&(this.useCurrentTimeForRange=e.useCurrentTimeForRange),this.originalSettings={},this.momentDate=r(),this.momentDateMax=r(),this.momentDate.startOf("hour"),this.momentDateMax.startOf("hour"),this.momentHourFormat="ha",this.momentDatetimeFormat="YYYY/M/D",this.render()},render:function(){var e=this;!this.rendered&&(this.rendered=!0)&&(this.$el.addClass("datetimeNav"),this.$buttonset=this.$(".buttonset"),this.$buttonset.buttonset(),this.$datepicker=this.$(".datepicker").datepicker({showOtherMonths:!0,selectOtherMonths:!0,dayNamesMin:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dateFormat:"yy/m/d",onSelect:this.onDatepickerSelect,onChangeMonthYear:this.onDatepickerChangeMonthYear}),this.$rangeButtonset=this.$(".range-buttonset"),this.$rangeButtonset.find("input").on("change",this.onRangeChange),this.$rangeButtonset.find("input:checked").change(),this.$(".date-nav .ui-button").mousedown(function(){i(this).addClass("ui-state-active")}).on("mouseup mouseout",function(){var e=i(this);t.delay(function(){e.removeClass("ui-state-active")},20)}),this.$dateToggle=this.$(".date-nav").find(".dateToggle"),this.$datePopover=this.$(".date-popover"),this.$(".dateToggleBtn").on("click",this.openPopover),this.$microRangePrev=this.$(".date-micro-range .prev"),this.$microRangePrev.on("click",this.onMicroRangePrevClick).disableSelection(),this.$microRangeNext=this.$(".date-micro-range .next"),this.$microRangeNext.on("click",this.onMicroRangeNextClick).disableSelection(),this.$hour=this.$(".hour"),this.$datetime=this.$(".datetime"),this.$datetimeMax=this.$(".datetimeMax"),this.$update=this.$("button.update"),this.$update.on("click",this.onUpdate),this.$cancel=this.$("button.cancel"),this.$cancel.on("click",this.onCancel),this.$title=this.$(".title"),this.$dateRange1Hour=this.$(".date-range-1hour"),this.$dateRangeHour=this.$(".date-range-hour"),this.$dateRangeMonth=this.$(".date-range-month"),this.$dateRange7Day=this.$(".date-range-7day"),this.$title.find(".ui-button-text").text(n.G_StatsDisplayRange),this.$dateRange1Hour.find(".ui-button-text").text(n.G_Stats1Hour),this.$dateRangeHour.find(".ui-button-text").text(n.G_Stats24Hour),this.$dateRangeMonth.find(".ui-button-text").text(n.G_Month),this.$dateRange7Day.find(".ui-button-text").text(n.G_Insights7Days),this.$update.find("span").after(n.G_Update),this.$cancel.find("span").after(n.G_Cancel),this.options.is7Day&&(this.$buttonset.addClass("is7Day"),this.$dateRange1Hour.css("display","inline-block"),this.$dateRange1Hour.find(".ui-button-text").show(),this.$dateRange7Day.show(),this.$dateRange7Day.find(".ui-button-text").show(),this.$dateRangeMonth.hide(),this.$dateRangeMonth.find(".ui-button-text").show()),this.updateHour(),this.updateDatetime())},onMicroRangePrevClick:function(e){this.range===this.RANGE_1HOUR?(this.momentDate.subtract("hours",1),this.updateHour()):this.range===this.RANGE_24HOUR?this.momentDateMax.subtract("days",1):(this.range===this.RANGE_MONTH||this.range==this.RANGE_7DAY)&&this.momentDateMax.subtract("days",1),this.updateDatetime(),i(e.currentTarget).hasClass("ui-button")&&this.onUpdate(e)},onMicroRangeNextClick:function(e){this.range===this.RANGE_1HOUR?(this.momentDate.add("hours",1),this.updateHour()):this.range===this.RANGE_24HOUR?this.momentDateMax.add("days",1):(this.range===this.RANGE_MONTH||this.range===this.RANGE_7DAY)&&this.momentDateMax.add("days",1),this.updateDatetime(),i(e.currentTarget).hasClass("ui-button")&&this.onUpdate(e)},onDatepickerSelect:function(e){this.momentDate=r(e).hour(this.momentDate.hour()),this.momentDateMax=this.momentDate.clone(),this.updateDatetime()},onDatepickerChangeMonthYear:function(e,n){var r=this;(this.range===this.RANGE_MONTH||this.range===this.RANGE_7DAY)&&t.delay(function(){r.setDaysInActiveRange()},100)},onRangeChange:function(e){var t=i(e.target),n=t.attr("id"),r=t.val();return this.$buttonset.find(".ui-button").removeClass("ui-state-active"),this.$buttonset.find("input").prop("checked",""),r&&(r===this.RANGE_24HOUR?(this.range=this.RANGE_24HOUR,this.$el.removeClass("isMonth is1Hr").addClass("is24Hr"),this.removeDaysInActiveRange(),this.momentDate=this.momentDateMax.clone()):r===this.RANGE_1HOUR?(this.range=this.RANGE_1HOUR,this.$el.removeClass("isMonth is24Hr").addClass("is1Hr"),this.removeDaysInActiveRange(),this.momentDate=this.momentDateMax.clone()):r===this.RANGE_MONTH?(this.range=this.RANGE_MONTH,this.$el.removeClass("is24Hr is1Hr").addClass("isMonth")):r===this.RANGE_7DAY&&(this.range=this.RANGE_7DAY,this.$el.removeClass("is24Hr is1Hr").addClass("isMonth"))),this.updateDatetime(),this.$buttonset.find('label[for="'+n+'"]').addClass("ui-state-active"),!1},updateHour:function(){this.$hour.text(this.momentDate.format(this.momentHourFormat).toUpperCase())},updateDatetime:function(){var e=this;this.range&&(this.range===this.RANGE_1HOUR?this.momentDateMax=this.momentDate.clone():this.range===this.RANGE_24HOUR?(this.momentDate=this.momentDateMax.clone(),this.momentDate.subtract("days",1)):this.range===this.RANGE_MONTH?(this.momentDate=this.momentDateMax.clone(),this.momentDate.subtract("months",1)):this.range===this.RANGE_7DAY&&(this.momentDate=this.momentDateMax.clone(),this.momentDate.subtract("days",7)),t.delay(function(){e.setDaysInActiveRange()},100),this.updateDatetimeText())},updateDatetimeText:function(){this.$datetime&&this.$datetimeMax&&(this.$datetime.text(this.momentDate.format(this.momentDatetimeFormat)),this.$datetimeMax.text(this.momentDateMax.format(this.momentDatetimeFormat)))},setDaysInActiveRange:function(){var e=this.$datepicker.find("tbody td"),n,s,o,u,a,f=e.length,l,c=this.momentDate.clone(),h=this.momentDateMax.clone();c=c.startOf("day"),h=h.startOf("day"),this.range==this.RANGE_24HOUR&&c.add("day",1),this.removeDaysInActiveRange(),t.each(e,function(e,t){n=i(e),s=n.data("month")+1,u=n.data("year"),o=n.text(),a=r(u+"/"+s+"/"+o,"YYYY/MM/DD"),a.startOf("hour"),a>=c&&a<=h&&n.find("a").addClass("ui-state-active-range")})},removeDaysInActiveRange:function(){this.$datepicker.find(".ui-state-active-range").removeClass("ui-state-active-range");if(this.range==this.RANGE_24HOUR){var e=this.$datepicker.find(".ui-datepicker-current-day");e.removeClass("ui-datepicker-current-day"),e.find(".ui-state-active").removeClass("ui-state-active")}},getDateRange:function(){var e,t,n=this.momentDate.clone().startOf("hour"),r=this.momentDateMax.clone().startOf("hour"),i={range:this.range,start:n.utc().unix()};return this.range===this.RANGE_24HOUR?(this.useCurrentTimeForRange?(e=r,t=r.clone().subtract("days",1)):(e=r.endOf("day"),t=r.clone().startOf("day")),i.end=e.utc().unix(),i.start=t.utc().unix()):this.range===this.RANGE_1HOUR?(t=n,e=n.clone().endOf("hour"),i.start=t.utc().unix(),i.end=e.utc().unix()):this.range===this.RANGE_MONTH?(e=r.endOf("day"),t=e.clone().subtract("months",1).startOf("day"),i.end=e.utc().unix(),i.start=t.utc().unix()):this.range===this.RANGE_7DAY&&(e=r.endOf("day"),t=e.clone().subtract("days",7).startOf("day"),i.end=e.utc().unix(),i.start=t.utc().unix()),i.start=parseInt(i.start+"000",10),i.end=parseInt(i.end+"000",10),i},openPopover:function(){this.originalSettings=this.getDateRange(),this.$datePopover.show(),i("body").on("click",this.onBodyClick)},closePopover:function(){this.$datePopover.hide(),i("body").off("click",this.onBodyClick)},onBodyClick:function(e){var t=this,n=i(e.target);n.hasClass("filter")&&t.closePopover(),!n.hasClass("date-popover")&&!n.parents(".date-popover").length&&!n.parents(".date-nav").length&&!n.hasClass("ui-datepicker-next")&&!n.hasClass("ui-datepicker-prev")&&!n.hasClass("filter")&&!n.parents(".filter-popover").length&&t.onCancel()},onUpdate:function(e){e.preventDefault(),this.closePopover(),this.$el.trigger("change",this.getDateRange())},onCancel:function(){this.revertSettings(),this.closePopover()},revertSettings:function(){this.$buttonset.find("input[value="+this.originalSettings.range+"]").click(),this.$datepicker.datepicker("setDate",new Date(this.originalSettings.end)),this.onDatepickerSelect(this.originalSettings.end)},remove:function(){this.$(".date-nav .ui-button").off(),this.$(".dateToggleBtn").on("click",this.openPopover),this.$microRangePrev.off("click",this.onMicroRangePrevClick).disableSelection(),this.$microRangeNext.off("click",this.onMicroRangeNextClick).disableSelection(),this.$update.off("click",this.onUpdate),this.$cancel.off("click",this.onCancel),this.$rangeButtonset.find("input").off("change",this.onRangeChange),i("body").off("click",this.onBodyClick),this.rendered=!1,e.View.prototype.remove.apply(this,arguments)}})}),define("text!includes/statistics/statisticsFilterListItemTemplate.html",[],function(){return'<li>\n    <span class="title"><%- title %></span>\n    <span class="size"><%- size %></span>\n</li>\n'}),define("unifi/view/statistics/FilterNavView",["backbone","underscore","jquery","msg/Msg","ubnt/backgrid","text!includes/statistics/statisticsFilterListItemTemplate.html"],function(e,t,n,r,i,s){"use strict";return e.View.extend({initialize:function(e){t.bindAll(this),this.colors=e.colors,this.maxItemsToDisplay=10,this.collections=e.collections,this.collections.filtered={},this.collections.stats.site.on("sync",this.updateDeviceList),this.collections.stats.devices.on("sync change",this.updateDeviceList),this.collections.devices.on("sync change",this.updateDeviceList),this.render()},render:function(){var i=this;!this.rendered&&(this.rendered=!0)&&(this.$filterButton=this.$("button.filter"),this.$filterButton.on("click",this.openPopover),n("body").on("click",this.onBodyClick),this.$popover=this.$(".filter-popover"),this.$buttonset=this.$(".buttonset"),this.$buttonset.buttonset(),this.$buttonset.find("input").change(this.onChangeFilter),this.listItemTemplate=t.template(s),this.$listApplications=n("#listApplications").find(".list"),this.$listDevices=n("#listDevices").find(".list"),this.$listClients=n("#listClients").find(".list"),this.applicationCollection=new e.Collection([{title:"YouTube",size:"30GB",percentage:"30%"},{title:"Facebook",size:"20GB",percentage:"20%"},{title:"Netflix",size:"12GB",percentage:"12%"},{title:"Hulu",size:"8GB",percentage:"8%"},{title:"Google",size:"6GB",percentage:"6%"}]),this.clientsCollection=new e.Collection([{title:"mFi",size:"30GB",percentage:"30%"},{title:"RLDP",size:"20GB",percentage:"20%"},{title:"ubnt5-PC",size:"12GB",percentage:"12%"},{title:"mFi 10.1.6.31",size:"8GB",percentage:"8%"},{title:"android-99aeb09cc5054ac3",size:"6GB",percentage:"6%"}]),this.applicationCollection.each(function(e){i.$listApplications.append(i.listItemTemplate(e.toJSON()))}),this.clientsCollection.each(function(e){i.$listClients.append(i.listItemTemplate(e.toJSON()))}),this.$buttonfilter=this.$("button.filter"),this.$filterApplicationsLabel=this.$("label[for=filterApplications]"),this.$filterDevicesLabel=this.$("label[for=filterDevices]"),this.$filterClientsLabel=this.$("label[for=filterClients]"),this.$buttonfilter.find("span").after(r.G_Filter),this.$filterApplicationsLabel.find(".ui-button-text").text(r.G_StatsApplications),this.$filterDevicesLabel.find(".ui-button-text").text(r.G_Devices),this.$filterClientsLabel.find(".ui-button-text").text(r.G_Clients),this.$(".list-wrapper").on("click","li",this.onListItemClick),this.$listApplications.show())},updateClientList:function(){var n=this,r=this.collections.stats.clients.orderByBytes(),s={};n.$listClients.empty(),r=t.first(r,this.maxItemsToDisplay),t.each(r,function(e){s={title:"title",size:i.Formatters.Bytes.fromRaw(e.attributes.bytes),percentage:"0%"},n.$listClients.append(n.listItemTemplate(s))}),this.collections.filtered.clients=new e.Collection(r)},updateDeviceList:function(){var n=this,r=this.collections.stats.devices.orderByBytes(),s={},o;n.$listDevices.empty(),r=t.first(r,this.maxItemsToDisplay),t.each(r,function(e){o=n.collections.devices.getDeviceFromMac(e.attributes.ap),s={title:o?o.name():e.attributes.ap,size:i.Formatters.Bytes.fromRaw(e.attributes.bytes),percentage:"0%"},n.$listDevices.append(n.listItemTemplate(s))}),this.collections.filtered.devices=new e.Collection(r)},onChangeFilter:function(e){var t=n(e.target),r=t.val();r&&(this.$(".list-wrapper").hide(),this.$(".list-wrapper."+r).show())},onListItemClick:function(e){var t=n(e.currentTarget),r=t.parents("ul"),i=t.index(),s=this.$buttonset.find("input[name=filter]:checked").val(),o=this.collections.filtered[s].at(i),u=o.get("o"),a=t.hasClass("selected"),f,l,c;this.$el.find("li").removeClass("selected").css("background-color",""),a?(t.css("background-color",""),s=null,f=null,l=null,c=null):(t.addClass("selected").css("background-color",this.colors[i]),f=t.find(".title").text(),l=o.get(u),c=this.colors[i]),this.$el.trigger("change",{filter:s,name:f,oPropValue:l,color:c})},openPopover:function(e){e.preventDefault(),this.$popover.show(),this.$filterButton.addClass("ui-state-selected")},closePopover:function(){this.$popover.hide(),this.$filterButton.removeClass("ui-state-selected")},onBodyClick:function(e){var t=this,r=n(e.target);!r.hasClass("filter-popover")&&!r.parents(".filter-popover").length&&!r.hasClass("filter")&&!r.parents(".filter").length&&t.closePopover()},remove:function(){this.collections.stats.site.off("sync",this.updateDeviceList),this.collections.stats.devices.off("sync change",this.updateDeviceList),this.collections.devices.off("sync change",this.updateDeviceList),n("body").off("click",this.onBodyClick),this.$(".list-wrapper").off("click","li"),this.rendered=!1,e.View.prototype.remove.apply(this,arguments)}})}),define("text!includes/statistics/statisticsIndexTemplate.html",[],function(){return'<div class="section section-main">\n    <h1><%- msg.G_Stats %></h1>\n    <form class="data-filters clearfix">\n        <div class="left">\n            <select name="system">\n                <option value="overview"><%- msg.G_PropertiesOverview %></option>\n            </select>\n            <a id="clearCurrentStats" href="#" class="link"><%- msg.G_StatsClearCurrentStats %></a>\n        </div>\n\n        <div class="right">\n            <div id="datetimeNav" class="left is24Hr">\n                <%= statisticsDateNavTemplate %>\n            </div>\n            <%= statisticsFilterTemplate() %>\n        </div>\n    </form>\n\n    <div class="data-stats-group data-stats-group-top">\n        <div id="statsClientsTotal" class="data-stats-group-small">\n            <div class="data-stats-group-cell">\n                <h2><%- msg.G_StatsClientsTitle %></h2>\n            </div>\n            <div id="clientsTotalPieChart" class="data-stats-group-cell data-stats-group-cell-content">\n                <div class="more-data-needed-title"><%- msg.G_StatsMoreDataPoints %></div>\n                <div class="data-stats-content">\n                    <div class="piechart-legend"></div>\n                    <div class="piechart-wrapper">\n                        <div class="piechart-title"><%- msg.G_StatsNumOfClients %></div>\n                        <div class="piechart"></div>\n                    </div>\n                </div>\n            </div>\n        </div>\n        <div id="statsCurrentUsage" class="data-stats-group-medium">\n            <div class="data-stats-group-cell">\n                <h2><%- msg.G_StatsCurrentUsageTopAPS %></h2>\n            </div>\n            <div id="clientsCurrentUsagePieCharts" class="data-stats-group-cell data-stats-group-cell-content">\n                <div class="more-data-needed-title"><%- msg.G_StatsMoreDataPoints %></div>\n                <div class="data-stats-content">\n                    <div class="piechart-legend"></div>\n                    <div class="piechart-wrapper">\n                        <div class="piechart-title"><%- msg.G_StatsNumOfClients %></div>\n                        <div class="piechart piechart-numClients"></div>\n                    </div>\n                    <div class="piechart-wrapper">\n                        <div class="piechart-title"><%- msg.G_StatsTrafficTitle %></div>\n                        <div class="piechart piechart-traffic"></div>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n\n    <div class="data-stats-group data-stats-group-bottom">\n        <div id="statsQuickLook" class="data-stats-group-small">\n            <div class="data-stats-group-cell">\n                <h2><%- msg.G_StatsQuickLook %></h2>\n            </div>\n            <div class="data-stats-group-cell data-stats-group-cell-content">\n                <div class="more-data-needed-title"><%- msg.G_StatsMoreDataPoints %></div>\n                <ul class="data-stats-content">\n                    <li class="data-stats-most-active-ap">\n                        <h4><%- msg.G_StatsMostActiveAP %></h4>\n                        <div class="name link"></div>\n                        <div class="down"><div class="sprite-arrow-down"></div> <span class="value"></span></div>\n                        <div class="up"><div class="sprite-arrow-up"></div> <span class="value"></span></div>\n                    </li>\n                    <li class="data-stats-most-active-client">\n                        <h4><%- msg.G_StatsMostActiveClient %></h4>\n                        <div class="name link"></div>\n                        <div class="down"><div class="sprite-arrow-down"></div> <span class="value"></span></div>\n                        <div class="up"><div class="sprite-arrow-up"></div> <span class="value"></span></div>\n                    </li>\n                    <li class="data-stats-all-time-top-client">\n                        <h4><%- msg.G_StatsAllTimeTopClient %></h4>\n                        <div class="name link"></div>\n                        <div class="down"><div class="sprite-arrow-down"></div> <span class="value"></span></div>\n                        <div class="up"><div class="sprite-arrow-up"></div> <span class="value"></span></div>\n                        <div class="duration"></div>\n                    </li>\n                </ul>\n            </div>\n        </div>\n        <div id="statsCurrentUsage" class="data-stats-group-medium">\n            <div class="data-stats-group-cell">\n                <h2><%- msg.G_StatsRecentActivities %></h2>\n            </div>\n            <div class="data-stats-group-cell data-stats-group-cell-content">\n                <div class="data-grids">\n                    <div id="clientsGrid" />\n                    <div id="trafficGrid" />\n                </div>\n            </div>\n        </div>\n    </div>\n</div>\n'}),define("text!includes/statistics/statisticsDateNavTemplate.html",[],function(){return'<div>\n    <div class="date-nav buttonset date-micro-range">\n        <input type="radio" id="dateNavPrev<%- id %>"/><label for="dateNavPrev<%- id %>" class="prev"><span class="ubnt-icon-angle-left"></span></label>\n        <input type="radio" id="dateToggle<%- id %>" class="dateToggleBtn"><label for="dateToggle<%- id %>" class="dateToggle"><span class="ubnt-icon-calendar-2"></span>\n        <span class="dateRange1Hr">\n            <span class="hour"></span> <span class="datetime"></span>\n        </span>\n        <span class="dateRange24Hr">\n            <span class="datetimeMax"></span>\n        </span>\n        <span class="dateRangeMonth">\n            <span class="datetime"></span> - <span class="datetimeMax"></span>\n        </span>\n    </label>\n        <input type="radio" id="dateNavNext<%- id %>"/><label for="dateNavNext<%- id %>" class="next"><span class="ubnt-icon-angle-right"></span></label>\n    </div>\n    <div class="date-popover">\n        <div class="date-popover-content">\n            <div class="header left">\n                <span class="title left"></span>\n                <div class="buttonset range-buttonset">\n                    <input type="radio" id="dateRange1Hour<%- id %>" class="dateRange1HourBtn" value="1hr" />\n                    <label class="date-range-1hour" for="dateRange1Hour<%- id %>"></label>\n                    <input type="radio" id="dateRange24Hour<%- id %>" class="dateRange24HourBtn" value="24hr" checked="checked" />\n                    <label class="date-range-hour" for="dateRange24Hour<%- id %>"></label>\n                    <input type="radio" id="dateRange7Day<%- id %>" class="dateRange7DayBtn" value="7day" />\n                    <label class="date-range-7day" for="dateRange7Day<%- id %>"></label>\n                    <input type="radio" id="dateRangeMonth<%- id %>" class="dateRangeMonthBtn" value="month" />\n                    <label class="date-range-month" for="dateRangeMonth<%- id %>"></label>\n                </div>\n            </div>\n            <div class="date-micro-range left">\n                <div class="dateRange1Hr">\n                    <span class="prev ubnt-icon-angle-left"></span>\n                    <span class="hour"></span>\n                    <span class="next ubnt-icon-angle-right"></span>\n                    <span class="datetime"></span>\n                </div>\n                <div class="dateRange24Hr">\n                    <span class="prev ubnt-icon-angle-left"></span>\n                    <span class="datetimeMax"></span>\n                    <span class="next ubnt-icon-angle-right"></span>\n                </div>\n                <div class="dateRangeMonth">\n                    <span class="prev ubnt-icon-angle-left"></span>\n                    <span class="datetime"></span>\n                    -\n                    <span class="datetimeMax"></span>\n                    <span class="next ubnt-icon-angle-right"></span>\n                </div>\n            </div>\n            <div class="datepicker left"></div>\n        </div>\n        <div class="footer left">\n            <button class="button tall blue update"><span class="ubnt-icon-check ui-button-icon"></span></button>\n            <button class="button tall cancel"><span class="ubnt-icon-close ui-button-icon"></span></button>\n        </div>\n    </div>\n</div>'}),define("text!includes/statistics/statisticsFilterTemplate.html",[],function(){return'<div id="filterNav" class="left">\n    <button class="button ui-button ui-state-default filter">\n        <span class="ubnt-icon-graph ui-button-icon"></span>\n        \n    </button>\n    <div class="filter-popover">\n        <div class="buttonset left hidden">\n            <input type="radio" id="filterApplications" name="filter" value="applications" />\n            <label for="filterApplications"></label>\n            <input type="radio" id="filterDevices" name="filter" value="devices" checked="checked" />\n            <label for="filterDevices"></label>\n            <input type="radio" id="filterClients" name="filter" value="clients" />\n            <label for="filterClients"></label>\n        </div>\n        <div id="listApplications" class="list-wrapper applications hidden">\n            <ul class="left list"></ul>\n        </div>\n\n        <div id="listDevices" class="list-wrapper devices" style="display:block">\n            <ul class="left list"></ul>\n        </div>\n\n        <div id="listClients" class="list-wrapper clients hidden">\n            <ul class="left list"></ul>\n        </div>\n    </div>\n</div>'}),define("unifi/view/statistics/IndexView",["unifi/view/app/ContentView","underscore","jquery","libs/d3","libs/moment","msg/Msg","ubnt/backgrid","unifi/model/StatisticsColors","unifi/collection/stats/SiteStats","unifi/collection/stats/ClientStats","unifi/collection/stats/DeviceStats","unifi/view/statistics/LineChartView","unifi/view/statistics/PieChartView","unifi/view/statistics/DatetimeNavView","unifi/view/statistics/FilterNavView","text!includes/statistics/statisticsIndexTemplate.html","text!includes/statistics/statisticsDateNavTemplate.html","text!includes/statistics/statisticsFilterTemplate.html"],function(e,t,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g){"use strict";return e.extend({id:"statisticsIndex",charts:{},pieCharts:{},collections:{},intervals:{},_limitStart:"",_limitEnd:"",_limitRange:"",_limitFilter:"",_limitFilterName:"",_limitFilterValue:"",_limitFilterColor:"",_chartConfig:{margin:{top:22,right:50,bottom:30,left:10},widthOffset:-40,height:90,points:{off:0,on:7},overlays:{databox:{width:180,heightDiff:16,valueWidth:60}}},_pieChartConfig:{width:200,height:150,radius:70,colors:["#00acfc","#f8ad18","#c96353","#0bde9b","#7562ac"],legend:!0},initialize:function(r){e.prototype.initialize.call(this,r),this.updateCharts=t.debounce(this._updateCharts,300),this.colors=new u,this.collections.clients=this.options.app.collection("Clients"),this.collections.devices=this.options.app.collection("Devices"),this.collections.stats={},this.collections.stats.clients=this.options.app.collection("ClientStats",null,f),this.collections.stats.devices=this.options.app.collection("DeviceStats",null,l),this.collections.stats.site=this.options.app.collection("SiteStats",null,a),this.collections.stats.site.on("sync change",this.updateCharts),this.collections.stats.clients.on("sync change",this.updateStats),this.collections.stats.devices.on("sync change",this.updateStats),this.render(),this.clients(),this.traffic(),this.clientStats(),this.currentUsage(),this.calendar=new p({el:"#datetimeNav",useCurrentTimeForRange:!0}),this.calendar.$el.on("change",n.proxy(function(e,t){t&&(this._limitRange=t.range,this._limitStart=t.start,this._limitEnd=t.end,this.load())},this)),this.filterNav=new d({el:"#filterNav",colors:this.colors.getAllButFirst(),collections:this.collections}),this.filterNav.$el.on("change",n.proxy(function(e,t){t&&(this._limitFilter=t.filter,this._limitFilterName=t.name,this._limitFilterValue=t.oPropValue,this._limitFilterColor=t.color,this.updateCharts())},this));var i=this.calendar.getDateRange();this._limitRange=i.range,this._limitStart=i.start,this._limitEnd=i.end,this.load()},load:function(e){var r=[],i=this._limitRange=="24hr"?"hourly":"daily",s=[];e&&s.push(e),t.each(this.collections.stats,function(e,t){r.push(this.collections.stats[t][i]({silent:!0,data:{start:this._limitStart,end:this._limitEnd}})),s.push(function(){e.trigger("change")})},this),n.when.apply(null,r).done(function(){t.each(s,function(e){e()})})},render:function(){e.prototype.render.call(this);if(!this.rendered&&(this.rendered=!0)){var r=this;this.$el.html(t.template(v,{statisticsDateNavTemplate:t.template(m,{id:"statisticsDateNav"}),msg:s,statisticsFilterTemplate:t.template(g)})),this.$grids=this.$el.find(".data-grids"),this.$stats=this.$el.find(".data-stats"),this.$statsClientsTotal=this.$("#statsClientsTotal"),this.$statsCurrentUsage=this.$("#statsCurrentUsage"),this.$statsQuickLook=this.$("#statsQuickLook"),this.$mostActiveAp=this.$(".data-stats-most-active-ap"),this.$mostActiveClient=this.$(".data-stats-most-active-client"),this.$allTimeTopClient=this.$(".data-stats-all-time-top-client"),this.$clearCurrentStats=this.$("#clearCurrentStats"),this.$clearCurrentStats.on("click",this.clearCurrentStats),this.$el.find("select:not(.plain)").each(function(){var e=n(this),t=e.parent();e.selectmenu({parent:t,appendTo:t,label:e.data("label"),icons:{button:"ubnt-icon-arrow-down secondary-color"},position:{at:"left bottom",collision:"flip"},change:function(){e.trigger("change")}})}),n("#clientsGrid, #trafficGrid").on("mousemove",function(e){var i=e.pageX-n(this).offset().left,s=e.pageY-n(this).offset().top;t.each(r.charts,function(e){e.mouse=[i,s],e.updateOverlays()})}),this.$el.find(".data-grids").on("mouseleave",function(e){r.intervals.overlays||(r.intervals.overlays=setTimeout(function(){t.each(r.charts,function(e){e.hideOverlays()})},1e3))}).on("mouseenter",function(e){clearTimeout(r.intervals.overlays),delete r.intervals.overlays,t.each(r.charts,function(e){e.showOverlays()})}),n(window).resize(function(){r.charts.clients.update(!0),r.charts.traffic.update(!0)})}this.charts&&this.charts.clients&&this.charts.clients.update(!0),this.charts&&this.charts.traffic&&this.charts.traffic.update(!0)},clients:function(){var e=this,t=n("#clientsGrid");this.charts.clients=new c({el:t,config:{title:s.G_StatsClientsTitle,margin:this._chartConfig.margin,width:function(){return t.width()+e._chartConfig.widthOffset},height:this._chartConfig.height,ticksize:[0,0,0],points:this._chartConfig.points,overlays:{databox:this._chartConfig.overlays.databox},colors:[this.colors.first()]},data:{xprop:"datetime",yprop:"num_sta",idprop:"_id",labels:[s.G_StatsClientsLabel],points:[]}})},traffic:function(){var e=this,t=n("#trafficGrid");this.charts.traffic=new c({el:t,config:{title:s.G_StatsTrafficTitle,margin:this._chartConfig.margin,width:function(){return t.width()+e._chartConfig.widthOffset},height:this._chartConfig.height,ticksize:[6,0,0],points:this._chartConfig.points,overlays:{databox:this._chartConfig.overlays.databox,ticktip:{format:function(e,t){return t=="24hr"?i(e).format("hA"):i(e).format("MMM D")},width:{min:60,max:150,padding:20},height:26,bottom:-1}},colors:[this.colors.first()]},data:{xprop:"datetime",yprop:"bytesFmt",idprop:"_id",labelprop:"bytesLbl",labels:[s.G_StatsTrafficLabel],points:[]}})},_updateCharts:function(){var e=this._limitRange=="24hr"?3600:86400,n=this.collections.stats.site.toGraph({fill:!0,interval:e});if(n){this.charts.clients.data.points[0]=this.collections.stats.site.validatePointsHasProp(n,this.charts.clients.data.yprop)?t.clone(n):[],this.charts.traffic.data.points[0]=this.collections.stats.site.validatePointsHasProp(n,this.charts.traffic.data.yprop)?t.clone(n):[];if(this._limitRange=="24hr"){var r=[new Date(i(this._limitStart).startOf("hour")),new Date(i(this._limitEnd).startOf("hour"))];this.charts.clients.data.xDomain=r,this.charts.traffic.data.xDomain=r}else delete this.charts.clients.data.xDomain,delete this.charts.traffic.data.xDomain;if(this._limitFilter){var s=this.collections.stats[this._limitFilter];n=s.toGraph({filter:this._limitFilterValue,fill:!0,interval:e}),this.charts.clients.data.points[1]=s.validatePointsHasProp(n,this.charts.clients.data.yprop)?t.clone(n):[],this.charts.traffic.data.points[1]=s.validatePointsHasProp(n,this.charts.traffic.data.yprop)?t.clone(n):[],this.charts.clients.data.labels[1]=this._limitFilterName,this.charts.traffic.data.labels[1]=this._limitFilterName,this.charts.clients.config.colors[1]=this._limitFilterColor,this.charts.traffic.config.colors[1]=this._limitFilterColor}else this.charts.clients.data.points.length>1&&(this.charts.clients.data.points.pop(),this.charts.traffic.data.points.pop(),this.charts.clients.data.labels.pop(),this.charts.traffic.data.labels.pop(),this.charts.clients.config.colors.pop(),this.charts.traffic.config.colors.pop());this.charts.clients.config.range=this._limitRange,this.charts.traffic.config.range=this._limitRange,this.charts.clients.update(!0),this.charts.traffic.update(!0)}},updateStats:function(){this.apsSortByBytes=this.collections.devices.sortByBytesOnlyAps(),this.clientsSortedByBytes=this.collections.clients.sortByBytes(),this.clientsSortedByUptime=this.collections.clients.sortByUptime(),this.clientsByEssid=this.collections.clients.clientsPerEssidStats(),this.updatePieCharts(),this.updateQuickLook()},clientStats:function(){var e=n("#clientsTotalPieChart");this.pieCharts.clientStats=new h({el:e,config:{width:this._pieChartConfig.width,height:this._pieChartConfig.height,radius:this._pieChartConfig.radius,colors:this._pieChartConfig.colors,legend:this._pieChartConfig.legend,pieChart:".piechart"},data:{prop:"count",points:[]}})},updatePieCharts:function(){this._updateClientStats(),this._updateDeviceStats()},_updateClientStats:function(){var e=this.clientsByEssid.slice(0,5);this.pieCharts.clientStats&&e&&e.length?(this.pieCharts.clientStats.data.points=e,this.$statsClientsTotal.removeClass("more-data-needed"),this.pieCharts.clientStats.update()):this.$statsClientsTotal.addClass("more-data-needed")},_updateDeviceStats:function(){var e=this.apsSortByBytes.slice(0,5);this.pieCharts.numClients&&this.pieCharts.traffic&&e&&e.length?(this.pieCharts.numClients.data.points=e,this.pieCharts.traffic.data.points=e,this.$statsCurrentUsage.removeClass("more-data-needed"),this.pieCharts.numClients.update(),this.pieCharts.traffic.update()):this.$statsCurrentUsage.addClass("more-data-needed")},currentUsage:function(){var e=n("#clientsCurrentUsagePieCharts");this.pieCharts.numClients=new h({el:e,config:{width:this._pieChartConfig.width,height:this._pieChartConfig.height,radius:this._pieChartConfig.radius,colors:this._pieChartConfig.colors,legend:this._pieChartConfig.legend,pieChart:".piechart-numClients"},data:{prop:"num_sta",points:[]}}),this.pieCharts.traffic=new h({el:e,config:{width:this._pieChartConfig.width,height:this._pieChartConfig.height,radius:this._pieChartConfig.radius,colors:this._pieChartConfig.colors,legend:this._pieChartConfig.legend,pieChart:".piechart-traffic"},data:{prop:"bytes",formatBytes:!0,points:[]}})},updateQuickLook:function(){var e=this,t=0;this.apsSortByBytes&&this.apsSortByBytes.length&&this.apsSortByBytes[0].get("rx_bytes")>0&&this.apsSortByBytes[0].get("tx_bytes")>0?(this.$mostActiveAp.find(".name").off().on("click",function(){var t=e.apsSortByBytes[0],n=e.collections.devices,r=n.getDeviceFromMac(t.get("ap_mac"));r||(r=t),e.options.app.routers.devices.views.index.property(r)}).text(this.apsSortByBytes[0].name()),this.$mostActiveAp.find(".down .value").text(o.Formatters.Bytes.fromRaw(this.apsSortByBytes[0].get("tx_bytes"))),this.$mostActiveAp.find(".up .value").text(o.Formatters.Bytes.fromRaw(this.apsSortByBytes[0].get("rx_bytes"))),this.$mostActiveAp.show(),t++):this.$mostActiveAp.hide(),this.clientsSortedByBytes&&this.clientsSortedByBytes.length&&this.clientsSortedByBytes[0].get("rx_bytes")>0&&this.clientsSortedByBytes[0].get("tx_bytes")>0?(this.$mostActiveClient.find(".name").off().on("click",function(){var t=e.clientsSortedByBytes[0],n=e.options.app.collection("Clients"),r=n.getClientFromMac(t.get("mac"));r||(r=t),e.options.app.routers.clients.views.index.property(r)}).text(this.clientsSortedByBytes[0].name()),this.$mostActiveClient.find(".down .value").text(o.Formatters.Bytes.fromRaw(this.clientsSortedByBytes[0].get("tx_bytes"))),this.$mostActiveClient.find(".up .value").text(o.Formatters.Bytes.fromRaw(this.clientsSortedByBytes[0].get("rx_bytes"))),this.$mostActiveClient.show(),t++):this.$mostActiveClient.hide(),this.clientsSortedByUptime&&this.clientsSortedByUptime.length&&this.clientsSortedByUptime[0].get("rx_bytes")>0&&this.clientsSortedByUptime[0].get("tx_bytes")>0?(this.$allTimeTopClient.find(".name").off().on("click",function(){var t=e.clientsSortedByUptime[0],n=e.options.app.collection("Clients"),r=n.getClientFromMac(t.get("mac"));r||(r=t),e.options.app.routers.clients.views.index.property(r)}).text(this.clientsSortedByUptime[0].name()),this.$allTimeTopClient.find(".down .value").text(o.Formatters.Bytes.fromRaw(this.clientsSortedByUptime[0].get("tx_bytes"))),this.$allTimeTopClient.find(".up .value").text(o.Formatters.Bytes.fromRaw(this.clientsSortedByUptime[0].get("rx_bytes"))),this.$allTimeTopClient.find(".duration").text(o.Formatters.Duration.fromRaw(this.clientsSortedByUptime[0].get("uptime"))),this.$allTimeTopClient.show(),t++):this.$allTimeTopClient.hide(),t>0?this.$statsQuickLook.removeClass("more-data-needed"):this.$statsQuickLook.addClass("more-data-needed")},clearCurrentStats:function(){var e=this;return this.collections.stats.site.clearStats({success:function(t){t.meta.rc==="ok"&&(e.apsSortByBytes=[],e._updateDeviceStats())}}),!1},remove:function(){this.collections.stats.site.off("sync change",this.updateCharts),this.collections.stats.clients.off("sync change",this.updateStats),this.collections.stats.devices.off("sync change",this.updateStats),this.calendar.$el.off("change"),this.filterNav.$el.off("change"),this.$clearCurrentStats.off("click"),n("#clientsGrid, #trafficGrid").off("mousemove"),this.$el.find(".data-grids").off("mouseleave").off("mouseenter"),this.$mostActiveAp.find(".name").off(),this.$mostActiveClient.find(".name").off(),this.$allTimeTopClient.find(".name").off(),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/router/StatisticsRouter",["unifi/router/Router","unifi/view/statistics/IndexView"],function(e,t){"use strict";return e.extend({_fullyQualifiedName:"UNIFI.Routers.Statistics",_associatedViews:{Index:t},routes:{statistics:"index"}})}),define("text!includes/insights/insightsChromeTemplate.html",[],function(){return'<div class="section section-main">\n    <h1><%- msg.G_Insights %></h1>\n\n    <div class="subnav">\n        <select name="insights-dropdown" id="insightsDropdown">\n            <option value="knownclients" selected="selected"><%- msg.G_InsightsKnownClients %></option>\n            <option value="rogueaccesspoints"><%- msg.G_InsightsRogueAccessPoints %></option>\n            <option value="pastconnections"><%- msg.G_InsightsPastConnections %></option>\n            <option value="pastguestauthorizations"><%- msg.G_InsightsPastGuestAuthorizations %></option>\n            <option value="switchstats"><%- msg.G_InsightsSwitchStats %></option>\n            <option value="remoteuservpnstats"><%- msg.G_InsightsRemoteUserVPNStats %></option>\n            <option value="dynamicdnsstats"><%- msg.G_InsightsDynamicDNS %></option>\n        </select>\n    </div>\n\n    <form class="data-filters clearfix">\n        <span class="ubnt-icon-search"></span>\n        <input type="text" name="search" class="search left" />\n\n        <div class="knownclients data-filter left">\n            <div class="buttonset">\n                <input type="radio" id="knownClientsAll" name="client-table-filter-type" value="all" checked="checked"/>\n                <label for="knownClientsAll"><%- msg.G_All %></label>\n                <input type="radio" id="knownClientsBlocked" name="client-table-filter-type" value="blocked"/>\n                <label for="knownClientsBlocked"><%- msg.G_InsightsBlocked %></label>\n                <input type="radio" id="knownClientsNoted" name="client-table-filter-type" value="noted"/>\n                <label for="knownClientsNoted"><%- msg.G_Noted %></label>\n                <input type="radio" id="knownClientsUser" name="client-table-filter-type" value="user"/>\n                <label for="knownClientsUser"><%- msg.G_User %></label>\n                <input type="radio" id="knownClientsGuest" name="client-table-filter-type" value="guest"/>\n                <label for="knownClientsGuest"><%- msg.G_Guest %></label>\n                <input type="radio" id="knownStaticIP" name="client-table-filter-type" value="staticip"/>\n                <label for="knownStaticIP"><%- msg.G_PropertiesStaticIP %></label>\n            </div>\n\n            <div class="buttonset conn-filters">\n                <input type="radio" id="knownClientsConnAll" name="table-filter-conn" value="all" checked="checked" /><label for="knownClientsConnAll"><%- msg.G_All %></label>\n                <input type="radio" id="knownClientsConnWireless" name="table-filter-conn" value="wireless" /><label for="knownClientsConnWireless"><%- msg.G_Wireless %></label>\n                <input type="radio" id="knownClientsConnWired" name="table-filter-conn" value="wired" /><label for="knownClientsConnWired"><%- msg.G_Wired %></label>\n            </div>\n            <div>\n                <select name="knownClientsLastSeen" data-label="Last Seen: ">\n                    <option value="24" selected="selected"><%- msg.G_Insights1Day %></option>\n                    <option value="72"><%- msg.G_Insights3Days %></option>\n                    <option value="168"><%- msg.G_Insights7Days %></option>\n                    <option value="336"><%- msg.G_Insights2Weeks %></option>\n                    <option value="720"><%- msg.G_Insights1Month %></option>\n                    <option value="1400"><%- msg.G_Insights2Months %></option>\n                    <option value="87600"><%- msg.G_InsightsAll %></option>\n                </select>\n            </div>\n        </div>\n\n        <div class="rogueaccesspoints data-filter left">\n            <div>\n                <select name="rogueAccessPointsLastSeen" data-label="Last Seen: ">\n                    <option value="24"><%- msg.G_Insights1Day %></option>\n                    <option value="72"><%- msg.G_Insights3Days %></option>\n                    <option value="168" selected="selected"><%- msg.G_Insights7Days %></option>\n                    <option value="336"><%- msg.G_Insights2Weeks %></option>\n                    <option value="720"><%- msg.G_Insights1Month %></option>\n                    <option value="1400"><%- msg.G_Insights2Months %></option>\n                    <option value="87600"><%- msg.G_InsightsAll %></option>\n                </select>\n            </div>\n        </div>\n\n        <div class="pastconnections data-filter left">\n            <div class="buttonset">\n                <input type="radio" id="pastConnectionsAll" name="table-filter-type" value="all" checked="checked"/>\n                <label for="pastConnectionsAll"><%- msg.G_All %></label>\n                <input type="radio" id="pastConnectionsUser" name="table-filter-type" value="user"/>\n                <label for="pastConnectionsUser"><%- msg.G_User %></label>\n                <input type="radio" id="pastConnectionsGuest" name="table-filter-type" value="guest"/>\n                <label for="pastConnectionsGuest"><%- msg.G_Guest %></label>\n            </div>\n\n            <div id="pastconnections-datetimeNav" class="left is24Hr">\n                <%= pastConnectionsCalendarTemplate %>\n            </div>\n        </div>\n\n        <div class="pastguestauthorizations data-filter left">\n            <div id="pastguestauthorizations-datetimeNav" class="left is24Hr">\n                <%= pastGuestAuthorizationsCalendarTemplate %>\n            </div>\n        </div>\n\n        <div class="switchstats data-filter left">\n            <div class="switch-filter left">\n                <select name="switch-filter" class="wide" data-label="<%- msg.G_InsightsSwitch %>: "></select>\n            </div>\n\n            <div class="network-link-filter left">\n                <select name="network-link-filter" class="wide" data-label="<%- msg.G_InsightsNetworkLinkStatus %>: "></select>\n            </div>\n\n            <div class="buttonset switch-subtab-filters">\n                <input type="radio" id="switchFilterOverview" name="switch-subtab-filter" value="overview" checked="checked" /><label for="switchFilterOverview"><%- msg.G_DevicesOverview %></label>\n                <input type="radio" id="switchFilterPOE" name="switch-subtab-filter" value="poe" /><label for="switchFilterPOE">POE</label>\n                <input type="radio" id="switchFilterCounters" name="switch-subtab-filter" value="counters" /><label for="switchFilterCounters"><%- msg.G_InsightsCounters %></label>\n            </div>\n\n            <div class="poe-filter left">\n                <select name="poe-filter" class="wide" data-label="<%- msg.G_InsightsPoeMode %>: "></select>\n            </div>\n\n            <div class="clear-counters left">\n                <select class="clear-counters" name="clear-counters" data-label="<%- msg.G_InsightsClearCounters %>: "></select>\n            </div>\n        </div>\n\n        <div class="remoteuservpnstats data-filter left">\n        </div>\n\n        <div class="dynamicdnsstats data-filter left">\n        </div>\n\n        <div class="right">\n            <select name="items-per-page" data-label="<%- msg.G_FilterItemsPerPage %>">\n                <option value="10">10</option>\n                <option value="50" selected="selected">50</option>\n                <option value="100">100</option>\n                <option value="200">200</option>\n            </select>\n        </div>\n    </form>\n\n    <div id="insightsContent" class="">\n        <!-- insights content -->\n    </div>\n\n</div>\n'}),define("unifi/view/insights/ChromeView",["unifi/view/app/ContentView","underscore","jquery","msg/Msg","text!includes/insights/insightsChromeTemplate.html","text!includes/statistics/statisticsDateNavTemplate.html",""],function(e,t,n,r,i,s){"use strict";return e.extend({id:"insightsChrome",_templateId:i,_contentView:null,initialize:function(t){e.prototype.initialize.call(this,t),this.render()},render:function(){e.prototype.render.call(this);if(!this.rendered&&(this.rendered=!0)){var i=this,o=t.template(s,{id:"pastconnections"}),u=t.template(s,{id:"pastguestauthorizations"});this.$el.html(t.template(this._templateId,{pastConnectionsCalendarTemplate:o,pastGuestAuthorizationsCalendarTemplate:u,msg:r})),this.$content=this.$el.find("#insightsContent"),this.$el.find(".buttonset").buttonset(),this.$el.find("form.data-filters").on("submit",function(e){e.preventDefault()}),this.$search=this.$el.find("input[name=search]"),this.$search.on("keyup",t.debounce(this.filter,300)),this.$insightsDropdown=this.$el.find("#insightsDropdown"),this.$insightsDropdown.on("change",function(e){e.preventDefault();var t=n(this).val();i.navigate(t),i.app.routers.insights.navigate("insights/"+t,{trigger:!0})})}},renderSelects:function(){n("#insightsChrome .section").find("select:visible").each(function(){var e=n(this),t=e.parent(),r=e.data("selectRendered"),i=e.data("myposition")||"left top";r||(e.selectmenu({parent:t,appendTo:t,label:e.data("label"),icons:{button:"ubnt-icon-arrow-down secondary-color"},position:{my:i,at:"left bottom",collision:"flip"},change:function(t,n){e.trigger("change")}}),e.data("selectRendered",!0).trigger("change",!0))})},navigate:function(e){this.$insightsDropdown.val()!=e&&this.$insightsDropdown.val(e).change(),this.$content.find("> div").hide(),this.$content.find("#"+e).show(),this.$(".section").attr("id","insights"+e),this.renderSelects()},filter:function(){this._contentView&&this._contentView.filter.call(this,null,this.$search.val())},remove:function(){t.each(this.views,function(e){e.remove&&e.remove()},this),this.views={},this.$el.find("form.data-filters").off("submit"),this.$search.off("keyup"),this.$insightsDropdown.off("change"),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("text!includes/insights/knownClientsTemplate.html",[],function(){return'<div class="data-table untitled">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n</div>'}),define("unifi/view/insights/KnownClientsView",["unifi/view/app/ListContentView","unifi/view/clients/IndexView","libs/backgrid","ubnt/backgrid","underscore","jquery","unifi/collection/insights/KnownClients","text!includes/insights/knownClientsTemplate.html","msg/Msg"],function(e,t,n,r,i,s,o,u,a){"use strict";return t.extend({id:"knownclients",_templateId:u,_collectionType:{name:"KnownClients",Class:o},_pageable:!0,_limitType:"all",_limitConn:"all",_limitTimeframe:"24",_includeTimeframe:!0,_filterMinimum:.1,initialize:function(e){var n=this;this.$insightsChrome=s("#insightsChrome"),t.prototype.initialize.call(this,e),this.$el.removeClass("content"),this.listenTo(this.collection,"sync",this.mergeClients),this.listenTo(this.collection,"change:blocked",this.handleBlockedChange),this.listenTo(this.options.app.collection("Clients"),"change:name",function(e){n.grids.content.$el.find('.column-name[title="'+e.get("mac")+'"]').text(e.name())})},columns:function(){var e=this;return[{name:"mac",customClass:"column-name",label:a.G_InsightsNameMACAddress,editable:!1,cell:r.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.options.app.collection("Clients"),r=n.getClientFromMac(t.get("mac"));return r||(r=t),r.name()},toRaw:function(e){return e}}}),callback:function(t){var n=e.options.app.collection("Clients"),r=n.getClientFromMac(t.get("mac"));r?r.set({blocked:t.get("blocked")},{silent:!0}):r=t,e.options.app.routers.clients.views.index.property(r)},title:"mac"},{name:"oui",label:a.G_InsightsManufacturer,editable:!1,cell:"string"},{name:"is_guest",label:a.G_UserGuest,editable:!1,cell:r.Cells.ModelCell.extend({callback:"userOrGuest"})},{name:"tx_bytes",label:a.G_Down,editable:!1,cell:n.StringCell.extend({formatter:r.Formatters.Bytes})},{name:"rx_bytes",label:a.G_Up,editable:!1,cell:n.StringCell.extend({formatter:r.Formatters.Bytes})},{name:"last_seen",label:a.G_LastSeen,editable:!1,cell:r.Cells.ModelCell.extend({callback:"absoluteLastSeen"})},{name:"_id",label:a.G_Actions,editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.ActionsCell.extend({actions:{unblock:{icon:"ubnt-icon-close",callback:this.rowUnblock,requiresAdminPrivilege:!0,render:function(e){return e.get("blocked")}},block:{icon:"ubnt-icon-close",callback:this.rowBlock,requiresAdminPrivilege:!0,render:function(e){return!e.get("blocked")}}}})}]},render:function(){var e=this.rendered;e||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),t.prototype.render.call(this);if(!e){var n=this.options.app.collection("Clients"),r=this,i;this.$inputFilterType=this.$insightsChrome.find('.knownclients input[name="client-table-filter-type"]').on("change",function(){var e=s(this).val(),t=r._limitType,n=r.grids.content;r.$lastSeenDropdownParent||(r.$lastSeenDropdownParent=r.$lastSeenDropdown.parents(".ui-selectmenu-parent:first")),r._limitType=e,n.removeFilter("blocked",!0),n.removeFilter("noted",!0),n.removeFilter("is_guest",!0),n.removeFilter("use_fixedip",!0),n.removeFilter("is_guest",!0);switch(e){case"blocked":n.setFilter("blocked",!0,1),r.$lastSeenDropdownParent.hide(),r._includeTimeframe=!1;break;case"noted":n.setFilter("noted",!0,1),r.$lastSeenDropdownParent.hide(),r._includeTimeframe=!1;break;case"user":n.setFilter("is_guest",!1,1),r.$lastSeenDropdownParent.show(),r._includeTimeframe=!0;break;case"guest":n.setFilter("is_guest",!0,1),r.$lastSeenDropdownParent.show(),r._includeTimeframe=!0;break;case"staticip":n.setFilter("use_fixedip",!0,1),r.$lastSeenDropdownParent.hide(),r._includeTimeframe=!1;break;case"all":r.$lastSeenDropdownParent.show(),r._includeTimeframe=!0}r._includeTimeframe&&(r._limitTimeframe=Math.max(parseInt(r.$lastSeenDropdown.find("option:selected").val(),10),24)),r.load(!0)}),this.$inputFilterWired=this.$insightsChrome.find('.knownclients input[name="table-filter-conn"]').on("change",function(){var e=s(this).val(),t=r._limitConn,n=r.grids.content;r._limitConn=e,n.removeFilter("is_wired",!0);switch(e){case"wired":n.setFilter("is_wired",!0,1,!1,!0);break;case"wireless":n.setFilter("is_wired",!0,-1,!1,!0);break;case"all":}r.load(!0)}),this.$lastSeenDropdown=this.$insightsChrome.find('.knownclients select[name="knownClientsLastSeen"]').on("change",function(){r._limitTimeframe=Math.max(parseInt(s(this).find("option:selected").val(),10),24),r.load(!0)}),this.$lastSeenDropdownParent=null}},load:function(e){e=e||!this.collection;if(!this.collection||e){var n={type:this._limitType,conn:this._limitConn};this._includeTimeframe&&(n.within=this._limitTimeframe),t.prototype.load.call(this,e,{data:n})}},mergeClients:function(){this.clients=this.options.app.collection("Clients"),this.clients&&this.clients.each(function(e){this.collection.add(e,{merge:!0})},this)},grid:function(){e.prototype.grid.call(this)},handleBlockedChange:function(){this._limitType=="blocked"&&this.grids.content._filter()},remove:function(){this.stopListening(this.collection),this.stopListening(this.options.app.collection("Clients")),this.$inputFilterType=this.$insightsChrome.find('.knownclients input[name="client-table-filter-type"]').off("change"),this.$insightsChrome.find('.knownclients input[name="table-filter-conn"]').off("change"),this.$insightsChrome.find('.knownclients select[name="knownClientsLastSeen"]').off("change"),this.rendered=!1,t.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/RogueAccessPoint",["unifi/model/Device","backbone","ubnt/backgrid","libs/moment","msg/Msg"],function(e,t,n,r,i){"use strict";return e.extend({toSearch:function(){return{name:this.name(),essid:this.essid(),bssid:this.attributes.bssid,mac:this.attributes.mac,ip:this.attributes.ip,location:this.attributes.ap_mac,lastSeen:this.absoluteLastSeen(),oui:this.attributes.oui}},essid:function(){return this.get("essid")||"<hidden>"},channelWithRadio:function(){return this.get("channel")+" ("+this.get("radio")+")"},type:function(){return this.get("security")+(this.get("is_adhoc")?" (Ad-Hoc)":"")}})}),define("unifi/collection/insights/RogueAccessPoints",["backbone","underscore","unifi/collection/Devices","unifi/model/insights/RogueAccessPoint"],function(e,t,n,r){"use strict";return n.extend({model:r,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/rogueap"},sync:function(n,r,i){i=i||{};switch(n){case"read":i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{}))}return e.sync.call(this,n,r,i)}})}),define("text!includes/insights/rogueAccessPointsTemplate.html",[],function(){return'<div class="data-table untitled">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n</div>'}),define("unifi/view/insights/RogueAccessPointsView",["unifi/view/app/ListContentView","libs/backgrid","ubnt/backgrid","underscore","jquery","msg/Msg","unifi/collection/insights/RogueAccessPoints","text!includes/insights/rogueAccessPointsTemplate.html"],function(e,t,n,r,i,s,o,u){"use strict";return e.extend({id:"rogueaccesspoints",_templateId:u,_collectionType:{name:"Rogueaccesspoints",Class:o},_pageable:!0,_limitTimeframe:"24",initialize:function(t){this.$insightsChrome=i("#insightsChrome"),e.prototype.initialize.call(this,t),this.$el.removeClass("content")},columns:function(){var e=this;return[{name:"essid",label:s.G_InsightsNameSSI,editable:!1,cell:n.Cells.ModelCell.extend({callback:"essid"})},{name:"bssid",label:s.G_InsightsBSSID,editable:!1,cell:"string"},{name:"channel",label:s.G_Channel,editable:!1,cell:n.Cells.ModelCell.extend({callback:"channelWithRadio"})},{name:"security",label:s.G_InsightsRogueType,editable:!1,cell:n.Cells.ModelCell.extend({callback:"type"})},{name:"oui",label:s.G_InsightsManufacturer,editable:!1,cell:"string"},{name:"ap_mac",label:s.G_InsightsLocation,editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.options.app.collection("Devices"),r=n.getDeviceFromMac(t.get("ap_mac"));return"near "+(r?r.name():t.get("ap_mac"))},toRaw:function(e){return e}}})},{name:"rssi",label:s.G_Signal,customClass:"column-signal",editable:!1,cell:n.Cells.ComplexHtmlCell.extend({className:"rssiWithRadio",formatter:{fromRaw:function(e){var t=e.get("rssi"),n=e.get("radio"),r="sprite-";return r+=n+"-"+(n==="na"?"5g":"2g"),'<span class="signal-value">'+t+'</span><span class="signal-icon '+r+'"></span>'},toRaw:function(e){return e}}})},{name:"last_seen",label:s.G_InsightsLastSeen,editable:!1,cell:n.Cells.ModelCell.extend({callback:"absoluteLastSeen"})}]},render:function(){var t=this.rendered;t||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),e.prototype.render.call(this);if(!t){var n=this;this.$lastSeenDropdown=this.$insightsChrome.find('.rogueaccesspoints select[name="rogueAccessPointsLastSeen"]').on("change",function(){n._limitTimeframe=Math.max(parseInt(i(this).find("option:selected").val(),10),24),n.load(!0)})}},load:function(t){t=t||!this.collection,(!this.collection||t)&&e.prototype.load.call(this,t,{data:{within:this._limitTimeframe}})},searchable:function(){var t=i.proxy(function(e){var t=this.options.app.collection("Devices").getDeviceFromMac(e.get("ap_mac"));t&&e.addSearchString("near",t.name()),e.addSearchString("channel",e.channelWithRadio()),e.addSearchString("type",e.type())},this),n=i.proxy(function(){this.collection.each(t),this.trigger("search:indexed")},this);this.listenTo(this.collection,"change",t),this.listenTo(this.collection,"add",t),this.listenTo(this.collection,"reset",n),n(),e.prototype.searchable.call(this)},remove:function(){this.$insightsChrome.find('.rogueaccesspoints select[name="rogueAccessPointsLastSeen"]').off("change"),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/PastConnection",["unifi/model/Client","backbone","ubnt/backgrid","libs/moment"],function(e,t,n,r){"use strict";return e.extend({toSearch:function(){return{name:this.name(),mac:this.attributes.mac,is_guest:this.isGuest(),assoc_time:n.Formatters.Moment.fromRaw(this.attributes.assoc_time)}}})}),define("unifi/collection/insights/PastConnections",["backbone","underscore","unifi/collection/Clients","unifi/model/insights/PastConnection"],function(e,t,n,r){"use strict";return n.extend({model:r,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/session"},sync:function(n,r,i){i=i||{};switch(n){case"read":i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{}))}return e.sync.call(this,n,r,i)}})}),define("text!includes/insights/pastConnectionsTemplate.html",[],function(){return'<div class="data-table untitled">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n</div>'}),define("unifi/view/insights/PastConnectionsView",["unifi/view/app/ListContentView","libs/backgrid","ubnt/backgrid","underscore","jquery","msg/Msg","unifi/collection/insights/PastConnections","text!includes/insights/pastConnectionsTemplate.html","unifi/view/statistics/DatetimeNavView"],function(e,t,n,r,i,s,o,u,a){"use strict";return e.extend({id:"pastconnections",_templateId:u,_collectionType:{name:"PastConnections",Class:o},_pageable:!0,_limitType:"all",_limitStart:null,_limitEnd:null,initialize:function(t){this.$insightsChrome=i("#insightsChrome"),e.prototype.initialize.call(this,t),this.$el.removeClass("content")},columns:function(){var e=this;return[{name:"mac",label:s.G_InsightsNameMACAddress,editable:!1,sortValue:"name",headerCell:n.Headers.customSortHeader,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.options.app.collection("Clients"),r=n.getClientFromMac(t.get("mac"));return r||(r=t),r.name()},toRaw:function(e){return e}}}),callback:function(t){var n=e.options.app.collection("Clients"),r=n.getClientFromMac(t.get("mac"));r?r.set({blocked:t.get("blocked")},{silent:!0}):r=t,e.options.app.routers.clients.views.index.property(r)},title:"mac"},{name:"is_guest",label:s.G_UserGuest,editable:!1,cell:n.Cells.ModelCell.extend({callback:"userOrGuest"})},{name:"assoc_time",label:s.G_InsightsAssociated,editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Moment})},{name:"duration",label:s.G_Duration,editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Duration})},{name:"tx_bytes",label:s.G_Down,editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"rx_bytes",label:s.G_Up,editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"ip",label:s.G_IP,editable:!1,sortValue:"ip2long",headerCell:n.Headers.customSortHeader,cell:"string"},{name:"ap_mac",label:s.G_InsightsLastAPPort,customClass:"column-apport",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.app.collection("Devices"),r;if(!t.get("is_wired"))return r=t.get("ap_mac")?n.getDeviceFromMac(t.get("ap_mac")):null,r?r.name():t.get("ap_mac");if(t.get("sw_mac"))return(r=n.getDeviceFromMac(t.get("sw_mac")))?r.name()+t.switch_port_suffix(!1):t.get("sw_mac");if(t.get("gw_mac"))return(r=n.getDeviceFromMac(t.get("gw_mac")))?r.name():t.get("gw_mac")},toRaw:function(e){return e}}}),callback:function(t){var n=e.app.routers.devices.views.index,r;t.get("is_wired")?(r=n.collection.getDeviceFromMac(t.get("sw_mac")?t.get("sw_mac"):t.get("gw_mac")),n.property(r,{port:t.get("sw_mac")?t.get("sw_port"):"lan"})):(r=n.collection.getDeviceFromMac(t.get("ap_mac")),n.property(r))}}]},render:function(){var t=this.rendered;t||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),e.prototype.render.call(this);if(!t){var n=this;this.$inputFilterType=this.$insightsChrome.find('.pastconnections input[name="table-filter-type"]').on("change",function(){n._limitType=i(this).val(),n.load(!0)}),this.calendar=new a({el:"#pastconnections-datetimeNav",is7Day:!0});var r=this.calendar.getDateRange();r&&(n._limitStart=r.start,n._limitEnd=r.end,n.load(!0)),this.calendar.$el.on("change",function(e,t){t&&(n._limitStart=t.start,n._limitEnd=t.end,n.load(!0))})}},load:function(t){t=t||!this.collection,(!this.collection||t)&&this._limitStart&&this._limitEnd&&(this.collection&&this.collection.reset(),e.prototype.load.call(this,t,{data:{type:this._limitType,start:this._limitStart/1e3,end:this._limitEnd/1e3}}))},remove:function(){this.$insightsChrome.find('.pastconnections input[name="table-filter-type"]').off("change"),this.calendar.$el.off("change"),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/model/Guest",["unifi/model/Model","backbone","ubnt/backgrid"],function(e,t,n){"use strict";return e.extend({name:function(){return this.get("name")||this.get("hostname")||this.get("mac")},authorization:function(){var e,t,r,i;switch(this.get("authorized_by")){case"none":return"None";case"password":return"Password";case"api":return"API";case"voucher":return t=this.get("voucher_code"),e="Voucher",t&&(e+="["+t+"]"),e;case"credit":return r=this.get("package"),i=this.get("amount"),e=this.get("payment_cardtype")||"Credit Card",r&&i&&(e+="("+r+","+n.Formatters.Currency.fromRaw(this)+")"),e;case"paypal":return"PayPal";default:return"None"}},extend:function(e){return this.sync("extend",this,e)},sync:function(e,n,r){switch(e){case"delete":r.contentType="application/json; charset=utf-8",r.type="POST",r.url="/api/s/"+SITE.name+"/cmd/hotspot",r.data=JSON.stringify({_id:n.id,cmd:"terminate"});break;case"extend":r.contentType="application/json; charset=utf-8",r.type="POST",r.url="/api/s/"+SITE.name+"/cmd/hotspot",r.data=JSON.stringify({_id:n.id,cmd:"extend"})}return t.sync.call(this,e,n,r)},toSearch:function(){return{name:this.attributes.name,ap:this.attributes.ap_mac,"package":this.attributes.package,amount:this.attributes.amount,authorization:this.authorization(),mac:this.attributes.mac,hostname:this.attributes.hostname}}})}),define("unifi/collection/Guests",["unifi/collection/Collection","backbone","unifi/model/Guest"],function(e,t,n){"use strict";return e.extend({model:n,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/guest"},sync:function(e,n,r){switch(e){case"read":r.type="POST",r.data=JSON.stringify(r.data)}return t.sync.call(this,e,n,r)}})}),define("unifi/model/insights/PastGuestAuthorization",["unifi/model/Guest","backbone","ubnt/backgrid","libs/moment"],function(e,t,n,r){"use strict";return e.extend({toSearch:function(){return{name:this.attributes.name,hostname:this.attributes.hostname,mac:this.attributes.mac,ap:this.attributes.ap_mac,"package":this.attributes.package,amount:this.attributes.amount,authorization:this.authorization()}}})}),define("unifi/collection/insights/PastGuestAuthorizations",["backbone","underscore","unifi/collection/Guests","unifi/model/insights/PastGuestAuthorization"],function(e,t,n,r){"use strict";return n.extend({model:r,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/authorization"},sync:function(n,r,i){i=i||{};switch(n){case"read":i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{}))}return e.sync.call(this,n,r,i)}})}),define("text!includes/insights/pastGuestAuthorizationsTemplate.html",[],function(){return'<div class="data-table untitled">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n</div>'}),define("unifi/view/insights/PastGuestAuthorizationsView",["unifi/view/app/ListContentView","libs/backgrid","ubnt/backgrid","underscore","jquery","msg/Msg","unifi/collection/insights/PastGuestAuthorizations","text!includes/insights/pastGuestAuthorizationsTemplate.html","unifi/view/statistics/DatetimeNavView"],function(e,t,n,r,i,s,o,u,a){"use strict";return e.extend({id:"pastguestauthorizations",_templateId:u,_collectionType:{name:"PastGuestAuthorizations",Class:o},_pageable:!0,initialize:function(t){this.$insightsChrome=i("#insightsChrome"),e.prototype.initialize.call(this,t),this.$el.removeClass("content")},columns:function(){var e=this;return[{name:"mac",label:s.G_InsightsNameMACAddress,editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.options.app.collection("Clients"),r=n.getClientFromMac(t.get("mac"));return r||(r=t),r.name()},toRaw:function(e){return e}}}),callback:function(t){var n=e.options.app.collection("Clients"),r=n.getClientFromMac(t.get("mac"));r?r.set({blocked:t.get("blocked")},{silent:!0}):r=t,e.options.app.routers.clients.views.index.property(r)},title:"mac"},{name:"package",label:s.G_Package,editable:!1,cell:"string"},{name:"amount",label:s.G_Amount,editable:!1,cell:n.Cells.ComplexCell.extend({formatter:n.Formatters.Currency})},{name:"authorized_by",label:s.G_InsightsAuthorizedBy,editable:!1,cell:n.Cells.ModelCell.extend({callback:"authorization"})},{name:"start",label:s.G_Start,editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Moment})},{name:"duration",label:s.G_Duration,editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Duration})},{name:"tx_bytes",label:s.G_Down,editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"rx_bytes",label:s.G_Up,editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"ip",label:s.G_IP,editable:!1,cell:"string"},{name:"ap_mac",label:s.G_InsightsLastAP,editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.options.app.collection("Devices"),r=n.getDeviceFromMac(t.get("ap_mac"));return r||(r=t),r.name()},toRaw:function(e){return e}}}),callback:function(t){var n=e.options.app.collection("Devices"),r=n.getDeviceFromMac(t.get("ap_mac"));r||(r=t),e.options.app.routers.devices.views.index.property(r)}}]},render:function(){var t=this.rendered;t||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),e.prototype.render.call(this);if(!t){var n=this;this.calendar=new a({el:"#pastguestauthorizations-datetimeNav",is7Day:!0});var r=this.calendar.getDateRange();r&&(n._limitStart=r.start,n._limitEnd=r.end,n.load(!0)),this.calendar.$el.on("change",function(e,t){t&&(n._limitStart=t.start,n._limitEnd=t.end,n.load(!0))})}},load:function(t){t=t||!this.collection,(!this.collection||t)&&this._limitStart&&this._limitEnd&&(this.collection&&this.collection.reset(),e.prototype.load.call(this,t,{data:{start:this._limitStart/1e3,end:this._limitEnd/1e3}}))},remove:function(){this.calendar.$el.off("change"),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/SwitchStats",["underscore","unifi/model/PortModel","ubnt/backgrid","msg/Msg"],function(e,t,n,r){"use strict";return t.extend({initialize:function(t,n){this.on("change:device change:port_idx",e.bind(this.generateId,this))},speed:function(){if(this.get("up")){var e=this.get("speed");return e<1e3?e+="M":(e/=1e3,e+="G"),e}return""},linkUsage:function(e){var t,n;return this.get("up")?(e==="tx"?t=this.get("tx_bytes-r"):e==="rx"?t=this.get("rx_bytes-r"):t=this.get("bytes-r"),n=t*8*100/(this.get("speed")*1024*1024),n.toFixed(2)):0},opMode:function(){return this.get("aggregated_by")?"aggregate":this.get("op_mode")||"switch"},opModeText:function(){var e=this.opMode();return e==="switch"?r.G_PropertiesSwitching:e==="aggregate"?r.G_PropertiesAggregate:e==="mirror"?r.G_PropertiesMirroring:""},poeMode:function(){return this.get("port_poe")?this.get("op_mode")!=="switch"||this.get("masked")?"":this.get("poe_mode")||"off":""},poeModeText:function(){var e=this.poeMode();return e==="auto"?r.G_PropertiesPoEModePoEPlus:e==="pasv24"?r.G_PropertiesPoEModePassive:r.G_InsightsPoeDisabled},isPDDetected:function(){return this.poeMode()==="auto"&&this.get("poe_enable")},poeDetection:function(){var e=this.poeMode();return e==="auto"?this.get("poe_enable")?this.get("poe_good")?r.G_InsightsPoeGood:r.G_InsightsPoeCpdHigh:r.G_InsightsPoeNotDetected:e==="pasv24"?r.G_InsightsPoePassive:""},isPoeEnabled:function(){return this.poeMode()!=="off"&&this.poeMode()!==""},isPassivePoe:function(){return this.poeDetection()=="Passive"},isPoePowerOn:function(){return this.isPassivePoe()||this.isPDDetected()},poeVoltage:function(){var e=this.poeMode();return this.isPDDetected()||e==="pasv24"?this.get("poe_voltage"):""},generateId:function(){this.set("id",this.get("device")+"-"+this.get("port_idx"))}})}),define("unifi/collection/insights/SwitchStats",["backbone","underscore","unifi/collection/Collection","unifi/model/insights/SwitchStats"],function(e,t,n,r){"use strict";return n.extend({model:r,bySite:!0})}),define("text!includes/insights/switchStatsTemplate.html",[],function(){return'<div class="data-table untitled">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n</div>'}),define("unifi/view/insights/SwitchStatsView",["unifi/view/app/ListContentView","libs/backgrid","ubnt/backgrid","ubnt/view/dialogs/ConfirmDialogView","underscore","jquery","msg/Msg","unifi/collection/PortConf","unifi/collection/insights/SwitchStats","text!includes/insights/switchStatsTemplate.html"],function(e,t,n,r,i,s,o,u,a,f){"use strict";return e.extend({id:"switchstats",_templateId:f,_collectionType:{name:"SwitchStats",Class:a},_pageable:!0,initialize:function(t){this.$insightsChrome=s("#insightsChrome"),e.prototype.initialize.call(this,t),this.$el.removeClass("content")},load:function(e,t){if(this._loaded.state()==="resolved")return;this.collection=new a,this.devices=this.app.collection("Devices"),this.devices&&i.each(this.devices.where({type:this.devices.typeMap["switch"]}),this.onSwitchAdd),this.listenTo(this.devices,"add",this.onSwitchAdd),this.listenTo(this.devices,"remove",this.onSwitchRemove),this.listenTo(this.devices,"add remove change",function(){this.trigger("device_change")}),this._loaded.resolve()},onSwitchAdd:function(e){e.get("type")===e.typeMap["switch"]&&(this.listenTo(e,"syncPortTable",s.proxy(function(){this.resetSwitchStats(e)},this)),this.resetSwitchStats(e))},onSwitchRemove:function(e){e.get("type")===e.typeMap["switch"]&&(this.collection.remove(this.collection.where({device:e.get("mac")})),this.stopListening(e,"syncPortTable"))},resetSwitchStats:function(e){var t=this.collection.where({device:e.get("mac")});e.collections.portTable.each(function(e){var n=i.find(t,function(t){return e.get("port_idx")===t.get("port_idx")});n?n.set(e.attributes):this.collection.add(e.toJSON())},this)},dependencies:function(){var e={PortConf:u},t=[],n={},r=this;i.each(e,function(e,r){t.push(n[r]=s.Deferred())},this),s.when.apply(s,t).then(function(){r._dependencies.resolve()},function(){r._dependencies.reject()}),i.each(e,function(e,t){this.app.collection(t,{fetch:{reload:!1,deferred:n[t]}},e)},this)},columns:function(){var e=this;return[{name:"diagram",customClass:"column-diagram",editable:!1,sortable:!1,headerCell:n.Headers.emptyHeader,cell:n.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(e){var t=s('<div class="properties"<div class="properties"><div class="diagram switch port24"><div class="port port-'+e.id+" "+e.diagramClasses()+'" data-port="'+e.id+'">'+'<div class="status">'+'<div class="poe"></div>'+'<div class="mirror"></div>'+'<div class="block"></div>'+"</div>"+"</div>"+"</div>"+"</div>");return t.find(".port").attr("title","Port "+e.get("port_idx")).tooltip({show:!1,hide:!1,track:!0,content:function(){return e.diagramTooltip()}}),t},toRaw:function(e){return e}}}),callback:this.rowView},{name:"device",label:o.G_InsightsSwitch,customClass:"column-device",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.app.collection("Devices"),r=n.getDeviceFromMac(t.get("device"));return r?r.name():t.get("device")},toRaw:function(e){return e}}}),callback:this.rowView},{name:"port_idx",label:o.G_Port,customClass:"column-port_idx",editable:!1,cell:"integer"},{name:"name",label:o.G_Name,customClass:"column-name",editable:!1,cell:"string"},{name:"poe_summary",label:o.G_PropertiesPoE,customClass:"column-poe_summary",editable:!1,sortable:!1,headerCell:n.Headers.noSortHeader,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:s.proxy(function(e){var t=e.poeModeText();return e.get("poe_mode")=="auto"&&e.get("poe_enable")?e.get("poe_power")+"w":t},this),toRaw:function(e){return e}}})},{name:"op_mode",label:o.G_InsightsMode,customClass:"column-op_mode",editable:!1,sortValue:"opModeText",headerCell:n.Headers.customSortHeader,cell:n.Cells.ModelCell.extend({callback:"opModeText"})},{name:"portconf_id",label:o.G_PropertiesNetworksVLANs,customClass:"column-portconf_id",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:s.proxy(function(t){if(t.get("aggregated_by"))return o.G_PropertiesAggregatedByPort+" "+t.get("aggregated_by");if(t.get("op_mode")=="mirror")return o.G_PropertiesMirroringPort+" "+t.get("mirror_port_idx");var n=t.get("portconf_id");if(n){var r=e.app.collection("PortConf").get(n);if(r)return r.get("name")}},this),toRaw:function(e){return e}}})},{name:"speed",label:o.G_InsightsNetworkLinkStatus,customClass:"column-speed",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){if(e.get("up")){var t=e.speed();return t+=" ",t+=e.get("full_duplex")?o.G_PropertiesFullDuplexAbbrv:o.G_PropertiesHalfDuplexAbbrv,e.get("is_uplink")&&(t+=" ("+o.G_PropertiesUplink+")"),t}return""},toRaw:function(e){return e}}})},{name:"stp_state",label:o.G_InsightsSTP,customClass:"column-stp_state",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:s.proxy(function(e){if(e.get("up")){if(e.get("stp_state")==="discarding")return o.G_InsightsSTPDiscarding;if(e.get("stp_state")==="forwarding")return o.G_InsightsSTPForwarding;if(e.get("stp_state")==="disabled")return o.G_InsightsSTPDisabled}return""},this),toRaw:function(e){return e}}})},{name:"tx_bytes",label:o.G_DevicesTX,customClass:"column-tx_bytes-abbrv",editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"rx_bytes",label:o.G_DevicesRX,customClass:"column-rx_bytes-abbrv",editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"tx_bytes-r",label:o.G_PropertiesTXRate,customClass:"column-tx_bytes-r",editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.BitsPerSecond})},{name:"rx_bytes-r",label:o.G_PropertiesRXRate,customClass:"column-rx_bytes-r",editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.BitsPerSecond})},{name:"bytes-r",label:o.G_Activity,customClass:"column-bytes-r",editable:!1,cell:n.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:s.proxy(function(e){var t=e.linkUsage("tx"),r=e.linkUsage("rx"),o=s('<div class="grid green-cells quarter"></div>'),u=s('<div class="grid green-cells quarter"></div>'),a=s('<div class="grid-wrapper"></div>'),f=[90,80,70,60,50,40,30,20,10,0];return i.each(f,function(e){t>e&&o.append(s('<span class="quarter red"></span>')),r>e&&u.append(s('<span class="quarter blue"></span>'))}),a.append(o.attr("data-value",t).attr("title","Tx: "+n.Formatters.BitsPerSecond.fromRaw(e.get("tx_bytes-r")))),a.append(u.attr("data-value",r).attr("title","Rx: "+n.Formatters.BitsPerSecond.fromRaw(e.get("rx_bytes-r")))),a},this),toRaw:s.proxy(function(e){return e.linkUsage()},this)}})},{name:"poe_mode",label:o.G_InsightsPoeMode,customClass:"column-poe_mode",editable:!1,sortValue:"poeModeText",headerCell:n.Headers.customSortHeader,cell:n.Cells.ModelCell.extend({callback:"poeModeText"})},{name:"poe_detection",label:o.G_InsightsPoeDetection,customClass:"column-poe_detection",editable:!1,sortValue:"poeDetection",headerCell:n.Headers.customSortHeader,cell:n.Cells.ModelCell.extend({callback:"poeDetection"})},{name:"poe_class",label:o.G_InsightsPoeClass,customClass:"column-poe_class",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:s.proxy(function(e){return e.isPDDetected()?e.get("poe_class"):""},this),toRaw:function(e){return e}}})},{name:"poe_power",label:o.G_InsightsPoePower,customClass:"column-poe_power",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:s.proxy(function(e){return e.isPDDetected()?e.get("poe_power"):""},this),toRaw:function(e){return e}}})},{name:"poe_voltage",label:o.G_InsightsPoeVoltage,customClass:"column-poe_voltage",editable:!1,sortValue:"poeVoltage",headerCell:n.Headers.customSortHeader,cell:n.Cells.ModelCell.extend({callback:"poeVoltage"})},{name:"poe_current",label:o.G_InsightsPoeCurrent,customClass:"column-poe_current",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:s.proxy(function(e){return e.isPDDetected()?e.get("poe_current"):""},this),toRaw:function(e){return e}}})},{name:"tx_bytes",label:o.G_InsightsCountersTxBytes,customClass:"column-tx_bytes",editable:!1,cell:"integer"},{name:"tx_packets",label:o.G_InsightsCountersTxFrames,customClass:"column-tx_packets",editable:!1,cell:"integer"},{name:"tx_multicast",label:o.G_InsightsCountersTxMulticast,customClass:"column-tx_multicast",editable:!1,cell:"integer"},{name:"tx_broadcast",label:o.G_InsightsCountersTxBroadcast,customClass:"column-tx_broadcast",editable:!1,cell:"integer"},{name:"tx_errors",label:o.G_InsightsCountersTxErrors,customClass:"column-tx_errors",editable:!1,cell:"integer"},{name:"rx_bytes",label:o.G_InsightsCountersRxBytes,customClass:"column-rx_bytes",editable:!1,cell:"integer"},{name:"rx_packets",label:o.G_InsightsCountersRxFrames,customClass:"column-rx_packets",editable:!1,cell:"integer"},{name:"rx_multicast",label:o.G_InsightsCountersRxMulticast,customClass:"column-rx_multicast",editable:!1,cell:"integer"},{name:"rx_broadcast",label:o.G_InsightsCountersRxBroadcast,customClass:"column-rx_broadcast",editable:!1,cell:"integer"},{name:"rx_errors",label:o.G_InsightsCountersRxErrors,customClass:"column-rx_errors",editable:!1,cell:"integer"},{name:"_id",label:o.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:n.Headers.noSortHeader,cell:n.Cells.ActionsCell.extend({actions:{edit:{icon:"ubnt-icon-edit",requiresAdminPrivilege:!0,buttonClasses:"narrow",callback:this.rowEdit,render:function(e){return!e.get("masked")}},restart:{icon:"ubnt-icon-rotate",text:o.G_InsightsPowerCycle,callback:this.rowPowerCycle,requiresAdminPrivilege:!0,buttonClasses:"narrow",render:function(e){return e.get("poe_enable")}},clearCounters:{icon:"ubnt-icon-trash",text:o.G_InsightsClear,callback:this.rowClearCounters,requiresAdminPrivilege:!0,buttonClasses:"narrow",render:function(e){return!0}}}})}]},render:function(){var t=this.rendered;t||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),e.prototype.render.call(this)},grid:function(){e.prototype.grid.call(this);var t=this.grids.content,n=this.$insightsChrome.find(".buttonset.switch-subtab-filters"),r=n.find("input[name=switch-subtab-filter]"),o=[];this.$switchFilter=this.$insightsChrome.find(".switchstats .switch-filter select"),this.$switchFilter.on("change",s.proxy(function(e){var n=s(e.target).val();n?(t.setFilter("device",n,1),t.$el.addClass("single-switch")):(t.removeFilter("device"),t.$el.removeClass("single-switch")),s.cookie("filterInsightsSwitchStatsSwitch",n)},this)),this.listenTo(this,"device_change",i.debounce(this.setupSwitchFilter,250)),this.setupSwitchFilter(),this.$switchFilter.val(s.cookie("filterInsightsSwitchStatsSwitch")||"").selectmenu("close").trigger("change"),this.$poeFilter=this.$insightsChrome.find(".switchstats .poe-filter select");var u=this.$poeFilter;this.$poeFilter.on("change",s.proxy(function(e){var n=s(e.target).val();t.removeFilter("isPoeEnabled"),t.removeFilter("isPassivePoe"),t.removeFilter("isPoePowerOn"),n=="enabled"?t.setFilter("isPoeEnabled",!0,1):n=="powerOn"?t.setFilter("isPoePowerOn",!0,1):n=="passive"?t.setFilter("isPassivePoe",!0,1):n=="disabled"&&t.setFilter("isPoeEnabled",!1,1),s.cookie("filterInsightsSwitchStatsPoeMode",n)},this)),this.setupPoeFilter(),this.$poeFilter.val(s.cookie("filterInsightsSwitchStatsPoeMode")||"").selectmenu("close").trigger("change"),this.$clearCounters=this.$insightsChrome.find(".switchstats .clear-counters select");var a=this.$clearCounters;this.$clearCounters.on("change",s.proxy(function(e){var t=s(e.target),n=t.val(),r=this.app.collection("Devices"),i=n&&n!="all"?r.getDeviceFromMac(n):null;if(!n)return;this.clearCounters(i),a.val(a.find("option:first").val()).selectmenu("close")},this)),this.listenTo(this,"device_change",i.debounce(this.setupSwitchClearCounters,250)),this.setupSwitchClearCounters(),this.$linkStatusFilter=this.$insightsChrome.find(".switchstats .network-link-filter select"),this.$linkStatusFilter.on("change",s.proxy(function(e){var n=s(e.target).val();n=="connected"?t.setFilter("up",!0,1):n=="disconnected"?t.setFilter("up",!0,-1):t.removeFilter("up"),s.cookie("filterInsightsSwitchStatsLinkStatus",n)},this)),this.setupLinkFilter(),this.$linkStatusFilter.val(s.cookie("filterInsightsSwitchStatsLinkStatus")||"all").selectmenu("close").trigger("change"),i.each(r,function(e,t){o.push(e.value)}),r.on("change",function(e){var n=s(this),r=n.val();r==="poe"?(t.setFilter("port_poe",!0,1),u.closest(".ui-selectmenu-parent").show()):(t.removeFilter("port_poe"),u.closest(".ui-selectmenu-parent").hide(),u.val("").selectmenu("close").trigger("change")),t.$el.removeClass(o.join(" ")).addClass(r||"overview"),s.cookie("filterInsightsSwitchStatsSubtab",r)}).filter(":checked").trigger("change"),r.filter('[value="'+(s.cookie("filterInsightsSwitchStatsSubtab")||"overview")+'"]').click()},searchable:function(){var t=this.app.collection("Devices"),n=s.proxy(function(e){e.addSearchString("device-name",t.getDeviceFromMac(e.get("device")).name())},this),r=s.proxy(function(){this.collection.each(n),this.trigger("search:indexed")},this);this.listenTo(this.collection,"change",n),this.listenTo(this.collection,"add",n),this.listenTo(this.collection,"reset",r),r(),e.prototype.searchable.call(this)},setupLinkFilter:function(){var e=this.$linkStatusFilter.find("options:selected").val();this.$linkStatusFilter.empty(),this.$linkStatusFilter.append(s('<option value="all"></option>').text(o.G_All)),this.$linkStatusFilter.append(s('<option value="connected"></option>').text(o.G_APConnected)),this.$linkStatusFilter.append(s('<option value="disconnected"></option>').text(o.G_APDisconnected)),this.$linkStatusFilter.find('option[value="'+(e||"")+'"]').prop("selected",!0),this.$linkStatusFilter.selectmenu("refresh")},setupSwitchFilter:function(){var e=this.$switchFilter.find("option:selected").val();this.$switchFilter.empty(),this.$switchFilter.append(s('<option value=""></option>').text(o.G_All)),this.devices&&i.each(this.devices.where({type:this.devices.typeMap["switch"]}),s.proxy(function(e){e.get("adopted")&&this.$switchFilter.append(s("<option />").attr("value",e.get("mac")).text(e.name()))},this)),this.$switchFilter.find('option[value="'+(e||"")+'"]').prop("selected",!0),this.$switchFilter.selectmenu("refresh")},setupPoeFilter:function(){var e=this.$poeFilter.find("option:selected").val(),t={enabled:o.G_InsightsPoeEnabled,powerOn:o.G_InsightsPoePowerOn,passive:o.G_InsightsPoePassive,disabled:o.G_InsightsPoeDisabled},n=this.$poeFilter;this.$poeFilter.empty(),this.$poeFilter.append(s('<option value=""></option>').text(o.G_All)),i.each(t,function(e,t){n.append(s('<option value="'+t+'"></option>').text(e))}),this.$poeFilter.find('option[value="'+(e||"")+'"]').prop("selected",!0),this.$poeFilter.selectmenu("refresh"),this.$poeFilter.closest(".ui-selectmenu-parent").hide().css({position:"static",left:0})},setupSwitchClearCounters:function(){var e=this.$clearCounters.find("option:selected").val();this.$clearCounters.empty(),this.$clearCounters.append(s('<option value="none"></option>')),this.$clearCounters.append(s('<option value="all"></option>').text(o.G_All)),this.devices&&i.each(this.devices.where({type:this.devices.typeMap["switch"]}),s.proxy(function(e){e.get("adopted")&&this.$clearCounters.append(s("<option />").attr("value",e.get("mac")).text(e.name()))},this)),this.$clearCounters.find('option[value="'+(e||"")+'"]').prop("selected",!0),this.$clearCounters.selectmenu("refresh"),this.$clearCounters.closest(".ui-selectmenu-parent").hide().css({position:"static",left:0})},rowEdit:function(e){this.rowView(e,!0)},rowView:function(e,t){var n=this.app.collection("Devices"),r=n.getDeviceFromMac(e.get("device")),i=this.app.routers.devices.views.index.property(r);i.statsPortForm(e,t)},clearAllCounters:function(){var e=this.app.collection("Devices");s.ajax({contentType:"application/json; charset=utf-8",url:"/api/s/"+SITE.name+"/cmd/devmgr",type:"POST",data:JSON.stringify({cmd:"clear-all-switch-counters"}),success:function(e,t,n){this.devices&&i.each(this.devices.where({type:this.devices.typeMap["switch"]}),s.proxy(function(e){e.fetch()},this))},error:function(e,t,n){this.app.views.app.flash("error","Error",o.apiError(e))}})},clearCounters:function(e,t){var n=this.app.collection("Devices"),i=e?n.getDeviceFromMac(e.get("mac")):undefined,u=e?e.get("mac"):undefined,a=t?t:undefined,f={mac:u,port_idx:a},l=this.clearAllCounters,c=o.G_ConfirmClearAllCounters;t?(l=i.clearPortCounters,c=o.localize(o.G_ConfirmClearPortCounters,e.name(),t)):e&&(l=i.clearSwitchCounters,c=o.localize(o.G_ConfirmClearSwitchCounters,e.name())),(new r).show(c,s.proxy(function(){t||e?l.call(i,{data:f,success:function(e,t,n){i&&i.fetch()},error:s.proxy(function(e,t,n){this.app.views.app.flash("error","Error",o.apiError(e))},this)}):l.call(this)},this))},rowClearCounters:function(e){var t=this.app.collection("Devices"),n=t.getDeviceFromMac(e.get("device")),r=e.get("port_idx");this.clearCounters(n,r)},rowPowerCycle:function(e){var t=this.app.collection("Devices"),n=t.getDeviceFromMac(e.get("device"));(new r).show(o.localize(o.N_ConfirmPowerCyclePort,e.get("port_idx")),s.proxy(function(){n.powerCyclePort({data:{port_idx:e.get("port_idx")},success:function(e,t,r){n.fetch()},error:s.proxy(function(e,t,n){this.app.views.app.flash("error","Error",o.apiError(e))},this)})},this))},remove:function(){this.stopListening(this.devices),this.devices&&i.each(this.devices.where({type:this.devices.typeMap["switch"]}),function(e){this.stopListening(e)},this),this.$switchFilter.off("change"),this.stopListening(this,"device_change"),this.$poeFilter.off("change"),this.$clearCounters.off("change"),this.$insightsChrome.find(".buttonset.switch-subtab-filters").find("input[name=switch-subtab-filter]").off("change"),this.stopListening(this.collection),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/RemoteUserVPNStats",["jquery","underscore","unifi/model/Model","ubnt/backgrid","msg/Msg","libs/moment"],function(e,t,n,r,i,s){"use strict";return n.extend({toSearch:function(){return{"interface":this.gw_interface(),remote_ip:this.remote_ip(),user:this.user()}},gw_interface:function(){return this.get("interface")},remote_ip:function(){return this.get("remote_ip")},remoteip2long:function(){return e.ip2long(this.get("remote_ip"))},rx_bytes:function(){return this.get("rx_bytes")},rx_packets:function(){return this.get("rx_packets")},tx_bytes:function(){return this.get("tx_bytes")},tx_packets:function(){return this.get("tx_packets")},uptime:function(e){return e=e||this.get("uptime"),e>0?r.Formatters.Duration.fromRaw(e||0):""},user:function(){return this.get("user")},up:function(){return this.get("up")}})}),define("unifi/collection/insights/RemoteUserVPNStats",["backbone","underscore","unifi/collection/Collection","unifi/model/insights/RemoteUserVPNStats"],function(e,t,n,r){"use strict";return n.extend({model:r,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/remoteuservpn"},sync:function(n,r,i){i=i||{};switch(n){case"read":i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{}))}return e.sync.call(this,n,r,i)}})}),define("text!includes/insights/remoteUserVPNStatsTemplate.html",[],function(){return'<div class="data-table untitled">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n</div>'}),define("unifi/view/insights/RemoteUserVPNStatsView",["unifi/view/app/ListContentView","libs/backgrid","ubnt/backgrid","underscore","jquery","msg/Msg","unifi/collection/insights/RemoteUserVPNStats","text!includes/insights/remoteUserVPNStatsTemplate.html"],function(e,t,n,r,i,s,o,u){"use strict";return e.extend({id:"remoteuservpnstats",_templateId:u,_collectionType:{name:"RemoteUserVPNStats",Class:o},_pageable:!0,initialize:function(t){this.$insightsChrome=i("#insightsChrome"),e.prototype.initialize.call(this,t),this.$el.removeClass("content")},columns:function(){return[{name:"interface",label:s.G_RemoteUserVPNInterface,editable:!1,cell:"string"},{name:"remote_ip",label:s.G_RemoteUserVPNRemoteIP,editable:!1,sortValue:"remoteip2long",headerCell:n.Headers.customSortHeader,cell:"string"},{name:"user",label:s.G_RemoteUserVPNUser,editable:!1,cell:"string"},{name:"rx_packets",label:s.G_RemoteUserVPNRxPackets,editable:!1,cell:"integer"},{name:"rx_bytes",label:s.G_RemoteUserVPNRxBytes,editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"tx_packets",label:s.G_RemoteUserVPNTxPackets,editable:!1,cell:"integer"},{name:"tx_bytes",label:s.G_RemoteUserVPNTxBytes,editable:!1,cell:t.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"uptime",label:s.G_Uptime,editable:!1,cell:n.Cells.ModelCell.extend({callback:"uptime"})}]},render:function(){var t=this.rendered;t||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),e.prototype.render.call(this)},searchable:function(){e.prototype.searchable.call(this)},remove:function(){this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/DynamicDNSStat",["unifi/model/DynamicDNS","jquery","backbone","msg/Msg","ubnt/backgrid","libs/moment"],function(e,t,n,r,i,s){"use strict";return e.extend({toSearch:function(){return{service:this.service(),host_name:this.hostname(),server:this.server(),login:this.username(),ip:this.ip(),status:this.status(),last_updated:this.lastUpdated()}},ip:function(){return this.get("ip")},ddnsStatus:function(){switch(this.get("status")){case"good":return r.G_PropertiesDDNSStatusGood;case"failed":case"noconnect":return r.G_PropertiesDDNSStatusFailed;case"updating":return r.G_PropertiesDDNSStatusUpdating;default:return r.G_Unknown}},ip2long:function(){return t.ip2long(this.get("ip"))},lastUpdated:function(){var e=this.get("last_updated"),t;return e>0?i.Formatters.Duration.fromRaw(e||0):""}})}),define("unifi/collection/insights/DynamicDNSStat",["backbone","underscore","unifi/collection/Collection","unifi/model/insights/DynamicDNSStat"],function(e,t,n,r){"use strict";return n.extend({model:r,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/dynamicdns"},sync:function(n,r,i){i=i||{};switch(n){case"read":i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{}))}return e.sync.call(this,n,r,i)}})}),define("text!includes/insights/DynamicDNSStatsTemplate.html",[],function(){return'<div class="data-table untitled">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n</div>'}),define("unifi/view/insights/DynamicDNSStatsView",["unifi/view/app/ListContentView","libs/backgrid","ubnt/backgrid","underscore","jquery","msg/Msg","unifi/collection/insights/DynamicDNSStat","text!includes/insights/DynamicDNSStatsTemplate.html"],function(e,t,n,r,i,s,o,u){"use strict";return e.extend({id:"dynamicdnsstats",_templateId:u,_collectionType:{name:"DynamicDNSStat",Class:o},_pageable:!0,initialize:function(t){this.$insightsChrome=i("#insightsChrome"),e.prototype.initialize.call(this,t),this.$el.removeClass("content")},columns:function(){return[{name:"service",label:s.G_PropertiesDDNSService,editable:!1,cell:"string"},{name:"status",label:s.G_PropertiesDDNSStatus,editable:!1,cell:n.Cells.ModelCell.extend({callback:"ddnsStatus"})},{name:"host_name",label:s.G_PropertiesDDNSHostname,editable:!1,cell:"string"},{name:"login",label:s.G_PropertiesDDNSUsername,editable:!1,cell:"string"},{name:"server",label:s.G_PropertiesDDNSServer,editable:!1,cell:"string"},{name:"ip",label:s.G_PropertiesDDNSIp,editable:!1,sortValue:"ip2long",headerCell:n.Headers.customSortHeader,cell:"string"},{name:"last_updated",label:s.G_PropertiesDDNSLastUpdated,editable:!1,cell:n.Cells.ModelCell.extend({callback:"lastUpdated"})},{name:"_id",label:s.G_Actions,editable:!1,sortable:!1,headerCell:n.Headers.noSortHeader,cell:n.Cells.ActionsCell.extend({actions:{edit:{icon:"ubnt-icon-edit",requiresAdminPrivilege:!0,buttonClasses:"narrow",callback:this.rowEdit,render:function(e){return!e.get("masked")}}}})}]},rowEdit:function(e){var t=this.app.collection("Devices"),n=t.where({type:"ugw",site_id:SITE.id}),r;n.length>0&&(r=this.app.routers.devices.views.index.property(n[0]),r.statsDynamicDNSForm(e,!0))},render:function(){var t=this.rendered;t||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),e.prototype.render.call(this)},searchable:function(){e.prototype.searchable.call(this)},remove:function(){this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/router/InsightsRouter",["unifi/router/Router","unifi/view/insights/ChromeView","unifi/view/insights/KnownClientsView","unifi/view/insights/RogueAccessPointsView","unifi/view/insights/PastConnectionsView","unifi/view/insights/PastGuestAuthorizationsView","unifi/view/insights/SwitchStatsView","unifi/view/insights/RemoteUserVPNStatsView","unifi/view/insights/DynamicDNSStatsView"],function(e,t,n,r,i,s,o,u,a){"use strict";return e.extend({_fullyQualifiedName:"UNIFI.Routers.Insights",_associatedViews:{Chrome:t,Knownclients:n,Rogueaccesspoints:r,Pastconnections:i,Pastguestauthorizations:s,Switchstats:o,Remoteuservpnstats:u,Dynamicdnsstats:a},routes:{insights:"index","insights/knownclients":"knownclients","insights/rogueaccesspoints":"rogueaccesspoints","insights/pastconnections":"pastconnections","insights/pastguestauthorizations":"pastguestauthorizations","insights/switchstats":"switchstats","insights/remoteuservpnstats":"remoteuservpnstats","insights/dynamicdnsstats":"dynamicdnsstats"},initialize:function(t){e.prototype.initialize.call(this,t),this.on("route",function(e){e!="index"&&this.views.chrome&&this.views.chrome.navigate(e)})},_render:function(t){e.prototype._render.call(this,"chrome"),e.prototype._render.call(this,t,this.views.chrome.$content),this.views.chrome._contentView=this.views[t]},index:function(){this.navigate("insights/knownclients",{replace:!0,trigger:!0})},knownclients:function(){this._render("knownclients")},rogueaccesspoints:function(){this._render("rogueaccesspoints")},pastconnections:function(){this._render("pastconnections")},pastguestauthorizations:function(){this._render("pastguestauthorizations")},switchstats:function(){this._render("switchstats")},remoteuservpnstats:function(){this._render("remoteuservpnstats")},dynamicdnsstats:function(){this._render("dynamicdnsstats")}})}),define("unifi/view/support/ChatView",["backbone","underscore","msg/Msg","jquery"],function(e,t,n,r){"use strict";return e.View.extend({initialize:function(){t.bindAll(this),this.num_agents=0,r.getJSON("https://ubnt.zendesk.com/node/ubnt/v2/availability/?callback=?",this.render)},render:function(e){var t=n.E_NoAgentsAvailable;this.num_agents=e&&e.online&&e.online>0?e.online:0,this.$link=this.$(".option-header-link").on("click",this.onLiveChatClick),this.$subtitle=this.$(".subtitle"),this.num_agents&&(t=n.G_AgentsAvailable,this.$link.removeClass("disabled")),this.$subtitle.text(t)},onLiveChatClick:function(){if(this.num_agents){var e=this.options.cloudUser.get("community_id")||this.options.cloudUser.get("name"),t=this.options.cloudUser.get("email")||"",n="";window.open("https://ubnt.zendesk.com/chat?dropboxID=20114087&user[name]="+e+"&user[email]="+t+"&user[subject]="+n+"]")}return!1},remove:function(){this.$(".option-header-link").off("click",this.onLiveChatClick),e.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/support/RequestFormView",["backbone","underscore","jquery"],function(e,t,n){"use strict";return e.View.extend({initialize:function(){t.bindAll(this),this.render()},render:function(){this.$subject=this.$("input[name=subject]"),this.$description=this.$("textarea[name=description]"),this.$el.on("submit",this.onSubmitHandler)},onSubmitHandler:function(){var e=this,t;return t=this.validateField(this.$subject),t&&(t=this.validateField(this.$description)),t&&n.ajax({url:"/api/cloud/ticket",type:"POST",data:{subject:encodeURIComponent(this.$subject.val()),message:encodeURIComponent(this.$description.val())}}).done(function(){e.$(".message").fadeIn().delay(3e3).fadeOut(),e.$subject.val(""),e.$description.val("")}),!1},validateField:function(e){var t=n.trim(e.val());return t.length>5?(e.removeClass("error"),!0):(e.addClass("error"),!1)},remove:function(){this.$el.off("submit",this.onSubmitHandler),e.View.prototype.remove.apply(this,arguments)}})}),define("text!includes/support/supportIndexTemplate.html",[],function(){return'<div class="section section-main">\n    <iframe src="https://community.ubnt.com/ubnt/plugins/custom/ubiquiti/ubnt/unifi_support"></iframe>\n\n    <div id="supportSidebar">\n        <h2><%- msg.G_SupportMoreSupportOpts %></h2>\n        <div class="options">\n\n            <div class="option-row option-request">\n                <div class="option-header">\n                    <span class="icon ubnt-icon-request"></span>\n                    <span class="title"><%- msg.G_SupportSbmtSupportReq %></span>\n                </div>\n                <form id="frmSupportRequest" action="javascript:void()" class="frm-support-request" method="post">\n                    <label for="supportRequestQuestion" class="label"><%- msg.G_SupportQuestion %>*</label>\n                    <input name="subject" type="text" id="supportRequestQuestion" placeholder="<%- msg.G_SupportBriefDescribeQuestion %>" class="input"/>\n                    <label for="supportRequestDetails" class="label"><%- msg.G_SupportDetails %>*</label>\n                    <textarea name="description" id="supportRequestDetails" placeholder="<%- msg.G_SupportFillDetails %>" class="input textarea"></textarea>\n                    <div class="message"><%- msg.G_SupportReqSubmitted %></div>\n                    <button type="submit" class="button submit"><span class="icon ubnt-icon-check"></span><%- msg.G_Submit %></button>\n                </form>\n            </div>\n\n            <div id="supportChat" class="option-row option-chat">\n                <a id="ZendeskSupportLink" href="javascript:void()" target="_blank" class="option-header option-header-link disabled">\n                    <span class="icon ubnt-icon-chat-bubbles"></span>\n                    <span class="title"><%- msg.G_SupportChatSupportAgt %></span>\n                    <span class="subtitle"></span>\n                    <span class="icon link-out"></span>\n                </a>\n            </div>\n\n            <div class="option-row option-community">\n                <a href="http://community.ubnt.com/t5/forums/postpage/board-id/UniFi" target="_blank" class="option-header option-header-link">\n                    <span class="icon ubnt-icon-people"></span>\n                    <span class="title"><%- msg.G_SupportAskComm %></span>\n                    <span class="icon link-out"></span>\n                </a>\n            </div>\n\n        </div>\n    </div>\n</div>'}),define("unifi/view/support/IndexView",["unifi/view/app/ContentView","underscore","backbone","unifi/view/support/RequestFormView","unifi/view/support/ChatView","jquery","msg/Msg","text!includes/support/supportIndexTemplate.html"],function(e,t,n,r,i,s,o,u){"use strict";return e.extend({id:"supportIndex",initialize:function(n){e.prototype.initialize.call(this,n),this.template=t.template(u),this.render()},render:function(){e.prototype.render.call(this);var t=this;!this.rendered&&(this.rendered=!0)&&(this.$el.html(this.template({msg:o})),this.supportRequest=new r({el:"#frmSupportRequest"}),this.supportChat=new i({el:"#supportChat",cloudUser:this.options.app.views.app.options.cloudUser}))},remove:function(){this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/router/SupportRouter",["unifi/router/Router","unifi/view/support/ChatView","unifi/view/support/IndexView","unifi/view/support/RequestFormView"],function(e,t,n,r){"use strict";return e.extend({_fullyQualifiedName:"UNIFI.Routers.Support",_associatedViews:{Chat:t,Index:n,Request:r},routes:{support:"index"}})}),define("unifi/view/app/SearchableMixin",["jquery","underscore"],function(e,t){"use strict";return{searchable:function(){this._initializedCollectionSearch=!1,this._runningCollectionSearch=!1,this._completedCollectionSearch=!1,this._searchEnabled=!1,this.$search.one("focus",e.proxy(function(){this._initializedCollectionSearch=!0,this._enableSearch()},this)),this.$search.on("focus",e.proxy(function(){this._completedCollectionSearch||this._prepareCollectionSearch()},this)),this.listenTo(this.collection,"add change",this._reconcileSearch),this.listenTo(this.collection,"sync",this._reconcileSearch),this.listenTo(this,"search:indexed",e.proxy(function(){this._completedCollectionSearch=!0,this._addSearchListeners()},this)),this.$el.on("content:show",this._enableSearch),this.$el.on("content:hide",this._disableSearch)},filter:function(n,r,i){r=e.trim(r||this.$search.val()),r&&this._runningCollectionSearch?!this._delayedFilter&&(this._delayedFilter=!0)&&this.listenToOnce(this,"search:indexed",e.proxy(function(){t.each(this.grids,function(e){r?e.setFilter(null,r,this._filterMinimum,!1,i):e.removeFilter(null)},this),this._delayedFilter=!1},this)):t.each(this.grids,function(e){r?e.setFilter(null,r,this._filterMinimum,!1,i):e.removeFilter(null)},this)},_enableSearch:function(){this._initializedCollectionSearch&&(this._initializedCollectionSearch=!0,this._searchEnabled=!0,this._addSearchListeners(),e.trim(this.$search.val())&&(this._completedCollectionSearch||(this._prepareCollectionSearch(),this.filter(null,null,!0))))},_disableSearch:function(){this._initializedCollectionSearch&&(this._searchEnabled=!1,this._removeSearchListeners())},_reconcileSearch:t.throttle(function(){this._searchEnabled||(this._completedCollectionSearch=!1)},1e3),_addSearchListeners:function(){this._removeSearchListeners(),this._completedCollectionSearch?this.listenTo(this.collection,"add change",this._prepareModelSearch):this.listenTo(this.collection,"sync",this._prepareCollectionSearch)},_removeSearchListeners:function(){this.stopListening(this.collection,"add change",this._prepareModelSearch),this.stopListening(this.collection,"sync",this._prepareCollectionSearch)},_prepareModelSearch:function(e){throw new Error("_prepareModelSearch must be overriden")},_prepareCollectionSearch:function(){if(!this._runningCollectionSearch&&(this._runningCollectionSearch=!0)){this.$search.addClass("indexing");var n=e.proxy(function(e,r,i){for(var s=i*r,o=Math.min(s+r,e.length);s<o;s++)this._prepareModelSearch(e[s]);s<e.length?t.defer(n,e,r,++i):(this.trigger("search:indexed"),this.$search.removeClass("indexing"),this._runningCollectionSearch=!1)},this);n(this.collection.models,500,0)}},searchableRemove:function(){this._disableSearch(),this.$search.off(),this.stopListening(this,"search:indexed"),this.stopListening(this.collection,"add change",this._reconcileSearch),this.stopListening(this.collection,"sync",this._reconcileSearch),this.stopListening(this.collection,"add change",this._prepareModelSearch),this.stopListening(this.collection,"sync",this._prepareCollectionSearch),this.$el.off("content:show",this._enableSearch),this.$el.off("content:hide",this._disableSearch)}}}),define("unifi/view/app/PanelListContentView",["jquery","underscore","libs/moment","unifi/view/app/ListContentView","unifi/view/app/SearchableMixin","libs/backgrid","ubnt/backgrid"],function(e,t,n,r,i,s,o){"use strict";return r.extend(t.extend({},i,{_gridTitles:o.Titles.Moment,_pageable:!0,_maxRecords:1e5,_perPage:50,_autoRender:!1,_autoLoad:!1,_filterMinimum:.1,_msgRegex:/((User|AP|Switch|Gateway|Phone|Guest|Client|Voucher|Admin)\[(.*?)\])/g,initialize:function(e){r.prototype.initialize.call(this,e);var t=this;this.$container.on("show:complete",function(){t.load()}),this.$container.on("hide:complete",this._disableSearch)},render:function(){var t=this.rendered;r.prototype.render.call(this),t||this._renderBadge&&e(this._badgeSelector).append(this.$badge=e('<div class="drop-count hidden"><div class="ubnt-icon-drop"></div><div class="count"></div></div>').on("change",function(t,n){var r=e(this),i=r.find(".count");parseInt(i.text(),10)<n&&r.effect("shake",{direction:"up",times:1,distance:5},300),r[n>0?"show":"hide"](),i.text(n)}))},badge:function(){this.$badge&&this.$badge.trigger("change",this.collection.size())},columns:function(){var t=this;return[{name:"datetime",renderable:!1,cell:s.StringCell.extend({className:"title-cell"})},{name:"key",label:"Type",editable:!1,sortable:!1,headerCell:o.Headers.noSortHeader,cell:o.Cells.HtmlCell.extend({className:"icon-cell",formatter:{fromRaw:function(e){if(e){var t;switch(e.substr(4,2)){case"AD":case"CF":case"DE":t="ubnt-icon-wrench";break;case"WW":t="ubnt-icon-globe";break;case"GW":t="ubnt-icon-lock";break;case"SW":case"LA":t="ubnt-icon-files";break;case"AP":t="ubnt-icon-wifi";break;case"PH":t="ubnt-icon-dial";break;case"LU":case"WU":case"WC":case"WG":case"HS":t="ubnt-icon-person"}return'<div class="panel-icons '+t+'"></div>'}return""},toRaw:function(e){return e}}})},{name:"msg",label:"Message",editable:!1,sortable:!1,headerCell:o.Headers.noSortHeader,cell:o.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(r){var i=r.get("msg");if(i){var s=e("<span>"+i.replace(t._msgRegex,function(n,r,i,s,o,u){var a=s.indexOf("(")>0?s.replace(/.*\((.*)\).*/,"$1"):s,f=t.model(i.toLowerCase(),a),l=s.indexOf("(")>0?s.replace(/([^\(]+)\(.*/,"$1"):f?f.name():s;return f?e('<a href="#" data-mac="'+a+'" data-type="'+i+'" class="link"></a>').text(i+" "+l).prop("outerHTML"):e('<span class="deleted"></span>').text(i+" "+l).prop("outerHTML")})+"</span>");return s.find("a").on("click",t.link),s.append(e('<span class="timestamp">'+n(r.get("datetime")).format("h:mma")+"</span>")),s}},toRaw:function(e){return e}}})}]},_prepareModelSearch:function(e){var t,n,r=[];while(t=this._msgRegex.exec(e.get("msg")))(n=this.model(t[2].toLowerCase(),t[3]))&&r.push(n.name());e.addSearchString("names",r)},model:function(e,t){var n;if(t)if(e=="ap"||e=="switch"||e=="gateway"||e=="phone")n=this.collections.devices.getDeviceFromMac(t);else if(e=="user"||e=="client"||e=="guest")n=this.collections.clients.getClientFromMac(t);return n},link:function(t){t.preventDefault();var n=e(t.target),r=n.data("mac"),i=n.data("type").toLowerCase(),s=this.model(i,r);s&&(i=="ap"||i=="switch"||i=="gateway"||i=="phone"?this.app.routers.devices.views.index.property(s):(i=="user"||i=="client"||i=="guest")&&this.app.routers.clients.views.index.property(s))},load:function(e,n){var i=!this.collection;if(i||e)n=n||{},n.reset=!1,this._maxRecords&&(n.data=t.extend(n.data||{},{_start:0,_limit:this._maxRecords}));r.prototype.load.call(this,e,n),i&&(this._renderBadge&&(this.listenTo(this.collection,"add",t.debounce(this.badge,250)),this.listenTo(this.collection,"remove",t.debounce(this.badge,250)),this.listenTo(this.collection,"sync",t.debounce(this.badge,250)),this.badge()),this.collections={},this.collections.devices=this.app.collection("Devices"),this.collections.clients=this.app.collection("Clients")),!i&&!e&&this.grids.content&&this.grids.content.refresh()},grid:function(){var e={columns:this.columns(),collection:this.collection,titles:this._gridTitles,footer:o.Paginators.Default},t=this.grids.content=new o.Grid(e);return t.paginate(1,this._perPage,!0),this.$el.find(".data-table").append(t.render().$el),this.$table=this.$el.find(".data-table table"),this.$loading=this.$el.find(".data-table .loading").hide(),this.listenTo(t,"backgrid:loading",this.reloading),this.listenTo(t,"backgrid:loaded",this.reloaded),this},reset:function(){this.searchableRemove(),this.$container.off("hide:complete",this._disableSearch),this.$container.off("show:complete").empty(),this.$badge&&this.$badge.remove(),this.stopListening(this.collection),this.collection=null,this.initialize(this.options)},remove:function(){this.$container.off("show:complete"),this.$container.off("hide:complete",this._disableSearch),this.$badge&&this.$badge.off("change"),this.stopListening(this.collection),this.stopListening(this.grids.content),this.rendered=!1,r.prototype.remove.apply(this,arguments)}}))}),define("text!includes/alerts/alertsTemplate.html",[],function(){return'<div class="section section-panel section-alerts">\n    <div class="section-header clearfix">\n        <h2><%- msg.G_Alerts %></h2>\n        <div class="hide-panel ubnt-icon-arrows-down right"></div>\n\n        <form class="data-filters clearfix">\n            <!--\n            <div class="buttonset">\n                <input type="radio" id="alertsFilterAll" name="filter" value="" checked="checked" /><label for="alertsFilterAll">All</label>\n                <input type="radio" id="alertsFilterWww" name="filter" value="www" /><label for="alertsFilterWww">WWW</label>\n                <input type="radio" id="alertsFilterWan" name="filter" value="wan" disabled="disabled" /><label for="alertsFilterWan">WAN</label>\n                <input type="radio" id="alertsFilterLan" name="filter" value="lan" disabled="disabled" /><label for="alertsFilterLan">LAN</label>\n                <input type="radio" id="alertsFilterWlan" name="filter" value="wlan" /><label for="alertsFilterWlan">WLAN</label>\n                <input type="radio" id="alertsFilterVoip" name="filter" value="voip" disabled="disabled" /><label for="alertsFilterVoip">VOIP</label>\n            </div>\n            -->\n\n            <div class="options">\n                <input type="checkbox" name="archived" id="showArchivedAlerts" class="checkbox left" />\n                <label for="showArchivedAlerts" class="label left"><%- msg.G_AlertsShowArchivedAlerts %></label>\n            </div>\n\n            <button type="button" class="button lightest archive-all is-admin"><%- msg.G_AlertsArchiveAll %></button>\n\n            <span class="ubnt-icon-search"></span>\n            <input type="text" name="search" class="search right" />\n        </form>\n    </div>\n\n    <div class="data-table simple">\n        <div class="loading"><span><%- msg.N_Loading %></span></div>\n    </div>\n</div>'}),define("unifi/view/app/AlertsView",["unifi/view/app/PanelListContentView","unifi/collection/Alerts","underscore","msg/Msg","jquery","ubnt/backgrid","text!includes/alerts/alertsTemplate.html"],function(e,t,n,r,i,s,o){"use strict";return e.extend({id:"alerts",_templateId:n.template(o,{msg:r}),_collectionType:{name:"Alerts",Class:t},_pageable:!1,_hideArchived:!0,_renderBadge:!0,_badgeSelector:"#toggleAlerts",render:function(){var t=this.rendered;e.prototype.render.call(this);if(!t){var n=this;this.$el.find("button.archive-all").on("click",this.archive),this.$el.find("input[name=archived]").on("change",function(){i(this).is(":checked")?n._hideArchived=!1:n._hideArchived=!0,n.load(!0)}),this.$(".hide-panel").on("click",function(){i("#toggleAlerts").trigger("click")})}},badge:function(){this.$badge&&this.$badge.trigger("change",n.size(this.collection.where({archived:!1})))},columns:function(){var t=e.prototype.columns.call(this),n=this;return t.push({name:"system",label:r.G_AlertsSystem,editable:!1,sortable:!1,headerCell:s.Headers.noSortHeader,cell:s.Cells.ComplexHtmlCell.extend({className:"system-cell",formatter:{fromRaw:function(e){var t=e.get("system");return t?i("<strong />").text(r.G_AlertsSystem+":").prop("outerHTML")+" "+i("<span />").text(t.toUpperCase()).prop("innerHTML"):""},toRaw:function(e){return e}}})}),t.push({name:"device",label:r.G_AlertsDevice,editable:!1,sortable:!1,headerCell:s.Headers.noSortHeader,cell:s.Cells.ComplexHtmlCell.extend({className:"device-cell",formatter:{fromRaw:function(e){var t=n.app.collection("Devices"),s=null;return e.get("ap")?s=t.getDeviceFromMac(e.get("ap")):e.get("gw")?s=t.getDeviceFromMac(e.get("gw")):e.get("sw")?s=t.getDeviceFromMac(e.get("sw")):e.get("ph")&&(s=t.getDeviceFromMac(e.get("ph"))),s?i("<strong />").text(r.G_AlertsDevice+":").prop("outerHTML")+" "+i("<span />").text(s.apModel()).prop("innerHTML"):""},toRaw:function(e){return e}}})}),t.push({name:"archived",label:r.G_AlertsArchive,editable:!1,sortable:!1,headerCell:s.Headers.noSortHeader,cell:s.Cells.HtmlCell.extend({className:"icon-cell transparent-cell",formatter:{fromRaw:function(e){return e?"":'<div class="ubnt-icon-archive archive"></div>'},toRaw:function(e){return e}}}),callback:function(e){e.archive().done(function(t){t.meta&&t.meta.rc==="ok"&&(e.set({archived:!0}),n._hideArchived&&e.collection.remove(e))})}}),t},load:function(t){t=t||!this.collection;if(!this.collection||t)this._hideArchived?this._fetchMethod="unarchived":this._fetchMethod="",this.collection&&this.collection.reset();e.prototype.load.call(this,t)},archive:function(){var e=this;this.collection.archiveAll().done(function(t){t.meta&&t.meta.rc==="ok"&&e.load(!0)})},grid:function(){e.prototype.grid.call(this);var t=this.grids.content;return this.$el.find(".buttonset input[name=filter]").on("change",function(e){var n=i(this).val();n?t.setFilter("system",n,1):t.removeFilter("system")}),this},remove:function(){this.$el.find("button.archive-all").off("click",this.archive),this.$el.find("input[name=archived]").off("change"),this.$(".hide-panel").off("click"),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/collection/Events",["unifi/collection/Collection","backbone","unifi/model/Event","libs/moment","underscore"],function(e,t,n,r,i){"use strict";return e.extend({model:n,bySite:!0,triggerReset:!1,url:function(){return"/api/s/"+SITE.name+"/stat/event"},comparator:function(e){return-r(e.get("datetime"))},filtered:function(e){return this.fetch(i.extend(e,{_method:"read-filtered"}))},sync:function(e,n,r){r=r||{},r._method&&(e=r._method,delete r._method);switch(e){case"read":r.url="/api/s/"+SITE.name+"/stat/event",r.contentType="application/json; charset=utf-8",r.type="POST",r.data=JSON.stringify({_sort:"-time"});break;case"read-filtered":r.url="/api/s/"+SITE.name+"/stat/event",r.contentType="application/json; charset=utf-8",r.type="POST",r.data=JSON.stringify(i.extend({_sort:"-time"},r.data||{}))}return t.sync.call(this,e,n,r)}})}),define("text!includes/events/eventsTemplate.html",[],function(){return'<div class="section section-panel section-events">\n    <div class="section-header clearfix">\n        <h2><%- msg.G_Events %></h2>\n        <div class="hide-panel ubnt-icon-arrows-down right"></div>\n\n        <form class="data-filters clearfix">\n            <div class="buttonset">\n                <input type="radio" id="eventsFilterAll" name="filter" value="" checked="checked" />\n                <label for="eventsFilterAll"><%- msg.G_EventsAll %></label>\n                <input type="radio" id="eventsFilterAdmin" name="filter" value="admin" />\n                <label for="eventsFilterAdmin"><%- msg.G_EventsAdmin %></label>\n                <input type="radio" id="eventsFilterLan" name="filter" value="lan" />\n                <label for="eventsFilterLan"><%- msg.G_EventLan %></label>\n                <input type="radio" id="eventsFilterWlan" name="filter" value="wlan" />\n                <label for="eventsFilterWlan"><%- msg.G_EventWlan %></label>\n            </div>\n\n            <div class="options">\n                <label for="eventsTimeframe" class="label left"><%- msg.G_EventsWithin %></label>\n\n                <div class="select left">\n                    <select name="time-filter" id="eventsTimeframe" class="plain">\n                        <option value="1" selected="selected">1 <%- msg.G_Hour %></option>\n                        <option value="8">8 <%- msg.G_Hours %></option>\n                        <option value="24">24 <%- msg.G_Hours %></option>\n                        <option value="48">2 <%- msg.G_Days %></option>\n                        <option value="168">7 <%- msg.G_Days %></option>\n                        <option value="336">2 <%- msg.G_Weeks %></option>\n                        <option value="720">1 <%- msg.G_Month %></option>\n                    </select>\n                </div>\n            </div>\n\n            <span class="ubnt-icon-search"></span>\n            <input type="text" name="search" class="search right" />\n        </form>\n    </div>\n\n    <div class="data-table simple">\n        <div class="loading"><span><%- msg.N_Loading %></span></div>\n    </div>\n</div>\n'}),define("unifi/view/app/EventsView",["unifi/view/app/PanelListContentView","unifi/collection/Events","underscore","jquery","msg/Msg","text!includes/events/eventsTemplate.html"],function(e,t,n,r,i,s){"use strict";return e.extend({id:"events",_templateId:n.template(s,{msg:i}),_collectionType:{name:"Events",Class:t},_fetchMethod:"filtered",_limitTimeframe:1,_limitType:null,_renderBadge:!1,_badgeSelector:"#toggleEvents",render:function(){var t=this.rendered;e.prototype.render.call(this);if(!t){this.$(".hide-panel").on("click",function(){r("#toggleEvents").trigger("click")}),this.$container.one("show",function(e){r(e.target).find("select").each(function(){var e=r(this);e.selectmenu({parent:e.parent(),appendTo:r("#columnMainPanel"),icons:{button:"ubnt-icon-arrow-down secondary-color"},position:{at:"left bottom",collision:"flip"},change:function(){e.trigger("change")}})})});var n=this;this.$el.find("select[name=time-filter]").on("change",function(){n._limitTimeframe=Math.max(parseInt(r(this).find("option:selected").val(),10),1),n.load(!0)}),this.$el.find(".buttonset input[name=filter]").on("change",function(){n._limitType=r(this).val(),n.load(!0)})}},load:function(t){t=t||!this.collection;if(!this.collection||t)this.collection&&this.collection.reset(),e.prototype.load.call(this,t,{data:{within:this._limitTimeframe,type:this._limitType}})},remove:function(){this.$(".hide-panel").off("click"),this.$el.find("select[name=time-filter]").off("change"),this.$el.find(".buttonset input[name=filter]").off("change"),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/view/app/PropertiesView",["backbone","jquery"],function(e,t){"use strict";return e.View.extend({render:function(){if(!this.rendered&&(this.rendered=!0)){t.expr[":"].activeAccordion=function(e){return t(e).find("> .ui-accordion-header").hasClass("ui-state-active")};var e=this.$el;e.on("toggle",function(){var e=t(this),n=e.find("> .accordion");n.length===n.filter(":activeAccordion").length?e.trigger("minimize"):e.trigger("maximize")}).on("minimize",function(){t(this).find("> .accordion:activeAccordion").find(".ui-accordion-header").click()}).on("maximize",function(){t(this).find("> :not(.accordion:activeAccordion)").find(".ui-accordion-header").click()}).on("empty",function(){t(this).find("> .accordion").find(".remove").click()}),t("#columnEastHeader .toggle-all").on("click",function(){e.trigger("toggle")}),t("#columnEastHeader .remove-all").on("click",function(){e.trigger("empty")}),this.$el.sortable({axis:"y",handle:"> .accordion-header",containment:"parent",opacity:.8,tolerance:"pointer",stop:function(e,t){t.item.find("> .accordion-header").triggerHandler("focusout")}}),this.$el.on("property:remove",function(){e.find("> .accordion").size()||t("#columnEast").panel("hide","west",!0)}),this.$el.on("property:render",function(){t("#columnEast").panel("show","west",!0)}),t.Body.append(this.$detached=t('<div id="propertiesLayer" />')),this.$detached.on("click","> .properties",function(e){var n=t(e.target),r=n.hasClass("properties")?n:n.parents(".properties"),i=t.makeArray(r.siblings(".properties")).sort(function(e,n){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(n).css("zIndex"),10)||0)});if(i.length){var s=parseInt(t(i[0]).css("zIndex"),10)||0;t(i).each(function(e){t(this).css("zIndex",s+e)}),r.css("zIndex",s+i.length)}})}},remove:function(){this.$el.off("toggle").off("minimize").off("maximize").off("empty"),t("#columnEastHeader .toggle-all").off("click"),t("#columnEastHeader .remove-all").off("click"),this.$el.off("property:remove"),this.$el.off("property:render"),this.$detached.off("click","> .properties"),this.rendered=!1,e.View.prototype.remove.apply(this,arguments)}})}),define("ubnt/ubnt.layout",["jquery","jquery-ui"],function(e){"use strict";e.widget("ubnt.layout",e.ui.mouse,{_create:function(){this.handles=[],this.elements=[],this.direction=null,this.originalMousePosition=null;for(var e in this.options.directions)this.options.directions.hasOwnProperty(e)&&this._initDirection(e,this.options.directions[e]);this._mouseInit()},_destroy:function(){this._mouseDestroy();for(var t in this.handles)this.handles.hasOwnProperty(t)&&this.handles[t].remove();this.element.removeClass("ubnt-layout ubnt-layout-resizing"),e("body").css("cursor","auto")},_initDirection:function(t,n){e.inArray(t,["north","south","east","west"]!==-1)&&(this.element.addClass("ubnt-layout"),n.draggable&&this.element.append(this.handles[t]=e('<div class="ubnt-layout drag-handle '+t+'" title="drag to expand or collapse"></div>')),this.elements[t]=n.also||[],this.elements[t].unshift({element:this.element,property:n.property,inverse:!1}))},_setInitial:function(e){for(var t in this.elements[e])if(this.elements[e].hasOwnProperty(t)){var n=this.elements[e][t];this.elements[e][t].initial=parseInt(n.element.css(n.property),10)}},_mouseCapture:function(t){for(var n in this.handles)if(e(this.handles[n])[0]==t.target)return this.direction=n,!0},_mouseStart:function(t){this.originalMousePosition={left:t.pageX,top:t.pageY},this._setInitial(this.direction),this.element.addClass("ubnt-layout-resizing"),e("body").css("cursor",this.direction.substring(0,1)+"-resize")},_mouseDrag:function(e,t,n){var r=0;t=t||e.pageX-this.originalMousePosition.left||0,n=n||e.pageY-this.originalMousePosition.top||0;switch(this.direction){case"north":r=-n;break;case"south":r=n;break;case"east":r=t;break;case"west":r=-t}this._resize(this.direction,r,!0)},_mouseStop:function(){this._constrain(this.direction),this.direction=null,this.element.removeClass("ubnt-layout-resizing"),e("body").css("cursor","auto")},_constrain:function(t){var n=this.options.directions[t],r=n.constraints,i=null,s=null;if(r){s=parseInt(this.element.css(n.property),10);if(r.min){i=e.isFunction(r.min)?r.min():r.min;if(s<i)return this._resize(t,i,!1)}if(r.max){i=e.isFunction(r.max)?r.max():r.max;if(s>i)return this._resize(t,i,!1)}}},_resize:function(e,t,n,r){n||(t-=this.elements[e][0].initial);for(var i in this.elements[e])if(this.elements[e].hasOwnProperty(i)){var s=this.elements[e][i];if(r){var o={};o[s.property]=(s.initial||0)+(s.inverse?-t:t),i>0&&delete r.complete,s.element.animate(o,r)}else s.element.css(s.property,(s.initial||0)+(s.inverse?-t:t))}},resize:function(t,n,r,i,s){this._setInitial(t),n=e.isFunction(n)?n():n,this._resize(t,n,r,i),s&&this._constrain(t)},position:function(e){var t=this.elements[e][0];return parseInt(t.element.css(t.property),10)}})}),define("ubnt/ubnt.panel",["jquery","jquery-ui","ubnt/ubnt.layout"],function(e){"use strict";e.widget("ubnt.panel",e.ubnt.layout,{_create:function(){e.ubnt.layout.prototype._create.apply(this,arguments),this.options.id=this.element.attr("id"),this.options.active="active",this._animating=0,this._visible={};var t=this.element.is(":visible");for(var n in this.options.directions)if(this.options.directions[n].hasOwnProperty("property")){this._visible[n]=t;if(this.options.directions.hasOwnProperty(n)&&this.options.directions[n].hasOwnProperty("buttons"))for(var r in this.options.directions[n].buttons)this.options.directions[n].buttons.hasOwnProperty(r)&&(this.options.directions[n].buttons[r].on("click",e.proxy(this,"toggle",n)),t?this.options.directions[n].buttons[r].addClass(this.options.active):this.element.data(this._datavar(n),this.position(n)))}},_destroy:function(){e.ubnt.layout.prototype._destroy.apply(this,arguments);for(var t in this.options.directions)if(this.options.directions.hasOwnProperty(t)){this.element.removeData(this._datavar(this.options.directions[t]));for(var n in this.options.directions[t].buttons)this.options.directions[t].buttons.hasOwnProperty(t)&&this.options.directions[t].buttons[t].off("click").removeClass(this.options.active)}},_datavar:function(e){return"layout-position-"+e},show:function(t,n,r){if(!this._animating&&!this.visible(t)){var i=this.options.directions[t].callbacks;i&&i.beforeShow&&i.beforeShow(),e("body").removeClass(this.options.id+"Hidden"),this.element.show(),this._animating++,this.resize(t,this.element.data(this._datavar(t)),!1,{duration:n?0:this.options.duration,start:e.proxy(function(){this.element.trigger("ubnt.panel.showing")},this),complete:e.proxy(function(){this.element.trigger("ubnt.panel.shown"),this._visible[t]=!0,this._animating--,r&&r(n),i&&i.show&&i.show(n)},this)});var s=this.options.directions[t].buttons;for(var o in s)s.hasOwnProperty(o)&&s[o].addClass(this.options.active)}},hide:function(t,n){if(!this._animating&&this.visible(t)){var r=this.options.directions[t].callbacks;r&&r.beforeHide&&r.beforeHide(),this.element.data(this._datavar(t),this.position(t)),this._animating++,this.resize(t,0,!1,{duration:n?0:this.options.duration,start:e.proxy(function(){this.element.trigger("ubnt.panel.hiding")},this),complete:e.proxy(function(){e("body").addClass(this.options.id+"Hidden"),this.element.trigger("ubnt.panel.hidden"),this._visible[t]=!1,this._animating--,r&&r.hide&&r.hide(n)},this)});var i=this.options.directions[t].buttons;for(var s in i)i.hasOwnProperty(s)&&i[s].removeClass(this.options.active)}},toggle:function(e){this.visible(e)?this.hide(e):this.show(e)},visible:function(e){return this._visible[e]}})}),define("unifi/view/app/AdminView",["unifi/view/app/ChromeView","unifi/view/app/AlertsView","unifi/view/app/EventsView","unifi/view/app/PropertiesView","underscore","msg/Msg","jquery","ubnt/GoogleAnalytics","ubnt/ubnt.panel"],function(e,t,n,r,i,s,o,u){"use strict";return e.extend({initialize:function(s){var u=this;e.prototype.initialize.call(this,s),this.config.site="Admin",this.$properties=o("#columnEastContent > .content"),this.$content=o("#columnMainContent"),this.$panel=o("#columnMainPanel"),this.$alerts=o("#panelAlerts"),this.$events=o("#panelEvents"),this.contentSize=i.bind(this.contentSize,this),o(window).on("resize",this.contentSize),this.views.alerts=new t({container:this.$alerts,app:this.options.app}),this.views.events=new n({container:this.$events,app:this.options.app}),this.views.properties=new r({el:this.$properties})},render:function(){var t=this.rendered;e.prototype.render.call(this);if(!t){o("#columnWestToggles").append(o('<li id="toggleAlerts"><div class="ubnt-icon-warning toggle-icons toggle-alerts"><span class="ir">'+s.G_ToggleAlerts+"</span></div></li>")).append(o('<li id="toggleEvents"><div class="ubnt-icon-calendar toggle-icons toggle-events"><span class="ir">'+s.G_ToggleEvents+"</span></div></li>")),o.Body.append(o('<div id="showSidebar" class="show-sidebar" title="Show Properties"><span class="ubnt-icon-properties-drop"></span><span class="underlay"></span><span class="ir">'+s.G_ShowSidebar+"</div>")),o("#columnEast").panel({duration:350,directions:{west:{draggable:!1,property:"width",constraints:{max:500,min:o("#columnEast").width()},also:[{element:o("#columnMain > .content"),property:"margin-right",inverse:!1}],buttons:[o("#columnEastHeader .toggle-sidebar"),o("#showSidebar")],callbacks:{beforeShow:this.contentSize,hide:function(e){e||o("#showSidebar").effect("shake",{times:1,distance:5},300)}}}}}),o("#columnMainPanel").panel({duration:350,directions:{north:{draggable:!0,property:"height",constraints:{max:o(window).height()-o("#header").height(),min:35},also:[{element:o("#columnMainContent"),property:"bottom",inverse:!1}]}}}),o("#columnMainPanel").panel("hide","north",!0),o("#columnEast").panel("hide","west",!0),o(".columnOuterContainer").removeClass("invisible"),o("#toggleAlerts, #toggleEvents").on("click",o.proxy(function(e){var t=o(e.target).closest("li"),n=t.attr("id").replace("toggle",""),r=o("#panel"+n);t.hasClass("active")?(this.$panel.one("ubnt.panel.hidden",function(){t.removeClass("active")}),this.$panel.panel("hide","north")):(this.$panel.panel("visible","north")?(this.showPanel(r,t),r.trigger("show:complete")):(this.$panel.one("ubnt.panel.showing",o.proxy(function(){this.showPanel(r,t)},this)),this.$panel.panel("show","north",!1,function(){r.trigger("show:complete")})),u.trackEvent("button","click","open "+n.toLowerCase()))},this)),o("#columnWestToggles").show(),o.Body.removeClass("columnWestTogglesHidden");var n=(new RegExp("[?&]settings=([^&]*)(&id=([a-z0-9]*))?")).exec(window.location.search);n&&this.openSettings(decodeURIComponent(n[1].replace(/\+/g," ")),n[3])}return i.each(this.views,function(e,t){e.render()},this),this.views.alerts._renderBadge&&this.views.alerts.load(),this.views.events._renderBadge&&this.views.events.load(),this.settings&&this.stopListening(this.settings,"change sync add",this.reflectSettingChanges),this.settings=this.app.collection("Settings"),this.listenTo(this.settings,"change sync add",this.reflectSettingChanges),this.reflectSettingChanges(),this},showPanel:function(e,t){t.addClass("active").siblings("li").removeClass("active"),e.show().trigger("show").siblings().hide().trigger("hide")},contentSize:function(){},openSettings:function(e,t){e&&(this.options.app.settings=e,o("#navigation").find("a[data-page=settings]").trigger("click",t))},reflectSettingChanges:function(){var e=this.app.collection("Settings"),t=e.getSettingFromKey("voip",SITE.id),n=!!t&&!!t.get("enabled");o.Body.toggleClass("hasVoip",n);if(n){var r=e.findWhere({key:"provider",site_id:SITE.id}),i=!!r&&r.get("type")==="external";o.Body.toggleClass("externalPbx",i),o.Body.toggleClass("internalPbx",!i)}},reset:function(){e.prototype.reset.call(this),o("#columnWestToggles li.active").removeClass("active"),o("#columnMainPanel").panel("hide","north",!0),o("#columnEast").panel("hide","west",!0)},remove:function(){i.each(this.views,function(e){e.remove&&e.remove()},this),this.views={},o(window).off("resize",this.contentSize),o("#toggleAlerts, #toggleEvents").off("click"),this.stopListening(this.settings,"change sync add",this.reflectSettingChanges),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/view/test/IndexView",["unifi/view/app/ContentView","unifi/view/settings/VoipAudioPickerView","unifi/model/Audio"],function(e,t,n){"use strict";return e.extend({id:"testIndex",initialize:function(t){e.prototype.initialize.call(this,t),this.render()},render:function(){var r=this;e.prototype.render.call(this),this.greeting=new t({app:r.app,el:this.$el,model:new n({_id:"54401250a0ee44a0e85af213",type:"tts",text:"hello"})}),this.greeting.populate()}})}),define("unifi/router/TestRouter",["unifi/router/Router","unifi/view/test/IndexView"],function(e,t){"use strict";return e.extend({_fullyQualifiedName:"UNIFI.Routers.Test",_associatedViews:{Index:t},routes:{test:"index"}})}),require(["jquery","app","unifi/router/DashboardRouter","unifi/router/MapRouter","unifi/router/DevicesRouter","unifi/router/ClientsRouter","unifi/router/CallsRouter","unifi/router/StatisticsRouter","unifi/router/InsightsRouter","unifi/router/SupportRouter","unifi/view/app/AdminView","unifi/router/TestRouter","unifi/collection/Sites","unifi/collection/Devices","unifi/collection/Clients","unifi/collection/Settings"],function(e,t,n,r,i,s,o,u,a,f,l,c,h,p,d,v){"use strict";e(function(){var e={Dashboard:n,Map:r,Devices:i,Clients:s,Calls:o,Statistics:u,Insights:a,Support:f,Test:c},m={Sites:h,Devices:p,Clients:d,Settings:v};t.initialize(e,m,l)})}),define("manage",function(){});