/*
  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.
 */

/*
  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')
          ]
        }
      }
    });
 */

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(t,e,n,i){"use strict";return t.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 t,e,s,a,r,o,l=[];switch(this.get("subsystem")){case"www":var c=this.get("ip"),d=this.get("nameservers"),h=this.get("uptime");if(o=this.get("gateways"),c&&l.push({name:"IP",value:this.get("ip")}),n.isArray(o)&&o.length>0&&l.push({name:"GATEWAY",value:this.get("gateways").join(" ")}),n.isArray(d)&&d.length>0&&l.push({name:"DNS",value:this.get("nameservers").join(" ")}),h){if(this.has("latency")){var u=this.get("latency");l.push({name:"LATENCY",value:(1>=u?"<1":u)+" ms"})}l.push({name:"UPTIME",value:i.Formatters.Seconds.fromRaw(h)})}return l;case"wan":var p=this.get("num_gateway"),m=this.get("num_sta");return s=this.get("tx_bytes-r"),a=this.get("rx_bytes-r"),void 0!==p||void 0!==m||void 0!==a||void 0!==s?[{name:"LAN IP",value:this.get("lan_ip")},{name:"CLIENTS",value:m},{name:"DOWN",value:i.Formatters.BytesPerSecond.fromRaw(a)||0},{name:"UP",value:i.Formatters.BytesPerSecond.fromRaw(s)||0}]:null;case"lan":var f=this.get("num_sw");return r=this.get("num_adopted"),o=this.get("gateways"),t=this.get("num_user"),e=this.get("num_guest"),a=this.get("tx_bytes-r"),s=this.get("rx_bytes-r"),void 0!==f||void 0!==e||void 0!==a||void 0!==s?(l=[{name:"SWITCHES",value:f==r?f:f+" / "+r},{name:"USERS",value:t},{name:"GUESTS",value:e}],n.isArray(o)&&o.length>0&&l.push({name:"DOWN",value:i.Formatters.BytesPerSecond.fromRaw(a)||0},{name:"UP",value:i.Formatters.BytesPerSecond.fromRaw(s)||0}),l):null;case"wlan":var g=this.get("num_ap");return r=this.get("num_adopted"),t=this.get("num_user"),e=this.get("num_guest"),a=this.get("tx_bytes-r"),s=this.get("rx_bytes-r"),void 0!==g||void 0!==t||void 0!==e||void 0!==a||void 0!==s?[{name:"APS",value:g==r?g:g+" / "+r},{name:"USERS",value:t},{name:"GUESTS",value:e},{name:"DOWN",value:i.Formatters.BytesPerSecond.fromRaw(a)||0},{name:"UP",value:i.Formatters.BytesPerSecond.fromRaw(s)||0}]:null;case"voip":var v=this.get("num_phone");return r=this.get("num_adopted"),[{name:"PHONES",value:v==r?v:v+" / "+r},{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(t,e,n,i,s,a,r,o){"use strict";return e.View.extend({initialize:function(t){n.bindAll(this),this.dashboardTable=i("#dashboardTable"),this.tableItemTemplate=n.template(s),this.model=t.model,this.app=t.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 t=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:r}))),this.configureLink=this.model.get("configureLink"),this.statsLink=this.model.get("statsLink"),this.$tableItem=this.dashboardTable.find(".table-item."+t),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(t){this.model&&t&&(this.model.clear({silent:!0}),this.model=new o(t.toJSON())),this.updateState(),this.updateStats(),this.updateNotifications()},updateState:function(){var t=this.model.state(),e=this.model.possibleStates;this.$el.removeClass(e.join(" ")).addClass(t),this.$tableItem.removeClass(e.join(" ")).addClass(t);var n=this.$tableItem.find(".state");n.removeClass(e.join(" ")).addClass(t),n.text(r[this.model.get("status_text")])},updateStats:function(){var t=this.model.stats(),e=this.$tableItem.find(".stats"),i=this.$tableItem.find(".no-data");if(t?(e.empty().removeClass("hidden"),i.addClass("hidden"),n.each(t,function(t){e.append(n.template(a,t))},this)):(e.empty().addClass("hidden"),i.removeClass("hidden")),"wan"===this.model.get("subsystem")){var s=this.model.get("gw_mac")?!0:!1;this.$tableItem.find(".btn-configure").toggle(s)}},updateNotifications:function(){var t=n.size(this.model.get("notifications"));t>0?this.showNotifications():this.hideNotifications();var e=this.$notifications.find(".count");parseInt(e.text(),10)<t&&this.$notifications.effect("shake",{direction:"up",times:1,distance:5},300),e.text(t)},showNotifications:function(){this.$notifications.show()},hideNotifications:function(){this.$notifications.hide()},viewNotifications:function(){var t=this.model.get("subsystem"),e=i("#panelAlerts"),n=e.is(":visible");n||i("#toggleAlerts").click(),e.find(".data-filters").find('input[value="'+t+'"]').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,e.View.prototype.remove.apply(this,arguments)}})}),define("unifi/collection/Subsystems",["unifi/collection/Collection","backbone","unifi/model/Subsystem","ubnt/backgrid"],function(t,e,n){"use strict";return t.extend({model:n,bySite:!0,possibleSubsystems:["www","wan","lan","wlan","voip"],url:function(){return"/api/s/"+SITE.name+"/stat/health"},getSubsystem:function(t){return this.findWhere({subsystem:t})}})}),define("unifi/model/SpeedTest",["unifi/model/Model","backbone","underscore","msg/Msg","libs/moment"],function(t,e,n,i,s){"use strict";return t.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(t,n,i){var s=[];switch(i=i||{},i._method&&(t=i._method,delete i._method),t){case"read":if(i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/cmd/devmgr",this.isTesting&&(i.url="/data/speedtest/"+this.speedtestIndex+".json"),i.type="POST",i.data=JSON.stringify({cmd:"speedtest-status"}),1===this.getStatus("download")){if(this.download_arrayIndex<this.download_array.length){if(s=this.download_array[this.download_arrayIndex],void 0===s){this._increaseTestIndex();break}return this.download_value=s[1]/100,this.set("xput_download",this.download_value),void this.download_arrayIndex++}this._increaseTestIndex();break}if(1===this.getStatus("upload")){if(this.upload_arrayIndex<this.upload_array.length){if(s=this.upload_array[this.upload_arrayIndex],void 0===s){this._increaseTestIndex();break}return this.upload_value=s[1]/100,this.set("xput_upload",this.upload_value),void this.upload_arrayIndex++}this._increaseTestIndex();break}this._increaseTestIndex();break;case"start":this.initializeProgressRecords(),i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/cmd/devmgr",i.type="POST",i.data=JSON.stringify({cmd:"speedtest"})}return e.sync.call(this,t,n,i)},_increaseTestIndex:function(){this.isTesting&&(this.speedtestIndex++,this.speedtestIndex>this.speedtestMaxIndex&&(this.speedtestIndex=1))},clearArray:function(t){for(;t.length;)t.pop()},initializeProgressRecords:function(){var t=this;n.each(["download","upload"],function(e){t[e+"_id"]=0,t[e+"_value"]=0,t[e+"_arrayIndex"]=0,t.clearArray(t[e+"_array"])})},getStatus:function(t){return this.get(t?"status_"+t:"summary_status")},getResult:function(t){switch(t){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 s(this.get("rundate"),"X").format("YYYY/MM/DD HH:mm:ss")},getProgressRecords:function(){var t=this,e=[];n.each(["download","upload"],function(i){e=t.get(i+"-progress"),n.each(e,function(e){e.id>t[i+"_id"]&&(t[i+"_id"]=e.id,t[i+"_array"]=t[i+"_array"].concat(e.records))})})},convertToMbps:function(t){return t/100},convertMbpsToPercentage:function(t,e){var n=this.convertToMbps(t);return n>e&&(n=e),n/e*100}})}),define("unifi/model/Event",["unifi/model/Model","underscore"],function(t,e){"use strict";return t.extend({toSearch:function(){var t,n,i={};return(t=this.attributes.msg.match(/([a-z0-9\-]{2,})/gi))&&e.each(t,function(t,e){i["word"+e]=t}),(n=this.attributes.msg.match(/(([0-9A-F]{2}:){5}([0-9A-F]{2}))/gi))&&e.each(n,function(t,e){i["mac"+e]=t}),i}})}),define("unifi/model/Alert",["unifi/model/Event","backbone"],function(t,e){"use strict";return t.extend({archive:function(t){return this.sync("archive",this,t)},sync:function(t,n,i){switch(i=i||{},t){case"archive":i.url="/api/s/"+SITE.name+"/cmd/evtmgr",i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify({_id:n.id,cmd:"archive-alarm"})}return e.sync.call(this,t,n,i)}})}),define("unifi/collection/Alerts",["unifi/collection/Collection","backbone","unifi/model/Alert","libs/moment","underscore"],function(t,e,n,i,s){"use strict";return t.extend({model:n,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/list/alarm"},comparator:function(t){return-i(t.get("datetime"))},parse:function(e,n){return s.filter(t.prototype.parse.call(this,e,n),function(t){return!!t.msg})},archiveAll:function(t){return this.sync("archive-all",this,t)},archived:function(t){return this.fetch(s.extend(t,{_method:"read-archived"}))},unarchived:function(t){return this.fetch(s.extend(t,{_method:"read-unarchived"}))},sync:function(t,n,i){switch(i=i||{},i._method&&(t=i._method,delete i._method),t){case"read":i.url="/api/s/"+SITE.name+"/list/alarm",i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify({_sort:"-time"});break;case"read-archived":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/list/alarm",i.type="POST",i.data=JSON.stringify({_sort:"-time",archived:!0});break;case"read-unarchived":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/list/alarm",i.type="POST",i.data=JSON.stringify({_sort:"-time",archived:!1});break;case"archive-all":i.url="/api/s/"+SITE.name+"/cmd/evtmgr",i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify({cmd:"archive-all-alarms"})}return e.sync.call(this,t,n,i)}})}),define("unifi/model/PortModel",["unifi/model/Model","underscore","backbone","msg/Msg","app","ubnt/backgrid"],function(t,e,n,i,s,a){"use strict";return t.extend({diagramClasses:function(){var t=[];return this.get("poe_enable")&&t.push("poe"),"mirror"==this.get("op_mode")&&t.push("mirror"),this.get("enable")||t.push("shutdown"),this.get("up")&&(t.push("up"),1e3==this.get("speed")?t.push("green"):(100==this.get("speed")||10==this.get("speed"))&&t.push("orange"),"discarding"==this.get("stp_state")&&t.push("block")),t.join(" ")},diagramTooltip:function(){var t="<table>",e=this.portIdxText(),n=this.get("name"),s=this.get("media"),r=this.statusText(),o=this.get("tx_bytes")&&a.Formatters.Bytes.fromRaw(this.get("tx_bytes")),l=this.get("rx_bytes")&&a.Formatters.Bytes.fromRaw(this.get("rx_bytes")),c=this.poeModeText(),d=this.networksVlansText(),h='<tr class="table-row"><td class="column-name">{1}</td><td class="column-value">{2}</td></tr>';if(e&&(t+=i.localize(h,i.G_Port,e)),n&&(t+=i.localize(h,i.G_Name,n)),r&&(t+=i.localize(h,i.G_Status,r)),o&&(t+=i.localize(h,i.G_DevicesTX,o)),l&&(t+=i.localize(h,i.G_DevicesRX,l)),c&&(t+=i.localize(h,i.G_PropertiesPoE,c)),d&&(t+=i.localize(h,i.G_PropertiesNetworksVLANs,d)),("SFP"===s||"SFP+"===s)&&this.get("sfp_found")){var u=this.get("sfp_vendor"),p=this.get("sfp_serial"),m=this.get("sfp_part"),f=this.get("sfp_rev"),g=this.get("sfp_compliance"),v=this.get("sfp_voltage"),b=this.get("sfp_current"),w=this.get("sfp_txpower"),y=this.get("sfp_rxpower"),_=this.get("sfp_temperature"),x=this.get("sfp_txfault"),k=this.get("sfp_rxfault");u&&(t+=i.localize(h,i.G_PropertiesSFPVendor,u)),p&&(t+=i.localize(h,i.G_PropertiesSFPSerial,p)),m&&(t+=i.localize(h,i.G_PropertiesSFPPartNum,m)),f&&(t+=i.localize(h,i.G_PropertiesSFPRev,f)),g&&(t+=i.localize(h,i.G_PropertiesSFPCompliance,g)),v&&(t+=i.localize(h,i.G_PropertiesSFPVoltage,v)),b&&(t+=i.localize(h,i.G_PropertiesSFPCurrent,b)),_&&(t+=i.localize(h,i.G_Temperature,_+i.G_DegreeCelsius)),w&&(t+=i.localize(h,i.G_PropertiesSFPOutputPower,w)),y&&(t+=i.localize(h,i.G_PropertiesSFPInputPower,y)),x&&(t+=i.localize(h,i.G_PropertiesSFPTXError,x)),k&&(t+=i.localize(h,i.G_PropertiesSFPRXError,k))}return t+="</table>"},portIdxText:function(){var t=this.get("port_idx");return this.get("masked")?"":("aggregate"==this.get("op_mode")&&(t+="-"+(parseInt(t,10)+parseInt(this.get("aggregate_num_ports")-1,10))),t)},statusText:function(){if(this.get("up")){var t=this.get("speed");return t+=" ",t+=this.get("full_duplex")?i.G_PropertiesFullDuplexAbbrv:i.G_PropertiesHalfDuplexAbbrv,this.get("is_uplink")&&(t+=" ("+i.G_PropertiesUplink+")"),"discarding"==this.get("stp_state")&&(t+=" ("+i.G_PropertiesBlocked+")"),t}return""},poeModeText:function(){if(!this.get("port_poe"))return"";if("switch"!==this.get("op_mode")||this.get("masked"))return"";var t=this.get("poe_mode");return"auto"===t&&this.get("poe_enable")?this.get("poe_power")+"w":"auto"===t?i.G_PropertiesPoEModePoEPlus:"pasv24"===t?i.G_PropertiesPoEModePassive:t},networksVlansText:function(){if(this.get("aggregated_by"))return i.G_PropertiesAggregatedByPort+" "+this.get("aggregated_by");if("mirror"==this.get("op_mode"))return i.G_PropertiesMirroringPort+" "+this.get("mirror_port_idx");var t=this.get("portconf_id");if(t){var e=s.collection("PortConf").get(t);if(e)return e.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(t,e,n,i,s,a,r,o){"use strict";return t.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||"usw"==this.attributes.type)&&this.syncPortTable()},validate:function(t,e){var n={},i=e?e.partial:null;if("advance-adopt"==i&&(t.username||(n.username=a.localize(a.E_CannotBeEmpty,a.G_UN)),t.password||(n.password=a.localize(a.E_CannotBeEmpty,a.G_PW))),t.port_overrides&&e.extra&&e.extra.portidx){var s=r.findWhere(t.port_overrides,{port_idx:e.extra.portidx});if(s){if("aggregate"==s.op_mode&&(!i||"aggregate_num_ports"==i)){for(var o=e.extra.portidx+1,l=e.extra.portidx+3,c=this.numPorts(),d=4,h=this.get("port_table"),u=(h.length,e.extra.portidx);l>u;u++)if(l>u){var p=h[u];if(p&&"switch"!==p.op_mode){l=u,d=l-e.extra.portidx+1;break}}l>c&&(l=c,d=l-e.extra.portidx+1),this.validator.range(s.aggregate_num_ports,2,d)||(n.aggregate_num_ports=a.localize(a.E_IncorrectNumberRange,a.G_PropertiesAggregatePorts,o,l))}"mirror"!=s.op_mode||i&&"mirror_port_idx"!=i||s.mirror_port_idx!=e.extra.portidx&&this.validator.range(s.mirror_port_idx,1,this.numPorts())||(n.mirror_port_idx=a.localize(a.E_InvalidMirroringPort,s.mirror_port_idx))}}return i&&"config_network_wan"!=i||t.config_network_wan&&(r.size(n.config_network_wan=this.validateNetwork(t,"config_network_wan"))||delete n.config_network_wan),i&&"config_network"!=i||t.config_network&&(r.size(n.config_network=this.validateNetwork(t,"config_network"))||delete n.config_network),i&&"wlan_overrides"!=i||t.wlan_overrides&&(n.wlan_overrides={},r.each(t.wlan_overrides,function(e,i){n.wlan_overrides[i]={};var s;if(t.hasOwnProperty("wlanconf")){var o=t.wlanconf.attributes.vlan_enabled;s=e.hasOwnProperty("vlan_enabled")?e.vlan_enabled:o}else s=e.vlan_enabled;s&&""===e.vlan?n.wlan_overrides[i].vlan=a.localize(a.E_CannotBeEmpty,a.G_PropertiesVLAN):e.vlan&&!this.validator.range(e.vlan,2,4095)&&(n.wlan_overrides[i].vlan=a.localize(a.E_IncorrectNumberRange,a.G_PropertiesVLAN,2,4095)),e.x_passphrase&&!this.validator.password(e.x_passphrase)&&(n.wlan_overrides[i].x_passphrase=a.localize(a.E_InvalidPassphrase,a.G_PropertiesPSK)),r.size(n.wlan_overrides[i])||delete n.wlan_overrides[i]},this),r.size(n.wlan_overrides)||delete n.wlan_overrides),t.name&&!this.validator.name(t.name)&&t.name.toLowerCase()!==t.mac.toLowerCase()&&(n.name=a.localize(a.E_InvalidName,a.G_PropertiesAlias)),r.size(n)?n:void 0},validateNetwork:function(t,e){var n={};switch(t[e].type){case"dhcp":t[e].dns1&&!this.validator.ip(t[e].dns1)&&(n.dns1=a.localize(a.E_IncorrectIPAddress,a.G_PropertiesPreferredDNS)),t[e].dns2&&!this.validator.ip(t[e].dns2)&&(n.dns2=a.localize(a.E_IncorrectIPAddress,a.G_PropertiesAlternateDNS));break;case"pppoe":t[e].username||(n.username=a.localize(a.E_CannotBeEmpty,a.G_UN)),t[e].x_password||(n.x_password=a.localize(a.E_CannotBeEmpty,a.G_PW)),t[e].dns1&&!this.validator.ip(t[e].dns1)&&(n.dns1=a.localize(a.E_IncorrectIPAddress,a.G_PropertiesPreferredDNS)),t[e].dns2&&!this.validator.ip(t[e].dns2)&&(n.dns2=a.localize(a.E_IncorrectIPAddress,a.G_PropertiesAlternateDNS));break;case"static":t[e].ip?this.validator.ip(t[e].ip)||(n.ip=a.localize(a.E_IncorrectIPAddress,a.G_IPAddress)):n.ip=a.localize(a.E_CannotBeEmpty,a.G_IPAddress),t[e].netmask?this.validator.netmask(t[e].netmask,t[e].ip)||(n.netmask=a.localize(a.E_IncorrectNetmask,a.G_Netmask)):n.netmask=a.localize(a.E_CannotBeEmpty,a.G_Netmask),t[e].gateway&&!this.validator.ip(t[e].gateway)&&(n.gateway=a.localize(a.E_IncorrectIPAddress,a.G_PropertiesGateway)),t[e].dns1&&!this.validator.ip(t[e].dns1)&&(n.dns1=a.localize(a.E_IncorrectIPAddress,a.G_PropertiesPreferredDNS)),t[e].dns2&&!this.validator.ip(t[e].dns2)&&(n.dns2=a.localize(a.E_IncorrectIPAddress,a.G_PropertiesAlternateDNS))}return n},parse:function(e,n){return e=t.prototype.parse.call(this,e,n),e&&0!==parseInt(e.state,10)&&(e.restarting=!1),e&&(e.uptime=e.uptime?parseInt(e.uptime,10):0),e},toSearch:function(){var t={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&&r.each(this.attributes.vap_table,function(e,n){t["bssid_"+n]=e.bssid}),t},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 t=this.get("model")||"";switch(t){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"U7PG2":return"UniFi AP-AC-Pro";case"U7LR":return"UniFi AP-AC-LR";case"U7LT":return"UniFi AP-AC-Lite";case"U2M":return"UniFi AP-Mini";case"U2IW":return"UniFi AP-In Wall";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"US8P150":return"UniFi Switch 8 POE-150W";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"UP4":return"UniFi Phone-X";case"UP5c":return"UniFi Phone";case"UP5tc":return"UniFi Phone-Pro";case"UP7c":return"UniFi Phone-Executive"}return"UniFi "+t},isGen2Ap:function(){var t=this.get("model")||"";switch(t){case"U7PG2":case"U7LR":case"U7LT":return!0}return!1},isAntennaGainEditable:function(){var t=this.get("model")||"",e=["U2O","U5O","U2HSR"];return-1!==r.indexOf(e,t)?!0:!1},apIcon:function(){var t=this.get("model")||"";switch(t){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"US8P150":return 8;case"UGW3":return 3;case"UGW8":return 8}},txPower:function(){var t=this.transmitPower("ng"),e=this.transmitPower("na");return r.isUndefined(e)||r.isUndefined(t)?r.isUndefined(e)?r.isUndefined(t)?void 0:t:e:t>e?t:e},getFrequency:function(t,e){if("ng"==t){var n={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};return n[e]}if("na"==t){var i={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};return i[e]}return void 0},transmitFrequency:function(t){if("ng"==t){var e=this.transmitPower("ng"),n=this.get("ng-channel");if(!r.isUndefined(e))return this.getFrequency(t,n)}if("na"==t){var i=this.transmitPower("na"),s=this.get("na-channel");if(!r.isUndefined(i))return this.getFrequency(t,s)}return void 0},uptime:function(t){return t=t||this.get("uptime"),t>0?s.Formatters.Duration.fromRaw(t||0):""},power:function(){var t=0;return r.each(this.get("port_table"),function(e){t+=parseFloat(e.poe_power||0,10)}),t.toFixed(2)},fan_level:function(){var t=this.get("fan_level");return t>=0?t:a.G_SettingsOff},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 t=this.uplink();if(t){var e;if(t.hasOwnProperty("uplink_mac")?e=t.uplink_mac:"wireless"===t.type&&t.hasOwnProperty("ap_mac")&&(e=t.ap_mac),e)return e}return""},uplinkDeviceText:function(){var t=this.uplink();if(t){var e=this.uplinkDeviceMac(),n=this.collection.findWhere({mac:e});return n?n.name()+(t.uplink_remote_port?" #"+t.uplink_remote_port:""):e}return""},uplinkRemotePort:function(){var t=this.uplink();if(t){var e=this.uplinkDeviceMac(),n=this.collection.findWhere({mac:e});if(n&&t.uplink_remote_port)return t.uplink_remote_port}return null},uplinkRssi:function(){var t=this.uplink();return t?this.calcRssi(t.rssi):void 0},calcRssi:function(t){return void 0===t&&(t=this.get("rssi")),t=parseFloat(t),t?(t>45?t=45:5>t&&(t=5),t=(t-5)/40*99,(0===t?"0":t.toPrecision(2))+"%"):""},apXRate:function(t){return isNaN(t)?"":parseInt(t,10)/1e3+"M"},uplinkTxRate:function(){var t=this.uplink();return t?this.apXRate(t.tx_rate):""},uplinkRxRate:function(){var t=this.uplink();return t?this.apXRate(t.rx_rate):""},uplinkSpeed:function(){var t=this.uplink();return t?t.speed:"Unknown"},uplinkDuplex:function(){var t=this.uplink();return t&&t.full_duplex?"Full Duplex":"Half Duplex"},uplinkDownPackets:function(){var t=this.uplink();return t&&t.rx_packets&&t.rx_bytes?s.Formatters.Bytes.fromRaw(t.rx_packets)+"/"+s.Formatters.Bytes.fromRaw(t.rx_bytes):"0.00 / 0.00"},uplinkUpPackets:function(){var t=this.uplink();return t&&t.tx_packets&&t.tx_bytes?s.Formatters.Bytes.fromRaw(t.tx_packets)+"/"+s.Formatters.Bytes.fromRaw(t.tx_bytes):"0.00 / 0.00"},uplinkActivity:function(){var t=this.uplink(),e=t?t["tx_bytes-r"]:0,n=t?t["rx_bytes-r"]:0,i=e+n,a=0;return i&&(a=s.Formatters.Bytes.fromRaw(i)),a+"B / sec"},uplinkActivityDown:function(){var t=this.uplink(),e=t?t["rx_bytes-r"]:0,n=0;return e&&(n=s.Formatters.Bytes.fromRaw(e)),n+"B / sec"},uplinkActivityUp:function(){var t=this.uplink(),e=t?t["tx_bytes-r"]:0,n=0;return e&&(n=s.Formatters.Bytes.fromRaw(e)),n+"B / sec"},adoptIp:function(){return this.get("adopt_ip")||this.get("ip")},adoptPort:function(){return this.get("sshd_port")},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 t=this.get("ng-channel"),e=this.get("na-channel"),n=[];return t&&n.push(t+" (2G)"),e&&n.push(e+" (5G)"),n.length?n.join(", "):""},apChannel:function(){if(!this.get("vap_table"))return"";var t,e,i,s=[];return i=this.get("model"),r.each(this.get("vap_table"),function(a){return 0===a.channel?!0:"RUN"!=(a.state||"RUN")?!0:(e=a.radio,"na"!=e||"U7E"!=i&&"U7O"!=i&&"U7Ev2"!=i&&"U7PG2"!=i&&"U7LR"!=i&&"U7LT"!=i||(e="ac"),t=a.channel+" ("+e+")",void(n.inArray(t,s)<0&&("ng"==a.radio?s=[t].concat(s):s.push(t))))}),s.join(", ")},sortApChannel:function(){if(!this.get("vap_table"))return-1;var t=0;return r.each(this.get("vap_table"),function(e){if(0===e.channel)return!0;if("RUN"!=(e.state||"RUN"))return!0;var n=e.radio;"na"==n?t+=1e3*(parseInt(e.channel,10)||0):"ng"==n&&(t+=parseInt(e.channel,10)||0)}),t},getRadio:function(t){return r.find(this.get("radio_table"),function(e){return e.hasOwnProperty("radio")?e.radio===t:void 0})},getNss:function(t){var e=this.getRadio(t);return e&&e.nss?e.nss:null},hasRadio:function(t){return void 0===this.getRadio(t)?!1:!0},channel:function(t){var e=this.get(t+"-state")||"INIT",n=this.get(t+"-extchannel")||0,i=n>0?",+1":0>n?",-1":"",s=this.get(t+"-channel")+i;return"INIT"==e?s="":"DFS_WAIT"==e&&(s+=" (DFS Waiting)"),s},transmitPower:function(t){var e=this.get(t+"-state")||"INIT";if("INIT"==e)return void 0;var n=Math.min(this.get(t+"-tx_power"),30),i=this.get(t+"-gain")||0,s=this.get(t+"-eirp")||parseInt(n,10)+i;return s},packetsPerBytes:function(t,e){var n=this.get("stat"),i=n?n[t+"-"+e+"_packets"]:0,a=n?n[t+"-"+e+"_bytes"]:0;return i=i||0,a=a||0,s.Formatters.Bytes.fromRaw(i)+" / "+s.Formatters.Bytes.fromRaw(a)},errorPercentage:function(t,e){var n,i=this.get("stat"),a=i?i[t+"-"+e+"_retries"]:0,r=i?i[t+"-"+e+"_packets"]:0,o=i?i[t+"-"+e+"_dropped"]:0;return a=a||0,r=r||0,o=o||0,n=r+o,s.Formatters.Percentage.fromRaw(a,n)+" / "+s.Formatters.Percentage.fromRaw(o,n)},getOverride:function(t,e){var n=null,i=this.get("wlan_overrides")||[];return r.each(i,function(i){return i.wlan_id==t&&i.radio==e?(n=i,!1):void 0}),n},hasOverrides:function(t,e){var n=!1,i=this.get("wlan_overrides")||[];return r.each(i,function(t){return t.radio==e?(n=!0,!1):void 0}),n},wlan2G:function(t){return this.wlangroup(this.get("wlangroup_id_ng"),"ng",t)},wlan5G:function(t){return this.wlangroup(this.get("wlangroup_id_na"),"na",t)},wlangroup:function(t,e,n){if(!(this.get("adopted")&&this.get("radio_"+e)&&n&&r.size(n)))return"";var i=n.findWhere({_id:t})||n.findWhere({attr_hidden_id:"Default"}),s=i.get("name");return i.get("roam_enabled")?s+=" (ZH)":this.hasOverrides(i.get("id"),e)&&(s+=" (*)"),s},radio2G:function(){return this.radioChannelAndPower(this.get("radio_ng"))},radio5G:function(){return this.radioChannelAndPower(this.get("radio_na"))},radioChannelAndPower:function(t){if(!this.get("adopted")||!t)return"";var e=t.channel&&!isNaN(t.channel)?parseInt(t.channel,10):"auto",n=t.tx_power_mode||"auto";return"custom"===n&&(n=t.builtin_antenna===!0?parseInt(t.tx_power,10)+parseInt(t.builtin_ant_gain,10)+" dBm":parseInt(t.tx_power,10)+parseInt(t.antenna_gain,10)+" dBm"),0===e&&(e="auto"),e+" / "+n},sortRadio2G:function(){return this.sortRadio(this.get("radio_ng"),"ng")},sortRadio5G:function(){return this.sortRadio(this.get("radio_na"),"na")},sortRadio:function(t,e){if(void 0===t||null===t)return-1;var n=t.channel&&!isNaN(t.channel)?parseInt(t.channel,10):0,i=this.transmitPower(e);return void 0===i&&(i=0),1e3*n+i},clientName:function(t){return t.hostname||t.mac},deviceName:function(t){return t.essid||t.mac},status:function(){var t,e=this.uplink()||{};switch(parseInt(this.get("state"),10)||0){case 0:t=this.get("restarting")?a.G_APRestarting:a.G_APDisconnected;break;case 1:t=a.G_APConnected,this.get("isolated")?t+=" (limited)":"wire"==e.type?"ugw"!==this.get("type")&&(e.max_speed==e.speed&&e.full_duplex||(t+=" ("+e.speed+" "+(e.full_duplex?"FDX":"HDX")+")")):"wireless"==e.type&&(t+=" (wireless)"),this.get("version_incompatible")&&(t+=" (needs upgrade)");break;case 2:t=this.get("default")?"scan"==this.get("discovered_via")?a.G_APIsolatedPending:a.G_APPending:a.G_APManagedByOthers;break;case 3:t=a.G_APFirmwareMismatch;break;case 4:t=a.G_APUpgrading;break;case 5:t=a.G_APProvisioning;break;case 6:t=a.G_APHeartbeatMissed;break;case 7:t=a.G_APAdopting,"wireless"==e.type&&(t+=" (wireless)");break;case 8:t=a.G_APDeleting;break;case 9:t=a.G_APDisconnected;break;case 10:t=a.G_APAdoptFailed;break;case 11:t=a.G_APIsolated}return t},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"ok"===this.statusType()},is11ac:function(){return-1!==n.inArray(this.get("model"),["U7E","U7O","U7Ev2","U7PG2","U7LR","U7LT"])},hasDfs:function(){return-1!==n.inArray(this.get("model"),["U5O","U7P"])},noZh:function(){return-1!==n.inArray(this.get("model"),["U7E","U7O","U7Ev2","U7PG2","U7LR","U7LT"])},lastSeen:function(){var t,e=this.get("last_seen");return e?(t=(new Date).getTime()/1e3-parseInt(e,10),isNaN(t)?"":86400>t?s.Formatters.Duration.fromRaw(t)+" "+a.G_Ago:o(e+"","X").format("YYYY/MM/DD HH:mm:ss")):a.G_Never},lastScan:function(t){if(t){var e=(new Date).getTime()/1e3-parseInt(t,10);return isNaN(e)?a.G_Never:86400>e?s.Formatters.Duration.fromRaw(e)+" "+a.G_Ago:o(t+"","X").format("YYYY/MM/DD HH:mm:ss")
}return a.G_Never},absoluteLastSeen:function(){var t=this.get("last_seen");return t?o(t+"","X").format("YYYY/MM/DD HH:mm:ss"):""},syncPortTable:function(){this.collections.portTable||(this.collections.portTable=new(i.Collection.extend({model:e.extend({idAttribute:"port_idx"})}))),r.each(this.attributes.port_table,n.proxy(function(t){var e=r.filter(this.attributes.port_overrides,function(e){return e.port_idx==t.port_idx});e.length&&(t=r.extend(t,e[0])),t.device=this.get("mac"),this.collections.portTable.add(t,{merge:!0})},this)),this.trigger("syncPortTable")},upgrade:function(t){return this.sync("upgrade",this,t)},adopt:function(t){return this.sync("adopt",this,t)},advanceAdopt:function(t){return this.validationError=this.validate(t.data,r.extend({partial:"advance-adopt"},t)),this.validationError?!1:this.sync("advance-adopt",this,t)},forget:function(t){return this.sync("forget",this,t)},restart:function(t){return this.sync("restart",this,t)},powerCyclePort:function(t){return this.sync("power-cycle",this,t)},clearSwitchCounters:function(t){return this.sync("clear-switch-counters",this,t)},clearPortCounters:function(t){return this.sync("clear-switch-port-counters",this,t)},setVwireUplink:function(t){return this.sync("set-vwire-uplink",this,t)},unsetVwireUplink:function(t){return this.sync("unset-vwire-uplink",this,t)},move:function(t){return this.sync("move",this,t)},copyConfig:function(t){return this.sync("copy-config",this,t)},update:function(t){return this.sync("update",this,t)},locate:function(t){return this.sync("locate",this,t)},spectrumScan:function(t){this.sync("spectrum-scan",this,t)},updateWlanGroup:function(t,e){var n={};return n["wlangroup_id_"+t]=e.wlangroup_id,n.wlan_overrides=r.reject(this.get("wlan_overrides"),function(e){return e.radio==t}),this.save(n,r.extend(e,{_method:"update-wlangroup-"+t}))},sort_Clients:function(){return void 0===this.get("num_sta")?-1:parseInt(this.get("num_sta"),10)},sort_2GClients:function(){return void 0===this.get("ng-num_sta")?-1:parseInt(this.get("ng-num_sta"),10)},sort_5GClients:function(){return void 0===this.get("na-num_sta")?-1:parseInt(this.get("na-num_sta"),10)},sort_txBytesD:function(){return void 0===this.get("tx_bytes-d")?-1:this.get("tx_bytes-d")},sort_rxBytesD:function(){return void 0===this.get("rx_bytes-d")?-1:this.get("rx_bytes-d")},sort_txBytes2g:function(){var t=(parseInt(this.get("ng_ast_be_xmit"),10)||0)+(parseInt(this.get("ng_tx_packets"),10)||0);return t},sort_txBytes5g:function(){var t=(parseInt(this.get("na_ast_be_xmit"),10)||0)+(parseInt(this.get("na_tx_packets"),10)||0);return t},sync:function(t,e,n){switch(n=n||{},n._method&&(t=n._method,delete n._method),t){case"read":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/stat/device/"+e.get("mac"),n.type="GET";break;case"update":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/upd/device/"+e.id,n.type="POST",n.data=JSON.stringify(n.data?n.data:e.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(r.extend(n.data||{},{mac:e.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(r.extend(n.data||{},{mac:e.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(r.extend(n.data||{},{mac:e.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(r.extend(n.data||{},{mac:e.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(r.extend(n.data||{},{mac:e.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(r.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(r.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:e.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:e.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:e.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(r.extend(n.data||{},{mac:e.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(r.extend(n.data||{},{mac:e.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":e.set(e.get("adopted")?{locating:!e.get("locating")}:{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:e.get("mac"),cmd:e.get("adopted")?e.get("locating")?"set-locate":"unset-locate":"locate"});break;case"update-wlangroup-ng":n.contentType="application/json",n.url="/api/s/"+SITE.name+"/upd/device/"+e.id,n.type="POST",n.data=JSON.stringify(r.extend(n.data||{},{wlangroup_id_ng:e.get("wlangroup_id_ng"),wlan_overrides:e.get("wlan_overrides")}));break;case"update-wlangroup-na":n.contentType="application/json",n.url="/api/s/"+SITE.name+"/upd/device/"+e.id,n.type="POST",n.data=JSON.stringify(r.extend(n.data||{},{wlangroup_id_na:e.get("wlangroup_id_na"),wlan_overrides:e.get("wlan_overrides")}));break;case"spectrum-scan":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify({mac:e.get("mac"),cmd:"spectrum-scan"})}return i.sync.call(this,t,e,n)}})}),define("unifi/collection/Devices",["unifi/collection/Collection","underscore","backbone","unifi/model/Device"],function(t,e,n,i){"use strict";return t.extend({model:i,bySite:!0,initialize:function(e){t.prototype.initialize.call(this,e),this.typeMap=(new this.model).typeMap},get:function(n){var i=t.prototype.get.call(this,n);return!i&&e.isObject(n)&&!n.id&&n.get("mac")&&(i=this.getDeviceFromMac(n.get("mac"))),i},getInformIP:function(){var t=this.find(function(t){return t.get("adopted")&&1==t.get("state")&&t.get("inform_ip")});return void 0===t?"":t.get("inform_ip")},hasUpgradableAP:function(){var t=this.find(function(t){return"uap"==t.get("type")&&1==t.get("state")&&t.get("upgradable")});return t?!0:!1},hasUpgradablePhone:function(){var t=this.find(function(t){return"uph"==t.get("type")&&1==t.get("state")&&t.get("upgradable")});return t?!0:!1},isUpgradingDevices:function(){var t=this.find(function(t){return t.get("rollupgrade")});return t?!0:!1},getDeviceFromMac:function(t){return this.find(function(e){return e.get("mac")==t})},sortByBytes:function(){var t=this.sortBy(function(t){return-1*(t.get("bytes")||0)});return t},sortByBytesOnlyAps:function(){var t=this.sortByBytes();return e.filter(t,function(t){return"uap"===t.get("type")})},url:function(){return"/api/s/"+SITE.name+"/stat/device"},all:function(t){return this.fetch(e.extend(t,{_method:"read-all"}))},discover:function(){return this.fetch({_method:"discover"})},scanUplink:function(t){return this.sync("scan-uplink",this,t)},upgradeAPs:function(t){return this.sync("upgrade-aps",this,t)},upgradePhones:function(t){return this.sync("upgrade-phones",this,t)},sync:function(t,i,s){switch(s=s||{},s._method&&(t=s._method,delete s._method),t){case"read-all":s.contentType="application/json; charset=utf-8",s.url="/api/stat/device",s.type="POST",s.data=JSON.stringify(s.data||{});break;case"discover":s.contentType="application/json; charset=utf-8",s.url="/api/stat/device",s.type="POST",s.data=JSON.stringify({state:2,"default":!0});break;case"read":s.contentType="application/json; charset=utf-8",s.url="/api/s/"+SITE.name+"/stat/device",s.type="GET";break;case"scan-uplink":s.contentType="application/json; charset=utf-8",s.url="/api/s/"+SITE.name+"/cmd/devmgr",s.type="POST",s.data=JSON.stringify(e.extend(s.data||{},{cmd:"scan-uplink"}));break;case"upgrade-aps":s.contentType="application/json; charset=utf-8",s.url="/api/s/"+SITE.name+"/cmd/devmgr",s.type="POST",s.data=JSON.stringify(e.extend(s.data||{},{cmd:this.isUpgradingDevices()?"unset-rollupgrade":"set-rollupgrade"}));break;case"upgrade-phones":s.contentType="application/json; charset=utf-8",s.url="/api/s/"+SITE.name+"/cmd/devmgr",s.type="POST",s.data=JSON.stringify(e.extend(s.data||{},{cmd:"upgrade-all",type:"uph"}))}return n.sync.call(this,t,i,s)}})}),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(){"use strict";function t(e,n){n=n||[];var i=Array.apply(null,n);return i.fixedSize=e,i.push=t.push,i.splice=t.splice,i.unshift=t.unshift,i.setAll=t.setAll,t.trimTail.call(i),i}return t.trimHead=function(){this.length<=this.fixedSize||Array.prototype.splice.call(this,0,this.length-this.fixedSize)},t.trimTail=function(){this.length<=this.fixedSize||Array.prototype.splice.call(this,this.fixedSize,this.length-this.fixedSize)},t.wrapMethod=function(t,e){var n=function(){var n=Array.prototype[t],i=n.apply(this,arguments);return e.call(this),i};return n},t.push=t.wrapMethod("push",t.trimHead),t.splice=t.wrapMethod("splice",t.trimTail),t.unshift=t.wrapMethod("unshift",t.trimTail),t.setAll=function(t){for(var e=0;e<this.fixedSize;e++)this.push(t)},t}),define("unifi/view/dashboard/SpeedTestView",["unifi/view/app/DialogView","text!includes/dashboard/speedTestTemplate.html","msg/Msg","backbone","underscore","jquery","libs/fixedqueue"],function(t,e,n,i,s,a,r){"use strict";return t.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(t){s.bindAll(this),this.app=t.app,this.model=t.model,this.progressBars=new r(this.progressBarCount)},render:function(){this.$el.html(s.template(e,{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(){t.prototype.open.call(this),a.Window.on("resize.speedTestDialog",s.debounce(this.onResizeWindow,250)),this.onResizeWindow(),this.startTest(),this.removeTooltips()},close:function(){t.prototype.close.call(this),a.Window.off("resize.speedTestDialog"),this.removeTooltips()},removeTooltips:function(){a(".ui-tooltip-content").parents("div").remove()},onResizeWindow:function(){this.center()},generateSpeedTestProgressBarHTML:function(){for(var t=[],e=0;e<this.progressBarCount;e++)t.push('<span class="speedtest-progress-bar speedtest-progress-bar-'+e+'"><span class="value"></span></span>');this.$progressBars.html(t.join(""))},polling:function(){var t=this;this.pollingInterval&&this.stopPolling(),this.pollingIntervalms=1===this.model.getStatus("download")||1===this.model.getStatus("upload")?this.fastInterval:this.slowInterval,this.pollingInterval=window.setInterval(function(){t.model.fetch()},this.pollingIntervalms)},stopPolling:function(){window.clearInterval(this.pollingInterval)},startTest:function(t){t&&t.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(t,e){var n=this.model.getStatus(t);"ping"===t&&2>n||1===n?e.addClass("running"):e.removeClass("running")},updateStatus:function(t,e,n,i){var s=!1;switch("summary"!==t&&this.updateStatusTitle(t,i),this.model.getStatus(t)){case 0:break;case 1:("download"===t||"upload"===t)&&("upload"===t&&this.uploadInitialized===!1&&(this.progressBars.setAll(0),this.resetProgressBars(),this.resetTachRing(),this.uploadInitialized=!0),this.updateTachRing(t),this.updateProgressBars(t));break;case 2:"summary"===t?s=!0:("ping"===t&&this.$testingPing.hide(),i.removeClass("running"),this.showResult(this.model.getResult(t),e,n));break;case 3:s=!0,this.hideStatuses(),this.showErrorMessage()}s?this.onTestComplete():this.polling()},showResult:function(t,e,n){n.text(t),e.removeClass("hide")},updateTachRing:function(t){var e,n,i,s=100*this.model.getResult(t),a=this.model.convertMbpsToPercentage(s,this.maxMbps),r=Math.ceil(this.tachIconCount*(a/100));if(e=r-this.currentTachSegmentsGlowing,0!==e){if(this.removeFlickeringTachSegment(this.currentTachSegmentsGlowing-1),e>0)for(n=0;e>n;n++)this._fadeTachSegment(this.currentTachSegmentsGlowing+n,n*this.tachDelayInterval,!0);else if(0>e)for(n=-1,i=1;n>=e;n--,i++)this._fadeTachSegment(this.currentTachSegmentsGlowing+n,i*this.tachDelayInterval,!1);this.flickerTachSegment(r-1),this.currentTachSegmentsGlowing=r}this.$speedometerStatsResult.show(),this.$speedometerStatsValue.text(this.model.convertToMbps(s).toFixed(2))},flickerTachSegment:function(t){t>-1&&t<this.tachIconCount&&this.$tachSegments.eq(t).addClass("flicker")},removeFlickeringTachSegment:function(t){t>-1&&t<this.tachIconCount&&this.$tachSegments.eq(t).removeClass("flicker")},_fadeTachSegment:function(t,e,n){t>-1&&t<this.tachIconCount&&this.$tachSegments.eq(t).delay(e).stop(!0,!0)[n?"fadeIn":"fadeOut"](this.tachFadeSpeed)},resetTachRing:function(){this.removeFlickeringTachSegment(this.currentTachSegmentsGlowing);for(var t=0,e=1;t>=-this.currentTachSegmentsGlowing;t--,e++)this.tachIconCount+t>-1&&this.$tachSegments.eq(this.currentTachSegmentsGlowing+t).delay(e*this.tachDelayInterval).fadeOut(this.tachFadeSpeed);this.currentTachSegmentsGlowing=0},updateProgressBars:function(t){var e,n,i=100*this.model.getResult(t);"download"===t?this.progressBars.push(i):this.progressBars.unshift(i),s.each(this.progressBars,function(t,i){e=this.model.convertMbpsToPercentage(t,this.maxMbps),n=(100-e).toFixed(2),this.$progressBars.find(".speedtest-progress-bar-"+i).find(".value").height(n+"%")},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),a.Window.off("resize.speedTestDialog"),t.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(t,e,n,i,s,a,r,o,l,c,d,h,u,p){"use strict";return t.extend({id:"dashboardIndex",layers:{},speedtest_status:"",pollingSpeedtestInterval:null,initialize:function(e){t.prototype.initialize.call(this,e),this.layers={},this.template=r.template(d),o.when(this._rendered=o.Deferred(),this._dependencies=o.Deferred()).then(this.populate,this.failed),this.dependencies(),this.render()},dependencies:function(){var t,e={Subsystems:n,Alerts:l,Devices:c},i=[],s={},a=this;r.each(e,function(t,e){i.push(s[e]=o.Deferred())},this),o.when.apply(o,i).then(function(){a._dependencies.resolve()},function(){a._dependencies.reject()}),r.each(e,function(e,n){t={fetch:{reload:!1,deferred:s[n]}},"Alerts"===n&&(t.fetch.method="unarchived"),this.options.app.collection(n,t,e)},this)},failed:function(){(new u).open(p.E_DataLoad)},onAlertsChange:function(){r.each(this.subsystems.possibleSubsystems,function(t){this.layers[t.toUpperCase()].model.set("notifications",this.alerts.where({system:t,archived:!1}))},this)},render:function(){if(t.prototype.render.call(this),!this.rendered&&(this.rendered=!0)){var n,a,l,c=this;this.$el.html(this.template({msg:p})),this.speedTestModel=new s,this.speedTestModel.fetch(),this.speedTestView=new h({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",r.debounce(this.onAlertsChange,500)),this.listenTo(this.alerts,"add",r.debounce(this.onAlertsChange,500)),this.listenTo(this.alerts,"remove",r.debounce(this.onAlertsChange,500)),this.listenTo(this.alerts,"reset",r.debounce(this.onAlertsChange,500)),this.listenTo(this.subsystems,"reset change sync",r.debounce(this.populate,500)),this.$speedTest=o("#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),l=o("#navSettings").find("a"),r.each(this.subsystems.possibleSubsystems,function(t){switch(n=!1,a=function(){c.app.routers.statistics.forward()},t){case"www":a=!1;break;case"wan":n=function(){var e=c.subsystems.findWhere({subsystem:t}),n=c.devices.findWhere({mac:e.get("gw_mac")});o("#devicesIndex").find(".mac-"+n.getMacNoColons()+" .column-name").click()},a=!1;break;case"lan":n=function(){l.click(),o("#navSettingsNetworks").find("a").click()},a=!1;break;case"wlan":n=function(){l.click(),o("#navSettingsWirelessNetworks").find("a").click()};break;case"voip":a=!1}c.layers[t.toUpperCase()]=new e({model:new i({subsystem:t,configureLink:n,statsLink:a}),$tableItem:c.$(".table-item."+t),el:".layer."+t,app:c.app})}),this.$nodeWWW=o(".nodes .www"),"resolved"===this._rendered.state()&&"resolved"==this._dependencies.state()?this.populate():"pending"===this._rendered.state()&&this._rendered.resolve()}},populate:function(){var t;r.each(this.subsystems.possibleSubsystems,function(e){t=this.subsystems.findWhere({subsystem:e}),this.layers[e.toUpperCase()].update(t)},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 t=!1,e=!1,n=!1;2===this.speedTestModel.getStatus("download")&&(this.$speedTestDownloadValue.text(this.speedTestModel.getDownloadSpeed()),this.$speedTestDownloadResult.show(),t=!0),2===this.speedTestModel.getStatus("upload")&&(this.$speedTestUploadValue.text(this.speedTestModel.getUploadSpeed()),this.$speedTestUploadResult.show(),e=!0),this.speedTestModel.get("rundate")&&(this.$speedLastRunValue.text(this.speedTestModel.getLastRun()),this.$speedLastRunResult.show(),n=!0),t&&e&&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,t.prototype.remove.apply(this,arguments)}})}),define("unifi/router/DashboardRouter",["unifi/router/Router","unifi/view/dashboard/IndexView","unifi/view/dashboard/LayerView"],function(t,e,n){"use strict";return t.extend({_fullyQualifiedName:"UNIFI.Routers.Dashboard",_associatedViews:{Index:e,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 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\n        <div class="button-container scan">\n            <div class="button"><div class="icon ubnt-icon-histogram"></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(t){window.console&&console.warn&&console.warn("Kinetic warning: "+t)},extend:function(t,e){for(var n in e.prototype)n in t.prototype||(t.prototype[n]=e.prototype[n])},_addId:function(t,e){void 0!==e&&(this.ids[e]=t)},_removeId:function(t){void 0!==t&&delete this.ids[t]},_addName:function(t,e){void 0!==e&&(void 0===this.names[e]&&(this.names[e]=[]),this.names[e].push(t))},_removeName:function(t,e){if(void 0!==t){var n=this.names[t];if(void 0!==n){for(var i=0;i<n.length;i++){var s=n[i];s._id===e&&n.splice(i,1)}0===n.length&&delete this.names[t]}}}}}(),function(t,e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define("libs/kinetic",e):t.returnExports=e()}(this,function(){return Kinetic}),function(){Kinetic.Type={_isElement:function(t){return!(!t||1!=t.nodeType)},_isFunction:function(t){return!!(t&&t.constructor&&t.call&&t.apply)},_isObject:function(t){return!!t&&t.constructor==Object},_isArray:function(t){return"[object Array]"==Object.prototype.toString.call(t)},_isNumber:function(t){return"[object Number]"==Object.prototype.toString.call(t)},_isString:function(t){return"[object String]"==Object.prototype.toString.call(t)},_hasMethods:function(t){var e=[];for(var n in t)this._isFunction(t[n])&&e.push(n);return e.length>0},_isInDocument:function(t){for(;t=t.parentNode;)if(t==document)return!0;return!1},_getXY:function(t){if(this._isNumber(t))return{x:t,y:t};if(this._isArray(t)){if(1===t.length){var e=t[0];if(this._isNumber(e))return{x:e,y:e};if(this._isArray(e))return{x:e[0],y:e[1]};if(this._isObject(e))return e}else if(t.length>=2)return{x:t[0],y:t[1]}}else if(this._isObject(t))return t;return null},_getSize:function(t){if(this._isNumber(t))return{width:t,height:t};if(this._isArray(t))if(1===t.length){var e=t[0];if(this._isNumber(e))return{width:e,height:e};if(this._isArray(e)){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}else{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;return null},_getPoints:function(t){if(void 0===t)return[];if(this._isArray(t[0])){for(var e=[],n=0;n<t.length;n++)e.push({x:t[n][0],y:t[n][1]});return e}if(this._isObject(t[0]))return t;for(var e=[],n=0;n<t.length;n+=2)e.push({x:t[n],y:t[n+1]});return e},_getImage:function(t,e){if(t)if(this._isElement(t))e(t);else if(this._isString(t)){var n=new Image;n.onload=function(){e(n)},n.src=t}else if(t.data){var i=document.createElement("canvas");i.width=t.width,i.height=t.height;var s=i.getContext("2d");s.putImageData(t,0,0);var a=i.toDataURL(),n=new Image;n.onload=function(){e(n)},n.src=a}else e(null);else e(null)},_rgbToHex:function(t,e,n){return((1<<24)+(t<<16)+(e<<8)+n).toString(16).slice(1)},_hexToRgb:function(t){var e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:255&e}},_getRandomColorKey:function(){var t=Math.round(255*Math.random()),e=Math.round(255*Math.random()),n=Math.round(255*Math.random());return this._rgbToHex(t,e,n)},_merge:function(t,e){var n=this._clone(e);for(var i in t)n[i]=this._isObject(t[i])?this._merge(t[i],n[i]):t[i];return n},_clone:function(t){var e={};for(var n in t)e[n]=this._isObject(t[n])?this._clone(t[n]):t[n];return e},_degToRad:function(t){return t*Math.PI/180},_radToDeg:function(t){return 180*t/Math.PI}}}(),function(){var t=document.createElement("canvas"),e=t.getContext("2d"),n=window.devicePixelRatio||1,i=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1,s=n/i;Kinetic.Canvas=function(t,e,n){this.pixelRatio=n||s,this.width=t,this.height=e,this.element=document.createElement("canvas"),this.context=this.element.getContext("2d"),this.setSize(t||0,e||0)},Kinetic.Canvas.prototype={clear:function(){var t=this.getContext(),e=this.getElement();t.clearRect(0,0,e.width,e.height)},getElement:function(){return this.element},getContext:function(){return this.context},setWidth:function(t){this.width=t,this.element.width=t*this.pixelRatio,this.element.style.width=t+"px"},setHeight:function(t){this.height=t,this.element.height=t*this.pixelRatio,this.element.style.height=t+"px"},getWidth:function(){return this.width},getHeight:function(){return this.height},setSize:function(t,e){this.setWidth(t),this.setHeight(e)},toDataURL:function(t,e){try{return this.element.toDataURL(t,e)}catch(n){try{return this.element.toDataURL()}catch(n){return Kinetic.Global.warn("Unable to get data URL. "+n.message),""}}},fill:function(t){t.getFillEnabled()&&this._fill(t)},stroke:function(t){t.getStrokeEnabled()&&this._stroke(t)},fillStroke:function(t){var e=t.getFillEnabled();e&&this._fill(t),t.getStrokeEnabled()&&this._stroke(t,t.hasShadow()&&t.hasFill()&&e)},applyShadow:function(t,e){var n=this.context;n.save(),this._applyShadow(t),e(),n.restore(),e()},_applyLineCap:function(t){var e=t.getLineCap();e&&(this.context.lineCap=e)},_applyOpacity:function(t){var e=t.getAbsoluteOpacity();1!==e&&(this.context.globalAlpha=e)},_applyLineJoin:function(t){var e=t.getLineJoin();e&&(this.context.lineJoin=e)},_applyAncestorTransforms:function(t){var e=this.context;t._eachAncestorReverse(function(t){var n=t.getTransform(),i=n.getMatrix();e.transform(i[0],i[1],i[2],i[3],i[4],i[5])},!0)}},Kinetic.SceneCanvas=function(t,e,n){Kinetic.Canvas.call(this,t,e,n)},Kinetic.SceneCanvas.prototype={setWidth:function(t){var e=this.pixelRatio;Kinetic.Canvas.prototype.setWidth.call(this,t),this.context.scale(e,e)},setHeight:function(t){var e=this.pixelRatio;Kinetic.Canvas.prototype.setHeight.call(this,t),this.context.scale(e,e)},_fillColor:function(t){var e=this.context,n=t.getFill();e.fillStyle=n,t._fillFunc(e)},_fillPattern:function(t){var e=this.context,n=t.getFillPatternImage(),i=t.getFillPatternX(),s=t.getFillPatternY(),a=t.getFillPatternScale(),r=t.getFillPatternRotation(),o=t.getFillPatternOffset(),l=t.getFillPatternRepeat();(i||s)&&e.translate(i||0,s||0),r&&e.rotate(r),a&&e.scale(a.x,a.y),o&&e.translate(-1*o.x,-1*o.y),e.fillStyle=e.createPattern(n,l||"repeat"),e.fill()},_fillLinearGradient:function(t){for(var e=this.context,n=t.getFillLinearGradientStartPoint(),i=t.getFillLinearGradientEndPoint(),s=t.getFillLinearGradientColorStops(),a=e.createLinearGradient(n.x,n.y,i.x,i.y),r=0;r<s.length;r+=2)a.addColorStop(s[r],s[r+1]);e.fillStyle=a,e.fill()},_fillRadialGradient:function(t){for(var e=this.context,n=t.getFillRadialGradientStartPoint(),i=t.getFillRadialGradientEndPoint(),s=t.getFillRadialGradientStartRadius(),a=t.getFillRadialGradientEndRadius(),r=t.getFillRadialGradientColorStops(),o=e.createRadialGradient(n.x,n.y,s,i.x,i.y,a),l=0;l<r.length;l+=2)o.addColorStop(r[l],r[l+1]);e.fillStyle=o,e.fill()},_fill:function(t,e){var n=this.context,i=t.getFill(),s=t.getFillPatternImage(),a=t.getFillLinearGradientStartPoint(),r=t.getFillRadialGradientStartPoint(),o=t.getFillPriority();n.save(),!e&&t.hasShadow()&&this._applyShadow(t),i&&"color"===o?this._fillColor(t):s&&"pattern"===o?this._fillPattern(t):a&&"linear-gradient"===o?this._fillLinearGradient(t):r&&"radial-gradient"===o?this._fillRadialGradient(t):i?this._fillColor(t):s?this._fillPattern(t):a?this._fillLinearGradient(t):r&&this._fillRadialGradient(t),n.restore(),!e&&t.hasShadow()&&this._fill(t,!0)},_stroke:function(t,e){var n=this.context,i=t.getStroke(),s=t.getStrokeWidth(),a=t.getDashArray();(i||s)&&(n.save(),this._applyLineCap(t),a&&t.getDashArrayEnabled()&&(n.setLineDash?n.setLineDash(a):"mozDash"in n?n.mozDash=a:"webkitLineDash"in n&&(n.webkitLineDash=a)),!e&&t.hasShadow()&&this._applyShadow(t),n.lineWidth=s||2,n.strokeStyle=i||"black",t._strokeFunc(n),n.restore(),!e&&t.hasShadow()&&this._stroke(t,!0))},_applyShadow:function(t){var e=this.context;if(t.hasShadow()&&t.getShadowEnabled()){var n=t.getAbsoluteOpacity(),i=t.getShadowColor()||"black",s=t.getShadowBlur()||5,a=t.getShadowOffset()||{x:0,y:0};t.getShadowOpacity()&&(e.globalAlpha=t.getShadowOpacity()*n),e.shadowColor=i,e.shadowBlur=s,e.shadowOffsetX=a.x,e.shadowOffsetY=a.y}}},Kinetic.Global.extend(Kinetic.SceneCanvas,Kinetic.Canvas),Kinetic.HitCanvas=function(t,e,n){Kinetic.Canvas.call(this,t,e,n)},Kinetic.HitCanvas.prototype={_fill:function(t){var e=this.context;e.save(),e.fillStyle="#"+t.colorKey,t._fillFuncHit(e),e.restore()},_stroke:function(t){var e=this.context,n=t.getStroke(),i=t.getStrokeWidth();(n||i)&&(this._applyLineCap(t),e.save(),e.lineWidth=i||2,e.strokeStyle="#"+t.colorKey,t._strokeFuncHit(e),e.restore())}},Kinetic.Global.extend(Kinetic.HitCanvas,Kinetic.Canvas)}(),function(){Kinetic.Tween=function(t,e,n,i,s,a){this._listeners=[],this.addListener(this),this.obj=t,this.propFunc=e,this.begin=i,this._pos=i,this.setDuration(a),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(s)},Kinetic.Tween.prototype={setTime:function(t){this.prevTime=this._time,t>this.getDuration()?this.looping?(this.rewind(t-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"})):0>t?(this.rewind(),this.update()):(this._time=t,this.update())},getTime:function(){return this._time},setDuration:function(t){this._duration=null===t||0>=t?1e5:t},getDuration:function(){return this._duration},setPosition:function(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t,this.broadcastMessage("onChanged",{target:this,type:"onChanged"})},getPosition:function(t){return void 0===t&&(t=this._time),this.func(t,this.begin,this._change,this._duration)},setFinish:function(t){this._change=t-this.begin},getFinish:function(){return this.begin+this._change},start:function(){this.rewind(),this.startEnterFrame(),this.broadcastMessage("onStarted",{target:this,type:"onStarted"})},rewind:function(t){this.stop(),this._time=void 0===t?0:t,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(t,e){this.begin=this._pos,this.setFinish(t),void 0!==this._duration&&this.setDuration(e),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(t){return this.removeListener(t),this._listeners.push(t)},removeListener:function(t){for(var e=this._listeners,n=e.length;n--;)if(e[n]==t)return e.splice(n,1),!0;return!1},broadcastMessage:function(){for(var t=[],e=0;e<arguments.length;e++)t.push(arguments[e]);for(var n=t.shift(),i=this._listeners,s=i.length,e=0;s>e;e++)i[e][n]&&i[e][n].apply(i[e],t)},fixTime:function(){this._startTime=this.getTimer()-1e3*this._time},getTimer:function(){return(new Date).getTime()-this._time}},Kinetic.Tweens={"back-ease-in":function(t,e,n,i){var s=1.70158;return n*(t/=i)*t*((s+1)*t-s)+e},"back-ease-out":function(t,e,n,i){var s=1.70158;return n*((t=t/i-1)*t*((s+1)*t+s)+1)+e},"back-ease-in-out":function(t,e,n,i){var s=1.70158;return(t/=i/2)<1?n/2*t*t*(((s*=1.525)+1)*t-s)+e:n/2*((t-=2)*t*(((s*=1.525)+1)*t+s)+2)+e},"elastic-ease-in":function(t,e,n,i,s,a){var r=0;return 0===t?e:1==(t/=i)?e+n:(a||(a=.3*i),!s||s<Math.abs(n)?(s=n,r=a/4):r=a/(2*Math.PI)*Math.asin(n/s),-(s*Math.pow(2,10*(t-=1))*Math.sin(2*(t*i-r)*Math.PI/a))+e)},"elastic-ease-out":function(t,e,n,i,s,a){var r=0;return 0===t?e:1==(t/=i)?e+n:(a||(a=.3*i),!s||s<Math.abs(n)?(s=n,r=a/4):r=a/(2*Math.PI)*Math.asin(n/s),s*Math.pow(2,-10*t)*Math.sin(2*(t*i-r)*Math.PI/a)+n+e)},"elastic-ease-in-out":function(t,e,n,i,s,a){var r=0;return 0===t?e:2==(t/=i/2)?e+n:(a||(a=.3*i*1.5),!s||s<Math.abs(n)?(s=n,r=a/4):r=a/(2*Math.PI)*Math.asin(n/s),1>t?-.5*s*Math.pow(2,10*(t-=1))*Math.sin(2*(t*i-r)*Math.PI/a)+e:s*Math.pow(2,-10*(t-=1))*Math.sin(2*(t*i-r)*Math.PI/a)*.5+n+e)},"bounce-ease-out":function(t,e,n,i){return(t/=i)<1/2.75?7.5625*n*t*t+e:2/2.75>t?n*(7.5625*(t-=1.5/2.75)*t+.75)+e:2.5/2.75>t?n*(7.5625*(t-=2.25/2.75)*t+.9375)+e:n*(7.5625*(t-=2.625/2.75)*t+.984375)+e},"bounce-ease-in":function(t,e,n,i){return n-Kinetic.Tweens["bounce-ease-out"](i-t,0,n,i)+e},"bounce-ease-in-out":function(t,e,n,i){return i/2>t?.5*Kinetic.Tweens["bounce-ease-in"](2*t,0,n,i)+e:.5*Kinetic.Tweens["bounce-ease-out"](2*t-i,0,n,i)+.5*n+e},"ease-in":function(t,e,n,i){return n*(t/=i)*t+e},"ease-out":function(t,e,n,i){return-n*(t/=i)*(t-2)+e},"ease-in-out":function(t,e,n,i){return(t/=i/2)<1?n/2*t*t+e:-n/2*(--t*(t-2)-1)+e},"strong-ease-in":function(t,e,n,i){return n*(t/=i)*t*t*t*t+e},"strong-ease-out":function(t,e,n,i){return n*((t=t/i-1)*t*t*t*t+1)+e},"strong-ease-in-out":function(t,e,n,i){return(t/=i/2)<1?n/2*t*t*t*t*t+e:n/2*((t-=2)*t*t*t*t+2)+e},linear:function(t,e,n,i){return n*t/i+e}}}(),function(){Kinetic.Transform=function(){this.m=[1,0,0,1,0,0]},Kinetic.Transform.prototype={translate:function(t,e){this.m[4]+=this.m[0]*t+this.m[2]*e,this.m[5]+=this.m[1]*t+this.m[3]*e},scale:function(t,e){this.m[0]*=t,this.m[1]*=t,this.m[2]*=e,this.m[3]*=e},rotate:function(t){var e=Math.cos(t),n=Math.sin(t),i=this.m[0]*e+this.m[2]*n,s=this.m[1]*e+this.m[3]*n,a=this.m[0]*-n+this.m[2]*e,r=this.m[1]*-n+this.m[3]*e;this.m[0]=i,this.m[1]=s,this.m[2]=a,this.m[3]=r},getTranslation:function(){return{x:this.m[4],y:this.m[5]}},multiply:function(t){var e=this.m[0]*t.m[0]+this.m[2]*t.m[1],n=this.m[1]*t.m[0]+this.m[3]*t.m[1],i=this.m[0]*t.m[2]+this.m[2]*t.m[3],s=this.m[1]*t.m[2]+this.m[3]*t.m[3],a=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],r=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];this.m[0]=e,this.m[1]=n,this.m[2]=i,this.m[3]=s,this.m[4]=a,this.m[5]=r},invert:function(){var t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),e=this.m[3]*t,n=-this.m[1]*t,i=-this.m[2]*t,s=this.m[0]*t,a=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),r=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);this.m[0]=e,this.m[1]=n,this.m[2]=i,this.m[3]=s,this.m[4]=a,this.m[5]=r},getMatrix:function(){return this.m}}}(),function(){Kinetic.Collection=function(){var t=[].slice.call(arguments),e=t.length,n=0;for(this.length=e;e>n;n++)this[n]=t[n];return this},Kinetic.Collection.prototype=new Array,Kinetic.Collection.prototype.apply=function(t){args=[].slice.call(arguments),args.shift();for(var e=0;e<this.length;e++)Kinetic.Type._isFunction(this[e][t])&&this[e][t].apply(this[e],args)},Kinetic.Collection.prototype.each=function(t){for(var e=0;e<this.length;e++)t.call(this[e],e,this[e])}}(),function(){Kinetic.Filters.Grayscale=function(t){for(var e=t.data,n=0;n<e.length;n+=4){var i=.34*e[n]+.5*e[n+1]+.16*e[n+2];e[n]=i,e[n+1]=i,e[n+2]=i}}}(),function(){Kinetic.Filters.Brighten=function(t,e){for(var n=e.val||0,i=t.data,s=0;s<i.length;s+=4)i[s]+=n,i[s+1]+=n,i[s+2]+=n}}(),function(){Kinetic.Filters.Invert=function(t){for(var e=t.data,n=0;n<e.length;n+=4)e[n]=255-e[n],e[n+1]=255-e[n+1],e[n+2]=255-e[n+2]}}(),function(){Kinetic.Node=function(t){this._nodeInit(t)},Kinetic.Node.prototype={_nodeInit:function(t){this._id=Kinetic.Global.idCounter++,this.defaultNodeAttrs={visible:!0,listening:!0,name:void 0,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(t)},on:function(t,e){for(var n=t.split(" "),i=n.length,s=0;i>s;s++){var a=n[s],r=a,o=r.split("."),l=o[0],c=o.length>1?o[1]:"";this.eventListeners[l]||(this.eventListeners[l]=[]),this.eventListeners[l].push({name:c,handler:e})}},off:function(t){for(var e=t.split(" "),n=e.length,i=0;n>i;i++){var s=e[i],a=s,r=a.split("."),o=r[0];if(r.length>1)if(o)this.eventListeners[o]&&this._off(o,r[1]);else for(var s in this.eventListeners)this._off(s,r[1]);else delete this.eventListeners[o]}},remove:function(){var t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices()),delete this.parent},destroy:function(){for(var t=(this.getParent(),this.getStage(),Kinetic.DD),e=Kinetic.Global;this.children&&this.children.length>0;)this.children[0].destroy();e._removeId(this.getId()),e._removeName(this.getName(),this._id),t&&t.node&&t.node._id===this._id&&node._endDrag(),this.trans&&this.trans.stop(),this.remove()},getAttrs:function(){return this.attrs},setDefaultAttrs:function(t){if(void 0===this.attrs&&(this.attrs={}),t)for(var e in t)void 0===this.attrs[e]&&(this.attrs[e]=t[e])},setAttrs:function(t){if(t)for(var e in t){var n="set"+e.charAt(0).toUpperCase()+e.slice(1);Kinetic.Type._isFunction(this[n])?this[n](t[e]):this.setAttr(e,t[e])}},getVisible:function(){var t=this.attrs.visible,e=this.getParent();return t&&e&&!e.getVisible()?!1:t},getListening:function(){var t=this.attrs.listening,e=this.getParent();return t&&e&&!e.getListening()?!1:t},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},getZIndex:function(){return this.index},getAbsoluteZIndex:function(){function t(s){for(var a=[],r=s.length,o=0;r>o;o++){var l=s[o];i++,"Shape"!==l.nodeType&&(a=a.concat(l.getChildren())),l._id===n._id&&(o=r)}a.length>0&&a[0].getLevel()<=e&&t(a)}var e=this.getLevel(),n=(this.getStage(),this),i=0;return"Stage"!==n.nodeType&&t(n.getStage().getChildren()),i},getLevel:function(){for(var t=0,e=this.parent;e;)t++,e=e.parent;return t},setPosition:function(){var t=Kinetic.Type._getXY([].slice.call(arguments));this.setAttr("x",t.x),this.setAttr("y",t.y)},getPosition:function(){var t=this.attrs;return{x:t.x,y:t.y}},getAbsolutePosition:function(){var t=this.getAbsoluteTransform(),e=this.getOffset();return t.translate(e.x,e.y),t.getTranslation()},setAbsolutePosition:function(){var t=Kinetic.Type._getXY([].slice.call(arguments)),e=this._clearTransform();this.attrs.x=e.x,this.attrs.y=e.y,delete e.x,delete e.y;var n=this.getAbsoluteTransform();n.invert(),n.translate(t.x,t.y),t={x:this.attrs.x+n.getTranslation().x,y:this.attrs.y+n.getTranslation().y},this.setPosition(t.x,t.y),this._setTransform(e)},move:function(){var t=Kinetic.Type._getXY([].slice.call(arguments)),e=this.getX(),n=this.getY();void 0!==t.x&&(e+=t.x),void 0!==t.y&&(n+=t.y),this.setPosition(e,n)},_eachAncestorReverse:function(t,e){var n=[],i=this.getParent();for(e&&n.unshift(this);i;)n.unshift(i),i=i.parent;for(var s=n.length,a=0;s>a;a++)t(n[a])},rotate:function(t){this.setRotation(this.getRotation()+t)},rotateDeg:function(t){this.setRotation(this.getRotation()+Kinetic.Type._degToRad(t))},moveToTop:function(){var t=this.index;return this.parent.children.splice(t,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0},moveUp:function(){var t=this.index,e=this.parent.getChildren().length;return e-1>t?(this.parent.children.splice(t,1),this.parent.children.splice(t+1,0,this),this.parent._setChildrenIndices(),!0):void 0},moveDown:function(){var t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):void 0},moveToBottom:function(){var t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):void 0},setZIndex:function(t){var e=this.index;this.parent.children.splice(e,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices()},getAbsoluteOpacity:function(){var t=this.getOpacity();return this.getParent()&&(t*=this.getParent().getAbsoluteOpacity()),t},moveTo:function(t){Kinetic.Node.prototype.remove.call(this),t.add(this)},toObject:function(){var t=Kinetic.Type,e={},n=this.attrs;e.attrs={};for(var i in n){var s=n[i];t._isFunction(s)||t._isElement(s)||t._isObject(s)&&t._hasMethods(s)||(e.attrs[i]=s)}return e.nodeType=this.nodeType,e.shapeType=this.shapeType,e},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():void 0},simulate:function(t,e){this._handleEvent(t,e||{})},fire:function(t,e){this._executeHandlers(t,e||{})},getAbsoluteTransform:function(){var t=new Kinetic.Transform;return this._eachAncestorReverse(function(e){var n=e.getTransform();t.multiply(n)},!0),t},getTransform:function(){var t=new Kinetic.Transform,e=this.attrs,n=e.x,i=e.y,s=e.rotation,a=e.scale,r=a.x,o=a.y,l=e.offset,c=l.x,d=l.y;return(0!==n||0!==i)&&t.translate(n,i),0!==s&&t.rotate(s),(1!==r||1!==o)&&t.scale(r,o),(0!==c||0!==d)&&t.translate(-1*c,-1*d),t},clone:function(t){var e=this.shapeType||this.nodeType,n=new Kinetic[e](this.attrs);for(var i in this.eventListeners)for(var s=this.eventListeners[i],a=s.length,r=0;a>r;r++){var o=s[r];o.name.indexOf("kinetic")<0&&(n.eventListeners[i]||(n.eventListeners[i]=[]),n.eventListeners[i].push(o))}return n.setAttrs(t),n},toDataURL:function(t){t=t||{};var e,n,i=t.mimeType||null,s=t.quality||null,a=t.x||0,r=t.y||0;return t.width&&t.height?e=new Kinetic.SceneCanvas(t.width,t.height,1):(e=this.getStage().bufferCanvas,e.clear()),n=e.getContext(),n.save(),(a||r)&&n.translate(-1*a,-1*r),this.drawScene(e),n.restore(),e.toDataURL(i,s)},toImage:function(t){Kinetic.Type._getImage(this.toDataURL(t),function(e){t.callback(e)})},setSize:function(){var t=Kinetic.Type._getSize(Array.prototype.slice.call(arguments));this.setWidth(t.width),this.setHeight(t.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(t){return this.nodeType===t?[this]:[]},_off:function(t,e){for(var n=0;n<this.eventListeners[t].length;n++)if(this.eventListeners[t][n].name===e){if(this.eventListeners[t].splice(n,1),0===this.eventListeners[t].length){delete this.eventListeners[t];break}n--}},_clearTransform:function(){var t=this.attrs,e=t.scale,n=t.offset,i={x:t.x,y:t.y,rotation:t.rotation,scale:{x:e.x,y:e.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},i},_setTransform:function(t){for(var e in t)this.attrs[e]=t[e]},_fireBeforeChangeEvent:function(t,e,n){this._handleEvent("before"+t.toUpperCase()+"Change",{oldVal:e,newVal:n})},_fireChangeEvent:function(t,e,n){this._handleEvent(t+"Change",{oldVal:e,newVal:n})},setId:function(t){var e=this.getId(),n=(this.getStage(),Kinetic.Global);n._removeId(e),n._addId(this,t),this.setAttr("id",t)},setName:function(t){var e=this.getName(),n=(this.getStage(),Kinetic.Global);n._removeName(e,this._id),n._addName(this,t),this.setAttr("name",t)},setAttr:function(t,e){if(void 0!==e){var n=this.attrs[t];this._fireBeforeChangeEvent(t,n,e),this.attrs[t]=e,this._fireChangeEvent(t,n,e)}},_handleEvent:function(t,e,n){e&&"Shape"===this.nodeType&&(e.shape=this);var i=(this.getStage(),this.eventListeners),s=!0;"mouseenter"===t&&n&&this._id===n._id?s=!1:"mouseleave"===t&&n&&this._id===n._id&&(s=!1),s&&(i[t]&&this.fire(t,e),e&&!e.cancelBubble&&this.parent&&(n&&n.parent?this._handleEvent.call(this.parent,t,e,n.parent):this._handleEvent.call(this.parent,t,e)))},_executeHandlers:function(t,e){for(var n=this.eventListeners[t],i=n.length,s=0;i>s;s++)n[s].handler.apply(this,[e])}},Kinetic.Node.addSetters=function(t,e){for(var n=e.length,i=0;n>i;i++){var s=e[i];this._addSetter(t,s)}},Kinetic.Node.addPointSetters=function(t,e){for(var n=e.length,i=0;n>i;i++){var s=e[i];this._addPointSetter(t,s)}},Kinetic.Node.addRotationSetters=function(t,e){for(var n=e.length,i=0;n>i;i++){var s=e[i];this._addRotationSetter(t,s)}},Kinetic.Node.addGetters=function(t,e){for(var n=e.length,i=0;n>i;i++){var s=e[i];this._addGetter(t,s)}},Kinetic.Node.addRotationGetters=function(t,e){for(var n=e.length,i=0;n>i;i++){var s=e[i];this._addRotationGetter(t,s)}},Kinetic.Node.addGettersSetters=function(t,e){this.addSetters(t,e),this.addGetters(t,e)},Kinetic.Node.addPointGettersSetters=function(t,e){this.addPointSetters(t,e),this.addGetters(t,e)
},Kinetic.Node.addRotationGettersSetters=function(t,e){this.addRotationSetters(t,e),this.addRotationGetters(t,e)},Kinetic.Node._addSetter=function(t,e){var n="set"+e.charAt(0).toUpperCase()+e.slice(1);t.prototype[n]=function(t){this.setAttr(e,t)}},Kinetic.Node._addPointSetter=function(t,e){var n="set"+e.charAt(0).toUpperCase()+e.slice(1);t.prototype[n]=function(){var t=Kinetic.Type._getXY([].slice.call(arguments));t&&void 0===t.x&&(t.x=this.attrs[e].x),t&&void 0===t.y&&(t.y=this.attrs[e].y),this.setAttr(e,t)}},Kinetic.Node._addRotationSetter=function(t,e){var n="set"+e.charAt(0).toUpperCase()+e.slice(1);t.prototype[n]=function(t){this.setAttr(e,t)},t.prototype[n+"Deg"]=function(t){this.setAttr(e,Kinetic.Type._degToRad(t))}},Kinetic.Node._addGetter=function(t,e){var n="get"+e.charAt(0).toUpperCase()+e.slice(1);t.prototype[n]=function(){return this.attrs[e]}},Kinetic.Node._addRotationGetter=function(t,e){var n="get"+e.charAt(0).toUpperCase()+e.slice(1);t.prototype[n]=function(){return this.attrs[e]},t.prototype[n+"Deg"]=function(){return Kinetic.Type._radToDeg(this.attrs[e])}},Kinetic.Node.create=function(t,e){return this._createNode(JSON.parse(t),e)},Kinetic.Node._createNode=function(t,e){var n;n="Shape"===t.nodeType?void 0===t.shapeType?"Shape":t.shapeType:t.nodeType,e&&(t.attrs.container=e);var i=new Kinetic[n](t.attrs);if(t.children)for(var s=t.children.length,a=0;s>a;a++)i.add(this._createNode(t.children[a]));return i},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;for(var t=["on","off"],e=0;2>e;e++)!function(e){var n=t[e];Kinetic.Collection.prototype[n]=function(){var t=[].slice.call(arguments);t.unshift(n),this.apply.apply(this,t)}}(e)}(),function(){Kinetic.Animation=function(t,e){this.func=t,this.node=e,this.id=Kinetic.Animation.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:(new Date).getTime()}},Kinetic.Animation.prototype={isRunning:function(){for(var t=Kinetic.Animation,e=t.animations,n=0;n<e.length;n++)if(e[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(t){this.frame.timeDiff=t-this.frame.lastTime,this.frame.lastTime=t,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(t){window.setTimeout(t,1e3/60)},Kinetic.Animation._addAnimation=function(t){this.animations.push(t),this._handleAnimation()},Kinetic.Animation._removeAnimation=function(t){for(var e=t.id,n=this.animations,i=n.length,s=0;i>s;s++)if(n[s].id===e){this.animations.splice(s,1);break}},Kinetic.Animation._runFrames=function(){for(var t={},e=this.animations,n=0;n<e.length;n++){var i=e[n],s=i.node,a=i.func;i._updateFrameObject((new Date).getTime()),s&&void 0!==s._id&&(t[s._id]=s),a&&a(i.frame)}for(var r in t)t[r].draw()},Kinetic.Animation._animationLoop=function(){var t=this;this.animations.length>0?(this._runFrames(),Kinetic.Animation.requestAnimFrame(function(){t._animationLoop()})):this.animRunning=!1},Kinetic.Animation._handleAnimation=function(){var t=this;this.animRunning||(this.animRunning=!0,t._animationLoop())},RAF=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||Kinetic.Animation.fixedRequestAnimFrame}(),Kinetic.Animation.requestAnimFrame=function(t){var e=Kinetic.DD&&Kinetic.DD.moving?this.fixedRequestAnimFrame:RAF;e(t)};var t=Kinetic.Node.prototype.moveTo;Kinetic.Node.prototype.moveTo=function(e){t.call(this,e)}}(),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(t){{var e,n,i=t.getStage();t.nodeType}return t._eachAncestorReverse(function(t){"Layer"===t.nodeType?(i.dragLayer.setAttrs(t.getAttrs()),e=i.dragLayer,i.add(i.dragLayer)):"Group"===t.nodeType&&(n=new Kinetic.Group(t.getAttrs()),e.add(n),e=n)}),e},Kinetic.DD._initDragLayer=function(t){t.dragLayer=new Kinetic.Layer,t.dragLayer.getCanvas().getElement().className="kinetic-drag-and-drop-layer"},Kinetic.DD._drag=function(t){var e=Kinetic.DD,n=e.node;if(n){var i=n.getStage().getUserPosition(),s=n.attrs.dragBoundFunc,a={x:i.x-e.offset.x,y:i.y-e.offset.y};void 0!==s&&(a=s.call(n,a,t)),n.setAbsolutePosition(a),e.moving||(e.moving=!0,n.setListening(!1),n._handleEvent("dragstart",t)),n._handleEvent("dragmove",t)}},Kinetic.DD._endDrag=function(t){var e=Kinetic.DD,n=e.node;if(n){{var i=n.nodeType;n.getStage()}n.setListening(!0),"Stage"===i?n.draw():(("Group"===i||"Shape"===i)&&n.getDragOnTop()&&e.prevParent&&(n.moveTo(e.prevParent),n.getStage().dragLayer.remove(),e.prevParent=null),n.getLayer().draw()),delete e.node,e.anim.stop(),e.moving&&(e.moving=!1,n._handleEvent("dragend",t))}},Kinetic.Node.prototype._startDrag=function(){var t=Kinetic.DD,e=this,n=this.getStage(),i=n.getUserPosition();if(i){var s,a=(this.getTransform().getTranslation(),this.getAbsolutePosition()),r=this.nodeType;t.node=this,t.offset.x=i.x-a.x,t.offset.y=i.y-a.y,"Stage"===r||"Layer"===r?(t.anim.node=this,t.anim.start()):this.getDragOnTop()?(s=t._setupDragLayerAndGetContainer(this),t.anim.node=n.dragLayer,t.prevParent=this.getParent(),setTimeout(function(){t.node&&(e.moveTo(s),t.prevParent.getLayer().draw(),n.dragLayer.draw(),t.anim.start())},0)):(t.anim.node=this.getLayer(),t.anim.start())}},Kinetic.Node.prototype.setDraggable=function(t){this.setAttr("draggable",t),this._dragChange()},Kinetic.Node.prototype.getDraggable=function(){return this.attrs.draggable},Kinetic.Node.prototype.isDragging=function(){var t=Kinetic.DD;return t.node&&t.node._id===this._id&&t.moving},Kinetic.Node.prototype._listenDrag=function(){this._dragCleanup();var t=this;this.on("mousedown.kinetic touchstart.kinetic",function(e){Kinetic.getNodeDragging()||t._startDrag(e)})},Kinetic.Node.prototype._dragChange=function(){if(this.attrs.draggable)this._listenDrag();else{this._dragCleanup();var t=this.getStage(),e=Kinetic.DD;t&&e.node&&e.node._id===this._id&&e._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 t=document.getElementsByTagName("html")[0];t.addEventListener("mouseup",Kinetic.DD._endDrag,!0),t.addEventListener("touchend",Kinetic.DD._endDrag,!0)}(),function(){Kinetic.Transition=function(t,e){function n(t,e,s,a){for(var r in t)"duration"!==r&&"easing"!==r&&"callback"!==r&&(Kinetic.Type._isObject(t[r])?(s[r]={},n(t[r],e[r],s[r],a)):i._add(i._getTween(e,r,t[r],s,a)))}var i=this,s={};this.node=t,this.config=e,this.tweens=[],n(e,t.attrs,s,s),this.tweens[0].onStarted=function(){},this.tweens[0].onStopped=function(){t.transAnim.stop()},this.tweens[0].onResumed=function(){t.transAnim.start()},this.tweens[0].onLooped=function(){},this.tweens[0].onChanged=function(){},this.tweens[0].onFinished=function(){var n={};for(var i in e)"duration"!==i&&"easing"!==i&&"callback"!==i&&(n[i]=e[i]);t.transAnim.stop(),t.setAttrs(n),e.callback&&e.callback()}},Kinetic.Transition.prototype={start:function(){for(var t=0;t<this.tweens.length;t++)this.tweens[t].start()},stop:function(){for(var t=0;t<this.tweens.length;t++)this.tweens[t].stop()},resume:function(){for(var t=0;t<this.tweens.length;t++)this.tweens[t].resume()},_onEnterFrame:function(){for(var t=0;t<this.tweens.length;t++)this.tweens[t].onEnterFrame()},_add:function(t){this.tweens.push(t)},_getTween:function(t,e,n,i,s){var a=this.config,r=this.node,o=a.easing;void 0===o&&(o="linear");var l=new Kinetic.Tween(r,function(t){i[e]=t,r.setAttrs(s)},Kinetic.Tweens[o],t[e],n,a.duration);return l}},Kinetic.Node.prototype.transitionTo=function(t){var e=new Kinetic.Transition(this,t);return this.transAnim||(this.transAnim=new Kinetic.Animation),this.transAnim.func=function(){e._onEnterFrame()},this.transAnim.node="Stage"===this.nodeType?this:this.getLayer(),e.start(),this.transAnim.start(),this.trans=e,e}}(),function(){Kinetic.Container=function(t){this._containerInit(t)},Kinetic.Container.prototype={_containerInit:function(t){this.children=[],Kinetic.Node.call(this,t)},getChildren:function(){return this.children},removeChildren:function(){for(;this.children.length>0;)this.children[0].remove()},add:function(t){var e=(Kinetic.Global,this.children);return t.index=e.length,t.parent=this,e.push(t),this},get:function(t){var e=new Kinetic.Collection;if("#"===t.charAt(0)){var n=this._getNodeById(t.slice(1));n&&e.push(n)}else if("."===t.charAt(0)){var i=this._getNodesByName(t.slice(1));Kinetic.Collection.apply(e,i)}else{for(var s=[],a=this.getChildren(),r=a.length,o=0;r>o;o++)s=s.concat(a[o]._get(t));Kinetic.Collection.apply(e,s)}return e},_getNodeById:function(t){var e=(this.getStage(),Kinetic.Global),n=e.ids[t];return void 0!==n&&this.isAncestorOf(n)?n:null},_getNodesByName:function(t){var e=Kinetic.Global,n=e.names[t]||[];return this._getDescendants(n)},_get:function(t){for(var e=Kinetic.Node.prototype._get.call(this,t),n=this.getChildren(),i=n.length,s=0;i>s;s++)e=e.concat(n[s]._get(t));return e},toObject:function(){var t=Kinetic.Node.prototype.toObject.call(this);t.children=[];for(var e=this.getChildren(),n=e.length,i=0;n>i;i++){var s=e[i];t.children.push(s.toObject())}return t},_getDescendants:function(t){for(var e=[],n=t.length,i=0;n>i;i++){var s=t[i];this.isAncestorOf(s)&&e.push(s)}return e},isAncestorOf:function(t){for(var e=t.getParent();e;){if(e._id===this._id)return!0;e=e.getParent()}return!1},clone:function(t){var e=Kinetic.Node.prototype.clone.call(this,t);for(var n in this.children)e.add(this.children[n].clone());return e},getIntersections:function(){for(var t=Kinetic.Type._getXY(Array.prototype.slice.call(arguments)),e=[],n=this.get("Shape"),i=n.length,s=0;i>s;s++){var a=n[s];a.isVisible()&&a.intersects(t)&&e.push(a)}return e},_setChildrenIndices:function(){for(var t=this.children,e=t.length,n=0;e>n;n++)t[n].index=n},draw:function(){this.drawScene(),this.drawHit()},drawScene:function(t){if(this.isVisible())for(var e=this.children,n=e.length,i=0;n>i;i++)e[i].drawScene(t)},drawHit:function(){if(this.isVisible()&&this.isListening())for(var t=this.children,e=t.length,n=0;e>n;n++)t[n].drawHit()}},Kinetic.Global.extend(Kinetic.Container,Kinetic.Node)}(),function(){function t(t){t.fill()}function e(t){t.stroke()}function n(t){t.fill()}function i(t){t.stroke()}Kinetic.Shape=function(t){this._initShape(t)},Kinetic.Shape.prototype={_initShape:function(s){this.setDefaultAttrs({fillEnabled:!0,strokeEnabled:!0,shadowEnabled:!0,dashArrayEnabled:!0,fillPriority:"color"}),this.nodeType="Shape",this._fillFunc=t,this._strokeFunc=e,this._fillFuncHit=n,this._strokeFuncHit=i;for(var a,r=Kinetic.Global.shapes;;)if(a=Kinetic.Type._getRandomColorKey(),a&&!(a in r))break;this.colorKey=a,r[a]=this,Kinetic.Node.call(this,s)},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(t){return this.nodeType===t||this.shapeType===t?[this]:[]},intersects:function(){var t=Kinetic.Type._getXY(Array.prototype.slice.call(arguments)),e=this.getStage(),n=e.hitCanvas;n.clear(),this.drawScene(n);var i=n.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data;return i[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(t){var e=this.attrs,n=e.drawFunc,t=t||this.getLayer().getCanvas(),i=t.getContext();n&&this.isVisible()&&(i.save(),t._applyOpacity(this),t._applyLineJoin(this),t._applyAncestorTransforms(this),n.call(this,t),i.restore())},drawHit:function(){var t=this.attrs,e=t.drawHitFunc||t.drawFunc,n=this.getLayer().hitCanvas,i=n.getContext();e&&this.isVisible()&&this.isListening()&&(i.save(),n._applyLineJoin(this),n._applyAncestorTransforms(this),e.call(this,n),i.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(t){this._initStage(t)},Kinetic.Stage.prototype={_initStage:function(t){var e=Kinetic.DD;this.setDefaultAttrs({width:400,height:200}),Kinetic.Container.call(this,t),this._setStageDefaultProperties(),this._id=Kinetic.Global.idCounter++,this._buildDOM(),this._bindContentEvents(),Kinetic.Global.stages.push(this),e&&e._initDragLayer(this)},setContainer:function(t){"string"==typeof t&&(t=document.getElementById(t)),this.setAttr("container",t)},setHeight:function(t){Kinetic.Node.prototype.setHeight.call(this,t),this._resizeDOM()},setWidth:function(t){Kinetic.Node.prototype.setWidth.call(this,t),this._resizeDOM()},clear:function(){for(var t=this.children,e=0;e<t.length;e++)t[e].clear()},remove:function(){var t=this.content;Kinetic.Node.prototype.remove.call(this),t&&Kinetic.Type._isInDocument(t)&&this.attrs.container.removeChild(t)},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(t){function e(s){var a=l[s],c=a.toDataURL(),d=new Image;d.onload=function(){o.drawImage(d,0,0),s<l.length-1?e(s+1):t.callback(r.toDataURL(n,i))},d.src=c}t=t||{};var n=t.mimeType||null,i=t.quality||null,s=t.x||0,a=t.y||0,r=new Kinetic.SceneCanvas(t.width||this.getWidth(),t.height||this.getHeight()),o=r.getContext(),l=this.children;(s||a)&&o.translate(-1*s,-1*a),e(0)},toImage:function(t){var e=t.callback;t.callback=function(t){Kinetic.Type._getImage(t,function(t){e(t)})},this.toDataURL(t)},getIntersection:function(t){for(var e,n=this.getChildren(),i=n.length-1;i>=0;i--){var s=n[i];if(s.isVisible()&&s.isListening()){var a=s.hitCanvas.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data;if(255===a[3]){var r=Kinetic.Type._rgbToHex(a[0],a[1],a[2]);return e=Kinetic.Global.shapes[r],{shape:e,pixel:a}}if(a[0]>0||a[1]>0||a[2]>0||a[3]>0)return{pixel:a}}}return null},_resizeDOM:function(){if(this.content){var t=this.attrs.width,e=this.attrs.height;this.content.style.width=t+"px",this.content.style.height=e+"px",this.bufferCanvas.setSize(t,e,1),this.hitCanvas.setSize(t,e);for(var n=this.children,i=0;i<n.length;i++){var s=n[i];s.getCanvas().setSize(t,e),s.hitCanvas.setSize(t,e),s.draw()}}},add:function(t){return Kinetic.Container.prototype.add.call(this,t),t.canvas.setSize(this.attrs.width,this.attrs.height),t.hitCanvas.setSize(this.attrs.width,this.attrs.height),t.draw(),this.content.appendChild(t.canvas.element),this},getDragLayer:function(){return this.dragLayer},_setUserPosition:function(t){t||(t=window.event),this._setMousePosition(t),this._setTouchPosition(t)},_bindContentEvents:function(){for(var t=(Kinetic.Global,this),e=["mousedown","mousemove","mouseup","mouseout","touchstart","touchmove","touchend"],n=0;n<e.length;n++){var i=e[n];!function(){var e=i;t.content.addEventListener(e,function(n){t["_"+e](n)},!1)}()}},_mouseout:function(t){this._setUserPosition(t);var e=Kinetic.DD,n=this.targetShape;!n||e&&e.moving||(n._handleEvent("mouseout",t),n._handleEvent("mouseleave",t),this.targetShape=null),this.mousePos=void 0},_mousemove:function(t){this._setUserPosition(t);var e=Kinetic.DD,n=this.getIntersection(this.getUserPosition());if(n){var i=n.shape;i&&(e&&e.moving||255!==n.pixel[3]||this.targetShape&&this.targetShape._id===i._id?i._handleEvent("mousemove",t):(this.targetShape&&(this.targetShape._handleEvent("mouseout",t,i),this.targetShape._handleEvent("mouseleave",t,i)),i._handleEvent("mouseover",t,this.targetShape),i._handleEvent("mouseenter",t,this.targetShape),this.targetShape=i))}else!this.targetShape||e&&e.moving||(this.targetShape._handleEvent("mouseout",t),this.targetShape._handleEvent("mouseleave",t),this.targetShape=null);e&&e._drag(t)},_mousedown:function(t){var e,n=Kinetic.DD;if(this._setUserPosition(t),e=this.getIntersection(this.getUserPosition()),e&&e.shape){var i=e.shape;this.clickStart=!0,i._handleEvent("mousedown",t)}n&&this.attrs.draggable&&!n.node&&this._startDrag(t)},_mouseup:function(t){this._setUserPosition(t);var e=this,n=Kinetic.DD,i=this.getIntersection(this.getUserPosition());if(i&&i.shape){var s=i.shape;s._handleEvent("mouseup",t),this.clickStart&&(n&&n.moving&&n.node||(s._handleEvent("click",t),this.inDoubleClickWindow&&s._handleEvent("dblclick",t),this.inDoubleClickWindow=!0,setTimeout(function(){e.inDoubleClickWindow=!1},this.dblClickWindow)))}this.clickStart=!1},_touchstart:function(t){var e,n=Kinetic.DD;if(this._setUserPosition(t),t.preventDefault(),e=this.getIntersection(this.getUserPosition()),e&&e.shape){var i=e.shape;this.tapStart=!0,i._handleEvent("touchstart",t)}n&&this.attrs.draggable&&!n.node&&this._startDrag(t)},_touchend:function(t){this._setUserPosition(t);var e=this,n=Kinetic.DD,i=this.getIntersection(this.getUserPosition());if(i&&i.shape){var s=i.shape;s._handleEvent("touchend",t),this.tapStart&&(n&&n.moving&&n.node||(s._handleEvent("tap",t),this.inDoubleClickWindow&&s._handleEvent("dbltap",t),this.inDoubleClickWindow=!0,setTimeout(function(){e.inDoubleClickWindow=!1},this.dblClickWindow)))}this.tapStart=!1},_touchmove:function(t){this._setUserPosition(t);var e=Kinetic.DD;t.preventDefault();var n=this.getIntersection(this.getUserPosition());if(n&&n.shape){var i=n.shape;i._handleEvent("touchmove",t)}e&&e._drag(t)},_setMousePosition:function(t){var e=t.clientX-this._getContentPosition().left,n=t.clientY-this._getContentPosition().top;this.mousePos={x:e,y:n}},_setTouchPosition:function(t){if(void 0!==t.touches&&1===t.touches.length){var e=t.touches[0],n=e.clientX-this._getContentPosition().left,i=e.clientY-this._getContentPosition().top;this.touchPos={x:n,y:i}}},_getContentPosition:function(){var t=this.content.getBoundingClientRect();return{top:t.top,left:t.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(t,e){for(var n=t.split(" "),i=0;i<n.length;i++){var s=n[i];this.content.addEventListener(s,e,!1)}},_setStageDefaultProperties:function(){this.nodeType="Stage",this.dblClickWindow=400,this.targetShape=null,this.mousePos=void 0,this.clickStart=!1,this.touchPos=void 0,this.tapStart=!1}},Kinetic.Global.extend(Kinetic.Stage,Kinetic.Container),Kinetic.Node.addGetters(Kinetic.Stage,["container"])}(),function(){Kinetic.Layer=function(t){this._initLayer(t)},Kinetic.Layer.prototype={_initLayer:function(t){this.setDefaultAttrs({clearBeforeDraw:!0}),this.nodeType="Layer",this.beforeDrawFunc=void 0,this.afterDrawFunc=void 0,this.canvas=new Kinetic.SceneCanvas,this.canvas.getElement().style.position="absolute",this.hitCanvas=new Kinetic.HitCanvas,Kinetic.Container.call(this,t)},draw:function(){this.getContext();void 0!==this.beforeDrawFunc&&this.beforeDrawFunc.call(this),Kinetic.Container.prototype.draw.call(this),void 0!==this.afterDrawFunc&&this.afterDrawFunc.call(this)},drawHit:function(){this.hitCanvas.clear(),Kinetic.Container.prototype.drawHit.call(this)},drawScene:function(t){t=t||this.getCanvas(),this.attrs.clearBeforeDraw&&t.clear(),Kinetic.Container.prototype.drawScene.call(this,t)},toDataURL:function(t){t=t||{};{var e=t.mimeType||null,n=t.quality||null;t.x||0,t.y||0}return t.width||t.height||t.x||t.y?Kinetic.Node.prototype.toDataURL.call(this,t):this.getCanvas().toDataURL(e,n)},beforeDraw:function(t){this.beforeDrawFunc=t},afterDraw:function(t){this.afterDrawFunc=t},getCanvas:function(){return this.canvas},getContext:function(){return this.canvas.context},clear:function(){this.getCanvas().clear()},setVisible:function(t){Kinetic.Node.prototype.setVisible.call(this,t),t?(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(t){Kinetic.Node.prototype.setZIndex.call(this,t);var e=this.getStage();e&&(e.content.removeChild(this.canvas.element),t<e.getChildren().length-1?e.content.insertBefore(this.canvas.element,e.getChildren()[t+1].canvas.element):e.content.appendChild(this.canvas.element))},moveToTop:function(){Kinetic.Node.prototype.moveToTop.call(this);var t=this.getStage();t&&(t.content.removeChild(this.canvas.element),t.content.appendChild(this.canvas.element))},moveUp:function(){if(Kinetic.Node.prototype.moveUp.call(this)){var t=this.getStage();t&&(t.content.removeChild(this.canvas.element),this.index<t.getChildren().length-1?t.content.insertBefore(this.canvas.element,t.getChildren()[this.index+1].canvas.element):t.content.appendChild(this.canvas.element))}},moveDown:function(){if(Kinetic.Node.prototype.moveDown.call(this)){var t=this.getStage();if(t){var e=t.getChildren();t.content.removeChild(this.canvas.element),t.content.insertBefore(this.canvas.element,e[this.index+1].canvas.element)}}},moveToBottom:function(){if(Kinetic.Node.prototype.moveToBottom.call(this)){var t=this.getStage();if(t){var e=t.getChildren();t.content.removeChild(this.canvas.element),t.content.insertBefore(this.canvas.element,e[1].canvas.element)}}},getLayer:function(){return this},remove:function(){var t=this.getStage(),e=this.canvas,n=e.element;Kinetic.Node.prototype.remove.call(this),t&&e&&Kinetic.Type._isInDocument(n)&&t.content.removeChild(n)}},Kinetic.Global.extend(Kinetic.Layer,Kinetic.Container),Kinetic.Node.addGettersSetters(Kinetic.Layer,["clearBeforeDraw"])}(),function(){Kinetic.Group=function(t){this._initGroup(t)},Kinetic.Group.prototype={_initGroup:function(t){this.nodeType="Group",Kinetic.Container.call(this,t)}},Kinetic.Global.extend(Kinetic.Group,Kinetic.Container)}(),function(){Kinetic.Rect=function(t){this._initRect(t)},Kinetic.Rect.prototype={_initRect:function(t){this.setDefaultAttrs({width:0,height:0,cornerRadius:0}),Kinetic.Shape.call(this,t),this.shapeType="Rect",this._setDrawFuncs()},drawFunc:function(t){var e=t.getContext();e.beginPath();var n=this.getCornerRadius(),i=this.getWidth(),s=this.getHeight();0===n?e.rect(0,0,i,s):(e.moveTo(n,0),e.lineTo(i-n,0),e.arc(i-n,n,n,3*Math.PI/2,0,!1),e.lineTo(i,s-n),e.arc(i-n,s-n,n,0,Math.PI/2,!1),e.lineTo(n,s),e.arc(n,s-n,n,Math.PI/2,Math.PI,!1),e.lineTo(0,n),e.arc(n,n,n,Math.PI,3*Math.PI/2,!1)),e.closePath(),t.fillStroke(this)}},Kinetic.Global.extend(Kinetic.Rect,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Rect,["cornerRadius"])}(),function(){Kinetic.Circle=function(t){this._initCircle(t)},Kinetic.Circle.prototype={_initCircle:function(t){this.setDefaultAttrs({radius:0}),Kinetic.Shape.call(this,t),this.shapeType="Circle",this._setDrawFuncs()},drawFunc:function(t){var e=t.getContext();e.beginPath(),e.arc(0,0,this.getRadius(),0,2*Math.PI,!0),e.closePath(),t.fillStroke(this)},getWidth:function(){return 2*this.getRadius()},getHeight:function(){return 2*this.getRadius()},setWidth:function(t){Kinetic.Node.prototype.setWidth.call(this,t),this.setRadius(t/2)},setHeight:function(t){Kinetic.Node.prototype.setHeight.call(this,t),this.setRadius(t/2)}},Kinetic.Global.extend(Kinetic.Circle,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Circle,["radius"])}(),function(){Kinetic.Wedge=function(t){this._initWedge(t)},Kinetic.Wedge.prototype={_initWedge:function(t){this.setDefaultAttrs({radius:0,angle:0,clockwise:!1}),Kinetic.Shape.call(this,t),this.shapeType="Wedge",this._setDrawFuncs()},drawFunc:function(t){var e=t.getContext();e.beginPath(),e.arc(0,0,this.getRadius(),0,this.getAngle(),this.getClockwise()),e.lineTo(0,0),e.closePath(),t.fillStroke(this)},setAngleDeg:function(t){this.setAngle(Kinetic.Type._degToRad(t))},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(t){this._initEllipse(t)},Kinetic.Ellipse.prototype={_initEllipse:function(t){this.setDefaultAttrs({radius:{x:0,y:0}}),Kinetic.Shape.call(this,t),this.shapeType="Ellipse",this._setDrawFuncs()},drawFunc:function(t){var e=t.getContext(),n=this.getRadius();e.beginPath(),e.save(),n.x!==n.y&&e.scale(1,n.y/n.x),e.arc(0,0,n.x,0,2*Math.PI,!0),e.restore(),e.closePath(),t.fillStroke(this)},getWidth:function(){return 2*this.getRadius().x},getHeight:function(){return 2*this.getRadius().y},setWidth:function(t){Kinetic.Node.prototype.setWidth.call(this,t),this.setRadius({x:t/2})},setHeight:function(t){Kinetic.Node.prototype.setHeight.call(this,t),this.setRadius({y:t/2})}},Kinetic.Global.extend(Kinetic.Ellipse,Kinetic.Shape),Kinetic.Node.addPointGettersSetters(Kinetic.Ellipse,["radius"])}(),function(){Kinetic.Image=function(t){this._initImage(t)},Kinetic.Image.prototype={_initImage:function(t){Kinetic.Shape.call(this,t),this.shapeType="Image",this._setDrawFuncs();var e=this;this.on("imageChange",function(){e._syncSize()}),this._syncSize()},drawFunc:function(t){var e,n=this.getWidth(),i=this.getHeight(),s=this,a=t.getContext();if(a.beginPath(),a.rect(0,0,n,i),a.closePath(),t.fillStroke(this),this.attrs.image){if(this.attrs.crop&&this.attrs.crop.width&&this.attrs.crop.height){var r=this.attrs.crop.x||0,o=this.attrs.crop.y||0,l=this.attrs.crop.width,c=this.attrs.crop.height;e=[this.attrs.image,r,o,l,c,0,0,n,i]}else e=[this.attrs.image,0,0,n,i];this.hasShadow()?t.applyShadow(this,function(){s._drawImage(a,e)}):this._drawImage(a,e)}},drawHitFunc:function(t){var e=this.getWidth(),n=this.getHeight(),i=this.imageHitRegion,s=t.getContext();i?(s.drawImage(i,0,0,e,n),s.beginPath(),s.rect(0,0,e,n),s.closePath(),t.stroke(this)):(s.beginPath(),s.rect(0,0,e,n),s.closePath(),t.fillStroke(this))},applyFilter:function(t,e,n){var i=new Kinetic.Canvas(this.attrs.image.width,this.attrs.image.height),s=i.getContext();s.drawImage(this.attrs.image,0,0);try{var a=s.getImageData(0,0,i.getWidth(),i.getHeight());t(a,e);var r=this;Kinetic.Type._getImage(a,function(t){r.setImage(t),n&&n()})}catch(o){Kinetic.Global.warn("Unable to apply filter. "+o.message)}},setCrop:function(){var t=[].slice.call(arguments),e=Kinetic.Type._getXY(t),n=Kinetic.Type._getSize(t),i=Kinetic.Type._merge(e,n);this.setAttr("crop",Kinetic.Type._merge(i,this.getCrop()))},createImageHitRegion:function(t){var e=new Kinetic.Canvas(this.attrs.width,this.attrs.height),n=e.getContext();n.drawImage(this.attrs.image,0,0);try{for(var i=n.getImageData(0,0,e.getWidth(),e.getHeight()),s=i.data,a=Kinetic.Type._hexToRgb(this.colorKey),r=0,o=s.length;o>r;r+=4)s[r]=a.r,s[r+1]=a.g,s[r+2]=a.b;var l=this;Kinetic.Type._getImage(i,function(e){l.imageHitRegion=e,t&&t()})}catch(c){Kinetic.Global.warn("Unable to create image hit region. "+c.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(t,e){5===e.length?t.drawImage(e[0],e[1],e[2],e[3],e[4]):9===e.length&&t.drawImage(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8])}},Kinetic.Global.extend(Kinetic.Image,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Image,["image"]),Kinetic.Node.addGetters(Kinetic.Image,["crop"])}(),function(){Kinetic.Polygon=function(t){this._initPolygon(t)},Kinetic.Polygon.prototype={_initPolygon:function(t){this.setDefaultAttrs({points:[]}),Kinetic.Shape.call(this,t),this.shapeType="Polygon",this._setDrawFuncs()},drawFunc:function(t){var e=t.getContext(),n=this.getPoints(),i=n.length;e.beginPath(),e.moveTo(n[0].x,n[0].y);for(var s=1;i>s;s++)e.lineTo(n[s].x,n[s].y);e.closePath(),t.fillStroke(this)},setPoints:function(t){this.setAttr("points",Kinetic.Type._getPoints(t))}},Kinetic.Global.extend(Kinetic.Polygon,Kinetic.Shape),Kinetic.Node.addGetters(Kinetic.Polygon,["points"])}(),function(){function t(t){t.fillText(this.partialText,0,0)}function e(t){t.strokeText(this.partialText,0,0)}var i="auto",s="Calibri",a="canvas",r="center",o="Change.kinetic",l="2d",c="\n",d="",h="left",u="\n",p="text",m="Text",f="top",g="middle",v="normal",b="px ",w=" ",y="right",_=["fontFamily","fontSize","fontStyle","padding","align","lineHeight","text","width","height"],x=_.length;Kinetic.Text=function(t){this._initText(t)},Kinetic.Text.prototype={_initText:function(n){var r=this;this.setDefaultAttrs({fontFamily:s,text:d,fontSize:12,align:h,verticalAlign:f,fontStyle:v,padding:0,width:i,height:i,lineHeight:1}),this.dummyCanvas=document.createElement(a),Kinetic.Shape.call(this,n),this._fillFunc=t,this._strokeFunc=e,this.shapeType=m,this._setDrawFuncs();for(var l=0;x>l;l++)this.on(_[l]+o,r._setTextData);this._setTextData()},drawFunc:function(t){var e=t.getContext(),n=this.getPadding(),i=this.getFontStyle(),s=this.getFontSize(),a=this.getFontFamily(),o=this.getTextHeight(),l=this.getLineHeight()*o,c=this.textArr,d=c.length,u=this.getWidth();e.font=i+w+s+b+a,e.textBaseline=g,e.textAlign=h,e.save(),e.translate(n,0),e.translate(0,n+o/2);for(var p=0;d>p;p++){var m=c[p],f=m.text,v=m.width;e.save(),this.getAlign()===y?e.translate(u-v-2*n,0):this.getAlign()===r&&e.translate((u-v-2*n)/2,0),this.partialText=f,t.fillStroke(this),e.restore(),e.translate(0,l)}e.restore()},drawHitFunc:function(t){var e=t.getContext(),n=this.getWidth(),i=this.getHeight();e.beginPath(),e.rect(0,0,n,i),e.closePath(),t.fillStroke(this)},setText:function(t){var e=Kinetic.Type._isString(t)?t:t.toString();this.setAttr(p,e)
},getWidth:function(){return this.attrs.width===i?this.getTextWidth()+2*this.getPadding():this.attrs.width},getHeight:function(){return this.attrs.height===i?this.getTextHeight()*this.textArr.length*this.attrs.lineHeight+2*this.attrs.padding:this.attrs.height},getTextWidth:function(){return this.textWidth},getTextHeight:function(){return this.textHeight},_getTextSize:function(t){var e,n=this.dummyCanvas,i=n.getContext(l),s=this.getFontSize();return i.save(),i.font=this.getFontStyle()+w+s+b+this.getFontFamily(),e=i.measureText(t),i.restore(),{width:e.width,height:parseInt(s,10)}},_expandTextData:function(t){var e=t.length;for(n=0,text=d,newArr=[],n=0;n<e;n++)text=t[n],newArr.push({text:text,width:this._getTextSize(text).width});return newArr},_setTextData:function(){var t=this.getText().split(d),e=[],n=0;for(addLine=!0,lineHeightPx=0,padding=this.getPadding(),this.textWidth=0,this.textHeight=this._getTextSize(this.getText()).height,lineHeightPx=this.getLineHeight()*this.textHeight;t.length>0&&addLine&&(this.attrs.height===i||lineHeightPx*(n+1)<this.attrs.height-2*padding);){var s=0,a=void 0;for(addLine=!1;s<t.length;){if(t.indexOf(u)===s){t.splice(s,1),a=t.splice(0,s).join(d);break}var r=t.slice(0,s);if(this.attrs.width!==i&&this._getTextSize(r.join(d)).width>this.attrs.width-2*padding){if(0==s)break;var o=r.lastIndexOf(w),l=r.lastIndexOf(c),h=Math.max(o,l);if(h>=0){a=t.splice(0,1+h).join(d);break}a=t.splice(0,s).join(d);break}s++,s===t.length&&(a=t.splice(0,s).join(d))}this.textWidth=Math.max(this.textWidth,this._getTextSize(a).width),void 0!==a&&(e.push(a),addLine=!0),n++}this.textArr=this._expandTextData(e)}},Kinetic.Global.extend(Kinetic.Text,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Text,["fontFamily","fontSize","fontStyle","padding","align","lineHeight"]),Kinetic.Node.addGetters(Kinetic.Text,[p])}(),function(){Kinetic.Line=function(t){this._initLine(t)},Kinetic.Line.prototype={_initLine:function(t){this.setDefaultAttrs({points:[],lineCap:"butt"}),Kinetic.Shape.call(this,t),this.shapeType="Line",this._setDrawFuncs()},drawFunc:function(t){var e=this.getPoints(),n=e.length,i=t.getContext();i.beginPath(),i.moveTo(e[0].x,e[0].y);for(var s=1;n>s;s++){var a=e[s];i.lineTo(a.x,a.y)}t.stroke(this)},setPoints:function(t){this.setAttr("points",Kinetic.Type._getPoints(t))}},Kinetic.Global.extend(Kinetic.Line,Kinetic.Shape),Kinetic.Node.addGetters(Kinetic.Line,["points"])}(),function(){Kinetic.Spline=function(t){this._initSpline(t)},Kinetic.Spline._getControlPoints=function(t,e,n,i){var s=t.x,a=t.y,r=e.x,o=e.y,l=n.x,c=n.y,d=Math.sqrt(Math.pow(r-s,2)+Math.pow(o-a,2)),h=Math.sqrt(Math.pow(l-r,2)+Math.pow(c-o,2)),u=i*d/(d+h),p=i*h/(d+h),m=r-u*(l-s),f=o-u*(c-a),g=r+p*(l-s),v=o+p*(c-a);return[{x:m,y:f},{x:g,y:v}]},Kinetic.Spline.prototype={_initSpline:function(t){this.setDefaultAttrs({tension:1}),Kinetic.Line.call(this,t),this.shapeType="Spline"},drawFunc:function(t){var e=this.getPoints(),n=e.length,i=t.getContext(),s=this.getTension();if(i.beginPath(),i.moveTo(e[0].x,e[0].y),0!==s&&n>2){var a=this.allPoints,r=a.length;i.quadraticCurveTo(a[0].x,a[0].y,a[1].x,a[1].y);for(var o=2;r-1>o;)i.bezierCurveTo(a[o].x,a[o++].y,a[o].x,a[o++].y,a[o].x,a[o++].y);i.quadraticCurveTo(a[r-1].x,a[r-1].y,e[n-1].x,e[n-1].y)}else for(var o=1;n>o;o++){var l=e[o];i.lineTo(l.x,l.y)}t.stroke(this)},setPoints:function(t){Kinetic.Line.prototype.setPoints.call(this,t),this._setAllPoints()},setTension:function(t){this.setAttr("tension",t),this._setAllPoints()},_setAllPoints:function(){for(var t=this.getPoints(),e=t.length,n=this.getTension(),i=[],s=1;e-1>s;s++){var a=Kinetic.Spline._getControlPoints(t[s-1],t[s],t[s+1],n);i.push(a[0]),i.push(t[s]),i.push(a[1])}this.allPoints=i}},Kinetic.Global.extend(Kinetic.Spline,Kinetic.Line),Kinetic.Node.addGetters(Kinetic.Spline,["tension"])}(),function(){Kinetic.Blob=function(t){this._initBlob(t)},Kinetic.Blob.prototype={_initBlob:function(t){Kinetic.Spline.call(this,t),this.shapeType="Blob"},drawFunc:function(t){var e=this.getPoints(),n=e.length,i=t.getContext(),s=this.getTension();if(i.beginPath(),i.moveTo(e[0].x,e[0].y),0!==s&&n>2)for(var a=this.allPoints,r=a.length,o=0;r-1>o;)i.bezierCurveTo(a[o].x,a[o++].y,a[o].x,a[o++].y,a[o].x,a[o++].y);else for(var o=1;n>o;o++){var l=e[o];i.lineTo(l.x,l.y)}i.closePath(),t.fillStroke(this)},_setAllPoints:function(){var t=this.getPoints(),e=t.length,n=this.getTension(),i=Kinetic.Spline._getControlPoints(t[e-1],t[0],t[1],n),s=Kinetic.Spline._getControlPoints(t[e-2],t[e-1],t[0],n);Kinetic.Spline.prototype._setAllPoints.call(this),this.allPoints.unshift(i[1]),this.allPoints.push(s[0]),this.allPoints.push(t[e-1]),this.allPoints.push(s[1]),this.allPoints.push(i[0]),this.allPoints.push(t[0])}},Kinetic.Global.extend(Kinetic.Blob,Kinetic.Spline)}(),function(){Kinetic.Sprite=function(t){this._initSprite(t)},Kinetic.Sprite.prototype={_initSprite:function(t){this.setDefaultAttrs({index:0,frameRate:17}),Kinetic.Shape.call(this,t),this.shapeType="Sprite",this._setDrawFuncs(),this.anim=new Kinetic.Animation;var e=this;this.on("animationChange",function(){e.setIndex(0)})},drawFunc:function(t){var e=this.attrs.animation,n=this.attrs.index,i=this.attrs.animations[e][n],s=t.getContext(),a=this.attrs.image;a&&s.drawImage(a,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},drawHitFunc:function(t){var e=this.attrs.animation,n=this.attrs.index,i=this.attrs.animations[e][n],s=t.getContext();s.beginPath(),s.rect(0,0,i.width,i.height),s.closePath(),t.fill(this)},start:function(){var t=this,e=this.getLayer();this.anim.node=e,this.interval=setInterval(function(){var e=t.attrs.index;t._updateIndex(),t.afterFrameFunc&&e===t.afterFrameIndex&&(t.afterFrameFunc(),delete t.afterFrameFunc,delete t.afterFrameIndex)},1e3/this.attrs.frameRate),this.anim.start()},stop:function(){this.anim.stop(),clearInterval(this.interval)},afterFrame:function(t,e){this.afterFrameIndex=t,this.afterFrameFunc=e},_updateIndex:function(){var t=this.attrs.index,e=this.attrs.animation;t<this.attrs.animations[e].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(t){this._initStar(t)},Kinetic.Star.prototype={_initStar:function(t){this.setDefaultAttrs({numPoints:0,innerRadius:0,outerRadius:0}),Kinetic.Shape.call(this,t),this.shapeType="Star",this._setDrawFuncs()},drawFunc:function(t){var e=t.getContext(),n=this.attrs.innerRadius,i=this.attrs.outerRadius,s=this.attrs.numPoints;e.beginPath(),e.moveTo(0,0-this.attrs.outerRadius);for(var a=1;2*s>a;a++){var r=a%2===0?i:n,o=r*Math.sin(a*Math.PI/s),l=-1*r*Math.cos(a*Math.PI/s);e.lineTo(o,l)}e.closePath(),t.fillStroke(this)}},Kinetic.Global.extend(Kinetic.Star,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.Star,["numPoints","innerRadius","outerRadius"])}(),function(){Kinetic.RegularPolygon=function(t){this._initRegularPolygon(t)},Kinetic.RegularPolygon.prototype={_initRegularPolygon:function(t){this.setDefaultAttrs({radius:0,sides:0}),Kinetic.Shape.call(this,t),this.shapeType="RegularPolygon",this._setDrawFuncs()},drawFunc:function(t){var e=t.getContext(),n=this.attrs.sides,i=this.attrs.radius;e.beginPath(),e.moveTo(0,0-i);for(var s=1;n>s;s++){var a=i*Math.sin(2*s*Math.PI/n),r=-1*i*Math.cos(2*s*Math.PI/n);e.lineTo(a,r)}e.closePath(),t.fillStroke(this)}},Kinetic.Global.extend(Kinetic.RegularPolygon,Kinetic.Shape),Kinetic.Node.addGettersSetters(Kinetic.RegularPolygon,["radius","sides"])}(),function(){Kinetic.Path=function(t){this._initPath(t)},Kinetic.Path.prototype={_initPath:function(t){this.dataArray=[];var e=this;Kinetic.Shape.call(this,t),this.shapeType="Path",this._setDrawFuncs(),this.dataArray=Kinetic.Path.parsePathData(this.attrs.data),this.on("dataChange",function(){e.dataArray=Kinetic.Path.parsePathData(e.attrs.data)})},drawFunc:function(t){var e=this.dataArray,n=t.getContext();n.beginPath();for(var i=0;i<e.length;i++){var s=e[i].command,a=e[i].points;switch(s){case"L":n.lineTo(a[0],a[1]);break;case"M":n.moveTo(a[0],a[1]);break;case"C":n.bezierCurveTo(a[0],a[1],a[2],a[3],a[4],a[5]);break;case"Q":n.quadraticCurveTo(a[0],a[1],a[2],a[3]);break;case"A":var r=a[0],o=a[1],l=a[2],c=a[3],d=a[4],h=a[5],u=a[6],p=a[7],m=l>c?l:c,f=l>c?1:l/c,g=l>c?c/l:1;n.translate(r,o),n.rotate(u),n.scale(f,g),n.arc(0,0,m,d,d+h,1-p),n.scale(1/f,1/g),n.rotate(-u),n.translate(-r,-o);break;case"z":n.closePath()}}t.fillStroke(this)}},Kinetic.Global.extend(Kinetic.Path,Kinetic.Shape),Kinetic.Path.getLineLength=function(t,e,n,i){return Math.sqrt((n-t)*(n-t)+(i-e)*(i-e))},Kinetic.Path.getPointOnLine=function(t,e,n,i,s,a,r){void 0===a&&(a=e),void 0===r&&(r=n);var o=(s-n)/(i-e+1e-8),l=Math.sqrt(t*t/(1+o*o));e>i&&(l*=-1);var c,d=o*l;if((r-n)/(a-e+1e-8)===o)c={x:a+l,y:r+d};else{var h,u,p=this.getLineLength(e,n,i,s);if(1e-8>p)return void 0;var m=(a-e)*(i-e)+(r-n)*(s-n);m/=p*p,h=e+m*(i-e),u=n+m*(s-n);var f=this.getLineLength(a,r,h,u),g=Math.sqrt(t*t-f*f);l=Math.sqrt(g*g/(1+o*o)),e>i&&(l*=-1),d=o*l,c={x:h+l,y:u+d}}return c},Kinetic.Path.getPointOnCubicBezier=function(t,e,n,i,s,a,r,o,l){function c(t){return t*t*t}function d(t){return 3*t*t*(1-t)}function h(t){return 3*t*(1-t)*(1-t)}function u(t){return(1-t)*(1-t)*(1-t)}var p=o*c(t)+a*d(t)+i*h(t)+e*u(t),m=l*c(t)+r*d(t)+s*h(t)+n*u(t);return{x:p,y:m}},Kinetic.Path.getPointOnQuadraticBezier=function(t,e,n,i,s,a,r){function o(t){return t*t}function l(t){return 2*t*(1-t)}function c(t){return(1-t)*(1-t)}var d=a*o(t)+i*l(t)+e*c(t),h=r*o(t)+s*l(t)+n*c(t);return{x:d,y:h}},Kinetic.Path.getPointOnEllipticalArc=function(t,e,n,i,s,a){var r=Math.cos(a),o=Math.sin(a),l={x:n*Math.cos(s),y:i*Math.sin(s)};return{x:t+(l.x*r-l.y*o),y:e+(l.x*o+l.y*r)}},Kinetic.Path.parsePathData=function(t){if(!t)return[];var e=t,n=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];e=e.replace(new RegExp(" ","g"),",");for(var i=0;i<n.length;i++)e=e.replace(new RegExp(n[i],"g"),"|"+n[i]);for(var s=e.split("|"),a=[],r=0,o=0,i=1;i<s.length;i++){var l=s[i],c=l.charAt(0);l=l.slice(1),l=l.replace(new RegExp(",-","g"),"-"),l=l.replace(new RegExp("-","g"),",-"),l=l.replace(new RegExp("e,-","g"),"e-");var d=l.split(",");d.length>0&&""===d[0]&&d.shift();for(var h=0;h<d.length;h++)d[h]=parseFloat(d[h]);for(;d.length>0&&!isNaN(d[0]);){var u=null,p=[],m=r,f=o;switch(c){case"l":r+=d.shift(),o+=d.shift(),u="L",p.push(r,o);break;case"L":r=d.shift(),o=d.shift(),p.push(r,o);break;case"m":r+=d.shift(),o+=d.shift(),u="M",p.push(r,o),c="l";break;case"M":r=d.shift(),o=d.shift(),u="M",p.push(r,o),c="L";break;case"h":r+=d.shift(),u="L",p.push(r,o);break;case"H":r=d.shift(),u="L",p.push(r,o);break;case"v":o+=d.shift(),u="L",p.push(r,o);break;case"V":o=d.shift(),u="L",p.push(r,o);break;case"C":p.push(d.shift(),d.shift(),d.shift(),d.shift()),r=d.shift(),o=d.shift(),p.push(r,o);break;case"c":p.push(r+d.shift(),o+d.shift(),r+d.shift(),o+d.shift()),r+=d.shift(),o+=d.shift(),u="C",p.push(r,o);break;case"S":var g=r,v=o,b=a[a.length-1];"C"===b.command&&(g=r+(r-b.points[2]),v=o+(o-b.points[3])),p.push(g,v,d.shift(),d.shift()),r=d.shift(),o=d.shift(),u="C",p.push(r,o);break;case"s":var g=r,v=o,b=a[a.length-1];"C"===b.command&&(g=r+(r-b.points[2]),v=o+(o-b.points[3])),p.push(g,v,r+d.shift(),o+d.shift()),r+=d.shift(),o+=d.shift(),u="C",p.push(r,o);break;case"Q":p.push(d.shift(),d.shift()),r=d.shift(),o=d.shift(),p.push(r,o);break;case"q":p.push(r+d.shift(),o+d.shift()),r+=d.shift(),o+=d.shift(),u="Q",p.push(r,o);break;case"T":var g=r,v=o,b=a[a.length-1];"Q"===b.command&&(g=r+(r-b.points[0]),v=o+(o-b.points[1])),r=d.shift(),o=d.shift(),u="Q",p.push(g,v,r,o);break;case"t":var g=r,v=o,b=a[a.length-1];"Q"===b.command&&(g=r+(r-b.points[0]),v=o+(o-b.points[1])),r+=d.shift(),o+=d.shift(),u="Q",p.push(g,v,r,o);break;case"A":var w=d.shift(),y=d.shift(),_=d.shift(),x=d.shift(),k=d.shift(),C=r,S=o;r=d.shift(),o=d.shift(),u="A",p=this.convertEndpointToCenterParameterization(C,S,r,o,x,k,w,y,_);break;case"a":var w=d.shift(),y=d.shift(),_=d.shift(),x=d.shift(),k=d.shift(),C=r,S=o;r+=d.shift(),o+=d.shift(),u="A",p=this.convertEndpointToCenterParameterization(C,S,r,o,x,k,w,y,_)}a.push({command:u||c,points:p,start:{x:m,y:f},pathLength:this.calcLength(m,f,u||c,p)})}("z"===c||"Z"===c)&&a.push({command:"z",points:[],start:void 0,pathLength:0})}return a},Kinetic.Path.calcLength=function(e,n,i,s){var a,r,o,l=Kinetic.Path;switch(i){case"L":return l.getLineLength(e,n,s[0],s[1]);case"C":for(a=0,r=l.getPointOnCubicBezier(0,e,n,s[0],s[1],s[2],s[3],s[4],s[5]),t=.01;t<=1;t+=.01)o=l.getPointOnCubicBezier(t,e,n,s[0],s[1],s[2],s[3],s[4],s[5]),a+=l.getLineLength(r.x,r.y,o.x,o.y),r=o;return a;case"Q":for(a=0,r=l.getPointOnQuadraticBezier(0,e,n,s[0],s[1],s[2],s[3]),t=.01;t<=1;t+=.01)o=l.getPointOnQuadraticBezier(t,e,n,s[0],s[1],s[2],s[3]),a+=l.getLineLength(r.x,r.y,o.x,o.y),r=o;return a;case"A":a=0;var c=s[4],d=s[5],h=s[4]+d,u=Math.PI/180;if(Math.abs(c-h)<u&&(u=Math.abs(c-h)),r=l.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],c,0),0>d)for(t=c-u;t>h;t-=u)o=l.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],t,0),a+=l.getLineLength(r.x,r.y,o.x,o.y),r=o;else for(t=c+u;t<h;t+=u)o=l.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],t,0),a+=l.getLineLength(r.x,r.y,o.x,o.y),r=o;return o=l.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],h,0),a+=l.getLineLength(r.x,r.y,o.x,o.y)}return 0},Kinetic.Path.convertEndpointToCenterParameterization=function(t,e,n,i,s,a,r,o,l){var c=l*(Math.PI/180),d=Math.cos(c)*(t-n)/2+Math.sin(c)*(e-i)/2,h=-1*Math.sin(c)*(t-n)/2+Math.cos(c)*(e-i)/2,u=d*d/(r*r)+h*h/(o*o);u>1&&(r*=Math.sqrt(u),o*=Math.sqrt(u));var p=Math.sqrt((r*r*o*o-r*r*h*h-o*o*d*d)/(r*r*h*h+o*o*d*d));s==a&&(p*=-1),isNaN(p)&&(p=0);var m=p*r*h/o,f=p*-o*d/r,g=(t+n)/2+Math.cos(c)*m-Math.sin(c)*f,v=(e+i)/2+Math.sin(c)*m+Math.cos(c)*f,b=function(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])},w=function(t,e){return(t[0]*e[0]+t[1]*e[1])/(b(t)*b(e))},y=function(t,e){return(t[0]*e[1]<t[1]*e[0]?-1:1)*Math.acos(w(t,e))},_=y([1,0],[(d-m)/r,(h-f)/o]),x=[(d-m)/r,(h-f)/o],k=[(-1*d-m)/r,(-1*h-f)/o],C=y(x,k);return w(x,k)<=-1&&(C=Math.PI),w(x,k)>=1&&(C=0),0===a&&C>0&&(C-=2*Math.PI),1==a&&0>C&&(C+=2*Math.PI),[g,v,r,o,_,C,c,a]},Kinetic.Node.addGettersSetters(Kinetic.Path,["data"])}(),function(){function t(t){t.fillText(this.partialText,0,0)}function e(t){t.strokeText(this.partialText,0,0)}Kinetic.TextPath=function(t){this._initTextPath(t)},Kinetic.TextPath.prototype={_initTextPath:function(n){this.setDefaultAttrs({fontFamily:"Calibri",fontSize:12,fontStyle:"normal",text:""}),this.dummyCanvas=document.createElement("canvas"),this.dataArray=[];var i=this;Kinetic.Shape.call(this,n),this._fillFunc=t,this._strokeFunc=e,this.shapeType="TextPath",this._setDrawFuncs(),this.dataArray=Kinetic.Path.parsePathData(this.attrs.data),this.on("dataChange",function(){i.dataArray=Kinetic.Path.parsePathData(this.attrs.data)});for(var s=["text","textStroke","textStrokeWidth"],a=0;a<s.length;a++){var r=s[a];this.on(r+"Change",i._setTextData)}i._setTextData()},drawFunc:function(t){var e=(this.charArr,t.getContext());e.font=this.attrs.fontStyle+" "+this.attrs.fontSize+"pt "+this.attrs.fontFamily,e.textBaseline="middle",e.textAlign="left",e.save();for(var n=this.glyphInfo,i=0;i<n.length;i++){e.save();{var s=n[i].p0;n[i].p1,parseFloat(this.attrs.fontSize)}e.translate(s.x,s.y),e.rotate(n[i].rotation),this.partialText=n[i].text,t.fillStroke(this),e.restore()}e.restore()},getTextWidth:function(){return this.textWidth},getTextHeight:function(){return this.textHeight},setText:function(t){Kinetic.Text.prototype.setText.call(this,t)},_getTextSize:function(t){var e=this.dummyCanvas,n=e.getContext("2d");n.save(),n.font=this.attrs.fontStyle+" "+this.attrs.fontSize+"pt "+this.attrs.fontFamily;var i=n.measureText(t);return n.restore(),{width:i.width,height:parseInt(this.attrs.fontSize,10)}},_setTextData:function(){var t=this,e=this._getTextSize(this.attrs.text);this.textWidth=e.width,this.textHeight=e.height,this.glyphInfo=[];for(var n,i,s,a=this.attrs.text.split(""),r=-1,o=0,l=function(){o=0;for(var e=t.dataArray,i=r+1;i<e.length;i++){if(e[i].pathLength>0)return r=i,e[i];"M"==e[i].command&&(n={x:e[i].points[0],y:e[i].points[1]})}return{}},c=function(e){var a=t._getTextSize(e).width,r=0,c=0;for(i=void 0;Math.abs(a-r)/a>.01&&25>c;){c++;for(var d=r;void 0===s;)s=l(),s&&d+s.pathLength<a&&(d+=s.pathLength,s=void 0);if(s==={}||void 0===n)return void 0;var h=!1;switch(s.command){case"L":Kinetic.Path.getLineLength(n.x,n.y,s.points[0],s.points[1])>a?i=Kinetic.Path.getPointOnLine(a,n.x,n.y,s.points[0],s.points[1],n.x,n.y):s=void 0;break;case"A":var u=s.points[4],p=s.points[5],m=s.points[4]+p;0===o?o=u+1e-8:a>r?o+=Math.PI/180*p/Math.abs(p):o-=Math.PI/360*p/Math.abs(p),Math.abs(o)>Math.abs(m)&&(o=m,h=!0),i=Kinetic.Path.getPointOnEllipticalArc(s.points[0],s.points[1],s.points[2],s.points[3],o,s.points[6]);break;case"C":0===o?o=a>s.pathLength?1e-8:a/s.pathLength:a>r?o+=(a-r)/s.pathLength:o-=(r-a)/s.pathLength,o>1&&(o=1,h=!0),i=Kinetic.Path.getPointOnCubicBezier(o,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":0===o?o=a/s.pathLength:a>r?o+=(a-r)/s.pathLength:o-=(r-a)/s.pathLength,o>1&&(o=1,h=!0),i=Kinetic.Path.getPointOnQuadraticBezier(o,s.start.x,s.start.y,s.points[0],s.points[1],s.points[2],s.points[3])}void 0!==i&&(r=Kinetic.Path.getLineLength(n.x,n.y,i.x,i.y)),h&&(h=!1,s=void 0)}},d=0;d<a.length&&(c(a[d]),void 0!==n&&void 0!==i);d++){var h=Kinetic.Path.getLineLength(n.x,n.y,i.x,i.y),u=0,p=Kinetic.Path.getPointOnLine(u+h/2,n.x,n.y,i.x,i.y),m=Math.atan2(i.y-n.y,i.x-n.x);this.glyphInfo.push({transposeX:p.x,transposeY:p.y,text:a[d],rotation:m,p0:n,p1:i}),n=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(t,e,n,i){"use strict";return t.View.extend({_fullyQualifiedName:"UBNT.views.map.Ruler",events:{click:"onRulerClick","click .close":"onCloseClick","click .submit":"onFormSubmit"},initialize:function(){e.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 t=i("#Map");this.layer=new n.Layer,this.stage=new n.Stage({container:"Map",width:t.width(),height:t.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 t=this.stage.getMousePosition();this.line.getPoints()[0].x=t.x,this.line.getPoints()[0].y=t.y,this.line.getPoints()[1].x=t.x,this.line.getPoints()[1].y=t.y,this.moving=!0,this.layer.drawScene()}},onStageMouseMove:function(){if(this.moving){{var t=this.stage.getMousePosition();t.x,t.y}this.line.getPoints()[1].x=t.x,this.line.getPoints()[1].y=t.y,this.moving=!0,this.layer.drawScene()}},onStageMouseUp:function(){var t=this.line.getPoints();this.measuredDistance=this.getDistance(t[0],t[1]),this.moving=!1,this.measuredDistance>0&&(this.$distance.prop("disabled",!1).removeClass("disabled").focus(),this.$submit.prop("disabled",!1).removeClass("disabled"))},onRulerClick:function(t){this.$el.hasClass("is-open")||(this.$el.addClass("is-open"),this.setupStage(),this.bindStageEvents()),t.preventDefault()},onCloseClick:function(t){return this.$el.removeClass("is-open"),this.unbindStageEvents(),this.destroyStage(),t.preventDefault(),t.stopPropagation(),!1},onFormSubmit:function(t){var e=parseFloat(this.$distance.val(),10),n=e/this.measuredDistance,i=this.$units.val();e&&(this.onCloseClick(t),this.$el.trigger("scaled",[n,i]),this.$distance.val(""))},getDistance:function(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))},remove:function(){this.unbindStageEvents(),this.rendered=!1,t.View.prototype.remove.apply(this,arguments)}})}),define("ubnt/EventDispatcher",{bind:function(t,e,n){"use strict";var i=this._callbacks||(this._callbacks={}),s=i[t]||(i[t]=[]);return s.push([e,n]),this},unbind:function(t,e){"use strict";var n;if(t){if(n=this._callbacks)if(e){var i=n[t];if(!i)return this;for(var s=0,a=i.length;a>s;s++)if(i[s]&&e===i[s][0]){i[s]=null;break}}else n[t]=[]}else this._callbacks={};return this},trigger:function(t){"use strict";var e,n,i,s,a,r=2;if(!(n=this._callbacks))return this;for(;r--;)if(i=r?t:"all",e=n[i])for(var o=0,l=e.length;l>o;o++)(s=e[o])?(a=r?Array.prototype.slice.call(arguments,1):arguments,s[0].apply(s[1]||this,a)):(e.splice(o,1),o--,l--);return this}}),define("ubnt/TimerEvent",{TIMER_COMPLETE:"timer complete",TIMER:"timer"}),define("ubnt/Timer",["underscore","ubnt/EventDispatcher","ubnt/TimerEvent"],function(t,e,n){"use strict";var i=function(e,n){t.bindAll(this),this._delay=e,this._repeatCount=n||0,this._interval=void 0,this._currentCount=0,this._isRunning=!1};return t.extend(i.prototype,e,{setRunning:function(){throw new Error("running is read-only")},setCurrentCount:function(){throw new Error("currentCount is read-only")},setDelay:function(t){this._delay=t},setRepeatCount:function(t){this._repeatCount=t||0},reset:function(){this.stop(),this._currentCount=0},start:function(){this._interval||this._repeatCount&&this._currentCount>=this._repeatCount||(this._interval=setTimeout(this.tick,this._delay))},stop:function(){this._interval&&clearTimeout(this._interval),this._interval=void 0},tick:function(){return this._currentCount+=1,this._repeatCount&&this._currentCount>=this._repeatCount?(this.reset(),void this.trigger(n.TIMER_COMPLETE,{target:this})):(this._interval=setTimeout(this.tick,this._delay),void this.trigger(n.TIMER))}}),i}),define("ubnt/view/map/MarkerView",["backbone","underscore","ubnt/Timer","ubnt/TimerEvent","jquery"],function(t,e,n,i,s){"use strict";return t.View.extend({_fullyQualifiedName:"UBNT.views.map.Marker",initialize:function(){e.bindAll(this),this.isHoldToDrag=!1,this.isMoving=!1,this.el=this.template({}),this.$el=s(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(i.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.setExpanded(!1),this.trigger("markerchange"),!0):!1},dragStopHandler:function(t,e){this.trigger("dragstop",t,e)},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(t,e){this.x=t,this.y=e,this.$el.css({left:this.x,top:this.y})},setExpanded:function(t){t?this.isExpanded||(this.$el.addClass("expand"),this.trigger("markerselect",this)):this.isExpanded&&(this.$el.removeClass("expand"),this.trigger("markerdeselect",this))},markerMouseDownHandler:function(){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(),s("body").bind("mouseup",this.markerMouseUpHandler)},isExpanded:function(){return this.$el.hasClass("expand")},markerMouseUpHandler:function(){this.isHoldToDrag&&this.holdTimer.reset(),this.disableMove(),s("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),s("body").unbind("mouseup",this.markerMouseUpHandler),t.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/map/MarkerView",["ubnt/view/map/MarkerView","underscore","jquery","msg/Msg"],function(t,e,n){"use strict";return t.extend({initialize:function(n){e.bindAll(this),this.template=this.options.template,this.map=this.options.map,t.prototype.initialize.apply(this,[n]),this.updateState(),this.updateUplink()},initHandlers:function(){t.prototype.initHandlers.apply(this,[]),this.$lockButton=this.$(".lock"),this.$configButton=this.$(".config"),this.$scanButton=this.$(".scan"),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.model.isGen2Ap()&&(this.$scanButton.on("click",this.scanClickHandler),this.$el.addClass("gen-2")),this.listenTo(this.model,"change:name",this.updateName),this.listenTo(this.model,"change:mac",this.updateMac),this.listenTo(this.model,"change:user-num_sta",this.updateUsers),this.listenTo(this.model,"change:user-num_sta",this.updateUsers),this.listenTo(this.model,"change:na-user-num_sta",this.updateUsers),this.listenTo(this.model,"change:na-guest-num_sta",this.updateGuests),this.listenTo(this.model,"change:ng-guest-num_sta",this.updateGuests),this.listenTo(this.model,"change:ng-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")||t.prototype.enableMove.apply(this,arguments)},lockClickHandler:function(){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(){var t=this;if(this.app.routers.devices.views.index.properties[this.model.get("mac")]){var n=function(){t.app.routers.devices.views.index.properties[t.model.get("mac")].setSection("config")};e.delay(n,0)}else this.app.routers.devices.views.index.property(this.model,{section:"config"})},scanClickHandler:function(){var t=this;if(this.app.routers.devices.views.index.properties[this.model.get("mac")]){var n=function(){t.app.routers.devices.views.index.properties[t.model.get("mac")].setSection("rfMap")};e.delay(n,0)}else this.app.routers.devices.views.index.property(this.model,{section:"rfMap"})},handleRemoveClick:function(){this.model.get("locked")||t.prototype.handleRemoveClick.apply(this,arguments)},render:function(){t.prototype.render.apply(this,[]);var e=this;!this.rendered&&(this.rendered=!0)&&(this.$details=this.$(".details"),n(".ruler").on("scaled",this.updateRulerScale),this.$coverageToggle2g=n("#mapFilterCoverage2G"),this.$coverageToggle2g.on("change",function(){e.is2gCoverageEnabled=e.$coverageToggle2g.is(":checked"),e.updateUsers(),e.updateGuests()}),this.$coverageToggle5g=n("#mapFilterCoverage5G"),this.$coverageToggle5g.on("change",function(){e.is2gCoverageEnabled=!e.$coverageToggle5g.is(":checked"),e.updateUsers(),e.updateGuests()}),this.is2gCoverageEnabled=this.$coverageToggle2g.is(":checked")),this.updateName(),this.updateMac(),this.updateUsers(),this.updateGuests(),this.$(".marker-icon").addClass(this.model.apIcon()),this.$el.addClass(this.model.get("type"))},updateName:function(){this.$(".title").text(this.model.name());var t="";switch(this.model.get("type")){case this.model.typeMap.ap:t="AP";break;case this.model.typeMap.gateway:t="Gateway";break;case this.model.typeMap["switch"]:t="Switch";break;case this.model.typeMap.phone:t="Phone"}this.$details.find(".ap-name").text(this.model.get("name")||"Unnamed "+t)},updateMac:function(){this.$details.find(".mac").text(this.model.get("mac"))},updateUsers:function(){if(this.model.get("type")===this.model.typeMap.phone)this.$details.find(".users").parent().hide();else{var t=this.model.get("user-num_sta"),e=this.model.get(this.is2gCoverageEnabled?"ng-user-num_sta":"na-user-num_sta");this.$details.find(".users").text(this.model.get("type")===this.model.typeMap.ap?(e||0)+" / "+(t||0):t||0)}},updateGuests:function(){if(this.model.get("type")===this.model.typeMap.phone)this.$details.find(".guests").parent().hide();else{var t=this.model.get("guest-num_sta"),e=this.model.get(this.is2gCoverageEnabled?"ng-guest-num_sta":"na-guest-num_sta");this.$details.find(".guests").text(this.model.get("type")===this.model.typeMap.ap?(e||0)+" / "+(t||0):t||0)}},updateState:function(){this.model.isConnected()?this.$el.addClass("ap-connected").removeClass("ap-disconnected"):this.$el.addClass("ap-disconnected").removeClass("ap-connected"),11===parseInt(this.model.get("state"),10)?this.$el.addClass("ap-isolated"):this.$el.removeClass("ap-isolated")},updateUplink:function(){var t=this.model.uplink();t&&"ath0"==t.name?this.$el.addClass("ap-vwireless"):this.$el.removeClass("ap-vwireless")},updateRulerScale:function(t,e,n){this.map.model.set({upp:e,unit:n}),this.map.$el.click()},save:function(t){this.app.isReadOnly?this.model.set({map_id:void 0!==t.map_id?t.map_id:this.model.get("map_id"),x:void 0!==t.x?t.x:this.model.get("x"),y:void 0!==t.y?t.y:this.model.get("y"),locked:void 0!==t.locked?t.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:void 0!==t.map_id?t.map_id:this.model.get("map_id"),x:void 0!==t.x?t.x:this.model.get("x"),y:void 0!==t.y?t.y:this.model.get("y"),locked:void 0!==t.locked?t.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.$scanButton.on("scan",this.scanClickHandler),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: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),this.rfMap&&(this.rfMap.remove(),this.rfMap=null),this.rendered=!1,t.prototype.remove.apply(this,arguments)
}})}),define("ubnt/view/map/UnplacedMarkerView",["backbone","underscore","jquery"],function(t,e,n){"use strict";return t.View.extend({initialize:function(){var t=this;e.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 t.$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(t){t.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),t.View.prototype.remove.apply(this,arguments)}})}),define("ubnt/view/map/MarkerDrawerView",["backbone","underscore","ubnt/view/map/UnplacedMarkerView","jquery"],function(t,e,n,i){"use strict";return t.View.extend({_fullyQualifiedName:"UBNT.views.map.MarkerDrawer",initialize:function(){e.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(t){return t.id&&t.get("adopted")},addMultipleMarkers:function(t){var e,n,i,s,a=this,r=t.length,o=document.createDocumentFragment();for(s=0;r>s;s++)e=t[s],n=e.get("map_id"),n||a.collections.maps.get(n)||!a.isMarkerMappable(e)||(i=new a.markerView({model:e,template:a.unplacedMarkerTemplate,draggableTemplate:a.unplacedMarkerDraggableTemplate}),i.render(),o.appendChild(i.$el[0]),a.markerViews[e.id]=i);a.$markerList.append(o),a.updateUnplacedMarkerCount()},addMarker:function(t){if((!t.get("map_id")||!this.collections.maps.get(t.get("map_id"))||this.isMarkerMappable(t))&&t.id){var e=new this.markerView({model:t,template:this.unplacedMarkerTemplate,draggableTemplate:this.unplacedMarkerDraggableTemplate});e.render(),this.$markerList.append(e.$el),this.markerViews[t.id]=e,this.updateUnplacedMarkerCount()}},updateMarker:function(t){t.changedAttributes();this.isMarkerMappable(t)&&(t.get("map_id")||this.collections.maps.get(t.get("map_id"))?this.removeMarker(t):(null===this.markerViews[t.id]||void 0===this.markerViews[t.id])&&this.addMarker(t))},resetMarkers:function(){i.each(this.markerViews,function(t,e){e.remove()}),this.markerViews={},this.addMultipleMarkers(this.collections.markers.models),this.updateUnplacedMarkerCount()},removeMarker:function(t){this.markerViews[t.id]&&(this.markerViews[t.id].remove(),delete this.markerViews[t.id],this.updateUnplacedMarkerCount())},hasUnplacedMarkers:function(){return i.isEmptyObject(this.markerViews)?!1:!0},updateUnplacedMarkerCount:function(){var t=e.size(this.markerViews);this.$unplacedMarkerCountElt.text(t),t?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,t.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/map/UnplacedMarkerView",["ubnt/view/map/UnplacedMarkerView","underscore"],function(t,e){"use strict";return t.extend({initialize:function(e){this.template=this.options.template,this.listenTo(this.model,"change:name",this.updateName),t.prototype.initialize.apply(this,[e]),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(e.escape(this.model.name()))},updateState:function(){this.$el.addClass(this.model.isConnected()?"ap-connected":"ap-disconnected"),11===parseInt(this.model.get("state"),10)?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),t.prototype.remove.apply(this,arguments)}})}),define("ubnt/view/map/MapBase",["backbone","underscore","jquery","msg/Msg"],function(t,e,n,i){"use strict";return t.View.extend({_fullyQualifiedName:"UBNT.views.map.MapBase",initialize:function(){e.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),e.each(this.layers,function(t){t.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),e.each(this.layers,function(t){t.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(t,e){e.toggleLabel()})},toggleDetails:function(){n.each(this.markers,function(t,e){e.toggleDetail()})},bringLayerItemToTop:function(t){var e=this.layerItems[t.cid];e&&(e.$el.css("zIndex",this.layerZ),this.layerZ++)},addMarker:function(t,e){var n=t.get("map_id"),s=t.id;if(this.model&&e&&n==this.model.id&&(null===this.markerViews[s]||void 0===this.markerViews[s])){var a=new this.MarkerView({model:t,map:this,template:this.markerTemplate});a.bind("markerselect",this.markerSelectHandler),a.bind("markerdeselect",this.markerDeselectHandler),this.markerViews[s]=a;var r=a.$(".detail.mac-text"),o=a.$(".detail.channel-text"),l=a.$(".detail.users-text"),c=a.$(".detail.guests-text");r.find("span").text(i.G_MapMAC),o.find("span").text(i.G_MapChannel),l.find("span").text(i.G_MapUsers),c.find("span").text(i.G_MapGuests)}},updateMarker:function(){throw"updateMarker: You must override this function."},resetMarkers:function(){e.each(this.markerViews,function(t){this.removeMarker(t.model)},this),this.markerViews={},this.collections.markers.each(function(t){this.addMarker(t)},this)},removeMarker:function(t){var e=this.markerViews[t.id];e&&(this.markerViews[t.id].remove(),delete this.markerViews[t.id],this.trigger("mapremovemarker",e))},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(t){e.each(this.markerViews,function(e){e!==t&&e.setExpanded(!1)},this)},markerDeselectHandler:function(){},remove:function(){this.unbindHandlers(),e.each(this.markerViews,function(t){t.unbind("markerselect",this.markerSelectHandler),t.unbind("markerdeselect",this.markerDeselectHandler)},this),t.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(t){return this.view=t,this},initialize:function(){this.Overlay.prototype=new google.maps.OverlayView,this.Overlay.prototype.onAdd=function(){var t=this.getPanes();t[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()}}}}),d3=function(){function t(t){return null!=t&&!isNaN(t)}function e(t){return t.length}function n(t){for(var e=1;t*e%1;)e*=10;return e}function i(t,e){try{for(var n in e)Object.defineProperty(t.prototype,n,{value:e[n],enumerable:!1})}catch(i){t.prototype=e}}function s(){}function a(){}function r(t,e,n){return function(){var i=n.apply(e,arguments);return i===e?t:i}}function o(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.substring(1);for(var n=0,i=ho.length;i>n;++n){var s=ho[n]+e;if(s in t)return s}}function l(){}function c(){}function d(t){function e(){for(var e,i=n,s=-1,a=i.length;++s<a;)(e=i[s].on)&&e.apply(this,arguments);return t}var n=[],i=new s;return e.on=function(e,s){var a,r=i.get(e);return arguments.length<2?r&&r.on:(r&&(r.on=null,n=n.slice(0,a=n.indexOf(r)).concat(n.slice(a+1)),i.remove(e)),s&&n.push(i.set(e,{on:s})),t)},e}function h(){qr.event.preventDefault()}function u(){for(var t,e=qr.event;t=e.sourceEvent;)e=t;return e}function p(t){for(var e=new c,n=0,i=arguments.length;++n<i;)e[arguments[n]]=d(e);return e.of=function(n,i){return function(s){try{var a=s.sourceEvent=qr.event;s.target=t,qr.event=s,e[s.type].apply(n,i)}finally{qr.event=a}}},e}function m(t){return po(t,bo),t}function f(t){return"function"==typeof t?t:function(){return mo(t,this)}}function g(t){return"function"==typeof t?t:function(){return fo(t,this)}}function v(t,e){function n(){this.removeAttribute(t)}function i(){this.removeAttributeNS(t.space,t.local)}function s(){this.setAttribute(t,e)}function a(){this.setAttributeNS(t.space,t.local,e)}function r(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}function o(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}return t=qr.ns.qualify(t),null==e?t.local?i:n:"function"==typeof e?t.local?o:r:t.local?a:s}function b(t){return t.trim().replace(/\s+/g," ")}function w(t){return new RegExp("(?:^|\\s+)"+qr.requote(t)+"(?:\\s+|$)","g")}function y(t,e){function n(){for(var n=-1;++n<s;)t[n](this,e)}function i(){for(var n=-1,i=e.apply(this,arguments);++n<s;)t[n](this,i)}t=t.trim().split(/\s+/).map(_);var s=t.length;return"function"==typeof e?i:n}function _(t){var e=w(t);return function(n,i){if(s=n.classList)return i?s.add(t):s.remove(t);var s=n.getAttribute("class")||"";i?(e.lastIndex=0,e.test(s)||n.setAttribute("class",b(s+" "+t))):n.setAttribute("class",b(s.replace(e," ")))}}function x(t,e,n){function i(){this.style.removeProperty(t)}function s(){this.style.setProperty(t,e,n)}function a(){var i=e.apply(this,arguments);null==i?this.style.removeProperty(t):this.style.setProperty(t,i,n)}return null==e?i:"function"==typeof e?a:s}function k(t,e){function n(){delete this[t]}function i(){this[t]=e}function s(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}return null==e?n:"function"==typeof e?s:i}function C(t){return"function"==typeof t?t:(t=qr.ns.qualify(t)).local?function(){return this.ownerDocument.createElementNS(t.space,t.local)}:function(){return this.ownerDocument.createElementNS(this.namespaceURI,t)}}function S(t){return{__data__:t}}function $(t){return function(){return vo(this,t)}}function M(t){return arguments.length||(t=qr.ascending),function(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}}function P(t,e){for(var n=0,i=t.length;i>n;n++)for(var s,a=t[n],r=0,o=a.length;o>r;r++)(s=a[r])&&e(s,r,n);return t}function D(t){return po(t,yo),t}function T(t){var e,n;return function(i,s,a){var r,o=t[a].update,l=o.length;for(a!=n&&(n=a,e=0),s>=e&&(e=s+1);!(r=o[e])&&++e<l;);return r}}function F(){var t=this.__transition__;t&&++t.active}function G(t,e,n){function i(){var e=this[r];e&&(this.removeEventListener(t,e,e.$),delete this[r])}function s(){var s=c(e,Yr(arguments));i.call(this),this.addEventListener(t,this[r]=s,s.$=n),s._=e}function a(){var e,n=new RegExp("^__on([^.]+)"+qr.requote(t)+"$");for(var i in this)if(e=i.match(n)){var s=this[i];this.removeEventListener(e[1],s,s.$),delete this[i]}}var r="__on"+t,o=t.indexOf("."),c=A;o>0&&(t=t.substring(0,o));var d=xo.get(t);return d&&(t=d,c=R),o?e?s:i:e?l:a}function A(t,e){return function(n){var i=qr.event;qr.event=n,e[0]=this.__data__;try{t.apply(this,e)}finally{qr.event=i}}}function R(t,e){var n=A(t,e);return function(t){var e=this,i=t.relatedTarget;i&&(i===e||8&i.compareDocumentPosition(e))||n.call(e,t)}}function L(){var t=".dragsuppress-"+ ++Co,e="click"+t,n=qr.select(Zr).on("touchmove"+t,h).on("dragstart"+t,h).on("selectstart"+t,h);if(ko){var i=Jr.style,s=i[ko];i[ko]="none"}return function(a){function r(){n.on(e,null)}n.on(t,null),ko&&(i[ko]=s),a&&(n.on(e,function(){h(),r()},!0),setTimeout(r,0))}}function N(t,e){e.changedTouches&&(e=e.changedTouches[0]);var n=t.ownerSVGElement||t;if(n.createSVGPoint){var i=n.createSVGPoint();if(0>So&&(Zr.scrollX||Zr.scrollY)){n=qr.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var s=n[0][0].getScreenCTM();So=!(s.f||s.e),n.remove()}return So?(i.x=e.pageX,i.y=e.pageY):(i.x=e.clientX,i.y=e.clientY),i=i.matrixTransform(t.getScreenCTM().inverse()),[i.x,i.y]}var a=t.getBoundingClientRect();return[e.clientX-a.left-t.clientLeft,e.clientY-a.top-t.clientTop]}function E(t){return t>0?1:0>t?-1:0}function I(t){return t>1?0:-1>t?$o:Math.acos(t)}function H(t){return t>1?Po:-1>t?-Po:Math.asin(t)}function U(t){return((t=Math.exp(t))-1/t)/2}function z(t){return((t=Math.exp(t))+1/t)/2}function O(t){return((t=Math.exp(2*t))-1)/(t+1)}function V(t){return(t=Math.sin(t/2))*t}function B(){}function K(t,e,n){return new W(t,e,n)}function W(t,e,n){this.h=t,this.s=e,this.l=n}function q(t,e,n){function i(t){return t>360?t-=360:0>t&&(t+=360),60>t?a+(r-a)*t/60:180>t?r:240>t?a+(r-a)*(240-t)/60:a}function s(t){return Math.round(255*i(t))}var a,r;return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:0>e?0:e>1?1:e,n=0>n?0:n>1?1:n,r=.5>=n?n*(1+e):n+e-n*e,a=2*n-r,re(s(t+120),s(t),s(t-120))}function j(t,e,n){return new Y(t,e,n)}function Y(t,e,n){this.h=t,this.c=e,this.l=n}function X(t,e,n){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),J(n,Math.cos(t*=Fo)*e,Math.sin(t)*e)}function J(t,e,n){return new Z(t,e,n)}function Z(t,e,n){this.l=t,this.a=e,this.b=n}function Q(t,e,n){var i=(t+16)/116,s=i+e/500,a=i-n/200;return s=ee(s)*Oo,i=ee(i)*Vo,a=ee(a)*Bo,re(ie(3.2404542*s-1.5371385*i-.4985314*a),ie(-.969266*s+1.8760108*i+.041556*a),ie(.0556434*s-.2040259*i+1.0572252*a))}function te(t,e,n){return t>0?j(Math.atan2(n,e)*Go,Math.sqrt(e*e+n*n),t):j(0/0,0/0,t)}function ee(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ie(t){return Math.round(255*(.00304>=t?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function se(t){return re(t>>16,t>>8&255,255&t)}function ae(t){return se(t)+""}function re(t,e,n){return new oe(t,e,n)}function oe(t,e,n){this.r=t,this.g=e,this.b=n}function le(t){return 16>t?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ce(t,e,n){var i,s,a,r=0,o=0,l=0;if(i=/([a-z]+)\((.*)\)/i.exec(t))switch(s=i[2].split(","),i[1]){case"hsl":return n(parseFloat(s[0]),parseFloat(s[1])/100,parseFloat(s[2])/100);case"rgb":return e(pe(s[0]),pe(s[1]),pe(s[2]))}return(a=qo.get(t))?e(a.r,a.g,a.b):(null!=t&&"#"===t.charAt(0)&&(4===t.length?(r=t.charAt(1),r+=r,o=t.charAt(2),o+=o,l=t.charAt(3),l+=l):7===t.length&&(r=t.substring(1,3),o=t.substring(3,5),l=t.substring(5,7)),r=parseInt(r,16),o=parseInt(o,16),l=parseInt(l,16)),e(r,o,l))}function de(t,e,n){var i,s,a=Math.min(t/=255,e/=255,n/=255),r=Math.max(t,e,n),o=r-a,l=(r+a)/2;return o?(s=.5>l?o/(r+a):o/(2-r-a),i=t==r?(e-n)/o+(n>e?6:0):e==r?(n-t)/o+2:(t-e)/o+4,i*=60):(i=0/0,s=l>0&&1>l?0:i),K(i,s,l)}function he(t,e,n){t=ue(t),e=ue(e),n=ue(n);var i=ne((.4124564*t+.3575761*e+.1804375*n)/Oo),s=ne((.2126729*t+.7151522*e+.072175*n)/Vo),a=ne((.0193339*t+.119192*e+.9503041*n)/Bo);return J(116*s-16,500*(i-s),200*(s-a))}function ue(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function pe(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}function me(t){return"function"==typeof t?t:function(){return t}}function fe(t){return t}function ge(t){return function(e,n,i){return 2===arguments.length&&"function"==typeof n&&(i=n,n=null),ve(e,n,t,i)}}function ve(t,e,n,i){function s(){var t,e=l.status;if(!e&&l.responseText||e>=200&&300>e||304===e){try{t=n.call(a,l)}catch(i){return void r.error.call(a,i)}r.load.call(a,t)}else r.error.call(a,l)}var a={},r=qr.dispatch("beforesend","progress","load","error"),o={},l=new XMLHttpRequest,c=null;return!Zr.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(t)||(l=new XDomainRequest),"onload"in l?l.onload=l.onerror=s:l.onreadystatechange=function(){l.readyState>3&&s()},l.onprogress=function(t){var e=qr.event;qr.event=t;try{r.progress.call(a,l)}finally{qr.event=e}},a.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?o[t]:(null==e?delete o[t]:o[t]=e+"",a)},a.mimeType=function(t){return arguments.length?(e=null==t?null:t+"",a):e},a.responseType=function(t){return arguments.length?(c=t,a):c},a.response=function(t){return n=t,a},["get","post"].forEach(function(t){a[t]=function(){return a.send.apply(a,[t].concat(Yr(arguments)))}}),a.send=function(n,i,s){if(2===arguments.length&&"function"==typeof i&&(s=i,i=null),l.open(n,t,!0),null==e||"accept"in o||(o.accept=e+",*/*"),l.setRequestHeader)for(var d in o)l.setRequestHeader(d,o[d]);return null!=e&&l.overrideMimeType&&l.overrideMimeType(e),null!=c&&(l.responseType=c),null!=s&&a.on("error",s).on("load",function(t){s(null,t)}),r.beforesend.call(a,l),l.send(null==i?null:i),a},a.abort=function(){return l.abort(),a},qr.rebind(a,r,"on"),null==i?a:a.get(be(i))}function be(t){return 1===t.length?function(e,n){t(null==e?n:null)}:t}function we(){var t=ye(),e=_e()-t;e>24?(isFinite(e)&&(clearTimeout(Jo),Jo=setTimeout(we,e)),Xo=0):(Xo=1,Qo(we))}function ye(){var t=Date.now();for(Zo=jo;Zo;)t>=Zo.t&&(Zo.f=Zo.c(t-Zo.t)),Zo=Zo.n;return t}function _e(){for(var t,e=jo,n=1/0;e;)e.f?e=t?t.n=e.n:jo=e.n:(e.t<n&&(n=e.t),e=(t=e).n);return Yo=t,n}function xe(t,e){var n=Math.pow(10,3*oo(8-e));return{scale:e>8?function(t){return t/n}:function(t){return t*n},symbol:t}}function ke(t,e){return e-(t?Math.ceil(Math.log(t)/Math.LN10):1)}function Ce(t){return t+""}function Se(){}function $e(t,e,n){var i=n.s=t+e,s=i-t,a=i-s;n.t=t-a+(e-s)}function Me(t,e){t&&hl.hasOwnProperty(t.type)&&hl[t.type](t,e)}function Pe(t,e,n){var i,s=-1,a=t.length-n;for(e.lineStart();++s<a;)i=t[s],e.point(i[0],i[1],i[2]);e.lineEnd()}function De(t,e){var n=-1,i=t.length;for(e.polygonStart();++n<i;)Pe(t[n],e,1);e.polygonEnd()}function Te(){function t(t,e){t*=Fo,e=e*Fo/2+$o/4;var n=t-i,r=Math.cos(e),o=Math.sin(e),l=a*o,c=s*r+l*Math.cos(n),d=l*Math.sin(n);pl.add(Math.atan2(d,c)),i=t,s=r,a=o}var e,n,i,s,a;ml.point=function(r,o){ml.point=t,i=(e=r)*Fo,s=Math.cos(o=(n=o)*Fo/2+$o/4),a=Math.sin(o)},ml.lineEnd=function(){t(e,n)}}function Fe(t){var e=t[0],n=t[1],i=Math.cos(n);return[i*Math.cos(e),i*Math.sin(e),Math.sin(n)]}function Ge(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Ae(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Re(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Le(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Ne(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Ee(t){return[Math.atan2(t[1],t[0]),H(t[2])]}function Ie(t,e){return oo(t[0]-e[0])<Do&&oo(t[1]-e[1])<Do}function He(t,e){t*=Fo;var n=Math.cos(e*=Fo);Ue(n*Math.cos(t),n*Math.sin(t),Math.sin(e))}function Ue(t,e,n){++fl,vl+=(t-vl)/fl,bl+=(e-bl)/fl,wl+=(n-wl)/fl}function ze(){function t(t,s){t*=Fo;var a=Math.cos(s*=Fo),r=a*Math.cos(t),o=a*Math.sin(t),l=Math.sin(s),c=Math.atan2(Math.sqrt((c=n*l-i*o)*c+(c=i*r-e*l)*c+(c=e*o-n*r)*c),e*r+n*o+i*l);gl+=c,yl+=c*(e+(e=r)),_l+=c*(n+(n=o)),xl+=c*(i+(i=l)),Ue(e,n,i)}var e,n,i;$l.point=function(s,a){s*=Fo;var r=Math.cos(a*=Fo);e=r*Math.cos(s),n=r*Math.sin(s),i=Math.sin(a),$l.point=t,Ue(e,n,i)}}function Oe(){$l.point=He}function Ve(){function t(t,e){t*=Fo;var n=Math.cos(e*=Fo),r=n*Math.cos(t),o=n*Math.sin(t),l=Math.sin(e),c=s*l-a*o,d=a*r-i*l,h=i*o-s*r,u=Math.sqrt(c*c+d*d+h*h),p=i*r+s*o+a*l,m=u&&-I(p)/u,f=Math.atan2(u,p);kl+=m*c,Cl+=m*d,Sl+=m*h,gl+=f,yl+=f*(i+(i=r)),_l+=f*(s+(s=o)),xl+=f*(a+(a=l)),Ue(i,s,a)}var e,n,i,s,a;$l.point=function(r,o){e=r,n=o,$l.point=t,r*=Fo;var l=Math.cos(o*=Fo);i=l*Math.cos(r),s=l*Math.sin(r),a=Math.sin(o),Ue(i,s,a)},$l.lineEnd=function(){t(e,n),$l.lineEnd=Oe,$l.point=He}}function Be(){return!0}function Ke(t,e,n,i,s){var a=[],r=[];if(t.forEach(function(t){if(!((e=t.length-1)<=0)){var e,n=t[0],i=t[e];if(Ie(n,i)){s.lineStart();for(var o=0;e>o;++o)s.point((n=t[o])[0],n[1]);return void s.lineEnd()}var l=new qe(n,t,null,!0),c=new qe(n,null,l,!1);l.o=c,a.push(l),r.push(c),l=new qe(i,t,null,!1),c=new qe(i,null,l,!0),l.o=c,a.push(l),r.push(c)}}),r.sort(e),We(a),We(r),a.length){for(var o=0,l=n,c=r.length;c>o;++o)r[o].e=l=!l;for(var d,h,u=a[0];;){for(var p=u,m=!0;p.v;)if((p=p.n)===u)return;d=p.z,s.lineStart();do{if(p.v=p.o.v=!0,p.e){if(m)for(var o=0,c=d.length;c>o;++o)s.point((h=d[o])[0],h[1]);else i(p.x,p.n.x,1,s);p=p.n}else{if(m){d=p.p.z;for(var o=d.length-1;o>=0;--o)s.point((h=d[o])[0],h[1])}else i(p.x,p.p.x,-1,s);p=p.p}p=p.o,d=p.z,m=!m}while(!p.v);s.lineEnd()}}}function We(t){if(e=t.length){for(var e,n,i=0,s=t[0];++i<e;)s.n=n=t[i],n.p=s,s=n;s.n=n=t[0],n.p=s}}function qe(t,e,n,i){this.x=t,this.z=e,this.o=n,this.e=i,this.v=!1,this.n=this.p=null}function je(t,e,n,i){return function(s,a){function r(e,n){var i=s(e,n);t(e=i[0],n=i[1])&&a.point(e,n)}function o(t,e){var n=s(t,e);g.point(n[0],n[1])}function l(){b.point=o,g.lineStart()}function c(){b.point=r,g.lineEnd()}function d(t,e){f.push([t,e]);var n=s(t,e);y.point(n[0],n[1])}function h(){y.lineStart(),f=[]}function u(){d(f[0][0],f[0][1]),y.lineEnd();var t,e=y.clean(),n=w.buffer(),i=n.length;if(f.pop(),m.push(f),f=null,i){if(1&e){t=n[0];var s,i=t.length-1,r=-1;for(a.lineStart();++r<i;)a.point((s=t[r])[0],s[1]);return void a.lineEnd()}i>1&&2&e&&n.push(n.pop().concat(n.shift())),p.push(n.filter(Ye))}}var p,m,f,g=e(a),v=s.invert(i[0],i[1]),b={point:r,lineStart:l,lineEnd:c,polygonStart:function(){b.point=d,b.lineStart=h,b.lineEnd=u,p=[],m=[],a.polygonStart()},polygonEnd:function(){b.point=r,b.lineStart=l,b.lineEnd=c,p=qr.merge(p);var t=Ze(v,m);p.length?Ke(p,Je,t,n,a):t&&(a.lineStart(),n(null,null,1,a),a.lineEnd()),a.polygonEnd(),p=m=null},sphere:function(){a.polygonStart(),a.lineStart(),n(null,null,1,a),a.lineEnd(),a.polygonEnd()}},w=Xe(),y=e(w);return b}}function Ye(t){return t.length>1}function Xe(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,n){t.push([e,n])},lineEnd:l,buffer:function(){var n=e;return e=[],t=null,n},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Je(t,e){return((t=t.x)[0]<0?t[1]-Po-Do:Po-t[1])-((e=e.x)[0]<0?e[1]-Po-Do:Po-e[1])}function Ze(t,e){var n=t[0],i=t[1],s=[Math.sin(n),-Math.cos(n),0],a=0,r=0;pl.reset();for(var o=0,l=e.length;l>o;++o){var c=e[o],d=c.length;if(d)for(var h=c[0],u=h[0],p=h[1]/2+$o/4,m=Math.sin(p),f=Math.cos(p),g=1;;){g===d&&(g=0),t=c[g];var v=t[0],b=t[1]/2+$o/4,w=Math.sin(b),y=Math.cos(b),_=v-u,x=oo(_)>$o,k=m*w;if(pl.add(Math.atan2(k*Math.sin(_),f*y+k*Math.cos(_))),a+=x?_+(_>=0?Mo:-Mo):_,x^u>=n^v>=n){var C=Ae(Fe(h),Fe(t));Ne(C);var S=Ae(s,C);Ne(S);var $=(x^_>=0?-1:1)*H(S[2]);(i>$||i===$&&(C[0]||C[1]))&&(r+=x^_>=0?1:-1)}if(!g++)break;u=v,m=w,f=y,h=t}}return(-Do>a||Do>a&&0>pl)^1&r}function Qe(t){var e,n=0/0,i=0/0,s=0/0;return{lineStart:function(){t.lineStart(),e=1},point:function(a,r){var o=a>0?$o:-$o,l=oo(a-n);oo(l-$o)<Do?(t.point(n,i=(i+r)/2>0?Po:-Po),t.point(s,i),t.lineEnd(),t.lineStart(),t.point(o,i),t.point(a,i),e=0):s!==o&&l>=$o&&(oo(n-s)<Do&&(n-=s*Do),oo(a-o)<Do&&(a-=o*Do),i=tn(n,i,a,r),t.point(s,i),t.lineEnd(),t.lineStart(),t.point(o,i),e=0),t.point(n=a,i=r),s=o},lineEnd:function(){t.lineEnd(),n=i=0/0},clean:function(){return 2-e}}}function tn(t,e,n,i){var s,a,r=Math.sin(t-n);return oo(r)>Do?Math.atan((Math.sin(e)*(a=Math.cos(i))*Math.sin(n)-Math.sin(i)*(s=Math.cos(e))*Math.sin(t))/(s*a*r)):(e+i)/2}function en(t,e,n,i){var s;if(null==t)s=n*Po,i.point(-$o,s),i.point(0,s),i.point($o,s),i.point($o,0),i.point($o,-s),i.point(0,-s),i.point(-$o,-s),i.point(-$o,0),i.point(-$o,s);else if(oo(t[0]-e[0])>Do){var a=t[0]<e[0]?$o:-$o;s=n*a/2,i.point(-a,s),i.point(0,s),i.point(a,s)}else i.point(e[0],e[1])}function nn(t){function e(t,e){return Math.cos(t)*Math.cos(e)>a}function n(t){var n,a,l,c,d;return{lineStart:function(){c=l=!1,d=1},point:function(h,u){var p,m=[h,u],f=e(h,u),g=r?f?0:s(h,u):f?s(h+(0>h?$o:-$o),u):0;if(!n&&(c=l=f)&&t.lineStart(),f!==l&&(p=i(n,m),(Ie(n,p)||Ie(m,p))&&(m[0]+=Do,m[1]+=Do,f=e(m[0],m[1]))),f!==l)d=0,f?(t.lineStart(),p=i(m,n),t.point(p[0],p[1])):(p=i(n,m),t.point(p[0],p[1]),t.lineEnd()),n=p;else if(o&&n&&r^f){var v;g&a||!(v=i(m,n,!0))||(d=0,r?(t.lineStart(),t.point(v[0][0],v[0][1]),t.point(v[1][0],v[1][1]),t.lineEnd()):(t.point(v[1][0],v[1][1]),t.lineEnd(),t.lineStart(),t.point(v[0][0],v[0][1])))}!f||n&&Ie(n,m)||t.point(m[0],m[1]),n=m,l=f,a=g},lineEnd:function(){l&&t.lineEnd(),n=null},clean:function(){return d|(c&&l)<<1}}}function i(t,e,n){var i=Fe(t),s=Fe(e),r=[1,0,0],o=Ae(i,s),l=Ge(o,o),c=o[0],d=l-c*c;if(!d)return!n&&t;var h=a*l/d,u=-a*c/d,p=Ae(r,o),m=Le(r,h),f=Le(o,u);Re(m,f);var g=p,v=Ge(m,g),b=Ge(g,g),w=v*v-b*(Ge(m,m)-1);if(!(0>w)){var y=Math.sqrt(w),_=Le(g,(-v-y)/b);if(Re(_,m),_=Ee(_),!n)return _;var x,k=t[0],C=e[0],S=t[1],$=e[1];k>C&&(x=k,k=C,C=x);var M=C-k,P=oo(M-$o)<Do,D=P||Do>M;if(!P&&S>$&&(x=S,S=$,$=x),D?P?S+$>0^_[1]<(oo(_[0]-k)<Do?S:$):S<=_[1]&&_[1]<=$:M>$o^(k<=_[0]&&_[0]<=C)){var T=Le(g,(-v+y)/b);return Re(T,m),[_,Ee(T)]}}}function s(e,n){var i=r?t:$o-t,s=0;return-i>e?s|=1:e>i&&(s|=2),-i>n?s|=4:n>i&&(s|=8),s}var a=Math.cos(t),r=a>0,o=oo(a)>Do,l=Fn(t,6*Fo);return je(e,n,l,r?[0,-t]:[-$o,t-$o])}function sn(t,e,n,i){return function(s){var a,r=s.a,o=s.b,l=r.x,c=r.y,d=o.x,h=o.y,u=0,p=1,m=d-l,f=h-c;if(a=t-l,m||!(a>0)){if(a/=m,0>m){if(u>a)return;p>a&&(p=a)}else if(m>0){if(a>p)return;a>u&&(u=a)}if(a=n-l,m||!(0>a)){if(a/=m,0>m){if(a>p)return;a>u&&(u=a)}else if(m>0){if(u>a)return;p>a&&(p=a)}if(a=e-c,f||!(a>0)){if(a/=f,0>f){if(u>a)return;p>a&&(p=a)}else if(f>0){if(a>p)return;a>u&&(u=a)}if(a=i-c,f||!(0>a)){if(a/=f,0>f){if(a>p)return;a>u&&(u=a)}else if(f>0){if(u>a)return;p>a&&(p=a)}return u>0&&(s.a={x:l+u*m,y:c+u*f}),1>p&&(s.b={x:l+p*m,y:c+p*f}),s}}}}}}function an(t,e,n,i){function s(i,s){return oo(i[0]-t)<Do?s>0?0:3:oo(i[0]-n)<Do?s>0?2:1:oo(i[1]-e)<Do?s>0?1:0:s>0?3:2}function a(t,e){return r(t.x,e.x)}function r(t,e){var n=s(t,1),i=s(e,1);return n!==i?n-i:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(o){function l(t){for(var e=0,n=v.length,i=t[1],s=0;n>s;++s)for(var a,r=1,o=v[s],l=o.length,d=o[0];l>r;++r)a=o[r],d[1]<=i?a[1]>i&&c(d,a,t)>0&&++e:a[1]<=i&&c(d,a,t)<0&&--e,d=a;return 0!==e}function c(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(n[0]-t[0])*(e[1]-t[1])}function d(a,o,l,c){var d=0,h=0;if(null==a||(d=s(a,l))!==(h=s(o,l))||r(a,o)<0^l>0){do c.point(0===d||3===d?t:n,d>1?i:e);while((d=(d+l+4)%4)!==h)}else c.point(o[0],o[1])}function h(s,a){return s>=t&&n>=s&&a>=e&&i>=a}function u(t,e){h(t,e)&&o.point(t,e)}function p(){T.point=f,v&&v.push(b=[]),S=!0,C=!1,x=k=0/0}function m(){g&&(f(w,y),_&&C&&P.rejoin(),g.push(P.buffer())),T.point=u,C&&o.lineEnd()}function f(t,e){t=Math.max(-Pl,Math.min(Pl,t)),e=Math.max(-Pl,Math.min(Pl,e));var n=h(t,e);if(v&&b.push([t,e]),S)w=t,y=e,_=n,S=!1,n&&(o.lineStart(),o.point(t,e));else if(n&&C)o.point(t,e);else{var i={a:{x:x,y:k},b:{x:t,y:e}};D(i)?(C||(o.lineStart(),o.point(i.a.x,i.a.y)),o.point(i.b.x,i.b.y),n||o.lineEnd(),$=!1):n&&(o.lineStart(),o.point(t,e),$=!1)}x=t,k=e,C=n}var g,v,b,w,y,_,x,k,C,S,$,M=o,P=Xe(),D=sn(t,e,n,i),T={point:u,lineStart:p,lineEnd:m,polygonStart:function(){o=P,g=[],v=[],$=!0},polygonEnd:function(){o=M,g=qr.merge(g);var e=l([t,i]),n=$&&e,s=g.length;(n||s)&&(o.polygonStart(),n&&(o.lineStart(),d(null,null,1,o),o.lineEnd()),s&&Ke(g,a,e,d,o),o.polygonEnd()),g=v=b=null}};return T}}function rn(t,e){function n(n,i){return n=t(n,i),e(n[0],n[1])}return t.invert&&e.invert&&(n.invert=function(n,i){return n=e.invert(n,i),n&&t.invert(n[0],n[1])}),n}function on(t){var e=0,n=$o/3,i=kn(t),s=i(e,n);return s.parallels=function(t){return arguments.length?i(e=t[0]*$o/180,n=t[1]*$o/180):[e/$o*180,n/$o*180]},s}function ln(t,e){function n(t,e){var n=Math.sqrt(a-2*s*Math.sin(e))/s;return[n*Math.sin(t*=s),r-n*Math.cos(t)]}var i=Math.sin(t),s=(i+Math.sin(e))/2,a=1+i*(2*s-i),r=Math.sqrt(a)/s;return n.invert=function(t,e){var n=r-e;return[Math.atan2(t,n)/s,H((a-(t*t+n*n)*s*s)/(2*s))]},n}function cn(){function t(t,e){Tl+=s*t-i*e,i=t,s=e}var e,n,i,s;Ll.point=function(a,r){Ll.point=t,e=i=a,n=s=r},Ll.lineEnd=function(){t(e,n)}}function dn(t,e){Fl>t&&(Fl=t),t>Al&&(Al=t),Gl>e&&(Gl=e),e>Rl&&(Rl=e)}function hn(){function t(t,e){r.push("M",t,",",e,a)}function e(t,e){r.push("M",t,",",e),o.point=n}function n(t,e){r.push("L",t,",",e)}function i(){o.point=t}function s(){r.push("Z")}var a=un(4.5),r=[],o={point:t,lineStart:function(){o.point=e},lineEnd:i,polygonStart:function(){o.lineEnd=s},polygonEnd:function(){o.lineEnd=i,o.point=t},pointRadius:function(t){return a=un(t),o},result:function(){if(r.length){var t=r.join("");return r=[],t}}};return o}function un(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function pn(t,e){vl+=t,bl+=e,++wl}function mn(){function t(t,i){var s=t-e,a=i-n,r=Math.sqrt(s*s+a*a);yl+=r*(e+t)/2,_l+=r*(n+i)/2,xl+=r,pn(e=t,n=i)}var e,n;El.point=function(i,s){El.point=t,pn(e=i,n=s)}}function fn(){El.point=pn}function gn(){function t(t,e){var n=t-i,a=e-s,r=Math.sqrt(n*n+a*a);yl+=r*(i+t)/2,_l+=r*(s+e)/2,xl+=r,r=s*t-i*e,kl+=r*(i+t),Cl+=r*(s+e),Sl+=3*r,pn(i=t,s=e)}var e,n,i,s;El.point=function(a,r){El.point=t,pn(e=i=a,n=s=r)},El.lineEnd=function(){t(e,n)}}function vn(t){function e(e,n){t.moveTo(e,n),t.arc(e,n,r,0,Mo)
}function n(e,n){t.moveTo(e,n),o.point=i}function i(e,n){t.lineTo(e,n)}function s(){o.point=e}function a(){t.closePath()}var r=4.5,o={point:e,lineStart:function(){o.point=n},lineEnd:s,polygonStart:function(){o.lineEnd=a},polygonEnd:function(){o.lineEnd=s,o.point=e},pointRadius:function(t){return r=t,o},result:l};return o}function bn(t){function e(t){return(o?i:n)(t)}function n(e){return _n(e,function(n,i){n=t(n,i),e.point(n[0],n[1])})}function i(e){function n(n,i){n=t(n,i),e.point(n[0],n[1])}function i(){w=0/0,C.point=a,e.lineStart()}function a(n,i){var a=Fe([n,i]),r=t(n,i);s(w,y,b,_,x,k,w=r[0],y=r[1],b=n,_=a[0],x=a[1],k=a[2],o,e),e.point(w,y)}function r(){C.point=n,e.lineEnd()}function l(){i(),C.point=c,C.lineEnd=d}function c(t,e){a(h=t,u=e),p=w,m=y,f=_,g=x,v=k,C.point=a}function d(){s(w,y,b,_,x,k,p,m,h,f,g,v,o,e),C.lineEnd=r,r()}var h,u,p,m,f,g,v,b,w,y,_,x,k,C={point:n,lineStart:i,lineEnd:r,polygonStart:function(){e.polygonStart(),C.lineStart=l},polygonEnd:function(){e.polygonEnd(),C.lineStart=i}};return C}function s(e,n,i,o,l,c,d,h,u,p,m,f,g,v){var b=d-e,w=h-n,y=b*b+w*w;if(y>4*a&&g--){var _=o+p,x=l+m,k=c+f,C=Math.sqrt(_*_+x*x+k*k),S=Math.asin(k/=C),$=oo(oo(k)-1)<Do||oo(i-u)<Do?(i+u)/2:Math.atan2(x,_),M=t($,S),P=M[0],D=M[1],T=P-e,F=D-n,G=w*T-b*F;(G*G/y>a||oo((b*T+w*F)/y-.5)>.3||r>o*p+l*m+c*f)&&(s(e,n,i,o,l,c,P,D,$,_/=C,x/=C,k,g,v),v.point(P,D),s(P,D,$,_,x,k,d,h,u,p,m,f,g,v))}}var a=.5,r=Math.cos(30*Fo),o=16;return e.precision=function(t){return arguments.length?(o=(a=t*t)>0&&16,e):Math.sqrt(a)},e}function wn(t){var e=bn(function(e,n){return t([e*Go,n*Go])});return function(t){return Cn(e(t))}}function yn(t){this.stream=t}function _n(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function xn(t){return kn(function(){return t})()}function kn(t){function e(t){return t=o(t[0]*Fo,t[1]*Fo),[t[0]*u+l,c-t[1]*u]}function n(t){return t=o.invert((t[0]-l)/u,(c-t[1])/u),t&&[t[0]*Go,t[1]*Go]}function i(){o=rn(r=Mn(v,b,w),a);var t=a(f,g);return l=p-t[0]*u,c=m+t[1]*u,s()}function s(){return d&&(d.valid=!1,d=null),e}var a,r,o,l,c,d,h=bn(function(t,e){return t=a(t,e),[t[0]*u+l,c-t[1]*u]}),u=150,p=480,m=250,f=0,g=0,v=0,b=0,w=0,y=Ml,_=fe,x=null,k=null;return e.stream=function(t){return d&&(d.valid=!1),d=Cn(y(r,h(_(t)))),d.valid=!0,d},e.clipAngle=function(t){return arguments.length?(y=null==t?(x=t,Ml):nn((x=+t)*Fo),s()):x},e.clipExtent=function(t){return arguments.length?(k=t,_=t?an(t[0][0],t[0][1],t[1][0],t[1][1]):fe,s()):k},e.scale=function(t){return arguments.length?(u=+t,i()):u},e.translate=function(t){return arguments.length?(p=+t[0],m=+t[1],i()):[p,m]},e.center=function(t){return arguments.length?(f=t[0]%360*Fo,g=t[1]%360*Fo,i()):[f*Go,g*Go]},e.rotate=function(t){return arguments.length?(v=t[0]%360*Fo,b=t[1]%360*Fo,w=t.length>2?t[2]%360*Fo:0,i()):[v*Go,b*Go,w*Go]},qr.rebind(e,h,"precision"),function(){return a=t.apply(this,arguments),e.invert=a.invert&&n,i()}}function Cn(t){return _n(t,function(e,n){t.point(e*Fo,n*Fo)})}function Sn(t,e){return[t,e]}function $n(t,e){return[t>$o?t-Mo:-$o>t?t+Mo:t,e]}function Mn(t,e,n){return t?e||n?rn(Dn(t),Tn(e,n)):Dn(t):e||n?Tn(e,n):$n}function Pn(t){return function(e,n){return e+=t,[e>$o?e-Mo:-$o>e?e+Mo:e,n]}}function Dn(t){var e=Pn(t);return e.invert=Pn(-t),e}function Tn(t,e){function n(t,e){var n=Math.cos(e),o=Math.cos(t)*n,l=Math.sin(t)*n,c=Math.sin(e),d=c*i+o*s;return[Math.atan2(l*a-d*r,o*i-c*s),H(d*a+l*r)]}var i=Math.cos(t),s=Math.sin(t),a=Math.cos(e),r=Math.sin(e);return n.invert=function(t,e){var n=Math.cos(e),o=Math.cos(t)*n,l=Math.sin(t)*n,c=Math.sin(e),d=c*a-l*r;return[Math.atan2(l*a+c*r,o*i+d*s),H(d*i-o*s)]},n}function Fn(t,e){var n=Math.cos(t),i=Math.sin(t);return function(s,a,r,o){var l=r*e;null!=s?(s=Gn(n,s),a=Gn(n,a),(r>0?a>s:s>a)&&(s+=r*Mo)):(s=t+r*Mo,a=t-.5*l);for(var c,d=s;r>0?d>a:a>d;d-=l)o.point((c=Ee([n,-i*Math.cos(d),-i*Math.sin(d)]))[0],c[1])}}function Gn(t,e){var n=Fe(e);n[0]-=t,Ne(n);var i=I(-n[1]);return((-n[2]<0?-i:i)+2*Math.PI-Do)%(2*Math.PI)}function An(t,e,n){var i=qr.range(t,e-Do,n).concat(e);return function(t){return i.map(function(e){return[t,e]})}}function Rn(t,e,n){var i=qr.range(t,e-Do,n).concat(e);return function(t){return i.map(function(e){return[e,t]})}}function Ln(t){return t.source}function Nn(t){return t.target}function En(t,e,n,i){var s=Math.cos(e),a=Math.sin(e),r=Math.cos(i),o=Math.sin(i),l=s*Math.cos(t),c=s*Math.sin(t),d=r*Math.cos(n),h=r*Math.sin(n),u=2*Math.asin(Math.sqrt(V(i-e)+s*r*V(n-t))),p=1/Math.sin(u),m=u?function(t){var e=Math.sin(t*=u)*p,n=Math.sin(u-t)*p,i=n*l+e*d,s=n*c+e*h,r=n*a+e*o;return[Math.atan2(s,i)*Go,Math.atan2(r,Math.sqrt(i*i+s*s))*Go]}:function(){return[t*Go,e*Go]};return m.distance=u,m}function In(){function t(t,s){var a=Math.sin(s*=Fo),r=Math.cos(s),o=oo((t*=Fo)-e),l=Math.cos(o);Il+=Math.atan2(Math.sqrt((o=r*Math.sin(o))*o+(o=i*a-n*r*l)*o),n*a+i*r*l),e=t,n=a,i=r}var e,n,i;Hl.point=function(s,a){e=s*Fo,n=Math.sin(a*=Fo),i=Math.cos(a),Hl.point=t},Hl.lineEnd=function(){Hl.point=Hl.lineEnd=l}}function Hn(t,e){function n(e,n){var i=Math.cos(e),s=Math.cos(n),a=t(i*s);return[a*s*Math.sin(e),a*Math.sin(n)]}return n.invert=function(t,n){var i=Math.sqrt(t*t+n*n),s=e(i),a=Math.sin(s),r=Math.cos(s);return[Math.atan2(t*a,i*r),Math.asin(i&&n*a/i)]},n}function Un(t,e){function n(t,e){var n=oo(oo(e)-Po)<Do?0:r/Math.pow(s(e),a);return[n*Math.sin(a*t),r-n*Math.cos(a*t)]}var i=Math.cos(t),s=function(t){return Math.tan($o/4+t/2)},a=t===e?Math.sin(t):Math.log(i/Math.cos(e))/Math.log(s(e)/s(t)),r=i*Math.pow(s(t),a)/a;return a?(n.invert=function(t,e){var n=r-e,i=E(a)*Math.sqrt(t*t+n*n);return[Math.atan2(t,n)/a,2*Math.atan(Math.pow(r/i,1/a))-Po]},n):On}function zn(t,e){function n(t,e){var n=a-e;return[n*Math.sin(s*t),a-n*Math.cos(s*t)]}var i=Math.cos(t),s=t===e?Math.sin(t):(i-Math.cos(e))/(e-t),a=i/s+t;return oo(s)<Do?Sn:(n.invert=function(t,e){var n=a-e;return[Math.atan2(t,n)/s,a-E(s)*Math.sqrt(t*t+n*n)]},n)}function On(t,e){return[t,Math.log(Math.tan($o/4+e/2))]}function Vn(t){var e,n=xn(t),i=n.scale,s=n.translate,a=n.clipExtent;return n.scale=function(){var t=i.apply(n,arguments);return t===n?e?n.clipExtent(null):n:t},n.translate=function(){var t=s.apply(n,arguments);return t===n?e?n.clipExtent(null):n:t},n.clipExtent=function(t){var r=a.apply(n,arguments);if(r===n){if(e=null==t){var o=$o*i(),l=s();a([[l[0]-o,l[1]-o],[l[0]+o,l[1]+o]])}}else e&&(r=null);return r},n.clipExtent(null)}function Bn(t,e){var n=Math.cos(e)*Math.sin(t);return[Math.log((1+n)/(1-n))/2,Math.atan2(Math.tan(e),Math.cos(t))]}function Kn(t){return t[0]}function Wn(t){return t[1]}function qn(t,e,n,i){var s,a,r,o,l,c,d;return s=i[t],a=s[0],r=s[1],s=i[e],o=s[0],l=s[1],s=i[n],c=s[0],d=s[1],(d-r)*(o-a)-(l-r)*(c-a)>0}function jn(t,e,n){return(n[0]-e[0])*(t[1]-e[1])<(n[1]-e[1])*(t[0]-e[0])}function Yn(t,e,n,i){var s=t[0],a=n[0],r=e[0]-s,o=i[0]-a,l=t[1],c=n[1],d=e[1]-l,h=i[1]-c,u=(o*(l-c)-h*(s-a))/(h*r-o*d);return[s+u*r,l+u*d]}function Xn(t){var e=t[0],n=t[t.length-1];return!(e[0]-n[0]||e[1]-n[1])}function Jn(){bi(this),this.edge=this.site=this.circle=null}function Zn(t){var e=Jl.pop()||new Jn;return e.site=t,e}function Qn(t){ci(t),jl.remove(t),Jl.push(t),bi(t)}function ti(t){var e=t.circle,n=e.x,i=e.cy,s={x:n,y:i},a=t.P,r=t.N,o=[t];Qn(t);for(var l=a;l.circle&&oo(n-l.circle.x)<Do&&oo(i-l.circle.cy)<Do;)a=l.P,o.unshift(l),Qn(l),l=a;o.unshift(l),ci(l);for(var c=r;c.circle&&oo(n-c.circle.x)<Do&&oo(i-c.circle.cy)<Do;)r=c.N,o.push(c),Qn(c),c=r;o.push(c),ci(c);var d,h=o.length;for(d=1;h>d;++d)c=o[d],l=o[d-1],fi(c.edge,l.site,c.site,s);l=o[0],c=o[h-1],c.edge=pi(l.site,c.site,null,s),li(l),li(c)}function ei(t){for(var e,n,i,s,a=t.x,r=t.y,o=jl._;o;)if(i=ni(o,r)-a,i>Do)o=o.L;else{if(s=a-ii(o,r),!(s>Do)){i>-Do?(e=o.P,n=o):s>-Do?(e=o,n=o.N):e=n=o;break}if(!o.R){e=o;break}o=o.R}var l=Zn(t);if(jl.insert(e,l),e||n){if(e===n)return ci(e),n=Zn(e.site),jl.insert(l,n),l.edge=n.edge=pi(e.site,l.site),li(e),void li(n);if(!n)return void(l.edge=pi(e.site,l.site));ci(e),ci(n);var c=e.site,d=c.x,h=c.y,u=t.x-d,p=t.y-h,m=n.site,f=m.x-d,g=m.y-h,v=2*(u*g-p*f),b=u*u+p*p,w=f*f+g*g,y={x:(g*b-p*w)/v+d,y:(u*w-f*b)/v+h};fi(n.edge,c,m,y),l.edge=pi(c,t,null,y),n.edge=pi(t,m,null,y),li(e),li(n)}}function ni(t,e){var n=t.site,i=n.x,s=n.y,a=s-e;if(!a)return i;var r=t.P;if(!r)return-1/0;n=r.site;var o=n.x,l=n.y,c=l-e;if(!c)return o;var d=o-i,h=1/a-1/c,u=d/c;return h?(-u+Math.sqrt(u*u-2*h*(d*d/(-2*c)-l+c/2+s-a/2)))/h+i:(i+o)/2}function ii(t,e){var n=t.N;if(n)return ni(n,e);var i=t.site;return i.y===e?i.x:1/0}function si(t){this.site=t,this.edges=[]}function ai(t){for(var e,n,i,s,a,r,o,l,c,d,h=t[0][0],u=t[1][0],p=t[0][1],m=t[1][1],f=ql,g=f.length;g--;)if(a=f[g],a&&a.prepare())for(o=a.edges,l=o.length,r=0;l>r;)d=o[r].end(),i=d.x,s=d.y,c=o[++r%l].start(),e=c.x,n=c.y,(oo(i-e)>Do||oo(s-n)>Do)&&(o.splice(r,0,new gi(mi(a.site,d,oo(i-h)<Do&&m-s>Do?{x:h,y:oo(e-h)<Do?n:m}:oo(s-m)<Do&&u-i>Do?{x:oo(n-m)<Do?e:u,y:m}:oo(i-u)<Do&&s-p>Do?{x:u,y:oo(e-u)<Do?n:p}:oo(s-p)<Do&&i-h>Do?{x:oo(n-p)<Do?e:h,y:p}:null),a.site,null)),++l)}function ri(t,e){return e.angle-t.angle}function oi(){bi(this),this.x=this.y=this.arc=this.site=this.cy=null}function li(t){var e=t.P,n=t.N;if(e&&n){var i=e.site,s=t.site,a=n.site;if(i!==a){var r=s.x,o=s.y,l=i.x-r,c=i.y-o,d=a.x-r,h=a.y-o,u=2*(l*h-c*d);if(!(u>=-To)){var p=l*l+c*c,m=d*d+h*h,f=(h*p-c*m)/u,g=(l*m-d*p)/u,h=g+o,v=Zl.pop()||new oi;v.arc=t,v.site=s,v.x=f+r,v.y=h+Math.sqrt(f*f+g*g),v.cy=h,t.circle=v;for(var b=null,w=Xl._;w;)if(v.y<w.y||v.y===w.y&&v.x<=w.x){if(!w.L){b=w.P;break}w=w.L}else{if(!w.R){b=w;break}w=w.R}Xl.insert(b,v),b||(Yl=v)}}}}function ci(t){var e=t.circle;e&&(e.P||(Yl=e.N),Xl.remove(e),Zl.push(e),bi(e),t.circle=null)}function di(t){for(var e,n=Wl,i=sn(t[0][0],t[0][1],t[1][0],t[1][1]),s=n.length;s--;)e=n[s],(!hi(e,t)||!i(e)||oo(e.a.x-e.b.x)<Do&&oo(e.a.y-e.b.y)<Do)&&(e.a=e.b=null,n.splice(s,1))}function hi(t,e){var n=t.b;if(n)return!0;var i,s,a=t.a,r=e[0][0],o=e[1][0],l=e[0][1],c=e[1][1],d=t.l,h=t.r,u=d.x,p=d.y,m=h.x,f=h.y,g=(u+m)/2,v=(p+f)/2;if(f===p){if(r>g||g>=o)return;if(u>m){if(a){if(a.y>=c)return}else a={x:g,y:l};n={x:g,y:c}}else{if(a){if(a.y<l)return}else a={x:g,y:c};n={x:g,y:l}}}else if(i=(u-m)/(f-p),s=v-i*g,-1>i||i>1)if(u>m){if(a){if(a.y>=c)return}else a={x:(l-s)/i,y:l};n={x:(c-s)/i,y:c}}else{if(a){if(a.y<l)return}else a={x:(c-s)/i,y:c};n={x:(l-s)/i,y:l}}else if(f>p){if(a){if(a.x>=o)return}else a={x:r,y:i*r+s};n={x:o,y:i*o+s}}else{if(a){if(a.x<r)return}else a={x:o,y:i*o+s};n={x:r,y:i*r+s}}return t.a=a,t.b=n,!0}function ui(t,e){this.l=t,this.r=e,this.a=this.b=null}function pi(t,e,n,i){var s=new ui(t,e);return Wl.push(s),n&&fi(s,t,e,n),i&&fi(s,e,t,i),ql[t.i].edges.push(new gi(s,t,e)),ql[e.i].edges.push(new gi(s,e,t)),s}function mi(t,e,n){var i=new ui(t,null);return i.a=e,i.b=n,Wl.push(i),i}function fi(t,e,n,i){t.a||t.b?t.l===n?t.b=i:t.a=i:(t.a=i,t.l=e,t.r=n)}function gi(t,e,n){var i=t.a,s=t.b;this.edge=t,this.site=e,this.angle=n?Math.atan2(n.y-e.y,n.x-e.x):t.l===e?Math.atan2(s.x-i.x,i.y-s.y):Math.atan2(i.x-s.x,s.y-i.y)}function vi(){this._=null}function bi(t){t.U=t.C=t.L=t.R=t.P=t.N=null}function wi(t,e){var n=e,i=e.R,s=n.U;s?s.L===n?s.L=i:s.R=i:t._=i,i.U=s,n.U=i,n.R=i.L,n.R&&(n.R.U=n),i.L=n}function yi(t,e){var n=e,i=e.L,s=n.U;s?s.L===n?s.L=i:s.R=i:t._=i,i.U=s,n.U=i,n.L=i.R,n.L&&(n.L.U=n),i.R=n}function _i(t){for(;t.L;)t=t.L;return t}function xi(t,e){var n,i,s,a=t.sort(ki).pop();for(Wl=[],ql=new Array(t.length),jl=new vi,Xl=new vi;;)if(s=Yl,a&&(!s||a.y<s.y||a.y===s.y&&a.x<s.x))(a.x!==n||a.y!==i)&&(ql[a.i]=new si(a),ei(a),n=a.x,i=a.y),a=t.pop();else{if(!s)break;ti(s.arc)}e&&(di(e),ai(e));var r={cells:ql,edges:Wl};return jl=Xl=Wl=ql=null,r}function ki(t,e){return e.y-t.y||e.x-t.x}function Ci(t,e,n){return(t.x-n.x)*(e.y-t.y)-(t.x-e.x)*(n.y-t.y)}function Si(t){return t.x}function $i(t){return t.y}function Mi(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function Pi(t,e,n,i,s,a){if(!t(e,n,i,s,a)){var r=.5*(n+s),o=.5*(i+a),l=e.nodes;l[0]&&Pi(t,l[0],n,i,r,o),l[1]&&Pi(t,l[1],r,i,s,o),l[2]&&Pi(t,l[2],n,o,r,a),l[3]&&Pi(t,l[3],r,o,s,a)}}function Di(t,e){t=qr.rgb(t),e=qr.rgb(e);var n=t.r,i=t.g,s=t.b,a=e.r-n,r=e.g-i,o=e.b-s;return function(t){return"#"+le(Math.round(n+a*t))+le(Math.round(i+r*t))+le(Math.round(s+o*t))}}function Ti(t,e){var n,i={},s={};for(n in t)n in e?i[n]=Ai(t[n],e[n]):s[n]=t[n];for(n in e)n in t||(s[n]=e[n]);return function(t){for(n in i)s[n]=i[n](t);return s}}function Fi(t,e){return e-=t=+t,function(n){return t+e*n}}function Gi(t,e){var n,i,s,a,r,o=0,l=0,c=[],d=[];for(t+="",e+="",tc.lastIndex=0,i=0;n=tc.exec(e);++i)n.index&&c.push(e.substring(o,l=n.index)),d.push({i:c.length,x:n[0]}),c.push(null),o=tc.lastIndex;for(o<e.length&&c.push(e.substring(o)),i=0,a=d.length;(n=tc.exec(t))&&a>i;++i)if(r=d[i],r.x==n[0]){if(r.i)if(null==c[r.i+1])for(c[r.i-1]+=r.x,c.splice(r.i,1),s=i+1;a>s;++s)d[s].i--;else for(c[r.i-1]+=r.x+c[r.i+1],c.splice(r.i,2),s=i+1;a>s;++s)d[s].i-=2;else if(null==c[r.i+1])c[r.i]=r.x;else for(c[r.i]=r.x+c[r.i+1],c.splice(r.i+1,1),s=i+1;a>s;++s)d[s].i--;d.splice(i,1),a--,i--}else r.x=Fi(parseFloat(n[0]),parseFloat(r.x));for(;a>i;)r=d.pop(),null==c[r.i+1]?c[r.i]=r.x:(c[r.i]=r.x+c[r.i+1],c.splice(r.i+1,1)),a--;return 1===c.length?null==c[0]?(r=d[0].x,function(t){return r(t)+""}):function(){return e}:function(t){for(i=0;a>i;++i)c[(r=d[i]).i]=r.x(t);return c.join("")}}function Ai(t,e){for(var n,i=qr.interpolators.length;--i>=0&&!(n=qr.interpolators[i](t,e)););return n}function Ri(t,e){var n,i=[],s=[],a=t.length,r=e.length,o=Math.min(t.length,e.length);for(n=0;o>n;++n)i.push(Ai(t[n],e[n]));for(;a>n;++n)s[n]=t[n];for(;r>n;++n)s[n]=e[n];return function(t){for(n=0;o>n;++n)s[n]=i[n](t);return s}}function Li(t){return function(e){return 0>=e?0:e>=1?1:t(e)}}function Ni(t){return function(e){return 1-t(1-e)}}function Ei(t){return function(e){return.5*(.5>e?t(2*e):2-t(2-2*e))}}function Ii(t){return t*t}function Hi(t){return t*t*t}function Ui(t){if(0>=t)return 0;if(t>=1)return 1;var e=t*t,n=e*t;return 4*(.5>t?n:3*(t-e)+n-.75)}function zi(t){return function(e){return Math.pow(e,t)}}function Oi(t){return 1-Math.cos(t*Po)}function Vi(t){return Math.pow(2,10*(t-1))}function Bi(t){return 1-Math.sqrt(1-t*t)}function Ki(t,e){var n;return arguments.length<2&&(e=.45),arguments.length?n=e/Mo*Math.asin(1/t):(t=1,n=e/4),function(i){return 1+t*Math.pow(2,-10*i)*Math.sin((i-n)*Mo/e)}}function Wi(t){return t||(t=1.70158),function(e){return e*e*((t+1)*e-t)}}function qi(t){return 1/2.75>t?7.5625*t*t:2/2.75>t?7.5625*(t-=1.5/2.75)*t+.75:2.5/2.75>t?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function ji(t,e){t=qr.hcl(t),e=qr.hcl(e);var n=t.h,i=t.c,s=t.l,a=e.h-n,r=e.c-i,o=e.l-s;return isNaN(r)&&(r=0,i=isNaN(i)?e.c:i),isNaN(a)?(a=0,n=isNaN(n)?e.h:n):a>180?a-=360:-180>a&&(a+=360),function(t){return X(n+a*t,i+r*t,s+o*t)+""}}function Yi(t,e){t=qr.hsl(t),e=qr.hsl(e);var n=t.h,i=t.s,s=t.l,a=e.h-n,r=e.s-i,o=e.l-s;return isNaN(r)&&(r=0,i=isNaN(i)?e.s:i),isNaN(a)?(a=0,n=isNaN(n)?e.h:n):a>180?a-=360:-180>a&&(a+=360),function(t){return q(n+a*t,i+r*t,s+o*t)+""}}function Xi(t,e){t=qr.lab(t),e=qr.lab(e);var n=t.l,i=t.a,s=t.b,a=e.l-n,r=e.a-i,o=e.b-s;return function(t){return Q(n+a*t,i+r*t,s+o*t)+""}}function Ji(t,e){return e-=t,function(n){return Math.round(t+e*n)}}function Zi(t){var e=[t.a,t.b],n=[t.c,t.d],i=ts(e),s=Qi(e,n),a=ts(es(n,e,-s))||0;e[0]*n[1]<n[0]*e[1]&&(e[0]*=-1,e[1]*=-1,i*=-1,s*=-1),this.rotate=(i?Math.atan2(e[1],e[0]):Math.atan2(-n[0],n[1]))*Go,this.translate=[t.e,t.f],this.scale=[i,a],this.skew=a?Math.atan2(s,a)*Go:0}function Qi(t,e){return t[0]*e[0]+t[1]*e[1]}function ts(t){var e=Math.sqrt(Qi(t,t));return e&&(t[0]/=e,t[1]/=e),e}function es(t,e,n){return t[0]+=n*e[0],t[1]+=n*e[1],t}function ns(t,e){var n,i=[],s=[],a=qr.transform(t),r=qr.transform(e),o=a.translate,l=r.translate,c=a.rotate,d=r.rotate,h=a.skew,u=r.skew,p=a.scale,m=r.scale;return o[0]!=l[0]||o[1]!=l[1]?(i.push("translate(",null,",",null,")"),s.push({i:1,x:Fi(o[0],l[0])},{i:3,x:Fi(o[1],l[1])})):i.push(l[0]||l[1]?"translate("+l+")":""),c!=d?(c-d>180?d+=360:d-c>180&&(c+=360),s.push({i:i.push(i.pop()+"rotate(",null,")")-2,x:Fi(c,d)})):d&&i.push(i.pop()+"rotate("+d+")"),h!=u?s.push({i:i.push(i.pop()+"skewX(",null,")")-2,x:Fi(h,u)}):u&&i.push(i.pop()+"skewX("+u+")"),p[0]!=m[0]||p[1]!=m[1]?(n=i.push(i.pop()+"scale(",null,",",null,")"),s.push({i:n-4,x:Fi(p[0],m[0])},{i:n-2,x:Fi(p[1],m[1])})):(1!=m[0]||1!=m[1])&&i.push(i.pop()+"scale("+m+")"),n=s.length,function(t){for(var e,a=-1;++a<n;)i[(e=s[a]).i]=e.x(t);return i.join("")}}function is(t,e){return e=e-(t=+t)?1/(e-t):0,function(n){return(n-t)*e}}function ss(t,e){return e=e-(t=+t)?1/(e-t):0,function(n){return Math.max(0,Math.min(1,(n-t)*e))}}function as(t){for(var e=t.source,n=t.target,i=os(e,n),s=[e];e!==i;)e=e.parent,s.push(e);for(var a=s.length;n!==i;)s.splice(a,0,n),n=n.parent;return s}function rs(t){for(var e=[],n=t.parent;null!=n;)e.push(t),t=n,n=n.parent;return e.push(t),e}function os(t,e){if(t===e)return t;for(var n=rs(t),i=rs(e),s=n.pop(),a=i.pop(),r=null;s===a;)r=s,s=n.pop(),a=i.pop();return r}function ls(t){t.fixed|=2}function cs(t){t.fixed&=-7}function ds(t){t.fixed|=4,t.px=t.x,t.py=t.y}function hs(t){t.fixed&=-5}function us(t,e,n){var i=0,s=0;if(t.charge=0,!t.leaf)for(var a,r=t.nodes,o=r.length,l=-1;++l<o;)a=r[l],null!=a&&(us(a,e,n),t.charge+=a.charge,i+=a.charge*a.cx,s+=a.charge*a.cy);if(t.point){t.leaf||(t.point.x+=Math.random()-.5,t.point.y+=Math.random()-.5);var c=e*n[t.point.index];t.charge+=t.pointCharge=c,i+=c*t.point.x,s+=c*t.point.y}t.cx=i/t.charge,t.cy=s/t.charge}function ps(t,e){return qr.rebind(t,e,"sort","children","value"),t.nodes=t,t.links=vs,t}function ms(t){return t.children}function fs(t){return t.value}function gs(t,e){return e.value-t.value}function vs(t){return qr.merge(t.map(function(t){return(t.children||[]).map(function(e){return{source:t,target:e}})}))}function bs(t){return t.x}function ws(t){return t.y}function ys(t,e,n){t.y0=e,t.y=n}function _s(t){return qr.range(t.length)}function xs(t){for(var e=-1,n=t[0].length,i=[];++e<n;)i[e]=0;return i}function ks(t){for(var e,n=1,i=0,s=t[0][1],a=t.length;a>n;++n)(e=t[n][1])>s&&(i=n,s=e);return i}function Cs(t){return t.reduce(Ss,0)}function Ss(t,e){return t+e[1]}function $s(t,e){return Ms(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Ms(t,e){for(var n=-1,i=+t[0],s=(t[1]-i)/e,a=[];++n<=e;)a[n]=s*n+i;return a}function Ps(t){return[qr.min(t),qr.max(t)]}function Ds(t,e){return t.parent==e.parent?1:2}function Ts(t){var e=t.children;return e&&e.length?e[0]:t._tree.thread}function Fs(t){var e,n=t.children;return n&&(e=n.length)?n[e-1]:t._tree.thread}function Gs(t,e){var n=t.children;if(n&&(s=n.length))for(var i,s,a=-1;++a<s;)e(i=Gs(n[a],e),t)>0&&(t=i);return t}function As(t,e){return t.x-e.x}function Rs(t,e){return e.x-t.x}function Ls(t,e){return t.depth-e.depth}function Ns(t,e){function n(t,i){var s=t.children;if(s&&(r=s.length))for(var a,r,o=null,l=-1;++l<r;)a=s[l],n(a,o),o=a;e(t,i)}n(t,null)}function Es(t){for(var e,n=0,i=0,s=t.children,a=s.length;--a>=0;)e=s[a]._tree,e.prelim+=n,e.mod+=n,n+=e.shift+(i+=e.change)}function Is(t,e,n){t=t._tree,e=e._tree;var i=n/(e.number-t.number);t.change+=i,e.change-=i,e.shift+=n,e.prelim+=n,e.mod+=n}function Hs(t,e,n){return t._tree.ancestor.parent==e.parent?t._tree.ancestor:n}function Us(t,e){return t.value-e.value}function zs(t,e){var n=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=n,n._pack_prev=e}function Os(t,e){t._pack_next=e,e._pack_prev=t}function Vs(t,e){var n=e.x-t.x,i=e.y-t.y,s=t.r+e.r;return.999*s*s>n*n+i*i}function Bs(t){function e(t){d=Math.min(t.x-t.r,d),h=Math.max(t.x+t.r,h),u=Math.min(t.y-t.r,u),p=Math.max(t.y+t.r,p)}if((n=t.children)&&(c=n.length)){var n,i,s,a,r,o,l,c,d=1/0,h=-1/0,u=1/0,p=-1/0;if(n.forEach(Ks),i=n[0],i.x=-i.r,i.y=0,e(i),c>1&&(s=n[1],s.x=s.r,s.y=0,e(s),c>2))for(a=n[2],js(i,s,a),e(a),zs(i,a),i._pack_prev=a,zs(a,s),s=i._pack_next,r=3;c>r;r++){js(i,s,a=n[r]);var m=0,f=1,g=1;for(o=s._pack_next;o!==s;o=o._pack_next,f++)if(Vs(o,a)){m=1;break}if(1==m)for(l=i._pack_prev;l!==o._pack_prev&&!Vs(l,a);l=l._pack_prev,g++);m?(g>f||f==g&&s.r<i.r?Os(i,s=o):Os(i=l,s),r--):(zs(i,a),s=a,e(a))}var v=(d+h)/2,b=(u+p)/2,w=0;for(r=0;c>r;r++)a=n[r],a.x-=v,a.y-=b,w=Math.max(w,a.r+Math.sqrt(a.x*a.x+a.y*a.y));t.r=w,n.forEach(Ws)}}function Ks(t){t._pack_next=t._pack_prev=t}function Ws(t){delete t._pack_next,delete t._pack_prev}function qs(t,e,n,i){var s=t.children;if(t.x=e+=i*t.x,t.y=n+=i*t.y,t.r*=i,s)for(var a=-1,r=s.length;++a<r;)qs(s[a],e,n,i)}function js(t,e,n){var i=t.r+n.r,s=e.x-t.x,a=e.y-t.y;if(i&&(s||a)){var r=e.r+n.r,o=s*s+a*a;r*=r,i*=i;var l=.5+(i-r)/(2*o),c=Math.sqrt(Math.max(0,2*r*(i+o)-(i-=o)*i-r*r))/(2*o);n.x=t.x+l*s+c*a,n.y=t.y+l*a-c*s}else n.x=t.x+i,n.y=t.y}function Ys(t){return 1+qr.max(t,function(t){return t.y})}function Xs(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}function Js(t){var e=t.children;return e&&e.length?Js(e[0]):t}function Zs(t){var e,n=t.children;return n&&(e=n.length)?Zs(n[e-1]):t}function Qs(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function ta(t,e){var n=t.x+e[3],i=t.y+e[0],s=t.dx-e[1]-e[3],a=t.dy-e[0]-e[2];return 0>s&&(n+=s/2,s=0),0>a&&(i+=a/2,a=0),{x:n,y:i,dx:s,dy:a}}function ea(t){var e=t[0],n=t[t.length-1];return n>e?[e,n]:[n,e]}function na(t){return t.rangeExtent?t.rangeExtent():ea(t.range())}function ia(t,e,n,i){var s=n(t[0],t[1]),a=i(e[0],e[1]);return function(t){return a(s(t))}}function sa(t,e){var n,i=0,s=t.length-1,a=t[i],r=t[s];return a>r&&(n=i,i=s,s=n,n=a,a=r,r=n),t[i]=e.floor(a),t[s]=e.ceil(r),t}function aa(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:dc}function ra(t,e,n,i){var s=[],a=[],r=0,o=Math.min(t.length,e.length)-1;for(t[o]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++r<=o;)s.push(n(t[r-1],t[r])),a.push(i(e[r-1],e[r]));return function(e){var n=qr.bisect(t,e,1,o)-1;return a[n](s[n](e))}}function oa(t,e,n,i){function s(){var s=Math.min(t.length,e.length)>2?ra:ia,l=i?ss:is;return r=s(t,e,l,n),o=s(e,t,l,Ai),a}function a(t){return r(t)}var r,o;return a.invert=function(t){return o(t)},a.domain=function(e){return arguments.length?(t=e.map(Number),s()):t},a.range=function(t){return arguments.length?(e=t,s()):e},a.rangeRound=function(t){return a.range(t).interpolate(Ji)},a.clamp=function(t){return arguments.length?(i=t,s()):i},a.interpolate=function(t){return arguments.length?(n=t,s()):n},a.ticks=function(e){return ha(t,e)},a.tickFormat=function(e,n){return ua(t,e,n)},a.nice=function(e){return ca(t,e),s()},a.copy=function(){return oa(t,e,n,i)},s()}function la(t,e){return qr.rebind(t,e,"range","rangeRound","interpolate","clamp")}function ca(t,e){return sa(t,aa(da(t,e)[2]))}function da(t,e){null==e&&(e=10);var n=ea(t),i=n[1]-n[0],s=Math.pow(10,Math.floor(Math.log(i/e)/Math.LN10)),a=e/i*s;return.15>=a?s*=10:.35>=a?s*=5:.75>=a&&(s*=2),n[0]=Math.ceil(n[0]/s)*s,n[1]=Math.floor(n[1]/s)*s+.5*s,n[2]=s,n}function ha(t,e){return qr.range.apply(qr,da(t,e))}function ua(t,e,n){var i=da(t,e);return qr.format(n?n.replace(al,function(t,e,n,s,a,r,o,l,c,d){return[e,n,s,a,r,o,l,c||"."+ma(d,i),d].join("")}):",."+pa(i[2])+"f")}function pa(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}function ma(t,e){var n=pa(e[2]);return t in hc?Math.abs(n-pa(Math.max(Math.abs(e[0]),Math.abs(e[1]))))+ +("e"!==t):n-2*("%"===t)}function fa(t,e,n,i){function s(t){return(n?Math.log(0>t?0:t):-Math.log(t>0?0:-t))/Math.log(e)}function a(t){return n?Math.pow(e,t):-Math.pow(e,-t)}function r(e){return t(s(e))}return r.invert=function(e){return a(t.invert(e))},r.domain=function(e){return arguments.length?(n=e[0]>=0,t.domain((i=e.map(Number)).map(s)),r):i},r.base=function(n){return arguments.length?(e=+n,t.domain(i.map(s)),r):e},r.nice=function(){var e=sa(i.map(s),n?Math:pc);return t.domain(e),i=e.map(a),r},r.ticks=function(){var t=ea(i),r=[],o=t[0],l=t[1],c=Math.floor(s(o)),d=Math.ceil(s(l)),h=e%1?2:e;if(isFinite(d-c)){if(n){for(;d>c;c++)for(var u=1;h>u;u++)r.push(a(c)*u);r.push(a(c))}else for(r.push(a(c));c++<d;)for(var u=h-1;u>0;u--)r.push(a(c)*u);for(c=0;r[c]<o;c++);for(d=r.length;r[d-1]>l;d--);r=r.slice(c,d)}return r},r.tickFormat=function(t,e){if(!arguments.length)return uc;arguments.length<2?e=uc:"function"!=typeof e&&(e=qr.format(e));var i,o=Math.max(.1,t/r.ticks().length),l=n?(i=1e-12,Math.ceil):(i=-1e-12,Math.floor);return function(t){return t/a(l(s(t)+i))<=o?e(t):""}},r.copy=function(){return fa(t.copy(),e,n,i)},la(r,t)}function ga(t,e,n){function i(e){return t(s(e))}var s=va(e),a=va(1/e);return i.invert=function(e){return a(t.invert(e))},i.domain=function(e){return arguments.length?(t.domain((n=e.map(Number)).map(s)),i):n},i.ticks=function(t){return ha(n,t)},i.tickFormat=function(t,e){return ua(n,t,e)},i.nice=function(t){return i.domain(ca(n,t))},i.exponent=function(r){return arguments.length?(s=va(e=r),a=va(1/e),t.domain(n.map(s)),i):e},i.copy=function(){return ga(t.copy(),e,n)},la(i,t)}function va(t){return function(e){return 0>e?-Math.pow(-e,t):Math.pow(e,t)}}function ba(t,e){function n(n){return r[((a.get(n)||"range"===e.t&&a.set(n,t.push(n)))-1)%r.length]}function i(e,n){return qr.range(t.length).map(function(t){return e+n*t})}var a,r,o;return n.domain=function(i){if(!arguments.length)return t;t=[],a=new s;for(var r,o=-1,l=i.length;++o<l;)a.has(r=i[o])||a.set(r,t.push(r));return n[e.t].apply(n,e.a)},n.range=function(t){return arguments.length?(r=t,o=0,e={t:"range",a:arguments},n):r},n.rangePoints=function(s,a){arguments.length<2&&(a=0);var l=s[0],c=s[1],d=(c-l)/(Math.max(1,t.length-1)+a);return r=i(t.length<2?(l+c)/2:l+d*a/2,d),o=0,e={t:"rangePoints",a:arguments},n},n.rangeBands=function(s,a,l){arguments.length<2&&(a=0),arguments.length<3&&(l=a);var c=s[1]<s[0],d=s[c-0],h=s[1-c],u=(h-d)/(t.length-a+2*l);return r=i(d+u*l,u),c&&r.reverse(),o=u*(1-a),e={t:"rangeBands",a:arguments},n},n.rangeRoundBands=function(s,a,l){arguments.length<2&&(a=0),arguments.length<3&&(l=a);var c=s[1]<s[0],d=s[c-0],h=s[1-c],u=Math.floor((h-d)/(t.length-a+2*l)),p=h-d-(t.length-a)*u;return r=i(d+Math.round(p/2),u),c&&r.reverse(),o=Math.round(u*(1-a)),e={t:"rangeRoundBands",a:arguments},n},n.rangeBand=function(){return o},n.rangeExtent=function(){return ea(e.a[0])},n.copy=function(){return ba(t,e)},n.domain(t)}function wa(t,e){function n(){var n=0,a=e.length;for(s=[];++n<a;)s[n-1]=qr.quantile(t,n/a);return i}function i(t){return isNaN(t=+t)?void 0:e[qr.bisect(s,t)]}var s;return i.domain=function(e){return arguments.length?(t=e.filter(function(t){return!isNaN(t)}).sort(qr.ascending),n()):t},i.range=function(t){return arguments.length?(e=t,n()):e},i.quantiles=function(){return s},i.invertExtent=function(n){return n=e.indexOf(n),0>n?[0/0,0/0]:[n>0?s[n-1]:t[0],n<s.length?s[n]:t[t.length-1]]},i.copy=function(){return wa(t,e)},n()}function ya(t,e,n){function i(e){return n[Math.max(0,Math.min(r,Math.floor(a*(e-t))))]}function s(){return a=n.length/(e-t),r=n.length-1,i}var a,r;return i.domain=function(n){return arguments.length?(t=+n[0],e=+n[n.length-1],s()):[t,e]},i.range=function(t){return arguments.length?(n=t,s()):n},i.invertExtent=function(e){return e=n.indexOf(e),e=0>e?0/0:e/a+t,[e,e+1/a]},i.copy=function(){return ya(t,e,n)},s()}function _a(t,e){function n(n){return n>=n?e[qr.bisect(t,n)]:void 0}return n.domain=function(e){return arguments.length?(t=e,n):t},n.range=function(t){return arguments.length?(e=t,n):e},n.invertExtent=function(n){return n=e.indexOf(n),[t[n-1],t[n]]},n.copy=function(){return _a(t,e)},n}function xa(t){function e(t){return+t}return e.invert=e,e.domain=e.range=function(n){return arguments.length?(t=n.map(e),e):t},e.ticks=function(e){return ha(t,e)},e.tickFormat=function(e,n){return ua(t,e,n)},e.copy=function(){return xa(t)},e}function ka(t){return t.innerRadius}function Ca(t){return t.outerRadius}function Sa(t){return t.startAngle}function $a(t){return t.endAngle}function Ma(t){function e(e){function r(){c.push("M",a(t(d),o))}for(var l,c=[],d=[],h=-1,u=e.length,p=me(n),m=me(i);++h<u;)s.call(this,l=e[h],h)?d.push([+p.call(this,l,h),+m.call(this,l,h)]):d.length&&(r(),d=[]);return d.length&&r(),c.length?c.join(""):null}var n=Kn,i=Wn,s=Be,a=Pa,r=a.key,o=.7;return e.x=function(t){return arguments.length?(n=t,e):n},e.y=function(t){return arguments.length?(i=t,e):i},e.defined=function(t){return arguments.length?(s=t,e):s},e.interpolate=function(t){return arguments.length?(r="function"==typeof t?a=t:(a=yc.get(t)||Pa).key,e):r},e.tension=function(t){return arguments.length?(o=t,e):o},e}function Pa(t){return t.join("L")}function Da(t){return Pa(t)+"Z"}function Ta(t){for(var e=0,n=t.length,i=t[0],s=[i[0],",",i[1]];++e<n;)s.push("H",(i[0]+(i=t[e])[0])/2,"V",i[1]);return n>1&&s.push("H",i[0]),s.join("")}function Fa(t){for(var e=0,n=t.length,i=t[0],s=[i[0],",",i[1]];++e<n;)s.push("V",(i=t[e])[1],"H",i[0]);return s.join("")}function Ga(t){for(var e=0,n=t.length,i=t[0],s=[i[0],",",i[1]];++e<n;)s.push("H",(i=t[e])[0],"V",i[1]);return s.join("")}function Aa(t,e){return t.length<4?Pa(t):t[1]+Na(t.slice(1,t.length-1),Ea(t,e))}function Ra(t,e){return t.length<3?Pa(t):t[0]+Na((t.push(t[0]),t),Ea([t[t.length-2]].concat(t,[t[1]]),e))}function La(t,e){return t.length<3?Pa(t):t[0]+Na(t,Ea(t,e))}function Na(t,e){if(e.length<1||t.length!=e.length&&t.length!=e.length+2)return Pa(t);var n=t.length!=e.length,i="",s=t[0],a=t[1],r=e[0],o=r,l=1;if(n&&(i+="Q"+(a[0]-2*r[0]/3)+","+(a[1]-2*r[1]/3)+","+a[0]+","+a[1],s=t[1],l=2),e.length>1){o=e[1],a=t[l],l++,i+="C"+(s[0]+r[0])+","+(s[1]+r[1])+","+(a[0]-o[0])+","+(a[1]-o[1])+","+a[0]+","+a[1];for(var c=2;c<e.length;c++,l++)a=t[l],o=e[c],i+="S"+(a[0]-o[0])+","+(a[1]-o[1])+","+a[0]+","+a[1]}if(n){var d=t[l];i+="Q"+(a[0]+2*o[0]/3)+","+(a[1]+2*o[1]/3)+","+d[0]+","+d[1]}return i}function Ea(t,e){for(var n,i=[],s=(1-e)/2,a=t[0],r=t[1],o=1,l=t.length;++o<l;)n=a,a=r,r=t[o],i.push([s*(r[0]-n[0]),s*(r[1]-n[1])]);return i}function Ia(t){if(t.length<3)return Pa(t);var e=1,n=t.length,i=t[0],s=i[0],a=i[1],r=[s,s,s,(i=t[1])[0]],o=[a,a,a,i[1]],l=[s,",",a,"L",Oa(kc,r),",",Oa(kc,o)];for(t.push(t[n-1]);++e<=n;)i=t[e],r.shift(),r.push(i[0]),o.shift(),o.push(i[1]),Va(l,r,o);return t.pop(),l.push("L",i),l.join("")}function Ha(t){if(t.length<4)return Pa(t);for(var e,n=[],i=-1,s=t.length,a=[0],r=[0];++i<3;)e=t[i],a.push(e[0]),r.push(e[1]);for(n.push(Oa(kc,a)+","+Oa(kc,r)),--i;++i<s;)e=t[i],a.shift(),a.push(e[0]),r.shift(),r.push(e[1]),Va(n,a,r);return n.join("")}function Ua(t){for(var e,n,i=-1,s=t.length,a=s+4,r=[],o=[];++i<4;)n=t[i%s],r.push(n[0]),o.push(n[1]);for(e=[Oa(kc,r),",",Oa(kc,o)],--i;++i<a;)n=t[i%s],r.shift(),r.push(n[0]),o.shift(),o.push(n[1]),Va(e,r,o);return e.join("")}function za(t,e){var n=t.length-1;if(n)for(var i,s,a=t[0][0],r=t[0][1],o=t[n][0]-a,l=t[n][1]-r,c=-1;++c<=n;)i=t[c],s=c/n,i[0]=e*i[0]+(1-e)*(a+s*o),i[1]=e*i[1]+(1-e)*(r+s*l);return Ia(t)}function Oa(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Va(t,e,n){t.push("C",Oa(_c,e),",",Oa(_c,n),",",Oa(xc,e),",",Oa(xc,n),",",Oa(kc,e),",",Oa(kc,n))}function Ba(t,e){return(e[1]-t[1])/(e[0]-t[0])}function Ka(t){for(var e=0,n=t.length-1,i=[],s=t[0],a=t[1],r=i[0]=Ba(s,a);++e<n;)i[e]=(r+(r=Ba(s=a,a=t[e+1])))/2;return i[e]=r,i}function Wa(t){for(var e,n,i,s,a=[],r=Ka(t),o=-1,l=t.length-1;++o<l;)e=Ba(t[o],t[o+1]),oo(e)<Do?r[o]=r[o+1]=0:(n=r[o]/e,i=r[o+1]/e,s=n*n+i*i,s>9&&(s=3*e/Math.sqrt(s),r[o]=s*n,r[o+1]=s*i));for(o=-1;++o<=l;)s=(t[Math.min(l,o+1)][0]-t[Math.max(0,o-1)][0])/(6*(1+r[o]*r[o])),a.push([s||0,r[o]*s||0]);return a}function qa(t){return t.length<3?Pa(t):t[0]+Na(t,Wa(t))}function ja(t){for(var e,n,i,s=-1,a=t.length;++s<a;)e=t[s],n=e[0],i=e[1]+bc,e[0]=n*Math.cos(i),e[1]=n*Math.sin(i);return t}function Ya(t){function e(e){function l(){f.push("M",o(t(v),h),d,c(t(g.reverse()),h),"Z")}for(var u,p,m,f=[],g=[],v=[],b=-1,w=e.length,y=me(n),_=me(s),x=n===i?function(){return p}:me(i),k=s===a?function(){return m}:me(a);++b<w;)r.call(this,u=e[b],b)?(g.push([p=+y.call(this,u,b),m=+_.call(this,u,b)]),v.push([+x.call(this,u,b),+k.call(this,u,b)])):g.length&&(l(),g=[],v=[]);
return g.length&&l(),f.length?f.join(""):null}var n=Kn,i=Kn,s=0,a=Wn,r=Be,o=Pa,l=o.key,c=o,d="L",h=.7;return e.x=function(t){return arguments.length?(n=i=t,e):i},e.x0=function(t){return arguments.length?(n=t,e):n},e.x1=function(t){return arguments.length?(i=t,e):i},e.y=function(t){return arguments.length?(s=a=t,e):a},e.y0=function(t){return arguments.length?(s=t,e):s},e.y1=function(t){return arguments.length?(a=t,e):a},e.defined=function(t){return arguments.length?(r=t,e):r},e.interpolate=function(t){return arguments.length?(l="function"==typeof t?o=t:(o=yc.get(t)||Pa).key,c=o.reverse||o,d=o.closed?"M":"L",e):l},e.tension=function(t){return arguments.length?(h=t,e):h},e}function Xa(t){return t.radius}function Ja(t){return[t.x,t.y]}function Za(t){return function(){var e=t.apply(this,arguments),n=e[0],i=e[1]+bc;return[n*Math.cos(i),n*Math.sin(i)]}}function Qa(){return 64}function tr(){return"circle"}function er(t){var e=Math.sqrt(t/$o);return"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+-e+"A"+e+","+e+" 0 1,1 0,"+e+"Z"}function nr(t,e){return po(t,Dc),t.id=e,t}function ir(t,e,n,i){var s=t.id;return P(t,"function"==typeof n?function(t,a,r){t.__transition__[s].tween.set(e,i(n.call(t,t.__data__,a,r)))}:(n=i(n),function(t){t.__transition__[s].tween.set(e,n)}))}function sr(t){return null==t&&(t=""),function(){this.textContent=t}}function ar(t,e,n,i){var a=t.__transition__||(t.__transition__={active:0,count:0}),r=a[n];if(!r){var o=i.time;r=a[n]={tween:new s,time:o,ease:i.ease,delay:i.delay,duration:i.duration},++a.count,qr.timer(function(i){function s(i){return a.active>n?c():(a.active=n,r.event&&r.event.start.call(t,d,e),r.tween.forEach(function(n,i){(i=i.call(t,d,e))&&f.push(i)}),void qr.timer(function(){return m.c=l(i||1)?Be:l,1},0,o))}function l(i){if(a.active!==n)return c();for(var s=i/p,o=h(s),l=f.length;l>0;)f[--l].call(t,o);return s>=1?(r.event&&r.event.end.call(t,d,e),c()):void 0}function c(){return--a.count?delete a[n]:delete t.__transition__,1}var d=t.__data__,h=r.ease,u=r.delay,p=r.duration,m=Zo,f=[];return m.t=u+o,i>=u?s(i-u):void(m.c=s)},0,o)}}function rr(t,e){t.attr("transform",function(t){return"translate("+e(t)+",0)"})}function or(t,e){t.attr("transform",function(t){return"translate(0,"+e(t)+")"})}function lr(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function cr(t,e,n){function i(e){var n=t(e),i=a(n,1);return i-e>e-n?n:i}function s(n){return e(n=t(new Nc(n-1)),1),n}function a(t,n){return e(t=new Nc(+t),n),t}function r(t,i,a){var r=s(t),o=[];if(a>1)for(;i>r;)n(r)%a||o.push(new Date(+r)),e(r,1);else for(;i>r;)o.push(new Date(+r)),e(r,1);return o}function o(t,e,n){try{Nc=lr;var i=new lr;return i._=t,r(i,e,n)}finally{Nc=Date}}t.floor=t,t.round=i,t.ceil=s,t.offset=a,t.range=r;var l=t.utc=dr(t);return l.floor=l,l.round=dr(i),l.ceil=dr(s),l.offset=dr(a),l.range=o,t}function dr(t){return function(e,n){try{Nc=lr;var i=new lr;return i._=e,t(i,n)._}finally{Nc=Date}}}function hr(t){function e(e){for(var i,s,a,r=[],o=-1,l=0;++o<n;)37===t.charCodeAt(o)&&(r.push(t.substring(l,o)),null!=(s=ed[i=t.charAt(++o)])&&(i=t.charAt(++o)),(a=nd[i])&&(i=a(e,null==s?"e"===i?" ":"0":s)),r.push(i),l=o+1);return r.push(t.substring(l,o)),r.join("")}var n=t.length;return e.parse=function(e){var n={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},i=ur(n,t,e,0);if(i!=e.length)return null;"p"in n&&(n.H=n.H%12+12*n.p);var s=null!=n.Z&&Nc!==lr,a=new(s?lr:Nc);return"j"in n?a.setFullYear(n.y,0,n.j):"w"in n&&("W"in n||"U"in n)?(a.setFullYear(n.y,0,1),a.setFullYear(n.y,0,"W"in n?(n.w+6)%7+7*n.W-(a.getDay()+5)%7:n.w+7*n.U-(a.getDay()+6)%7)):a.setFullYear(n.y,n.m,n.d),a.setHours(n.H+Math.floor(n.Z/100),n.M+n.Z%100,n.S,n.L),s?a._:a},e.toString=function(){return t},e}function ur(t,e,n,i){for(var s,a,r,o=0,l=e.length,c=n.length;l>o;){if(i>=c)return-1;if(s=e.charCodeAt(o++),37===s){if(r=e.charAt(o++),a=id[r in ed?e.charAt(o++):r],!a||(i=a(t,n,i))<0)return-1}else if(s!=n.charCodeAt(i++))return-1}return i}function pr(t){return new RegExp("^(?:"+t.map(qr.requote).join("|")+")","i")}function mr(t){for(var e=new s,n=-1,i=t.length;++n<i;)e.set(t[n].toLowerCase(),n);return e}function fr(t,e,n){var i=0>t?"-":"",s=(i?-t:t)+"",a=s.length;return i+(n>a?new Array(n-a+1).join(e)+s:s)}function gr(t,e,n){jc.lastIndex=0;var i=jc.exec(e.substring(n));return i?(t.w=Yc.get(i[0].toLowerCase()),n+i[0].length):-1}function vr(t,e,n){Wc.lastIndex=0;var i=Wc.exec(e.substring(n));return i?(t.w=qc.get(i[0].toLowerCase()),n+i[0].length):-1}function br(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n,n+1));return i?(t.w=+i[0],n+i[0].length):-1}function wr(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n));return i?(t.U=+i[0],n+i[0].length):-1}function yr(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n));return i?(t.W=+i[0],n+i[0].length):-1}function _r(t,e,n){Zc.lastIndex=0;var i=Zc.exec(e.substring(n));return i?(t.m=Qc.get(i[0].toLowerCase()),n+i[0].length):-1}function xr(t,e,n){Xc.lastIndex=0;var i=Xc.exec(e.substring(n));return i?(t.m=Jc.get(i[0].toLowerCase()),n+i[0].length):-1}function kr(t,e,n){return ur(t,nd.c.toString(),e,n)}function Cr(t,e,n){return ur(t,nd.x.toString(),e,n)}function Sr(t,e,n){return ur(t,nd.X.toString(),e,n)}function $r(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n,n+4));return i?(t.y=+i[0],n+i[0].length):-1}function Mr(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n,n+2));return i?(t.y=Dr(+i[0]),n+i[0].length):-1}function Pr(t,e,n){return/^[+-]\d{4}$/.test(e=e.substring(n,n+5))?(t.Z=+e,n+5):-1}function Dr(t){return t+(t>68?1900:2e3)}function Tr(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n,n+2));return i?(t.m=i[0]-1,n+i[0].length):-1}function Fr(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n,n+2));return i?(t.d=+i[0],n+i[0].length):-1}function Gr(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n,n+3));return i?(t.j=+i[0],n+i[0].length):-1}function Ar(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n,n+2));return i?(t.H=+i[0],n+i[0].length):-1}function Rr(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n,n+2));return i?(t.M=+i[0],n+i[0].length):-1}function Lr(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n,n+2));return i?(t.S=+i[0],n+i[0].length):-1}function Nr(t,e,n){sd.lastIndex=0;var i=sd.exec(e.substring(n,n+3));return i?(t.L=+i[0],n+i[0].length):-1}function Er(t,e,n){var i=ad.get(e.substring(n,n+=2).toLowerCase());return null==i?-1:(t.p=i,n)}function Ir(t){var e=t.getTimezoneOffset(),n=e>0?"-":"+",i=~~(oo(e)/60),s=oo(e)%60;return n+fr(i,"0",2)+fr(s,"0",2)}function Hr(t,e,n){td.lastIndex=0;var i=td.exec(e.substring(n,n+1));return i?n+i[0].length:-1}function Ur(t){function e(t){try{Nc=lr;var e=new Nc;return e._=t,n(e)}finally{Nc=Date}}var n=hr(t);return e.parse=function(t){try{Nc=lr;var e=n.parse(t);return e&&e._}finally{Nc=Date}},e.toString=n.toString,e}function zr(t){return t.toISOString()}function Or(t,e,n){function i(e){return t(e)}function s(t,n){var i=t[1]-t[0],s=i/n,a=qr.bisect(od,s);return a==od.length?[e.year,da(t.map(function(t){return t/31536e6}),n)[2]]:a?e[s/od[a-1]<od[a]/s?a-1:a]:[hd,da(t,n)[2]]}return i.invert=function(e){return Vr(t.invert(e))},i.domain=function(e){return arguments.length?(t.domain(e),i):t.domain().map(Vr)},i.nice=function(t,e){function n(n){return!isNaN(n)&&!t.range(n,Vr(+n+1),e).length}var a=i.domain(),r=ea(a),o=null==t?s(r,10):"number"==typeof t&&s(r,t);return o&&(t=o[0],e=o[1]),i.domain(sa(a,e>1?{floor:function(e){for(;n(e=t.floor(e));)e=Vr(e-1);return e},ceil:function(e){for(;n(e=t.ceil(e));)e=Vr(+e+1);return e}}:t))},i.ticks=function(t,e){var n=ea(i.domain()),a=null==t?s(n,10):"number"==typeof t?s(n,t):!t.range&&[{range:t},e];return a&&(t=a[0],e=a[1]),t.range(n[0],Vr(+n[1]+1),1>e?1:e)},i.tickFormat=function(){return n},i.copy=function(){return Or(t.copy(),e,n)},la(i,t)}function Vr(t){return new Date(t)}function Br(t){return function(e){for(var n=t.length-1,i=t[n];!i[1](e);)i=t[--n];return i[0](e)}}function Kr(t){return JSON.parse(t.responseText)}function Wr(t){var e=Xr.createRange();return e.selectNode(Xr.body),e.createContextualFragment(t.responseText)}var qr={version:"3.3.10"};Date.now||(Date.now=function(){return+new Date});var jr=[].slice,Yr=function(t){return jr.call(t)},Xr=document,Jr=Xr.documentElement,Zr=window;try{Yr(Jr.childNodes)[0].nodeType}catch(Qr){Yr=function(t){for(var e=t.length,n=new Array(e);e--;)n[e]=t[e];return n}}try{Xr.createElement("div").style.setProperty("opacity",0,"")}catch(to){var eo=Zr.Element.prototype,no=eo.setAttribute,io=eo.setAttributeNS,so=Zr.CSSStyleDeclaration.prototype,ao=so.setProperty;eo.setAttribute=function(t,e){no.call(this,t,e+"")},eo.setAttributeNS=function(t,e,n){io.call(this,t,e,n+"")},so.setProperty=function(t,e,n){ao.call(this,t,e+"",n)}}qr.ascending=function(t,e){return e>t?-1:t>e?1:t>=e?0:0/0},qr.descending=function(t,e){return t>e?-1:e>t?1:e>=t?0:0/0},qr.min=function(t,e){var n,i,s=-1,a=t.length;if(1===arguments.length){for(;++s<a&&!(null!=(n=t[s])&&n>=n);)n=void 0;for(;++s<a;)null!=(i=t[s])&&n>i&&(n=i)}else{for(;++s<a&&!(null!=(n=e.call(t,t[s],s))&&n>=n);)n=void 0;for(;++s<a;)null!=(i=e.call(t,t[s],s))&&n>i&&(n=i)}return n},qr.max=function(t,e){var n,i,s=-1,a=t.length;if(1===arguments.length){for(;++s<a&&!(null!=(n=t[s])&&n>=n);)n=void 0;for(;++s<a;)null!=(i=t[s])&&i>n&&(n=i)}else{for(;++s<a&&!(null!=(n=e.call(t,t[s],s))&&n>=n);)n=void 0;for(;++s<a;)null!=(i=e.call(t,t[s],s))&&i>n&&(n=i)}return n},qr.extent=function(t,e){var n,i,s,a=-1,r=t.length;if(1===arguments.length){for(;++a<r&&!(null!=(n=s=t[a])&&n>=n);)n=s=void 0;for(;++a<r;)null!=(i=t[a])&&(n>i&&(n=i),i>s&&(s=i))}else{for(;++a<r&&!(null!=(n=s=e.call(t,t[a],a))&&n>=n);)n=void 0;for(;++a<r;)null!=(i=e.call(t,t[a],a))&&(n>i&&(n=i),i>s&&(s=i))}return[n,s]},qr.sum=function(t,e){var n,i=0,s=t.length,a=-1;if(1===arguments.length)for(;++a<s;)isNaN(n=+t[a])||(i+=n);else for(;++a<s;)isNaN(n=+e.call(t,t[a],a))||(i+=n);return i},qr.mean=function(e,n){var i,s=e.length,a=0,r=-1,o=0;if(1===arguments.length)for(;++r<s;)t(i=e[r])&&(a+=(i-a)/++o);else for(;++r<s;)t(i=n.call(e,e[r],r))&&(a+=(i-a)/++o);return o?a:void 0},qr.quantile=function(t,e){var n=(t.length-1)*e+1,i=Math.floor(n),s=+t[i-1],a=n-i;return a?s+a*(t[i]-s):s},qr.median=function(e,n){return arguments.length>1&&(e=e.map(n)),e=e.filter(t),e.length?qr.quantile(e.sort(qr.ascending),.5):void 0},qr.bisector=function(t){return{left:function(e,n,i,s){for(arguments.length<3&&(i=0),arguments.length<4&&(s=e.length);s>i;){var a=i+s>>>1;t.call(e,e[a],a)<n?i=a+1:s=a}return i},right:function(e,n,i,s){for(arguments.length<3&&(i=0),arguments.length<4&&(s=e.length);s>i;){var a=i+s>>>1;n<t.call(e,e[a],a)?s=a:i=a+1}return i}}};var ro=qr.bisector(function(t){return t});qr.bisectLeft=ro.left,qr.bisect=qr.bisectRight=ro.right,qr.shuffle=function(t){for(var e,n,i=t.length;i;)n=Math.random()*i--|0,e=t[i],t[i]=t[n],t[n]=e;return t},qr.permute=function(t,e){for(var n=e.length,i=new Array(n);n--;)i[n]=t[e[n]];return i},qr.pairs=function(t){for(var e,n=0,i=t.length-1,s=t[0],a=new Array(0>i?0:i);i>n;)a[n]=[e=s,s=t[++n]];return a},qr.zip=function(){if(!(s=arguments.length))return[];for(var t=-1,n=qr.min(arguments,e),i=new Array(n);++t<n;)for(var s,a=-1,r=i[t]=new Array(s);++a<s;)r[a]=arguments[a][t];return i},qr.transpose=function(t){return qr.zip.apply(qr,t)},qr.keys=function(t){var e=[];for(var n in t)e.push(n);return e},qr.values=function(t){var e=[];for(var n in t)e.push(t[n]);return e},qr.entries=function(t){var e=[];for(var n in t)e.push({key:n,value:t[n]});return e},qr.merge=function(t){for(var e,n,i,s=t.length,a=-1,r=0;++a<s;)r+=t[a].length;for(n=new Array(r);--s>=0;)for(i=t[s],e=i.length;--e>=0;)n[--r]=i[e];return n};var oo=Math.abs;qr.range=function(t,e,i){if(arguments.length<3&&(i=1,arguments.length<2&&(e=t,t=0)),(e-t)/i===1/0)throw new Error("infinite range");var s,a=[],r=n(oo(i)),o=-1;if(t*=r,e*=r,i*=r,0>i)for(;(s=t+i*++o)>e;)a.push(s/r);else for(;(s=t+i*++o)<e;)a.push(s/r);return a},qr.map=function(t){var e=new s;if(t instanceof s)t.forEach(function(t,n){e.set(t,n)});else for(var n in t)e.set(n,t[n]);return e},i(s,{has:function(t){return lo+t in this},get:function(t){return this[lo+t]},set:function(t,e){return this[lo+t]=e},remove:function(t){return t=lo+t,t in this&&delete this[t]},keys:function(){var t=[];return this.forEach(function(e){t.push(e)}),t},values:function(){var t=[];return this.forEach(function(e,n){t.push(n)}),t},entries:function(){var t=[];return this.forEach(function(e,n){t.push({key:e,value:n})}),t},forEach:function(t){for(var e in this)e.charCodeAt(0)===co&&t.call(this,e.substring(1),this[e])}});var lo="\x00",co=lo.charCodeAt(0);qr.nest=function(){function t(e,o,l){if(l>=r.length)return i?i.call(a,o):n?o.sort(n):o;for(var c,d,h,u,p=-1,m=o.length,f=r[l++],g=new s;++p<m;)(u=g.get(c=f(d=o[p])))?u.push(d):g.set(c,[d]);return e?(d=e(),h=function(n,i){d.set(n,t(e,i,l))}):(d={},h=function(n,i){d[n]=t(e,i,l)}),g.forEach(h),d}function e(t,n){if(n>=r.length)return t;var i=[],s=o[n++];return t.forEach(function(t,s){i.push({key:t,values:e(s,n)})}),s?i.sort(function(t,e){return s(t.key,e.key)}):i}var n,i,a={},r=[],o=[];return a.map=function(e,n){return t(n,e,0)},a.entries=function(n){return e(t(qr.map,n,0),0)},a.key=function(t){return r.push(t),a},a.sortKeys=function(t){return o[r.length-1]=t,a},a.sortValues=function(t){return n=t,a},a.rollup=function(t){return i=t,a},a},qr.set=function(t){var e=new a;if(t)for(var n=0,i=t.length;i>n;++n)e.add(t[n]);return e},i(a,{has:function(t){return lo+t in this},add:function(t){return this[lo+t]=!0,t},remove:function(t){return t=lo+t,t in this&&delete this[t]},values:function(){var t=[];return this.forEach(function(e){t.push(e)}),t},forEach:function(t){for(var e in this)e.charCodeAt(0)===co&&t.call(this,e.substring(1))}}),qr.behavior={},qr.rebind=function(t,e){for(var n,i=1,s=arguments.length;++i<s;)t[n=arguments[i]]=r(t,e,e[n]);return t};var ho=["webkit","ms","moz","Moz","o","O"];qr.dispatch=function(){for(var t=new c,e=-1,n=arguments.length;++e<n;)t[arguments[e]]=d(t);return t},c.prototype.on=function(t,e){var n=t.indexOf("."),i="";if(n>=0&&(i=t.substring(n+1),t=t.substring(0,n)),t)return arguments.length<2?this[t].on(i):this[t].on(i,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(i,null);return this}},qr.event=null,qr.requote=function(t){return t.replace(uo,"\\$&")};var uo=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,po={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var n in e)t[n]=e[n]},mo=function(t,e){return e.querySelector(t)},fo=function(t,e){return e.querySelectorAll(t)},go=Jr[o(Jr,"matchesSelector")],vo=function(t,e){return go.call(t,e)};"function"==typeof Sizzle&&(mo=function(t,e){return Sizzle(t,e)[0]||null},fo=function(t,e){return Sizzle.uniqueSort(Sizzle(t,e))},vo=Sizzle.matchesSelector),qr.selection=function(){return _o};var bo=qr.selection.prototype=[];bo.select=function(t){var e,n,i,s,a=[];t=f(t);for(var r=-1,o=this.length;++r<o;){a.push(e=[]),e.parentNode=(i=this[r]).parentNode;for(var l=-1,c=i.length;++l<c;)(s=i[l])?(e.push(n=t.call(s,s.__data__,l,r)),n&&"__data__"in s&&(n.__data__=s.__data__)):e.push(null)}return m(a)},bo.selectAll=function(t){var e,n,i=[];t=g(t);for(var s=-1,a=this.length;++s<a;)for(var r=this[s],o=-1,l=r.length;++o<l;)(n=r[o])&&(i.push(e=Yr(t.call(n,n.__data__,o,s))),e.parentNode=n);return m(i)};var wo={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/"};qr.ns={prefix:wo,qualify:function(t){var e=t.indexOf(":"),n=t;return e>=0&&(n=t.substring(0,e),t=t.substring(e+1)),wo.hasOwnProperty(n)?{space:wo[n],local:t}:t}},bo.attr=function(t,e){if(arguments.length<2){if("string"==typeof t){var n=this.node();return t=qr.ns.qualify(t),t.local?n.getAttributeNS(t.space,t.local):n.getAttribute(t)}for(e in t)this.each(v(e,t[e]));return this}return this.each(v(t,e))},bo.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var n=this.node(),i=(t=t.trim().split(/^|\s+/g)).length,s=-1;if(e=n.classList){for(;++s<i;)if(!e.contains(t[s]))return!1}else for(e=n.getAttribute("class");++s<i;)if(!w(t[s]).test(e))return!1;return!0}for(e in t)this.each(y(e,t[e]));return this}return this.each(y(t,e))},bo.style=function(t,e,n){var i=arguments.length;if(3>i){if("string"!=typeof t){2>i&&(e="");for(n in t)this.each(x(n,t[n],e));return this}if(2>i)return Zr.getComputedStyle(this.node(),null).getPropertyValue(t);n=""}return this.each(x(t,e,n))},bo.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(k(e,t[e]));return this}return this.each(k(t,e))},bo.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent},bo.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML},bo.append=function(t){return t=C(t),this.select(function(){return this.appendChild(t.apply(this,arguments))})},bo.insert=function(t,e){return t=C(t),e=f(e),this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})},bo.remove=function(){return this.each(function(){var t=this.parentNode;t&&t.removeChild(this)})},bo.data=function(t,e){function n(t,n){var i,a,r,o=t.length,h=n.length,u=Math.min(o,h),p=new Array(h),m=new Array(h),f=new Array(o);if(e){var g,v=new s,b=new s,w=[];for(i=-1;++i<o;)g=e.call(a=t[i],a.__data__,i),v.has(g)?f[i]=a:v.set(g,a),w.push(g);for(i=-1;++i<h;)g=e.call(n,r=n[i],i),(a=v.get(g))?(p[i]=a,a.__data__=r):b.has(g)||(m[i]=S(r)),b.set(g,r),v.remove(g);for(i=-1;++i<o;)v.has(w[i])&&(f[i]=t[i])}else{for(i=-1;++i<u;)a=t[i],r=n[i],a?(a.__data__=r,p[i]=a):m[i]=S(r);for(;h>i;++i)m[i]=S(n[i]);for(;o>i;++i)f[i]=t[i]}m.update=p,m.parentNode=p.parentNode=f.parentNode=t.parentNode,l.push(m),c.push(p),d.push(f)}var i,a,r=-1,o=this.length;if(!arguments.length){for(t=new Array(o=(i=this[0]).length);++r<o;)(a=i[r])&&(t[r]=a.__data__);return t}var l=D([]),c=m([]),d=m([]);if("function"==typeof t)for(;++r<o;)n(i=this[r],t.call(i,i.parentNode.__data__,r));else for(;++r<o;)n(i=this[r],t);return c.enter=function(){return l},c.exit=function(){return d},c},bo.datum=function(t){return arguments.length?this.property("__data__",t):this.property("__data__")},bo.filter=function(t){var e,n,i,s=[];"function"!=typeof t&&(t=$(t));for(var a=0,r=this.length;r>a;a++){s.push(e=[]),e.parentNode=(n=this[a]).parentNode;for(var o=0,l=n.length;l>o;o++)(i=n[o])&&t.call(i,i.__data__,o,a)&&e.push(i)}return m(s)},bo.order=function(){for(var t=-1,e=this.length;++t<e;)for(var n,i=this[t],s=i.length-1,a=i[s];--s>=0;)(n=i[s])&&(a&&a!==n.nextSibling&&a.parentNode.insertBefore(n,a),a=n);return this},bo.sort=function(t){t=M.apply(this,arguments);for(var e=-1,n=this.length;++e<n;)this[e].sort(t);return this.order()},bo.each=function(t){return P(this,function(e,n,i){t.call(e,e.__data__,n,i)})},bo.call=function(t){var e=Yr(arguments);return t.apply(e[0]=this,e),this},bo.empty=function(){return!this.node()},bo.node=function(){for(var t=0,e=this.length;e>t;t++)for(var n=this[t],i=0,s=n.length;s>i;i++){var a=n[i];if(a)return a}return null},bo.size=function(){var t=0;return this.each(function(){++t}),t};var yo=[];qr.selection.enter=D,qr.selection.enter.prototype=yo,yo.append=bo.append,yo.empty=bo.empty,yo.node=bo.node,yo.call=bo.call,yo.size=bo.size,yo.select=function(t){for(var e,n,i,s,a,r=[],o=-1,l=this.length;++o<l;){i=(s=this[o]).update,r.push(e=[]),e.parentNode=s.parentNode;for(var c=-1,d=s.length;++c<d;)(a=s[c])?(e.push(i[c]=n=t.call(s.parentNode,a.__data__,c,o)),n.__data__=a.__data__):e.push(null)}return m(r)},yo.insert=function(t,e){return arguments.length<2&&(e=T(this)),bo.insert.call(this,t,e)},bo.transition=function(){for(var t,e,n=Sc||++Tc,i=[],s=$c||{time:Date.now(),ease:Ui,delay:0,duration:250},a=-1,r=this.length;++a<r;){i.push(t=[]);for(var o=this[a],l=-1,c=o.length;++l<c;)(e=o[l])&&ar(e,l,n,s),t.push(e)}return nr(i,n)},bo.interrupt=function(){return this.each(F)},qr.select=function(t){var e=["string"==typeof t?mo(t,Xr):t];return e.parentNode=Jr,m([e])},qr.selectAll=function(t){var e=Yr("string"==typeof t?fo(t,Xr):t);return e.parentNode=Jr,m([e])};var _o=qr.select(Jr);bo.on=function(t,e,n){var i=arguments.length;if(3>i){if("string"!=typeof t){2>i&&(e=!1);for(n in t)this.each(G(n,t[n],e));return this}if(2>i)return(i=this.node()["__on"+t])&&i._;n=!1}return this.each(G(t,e,n))};var xo=qr.map({mouseenter:"mouseover",mouseleave:"mouseout"});xo.forEach(function(t){"on"+t in Xr&&xo.remove(t)});var ko="onselectstart"in Xr?null:o(Jr.style,"userSelect"),Co=0;qr.mouse=function(t){return N(t,u())};var So=/WebKit/.test(Zr.navigator.userAgent)?-1:0;qr.touches=function(t,e){return arguments.length<2&&(e=u().touches),e?Yr(e).map(function(e){var n=N(t,e);return n.identifier=e.identifier,n}):[]},qr.behavior.drag=function(){function t(){this.on("mousedown.drag",r).on("touchstart.drag",o)}function e(){return qr.event.changedTouches[0].identifier}function n(t,e){return qr.touches(t).filter(function(t){return t.identifier===e})[0]}function i(t,e,n,i){return function(){function r(){var t=e(d,p),n=t[0]-f[0],i=t[1]-f[1];g|=n|i,f=t,h({type:"drag",x:t[0]+l[0],y:t[1]+l[1],dx:n,dy:i})}function o(){v.on(n+"."+m,null).on(i+"."+m,null),b(g&&qr.event.target===u),h({type:"dragend"})}var l,c=this,d=c.parentNode,h=s.of(c,arguments),u=qr.event.target,p=t(),m=null==p?"drag":"drag-"+p,f=e(d,p),g=0,v=qr.select(Zr).on(n+"."+m,r).on(i+"."+m,o),b=L();a?(l=a.apply(c,arguments),l=[l.x-f[0],l.y-f[1]]):l=[0,0],h({type:"dragstart"})}}var s=p(t,"drag","dragstart","dragend"),a=null,r=i(l,qr.mouse,"mousemove","mouseup"),o=i(e,n,"touchmove","touchend");return t.origin=function(e){return arguments.length?(a=e,t):a},qr.rebind(t,s,"on")};var $o=Math.PI,Mo=2*$o,Po=$o/2,Do=1e-6,To=Do*Do,Fo=$o/180,Go=180/$o,Ao=Math.SQRT2,Ro=2,Lo=4;qr.interpolateZoom=function(t,e){function n(t){var e=t*b;if(v){var n=z(f),r=a/(Ro*u)*(n*O(Ao*e+f)-U(f));return[i+r*c,s+r*d,a*n/z(Ao*e+f)]}return[i+t*c,s+t*d,a*Math.exp(Ao*e)]}var i=t[0],s=t[1],a=t[2],r=e[0],o=e[1],l=e[2],c=r-i,d=o-s,h=c*c+d*d,u=Math.sqrt(h),p=(l*l-a*a+Lo*h)/(2*a*Ro*u),m=(l*l-a*a-Lo*h)/(2*l*Ro*u),f=Math.log(Math.sqrt(p*p+1)-p),g=Math.log(Math.sqrt(m*m+1)-m),v=g-f,b=(v||Math.log(l/a))/Ao;return n.duration=1e3*b,n},qr.behavior.zoom=function(){function t(t){t.on(M,c).on(Io+".zoom",u).on(P,m).on("dblclick.zoom",f).on(T,d)}function e(t){return[(t[0]-C.x)/C.k,(t[1]-C.y)/C.k]}function n(t){return[t[0]*C.k+C.x,t[1]*C.k+C.y]}function i(t){C.k=Math.max($[0],Math.min($[1],t))}function s(t,e){e=n(e),C.x+=t[0]-e[0],C.y+=t[1]-e[1]}function a(){_&&_.domain(y.range().map(function(t){return(t-C.x)/C.k}).map(y.invert)),k&&k.domain(x.range().map(function(t){return(t-C.y)/C.k}).map(x.invert))}function r(t){t({type:"zoomstart"})}function o(t){a(),t({type:"zoom",scale:C.k,translate:[C.x,C.y]})}function l(t){t({type:"zoomend"})}function c(){function t(){d=1,s(qr.mouse(i),u),o(a)}function n(){h.on(P,Zr===i?m:null).on(D,null),p(d&&qr.event.target===c),l(a)}var i=this,a=G.of(i,arguments),c=qr.event.target,d=0,h=qr.select(Zr).on(P,t).on(D,n),u=e(qr.mouse(i)),p=L();F.call(i),r(a)}function d(){function t(){var t=qr.touches(m);return p=C.k,t.forEach(function(t){t.identifier in g&&(g[t.identifier]=e(t))}),t}function n(){for(var e=qr.event.changedTouches,n=0,a=e.length;a>n;++n)g[e[n].identifier]=null;var r=t(),l=Date.now();if(1===r.length){if(500>l-w){var c=r[0],d=g[c.identifier];i(2*C.k),s(c,d),h(),o(f)}w=l}else if(r.length>1){var c=r[0],u=r[1],p=c[0]-u[0],m=c[1]-u[1];v=p*p+m*m}}function a(){for(var t,e,n,a,r=qr.touches(m),l=0,c=r.length;c>l;++l,a=null)if(n=r[l],a=g[n.identifier]){if(e)break;t=n,e=a}if(a){var d=(d=n[0]-t[0])*d+(d=n[1]-t[1])*d,h=v&&Math.sqrt(d/v);t=[(t[0]+n[0])/2,(t[1]+n[1])/2],e=[(e[0]+a[0])/2,(e[1]+a[1])/2],i(h*p)}w=null,s(t,e),o(f)}function u(){if(qr.event.touches.length){for(var e=qr.event.changedTouches,n=0,i=e.length;i>n;++n)delete g[e[n].identifier];for(var s in g)return void t()}x.on(y,null).on(_,null),k.on(M,c).on(T,d),S(),l(f)}var p,m=this,f=G.of(m,arguments),g={},v=0,b=qr.event.changedTouches[0].identifier,y="touchmove.zoom-"+b,_="touchend.zoom-"+b,x=qr.select(Zr).on(y,a).on(_,u),k=qr.select(m).on(M,null).on(T,n),S=L();F.call(m),n(),r(f)}function u(){var t=G.of(this,arguments);b?clearTimeout(b):(F.call(this),r(t)),b=setTimeout(function(){b=null,l(t)},50),h();var n=v||qr.mouse(this);g||(g=e(n)),i(Math.pow(2,.002*No())*C.k),s(n,g),o(t)}function m(){g=null}function f(){var t=G.of(this,arguments),n=qr.mouse(this),a=e(n),c=Math.log(C.k)/Math.LN2;r(t),i(Math.pow(2,qr.event.shiftKey?Math.ceil(c)-1:Math.floor(c)+1)),s(n,a),o(t),l(t)}var g,v,b,w,y,_,x,k,C={x:0,y:0,k:1},S=[960,500],$=Eo,M="mousedown.zoom",P="mousemove.zoom",D="mouseup.zoom",T="touchstart.zoom",G=p(t,"zoomstart","zoom","zoomend");return t.event=function(t){t.each(function(){var t=G.of(this,arguments),e=C;Sc?qr.select(this).transition().each("start.zoom",function(){C=this.__chart__||{x:0,y:0,k:1},r(t)}).tween("zoom:zoom",function(){var n=S[0],i=S[1],s=n/2,a=i/2,r=qr.interpolateZoom([(s-C.x)/C.k,(a-C.y)/C.k,n/C.k],[(s-e.x)/e.k,(a-e.y)/e.k,n/e.k]);return function(e){var i=r(e),l=n/i[2];this.__chart__=C={x:s-i[0]*l,y:a-i[1]*l,k:l},o(t)}}).each("end.zoom",function(){l(t)}):(this.__chart__=C,r(t),o(t),l(t))})},t.translate=function(e){return arguments.length?(C={x:+e[0],y:+e[1],k:C.k},a(),t):[C.x,C.y]},t.scale=function(e){return arguments.length?(C={x:C.x,y:C.y,k:+e},a(),t):C.k},t.scaleExtent=function(e){return arguments.length?($=null==e?Eo:[+e[0],+e[1]],t):$},t.center=function(e){return arguments.length?(v=e&&[+e[0],+e[1]],t):v},t.size=function(e){return arguments.length?(S=e&&[+e[0],+e[1]],t):S},t.x=function(e){return arguments.length?(_=e,y=e.copy(),C={x:0,y:0,k:1},t):_},t.y=function(e){return arguments.length?(k=e,x=e.copy(),C={x:0,y:0,k:1},t):k},qr.rebind(t,G,"on")};var No,Eo=[0,1/0],Io="onwheel"in Xr?(No=function(){return-qr.event.deltaY*(qr.event.deltaMode?120:1)},"wheel"):"onmousewheel"in Xr?(No=function(){return qr.event.wheelDelta},"mousewheel"):(No=function(){return-qr.event.detail},"MozMousePixelScroll");B.prototype.toString=function(){return this.rgb()+""},qr.hsl=function(t,e,n){return 1===arguments.length?t instanceof W?K(t.h,t.s,t.l):ce(""+t,de,K):K(+t,+e,+n)};var Ho=W.prototype=new B;Ho.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),K(this.h,this.s,this.l/t)},Ho.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),K(this.h,this.s,t*this.l)},Ho.rgb=function(){return q(this.h,this.s,this.l)},qr.hcl=function(t,e,n){return 1===arguments.length?t instanceof Y?j(t.h,t.c,t.l):t instanceof Z?te(t.l,t.a,t.b):te((t=he((t=qr.rgb(t)).r,t.g,t.b)).l,t.a,t.b):j(+t,+e,+n)};var Uo=Y.prototype=new B;Uo.brighter=function(t){return j(this.h,this.c,Math.min(100,this.l+zo*(arguments.length?t:1)))},Uo.darker=function(t){return j(this.h,this.c,Math.max(0,this.l-zo*(arguments.length?t:1)))},Uo.rgb=function(){return X(this.h,this.c,this.l).rgb()},qr.lab=function(t,e,n){return 1===arguments.length?t instanceof Z?J(t.l,t.a,t.b):t instanceof Y?X(t.l,t.c,t.h):he((t=qr.rgb(t)).r,t.g,t.b):J(+t,+e,+n)};var zo=18,Oo=.95047,Vo=1,Bo=1.08883,Ko=Z.prototype=new B;Ko.brighter=function(t){return J(Math.min(100,this.l+zo*(arguments.length?t:1)),this.a,this.b)},Ko.darker=function(t){return J(Math.max(0,this.l-zo*(arguments.length?t:1)),this.a,this.b)},Ko.rgb=function(){return Q(this.l,this.a,this.b)},qr.rgb=function(t,e,n){return 1===arguments.length?t instanceof oe?re(t.r,t.g,t.b):ce(""+t,re,q):re(~~t,~~e,~~n)};var Wo=oe.prototype=new B;Wo.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,n=this.g,i=this.b,s=30;return e||n||i?(e&&s>e&&(e=s),n&&s>n&&(n=s),i&&s>i&&(i=s),re(Math.min(255,~~(e/t)),Math.min(255,~~(n/t)),Math.min(255,~~(i/t)))):re(s,s,s)},Wo.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),re(~~(t*this.r),~~(t*this.g),~~(t*this.b))},Wo.hsl=function(){return de(this.r,this.g,this.b)},Wo.toString=function(){return"#"+le(this.r)+le(this.g)+le(this.b)};var qo=qr.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});qo.forEach(function(t,e){qo.set(t,se(e))}),qr.functor=me,qr.xhr=ge(fe),qr.dsv=function(t,e){function n(t,n,a){arguments.length<3&&(a=n,n=null);var r=qr.xhr(t,e,a);return r.row=function(t){return arguments.length?r.response(null==(n=t)?i:s(t)):n},r.row(n)}function i(t){return n.parse(t.responseText)}function s(t){return function(e){return n.parse(e.responseText,t)}}function r(e){return e.map(o).join(t)}function o(t){return l.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}var l=new RegExp('["'+t+"\n]"),c=t.charCodeAt(0);return n.parse=function(t,e){var i;return n.parseRows(t,function(t,n){if(i)return i(t,n-1);var s=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");i=e?function(t,n){return e(s(t),n)}:s})},n.parseRows=function(t,e){function n(){if(d>=l)return r;if(s)return s=!1,a;var e=d;if(34===t.charCodeAt(e)){for(var n=e;n++<l;)if(34===t.charCodeAt(n)){if(34!==t.charCodeAt(n+1))break;++n}d=n+2;var i=t.charCodeAt(n+1);return 13===i?(s=!0,10===t.charCodeAt(n+2)&&++d):10===i&&(s=!0),t.substring(e+1,n).replace(/""/g,'"')
}for(;l>d;){var i=t.charCodeAt(d++),o=1;if(10===i)s=!0;else if(13===i)s=!0,10===t.charCodeAt(d)&&(++d,++o);else if(i!==c)continue;return t.substring(e,d-o)}return t.substring(e)}for(var i,s,a={},r={},o=[],l=t.length,d=0,h=0;(i=n())!==r;){for(var u=[];i!==a&&i!==r;)u.push(i),i=n();(!e||(u=e(u,h++)))&&o.push(u)}return o},n.format=function(e){if(Array.isArray(e[0]))return n.formatRows(e);var i=new a,s=[];return e.forEach(function(t){for(var e in t)i.has(e)||s.push(i.add(e))}),[s.map(o).join(t)].concat(e.map(function(e){return s.map(function(t){return o(e[t])}).join(t)})).join("\n")},n.formatRows=function(t){return t.map(r).join("\n")},n},qr.csv=qr.dsv(",","text/csv"),qr.tsv=qr.dsv("	","text/tab-separated-values");var jo,Yo,Xo,Jo,Zo,Qo=Zr[o(Zr,"requestAnimationFrame")]||function(t){setTimeout(t,17)};qr.timer=function(t,e,n){var i=arguments.length;2>i&&(e=0),3>i&&(n=Date.now());var s=n+e,a={c:t,t:s,f:!1,n:null};Yo?Yo.n=a:jo=a,Yo=a,Xo||(Jo=clearTimeout(Jo),Xo=1,Qo(we))},qr.timer.flush=function(){ye(),_e()};var tl=".",el=",",nl=[3,3],il="$",sl=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"].map(xe);qr.formatPrefix=function(t,e){var n=0;return t&&(0>t&&(t*=-1),e&&(t=qr.round(t,ke(t,e))),n=1+Math.floor(1e-12+Math.log(t)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((0>=n?n+1:n-1)/3)))),sl[8+n/3]},qr.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)},qr.format=function(t){var e=al.exec(t),n=e[1]||" ",i=e[2]||">",s=e[3]||"",a=e[4]||"",r=e[5],o=+e[6],l=e[7],c=e[8],d=e[9],h=1,u="",p=!1;switch(c&&(c=+c.substring(1)),(r||"0"===n&&"="===i)&&(r=n="0",i="=",l&&(o-=Math.floor((o-1)/4))),d){case"n":l=!0,d="g";break;case"%":h=100,u="%",d="f";break;case"p":h=100,u="%",d="r";break;case"b":case"o":case"x":case"X":"#"===a&&(a="0"+d.toLowerCase());case"c":case"d":p=!0,c=0;break;case"s":h=-1,d="r"}"#"===a?a="":"$"===a&&(a=il),"r"!=d||c||(d="g"),null!=c&&("g"==d?c=Math.max(1,Math.min(21,c)):("e"==d||"f"==d)&&(c=Math.max(0,Math.min(20,c)))),d=rl.get(d)||Ce;var m=r&&l;return function(t){if(p&&t%1)return"";var e=0>t||0===t&&0>1/t?(t=-t,"-"):s;if(0>h){var f=qr.formatPrefix(t,c);t=f.scale(t),u=f.symbol}else t*=h;t=d(t,c);var g=t.lastIndexOf("."),v=0>g?t:t.substring(0,g),b=0>g?"":tl+t.substring(g+1);!r&&l&&(v=ol(v));var w=a.length+v.length+b.length+(m?0:e.length),y=o>w?new Array(w=o-w+1).join(n):"";return m&&(v=ol(y+v)),e+=a,t=v+b,("<"===i?e+t+y:">"===i?y+e+t:"^"===i?y.substring(0,w>>=1)+e+t+y.substring(w):e+(m?t:y+t))+u}};var al=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,rl=qr.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,e){return(t=qr.round(t,ke(t,e))).toFixed(Math.max(0,Math.min(20,ke(t*(1+1e-15),e))))}}),ol=fe;if(nl){var ll=nl.length;ol=function(t){for(var e=t.length,n=[],i=0,s=nl[0];e>0&&s>0;)n.push(t.substring(e-=s,e+s)),s=nl[i=(i+1)%ll];return n.reverse().join(el)}}qr.geo={},Se.prototype={s:0,t:0,add:function(t){$e(t,this.t,cl),$e(cl.s,this.s,this),this.s?this.t+=cl.t:this.s=cl.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var cl=new Se;qr.geo.stream=function(t,e){t&&dl.hasOwnProperty(t.type)?dl[t.type](t,e):Me(t,e)};var dl={Feature:function(t,e){Me(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,i=-1,s=n.length;++i<s;)Me(n[i].geometry,e)}},hl={Sphere:function(t,e){e.sphere()},Point:function(t,e){t=t.coordinates,e.point(t[0],t[1],t[2])},MultiPoint:function(t,e){for(var n=t.coordinates,i=-1,s=n.length;++i<s;)t=n[i],e.point(t[0],t[1],t[2])},LineString:function(t,e){Pe(t.coordinates,e,0)},MultiLineString:function(t,e){for(var n=t.coordinates,i=-1,s=n.length;++i<s;)Pe(n[i],e,0)},Polygon:function(t,e){De(t.coordinates,e)},MultiPolygon:function(t,e){for(var n=t.coordinates,i=-1,s=n.length;++i<s;)De(n[i],e)},GeometryCollection:function(t,e){for(var n=t.geometries,i=-1,s=n.length;++i<s;)Me(n[i],e)}};qr.geo.area=function(t){return ul=0,qr.geo.stream(t,ml),ul};var ul,pl=new Se,ml={sphere:function(){ul+=4*$o},point:l,lineStart:l,lineEnd:l,polygonStart:function(){pl.reset(),ml.lineStart=Te},polygonEnd:function(){var t=2*pl;ul+=0>t?4*$o+t:t,ml.lineStart=ml.lineEnd=ml.point=l}};qr.geo.bounds=function(){function t(t,e){w.push(y=[d=t,u=t]),h>e&&(h=e),e>p&&(p=e)}function e(e,n){var i=Fe([e*Fo,n*Fo]);if(v){var s=Ae(v,i),a=[s[1],-s[0],0],r=Ae(a,s);Ne(r),r=Ee(r);var l=e-m,c=l>0?1:-1,f=r[0]*Go*c,g=oo(l)>180;if(g^(f>c*m&&c*e>f)){var b=r[1]*Go;b>p&&(p=b)}else if(f=(f+360)%360-180,g^(f>c*m&&c*e>f)){var b=-r[1]*Go;h>b&&(h=b)}else h>n&&(h=n),n>p&&(p=n);g?m>e?o(d,e)>o(d,u)&&(u=e):o(e,u)>o(d,u)&&(d=e):u>=d?(d>e&&(d=e),e>u&&(u=e)):e>m?o(d,e)>o(d,u)&&(u=e):o(e,u)>o(d,u)&&(d=e)}else t(e,n);v=i,m=e}function n(){_.point=e}function i(){y[0]=d,y[1]=u,_.point=t,v=null}function s(t,n){if(v){var i=t-m;b+=oo(i)>180?i+(i>0?360:-360):i}else f=t,g=n;ml.point(t,n),e(t,n)}function a(){ml.lineStart()}function r(){s(f,g),ml.lineEnd(),oo(b)>Do&&(d=-(u=180)),y[0]=d,y[1]=u,v=null}function o(t,e){return(e-=t)<0?e+360:e}function l(t,e){return t[0]-e[0]}function c(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t<e[0]||e[1]<t}var d,h,u,p,m,f,g,v,b,w,y,_={point:t,lineStart:n,lineEnd:i,polygonStart:function(){_.point=s,_.lineStart=a,_.lineEnd=r,b=0,ml.polygonStart()},polygonEnd:function(){ml.polygonEnd(),_.point=t,_.lineStart=n,_.lineEnd=i,0>pl?(d=-(u=180),h=-(p=90)):b>Do?p=90:-Do>b&&(h=-90),y[0]=d,y[1]=u}};return function(t){p=u=-(d=h=1/0),w=[],qr.geo.stream(t,_);var e=w.length;if(e){w.sort(l);for(var n,i=1,s=w[0],a=[s];e>i;++i)n=w[i],c(n[0],s)||c(n[1],s)?(o(s[0],n[1])>o(s[0],s[1])&&(s[1]=n[1]),o(n[0],s[1])>o(s[0],s[1])&&(s[0]=n[0])):a.push(s=n);for(var r,n,m=-1/0,e=a.length-1,i=0,s=a[e];e>=i;s=n,++i)n=a[i],(r=o(s[1],n[0]))>m&&(m=r,d=n[0],u=s[1])}return w=y=null,1/0===d||1/0===h?[[0/0,0/0],[0/0,0/0]]:[[d,h],[u,p]]}}(),qr.geo.centroid=function(t){fl=gl=vl=bl=wl=yl=_l=xl=kl=Cl=Sl=0,qr.geo.stream(t,$l);var e=kl,n=Cl,i=Sl,s=e*e+n*n+i*i;return To>s&&(e=yl,n=_l,i=xl,Do>gl&&(e=vl,n=bl,i=wl),s=e*e+n*n+i*i,To>s)?[0/0,0/0]:[Math.atan2(n,e)*Go,H(i/Math.sqrt(s))*Go]};var fl,gl,vl,bl,wl,yl,_l,xl,kl,Cl,Sl,$l={sphere:l,point:He,lineStart:ze,lineEnd:Oe,polygonStart:function(){$l.lineStart=Ve},polygonEnd:function(){$l.lineStart=ze}},Ml=je(Be,Qe,en,[-$o,-$o/2]),Pl=1e9;qr.geo.clipExtent=function(){var t,e,n,i,s,a,r={stream:function(t){return s&&(s.valid=!1),s=a(t),s.valid=!0,s},extent:function(o){return arguments.length?(a=an(t=+o[0][0],e=+o[0][1],n=+o[1][0],i=+o[1][1]),s&&(s.valid=!1,s=null),r):[[t,e],[n,i]]}};return r.extent([[0,0],[960,500]])},(qr.geo.conicEqualArea=function(){return on(ln)}).raw=ln,qr.geo.albers=function(){return qr.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},qr.geo.albersUsa=function(){function t(t){var a=t[0],r=t[1];return e=null,n(a,r),e||(i(a,r),e)||s(a,r),e}var e,n,i,s,a=qr.geo.albers(),r=qr.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),o=qr.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,n){e=[t,n]}};return t.invert=function(t){var e=a.scale(),n=a.translate(),i=(t[0]-n[0])/e,s=(t[1]-n[1])/e;return(s>=.12&&.234>s&&i>=-.425&&-.214>i?r:s>=.166&&.234>s&&i>=-.214&&-.115>i?o:a).invert(t)},t.stream=function(t){var e=a.stream(t),n=r.stream(t),i=o.stream(t);return{point:function(t,s){e.point(t,s),n.point(t,s),i.point(t,s)},sphere:function(){e.sphere(),n.sphere(),i.sphere()},lineStart:function(){e.lineStart(),n.lineStart(),i.lineStart()},lineEnd:function(){e.lineEnd(),n.lineEnd(),i.lineEnd()},polygonStart:function(){e.polygonStart(),n.polygonStart(),i.polygonStart()},polygonEnd:function(){e.polygonEnd(),n.polygonEnd(),i.polygonEnd()}}},t.precision=function(e){return arguments.length?(a.precision(e),r.precision(e),o.precision(e),t):a.precision()},t.scale=function(e){return arguments.length?(a.scale(e),r.scale(.35*e),o.scale(e),t.translate(a.translate())):a.scale()},t.translate=function(e){if(!arguments.length)return a.translate();var c=a.scale(),d=+e[0],h=+e[1];return n=a.translate(e).clipExtent([[d-.455*c,h-.238*c],[d+.455*c,h+.238*c]]).stream(l).point,i=r.translate([d-.307*c,h+.201*c]).clipExtent([[d-.425*c+Do,h+.12*c+Do],[d-.214*c-Do,h+.234*c-Do]]).stream(l).point,s=o.translate([d-.205*c,h+.212*c]).clipExtent([[d-.214*c+Do,h+.166*c+Do],[d-.115*c-Do,h+.234*c-Do]]).stream(l).point,t},t.scale(1070)};var Dl,Tl,Fl,Gl,Al,Rl,Ll={point:l,lineStart:l,lineEnd:l,polygonStart:function(){Tl=0,Ll.lineStart=cn},polygonEnd:function(){Ll.lineStart=Ll.lineEnd=Ll.point=l,Dl+=oo(Tl/2)}},Nl={point:dn,lineStart:l,lineEnd:l,polygonStart:l,polygonEnd:l},El={point:pn,lineStart:mn,lineEnd:fn,polygonStart:function(){El.lineStart=gn},polygonEnd:function(){El.point=pn,El.lineStart=mn,El.lineEnd=fn}};qr.geo.path=function(){function t(t){return t&&("function"==typeof o&&a.pointRadius(+o.apply(this,arguments)),r&&r.valid||(r=s(a)),qr.geo.stream(t,r)),a.result()}function e(){return r=null,t}var n,i,s,a,r,o=4.5;return t.area=function(t){return Dl=0,qr.geo.stream(t,s(Ll)),Dl},t.centroid=function(t){return vl=bl=wl=yl=_l=xl=kl=Cl=Sl=0,qr.geo.stream(t,s(El)),Sl?[kl/Sl,Cl/Sl]:xl?[yl/xl,_l/xl]:wl?[vl/wl,bl/wl]:[0/0,0/0]},t.bounds=function(t){return Al=Rl=-(Fl=Gl=1/0),qr.geo.stream(t,s(Nl)),[[Fl,Gl],[Al,Rl]]},t.projection=function(t){return arguments.length?(s=(n=t)?t.stream||wn(t):fe,e()):n},t.context=function(t){return arguments.length?(a=null==(i=t)?new hn:new vn(t),"function"!=typeof o&&a.pointRadius(o),e()):i},t.pointRadius=function(e){return arguments.length?(o="function"==typeof e?e:(a.pointRadius(+e),+e),t):o},t.projection(qr.geo.albersUsa()).context(null)},qr.geo.transform=function(t){return{stream:function(e){var n=new yn(e);for(var i in t)n[i]=t[i];return n}}},yn.prototype={point:function(t,e){this.stream.point(t,e)},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()}},qr.geo.projection=xn,qr.geo.projectionMutator=kn,(qr.geo.equirectangular=function(){return xn(Sn)}).raw=Sn.invert=Sn,qr.geo.rotation=function(t){function e(e){return e=t(e[0]*Fo,e[1]*Fo),e[0]*=Go,e[1]*=Go,e}return t=Mn(t[0]%360*Fo,t[1]*Fo,t.length>2?t[2]*Fo:0),e.invert=function(e){return e=t.invert(e[0]*Fo,e[1]*Fo),e[0]*=Go,e[1]*=Go,e},e},$n.invert=Sn,qr.geo.circle=function(){function t(){var t="function"==typeof i?i.apply(this,arguments):i,e=Mn(-t[0]*Fo,-t[1]*Fo,0).invert,s=[];return n(null,null,1,{point:function(t,n){s.push(t=e(t,n)),t[0]*=Go,t[1]*=Go}}),{type:"Polygon",coordinates:[s]}}var e,n,i=[0,0],s=6;return t.origin=function(e){return arguments.length?(i=e,t):i},t.angle=function(i){return arguments.length?(n=Fn((e=+i)*Fo,s*Fo),t):e},t.precision=function(i){return arguments.length?(n=Fn(e*Fo,(s=+i)*Fo),t):s},t.angle(90)},qr.geo.distance=function(t,e){var n,i=(e[0]-t[0])*Fo,s=t[1]*Fo,a=e[1]*Fo,r=Math.sin(i),o=Math.cos(i),l=Math.sin(s),c=Math.cos(s),d=Math.sin(a),h=Math.cos(a);return Math.atan2(Math.sqrt((n=h*r)*n+(n=c*d-l*h*o)*n),l*d+c*h*o)},qr.geo.graticule=function(){function t(){return{type:"MultiLineString",coordinates:e()}}function e(){return qr.range(Math.ceil(a/g)*g,s,g).map(u).concat(qr.range(Math.ceil(c/v)*v,l,v).map(p)).concat(qr.range(Math.ceil(i/m)*m,n,m).filter(function(t){return oo(t%g)>Do}).map(d)).concat(qr.range(Math.ceil(o/f)*f,r,f).filter(function(t){return oo(t%v)>Do}).map(h))}var n,i,s,a,r,o,l,c,d,h,u,p,m=10,f=m,g=90,v=360,b=2.5;return t.lines=function(){return e().map(function(t){return{type:"LineString",coordinates:t}})},t.outline=function(){return{type:"Polygon",coordinates:[u(a).concat(p(l).slice(1),u(s).reverse().slice(1),p(c).reverse().slice(1))]}},t.extent=function(e){return arguments.length?t.majorExtent(e).minorExtent(e):t.minorExtent()},t.majorExtent=function(e){return arguments.length?(a=+e[0][0],s=+e[1][0],c=+e[0][1],l=+e[1][1],a>s&&(e=a,a=s,s=e),c>l&&(e=c,c=l,l=e),t.precision(b)):[[a,c],[s,l]]},t.minorExtent=function(e){return arguments.length?(i=+e[0][0],n=+e[1][0],o=+e[0][1],r=+e[1][1],i>n&&(e=i,i=n,n=e),o>r&&(e=o,o=r,r=e),t.precision(b)):[[i,o],[n,r]]},t.step=function(e){return arguments.length?t.majorStep(e).minorStep(e):t.minorStep()},t.majorStep=function(e){return arguments.length?(g=+e[0],v=+e[1],t):[g,v]},t.minorStep=function(e){return arguments.length?(m=+e[0],f=+e[1],t):[m,f]},t.precision=function(e){return arguments.length?(b=+e,d=An(o,r,90),h=Rn(i,n,b),u=An(c,l,90),p=Rn(a,s,b),t):b},t.majorExtent([[-180,-90+Do],[180,90-Do]]).minorExtent([[-180,-80-Do],[180,80+Do]])},qr.geo.greatArc=function(){function t(){return{type:"LineString",coordinates:[e||i.apply(this,arguments),n||s.apply(this,arguments)]}}var e,n,i=Ln,s=Nn;return t.distance=function(){return qr.geo.distance(e||i.apply(this,arguments),n||s.apply(this,arguments))},t.source=function(n){return arguments.length?(i=n,e="function"==typeof n?null:n,t):i},t.target=function(e){return arguments.length?(s=e,n="function"==typeof e?null:e,t):s},t.precision=function(){return arguments.length?t:0},t},qr.geo.interpolate=function(t,e){return En(t[0]*Fo,t[1]*Fo,e[0]*Fo,e[1]*Fo)},qr.geo.length=function(t){return Il=0,qr.geo.stream(t,Hl),Il};var Il,Hl={sphere:l,point:l,lineStart:In,lineEnd:l,polygonStart:l,polygonEnd:l},Ul=Hn(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(qr.geo.azimuthalEqualArea=function(){return xn(Ul)}).raw=Ul;var zl=Hn(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},fe);(qr.geo.azimuthalEquidistant=function(){return xn(zl)}).raw=zl,(qr.geo.conicConformal=function(){return on(Un)}).raw=Un,(qr.geo.conicEquidistant=function(){return on(zn)}).raw=zn;var Ol=Hn(function(t){return 1/t},Math.atan);(qr.geo.gnomonic=function(){return xn(Ol)}).raw=Ol,On.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-Po]},(qr.geo.mercator=function(){return Vn(On)}).raw=On;var Vl=Hn(function(){return 1},Math.asin);(qr.geo.orthographic=function(){return xn(Vl)}).raw=Vl;var Bl=Hn(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});(qr.geo.stereographic=function(){return xn(Bl)}).raw=Bl,Bn.invert=function(t,e){return[Math.atan2(U(t),Math.cos(e)),H(Math.sin(e)/z(t))]},(qr.geo.transverseMercator=function(){return Vn(Bn)}).raw=Bn,qr.geom={},qr.geom.hull=function(t){function e(t){if(t.length<3)return[];var e,s,a,r,o,l,c,d,h,u,p,m,f=me(n),g=me(i),v=t.length,b=v-1,w=[],y=[],_=0;if(f===Kn&&i===Wn)e=t;else for(a=0,e=[];v>a;++a)e.push([+f.call(this,s=t[a],a),+g.call(this,s,a)]);for(a=1;v>a;++a)(e[a][1]<e[_][1]||e[a][1]==e[_][1]&&e[a][0]<e[_][0])&&(_=a);for(a=0;v>a;++a)a!==_&&(l=e[a][1]-e[_][1],o=e[a][0]-e[_][0],w.push({angle:Math.atan2(l,o),index:a}));for(w.sort(function(t,e){return t.angle-e.angle}),p=w[0].angle,u=w[0].index,h=0,a=1;b>a;++a){if(r=w[a].index,p==w[a].angle){if(o=e[u][0]-e[_][0],l=e[u][1]-e[_][1],c=e[r][0]-e[_][0],d=e[r][1]-e[_][1],o*o+l*l>=c*c+d*d){w[a].index=-1;continue}w[h].index=-1}p=w[a].angle,h=a,u=r}for(y.push(_),a=0,r=0;2>a;++r)w[r].index>-1&&(y.push(w[r].index),a++);for(m=y.length;b>r;++r)if(!(w[r].index<0)){for(;!qn(y[m-2],y[m-1],w[r].index,e);)--m;y[m++]=w[r].index}var x=[];for(a=m-1;a>=0;--a)x.push(t[y[a]]);return x}var n=Kn,i=Wn;return arguments.length?e(t):(e.x=function(t){return arguments.length?(n=t,e):n},e.y=function(t){return arguments.length?(i=t,e):i},e)},qr.geom.polygon=function(t){return po(t,Kl),t};var Kl=qr.geom.polygon.prototype=[];Kl.area=function(){for(var t,e=-1,n=this.length,i=this[n-1],s=0;++e<n;)t=i,i=this[e],s+=t[1]*i[0]-t[0]*i[1];return.5*s},Kl.centroid=function(t){var e,n,i=-1,s=this.length,a=0,r=0,o=this[s-1];for(arguments.length||(t=-1/(6*this.area()));++i<s;)e=o,o=this[i],n=e[0]*o[1]-o[0]*e[1],a+=(e[0]+o[0])*n,r+=(e[1]+o[1])*n;return[a*t,r*t]},Kl.clip=function(t){for(var e,n,i,s,a,r,o=Xn(t),l=-1,c=this.length-Xn(this),d=this[c-1];++l<c;){for(e=t.slice(),t.length=0,s=this[l],a=e[(i=e.length-o)-1],n=-1;++n<i;)r=e[n],jn(r,d,s)?(jn(a,d,s)||t.push(Yn(a,r,d,s)),t.push(r)):jn(a,d,s)&&t.push(Yn(a,r,d,s)),a=r;o&&t.push(t[0]),d=s}return t};var Wl,ql,jl,Yl,Xl,Jl=[],Zl=[];si.prototype.prepare=function(){for(var t,e=this.edges,n=e.length;n--;)t=e[n].edge,t.b&&t.a||e.splice(n,1);return e.sort(ri),e.length},gi.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}},vi.prototype={insert:function(t,e){var n,i,s;if(t){if(e.P=t,e.N=t.N,t.N&&(t.N.P=e),t.N=e,t.R){for(t=t.R;t.L;)t=t.L;t.L=e}else t.R=e;n=t}else this._?(t=_i(this._),e.P=null,e.N=t,t.P=t.L=e,n=t):(e.P=e.N=null,this._=e,n=null);for(e.L=e.R=null,e.U=n,e.C=!0,t=e;n&&n.C;)i=n.U,n===i.L?(s=i.R,s&&s.C?(n.C=s.C=!1,i.C=!0,t=i):(t===n.R&&(wi(this,n),t=n,n=t.U),n.C=!1,i.C=!0,yi(this,i))):(s=i.L,s&&s.C?(n.C=s.C=!1,i.C=!0,t=i):(t===n.L&&(yi(this,n),t=n,n=t.U),n.C=!1,i.C=!0,wi(this,i))),n=t.U;this._.C=!1},remove:function(t){t.N&&(t.N.P=t.P),t.P&&(t.P.N=t.N),t.N=t.P=null;var e,n,i,s=t.U,a=t.L,r=t.R;if(n=a?r?_i(r):a:r,s?s.L===t?s.L=n:s.R=n:this._=n,a&&r?(i=n.C,n.C=t.C,n.L=a,a.U=n,n!==r?(s=n.U,n.U=t.U,t=n.R,s.L=t,n.R=r,r.U=n):(n.U=s,s=n,t=n.R)):(i=t.C,t=n),t&&(t.U=s),!i){if(t&&t.C)return void(t.C=!1);do{if(t===this._)break;if(t===s.L){if(e=s.R,e.C&&(e.C=!1,s.C=!0,wi(this,s),e=s.R),e.L&&e.L.C||e.R&&e.R.C){e.R&&e.R.C||(e.L.C=!1,e.C=!0,yi(this,e),e=s.R),e.C=s.C,s.C=e.R.C=!1,wi(this,s),t=this._;break}}else if(e=s.L,e.C&&(e.C=!1,s.C=!0,yi(this,s),e=s.L),e.L&&e.L.C||e.R&&e.R.C){e.L&&e.L.C||(e.R.C=!1,e.C=!0,wi(this,e),e=s.L),e.C=s.C,s.C=e.L.C=!1,yi(this,s),t=this._;break}e.C=!0,t=s,s=s.U}while(!t.C);t&&(t.C=!1)}}},qr.geom.voronoi=function(t){function e(t){var e=new Array(t.length),i=o[0][0],s=o[0][1],a=o[1][0],r=o[1][1];return xi(n(t),o).cells.forEach(function(n,o){var l=n.edges,c=n.site,d=e[o]=l.length?l.map(function(t){var e=t.start();return[e.x,e.y]}):c.x>=i&&c.x<=a&&c.y>=s&&c.y<=r?[[i,r],[a,r],[a,s],[i,s]]:[];d.point=t[o]}),e}function n(t){return t.map(function(t,e){return{x:Math.round(a(t,e)/Do)*Do,y:Math.round(r(t,e)/Do)*Do,i:e}})}var i=Kn,s=Wn,a=i,r=s,o=Ql;return t?e(t):(e.links=function(t){return xi(n(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},e.triangles=function(t){var e=[];return xi(n(t)).cells.forEach(function(n,i){for(var s,a,r=n.site,o=n.edges.sort(ri),l=-1,c=o.length,d=o[c-1].edge,h=d.l===r?d.r:d.l;++l<c;)s=d,a=h,d=o[l].edge,h=d.l===r?d.r:d.l,i<a.i&&i<h.i&&Ci(r,a,h)<0&&e.push([t[i],t[a.i],t[h.i]])}),e},e.x=function(t){return arguments.length?(a=me(i=t),e):i},e.y=function(t){return arguments.length?(r=me(s=t),e):s},e.clipExtent=function(t){return arguments.length?(o=null==t?Ql:t,e):o===Ql?null:o},e.size=function(t){return arguments.length?e.clipExtent(t&&[[0,0],t]):o===Ql?null:o&&o[1]},e)};var Ql=[[-1e6,-1e6],[1e6,1e6]];qr.geom.delaunay=function(t){return qr.geom.voronoi().triangles(t)},qr.geom.quadtree=function(t,e,n,i,s){function a(t){function a(t,e,n,i,s,a,r,o){if(!isNaN(n)&&!isNaN(i))if(t.leaf){var l=t.x,d=t.y;if(null!=l)if(oo(l-n)+oo(d-i)<.01)c(t,e,n,i,s,a,r,o);else{var h=t.point;t.x=t.y=t.point=null,c(t,h,l,d,s,a,r,o),c(t,e,n,i,s,a,r,o)}else t.x=n,t.y=i,t.point=e}else c(t,e,n,i,s,a,r,o)}function c(t,e,n,i,s,r,o,l){var c=.5*(s+o),d=.5*(r+l),h=n>=c,u=i>=d,p=(u<<1)+h;t.leaf=!1,t=t.nodes[p]||(t.nodes[p]=Mi()),h?s=c:o=c,u?r=d:l=d,a(t,e,n,i,s,r,o,l)}var d,h,u,p,m,f,g,v,b,w=me(o),y=me(l);if(null!=e)f=e,g=n,v=i,b=s;else if(v=b=-(f=g=1/0),h=[],u=[],m=t.length,r)for(p=0;m>p;++p)d=t[p],d.x<f&&(f=d.x),d.y<g&&(g=d.y),d.x>v&&(v=d.x),d.y>b&&(b=d.y),h.push(d.x),u.push(d.y);else for(p=0;m>p;++p){var _=+w(d=t[p],p),x=+y(d,p);f>_&&(f=_),g>x&&(g=x),_>v&&(v=_),x>b&&(b=x),h.push(_),u.push(x)}var k=v-f,C=b-g;k>C?b=g+k:v=f+C;var S=Mi();if(S.add=function(t){a(S,t,+w(t,++p),+y(t,p),f,g,v,b)},S.visit=function(t){Pi(t,S,f,g,v,b)},p=-1,null==e){for(;++p<m;)a(S,t[p],h[p],u[p],f,g,v,b);--p}else t.forEach(S.add);return h=u=t=d=null,S}var r,o=Kn,l=Wn;return(r=arguments.length)?(o=Si,l=$i,3===r&&(s=n,i=e,n=e=0),a(t)):(a.x=function(t){return arguments.length?(o=t,a):o},a.y=function(t){return arguments.length?(l=t,a):l},a.extent=function(t){return arguments.length?(null==t?e=n=i=s=null:(e=+t[0][0],n=+t[0][1],i=+t[1][0],s=+t[1][1]),a):null==e?null:[[e,n],[i,s]]},a.size=function(t){return arguments.length?(null==t?e=n=i=s=null:(e=n=0,i=+t[0],s=+t[1]),a):null==e?null:[i-e,s-n]},a)},qr.interpolateRgb=Di,qr.interpolateObject=Ti,qr.interpolateNumber=Fi,qr.interpolateString=Gi;var tc=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;qr.interpolate=Ai,qr.interpolators=[function(t,e){var n=typeof e;return("string"===n?qo.has(e)||/^(#|rgb\(|hsl\()/.test(e)?Di:Gi:e instanceof B?Di:"object"===n?Array.isArray(e)?Ri:Ti:Fi)(t,e)}],qr.interpolateArray=Ri;var ec=function(){return fe},nc=qr.map({linear:ec,poly:zi,quad:function(){return Ii},cubic:function(){return Hi},sin:function(){return Oi},exp:function(){return Vi},circle:function(){return Bi},elastic:Ki,back:Wi,bounce:function(){return qi}}),ic=qr.map({"in":fe,out:Ni,"in-out":Ei,"out-in":function(t){return Ei(Ni(t))}});qr.ease=function(t){var e=t.indexOf("-"),n=e>=0?t.substring(0,e):t,i=e>=0?t.substring(e+1):"in";return n=nc.get(n)||ec,i=ic.get(i)||fe,Li(i(n.apply(null,jr.call(arguments,1))))},qr.interpolateHcl=ji,qr.interpolateHsl=Yi,qr.interpolateLab=Xi,qr.interpolateRound=Ji,qr.transform=function(t){var e=Xr.createElementNS(qr.ns.prefix.svg,"g");return(qr.transform=function(t){if(null!=t){e.setAttribute("transform",t);var n=e.transform.baseVal.consolidate()}return new Zi(n?n.matrix:sc)})(t)},Zi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var sc={a:1,b:0,c:0,d:1,e:0,f:0};qr.interpolateTransform=ns,qr.layout={},qr.layout.bundle=function(){return function(t){for(var e=[],n=-1,i=t.length;++n<i;)e.push(as(t[n]));return e}},qr.layout.chord=function(){function t(){var t,c,h,u,p,m={},f=[],g=qr.range(a),v=[];for(n=[],i=[],t=0,u=-1;++u<a;){for(c=0,p=-1;++p<a;)c+=s[u][p];f.push(c),v.push(qr.range(a)),t+=c}for(r&&g.sort(function(t,e){return r(f[t],f[e])}),o&&v.forEach(function(t,e){t.sort(function(t,n){return o(s[e][t],s[e][n])})}),t=(Mo-d*a)/t,c=0,u=-1;++u<a;){for(h=c,p=-1;++p<a;){var b=g[u],w=v[b][p],y=s[b][w],_=c,x=c+=y*t;m[b+"-"+w]={index:b,subindex:w,startAngle:_,endAngle:x,value:y}}i[b]={index:b,startAngle:h,endAngle:c,value:(c-h)/t},c+=d}for(u=-1;++u<a;)for(p=u-1;++p<a;){var k=m[u+"-"+p],C=m[p+"-"+u];(k.value||C.value)&&n.push(k.value<C.value?{source:C,target:k}:{source:k,target:C})}l&&e()}function e(){n.sort(function(t,e){return l((t.source.value+t.target.value)/2,(e.source.value+e.target.value)/2)})}var n,i,s,a,r,o,l,c={},d=0;return c.matrix=function(t){return arguments.length?(a=(s=t)&&s.length,n=i=null,c):s},c.padding=function(t){return arguments.length?(d=t,n=i=null,c):d},c.sortGroups=function(t){return arguments.length?(r=t,n=i=null,c):r},c.sortSubgroups=function(t){return arguments.length?(o=t,n=null,c):o},c.sortChords=function(t){return arguments.length?(l=t,n&&e(),c):l},c.chords=function(){return n||t(),n},c.groups=function(){return i||t(),i},c},qr.layout.force=function(){function t(t){return function(e,n,i,s){if(e.point!==t){var a=e.cx-t.x,r=e.cy-t.y,o=1/Math.sqrt(a*a+r*r);if(f>(s-n)*o){var l=e.charge*o*o;return t.px-=a*l,t.py-=r*l,!0}if(e.point&&isFinite(o)){var l=e.pointCharge*o*o;t.px-=a*l,t.py-=r*l}}return!e.charge}}function e(t){t.px=qr.event.x,t.py=qr.event.y,o.resume()}var n,i,s,a,r,o={},l=qr.dispatch("start","tick","end"),c=[1,1],d=.9,h=ac,u=rc,p=-30,m=.1,f=.8,g=[],v=[];return o.tick=function(){if((i*=.99)<.005)return l.end({type:"end",alpha:i=0}),!0;var e,n,o,h,u,f,b,w,y,_=g.length,x=v.length;for(n=0;x>n;++n)o=v[n],h=o.source,u=o.target,w=u.x-h.x,y=u.y-h.y,(f=w*w+y*y)&&(f=i*a[n]*((f=Math.sqrt(f))-s[n])/f,w*=f,y*=f,u.x-=w*(b=h.weight/(u.weight+h.weight)),u.y-=y*b,h.x+=w*(b=1-b),h.y+=y*b);if((b=i*m)&&(w=c[0]/2,y=c[1]/2,n=-1,b))for(;++n<_;)o=g[n],o.x+=(w-o.x)*b,o.y+=(y-o.y)*b;if(p)for(us(e=qr.geom.quadtree(g),i,r),n=-1;++n<_;)(o=g[n]).fixed||e.visit(t(o));for(n=-1;++n<_;)o=g[n],o.fixed?(o.x=o.px,o.y=o.py):(o.x-=(o.px-(o.px=o.x))*d,o.y-=(o.py-(o.py=o.y))*d);l.tick({type:"tick",alpha:i})},o.nodes=function(t){return arguments.length?(g=t,o):g},o.links=function(t){return arguments.length?(v=t,o):v},o.size=function(t){return arguments.length?(c=t,o):c},o.linkDistance=function(t){return arguments.length?(h="function"==typeof t?t:+t,o):h},o.distance=o.linkDistance,o.linkStrength=function(t){return arguments.length?(u="function"==typeof t?t:+t,o):u},o.friction=function(t){return arguments.length?(d=+t,o):d},o.charge=function(t){return arguments.length?(p="function"==typeof t?t:+t,o):p},o.gravity=function(t){return arguments.length?(m=+t,o):m},o.theta=function(t){return arguments.length?(f=+t,o):f},o.alpha=function(t){return arguments.length?(t=+t,i?i=t>0?t:0:t>0&&(l.start({type:"start",alpha:i=t}),qr.timer(o.tick)),o):i},o.start=function(){function t(t,i){if(!n){for(n=new Array(l),o=0;l>o;++o)n[o]=[];for(o=0;c>o;++o){var s=v[o];n[s.source.index].push(s.target),n[s.target.index].push(s.source)}}for(var a,r=n[e],o=-1,c=r.length;++o<c;)if(!isNaN(a=r[o][t]))return a;return Math.random()*i}var e,n,i,l=g.length,d=v.length,m=c[0],f=c[1];for(e=0;l>e;++e)(i=g[e]).index=e,i.weight=0;for(e=0;d>e;++e)i=v[e],"number"==typeof i.source&&(i.source=g[i.source]),"number"==typeof i.target&&(i.target=g[i.target]),++i.source.weight,++i.target.weight;for(e=0;l>e;++e)i=g[e],isNaN(i.x)&&(i.x=t("x",m)),isNaN(i.y)&&(i.y=t("y",f)),isNaN(i.px)&&(i.px=i.x),isNaN(i.py)&&(i.py=i.y);if(s=[],"function"==typeof h)for(e=0;d>e;++e)s[e]=+h.call(this,v[e],e);else for(e=0;d>e;++e)s[e]=h;if(a=[],"function"==typeof u)for(e=0;d>e;++e)a[e]=+u.call(this,v[e],e);else for(e=0;d>e;++e)a[e]=u;if(r=[],"function"==typeof p)for(e=0;l>e;++e)r[e]=+p.call(this,g[e],e);else for(e=0;l>e;++e)r[e]=p;return o.resume()},o.resume=function(){return o.alpha(.1)},o.stop=function(){return o.alpha(0)},o.drag=function(){return n||(n=qr.behavior.drag().origin(fe).on("dragstart.force",ls).on("drag.force",e).on("dragend.force",cs)),arguments.length?void this.on("mouseover.force",ds).on("mouseout.force",hs).call(n):n},qr.rebind(o,l,"on")};var ac=20,rc=1;qr.layout.hierarchy=function(){function t(e,r,o){var l=s.call(n,e,r);if(e.depth=r,o.push(e),l&&(c=l.length)){for(var c,d,h=-1,u=e.children=new Array(c),p=0,m=r+1;++h<c;)d=u[h]=t(l[h],m,o),d.parent=e,p+=d.value;i&&u.sort(i),a&&(e.value=p)}else delete e.children,a&&(e.value=+a.call(n,e,r)||0);return e}function e(t,i){var s=t.children,r=0;if(s&&(o=s.length))for(var o,l=-1,c=i+1;++l<o;)r+=e(s[l],c);else a&&(r=+a.call(n,t,i)||0);return a&&(t.value=r),r}function n(e){var n=[];return t(e,0,n),n}var i=gs,s=ms,a=fs;return n.sort=function(t){return arguments.length?(i=t,n):i},n.children=function(t){return arguments.length?(s=t,n):s},n.value=function(t){return arguments.length?(a=t,n):a},n.revalue=function(t){return e(t,0),t},n},qr.layout.partition=function(){function t(e,n,i,s){var a=e.children;if(e.x=n,e.y=e.depth*s,e.dx=i,e.dy=s,a&&(r=a.length)){var r,o,l,c=-1;for(i=e.value?i/e.value:0;++c<r;)t(o=a[c],n,l=o.value*i,s),n+=l}}function e(t){var n=t.children,i=0;if(n&&(s=n.length))for(var s,a=-1;++a<s;)i=Math.max(i,e(n[a]));return 1+i}function n(n,a){var r=i.call(this,n,a);return t(r[0],0,s[0],s[1]/e(r[0])),r}var i=qr.layout.hierarchy(),s=[1,1];return n.size=function(t){return arguments.length?(s=t,n):s},ps(n,i)},qr.layout.pie=function(){function t(a){var r=a.map(function(n,i){return+e.call(t,n,i)}),o=+("function"==typeof i?i.apply(this,arguments):i),l=(("function"==typeof s?s.apply(this,arguments):s)-o)/qr.sum(r),c=qr.range(a.length);null!=n&&c.sort(n===oc?function(t,e){return r[e]-r[t]}:function(t,e){return n(a[t],a[e])});var d=[];return c.forEach(function(t){var e;d[t]={data:a[t],value:e=r[t],startAngle:o,endAngle:o+=e*l}}),d}var e=Number,n=oc,i=0,s=Mo;return t.value=function(n){return arguments.length?(e=n,t):e},t.sort=function(e){return arguments.length?(n=e,t):n},t.startAngle=function(e){return arguments.length?(i=e,t):i},t.endAngle=function(e){return arguments.length?(s=e,t):s},t};var oc={};qr.layout.stack=function(){function t(o,l){var c=o.map(function(n,i){return e.call(t,n,i)}),d=c.map(function(e){return e.map(function(e,n){return[a.call(t,e,n),r.call(t,e,n)]})}),h=n.call(t,d,l);c=qr.permute(c,h),d=qr.permute(d,h);var u,p,m,f=i.call(t,d,l),g=c.length,v=c[0].length;for(p=0;v>p;++p)for(s.call(t,c[0][p],m=f[p],d[0][p][1]),u=1;g>u;++u)s.call(t,c[u][p],m+=d[u-1][p][1],d[u][p][1]);return o}var e=fe,n=_s,i=xs,s=ys,a=bs,r=ws;return t.values=function(n){return arguments.length?(e=n,t):e},t.order=function(e){return arguments.length?(n="function"==typeof e?e:lc.get(e)||_s,t):n},t.offset=function(e){return arguments.length?(i="function"==typeof e?e:cc.get(e)||xs,t):i},t.x=function(e){return arguments.length?(a=e,t):a},t.y=function(e){return arguments.length?(r=e,t):r},t.out=function(e){return arguments.length?(s=e,t):s},t};var lc=qr.map({"inside-out":function(t){var e,n,i=t.length,s=t.map(ks),a=t.map(Cs),r=qr.range(i).sort(function(t,e){return s[t]-s[e]}),o=0,l=0,c=[],d=[];for(e=0;i>e;++e)n=r[e],l>o?(o+=a[n],c.push(n)):(l+=a[n],d.push(n));return d.reverse().concat(c)},reverse:function(t){return qr.range(t.length).reverse()},"default":_s}),cc=qr.map({silhouette:function(t){var e,n,i,s=t.length,a=t[0].length,r=[],o=0,l=[];for(n=0;a>n;++n){for(e=0,i=0;s>e;e++)i+=t[e][n][1];i>o&&(o=i),r.push(i)}for(n=0;a>n;++n)l[n]=(o-r[n])/2;return l},wiggle:function(t){var e,n,i,s,a,r,o,l,c,d=t.length,h=t[0],u=h.length,p=[];for(p[0]=l=c=0,n=1;u>n;++n){for(e=0,s=0;d>e;++e)s+=t[e][n][1];for(e=0,a=0,o=h[n][0]-h[n-1][0];d>e;++e){for(i=0,r=(t[e][n][1]-t[e][n-1][1])/(2*o);e>i;++i)r+=(t[i][n][1]-t[i][n-1][1])/o;a+=r*t[e][n][1]}p[n]=l-=s?a/s*o:0,c>l&&(c=l)}for(n=0;u>n;++n)p[n]-=c;return p},expand:function(t){var e,n,i,s=t.length,a=t[0].length,r=1/s,o=[];for(n=0;a>n;++n){for(e=0,i=0;s>e;e++)i+=t[e][n][1];if(i)for(e=0;s>e;e++)t[e][n][1]/=i;else for(e=0;s>e;e++)t[e][n][1]=r}for(n=0;a>n;++n)o[n]=0;return o},zero:xs});qr.layout.histogram=function(){function t(t,a){for(var r,o,l=[],c=t.map(n,this),d=i.call(this,c,a),h=s.call(this,d,c,a),a=-1,u=c.length,p=h.length-1,m=e?1:1/u;++a<p;)r=l[a]=[],r.dx=h[a+1]-(r.x=h[a]),r.y=0;if(p>0)for(a=-1;++a<u;)o=c[a],o>=d[0]&&o<=d[1]&&(r=l[qr.bisect(h,o,1,p)-1],r.y+=m,r.push(t[a]));return l}var e=!0,n=Number,i=Ps,s=$s;return t.value=function(e){return arguments.length?(n=e,t):n},t.range=function(e){return arguments.length?(i=me(e),t):i},t.bins=function(e){return arguments.length?(s="number"==typeof e?function(t){return Ms(t,e)}:me(e),t):s},t.frequency=function(n){return arguments.length?(e=!!n,t):e},t},qr.layout.tree=function(){function t(t,a){function r(t,e){var i=t.children,s=t._tree;if(i&&(a=i.length)){for(var a,o,c,d=i[0],h=d,u=-1;++u<a;)c=i[u],r(c,o),h=l(c,o,h),o=c;Es(t);var p=.5*(d._tree.prelim+c._tree.prelim);e?(s.prelim=e._tree.prelim+n(t,e),s.mod=s.prelim-p):s.prelim=p}else e&&(s.prelim=e._tree.prelim+n(t,e))}function o(t,e){t.x=t._tree.prelim+e;var n=t.children;if(n&&(i=n.length)){var i,s=-1;for(e+=t._tree.mod;++s<i;)o(n[s],e)}}function l(t,e,i){if(e){for(var s,a=t,r=t,o=e,l=t.parent.children[0],c=a._tree.mod,d=r._tree.mod,h=o._tree.mod,u=l._tree.mod;o=Fs(o),a=Ts(a),o&&a;)l=Ts(l),r=Fs(r),r._tree.ancestor=t,s=o._tree.prelim+h-a._tree.prelim-c+n(o,a),s>0&&(Is(Hs(o,t,i),t,s),c+=s,d+=s),h+=o._tree.mod,c+=a._tree.mod,u+=l._tree.mod,d+=r._tree.mod;o&&!Fs(r)&&(r._tree.thread=o,r._tree.mod+=h-d),a&&!Ts(l)&&(l._tree.thread=a,l._tree.mod+=c-u,i=t)}return i}var c=e.call(this,t,a),d=c[0];Ns(d,function(t,e){t._tree={ancestor:t,prelim:0,mod:0,change:0,shift:0,number:e?e._tree.number+1:0}}),r(d),o(d,-d._tree.prelim);var h=Gs(d,Rs),u=Gs(d,As),p=Gs(d,Ls),m=h.x-n(h,u)/2,f=u.x+n(u,h)/2,g=p.depth||1;
return Ns(d,s?function(t){t.x*=i[0],t.y=t.depth*i[1],delete t._tree}:function(t){t.x=(t.x-m)/(f-m)*i[0],t.y=t.depth/g*i[1],delete t._tree}),c}var e=qr.layout.hierarchy().sort(null).value(null),n=Ds,i=[1,1],s=!1;return t.separation=function(e){return arguments.length?(n=e,t):n},t.size=function(e){return arguments.length?(s=null==(i=e),t):s?null:i},t.nodeSize=function(e){return arguments.length?(s=null!=(i=e),t):s?i:null},ps(t,e)},qr.layout.pack=function(){function t(t,a){var r=n.call(this,t,a),o=r[0],l=s[0],c=s[1],d=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(o.x=o.y=0,Ns(o,function(t){t.r=+d(t.value)}),Ns(o,Bs),i){var h=i*(e?1:Math.max(2*o.r/l,2*o.r/c))/2;Ns(o,function(t){t.r+=h}),Ns(o,Bs),Ns(o,function(t){t.r-=h})}return qs(o,l/2,c/2,e?1:1/Math.max(2*o.r/l,2*o.r/c)),r}var e,n=qr.layout.hierarchy().sort(Us),i=0,s=[1,1];return t.size=function(e){return arguments.length?(s=e,t):s},t.radius=function(n){return arguments.length?(e=null==n||"function"==typeof n?n:+n,t):e},t.padding=function(e){return arguments.length?(i=+e,t):i},ps(t,n)},qr.layout.cluster=function(){function t(t,a){var r,o=e.call(this,t,a),l=o[0],c=0;Ns(l,function(t){var e=t.children;e&&e.length?(t.x=Xs(e),t.y=Ys(e)):(t.x=r?c+=n(t,r):0,t.y=0,r=t)});var d=Js(l),h=Zs(l),u=d.x-n(d,h)/2,p=h.x+n(h,d)/2;return Ns(l,s?function(t){t.x=(t.x-l.x)*i[0],t.y=(l.y-t.y)*i[1]}:function(t){t.x=(t.x-u)/(p-u)*i[0],t.y=(1-(l.y?t.y/l.y:1))*i[1]}),o}var e=qr.layout.hierarchy().sort(null).value(null),n=Ds,i=[1,1],s=!1;return t.separation=function(e){return arguments.length?(n=e,t):n},t.size=function(e){return arguments.length?(s=null==(i=e),t):s?null:i},t.nodeSize=function(e){return arguments.length?(s=null!=(i=e),t):s?i:null},ps(t,e)},qr.layout.treemap=function(){function t(t,e){for(var n,i,s=-1,a=t.length;++s<a;)i=(n=t[s]).value*(0>e?0:e),n.area=isNaN(i)||0>=i?0:i}function e(n){var a=n.children;if(a&&a.length){var r,o,l,c=h(n),d=[],u=a.slice(),m=1/0,f="slice"===p?c.dx:"dice"===p?c.dy:"slice-dice"===p?1&n.depth?c.dy:c.dx:Math.min(c.dx,c.dy);for(t(u,c.dx*c.dy/n.value),d.area=0;(l=u.length)>0;)d.push(r=u[l-1]),d.area+=r.area,"squarify"!==p||(o=i(d,f))<=m?(u.pop(),m=o):(d.area-=d.pop().area,s(d,f,c,!1),f=Math.min(c.dx,c.dy),d.length=d.area=0,m=1/0);d.length&&(s(d,f,c,!0),d.length=d.area=0),a.forEach(e)}}function n(e){var i=e.children;if(i&&i.length){var a,r=h(e),o=i.slice(),l=[];for(t(o,r.dx*r.dy/e.value),l.area=0;a=o.pop();)l.push(a),l.area+=a.area,null!=a.z&&(s(l,a.z?r.dx:r.dy,r,!o.length),l.length=l.area=0);i.forEach(n)}}function i(t,e){for(var n,i=t.area,s=0,a=1/0,r=-1,o=t.length;++r<o;)(n=t[r].area)&&(a>n&&(a=n),n>s&&(s=n));return i*=i,e*=e,i?Math.max(e*s*m/i,i/(e*a*m)):1/0}function s(t,e,n,i){var s,a=-1,r=t.length,o=n.x,c=n.y,d=e?l(t.area/e):0;if(e==n.dx){for((i||d>n.dy)&&(d=n.dy);++a<r;)s=t[a],s.x=o,s.y=c,s.dy=d,o+=s.dx=Math.min(n.x+n.dx-o,d?l(s.area/d):0);s.z=!0,s.dx+=n.x+n.dx-o,n.y+=d,n.dy-=d}else{for((i||d>n.dx)&&(d=n.dx);++a<r;)s=t[a],s.x=o,s.y=c,s.dx=d,c+=s.dy=Math.min(n.y+n.dy-c,d?l(s.area/d):0);s.z=!1,s.dy+=n.y+n.dy-c,n.x+=d,n.dx-=d}}function a(i){var s=r||o(i),a=s[0];return a.x=0,a.y=0,a.dx=c[0],a.dy=c[1],r&&o.revalue(a),t([a],a.dx*a.dy/a.value),(r?n:e)(a),u&&(r=s),s}var r,o=qr.layout.hierarchy(),l=Math.round,c=[1,1],d=null,h=Qs,u=!1,p="squarify",m=.5*(1+Math.sqrt(5));return a.size=function(t){return arguments.length?(c=t,a):c},a.padding=function(t){function e(e){var n=t.call(a,e,e.depth);return null==n?Qs(e):ta(e,"number"==typeof n?[n,n,n,n]:n)}function n(e){return ta(e,t)}if(!arguments.length)return d;var i;return h=null==(d=t)?Qs:"function"==(i=typeof t)?e:"number"===i?(t=[t,t,t,t],n):n,a},a.round=function(t){return arguments.length?(l=t?Math.round:Number,a):l!=Number},a.sticky=function(t){return arguments.length?(u=t,r=null,a):u},a.ratio=function(t){return arguments.length?(m=t,a):m},a.mode=function(t){return arguments.length?(p=t+"",a):p},ps(a,o)},qr.random={normal:function(t,e){var n=arguments.length;return 2>n&&(e=1),1>n&&(t=0),function(){var n,i,s;do n=2*Math.random()-1,i=2*Math.random()-1,s=n*n+i*i;while(!s||s>1);return t+e*n*Math.sqrt(-2*Math.log(s)/s)}},logNormal:function(){var t=qr.random.normal.apply(qr,arguments);return function(){return Math.exp(t())}},irwinHall:function(t){return function(){for(var e=0,n=0;t>n;n++)e+=Math.random();return e/t}}},qr.scale={};var dc={floor:fe,ceil:fe};qr.scale.linear=function(){return oa([0,1],[0,1],Ai,!1)};var hc={s:1,g:1,p:1,r:1,e:1};qr.scale.log=function(){return fa(qr.scale.linear().domain([0,1]),10,!0,[1,10])};var uc=qr.format(".0e"),pc={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};qr.scale.pow=function(){return ga(qr.scale.linear(),1,[0,1])},qr.scale.sqrt=function(){return qr.scale.pow().exponent(.5)},qr.scale.ordinal=function(){return ba([],{t:"range",a:[[]]})},qr.scale.category10=function(){return qr.scale.ordinal().range(mc)},qr.scale.category20=function(){return qr.scale.ordinal().range(fc)},qr.scale.category20b=function(){return qr.scale.ordinal().range(gc)},qr.scale.category20c=function(){return qr.scale.ordinal().range(vc)};var mc=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(ae),fc=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(ae),gc=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(ae),vc=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(ae);qr.scale.quantile=function(){return wa([],[])},qr.scale.quantize=function(){return ya(0,1,[0,1])},qr.scale.threshold=function(){return _a([.5],[0,1])},qr.scale.identity=function(){return xa([0,1])},qr.svg={},qr.svg.arc=function(){function t(){var t=e.apply(this,arguments),a=n.apply(this,arguments),r=i.apply(this,arguments)+bc,o=s.apply(this,arguments)+bc,l=(r>o&&(l=r,r=o,o=l),o-r),c=$o>l?"0":"1",d=Math.cos(r),h=Math.sin(r),u=Math.cos(o),p=Math.sin(o);return l>=wc?t?"M0,"+a+"A"+a+","+a+" 0 1,1 0,"+-a+"A"+a+","+a+" 0 1,1 0,"+a+"M0,"+t+"A"+t+","+t+" 0 1,0 0,"+-t+"A"+t+","+t+" 0 1,0 0,"+t+"Z":"M0,"+a+"A"+a+","+a+" 0 1,1 0,"+-a+"A"+a+","+a+" 0 1,1 0,"+a+"Z":t?"M"+a*d+","+a*h+"A"+a+","+a+" 0 "+c+",1 "+a*u+","+a*p+"L"+t*u+","+t*p+"A"+t+","+t+" 0 "+c+",0 "+t*d+","+t*h+"Z":"M"+a*d+","+a*h+"A"+a+","+a+" 0 "+c+",1 "+a*u+","+a*p+"L0,0Z"}var e=ka,n=Ca,i=Sa,s=$a;return t.innerRadius=function(n){return arguments.length?(e=me(n),t):e},t.outerRadius=function(e){return arguments.length?(n=me(e),t):n},t.startAngle=function(e){return arguments.length?(i=me(e),t):i},t.endAngle=function(e){return arguments.length?(s=me(e),t):s},t.centroid=function(){var t=(e.apply(this,arguments)+n.apply(this,arguments))/2,a=(i.apply(this,arguments)+s.apply(this,arguments))/2+bc;return[Math.cos(a)*t,Math.sin(a)*t]},t};var bc=-Po,wc=Mo-Do;qr.svg.line=function(){return Ma(fe)};var yc=qr.map({linear:Pa,"linear-closed":Da,step:Ta,"step-before":Fa,"step-after":Ga,basis:Ia,"basis-open":Ha,"basis-closed":Ua,bundle:za,cardinal:La,"cardinal-open":Aa,"cardinal-closed":Ra,monotone:qa});yc.forEach(function(t,e){e.key=t,e.closed=/-closed$/.test(t)});var _c=[0,2/3,1/3,0],xc=[0,1/3,2/3,0],kc=[0,1/6,2/3,1/6];qr.svg.line.radial=function(){var t=Ma(ja);return t.radius=t.x,delete t.x,t.angle=t.y,delete t.y,t},Fa.reverse=Ga,Ga.reverse=Fa,qr.svg.area=function(){return Ya(fe)},qr.svg.area.radial=function(){var t=Ya(ja);return t.radius=t.x,delete t.x,t.innerRadius=t.x0,delete t.x0,t.outerRadius=t.x1,delete t.x1,t.angle=t.y,delete t.y,t.startAngle=t.y0,delete t.y0,t.endAngle=t.y1,delete t.y1,t},qr.svg.chord=function(){function t(t,o){var l=e(this,a,t,o),c=e(this,r,t,o);return"M"+l.p0+i(l.r,l.p1,l.a1-l.a0)+(n(l,c)?s(l.r,l.p1,l.r,l.p0):s(l.r,l.p1,c.r,c.p0)+i(c.r,c.p1,c.a1-c.a0)+s(c.r,c.p1,l.r,l.p0))+"Z"}function e(t,e,n,i){var s=e.call(t,n,i),a=o.call(t,s,i),r=l.call(t,s,i)+bc,d=c.call(t,s,i)+bc;return{r:a,a0:r,a1:d,p0:[a*Math.cos(r),a*Math.sin(r)],p1:[a*Math.cos(d),a*Math.sin(d)]}}function n(t,e){return t.a0==e.a0&&t.a1==e.a1}function i(t,e,n){return"A"+t+","+t+" 0 "+ +(n>$o)+",1 "+e}function s(t,e,n,i){return"Q 0,0 "+i}var a=Ln,r=Nn,o=Xa,l=Sa,c=$a;return t.radius=function(e){return arguments.length?(o=me(e),t):o},t.source=function(e){return arguments.length?(a=me(e),t):a},t.target=function(e){return arguments.length?(r=me(e),t):r},t.startAngle=function(e){return arguments.length?(l=me(e),t):l},t.endAngle=function(e){return arguments.length?(c=me(e),t):c},t},qr.svg.diagonal=function(){function t(t,s){var a=e.call(this,t,s),r=n.call(this,t,s),o=(a.y+r.y)/2,l=[a,{x:a.x,y:o},{x:r.x,y:o},r];return l=l.map(i),"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var e=Ln,n=Nn,i=Ja;return t.source=function(n){return arguments.length?(e=me(n),t):e},t.target=function(e){return arguments.length?(n=me(e),t):n},t.projection=function(e){return arguments.length?(i=e,t):i},t},qr.svg.diagonal.radial=function(){var t=qr.svg.diagonal(),e=Ja,n=t.projection;return t.projection=function(t){return arguments.length?n(Za(e=t)):e},t},qr.svg.symbol=function(){function t(t,i){return(Cc.get(e.call(this,t,i))||er)(n.call(this,t,i))}var e=tr,n=Qa;return t.type=function(n){return arguments.length?(e=me(n),t):e},t.size=function(e){return arguments.length?(n=me(e),t):n},t};var Cc=qr.map({circle:er,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*Pc)),n=e*Pc;return"M0,"+-e+"L"+n+",0 0,"+e+" "+-n+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/Mc),n=e*Mc/2;return"M0,"+n+"L"+e+","+-n+" "+-e+","+-n+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/Mc),n=e*Mc/2;return"M0,"+-n+"L"+e+","+n+" "+-e+","+n+"Z"}});qr.svg.symbolTypes=Cc.keys();var Sc,$c,Mc=Math.sqrt(3),Pc=Math.tan(30*Fo),Dc=[],Tc=0;Dc.call=bo.call,Dc.empty=bo.empty,Dc.node=bo.node,Dc.size=bo.size,qr.transition=function(t){return arguments.length?Sc?t.transition():t:_o.transition()},qr.transition.prototype=Dc,Dc.select=function(t){var e,n,i,s=this.id,a=[];t=f(t);for(var r=-1,o=this.length;++r<o;){a.push(e=[]);for(var l=this[r],c=-1,d=l.length;++c<d;)(i=l[c])&&(n=t.call(i,i.__data__,c,r))?("__data__"in i&&(n.__data__=i.__data__),ar(n,c,s,i.__transition__[s]),e.push(n)):e.push(null)}return nr(a,s)},Dc.selectAll=function(t){var e,n,i,s,a,r=this.id,o=[];t=g(t);for(var l=-1,c=this.length;++l<c;)for(var d=this[l],h=-1,u=d.length;++h<u;)if(i=d[h]){a=i.__transition__[r],n=t.call(i,i.__data__,h,l),o.push(e=[]);for(var p=-1,m=n.length;++p<m;)(s=n[p])&&ar(s,p,r,a),e.push(s)}return nr(o,r)},Dc.filter=function(t){var e,n,i,s=[];"function"!=typeof t&&(t=$(t));for(var a=0,r=this.length;r>a;a++){s.push(e=[]);for(var n=this[a],o=0,l=n.length;l>o;o++)(i=n[o])&&t.call(i,i.__data__,o,a)&&e.push(i)}return nr(s,this.id)},Dc.tween=function(t,e){var n=this.id;return arguments.length<2?this.node().__transition__[n].tween.get(t):P(this,null==e?function(e){e.__transition__[n].tween.remove(t)}:function(i){i.__transition__[n].tween.set(t,e)})},Dc.attr=function(t,e){function n(){this.removeAttribute(o)}function i(){this.removeAttributeNS(o.space,o.local)}function s(t){return null==t?n:(t+="",function(){var e,n=this.getAttribute(o);return n!==t&&(e=r(n,t),function(t){this.setAttribute(o,e(t))})})}function a(t){return null==t?i:(t+="",function(){var e,n=this.getAttributeNS(o.space,o.local);return n!==t&&(e=r(n,t),function(t){this.setAttributeNS(o.space,o.local,e(t))})})}if(arguments.length<2){for(e in t)this.attr(e,t[e]);return this}var r="transform"==t?ns:Ai,o=qr.ns.qualify(t);return ir(this,"attr."+t,e,o.local?a:s)},Dc.attrTween=function(t,e){function n(t,n){var i=e.call(this,t,n,this.getAttribute(s));return i&&function(t){this.setAttribute(s,i(t))}}function i(t,n){var i=e.call(this,t,n,this.getAttributeNS(s.space,s.local));return i&&function(t){this.setAttributeNS(s.space,s.local,i(t))}}var s=qr.ns.qualify(t);return this.tween("attr."+t,s.local?i:n)},Dc.style=function(t,e,n){function i(){this.style.removeProperty(t)}function s(e){return null==e?i:(e+="",function(){var i,s=Zr.getComputedStyle(this,null).getPropertyValue(t);return s!==e&&(i=Ai(s,e),function(e){this.style.setProperty(t,i(e),n)})})}var a=arguments.length;if(3>a){if("string"!=typeof t){2>a&&(e="");for(n in t)this.style(n,t[n],e);return this}n=""}return ir(this,"style."+t,e,s)},Dc.styleTween=function(t,e,n){function i(i,s){var a=e.call(this,i,s,Zr.getComputedStyle(this,null).getPropertyValue(t));return a&&function(e){this.style.setProperty(t,a(e),n)}}return arguments.length<3&&(n=""),this.tween("style."+t,i)},Dc.text=function(t){return ir(this,"text",t,sr)},Dc.remove=function(){return this.each("end.transition",function(){var t;this.__transition__.count<2&&(t=this.parentNode)&&t.removeChild(this)})},Dc.ease=function(t){var e=this.id;return arguments.length<1?this.node().__transition__[e].ease:("function"!=typeof t&&(t=qr.ease.apply(qr,arguments)),P(this,function(n){n.__transition__[e].ease=t}))},Dc.delay=function(t){var e=this.id;return P(this,"function"==typeof t?function(n,i,s){n.__transition__[e].delay=+t.call(n,n.__data__,i,s)}:(t=+t,function(n){n.__transition__[e].delay=t}))},Dc.duration=function(t){var e=this.id;return P(this,"function"==typeof t?function(n,i,s){n.__transition__[e].duration=Math.max(1,t.call(n,n.__data__,i,s))}:(t=Math.max(1,t),function(n){n.__transition__[e].duration=t}))},Dc.each=function(t,e){var n=this.id;if(arguments.length<2){var i=$c,s=Sc;Sc=n,P(this,function(e,i,s){$c=e.__transition__[n],t.call(e,e.__data__,i,s)}),$c=i,Sc=s}else P(this,function(i){var s=i.__transition__[n];(s.event||(s.event=qr.dispatch("start","end"))).on(t,e)});return this},Dc.transition=function(){for(var t,e,n,i,s=this.id,a=++Tc,r=[],o=0,l=this.length;l>o;o++){r.push(t=[]);for(var e=this[o],c=0,d=e.length;d>c;c++)(n=e[c])&&(i=Object.create(n.__transition__[s]),i.delay+=i.duration,ar(n,c,a,i)),t.push(n)}return nr(r,a)},qr.svg.axis=function(){function t(t){t.each(function(){var t,c=qr.select(this),d=this.__chart__||n,h=this.__chart__=n.copy(),u=null==l?h.ticks?h.ticks.apply(h,o):h.domain():l,p=null==e?h.tickFormat?h.tickFormat.apply(h,o):fe:e,m=c.selectAll(".tick").data(u,h),f=m.enter().insert("g",".domain").attr("class","tick").style("opacity",Do),g=qr.transition(m.exit()).style("opacity",Do).remove(),v=qr.transition(m).style("opacity",1),b=na(h),w=c.selectAll(".domain").data([0]),y=(w.enter().append("path").attr("class","domain"),qr.transition(w));f.append("line"),f.append("text");var _=f.select("line"),x=v.select("line"),k=m.select("text").text(p),C=f.select("text"),S=v.select("text");switch(i){case"bottom":t=rr,_.attr("y2",s),C.attr("y",Math.max(s,0)+r),x.attr("x2",0).attr("y2",s),S.attr("x",0).attr("y",Math.max(s,0)+r),k.attr("dy",".71em").style("text-anchor","middle"),y.attr("d","M"+b[0]+","+a+"V0H"+b[1]+"V"+a);break;case"top":t=rr,_.attr("y2",-s),C.attr("y",-(Math.max(s,0)+r)),x.attr("x2",0).attr("y2",-s),S.attr("x",0).attr("y",-(Math.max(s,0)+r)),k.attr("dy","0em").style("text-anchor","middle"),y.attr("d","M"+b[0]+","+-a+"V0H"+b[1]+"V"+-a);break;case"left":t=or,_.attr("x2",-s),C.attr("x",-(Math.max(s,0)+r)),x.attr("x2",-s).attr("y2",0),S.attr("x",-(Math.max(s,0)+r)).attr("y",0),k.attr("dy",".32em").style("text-anchor","end"),y.attr("d","M"+-a+","+b[0]+"H0V"+b[1]+"H"+-a);break;case"right":t=or,_.attr("x2",s),C.attr("x",Math.max(s,0)+r),x.attr("x2",s).attr("y2",0),S.attr("x",Math.max(s,0)+r).attr("y",0),k.attr("dy",".32em").style("text-anchor","start"),y.attr("d","M"+a+","+b[0]+"H0V"+b[1]+"H"+a)}if(h.rangeBand){var $=h,M=$.rangeBand()/2;d=h=function(t){return $(t)+M}}else d.rangeBand?d=h:g.call(t,h);f.call(t,d),v.call(t,h)})}var e,n=qr.scale.linear(),i=Fc,s=6,a=6,r=3,o=[10],l=null;return t.scale=function(e){return arguments.length?(n=e,t):n},t.orient=function(e){return arguments.length?(i=e in Gc?e+"":Fc,t):i},t.ticks=function(){return arguments.length?(o=arguments,t):o},t.tickValues=function(e){return arguments.length?(l=e,t):l},t.tickFormat=function(n){return arguments.length?(e=n,t):e},t.tickSize=function(e){var n=arguments.length;return n?(s=+e,a=+arguments[n-1],t):s},t.innerTickSize=function(e){return arguments.length?(s=+e,t):s},t.outerTickSize=function(e){return arguments.length?(a=+e,t):a},t.tickPadding=function(e){return arguments.length?(r=+e,t):r},t.tickSubdivide=function(){return arguments.length&&t},t};var Fc="bottom",Gc={top:1,right:1,bottom:1,left:1};qr.svg.brush=function(){function t(a){a.each(function(){var a=qr.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",s).on("touchstart.brush",s),r=a.selectAll(".background").data([0]);r.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),a.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var o=a.selectAll(".resize").data(g,fe);o.exit().remove(),o.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Ac[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),o.style("display",t.empty()?"none":null);var d,h=qr.transition(a),u=qr.transition(r);l&&(d=na(l),u.attr("x",d[0]).attr("width",d[1]-d[0]),n(h)),c&&(d=na(c),u.attr("y",d[0]).attr("height",d[1]-d[0]),i(h)),e(h)})}function e(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+d[+/e$/.test(t)]+","+u[+/^s/.test(t)]+")"})}function n(t){t.select(".extent").attr("x",d[0]),t.selectAll(".extent,.n>rect,.s>rect").attr("width",d[1]-d[0])}function i(t){t.select(".extent").attr("y",u[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",u[1]-u[0])}function s(){function s(){32==qr.event.keyCode&&(P||(w=null,T[0]-=d[1],T[1]-=u[1],P=2),h())}function p(){32==qr.event.keyCode&&2==P&&(T[0]+=d[1],T[1]+=u[1],P=0,h())}function g(){var t=qr.mouse(_),s=!1;y&&(t[0]+=y[0],t[1]+=y[1]),P||(qr.event.altKey?(w||(w=[(d[0]+d[1])/2,(u[0]+u[1])/2]),T[0]=d[+(t[0]<w[0])],T[1]=u[+(t[1]<w[1])]):w=null),$&&v(t,l,0)&&(n(C),s=!0),M&&v(t,c,1)&&(i(C),s=!0),s&&(e(C),k({type:"brush",mode:P?"move":"resize"}))}function v(t,e,n){var i,s,o=na(e),l=o[0],c=o[1],h=T[n],p=n?u:d,g=p[1]-p[0];return P&&(l-=h,c-=g+h),i=(n?f:m)?Math.max(l,Math.min(c,t[n])):t[n],P?s=(i+=h)+g:(w&&(h=Math.max(l,Math.min(c,2*w[n]-i))),i>h?(s=i,i=h):s=h),p[0]!=i||p[1]!=s?(n?r=null:a=null,p[0]=i,p[1]=s,!0):void 0}function b(){g(),C.style("pointer-events","all").selectAll(".resize").style("display",t.empty()?"none":null),qr.select("body").style("cursor",null),F.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),D(),k({type:"brushend"})}var w,y,_=this,x=qr.select(qr.event.target),k=o.of(_,arguments),C=qr.select(_),S=x.datum(),$=!/^(n|s)$/.test(S)&&l,M=!/^(e|w)$/.test(S)&&c,P=x.classed("extent"),D=L(),T=qr.mouse(_),F=qr.select(Zr).on("keydown.brush",s).on("keyup.brush",p);if(qr.event.changedTouches?F.on("touchmove.brush",g).on("touchend.brush",b):F.on("mousemove.brush",g).on("mouseup.brush",b),C.interrupt().selectAll("*").interrupt(),P)T[0]=d[0]-T[0],T[1]=u[0]-T[1];else if(S){var G=+/w$/.test(S),A=+/^n/.test(S);y=[d[1-G]-T[0],u[1-A]-T[1]],T[0]=d[G],T[1]=u[A]}else qr.event.altKey&&(w=T.slice());C.style("pointer-events","none").selectAll(".resize").style("display",null),qr.select("body").style("cursor",x.style("cursor")),k({type:"brushstart"}),g()}var a,r,o=p(t,"brushstart","brush","brushend"),l=null,c=null,d=[0,0],u=[0,0],m=!0,f=!0,g=Rc[0];return t.event=function(t){t.each(function(){var t=o.of(this,arguments),e={x:d,y:u,i:a,j:r},n=this.__chart__||e;this.__chart__=e,Sc?qr.select(this).transition().each("start.brush",function(){a=n.i,r=n.j,d=n.x,u=n.y,t({type:"brushstart"})}).tween("brush:brush",function(){var n=Ri(d,e.x),i=Ri(u,e.y);return a=r=null,function(s){d=e.x=n(s),u=e.y=i(s),t({type:"brush",mode:"resize"})}}).each("end.brush",function(){a=e.i,r=e.j,t({type:"brush",mode:"resize"}),t({type:"brushend"})}):(t({type:"brushstart"}),t({type:"brush",mode:"resize"}),t({type:"brushend"}))})},t.x=function(e){return arguments.length?(l=e,g=Rc[!l<<1|!c],t):l},t.y=function(e){return arguments.length?(c=e,g=Rc[!l<<1|!c],t):c},t.clamp=function(e){return arguments.length?(l&&c?(m=!!e[0],f=!!e[1]):l?m=!!e:c&&(f=!!e),t):l&&c?[m,f]:l?m:c?f:null},t.extent=function(e){var n,i,s,o,h;return arguments.length?(l&&(n=e[0],i=e[1],c&&(n=n[0],i=i[0]),a=[n,i],l.invert&&(n=l(n),i=l(i)),n>i&&(h=n,n=i,i=h),(n!=d[0]||i!=d[1])&&(d=[n,i])),c&&(s=e[0],o=e[1],l&&(s=s[1],o=o[1]),r=[s,o],c.invert&&(s=c(s),o=c(o)),s>o&&(h=s,s=o,o=h),(s!=u[0]||o!=u[1])&&(u=[s,o])),t):(l&&(a?(n=a[0],i=a[1]):(n=d[0],i=d[1],l.invert&&(n=l.invert(n),i=l.invert(i)),n>i&&(h=n,n=i,i=h))),c&&(r?(s=r[0],o=r[1]):(s=u[0],o=u[1],c.invert&&(s=c.invert(s),o=c.invert(o)),s>o&&(h=s,s=o,o=h))),l&&c?[[n,s],[i,o]]:l?[n,i]:c&&[s,o])},t.clear=function(){return t.empty()||(d=[0,0],u=[0,0],a=r=null),t},t.empty=function(){return!!l&&d[0]==d[1]||!!c&&u[0]==u[1]},qr.rebind(t,o,"on")};var Ac={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Rc=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Lc=qr.time={},Nc=Date,Ec=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];lr.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(){Ic.setUTCDate.apply(this._,arguments)},setDay:function(){Ic.setUTCDay.apply(this._,arguments)},setFullYear:function(){Ic.setUTCFullYear.apply(this._,arguments)},setHours:function(){Ic.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Ic.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Ic.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Ic.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Ic.setUTCSeconds.apply(this._,arguments)},setTime:function(){Ic.setTime.apply(this._,arguments)}};var Ic=Date.prototype,Hc="%a %b %e %X %Y",Uc="%m/%d/%Y",zc="%H:%M:%S",Oc=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Vc=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Bc=["January","February","March","April","May","June","July","August","September","October","November","December"],Kc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];Lc.year=cr(function(t){return t=Lc.day(t),t.setMonth(0,1),t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()}),Lc.years=Lc.year.range,Lc.years.utc=Lc.year.utc.range,Lc.day=cr(function(t){var e=new Nc(2e3,0);return e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1}),Lc.days=Lc.day.range,Lc.days.utc=Lc.day.utc.range,Lc.dayOfYear=function(t){var e=Lc.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)},Ec.forEach(function(t,e){t=t.toLowerCase(),e=7-e;var n=Lc[t]=cr(function(t){return(t=Lc.day(t)).setDate(t.getDate()-(t.getDay()+e)%7),t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var n=Lc.year(t).getDay();return Math.floor((Lc.dayOfYear(t)+(n+e)%7)/7)-(n!==e)});Lc[t+"s"]=n.range,Lc[t+"s"].utc=n.utc.range,Lc[t+"OfYear"]=function(t){var n=Lc.year(t).getDay();return Math.floor((Lc.dayOfYear(t)+(n+e)%7)/7)}}),Lc.week=Lc.sunday,Lc.weeks=Lc.sunday.range,Lc.weeks.utc=Lc.sunday.utc.range,Lc.weekOfYear=Lc.sundayOfYear,Lc.format=hr;var Wc=pr(Oc),qc=mr(Oc),jc=pr(Vc),Yc=mr(Vc),Xc=pr(Bc),Jc=mr(Bc),Zc=pr(Kc),Qc=mr(Kc),td=/^%/,ed={"-":"",_:" ",0:"0"},nd={a:function(t){return Vc[t.getDay()]},A:function(t){return Oc[t.getDay()]},b:function(t){return Kc[t.getMonth()]},B:function(t){return Bc[t.getMonth()]},c:hr(Hc),d:function(t,e){return fr(t.getDate(),e,2)},e:function(t,e){return fr(t.getDate(),e,2)},H:function(t,e){return fr(t.getHours(),e,2)},I:function(t,e){return fr(t.getHours()%12||12,e,2)},j:function(t,e){return fr(1+Lc.dayOfYear(t),e,3)},L:function(t,e){return fr(t.getMilliseconds(),e,3)},m:function(t,e){return fr(t.getMonth()+1,e,2)},M:function(t,e){return fr(t.getMinutes(),e,2)},p:function(t){return t.getHours()>=12?"PM":"AM"},S:function(t,e){return fr(t.getSeconds(),e,2)},U:function(t,e){return fr(Lc.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return fr(Lc.mondayOfYear(t),e,2)},x:hr(Uc),X:hr(zc),y:function(t,e){return fr(t.getFullYear()%100,e,2)},Y:function(t,e){return fr(t.getFullYear()%1e4,e,4)},Z:Ir,"%":function(){return"%"}},id={a:gr,A:vr,b:_r,B:xr,c:kr,d:Fr,e:Fr,H:Ar,I:Ar,j:Gr,L:Nr,m:Tr,M:Rr,p:Er,S:Lr,U:wr,w:br,W:yr,x:Cr,X:Sr,y:Mr,Y:$r,Z:Pr,"%":Hr},sd=/^\s*\d+/,ad=qr.map({am:0,pm:1});hr.utc=Ur;var rd=Ur("%Y-%m-%dT%H:%M:%S.%LZ");hr.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?zr:rd,zr.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},zr.toString=rd.toString,Lc.second=cr(function(t){return new Nc(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),Lc.seconds=Lc.second.range,Lc.seconds.utc=Lc.second.utc.range,Lc.minute=cr(function(t){return new Nc(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),Lc.minutes=Lc.minute.range,Lc.minutes.utc=Lc.minute.utc.range,Lc.hour=cr(function(t){var e=t.getTimezoneOffset()/60;return new Nc(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),Lc.hours=Lc.hour.range,Lc.hours.utc=Lc.hour.utc.range,Lc.month=cr(function(t){return t=Lc.day(t),t.setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),Lc.months=Lc.month.range,Lc.months.utc=Lc.month.utc.range;var od=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],ld=[[Lc.second,1],[Lc.second,5],[Lc.second,15],[Lc.second,30],[Lc.minute,1],[Lc.minute,5],[Lc.minute,15],[Lc.minute,30],[Lc.hour,1],[Lc.hour,3],[Lc.hour,6],[Lc.hour,12],[Lc.day,1],[Lc.day,2],[Lc.week,1],[Lc.month,1],[Lc.month,3],[Lc.year,1]],cd=[[hr("%Y"),Be],[hr("%B"),function(t){return t.getMonth()}],[hr("%b %d"),function(t){return 1!=t.getDate()}],[hr("%a %d"),function(t){return t.getDay()&&1!=t.getDate()}],[hr("%I %p"),function(t){return t.getHours()}],[hr("%I:%M"),function(t){return t.getMinutes()}],[hr(":%S"),function(t){return t.getSeconds()}],[hr(".%L"),function(t){return t.getMilliseconds()}]],dd=Br(cd);ld.year=Lc.year,Lc.scale=function(){return Or(qr.scale.linear(),ld,dd)};var hd={range:function(t,e,n){return qr.range(+t,+e,n).map(Vr)}},ud=ld.map(function(t){return[t[0].utc,t[1]]}),pd=[[Ur("%Y"),Be],[Ur("%B"),function(t){return t.getUTCMonth()}],[Ur("%b %d"),function(t){return 1!=t.getUTCDate()}],[Ur("%a %d"),function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],[Ur("%I %p"),function(t){return t.getUTCHours()}],[Ur("%I:%M"),function(t){return t.getUTCMinutes()}],[Ur(":%S"),function(t){return t.getUTCSeconds()}],[Ur(".%L"),function(t){return t.getUTCMilliseconds()}]],md=Br(pd);return ud.year=Lc.year.utc,Lc.scale.utc=function(){return Or(qr.scale.linear(),ud,md)},qr.text=ge(function(t){return t.responseText}),qr.json=function(t,e){return ve(t,"application/json",Kr,e)},qr.html=function(t,e){return ve(t,"text/html",Wr,e)},qr.xml=ge(function(t){return t.responseXML}),qr}(),define("libs/d3",function(t){return function(){var e;return e||t.d3}}(this)),define("unifi/view/map/MarkerRfMapView",["backbone","underscore","jquery","libs/d3","msg/Msg"],function(t,e,n,i){"use strict";return t.View.extend({rfMapBorderData:{normalCircle:{cx:75,cy:75,r:65,fill:"none",stroke:"rgba(50,110,140,1)","stroke-width":2},warningPath:{data1:{fill:"none",stroke:"#FBE800","stroke-width":2,"stroke-miterlimit":10,d:"M592,306.9c0,1.6-4.6,3-4.7,4.5c-0.1,1.5,4.4,3.5,4.2,5c-0.2,1.5-4.9,2.5-5.2,4c-0.2,1.5,4,3.9,3.6,5.4c-0.3,1.5-5.1,1.9-5.6,3.4c-0.4,1.5,3.5,4.3,3,5.8c-0.5,1.5-5.3,1.3-5.9,2.8c-0.6,1.4,3,4.7,2.4,6.1c-0.7,1.4-5.4,0.7-6.2,2.1c-0.7,1.4,2.5,5,1.7,6.3c-0.8,1.3-5.5,0.2-6.3,1.4c-0.9,1.3,1.9,5.2,1,6.4c-0.9,1.2-5.5-0.4-6.5,0.7c-1,1.2,1.4,5.4,0.3,6.5c-1.1,1.1-5.4-1-6.5,0c-1.1,1.1,0.8,5.5-0.4,6.5c-1.2,1-5.2-1.6-6.5-0.7c-1.2,0.9,0.2,5.5-1.1,6.4c-1.3,0.9-5-2.2-6.4-1.4c-1.3,0.8-0.4,5.5-1.8,6.3c-1.4,0.7-4.8-2.7-6.2-2c-1.4,0.6-1,5.5-2.4,6c-1.4,0.6-4.5-3.2-5.9-2.7c-1.5,0.5-1.6,5.3-3.1,5.7c-1.5,0.4-4.1-3.7-5.6-3.3c-1.5,0.3-2.2,5.1-3.7,5.4c-1.5,0.2-3.7-4.1-5.2-3.9c-1.5,0.2-2.7,4.8-4.2,4.9c-1.5,0.1-3.2-4.4-4.7-4.4c-1.6,0-3.2,4.5-4.7,4.4c-1.5-0.1-2.7-4.8-4.2-4.9c-1.5-0.2-3.7,4.2-5.2,3.9c-1.5-0.2-2.2-5-3.7-5.4c-1.5-0.3-4.1,3.7-5.6,3.3c-1.5-0.4-1.6-5.2-3.1-5.7c-1.5-0.5-4.5,3.3-5.9,2.7c-1.4-0.6-1-5.4-2.4-6c-1.4-0.7-4.8,2.8-6.2,2c-1.4-0.7-0.5-5.5-1.8-6.3c-1.3-0.8-5.1,2.2-6.4,1.4c-1.3-0.9,0.1-5.5-1.1-6.4c-1.2-0.9-5.3,1.7-6.5,0.7c-1.2-1,0.7-5.4-0.4-6.5c-1.1-1.1-5.4,1.1-6.5,0c-1.1-1.1,1.3-5.3,0.3-6.5c-1-1.2-5.5,0.5-6.5-0.7c-0.9-1.2,1.9-5.1,1-6.4c-0.9-1.3-5.5-0.1-6.3-1.4c-0.8-1.3,2.4-4.9,1.7-6.3c-0.7-1.4-5.5-0.7-6.2-2.1c-0.6-1.4,2.9-4.6,2.4-6.1c-0.6-1.4-5.4-1.3-5.9-2.8c-0.5-1.5,3.4-4.3,3-5.8c-0.4-1.5-5.2-1.9-5.6-3.4c-0.3-1.5,3.9-3.9,3.6-5.4c-0.2-1.5-5-2.4-5.2-4c-0.2-1.5,4.3-3.4,4.2-5c-0.1-1.5-4.7-3-4.7-4.5s4.6-3,4.7-4.5c0.1-1.5-4.4-3.5-4.2-5c0.2-1.5,4.9-2.5,5.2-4c0.2-1.5-4-3.9-3.6-5.4c0.3-1.5,5.1-1.9,5.6-3.4c0.4-1.5-3.5-4.3-3-5.8c0.5-1.5,5.3-1.3,5.9-2.8c0.6-1.4-3-4.7-2.4-6.1c0.6-1.4,5.4-0.7,6.2-2.1c0.7-1.4-2.5-5-1.7-6.3c0.8-1.3,5.5-0.2,6.3-1.4c0.9-1.3-1.9-5.2-1-6.4c0.9-1.2,5.5,0.4,6.5-0.7c1-1.2-1.4-5.4-0.3-6.5c1.1-1.1,5.4,1,6.5,0c1.1-1.1-0.8-5.5,0.4-6.5c1.2-1,5.2,1.6,6.5,0.7c1.2-0.9-0.2-5.5,1.1-6.4c1.3-0.9,5,2.2,6.4,1.4c1.3-0.8,0.4-5.5,1.8-6.3c1.4-0.7,4.8,2.7,6.2,2c1.4-0.6,1-5.5,2.4-6c1.4-0.6,4.5,3.2,5.9,2.7c1.5-0.5,1.6-5.3,3.1-5.7c1.5-0.4,4.1,3.7,5.6,3.3c1.5-0.3,2.2-5.1,3.7-5.4c1.5-0.2,3.7,4.1,5.2,3.9c1.5-0.2,2.7-4.8,4.2-4.9c1.5-0.1,3.2,4.4,4.7,4.4s3.2-4.5,4.7-4.4c1.5,0.1,2.7,4.8,4.2,4.9c1.5,0.2,3.7-4.2,5.2-3.9c1.5,0.2,2.2,5,3.7,5.4c1.5,0.3,4.1-3.7,5.6-3.3c1.5,0.4,1.6,5.2,3.1,5.7c1.5,0.5,4.5-3.3,5.9-2.7c1.4,0.6,1,5.4,2.4,6c1.4,0.7,4.8-2.8,6.2-2c1.4,0.7,0.5,5.5,1.8,6.3c1.3,0.8,5.1-2.2,6.4-1.4c1.3,0.9-0.1,5.5,1.1,6.4c1.2,0.9,5.3-1.7,6.5-0.7c1.2,1-0.7,5.4,0.4,6.5c1.1,1.1,5.4-1.1,6.5,0c1.1,1.1-1.3,5.3-0.3,6.5c1,1.2,5.5-0.5,6.5,0.7c0.9,1.2-1.9,5.1-1,6.4c0.9,1.3,5.5,0.1,6.3,1.4c0.8,1.3-2.4,4.9-1.7,6.3c0.7,1.4,5.5,0.7,6.2,2.1c0.6,1.4-2.9,4.6-2.4,6.1c0.6,1.4,5.4,1.3,5.9,2.8c0.5,1.5-3.4,4.3-3,5.8c0.4,1.5,5.2,1.9,5.6,3.4c0.3,1.5-3.9,3.9-3.6,5.4c0.2,1.5,5,2.4,5.2,4c0.2,1.5-4.3,3.4-4.2,5C587.4,304,592,305.4,592,306.9z",transform:"translate(-304,-156) scale(0.75)"},data2:{fill:"none",stroke:"#FBE800","stroke-width":2,"stroke-miterlimit":10,d:"M592,306.9c0,1.6-4.6,3-4.7,4.5c-0.1,1.5,4.4,3.5,4.2,5c-0.2,1.5-4.9,2.5-5.2,4c-0.2,1.5,4,3.9,3.6,5.4c-0.3,1.5-5.1,1.9-5.6,3.4c-0.4,1.5,3.5,4.3,3,5.8c-0.5,1.5-5.3,1.3-5.9,2.8c-0.6,1.4,3,4.7,2.4,6.1c-0.7,1.4-5.4,0.7-6.2,2.1c-0.7,1.4,2.5,5,1.7,6.3c-0.8,1.3-5.5,0.2-6.3,1.4c-0.9,1.3,1.9,5.2,1,6.4c-0.9,1.2-5.5-0.4-6.5,0.7c-1,1.2,1.4,5.4,0.3,6.5c-1.1,1.1-5.4-1-6.5,0c-1.1,1.1,0.8,5.5-0.4,6.5c-1.2,1-5.2-1.6-6.5-0.7c-1.2,0.9,0.2,5.5-1.1,6.4c-1.3,0.9-5-2.2-6.4-1.4c-1.3,0.8-0.4,5.5-1.8,6.3c-1.4,0.7-4.8-2.7-6.2-2c-1.4,0.6-1,5.5-2.4,6c-1.4,0.6-4.5-3.2-5.9-2.7c-1.5,0.5-1.6,5.3-3.1,5.7c-1.5,0.4-4.1-3.7-5.6-3.3c-1.5,0.3-2.2,5.1-3.7,5.4c-1.5,0.2-3.7-4.1-5.2-3.9c-1.5,0.2-2.7,4.8-4.2,4.9c-1.5,0.1-3.2-4.4-4.7-4.4c-1.6,0-3.2,4.5-4.7,4.4c-1.5-0.1-2.7-4.8-4.2-4.9c-1.5-0.2-3.7,4.2-5.2,3.9c-1.5-0.2-2.2-5-3.7-5.4c-1.5-0.3-4.1,3.7-5.6,3.3c-1.5-0.4-1.6-5.2-3.1-5.7c-1.5-0.5-4.5,3.3-5.9,2.7c-1.4-0.6-1-5.4-2.4-6c-1.4-0.7-4.8,2.8-6.2,2c-1.4-0.7-0.5-5.5-1.8-6.3c-1.3-0.8-5.1,2.2-6.4,1.4c-1.3-0.9,0.1-5.5-1.1-6.4c-1.2-0.9-5.3,1.7-6.5,0.7c-1.2-1,0.7-5.4-0.4-6.5c-1.1-1.1-5.4,1.1-6.5,0c-1.1-1.1,1.3-5.3,0.3-6.5c-1-1.2-5.5,0.5-6.5-0.7c-0.9-1.2,1.9-5.1,1-6.4c-0.9-1.3-5.5-0.1-6.3-1.4c-0.8-1.3,2.4-4.9,1.7-6.3c-0.7-1.4-5.5-0.7-6.2-2.1c-0.6-1.4,2.9-4.6,2.4-6.1c-0.6-1.4-5.4-1.3-5.9-2.8c-0.5-1.5,3.4-4.3,3-5.8c-0.4-1.5-5.2-1.9-5.6-3.4c-0.3-1.5,3.9-3.9,3.6-5.4c-0.2-1.5-5-2.4-5.2-4c-0.2-1.5,4.3-3.4,4.2-5c-0.1-1.5-4.7-3-4.7-4.5s4.6-3,4.7-4.5c0.1-1.5-4.4-3.5-4.2-5c0.2-1.5,4.9-2.5,5.2-4c0.2-1.5-4-3.9-3.6-5.4c0.3-1.5,5.1-1.9,5.6-3.4c0.4-1.5-3.5-4.3-3-5.8c0.5-1.5,5.3-1.3,5.9-2.8c0.6-1.4-3-4.7-2.4-6.1c0.6-1.4,5.4-0.7,6.2-2.1c0.7-1.4-2.5-5-1.7-6.3c0.8-1.3,5.5-0.2,6.3-1.4c0.9-1.3-1.9-5.2-1-6.4c0.9-1.2,5.5,0.4,6.5-0.7c1-1.2-1.4-5.4-0.3-6.5c1.1-1.1,5.4,1,6.5,0c1.1-1.1-0.8-5.5,0.4-6.5c1.2-1,5.2,1.6,6.5,0.7c1.2-0.9-0.2-5.5,1.1-6.4c1.3-0.9,5,2.2,6.4,1.4c1.3-0.8,0.4-5.5,1.8-6.3c1.4-0.7,4.8,2.7,6.2,2c1.4-0.6,1-5.5,2.4-6c1.4-0.6,4.5,3.2,5.9,2.7c1.5-0.5,1.6-5.3,3.1-5.7c1.5-0.4,4.1,3.7,5.6,3.3c1.5-0.3,2.2-5.1,3.7-5.4c1.5-0.2,3.7,4.1,5.2,3.9c1.5-0.2,2.7-4.8,4.2-4.9c1.5-0.1,3.2,4.4,4.7,4.4s3.2-4.5,4.7-4.4c1.5,0.1,2.7,4.8,4.2,4.9c1.5,0.2,3.7-4.2,5.2-3.9c1.5,0.2,2.2,5,3.7,5.4c1.5,0.3,4.1-3.7,5.6-3.3c1.5,0.4,1.6,5.2,3.1,5.7c1.5,0.5,4.5-3.3,5.9-2.7c1.4,0.6,1,5.4,2.4,6c1.4,0.7,4.8-2.8,6.2-2c1.4,0.7,0.5,5.5,1.8,6.3c1.3,0.8,5.1-2.2,6.4-1.4c1.3,0.9-0.1,5.5,1.1,6.4c1.2,0.9,5.3-1.7,6.5-0.7c1.2,1-0.7,5.4,0.4,6.5c1.1,1.1,5.4-1.1,6.5,0c1.1,1.1-1.3,5.3-0.3,6.5c1,1.2,5.5-0.5,6.5,0.7c0.9,1.2-1.9,5.1-1,6.4c0.9,1.3,5.5,0.1,6.3,1.4c0.8,1.3-2.4,4.9-1.7,6.3c0.7,1.4,5.5,0.7,6.2,2.1c0.6,1.4-2.9,4.6-2.4,6.1c0.6,1.4,5.4,1.3,5.9,2.8c0.5,1.5-3.4,4.3-3,5.8c0.4,1.5,5.2,1.9,5.6,3.4Ic0.3,1.5-3.9,3.9-3.6,5.4c0.2,1.5,5,2.4,5.2,4c0.2,1.5-4.3,3.4-4.2,5C587.4,304,592,305.4,592,306.9z",transform:"translate(-304,-156) scale(0.75)"}},dangerPolygon:{data1:{fill:"none",stroke:"#ED2224","stroke-width":2,"stroke-miterlimit":10,points:"591.4,308.6 595.2,311.8 589.4,314.6 592.1,317.9 589.3,320.7 594.2,324.6 595.2,328.2 593.3,331.1 587.7,332.8 586.8,335.8 587.1,339.1 582.6,340.7 581.7,343.5 581.8,346.9 577.7,348.2 582.5,354.4 577.8,355.3 580.5,360.9 575.9,361.5 576.5,366.1 572.8,367.2 570,368.9 565.1,368.5 563,370.7 560.4,372.4 557.9,374.1 557.8,378.9 554.4,379.5 552.7,382.5 549.4,383.1 548.2,387.3 545,388.1 541.3,387.8 539.5,391.4 536.5,392.7 533.7,394.4 529,389.6 526.4,391.8 524.3,396.6 520,390.8 517.8,396.6 514.4,394.9 511.8,401.2 508.4,398.7 505.2,400.1 502.1,393.9 498.8,397.3 495.8,395.1 493.4,390.6 490.1,392.1 487,392.1 484.2,390.8 480.5,392.4 476.5,394.5 474,392.2 470.4,392.4 466.7,392.8 463.9,391 460.8,389.8 458.9,386.6 455.8,385.4 453.5,382.9 454.8,375.8 450.3,376.6 445.1,377.9 442.2,376.2 442.6,371.1 441.1,368.2 441.8,363.5 439.4,361.5 432.7,362.8 435.9,356.7 428.4,357.9 428.4,354.1 427.3,351.1 426.4,348 428.8,343.4 428.9,340.1 420.2,340.2 418.2,337.5 416,334.7 422.8,329.6 420.3,327 419.1,324.1 413.6,321.7 412.8,318.5 416.9,314.9 419.3,311.6 420.4,308.6 419.2,305.5 420,302.5 422.8,299.7 417.2,295.9 423.2,293.8 422.1,290.5 422.7,287.5 417.3,282.8 425.6,282.1 422.9,277.9 423.7,274.8 421.3,270.3 428.2,270 429.6,267.3 433.7,266.1 430.3,260.4 435.8,260.4 432.8,254.4 440.7,256.6 439.5,251.7 439.9,247.8 441.9,245.3 446.8,245.9 447.3,241.8 447.7,237.3 453.1,239.1 452.2,232.4 458.3,235.7 458.7,230.3 464.1,233.3 465.4,229.1 470,231.6 472,228.4 475.6,229.3 477.2,224.5 481.5,228 483.3,223 486.1,221 489.7,223 492.2,218.2 495.7,220.9 498.7,218.5 501.9,218.4 505.2,223.9 508.5,216.2 511.6,218.2 514.2,224.3 518.2,217.8 521.4,218.3 523.7,223.6 527.3,222 531.1,220.2 532.9,225.2 535.9,226.2 538.3,228.6 540.8,230.5 545.6,227.9 546,233.7 547.3,237.6 554.5,231.9 558,232.5 555.9,240.8 562.1,237.9 562.3,242.6 566.9,242.2 570.6,243.1 571.6,246.7 571.8,250.9 574.4,252.7 572.7,258 580.6,256.2 579.4,260.9 577.3,265.8 577.9,268.8 586.5,267.8 584.3,272.4 584.5,275.7 586.6,278.2 588.4,280.8 592.1,283 587.2,287.6 587.4,290.7 593.7,292.6 593.3,295.9 588.1,299.6 593.1,302.3 590,305.5",transform:"translate(-304,-157) scale(0.75)"},data2:{fill:"none",stroke:"#ED2224","stroke-width":1.2,"stroke-miterlimit":10,points:"458.4,379.7 453.1,381.9 452.4,377.5 447.8,378.2 449.8,371.1 442.7,374.2 441.8,370.6 444.1,364.2 435,368.1 433.9,364.7 436.9,358.5 433,357.6 427.2,357.5 426,354.4 426.7,350.3 425,347.6 423.1,345 423.4,341.4 423,338.2 422.6,335.1 422.2,332 419.6,329.4 420.4,326.1 420.1,323 418.3,320.1 416.9,317.1 412.7,314.2 419,310.7 422,307.7 416.5,304.5 422.4,301.8 423.1,298.9 421.7,295.7 416.9,291.7 415.2,288 418.4,285.4 418.9,282.3 423.8,280.5 425,277.7 421,272.7 429.9,273.3 430.4,270.2 425.4,263.9 434.7,265.8 431.4,260.1 432.2,256.8 432.3,252.8 437.5,252.8 440.9,251.7 440.7,247.3 444.6,246.7 448,245.8 446.3,239.2 448.5,236.8 451.3,235.1 456.4,236.7 457.5,232.7 460,230.5 464.3,231.8 466.3,228.9 469.3,227.9 470.9,223.3 476.2,228.3 479.7,229.2 482.3,227.7 484.9,225.4 488,225.6 489.7,217.3 493.7,222.5 496.7,221.1 500.1,225 502.9,218.2 506.1,216.4 509,225.7 512.5,219.6 514.8,226.6 518.6,221.3 522.1,219.9 525.4,219.8 528.7,220.1 530.3,226.2 532.2,230.2 537.4,224.8 541,224.5 543.4,227 543.6,233.8 547.5,233 548,238.1 550.8,239.2 557.8,234.4 561,235.5 560.5,241.4 563.1,243.2 567.8,242.7 568.4,246.7 571,248.6 570,253.6 577.7,251.4 572.7,259.1 577.5,259.5 578.7,262.4 581.9,264.1 586.4,265.3 582,271.1 580.9,274.9 585.8,276.1 584.7,279.9 583.7,283.4 592.1,284 590.6,287.7 588.4,291.4 591.9,293.9 587,297.7 593.3,300 597.7,302.9 594.3,306.3 595.7,309.5 590.7,312.5 588.3,315.4 591.4,318.8 594.8,322.4 592.3,325.2 588.2,327.6 588.7,330.8 589.5,334.3 591.2,338.2 585,339.3 587.4,343.7 587.4,347.2 584.8,349.5 577.3,348.9 576.1,351.7 581,358.5 572.5,356.4 576.4,363.1 572.4,363.9 568.5,364.6 571.8,372 567.6,372.4 563.8,372.9 563.8,377.7 560.2,378.4 554.1,375.5 555.7,383.1 553.6,385.7 549.8,385.7 545.9,385.1 545.4,391.2 540.2,387.5 537.1,388.2 536.4,395.1 531.4,390.4 528.5,391.3 526,394.1 523.8,398.7 520.4,398.4 516.4,393.4 513.7,397.1 510.7,399.5 507.4,397.3 504.2,396.1 501.2,393.5 497.7,399.5 494.9,395.4 491.9,394 489,393.2 485.6,393.9 482.3,394.3 479.6,392.4 475.7,394.1 473,392.1 470.1,390.7 470,383.4 463.7,389.2 464.4,381.4 462.1,379.4",transform:"translate(-304,-157) scale(0.75)"}}},initialize:function(e){t.View.prototype.initialize.apply(this,arguments),this.markerView=e.markerView,this.model=this.markerView.model,this.render()
},render:function(){var t=this;!this.rendered&&(this.rendered=!0)&&(this.width=150,this.height=150,this.$el=n("<div></div>"),this.$el.addClass("rfmap"),this.$el.css({position:"absolute",width:this.width+"px",height:this.height+"px","z-index":2}),this.svgContainer=i.select(this.$el.get(0)).append("svg").attr("width",this.width).attr("height",this.height),this.$labels=n('<div class="labels"></div'),this.$el.append(this.$labels),this.$upperLabels=n('<div class="upperLabels"></div'),this.$labels.append(this.$upperLabels),this.$lowerLabels=n('<div class="lowerLabels"></div'),this.$labels.append(this.$lowerLabels),this.$mapToggles=n(".buttonset.mainToggles input"),this.$mapToggles.on("click",this.toggleRfMap.bind(this)),this.$coverageToggle2g=n("#mapFilterCoverage2G"),this.$coverageToggle2g.on("change",function(){t.is2gCoverageEnabled=t.$coverageToggle2g.is(":checked"),t.toggleRfMap(),t.renderComponents()}),this.$coverageToggle5g=n("#mapFilterCoverage5G"),this.$coverageToggle5g.on("change",function(){t.is2gCoverageEnabled=!t.$coverageToggle5g.is(":checked"),t.toggleRfMap(),t.renderComponents()}),this.is2gCoverageEnabled=this.$coverageToggle2g.is(":checked"),this.markerView.$el.before(this.$el),this.markerView.$el.on("drag",function(e,n){t.setPosition(n.position.left,n.position.top)}),this.listenTo(this.model,"change:state",this.renderComponents),this.listenTo(this.model,"change:ng-channel change:na-channel",this.renderChannelLabel),this.listenTo(this.model,"change:ng-tx_power change:na-tx_power change:ng-gain change:na-gain change:ng-eirp change:na-eirp",this.renderTxPowerLabel)),this.toggleRfMap(),this.renderComponents()},renderComponents:function(){this.renderBackgroundCircle(),this.renderChannelLabel(),this.renderBandLabel(),this.renderAntennaLabel(),this.renderTxPowerLabel(),this.renderBackgroundCircleOutline()},toggleRfMap:function(){n("#Map").hasClass("details")&&this.isRfMapSupported()?(this.$el.show(),this.markerView.$el.addClass("withRfMap")):(this.$el.hide(),this.markerView.$el.removeClass("withRfMap"))},isRfMapSupported:function(){return this.model.isConnected()&&this.model.hasRadio(this.is2gCoverageEnabled?"ng":"na")?!0:!1},renderBackgroundCircle:function(){this.backgroundCircle&&this.backgroundCircle.remove(),this.backgroundCircle=this.svgContainer.append("g"),this.backgroundCircle.append("circle").attr("cx",75).attr("cy",75).attr("r",60).attr("fill","rgba(80,80,80,0.7)").attr("stroke","rgba(80,80,80,0.85)").attr("stroke-width",1)},renderBackgroundCircleOutlineShape:function(t,n,i){var s=t.append(n);return e.each(i,function(t,e){s.attr(e,t)}),s},renderBackgroundCircleOutline:function(){this.backgroundCircleOutline&&this.backgroundCircleOutline.remove(),this.backgroundCircleOutline=this.svgContainer.append("g"),this.renderBackgroundCircleOutlineShape(this.backgroundCircleOutline,"circle",this.rfMapBorderData.normalCircle)},renderThroughputChart:function(){var t,e=0;this.throughputChart&&this.throughputChart.remove(),this.throughputChart=this.svgContainer.append("g");for(var n=0;8>n;n++)t=n>=8*e?.5:1,this.throughputChart.append("rect").attr("x",47).attr("y",88-4*n).attr("width",5).attr("height",2.75).attr("fill","rgba(255,255,255,"+t+")")},renderThroughputChartLabel:function(){var t="0",e="mbps";this.throughputChartLabel&&this.throughputChartLabel.remove(),this.throughputChartLabel=n("<div></div").addClass("throughputChartLabel"),this.throughputChartLabel.append(n("<div></div>").text(t).addClass("mediumText")),this.throughputChartLabel.append(n("<div></div>").text(e).addClass("smallText")),this.$labels.append(this.throughputChartLabel)},renderUtilizationChart:function(){var t=0;this.utilizationChart&&this.utilizationChart.remove(),this.utilizationChart=this.svgContainer.append("g"),this.utilizationChart.append("rect").attr("x",98).attr("y",60).attr("width",5).attr("height",30*(1-t)).attr("fill","rgba(255,255,255,0.5)"),this.utilizationChart.append("rect").attr("x",98).attr("y",60+32*(1-t)).attr("width",5).attr("height",30*t).attr("fill","rgba(255,255,255,1)")},renderUtilizationChartLabel:function(){var t="0",e="%";this.utilizationChartLabel&&this.utilizationChartLabel.remove(),this.utilizationChartLabel=n("<div></div").addClass("utilizationChartLabel"),this.utilizationChartLabel.append(n("<span></span>").text(t).addClass("mediumText")),this.utilizationChartLabel.append(n("<span></span>").text(e).addClass("smallText")),this.$labels.append(this.utilizationChartLabel)},renderChannelLabel:function(){var t="ch",e=this.model.channel(this.is2gCoverageEnabled?"ng":"na");this.channelLabel&&this.channelLabel.remove(),this.channelLabel=n("<div></div").addClass("channelLabel"),this.channelLabel.append(n("<span></span>").text(t).addClass("smallText")),this.channelLabel.append(n("<span></span>").text(e).addClass("mediumText")),this.$upperLabels.append(this.channelLabel)},renderAntennaLabel:function(){var t=this.model.getNss(this.is2gCoverageEnabled?"ng":"na"),e=t,i=t;t&&(this.antennaLabel&&this.antennaLabel.remove(),this.antennaLabel=n("<div></div").addClass("antennaLabel"),this.antennaLabel.append(n("<span></span>").text(e).addClass("mediumText")),this.antennaLabel.append(n("<span></span>").text("x").addClass("smallText")),this.antennaLabel.append(n("<span></span>").text(i).addClass("mediumText")),this.$lowerLabels.append(this.antennaLabel))},renderBandLabel:function(){var t="11",e=this.is2gCoverageEnabled?"n/b/g":this.model.is11ac()?"n/a/ac":"n/a";this.bandLabel&&this.bandLabel.remove(),e&&(this.bandLabel=n("<div></div").addClass("bandLabel"),this.bandLabel.append(n("<span></span>").text(t).addClass("smallText")),this.bandLabel.append(n("<span></span>").text(e).addClass("mediumText")),this.$lowerLabels.append(this.bandLabel))},renderTxPowerLabel:function(){var t=this.model.transmitPower(this.is2gCoverageEnabled?"ng":"na"),e="dbm";this.txPowerLabel&&this.txPowerLabel.remove(),t&&(this.txPowerLabel=n("<div></div").addClass("txPowerLabel"),this.txPowerLabel.append(n("<span></span>").text(t).addClass("mediumText")),this.txPowerLabel.append(n("<span></span>").text(e).addClass("smallText")),this.$upperLabels.append(this.txPowerLabel))},setPosition:function(t,e){this.$el.css({left:t-75,top:e-75})},remove:function(){t.View.prototype.remove.apply(this,arguments)}})}),define("ubnt/view/map/GoogleMapMarkerWrapperView",["unifi/view/map/MarkerRfMapView"],function(t){"use strict";return{Overlay:function(t){return this.markerView=t,this},initialize:function(){this.Overlay.prototype=new google.maps.OverlayView,this.Overlay.prototype.onAdd=function(){var t=this.getPanes();t.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(),n=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",n.y+"px"),this.markerView.$el.css("left",n.x+"px"),this.markerView.$el.show(),!this.markerView.rfMap&&this.markerView.$el.parent().size()&&this.markerView.model.get("type")==this.markerView.model.typeMap.ap&&(this.markerView.rfMap=new t({markerView:this.markerView})),this.markerView.rfMap&&this.markerView.rfMap.setPosition(n.x,n.y)},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 t(t){var e,n;e=document.createElement("script"),e.type="text/javascript",e.async=!0,e.src=t,n=document.getElementsByTagName("script")[0],n.parentNode.insertBefore(e,n)}function e(t,e){var n=/!(.+)/,s=t.replace(n,""),a=n.test(t)?t.replace(/.+!/,""):i;return s+=s.indexOf("?")<0?"?":"&",s+a+"="+e}function n(){return s+=1,"__async_req_"+s+"__"}var i="callback",s=0;return{load:function(i,s,a,r){if(r.isBuild)a(null);else{var o=n();window[o]=a,t(e(i,o))}}}}),define("gmaps",["jquery"],function(t){"use strict";if(window.google&&window.google.maps)return window.google;var e=t.Deferred();return require(["async!//maps.google.com/maps/api/js?libraries=geometry&sensor=false!callback"],function(){e.resolve(window.google)},function(){window.googleMapsNotLoaded(),e.reject()}),e.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(t,e,n,i,s,a,r,o,l){"use strict";return e.extend({_fullyQualifiedName:"UBNT.views.map.GoogleMap",initialize:function(n){t.bindAll(this),this.app=n.app,this.loaded=!1,l.maps?r("body").hasClass("googlemaps-notLoaded")||(this.loaded=!0):l.done(r.proxy(function(t){l=t,this.onLoad()},this)).fail(function(){r("body").addClass("googlemaps-notLoaded")}),this.mapBaseType="google",e.prototype.initialize.apply(this,[n]),this.markerViewOverlays={},this.layerItemOverlays={},this.layerQueue=[]},onLoad:function(){this.loaded=!0,i.initialize(),n.initialize(),this.trigger("googlemaps-loaded")},setMap:function(t){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=t,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"),r("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 e=this,n={zoom:this.model?this.model.get("zoom"):1,center:new l.maps.LatLng(this.model.get("lat"),this.model.get("lng")),mapTypeId:l.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 l.maps.Map(this.$el.get(0),n),l.maps.event.addListener(this.googleMap,"zoom_changed",function(){var t=e.googleMap.getZoom();t>20&&(t=20),1>t&&(t=1),e.setZoom(t)}),l.maps.event.addListener(this.googleMap,"center_changed",function(){e.setOffset(e.googleMap.center.lat(),e.googleMap.center.lng())}),l.maps.event.addListener(this.googleMap,"maptypeid_changed",function(){e.setMapType(e.googleMap.getMapTypeId())}),this.googleMapOverlay=new l.maps.OverlayView,this.googleMapOverlay.onAdd=function(){},this.googleMapOverlay.draw=function(){},this.googleMapOverlay.onRemove=function(){},this.googleMapOverlay.setMap(this.googleMap),t.each(this.layerQueue,function(t){this.layers[t.cid]=t,t.bindHandlers()},this),this.layerQueue=[],this.loaded=!0),this.previousMapZoom=n.zoom,this.googleMapOverlay&&this.resetMarkers()},addLayer:function(e,n){var i=t.extend(n,{mapBase:this}),s=new e(i);null===this.googleMap||void 0===this.googleMap?this.layerQueue.push(s):this.layers[s.cid]=e},addLayerItem:function(t){if(this.googleMap){var e=new n.Overlay(t,this.googleMap);e.setMap(this.googleMap),this.layerItems[t.cid]=t,this.layerItemOverlays[t.cid]=e,t.$el.css("zIndex",this.layerZ),this.layerZ++,t.trigger("layeritemadded")}},removeLayerItem:function(t){var e=this.layerItemOverlays[t.cid];e&&e.setMap(null)},positionMarker:function(t){this.googleMap&&this.markerViewOverlays[t.model.id]&&this.markerViewOverlays[t.model.id].setMap(t.model.attributes.map_id==this.model.id?this.googleMap:null)},updateMarkerPositions:function(){t.each(this.markerViews,this.positionMarker)},addMarker:function(t){e.prototype.addMarker.apply(this,[t,this.model]);var n=this.markerViews[t.id];if(n){(null===this.markerViewOverlays[t.id]||void 0===this.markerViewOverlays[t.id])&&(this.markerViewOverlays[t.id]=new i.Overlay(n,this.googleMap));var s=this.markerViewOverlays[t.id];this.model&&this.model.id==t.attributes.map_id&&s.setMap(this.googleMap),n.unbind("dragstart",this.markerDragStartHandler).bind("dragstart",this.markerDragStartHandler),n.unbind("dragstop",this.markerDragStopHandler).bind("dragstop",this.markerDragStopHandler)}},updateMarker:function(t){void 0!==t.get("map_id")&&(this.model&&t.get("map_id")==this.model.id?this.addMarker(t):this.removeMarker(t))},removeMarker:function(t){this.markerViewOverlays[t.id];this.markerViewOverlays[t.id]&&(this.markerViewOverlays[t.id].setMap(null),delete this.markerViewOverlays[t.id]),e.prototype.removeMarker.apply(this,[t])},resize:function(){this.loaded&&this.googleMap&&l.maps.event.trigger(this.googleMap,"resize")},markerDragStartHandler:function(){this.isMarkerDragging=!0,this.disableMapDrag()},markerDragStopHandler:function(t,e){if(this.isMarkerDragging=!1,this.enableMapDrag(),e&&e.position){var n=this.googleMapOverlay.getProjection().fromDivPixelToLatLng(new l.maps.Point(e.position.left,e.position.top)),i=e.helper.data("view"),s=i.model;this.app.isReadOnly?s.set({x:Number(n.lat().toFixed(5)),y:Number(n.lng().toFixed(5))}):s.save({x:Number(n.lat().toFixed(5)),y:Number(n.lng().toFixed(5))})}},dropHandler:function(t,e){var n=this.googleMapOverlay.getProjection().fromContainerPixelToLatLng(new l.maps.Point(e.position.left,e.position.top-42)),i=e.helper.data("view"),s=i.model;this.app.isReadOnly?s.set({x:Number(n.lat().toFixed(5)),y:Number(n.lng().toFixed(5)),map_id:this.model.id}):s.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(t){this.setMapType(t.get("mapTypeId"),!0)},setMapType:function(t,e){this.model.set({mapTypeId:t}),e||this.app.isReadOnly||this.saveMapType(t)},saveMapType:t.debounce(function(t){this.model.unset("mapTypeId",{silent:!0}),this.model.save({mapTypeId:t},{silent:!0})},250),mapOffsetHandler:function(t){this.setOffset(t.get("lat")||0,t.get("lng")||0,!0)},setOffset:function(t,e,n){this.model.set({lat:t,lng:e}),n||this.app.isReadOnly||this.saveOffset(t,e)},saveOffset:t.debounce(function(t,e){this.model.unset("lat",{silent:!0}),this.model.unset("lng",{silent:!0}),this.model.save({lat:t,lng:e},{silent:!0})},250),mapZoomHandler:function(t){this.setZoom(t.get("zoom")||this.zoomLevel,!0),this.renderMap(),this.updateMarkerPositions()},setZoom:function(t,e){this.zoomLevel!=t&&(this.zoomLevel=t,this.model.set({zoom:t}),e||this.app.isReadOnly||this.saveZoom(t))},saveZoom:t.debounce(function(t){this.model.unset("zoom",{silent:!0}),this.model.save({zoom:t},{silent:!0})},250),computeDistanceBetween:function(t,e,n,i){var s=this.googleMapOverlay.getProjection().fromDivPixelToLatLng(new l.maps.Point(t,e)),a=this.googleMapOverlay.getProjection().fromDivPixelToLatLng(new l.maps.Point(n,i));return l.maps.geometry.spherical.computeDistanceBetween(s,a)},computeOffset:function(t,e,n,i){var s=this.googleMapOverlay.getProjection().fromDivPixelToLatLng(new l.maps.Point(t,e)),a=l.maps.geometry.spherical.computeOffset(s,n,(i+Math.PI)*(180/Math.PI)),r=this.googleMapOverlay.getProjection().fromLatLngToDivPixel(a);return{x:Math.round(r.x),y:Math.round(r.y)}},translateToPixelCoordinates:function(t,e){var n=this.googleMapOverlay.getProjection().fromLatLngToDivPixel(new l.maps.LatLng(t,e));return n},translateToMapCoordinates:function(t,e){var n=this.googleMapOverlay.getProjection().fromDivPixelToLatLng(new l.maps.Point(t,e));return{x:n.lat(),y:n.lng()}},remove:function(){this.model.off("change",this.mapChangeHandler),t.each(this.markerViews,function(t){t.unbind("dragstart",this.markerDragStartHandler),t.unbind("dragstop",this.markerDragStopHandler)},this),this.googleMap&&(l.maps.event.removeListener(this.googleMap,"zoom_changed"),l.maps.event.removeListener(this.googleMap,"center_changed"),l.maps.event.removeListener(this.googleMap,"bounds_changed"),l.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)),e.prototype.remove.apply(this,arguments)}})}),function(t){"function"==typeof define&&define.amd?define("libs/jquery.mousewheel",["jquery"],t):"object"==typeof exports?module.exports=t:t(jQuery)}(function(t){function e(e){var a=e||window.event,r=o.call(arguments,1),l=0,c=0,d=0,h=0;return e=t.event.fix(a),e.type="mousewheel","detail"in a&&(d=-1*a.detail),"wheelDelta"in a&&(d=a.wheelDelta),"wheelDeltaY"in a&&(d=a.wheelDeltaY),"wheelDeltaX"in a&&(c=-1*a.wheelDeltaX),"axis"in a&&a.axis===a.HORIZONTAL_AXIS&&(c=-1*d,d=0),l=0===d?c:d,"deltaY"in a&&(d=-1*a.deltaY,l=d),"deltaX"in a&&(c=a.deltaX,0===d&&(l=-1*c)),0!==d||0!==c?(h=Math.max(Math.abs(d),Math.abs(c)),(!s||s>h)&&(s=h),l=Math[l>=1?"floor":"ceil"](l/s),c=Math[c>=1?"floor":"ceil"](c/s),d=Math[d>=1?"floor":"ceil"](d/s),e.deltaX=c,e.deltaY=d,e.deltaFactor=s,r.unshift(e,l,c,d),i&&clearTimeout(i),i=setTimeout(n,200),(t.event.dispatch||t.event.handle).apply(this,r)):void 0}function n(){s=null}var i,s,a=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],r="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],o=Array.prototype.slice;if(t.event.fixHooks)for(var l=a.length;l;)t.event.fixHooks[a[--l]]=t.event.mouseHooks;t.event.special.mousewheel={version:"3.1.6",setup:function(){if(this.addEventListener)for(var t=r.length;t;)this.addEventListener(r[--t],e,!1);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var t=r.length;t;)this.removeEventListener(r[--t],e,!1);else this.onmousewheel=null}},t.fn.extend({mousewheel:function(t){return t?this.bind("mousewheel",t):this.trigger("mousewheel")},unmousewheel:function(t){return this.unbind("mousewheel",t)}})}),define("ubnt/view/map/ImageMapView",["ubnt/view/map/MapBase","underscore","jquery","unifi/view/map/MarkerRfMapView","libs/jquery.mousewheel"],function(t,e,n,i){"use strict";return t.extend({_fullyQualifiedName:"UBNT.views.map.ImageMap",initialize:function(n){e.bindAll(this),this.mapBaseType="image",this.app=n.app,t.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(t){if(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=t,this.$img=this.mapImages[this.model.id],this.$(".image-map-layer").empty(),void 0===this.$img)this.loadMap();else{var e=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>e/n?(this.$img.height(e/this.imgWidth*this.imgHeight),this.$img.width(e)):(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",(e-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(t){this.setZoom(t.get("zoom"),!0)},mapOffsetHandler:function(t){this.setOffset(t.get("offset_top")||0,t.get("offset_left")||0,!0)},loadMap:function(){var t=this;this.$img=n(new Image),this.$img.load(function(){t.mapImages[t.model.id]=n(this),t.$img.unbind("load"),t.setMap(t.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(t){t.stopPropagation()},addMarker:function(e){t.prototype.addMarker.apply(this,[e,this.model]);var n=this.markerViews[e.id];n&&(n.$el.unbind("mousedown",this.preventEventPropagationFunc).bind("mousedown",this.preventEventPropagationFunc),n.unbind("dragstart",this.markerDragStartHandler).bind("dragstart",this.markerDragStartHandler),n.unbind("dragstop",this.markerDragStopHandler).bind("dragstop",this.markerDragStopHandler),this.positionMarker(n),this.$markerLayer.append(n.$el))},updateMarker:function(t){void 0!==t.get("map_id")&&(this.model&&t.get("map_id")==this.model.id?this.addMarker(t):this.removeMarker(t))},positionMarker:function(t){if(this.model&&t.model.attributes.map_id==this.model.id){var e=t.model.get("x")*this.zoom,n=t.model.get("y")*this.zoom;t.setPosition(e,n),t.show(),!t.rfMap&&t.$el.parent().size()&&t.model.get("type")==t.model.typeMap.ap&&(t.rfMap=new i({markerView:t})),t.rfMap&&t.rfMap.setPosition(e,n)}else t.hide()},updateMarkerPositions:function(){e.each(this.markerViews,this.positionMarker)},addLayer:function(t,n){var i=e.extend(n,{mapBase:this}),s=new t(i);this.layers[s.cid]=s},addLayerItem:function(t){this.$subMarkerLayer.append(t.$el),t.trigger("layeritemadded")},removeLayerItem:function(t){t.$el.remove()},markerDragStartHandler:function(){this.isMarkerDragging=!0},markerDragStopHandler:function(t,e){if(this.isMarkerDragging=!1,e&&e.helper){var n=e.helper.data("view"),i=n.model;this.app.isReadOnly?i.set({x:e.position.left/this.zoom,y:e.position.top/this.zoom}):i.save({x:e.position.left/this.zoom,y:e.position.top/this.zoom})}},mouseDownHandler:function(t){return 2==t.button?(t.preventDefault(),t.stopPropagation(),!1):(this.startPageX=t.pageX,this.startPageY=t.pageY,n("body").bind("mouseup",this.mouseUpHandler),this.$el.bind("mousemove",this.mouseMoveHandler),!1)},mouseWheelHandler:function(){},mouseUpHandler:function(){n("body").unbind("mouseup",this.mouseUpHandler),this.$el.unbind("mousemove",this.mouseMoveHandler)},mouseMoveHandler:function(t){if(!this.isMarkerDragging){this.deltaX=t.pageX-this.startPageX,this.deltaY=t.pageY-this.startPageY,this.startPageX=t.pageX,this.startPageY=t.pageY;var e=this.$dragLayer.offset(),n=e.top+this.deltaY,i=e.left+this.deltaX;this.setOffset(n,i)}},clickHandler:function(t){var e=n(t.target);e.hasClass("phone-icon")&&(e.parent().css("z-index",this.currentZIndex),this.currentZIndex++)},dropHandler:function(t,e){var n=e.helper.data("view"),i=n.model,s=this.$dragLayer.position(),a=(e.position.left-s.left)/this.zoom,r=(e.position.top-s.top-42)/this.zoom;this.app.isReadOnly?i.set({x:a,y:r,map_id:this.model.id}):i.save({x:a,y:r,map_id:this.model.id})},setOffset:function(t,e,n){this.$dragLayer.offset({top:t,left:e}),this.model.set({offset_top:t,offset_left:e}),n||this.app.isReadOnly||this.saveOffset(t,e)},saveOffset:e.debounce(function(t,e){this.model.unset("offset_top",{silent:!0}),this.model.unset("offset_left",{silent:!0}),this.model.save({offset_top:t,offset_left:e},{silent:!0})},250),setZoom:function(t){this.$dragLayer.position(),this.$el.width(),this.$el.height();this.zoom=t/10,this.$img.width(this.scale*this.imgWidth*this.zoom),this.$img.height(this.scale*this.imgHeight*this.zoom),this.updateMarkerPositions()},setFocus:function(t,e,n){var i=this.translateToPixelCoordinates(t,e),s=this.$el.width(),a=this.$el.height(),r=s/2-i.x,o=a/2-i.y;n||(this.$dragLayer.css("top",o+"px"),this.$dragLayer.css("left",r+"px"))},enableMapDrag:function(){this.$el.on("mousedown",this.mouseDownHandler)},disableMapDrag:function(){this.$el.off("mousedown",this.mouseDownHandler)},translateToPixelCoordinates:function(t,e){return{x:t*this.scale*this.zoom,y:e*this.scale*this.zoom}},translateToMapCoordinates:function(t,e){return{x:t/this.scale/this.zoom,y:e/this.scale/this.zoom}},computeOffset:function(t,e,n,i){return{x:t+Math.sin(i)*n*this.scale*this.zoom,y:e-Math.cos(i)*n*this.scale*this.zoom}},computeDistanceBetween:function(t,e,n,i){var s=this.translateToMapCoordinates(t,e),a=this.translateToMapCoordinates(n,i);return Math.sqrt((a.x-s.x)*(a.x-s.x)+(a.y-s.y)*(a.y-s.y))},remove:function(){this.$el.unbind("mousedown",this.mouseDownHandler),this.$el.unbind("mousewheel",this.mouseWheelHandler),e.each(this.markerViews,function(t){t.$el.unbind("mousedown"),t.unbind("dragstart",this.markerDragStartHandler),t.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)),t.prototype.remove.apply(this,arguments)}})}),define("ubnt/view/uicomponents/DroppableItemView",["backbone","jquery"],function(t,e){"use strict";return t.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 t=this;this.$el.droppable({tolerance:"pointer",accept:this.accept,greedy:this._greedy,activeClass:"droppable",drop:function(n,i){e(this).removeClass("ui-state-highlight"),t.trigger("drop",n,i)},over:function(n,i){e(this).addClass("ui-state-highlight"),t.trigger("over",n,i)},out:function(n,i){e(this).removeClass("ui-state-highlight"),t.trigger("out",n,i)}})},destroy:function(){this.$el.droppable("destroy")},setScope:function(t){this.$el.droppable("option","scope",t)},setAccept:function(t){this.$el.droppable("option","accept",t)}})}),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(t,e,n,i,s,a,r){"use strict";return t.View.extend({_fullyQualifiedName:"UBNT.views.map.MapWidget",initialize:function(){n.bindAll(this),this.markerView=this.options.markerView||i,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 s({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 a({app:this.app,el:this.$imageMapContainer,collection:this.maps,markers:this.markers,markerView:this.markerView,markerTemplate:this.markerTemplate}),this.initHandlers(),this.initDroppable()},initHandlers:function(){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(t){if(this.isRendered){if(this.markers.get(t)&&this.model.id==t.get("map_id")){var e;if(e="googleMap"===this.model.get("type")?this.googleMap.markerViews[t.id]:this.imageMap.markerViews[t.id]){if("imageMap"===this.model.get("type")){var i=e.$el.position(),s=this.imageMap.translateToMapCoordinates(i.left,i.top);this.imageMap.setFocus(s.x,s.y)}e.pulse()}else n.delay(this.locateDevice,50,t)}}else n.delay(this.locateDevice,50,t)},addLayer:function(t,e){this.googleMap.addLayer(t,e),this.imageMap.addLayer(t,e)},setMap:function(t){t&&(this.model&&this.model.off("change:type",this.setMap),this.model=t,this.model.on("change:type",this.setMap),"googleMap"===t.get("type")?(this.googleMap.show(),this.googleMap.setMap(t),this.imageMap.hide(),e("#Map").addClass("isGoogleMap")):(this.imageMap.show(),this.imageMap.setMap(t),this.googleMap.hide(),e("#Map").removeClass("isGoogleMap")),this.zoomLevel=t.get("zoom"))},initDroppable:function(){this.droppable=new r({el:this.el,accept:".unplaced-marker"}),this.droppable.bind("drop",this.dropHandler)},dropHandler:function(t,e){"googleMap"==this.model.attributes.type?this.googleMap.dropHandler(t,e):this.imageMap.dropHandler(t,e)},mouseWheelHandler:function(t,e,n,i){i=i||t.originalEvent.wheelDeltaY;var s=this.zoomLevel;if(i>0){if(!(this.zoomLevel<20))return;s+=1}else{if(!(this.zoomLevel>1))return;s-=1}this.setZoom(s)},setZoom:function(t,e){this.zoomLevel!=t&&(this.zoomLevel=t,this.model.set({zoom:t}),e||this.app.isReadOnly||this.saveZoom(t))},saveZoom:n.debounce(function(t){this.model.unset("zoom",{silent:!0}),this.model.save({zoom:t},{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,t.View.prototype.remove.apply(this,arguments)}})}),define("ubnt/view/map/MapView",["backbone","underscore","jquery","ubnt/view/map/MapWidgetView","msg/Msg","libs/jquery.cookie"],function(t,e,n,i){"use strict";return t.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 i({app:this.app,el:this.$(".ubnt-map-widget"),maps:this.maps,markers:this.markers,markerView:this.markerView,markerTemplate:this.markerTemplate})},setMap:function(t){this.model=t,this.mapWidget.setMap(t)},tabShowHandler:function(){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(t){this.rendered?this.markers.get(t)&&this.mapWidget.locateDevice(t):e.delay(this.locateDevice,50,t)},remove:function(){this.rendered=!1,t.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/map/TopologyView",["backbone","underscore","jquery","libs/kinetic"],function(t,e,n,i){"use strict";return t.View.extend({LINK_COLOR:[{value:45,color:"#57c23e"},{value:30,color:"#f78100"},{value:20,color:"#ff0000"}],DISCONNECTED_COLOR:"#CCCCCC",initialize:function(t){e.bindAll(this),this.indexView=t.indexView,this.markers=this.indexView.app.collection("Devices"),this.linkLines=[],this.isMoving=!1,this.isVisible=!1},setMap:function(t){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=t,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 t=n(".marker-layer");this.layer=new i.Layer,this.stage=new i.Stage({container:t[0],width:t.width(),height:t.parent().height()}),this.stage.add(this.layer)},destroyStage:function(){this.layer&&(this.layer.destroy(),this.stage.destroy())},getMarkerPosition:function(t){var e=this.markers.get(t),n=this.model.get("zoom");if("googleMap"===this.model.get("type")){var i=this.indexView.getActiveMap().googleMapOverlay.getProjection(),s=i.fromLatLngToDivPixel(new google.maps.LatLng(e.get("x"),e.get("y")));return{left:s.x,top:s.y}}return{left:e.get("x")*n/10,top:e.get("y")*n/10}},rebuildUplinks:function(){if("googleMap"!==this.model.get("type")){var t,n,i;this.model&&(t=this.markers.filter(function(t){return t.get("map_id")===this.model.get("_id")},this),e.each(this.linkLines,function(t){t.line.destroy()}),e.each(t,function(t){n=t.uplinks(),e.each(n,function(e){e.configured&&(i=this.markers.findWhere({mac:e.mac}),i&&i.get("map_id")===this.model.get("_id")&&this.setTopologyLink(t,i,e))},this)},this))}},setTopologyLink:function(t,n,i){var s,a,r,o=.8,l=this.getMarkerPosition(t.id),c=this.getMarkerPosition(n.id);i.configured?(i.up?(s=!0,a=this.LINK_COLOR[0].color,e.each(this.LINK_COLOR,function(t){i.rssi<t.value&&(a=t.color)},this)):(s=!0,a=this.DISCONNECTED_COLOR),o=1):o=.25,r=this._createLine(l.left,l.top,c.left,c.top,a,o),this.linkLines.push({line:r,islandDevice:t,uplinkDevice:n}),this.layer.add(r),this.layer.drawScene()},_createLine:function(t,e,n,s,a,r){var o=new i.Line({points:this._getArrowPoints(t,e,n,s),stroke:a,opacity:r,dashArray:[10,10]});return o},_getArrowPoints:function(t,e,n,i){return[t,e,n,i]},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),t.View.prototype.remove.apply(this,arguments)}})}),function(t,e,n){"undefined"!=typeof module&&module.exports?module.exports=n():"function"==typeof define&&define.amd?define("heatmap",n):e[t]=n()}("h337",this,function(){var t={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:{}},e=function(){var e=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)},n=t.defaultRadius;return e.prototype={_organiseData:function(t,e){var i=t[this._xField],s=t[this._yField],a=this._radi,r=this._data,o=this._max,l=this._min,c=t[this._valueField]||1,d=t.radius||this._cfgRadius||n;return r[i]||(r[i]=[],a[i]=[]),r[i][s]?r[i][s]+=c:(r[i][s]=c,a[i][s]=d),r[i][s]>o?(e?this.setDataMax(r[i][s]):this._max=r[i][s],!1):{x:i,y:s,value:c,radius:d,min:l,max:o}},_unOrganizeData:function(){var t=[],e=this._data,n=this._radi;for(var i in e)for(var s in e[i])t.push({x:i,y:s,radius:n[i][s],value:e[i][s]});return{min:this._min,max:this._max,data:t}},_onExtremaChange:function(){this._coordinator.emit("extremachange",{min:this._min,max:this._max})},addData:function(){if(arguments[0].length>0)for(var t=arguments[0],e=t.length;e--;)this.addData.call(this,t[e]);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(t){var e=t.data,n=e.length;this._data=[],this._radi=[];for(var i=0;n>i;i++)this._organiseData(e[i],!1);return this._max=t.max,this._min=t.min||0,this._onExtremaChange(),this._coordinator.emit("renderall",this._getInternalData()),this},removeData:function(){},setDataMax:function(t){return this._max=t,this._onExtremaChange(),this._coordinator.emit("renderall",this._getInternalData()),this},setDataMin:function(t){return this._min=t,this._onExtremaChange(),this._coordinator.emit("renderall",this._getInternalData()),this},setCoordinator:function(t){this._coordinator=t},_getInternalData:function(){return{max:this._max,min:this._min,data:this._data,radi:this._radi}},getData:function(){return this._unOrganizeData()}},e}(),n=function(){function t(t){var n=t.container,i=this.shadowCanvas=document.createElement("canvas"),s=this.canvas=t.canvas||document.createElement("canvas"),a=(this._renderBoundaries=[1e4,1e4,0,0],getComputedStyle(t.container)||{});s.className="heatmap-canvas",this._width=s.width=i.width=+a.width.replace(/px/,""),this._height=s.height=i.height=+a.height.replace(/px/,""),this.shadowCtx=i.getContext("2d"),this.ctx=s.getContext("2d"),s.style.cssText=i.style.cssText="position:absolute;left:0;top:0;",n.style.position="relative",n.appendChild(s),this._palette=e(t),this._templates={},this._setStyles(t)}var e=function(t){var e=t.gradient||t.defaultGradient,n=document.createElement("canvas"),i=n.getContext("2d");n.width=256,n.height=1;var s=i.createLinearGradient(0,0,256,1);for(var a in e)s.addColorStop(a,e[a]);return i.fillStyle=s,i.fillRect(0,0,256,1),i.getImageData(0,0,256,1).data},n=function(t,e){var n=document.createElement("canvas"),i=n.getContext("2d"),s=t,a=t;if(n.width=n.height=2*t,1==e)i.beginPath(),i.arc(s,a,t,0,2*Math.PI,!1),i.fillStyle="rgba(0,0,0,1)",i.fill();else{var r=i.createRadialGradient(s,a,t*e,s,a,t);r.addColorStop(0,"rgba(0,0,0,1)"),r.addColorStop(1,"rgba(0,0,0,0)"),i.fillStyle=r,i.fillRect(0,0,2*t,2*t)}return n},i=function(t){for(var e=[],n=t.min,i=t.max,s=t.radi,t=t.data,a=Object.keys(t),r=a.length;r--;)for(var o=a[r],l=Object.keys(t[o]),c=l.length;c--;){var d=l[c],h=t[o][d],u=s[o][d];e.push({x:o,y:d,value:h,radius:u})}return{min:n,max:i,data:e}};return t.prototype={renderPartial:function(t){this._drawAlpha(t),this._colorize()},renderAll:function(t){this._clear(),this._drawAlpha(i(t)),this._colorize()},_updateGradient:function(t){this._palette=e(t)},updateConfig:function(t){t.gradient&&this._updateGradient(t),this._setStyles(t)},setDimensions:function(t,e){this._width=t,this._height=e,this.canvas.width=this.shadowCanvas.width=t,this.canvas.height=this.shadowCanvas.height=e},_clear:function(){this.shadowCtx.clearRect(0,0,this._width,this._height),this.ctx.clearRect(0,0,this._width,this._height)},_setStyles:function(t){this._blur=0==t.blur?0:t.blur||t.defaultBlur,t.backgroundColor&&(this.canvas.style.backgroundColor=t.backgroundColor),this._opacity=255*(t.opacity||0),this._maxOpacity=255*(t.maxOpacity||t.defaultMaxOpacity),this._minOpacity=255*(t.minOpacity||t.defaultMinOpacity),this._useGradientOpacity=!!t.useGradientOpacity},_drawAlpha:function(t){for(var e=this._min=t.min,i=this._max=t.max,t=t.data||[],s=t.length,a=1-this._blur;s--;){var r,o=t[s],l=o.x,c=o.y,d=o.radius,h=Math.min(o.value,i),u=l-d,p=c-d,m=this.shadowCtx;this._templates[d]?r=this._templates[d]:this._templates[d]=r=n(d,a),m.globalAlpha=(h-e)/(i-e),m.drawImage(r,u,p),u<this._renderBoundaries[0]&&(this._renderBoundaries[0]=u),p<this._renderBoundaries[1]&&(this._renderBoundaries[1]=p),u+2*d>this._renderBoundaries[2]&&(this._renderBoundaries[2]=u+2*d),p+2*d>this._renderBoundaries[3]&&(this._renderBoundaries[3]=p+2*d)}},_colorize:function(){var t=this._renderBoundaries[0],e=this._renderBoundaries[1],n=this._renderBoundaries[2]-t,i=this._renderBoundaries[3]-e,s=this._width,a=this._height,r=this._opacity,o=this._maxOpacity,l=this._minOpacity,c=this._useGradientOpacity;0>t&&(t=0),0>e&&(e=0),t+n>s&&(n=s-t),e+i>a&&(i=a-e);for(var d=this.shadowCtx.getImageData(t,e,n,i),h=d.data,u=h.length,p=this._palette,m=3;u>m;m+=4){var f=h[m],g=4*f;if(g){var v;v=r>0?r:o>f?l>f?l:f:o,h[m-3]=p[g],h[m-2]=p[g+1],h[m-1]=p[g+2],h[m]=c?p[g+3]:v}}d.data=h,this.ctx.putImageData(d,t,e),this._renderBoundaries=[1e3,1e3,0,0]},getValueAt:function(t){var e,n=this.shadowCtx,i=n.getImageData(t.x,t.y,1,1),s=i.data[3],a=this._max,r=this._min;return e=Math.abs(a-r)*(s/255)>>0},getDataURL:function(){return this.canvas.toDataURL()}},t}(),i=function(){var e=!1;return"canvas2d"===t.defaultRenderer&&(e=n),e}(),s={merge:function(){for(var t={},e=arguments.length,n=0;e>n;n++){var i=arguments[n];for(var s in i)t[s]=i[s]}return t}},a=function(){function n(){var n=this._config=s.merge(t,arguments[0]||{});if(this._coordinator=new a,n.plugin){var o=n.plugin;if(!t.plugins[o])throw new Error("Plugin '"+o+"' not found. Maybe it was not registered.");var l=t.plugins[o];this._renderer=new l.renderer(n),this._store=new l.store(n)}else this._renderer=new i(n),this._store=new e(n);r(this)}var a=function(){function t(){this.cStore={}}return t.prototype={on:function(t,e,n){var i=this.cStore;i[t]||(i[t]=[]),i[t].push(function(t){return e.call(n,t)})},emit:function(t,e){var n=this.cStore;if(n[t])for(var i=n[t].length,s=0;i>s;s++){var a=n[t][s];a(e)}}},t}(),r=function(t){var e=t._renderer,n=t._coordinator,i=t._store;n.on("renderpartial",e.renderPartial,e),n.on("renderall",e.renderAll,e),n.on("extremachange",function(e){t._config.onExtremaChange&&t._config.onExtremaChange({min:e.min,max:e.max,gradient:t._config.gradient||t._config.defaultGradient})}),i.setCoordinator(n)};return n.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(t){return this._config=s.merge(this._config,t),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(t){return this._store.getValueAt?this._store.getValueAt(t):this._renderer.getValueAt?this._renderer.getValueAt(t):null}},n}(),r={create:function(t){return new a(t)},register:function(e,n){t.plugins[e]=n}};return r}),function(t,e,n){"undefined"!=typeof module&&module.exports?module.exports=n(require("jquery"),require("heatmap"),require("gmaps")):"function"==typeof define&&define.amd?define("heatmap-gmaps",["jquery","heatmap","gmaps"],n):e[t]=n($,h337,google)}("HeatmapOverlay",this,function(t,e,n){if(window.HeatmapOverlay)return window.HeatmapOverlay;var i=t.Deferred(),s=function(t){var n=function(t,e){this.setMap(t),this.initialize(e||{})};return n.prototype=new t.maps.OverlayView,n.CSS_TRANSFORM=function(){for(var t=document.createElement("div"),e=["transform","WebkitTransform","MozTransform","OTransform","msTransform"],n=0;n<e.length;n++){var i=e[n];if(void 0!==t.style[i])return i}return e[0]}(),n.prototype.initialize=function(t){this.cfg=t;var e=this.map=this.getMap(),n=this.container=document.createElement("div"),i=e.getDiv(),s=this.width=i.clientWidth,a=this.height=i.clientHeight;n.style.cssText="width:"+s+"px;height:"+a+"px;",this.data=[],this.max=1,this.min=0,t.container=n},n.prototype.onAdd=function(){this.getPanes().overlayLayer.appendChild(this.container),this.changeHandler=t.maps.event.addListener(this.map,"bounds_changed",this.draw),this.heatmap||(this.heatmap=e.create(this.cfg)),this.draw()},n.prototype.onRemove=function(){this.map&&(this.map=null,this.container.parentElement.removeChild(this.container),this.container=null,this.changeHandler&&(t.maps.event.removeListener(this.changeHandler),this.changeHandler=null))},n.prototype.draw=function(){if(this.map){var e=this.map.getBounds(),i=new t.maps.LatLng(e.getNorthEast().lat(),e.getSouthWest().lng()),s=this.getProjection(),a=s.fromLatLngToDivPixel(i);this.container.style[n.CSS_TRANSFORM]="translate("+Math.round(a.x)+"px,"+Math.round(a.y)+"px)",this.update()}},n.prototype.resize=function(){if(this.map){var t=this.map.getDiv(),e=t.clientWidth,n=t.clientHeight;(e!=this.width||n!=this.height)&&(this.width=e,this.height=n,this.heatmap._renderer.setDimensions(e,n),this.update())}},n.prototype.update=function(){var e,n,i,s,a=this.map.getProjection();if(a&&(i=this.map.getBounds(),s=new t.maps.LatLng(i.getNorthEast().lat(),i.getSouthWest().lng()),e=this.map.getZoom(),n=Math.pow(2,e),this.resize(),0!=this.data.length)){for(var r={max:this.max,min:this.min},o=[],l=this.data.length,c=this.getProjection(),d=c.fromLatLngToDivPixel(s),h=this.cfg.scaleRadius?n:1,u=0,p=0,m=this.cfg.valueField||"value";l--;){var f=this.data[l],g=f[m],v=f.latlng;if(i.contains(v)){u=Math.max(g,u),p=Math.min(g,p);var b=c.fromLatLngToDivPixel(v),w={x:Math.round(b.x-d.x),y:Math.round(b.y-d.y)};w[m]=g;var y;y=f.radius?f.radius*h:(this.cfg.radius||2)*h,w.radius=y,o.push(w)}}this.cfg.useLocalExtrema&&(r.max=u,r.min=p),r.data=o,this.heatmap.setData(r)}},n.prototype.setData=function(e){this.max=e.max,this.min=e.min;for(var n=this.cfg.latField||"lat",i=this.cfg.lngField||"lng",s=this.cfg.valueField||"value",e=e.data,a=e.length,r=[];a--;){var o=e[a],l=new t.maps.LatLng(o[n],o[i]),c={latlng:l};c[s]=o[s],o.radius&&(c.radius=o.radius),r.push(c)}this.data=r,this.update()},n.prototype.addData=function(e){if(e.length>0)for(var n=e.length;n--;)this.addData(e[n]);else{var i=this.cfg.latField||"lat",s=this.cfg.lngField||"lng",a=this.cfg.valueField||"value",r=e,o=new t.maps.LatLng(r[i],r[s]),l={latlng:o};l[a]=r[a],r.radius&&(l.radius=r.radius),this.max=Math.max(this.max,l[a]),this.min=Math.min(this.min,l[a]),this.data.push(l),this.update()}},n};return n.maps?s(n):(n.done(t.proxy(function(t){n=t;var e=s(n);e.isResolved=!0,i.resolve(e)},this)).fail(function(){i.reject()}),i.promise())}),define("unifi/view/map/CoverageView",["backbone","underscore","jquery","heatmap","heatmap-gmaps"],function(t,e,n,i,s){"use strict";return t.View.extend({el:".image-map-coverage-layer",initialize:function(t){e.bindAll(this);this.indexView=t.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(t){this.coverageFilter=t,this.mapChangeHandler()},setMap:function(t){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=t,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 t=n(".image-map-container");if(t.length){var e=n(".ubnt-map-widget").outerWidth(),i=n(".ubnt-map-widget").outerHeight();this.$heatmapElt.css({width:e,height:i});var s=this.$heatmapElt.find("canvas");if(s.length){var a=s[0].getContext("2d");a.canvas.style.width=e+"px",a.canvas.style.height=i+"px",a.canvas.width=e,a.canvas.height=i}this.updateCoverage(!0)}},updateCoverage:e.debounce(function(e){if("map"===t.history.fragment&&this.model&&this.isVisible){if(!e)return void this.resize();"googleMap"===this.model.get("type")?this.updateGoogleMapCoverage():this.updateImageMapCoverage()}},100),updateGoogleMapCoverage:function(){var t=this;if(t.HeatmapOverlay)t._updateGoogleMapCoverage();else{if(t.HeatmapOverlayLoading)return;t.HeatmapOverlayLoading=!0,s.isResolved?(t.HeatmapOverlay=s,t._updateGoogleMapCoverage()):s.done(n.proxy(function(e){t.HeatmapOverlay=e,t._updateGoogleMapCoverage()},this))}},_updateGoogleMapCoverage:function(){var t=this.indexView.map.mapWidget.googleMap,n=t.googleMap;if(window.google.maps.hasOwnProperty("OverlayView")&&t.loaded&&google.maps){this.googleHeatmap&&(this.googleHeatmap.onRemove(),this.googleHeatmap=null),this.googleHeatmap=new this.HeatmapOverlay(n,this.heatmapOptions);var i=function(){return this.googleHeatmap.heatmap?(this.googleData=[],e.each(t.markerViews,function(t){var e=this.calculateCoverage(t.model);e>=0&&this.googleData.push({lat:t.model.get("x"),lng:t.model.get("y"),value:this.markerHeatmapCount,radius:e})},this),void(this.googleData.length?this.googleHeatmap.setData({max:this.dataSetMax,min:this.dataSetMin,data:this.googleData}):this.googleHeatmap.heatmap.setData({data:[]}))):void e.delay(e.bind(i,this),50)};e.delay(e.bind(i,this),50)}},updateImageMapCoverage:function(){var t,s,a,r=this,o=n(".image-map-container"),l=o.find(".marker"),c=n(".image-drag-layer").position(),d=[];this.$el.empty(),this.heatmap=i.create(e.extend(this.heatmapOptions,{container:this.heatmapElt})),window.heatmap=this.heatmap;var h=function(){l.each(function(){t=n(this),s=t.position(),a=t.find(".mac").text();var e=r.calculateCoverage(r.markers.findWhere({mac:a}));e>=0&&d.push({x:s.left+c.left,y:s.top+c.top,value:r.markerHeatmapCount,radius:e})}),this.heatmap.setData({max:this.dataSetMax,min:this.dataSetMin,data:d})};e.delay(e.bind(h,this),50)},calculateCoverage:function(t){var e,n,i,s=100,a=1,r=t.transmitPower("2G"==this.coverageFilter?"ng":"na"),o=t.transmitFrequency("2G"==this.coverageFilter?"ng":"na"),l=this.model.get("unit")||"m",c=this.model.get("upp")||10,d=this.model.get("zoom")||1,h=this.indexView.getActiveMap().scale||1;return c>0?(a=1,c/="m"===l?1:3.2808399,a=10/c*d*h):a=15*d*h,1==t.get("state")&&r>=0?(e=a,n=r,i=Math.pow(10,n/20)/(o/3e5),e*=Math.sqrt(i/200),1>e&&(e=1),e=Math.floor(e),s=e):void 0},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),t.View.prototype.remove.apply(this,arguments)}})}),define("unifi/model/Map",["unifi/model/Model","backbone"],function(t,e){"use strict";return t.extend({defaults:{upp:.5,unit:"m",offset_top:130,offset_left:200,zoom:10},sync:function(t,n,i){switch(i=i||{},t){case"update":i.contentType="application/json; charset=utf-8","googleMap"===this.get("type")?(i.url="/api/s/"+SITE.name+"/rest/map/"+n.id,i.type="PUT",i.data=JSON.stringify(n.attributes)):(i.url="/api/s/"+SITE.name+"/rest/map/"+n.id,i.type="PUT",i.data=JSON.stringify(n.changed));break;case"delete":i.url="/api/s/"+SITE.name+"/rest/map/"+n.id}return e.sync.call(this,t,n,i)}})}),define("unifi/collection/Maps",["unifi/collection/Collection","unifi/model/Map","underscore"],function(t,e){"use strict";return t.extend({model:e,bySite:!0,url:function(t,e){return t?e?"/api/s/"+SITE.name+"/rest/map/":"/upload/map/s/"+SITE.name:"/api/s/"+SITE.name+"/list/map"},createGoogleMapModel:function(t,e){return e=e||{data:null},e.url=this.url(!0,!0),e.data=JSON.stringify(t),this.create(t,e)},comparator:function(t){return t.get("name")}})}),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(t){t.extend(t.fn,{validate:function(e){if(!this.length)return void(e&&e.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing."));var n=t.data(this[0],"validator");return n?n:(this.attr("novalidate","novalidate"),n=new t.validator(e,this[0]),t.data(this[0],"validator",n),n.settings.onsubmit&&(this.validateDelegate(":submit","click",function(e){n.settings.submitHandler&&(n.submitButton=e.target),t(e.target).hasClass("cancel")&&(n.cancelSubmit=!0),void 0!==t(e.target).attr("formnovalidate")&&(n.cancelSubmit=!0)}),this.submit(function(e){function i(){var i;return n.settings.submitHandler?(n.submitButton&&(i=t("<input type='hidden'/>").attr("name",n.submitButton.name).val(t(n.submitButton).val()).appendTo(n.currentForm)),n.settings.submitHandler.call(n,n.currentForm,e),n.submitButton&&i.remove(),!1):!0}return n.settings.debug&&e.preventDefault(),n.cancelSubmit?(n.cancelSubmit=!1,i()):n.form()?n.pendingRequest?(n.formSubmitted=!0,!1):i():(n.focusInvalid(),!1)})),n)},valid:function(){if(t(this[0]).is("form"))return this.validate().form();var e=!0,n=t(this[0].form).validate();return this.each(function(){e=e&&n.element(this)}),e},removeAttrs:function(e){var n={},i=this;return t.each(e.split(/\s/),function(t,e){n[e]=i.attr(e),i.removeAttr(e)}),n},rules:function(e,n){var i=this[0];if(e){var s=t.data(i.form,"validator").settings,a=s.rules,r=t.validator.staticRules(i);switch(e){case"add":t.extend(r,t.validator.normalizeRule(n)),delete r.messages,a[i.name]=r,n.messages&&(s.messages[i.name]=t.extend(s.messages[i.name],n.messages));break;case"remove":if(!n)return delete a[i.name],r;var o={};return t.each(n.split(/\s/),function(t,e){o[e]=r[e],delete r[e]}),o}}var l=t.validator.normalizeRules(t.extend({},t.validator.classRules(i),t.validator.attributeRules(i),t.validator.dataRules(i),t.validator.staticRules(i)),i);if(l.required){var c=l.required;delete l.required,l=t.extend({required:c},l)}return l}}),t.extend(t.expr[":"],{blank:function(e){return!t.trim(""+t(e).val())},filled:function(e){return!!t.trim(""+t(e).val())},unchecked:function(e){return!t(e).prop("checked")}}),t.validator=function(e,n){this.settings=t.extend(!0,{},t.validator.defaults,e),this.currentForm=n,this.init()},t.validator.format=function(e,n){return 1===arguments.length?function(){var n=t.makeArray(arguments);return n.unshift(e),t.validator.format.apply(this,n)}:(arguments.length>2&&n.constructor!==Array&&(n=t.makeArray(arguments).slice(1)),n.constructor!==Array&&(n=[n]),t.each(n,function(t,n){e=e.replace(new RegExp("\\{"+t+"\\}","g"),function(){return n})}),e)},t.extend(t.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:!0,errorContainer:t([]),errorLabelContainer:t([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(t){this.lastActive=t,this.settings.focusCleanup&&!this.blockFocusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,t,this.settings.errorClass,this.settings.validClass),this.addWrapper(this.errorsFor(t)).hide())},onfocusout:function(t){this.checkable(t)||!(t.name in this.submitted)&&this.optional(t)||this.element(t)},onkeyup:function(t,e){(9!==e.which||""!==this.elementValue(t))&&(t.name in this.submitted||t===this.lastElement)&&this.element(t)},onclick:function(t){t.name in this.submitted?this.element(t):t.parentNode.name in this.submitted&&this.element(t.parentNode)},highlight:function(e,n,i){"radio"===e.type?this.findByName(e.name).addClass(n).removeClass(i):t(e).addClass(n).removeClass(i)},unhighlight:function(e,n,i){"radio"===e.type?this.findByName(e.name).removeClass(n).addClass(i):t(e).removeClass(n).addClass(i)}},setDefaults:function(e){t.extend(t.validator.defaults,e)},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:t.validator.format("Please enter no more than {0} characters."),minlength:t.validator.format("Please enter at least {0} characters."),rangelength:t.validator.format("Please enter a value between {0} and {1} characters long."),range:t.validator.format("Please enter a value between {0} and {1}."),max:t.validator.format("Please enter a value less than or equal to {0}."),min:t.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:!1,prototype:{init:function(){function e(e){var n=t.data(this[0].form,"validator"),i="on"+e.type.replace(/^validate/,"");n.settings[i]&&n.settings[i].call(n,this[0],e)}this.labelContainer=t(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||t(this.currentForm),this.containers=t(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var n=this.groups={};t.each(this.settings.groups,function(e,i){"string"==typeof i&&(i=i.split(/\s/)),t.each(i,function(t,i){n[i]=e})});var i=this.settings.rules;t.each(i,function(e,n){i[e]=t.validator.normalizeRule(n)}),t(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",e).validateDelegate("[type='radio'], [type='checkbox'], select, option","click",e),this.settings.invalidHandler&&t(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){return this.checkForm(),t.extend(this.submitted,this.errorMap),this.invalid=t.extend({},this.errorMap),this.valid()||t(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var t=0,e=this.currentElements=this.elements();e[t];t++)this.check(e[t]);return this.valid()},element:function(e){e=this.validationTargetFor(this.clean(e)),this.lastElement=e,this.prepareElement(e),this.currentElements=t(e);var n=this.check(e)!==!1;return n?delete this.invalid[e.name]:this.invalid[e.name]=!0,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),n},showErrors:function(e){if(e){t.extend(this.errorMap,e),this.errorList=[];for(var n in e)this.errorList.push({message:e[n],element:this.findByName(n)[0]});this.successList=t.grep(this.successList,function(t){return!(t.name in e)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){t.fn.resetForm&&t(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(t){var e=0;for(var n in t)e++;return e},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{t(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(e){}},findLastActive:function(){var e=this.lastActive;return e&&1===t.grep(this.errorList,function(t){return t.element.name===e.name}).length&&e},elements:function(){var e=this,n={};return t(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){return!this.name&&e.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.name in n||!e.objectLength(t(this).rules())?!1:(n[this.name]=!0,!0)})},clean:function(e){return t(e)[0]},errors:function(){var e=this.settings.errorClass.replace(" ",".");return t(this.settings.errorElement+"."+e,this.errorContext)},reset:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=t([]),this.toHide=t([]),this.currentElements=t([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(t){this.reset(),this.toHide=this.errorsFor(t)},elementValue:function(e){var n=t(e).attr("type"),i=t(e).val();return"radio"===n||"checkbox"===n?t("input[name='"+t(e).attr("name")+"']:checked").val():"string"==typeof i?i.replace(/\r/g,""):i},check:function(e){e=this.validationTargetFor(this.clean(e));var n,i=t(e).rules(),s=!1,a=this.elementValue(e);for(var r in i){var o={method:r,parameters:i[r]};try{if(n=t.validator.methods[r].call(this,a,e,o.parameters),"dependency-mismatch"===n){s=!0;continue}if(s=!1,"pending"===n)return void(this.toHide=this.toHide.not(this.errorsFor(e)));if(!n)return this.formatAndAdd(e,o),!1}catch(l){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+e.id+", check the '"+o.method+"' method.",l),l}}return s?void 0:(this.objectLength(i)&&this.successList.push(e),!0)},customDataMessage:function(e,n){return t(e).data("msg-"+n.toLowerCase())||e.attributes&&t(e).attr("data-msg-"+n.toLowerCase())},customMessage:function(t,e){var n=this.settings.messages[t];return n&&(n.constructor===String?n:n[e])},findDefined:function(){for(var t=0;t<arguments.length;t++)if(void 0!==arguments[t])return arguments[t];return void 0},defaultMessage:function(e,n){return this.findDefined(this.customMessage(e.name,n),this.customDataMessage(e,n),!this.settings.ignoreTitle&&e.title||void 0,t.validator.messages[n],"<strong>Warning: No message defined for "+e.name+"</strong>")},formatAndAdd:function(e,n){var i=this.defaultMessage(e,n.method),s=/\$?\{(\d+)\}/g;"function"==typeof i?i=i.call(this,n.parameters,e):s.test(i)&&(i=t.validator.format(i.replace(s,"{$1}"),n.parameters)),this.errorList.push({message:i,element:e}),this.errorMap[e.name]=i,this.submitted[e.name]=i},addWrapper:function(t){return this.settings.wrapper&&(t=t.add(t.parent(this.settings.wrapper))),t},defaultShowErrors:function(){var t,e;for(t=0;this.errorList[t];t++){var n=this.errorList[t];this.settings.highlight&&this.settings.highlight.call(this,n.element,this.settings.errorClass,this.settings.validClass),this.showLabel(n.element,n.message)}if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(t=0;this.successList[t];t++)this.showLabel(this.successList[t]);if(this.settings.unhighlight)for(t=0,e=this.validElements();e[t];t++)this.settings.unhighlight.call(this,e[t],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 t(this.errorList).map(function(){return this.element})},showLabel:function(e,n){var i=this.errorsFor(e);i.length?(i.removeClass(this.settings.validClass).addClass(this.settings.errorClass),i.html(n)):(i=t("<"+this.settings.errorElement+">").attr("for",this.idOrName(e)).addClass(this.settings.errorClass).html(n||""),this.settings.wrapper&&(i=i.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.append(i).length||(this.settings.errorPlacement?this.settings.errorPlacement(i,t(e)):i.insertAfter(e))),!n&&this.settings.success&&(i.text(""),"string"==typeof this.settings.success?i.addClass(this.settings.success):this.settings.success(i,e)),this.toShow=this.toShow.add(i)},errorsFor:function(e){var n=this.idOrName(e);return this.errors().filter(function(){return t(this).attr("for")===n})},idOrName:function(t){return this.groups[t.name]||(this.checkable(t)?t.name:t.id||t.name)},validationTargetFor:function(t){return this.checkable(t)&&(t=this.findByName(t.name).not(this.settings.ignore)[0]),t},checkable:function(t){return/radio|checkbox/i.test(t.type)},findByName:function(e){return t(this.currentForm).find("[name='"+e+"']")},getLength:function(e,n){switch(n.nodeName.toLowerCase()){case"select":return t("option:selected",n).length;case"input":if(this.checkable(n))return this.findByName(n.name).filter(":checked").length}return e.length},depend:function(t,e){return this.dependTypes[typeof t]?this.dependTypes[typeof t](t,e):!0},dependTypes:{"boolean":function(t){return t},string:function(e,n){return!!t(e,n.form).length},"function":function(t,e){return t(e)}},optional:function(e){var n=this.elementValue(e);return!t.validator.methods.required.call(this,n,e)&&"dependency-mismatch"},startRequest:function(t){this.pending[t.name]||(this.pendingRequest++,this.pending[t.name]=!0)},stopRequest:function(e,n){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[e.name],n&&0===this.pendingRequest&&this.formSubmitted&&this.form()?(t(this.currentForm).submit(),this.formSubmitted=!1):!n&&0===this.pendingRequest&&this.formSubmitted&&(t(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(e){return t.data(e,"previousValue")||t.data(e,"previousValue",{old:null,valid:!0,message:this.defaultMessage(e,"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(e,n){e.constructor===String?this.classRuleSettings[e]=n:t.extend(this.classRuleSettings,e)},classRules:function(e){var n={},i=t(e).attr("class");return i&&t.each(i.split(" "),function(){this in t.validator.classRuleSettings&&t.extend(n,t.validator.classRuleSettings[this])}),n},attributeRules:function(e){var n={},i=t(e),s=i[0].getAttribute("type");for(var a in t.validator.methods){var r;"required"===a?(r=i.get(0).getAttribute(a),""===r&&(r=!0),r=!!r):r=i.attr(a),/min|max/.test(a)&&(null===s||/number|range|text/.test(s))&&(r=Number(r)),r?n[a]=r:s===a&&"range"!==s&&(n[a]=!0)}return n.maxlength&&/-1|2147483647|524288/.test(n.maxlength)&&delete n.maxlength,n},dataRules:function(e){var n,i,s={},a=t(e);for(n in t.validator.methods)i=a.data("rule-"+n.toLowerCase()),void 0!==i&&(s[n]=i);return s},staticRules:function(e){var n={},i=t.data(e.form,"validator");return i.settings.rules&&(n=t.validator.normalizeRule(i.settings.rules[e.name])||{}),n},normalizeRules:function(e,n){return t.each(e,function(i,s){if(s===!1)return void delete e[i];if(s.param||s.depends){var a=!0;switch(typeof s.depends){case"string":a=!!t(s.depends,n.form).length;break;case"function":a=s.depends.call(n,n)}a?e[i]=void 0!==s.param?s.param:!0:delete e[i]}}),t.each(e,function(i,s){e[i]=t.isFunction(s)?s(n):s}),t.each(["minlength","maxlength"],function(){e[this]&&(e[this]=Number(e[this]))}),t.each(["rangelength","range"],function(){var n;e[this]&&(t.isArray(e[this])?e[this]=[Number(e[this][0]),Number(e[this][1])]:"string"==typeof e[this]&&(n=e[this].split(/[\s,]+/),e[this]=[Number(n[0]),Number(n[1])]))}),t.validator.autoCreateRanges&&(e.min&&e.max&&(e.range=[e.min,e.max],delete e.min,delete e.max),e.minlength&&e.maxlength&&(e.rangelength=[e.minlength,e.maxlength],delete e.minlength,delete e.maxlength)),e},normalizeRule:function(e){if("string"==typeof e){var n={};t.each(e.split(/\s/),function(){n[this]=!0}),e=n}return e},addMethod:function(e,n,i){t.validator.methods[e]=n,t.validator.messages[e]=void 0!==i?i:t.validator.messages[e],n.length<3&&t.validator.addClassRules(e,t.validator.normalizeRule(e))},methods:{required:function(e,n,i){if(!this.depend(i,n))return"dependency-mismatch";if("select"===n.nodeName.toLowerCase()){var s=t(n).val();return s&&s.length>0}return this.checkable(n)?this.getLength(e,n)>0:t.trim(e).length>0},email:function(t,e){return this.optional(e)||/^((([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(t)},url:function(t,e){return this.optional(e)||/^(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(t)},date:function(t,e){return this.optional(e)||!/Invalid|NaN/.test(new Date(t).toString())},dateISO:function(t,e){return this.optional(e)||/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(t)},number:function(t,e){return this.optional(e)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(t)},digits:function(t,e){return this.optional(e)||/^\d+$/.test(t)},creditcard:function(t,e){if(this.optional(e))return"dependency-mismatch";if(/[^0-9 \-]+/.test(t))return!1;var n=0,i=0,s=!1;t=t.replace(/\D/g,"");for(var a=t.length-1;a>=0;a--){var r=t.charAt(a);i=parseInt(r,10),s&&(i*=2)>9&&(i-=9),n+=i,s=!s}return n%10===0},minlength:function(e,n,i){var s=t.isArray(e)?e.length:this.getLength(t.trim(e),n);return this.optional(n)||s>=i},maxlength:function(e,n,i){var s=t.isArray(e)?e.length:this.getLength(t.trim(e),n);return this.optional(n)||i>=s},rangelength:function(e,n,i){var s=t.isArray(e)?e.length:this.getLength(t.trim(e),n);return this.optional(n)||s>=i[0]&&s<=i[1]},min:function(t,e,n){return this.optional(e)||t>=n},max:function(t,e,n){return this.optional(e)||n>=t},range:function(t,e,n){return this.optional(e)||t>=n[0]&&t<=n[1]},equalTo:function(e,n,i){var s=t(i);return this.settings.onfocusout&&s.unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){t(n).valid()}),e===s.val()},remote:function(e,n,i){if(this.optional(n))return"dependency-mismatch";var s=this.previousValue(n);if(this.settings.messages[n.name]||(this.settings.messages[n.name]={}),s.originalMessage=this.settings.messages[n.name].remote,this.settings.messages[n.name].remote=s.message,i="string"==typeof i&&{url:i}||i,s.old===e)return s.valid;s.old=e;var a=this;this.startRequest(n);var r={};return r[n.name]=e,t.ajax(t.extend(!0,{url:i,mode:"abort",port:"validate"+n.name,dataType:"json",data:r,success:function(i){a.settings.messages[n.name].remote=s.originalMessage;var r=i===!0||"true"===i;if(r){var o=a.formSubmitted;a.prepareElement(n),a.formSubmitted=o,a.successList.push(n),delete a.invalid[n.name],a.showErrors()}else{var l={},c=i||a.defaultMessage(n,"remote");l[n.name]=s.message=t.isFunction(c)?c(e):c,a.invalid[n.name]=!0,a.showErrors(l)}s.valid=r,a.stopRequest(n,r)}},i)),"pending"}}}),t.format=t.validator.format}(jQuery),function(t){var e={};if(t.ajaxPrefilter)t.ajaxPrefilter(function(t,n,i){var s=t.port;"abort"===t.mode&&(e[s]&&e[s].abort(),e[s]=i)});else{var n=t.ajax;t.ajax=function(i){var s=("mode"in i?i:t.ajaxSettings).mode,a=("port"in i?i:t.ajaxSettings).port;return"abort"===s?(e[a]&&e[a].abort(),e[a]=n.apply(this,arguments),e[a]):n.apply(this,arguments)}}}(jQuery),function(t){t.extend(t.fn,{validateDelegate:function(e,n,i){return this.bind(n,function(n){var s=t(n.target);return s.is(e)?i.apply(s,arguments):void 0})}})}(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(t,e,n,i,s,a,r,o,l,c){"use strict";return e.extend({_fullyQualifiedName:"UBNT.views.map.AddEditMapDialog",initialize:function(n){t.bindAll(this);var s=this;this.template=t.template(c),this.mapIndexView=n.mapIndexView;var a={title:i.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(){s.mapIndexView.addMapPending=!1,s.destroy(),s.mapIndexView.configureMapsHandler()}},DoneButton:{buttonClass:"ui-button-positive button tall auto green",handler:this.addMapHandler},buttons:{},close:this.destroy};a.buttons[i.G_Cancel]=a.CancelButton,a.buttons[i.G_Done]=a.DoneButton,n.dialogOptions=t.extend(a,n.dialogOptions||{}),e.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(){s.validator.addMethod("regex",function(t,e,n){return this.optional(e)||n.test(t)},""),s.validator.addMethod("custom_xregex",function(t,e){var n=new a("^[\\p{L}\\p{Z}\\p{P}\\p{S}\\p{N}]{0,}$");return this.optional(e)||n.test(t)},""),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 t=this;return this.geocoder.geocode({address:s('input[name="location"]').val()},function(e,s){if(s===google.maps.GeocoderStatus.OK)t.googleMap.setOptions({center:e[0].geometry.location});else switch(t.errorDialog||(t.errorDialog=new n),s){case"ZERO_RESULTS":t.errorDialog.open(i.E_GoogleNotFound);break;default:t.errorDialog.open(s)}}),!1},setImageMap:function(){var t=this.$mapImageBrowser.get(0).files[0],e=new FileReader,n=this;e.onload=function(t){n.$mapImage.attr("src",t.target.result)},e.readAsDataURL(t)},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 t=s("body");if(this.$mapImage.hide(),this.$selectMapLink.hide(),this.$setLocation.show(),this.$googleMapContainer.show(),t.hasClass("googlemaps-notLoaded"))window.googleMapsNotLoaded();else if(r.loaded||s("body").bind("googleMapsLoaded.AddMapDialog",this.googleMapLoadedHandler),r.loading||r.loaded||(window.UBNTMapGoogleMapCallback=function(){r.loaded=!0,l.initialize(),o.initialize(),s("body").trigger("googleMapsLoaded")},r.loading=!0,window.google&&window.google.maps&&window.UBNTMapGoogleMapCallback()),r.loaded){var e=new google.maps.LatLng(37.411146,-121.943083),n={};n=this.model&&"googleMap"===this.model.get("type")?{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")}:{zoom:14,center:e,mapTypeId:google.maps.MapTypeId.SATELLITE,tilt:0},null===this.googleMap||void 0===this.googleMap?(this.googleMap=new google.maps.Map(this.$googleMapContainer.get(0),n),this.geocoder=new google.maps.Geocoder):this.googleMap.setOptions(n)}},setModel:function(t){this.model=t,this.render()},removeMarkers:function(){var e=this,n=t.filter(this.mapIndexView.markers.models,function(t){return e.model&&t.get("map_id")==e.model.id});t.each(n,function(t){t.save({map_id:"",x:"",y:""})})},saveMap:function(){var t=this,e={name:this.$mapLabel.val(),type:this.$('input[type="radio"]:checked').val()};switch(e.type){case"imageMap":var s=this.$mapImageBrowser.get(0).files[0];if(s){this.mapIndexView.addMapPending=!0,this.removeMarkers();var a=new XMLHttpRequest,r=new FormData(this.$form.get(0));a.upload.addEventListener("progress",this.handleUploadProgress,!1),a.addEventListener("load",this.handleUploadComplete,!1),a.addEventListener("error",this.handleUploadFailed,!1),a.addEventListener("abort",this.handleUploadCanceled,!1),a.open("POST","/upload/s/"+SITE.name+"/map"+(null===this.model?"":"/"+this.model.get("_id"))),a.setRequestHeader("X-Requested-With","XMLHttpRequest"),a.send(r)}else this.model&&this.$mapImage.attr("src")?this.model.save(e,{success:this.destroy}):(this.errorDialog||(this.errorDialog=new n),this.errorDialog.open(i.E_NoImageSpecified));break;case"googleMap":e.lat=this.googleMap.getCenter().lat(),e.lng=this.googleMap.getCenter().lng(),e.zoom=this.googleMap.getZoom(),e.tilt=this.googleMap.getTilt(),e.mapTypeId=this.googleMap.getMapTypeId(),this.model?(this.removeMarkers(),this.model.save(e,{wait:!0,success:t.destroy})):(this.mapIndexView.addMapPending=!0,this.collection.createGoogleMapModel(e,{wait:!0,success:t.destroy}))}},render:function(){if(e.prototype.render.apply(this,[]),this.isRenderedd||(this.isRenderedd=!0,this.initElements(),this.initHandlers(),this.initValidation(),this.$searchButton.button(),s(".ui-button-cancel").attr("tabindex",4).button({icons:{primary:"ubnt-icon-close"}}),s(".ui-button-positive").attr("tabindex",5).button({icons:{primary:"ubnt-icon-check"}}),this.$uploadImageLabel.find(".ui-button-text").text(i.G_MapUploadImage),this.$mapTypeLabel.find(".ui-button-text").text(i.G_MapGoogleMaps),this.$notMap.text(i.G_MapNotWhatYouLookingFor),this.$selectDiffMap.text(i.G_MapSelectDiffMap),this.$buttonLocate.find("span.copy").text(i.G_Locate)),this.$mapLabel.val(""),this.$mapImage.hide(),this.model){this.$el.dialog("option",{title:i.G_MapEditMapHeader}),this.$mapLabel.val(this.model.get("name"));var t=this.model.get("type")||"imageMap";"imageMap"===t?(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(s('input[value="'+t+'"]'))}else this.$el.dialog("option",{title:i.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(s.cookie("unifises"))},imageMapLoadHandler:function(t){this.$mapImage.css("width","auto"),this.$mapImage.css("height","auto");var e=t.target.width,n=t.target.height,i=this.$imageMapContainer.width(),s=this.$imageMapContainer.height();e/n>i/s?(this.$mapImage.height(i/e*n),this.$mapImage.width(i),this.$mapImage.css("margin-top",(s-this.$mapImage.height())/2+"px"),this.$mapImage.css("margin-left","0px")):(this.$mapImage.width(s/n*e),this.$mapImage.height(s),this.$mapImage.css("margin-left",(i-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(t){var e=s(t.target).val();switch(e){case"imageMap":this.showImageMap();break;case"googleMap":this.showGoogleMap()}},googleMapLoadedHandler:function(){s("body").unbind("googleMapsLoaded.AddMapDialog"),this.showGoogleMap()},addMapHandler:function(){this.$form.submit()},handleUploadProgress:function(){},handleUploadComplete:function(t){var n=s.parseJSON(t.currentTarget.response).data[0],i=this.collection.get(n._id);i?i.set(n,{silent:!1}):this.collection.add(n),e.prototype.destroy.apply(this,arguments),this.$mapImageBrowser.val("")},handleUploadFailed:function(){},handleUploadCanceled:function(){},dialogOpenHandler:function(){this.model&&"googleMap"===this.model.get("type")?(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.prototype.dialogCloseHandler.apply(this,arguments),this.setDefaultMapType=null},hide:function(){e.prototype.hide.apply(this,arguments)},destroy:function(){e.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),s("body").unbind("googleMapsLoaded.AddMapDialog",this.googleMapLoadedHandler),this.isRenderedd=!1,e.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.7.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(t,e,n,i,s){"use strict";return e.extend({_fullyQualifiedName:"UBNT.views.dialogs.ConfirmRemoveDialog",initialize:function(){t.bindAll(this),this.template=t.template(s);var i={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:{}};i.buttons[n.G_Cancel]=i.CancelButton,i.buttons[n.G_Confirm]=i.ConfirmButton,this.options.dialogOptions=t.extend(i,this.options.dialogOptions||{}),e.prototype.initialize.apply(this,[this.options])},render:function(){e.prototype.render.apply(this,[]),i(".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.7.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(t){this.map=t,"imageMap"===this.map.get("type")&&(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(t,e,n,i,s){"use strict";return e.extend({_fullyQualifiedName:"UBNT.views.map.ConfigureMapsDialog",initialize:function(i){t.bindAll(this),this.mapIndexView=i.mapIndexView,this.template=t.template(s);var a={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};a.buttons[n.G_MapAddMap]=a.AddMapButton,a.buttons[n.G_Done]=a.DoneButton,i.dialogOptions=t.extend(a,i.dialogOptions||{}),e.prototype.initialize.apply(this,[i]),this.collection.on("change",this.updateMapNames)},render:function(){var t={items:this.collection.toJSON(),length:this.collection.length};e.prototype.render.apply(this,[{template_json:t}]),this.$tableCellMapName=i("thead .table-cell-map-name"),this.$tableCellActions=i("thead .table-cell-actions"),this.$noMaps=i(".no-maps"),this.$edit=i(".edit span"),this.$remove=i(".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||(i(".ui-button-cancel").button({icons:{primary:"ubnt-icon-close"}}),i(".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 e=this;t.each(this.collection.models,function(t){e.$(".map-"+t.get("_id")).find(".table-cell-map-name").text(t.get("name"))})},setModel:function(t){this.model=t},editMapHandler:function(t){this.destroy(),this.mapIndexView.editMapClickHandler(t)},removeMapHandler:function(t){this.destroy();var e=i(t.target).parents(".table-row").data("id"),n=this.collection.findWhere({_id:e});this.mapIndexView.removeMapClickHandler(n)},addMapHandler:function(){this.destroy(),this.mapIndexView.addMapClickHandler()},remove:function(){this.collection.off("change",this.updateMapNames),this.isRendered=!1,e.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(t,e,n,i,s,a,r,o,l,c,d,h,u,p,m,f,g,v,b,w,y,_){"use strict";return s.extend({template:e.template(a),id:"mapIndex",initialize:function(t){s.prototype.initialize.call(this,t),this._dependencies=n.Deferred(),this.drawerHidden=!0,n.when(this._dependencies).then(this.render,this.failed),this.dependencies()},render:function(){if("pending"!==this._dependencies.state()){var t=this;if(s.prototype.render.call(this),!this.rendered&&(this.rendered=!0)){if(this.maps=this.app.collection("Maps"),this.markers=this.options.app.collection("Devices"),this.$el.html(this.template({msg:i})),this.$el.find("select").each(function(){var t=n(this),e=t.parent();"mapSelect"!=t.attr("name")&&t.selectmenu({parent:e,appendTo:e,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 v({el:this.$mapSelect,collection:this.maps,width:200,create:function(e,s){s.menuWrap.append(n('<div class="ui-menu-item configure-maps is-admin"><span class="ubnt-icon-gear gear"></span>'+i.G_ConfigureMaps+"</div>").on("click",function(){t.configureMapsHandler()}).on("mouseover",function(){s.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 h({el:this.$("div.marker-drawer"),markers:this.markers,maps:this.maps,markerView:u,unplacedMarkerTemplate:e.template(o),unplacedMarkerDraggableTemplate:e.template(l)}),this.$markerDrawer=this.markerDrawer.render(),this.maps.models[0]){var a=n.cookie?n.cookie("default-map"):null,g=this.maps.get(a)||this.maps.models[0];
g&&(this.mapSelector.set(g.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:d.extend({app:this.options.app}),markerTemplate:e.template(r)}),this.coverageView=new f({indexView:this}),this.topologyView=new m({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 c({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(){this.markerDrawer.hasUnplacedMarkers()&&this.showDrawer()},updateDevice:function(t){var e=t.changedAttributes();(void 0!==e.map_id||void 0!==e.provisioned)&&(this.markerDrawer.hasUnplacedMarkers()?this.showDrawer():this.hideDrawer())},removeDevice:function(){this.markerDrawer.hasUnplacedMarkers()?this.showDrawer():this.hideDrawer()},resetDevices:function(){},configureMapsHandler:function(){var t=new y({mapIndexView:this,collection:this.maps});t.render()},toggleDrawer:function(){this.drawerHidden?this.showDrawer():this.hideDrawer()},showDrawer:function(){this.markerDrawer.$el.addClass("is-open"),this.drawerHidden=!1},hideDrawer:function(){this.markerDrawer.$el.removeClass("is-open"),this.drawerHidden=!0},mapSelectHandler:function(){var t=this.$mapSelect.val();n.cookie&&n.cookie("default-map",t);var e=this.maps.findWhere({_id:t});this.setMap(e)},setMap:function(t){this.model&&this.model.off("change:zoom",this.mapZoomHandler),this.model=t,this.model.on("change:zoom",this.mapZoomHandler),this.map.setMap(t),this.coverageView.setMap(t),this.topologyView.setMap(t),this.setZoom(this.model.get("zoom"),!0)},getActiveMap:function(){var t=this.model;return t?"googleMap"===t.get("type")?this.map.mapWidget.googleMap:this.map.mapWidget.imageMap:null},setScaleBar:function(){var t,e,n=this.getActiveMap(),i=1;n&&(e=this.model.get("upp")||.5,t=1*n.scale*n.zoomLevel*e,i=t>1e4||Math.abs(t-1e4)<Math.abs(t-5e3)?1e4:t>5e3||Math.abs(t-5e3)<Math.abs(t-1e3)?5e3:t>1e3||Math.abs(t-1e3)<Math.abs(t-500)?1e3:t>500||Math.abs(t-500)<Math.abs(t-100)?500:t>100||Math.abs(t-100)<Math.abs(t-50)?100:Math.abs(t-50)<Math.abs(t-20)?50:Math.abs(t-20)<Math.abs(t-10)?20:Math.abs(t-10)<Math.abs(t-5)?10:Math.abs(t-5)<Math.abs(t-1)?5:1,this.$scaleMeasurement.text(i+" "+(this.model.get("unit")||"m")),this.$scaleIcon.width(i*n.scale*this.model.get("zoom")/e),this.$scale.show())},setUpp:function(t,e,n){var i,s=this.getActiveMap();return s&&(i=e*s.scale*this.model.get("zoom"),this.app.isReadOnly?s.model.set({upp:i,unit:n}):s.model.save({upp:i,unit:n}),this.setScaleBar()),!1},mapViewClick:function(){var t=this.$('input[name="filter"]:checked'),i=[];t.each(function(){i.push(n(this).val())}),this.mapView||(this.mapView=[]),this.map.$el.removeClass(this.mapView.join(" ")).addClass(i.join(" ")),this.mapView=i,e.contains(this.mapView,"details")?(n("#mapFilterDetails").next("label:first").addClass("ui-state-active"),this.map.$el.removeClass("labels")):this.map.$el.addClass("labels"),e.contains(this.mapView,"coverage")?(n("#mapFilterCoverage").next("label:first").addClass("ui-state-active"),this.coverageView.show()):this.coverageView.hide(),e.contains(this.mapView,"details")||e.contains(this.mapView,"coverage")?this.$(".buttonset.coverage").show():this.$(".buttonset.coverage").hide(),e.contains(this.mapView,"topology")?(n("#mapFilterTopology").next("label:first").addClass("ui-state-active"),this.topologyView.show()):this.topologyView.hide()},mapCoverageViewClick:function(){var t=this.$('input[name="coverageFilter"]:checked'),i=[];t.each(function(){i.push(n(this).val())}),this.mapViewCoverageType||(this.mapViewCoverageType=[]),this.map.$el.removeClass(this.mapViewCoverageType.join(" ")).addClass(i.join(" ")),this.mapViewCoverageType=i,e.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")),e.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(t,e){var n=e.value;this.setZoom(n,!1,!0)},zoomOut:function(){var t=this.$slider.slider("value"),e=this.$slider.slider("option","min"),n=t-1;return n>=e&&this.setZoom(n),!1},zoomIn:function(){var t=this.$slider.slider("value"),e=this.$slider.slider("option","max"),n=t+1;return e>=n&&this.setZoom(n),!1},mapZoomHandler:function(t){this.setZoom(t.get("zoom"),!0)},setZoom:function(t,e,n){n||this.$slider.slider("option","value",t),this.model.set({zoom:t}),this.setScaleBar(),e||this.app.isReadOnly||this.saveZoom(t)},saveZoom:e.debounce(function(t){this.model.unset("zoom",{silent:!0}),this.model.save({zoom:t},{silent:!0})},250),addMapClickHandler:function(){this.addEditMapDialog=new b({collection:this.maps,mapIndexView:this}),this.$addEditMapDialog=this.addEditMapDialog.render(),this.addEditMapDialog.setModel(null),this.addEditMapDialog.show()},editMapClickHandler:function(t){var e=this.maps.get(n(t.target).parents(".table-row:first").data("id"));e&&(this.addEditMapDialog=new b({collection:this.maps,model:e,mapIndexView:this}),this.$addEditMapDialog=this.addEditMapDialog.render(),this.addEditMapDialog.setModel(e),this.addEditMapDialog.show())},removeMapClickHandler:function(t){var e=new w({cancelHandler:this.cancelRemoveMapHandler,confirmHandler:this.confirmRemoveMapHandler});e.show(t)},cancelRemoveMapHandler:function(){this.configureMapsHandler(),this.removeMapPending=!1},confirmRemoveMapHandler:function(t){var e=this;t&&(this.maps.remove(t),t.destroy({success:function(){var t=e.maps.at(0);t&&(e.setMap(t),e.mapSelector.set(t.id))}})),this.configureMapsHandler()},addMap:function(t){this.addMapPending&&(this.addMapPending=!1,n(".ui-dialog").is(":visible")||this.configureMapsHandler(),this.setMap(t),this.mapSelector.set(t.id))},updateMap:function(){},removeMap:function(t){if(this.model.id===t.id){var e=this.maps.at(0);e&&(this.setMap(e),this.mapSelector.set(e.id))}this.removeMapPending&&(this.removeMapPending=!1,this.configureMapsHandler())},resetMaps:function(){},dependencies:function(){var t={Maps:g},i=[],s={},a=this;e.each(t,function(t,e){i.push(s[e]=n.Deferred())},this),n.when.apply(n,i).then(function(){a._dependencies.resolve()},function(){a._dependencies.reject()}),e.each(t,function(t,e){this.app.collection(e,{fetch:{reload:!1,deferred:s[e]}},t)},this)},failed:function(){(new _).open(i.E_DataLoad)},locateDevice:function(t){this.rendered?(this.$mapSelect.val(t.get("map_id")),this.mapSelectHandler(),this.markers.get(t)&&this.map.locateDevice(t)):e.delay(this.locateDevice,50,t)},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,s.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(t,e,n,i){"use strict";return t.extend({_fullyQualifiedName:"UNIFI.Routers.Map",_associatedViews:{Index:e,Marker:n,UnplacedMarker:i},routes:{map:"index"}})}),define("unifi/view/app/PropertyView",["backbone","underscore","jquery","ubnt/backgrid","ubnt/view/dialogs/ErrorDialogView","msg/Msg"],function(t,e,n,i,s,a){"use strict";return t.View.extend({tagName:"div",className:"properties accordion",templateId:null,_autoRender:!1,_detached:!1,initialize:function(t){if(!this.templateId)throw"Missing templateId";e.bindAll(this),this.template=e.template(this.templateId),this.properties=t.properties,this.parent=t.parent,this.app=this.parent.app,this.id=t.property_id,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(t){return!this.rendered&&(this.rendered=!0)?(this.$el.html(this.template(e.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(){return n(this).hasClass("ui-dragging-stopped")?!1:void 0},activate:n.proxy(function(){this.position()},this)}),this.$el.find(".accordion .accordion-header").on("click",this.renderSelects),this.$el.find(".accordion-header .remove").on("click",n.proxy(function(t){t.stopPropagation(),t.preventDefault(),this.remove()},this)),this.$el.find(".accordion-header .detach").on("click",n.proxy(function(t){t.stopPropagation(),t.preventDefault(),this._detached?this.attach():this.detach()},this)),this.$tabs.tabs({activate:n.proxy(function(){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)):(t||(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 t=n(this),e=t.parent(),i=t.data("selectRendered"),s=t.data("myposition")||"left top",a=t.data("atposition")||"left bottom";i||(t.selectmenu({parent:e,appendTo:e,icons:{button:"ubnt-icon-arrow-down secondary-color"},position:{my:s,at:a,collision:"flip"},change:function(e,n){var i=n.item.element.parents(".row:first"),s=i.next(".custom:first");"custom"===n.item.value?s.show():s.hide(),t.trigger("change")}}),t.data("selectRendered",!0).trigger("change",!0))})},args:function(){return{_id:this.id,msg:a}},remove:function(){this.model&&(this.parent.properties[this.model.get("mac")]=null,delete this.parent.properties[this.model.get("mac")]),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(),e.each(this.grids,function(t){t.remove()}),this.grids={},this.removeTooltips(),this.$el.fadeOut(n.proxy(function(){t.View.prototype.remove.apply(this,arguments),this.$container.trigger("property:remove")},this))},attach:function(t){this.removeTooltips(),t||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",a.G_Detach).tooltip({show:!1,hide:!1,track:!0,close:n.proxy(function(){this.$el.find(".accordion-header .detach").attr("title",this._detached?a.G_Attach:a.G_Detach)},this)}),this.overflow(!1),this._detached=!1,this.$container.trigger("property:render")},detach:function(t){var e=this.properties.$detached.find("> div.properties").size();this.removeTooltips(),t||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(t){n(t.target).addClass("ui-dragging-stopped").delay(300).queue(function(t){n(this).removeClass("ui-dragging-stopped"),t()})}}).resizable({handles:"e"}).css("width","").css("position","absolute").position({my:"center+"+10*e+" center+"+10*e,of:n.Window}).accordion("option","animate",200).trigger("click").find(".accordion-header .detach").attr("title",a.G_Attach).tooltip({show:!1,hide:!1,track:!0,close:n.proxy(function(){this.$el.find(".accordion-header .detach").attr("title",this._detached?a.G_Attach:a.G_Detach)},this)}),this._detached=!0,this.position(),this.$container.trigger("property:remove")},removeTooltips:function(){n(".ui-tooltip-content").parents("div").remove()},overflow:function(t){if(this.$overflow.css("max-height",""),t){var e=n(window).height(),i=this.$el.outerHeight(!0)-this.$overflow.height();this.$overflow.css("max-height",Math.max(0,e-i)+"px")}},position:function(){if(this._detached){this.overflow(!1);var t=this.$el.offset().top;0>t&&this.$el.css("top",t=0);var e,i=t+this.$el.outerHeight(!0),s=i-n(window).height();s>0&&((e=(t-=s)<0)&&(t=0),this.$el.css("top",t),e&&this.overflow(!0))}},grid:function(t,n,s,a,r){if(n){var o=new i.Grid(r=e.extend({columns:t,collection:n,pageable:!0,footer:i.Paginators.Mini,noRows:a},r||{}));return s.html(o.render().$el),r.pageable&&o.paginate(1,5),o}a&&s.html(a)},failed:function(){(new s).open(a.E_DataLoad)},showSavedState:function(){this.$statusSaved.stop().fadeIn().delay(2e3).fadeOut()},showErrorState:function(){this.$statusError.stop().fadeIn().delay(2e3).fadeOut()}})}),function(t){Backbone.Stickit={_handlers:[],addHandler:function(t){t=_.map(_.flatten([t]),function(t){return _.extend({updateModel:!0,updateView:!0,updateMethod:"text"},t)}),this._handlers=this._handlers.concat(t)}},_.extend(Backbone.View.prototype,{_modelBindings:null,unstickit:function(t){_.each(this._modelBindings,_.bind(function(e,n){return t&&e.model!==t?!1:(e.model.off(e.event,e.fn),void delete this._modelBindings[n])},this)),this._modelBindings=_.compact(this._modelBindings),this.$el.off(".stickit"+(t?"."+t.cid:""))},stickit:function(t,e){var i=this,u=t||this.model,p=".stickit."+u.cid,m=e||this.bindings||{};this._modelBindings||(this._modelBindings=[]),this.unstickit(u),_.each(_.keys(m),function(t){var e,f,g,v,b=m[t]||{},w=_.uniqueId();":el"!=t?e=i.$(t):(e=i.$el,t=""),e.length&&(_.isString(b)&&(b={observe:b}),v=l(e,b),g=v.observe,f=_.extend({bindKey:w},v.setOptions||{}),c(i,e,v,u,g),d(i,e,v,u,g),g&&(_.each(v.events||[],function(n){var a=n+p,o=function(t){var n=v.getVal.call(i,e,t,v);s(i,v.updateModel,n,v)&&r(u,g,n,f,i,v)};""===t?i.$el.on(a,o):i.$el.on(a,t,o)}),_.each(_.flatten([g]),function(t){a(u,i,"change:"+t,function(t,n,s){(null==s||s.bindKey!=w)&&h(i,e,v,o(t,g,v,i),t)})}),h(i,e,v,o(u,g,v,i),u,!0)),n(i,v.initialize,e,u,v))}),this.remove=_.wrap(this.remove,function(t){i.unstickit(),t&&t.call(i)})}});var e=function(t,e){var n=(e||"").split("."),i=_.reduce(n,function(t,e){return t[e]},t);return null==i?t:i},n=function(t,e){return e?(_.isString(e)?t[e]:e).apply(t,_.toArray(arguments).slice(2)):void 0},i=function(t){return t.find("option").not(function(){return!this.selected})},s=function(t,e){return _.isBoolean(e)?e:_.isFunction(e)||_.isString(e)?n.apply(this,_.toArray(arguments)):!1},a=function(t,e,n,i){t.on(n,i,e),e._modelBindings.push({model:t,event:n,fn:i})},r=function(t,e,i,s,a,r){r.onSet&&(i=n(a,r.onSet,i,r)),t.set(e,i,s)},o=function(t,e,i,s){var a,r=function(e){var n=i.escape?t.escape(e):t.get(e);return _.isUndefined(n)?"":n};return a=_.isArray(e)?_.map(e,r):r(e),i.onGet?n(s,i.onGet,a,i):a},l=function(t,e){var n=[{updateModel:!1,updateView:!0,updateMethod:"text",update:function(t,e,n,i){t[i.updateMethod](e)},getVal:function(t,e,n){return t[n.updateMethod]()}}];_.each(Backbone.Stickit._handlers,function(e){t.is(e.selector)&&n.push(e)}),n.push(e);var i=_.extend.apply(_,n);return delete i.selector,i},c=function(t,e,n,i,s){var r=["autofocus","autoplay","async","checked","controls","defer","disabled","hidden","loop","multiple","open","readonly","required","scoped","selected"];_.each(n.attributes||[],function(n){var l="",c=n.observe||(n.observe=s),d=function(){var s=_.indexOf(r,n.name,!0)>-1?"prop":"attr",a=o(i,c,n,t);"class"==n.name?(e.removeClass(l).addClass(a),l=a):e[s](n.name,a)};_.each(_.flatten([c]),function(e){a(i,t,"change:"+e,d)}),d()})},d=function(t,e,i,s,r){if(null!=i.visible){var l=function(){var a=i.visible,l=i.visibleFn,c=o(s,r,i,t),d=!!c;(_.isFunction(a)||_.isString(a))&&(d=n(t,a,c,i)),l?n(t,l,e,d,i):d?e.show():e.hide()};_.each(_.flatten([r]),function(e){a(s,t,"change:"+e,l)}),l()}},h=function(t,e,i,a,r,o){s(t,i.updateView,a,i)&&(i.update.call(t,e,a,r,i),o||n(t,i.afterUpdate,e,a,i))};Backbone.Stickit.addHandler([{selector:'[contenteditable="true"]',updateMethod:"html",events:["keyup","change","paste","cut"]},{selector:"input",events:["keyup","change","paste","cut"],update:function(t,e){t.val(e)},getVal:function(t){var e=t.val();return t.is('[type="number"]')?null==e?e:Number(e):e}},{selector:"textarea",events:["keyup","change","paste","cut"],update:function(t,e){t.val(e)},getVal:function(t){return t.val()}},{selector:'input[type="radio"]',events:["change"],update:function(t,e){t.filter('[value="'+e+'"]').prop("checked",!0)},getVal:function(t){return t.filter(":checked").val()}},{selector:'input[type="checkbox"]',events:["change"],update:function(e,n){e.length>1?(n||(n=[]),_.each(e,function(e){_.indexOf(n,t(e).val())>-1?t(e).prop("checked",!0):t(e).prop("checked",!1)})):_.isBoolean(n)?e.prop("checked",n):e.prop("checked",n==e.val())},getVal:function(e){var n;if(e.length>1)n=_.reduce(e,function(e,n){return t(n).prop("checked")&&e.push(t(n).val()),e},[]);else{n=e.prop("checked");var i=e.val();"on"!=i&&null!=i&&(n=n?e.val():null)}return n}},{selector:"select",events:["change"],update:function(i,s,a,r){var o,l=r.selectOptions,c=l&&l.collection||void 0,d=i.prop("multiple");if(!l){l={};var h=function(t){return t.find("option").map(function(){return{value:this.value,label:this.text}}).get()};i.find("optgroup").length?(c={opt_labels:[]},_.each(i.find("optgroup"),function(e){var n=t(e).attr("label");c.opt_labels.push(n),c[n]=h(t(e))})):c=h(i)}l.valuePath=l.valuePath||"value",l.labelPath=l.labelPath||"label";var u=function(n,i,s){l.defaultOption&&(n=_.clone(n),n.unshift("__default__")),_.each(n,function(n){var a=t("<option/>"),r=n,o=function(t,e){a.text(t),r=e,a.data("stickit_bind_val",r),_.isArray(r)||_.isObject(r)||a.val(r)};"__default__"===n?o(l.defaultOption.label,l.defaultOption.value):o(e(n,l.labelPath),e(n,l.valuePath)),!d&&null!=r&&null!=s&&r==s||_.isObject(s)&&_.isEqual(r,s)?a.prop("selected",!0):d&&_.isArray(s)&&_.each(s,function(t){_.isObject(t)&&(t=e(t,l.valuePath)),(t==r||_.isObject(t)&&_.isEqual(r,t))&&a.prop("selected",!0)}),i.append(a)})};i.html("");var p=function(t,n){var i=window;return 0===n.indexOf("this.")&&(i=t),n=n.replace(/^[a-z]*\.(.+)$/,"$1"),e(i,n)};o=_.isString(c)?p(this,c):_.isFunction(c)?n(this,c,i,r):c,o instanceof Backbone.Collection&&(o=o.toJSON()),_.isArray(o)?u(o,i,s):_.each(o.opt_labels,function(e){var n=t("<optgroup/>").attr("label",e);u(o[e],n,s),i.append(n)})},getVal:function(e){var n;return n=e.prop("multiple")?t(i(e).map(function(){return t(this).data("stickit_bind_val")})).get():i(e).data("stickit_bind_val")}}])}(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(t,e,n,i,s,a,r){"use strict";return t.extend({initialize:function(e){t.prototype.initialize.call(this,e),this.model.on("change",this.populate),s.when(this._rendered=s.Deferred(),this._dependencies=s.Deferred()).then(this.populate,this.failed),this.dependencies(),this.render()},bindings:function(){return{".button-locate":{observe:["state","map_id","default","upgradable","locating"],onGet:function(){1==this.model.get("state")?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")),1==this.model.get("state")?this.$btnRestart.show():this.$btnRestart.hide(),2!=this.model.get("state")&&12!=this.model.get("state")||!this.model.get("default")?this.$btnAdopt.hide():"scan"==this.model.get("discovered_via")&&this.model.get("vwireEnabled")===!1?this.$btnAdopt.hide():this.$btnAdopt.show(),5==this.model.get("state")&&this.$btnAdopt.hide(),1==this.model.get("state")&&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-port":{observe:["sshd_port"],onGet:function(){return this.model.adoptPort()}},".bind-adopt-url":{observe:["adopt_url","inform_url"],onGet:function(){return this.model.adoptUrl()}}}},dependencies:function(){this._dependencies.resolve()},render:function(e){var n=this.rendered;return t.prototype.render.call(this,e),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&&"resolved"==this._dependencies.state()){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"),10==parseInt(this.model.get("state"),10)&&this.$el.addClass("ap-adoptfailed")):(this.$el.addClass("ap-pending"),this.model.get("default")||this.$el.addClass("ap-unmanaged")),"Adopting"===this.model.status()&&(this.$el.addClass("ap-adopting"),this.$el.find(".basic-overview").show());var t=this.model.uplinkDeviceMac();""!==t&&this.$el.addClass("has-uplink-dev"),this.setupMoveDropdown(),this.setupCopyConfigDropdown()}},populateNetworkForm:function(t,e){t[0].reset(),"pppoe"==e.type?(this.$connectionType.val("pppoe").trigger("change"),t.find("input[name=username]").val(e.username),t.find("input[name=x_password]").val(e.x_password),t.find("input[name=dns1]").val(e.dns1),t.find("input[name=dns2]").val(e.dns2),t.find("input[name=dnssuffix]").val(e.dnssuffix)):"static"==e.type?(this.$connectionType.val("static").trigger("change"),t.find("input[name=ip]").val(e.ip),t.find("input[name=netmask]").val(e.netmask),t.find("input[name=gateway]").val(e.gateway),t.find("input[name=dns1]").val(e.dns1),t.find("input[name=dns2]").val(e.dns2),t.find("input[name=dnssuffix]").val(e.dnssuffix)):(this.$connectionType.val("dhcp").trigger("change"),t.find("input[name=dns1]").val(e.dns1),t.find("input[name=dns2]").val(e.dns2),t.find("input[name=dnssuffix]").val(e.dnssuffix))},setupMoveDropdown:function(){this.$moveDropdown.empty().append(s('<option value=""></option>').text(a.G_MoveTo)),this.app.collection("Sites").each(function(t){if(!t.get("attr_hidden")){var e=t.get("desc");t.get("_id")==SITE.id&&(e+=" (current)"),this.$moveDropdown.append(s('<option value="'+t.get("_id")+'"></option>').text(e))}},this)},setupCopyConfigDropdown:function(){this.$copyConfigDropdown.empty().append(s('<option value=""></option>').text(a.G_CopyFrom)),this.app.collection("Devices").each(function(t){var e=t.get("mac"),n=t.get("type"),i=t.get("model");if(n===this.model.typeMap["switch"]&&e!==this.model.get("mac")&&(this.model.copyConfigMap[this.model.get("model")]&&this.model.copyConfigMap[this.model.get("model")].indexOf(i)>-1||i===this.model.get("model"))){var a=t.get("name");this.$copyConfigDropdown.append(s('<option value="'+e+'"></option>').text(a?a+" ("+e+")":e))}},this)},moveDropdownChange:function(){var t=this.$moveDropdown.val(),e=this.$moveDropdown.find("option:selected").text(),n=this,i=a.localize(a.G_PropertiesMoveDeviceConfirmTxt,e,e);if(t&&t!=SITE.id){var o=new r;o.options.dialogOptions.title=a.G_PropertiesMoveDeviceConfirmTitle,o.show(i,s.proxy(function(){n.model.move({data:{site:t},success:function(){s("#header .refresh-status").click()},error:s.proxy(function(t){n.app.views.app.flash("error","Error",a.apiError(t))},n)})},n)),o.closeDialog(function(){n.$moveDropdown.val("").trigger("change")},n)}},copyConfigDropdownChange:function(){var t=this,e=this.$copyConfigDropdown.val();if(e){var n=this.$copyConfigDropdown.find("option:selected").text(),i=a.localize(a.G_PropertiesCopyDeviceConfigConfirmTxt,n),o=new r;o.options.dialogOptions.title=a.G_PropertiesCopyDeviceConfigConfirmTitle,o.show(i,s.proxy(function(){t.model.copyConfig({selectedMac:e,success:function(){s("#header .refresh-status").click()},error:s.proxy(function(e){t.app.views.app.flash("error","Error",a.apiError(e))},t)})})),o.closeDialog(function(){t.$copyConfigDropdown.val("").trigger("change")},t)}},updateAlias:function(){var t,e,n=this,i=this.$aliasForm.find('input[name="name"]'),a=i.val(),r=!1;return this.$aliasForm.find(".error").removeClass("error"),this.$aliasForm.find(".row-error").remove(),""===a?(r=!0,a=this.model.get("mac"),t={name:a}):t=this.$aliasForm.serializeObject(),e=this.model.save(t,{wait:!0,data:t,success:function(t,e){"ok"===e.meta.rc?(n.showSavedState(),i.val(r?"":a)):n.showErrorState()},error:function(){n.showErrorState()}}),!e&&this.model.validationError&&this.model.validationError.name&&(i.addClass("error"),this.$aliasForm.find(".row").after(s('<div class="row row-error"></div>').text(this.model.validationError.name))),!1},updateNetwork:function(t,e){var i={};switch(this.$connectionType.val()){case"pppoe":i[e]={type:"pppoe",username:t.find("input[name=username]").val(),x_password:t.find("input[name=x_password]").val(),dns1:t.find("input[name=dns1]").val(),dns2:t.find("input[name=dns2]").val(),dnssuffix:t.find("input[name=dnssuffix]").val()},i[e].dns1||delete i[e].dns1,i[e].dns2||delete i[e].dns2,i[e].dnssuffix||delete i[e].dnssuffix;break;case"static":i[e]={type:"static",ip:t.find("input[name=ip]").val(),netmask:t.find("input[name=netmask]").val(),gateway:t.find("input[name=gateway]").val(),dns1:t.find("input[name=dns1]").val(),dns2:t.find("input[name=dns2]").val(),dnssuffix:t.find("input[name=dnssuffix]").val()},i[e].gateway||delete i[e].gateway,i[e].dns1||delete i[e].dns1,i[e].dns2||delete i[e].dns2,i[e].dnssuffix||delete i[e].dnssuffix;break;case"dhcp":i[e]={type:"dhcp",dns1:t.find("input[name=dns1]").val(),dns2:t.find("input[name=dns2]").val(),dnssuffix:t.find("input[name=dnssuffix]").val()},i[e].dns1||delete i[e].dns1,i[e].dns2||delete i[e].dns2,i[e].dnssuffix||delete i[e].dnssuffix}t.find(".error").removeClass("error");var a=this.model.save(i,{success:s.proxy(function(t,e){"ok"===e.meta.rc?this.showSavedState():this.showErrorState()},this),error:s.proxy(function(){this.showErrorState()},this)});!a&&this.model.validationError&&this.model.validationError[e]&&n.each(this.model.validationError[e],function(e,n){switch(n){case"username":case"x_password":case"ip":case"netmask":case"gateway":case"dns1":case"dns2":case"dnssuffix":t.find('input[name="'+n+'"]').addClass("error")}},this)},forget:function(){var t=new r;return t.options.dialogOptions.title=a.G_PropertiesForgetDeviceConfirmTitle,t.show(a.G_PropertiesForgetDeviceConfirmTxt,s.proxy(function(){this.model.forget({success:s.proxy(function(){this.app.collection("Devices").remove(this.model),this.remove()},this),error:s.proxy(function(t){this.app.views.app.flash("error","Error",a.apiError(t))},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,t.prototype.remove.call(this)}})}),define("unifi/model/RfItemModel",["backbone","underscore"],function(t){"use strict";return t.Model.extend({defaults:{utilization:0,interference:0,frequencies:[],channels:[]}})}),define("unifi/view/aps/RfItemView",["backbone","jquery","libs/d3"],function(t,e,n){"use strict";return t.View.extend({TRAPEZOID_X_OFFSET:8,render:function(t){var e,i=this.model.get("width"),s=this.options.frequencies[0],a=s-10,r=a+i;switch(i){case 80:e=4;break;case 40:e=2;break;default:e=1}t=t||!1,this.svgEl=t?n.select(this.el).select("#channel-"+this.model.get("channel")):n.select(this.el).append("svg"),this.svgEl.attr("id","channel-"+this.model.get("channel")).attr("data-channel",this.model.get("channel")).attr("data-start-frequency",a).attr("data-end-frequency",r).attr("data-utilization",this.model.get("utilization")).attr("data-interference",this.model.get("interference")).attr("data-interference-histogram",this.model.get("rssi_histogram")).attr("data-interference-types",this.model.get("interference_type")).attr("class","unifiRf__item unifiRf__item--"+e),t&&(this.svgEl.selectAll("rect").remove(),this.svgEl.selectAll("text").remove()),this._renderBackgroundRectangle(),this._renderLevelRectangle(),this._renderValue()},_renderBackgroundRectangle:function(){var t=e(this.svgEl.node()).width(),n=e(this.svgEl.node()).height(),i=this.svgEl.append("rect").attr("width",t).attr("height",n).attr("class","unifiRf__itemBackground");if(this.options.radioChannelWidth==this.model.get("width")&&this.options.highlightChannel==this.model.get("channel")){var s=this.model.get("utilization"),a=this._calculateHue(s),r="stroke: hsl("+a+", 75%, 50%) !important; stroke-width: 2px";i.attr("style",r)}},_renderLevelRectangle:function(){var t=this.model.get("utilization"),n=e(this.svgEl.node()).width(),i=e(this.svgEl.node()).height(),s=i*t/100,a=i-s,r=this._calculateHue(t),o="fill: hsl("+r+", 75%, 50%) !important";
this.svgEl.append("rect").attr("width",n).attr("height",s).attr("style",o).attr("y",a).attr("class","unifiRf__itemLevel")},_renderValue:function(){this.svgEl.append("svg:text").attr("class","unifiRf__value").attr("x","50%").attr("y","50%").attr("dy","30px").text(this.model.get("channel"))},_calculateHue:function(t){var e=240,n=t/100*e;return e-n}})}),define("unifi/view/aps/RfLegendView",["underscore","backbone","jquery","libs/d3"],function(t,e,n,i){"use strict";return e.View.extend({options:{precision:15,maxHueValue:240,itemHeight:5,padding:1,labels:[-96,-80,-64,-48,-32]},render:function(){this.svgEl=i.select(this.el).append("svg"),this._renderColorItems(),this._renderLabels()},_renderColorItems:function(){for(var t=this.options.padding,e=n(this.svgEl.node()).width(),i=n(this.svgEl.node()).height(),s=this.options.precision,a=(e-t)/s+t/s,r=i-this.options.itemHeight,o=0;s>o;o++){var l=a*o+(o>0?t*o:0),c=this._calculateHue(o),d="hsl("+c+", 75%, 50%)";this.svgEl.append("rect").attr("x",l).attr("y",r).attr("width",a).attr("height",i).attr("fill",d)}},_renderLabels:function(){for(var t=this.options.labels,e=n(this.svgEl.node()).width(),i=this.svgEl.append("g"),s=0;s<t.length;s++){var a=e/(t.length-1)*s;i.append("svg:text").attr("class","unifiRf__legendLabel").attr("x",a).attr("y","0").attr("dy","8px").text(t[s])}},_calculateHue:function(t){var e=t/(this.options.precision-1)*this.options.maxHueValue;return this.options.maxHueValue-e}})}),define("unifi/view/aps/RfInterferenceLevelView",["underscore","backbone","jquery","libs/d3"],function(t,e,n,i){"use strict";return e.View.extend({options:{minValue:0,maxValue:10,minOpacity:0,maxOpacity:100},render:function(){this.svgEl=i.select(this.el).append("svg"),this._renderHistogram()},_renderHistogram:function(){var t=n(this.svgEl.node()).width(),e=n(this.svgEl.node()).height(),i=this.model.get("interference"),s=this.options.maxValue,a=this.options.minValue,r=Math.round(t/i.length);this.svgEl.append("rect").attr("class","background").attr("x",0).attr("y",0).attr("width",32*r).attr("height",e);for(var o=0;o<i.length;o++){var l=r*o,c=this._calculateOpacity(i[o],s,a)/100;this.svgEl.append("rect").attr("x",l).attr("y",0).attr("width",r).attr("height",e).attr("fill-opacity",c)}},_calculateOpacity:function(t,e,n){e>this.options.maxValue&&(e=this.options.maxValue),n<this.options.minValue&&(n=this.options.minValue);var i=e-n,s=this.options.maxOpacity-this.options.minOpacity;return(t-n)*s/i+this.options.minOpacity}})}),define("text!includes/aps/rfEnvironmentTemplate.html",[],function(){return'<div class="unifiRf__items">\n    <div class="unifiRf__scrollable">\n        <% bandwidthGroups.forEach(function(group) { %>\n        <div class="unifiRf__row unifiRf__row<%- group.width %>">\n            <div class="unifiRf__bandwidthLegend"><%- group.width %> Mhz</div>\n        </div>\n        <% }); %>\n    </div>\n</div>\n'}),define("text!includes/aps/rfTooltipTemplate.html",[],function(){return'<div class="unifiRf__tooltip">\n    <h2>Channel <%- channel %></h2>\n    <h3><%- startFrequency %> - <%- endFrequency %></h3>\n\n    <dl>\n        <dt class="unifiRf__tooltipKey unifiRf__tooltipKey--inline"><%- msg.G_PropertiesRFUtilization %>:</dt>\n        <dd class="unifiRf__tooltipValue unifiRf__tooltipValue--inline unifiRf__tooltipValue--highlighted"><%- utilization %>%</dd>\n\n        <br/>\n\n        <dt class="unifiRf__tooltipKey unifiRf__tooltipKey--inline"><%- msg.G_PropertiesRFInterference %>:</dt>\n        <dd class="unifiRf__tooltipValue unifiRf__tooltipValue--inline unifiRf__tooltipValue--highlighted"><%- interference %> <%- msg.G_PropertiesDBM %></dd>\n\n        <dd class="unifiRf__tooltipValue">\n            <div class="unifiRf__interferenceLevel"></div>\n            <div class="unifiRf__interferenceLevelLegend">\n                <div class="unifiRf__interferenceLevelLegend--left">LOW</div>\n                <div class="unifiRf__interferenceLevelLegend--right">HIGH</div>\n            </div>\n        </dd>\n\n        <dt class="unifiRf__tooltipKey"><%- msg.G_PropertiesRFInterferenceTypes %>:</dt>\n        <dd class="unifiRf__tooltipValue">\n            <% interferenceTypes.forEach(function(interferenceType) { %>\n            <i><%- interferenceType %></i>\n            <% }); %>\n        </dd>\n    </dl>\n</div>\n'}),define("unifi/view/aps/RfEnvironmentView",["underscore","backbone","jquery","unifi/model/RfItemModel","unifi/view/aps/RfItemView","unifi/view/aps/RfLegendView","unifi/view/aps/RfInterferenceLevelView","text!includes/aps/rfEnvironmentTemplate.html","text!includes/aps/rfTooltipTemplate.html","msg/Msg"],function(t,e,n,i,s,a,r,o,l,c){"use strict";return e.View.extend({initialize:function(t){e.View.prototype.initialize.call(this,t),this.bandwidthGroups=this._getProcessedBandwidthGroups(),this.radioChannel=t.radioChannel,this.radioChannelWidth=t.radioChannelWidth,this.radioType=t.radioType},_getProcessedBandwidthGroups:function(){var e=this.model.get("bandwidthGroups"),n=t.chain(e).groupBy("width").map(function(t,e){return{width:e,data:t}}).value();return n.reverse()},render:function(){this._renderLayout(),this._renderItems(),this._setupTooltips();var t=this;this.$(".unifiRf__item").on("mouseover",function(e){t.histogram=n(e.currentTarget).attr("data-interference-histogram")})},update:function(t,i,s,a){this.model=t,this.bandwidthGroups=this._getProcessedBandwidthGroups(),this.radioChannel=s,this.radioChannelWidth=a,this._renderItems(!0),this._setupTooltips();var o=this;if(i===this.radioType&&this.histogram){var l=new r({el:n(".unifiRf__interferenceLevel"),model:new e.Model({interference:o.histogram.split(",")})});l.render()}},_renderLayout:function(){this.$el.html(t.template(o,{bandwidthGroups:this.bandwidthGroups}))},_renderItems:function(e){e=e||!1,t.each(this.bandwidthGroups,t.bind(function(n){var a=this._highlightChannel(n.data,this.radioChannel);t.each(n.data,t.bind(function(t){var r=this.$(".unifiRf__row"+n.width),o=new s({el:r,model:new i(t),radioChannel:this.radioChannel,radioChannelWidth:this.radioChannelWidth,frequencies:t.frequencies,highlightChannel:a});o.render(e)},this))},this))},_highlightChannel:function(t,e){for(var n=0;n<t.length-1;n++)if(t[n].channel<=e&&t[n+1].channel>e)return t[n].channel;return t[t.length-1].channel},_setupTooltips:function(){this.$(".unifiRf__item").attr("title","").tooltip({show:!1,hide:!1,content:function(){var e=n(this),i={msg:c,channel:e.attr("data-channel"),startFrequency:e.attr("data-start-frequency"),endFrequency:e.attr("data-end-frequency"),utilization:e.attr("data-utilization"),interference:e.attr("data-interference"),interferenceTypes:e.attr("data-interference-types").split(",")};return t.template(l,i)},position:{at:"center+20 top-2",my:"right bottom"},open:function(){var t=n(this),i=new r({el:n(".unifiRf__interferenceLevel"),model:new e.Model({interference:t.attr("data-interference-histogram").split(",")})});i.render()}})}})}),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\n                    <div class="accordion-header ap-rf-environment">\n                        <div class="accordion-title"><%- msg.G_PropertiesRFEnvironment %></div>\n                    </div>\n                    <div class="radio-na ap-rf-environment unifiRf">\n                        <form class="data-filters ap-rf-environment-frequency-filters clearfix">\n                            <div class="buttonset frequency-filters ui-buttonset">\n                                <input type="radio" id="frequencyFilter2G_<%- _id %>" name="ap-rf-frequency-filter" value="2G" checked="checked" /><label for="frequencyFilter2G_<%- _id %>"><%- msg.G_2G %></label>\n                                <input type="radio" id="frequencyFilter5G_<%- _id %>" name="ap-rf-frequency-filter" value="5G" /><label for="frequencyFilter5G_<%- _id %>"><%- msg.G_5G %></label>\n                            </div>\n                        </form>\n                        <div class="bind-rf-legend unifiRf__legend"></div>\n\n                        <div class="bind-rf-environment bind-rf-environment-2G"></div>\n                        <div class="bind-rf-environment bind-rf-environment-5G"></div>\n\n                        <br />\n\n                        <div class="bind-rf-environment-last-updated bind-rf-environment-last-updated-2G unifiRf__lastUpdated unifiRf__lastUpdated--inline"></div>\n                        <div class="bind-rf-environment-last-updated bind-rf-environment-last-updated-5G unifiRf__lastUpdated unifiRf__lastUpdated--inline"></div>\n                        <button class="button button-rfScan right lighter skinny unifiRf__scan is-admin">\n                            <span class="ui-button-icon-primary ubnt-icon-refresh sidebar-icons"></span>\n                            <span class="text"><%- msg.G_PropertiesRFScan %></span>\n                        </button>\n                    </div>\n\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\') %>" pattern=".{1,128}" title="<%- msg.E_AliasName %>" />\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>\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="number" max="99" min="-99" step="1" name="ng.antenna_gain" value="<%- get(\'ng.antenna_gain\') || \'6\' %>" />\n                                    <label class="label unit"><%- msg.G_PropertiesDBI %></label>\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>\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="number" max="99" min="-99" step="1" name="na.antenna_gain" value="<%- get(\'na.antenna_gain\') || \'6\' %>" />\n                                    <label class="label unit"><%- msg.G_PropertiesDBI %></label>\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-dualband-configs">\n                        <div class="accordion-title"><%- msg.G_PropertiesBandSteering %></div>\n                    </div>\n                    <div class="ap-dualband-configs">\n                        <form>\n                            <div class="clearfix">\n                                <div class="buttonset band-steering">\n                                  <input type="radio" id="bandSteeringTo5G_<%- _id %>" name="bandSteeringSelection" value="prefer_5g" />\n                                  <label for="bandSteeringTo5G_<%- _id %>"><%- msg.G_PropertiesPrefer5G %></label>\n                                  <input type="radio" id="bandSteeringEqual_<%- _id %>" name="bandSteeringSelection" value="equal" />\n                                  <label for="bandSteeringEqual_<%- _id %>"><%- msg.G_PropertiesBalanced %></label>\n                                  <input type="radio" id="bandSteeringOff_<%- _id %>" name="bandSteeringSelection" value="off" />\n                                  <label for="bandSteeringOff_<%- _id %>"><%- msg.G_SettingsOff %></label>\n                              </div>\n                            </div>\n                        </form>\n                    </div>\n                    -->\n                    <!-- <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_PropertiesAirtimeFairness %></div>\n                    </div>\n                    <div>\n                        <form>\n                            <div class="clearfix">\n                                <div class="buttonset airtime-fairness">\n                                    <input type="radio" id="airtimeFairnessOff_<%- _id %>" name="bandSteeringSelection" value="false" />\n                                    <label for="airtimeFairnessOff_<%- _id %>"><%- msg.G_SettingsOff %></label>\n                                    <input type="radio" id="airtimeFairnessOn_<%- _id %>" name="bandSteeringSelection" value="true" />\n                                    <label for="airtimeFairnessOn_<%- _id %>"><%- msg.G_SettingsOn %></label>\n                                </div>\n                            </div>\n                        </form>\n                    </div> -->\n                    <!-- <div class="accordion-header">\n                        <div class="accordion-title"><%- msg.G_PropertiesAggregationFragmentation %></div>\n                    </div>\n                    <div>\n                        <fieldset class="fieldset">\n                            <form>\n                                <div class="clearfix">\n                                    <div class="buttonset aggregation-fragmentation">\n                                        <input type="radio" id="aggregationFragmentationOff_<%- _id %>" name="bandSteeringSelection" value="off" />\n                                        <label for="aggregationFragmentationOff_<%- _id %>"><%- msg.G_SettingsOff %></label>\n                                        <input type="radio" id="aggregationFragmentationOn_<%- _id %>" name="bandSteeringSelection" value="on" />\n                                        <label for="aggregationFragmentationOn_<%- _id %>"><%- msg.G_SettingsOn %></label>\n                                        <input type="radio" id="aggregationFragmentationAuto_<%- _id %>" name="bandSteeringSelection" value="auto" />\n                                        <label for="aggregationFragmentationAuto_<%- _id %>"><%- msg.G_PropertiesAuto %></label>\n                                    </div>\n                                    <br/>\n                                    <legend class="legend">Adjust Setting</legend>\n                                    <div class=\'slider-wrapper\'>\n                                        <div class=\'aggregation-fragmentation-slider slider\'></div>\n                                        <label>Lower Latency</label>\n                                        <label>Higher Throughput</label>\n                                    </div>\n                                </div>\n                            </form>\n                        </fieldset>\n                    </div> -->\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","unifi/view/aps/RfEnvironmentView","unifi/view/aps/RfLegendView","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","ubnt/view/dialogs/ConfirmDialogView","libs/moment","stickit"],function(t,e,n,i,s,a,r,o,l,c,d,h,u,p,m,f){"use strict";return t.extend({templateId:p,events:{"change input[name=ap-rf-frequency-filter]":"_onRfEnvironmentFrequencyChange"},initialize:function(e){this.configuredRadios=!1,this.spectrum_rendered={na:!1,ng:!1},this.rfEnvironments={},t.prototype.initialize.call(this,e),this.listenTo(this.app.collection("Wlans"),"add remove destroy change",this.setupWlanPanel),this.listenTo(this.model,"change:radio_na change:radio_ng",r.proxy("updateRadiosForm",this))},bindings:function(){var e={".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(t){this.$bindNumUsers.text(t||0)}},".bind-num-guests":{observe:"guest-num_sta",onGet:function(t){this.$bindNumGuests.text(t||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 t=this.model.transmitPower("ng"),e=this.model.transmitPower("na"),n=" "+o.G_PropertiesDBM+" ("+o.G_PropertiesEIRP+")";this.$bindNgTransmitPower.text(s.isUndefined(t)?"":t+n),this.$bindNaTransmitPower.text(s.isUndefined(e)?"":e+n)}},".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(t){this.$bindWlanGroupNg.find("select").val(t).trigger("change",!0),this.setupWlanTable("ng")}},".bind-wlan-group-na":{observe:"wlangroup_id_na",updateView:!1,onGet:function(t){this.$bindWlanGroupNa.find("select").val(t).trigger("change",!0),this.setupWlanTable("na")}},".bind-network":{observe:"config_network",onGet:function(t){this.populateNetworkForm(this.$networkForm,t)}}},n={};return this.model.isGen2Ap()&&s.extend(n,{".bind-rf-environment-2G":{observe:"spectrum_table_ng",onGet:function(t){this.renderRfEnvironment(this.$bindRfEnvironment2G,t,"ng")}},".bind-rf-environment-5G":{observe:"spectrum_table_na",onGet:function(t){this.renderRfEnvironment(this.$bindRfEnvironment5G,t,"na")}}}),s.extend({},t.prototype.bindings.call(this),e,n)},updateScanDisplay:function(){var t=this.model.get("spectrum_scanning"),e=this.model.get("spectrum_table_time_na"),n=this.model.get("spectrum_table_time_ng");t?(this.$bindRfEnvironmentLastUpdated2G.text(o.G_PropertiesRFScanScanning),this.$bindRfEnvironmentLastUpdated5G.text(o.G_PropertiesRFScanScanning)):(this.$bindRfEnvironmentLastUpdated5G.text(o.localize(o.G_PropertiesRFLastUpdated,this.model.lastScan(e))),this.$bindRfEnvironmentLastUpdated2G.text(o.localize(o.G_PropertiesRFLastUpdated,this.model.lastScan(n)))),this.toggleRfScanButton(t)},dependencies:function(){var t={SystemInfos:c,WlanGroups:d,Wlans:h,Sites:u},e=[],n={},i=this;s.each(t,function(t,i){e.push(n[i]=r.Deferred())},this),r.when.apply(r,e).then(function(){i._dependencies.resolve()},function(){i._dependencies.reject()}),s.each(t,function(t,e){this.app.collection(e,{fetch:{reload:!1,deferred:n[e]}},t)},this)},render:function(e){var n=this.rendered;return t.prototype.render.call(this,e),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.$rfScanButton=this.$(".button-rfScan"),this.$bindRfEnvironment=this.$(".bind-rf-environment"),this.$bindRfEnvironment2G=this.$(".bind-rf-environment-2G"),this.$bindRfEnvironment5G=this.$(".bind-rf-environment-5G"),this.$bindRfEnvironmentLastUpdated=this.$(".bind-rf-environment-last-updated"),this.$bindRfEnvironmentLastUpdated2G=this.$(".bind-rf-environment-last-updated-2G"),this.$bindRfEnvironmentLastUpdated5G=this.$(".bind-rf-environment-last-updated-5G"),this.$bindRfLegend=this.$(".bind-rf-legend"),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.$(".buttonset").buttonset(),this.$advAdoptForm.on("submit",this.onAdvAdoptFormSubmit),this.$networkForm.on("submit",r.proxy(function(t){t.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",r.proxy(function(t){var e=r(t.target).val();this.$networkForm.find(".connection-toggled").hide().filter(".connection-"+e).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),"resolved"===this._rendered.state()&&"resolved"==this._dependencies.state()?(this.configuredRadios=!1,this.populate()):"pending"===this._rendered.state()&&this._rendered.resolve(),this.model.isGen2Ap()?(this._showRfTab(this.$bindRfEnvironment2G,this.$bindRfEnvironmentLastUpdated2G),this.renderRfLegend(),this.$rfScanButton.on("click",this.onRfScanClick),this.updateScanDisplay(this.model.get("spectrum_scanning"))):this.$(".ap-rf-environment").hide(),this.stickit(this.model,this.bindings())),this.options.options&&this.options.options.section&&this.setSection(this.options.options.section),this},setSection:function(t){var e,n;switch(t){case"rfMap":e=0,n=6;break;case"config":e=3,n=0}this.$tabs.tabs("option","active",e),this.$el.find(".properties-container > div:nth-child("+(e+1)+") > .accordion").accordion("option","active",n)},toggleRfScanButton:function(t){t===!0?this.$rfScanButton.addClass("disabled").attr("disabled","disabled"):this.$rfScanButton.removeClass("disabled").removeAttr("disabled")},populate:function(){if(t.prototype.populate.call(this),this._dependencies&&"resolved"==this._dependencies.state()){var e=this.model.isConnected(),n=this.model.uplink(),i=n?"wireless"===n.type:!1,a=!1;this.$el.removeClass("ap-uplink-wire ap-uplink-wireless ap-has-downlinks ap-needs-uplinks ap-ng-radio ap-na-radio ap-dualband-radio"),this.model.get("adopted")&&(this.model.get("locating")?this.$btnLocate.addClass("locating"):this.$btnLocate.removeClass("locating")),this.setupAP(),s.each(this.model.uplinks(),function(t,e){e.configured&&(a=!0)}),this.model.get("vwireEnabled")&&(i||a||!e)&&(this.$el.addClass("ap-needs-uplinks"),e||this.setupUplinksTable()),this.model.isGen2Ap()&&this.updateScanDisplay(),this.position()}},setupAP:function(){var t=this.model.hasRadio("ng"),e=this.model.hasRadio("na"),n=s.size(this.model.downlinks())>0,i=this.model.uplink()||{},a=(this.model.downlinks(),this.model.is11ac());"eth0"==i.name||"eth1"==i.name?(this.$el.addClass("ap-uplink-wire"),this.$(".uplink-type").text("("+o.G_Wire+")")):"ath0"==i.name&&(this.$el.addClass("ap-uplink-wireless"),this.$(".uplink-type").text("("+o.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&&0!==this.currentCCode.channels_na_80.length&&this.model.is11ac()||this.$('select[name="na.ht"] option[value=80]').remove(),n&&this.$el.addClass("ap-has-downlinks"),t&&this.$el.addClass("ap-ng-radio"),e&&(this.$el.addClass("ap-na-radio"),a&&(this.$("fieldset.ap-na-configs legend").text(o.G_PropertiesRadio5G11AC),this.$("fieldset.ap-na-configs.fieldset-wlan legend").text(o.G_PropertiesWLANS5G11AC),this.$("div.radio-na").find("div.accordion-title").text(o.G_PropertiesRadio11AC))),e&&t&&this.$el.addClass("ap-dualband-radio"),this.configuredRadios||this.updateRadiosForm(),this.userTable(),this.guestTable(),this.$("select.radio-ht").each(function(){r(this).trigger("change")}),this.setupWlanPanel()},onRfScanClick:function(t){var e=r(t.target);if(!e.hasClass("disabled")){var n=new f;return n.options.dialogOptions.title=o.G_PropertiesRFScanConfirmTitle,n.show(o.G_PropertiesRFScanConfirmTxt,r.proxy(function(){this.toggleRfScanButton(!0),this.$bindRfEnvironmentLastUpdated2G.text(o.G_PropertiesRFScanScanning),this.$bindRfEnvironmentLastUpdated5G.text(o.G_PropertiesRFScanScanning),this.model.spectrumScan()},this)),!1}},onAdvAdoptFormSubmit:function(t){t.preventDefault();var e=this,n=this.model,i=r(t.target).find("button");this.$advAdoptForm.find(".error").removeClass("error"),i.attr("disabled","disabled");var a=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(t){"ok"===t.meta.rc?n.fetch({success:function(t,n){"ok"===n.meta.rc&&e.parent.property(t)},complete:function(){i.removeAttr("disabled")}}):(e.showErrorState(),i.removeAttr("disabled"))},error:function(){e.showErrorState(),i.removeAttr("disabled")}});!a&&this.model.validationError&&s.each(this.model.validationError,function(t,e){switch(e){case"username":case"password":this.$advAdoptForm.find('input[name="'+e+'"]').addClass("error"),i.removeAttr("disabled")}},this)},displayUplinkDevice:function(){var t=this.app.routers.devices.views.index,e=t.collection.getDeviceFromMac(this.model.uplinkDeviceMac()),n=e&&t.property(e),i=this.model.uplinkRemotePort();return i&&(n.$el.find(".switchPorts-anchor").click(),s.delay(function(){n.$el.find(".port-"+i).click()},100)),!1},userAndGuestColumns:function(){var t=this;return[{name:"hostname",label:o.G_Name,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ModelCell.extend({callback:"name"}),callback:function(e){var n=t.app.routers.clients.views.index,i=n.collection.getClientFromMac(e.get("mac"));n.property(i)}},{name:"essid",label:o.G_Wlan,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:"string"},{name:"signal",label:o.G_DevicesSignal,editable:!1,cell:i.Cells.ModelCell.extend({callback:"signalWithDbm"})},{name:"tx_rate",label:o.G_DevicesTX,editable:!1,cell:i.Cells.ModelCell.extend({callback:"txRateInM"})}]},userTable:function(){if(!this.rendered)return!1;var t=this.app.collection("Clients"),e=t.where({ap_mac:this.model.get("mac"),is_guest:!1});this.grids.users?this.grids.users.collection.set(e):this.grids.users=this.grid(this.userAndGuestColumns(),new a.Collection(e),this.$(".data-table-users"),this.noUserRows)},guestTable:function(){if(!this.rendered)return!1;var t=this.app.collection("Clients"),e=t.where({ap_mac:this.model.get("mac"),is_guest:!0});this.grids.guests?this.grids.guests.collection.set(e):this.grids.guests=this.grid(this.userAndGuestColumns(),new a.Collection(e),this.$(".data-table-guests"),this.noGuestRows)},updateRadioTable:function(t){var e,n=this;s.each(t,function(t){if(e=n.model.getRadio(t.radio),void 0!==e)for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})},updateRadiosForm:function(){var t,e,n=this;s.each(this.model.get("radio_table"),function(i){e=i.radio,t=n.$("fieldset.radio-"+e),t.find('select[name="'+e+'.ht"]').val(i.ht||("ng"==e?20:40)).change(),t.find('select[name="'+e+'.tx_power_mode"]').val(i.tx_power_mode||"auto").change(),t.find('input[name="'+e+'.tx_power"]').val(i.tx_power||"0"),t.find('input[name="'+e+'.antenna_gain"]').val(i.antenna_gain||"6"),i.builtin_antenna!==!1&&t.find("div.antenna-gain").remove(),"custom"===i.tx_power_mode?t.find("div.custom").show():t.find("div.custom").hide(),this.configuredRadios=!0},this),this.configuredRadios&&this.renderSelects()},updateRadios:function(){var t=this,e=this.$radiosForm.serializeObject(),n={},i={},a=[],r=0,l=0,c="",d=!0,h={};return s.each(e,function(t,e){0===e.indexOf("ng.")?n[e.replace("ng.","")]=t:0===e.indexOf("na.")&&(i[e.replace("na.","")]=t)}),n&&this.model.hasRadio("ng")&&a.push(n),i&&this.model.hasRadio("na")&&a.push(i),s.each(a,function(e){return c=e.radio,"custom"===e.tx_power_mode&&(r=t.model.get("radio_"+c).max_txpower||"0",l=t.model.get("radio_"+c).min_txpower||"0",e.tx_power>r||e.tx_power<l)?((new m).open(o.localize(o.E_IncorrectNumberRange,("ng"===c?o.G_2G:o.G_5G)+" "+o.G_PropertiesTransmitPower,l,r)),void(d=!1)):void 0}),d?(this.model.update({data:{radio_table:a},success:function(e){"ok"===e.meta.rc?(h=s.find(e.data,function(e){return e.mac===t.model.get("mac")}),void 0!==h&&t.updateRadioTable(h.radio_table),t.updateRadiosForm(),t.showSavedState()):t.showErrorState()},error:function(){t.showErrorState()}}),!1):!1},saveAirtimeFairness:function(){},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(t){var e=r(t.target),n=e.data("mac"),i=this.app.collection("Clients"),s=i.getClientFromMac(n);s.block()},reconnectUser:function(){var t=r(event.target),e=t.data("mac"),n=this.app.collection("Clients"),i=n.getClientFromMac(e);i.reconnect()},updateChannelSelect:function(t){var e,n=r(t.target),i=n.val()||20,a=n.data("radio"),l=this.$('select[name="'+a+'.channel"]'),c=l.val()||(this.model.get("radio_"+a)||{}).channel,d=this.model.hasDfs();if(l.empty().append(r('<option value="auto" />').text(o.G_Auto)),s.each(this.currentCCode["channels_"+a+(20==i?"":"_"+i)],r.proxy(function(t){var e=r("<option />").attr("value",t).text(t);if("na"==a){var n=-1!==r.inArray(t,this.currentCCode.channels_na_dfs);if(n){if(!d)return;e.text(function(t,e){return e+" (dfs)"})}e.attr("band",s.escape(52>t?1:149>t?2:3))}l.append(e)},this)),"na"==a&&("US"==this.currentCountryKey||"CA"==this.currentCountryKey))switch(this.model.get("model")){case"U5O":l.find("[band=1]").remove(),l.find("[band=2]").remove();break;case"U7P":l.find("[band=2]").remove()}e=l.find("option[value="+c+"]"),e.length||(e=l.find("option[value=auto]")),e.attr("selected",!0).trigger("change")},updateWlan:function(t,e){{var n,i=r(t.target),s=i.data("radio"),a=i.val(),o=this.app.collection("WlanGroups"),l=o.findWhere({_id:a}),c=this.app.collection("Wlans");c.findWhere({wlangroup_id:a})}if(i.data("wlangroup",l),n=this.$radiosForm.find(".radio-"+s),l&&l.get("roam_enabled")){n.find('select[name="'+s+'.channel"]').val(l.get("ng"==s?"roam_channel_ng":"roam_channel_na")).disable(),n.find('select[name="'+s+'.ht"]').disable(),"resolved"===this._rendered.state()&&"resolved"==this._dependencies.state()&&n.find('select[name="'+s+'.ht"]').val("20").change();try{n.find('select[name="'+s+'.channel"]').selectmenu("disable"),n.find('select[name="'+s+'.ht"]').selectmenu("disable")}catch(d){}}else{n.find('select[name="'+s+'.channel"]').enable(),n.find('select[name="'+s+'.ht"]').enable();try{n.find('select[name="'+s+'.channel"]').selectmenu("enable"),n.find('select[name="'+s+'.ht"]').selectmenu("enable")}catch(d){}}e||this.model.get("_id")&&this.model.get("wlangroup_id_"+s)!=a&&this.model.updateWlanGroup(s,{wait:!0,wlangroup_id:a,success:r.proxy(function(){this.showSavedState(),this.setupWlanTable(s)},this),error:r.proxy(function(){this.showErrorState()},this)})},setupWlanPanel:function(){var t=this,e=["ng","na"],n=this.app.collection("WlanGroups");s.each(e,function(e){var i=t.$("select.wlan-group-"+e);i.empty(),s.each(n.models,function(n){var a=r('<option value="'+s.escape(n.get("_id"))+'"></option>');if(n.get("roam_enabled")){if(e!=n.get("roam_radio"))return null;a.addClass("roam"),a.text(n.get("name")+" (Zero-Handoff)")}else a.text(n.get("name"));a.hasClass("roam")&&(t.$el.hasClass("ap-uplink-wireless")||t.model.noZh())?a=null:i.append(a)});try{i.selectmenu("refresh")}catch(a){}var o=t.model.get("wlangroup_id_"+e);o&&(i.val(o).trigger("change",!0),t.setupWlanTable(e,o))})},fillWlanForm:function(t){if(this.$overrideForm.find(".error").removeClass("error"),this.$overrideForm.find(".row-error").remove(),this.wLanOverrideModel){var e=this.wLanOverrideModel.get("_id"),n=this.wLanOverrideRadio,i=this.model.getOverride(e,n),s=this.wLanOverrideModel.toJSON();(!i||t)&&(i=this.wLanOverrideModel.toJSON()),this.$overrideForm.find('input[name="name"]').val(i.hasOwnProperty("name")?i.name:s.name),this.$overrideForm.find('input[name="wlanEnabled"]').prop("checked",i.hasOwnProperty("enabled")?i.enabled===!0:s.enabled===!0),this.$overrideForm.find('input[name="vlanEnabled"]').prop("checked",i.hasOwnProperty("vlan_enabled")?i.vlan_enabled===!0:s.vlan_enabled===!0),this.$overrideForm.find('input[name="vlan"]').val(i.hasOwnProperty("vlan")?i.vlan>1?i.vlan:"":s.vlan>1?s.vlan:""),this.$overrideForm.find(".wpapsk").attr("display",i.hasOwnProperty("security")?"wpapsk"==i.security?"block":"none":"wpapsk"==s.security?"block":"none"),this.$overrideForm.find('input[name="passphrase"]').val(i.hasOwnProperty("x_passphrase")?i.x_passphrase:s.x_passphrase),"wpapsk"==this.wLanOverrideModel.get("security")?this.$overrideForm.find("div.row.wpapsk").show():this.$overrideForm.find("div.row.wpapsk").hide()}var a=this.$overrideForm.find('input[name="vlanEnabled"]'),r=this.$overrideForm.find('input[name="vlan"]');a.prop("checked")===!0?r.prop("disabled",!1):r.prop("disabled",!0),a.click(function(){a.is(":checked")?r.prop("disabled",!1):r.prop("disabled",!0)})},onOverrideFormSubmit:function(t){t&&t.preventDefault(),this.submitOverride(!1)},submitOverride:function(t){if(this.$overrideForm.find(".error").removeClass("error"),this.$overrideForm.find(".row-error").remove(),this.wLanOverrideModel){var e=this,n=this.model.get("wlan_overrides")||[],i=this.wLanOverrideModel.get("_id"),a=this.wLanOverrideRadio,o=this.model.getOverride(i,a)||this.wLanOverrideModel.toJSON(),l=!0;if(n=r.grep(n,function(t){return t!=o}),!t){var c=["enabled","name","radio","vlan","vlan_enabled","wlan_id","x_passphrase"];o=s.pick(o,c),o.wlan_id=i,o.radio=a,o.name=this.$overrideForm.find('input[name="name"]').val(),o.enabled=this.$overrideForm.find('input[name="wlanEnabled"]').is(":checked");var d=o.vlan_enabled=this.$overrideForm.find('input[name="vlanEnabled"]').is(":checked");o.vlan=this.$overrideForm.find('input[name="vlan"]').val(),o.x_passphrase=this.$overrideForm.find('input[name="passphrase"]').val();var h=this.wLanOverrideModel;o.name!=h.get("name")?l=!1:delete o.name,o.enabled!=h.get("enabled")?l=!1:delete o.enabled,o.vlan_enabled!=h.get("vlan_enabled")?l=!1:delete o.vlan_enabled,""===o.vlan?d?l=!1:delete o.vlan:o.vlan!=h.get("vlan")?l=!1:delete o.vlan,o.x_passphrase!=h.get("x_passphrase")?l=!1:delete o.x_passphrase,l||n.push(o)}var u=this.model.save({wlan_overrides:n,wlanconf:this.app.collection("Wlans").findWhere({_id:i})},{wait:!0,data:{wlan_overrides:n},success:function(t,n){"ok"===n.meta.rc?(e.setupWlanTable(a),e.$el.removeClass("ap-show-override"),e.showSavedState()):e.showErrorState()},error:function(){e.showErrorState()}});!u&&this.model.validationError&&this.model.validationError.wlan_overrides&&s.each(this.model.validationError.wlan_overrides,function(t){s.each(t,function(t,e){var n;switch(e){case"name":case"vlan":n=this.$overrideForm.find('input[name="'+e+'"]').addClass("error");break;case"x_passphrase":n=this.$overrideForm.find('input[name="passphrase"]').addClass("error")}n.parents(".row").after(r('<div class="row row-error"></div>').text(t))},this)},this)}},onOverrideFormRestore:function(t,e){return this.fillWlanForm(!0),!e&&this.submitOverride(!0),!1},onOverrideFormCancel:function(){return this.onOverrideFormRestore(null,!0),this.$el.removeClass("ap-show-override"),!1},setupWlanTable:function(t,e){if(!this.rendered)return!1;var n=this,a=n.$("select.wlan-group-"+t),r=e||a.val(),l=this.app.collection("Wlans").filter(function(t){return t.get("wlangroup_id")==r}),c=this.$(".data-table-wlans-"+t);if(c.next(".WLANSDisabled").hide(),this.grids["wlan_"+t])this.grids["wlan_"+t].collection.reset(),this.grids["wlan_"+t].collection.set(l);else{var d=[{name:"name",label:o.G_Name,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ComplexCell.extend({className:"string-cell",formatter:{fromRaw:function(t){var e=(t.get("enabled")||!1,t.get("name"));return e},toRaw:function(t){return t}}})},{name:"essid",label:o.G_Overrides,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ComplexCell.extend({className:"string-cell",formatter:{fromRaw:function(e){var i=[],s=n.model.getOverride(e.get("_id"),t);if(!s)return"";if(s.hasOwnProperty("enabled")&&s.enabled!=e.get("enabled")){if(s.enabled===!0)return o.G_Enabled;if(s.enabled===!1)return o.G_Disabled}s.hasOwnProperty("name")&&s.name!=e.get("name")&&i.push("SSID:"+s.name),s.hasOwnProperty("vlan_enabled")&&(e.get("vlan_enabled")&&!s.vlan_enabled?i.push("VLAN:"+o.G_Disabled):!e.get("vlan_enabled")&&s.vlan_enabled&&i.push("VLAN:"+o.G_Enabled));var a=e.get("vlan_enabled")===!0&&s.vlan_enabled!==!1||e.get("vlan_enabled")===!1&&s.vlan_enabled===!0;return s.hasOwnProperty("vlan")&&a&&e.get("vlan")!=s.vlan&&i.push("VLAN:"+s.vlan),s.hasOwnProperty("x_passphrase")&&"wpapsk"==e.get("security")&&s.x_passphrase!=e.get("x_passphrase")&&i.push("PSK"),i.join(", ")},toRaw:function(t){return t}}})},{name:"_id",label:o.G_Actions,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ActionsCell.extend({actions:{override:{render:function(t){var e=n.app.collection("WlanGroups"),i=e.findWhere({_id:t.get("wlangroup_id")});return i&&i.get("roam_enabled")?!1:!0},callback:function(e){n.wLanOverrideModel=e,n.wLanOverrideRadio=t,n.$el.addClass("ap-show-override"),n.fillWlanForm()}}}})}];this.grids["wlan_"+t]=this.grid(d,new h(l),c,this["noWlanRows_"+t])}s.size(l)?c.show():c.hide();try{a.selectmenu("refresh")}catch(u){}},setupUplinksTable:function(){if(!this.rendered)return!1;var t=this,e=this.app.routers.devices.views.index,n=this.model.uplinks(),c=this.$(".data-table-uplinks"),d=this.$(".data-table-uplinks-none");if(s.size(n)?(c.show(),d.hide()):(c.hide(),d.show()),this.grids.uplinks)this.grids.uplinks.collection.set(n);else{var h=[{name:"mac",label:o.G_AP,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.collection.getDeviceFromMac(t.get("mac"));return n||(n=t),n.name()},toRaw:function(t){return t}}}),callback:function(t){var n=e.collection.getDeviceFromMac(t.get("mac"));n&&e.property(n)},title:"mac"},{name:"channel",label:o.G_ChannelAbbrev,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:"string"},{name:"rssi",label:o.G_DevicesSignal,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ModelCell.extend({callback:"calcRssi"})},{name:"configured",label:o.G_Actions,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ActionsCell.extend({actions:{select:{buttonClasses:"narrow",render:function(t){return!t.get("configured")},callback:function(e,n){var i=r(n.currentTarget);i.prop("disabled",!0),t.model.setVwireUplink({data:{uplink:e.get("mac"),mac:t.model.get("mac")},success:function(){(new m).open(o.G_DevicesTopologyChanged)},complete:function(){i.prop("disabled",!1)}})}},remove:{buttonClasses:"narrow",render:function(t){return t.get("configured")},callback:function(e,n){var i=r(n.currentTarget);i.prop("disabled",!0),t.model.unsetVwireUplink({data:{uplink:e.get("mac"),mac:t.model.get("mac")},success:function(){(new m).open(o.G_DevicesTopologyChanged)},complete:function(){i.prop("disabled",!1)}})}}}})}];this.grids.uplinks=this.grid(h,new a.Collection(n,{model:l}),this.$(".data-table-uplinks"),this.noUplinkRows)}},setupDownlinksTable:function(){if(!this.rendered)return!1;var t=this,e=this.app.routers.devices.views.index;if(this.grids.downlinks)this.grids.downlinks.collection.set(this.model.downlinks());else{var n=[{name:"ap_mac",label:o.G_AP,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var n=e.collection.getDeviceFromMac(t.get("ap_mac"));return n||(n=t),n.name()},toRaw:function(t){return t}}}),callback:function(t){var n=t.get("ap_mac"),i=e.collection.getDeviceFromMac(n);e.property(i)},title:"ap_mac"},{name:"rssi",label:o.G_DevicesSignal,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ModelCell.extend({callback:"calcRssi"})},{name:"_id",label:o.G_Actions,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ActionsCell.extend({actions:{remove:{buttonClasses:"narrow",callback:function(e,n){var i=r(n.currentTarget);i.prop("disabled",!0),t.model.unsetVwireUplink({data:{mac:e.get("ap_mac"),uplink:t.model.get("mac")},success:function(){(new m).open(o.G_DevicesTopologyChanged)},complete:function(){i.prop("disabled",!1)}})}}}})}];this.grids.downlinks=this.grid(n,new a.Collection(this.model.downlinks(),{model:l}),this.$(".data-table-downlinks"),this.noDownlinkRows)}},renderRfLegend:function(){var t=new n({el:this.$bindRfLegend});t.render()},renderRfEnvironment:function(t,e,n){this.spectrum_rendered[n]?(this.updateRfEnvironment(t,e,n),this.model.get("spectrum_scanning")===!0&&(this.populateRfEnvironment(t,e,n),this.spectrum_rendered[n]=!1)):(this.populateRfEnvironment(t,e,n),this.model.get("spectrum_scanning")===!1&&(this.spectrum_rendered[n]=!0))},populateRfEnvironment:function(t,n,i){var r=this,o=s.map(n,function(t){return s.extend(t,{frequencies:[r.model.getFrequency(i,t.channel)]})}),l=this.model.get("ng"==i?"ng-channel":"na-channel"),c=s.findWhere(this.model.get("radio_table"),{radio:i}),d=c?c.ht?c.ht:"ng"==i?"20":"40":null,h=new e({el:t,model:new a.Model({bandwidthGroups:o}),radioChannel:l,radioChannelWidth:d,radioType:i});this.rfEnvironments[i]=h,h.render()},updateRfEnvironment:function(t,e,n){if(this.rfEnvironments[n]){var i=this,o=s.map(e,function(t){return s.extend(t,{frequencies:[i.model.getFrequency(n,t.channel)]})}),l=this.model.get("ng"==n?"ng-channel":"na-channel"),c=s.findWhere(this.model.get("radio_table"),{radio:n}),d=c?c.ht?c.ht:"ng"==n?"20":"40":null;this.rfEnvironments[n].update(new a.Model({bandwidthGroups:o}),"2G"===r("input[name=ap-rf-frequency-filter]:checked").val()?"ng":"na",l,d)}},_onRfEnvironmentFrequencyChange:function(t){switch(r(t.target).val()){case"2G":this._showRfTab(this.$bindRfEnvironment2G,this.$bindRfEnvironmentLastUpdated2G);break;case"5G":this._showRfTab(this.$bindRfEnvironment5G,this.$bindRfEnvironmentLastUpdated5G)}},_hideAllRfTabs:function(){this.$bindRfEnvironment.hide(),this.$bindRfEnvironmentLastUpdated.hide()},_showRfTab:function(t,e){this._hideAllRfTabs(),t.show(),e.show()},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,t.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(t,e,n,i,s){"use strict";return t.extend({_templateId:n.template(s,{msg:i}),_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 e=this,n=this.rendered;t.prototype.render.call(this);var i=this.$container.parents(".portfwd-config");if(i.addClass("show-form"),!n){this.on("remove",function(){i.removeClass("show-form")}),this.$fwdPort=this.$("input[name=fwd_port]"),this.$dstPort=this.$("input[name=dst_port]"),this.$src_type=this.$("input[name=src_type]"),this.$src_type_limited=this.$("input[name=src_type][value=limited]"),this.$src=this.$("input[name=src]"),this.$dstPort.on("change",function(){var t=e.$dstPort.val().indexOf("-")>=0||e.$dstPort.val().indexOf(",")>=0;e.$fwdPort.val(e.$dstPort.val()),e.$fwdPort.enable(),t&&t&&e.$fwdPort.disable()}),this.$fwdPort.on("change",function(){var t=e.$fwdPort.val().indexOf("-")>=0||e.$fwdPort.val().indexOf(",")>=0;e.$fwdPort.enable(),t&&(e.$dstPort.val(e.$fwdPort.val()),t&&e.$fwdPort.disable())});var s=this.$dstPort.val().indexOf("-")>=0||this.$dstPort.val().indexOf(",")>=0;this.$fwdPort.val(this.$dstPort.val()),this.$fwdPort.enable(),s&&s&&this.$fwdPort.disable(),this.$src_type.on("change",function(){e.$src_type_limited.is(":checked")?e.$src.enable():(e.$src.disable(),e.$src.val(""),e.valid(["src"]))}),this.$src_type_limited.is(":checked")?this.$src.enable():this.$src.disable(),this.app.isReadOnly||this.prevalidator()}},populate:function(){var t=this.model.get("src"),e=!t||"any"==t;this.model&&(this.$el.find("input[name=name]").val(this.model.get("name")),this.$el.find("input[name=src_type][value="+(e?"any":"limited")+"]").prop("checked",!0),this.$el.find("input[name=src]").val(e?"":t),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 t=this.$el.find("input[name=src]").val(),e="any"==this.$el.find("input[name=src_type]:checked").val();return{name:this.$el.find("input[name=name]").val(),src:e?"any":t,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(t,e){this.options.app.views.app.flash("error","Error",i.apiError(e))},remove:function(){this.$("input[name=dst_port]").off(),t.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(t,e,n,i,s){"use strict";return t.extend({_templateId:n.template(s,{msg:i}),_prevalidate:{login:{input:"text"},x_password:{input:"password"},host_name:{input:"text"},server:{input:"text"}},events:{"click button[name=cancel]":"remove"},render:function(){var e=this.rendered;t.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"),e||(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 t={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 t},success:function(){this.remove()},error:function(t,e){this.options.app.views.app.flash("error","Error",i.apiError(e))},remove:function(){t.prototype.remove.apply(this,arguments)}})}),define("unifi/model/PortForward",["unifi/model/Model","underscore","backbone","msg/Msg"],function(t,e,n,i){"use strict";return t.extend({validate:function(t,n){var s={},a=n?n.partial:null;return a&&"name"!=a||(t.name?this.validator.name(t.name)||(s.name=i.localize(i.E_InvalidName,i.G_Name)):s.name=i.localize(i.E_CannotBeEmpty,i.G_Name)),a&&"src"!=a||(t.src?"any"==t.src||this.validator.ip(t.src)||this.validator.iprange(t.src)||this.validator.subnet(t.src)||"!"===t.src.charAt(0)&&(this.validator.ip(t.src.substring(1))||this.validator.iprange(t.src.substring(1))||this.validator.subnet(t.src.substring(1)))||(s.src=i.localize(i.E_IncorrectIPRangeSubnet,i.G_PortForwardSource)):s.src=i.localize(i.E_CannotBeEmpty,i.G_PortForwardSource)),a&&"dst_port"!=a||(t.dst_port?this.validator.rangeList(t.dst_port,",-",15,1,65535)||(s.dst_port=i.localize(i.E_IncorrectNumberRangeList,i.G_Port,15,1,65535)):s.dst_port=i.localize(i.E_CannotBeEmpty,i.G_Port)),a&&"fwd"!=a||(t.fwd?this.validator.ip(t.fwd)||(s.fwd=i.localize(i.E_IncorrectIPAddress,i.G_PortForwardDestIp)):s.fwd=i.localize(i.E_CannotBeEmpty,i.G_PortForwardDestIp)),a&&"fwd_port"!=a||(t.fwd_port?this.validator.rangeList(t.fwd_port,",-",15,1,65535)||(s.fwd_port=i.localize(i.E_IncorrectNumberRangeList,i.G_PortForwardDestPort,15,1,65535)):s.fwd_port=i.localize(i.E_CannotBeEmpty,i.G_PortForwardDestPort)),e.size(s)?s:void 0},sync:function(t,e,i){switch(i=i||{},t){case"create":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/add/portforward",i.type="POST";break;case"update":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/upd/portforward/"+e.id,i.type="POST",i.data=JSON.stringify(e.toJSON({exclude:["_id","site_id"]}));break;case"delete":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/del/portforward/"+e.id,i.type="POST"}return n.sync.call(this,t,e,i)}})}),define("unifi/collection/PortForward",["unifi/collection/Collection","underscore","unifi/model/PortForward"],function(t,e,n){"use strict";return t.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(t,e,n,i){"use strict";return t.extend({validate:function(t,n){var s={},a=n?n.partial:null;return a&&"login"!=a||t.login||(s.login=i.localize(i.E_CannotBeEmpty,i.G_PropertiesDDNSUsername)),a&&"x_password"!=a||t.x_password||(s.x_password=i.localize(i.E_CannotBeEmpty,i.G_PropertiesDDNSPassword)),a&&"host_name"!=a||t.host_name||(s.host_name=i.localize(i.E_CannotBeEmpty,i.G_PropertiesDDNSHostname)),e.size(s)?s:void 0},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(t,e,i){switch(i=i||{},t){case"create":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/add/dynamicdns",i.type="POST";break;case"update":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/upd/dynamicdns/"+e.id,i.type="POST",i.data=JSON.stringify(e.toJSON({exclude:["_id","site_id"]}));break;case"delete":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/del/dynamicdns/"+e.id,i.type="POST"}return n.sync.call(this,t,e,i)}})}),define("unifi/collection/DynamicDNS",["unifi/collection/Collection","underscore","unifi/model/DynamicDNS"],function(t,e,n){"use strict";return t.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>\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\') %>" pattern=".{1,128}" title="<%- msg.E_AliasName %>" />\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>\n'}),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(t,e,n,i,s,a,r,o,l,c,d,h,u,p,m,f){"use strict";return t.extend({templateId:h,diagramTemplate:null,bindings:function(){return a.extend({},t.prototype.bindings.call(this),{".bind-wan-ip":{observe:"uplink",onGet:function(t){this.$bindWanIp.text(t.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(t){this.populateNetworkForm(this.$wanForm,t)}},".bind-networks":{observe:"network_table",onGet:function(){this.networkTable()}},".bind-state":{observe:["uplink","port_table"],onGet:function(){this.populateStates()}},".bind-lan-ip":{observe:"port_table",onGet:function(t){var e=a.findWhere(t,{name:"lan"});e&&this.$bindLanIp.text(e.ip||"")}}})},initialize:function(e){switch(this.model.get("model")){case"UGW3":this.diagramTemplate=a.template(u,{msg:l});
break;case"UGW8":this.diagramTemplate=a.template(p,{msg:l})}t.prototype.initialize.call(this,e)},dependencies:function(){var t={PortForward:c,DynamicDNS:d},e=[],n={},i=this;a.each(t,function(t,i){e.push(n[i]=o.Deferred())},this),o.when.apply(o,e).then(function(){i._dependencies.resolve()},function(){i._dependencies.reject()}),a.each(t,function(t,e){this.app.collection(e,{fetch:{reload:!1,deferred:n[e]}},t)},this)},render:function(e){var n=this.rendered;return t.prototype.render.call(this,e),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.$portFwdCreate=this.$('.portfwd-config button[name="create"]'),this.$portFwdList=this.$(".portfwd-list"),this.$portFwdForm=this.$(".portfwd-form"),this.$portFwdCreate.on("click",o.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",o.proxy(function(){this.dynamicDNSForm()},this)),this.$dynamicDNSForm.hide(),this.$connectionType.on("change",o.proxy(function(t){var e=o(t.target).val();this.$wanForm.find(".connection-toggled").hide().filter(".connection-"+e).show()},this)).trigger("change"),this.$wanForm.on("submit",o.proxy(function(t){t.preventDefault(),this.updateNetwork(this.$wanForm,"config_network_wan")},this)),this.renderDiagram(),"resolved"===this._rendered.state()&&"resolved"==this._dependencies.state()?this.populate():"pending"===this._rendered.state()&&this._rendered.resolve(),this.stickit(this.model,this.bindings())),this.populateStates(),this.networkTable(),this.portForwardTable(),this.dynamicDNSTable(),this.toggleAdvancedAdoption(),n||this.detach(),this.options.options&&"lan"==this.options.options.port&&this.$diagramLan.click(),this},toggleAdvancedAdoption:function(){var t=this.app.collection("Devices"),e=t.where({type:"ugw",site_id:SITE.id});e.length?(this.isAdoptable?(this.$el.find("div.gw-adv-adopt").hide(),this.$advAdoptForm.off("submit",this.onAdvAdoptFormSubmit)):void 0===this.isAdoptable&&this.$el.find("div.gw-adv-adopt").hide(),this.isAdoptable=!1):this.isAdoptable||(this.isAdoptable=!0,this.$el.find("div.gw-adv-adopt").hide(),this.$el.find("div.gw-adv-adopt.accordion-header").show(),this.$advAdoptForm.on("submit",this.onAdvAdoptFormSubmit))},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",o.proxy(function(){var t=a.findWhere(this.model.get("port_table"),{name:"wan"}),e=t&&t.up?t.up:!1;this.$tabs.tabs("option","active",0),e&&this.$gatewayDetails.find(".accordion").accordion("option","active",1)},this)),this.$diagramLan.on("click",o.proxy(function(){this.$tabs.tabs("option","active",1)},this)),this.$diagramVoice.on("click",o.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:l}},onAdvAdoptFormSubmit:function(t){t.preventDefault();var e=this,n=this.model,i=o(t.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(t){"ok"===t.meta.rc?n.fetch({success:function(t,n){"ok"===n.meta.rc&&e.parent.property(t)},complete:function(){i.removeAttr("disabled")}}):(e.showErrorState(),i.removeAttr("disabled"))},error:function(){e.showErrorState(),i.removeAttr("disabled")}});!s&&this.model.validationError&&a.each(this.model.validationError,function(t,e){switch(e){case"username":case"password":this.$advAdoptForm.find('input[name="'+e+'"]').addClass("error"),i.removeAttr("disabled")}},this)},populate:function(){this.$el.addClass("gateway-properties"),t.prototype.populate.call(this),this._dependencies&&"resolved"==this._dependencies.state()&&this.position()},populateStates:function(){this.$el.removeClass("gw-has-wan gw-has-lan gw-has-voice"),a.each(this.model.get("port_table")||[],o.proxy(function(t){var e=this.$diagram.find(".port."+t.name);e.removeClass("shutdown up green orange"),t.enable||e.addClass("shutdown"),t.up&&(this.$el.addClass("gw-has-"+t.name.replace(/[^a-z]/,"")),e.addClass("up"),1e3==t.speed?e.addClass("green"):(100==t.speed||10==t.speed)&&e.addClass("orange"))},this))},networkTable:function(){if(!this.rendered)return!1;if(this.grids.networks)this.grids.networks.collection.set(this.model.networks());else{var t=[{name:"name",label:l.G_Network,editable:!1,cell:"string"},{name:"ip",label:l.G_IP,editable:!1,cell:"string"},{name:"tx_bytes",label:l.G_DevicesTX,editable:!1,cell:s.StringCell.extend({formatter:i.Formatters.Bytes})},{name:"rx_bytes",label:l.G_DevicesRX,editable:!1,cell:s.StringCell.extend({formatter:i.Formatters.Bytes})},{name:"num_sta",label:l.G_PropertiesNumHosts,editable:!1,cell:"integer"}];this.grids.networks=this.grid(t,new r.Collection(this.model.networks()),this.$(".data-table-networks"),this.noNetworkRows)}},portForwardTable:function(){if(!this.rendered)return!1;if(!this.grids.portfwd){var t=[{name:"name",label:l.G_Name,editable:!1,cell:"string"},{name:"src",label:l.G_PortForwardSource,editable:!1,cell:s.StringCell.extend({formatter:{fromRaw:function(t){return t&&"any"!=t?t:"*"},toRaw:function(t){return t}}})},{name:"dst_port",label:l.G_Port,customClass:"detached-only",editable:!1,cell:"string"},{name:"fwd",label:l.G_PortForwardDest,customClass:"detached-only",editable:!1,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){return a.filter([t.get("fwd"),t.get("fwd_port")],function(t){return t}).join(":")},toRaw:function(t){return t}}})},{name:"_id",label:l.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.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:o.proxy(function(t){(new f).show(l.G_PropertiesPortForwardDeleteConfirm,o.proxy(function(){t.destroy({success:o.proxy(function(t,e){"ok"===e.meta.rc?this.showSavedState():this.showErrorState()},this),error:o.proxy(function(){this.showErrorState()},this)})},this))},this)}}})}];this.grids.portfwd=this.grid(t,this.app.collection("PortForward"),this.$(".data-table-portfwd"),this.noPortFwdRows,{paginateToAddedModel:!0}),this.grids.portfwd&&this.grids.portfwd.setFilter("name")}},portForwardForm:function(t){var n=this.app.collection("PortForward");this.forms.PortForward=new e({app:this.app,container:this.$portFwdForm,collection:n,model:t||new n.model}),this.listenTo(this.forms.PortForward,"remove",o.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 t=[{name:"service",label:l.G_PropertiesDDNSService,editable:!1,cell:"string"},{name:"host_name",label:l.G_PropertiesDDNSHostname,editable:!1,cell:"string"},{name:"login",label:l.G_PropertiesDDNSUsername,customClass:"detached-only",editable:!1,cell:"string"},{name:"x_password",label:l.G_PropertiesDDNSPassword,customClass:"detached-only",editable:!1,cell:"string"},{name:"server",label:l.G_PropertiesDDNSServer,customClass:"detached-only",editable:!1,cell:"string"},{name:"_id",label:l.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.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:o.proxy(function(t){(new f).show(l.G_PropertiesDDNSDynamicDNSDeleteConfirm,o.proxy(function(){t.destroy({success:o.proxy(function(t,e){"ok"===e.meta.rc?this.showSavedState():this.showErrorState()},this),error:o.proxy(function(){this.showErrorState()},this)})},this))},this)}}})}];this.grids.dynamicdns=this.grid(t,this.app.collection("DynamicDNS"),this.$(".data-table-dynamicdns"),this.noDynamicDNSRows,{paginateToAddedModel:!0}),this.grids.dynamicdns&&this.grids.dynamicdns.setFilter("service")}},dynamicDNSForm:function(t){var e=this.app.collection("DynamicDNS");this.forms.DynamicDNS=new n({app:this.app,container:this.$dynamicDNSForm,collection:e,model:t||new e.model}),this.listenTo(this.forms.DynamicDNS,"remove",o.proxy(function(){this.forms.DynamicDNS=null},this)),this.forms.DynamicDNS.render(),this.position()},statsDynamicDNSForm:function(t,e){this.$tabs.tabs("option","active",2),this.$gatewayConfig.find(".accordion").accordion("option","active",3),e&&this.dynamicDNSForm(t)},statsPortForwardForm:function(t,e){this.$tabs.tabs("option","active",2),this.$gatewayConfig.find(".accordion").accordion("option","active",2),e&&this.portForwardForm(t)},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.$advAdoptForm.off("submit",this.onAdvAdoptFormSubmit),this.rendered=!1,t.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(t,e,n,i,s){"use strict";return t.extend({_templateId:n.template(s,{msg:i}),_prevalidate:{name:{input:"text"}},events:{"change #network":"onNetworkChange","click button[name=cancel]":"remove",'click input[name="networks"]':"onTaggedNetworkChange"},onNetworkChange:function(t){var e=this.$el.find("input[type=checkbox][name=networks]");e.prop("disabled",!1),e.filter(":checkbox[value="+t.target.value+"]").prop("checked",!1).prop("disabled",!0)},onTaggedNetworkChange:function(t){var n=e(t.target),i=this.$el.find("select[name=network]"),s=i.find('option[value="'+n.val()+'"]');n.is(":checked")&&(s.prop("selected",!1),i.val()==n.val()&&(s=i.find("option:first"),s.prop("selected",!0))),i.selectmenu("refresh")},render:function(){var e=this.rendered;t.prototype.render.call(this);var n=this.$container.parents(".networks-vlan-config");n.addClass("show-form"),e||(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 t=this.app.collection("Networks").filterByPurpose(["corporate","guest","voip","vlan-only"]),s=this.$("select[name=network]"),a=this.$(".networks");a.empty(),s.empty(),s.append(e('<option value=""></option>').text(i.G_None)),n.each(t,function(t){a.append(e('<label><input type="checkbox" name="networks" value="'+t.id+'" /> '+t.get("name")+"</label>")),s.append(e('<option value="'+t.id+'"></option>').text(t.get("name")))}),s.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 t=this.$el.find("input[type=checkbox][name=networks]");t.prop("checked",!1),n.each(this.model.get("tagged_networkconf_ids")||[],function(e){t.filter(":checkbox[value="+e+"]").prop("checked",!0)})}},gather:function(){var t={name:this.$el.find("input[name=name]").val()};return t.native_networkconf_id=this.$el.find("select[name=network] option:selected").val(),t.tagged_networkconf_ids=this.$el.find("input[name=networks]:checked").map(function(){return e(this).val()}).get(),t.forward=t.native_networkconf_id&&n.isEmpty(t.tagged_networkconf_ids)?"native":"customize",t},success:function(){this.remove()},error:function(t,e){this.options.app.views.app.flash("error","Error",i.apiError(e))},remove:function(){this.stopListening(this.app.collection("Networks"),"add remove"),this.rendered=!1,t.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 duplex 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="portconf_speed" class="input inline" name="portconf_speed">\n                        <option value="10000"><%- msg.G_Properties10Gbps %></option>\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(t,e,n,i,s,a){"use strict";return t.extend({_templateId:i.template(a,{msg:s}),_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 e=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 s=[],a=null,r=!1;i.each(this.options.overrides,function(t){var e=t.get("port_idx");r||(r=t.get("port_poe")),"aggregate"==t.get("op_mode")?(s.push(e+"-"+(e+t.get("aggregate_num_ports")-1)),a=null):e===this.selection.firstIdx?s.push(e):e!==a+1?(s[s.length-1]!==a&&(s[s.length-1]+="-"+a),s.push(e)):e===this.selection.lastIdx&&(e===a+1?s[s.length-1]+="-"+e:s.push(e)),a=e},this),this.selection.indexesLabel=s.join(", "),this.selection.supportsPoe=r,t.prototype.render.call(this);var o=this.$container.parents(".port-list-config");o.addClass("show-form");this.$el;if(!e){this.on("remove",function(){o.removeClass("show-form")}),this.$el.find("input[name=op_mode]").radiotoggle({container:this.$el});var l=1===this.selection.count?this.options.overrides[0]:null;l&&l.get("media")&&"SFP"!==l.get("media")?(n(".autoneg").show(),this.$el.find("input[name=portconf_autoneg]").change(function(){"auto"===n(this).val()?n(".autoneg-disable").hide():(n(".autoneg-disable").show(),"SFP+"===l.get("media")&&n(".duplex").hide())})):n(".autoneg").hide(),this.renderPortConf(),this.app.isReadOnly||this.prevalidator()}},renderPortConf:function(){var t=this.$el.find("select[name=portconf_id]");t.empty(),this.selection.count>1&&t.append(n('<option value=""></option>').text("(Keep existing)")),this.app.collection("PortConf").each(function(e){t.append(n('<option value="'+e.id+'"></option>').text(e.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),t.selectmenu("refresh"),this.populate()},populate:function(){var t=1===this.selection.count?this.options.overrides[0]:null,e=t?t.get("poe_mode")||"auto":"auto",n=t?t.get("op_mode")||"switch":"switch",a={};if(i.each(this.model.get("port_overrides"),function(t){a[t.port_idx]=!0},this),t){this.$el.find("input[name=name]").val(t.get("name")),this.$el.find("input[name=poe_mode][value="+e+"]").prop("checked",!0).trigger("change"),this.$el.find("select[name=portconf_id]").val(t.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(t.get("mirror_port_idx")),this.$el.find("input[name=aggregate_num_ports]").val(t.get("aggregate_num_ports")?parseInt(t.get("port_idx"),10)+parseInt(t.get("aggregate_num_ports"),10)-1:"");var r,o,l;a[t.get("port_idx")]?(r=t.get("autoneg")?"auto":"manual",o=t.get("full_duplex"),l=t.get("speed")):(r="auto",o=!0,l="1000");{t.get("media")}"SFP"!==t.get("media")&&"SFP+"!==t.get("media")?this.$el.find('select[name="portconf_speed"] option[value=10000]').remove():"SFP+"===t.get("media")&&(this.$el.find('select[name="portconf_speed"] option[value=100]').remove(),this.$el.find('select[name="portconf_speed"] option[value=10]').remove()),this.$el.find("input[name=portconf_autoneg][value="+r+"]").prop("checked",!0).trigger("change"),this.$el.find("input[name=portconf_fullduplex]").prop("checked",o).trigger("change"),this.$el.find("select[name=portconf_speed]").val(l).trigger("change"),"switch"!=n&&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(1===this.selection.count){this.$el.find("fieldset.advanced input").prop("disabled",!1),this.$el.find("input[name=aggregate_start]").val(t.get("port_idx")).disable();for(var c=this.selection.firstIdx+1,d=this.selection.firstIdx+3,h=this.model.numPorts(),u=this.$el.find("input[name=aggregate_num_ports]"),p=this.model.get("port_table"),m=(p.length,this.selection.firstIdx);d>m;m++)if(d>m){var f=p[m];if(f&&"switch"!==f.op_mode){d=m;break}}d>h&&(d=h),this.$el.find('input[name=op_mode][value="aggregate"]').parents("label:first").css("display",c>h||c>d?"none":"inline-block"),d-c>0?(this.$el.find(".aggregate-limits").text("("+s.localize(s.G_BetweenXandY,c,d)+")"),u.enable()):(u.val(c),u.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 t=i.clone(this.model.get("port_overrides")),e=[],s=this.$el.find("input[name=name]").val(),a=this.$el.find("input[name=poe_mode]:checked").val(),r=this.$el.find("select[name=portconf_id]").val(),o=this.$el.find("input[name=op_mode]:checked").val();i.each(this.options.overrides,function(t){var i={port_idx:t.get("port_idx"),name:"(Keep existing)"===s?t.get("name"):s,portconf_id:r||t.get("portconf_id"),op_mode:o};if(this.selection.supportsPoe&&"SFP"!==t.get("media")&&"SFP+"!==t.get("media")&&(i.poe_mode=a),!i.name)switch(i.name="Port "+t.get("port_idx"),this.model.get("model")){case"US24":case"US24P250":case"US24P500":i.port_idx>24&&(i.name="SFP "+(i.port_idx-24));break;case"US48":case"US48P500":case"US48P750":i.port_idx>50?i.name="SFP "+(i.port_idx-50):i.port_idx>48&&(i.name="SFP+ "+(i.port_idx-48))}"mirror"==i.op_mode?i.mirror_port_idx=this.$el.find("input[name=mirror_port_idx]").val():"aggregate"==i.op_mode&&(i.aggregate_num_ports=this.$el.find("input[name=aggregate_num_ports]").val()-this.selection.firstIdx+1),n(".autoneg").is(":visible")&&(i.autoneg="auto"===this.$el.find("input[name=portconf_autoneg]:checked").val()?!0:!1,i.autoneg||(i.full_duplex=this.$el.find("input[name=portconf_fullduplex]:checked").is(":checked"),i.speed=this.$el.find("select[name=portconf_speed]").val())),e.push(i)},this);var l=e.map(function(t){return t.port_idx});return t=t?i.reject(t,function(t){return l.indexOf(t.port_idx)>-1}):[],t=t.concat(e),{port_overrides:t}},save:function(t){t&&t.preventDefault();var i=n.proxy(function(){this.clear(),this.$submit.trigger("saving");var t=this._save(this.model,null,{wait:!0,data:this.gather(),extra:{portidx:this.selection.firstIdx}});t?this.formResult="success":this.$submit.trigger("error",!0)},this),a=this.model.get("inform_ip"),r=this.app.collection("Clients").getUserFromIp(a);"undefined"!=typeof r&&this.model.get("mac")===r.get("sw_mac")&&this.portidx==r.get("sw_port")?(new e).show(s.localize(s.N_ConfirmPortConfigApply,this.portidx,a),i):i()},success:function(){this.model.fetch(),this.remove()},error:function(t,e){this.options.app.views.app.flash("error","Error",s.apiError(e,!0))},remove:function(){this.rendered=!1,this.$el.find("input[name=portconf_autoneg]").off(),t.prototype.remove.apply(this,arguments)}})}),define("unifi/model/PortConf",["unifi/model/Model","underscore","backbone","msg/Msg"],function(t,e,n,i){"use strict";return t.extend({validate:function(t,n){var s={},a=n?n.partial:null;return a&&"name"!=a||(t.name?this.validator.name(t.name)||(s.name=i.localize(i.E_InvalidName,i.G_Name)):a||(s.name=i.localize(i.E_CannotBeEmpty,i.G_Name))),e.size(s)?s:void 0},sync:function(t,e,i){switch(i=i||{},t){case"create":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/add/portconf",i.type="POST";break;case"update":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/upd/portconf/"+e.id,i.type="POST",i.data=JSON.stringify(e.toJSON({exclude:["_id","site_id"]}));break;case"delete":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/del/portconf/"+e.id,i.type="POST"}return n.sync.call(this,t,e,i)}})}),define("unifi/collection/PortConf",["unifi/collection/Collection","underscore","unifi/model/PortConf"],function(t,e,n){"use strict";return t.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 temperature">\n                                <td class="column-name"><%- msg.G_Temperature %></td>\n                                <td class="column-value bind-temperature"></td>\n                            </tr>\n                            <tr class="table-row fan-level sw-fan-details">\n                                <td class="column-name"><%- msg.G_FanLevel %></td>\n                                <td class="column-value bind-fan-level"></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\') %>" pattern=".{1,128}" title="<%- msg.E_AliasName %>" />\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="mgmt_network" id="mgmt_network<%- _id %>">\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/switchDiagramUS8PTemplate.html",[],function(){return'<div class="diagram switch port8 bind-state">\n    <div class="detached">\n        <div class="top">\n            <% for (var i = 1; i <= 8; i++) { %>\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        </div>\n    </div>\n    <div class="attached">\n        <div class="top">\n            <% for (var i = 1; i <= 8; i++) { %>\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        </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/switchDiagramUS8PTemplate.html","text!includes/switches/switchDiagramUS24PTemplate.html","text!includes/switches/switchDiagramUS48PTemplate.html","ubnt/view/dialogs/AlertDialogView","ubnt/view/dialogs/ConfirmDialogView","stickit"],function(t,e,n,i,s,a,r,o,l,c,d,h,u,p,m,f,g){"use strict";return t.extend({templateId:h,diagramTemplate:null,bindings:function(){return a.extend({},t.prototype.bindings.call(this),{".bind-uplink":{observe:"uplink",onGet:function(t){if(t){var e=this.parent.options.app.collection("Devices").getDeviceFromMac(t.uplink_mac);e&&this.$bindUplinkDevice.text(e.name()).data("mac",e.get("mac")||""),this.$bindUplinkPort.text(t.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(){this.downlinksTable()}},".bind-ports":{observe:"port_table",onGet:function(){this.portsTable(!0)}},".bind-power-consumption":{observe:"port_table",onGet:function(){this.$bindPowerConsumption.text(this.model.power()+" "+l.G_Watt)}},".bind-temperature":{observe:"general_temperature",onGet:function(){var t=parseInt(this.model.get("general_temperature"),10)||-1;this.$bindTemperature.empty(),t>0&&this.$bindTemperature.text(this.model.get("general_temperature")).append(l.G_DegreeCelsius)}},".bind-fan-level":{observe:"fan_level",onGet:function(){this.$bindFanLevel.text(this.model.fan_level())}},".bind-network":{observe:"config_network",onGet:function(t){this.populateNetworkForm(this.$networkForm,t)}},".button-edit":{observe:["state","map_id","default","upgradable","locating"],onGet:function(){var t=this.model.get("state");1==t?this.$btnEdit.show():this.$btnEdit.hide(),t!==this.lastPortState&&(this.position(),this.lastPortState=t)}}})},initialize:function(e){switch(this.portConfCollection=e.parent.options.app.collection("PortConf"),this.model.get("model")){case"US8P150":this.diagramTemplate=a.template(u,{msg:l});break;case"US24":case"US24P250":case"US24P500":this.diagramTemplate=a.template(p,{msg:l});break;case"US48":case"US48P500":case"US48P750":this.diagramTemplate=a.template(m,{msg:l})}this.listenTo(this.portConfCollection,"add remove change",o.proxy(function(){this.networksVlanTable(),this.portsTable()},this)),t.prototype.initialize.call(this,e)},dependencies:function(){var t={PortConf:c,Networks:d},e=[],n={},i=this;a.each(t,function(t,i){e.push(n[i]=o.Deferred())},this),o.when.apply(o,e).then(function(){i._dependencies.resolve()},function(){i._dependencies.reject()}),a.each(t,function(t,e){this.options.parent.app.collection(e,{fetch:{reload:!1,deferred:n[e]}},t)},this)},render:function(e){var n=this.rendered;return t.prototype.render.call(this,e),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.$bindTemperature=this.$(".bind-temperature"),this.$bindFanLevel=this.$(".bind-fan-level"),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",o.proxy(function(t){t.preventDefault(),this.updateServices()},this)),this.$networkForm.on("submit",o.proxy(function(t){t.preventDefault(),this.updateNetwork(this.$networkForm,"config_network")},this)),this.$connectionType.on("change",o.proxy(function(t){var e=o(t.target).val();this.$networkForm.find(".connection-toggled").hide().filter(".connection-"+e).show()},this)).trigger("change"),this.$networksVlanCreate.on("click",o.proxy(function(){this.networksVlanForm()},this)),this.$networksVlanForm.hide(),this.$portList.on("click","tr",o.proxy(function(t){var e,n=o(t.target).closest("tr");if(t.metaKey||t.ctrlKey){{var i=n.closest("tr").find(".column-checkboxes input:not([disabled])");i.is(":checked")}window.getSelection?window.getSelection().removeAllRanges():document.selection&&document.selection.empty(),i.trigger("click"),this.highlightPort(e,!1)}else"tbody"==n.parent().prop("tagName").toLowerCase()&&(e=n.attr("class").replace("port-","")),this.highlightPort(e)},this)),this.$diagram.on("click",".port",o.proxy(function(t){if(t.preventDefault(),!this.forms.Port){var e=o(t.target).closest(".port"),n=e.data("port");if(t.metaKey||t.ctrlKey){var i=this.$portList.find("tr.port-"+n).find(".column-checkboxes input:not([disabled])");i.trigger("click"),this.highlightPort(n,!1)}else this.highlightPort(n)}},this)),"resolved"===this._rendered.state()&&"resolved"===this._dependencies.state()?this.populate():"pending"===this._rendered.state()&&this._rendered.resolve(),this.adjustData&&this.adjustData(),this.stickit(this.model,this.bindings()),this.$tabs.on("change",o.proxy(function(){this.toggleEditButton()},this)),this.toggleEditButton(),this.listenTo(this.app.collection("Networks"),"add remove",this.renderMgmtNetworks)),this.networksVlanTable(),this.portsTable(),this.renderMgmtNetworks(),n||this.detach(),this.options.options&&this.options.options.port&&this.highlightPort(this.options.options.port),this},renderMgmtNetworks:function(){var t=this.app.collection("Networks").filterByPurpose(["corporate","guest","voip","vlan-only"]),e=this.$("select[name=mgmt_network]"),n=this.model.get("networkgroup")||"LAN",i=a.find(t,function(t){return t.get("attr_no_delete")===!0&&t.get("networkgroup")===n})||t[0],s=this.model.get("mgmt_network_id")||i.id;e.empty(),a.each(t,function(t){e.append(o('<option value="'+t.id+'"></option>').text(t.get("name")))}),e.find('option[value="'+s+'"]').prop("selected",!0)},toggleEditButton:function(){1!==this.$tabs.tabs("option","active")||this.forms.Port?this.$tabs.find(".dialog-controls .button-edit").hide():this.$tabs.find(".dialog-controls .button-edit").show();var t=this.model.get("state");t!==this.lastPortState&&(this.position(),this.lastPortState=t)},edit:function(t){var e=o(t.target),n=e.hasClass("disabled"),i=this.$portList.find('.checkbox-cell input[type="checkbox"]:checked'),s=a.map(i,function(t){return t.id}),r=a.filter(this.model.collections.portTable.models,function(t){return-1!==s.indexOf(""+t.id)});!n&&i.length&&(this.portForm(r,null,!0),this.toggleEditButton())},args:function(){return{_id:this.id,diagram:this.diagramTemplate,msg:l}},adjustData:function(){},onAdvAdoptFormSubmit:function(t){t.preventDefault();var e=this,n=this.model,i=o(t.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(t){"ok"===t.meta.rc?n.fetch({success:function(t,n){"ok"===n.meta.rc&&e.parent.property(t)},complete:function(){i.removeAttr("disabled")}}):(e.showErrorState(),i.removeAttr("disabled"))},error:function(){e.showErrorState(),i.removeAttr("disabled")}});!s&&this.model.validationError&&a.each(this.model.validationError,function(t,e){switch(e){case"username":case"password":this.$advAdoptForm.find('input[name="'+e+'"]').addClass("error"),i.removeAttr("disabled")}},this)},populate:function(){var e=this.$(".properties-container"),n=e.scrollTop();this.$el.addClass("switch-properties"),t.prototype.populate.call(this),this._dependencies&&"resolved"==this._dependencies.state()&&(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")),a.each(this.model.collections.portTable.models||[],o.proxy(function(t){var e=this.$diagram.find(".port-"+t.id);e.removeClass("shutdown up green orange poe mirror block").addClass(t.diagramClasses()).attr("title","Port "+t.get("port_idx")).tooltip({show:!1,hide:!1,track:!0,content:function(){return t.diagramTooltip()}})},this)),this.position(),a.delay(function(){e.scrollTop(n)},0))},populateStates:function(){this.$el.removeClass("sw-has-fan, 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"),this.model.get("has_fan")&&this.$el.addClass("sw-has-fan")},downlinksTable:function(){if(!this.rendered)return!1;if(this.grids.downlinks)this.grids.downlinks.collection.set(this.model.get("downlink_table"));else{var t=[{name:"port_idx",label:l.G_Port,editable:!1,cell:"integer"},{name:"mac",label:l.G_PropertiesDevice,editable:!1,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:o.proxy(function(t){var e=this.parent.options.app.collection("Devices"),n=t.get("mac")?e.getDeviceFromMac(t.get("mac")):null;return n?n.name():t.get("mac")},this),toRaw:function(t){return t}}}),callback:o.proxy(function(t){var e=this.parent.options.app.routers.devices.views.index,n=e.collection.getDeviceFromMac(t.get("mac"));e.property(n)},this)},{name:"model",label:l.G_DevicesModel,editable:!1,headerCell:i.Headers.customSortHeader,sortValue:o.proxy(function(t){var e=this.parent.options.app.collection("Devices"),n=t.get("mac")?e.getDeviceFromMac(t.get("mac")):null;return n?n.apModel():""},this),cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:o.proxy(function(t){var e=this.parent.options.app.collection("Devices"),n=t.get("mac")?e.getDeviceFromMac(t.get("mac")):null;return n?n.apModel():""},this),toRaw:function(t){return t}}})},{name:"status",label:l.G_Status,editable:!1,headerCell:i.Headers.customSortHeader,sortValue:o.proxy(function(t){var e=t.get("speed")+" ";return e+=t.get("full_duplex")?l.G_PropertiesFullDuplexAbbrv:l.G_PropertiesHalfDuplexAbbrv},this),cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){var e=t.get("speed")+" ";return e+=t.get("full_duplex")?l.G_PropertiesFullDuplexAbbrv:l.G_PropertiesHalfDuplexAbbrv},toRaw:function(t){return t}}})}];this.grids.downlinks=this.grid(t,new r.Collection(this.model.get("downlink_table")),this.$(".data-table-downlinks"),this.noDownlinksRows)}},displayUplinkDevice:function(){var t=this.app.routers.devices.views.index,e=t.collection.getDeviceFromMac(this.model.uplinkDeviceMac());return e&&t.property(e),!1},portsTable:function(t){if(this.lastPortState=null,!this.rendered)return!1;if(this.grids.ports)this.grids.ports.refresh();else{var e=[{name:"_checkboxes",customClass:"column-checkboxes",editable:!1,sortable:!1,headerCell:i.Headers.CheckboxHeader,cell:i.Cells.CheckboxCell.extend({config:{callback:this.portSelectionChanged},render:function(){var t=!!this.$checkbox;if(!t){this.$checkbox=this.$el.find('input[type="checkbox"]'),this.$el.empty();var e=this.config,n=e.callback||o.noop,i=this.model,s=e.options;(!e.render||e.render(i,s))&&this.$el.append(o('<input type="checkbox" id="'+i.id+'">').on("click",function(t){var e=o(t.target),s=e.is(":checked");s?(e.closest("tr").addClass("select"),e.closest(".property-content").find(".diagram div.port-"+i.id).addClass("select")):(e.closest("tr").removeClass("select"),e.closest(".property-content").find(".diagram div.port-"+i.id).removeClass("select")),t.stopPropagation(),n(i,t)}))}return this.model.get("aggregated_by")||"switch"!==this.model.get("op_mode")?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:l.G_Port,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){return t.portIdxText()},toRaw:function(t){return t}}})},{name:"name",label:l.G_Name,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:"string"},{name:"speed",label:l.G_Status,customClass:"detached-only",editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){return t.statusText()},toRaw:function(t){return t}}})},{name:"tx_bytes",label:l.G_DevicesTX,customClass:"detached-only",editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:s.StringCell.extend({formatter:i.Formatters.Bytes})},{name:"rx_bytes",label:l.G_DevicesRX,customClass:"detached-only",editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:s.StringCell.extend({formatter:i.Formatters.Bytes})},{name:"poe_mode",label:l.G_PropertiesPoE,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:o.proxy(function(t){return t.poeModeText()},this),toRaw:function(t){return t}}})},{name:"portconf_id",label:l.G_PropertiesNetworksVLANs,customClass:"detached-only",editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:o.proxy(function(t){return t.networksVlansText()},this),toRaw:function(t){return t}}})},{name:"_id",label:l.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ActionsCell.extend({actions:{edit:{icon:"ubnt-icon-edit",iconOnly:!0,requiresAdminPrivilege:!0,callback:this.portForm,render:function(t){return!t.get("masked")}},restart:{icon:"ubnt-icon-rotate",iconOnly:!0,callback:this.rowPowerCycle,requiresAdminPrivilege:!0,render:function(t){return t.get("poe_enable")}}}})}],n={pageable:!1,rowClassName:function(t){return"port-"+t.get("port_idx")}};this.grids.ports=this.grid(e,this.model.collections.portTable,this.$(".data-table-ports"),this.noPortsRows,n)}if(this.grids.ports){var a,r;(a=this.$diagram.find("div.highlight"))&&(r=a.data("port"))&&this.highlightPort(r,!0,t)}},statsPortForm:function(t,e){this.$tabs.tabs("option","active",1);var n=t.get("port_idx");this.highlightPort(n),e&&(this.forms.Port&&this.forms.Port.remove(),this.portForm(t))},portForm:function(t,e,i){e&&e.stopPropagation();var s=this,r=(this.parent.options.app.collection("PortConf"),this.$(".properties-container")),l=r.scrollTop();this.forms.Port=new n({app:this.parent.options.app,container:this.$portForm,model:this.model,overrides:i?t:[t]}),this.forms.Port.render(),this.position(),i||(this.$diagram.find("div.port.select").removeClass("select"),this.highlightPort(t.id)),this.listenTo(this.forms.Port,"remove",o.proxy(function(){this.position();var t=this.$portList.find('.checkbox-cell input[type="checkbox"]:checked'),e=a.map(t,function(t){return t.id}),n=this.forms.Port.formResult&&"success"===this.forms.Port.formResult||!1,i=this.$diagram.find("div.port.highlight"),s=this.$portList.find("tr.highlight");e.length&&(i.removeClass("highlight"),s.removeClass("highlight"),a.each(e,function(t){this.$diagram.find("div.port.port-"+t).addClass("select")},this),!s.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(){a.delay(function(){r.scrollTop(l),s.toggleEditButton()},0)})},portSelectionChanged:a.debounce(function(){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 t=this;if(!this.rendered)return!1;if(!this.grids.networks){var e=[{name:"name",label:l.G_Name,editable:!1,cell:"string"},{name:"forward",label:l.G_Config,editable:!1,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var n="",i=t.app.collection("Networks"),s=i.filterByPurpose(["corporate","guest","voip","vlan-only"]),r=a.findWhere(s,{id:e.get("native_networkconf_id")});switch(e.get("forward")){case"customize":n+=l.G_PropertiesCustomized;break;case"native":n+=l.G_PropertiesNative,r&&(n+=" ("+r.get("name")+")")}return n},toRaw:function(t){return t}}})},{name:"_id",label:l.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.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:o.proxy(function(t){(new g).show(l.G_PropertiesNetworkDeleteConfirm,o.proxy(function(){t.destroy({success:o.proxy(function(t,e){"ok"===e.meta.rc?this.showSavedState():this.showErrorState()},this),error:o.proxy(function(){this.showErrorState()},this)})},this))},this)}}})}];this.grids.networks=this.grid(e,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(t){var n=this.parent.options.app.collection("PortConf");this.forms.NetworksVlan=new e({app:this.parent.options.app,container:this.$networksVlanForm,collection:n,model:t||new n.model}),this.listenTo(this.forms.NetworksVlan,"remove",o.proxy(function(){this.forms.NetworksVlan=null},this)),this.forms.NetworksVlan.render(),this.position()},updateServices:function(){var t={mgmt_network_id:this.$servicesForm.find("select[name=mgmt_network]").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(t,{success:o.proxy(function(t,e){"ok"===e.meta.rc?this.showSavedState():this.showErrorState()},this),error:o.proxy(function(){this.showErrorState()},this)}),!1},highlightPort:function(t,e,n){var i=this.$portList.find("tr.port-"+t),s=this.$diagram.find("div.port-"+t),r=a.isUndefined(e)?s.hasClass("highlight"):!e,o=this.$diagram.find("div.port.select").length>0;this.$portList.find("tr.highlight").removeClass("highlight"),this.$diagram.find("div.port.highlight").removeClass("highlight"),r||(o||s.addClass("highlight"),n||this.$tabs.tabs("option","active",1),i.length&&(o||i.addClass("highlight"))),i.length&&this.$(".properties-container").scrollTop(i.position().top)},rowPowerCycle:function(t){var e=this,n=function(){e.model.powerCyclePort({data:{port_idx:t.get("port_idx")},success:function(){e.model.fetch()},error:function(t){e.app.views.app.flash("error","Error",l.apiError(t))}})};(new g).show(l.localize(l.N_ConfirmPowerCyclePort,t.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.$advAdoptForm.off("submit",this.onAdvAdoptFormSubmit),this.forms.Port&&this.forms.Port.remove(),this.forms.NetworksVlan&&this.forms.NetworksVlan.remove(),this.rendered=!1,t.prototype.remove.apply(this,arguments)}})}),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 bind-adopt-port" type="text" value="" 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","ubnt/backgrid","underscore","backbone","libs/backgrid","jquery","msg/Msg","unifi/model/Device","text!includes/phones/phonePropertiesTemplate.html","ubnt/view/dialogs/AlertDialogView","stickit"],function(t,e,n,i,s,a,r,o,l){"use strict";return t.extend(n.extend({},{templateId:l,render:function(e){var n=this.rendered;return t.prototype.render.call(this,e),n||(this.$advAdoptForm=this.$(".advAdoptForm"),this.$advAdoptForm.on("submit",this.onAdvAdoptFormSubmit),"resolved"===this._rendered.state()&&"resolved"==this._dependencies.state()?this.populate():"pending"===this._rendered.state()&&this._rendered.resolve(),this.stickit(this.model,this.bindings())),this},onAdvAdoptFormSubmit:function(t){t.preventDefault();var e=this,i=this.model,s=a(t.target).find("button");this.$advAdoptForm.find(".error").removeClass("error"),s.attr("disabled","disabled");var r=i.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(t){"ok"===t.meta.rc?i.fetch({success:function(t,n){"ok"===n.meta.rc&&e.parent.property(t)},complete:function(){s.removeAttr("disabled")}}):(e.showErrorState(),s.removeAttr("disabled"))},error:function(){e.showErrorState(),s.removeAttr("disabled")}});!r&&this.model.validationError&&n.each(this.model.validationError,function(t,e){switch(e){case"username":case"password":this.$advAdoptForm.find('input[name="'+e+'"]').addClass("error"),s.removeAttr("disabled")}},this)},populate:function(){t.prototype.populate.call(this),this._dependencies&&"resolved"==this._dependencies.state()&&this.position()},remove:function(){this.rendered=!1,this.unstickit(this.model),this.$advAdoptForm.off("submit",this.onAdvAdoptFormSubmit),t.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(t,e,n,i,s,a,r){"use strict";return t.extend({events:{"keyup input[name=device-address]":"validateInputs","keyup input[name=device-code]":"validateInputs","click .button-submit":"onSubmit","submit #addSiteForm":"onSubmit"},dialogOptions:{title:i.G_DevicesAddNewDevice,width:"auto",height:"auto",modal:!0,resizable:!1,draggable:!1,dialogClass:"dialog-add-device dialog-simple"},initialize:function(t){a.bindAll(this),this.app=t.app,this.device=new n},render:function(){this.$el.html(a.template(e,{msg:i})),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(){t.prototype.open.call(this),r.Window.on("resize.addDeviceDialog",a.debounce(this.onResizeWindow,250)),this.$submitButton.prop("disabled",!0),this.onResizeWindow()},close:function(){t.prototype.close.call(this),r.Window.off("resize.addDeviceDialog")},onResizeWindow:function(){this.center()},validateInputs:function(){var t=0,e=[this.$deviceAddressInput];a.each(e,function(e){e.val()||t++},this),this.$submitButton.prop("disabled",!!t)},onSubmit:function(t){t.preventDefault();var e=this,n=this.$deviceAddressInput.val(),s=this.$deviceCodeInput.val(),a=n+s,r={macidqr:a,success:function(t){"ok"===t.meta.rc&&(e.$errors.hide(),e.$success.show(),e.$success.text(i.G_DevicesAddSuccess),e.app.refresh(),setTimeout(function(){e.close()},1e3))},error:function(t){"Bad Request"===t.statusText&&(e.$errors.show(),e.$errors.text(i.E_InvalidDevice))}};return this.device.sync("add-device",this,r)},remove:function(){r.Window.off("resize.addDeviceDialog"),t.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(t,e,n,i,s,a,r,o,l,c,d,h,u,p,m,f,g,v){"use strict";return t.extend({id:"devicesIndex",_templateId:g,_collectionType:{name:"Devices",Class:u},_pageable:!0,_filterMinimum:.1,initialize:function(e){this.properties={},this.locateTimer=null,this.locateLit=!1,t.prototype.initialize.call(this,e),this.listenTo(this.collection,"change:upgradable change:rollupgrade add remove sync",o.debounce(this.changeUpgradeButtonStatus,250)),this.listenTo(this.collection,"remove",o.debounce(this.removeProperty,250)),this.listenTo(this.collection,"change:locating",o.debounce(this.toggleLocating,250)),this.listenTo(this.collection,"sync",o.debounce(this.enableLocateTimerIfNeeded,250))},render:function(){var e=this.rendered;t.prototype.render.call(this,!0),e||(this.$btnAddDevice=h("#addDevice"),this.$btnAddDevice.on("click",this.addDevice),this.$btnUpgradeAPs=h("#upgradeAPs"),this.$btnUpgradeAPsCopy=this.$btnUpgradeAPs.find(".copy"),this.$btnUpgradeAPs.on("click",this.upgradeAPs),this.changeUpgradeAPsStatus(),this.$btnUpgradePhones=h("#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",h.proxy(function(){this.grids.content&&this.grids.content.reset()},this)),this.extensions=this.app.collection("Extensions",{fetch:{reload:!1}},m)},columns:function(){var t=this;return[{name:"state",customClass:"column-name",editable:!1,sortable:!1,headerCell:c.Headers.emptyHeader,cell:c.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(t){return h("<div />").addClass("ap-model-"+t.get("model")).addClass(t.isConnected()?"ap-connected":"ap-disconnected").append(h('<div class="device-icons access-point half"></div>'))},toRaw:function(t){return t}}})},{name:"name",label:d.G_DevicesNameMACAddress,customClass:"column-name",editable:!1,sortValue:"name",sortFormatter:"toLowerCase",headerCell:c.Headers.customSortHeader,cell:c.Cells.ModelCell.extend({callback:"name"}),callback:this.property,title:"mac"},{name:"mac",label:d.G_NameMACAddress,customClass:"column-mac",editable:!1,cell:"string"},{name:"ip",label:d.G_IPAddress,customClass:"column-ip",editable:!1,sortValue:"ip2long",headerCell:c.Headers.customSortHeader,cell:c.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){if(t.get("type")===t.typeMap.gateway){var e=o.findWhere(t.get("port_table"),{name:"lan"});if(e&&e.ip)return e.ip}return t.get("ip")},toRaw:function(t){return t}}})},{name:"state",label:d.G_Status,customClass:"column-state",editable:!1,sortValue:"status",headerCell:c.Headers.customSortHeader,cell:c.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(t){return h("<span />").addClass(t.statusType()).text(t.status())},toRaw:function(t){return t}}})},{name:"model",label:d.G_DevicesModel,customClass:"column-model",editable:!1,sortValue:"apModel",headerCell:c.Headers.customSortHeader,cell:c.Cells.ModelCell.extend({callback:"apModel"})},{name:"version",label:d.G_Version,customClass:"column-version",editable:!1,cell:"string",title:function(t){return t.get("type")===t.typeMap.phone?t.get("version")+" / "+t.get("platform_version"):""}},{name:"num_sta",label:d.G_DevicesClients,customClass:"column-num_sta",editable:!1,sortValue:"sort_Clients",headerCell:c.Headers.customSortHeader,cell:"integer"},{name:"ng-num_sta",label:d.G_Devices2GClients,customClass:"column-ng-num_sta",editable:!1,sortValue:"sort_2GClients",headerCell:c.Headers.customSortHeader,cell:"integer"},{name:"na-num_sta",label:d.G_Devices5GClients,customClass:"column-na-num_sta",editable:!1,sortValue:"sort_5GClients",headerCell:c.Headers.customSortHeader,cell:"integer"},{name:"tx_bytes",label:d.G_DevicesDown,customClass:"column-tx_bytes",editable:!1,cell:l.StringCell.extend({formatter:c.Formatters.Bytes})},{name:"rx_bytes",label:d.G_DevicesUp,customClass:"column-rx_bytes",editable:!1,cell:l.StringCell.extend({formatter:c.Formatters.Bytes})},{name:"tx_bytes-d",label:d.G_DevicesTX,customClass:"column-tx_bytes-d",editable:!1,sortValue:"sort_txBytesD",headerCell:c.Headers.customSortHeader,cell:l.StringCell.extend({formatter:c.Formatters.Bytes})},{name:"rx_bytes-d",label:d.G_DevicesRX,customClass:"column-rx_bytes-d",editable:!1,sortValue:"sort_rxBytesD",headerCell:c.Headers.customSortHeader,cell:l.StringCell.extend({formatter:c.Formatters.Bytes})},{name:"tx_bytes_2g",label:d.G_DevicesTX2G,customClass:"column-tx_bytes_2g",editable:!1,sortValue:"sort_txBytes2g",headerCell:c.Headers.customSortHeader,cell:c.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:h.proxy(function(t){return this.radioBar("ng",t)},this)}})},{name:"tx_bytes_5g",label:d.G_DevicesTX5G,customClass:"column-tx_bytes_5g",editable:!1,sortValue:"sort_txBytes5g",headerCell:c.Headers.customSortHeader,cell:c.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:h.proxy(function(t){return this.radioBar("na",t)},this)}})},{name:"ng-channel",label:d.G_DevicesChannel,customClass:"column-ng-channel",editable:!1,sortValue:"sortApChannel",headerCell:c.Headers.customSortHeader,cell:c.Cells.ModelCell.extend({callback:"apChannel"})},{name:"wlangroup_id_na",label:d.G_DevicesWLAN2G,customClass:"column-wlangroup_id_na",editable:!1,sortValue:h.proxy(function(e){return e.wlan2G(t.app.collection("WlanGroups"))},this),headerCell:c.Headers.customSortHeader,cell:c.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){return e.wlan2G(t.app.collection("WlanGroups"))},toRaw:function(t){return t}}})},{name:"wlangroup_id_ng",label:d.G_DevicesWLAN5G,customClass:"column-wlangroup_id_ng",editable:!1,sortValue:h.proxy(function(e){return e.wlan5G(t.app.collection("WlanGroups"))},this),headerCell:c.Headers.customSortHeader,cell:c.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){return e.wlan5G(t.app.collection("WlanGroups"))},toRaw:function(t){return t}}})},{name:"radio_ng",label:d.G_DevicesRadio2G,customClass:"column-radio_ng",editable:!1,sortValue:"sortRadio2G",headerCell:c.Headers.customSortHeader,cell:c.Cells.ModelCell.extend({callback:"radio2G"})},{name:"radio_na",label:d.G_DevicesRadio5G,customClass:"column-radio_na",editable:!1,sortValue:"sortRadio5G",headerCell:c.Headers.customSortHeader,cell:c.Cells.ModelCell.extend({callback:"radio5G"})},{name:"extension",label:d.G_DevicesExtension,customClass:"column-extension",editable:!1,cell:c.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){return t.get("extension")},toRaw:function(t){return t}}}),callback:function(e){var n=t.app.collection("Extensions").filterByExtension(e.get("extension"));n&&t.options.app.views.app.openSettings("extensions",n.id)}},{name:"uptime",label:d.G_Uptime,customClass:"column-uptime",editable:!1,cell:c.Cells.ModelCell.extend({callback:"uptime"})},{name:"_id",label:d.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:c.Headers.noSortHeader,cell:c.Cells.ActionsCell.extend({actions:{locate:{icon:"ubnt-icon-location",callback:this.rowLocate,requiresAdminPrivilege:!0,classCallback:function(t){return t.get("locating")?"locating":""},render:function(t){return 1==t.get("state")}},restart:{icon:"ubnt-icon-rotate",callback:this.rowRestart,requiresAdminPrivilege:!0,render:function(t){return 1==t.get("state")}},adopt:{icon:"ubnt-icon-plus",callback:this.rowAdopt,requiresAdminPrivilege:!0,render:function(t){return 2!=t.get("state")&&12!=t.get("state")||!t.get("default")?!1:"scan"==t.get("discovered_via")&&t.get("vwireEnabled")===!1?!1:!0}},upgrade:{icon:"ubnt-icon-download",callback:this.rowUpgrade,requiresAdminPrivilege:!0,render:function(t){if(t.get("upgradable")===!0){if(1==t.get("state"))return!0;if(2==t.get("state"))return t.get("uplink")&&"wireless"===t.get("uplink").type?!1:!0}return!1}}}})}]},grid:function(){this._gridRowClassName=this.gridRowClassName,t.prototype.grid.call(this);var e=this.grids.content,n=this.$el.find(".buttonset.type-filters"),i=n.find("input[name=type-filter]"),s=this.$el.find(".buttonset.ap-filters"),a=s.find("input[name=ap-filter]"),r=[],l=[],c=this.collection.typeMap,d=this.$btnUpgradeAPs,u=this.$btnUpgradePhones;return i.filter('[value="'+(h.cookie("filterDeviceType")||"all")+'"]').click(),a.filter('[value="'+(h.cookie("filterDeviceAp")||"overview")+'"]').click(),o.each(i,function(t){r.push(t.value)}),o.each(a,function(t){l.push(t.value)}),i.on("change",function(){var t=h(this).val(),n=t?t.split("-"):null,i=[];n&&o.each(n,function(t){c[t]&&i.push(c[t])}),i&&i.length?e.setFilter("type",i.length>1?i:i[0],1):e.removeFilter("type"),e.$el.removeClass(r.join(" ")).addClass(t||r[0]),"ap"==t?(s.show(),d.show(),u.hide()):"phone"==t?(s.hide(),d.hide(),u.show()):(s.hide(),d.hide(),u.hide()),a.filter(":checked").trigger("change"),h.cookie("filterDeviceType",t)}).filter(":checked").trigger("change"),a.on("change",function(){var t=h(this),n=t.val();e.$el.removeClass(l.join(" ")).addClass(t.is(":visible")?n||l[0]:""),h.cookie("filterDeviceAp",n)}).filter(":checked").trigger("change"),this},gridRowClassName:function(t){return"mac-"+t.getMacNoColons()},property:function(t,a){if(!t)throw"Missing model";var r,o=t.get("mac");if(this.properties[o])this.properties[o].render();else{switch(t.get("type")){case t.typeMap.ap:r=e;break;case t.typeMap.gateway:r=n;break;case t.typeMap["switch"]:r=i;break;case t.typeMap.phone:r=s}r&&(this.properties[o]=new r({properties:this.app.views.app.views.properties,parent:this,model:t,property_id:o.split(":").join(""),show:!0,options:a}))}return this.properties[o]},removeProperty:function(t){var e=t.get("mac");this.properties[e]&&delete this.properties[e]},rowLocate:function(t){t.locate(),1===t.get("state")&&t.get("map_id")&&(this.app.routers.map.forward(),this.app.routers.map.views.index.locateDevice(t))},toggleLocating:function(t){1===t.get("state")&&t.get("locating")?this.getLocateButtons(t).addClass("locating"):this.getLocateButtons(t).removeClass("locating"),this.enableLocateTimerIfNeeded()},enableLocateTimerIfNeeded:function(){var t=this,e=this.collection.findWhere({locating:!0});e?this.locateTimer||(t.locateLit=!0,this.locateTimer=window.setInterval(function(){h(".button-locate.locating").toggleClass("on",t.locateLit),t.locateLit=!t.locateLit},500)):(this.locateTimer&&(clearTimeout(this.locateTimer),delete this.locateTimer),this.locateTimer=null)},getLocateButtons:function(t){return h("."+this.gridRowClassName(t)).find(".button-locate")},rowRestart:function(t){var e=this,n=function(){t.restart({success:function(n){"ok"===n.meta.rc?(t.fetch(),t.set({restarting:!0})):e.app.views.app.flash("error")},error:function(t){e.app.views.app.flash("error","Error",d.apiError(t))}})};t.get("type")===t.typeMap.gateway||t.get("type")===t.typeMap["switch"]?(new r).show(d.N_ConfirmRestartDevice,n):n()},rowAdopt:function(t){var e=this;t.adopt({success:function(n){"ok"===n.meta.rc?t.fetch({success:function(){},error:function(){e.app.views.app.flash("error")}}):e.app.views.app.flash("error")},error:function(t){e.app.views.app.flash("error","Error",d.apiError(t))}})},rowUpgrade:function(t){var e=this,n=function(){t.upgrade({success:function(n){"ok"===n.meta.rc?t.fetch({success:function(){"ok"===n.meta.rc&&e.app.views.app.flash("success")}}):e.app.views.app.flash("error")},error:function(t){e.app.views.app.flash("error","Error",d.apiError(t))}})};t.get("type")===t.typeMap.gateway||t.get("type")===t.typeMap["switch"]?(new r).show(d.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.$btnUpgradeAPsCopy.text(this.collection.isUpgradingDevices()?d.G_DevicesRollingUpgradeInProgress:d.G_DevicesStartRollingUpgrade)},upgradeAPs:function(){var t=this;this.collection.upgradeAPs({success:function(){(new v).open(t.collection.isUpgradingDevices()?d.G_DevicesRollingUpgradeCancelled:d.G_APRollingUpgrade),t.app.refresh(),t.changeUpgradeAPsStatus()}})},changeUpgradePhonesStatus:function(){this.collection.hasUpgradablePhone()?this.$btnUpgradePhones.removeAttr("disabled"):this.$btnUpgradePhones.attr("disabled","disabled"),this.changeUpgradeAPsText()},upgradePhones:function(){var t=this;this.collection.upgradePhones({success:function(){t.app.refresh(),t.changeUpgradePhonesStatus()}})},addDevice:function(){var t=new a({app:this.app});t.open()},radioBar:function(t,e){if(!e.get("adopted")||1!=e.get("state")||!e.get("radio_"+t))return"";var n,i,s=(parseInt(e.get(t+"_ast_txto"),10)||0)+(parseInt(e.get(t+"_ast_cst"),10)||0),a=parseInt(e.get(t+"_tx_retries"),10)||0,r=(parseInt(e.get(t+"_ast_be_xmit"),10)||0)+(parseInt(e.get(t+"_tx_packets"),10)||0),l=[s,a,r],c=["red","yellow","green"],d=100;if(!(n=o.reduce(l,function(t,e){return t+e},0)))return"";var u=h('<ul class="ratio-bar"></ul>');return o.each(l,function(t,e){i=Math.ceil(100*t/n),i>d&&(i=d),h("<li></li>",{"class":c[e],width:(e+1==l.length?d:i)+"%"}).appendTo(u),d-=i}),u.attr("title",l.join(" / ")),u},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 e=this.$el.find(".buttonset.type-filters"),n=e.find("input[name=type-filter]"),i=this.$el.find(".buttonset.ap-filters"),s=i.find("input[name=ap-filter]");n.off("change"),s.off("change"),this.rendered=!1,t.prototype.remove.apply(this,arguments)}})}),define("unifi/router/DevicesRouter",["unifi/router/Router","unifi/view/devices/IndexView","unifi/view/devices/PropertyView"],function(t,e,n){"use strict";return t.extend({_fullyQualifiedName:"UNIFI.Routers.Devices",_associatedViews:{Index:e,Property:n},routes:{devices:"index"}})}),define("unifi/model/ClientHistory",["unifi/model/Model"],function(t){"use strict";return t.extend()}),define("unifi/collection/ClientHistory",["unifi/collection/Collection","backbone","underscore","unifi/model/ClientHistory"],function(t,e,n,i){"use strict";return t.extend({model:i,bySite:!0,initialize:function(e){this.mac=e.mac,t.prototype.initialize.call(this,e)},url:function(){return"/api/s/"+SITE.name+"/stat/session"},sync:function(t,n,i){switch(i=i||{},t){case"read":i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify({mac:this.mac,_limit:5,_sort:"-assoc_time"})}return e.sync.call(this,t,n,i)},parse:function(t){var e=t.data;return n.where(e,{mac:this.mac})}})}),define("unifi/model/User",["unifi/model/Model","jquery","underscore","backbone","msg/Msg","ubnt/ubnt.ip"],function(t,e,n,i,s){"use strict";return t.extend({validate:function(t,i){var a={},r=i?i.partial:null;return r&&"fixed_ip"!=r||t.use_fixedip&&(this.validator.ip(t.fixed_ip)?i.extra&&i.extra.subnet&&!e.ipsubnet_hasip(i.extra.subnet,t.fixed_ip)&&(a.fixed_ip=s.localize(s.E_IncorrectIPSubnet,t.fixed_ip,i.extra.subnet)):a.fixed_ip=s.localize(s.E_IncorrectIPAddress,s.G_ClientsFixedIP)),n.size(a)?a:void 0},sync:function(t,e,n){switch(n=n||{},t){case"read":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/rest/user/"+e.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/"+e.id,n.type="PUT",n.data=JSON.stringify(e.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/"+e.id,n.type="DELETE"}return i.sync.call(this,t,e,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\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-undo 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-undo 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-plus 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(t,e,n,i,s,a,r,o,l,c,d){"use strict";return t.extend({templateId:d,initialize:function(e){t.prototype.initialize.call(this,e),a.when(this._rendered=a.Deferred(),this._dependencies=a.Deferred()).then(this.populate,this.failed),this.user=new s,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(t){if(t){var e=this.networks.get(t);this.$bindConnectedNetwork.text(e.get("name")),this.$selectNetwork.val(e.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 t={UserGroups:n,Networks:i},e=[],s={},o=this;r.each(t,function(t,n){e.push(s[n]=a.Deferred())},this),e.push(s.user=a.Deferred()),a.when.apply(a,e).then(function(){o._dependencies.resolve()},function(){o._dependencies.reject()}),r.each(t,function(t,e){this.app.collection(e,{fetch:{reload:!1,deferred:s[e]}},t)},this),this.user.fetch({complete:function(){s.user.resolve()}})},render:function(i){var s=this.rendered;return t.prototype.render.call(this,i),s||(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",a.proxy(function(t){var e=a(t.target);e.parents(".row").siblings().toggle(e.is(":checked")),e.is(":checked")&&this.renderSelects()},this)).trigger("change"),this.collections.history=new e({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),"resolved"===this._rendered.state()&&"resolved"==this._dependencies.state()?this.populate():"pending"===this._rendered.state()&&this._rendered.resolve(),this.stickit(this.model,this.bindings())),this},populate:function(){if(this._dependencies&&"resolved"==this._dependencies.state()){this.$el.find(".property-content .loading").remove();var t=this.model.isConnected(),e=this.model.get("is_wired"),n=this.model.get("is_guest"),i=this.model.get("blocked"),s=this.model.authorizable(),a=this.model.get("authorized");this.$el.removeClass("sta-connected sta-disconnected sta-isguest sta-authorizable sta-authorized sta-blocked sta-wired sta-wireless"),this.$el.addClass("client-properties"),t?(this.$el.addClass("sta-connected"),n&&this.$el.addClass("sta-isguest"),s&&this.$el.addClass("sta-authorizable"),a&&this.$el.addClass("sta-authorized")):this.$el.addClass("sta-disconnected"),this.$el.addClass(e?"sta-wired":"sta-wireless"),i&&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 t,e="";this.model.get("is_wired")?(this.model.get("sw_mac")?e=(t=this.devices.getDeviceFromMac(this.model.get("sw_mac")))?t.name()+(this.model.get("sw_port")?" #"+this.model.get("sw_port"):""):this.model.get("sw_mac"):this.model.get("gw_mac")&&(e=(t=this.devices.getDeviceFromMac(this.model.get("gw_mac")))?t.name():this.model.get("gw_mac")),this.$bindConnectedPort.text(e)):(e=(t=this.model.get("ap_mac")?this.devices.getDeviceFromMac(this.model.get("ap_mac")):null)?t.name():this.model.get("ap_mac"),this.$bindConnectedAP.text(e))},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:a.proxy(function(){this.remove()},this)})},unauthorize:function(){var t=this;return this.model.unauthorize({success:function(){t.$el.removeClass("sta-authorized"),t.model.set({authorized:!1})}}),!1},authorize:function(){var t=this;return this.model.authorize({success:function(){t.$el.addClass("sta-authorized"),t.model.set({authorized:!0})}}),!1},updateConfig:function(t){t&&t.preventDefault();var e,n=this,i=this.$configForm.serializeObject(),s=this.$configForm.find('input[name="name"]');return this.$configForm.find(".error").removeClass("error"),this.$configForm.find(".row-error").remove(),this.model.get("name")||""!==i.name||delete i.name,i.noted=i.note?!0:!1,e=this.model.save(i,{data:i,success:function(t,e){if("ok"===e.meta.rc){var i=n.app.collection("Clients");if(r.each(i.where({mac:t.get("mac")}),function(e){e.set(t.attributes)}),n.app.data.hasOwnProperty("KnownClients")){var s=n.app.collection("KnownClients");r.each(s.where({mac:t.get("mac")}),function(e){e.set(t.attributes)})}n.showSavedState()}else n.showErrorState()},error:function(){n.showErrorState()}}),!e&&this.model.validationError&&this.model.validationError.name&&(s.addClass("error"),this.$configForm.find(".row").after(a('<div class="row row-error"></div>').text(this.model.validationError.name))),!1},toggleFixedIP:function(){var t=this.devices.where({type:"ugw",adopted:!0}),e=this.networks.where({dhcpd_enabled:!0}),n=t.length&&e.length;n?this.$useFixedIp.removeAttr("disabled"):this.$useFixedIp.attr("disabled","disabled")},updateConfigIp:function(t){t&&t.preventDefault(),this.$configIpForm.find(".error").removeClass("error"),this.$configIpForm.find(".error-msg").remove();var e,n,i=this,s=this.$configIpForm.find("input[name=use_fixedip]").is(":checked"),l={use_fixedip:s};s&&(l.network_id=this.$configIpForm.find("select[name=network_id]").val(),l.fixed_ip=this.$configIpForm.find("input[name=fixed_ip]").val(),l.network_id&&(e=this.networks.get(l.network_id))&&(n=e.get("ip_subnet")));var c=this.user.save(l,{extra:{subnet:n},success:function(t,e){"ok"===e.meta.rc?i.showSavedState():i.showErrorState()},error:function(t,e){i.app.views.app.flash("error","Error",o.apiError(e,!0))}});return!c&&this.user.validationError&&r.each(this.user.validationError,a.proxy(function(t,e){this.$configIpForm.find("[name="+e+"]").addClass("error").parent().append('<div class="error-msg">'+t+"</div>")},this)),!1},displayConnectedAP:function(){var t=this.app.routers.devices.views.index,e=t.collection.getDeviceFromMac(this.model.get("ap_mac"));return t.property(e),!1},displayConnectedPort:function(){var t=this.app.routers.devices.views.index,e=t.collection.getDeviceFromMac(this.model.get(this.model.get("sw_mac")?"sw_mac":"gw_mac"));return t.property(e,{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 t=[{name:"assoc_time",label:o.G_DateTime,editable:!1,cell:l.StringCell.extend({formatter:c.Formatters.Moment,className:"time-cell"})},{name:"duration",label:o.G_Duration,editable:!1,cell:l.StringCell.extend({formatter:c.Formatters.Duration,className:"duration-cell"})},{name:"tx_bytes",label:o.G_Down,editable:!1,cell:l.StringCell.extend({formatter:c.Formatters.Bytes,className:"down-cell"})},{name:"rx_bytes",label:o.G_Up,editable:!1,cell:l.StringCell.extend({formatter:c.Formatters.Bytes,className:"up-cell"})}];this.grids.history=this.grid(t,this.collections.history,this.$(".data-table-clients-history"),this.noClientHistoryRows)}},setupUserGroups:function(){var t=this.app.collection("UserGroups");if(this.$bindUserGroups.empty(),this.$bindUserGroups.append(a('<option value=""></option>').text(o.G_PropertiesAutomatic)),t.each(function(t){t.get("site_id")===SITE.id&&this.$bindUserGroups.append(a('<option value="'+t.get("_id")+'"></option>').text(t.get("name")))},this),this.model.get("usergroup_id")){this.$bindUserGroups.val(this.model.get("usergroup_id"));try{this.$bindUserGroups.selectmenu("refresh")}catch(e){}}},setupNetworks:function(){if(this.$selectNetwork.empty(),r.each(this.networks.filterByPurpose(["corporate","guest","voip"]),a.proxy(function(t){this.$selectNetwork.append(a('<option value="'+t.get("_id")+'"></option>').text(t.get("name")))},this)),this.user.get("network_id")){this.$selectNetwork.val(this.user.get("network_id"));try{this.$selectNetwork.selectmenu("refresh")}catch(t){}}},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;var e=this.app.routers.clients.views.index.properties;for(var n in e)n===this.model.get("mac")&&delete e[n];t.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="<%- msg.G_AP %>: "></select>\n            </div>\n            <div class="network-filter">\n                <select name="network-filter" data-label="<%- msg.G_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/model/Client","unifi/collection/insights/KnownClients","unifi/collection/Networks","text!includes/clients/clientsIndexTemplate.html","libs/jquery.cookie"],function(t,e,n,i,s,a,r,o,l,c,d,h,u){"use strict";return t.extend({id:"clientsIndex",_templateId:u,_collectionType:{name:"Clients",Class:l},_pageable:!0,initialize:function(e){if(this.properties={},t.prototype.initialize.call(this,e),!e.skipBindings){var n=this;this.listenTo(this.options.app.collection("Devices"),"change:name",function(t){var e,i,s=t.get("type");if("usw"===s?e=n.collection.where({is_wired:!0,sw_mac:t.get("mac")}):"ugw"===s?e=n.collection.where({is_wired:!0,gw_mac:t.get("mac")}):"uap"===s&&(e=n.collection.where({is_wired:!1,ap_mac:t.get("mac")})),e&&e.length)for(i=0;i<e.length;i++)e[i].trigger("change",e[i])}),this.listenTo(this.collection,"change",a.debounce(function(){a.each(n.options.app.routers.clients.views.index.properties,function(t){var e=n.app.collection("Clients"),i=n.app.data.KnownClients?n.app.collection("KnownClients"):null,s=e.findWhere({mac:t.model.get("mac")});s&&t.model.set(s.attributes);var a=i?i.findWhere({mac:t.model.get("mac")}):null;a&&t.model.set(a.attributes),s||a||t.model.fetch()})},250))}},render:function(){var e=this.rendered;t.prototype.render.call(this,!0),e||(this.$apFilter=this.$el.find("select[name=ap-filter]"),this.$networkFilter=this.$el.find("select[name=network-filter]"),this._rendered.resolve())},columns:function(){var t=this;return[{name:"hostname",label:o.G_ClientsNameMACAddress,customClass:"column-name",editable:!1,sortValue:"name",sortFormatter:"toLowerCase",headerCell:s.Headers.customSortHeader,cell:s.Cells.ModelCell.extend({callback:"name"}),callback:this.property,title:"mac"},{name:"ip",label:o.G_IPAddress,customClass:"column-ip",editable:!1,sortValue:"ip2long",headerCell:s.Headers.customSortHeader,cell:"string"},{name:"status",label:o.G_Status,customClass:"column-status",editable:!1,sortValue:"sortStatus",headerCell:s.Headers.customSortHeader,cell:s.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(t){return t.authorizable()?r(t.get("authorized")?'<span class="ok">'+o.G_ClientsAuthorized+"</span>":'<span class="pending">'+o.G_ClientsPending+"</span>"):void 0},toRaw:function(t){return t}}})},{name:"network",label:o.G_ClientsConnection,customClass:"column-connection",editable:!1,sortValue:"connection",headerCell:s.Headers.customSortHeader,cell:s.Cells.ModelCell.extend({callback:"connection"})},{name:"network",label:o.G_Network,customClass:"column-network",editable:!1,cell:"string"},{name:"essid",label:o.G_ClientsWLAN,customClass:"column-wlan",editable:!1,cell:"string"},{name:"sw_port",label:o.G_Port,customClass:"column-port",editable:!1,sortValue:"wired_connection",headerCell:s.Headers.customSortHeader,cell:s.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var n,i=t.app.collection("Devices");return e.get("sw_mac")?(n=i.getDeviceFromMac(e.get("sw_mac")))?n.name()+e.switch_port_suffix(!1):e.get("sw_mac"):e.get("gw_mac")?(n=i.getDeviceFromMac(e.get("gw_mac")))?n.name():e.get("gw_mac"):void 0},toRaw:function(t){return t}}}),callback:function(e){var n=t.app.routers.devices.views.index,i=n.collection.getDeviceFromMac(e.get(e.get("sw_mac")?"sw_mac":"gw_mac"));n.property(i,{port:e.get("sw_mac")?e.get("sw_port"):"lan"})},title:function(t){return t.get("sw_mac")||t.get("gw_mac")}},{name:"ap_mac",label:o.G_ClientsAP,customClass:"column-ap",editable:!1,cell:s.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var n=t.app.collection("Devices"),i=e.get("ap_mac")?n.getDeviceFromMac(e.get("ap_mac")):null;return i?i.name():e.get("ap_mac")},toRaw:function(t){return t}}}),callback:function(e){var n=t.app.routers.devices.views.index,i=n.collection.getDeviceFromMac(e.get("ap_mac"));n.property(i)},title:"ap_mac"},{name:"sw_mac",label:o.G_ClientsAPPort,customClass:"column-apport",editable:!1,sortable:!1,headerCell:s.Headers.noSortHeader,cell:s.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var n,i=t.app.collection("Devices");return e.get("is_wired")?e.get("sw_mac")?(n=i.getDeviceFromMac(e.get("sw_mac")))?n.name()+e.switch_port_suffix(!1):e.get("sw_mac"):e.get("gw_mac")?(n=i.getDeviceFromMac(e.get("gw_mac")))?n.name():e.get("gw_mac"):void 0:(n=e.get("ap_mac")?i.getDeviceFromMac(e.get("ap_mac")):null,n?n.name():e.get("ap_mac"))},toRaw:function(t){return t}}}),callback:function(e){var n,i=t.app.routers.devices.views.index;e.get("is_wired")?(n=i.collection.getDeviceFromMac(e.get(e.get("sw_mac")?"sw_mac":"gw_mac")),i.property(n,{port:e.get("sw_mac")?e.get("sw_port"):"lan"})):(n=i.collection.getDeviceFromMac(e.get("ap_mac")),i.property(n))},title:"ap_mac"},{name:"rssi",label:o.G_Signal,customClass:"column-signal",editable:!1,cell:s.Cells.ComplexHtmlCell.extend({className:"rssiWithRadio",formatter:{fromRaw:function(t){var e=t.rssi(),n="sprite-";return n+=t.radioType(),n+="-"+(t.is5g()?"5g":"2g"),n+=t.get("powersave_enabled")?"-powersave":"",'<span class="signal-value">'+e+'</span><span class="signal-icon '+n+'"></span>'},toRaw:function(t){return t}}})},{name:"tx_bytes",label:o.G_Down,customClass:"column-down",editable:!1,cell:i.StringCell.extend({formatter:s.Formatters.Bytes})},{name:"rx_bytes",label:o.G_Up,customClass:"column-up",editable:!1,cell:i.StringCell.extend({formatter:s.Formatters.Bytes})},{name:"bytes-r",label:o.G_Activity,customClass:"column-activity",editable:!1,sortValue:"activitySort",headerCell:s.Headers.customSortHeader,cell:s.Cells.HtmlCell.extend({formatter:a.extend({},s.Formatters.Grid,{className:"green-cells",levels:[2048e3,512e3,64e3,8e3,500]})})},{name:"uptime",label:o.G_Uptime,customClass:"column-uptime",editable:!1,cell:i.StringCell.extend({formatter:s.Formatters.Seconds})},{name:"_id",label:o.G_Actions,customClass:"column-actions is-admin",editable:!1,sortable:!1,headerCell:s.Headers.noSortHeader,cell:s.Cells.ActionsCell.extend({actions:{block:{icon:"ubnt-icon-close",callback:this.rowBlock,requiresAdminPrivilege:!0,render:function(t){return!t.get("blocked")}},unblock:{icon:"ubnt-icon-undo",callback:this.rowUnblock,requiresAdminPrivilege:!0,render:function(t){return t.get("blocked")}},reconnect:{icon:"ubnt-icon-reconnect",callback:this.rowReconnect,requiresAdminPrivilege:!0,buttonClasses:"narrow",render:function(t){return!t.get("is_wired")}},authorize:{icon:"ubnt-icon-plus",callback:this.rowAuthorize,requiresAdminPrivilege:!0,buttonClasses:"narrow",render:function(t){return t.authorizable()&&!t.get("authorized")}},unauthorize:{icon:"ubnt-icon-undo",callback:this.rowUnauthorize,requiresAdminPrivilege:!0,buttonClasses:"narrow",render:function(t){return t.authorizable()&&t.get("authorized")}}}})}]},load:function(e,n){return n=n||{},n.reset=!0,t.prototype.load.call(this,e,n)},grid:function(){this._gridRowClassName=this.gridRowClassName,t.prototype.grid.call(this);var e=this.grids.content,n=this.$el.find(".network-filters .ap-filter"),i=this.$el.find(".network-filters .network-filter"),s=this.$el.find(".buttonset.conn-filters"),o=s.find("input[name=conn-filter]"),l=this.$el.find(".buttonset.wireless-filters"),c=l.find("input[name=wireless-filter]"),d=this.$el.find(".buttonset.access-filters"),u=d.find("input[name=access-filter]"),p=[],m=[],f=[],g=this;return this.devices=this.app.collection("Devices"),this.listenTo(this.devices,"add remove change",a.debounce(this.setupApFilter,250)),this.setupApFilter(),this.networks=this.app.collection("Networks",{fetch:{reload:!1}},h),this.clients=this.app.collection("Clients"),this.listenTo(this.networks,"add remove change",this.setupNetworkFilter),this.listenTo(this.clients,"add remove change",this.setupNetworkFilter),this.setupNetworkFilter(),this.$el.find('.buttonset input[name=conn-filter][value="'+(r.cookie("filterClientConn")||"conn-all")+'"]').click(),this.$el.find('.buttonset input[name=wireless-filter][value="'+(r.cookie("filterClientWireless")||"wireless-all")+'"]').click(),this.$el.find('.buttonset input[name=access-filter][value="'+(r.cookie("filterClientAccess")||"access-all")+'"]').click(),a.each(o,function(t){p.push(t.value)}),a.each(c,function(t){m.push(t.value)}),a.each(u,function(t){f.push(t.value)}),o.on("change",function(){var t=r(this).val();"wired"==t?(e.setFilter("is_wired",!0,1),n.hide(),i.show()):"wireless"==t?(e.setFilter("is_wired",!0,-1),n.show(),i.hide()):(e.removeFilter("is_wired"),n.hide(),i.hide()),"wireless"==t?l.show():l.hide(),e.$el.removeClass(p.join(" ")).addClass(t||p[0]),c.filter(":checked").trigger("change"),n.trigger("change"),i.trigger("change"),r.cookie("filterClientConn",t)}).filter(":checked").trigger("change"),c.on("change",function(){var t=r(this),n=t.val(),i=t.is(":visible");!i||"na"!=n&&"ng"!=n?e.removeFilter("radio"):e.setFilter("radio",n,1),e.$el.removeClass(m.join(" ")).addClass(i?n||m[0]:""),g.setupApFilter(),r.cookie("filterClientWireless",n)}).filter(":checked").trigger("change"),u.on("change",function(){var t=r(this).val();"users"==t?e.setFilter("is_guest",!1,1):"guests"==t?e.setFilter("is_guest",!0,1):e.removeFilter("is_guest");var n=g.$el.find("input:radio[name=conn-filter]:checked").val();"wireless"===n?g.setupApFilter():"wired"===n&&g.setupNetworkFilter(),e.$el.removeClass(f.join(" ")).addClass(t||f[0]),r.cookie("filterClientAccess",t)}).filter(":checked").trigger("change"),n.on("change",function(){var t=r(this),n=t.find("option:selected").val(),i=t.is(":visible");i&&n?e.setFilter("ap_mac",n,1):e.removeFilter("ap_mac")}),i.on("change",function(){var t=r(this),n=t.find("option:selected").val(),i=t.is(":visible");i&&n?e.setFilter("network_id",n,1):e.removeFilter("network_id")}),this},gridRowClassName:function(t){return"id-"+t.id},property:function(t){if(!t)throw"Missing model";var n=t.get("mac")||t.id,i=this,s=this.options.app.routers.clients.views.index.properties;if(!s[n]){var a=new c;a.url="/api/s/"+SITE.name+"/stat/user/"+n,s[n]=!0,a.fetch({success:function(){s[n]=new e({properties:i.app.views.app.views.properties,parent:i,model:a,property_id:n.split(":").join(""),show:!0})},error:function(t){delete s[n],i.app.views.app.flash("error","Error",o.apiError(t,!0))}})}},updateBlocked:function(t,e){var n=this.app.collection("Clients",{},l),i=t.get("mac"),s=this.options.app.routers.clients.views.index.properties[i],r=s?s.model:null;if(r&&r.set({blocked:e})&&r.set({uptime:null}),a.each(n.where({mac:i}),function(t){t.set({blocked:e}),t.set({uptime:null})}),this.app.data.KnownClients){var o=this.app.collection("KnownClients");a.each(o.where({mac:i}),function(t){t.set({blocked:e,silent:!1}),t.set({uptime:null,silent:!1})})}},rowUnblock:function(t){var e=this;t.unblock({success:function(){e.updateBlocked(t,!1)},error:function(t){e.app.views.app.flash("error","Error",o.apiError(t,!0))}})},rowBlock:function(t){var e=this,i=e.app.collection("Devices").getInformIP(),s=function(){t.block({success:function(){e.updateBlocked(t,!0)},error:function(t){e.app.views.app.flash("error","Error",o.apiError(t,!0))}})};t.get("ip")===i?(new n).show(o.localize(o.N_ConfirmBlockController,t.get("mac")),s):s()},rowReconnect:function(t,e){var n=this;t.reconnect({success:function(){var i=n.app.collection("Clients",{},l),s=t.get("mac"),r=n.options.app.routers.clients.views.index.properties[s],o=r?r.model:null;o&&o.set({uptime:null}),r.remove(),a.each(i.where({mac:s}),function(t){t.set({uptime:null})}),n.app.refresh(),e&&e.success&&e.success()},error:function(t){n.app.views.app.flash("error","Error",o.apiError(t))}})},updateAuthorized:function(t,e){var n=this.app.collection("Clients",{},l);a.each(n.where({mac:t}),function(t){t.set({authorized:e})})},rowAuthorize:function(t){var e=this;t.authorize({success:function(){e.updateAuthorized(t.get("mac"),!0)},error:function(t){e.app.views.app.flash("error","Error",o.apiError(t))}})},rowUnauthorize:function(t){var e=this;t.unauthorize({success:function(){e.app.refresh()},error:function(t){e.app.views.app.flash("error","Error",o.apiError(t))}})},setupApFilter:function(){var t,e=this.$apFilter.find("option:selected").val(),n=this.$el.find("input:radio[name=wireless-filter]:checked").val(),i=this.$el.find("input:radio[name=access-filter]:checked").val();"wireless-all"===n&&"access-all"===i?t="num_sta":"wireless-all"===n&&"users"===i?t="user-num_sta":"wireless-all"===n&&"guests"===i?t="guest-num_sta":"na"===n&&"access-all"===i?t="na-num_sta":"na"===n&&"users"===i?t="na-user-num_sta":"na"===n&&"guests"===i?t="na-guest-num_sta":"ng"===n&&"access-all"===i?t="ng-num_sta":"ng"===n&&"users"===i?t="ng-user-num_sta":"ng"===n&&"guests"===i&&(t="ng-guest-num_sta"),this.$apFilter.empty(),this.$apFilter.append(r('<option value=""></option>').text(o.G_All));var s=0;this.devices&&a.each(this.devices.where({type:this.devices.typeMap.ap}),r.proxy(function(e){e.isConnected()&&(this.$apFilter.append(r("<option />").attr("value",e.get("mac")).text(e.name()+" ("+e.get(t)+")")),s+=e.get(t))},this)),this.$apFilter.find("option:first").text(o.G_All+" ("+s+")"),this.$apFilter.val(e),this.$apFilter.selectmenu("refresh")},setupNetworkFilter:function(){var t=this.$networkFilter.find("option:selected").val(),e=this.$el.find("input:radio[name=access-filter]:checked").val(),n={};"users"===e?n.is_guest=!1:"guests"===e&&(n.is_guest=!0);var i={},s=this.app.collection("Clients",{},l);s&&a.each(s.where(a.extend({is_wired:!0},n)),function(t){t&&(i[t.get("network")]=i.hasOwnProperty(t.get("network"))?i[t.get("network")]+1:1)}),this.$networkFilter.empty(),this.$networkFilter.append(r('<option value=""></option>').text(o.G_All));var c=0;this.networks&&a.each(this.networks.filterByPurpose(["corporate","guest","voip","vlan-only"]),r.proxy(function(t){var e=t.get("name"),n=0;i.hasOwnProperty(e)&&(n=i[e]),c+=n,this.$networkFilter.append(r("<option />").attr("value",t.id).text(e+" ("+n+")"))},this)),this.$networkFilter.find("option:first").text(o.G_All+" ("+c+")"),this.$networkFilter.val(t),this.$networkFilter.selectmenu("refresh")},searchable:function(){var e=this.app.collection("Devices"),n=r.proxy(function(t){var n;t.get("is_wired")?t.get("sw_mac")?(n=e.getDeviceFromMac(t.get("sw_mac")),n&&t.addSearchString("device-name",n.name()+t.switch_port_suffix(!1))):t.get("gw_mac")&&(n=e.getDeviceFromMac(t.get("gw_mac")),n&&t.addSearchString("device-name",n.name())):(n=t.get("ap_mac")?e.getDeviceFromMac(t.get("ap_mac")):null,n&&t.addSearchString("device-name",n.name()))},this),i=r.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",i),i(),t.prototype.searchable.call(this)},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"),t.prototype.remove.apply(this,arguments)}})}),define("unifi/router/ClientsRouter",["unifi/router/Router","unifi/view/clients/IndexView","unifi/view/clients/PropertyView"],function(t,e,n){"use strict";return t.extend({_fullyQualifiedName:"UNIFI.Routers.Clients",_associatedViews:{Index:e,Property:n},routes:{clients:"index"}})}),define("unifi/model/StatisticsColors",["backbone","underscore"],function(t,e){"use strict";return t.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 e.first(this.colors)},getAllButFirst:function(){return e.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(t){return this.colors[t%this.numColors]
}})}),define("unifi/collection/stats/Stats",["unifi/collection/Collection","backbone","unifi/model/Model","libs/moment","underscore"],function(t,e,n,i,s){"use strict";return t.extend({model:n,bySite:!0,_o:null,_type:null,toGraph:function(t){var e,n,i=this,a=s.compact(i.chain().filter(function(e){return t&&t.filter?e.get(i._o)==t.filter:!0}).map(function(t){if(t.get("o")==i._o){var e=t.toJSON();return e.datetime=new Date(t.get("time")),e}}).value()),r=s.max(a,function(t){return t.bytes}).bytes;if(n=r>(e=Math.pow(1e3,3))?"GB":r>(e=Math.pow(1e3,2))?"MB":r>(e=1e3)?"KB":"B",t.fill===!0&&t.interval){for(var o=s.pluck(a,"time"),l=s.min(o),c=s.max(o),d=l;c>d;d+=1e3*t.interval)-1===o.indexOf(d)&&a.push({bytes:null,num_sta:null,datetime:new Date(d)});a=s.sortBy(a,function(t){return t.datetime})}return a.map(function(t){return delete t.time,delete t.o,delete t.site,t.bytesFmt=t.bytes?+(t.bytes/e).toPrecision(2):null,t.bytesLbl=n,t})},validatePointsHasProp:function(t,e){for(var n=0,i=t.length;i>n;n++)if(s.has(t[n],e)&&!s.isNull(t[n][e]))return!0;return!1},orderByBytes:function(){var t=this,e=this.sortBy(function(t){return t.get("bytes")});return e=e.reverse(),e=s.uniq(e,!1,function(e){return e.attributes[t._o]})},comparator:function(t){return-i(t.get("time"))},hourly:function(t){return this.fetch(s.extend(t,{_method:"read-hourly"}))},daily:function(t){return this.fetch(s.extend(t,{_method:"read-daily"}))},clearStats:function(t){this.sync("clear",this,t)},sync:function(t,n,i){switch(i=i||{},i._method&&(t=i._method,delete i._method),t){case"read-hourly":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/stat/report/hourly."+this._type,i.type="POST",i.data=JSON.stringify(s.extend({attrs:["bytes","num_sta","time"]},i.data||{}));break;case"read-daily":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/stat/report/daily."+this._type,i.type="POST",i.data=JSON.stringify(s.extend({attrs:["bytes","num_sta","time"]},i.data||{}));break;case"clear":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/cmd/stat",i.type="POST",i.data=JSON.stringify(s.extend({cmd:"reset-current"},i.data||{}))}return e.sync.call(this,t,n,i)}})}),define("unifi/collection/stats/SiteStats",["unifi/collection/stats/Stats"],function(t){"use strict";return t.extend({_o:"site",_type:"site"})}),define("unifi/collection/stats/ClientStats",["unifi/collection/stats/Stats"],function(t){"use strict";return t.extend({_o:"user",_type:"user"})}),define("unifi/collection/stats/DeviceStats",["unifi/collection/stats/Stats"],function(t){"use strict";return t.extend({_o:"ap",_type:"ap"})}),define("unifi/view/statistics/LineChartView",["backbone","underscore","msg/Msg","jquery","libs/d3"],function(t,e,n,i,s){"use strict";return t.View.extend({initialize:function(t){this.config=t.config,this.data=t.data,this.plottable=!1,this.components={},this.mouse=[0,0],this.xpos,this.render()},render:function(){var t=this.config,e=this.data,n=this.components;!this.rendered&&(this.rendered=!0)&&(this.renderChart(),t.overlays.databox&&this.renderDatabox(),t.overlays.ticktip&&this.renderTicktip(),this.hideOverlays(!0),n.overlays.style("visibility","visible")),e.points.length&&this.update(!0)},renderChart:function(){var t=this.config,e=this.data,i=this.components;i.xScale=s.time.scale().domain([0,24]).range([0,t.width()]),i.yScale=s.scale.linear().domain([t.height,0]).range([0,t.height]),i.xAxis=s.svg.axis().scale(i.xScale).orient("bottom").ticks(24).tickSize.apply(null,t.ticksize).tickFormat(""),i.yAxis=s.svg.axis().scale(i.yScale).orient("right").ticks(6).tickSize(-t.width(),0,0).tickPadding(5),i.container=s.select(this.$el[0]).append("svg").attr("width",t.width()+t.margin.left+t.margin.right).attr("height",t.height+t.margin.top+t.margin.bottom),i.title=i.container.append("text").attr("x",t.margin.left).attr("y",t.margin.top/2).attr("class","title").text(t.title),i.chart=i.container.append("g").attr("class","chart").attr("transform","translate("+t.margin.left+","+t.margin.top+")"),i.border=i.chart.append("rect").attr("height",t.height).attr("width",t.width()).attr("class","border");var a=i.chart.append("svg:defs");a.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"),a.append("clipPath").attr("id","clip").append("rect").attr("width",t.width()).attr("height",t.height),i.chart.append("g").attr("class","x axis").attr("transform","translate(0,"+t.height+")"),i.chart.append("g").attr("class","y axis").attr("transform","translate("+t.width()+",0)"),i.chart.append("g").attr("clip-path","url(#clip)").attr("class","x grid").attr("width",t.width()).attr("height",t.height),i.datasets=i.chart.append("g").attr("class","datasets"),i.overlays=i.chart.append("g").attr("class","overlays").style("visibility","hidden"),i.line=s.svg.line().defined(function(t){return null!==t[e.yprop]}).x(function(t){return i.xScale(t[e.xprop])}).y(function(t){return i.yScale(t[e.yprop]||0)}),i.moreDataNeeded=i.container.append("text").attr("class","more-data-needed").text(n.G_StatsMoreDataPoints);var r=i.moreDataNeeded[0][0].getBBox();i.moreDataNeededBBox=r,i.moreDataNeeded.attr("x",(t.width()-r.width)/2).attr("y",(t.height+r.height)/2),i.moreDataNeeded.style("visibility","hidden")},renderDatabox:function(){var t=this.config,e=this.components;e.databox=e.overlays.append("g").attr("width",t.overlays.databox.width).attr("height",t.height+t.overlays.databox.heightDiff).attr("class","databox");var n=e.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 i=n.append("svg:feMerge");i.append("svg:feMergeNode"),i.append("svg:feMergeNode").attr("in","SourceGraphic"),e.databox.append("rect").attr("y",-t.overlays.databox.heightDiff/2).attr("width",t.overlays.databox.width).attr("height",t.height+t.overlays.databox.heightDiff).attr("filter","url(#blur)"),e.databox.append("g").attr("class","labels").attr("transform","translate(0,20)")},renderTicktip:function(){var t=this.config,e=this.components;e.ticktip=e.overlays.append("g").attr("class","ticktip"),e.ticktip.append("rect").attr("width",t.overlays.ticktip.width.min).attr("height",t.overlays.ticktip.height).attr("rx","3"),e.ticktip.append("text"),e.ticktip.style("visibility","hidden")},update:function(t){var n=(this.config,this.data),i=this.components,a=s.merge(n.points);a=e.filter(a,function(t){return null!==t[n.yprop]}),i.xScale.domain(n.xDomain||s.extent(a,function(t){return t[n.xprop]})),i.yScale.domain([s.max(a,function(t){return t[n.yprop]||0}),s.min(a,function(t){return t[n.yprop]||0})]),t===!0&&i.datasets.selectAll(".dataset").remove(),this.updateChart(),this.updateSections(),this.updateOverlays(!0)},updateChart:function(){var t=this.config,e=this.data,n=this.components;return this.plottable=e.points.length&&e.points[0]&&(e.points[0].length||e.points[1]&&e.points[1].length),n.container.attr("width",t.width()+t.margin.left+t.margin.right),n.border.attr("width",t.width()),n.xScale.range([0,t.width()]),n.chart.select("#clip rect").attr("width",t.width()),n.chart.select(".y.axis").attr("transform","translate("+t.width()+",0)"),n.chart.select(".x.grid").attr("width",t.width()),n.container.select(".more-data-needed").attr("x",(t.width()-n.moreDataNeededBBox.width)/2),this.plottable?(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(e.points),n.data.enter().append("g").attr("class",function(t,e){return"dataset dataset-"+e}),n.data.exit().remove(),n.paths=n.data.selectAll("path").data(function(t){return[t]}).attr("d",n.line),n.paths.enter().append("path").attr("d",n.line).attr("class","line").attr("clip-path","url(#clip)").style("stroke",function(e,n,i){return t.colors[i]}),n.paths.exit().remove(),n.circles=n.data.selectAll("circle").data(function(t){return t.filter(function(t){return null!==t[e.yprop]})},function(t){return t[e.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",t.points.off).attr("class","point").attr("fill",function(e,n,i){return t.colors[i]}),void n.circles.exit().remove()):(n.moreDataNeeded.style("visibility","visible"),void this.hideOverlays(!0))},updateSections:function(){var t=this.config,e=this.components,n=e.chart.selectAll(".x.grid"),i=e.chart.selectAll(".x.axis .tick"),a=4,r=Math.round(i[0].length/a),o=t.width()/(i[0].length-1)*a,l=[];n.selectAll("rect").remove(),l=i[0].map(function(t){return parseFloat(s.select(t).attr("transform").match(/translate\(\s*([^\s,)]+)[ ,]([^\s,)]+)/)[1])}).sort(function(t,e){return t-e}),o=l[a]-l[0]||o;for(var c=0;r>c;c++)c%2&&n.insert("svg:rect").attr("transform","translate("+l[c*a]+",0)").attr("height",t.height).attr("width",o).style("fill","url(#hatched)")},updateOverlays:function(t){var n,i=this.config,a=this.data,r=this.components;n=Math.max(Math.min(this.mouse[0]-10,i.width()),0);var o=[],l=[];if(r.data&&e.each(r.data.selectAll("circle"),function(t,a){var r,c;e.each(t,function(t){t=s.select(t);var a=t.attr("cx")-n;a>=0&&(e.isUndefined(r)||r>a)&&(c=t,r=a),t.attr("r",i.points.off)},this),c&&(c.attr("r",i.points.on),o[a]=c,l[a]=r)},this),e.each(l,function(t,n){t>e.min(l)&&delete o[n]}),o.length&&(n=e.first(e.compact(o)).attr("cx"),t||n!=this.xpos)){if(i.overlays.databox){r.databox.selectAll("circle").remove(),e.each(o,function(t,e){t.attr("cx")>i.overlays.databox.width&&r.databox.append("circle").attr("cx",i.overlays.databox.width).attr("cy",t.attr("cy")).attr("r",i.points.on).attr("class","point").attr("fill",i.colors[e])});var c=r.databox.select(".labels");c.selectAll("g").remove(),e.each(a.labels,function(t,e){if(o[e]){var n=c.append("g").attr("transform","translate(0,"+30*e+")").style("fill",i.colors[e]),s=o[e].datum();n.append("text").attr("x",i.overlays.databox.valueWidth).attr("width",i.overlays.databox.valueWidth).attr("class","value").text(s[a.yprop]||0),n.append("text").attr("x",i.overlays.databox.valueWidth+5).text((a.labelprop?s[a.labelprop]+" ":"")+t)}}),r.databox.attr("transform","translate("+Math.max(0,n-i.overlays.databox.width)+",0)")}if(i.overlays.ticktip){var d=e.first(e.values(o)).datum()[a.xprop],h=r.ticktip.select("text");h.text(i.overlays.ticktip.format?i.overlays.ticktip.format(d,this.config.range):d);var u=Math.max(i.overlays.ticktip.width.min,Math.min(h.node().getComputedTextLength()+2*i.overlays.ticktip.width.padding,i.overlays.ticktip.width.max));h.attr("transform","translate("+(u-i.overlays.ticktip.width.padding)+",17)"),r.ticktip.attr("transform","translate("+Math.max(i.overlays.databox.width-u,n-u)+","+(i.height+i.overlays.ticktip.bottom)+")").select("rect").attr("width",u),r.ticktip.style("visibility","visible")}}this.xpos=n},hideOverlays:function(t){var e=this,n=this.config,i=this.components;i.data&&i.data.selectAll("circle").transition().duration(t?0:600).attr("r",n.points.off),i.overlays&&i.overlays.transition().duration(t?0:600).style("opacity",0).each("end",function(){e._overlaysVisible=!1})},showOverlays:function(){if(this.plottable){var t=this.components;this._overlaysVisible=!0,t.overlays.transition().duration(0).style("opacity",null)}},remove:function(){this.rendered=!1,t.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/statistics/PieChartView",["backbone","underscore","msg/Msg","jquery","libs/d3","ubnt/backgrid"],function(t,e,n,i,s,a){"use strict";return t.View.extend({initialize:function(t){this.config=t.config,this.data=t.data,this.components={},this.render()},render:function(){{var t=this,e=(this.config,this.data);this.components}!this.rendered&&(this.rendered=!0)&&(this.renderChart(),this.$el.on("mouseover",".arc",function(){var e=i(this),n=e.data("arc");t.$(".tooltip-"+n).css({visibility:"visible"}),t.$(".piechart-item-"+n).addClass("over"),t.tooltipIndex=n}).on("mouseout",".arc",function(){var e=(i(this),i(this).data("arc"));t.$(".tooltip-"+e).css({visibility:"hidden"}),t.$(".piechart-item-"+e).removeClass("over")})),e.points.length&&this.update()},renderChart:function(){var t=this.config,e=this.data,n=this.components;n.pie=s.layout.pie().sort(null).value(function(t){return t.get(e.prop)||0}),n.arc=s.svg.arc().innerRadius(0).outerRadius(this.config.radius-10),n.svg=s.select(this.$(t.pieChart)[0]).append("svg").attr("width",t.width).attr("height",t.height).append("g").attr("transform","translate("+t.width/2+","+t.height/2+")"),t.legend&&this.renderLegend()},renderLegend:function(){var t,n=this.config,i=this.data;n.legend&&(this.$legend=this.$legend||this.$(".piechart-legend"),this.$legend.empty(),e.each(i.points,function(e,i){t="function"==typeof e.name?e.name():e.get("name"),this.$legend.append('<div class="piechart-legend-item piechart-item-'+i+'"><div class="piechart-legend-color" style="background-color:'+n.colors[i]+'"></div>'+t+"</div>")},this))},update:function(){var t=this.config,e=this.data,n=this.components;e.points&&(n.g=n.svg.selectAll(".arc").data(n.pie(e.points)),n.g.enter().append("g").attr("class","arc").attr("data-arc",function(t,e){return e}),n.g.enter().append("text").attr("class",function(t,e){return"tooltip tooltip-"+e}).attr("data-arc",function(t,e){return e}).attr("transform",function(e){var i=n.arc.centroid(e),s=i[0],a=i[1],r=Math.sqrt(s*s+a*a);return"translate("+s/r*(t.radius-3)+","+a/r*(t.radius-3)+")"}).attr("dy",".35em").style("text-anchor",function(t){return(t.endAngle+t.startAngle)/2>Math.PI?"end":"start"}).style("visibility","hidden").text(function(t){var n=t.data.get(e.prop)||0;return e.formatBytes&&(n=a.Formatters.Bytes.fromRaw(n)),n}),n.g.selectAll("path").remove(),n.g.append("path").attr("d",n.arc).attr("fill",function(e,n){return t.colors[n]}),n.g.exit().remove(),this.renderLegend())},remove:function(){this.$el.off("mouseover",".arc").off("mouseout",".arc"),this.rendered=!1,t.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/statistics/DatetimeNavView",["backbone","underscore","msg/Msg","libs/moment","jquery","jquery-ui"],function(t,e,n,i,s){"use strict";return t.View.extend({initialize:function(t){e.bindAll(this),this.RANGE_1HOUR=s(".dateRange1HourBtn").val(),this.RANGE_24HOUR=s(".dateRange24HourBtn").val(),this.RANGE_MONTH=s(".dateRangeMonthBtn").val(),this.RANGE_7DAY=s(".dateRange7DayBtn").val(),this.useCurrentTimeForRange=!1,t.useCurrentTimeForRange&&(this.useCurrentTimeForRange=t.useCurrentTimeForRange),this.originalSettings={},this.momentDate=i(),this.momentDateMax=i(),this.momentDate.startOf("hour"),this.momentDateMax.startOf("hour"),this.momentHourFormat="ha",this.momentDatetimeFormat="YYYY/M/D",this.render()},render:function(){!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(){s(this).addClass("ui-state-active")}).on("mouseup mouseout",function(){var t=s(this);e.delay(function(){t.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(t){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(),s(t.currentTarget).hasClass("ui-button")&&this.onUpdate(t)},onMicroRangeNextClick:function(t){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(),s(t.currentTarget).hasClass("ui-button")&&this.onUpdate(t)},onDatepickerSelect:function(t){this.momentDate=i(t).hour(this.momentDate.hour()),this.momentDateMax=this.momentDate.clone(),this.updateDatetime()},onDatepickerChangeMonthYear:function(){var t=this;(this.range===this.RANGE_MONTH||this.range===this.RANGE_7DAY)&&e.delay(function(){t.setDaysInActiveRange()},100)},onRangeChange:function(t){var e=s(t.target),n=e.attr("id"),i=e.val();return this.$buttonset.find(".ui-button").removeClass("ui-state-active"),this.$buttonset.find("input").prop("checked",""),i&&(i===this.RANGE_24HOUR?(this.range=this.RANGE_24HOUR,this.$el.removeClass("isMonth is1Hr").addClass("is24Hr"),this.removeDaysInActiveRange(),this.momentDate=this.momentDateMax.clone()):i===this.RANGE_1HOUR?(this.range=this.RANGE_1HOUR,this.$el.removeClass("isMonth is24Hr").addClass("is1Hr"),this.removeDaysInActiveRange(),this.momentDate=this.momentDateMax.clone()):i===this.RANGE_MONTH?(this.range=this.RANGE_MONTH,this.$el.removeClass("is24Hr is1Hr").addClass("isMonth")):i===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 t=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)),e.delay(function(){t.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 t,n,a,r,o,l=this.$datepicker.find("tbody td"),c=(l.length,this.momentDate.clone()),d=this.momentDateMax.clone();c=c.startOf("day"),d=d.startOf("day"),this.range==this.RANGE_24HOUR&&c.add("day",1),this.removeDaysInActiveRange(),e.each(l,function(e){t=s(e),n=t.data("month")+1,r=t.data("year"),a=t.text(),o=i(r+"/"+n+"/"+a,"YYYY/MM/DD"),o.startOf("hour"),o>=c&&d>=o&&t.find("a").addClass("ui-state-active-range")})},removeDaysInActiveRange:function(){if(this.$datepicker.find(".ui-state-active-range").removeClass("ui-state-active-range"),this.range==this.RANGE_24HOUR){var t=this.$datepicker.find(".ui-datepicker-current-day");t.removeClass("ui-datepicker-current-day"),t.find(".ui-state-active").removeClass("ui-state-active")}},getDateRange:function(){var t,e,n=this.momentDate.clone().startOf("hour"),i=this.momentDateMax.clone().startOf("hour"),s={range:this.range,start:n.utc().unix()};return this.range===this.RANGE_24HOUR?(this.useCurrentTimeForRange?(t=i,e=i.clone().subtract("days",1)):(t=i.endOf("day"),e=i.clone().startOf("day")),s.end=t.utc().unix(),s.start=e.utc().unix()):this.range===this.RANGE_1HOUR?(e=n,t=n.clone().endOf("hour"),s.start=e.utc().unix(),s.end=t.utc().unix()):this.range===this.RANGE_MONTH?(t=i.endOf("day"),e=t.clone().subtract("months",1).startOf("day"),s.end=t.utc().unix(),s.start=e.utc().unix()):this.range===this.RANGE_7DAY&&(t=i.endOf("day"),e=t.clone().subtract("days",7).startOf("day"),s.end=t.utc().unix(),s.start=e.utc().unix()),s.start=parseInt(s.start+"000",10),s.end=parseInt(s.end+"000",10),s},openPopover:function(){this.originalSettings=this.getDateRange(),this.$datePopover.show(),s("body").on("click",this.onBodyClick)},closePopover:function(){this.$datePopover.hide(),s("body").off("click",this.onBodyClick)},onBodyClick:function(t){var e=this,n=s(t.target);n.hasClass("filter")&&e.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||e.onCancel()},onUpdate:function(t){t.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),s("body").off("click",this.onBodyClick),this.rendered=!1,t.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(t,e,n,i,s,a){"use strict";return t.View.extend({initialize:function(t){e.bindAll(this),this.colors=t.colors,this.maxItemsToDisplay=10,this.collections=t.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 s=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=e.template(a),this.$listApplications=n("#listApplications").find(".list"),this.$listDevices=n("#listDevices").find(".list"),this.$listClients=n("#listClients").find(".list"),this.applicationCollection=new t.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 t.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(t){s.$listApplications.append(s.listItemTemplate(t.toJSON()))}),this.clientsCollection.each(function(t){s.$listClients.append(s.listItemTemplate(t.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(i.G_Filter),this.$filterApplicationsLabel.find(".ui-button-text").text(i.G_StatsApplications),this.$filterDevicesLabel.find(".ui-button-text").text(i.G_Devices),this.$filterClientsLabel.find(".ui-button-text").text(i.G_Clients),this.$(".list-wrapper").on("click","li",this.onListItemClick),this.$listApplications.show())},updateClientList:function(){var n=this,i=this.collections.stats.clients.orderByBytes(),a={};n.$listClients.empty(),i=e.first(i,this.maxItemsToDisplay),e.each(i,function(t){a={title:"title",size:s.Formatters.Bytes.fromRaw(t.attributes.bytes),percentage:"0%"},n.$listClients.append(n.listItemTemplate(a))}),this.collections.filtered.clients=new t.Collection(i)},updateDeviceList:function(){var n,i=this,a=this.collections.stats.devices.orderByBytes(),r={};i.$listDevices.empty(),a=e.first(a,this.maxItemsToDisplay),e.each(a,function(t){n=i.collections.devices.getDeviceFromMac(t.attributes.ap),r={title:n?n.name():t.attributes.ap,size:s.Formatters.Bytes.fromRaw(t.attributes.bytes),percentage:"0%"},i.$listDevices.append(i.listItemTemplate(r))}),this.collections.filtered.devices=new t.Collection(a)},onChangeFilter:function(t){var e=n(t.target),i=e.val();i&&(this.$(".list-wrapper").hide(),this.$(".list-wrapper."+i).show())},onListItemClick:function(t){var e,i,s,a=n(t.currentTarget),r=(a.parents("ul"),a.index()),o=this.$buttonset.find("input[name=filter]:checked").val(),l=this.collections.filtered[o].at(r),c=l.get("o"),d=a.hasClass("selected");this.$el.find("li").removeClass("selected").css("background-color",""),d?(a.css("background-color",""),o=null,e=null,i=null,s=null):(a.addClass("selected").css("background-color",this.colors[r]),e=a.find(".title").text(),i=l.get(c),s=this.colors[r]),this.$el.trigger("change",{filter:o,name:e,oPropValue:i,color:s})},openPopover:function(t){t.preventDefault(),this.$popover.show(),this.$filterButton.addClass("ui-state-selected")},closePopover:function(){this.$popover.hide(),this.$filterButton.removeClass("ui-state-selected")},onBodyClick:function(t){var e=this,i=n(t.target);i.hasClass("filter-popover")||i.parents(".filter-popover").length||i.hasClass("filter")||i.parents(".filter").length||e.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,t.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(t,e,n,i,s,a,r,o,l,c,d,h,u,p,m,f,g,v){"use strict";return t.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(i){t.prototype.initialize.call(this,i),this.updateCharts=e.debounce(this._updateCharts,300),this.colors=new o,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,c),this.collections.stats.devices=this.options.app.collection("DeviceStats",null,d),this.collections.stats.site=this.options.app.collection("SiteStats",null,l),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(t,e){e&&(this._limitRange=e.range,this._limitStart=e.start,this._limitEnd=e.end,this.load())},this)),this.filterNav=new m({el:"#filterNav",colors:this.colors.getAllButFirst(),collections:this.collections}),this.filterNav.$el.on("change",n.proxy(function(t,e){e&&(this._limitFilter=e.filter,this._limitFilterName=e.name,this._limitFilterValue=e.oPropValue,this._limitFilterColor=e.color,this.updateCharts())},this));var s=this.calendar.getDateRange();this._limitRange=s.range,this._limitStart=s.start,this._limitEnd=s.end,this.load()},load:function(t){var i=[],s="24hr"==this._limitRange?"hourly":"daily",a=[];t&&a.push(t),e.each(this.collections.stats,function(t,e){i.push(this.collections.stats[e][s]({silent:!0,data:{start:this._limitStart,end:this._limitEnd}})),a.push(function(){t.trigger("change")})},this),n.when.apply(null,i).done(function(){e.each(a,function(t){t()})})},render:function(){if(t.prototype.render.call(this),!this.rendered&&(this.rendered=!0)){var i=this;this.$el.html(e.template(f,{statisticsDateNavTemplate:e.template(g,{id:"statisticsDateNav"}),msg:a,statisticsFilterTemplate:e.template(v)})),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 t=n(this),e=t.parent();t.selectmenu({parent:e,appendTo:e,label:t.data("label"),icons:{button:"ubnt-icon-arrow-down secondary-color"},position:{at:"left bottom",collision:"flip"},change:function(){t.trigger("change")}})}),n("#clientsGrid, #trafficGrid").on("mousemove",function(t){var s=t.pageX-n(this).offset().left,a=t.pageY-n(this).offset().top;e.each(i.charts,function(t){t.mouse=[s,a],t.updateOverlays()})}),this.$el.find(".data-grids").on("mouseleave",function(){i.intervals.overlays||(i.intervals.overlays=setTimeout(function(){e.each(i.charts,function(t){t.hideOverlays()})},1e3))}).on("mouseenter",function(){clearTimeout(i.intervals.overlays),delete i.intervals.overlays,e.each(i.charts,function(t){t.showOverlays()})}),n(window).resize(function(){i.charts.clients.update(!0),i.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 t=this,e=n("#clientsGrid");this.charts.clients=new h({el:e,config:{title:a.G_StatsClientsTitle,margin:this._chartConfig.margin,width:function(){return e.width()+t._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:[a.G_StatsClientsLabel],points:[]}})},traffic:function(){var t=this,e=n("#trafficGrid");this.charts.traffic=new h({el:e,config:{title:a.G_StatsTrafficTitle,margin:this._chartConfig.margin,width:function(){return e.width()+t._chartConfig.widthOffset},height:this._chartConfig.height,ticksize:[6,0,0],points:this._chartConfig.points,overlays:{databox:this._chartConfig.overlays.databox,ticktip:{format:function(t,e){return s(t).format("24hr"==e?"hA":"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:[a.G_StatsTrafficLabel],points:[]}})},_updateCharts:function(){var t="24hr"==this._limitRange?3600:86400,n=this.collections.stats.site.toGraph({fill:!0,interval:t});if(n){if(this.charts.clients.data.points[0]=this.collections.stats.site.validatePointsHasProp(n,this.charts.clients.data.yprop)?e.clone(n):[],this.charts.traffic.data.points[0]=this.collections.stats.site.validatePointsHasProp(n,this.charts.traffic.data.yprop)?e.clone(n):[],"24hr"==this._limitRange){var i=[new Date(s(this._limitStart).startOf("hour")),new Date(s(this._limitEnd).startOf("hour"))];this.charts.clients.data.xDomain=i,this.charts.traffic.data.xDomain=i}else delete this.charts.clients.data.xDomain,delete this.charts.traffic.data.xDomain;if(this._limitFilter){var a=this.collections.stats[this._limitFilter];n=a.toGraph({filter:this._limitFilterValue,fill:!0,interval:t}),this.charts.clients.data.points[1]=a.validatePointsHasProp(n,this.charts.clients.data.yprop)?e.clone(n):[],this.charts.traffic.data.points[1]=a.validatePointsHasProp(n,this.charts.traffic.data.yprop)?e.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 t=n("#clientsTotalPieChart");this.pieCharts.clientStats=new u({el:t,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 t=this.clientsByEssid.slice(0,5);this.pieCharts.clientStats&&t&&t.length?(this.pieCharts.clientStats.data.points=t,this.$statsClientsTotal.removeClass("more-data-needed"),this.pieCharts.clientStats.update()):this.$statsClientsTotal.addClass("more-data-needed")},_updateDeviceStats:function(){var t=this.apsSortByBytes.slice(0,5);this.pieCharts.numClients&&this.pieCharts.traffic&&t&&t.length?(this.pieCharts.numClients.data.points=t,this.pieCharts.traffic.data.points=t,this.$statsCurrentUsage.removeClass("more-data-needed"),this.pieCharts.numClients.update(),this.pieCharts.traffic.update()):this.$statsCurrentUsage.addClass("more-data-needed")},currentUsage:function(){var t=n("#clientsCurrentUsagePieCharts");this.pieCharts.numClients=new u({el:t,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 u({el:t,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 t=this,e=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 e=t.apsSortByBytes[0],n=t.collections.devices,i=n.getDeviceFromMac(e.get("ap_mac"));i||(i=e),t.options.app.routers.devices.views.index.property(i)}).text(this.apsSortByBytes[0].name()),this.$mostActiveAp.find(".down .value").text(r.Formatters.Bytes.fromRaw(this.apsSortByBytes[0].get("tx_bytes"))),this.$mostActiveAp.find(".up .value").text(r.Formatters.Bytes.fromRaw(this.apsSortByBytes[0].get("rx_bytes"))),this.$mostActiveAp.show(),e++):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 e=t.clientsSortedByBytes[0],n=t.options.app.collection("Clients"),i=n.getClientFromMac(e.get("mac"));i||(i=e),t.options.app.routers.clients.views.index.property(i)}).text(this.clientsSortedByBytes[0].name()),this.$mostActiveClient.find(".down .value").text(r.Formatters.Bytes.fromRaw(this.clientsSortedByBytes[0].get("tx_bytes"))),this.$mostActiveClient.find(".up .value").text(r.Formatters.Bytes.fromRaw(this.clientsSortedByBytes[0].get("rx_bytes"))),this.$mostActiveClient.show(),e++):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 e=t.clientsSortedByUptime[0],n=t.options.app.collection("Clients"),i=n.getClientFromMac(e.get("mac"));i||(i=e),t.options.app.routers.clients.views.index.property(i)}).text(this.clientsSortedByUptime[0].name()),this.$allTimeTopClient.find(".down .value").text(r.Formatters.Bytes.fromRaw(this.clientsSortedByUptime[0].get("tx_bytes"))),this.$allTimeTopClient.find(".up .value").text(r.Formatters.Bytes.fromRaw(this.clientsSortedByUptime[0].get("rx_bytes"))),this.$allTimeTopClient.find(".duration").text(r.Formatters.Duration.fromRaw(this.clientsSortedByUptime[0].get("uptime"))),this.$allTimeTopClient.show(),e++):this.$allTimeTopClient.hide(),e>0?this.$statsQuickLook.removeClass("more-data-needed"):this.$statsQuickLook.addClass("more-data-needed")},clearCurrentStats:function(){var t=this;return this.collections.stats.site.clearStats({success:function(e){"ok"===e.meta.rc&&(t.apsSortByBytes=[],t._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,t.prototype.remove.apply(this,arguments)}})}),define("unifi/router/StatisticsRouter",["unifi/router/Router","unifi/view/statistics/IndexView"],function(t,e){"use strict";return t.extend({_fullyQualifiedName:"UNIFI.Routers.Statistics",_associatedViews:{Index:e},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            <option value="portforwardstats"><%- msg.G_InsightsPortForwardStats %></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="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            </div>\n        \n            <div class="buttonset">\n                <input type="checkbox" id="knownClientsBlocked" name="client-table-filter-type-options" value="blocked"/>\n                <label for="knownClientsBlocked"><%- msg.G_InsightsBlocked %></label>\n                <input type="checkbox" id="knownClientsNoted" name="client-table-filter-type-options" value="noted"/>\n                <label for="knownClientsNoted"><%- msg.G_Noted %></label>\n                <input type="checkbox" id="knownClientsStaticIP" name="client-table-filter-type-options" value="staticIP"/>\n                <label for="knownClientsStaticIP"><%- msg.G_StaticIP %></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            \n            <div>\n                <select class="knownClientsLastSeen" name="knownClientsLastSeen" data-label="<%- msg.G_LastSeen %>: ">\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="<%- msg.G_LastSeen %>: ">\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="portforwardstats data-filter left">\n            <div class="buttonset portforward-subtab-filters">\n                <input type="radio" id="portforwardFilterAll" name="portforward-subtab-filter" value="all" checked="checked" /><label for="portforwardFilterAll"><%- msg.G_PortForwardAll %></label>\n                <input type="radio" id="portforwardFilterUserDefined" name="portforward-subtab-filter" value="user_defined" /><label for="portforwardFilterUserDefined"><%- msg.G_PortForwardUserDefined %></label>\n                <input type="radio" id="portforwardFilterUpnp" name="portforward-subtab-filter" value="upnp" /><label for="portforwardFilterUpnp"><%- msg.G_PortForwardUpnp %></label>\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 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(t,e,n,i,s,a){"use strict";return t.extend({id:"insightsChrome",_templateId:s,_contentView:null,initialize:function(e){t.prototype.initialize.call(this,e),this.render()},render:function(){if(t.prototype.render.call(this),!this.rendered&&(this.rendered=!0)){var s=this,r=e.template(a,{id:"pastconnections"}),o=e.template(a,{id:"pastguestauthorizations"});this.$el.html(e.template(this._templateId,{pastConnectionsCalendarTemplate:r,pastGuestAuthorizationsCalendarTemplate:o,msg:i})),this.$content=this.$el.find("#insightsContent"),this.$el.find(".buttonset").buttonset(),this.$el.find("form.data-filters").on("submit",function(t){t.preventDefault()}),this.$search=this.$el.find("input[name=search]"),this.$search.on("keyup",e.debounce(this.filter,300)),this.$insightsDropdown=this.$el.find("#insightsDropdown"),this.$insightsDropdown.on("change",function(t){t.preventDefault();var e=n(this).val();s.navigate(e),s.app.routers.insights.navigate("insights/"+e,{trigger:!0})})}},renderSelects:function(){n("#insightsChrome .section").find("select:visible").each(function(){var t=n(this),e=t.parent(),i=t.data("selectRendered"),s=t.data("myposition")||"left top";i||(t.selectmenu({parent:e,appendTo:e,label:t.data("label"),icons:{button:"ubnt-icon-arrow-down secondary-color"},position:{my:s,at:"left bottom",collision:"flip"},change:function(){t.trigger("change")}}),t.data("selectRendered",!0).trigger("change",!0))})},navigate:function(t){this.$insightsDropdown.val()!=t&&this.$insightsDropdown.val(t).change(),this.$content.find("> div").hide(),this.$content.find("#"+t).show(),this.$(".section").attr("id","insights"+t),this.renderSelects()},filter:function(){this._contentView&&this._contentView.filter.call(this,null,this.$search.val())},remove:function(){e.each(this.views,function(t){t.remove&&t.remove()},this),this.views={},this.$el.find("form.data-filters").off("submit"),this.$search.off("keyup"),this.$insightsDropdown.off("change"),this.rendered=!1,t.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(t,e,n,i,s,a,r,o,l){"use strict";return e.extend({id:"knownclients",_templateId:o,_collectionType:{name:"KnownClients",Class:r},_pageable:!0,_limitType:"all",_limitConn:"all",_limitTimeframe:"24",_includeTimeframe:!0,_filterMinimum:.1,initialize:function(t){this.$insightsChrome=a("#insightsChrome"),e.prototype.initialize.call(this,s.extend({skipBindings:!0},t)),this.$el.removeClass("content"),this.listenTo(this.collection,"change:blocked",this.handleBlockedChange)},columns:function(){var t=this;return[{name:"mac",customClass:"column-name",label:l.G_InsightsNameMACAddress,editable:!1,cell:i.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){return t.name()},toRaw:function(t){return t}}}),callback:function(e){t.options.app.routers.clients.views.index.property(e)},title:"mac"},{name:"oui",label:l.G_InsightsManufacturer,editable:!1,cell:"string"},{name:"is_guest",label:l.G_UserGuest,editable:!1,cell:i.Cells.ModelCell.extend({callback:"userOrGuest"})},{name:"tx_bytes",label:l.G_Down,editable:!1,cell:n.StringCell.extend({formatter:i.Formatters.Bytes})},{name:"rx_bytes",label:l.G_Up,editable:!1,cell:n.StringCell.extend({formatter:i.Formatters.Bytes})},{name:"last_seen",label:l.G_LastSeen,editable:!1,cell:i.Cells.ModelCell.extend({callback:"absoluteLastSeen"})},{name:"_id",label:l.G_Actions,editable:!1,sortable:!1,headerCell:i.Headers.noSortHeader,cell:i.Cells.ActionsCell.extend({actions:{unblock:{icon:"ubnt-icon-undo",callback:this.rowUnblock,requiresAdminPrivilege:!0,render:function(t){return t.get("blocked")}},block:{icon:"ubnt-icon-close",callback:this.rowBlock,requiresAdminPrivilege:!0,render:function(t){return!t.get("blocked")}}}})}]},render:function(){var t=this.rendered;if(t||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),e.prototype.render.call(this),!t){var n=(this.options.app.collection("Clients"),this);this.$inputFilterType=this.$insightsChrome.find('.knownclients input[name="client-table-filter-type"]'),this.$inputFilterTypeOptions=this.$insightsChrome.find('.knownclients input[name="client-table-filter-type-options"]'),this.$inputFilterWired=this.$insightsChrome.find('.knownclients input[name="table-filter-conn"]'),this.$lastSeenDropdown=this.$insightsChrome.find('.knownclients select[name="knownClientsLastSeen"]'),this.$insightsChrome.find('.knownclients input[name="client-table-filter-type"][value="'+(a.cookie("filterInsightsKnownClientsType")||"all")+'"]').click(),this.$insightsChrome.find('.knownclients input[name="table-filter-conn"][value="'+(a.cookie("filterInsightsKnownClientsConn")||"all")+'"]').click(),s.each((a.cookie("filterInsightsKnownClientsTypeOptions")||"").split(","),function(t){n.$insightsChrome.find('.knownclients input[name="client-table-filter-type-options"][value="'+t+'"]').click()}),this.$inputFilterType.on("change",this.handleFilterChange),this.$inputFilterTypeOptions.on("change",this.handleFilterChange),this.$inputFilterWired.on("change",this.handleFilterChange),this.$lastSeenDropdown.on("change",function(){n._limitTimeframe=Math.max(parseInt(a(this).find("option:selected").val(),10),24),n.load(!0)
}),this.$lastSeenDropdownParent=null}},handleFilterChange:function(){var t=this.$inputFilterType.first().parent().find("input:checked").val(),e=this.grids.content;if(e){switch(this.$lastSeenDropdownParent||(this.$lastSeenDropdownParent=this.$lastSeenDropdown.parents(".ui-selectmenu-parent:first")),this._limitType=t||void 0,e.removeFilter("is_guest",!0),t){case"user":e.setFilter("is_guest",!1,1),this.$lastSeenDropdownParent.show();break;case"guest":e.setFilter("is_guest",!0,1),this.$lastSeenDropdownParent.show();break;case"all":this.$lastSeenDropdownParent.show()}this._includeTimeframe&&(this._limitTimeframe=Math.max(parseInt(this.$lastSeenDropdown.find("option:selected").val(),10),24)),a.cookie("filterInsightsKnownClientsType",t);var n=[];this.$inputFilterTypeOptions.first().parent().find("input:checked").each(function(t,e){n.push(a(e).val())}),this.$lastSeenDropdownParent||(this.$lastSeenDropdownParent=this.$lastSeenDropdown.parents(".ui-selectmenu-parent:first")),e.removeFilter("blocked",!0),e.removeFilter("noted",!0),e.removeFilter("use_fixedip",!0),this._includeTimeframe=!0,this._limitBlocked=void 0,this._limitNoted=void 0,this._limitFixed=void 0,n.indexOf("blocked")>=0&&(e.setFilter("blocked",!0,1),this.$lastSeenDropdownParent.hide(),this._includeTimeframe=!1,this._limitBlocked=!0),n.indexOf("noted")>=0&&(e.setFilter("noted",!0,1),this.$lastSeenDropdownParent.hide(),this._includeTimeframe=!1,this._limitNoted=!0),n.indexOf("staticIP")>=0&&(e.setFilter("use_fixedip",!0,1),this.$lastSeenDropdownParent.hide(),this._includeTimeframe=!1,this._limitFixed=!0),this._includeTimeframe&&(this._limitTimeframe=Math.max(parseInt(this.$lastSeenDropdown.find("option:selected").val(),10),24)),a.cookie("filterInsightsKnownClientsTypeOptions",n.join(","));var i=this.$inputFilterWired.first().parent().find("input:checked").val();switch(this._limitConn=i,e.removeFilter("is_wired",!0),i){case"wired":e.setFilter("is_wired",!0,1,!1,!0);break;case"wireless":e.setFilter("is_wired",!0,-1,!1,!0);break;case"all":}a.cookie("filterInsightsKnownClientsConn",i),this.load(!0)}},load:function(t){if(t=t||!this.collection,!this.collection||t){var n={type:this._limitType,conn:this._limitConn,use_fixedip:this._limitFixed,noted:this._limitNoted,blocked:this._limitBlocked};this._includeTimeframe&&(n.within=this._limitTimeframe),e.prototype.load.call(this,t,{data:n})}},grid:function(){t.prototype.grid.call(this),this.handleFilterChange()},handleBlockedChange:function(){"blocked"==this._limitType&&this.grids.content._filter()},searchable:function(){var e=a.proxy(function(t){var e=this.options.app.collection("Clients").getClientFromMac(t.get("mac"));e&&t.addSearchString("alias_name",e.name())},this),n=a.proxy(function(){this.collection.each(e),this.trigger("search:indexed")},this);this.listenTo(this.collection,"change",e),this.listenTo(this.collection,"add",e),this.listenTo(this.collection,"reset",n),n(),t.prototype.searchable.call(this)},remove:function(){this.stopListening(this.collection),this.stopListening(this.options.app.collection("Clients")),this.$inputFilterType.off("change",this.handleFilterChange),this.$inputFilterTypeOptions.off("change",this.handleFilterChange),this.$inputFilterIp.off("change",this.handleFilterChange),this.$inputFilterWired.off("change",this.handleFilterChange),this.$lastSeenDropdown.off("change"),this.rendered=!1,e.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/RogueAccessPoint",["unifi/model/Device","backbone","ubnt/backgrid","libs/moment","msg/Msg"],function(t){"use strict";return t.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(t,e,n,i){"use strict";return n.extend({model:i,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/rogueap"},sync:function(n,i,s){switch(s=s||{},n){case"read":s.contentType="application/json; charset=utf-8",s.type="POST",s.data=JSON.stringify(e.extend(s.data||{}))}return t.sync.call(this,n,i,s)}})}),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(t,e,n,i,s,a,r,o){"use strict";return t.extend({id:"rogueaccesspoints",_templateId:o,_collectionType:{name:"Rogueaccesspoints",Class:r},_pageable:!0,_limitTimeframe:"24",initialize:function(e){this.$insightsChrome=s("#insightsChrome"),t.prototype.initialize.call(this,e),this.$el.removeClass("content")},columns:function(){var t=this;return[{name:"essid",label:a.G_InsightsNameSSI,editable:!1,cell:n.Cells.ModelCell.extend({callback:"essid"})},{name:"bssid",label:a.G_InsightsBSSID,editable:!1,cell:"string"},{name:"channel",label:a.G_Channel,editable:!1,cell:n.Cells.ModelCell.extend({callback:"channelWithRadio"})},{name:"security",label:a.G_InsightsRogueType,editable:!1,cell:n.Cells.ModelCell.extend({callback:"type"})},{name:"oui",label:a.G_InsightsManufacturer,editable:!1,cell:"string"},{name:"ap_mac",label:a.G_InsightsLocation,editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var n=t.options.app.collection("Devices"),i=n.getDeviceFromMac(e.get("ap_mac"));return"near "+(i?i.name():e.get("ap_mac"))},toRaw:function(t){return t}}})},{name:"rssi",label:a.G_Signal,customClass:"column-signal",editable:!1,cell:n.Cells.ComplexHtmlCell.extend({className:"rssiWithRadio",formatter:{fromRaw:function(t){var e=t.get("rssi"),n=t.get("radio"),i="sprite-";return i+=n+"-"+("na"===n?"5g":"2g"),'<span class="signal-value">'+e+'</span><span class="signal-icon '+i+'"></span>'},toRaw:function(t){return t}}})},{name:"last_seen",label:a.G_InsightsLastSeen,editable:!1,cell:n.Cells.ModelCell.extend({callback:"absoluteLastSeen"})}]},render:function(){var e=this.rendered;if(e||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),t.prototype.render.call(this),!e){var n=this;this.$lastSeenDropdown=this.$insightsChrome.find('.rogueaccesspoints select[name="rogueAccessPointsLastSeen"]').on("change",function(){n._limitTimeframe=Math.max(parseInt(s(this).find("option:selected").val(),10),24),n.load(!0)})}},load:function(e){e=e||!this.collection,(!this.collection||e)&&t.prototype.load.call(this,e,{data:{within:this._limitTimeframe}})},searchable:function(){var e=s.proxy(function(t){var e=this.options.app.collection("Devices").getDeviceFromMac(t.get("ap_mac"));e&&t.addSearchString("near",e.name()),t.addSearchString("channel",t.channelWithRadio()),t.addSearchString("type",t.type())},this),n=s.proxy(function(){this.collection.each(e),this.trigger("search:indexed")},this);this.listenTo(this.collection,"change",e),this.listenTo(this.collection,"add",e),this.listenTo(this.collection,"reset",n),n(),t.prototype.searchable.call(this)},remove:function(){this.$insightsChrome.find('.rogueaccesspoints select[name="rogueAccessPointsLastSeen"]').off("change"),this.rendered=!1,t.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/PastConnection",["unifi/model/Client","backbone","ubnt/backgrid","libs/moment"],function(t,e,n){"use strict";return t.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(t,e,n,i){"use strict";return n.extend({model:i,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/session"},sync:function(n,i,s){switch(s=s||{},n){case"read":s.contentType="application/json; charset=utf-8",s.type="POST",s.data=JSON.stringify(e.extend(s.data||{}))}return t.sync.call(this,n,i,s)}})}),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(t,e,n,i,s,a,r,o,l){"use strict";return t.extend({id:"pastconnections",_templateId:o,_collectionType:{name:"PastConnections",Class:r},_pageable:!0,_limitType:"all",_limitStart:null,_limitEnd:null,initialize:function(e){this.$insightsChrome=s("#insightsChrome"),t.prototype.initialize.call(this,e),this.$el.removeClass("content");var n=this;this.listenTo(this.options.app.collection("Clients"),"change:name",function(t){var e,i=n.collection.where({mac:t.get("mac")});for(e=0;e<i.length;e++)i[e].trigger("change",i[e])}),this.listenTo(this.options.app.collection("Devices"),"change:name",function(t){var e,i,s=t.get("type");for("usw"===s?e=n.collection.where({is_wired:!0,sw_mac:t.get("mac")}):"ugw"===s?e=n.collection.where({is_wired:!0,gw_mac:t.get("mac")}):"uap"===s&&(e=n.collection.where({is_wired:!1,ap_mac:t.get("mac")})),i=0;i<e.length;i++)e[i].trigger("change",e[i])})},columns:function(){var t=this;return[{name:"mac",label:a.G_InsightsNameMACAddress,editable:!1,sortValue:"name",headerCell:n.Headers.customSortHeader,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var n=t.options.app.collection("Clients"),i=n.getClientFromMac(e.get("mac"));return i||(i=e),i.name()},toRaw:function(t){return t}}}),callback:function(e){var n=t.options.app.collection("Clients"),i=n.getClientFromMac(e.get("mac"));i?i.set({blocked:e.get("blocked")},{silent:!0}):i=e,t.options.app.routers.clients.views.index.property(i)},title:"mac"},{name:"is_guest",label:a.G_UserGuest,editable:!1,cell:n.Cells.ModelCell.extend({callback:"userOrGuest"})},{name:"assoc_time",label:a.G_InsightsAssociated,editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Moment})},{name:"duration",label:a.G_Duration,editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Duration})},{name:"tx_bytes",label:a.G_Down,editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"rx_bytes",label:a.G_Up,editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"ip",label:a.G_IP,editable:!1,sortValue:"ip2long",headerCell:n.Headers.customSortHeader,cell:"string"},{name:"ap_mac",label:a.G_InsightsLastAPPort,customClass:"column-apport",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var n,i=t.app.collection("Devices");return e.get("is_wired")?e.get("sw_mac")?(n=i.getDeviceFromMac(e.get("sw_mac")))?n.name()+e.switch_port_suffix(!1):e.get("sw_mac"):e.get("gw_mac")?(n=i.getDeviceFromMac(e.get("gw_mac")))?n.name():e.get("gw_mac"):void 0:(n=e.get("ap_mac")?i.getDeviceFromMac(e.get("ap_mac")):null,n?n.name():e.get("ap_mac"))},toRaw:function(t){return t}}}),callback:function(e){var n,i=t.app.routers.devices.views.index;e.get("is_wired")?(n=i.collection.getDeviceFromMac(e.get(e.get("sw_mac")?"sw_mac":"gw_mac")),i.property(n,{port:e.get("sw_mac")?e.get("sw_port"):"lan"})):(n=i.collection.getDeviceFromMac(e.get("ap_mac")),i.property(n))}}]},render:function(){var e=this.rendered;if(e||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),t.prototype.render.call(this),!e){var n=this;this.$inputFilterType=this.$insightsChrome.find('.pastconnections input[name="table-filter-type"]').on("change",function(){var t=s(this).val();n._limitType=t,s.cookie("filterInsightsPastConnectionsType",t),n.load(!0)}),this.$insightsChrome.find('.pastconnections input[name="table-filter-type"][value="'+(s.cookie("filterInsightsPastConnectionsType")||"all")+'"]').click(),this.calendar=new l({el:"#pastconnections-datetimeNav",is7Day:!0});var i=this.calendar.getDateRange();i&&(n._limitStart=i.start,n._limitEnd=i.end,n.load(!0)),this.calendar.$el.on("change",function(t,e){e&&(n._limitStart=e.start,n._limitEnd=e.end,n.load(!0))})}},load:function(e){e=e||!this.collection,(!this.collection||e)&&this._limitStart&&this._limitEnd&&(this.collection&&this.collection.reset(),t.prototype.load.call(this,e,{data:{type:this._limitType,start:this._limitStart/1e3,end:this._limitEnd/1e3}}))},searchable:function(){var e=s.proxy(function(t){var e=this.options.app.collection("Devices").getDeviceFromMac(t.get("ap_mac"));e&&t.addSearchString("device_name",e.name());var n=this.options.app.collection("Clients").getClientFromMac(t.get("mac"));n&&t.addSearchString("alias_name",n.name())},this),n=s.proxy(function(){this.collection.each(e),this.trigger("search:indexed")},this);this.listenTo(this.collection,"change",e),this.listenTo(this.collection,"add",e),this.listenTo(this.collection,"reset",n),n(),t.prototype.searchable.call(this)},remove:function(){this.stopListening(this.options.app.collection("Clients")),this.stopListening(this.options.app.collection("Devices")),this.$insightsChrome.find('.pastconnections input[name="table-filter-type"]').off("change"),this.calendar.$el.off("change"),this.rendered=!1,t.prototype.remove.apply(this,arguments)}})}),define("unifi/model/Guest",["unifi/model/Model","backbone","ubnt/backgrid"],function(t,e,n){"use strict";return t.extend({name:function(){return this.get("name")||this.get("hostname")||this.get("mac")},authorization:function(){var t,e,i,s;switch(this.get("authorized_by")){case"none":return"None";case"password":return"Password";case"api":return"API";case"voucher":return e=this.get("voucher_code"),t="Voucher",e&&(t+="["+e+"]"),t;case"credit":return i=this.get("package"),s=this.get("amount"),t=this.get("payment_cardtype")||"Credit Card",i&&s&&(t+="("+i+","+n.Formatters.Currency.fromRaw(this)+")"),t;case"paypal":return"PayPal";default:return"None"}},extend:function(t){return this.sync("extend",this,t)},sync:function(t,n,i){switch(t){case"delete":i.contentType="application/json; charset=utf-8",i.type="POST",i.url="/api/s/"+SITE.name+"/cmd/hotspot",i.data=JSON.stringify({_id:n.id,cmd:"terminate"});break;case"extend":i.contentType="application/json; charset=utf-8",i.type="POST",i.url="/api/s/"+SITE.name+"/cmd/hotspot",i.data=JSON.stringify({_id:n.id,cmd:"extend"})}return e.sync.call(this,t,n,i)},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(t,e,n){"use strict";return t.extend({model:n,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/guest"},sync:function(t,n,i){switch(t){case"read":i.type="POST",i.data=JSON.stringify(i.data)}return e.sync.call(this,t,n,i)}})}),define("unifi/model/insights/PastGuestAuthorization",["unifi/model/Guest","backbone","ubnt/backgrid","libs/moment"],function(t){"use strict";return t.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(t,e,n,i){"use strict";return n.extend({model:i,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/authorization"},sync:function(n,i,s){switch(s=s||{},n){case"read":s.contentType="application/json; charset=utf-8",s.type="POST",s.data=JSON.stringify(e.extend(s.data||{}))}return t.sync.call(this,n,i,s)}})}),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(t,e,n,i,s,a,r,o,l){"use strict";return t.extend({id:"pastguestauthorizations",_templateId:o,_collectionType:{name:"PastGuestAuthorizations",Class:r},_pageable:!0,initialize:function(e){this.$insightsChrome=s("#insightsChrome"),t.prototype.initialize.call(this,e),this.$el.removeClass("content");var n=this;this.listenTo(this.options.app.collection("Clients"),"change:name",function(t){var e,i=n.collection.where({mac:t.get("mac")});for(e=0;e<i.length;e++)i[e].trigger("change",i[e])}),this.listenTo(this.options.app.collection("Devices"),"change:name",function(t){var e,i=n.collection.where({ap_mac:t.get("mac")});for(e=0;e<i.length;e++)i[e].trigger("change",i[e])})},columns:function(){var t=this;return[{name:"mac",label:a.G_InsightsNameMACAddress,editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var n=t.options.app.collection("Clients"),i=n.getClientFromMac(e.get("mac"));return i||(i=e),i.name()},toRaw:function(t){return t}}}),callback:function(e){var n=t.options.app.collection("Clients"),i=n.getClientFromMac(e.get("mac"));i?i.set({blocked:e.get("blocked")},{silent:!0}):i=e,t.options.app.routers.clients.views.index.property(i)},title:"mac"},{name:"package",label:a.G_Package,editable:!1,cell:"string"},{name:"amount",label:a.G_Amount,editable:!1,cell:n.Cells.ComplexCell.extend({formatter:n.Formatters.Currency})},{name:"authorized_by",label:a.G_InsightsAuthorizedBy,editable:!1,cell:n.Cells.ModelCell.extend({callback:"authorization"})},{name:"start",label:a.G_Start,editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Moment})},{name:"duration",label:a.G_Duration,editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Duration})},{name:"tx_bytes",label:a.G_Down,editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"rx_bytes",label:a.G_Up,editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"ip",label:a.G_IP,editable:!1,cell:"string"},{name:"ap_mac",label:a.G_InsightsLastAP,editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var n=t.options.app.collection("Devices"),i=n.getDeviceFromMac(e.get("ap_mac"));return i||(i=e),i.name()},toRaw:function(t){return t}}}),callback:function(e){var n=t.options.app.collection("Devices"),i=n.getDeviceFromMac(e.get("ap_mac"));i||(i=e),t.options.app.routers.devices.views.index.property(i)}}]},render:function(){var e=this.rendered;if(e||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),t.prototype.render.call(this),!e){var n=this;this.calendar=new l({el:"#pastguestauthorizations-datetimeNav",is7Day:!0});var i=this.calendar.getDateRange();i&&(n._limitStart=i.start,n._limitEnd=i.end,n.load(!0)),this.calendar.$el.on("change",function(t,e){e&&(n._limitStart=e.start,n._limitEnd=e.end,n.load(!0))})}},load:function(e){e=e||!this.collection,(!this.collection||e)&&this._limitStart&&this._limitEnd&&(this.collection&&this.collection.reset(),t.prototype.load.call(this,e,{data:{start:this._limitStart/1e3,end:this._limitEnd/1e3}}))},searchable:function(){var e=s.proxy(function(t){var e=this.options.app.collection("Devices").getDeviceFromMac(t.get("ap_mac"));e&&t.addSearchString("device_name",e.name());var n=this.options.app.collection("Clients").getClientFromMac(t.get("mac"));n&&t.addSearchString("alias_name",n.name())},this),n=s.proxy(function(){this.collection.each(e),this.trigger("search:indexed")},this);this.listenTo(this.collection,"change",e),this.listenTo(this.collection,"add",e),this.listenTo(this.collection,"reset",n),n(),t.prototype.searchable.call(this)},remove:function(){this.stopListening(this.options.app.collection("Clients")),this.stopListening(this.options.app.collection("Devices")),this.calendar.$el.off("change"),this.rendered=!1,t.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/SwitchStats",["underscore","unifi/model/PortModel","ubnt/backgrid","msg/Msg"],function(t,e,n,i){"use strict";return e.extend({initialize:function(){this.on("change:device change:port_idx",t.bind(this.generateId,this))},speed:function(){if(this.get("up")){var t=this.get("speed");return 1e3>t?t+="M":(t/=1e3,t+="G"),t}return""},linkUsage:function(t){var e,n;return this.get("up")?(e=this.get("tx"===t?"tx_bytes-r":"rx"===t?"rx_bytes-r":"bytes-r"),n=8*e*100/(1024*this.get("speed")*1024),n.toFixed(2)):0},opMode:function(){return this.get("aggregated_by")?"aggregate":this.get("op_mode")||"switch"},opModeText:function(){var t=this.opMode();return"switch"===t?i.G_PropertiesSwitching:"aggregate"===t?i.G_PropertiesAggregate:"mirror"===t?i.G_PropertiesMirroring:""},poeMode:function(){return this.get("port_poe")?"switch"!==this.get("op_mode")||this.get("masked")?"":this.get("poe_mode")||"off":""},poeModeText:function(){var t=this.poeMode();return"auto"===t?i.G_PropertiesPoEModePoEPlus:"pasv24"===t?i.G_PropertiesPoEModePassive:i.G_InsightsPoeDisabled},isPDDetected:function(){return"auto"===this.poeMode()&&this.get("poe_enable")},poeDetection:function(){var t=this.poeMode();return"auto"===t?this.get("poe_enable")?this.get("poe_good")?i.G_InsightsPoeGood:i.G_InsightsPoeCpdHigh:i.G_InsightsPoeNotDetected:"pasv24"===t?i.G_InsightsPoePassive:""},isPoeEnabled:function(){return"off"!==this.poeMode()&&""!==this.poeMode()},isPassivePoe:function(){return"Passive"==this.poeDetection()},isPoePowerOn:function(){return this.isPassivePoe()||this.isPDDetected()},poeVoltage:function(){var t=this.poeMode();return this.isPDDetected()||"pasv24"===t?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(t,e,n,i){"use strict";return n.extend({model:i,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(t,e,n,i,s,a,r,o,l,c){"use strict";return t.extend({id:"switchstats",_templateId:c,_collectionType:{name:"SwitchStats",Class:l},_pageable:!0,initialize:function(e){this.$insightsChrome=a("#insightsChrome"),t.prototype.initialize.call(this,e),this.$el.removeClass("content")},load:function(){"resolved"!==this._loaded.state()&&(this.collection=new l,this.devices=this.app.collection("Devices"),this.devices&&s.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(t){t.get("type")===t.typeMap["switch"]&&(this.listenTo(t,"syncPortTable",a.proxy(function(){this.resetSwitchStats(t)},this)),this.resetSwitchStats(t))},onSwitchRemove:function(t){t.get("type")===t.typeMap["switch"]&&(this.collection.remove(this.collection.where({device:t.get("mac")})),this.stopListening(t,"syncPortTable"))},resetSwitchStats:function(t){var e=this.collection.where({device:t.get("mac")});t.collections.portTable.each(function(t){var n=s.find(e,function(e){return t.get("port_idx")===e.get("port_idx")});n?n.set(t.attributes):this.collection.add(t.toJSON())},this)},dependencies:function(){var t={PortConf:o},e=[],n={},i=this;s.each(t,function(t,i){e.push(n[i]=a.Deferred())},this),a.when.apply(a,e).then(function(){i._dependencies.resolve()},function(){i._dependencies.reject()}),s.each(t,function(t,e){this.app.collection(e,{fetch:{reload:!1,deferred:n[e]}},t)},this)},columns:function(){var t=this;return[{name:"diagram",customClass:"column-diagram",editable:!1,sortable:!1,headerCell:n.Headers.emptyHeader,cell:n.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(t){var e=a('<div class="properties"<div class="properties"><div class="diagram switch port24"><div class="port port-'+t.id+" "+t.diagramClasses()+'" data-port="'+t.id+'"><div class="status"><div class="poe"></div><div class="mirror"></div><div class="block"></div></div></div></div></div>');return e.find(".port").attr("title","Port "+t.get("port_idx")).tooltip({show:!1,hide:!1,track:!0,content:function(){return t.diagramTooltip()}}),e},toRaw:function(t){return t}}}),callback:this.rowView},{name:"device",label:r.G_InsightsSwitch,customClass:"column-device",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(e){var n=t.app.collection("Devices"),i=n.getDeviceFromMac(e.get("device"));return i?i.name():e.get("device")},toRaw:function(t){return t}}}),callback:this.rowView},{name:"port_idx",label:r.G_Port,customClass:"column-port_idx",editable:!1,cell:"integer"},{name:"name",label:r.G_Name,customClass:"column-name",editable:!1,cell:"string"},{name:"poe_summary",label:r.G_PropertiesPoE,customClass:"column-poe_summary",editable:!1,sortable:!1,headerCell:n.Headers.noSortHeader,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:a.proxy(function(t){var e=t.poeModeText();return"auto"==t.get("poe_mode")&&t.get("poe_enable")?t.get("poe_power")+"w":e},this),toRaw:function(t){return t}}})},{name:"op_mode",label:r.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:r.G_PropertiesNetworksVLANs,customClass:"column-portconf_id",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:a.proxy(function(e){if(e.get("aggregated_by"))return r.G_PropertiesAggregatedByPort+" "+e.get("aggregated_by");if("mirror"==e.get("op_mode"))return r.G_PropertiesMirroringPort+" "+e.get("mirror_port_idx");var n=e.get("portconf_id");if(n){var i=t.app.collection("PortConf").get(n);if(i)return i.get("name")}},this),toRaw:function(t){return t}}})},{name:"speed",label:r.G_InsightsNetworkLinkStatus,customClass:"column-speed",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:function(t){if(t.get("up")){var e=t.speed();return e+=" ",e+=t.get("full_duplex")?r.G_PropertiesFullDuplexAbbrv:r.G_PropertiesHalfDuplexAbbrv,t.get("is_uplink")&&(e+=" ("+r.G_PropertiesUplink+")"),e}return""},toRaw:function(t){return t}}})},{name:"stp_state",label:r.G_InsightsSTP,customClass:"column-stp_state",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:a.proxy(function(t){if(t.get("up")){if("discarding"===t.get("stp_state"))return r.G_InsightsSTPDiscarding;if("forwarding"===t.get("stp_state"))return r.G_InsightsSTPForwarding;if("disabled"===t.get("stp_state"))return r.G_InsightsSTPDisabled}return""},this),toRaw:function(t){return t}}})},{name:"tx_bytes",label:r.G_DevicesTX,customClass:"column-tx_bytes-abbrv",editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"rx_bytes",label:r.G_DevicesRX,customClass:"column-rx_bytes-abbrv",editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"tx_bytes-r",label:r.G_PropertiesTXRate,customClass:"column-tx_bytes-r",editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.BitsPerSecond})},{name:"rx_bytes-r",label:r.G_PropertiesRXRate,customClass:"column-rx_bytes-r",editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.BitsPerSecond})},{name:"bytes-r",label:r.G_Activity,customClass:"column-bytes-r",editable:!1,cell:n.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:a.proxy(function(t){var e=t.linkUsage("tx"),i=t.linkUsage("rx"),r=a('<div class="grid green-cells quarter"></div>'),o=a('<div class="grid green-cells quarter"></div>'),l=a('<div class="grid-wrapper"></div>'),c=[90,80,70,60,50,40,30,20,10,0];return s.each(c,function(t){e>t&&r.append(a('<span class="quarter red"></span>')),i>t&&o.append(a('<span class="quarter blue"></span>'))}),l.append(r.attr("data-value",e).attr("title","Tx: "+n.Formatters.BitsPerSecond.fromRaw(t.get("tx_bytes-r")))),l.append(o.attr("data-value",i).attr("title","Rx: "+n.Formatters.BitsPerSecond.fromRaw(t.get("rx_bytes-r")))),l},this),toRaw:a.proxy(function(t){return t.linkUsage()},this)}})},{name:"poe_mode",label:r.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:r.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:r.G_InsightsPoeClass,customClass:"column-poe_class",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:a.proxy(function(t){return t.isPDDetected()?t.get("poe_class"):""},this),toRaw:function(t){return t}}})},{name:"poe_power",label:r.G_InsightsPoePower,customClass:"column-poe_power",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:a.proxy(function(t){return t.isPDDetected()?t.get("poe_power"):""},this),toRaw:function(t){return t}}})},{name:"poe_voltage",label:r.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:r.G_InsightsPoeCurrent,customClass:"column-poe_current",editable:!1,cell:n.Cells.ComplexCell.extend({formatter:{fromRaw:a.proxy(function(t){return t.isPDDetected()?t.get("poe_current"):""},this),toRaw:function(t){return t}}})},{name:"tx_bytes",label:r.G_InsightsCountersTxBytes,customClass:"column-tx_bytes",editable:!1,cell:"integer"},{name:"tx_packets",label:r.G_InsightsCountersTxFrames,customClass:"column-tx_packets",editable:!1,cell:"integer"},{name:"tx_multicast",label:r.G_InsightsCountersTxMulticast,customClass:"column-tx_multicast",editable:!1,cell:"integer"},{name:"tx_broadcast",label:r.G_InsightsCountersTxBroadcast,customClass:"column-tx_broadcast",editable:!1,cell:"integer"},{name:"tx_errors",label:r.G_InsightsCountersTxErrors,customClass:"column-tx_errors",editable:!1,cell:"integer"},{name:"rx_bytes",label:r.G_InsightsCountersRxBytes,customClass:"column-rx_bytes",editable:!1,cell:"integer"},{name:"rx_packets",label:r.G_InsightsCountersRxFrames,customClass:"column-rx_packets",editable:!1,cell:"integer"},{name:"rx_multicast",label:r.G_InsightsCountersRxMulticast,customClass:"column-rx_multicast",editable:!1,cell:"integer"},{name:"rx_broadcast",label:r.G_InsightsCountersRxBroadcast,customClass:"column-rx_broadcast",editable:!1,cell:"integer"},{name:"rx_errors",label:r.G_InsightsCountersRxErrors,customClass:"column-rx_errors",editable:!1,cell:"integer"},{name:"_id",label:r.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(t){return!t.get("masked")
}},restart:{icon:"ubnt-icon-rotate",text:r.G_InsightsPowerCycle,callback:this.rowPowerCycle,requiresAdminPrivilege:!0,buttonClasses:"narrow",render:function(t){return t.get("poe_enable")}},clearCounters:{icon:"ubnt-icon-trash",text:r.G_InsightsClear,callback:this.rowClearCounters,requiresAdminPrivilege:!0,buttonClasses:"narrow",render:function(){return!0}}}})}]},render:function(){var e=this.rendered;e||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),t.prototype.render.call(this)},grid:function(){t.prototype.grid.call(this);var e=this.grids.content,n=this.$insightsChrome.find(".buttonset.switch-subtab-filters"),i=n.find("input[name=switch-subtab-filter]"),r=[];this.$switchFilter=this.$insightsChrome.find(".switchstats .switch-filter select"),this.$switchFilter.on("change",a.proxy(function(t){var n=a(t.target).val();n?(e.setFilter("device",n,1),e.$el.addClass("single-switch")):(e.removeFilter("device"),e.$el.removeClass("single-switch")),a.cookie("filterInsightsSwitchStatsSwitch",n)},this)),this.listenTo(this,"device_change",s.debounce(this.setupSwitchFilter,250)),this.setupSwitchFilter(),this.$switchFilter.val(a.cookie("filterInsightsSwitchStatsSwitch")||"overview").selectmenu("close").trigger("change"),this.$poeFilter=this.$insightsChrome.find(".switchstats .poe-filter select");var o=this.$poeFilter;this.$poeFilter.on("change",a.proxy(function(t){var n=a(t.target).val();e.removeFilter("isPoeEnabled"),e.removeFilter("isPassivePoe"),e.removeFilter("isPoePowerOn"),"enabled"==n?e.setFilter("isPoeEnabled",!0,1):"powerOn"==n?e.setFilter("isPoePowerOn",!0,1):"passive"==n?e.setFilter("isPassivePoe",!0,1):"disabled"==n&&e.setFilter("isPoeEnabled",!1,1),a.cookie("filterInsightsSwitchStatsPoeMode",n)},this)),this.setupPoeFilter(),this.$poeFilter.val(a.cookie("filterInsightsSwitchStatsPoeMode")||"").selectmenu("close").trigger("change"),this.$clearCounters=this.$insightsChrome.find(".switchstats .clear-counters select");var l=this.$clearCounters;this.$clearCounters.on("change",a.proxy(function(t){var e=a(t.target),n=e.val(),i=this.app.collection("Devices"),s=n&&"all"!=n?i.getDeviceFromMac(n):null;n&&(this.clearCounters(s),l.val(l.find("option:first").val()).selectmenu("close"))},this)),this.listenTo(this,"device_change",s.debounce(this.setupSwitchClearCounters,250)),this.setupSwitchClearCounters(),this.$linkStatusFilter=this.$insightsChrome.find(".switchstats .network-link-filter select"),this.$linkStatusFilter.on("change",a.proxy(function(t){var n=a(t.target).val();"connected"==n?e.setFilter("up",!0,1):"disconnected"==n?e.setFilter("up",!0,-1):e.removeFilter("up"),a.cookie("filterInsightsSwitchStatsLinkStatus",n)},this)),this.setupLinkFilter(),this.$linkStatusFilter.val(a.cookie("filterInsightsSwitchStatsLinkStatus")||"all").selectmenu("close").trigger("change"),s.each(i,function(t){r.push(t.value)}),i.filter('[value="'+(a.cookie("filterInsightsSwitchStatsSubtab")||"overview")+'"]').click(),i.on("change",function(){var t=a(this),n=t.val();o.closest(".ui-selectmenu-parent").hide(),l.closest(".ui-selectmenu-parent").hide(),"poe"===n?(e.setFilter("port_poe",!0,1),o.closest(".ui-selectmenu-parent").show()):("counters"===n&&l.closest(".ui-selectmenu-parent").show(),e.removeFilter("port_poe"),o.val("").selectmenu("close").trigger("change")),e.$el.removeClass(r.join(" ")).addClass(n||"overview"),a.cookie("filterInsightsSwitchStatsSubtab",n)}).filter(":checked").trigger("change")},searchable:function(){var e=this.app.collection("Devices"),n=a.proxy(function(t){t.addSearchString("device-name",e.getDeviceFromMac(t.get("device")).name())},this),i=a.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",i),i(),t.prototype.searchable.call(this)},setupLinkFilter:function(){var t=this.$linkStatusFilter.find("options:selected").val();this.$linkStatusFilter.empty(),this.$linkStatusFilter.append(a('<option value="all"></option>').text(r.G_All)),this.$linkStatusFilter.append(a('<option value="connected"></option>').text(r.G_APConnected)),this.$linkStatusFilter.append(a('<option value="disconnected"></option>').text(r.G_APDisconnected)),this.$linkStatusFilter.find('option[value="'+(t||"")+'"]').prop("selected",!0),this.$linkStatusFilter.selectmenu("refresh")},setupSwitchFilter:function(){var t=this.$switchFilter.find("option:selected").val();this.$switchFilter.empty(),this.$switchFilter.append(a('<option value=""></option>').text(r.G_All));var e=this.devices.where({type:this.devices.typeMap["switch"],adopted:!0}).sort(function(t,e){return t.name()>e.name()?1:t.name()<e.name()?-1:0});this.devices&&s.each(e,a.proxy(function(t){this.$switchFilter.append(a("<option />").attr("value",t.get("mac")).text(t.name()))},this)),this.$switchFilter.find('option[value="'+(t||"")+'"]').prop("selected",!0),this.$switchFilter.selectmenu("refresh")},setupPoeFilter:function(){var t=this.$poeFilter.find("option:selected").val(),e={enabled:r.G_InsightsPoeEnabled,powerOn:r.G_InsightsPoePowerOn,passive:r.G_InsightsPoePassive,disabled:r.G_InsightsPoeDisabled},n=this.$poeFilter;this.$poeFilter.empty(),this.$poeFilter.append(a('<option value=""></option>').text(r.G_All)),s.each(e,function(t,e){n.append(a('<option value="'+e+'"></option>').text(t))}),this.$poeFilter.find('option[value="'+(t||"")+'"]').prop("selected",!0),this.$poeFilter.selectmenu("refresh"),this.$poeFilter.closest(".ui-selectmenu-parent").css({position:"static",left:0})},setupSwitchClearCounters:function(){var t=this.$clearCounters.find("option:selected").val();this.$clearCounters.empty(),this.$clearCounters.append(a('<option value="none"></option>')),this.$clearCounters.append(a('<option value="all"></option>').text(r.G_All)),this.devices&&s.each(this.devices.where({type:this.devices.typeMap["switch"]}),a.proxy(function(t){t.get("adopted")&&this.$clearCounters.append(a("<option />").attr("value",t.get("mac")).text(t.name()))},this)),this.$clearCounters.find('option[value="'+(t||"")+'"]').prop("selected",!0),this.$clearCounters.selectmenu("refresh"),this.$clearCounters.closest(".ui-selectmenu-parent").css({position:"static",left:0})},rowEdit:function(t){this.rowView(t,!0)},rowView:function(t,e){var n=this.app.collection("Devices"),i=n.getDeviceFromMac(t.get("device")),s=this.app.routers.devices.views.index.property(i);s.statsPortForm(t,e)},clearAllCounters:function(){this.app.collection("Devices");a.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(){this.devices&&s.each(this.devices.where({type:this.devices.typeMap["switch"]}),a.proxy(function(t){t.fetch()},this))},error:function(t){this.app.views.app.flash("error","Error",r.apiError(t))}})},clearCounters:function(t,e){var n=this.app.collection("Devices"),s=t?n.getDeviceFromMac(t.get("mac")):void 0,o=t?t.get("mac"):void 0,l=e?e:void 0,c={mac:o,port_idx:l},d=this.clearAllCounters,h=r.G_ConfirmClearAllCounters;e?(d=s.clearPortCounters,h=r.localize(r.G_ConfirmClearPortCounters,t.name(),e)):t&&(d=s.clearSwitchCounters,h=r.localize(r.G_ConfirmClearSwitchCounters,t.name())),(new i).show(h,a.proxy(function(){e||t?d.call(s,{data:c,success:function(){s&&s.fetch()},error:a.proxy(function(t){this.app.views.app.flash("error","Error",r.apiError(t))},this)}):d.call(this)},this))},rowClearCounters:function(t){var e=this.app.collection("Devices"),n=e.getDeviceFromMac(t.get("device")),i=t.get("port_idx");this.clearCounters(n,i)},rowPowerCycle:function(t){var e=this.app.collection("Devices"),n=e.getDeviceFromMac(t.get("device"));(new i).show(r.localize(r.N_ConfirmPowerCyclePort,t.get("port_idx")),a.proxy(function(){n.powerCyclePort({data:{port_idx:t.get("port_idx")},success:function(){n.fetch()},error:a.proxy(function(t){this.app.views.app.flash("error","Error",r.apiError(t))},this)})},this))},remove:function(){this.stopListening(this.devices),this.devices&&s.each(this.devices.where({type:this.devices.typeMap["switch"]}),function(t){this.stopListening(t)},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,t.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/RemoteUserVPNStats",["jquery","underscore","unifi/model/Model","ubnt/backgrid","msg/Msg","libs/moment"],function(t,e,n,i){"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 t.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(t){return t=t||this.get("uptime"),t>0?i.Formatters.Duration.fromRaw(t||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(t,e,n,i){"use strict";return n.extend({model:i,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/remoteuservpn"},sync:function(n,i,s){switch(s=s||{},n){case"read":s.contentType="application/json; charset=utf-8",s.type="POST",s.data=JSON.stringify(e.extend(s.data||{}))}return t.sync.call(this,n,i,s)}})}),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","ubnt/view/dialogs/ConfirmDialogView"],function(t,e,n,i,s,a,r,o,l){"use strict";return t.extend({id:"remoteuservpnstats",_templateId:o,_collectionType:{name:"RemoteUserVPNStats",Class:r},_pageable:!0,initialize:function(e){this.$insightsChrome=s("#insightsChrome"),t.prototype.initialize.call(this,e),this.$el.removeClass("content")},columns:function(){return[{name:"interface",label:a.G_RemoteUserVPNInterface,editable:!1,cell:"string"},{name:"remote_ip",label:a.G_RemoteUserVPNRemoteIP,editable:!1,sortValue:"remoteip2long",headerCell:n.Headers.customSortHeader,cell:"string"},{name:"user",label:a.G_RemoteUserVPNUser,editable:!1,cell:"string"},{name:"rx_packets",label:a.G_RemoteUserVPNRxPackets,editable:!1,cell:"integer"},{name:"rx_bytes",label:a.G_RemoteUserVPNRxBytes,editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"tx_packets",label:a.G_RemoteUserVPNTxPackets,editable:!1,cell:"integer"},{name:"tx_bytes",label:a.G_RemoteUserVPNTxBytes,editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"uptime",label:a.G_Uptime,editable:!1,cell:n.Cells.ModelCell.extend({callback:"uptime"})},{name:"_id",label:a.G_Actions,customClass:"column-actions",editable:!1,sortable:!1,headerCell:n.Headers.noSortHeader,cell:n.Cells.ActionsCell.extend({actions:{terminate:{icon:"ubnt-icon-unlink",requiresAdminPrivilege:!0,buttonClasses:"narrow",callback:this.termiteRemoteInterface,render:function(t){return!t.get("masked")}}}})}]},render:function(){var e=this.rendered;e||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),t.prototype.render.call(this)},termiteRemoteInterface:function(t){var e=this;(new l).show(a.N_ConfirmTerminateRemoteUserVPNConnection,function(){s.ajax({contentType:"application/json; charset=utf-8",url:"/api/s/"+SITE.name+"/cmd/devmgr",type:"POST",data:JSON.stringify({cmd:"terminate-remote-user-vpn","interface":t.get("interface"),user:t.get("user"),remote_ip:t.get("remote_ip")}),success:function(){var n=e.grids.content.collection.where({"interface":t.get("interface"),user:t.get("user"),remote_ip:t.get("remote_ip")});e.grids.content.removeRow(n)},error:function(t){this.app.views.app.flash("error","Error",a.apiError(t))}})})},searchable:function(){t.prototype.searchable.call(this)},remove:function(){this.rendered=!1,t.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/DynamicDNSStat",["unifi/model/DynamicDNS","jquery","backbone","msg/Msg","ubnt/backgrid","libs/moment"],function(t,e,n,i,s){"use strict";return t.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 i.G_PropertiesDDNSStatusGood;case"failed":case"noconnect":return i.G_PropertiesDDNSStatusFailed;case"updating":return i.G_PropertiesDDNSStatusUpdating;default:return i.G_Unknown}},ip2long:function(){return e.ip2long(this.get("ip"))},lastUpdated:function(){var t=this.get("last_updated");return t>0?s.Formatters.Duration.fromRaw(t||0):""}})}),define("unifi/collection/insights/DynamicDNSStat",["backbone","underscore","unifi/collection/Collection","unifi/model/insights/DynamicDNSStat"],function(t,e,n,i){"use strict";return n.extend({model:i,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/dynamicdns"},sync:function(n,i,s){switch(s=s||{},n){case"read":s.contentType="application/json; charset=utf-8",s.type="POST",s.data=JSON.stringify(e.extend(s.data||{}))}return t.sync.call(this,n,i,s)}})}),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(t,e,n,i,s,a,r,o){"use strict";return t.extend({id:"dynamicdnsstats",_templateId:o,_collectionType:{name:"DynamicDNSStat",Class:r},_pageable:!0,initialize:function(e){this.$insightsChrome=s("#insightsChrome"),t.prototype.initialize.call(this,e),this.$el.removeClass("content")},columns:function(){return[{name:"service",label:a.G_PropertiesDDNSService,editable:!1,cell:"string"},{name:"status",label:a.G_PropertiesDDNSStatus,editable:!1,cell:n.Cells.ModelCell.extend({callback:"ddnsStatus"})},{name:"host_name",label:a.G_PropertiesDDNSHostname,editable:!1,cell:"string"},{name:"login",label:a.G_PropertiesDDNSUsername,editable:!1,cell:"string"},{name:"server",label:a.G_PropertiesDDNSServer,editable:!1,cell:"string"},{name:"ip",label:a.G_PropertiesDDNSIp,editable:!1,sortValue:"ip2long",headerCell:n.Headers.customSortHeader,cell:"string"},{name:"last_updated",label:a.G_PropertiesDDNSLastUpdated,editable:!1,cell:n.Cells.ModelCell.extend({callback:"lastUpdated"})},{name:"_id",label:a.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(t){return!t.get("masked")}}}})}]},rowEdit:function(t){var e,n=this.app.collection("Devices"),i=n.where({type:"ugw",site_id:SITE.id});i.length>0&&(e=this.app.routers.devices.views.index.property(i[0]),e.statsDynamicDNSForm(t,!0))},render:function(){var e=this.rendered;e||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),t.prototype.render.call(this)},searchable:function(){t.prototype.searchable.call(this)},remove:function(){this.rendered=!1,t.prototype.remove.apply(this,arguments)}})}),define("unifi/model/insights/PortForwardStats",["jquery","underscore","unifi/model/PortForward","ubnt/backgrid","msg/Msg","libs/moment"],function(t,e,n,i,s){"use strict";return n.extend({toSearch:function(){return{name:this.name(),src:this.src(),fwd:this.fwd(),fwd_port:this.fwd_port(),proto:this.proto()}},name:function(){return this.get("name")},src:function(){return this.get("src")},fwd:function(){return this.get("fwd")},ip2long:function(){return t.ip2long(this.get("fwd"))},sort_port:function(t,e){for(var n=t.toString().replace("-",",").split(","),i=[],s=0;s<n.length;s++)i.push(parseInt(n[s],10)||0);if(i.length>0){if(i.sort(function(t,e){return t-e}),"ascending"===e)return i[0];if("descending"===e)return i[i.length-1]}return 0},fwd_port:function(){return this.get("fwd_port")},proto:function(){return this.get("proto")},protoText:function(){var t=this.proto();return"tcp_udp"===t?s.G_Both:"tcp"===t?s.G_PropertiesTcp:"udp"===t?s.G_PropertiesUdp:t},srcText:function(){var t=this.src();return"any"===t?s.G_PropertiesPortFwdSrcAnywhere:t},leaseDuration:function(){var t=this.get("lease_duration");return t?i.Formatters.Duration.fromRaw(t||0):""}})}),define("unifi/collection/insights/PortForwardStats",["backbone","underscore","unifi/collection/Collection","unifi/model/insights/PortForwardStats"],function(t,e,n,i){"use strict";return n.extend({model:i,bySite:!0,url:function(){return"/api/s/"+SITE.name+"/stat/portforward"},sync:function(n,i,s){switch(s=s||{},n){case"read":s.contentType="application/json; charset=utf-8",s.type="POST",s.data=JSON.stringify(e.extend(s.data||{}))}return t.sync.call(this,n,i,s)}})}),define("text!includes/insights/PortForwardStatsTemplate.html",[],function(){return'<div class="data-table untitled">\n    <div class="loading"><span><%- msg.N_Loading %></span></div>\n</div>'}),define("unifi/view/insights/PortForwardStatsView",["unifi/view/app/ListContentView","libs/backgrid","ubnt/backgrid","underscore","jquery","msg/Msg","unifi/collection/insights/PortForwardStats","text!includes/insights/PortForwardStatsTemplate.html"],function(t,e,n,i,s,a,r,o){"use strict";return t.extend({id:"portforwardstats",_templateId:o,_collectionType:{name:"PortForwardStats",Class:r},_pageable:!0,initialize:function(e){this.$insightsChrome=s("#insightsChrome"),t.prototype.initialize.call(this,e),this.$el.removeClass("content")},columns:function(){return[{name:"name",label:a.G_PortForwardName,customClass:"column-name",editable:!1,cell:"string"},{name:"src",label:a.G_PortForwardSource,customClass:"column-src",editable:!1,cell:n.Cells.ModelCell.extend({callback:"srcText"})},{name:"proto",label:a.G_PortForwardProtocol,customClass:"column-proto",editable:!1,cell:n.Cells.ModelCell.extend({callback:"protoText"})},{name:"dst_port",label:a.G_PortForwardDestinationPort,customClass:"column-dst_port",editable:!1,sortValue:s.proxy(function(t,e){return t.sort_port(t.get("dst_port"),e)},this),headerCell:n.Headers.customSortHeader,cell:"string"},{name:"fwd",label:a.G_PortForwardDestIp,customClass:"column-fwd",editable:!1,sortValue:"ip2long",headerCell:n.Headers.customSortHeader,cell:"string"},{name:"fwd_port",label:a.G_PortForwardDestPort,customClass:"column-fwd_port",editable:!1,sortValue:s.proxy(function(t,e){return t.sort_port(t.get("fwd_port"),e)},this),headerCell:n.Headers.customSortHeader,cell:"string"},{name:"rx_packets",label:a.G_PortForwardUpPkts,customClass:"column-rx_packets",editable:!1,cell:"integer"},{name:"rx_bytes",label:a.G_PortForwardUpBytes,customClass:"column-rx_bytes",editable:!1,cell:e.StringCell.extend({formatter:n.Formatters.Bytes})},{name:"lease_duration",label:a.G_PortForwardLeaseDuration,customClass:"column-duration",editable:!1,cell:n.Cells.ModelCell.extend({callback:"leaseDuration"})},{name:"_id",label:a.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(t){return!t.get("is_upnp")}}}})}]},rowEdit:function(t){var e,n=this.app.collection("Devices"),i=n.where({type:"ugw",site_id:SITE.id});i.length>0&&(e=this.app.routers.devices.views.index.property(i[0]),e.statsPortForwardForm(t,!0))},render:function(){var e=this.rendered;e||(this.$pageSize=this.$insightsChrome.find("select[name=items-per-page]")),t.prototype.render.call(this)},grid:function(){t.prototype.grid.call(this);var e=this.grids.content,n=this.$insightsChrome.find(".buttonset.portforward-subtab-filters"),a=n.find("input[name=portforward-subtab-filter]"),r=[];i.each(a,function(t){r.push(t.value)}),a.on("change",function(){var t=s(this),n=t.val();e.removeFilter("is_upnp"),"upnp"===n?e.setFilter("is_upnp",!0,1):"user_defined"===n&&e.setFilter("is_upnp",!0,-1),e.$el.removeClass(r.join(" ")).addClass(n||"all"),s.cookie("filterInsightsPortForwardStatsSubtab",n)}).filter(":checked").trigger("change"),a.filter('[value="'+(s.cookie("filterInsightsPortForwardStatsSubtab")||"all")+'"]').click()},searchable:function(){t.prototype.searchable.call(this)},remove:function(){this.rendered=!1,t.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","unifi/view/insights/PortForwardStatsView"],function(t,e,n,i,s,a,r,o,l,c){"use strict";return t.extend({_fullyQualifiedName:"UNIFI.Routers.Insights",_associatedViews:{Chrome:e,Knownclients:n,Rogueaccesspoints:i,Pastconnections:s,Pastguestauthorizations:a,Switchstats:r,Remoteuservpnstats:o,Dynamicdnsstats:l,Portforwardstats:c},routes:{insights:"index","insights/knownclients":"knownclients","insights/rogueaccesspoints":"rogueaccesspoints","insights/pastconnections":"pastconnections","insights/pastguestauthorizations":"pastguestauthorizations","insights/switchstats":"switchstats","insights/remoteuservpnstats":"remoteuservpnstats","insights/dynamicdnsstats":"dynamicdnsstats","insights/portforwardstats":"portforwardstats"},initialize:function(e){t.prototype.initialize.call(this,e),this.on("route",function(t){"index"!=t&&this.views.chrome&&this.views.chrome.navigate(t)})},_render:function(e){t.prototype._render.call(this,"chrome"),t.prototype._render.call(this,e,this.views.chrome.$content),this.views.chrome._contentView=this.views[e]},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")},portforwardstats:function(){this._render("portforwardstats")}})}),define("unifi/view/support/ChatView",["backbone","underscore","msg/Msg","jquery"],function(t,e,n,i){"use strict";return t.View.extend({initialize:function(){e.bindAll(this),this.num_agents=0,i.getJSON("https://ubnt.zendesk.com/node/ubnt/v2/availability/?callback=?",this.render)},render:function(t){var e=n.E_NoAgentsAvailable;this.num_agents=t&&t.online&&t.online>0?t.online:0,this.$link=this.$(".option-header-link").on("click",this.onLiveChatClick),this.$subtitle=this.$(".subtitle"),this.num_agents&&(e=n.G_AgentsAvailable,this.$link.removeClass("disabled")),this.$subtitle.text(e)},onLiveChatClick:function(){if(this.num_agents){var t=this.options.cloudUser.get("community_id")||this.options.cloudUser.get("name"),e=this.options.cloudUser.get("email")||"",n="";window.open("https://ubnt.zendesk.com/chat?dropboxID=20114087&user[name]="+t+"&user[email]="+e+"&user[subject]="+n+"]")}return!1},remove:function(){this.$(".option-header-link").off("click",this.onLiveChatClick),t.View.prototype.remove.apply(this,arguments)}})}),define("unifi/view/support/RequestFormView",["backbone","underscore","jquery"],function(t,e,n){"use strict";return t.View.extend({initialize:function(){e.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 t,e=this;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(t){var e=n.trim(t.val());return e.length>5?(t.removeClass("error"),!0):(t.addClass("error"),!1)},remove:function(){this.$el.off("submit",this.onSubmitHandler),t.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(t,e,n,i,s,a,r,o){"use strict";return t.extend({id:"supportIndex",initialize:function(n){t.prototype.initialize.call(this,n),this.template=e.template(o),this.render()},render:function(){t.prototype.render.call(this);!this.rendered&&(this.rendered=!0)&&(this.$el.html(this.template({msg:r})),this.supportRequest=new i({el:"#frmSupportRequest"}),this.supportChat=new s({el:"#supportChat",cloudUser:this.options.app.views.app.options.cloudUser}))},remove:function(){this.rendered=!1,t.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(t,e,n,i){"use strict";return t.extend({_fullyQualifiedName:"UNIFI.Routers.Support",_associatedViews:{Chat:e,Index:n,Request:i},routes:{support:"index"}})}),define("unifi/view/app/SearchableMixin",["jquery","underscore"],function(t,e){"use strict";return{searchable:function(){this._initializedCollectionSearch=!1,this._runningCollectionSearch=!1,this._completedCollectionSearch=!1,this._searchEnabled=!1,this.$search.one("focus",t.proxy(function(){this._initializedCollectionSearch=!0,this._enableSearch()},this)),this.$search.on("focus",t.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",t.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,i,s){i=t.trim(i||this.$search.val()),i&&this._runningCollectionSearch?!this._delayedFilter&&(this._delayedFilter=!0)&&this.listenToOnce(this,"search:indexed",t.proxy(function(){e.each(this.grids,function(t){i?t.setFilter(null,i,this._filterMinimum,!1,s):t.removeFilter(null)},this),this._delayedFilter=!1},this)):e.each(this.grids,function(t){i?t.setFilter(null,i,this._filterMinimum,!1,s):t.removeFilter(null)},this)},_enableSearch:function(){this._initializedCollectionSearch&&(this._initializedCollectionSearch=!0,this._searchEnabled=!0,this._addSearchListeners(),t.trim(this.$search.val())&&(this._completedCollectionSearch||(this._prepareCollectionSearch(),this.filter(null,null,!0))))},_disableSearch:function(){this._initializedCollectionSearch&&(this._searchEnabled=!1,this._removeSearchListeners())},_reconcileSearch:e.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(){throw new Error("_prepareModelSearch must be overriden")},_prepareCollectionSearch:function(){if(!this._runningCollectionSearch&&(this._runningCollectionSearch=!0)){this.$search.addClass("indexing");var n=t.proxy(function(t,i,s){for(var a=s*i,r=Math.min(a+i,t.length);r>a;a++)this._prepareModelSearch(t[a]);a<t.length?e.defer(n,t,i,++s):(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(t,e,n,i,s,a,r){"use strict";return i.extend(e.extend({},s,{_gridTitles:r.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(t){i.prototype.initialize.call(this,t);var e=this;this.$container.on("show:complete",function(){e.load()}),this.$container.on("hide:complete",this._disableSearch)},render:function(){var e=this.rendered;i.prototype.render.call(this),e||this._renderBadge&&t(this._badgeSelector).append(this.$badge=t('<div class="drop-count hidden"><div class="ubnt-icon-drop"></div><div class="count"></div></div>').on("change",function(e,n){var i=t(this),s=i.find(".count");parseInt(s.text(),10)<n&&i.effect("shake",{direction:"up",times:1,distance:5},300),i[n>0?"show":"hide"](),s.text(n)}))},badge:function(){this.$badge&&this.$badge.trigger("change",this.collection.size())},columns:function(){var e=this;return[{name:"datetime",renderable:!1,cell:a.StringCell.extend({className:"title-cell"})},{name:"key",label:"Type",editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.HtmlCell.extend({className:"icon-cell",formatter:{fromRaw:function(t){if(t){var e;switch(t.substr(4,2)){case"AD":case"CF":case"DE":e="ubnt-icon-wrench";break;case"WW":e="ubnt-icon-globe";break;case"GW":e="ubnt-icon-lock";break;case"SW":e="ubnt-icon-files";break;case"AP":e="ubnt-icon-wifi";break;case"PH":e="ubnt-icon-dial";break;case"LC":case"LU":case"LG":case"WC":case"WU":case"WG":case"HS":e="ubnt-icon-person"}return'<div class="panel-icons '+e+'"></div>'}return""},toRaw:function(t){return t}}})},{name:"msg",label:"Message",editable:!1,sortable:!1,headerCell:r.Headers.noSortHeader,cell:r.Cells.ComplexHtmlCell.extend({formatter:{fromRaw:function(i){var s=i.get("msg");if(s){var a=t("<span>"+s.replace(e._msgRegex,function(n,i,s,a){var r=a.indexOf("(")>0?a.replace(/.*\((.*)\).*/,"$1"):a,o=e.model(s.toLowerCase(),r),l=a.indexOf("(")>0?a.replace(/([^\(]+)\(.*/,"$1"):o?o.name():a;return o?t('<a href="#" data-mac="'+r+'" data-type="'+s+'" class="link"></a>').text(s+" "+l).prop("outerHTML"):t('<span class="deleted"></span>').text(s+" "+l).prop("outerHTML")})+"</span>");return a.find("a").on("click",e.link),a.append(t('<span class="timestamp">'+n(i.get("datetime")).format("h:mma")+"</span>")),a}},toRaw:function(t){return t}}})}]},_prepareModelSearch:function(t){for(var e,n,i=[];e=this._msgRegex.exec(t.get("msg"));)(n=this.model(e[2].toLowerCase(),e[3]))&&i.push(n.name());t.addSearchString("names",i)},model:function(t,e){var n;return e&&("ap"==t||"switch"==t||"gateway"==t||"phone"==t?n=this.collections.devices.getDeviceFromMac(e):("user"==t||"client"==t||"guest"==t)&&(n=this.collections.clients.getClientFromMac(e))),n},link:function(e){e.preventDefault();var n=t(e.target),i=n.data("mac"),s=n.data("type").toLowerCase(),a=this.model(s,i);a&&("ap"==s||"switch"==s||"gateway"==s||"phone"==s?this.app.routers.devices.views.index.property(a):("user"==s||"client"==s||"guest"==s)&&this.app.routers.clients.views.index.property(a))},load:function(t,n){var s=!this.collection;(s||t)&&(n=n||{},n.reset=!1,this._maxRecords&&(n.data=e.extend(n.data||{},{_start:0,_limit:this._maxRecords}))),i.prototype.load.call(this,t,n),s&&(this._renderBadge&&(this.listenTo(this.collection,"add",e.debounce(this.badge,250)),this.listenTo(this.collection,"remove",e.debounce(this.badge,250)),this.listenTo(this.collection,"sync",e.debounce(this.badge,250)),this.badge()),this.collections={},this.collections.devices=this.app.collection("Devices"),this.collections.clients=this.app.collection("Clients")),s||t||!this.grids.content||this.grids.content.refresh()},grid:function(){var t={columns:this.columns(),collection:this.collection,titles:this._gridTitles,footer:r.Paginators.Default},e=this.grids.content=new r.Grid(t);return e.paginate(1,this._perPage,!0),this.$el.find(".data-table").append(e.render().$el),this.$table=this.$el.find(".data-table table"),this.$loading=this.$el.find(".data-table .loading").hide(),this.listenTo(e,"backgrid:loading",this.reloading),this.listenTo(e,"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,i.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(t,e,n,i,s,a,r){"use strict";return t.extend({id:"alerts",_templateId:n.template(r,{msg:i}),_collectionType:{name:"Alerts",Class:e},_pageable:!1,_hideArchived:!0,_renderBadge:!0,_badgeSelector:"#toggleAlerts",render:function(){var e=this.rendered;if(t.prototype.render.call(this),!e){var n=this;this.$el.find("button.archive-all").on("click",this.archive),this.$el.find("input[name=archived]").on("change",function(){n._hideArchived=s(this).is(":checked")?!1:!0,n.load(!0)}),this.$(".hide-panel").on("click",function(){s("#toggleAlerts").trigger("click")})}},badge:function(){this.$badge&&this.$badge.trigger("change",n.size(this.collection.where({archived:!1})))},columns:function(){var e=t.prototype.columns.call(this),n=this;return e.push({name:"system",label:i.G_AlertsSystem,editable:!1,sortable:!1,headerCell:a.Headers.noSortHeader,cell:a.Cells.ComplexHtmlCell.extend({className:"system-cell",formatter:{fromRaw:function(t){var e=t.get("system");return e?s("<strong />").text(i.G_AlertsSystem+":").prop("outerHTML")+" "+s("<span />").text(e.toUpperCase()).prop("innerHTML"):""},toRaw:function(t){return t}}})}),e.push({name:"device",label:i.G_AlertsDevice,editable:!1,sortable:!1,headerCell:a.Headers.noSortHeader,cell:a.Cells.ComplexHtmlCell.extend({className:"device-cell",formatter:{fromRaw:function(t){var e=n.app.collection("Devices"),a=null;return t.get("ap")?a=e.getDeviceFromMac(t.get("ap")):t.get("gw")?a=e.getDeviceFromMac(t.get("gw")):t.get("sw")?a=e.getDeviceFromMac(t.get("sw")):t.get("ph")&&(a=e.getDeviceFromMac(t.get("ph"))),a?s("<strong />").text(i.G_AlertsDevice+":").prop("outerHTML")+" "+s("<span />").text(a.apModel()).prop("innerHTML"):""},toRaw:function(t){return t}}})}),e.push({name:"archived",label:i.G_AlertsArchive,editable:!1,sortable:!1,headerCell:a.Headers.noSortHeader,cell:a.Cells.HtmlCell.extend({className:"icon-cell transparent-cell",formatter:{fromRaw:function(t){return t?"":'<div class="ubnt-icon-archive archive"></div>'},toRaw:function(t){return t}}}),callback:function(t){t.archive().done(function(e){e.meta&&"ok"===e.meta.rc&&(t.set({archived:!0}),n._hideArchived&&t.collection.remove(t))})}}),e},load:function(e){e=e||!this.collection,(!this.collection||e)&&(this._fetchMethod=this._hideArchived?"unarchived":"",this.collection&&this.collection.reset()),t.prototype.load.call(this,e)},archive:function(){var t=this;this.collection.archiveAll().done(function(e){e.meta&&"ok"===e.meta.rc&&t.load(!0)})},grid:function(){t.prototype.grid.call(this);var e=this.grids.content;return this.$el.find(".buttonset input[name=filter]").on("change",function(){var t=s(this).val();t?e.setFilter("system",t,1):e.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,t.prototype.remove.apply(this,arguments)}})}),define("unifi/collection/Events",["unifi/collection/Collection","backbone","unifi/model/Event","libs/moment","underscore"],function(t,e,n,i,s){"use strict";return t.extend({model:n,bySite:!0,triggerReset:!1,url:function(){return"/api/s/"+SITE.name+"/stat/event"},comparator:function(t){return-i(t.get("datetime"))},filtered:function(t){return this.fetch(s.extend(t,{_method:"read-filtered"}))},sync:function(t,n,i){switch(i=i||{},i._method&&(t=i._method,delete i._method),t){case"read":i.url="/api/s/"+SITE.name+"/stat/event",i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify({_sort:"-time"});break;case"read-filtered":i.url="/api/s/"+SITE.name+"/stat/event",i.contentType="application/json; charset=utf-8",i.type="POST",i.data=JSON.stringify(s.extend({_sort:"-time"},i.data||{}))}return e.sync.call(this,t,n,i)}})}),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(t,e,n,i,s,a){"use strict";return t.extend({id:"events",_templateId:n.template(a,{msg:s}),_collectionType:{name:"Events",Class:e},_fetchMethod:"filtered",_limitTimeframe:1,_limitType:null,_renderBadge:!1,_badgeSelector:"#toggleEvents",render:function(){var e=this.rendered;if(t.prototype.render.call(this),!e){this.$(".hide-panel").on("click",function(){i("#toggleEvents").trigger("click")}),this.$container.one("show",function(t){i(t.target).find("select").each(function(){var t=i(this);t.selectmenu({parent:t.parent(),appendTo:i("#columnMainPanel"),icons:{button:"ubnt-icon-arrow-down secondary-color"},position:{at:"left bottom",collision:"flip"},change:function(){t.trigger("change")}})})});var n=this;this.$el.find("select[name=time-filter]").on("change",function(){n._limitTimeframe=Math.max(parseInt(i(this).find("option:selected").val(),10),1),n.load(!0)}),this.$el.find(".buttonset input[name=filter]").on("change",function(){n._limitType=i(this).val(),n.load(!0)})}},load:function(e){e=e||!this.collection,(!this.collection||e)&&(this.collection&&this.collection.reset(),t.prototype.load.call(this,e,{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,t.prototype.remove.apply(this,arguments)}})}),define("unifi/view/app/PropertiesView",["backbone","jquery"],function(t,e){"use strict";return t.View.extend({render:function(){if(!this.rendered&&(this.rendered=!0)){e.expr[":"].activeAccordion=function(t){return e(t).find("> .ui-accordion-header").hasClass("ui-state-active")};var t=this.$el;t.on("toggle",function(){var t=e(this),n=t.find("> .accordion");t.trigger(n.length===n.filter(":activeAccordion").length?"minimize":"maximize")}).on("minimize",function(){e(this).find("> .accordion:activeAccordion").find(".ui-accordion-header").click()}).on("maximize",function(){e(this).find("> :not(.accordion:activeAccordion)").find(".ui-accordion-header").click()}).on("empty",function(){e(this).find("> .accordion").find(".remove").click()}),e("#columnEastHeader .toggle-all").on("click",function(){t.trigger("toggle")}),e("#columnEastHeader .remove-all").on("click",function(){t.trigger("empty")}),this.$el.sortable({axis:"y",handle:"> .accordion-header",containment:"parent",opacity:.8,tolerance:"pointer",stop:function(t,e){e.item.find("> .accordion-header").triggerHandler("focusout")}}),this.$el.on("property:remove",function(){t.find("> .accordion").size()||e("#columnEast").panel("hide","west",!0)}),this.$el.on("property:render",function(){e("#columnEast").panel("show","west",!0)}),e.Body.append(this.$detached=e('<div id="propertiesLayer" />')),this.$detached.on("click","> .properties",function(t){var n=e(t.target),i=n.hasClass("properties")?n:n.parents(".properties"),s=e.makeArray(i.siblings(".properties")).sort(function(t,n){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(n).css("zIndex"),10)||0)});if(s.length){var a=parseInt(e(s[0]).css("zIndex"),10)||0;e(s).each(function(t){e(this).css("zIndex",a+t)}),i.css("zIndex",a+s.length)}})}},remove:function(){this.$el.off("toggle").off("minimize").off("maximize").off("empty"),e("#columnEastHeader .toggle-all").off("click"),e("#columnEastHeader .remove-all").off("click"),this.$el.off("property:remove"),this.$el.off("property:render"),this.$detached.off("click","> .properties"),this.rendered=!1,t.View.prototype.remove.apply(this,arguments)}})}),define("ubnt/ubnt.layout",["jquery","jquery-ui"],function(t){"use strict";t.widget("ubnt.layout",t.ui.mouse,{_create:function(){this.handles=[],this.elements=[],this.direction=null,this.originalMousePosition=null;for(var t in this.options.directions)this.options.directions.hasOwnProperty(t)&&this._initDirection(t,this.options.directions[t]);this._mouseInit()},_destroy:function(){this._mouseDestroy();for(var e in this.handles)this.handles.hasOwnProperty(e)&&this.handles[e].remove();this.element.removeClass("ubnt-layout ubnt-layout-resizing"),t("body").css("cursor","auto")},_initDirection:function(e,n){t.inArray(e,-1!==["north","south","east","west"])&&(this.element.addClass("ubnt-layout"),n.draggable&&this.element.append(this.handles[e]=t('<div class="ubnt-layout drag-handle '+e+'" title="drag to expand or collapse"></div>')),this.elements[e]=n.also||[],this.elements[e].unshift({element:this.element,property:n.property,inverse:!1}))},_setInitial:function(t){for(var e in this.elements[t])if(this.elements[t].hasOwnProperty(e)){var n=this.elements[t][e];this.elements[t][e].initial=parseInt(n.element.css(n.property),10)}},_mouseCapture:function(e){for(var n in this.handles)if(t(this.handles[n])[0]==e.target)return this.direction=n,!0},_mouseStart:function(e){this.originalMousePosition={left:e.pageX,top:e.pageY},this._setInitial(this.direction),this.element.addClass("ubnt-layout-resizing"),t("body").css("cursor",this.direction.substring(0,1)+"-resize")},_mouseDrag:function(t,e,n){var i=0;switch(e=e||t.pageX-this.originalMousePosition.left||0,n=n||t.pageY-this.originalMousePosition.top||0,this.direction){case"north":i=-n;break;case"south":i=n;break;case"east":i=e;break;case"west":i=-e}this._resize(this.direction,i,!0)},_mouseStop:function(){this._constrain(this.direction),this.direction=null,this.element.removeClass("ubnt-layout-resizing"),t("body").css("cursor","auto")},_constrain:function(e){var n=this.options.directions[e],i=n.constraints,s=null,a=null;if(i){if(a=parseInt(this.element.css(n.property),10),i.min&&(s=t.isFunction(i.min)?i.min():i.min,s>a))return this._resize(e,s,!1);if(i.max&&(s=t.isFunction(i.max)?i.max():i.max,a>s))return this._resize(e,s,!1)}},_resize:function(t,e,n,i){n||(e-=this.elements[t][0].initial);for(var s in this.elements[t])if(this.elements[t].hasOwnProperty(s)){var a=this.elements[t][s];if(i){var r={};r[a.property]=(a.initial||0)+(a.inverse?-e:e),s>0&&delete i.complete,a.element.animate(r,i)}else a.element.css(a.property,(a.initial||0)+(a.inverse?-e:e))}},resize:function(e,n,i,s,a){this._setInitial(e),n=t.isFunction(n)?n():n,this._resize(e,n,i,s),a&&this._constrain(e)},position:function(t){var e=this.elements[t][0];return parseInt(e.element.css(e.property),10)}})}),define("ubnt/ubnt.panel",["jquery","jquery-ui","ubnt/ubnt.layout"],function(t){"use strict";t.widget("ubnt.panel",t.ubnt.layout,{_create:function(){t.ubnt.layout.prototype._create.apply(this,arguments),this.options.id=this.element.attr("id"),this.options.active="active",this._animating=0,this._visible={};var e=this.element.is(":visible");for(var n in this.options.directions)if(this.options.directions[n].hasOwnProperty("property")&&(this._visible[n]=e,this.options.directions.hasOwnProperty(n)&&this.options.directions[n].hasOwnProperty("buttons")))for(var i in this.options.directions[n].buttons)this.options.directions[n].buttons.hasOwnProperty(i)&&(this.options.directions[n].buttons[i].on("click",t.proxy(this,"toggle",n)),e?this.options.directions[n].buttons[i].addClass(this.options.active):this.element.data(this._datavar(n),this.position(n)))},_destroy:function(){t.ubnt.layout.prototype._destroy.apply(this,arguments);for(var e in this.options.directions)if(this.options.directions.hasOwnProperty(e)){this.element.removeData(this._datavar(this.options.directions[e]));for(var n in this.options.directions[e].buttons)this.options.directions[e].buttons.hasOwnProperty(e)&&this.options.directions[e].buttons[e].off("click").removeClass(this.options.active)}},_datavar:function(t){return"layout-position-"+t},show:function(e,n,i){if(!this._animating&&!this.visible(e)){var s=this.options.directions[e].callbacks;s&&s.beforeShow&&s.beforeShow(),t("body").removeClass(this.options.id+"Hidden"),this.element.show(),this._animating++,this.resize(e,this.element.data(this._datavar(e)),!1,{duration:n?0:this.options.duration,start:t.proxy(function(){this.element.trigger("ubnt.panel.showing")},this),complete:t.proxy(function(){this.element.trigger("ubnt.panel.shown"),this._visible[e]=!0,this._animating--,i&&i(n),s&&s.show&&s.show(n)},this)});var a=this.options.directions[e].buttons;for(var r in a)a.hasOwnProperty(r)&&a[r].addClass(this.options.active)}},hide:function(e,n){if(!this._animating&&this.visible(e)){var i=this.options.directions[e].callbacks;i&&i.beforeHide&&i.beforeHide(),this.element.data(this._datavar(e),this.position(e)),this._animating++,this.resize(e,0,!1,{duration:n?0:this.options.duration,start:t.proxy(function(){this.element.trigger("ubnt.panel.hiding")},this),complete:t.proxy(function(){t("body").addClass(this.options.id+"Hidden"),this.element.trigger("ubnt.panel.hidden"),this._visible[e]=!1,this._animating--,i&&i.hide&&i.hide(n)},this)});var s=this.options.directions[e].buttons;for(var a in s)s.hasOwnProperty(a)&&s[a].removeClass(this.options.active)}},toggle:function(t){this.visible(t)?this.hide(t):this.show(t)},visible:function(t){return this._visible[t]}})}),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(t,e,n,i,s,a,r,o){"use strict";return t.extend({initialize:function(a){t.prototype.initialize.call(this,a),this.config.site="Admin",this.$properties=r("#columnEastContent > .content"),this.$content=r("#columnMainContent"),this.$panel=r("#columnMainPanel"),this.$alerts=r("#panelAlerts"),this.$events=r("#panelEvents"),this.contentSize=s.bind(this.contentSize,this),r(window).on("resize",this.contentSize),this.views.alerts=new e({container:this.$alerts,app:this.options.app}),this.views.events=new n({container:this.$events,app:this.options.app}),this.views.properties=new i({el:this.$properties})},render:function(){var e=this.rendered;if(t.prototype.render.call(this),!e){r("#columnWestToggles").append(r('<li id="toggleAlerts"><div class="ubnt-icon-warning toggle-icons toggle-alerts"><span class="ir">'+a.G_ToggleAlerts+"</span></div></li>")).append(r('<li id="toggleEvents"><div class="ubnt-icon-calendar toggle-icons toggle-events"><span class="ir">'+a.G_ToggleEvents+"</span></div></li>")),r.Body.append(r('<div id="showSidebar" class="show-sidebar" title="Show Properties"><span class="ubnt-icon-properties-drop"></span><span class="underlay"></span><span class="ir">'+a.G_ShowSidebar+"</div>")),r("#columnEast").panel({duration:350,directions:{west:{draggable:!1,property:"width",constraints:{max:500,min:r("#columnEast").width()},also:[{element:r("#columnMain > .content"),property:"margin-right",inverse:!1}],buttons:[r("#columnEastHeader .toggle-sidebar"),r("#showSidebar")],callbacks:{beforeShow:this.contentSize,hide:function(t){t||r("#showSidebar").effect("shake",{times:1,distance:5},300)}}}}}),r("#columnMainPanel").panel({duration:350,directions:{north:{draggable:!0,property:"height",constraints:{max:r(window).height()-r("#header").height(),min:35},also:[{element:r("#columnMainContent"),property:"bottom",inverse:!1}]}}}),r("#columnMainPanel").panel("hide","north",!0),r("#columnEast").panel("hide","west",!0),r(".columnOuterContainer").removeClass("invisible"),r("#toggleAlerts, #toggleEvents").on("click",r.proxy(function(t){var e=r(t.target).closest("li"),n=e.attr("id").replace("toggle",""),i=r("#panel"+n);e.hasClass("active")?(this.$panel.one("ubnt.panel.hidden",function(){e.removeClass("active")}),this.$panel.panel("hide","north")):(this.$panel.panel("visible","north")?(this.showPanel(i,e),i.trigger("show:complete")):(this.$panel.one("ubnt.panel.showing",r.proxy(function(){this.showPanel(i,e)},this)),this.$panel.panel("show","north",!1,function(){i.trigger("show:complete")})),o.trackEvent("button","click","open "+n.toLowerCase()))},this)),r("#columnWestToggles").show(),r.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 s.each(this.views,function(t){t.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(t,e){e.addClass("active").siblings("li").removeClass("active"),t.show().trigger("show").siblings().hide().trigger("hide")},contentSize:function(){},openSettings:function(t,e){t&&(this.options.app.settings=t,r("#navigation").find("a[data-page=settings]").trigger("click",e))},reflectSettingChanges:function(){var t=this.app.collection("Settings"),e=t.getSettingFromKey("voip",SITE.id),n=!(!e||!e.get("enabled"));r.Body.toggleClass("hasVoip",n)},reset:function(){t.prototype.reset.call(this),r("#columnWestToggles li.active").removeClass("active"),r("#columnMainPanel").panel("hide","north",!0),r("#columnEast").panel("hide","west",!0)},remove:function(){s.each(this.views,function(t){t.remove&&t.remove()},this),this.views={},r(window).off("resize",this.contentSize),r("#toggleAlerts, #toggleEvents").off("click"),this.stopListening(this.settings,"change sync add",this.reflectSettingChanges),this.rendered=!1,t.prototype.remove.apply(this,arguments)}})}),require(["jquery","app","unifi/router/DashboardRouter","unifi/router/MapRouter","unifi/router/DevicesRouter","unifi/router/ClientsRouter","unifi/router/StatisticsRouter","unifi/router/InsightsRouter","unifi/router/SupportRouter","unifi/view/app/AdminView","unifi/collection/Sites","unifi/collection/Devices","unifi/collection/Clients","unifi/collection/Settings"],function(t,e,n,i,s,a,r,o,l,c,d,h,u,p){"use strict";t(function(){var t={Dashboard:n,Map:i,Devices:s,Clients:a,Statistics:r,Insights:o,Support:l},m={Sites:d,Devices:h,Clients:u,Settings:p};e.initialize(t,m,c)})}),define("manage",function(){});