/*
  backgrid-select-all
  http://github.com/wyuenho/backgrid

  Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  Licensed under the MIT @license.
*/

/*! http://mths.be/placeholder v2.0.7 by @mathias 
	Modified to work with Zepto.js by ZURB
*/

define("text!includes/wizard/WelcomeTemplate.html",[],function(){return'<h2><%- msg.Wizard.G_WelcomeMessage %></h2>\n<div class="row input">\n    <div class="large-12 columns">\n        <label for="country"><%- msg.Wizard.G_WelcomeSelectCountry %></label>\n        <span class="custom-dropdown custom-dropdown--white">\n            <select id="country" name="country" class="custom-dropdown__select custom-dropdown__select--white">\n                <% _(ccodes).each(function (ccode) {%><option value="<%= ccode.code %>"><%= ccode.name %></option><% }); %>\n            </select>\n        </span>\n    </div>\n    <div class="large-12 columns">\n        <label for="timezone"><%- msg.Wizard.G_WelcomeSelectTimezone %></label>\n        <span class="custom-dropdown custom-dropdown--white">\n            <select id="timezone" name="timezone" class="custom-dropdown__select custom-dropdown__select--white">\n                <%= timezoneOptionsTemplate() %>\n            </select>\n        </span>\n    </div>\n</div>\n<div class="row"><div class="large-12 columns">\n        <%- msg.Wizard.G_WelcomeRestoreLinkPrefix %> <a id="Backup" href="#Backup"><%- msg.Wizard.G_WelcomeRestoreLinkText %></a>.\n</div></div>\n<div class="row">\n    <div class="large-12 columns">\n        <input type="file" name="file" id="restoreFile"/>\n        <progress />\n    </div>\n</div>\n'}),define("unifi/view/wizard/WelcomeView",["underscore","backbone","msg/Msg","ubnt/view/dialogs/ConfirmDialogView","ubnt/view/dialogs/ErrorDialogView","ubnt/view/dialogs/AlertDialogView","text!includes/wizard/WelcomeTemplate.html","text!includes/global/timezoneOptions.html","libs/fileupload"],function(e,t,n,r,i,s,o,u,a){"use strict";return t.View.extend({template:e.template(o),el:"#Step",events:{"click #Backup":"onBackup",'change [type="file"]':"onFileChange","change #country":"onCountryChange","change #language":"onLanguageChange","change #timezone":"onTimezoneChange"},initialize:function(t){this.options=t,e.bindAll(this,"onProgress","restore"),this.listenTo(this.model,"change:up",this.backupRestored)},render:function(){this.$el.html(this.template({ccodes:this.model.get("ccodes"),languages:[{name:"English (US)",code:"en_us"}],timezoneOptionsTemplate:e.template(u),msg:n}));var r=this.$("#timezone");if(!this.model.get("timezone")){var i=this.model.getTimezoneOffset();if(i){var s=r.find('option[title="'+i+'"]');s&&this.model.set("timezone",s.val())}}return this.$("#country").val(this.model.get("country")),this.$("#language").val(this.model.get("language")),r.val(this.model.get("timezone")).change(),this.$progress=this.$("progress"),this.$file=this.$("#restoreFile"),this},onCountryChange:function(e){this.model.set("country",this.$(e.target).val())},onLanguageChange:function(e){this.model.set("language",this.$(e.target).val())},onTimezoneChange:function(e){this.model.set("timezone",this.$(e.target).val())},onBackup:function(t){t.preventDefault(),this.$file.show()},onFileChange:function(e){this.$progress.show(),this.$file.hide();var n=new a,r=n.upload(t.$("form").get(0),{url:"/upload/backup"});r.progress(this.onProgress),r.done(this.restore),r.fail(this.restore)},onProgress:function(t){var n=this.$progress.get(0);this.$progress.val(t.loaded),t.total!==n.max&&(n.max=t.total)},restore:function(e,t,i){this.$progress.hide(),this.$file=this.$("#restoreFile").show();var s=this,o,u;if(!e||!e.meta||e.meta.rc!="ok")return this.failedUpload(i,t,e);e=e.meta,(new r).show(n.localize(n.I_ConfirmRestore,e.filename,new Date(parseInt(e.timestamp,10))),function(){s.model.cmdRestore().done(function(e){e.meta.rc==="ok"?s.model.pollServer():alert("something went wrong:"+e.msg)})})},backupRestored:function(e,t,r){return t?window.location.reload():(new s).open(n.Wizard.N_Restoring),this},failedUpload:function(e,t,r){var s=new i,o;r.meta.msg==="api.err.InvalidBackupVersion"?o=n.localize(n.E_InvalidBackupVersion,r.meta.filename,r.meta.version):o=n.localize(n.E_InvalidBackup,r.meta.filename),s.open(o)}})}),define("text!includes/wizard/DiscoverTemplate.html",[],function(){return'<h2>\n    <%- msg.Wizard.G_DiscoverMessage %>\n</h2>\n<div class="row">\n    <div class="large-24 columns">\n        <div id="Devices" class="data-table untitled"></div>\n    </div>\n</div>\n<button id="Refresh" type="button" class="button secondary"><span class=ubnt-icon-refresh>   </span><%- msg.Wizard.G_Refresh %></button>\n'}),function(e){typeof exports=="object"?module.exports=e(require("backbone"),require("backgrid")):typeof Backbone!="undefined"&&typeof Backgrid!="undefined"&&e(Backbone,Backgrid)}(function(e,t){"use strict";var n=e.$,r=t.Extension.SelectRowCell=e.View.extend({className:"select-row-cell",tagName:"td",events:{"keydown :checkbox":"onKeydown","change :checkbox":"onChange","click :checkbox":"enterEditMode"},initialize:function(e){this.column=e.column,this.column instanceof t.Column||(this.column=new t.Column(this.column)),this.listenTo(this.model,"backgrid:select",function(e,t){this.$el.find(":checkbox").prop("checked",t).change()});var n=this.column,r=this.$el;this.listenTo(n,"change:renderable",function(e,t){r.toggleClass("renderable",t)}),n.get("renderable")&&r.addClass("renderable")},enterEditMode:function(){this.$el.find(":checkbox").focus()},exitEditMode:function(){this.$el.find(":checkbox").blur()},onKeydown:function(e){var n=new t.Command(e);if(n.passThru())return!0;if(n.cancel())e.stopPropagation(),this.$el.find(":checkbox").blur();else if(n.save()||n.moveLeft()||n.moveRight()||n.moveUp()||n.moveDown())e.preventDefault(),e.stopPropagation(),this.model.trigger("backgrid:edited",this.model,this.column,n)},onChange:function(e){var t=n(e.target).prop("checked");this.$el.parent().toggleClass("selected",t),this.model.trigger("backgrid:selected",this.model,t)},render:function(){return this.$el.empty().append('<input tabindex="-1" type="checkbox" />'),this.delegateEvents(),this}}),i=t.Extension.SelectAllHeaderCell=r.extend({className:"select-all-header-cell",tagName:"th",initialize:function(e){this.column=e.column,this.column instanceof t.Column||(this.column=new t.Column(this.column));var n=this.collection,r=this.selectedModels={};this.listenTo(n,"backgrid:selected",function(e,t){t?r[e.id||e.cid]=e:(delete r[e.id||e.cid],this.$el.find(":checkbox").prop("checked",!1))}),this.listenTo(n,"remove",function(e){delete r[e.id||e.cid]}),this.listenTo(n,"backgrid:refresh",function(){this.$el.find(":checkbox").prop("checked",!1);for(var e=0;e<n.length;e++){var t=n.at(e);r[t.id||t.cid]&&t.trigger("backgrid:select",t,!0)}});var i=this.column,s=this.$el;this.listenTo(i,"change:renderable",function(e,t){s.toggleClass("renderable",t)}),i.get("renderable")&&s.addClass("renderable")},onChange:function(e){var t=n(e.target).prop("checked"),r=this.collection;r.each(function(e){e.trigger("backgrid:select",e,t)}),r.trigger("backgrid:select-all",r,t)}});t.Grid.prototype.getSelectedModels=function(){var e,t=this.header.row.cells;for(var n=0,r=t.length;n<r;n++){var s=t[n];if(s instanceof i){e=s;break}}var o=[],u=this.collection;"fullCollection"in u&&(u=u.fullCollection);if(e)for(var a in e.selectedModels)o.push(u.get(a));return o}}),define("libs/backgrid-select-all",function(){}),define("unifi/view/wizard/SelectDevicesView",["jquery","underscore","backbone","libs/backgrid","ubnt/backgrid","msg/Msg","text!includes/wizard/WelcomeTemplate.html","libs/backgrid-select-all"],function(e,t,n,r,i,s,o){"use strict";var u=function(t){};return u.prototype=new r.NumberFormatter,t.extend(u.prototype,i.Formatters.Seconds),n.View.extend({el:"#Devices",template:t.template('<div class="error"><p class="message"><%= message %></p><p><%= instructions %></p>'),events:{"click .prev":"_onChangePage","click .next":"_onChangePage"},initialize:function(t,n){this.listenTo(this.collection,"add",this.sizeCheck),this.listenTo(this.collection,"remove",this.sizeCheck),this.listenTo(this.collection,"reset",this.sizeCheck)},sizeCheck:function(t,n,r){this.collection.length===0||this.grid._collection().length===0?(this.$("table.backgrid").hide(),this.$error.show()):(this.$("table.backgrid").show(),this.$error.hide())},render:function(){return this.$error=n.$(this.template({message:s.Wizard.E_NoDevicesMsg,instructions:s.Wizard.E_NoDevicesInstructions})),this.grid=new i.Grid({columns:this.columns,collection:this.collection,pageable:!0,footer:i.Paginators.Mini}),this.grid.setFilter("default",!0,1),this.grid.paginate(1,10),this.$el.html(this.grid.render().el),this._selectFix(),this.$el.append(this.$error),this.sizeCheck(),this},_onChangePage:function(){var n=this.grid.getSelectedModels(),r=this,i,s,o;t.delay(function(){r.$("tbody").find("tr").each(function(){i=e(this),o=i.find("td:eq(1)").text(),s=i.find("td:first").find("input"),t.find(n,function(e){return e.attributes.mac===o})?s.attr("checked","checked"):s.removeAttr("checked")})},200)},_selectFix:function(){var n=this.grid.header.row.cells[0];n.collection=this.collection,n.initialize({column:n.column});var r=this;return this.grid.body.$el.on("refresh",function(){r.collection.length&&r.collection.trigger("backgrid:refresh")}),n.$el.on("change",":checkbox",function(){var t=e(this).is(":checked");r.collection.each(function(e){e.trigger("backgrid:selected",e,t)})}),this.collection.selectedDevices=n.selectedModels,this},columns:[{name:"",headerCell:"select-all",cell:"select-row"},{name:"name",label:s.G_PropertiesMACAddress,sortable:!1,editable:!1,headerCell:i.Headers.noLinkHeader,cell:i.Cells.ModelCell.extend({callback:"name"})},{name:"version",label:s.G_Version,sortable:!1,editable:!1,headerCell:i.Headers.noLinkHeader,cell:"string"},{name:"ip",label:s.G_IPAddress,sortable:!1,editable:!1,headerCell:i.Headers.noLinkHeader,cell:"string"},{name:"uptime",label:s.G_Uptime,editable:!1,cell:r.IntegerCell.extend({formatter:u})}]})}),define("unifi/view/wizard/DiscoverView",["backbone","underscore","msg/Msg","text!includes/wizard/DiscoverTemplate.html","unifi/view/wizard/SelectDevicesView"],function(e,t,n,r,i){"use strict";return e.View.extend({template:t.template(r),events:{"click #Refresh":"onRefresh"},el:"#Step",render:function(){return this.$el.html(this.template({msg:n})),this.devicesView=new i({collection:this.model.get("devices")}),this.devicesView.render(),this},onRefresh:function(t){this.model.fetchDeviceStatus({type:"POST"})}})}),define("text!includes/wizard/WirelessTemplate.html",[],function(){return'<h2><%- msg.Wizard.G_WirelessMessage %></h2>\n<p><%- msg.Wizard.G_WirelessMessageSkip %></p>\n<div class="row">\n    <div class="large-9 columns">\n        <label for="SSID"><%- msg.Wizard.G_WirelessSecureSsid %></label>\n        <input id="SSID" name="SSID" type="text" value="<%- ssid %>" required pattern="(^([\\x20-\\x7E]){1,32}$)" title="<%- msg.Wizard.G_WirelessSecureSsidTitle %>"/>\n    </div>\n    <div class="large-9 columns large-offset-2">\n        <label for="SecurityKey"><%- msg.Wizard.G_WirelessSecurityKey %></label>\n        <input id="SecurityKey" name="SecurityKey" type="password" value="<%- securityKey %>" title="<%- msg.Wizard.G_WirelessSecurityKeyTitle %>" pattern="^([\\x20-\\x7E]){8,63}$" required/>\n    </div>\n    <div class="large-4 columns"></div>\n</div>\n<p><%- msg.Wizard.G_WirelessOptionMessage %></p>\n<div>\n    <input type="checkbox" name="Guest" id="Guest" value="true" <% if (guest) {%>checked<% } %> /> <label for="Guest"><%- msg.Wizard.G_WirelessEnableGuestAccess %></label>\n    <div class="row">\n        <div class="large-9 columns guest">\n            <label for="GuestSSID"><%- msg.Wizard.G_WirelessGuestSsid %></label>\n            <input id="GuestSSID" name="GuestSSID" type="text" value="<%- guest_ssid %>" required pattern="(^([\\x20-\\x7E]){1,32}$)" title="<%- msg.Wizard.G_WirelessSecureSsidTitle %>" <% if (guest) {%>disabled<% } %>/>\n        </div>\n    </div>\n</div>\n'}),define("unifi/view/wizard/WirelessView",["underscore","backbone","msg/Msg","text!includes/wizard/WirelessTemplate.html"],function(e,t,n,r){"use strict";return t.View.extend({events:{"change #Guest":"onGuestChange","change #SecurityKey":"onSecurityKeyChange","change #SSID":"onSSIDChange","change #GuestSSID":"onGuestSSIDChange"},template:e.template(r),el:"#Step",initialize:function(t){this.options=t,this.listenTo(this.model,"change:guest",this.showGuestSSID)},render:function(){return this.$el.html(this.template({securityKey:this.model.get("securityKey"),ssid:this.model.get("ssid"),guest:this.model.get("guest"),guest_ssid:this.model.get("guest_ssid"),msg:n})),this.showGuestSSID(this.model,this.model.get("guest")),this},onSSIDChange:function(t){this.model.set({ssid:t.target.value})},onSecurityKeyChange:function(t){this.model.set({securityKey:t.target.value})},onGuestChange:function(t){this.model.set({guest:t.target.checked})},onGuestSSIDChange:function(t){this.model.set({guest_ssid:t.target.value})},showGuestSSID:function(t,n,r){return n?(this.$(".guest").show(),this.$("#GuestSSID").get(0).disabled=!1):(this.$("#GuestSSID").get(0).disabled=!0,this.$(".guest").hide()),this}})}),define("text!includes/wizard/PasswordTemplate.html",[],function(){return'<h2><%- msg.Wizard.G_PasswordMessage %></h2>\n<div class="row">\n    <div class="large-9 columns">\n        <label for="admin"><%- msg.Wizard.G_PasswordAdminName %></label>\n        <input id="admin" name="admin" type="text" value="<%- admin %>" pattern="^[_A-Za-z0-9][-_.A-Za-z0-9]*$" title="<%- msg.Wizard.G_PasswordAdminNameTitle %>" required/>\n    </div>\n</div>\n<div class="row">\n    <div class="large-9 columns">\n        <label for="password"><%- msg.Wizard.G_Password %></label>\n        <input id="password" name="password" type="password" value="<%- password %>" required title=""/>\n    </div>\n    <div class="large-9 columns large-offset-2">\n        <label for="password"><%- msg.Wizard.G_ConfirmPassword %></label>\n        <input id="password-confirm" name="password-confirm" type="password" value="<%- passwordConfirm %>" required/>\n    </div>\n    <div class="large-4 columns"></div>\n</div>\n'}),define("unifi/view/wizard/PasswordView",["underscore","backbone","msg/Msg","text!includes/wizard/PasswordTemplate.html"],function(e,t,n,r){"use strict";return t.View.extend({events:{"change #password":"onPasswordChange","change #password-confirm":"onPasswordChangeConfirm","change #admin":"onAdminChange","keyup #password-confirm":"onPasswordChangeConfirm"},template:e.template(r),el:"#Step",initialize:function(t){this.options=t,this.listenTo(this.model,"invalid",this.setInvalid)},render:function(){return this.$el.html(this.template({password:this.model.get("password"),passwordConfirm:this.model.get("password-confirm"),admin:this.model.get("admin"),msg:n})),this.passwordConfirm=this.el.querySelector("#password-confirm"),this.$passwordConfirm=t.$(this.passwordConfirm),this},setInvalid:function(t,n){return n==="passwords do not match"&&(this.passwordConfirm.setCustomValidity("Passwords do not match"),this.$passwordConfirm.addClass("error")),this},setValid:function(t){this.passwordConfirm.setCustomValidity(""),this.$passwordConfirm.removeClass("error")},onPasswordChange:function(t){this.model.set("password",this.$el.find("#password").val()),this.model.isValid()&&this.setValid()},onPasswordChangeConfirm:function(t){this.onPasswordChange(),this.onAdminChange(),this.passwordConfirm.setCustomValidity(""),this.$passwordConfirm.removeClass("error"),this.model.set("password-confirm",this.$el.find("#password-confirm").val()),this.model.isValid()},onAdminChange:function(t){this.model.set("admin",this.$el.find("#admin").val())}})}),define("text!includes/wizard/FinishTemplate.html",[],function(){return'<h2><%- msg.Wizard.G_FinishMessage %></h2>\n<div class="row">\n    <div class="large-12 columns">\n        <label><%- msg.Wizard.G_WirelessSecureSsid %></label>\n    </div>\n    <div class="large-12 columns">\n        <label><%- msg.Wizard.G_PasswordAdminName %></label>\n    </div>\n</div>\n<div class="row">\n    <div class="large-12 columns">\n        <span><%- ssid %></span>\n    </div>\n    <div class="large-12 columns">\n        <span><%- admin %></span>\n    </div>\n</div>\n'}),define("unifi/view/wizard/FinishView",["underscore","backbone","msg/Msg","text!includes/wizard/FinishTemplate.html"],function(e,t,n,r){"use strict";return t.View.extend({template:e.template(r),el:"#Step",render:function(){return this.$el.html(this.template({admin:this.model.get("admin"),ssid:this.model.get("ssid")||n.Wizard.N_NoSSID,msg:n})),this}})}),define("text!includes/wizard/ProgressTemplate.html",[],function(){return'<ol>\n    <li class="welcome in-progress">\n        <button type=button name=step value=welcome>1</button>\n        <a href="#welcome"><%- msg.Wizard.G_Welcome %></a>\n    </li>\n    <li class="discover">\n        <button type=button name=step value=discover>2</button>\n        <div class="connection"></div>\n        <a href="#discover"><%- msg.Wizard.G_Discover %></a>\n    </li>\n    <li class="wireless">\n        <button type=button name=step value=wireless>3</button>\n        <div class="connection"></div>\n        <a href="#wireless"><%- msg.Wizard.G_Wireless %></a>\n    </li>\n    <li class="password">\n        <button type=button name=step value=password>4</button>\n        <div class="connection"></div>\n        <a href="#password"><%- msg.Wizard.G_Password %></a>\n    </li>\n    <li class="finish">\n        <button type=button name=step value=finish>5</button>\n        <div class="connection"></div>\n        <a href="#finish"><%- msg.Wizard.G_Finish %></a>\n    </li>\n</ol>\n'}),define("unifi/view/wizard/ProgressView",["backbone","underscore","msg/Msg","text!includes/wizard/ProgressTemplate.html"],function(e,t,n,r){"use strict";return e.View.extend({template:t.template(r),el:"#Progress",initialize:function(t){this.listenTo(this.model,"change:step",this.showStep)},render:function(){return this.$el.html(this.template({msg:n})),this},showStep:function(e,t){return this.$("."+t).prevAll().removeClass("in-progress").addClass("complete"),this.$("."+t).removeClass("complete").addClass("in-progress"),this.$("."+t+" ~ li").removeClass("complete in-progress"),this},setStep:function(n){n.preventDefault();var r=e.$(n.target),i=r.val();i||(i=r.attr("href").slice(1)),this.model.set("step",i)}})}),function(e,t,n){function f(e){var t={},r=/^jQuery\d+$/;return n.each(e.attributes,function(e,n){n.specified&&!r.test(n.name)&&(t[n.name]=n.value)}),t}function l(e,r){var i=this,s=n(i);if(i.value==s.attr("placeholder")&&s.hasClass("placeholder"))if(s.data("placeholder-password")){s=s.hide().next().show().attr("id",s.removeAttr("id").data("placeholder-id"));if(e===!0)return s[0].value=r;s.focus()}else i.value="",s.removeClass("placeholder"),i==t.activeElement&&i.select()}function c(){var e,t=this,r=n(t),i=r,s=this.id;if(t.value==""){if(t.type=="password"){if(!r.data("placeholder-textinput")){try{e=r.clone().attr({type:"text"})}catch(o){e=n("<input>").attr(n.extend(f(this),{type:"text"}))}e.removeAttr("name").data({"placeholder-password":!0,"placeholder-id":s}).bind("focus.placeholder",l),r.data({"placeholder-textinput":e,"placeholder-id":s}).before(e)}r=r.removeAttr("id").hide().prev().attr("id",s).show()}r.addClass("placeholder"),r[0].value=r.attr("placeholder")}else r.removeClass("placeholder")}var r="placeholder"in t.createElement("input"),i="placeholder"in t.createElement("textarea"),s=n.fn,o=n.valHooks,u,a;r&&i?(a=s.placeholder=function(){return this},a.input=a.textarea=!0):(a=s.placeholder=function(){var e=this;return e.filter((r?"textarea":":input")+"[placeholder]").not(".placeholder").bind({"focus.placeholder":l,"blur.placeholder":c}).data("placeholder-enabled",!0).trigger("blur.placeholder"),e},a.input=r,a.textarea=i,u={get:function(e){var t=n(e);return t.data("placeholder-enabled")&&t.hasClass("placeholder")?"":e.value},set:function(e,r){var i=n(e);return i.data("placeholder-enabled")?(r==""?(e.value=r,e!=t.activeElement&&c.call(e)):i.hasClass("placeholder")?l.call(e,!0,r)||(e.value=r):e.value=r,i):e.value=r}},r||(o.input=u),i||(o.textarea=u),n(function(){n(t).delegate("form","submit.placeholder",function(){var e=n(".placeholder",this).each(l);setTimeout(function(){e.each(c)},10)})}),n(e).bind("beforeunload.placeholder",function(){n(".placeholder").each(function(){this.value=""})}))}(this,document,Foundation.zj),define("foundation.placeholder",function(){}),define("unifi/view/wizard/ChromeView",["jquery","backbone","msg/Msg","unifi/view/wizard/WelcomeView","unifi/view/wizard/DiscoverView","unifi/view/wizard/WirelessView","unifi/view/wizard/PasswordView","unifi/view/wizard/FinishView","unifi/view/wizard/ProgressView","foundation.placeholder"],function(e,t,n,r,i,s,o,u,a){"use strict";return t.View.extend({events:{"submit form":"onNext","click #Skip":"onSkip","click #Back":"onBack","click #Finish":"onFinish"},el:"#Wizard",initialize:function(){this.localize(),this.listenTo(this.model,"change:step",this.renderStep),this.listenTo(this.model,"invalid",this.invalid)},localize:function(){var t=e(this.el).find("form");t.find("> h1").first().text(n.Wizard.G_UniFiSetupWizardTitle),t.find(".buttons > div > #Back").text(n.Wizard.G_Back),t.find(".buttons > div > #Skip").text(n.Wizard.G_Skip),t.find(".buttons > div > #Next").text(n.Wizard.G_Next),t.find(".buttons > div > #Finish").text(n.Wizard.G_Finish);var r=e("body > #Wrapper > #Modal > .modal-background");r.find("> h1").text(n.E_WontWork),r.find("> p").text(n.E_WontWorkDetail)},onNext:function(t){t.preventDefault();var n=this.model.get("step"),r={v:{}};switch(n){case"wireless":r.v={ssid:!0,securityKey:!0,guest_ssid:!0};break;case"password":r.v={password:!0,admin:!0}}this.el.querySelector("form").checkValidity()&&this.model.isValid(r)&&this.model.step()},onSkip:function(t){this.model.resetStep(this.model.get("step")),this.model.step()},onBack:function(t){this.model.stepBack()},onFinish:function(t){t.preventDefault(),this.model.save({},{success:function(){window.location.replace("/login")}})},render:function(){e("#Main").removeClass("loading");var t=new a({model:this.model});return t.render(),this.renderStep(this.model,this.model.get("step"))},renderStep:function(t,n,a){a=a||{};var f,l,c=!0;switch(n){case"discover":f=i;break;case"wireless":f=s,c=!1;break;case"password":f=o;break;case"finish":f=u;break;default:f=r}return a.model=t,l=new f(a),l.render(),c?this.$el.addClass("required"):this.$el.removeClass("required"),this.model.steps[n].p?this.$el.removeClass("first"):this.$el.addClass("first"),this.model.steps[n].n?this.$el.removeClass("last"):this.$el.addClass("last"),this},invalid:function(t,n,r){t.get("step")==="finish"&&alert(n)}})}),define("unifi/model/PortModel",["unifi/model/Model","underscore","backbone","msg/Msg","app","ubnt/backgrid"],function(e,t,n,r,i,s){"use strict";return e.extend({diagramClasses:function(){var e=[];return this.get("poe_enable")&&e.push("poe"),this.get("op_mode")=="mirror"&&e.push("mirror"),this.get("enable")||e.push("shutdown"),this.get("up")&&(e.push("up"),this.get("speed")==1e3?e.push("green"):(this.get("speed")==100||this.get("speed")==10)&&e.push("orange"),this.get("stp_state")=="discarding"&&e.push("block")),e.join(" ")},diagramTooltip:function(){var e="<table>",t=this.portIdxText(),n=this.get("name"),i=this.statusText(),o=this.get("tx_bytes")&&s.Formatters.Bytes.fromRaw(this.get("tx_bytes")),u=this.get("rx_bytes")&&s.Formatters.Bytes.fromRaw(this.get("rx_bytes")),a=this.poeModeText(),f=this.networksVlansText(),l='<tr class="table-row"><td class="column-name">{1}</td><td class="column-value">{2}</td></tr>';return t&&(e+=r.localize(l,r.G_Port,t)),n&&(e+=r.localize(l,r.G_Name,n)),i&&(e+=r.localize(l,r.G_Status,i)),o&&(e+=r.localize(l,r.G_DevicesTX,o)),u&&(e+=r.localize(l,r.G_DevicesRX,u)),a&&(e+=r.localize(l,r.G_PropertiesPoE,a)),f&&(e+=r.localize(l,r.G_PropertiesNetworksVLANs,f)),e+="</table>",e},portIdxText:function(){var e=this.get("port_idx");return this.get("masked")?"":(this.get("op_mode")=="aggregate"&&(e+="-"+(parseInt(e,10)+parseInt(this.get("aggregate_num_ports")-1,10))),e)},statusText:function(){if(this.get("up")){var e=this.get("speed");return e+=" ",e+=this.get("full_duplex")?r.G_PropertiesFullDuplexAbbrv:r.G_PropertiesHalfDuplexAbbrv,this.get("is_uplink")&&(e+=" ("+r.G_PropertiesUplink+")"),this.get("stp_state")=="discarding"&&(e+=" ("+r.G_PropertiesBlocked+")"),e}return""},poeModeText:function(){if(!this.get("port_poe"))return"";if(this.get("op_mode")!=="switch"||this.get("masked"))return"";var e=this.get("poe_mode");return e==="auto"&&this.get("poe_enable")?this.get("poe_power")+"w":e==="auto"?r.G_PropertiesPoEModePoEPlus:e==="pasv24"?r.G_PropertiesPoEModePassive:e},networksVlansText:function(){if(this.get("aggregated_by"))return r.G_PropertiesAggregatedByPort+" "+this.get("aggregated_by");if(this.get("op_mode")=="mirror")return r.G_PropertiesMirroringPort+" "+this.get("mirror_port_idx");var e=this.get("portconf_id");if(e){var t=i.collection("PortConf").get(e);if(t)return t.get("name")}}})}),define("unifi/model/Device",["unifi/model/Model","unifi/model/PortModel","jquery","backbone","ubnt/backgrid","msg/Msg","underscore","libs/moment","ubnt/ubnt.ip"],function(e,t,n,r,i,s,o,u){"use strict";return e.extend({typeMap:{gateway:"ugw","switch":"usw",ap:"uap",phone:"uph"},copyConfigMap:{US24:["US24P250","US24P500"],US24P250:["US24","US24P500"],US24P500:["US24","US24P250"],US48:["US48P500","US48P750"],US48P500:["US48","US48P750"],US48P750:["US48","US48P500"]},initialize:function(){this.collections={},this.listenTo(this,"change:port_table",this.syncPortTable),this.listenTo(this,"change:port_overrides",this.syncPortTable),(this.attributes.port_table||this.attributes.type=="usw")&&this.syncPortTable()},validate:function(e,t){var n={},r=t?t.partial:null;r=="advance-adopt"&&(e.username||(n.username=s.localize(s.E_CannotBeEmpty,s.G_UN)),e.password||(n.password=s.localize(s.E_CannotBeEmpty,s.G_PW)));if(e.port_overrides&&t.extra&&t.extra.portidx){var i=o.findWhere(e.port_overrides,{port_idx:t.extra.portidx});if(i){if(i.op_mode=="aggregate"&&(!r||r=="aggregate_num_ports")){var u=t.extra.portidx+1,a=t.extra.portidx+3,f=this.numPorts(),l=4,c=this.get("port_table"),h=c.length;for(var p=t.extra.portidx;p<a;p++)if(p<a){var d=c[p];if(d&&d.op_mode!=="switch"){a=p,l=a-t.extra.portidx+1;break}}a>f&&(a=f,l=a-t.extra.portidx+1),this.validator.range(i.aggregate_num_ports,2,l)||(n.aggregate_num_ports=s.localize(s.E_IncorrectNumberRange,s.G_PropertiesAggregatePorts,u,a))}i.op_mode=="mirror"&&(!r||r=="mirror_port_idx")&&(i.mirror_port_idx==t.extra.portidx||!this.validator.range(i.mirror_port_idx,1,this.numPorts()))&&(n.mirror_port_idx=s.localize(s.E_InvalidMirroringPort,i.mirror_port_idx))}}(!r||r=="config_network_wan")&&e.config_network_wan&&(o.size(n.config_network_wan=this.validateNetwork(e,"config_network_wan"))||delete n.config_network_wan),(!r||r=="config_network")&&e.config_network&&(o.size(n.config_network=this.validateNetwork(e,"config_network"))||delete n.config_network),(!r||r=="wlan_overrides")&&e.wlan_overrides&&(n.wlan_overrides={},o.each(e.wlan_overrides,function(t,r){n.wlan_overrides[r]={};var i;if(e.hasOwnProperty("wlanconf")){var u=e.wlanconf.attributes.vlan_enabled;i=t.hasOwnProperty("vlan_enabled")?t.vlan_enabled:u}else i=t.vlan_enabled;i&&t.vlan===""?n.wlan_overrides[r].vlan=s.localize(s.E_CannotBeEmpty,s.G_PropertiesVLAN):t.vlan&&!this.validator.range(t.vlan,2,4095)&&(n.wlan_overrides[r].vlan=s.localize(s.E_IncorrectNumberRange,s.G_PropertiesVLAN,2,4095)),t.x_passphrase&&!this.validator.password(t.x_passphrase)&&(n.wlan_overrides[r].x_passphrase=s.localize(s.E_InvalidPassphrase,s.G_PropertiesPSK)),o.size(n.wlan_overrides[r])||delete n.wlan_overrides[r]},this),o.size(n.wlan_overrides)||delete n.wlan_overrides),e.name&&!this.validator.name(e.name)&&e.name.toLowerCase()!==e.mac.toLowerCase()&&(n.name=s.localize(s.E_InvalidName,s.G_PropertiesAlias));if(o.size(n))return n},validateNetwork:function(e,t){var n={};switch(e[t].type){case"dhcp":e[t].dns1&&!this.validator.ip(e[t].dns1)&&(n.dns1=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesPreferredDNS)),e[t].dns2&&!this.validator.ip(e[t].dns2)&&(n.dns2=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesAlternateDNS));break;case"pppoe":e[t].username||(n.username=s.localize(s.E_CannotBeEmpty,s.G_UN)),e[t].x_password||(n.x_password=s.localize(s.E_CannotBeEmpty,s.G_PW)),e[t].dns1&&!this.validator.ip(e[t].dns1)&&(n.dns1=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesPreferredDNS)),e[t].dns2&&!this.validator.ip(e[t].dns2)&&(n.dns2=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesAlternateDNS));break;case"static":e[t].ip?this.validator.ip(e[t].ip)||(n.ip=s.localize(s.E_IncorrectIPAddress,s.G_IPAddress)):n.ip=s.localize(s.E_CannotBeEmpty,s.G_IPAddress),e[t].netmask?this.validator.netmask(e[t].netmask,e[t].ip)||(n.netmask=s.localize(s.E_IncorrectNetmask,s.G_Netmask)):n.netmask=s.localize(s.E_CannotBeEmpty,s.G_Netmask),e[t].gateway&&!this.validator.ip(e[t].gateway)&&(n.gateway=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesGateway)),e[t].dns1&&!this.validator.ip(e[t].dns1)&&(n.dns1=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesPreferredDNS)),e[t].dns2&&!this.validator.ip(e[t].dns2)&&(n.dns2=s.localize(s.E_IncorrectIPAddress,s.G_PropertiesAlternateDNS))}return n},parse:function(t,n){return t=e.prototype.parse.call(this,t,n),t&&parseInt(t.state,10)!==0&&(t.restarting=!1),t&&(t.uptime?t.uptime=parseInt(t.uptime,10):t.uptime=0),t},toSearch:function(){var e={name:this.attributes.name,mac:this.attributes.mac,ip:this.attributes.ip,status:this.status(),model:this.apModel(),version:this.attributes.version};return this.attributes.vap_table&&o.each(this.attributes.vap_table,function(t,n){e["bssid_"+n]=t.bssid}),e},name:function(){return this.get("name")||this.get("mac")},ip2long:function(){return n.ip2long(this.get("ip"))},getMacNoColons:function(){return this.get("mac").replace(/:/g,"")},apModel:function(){var e=this.get("model")||"";switch(e){case"BZ2":return"UniFi AP";case"BZ2LR":return"UniFi AP-LR";case"U2S48":return"UniFi AP";case"U2L48":return"UniFi AP-LR";case"U2HSR":return"UniFi AP-Outdoor+";case"U2O":return"UniFi AP-Outdoor";case"U5O":return"UniFi AP-Outdoor 5G";case"U7P":return"UniFi AP-Pro";case"U2M":return"UniFi AP-Mini";case"U7E":return"UniFi AP-AC";case"U7Ev2":return"UniFi AP-AC v2";case"U2Sv2":return"UniFi AP v2";case"U2Lv2":return"UniFi AP-LR v2";case"U7O":return"UniFi AP-AC Outdoor";case"p2N":return"PicoStation M2";case"US24":return"UniFi Switch 24";case"US24P250":return"UniFi Switch 24 POE-250W";case"US24P500":return"UniFi Switch 24 POE-500W";case"US48":return"UniFi Switch 48";case"US48P500":return"UniFi Switch 48 POE-500W";case"US48P750":return"UniFi Switch 48 POE-750W";case"UGW3":return"UniFi Security Gateway 3P";case"UGW8":return"UniFi Security Gateway 8P";case"UP5":return"UniFi Phone";case"UP5t":return"UniFi Phone-Pro";case"UP7":return"UniFi Phone-Executive";case"UP5c":return"UniFi Phone";case"UP5tc":return"UniFi Phone-Pro";case"UP7c":return"UniFi Phone-Executive"}return"UniFi "+e},isAntennaGainEditable:function(){var e=this.get("model")||"",t=["U2O","U5O","U2HSR"];return o.indexOf(t,e)!==-1?!0:!1},apIcon:function(){var e=this.get("model")||"";switch(e){case"U7P":return"ap-pro-icon";default:return"ap-icon"}},numPorts:function(){switch(this.get("model")){case"US24":case"US24P250":case"US24P500":return 26;case"US48":case"US48P500":case"US48P750":return 52;case"UGW3":return 3;case"UGW8":return 8}},txPower:function(){var e=this.transmitPower("ng"),t=this.transmitPower("na");return!o.isUndefined(t)&&!o.isUndefined(e)?e>t?e:t:o.isUndefined(t)?o.isUndefined(e)?undefined:e:t},transmitFrequency:function(e){if(e=="ng"){var t=this.transmitPower("ng"),n=this.get("ng-channel"),r={1:2412,2:2417,3:2422,4:2427,5:2432,6:2437,7:2442,8:2447,9:2452,10:2457,11:2462,12:2467,13:2472,14:2484};if(!o.isUndefined(t))return r[n]}if(e=="na"){var i=this.transmitPower("na"),s=this.get("na-channel"),u={7:5035,8:5040,9:5045,11:5055,12:5060,16:5080,34:5170,36:5180,38:5190,40:5200,42:5210,44:5220,46:5230,48:5240,52:5260,56:5280,60:5300,64:5320,100:5500,104:5520,108:5540,112:5560,116:5580,120:5600,124:5620,128:5640,132:5660,136:5680,140:5700,149:5745,153:5765,157:5785,161:5805,165:5825,183:4915,184:4920,185:4925,187:4935,188:4940,189:4945,192:4960,196:4980};if(!o.isUndefined(i))return u[s]}return undefined},uptime:function(e){return e=e||this.get("uptime"),e>0?i.Formatters.Duration.fromRaw(e||0):""},power:function(){var e=0;return o.each(this.get("port_table"),function(t,n){e+=parseFloat(t.poe_power||0,10)}),e.toFixed(2)},uplink:function(){return this.isConnected()?this.get("uplink"):this.get("last_uplink")||this.get("uplink")},uplinks:function(){return this.get("uplink_table")||{}},uplinkDeviceMac:function(){var e=this.uplink();if(e){var t;e.hasOwnProperty("uplink_mac")?t=e.uplink_mac:e.type==="wireless"&&e.hasOwnProperty("ap_mac")&&(t=e.ap_mac);if(t)return t}return""},uplinkDeviceText:function(){var e=this.uplink();if(e){var t=this.uplinkDeviceMac(),n=this.collection.findWhere({mac:t});return n?n.name()+(e.uplink_remote_port?" #"+e.uplink_remote_port:""):t}return""},uplinkRemotePort:function(){var e=this.uplink();if(e){var t=this.uplinkDeviceMac(),n=this.collection.findWhere({mac:t});if(n&&e.uplink_remote_port)return e.uplink_remote_port}return null},uplinkRssi:function(){var e=this.uplink();if(e)return this.calcRssi(e.rssi)},calcRssi:function(e){return e===undefined&&(e=this.get("rssi")),e=parseFloat(e),e?(e>45?e=45:e<5&&(e=5),e=(e-5)/40*99,(e===0?"0":e.toPrecision(2))+"%"):""},apXRate:function(e){return isNaN(e)?"":parseInt(e,10)/1e3+"M"},uplinkTxRate:function(){var e=this.uplink();return e?this.apXRate(e.tx_rate):""},uplinkRxRate:function(){var e=this.uplink();return e?this.apXRate(e.rx_rate):""},uplinkSpeed:function(){var e=this.uplink();return e?e.speed:"Unknown"},uplinkDuplex:function(){var e=this.uplink();return e&&e.full_duplex?"Full Duplex":"Half Duplex"},uplinkDownPackets:function(){var e=this.uplink();return e&&e.rx_packets&&e.rx_bytes?i.Formatters.Bytes.fromRaw(e.rx_packets)+"/"+i.Formatters.Bytes.fromRaw(e.rx_bytes):"0.00 / 0.00"},uplinkUpPackets:function(){var e=this.uplink();return e&&e.tx_packets&&e.tx_bytes?i.Formatters.Bytes.fromRaw(e.tx_packets)+"/"+i.Formatters.Bytes.fromRaw(e.tx_bytes):"0.00 / 0.00"},uplinkActivity:function(){var e=this.uplink(),t=e?e["tx_bytes-r"]:0,n=e?e["rx_bytes-r"]:0,r=t+n,s=0;return r&&(s=i.Formatters.Bytes.fromRaw(r)),s+"B / sec"},uplinkActivityDown:function(){var e=this.uplink(),t=e?e["rx_bytes-r"]:0,n=0;return t&&(n=i.Formatters.Bytes.fromRaw(t)),n+"B / sec"},uplinkActivityUp:function(){var e=this.uplink(),t=e?e["tx_bytes-r"]:0,n=0;return t&&(n=i.Formatters.Bytes.fromRaw(t)),n+"B / sec"},adoptIp:function(){return this.get("adopt_ip")||this.get("ip")},adoptUrl:function(){return this.get("adopt_url")||this.get("inform_url")||"http://unifi:8080/inform"},downlinks:function(){return this.get("downlink_table")||[]},networks:function(){return this.get("network_table")||[]},getChannel:function(){var e=this.get("ng-channel"),t=this.get("na-channel"),n=[];return e&&n.push(e+" (2G)"),t&&n.push(t+" (5G)"),n.length?n.join(", "):""},apChannel:function(){if(!this.get("vap_table"))return"";var e=[],t,r,i;return i=this.get("model"),o.each(this.get("vap_table"),function(s,o){if(s.channel===0)return!0;if((s.state||"RUN")!="RUN")return!0;r=s.radio,r=="na"&&(i=="U7E"||i=="U7O"||i=="U7Ev2")&&(r="ac"),t=s.channel+" ("+r+")",n.inArray(t,e)<0&&(s.radio=="ng"?e=[t].concat(e):e.push(t))}),e.join(", ")},getRadio:function(e){return o.find(this.get("radio_table"),function(t){if(t.hasOwnProperty("radio"))return t.radio===e})},hasRadio:function(e){return this.getRadio(e)===undefined?!1:!0},channel:function(e){var t=this.get(e+"-state")||"INIT",n=this.get(e+"-extchannel")||0,r=n>0?",+1":n<0?",-1":"",i=this.get(e+"-channel")+r;return"INIT"==t?i="":"DFS_WAIT"==t&&(i+=" (DFS Waiting)"),i},transmitPower:function(e){var t=this.get(e+"-state")||"INIT";if("INIT"==t)return undefined;var n=Math.min(this.get(e+"-tx_power"),30),r=this.get(e+"-gain")||0,i=this.get(e+"-eirp")||parseInt(n,10)+r;return i},packetsPerBytes:function(e,t){var n=this.get("stat"),r=n?n[e+"-"+t+"_packets"]:0,s=n?n[e+"-"+t+"_bytes"]:0;return r=r||0,s=s||0,i.Formatters.Bytes.fromRaw(r)+" / "+i.Formatters.Bytes.fromRaw(s)},errorPercentage:function(e,t){var n=this.get("stat"),r=n?n[e+"-"+t+"_retries"]:0,s=n?n[e+"-"+t+"_packets"]:0,o=n?n[e+"-"+t+"_dropped"]:0,u;return r=r||0,s=s||0,o=o||0,u=s+o,i.Formatters.Percentage.fromRaw(r,u)+" / "+i.Formatters.Percentage.fromRaw(o,u)},getOverride:function(e,t){var n=null,r=this.get("wlan_overrides")||[];return o.each(r,function(r){if(r.wlan_id==e&&r.radio==t)return n=r,!1}),n},hasOverrides:function(e,t){var n=!1,r=this.get("wlan_overrides")||[];return o.each(r,function(e){if(e.radio==t)return n=!0,!1}),n},wlan2G:function(e){return this.wlangroup(this.get("wlangroup_id_ng"),"ng",e)},wlan5G:function(e){return this.wlangroup(this.get("wlangroup_id_na"),"na",e)},wlangroup:function(e,t,n){if(!this.get("adopted")||!this.get("radio_"+t)||!n||!o.size(n))return"";var r=n.findWhere({_id:e})||n.findWhere({attr_hidden_id:"Default"}),i=r.get("name");return r.get("roam_enabled")?i+=" (ZH)":this.hasOverrides(r.get("id"),t)&&(i+=" (*)"),i},radio2G:function(){return this.radioChannelAndPower(this.get("radio_ng"))},radio5G:function(){return this.radioChannelAndPower(this.get("radio_na"))},radioChannelAndPower:function(e){if(!this.get("adopted")||!e)return"";var t=e.channel&&!isNaN(e.channel)?parseInt(e.channel,10):"auto",n=e.tx_power_mode||"auto";return n==="custom"&&(n=parseInt(e.tx_power,10)+parseInt(e.antenna_gain,10)+" dBm"),t===0&&(t="auto"),t+" / "+n},clientName:function(e){return e.hostname||e.mac},deviceName:function(e){return e.essid||e.mac},status:function(){var e,t=this.uplink()||{};switch(parseInt(this.get("state"),10)||0){case 0:e=this.get("restarting")?s.G_APRestarting:s.G_APDisconnected;break;case 1:e=s.G_APConnected,this.get("isolated")?e+=" (limited)":t.type=="wire"?this.get("type")!=="ugw"&&(t.max_speed!=t.speed||!t.full_duplex)&&(e+=" ("+t.speed+" "+(t.full_duplex?"FDX":"HDX")+")"):t.type=="wireless"&&(e+=" (wireless)"),this.get("version_incompatible")&&(e+=" (needs upgrade)");break;case 2:this.get("default")?this.get("discovered_via")=="scan"?e=s.G_APIsolatedPending:e=s.G_APPending:e=s.G_APManagedByOthers;break;case 3:e=s.G_APFirmwareMismatch;break;case 4:e=s.G_APUpgrading;break;case 5:e=s.G_APProvisioning;break;case 6:e=s.G_APHeartbeatMissed;break;case 7:e=s.G_APAdopting,t.type=="wireless"&&(e+=" (wireless)");break;case 8:e=s.G_APDeleting;break;case 9:e=s.G_APDisconnected;break;case 10:e=s.G_APAdoptFailed;break;case 11:e=s.G_APIsolated}return e},statusType:function(){switch(parseInt(this.get("state"),10)||0){case 1:case 4:case 5:return"ok";case 2:case 7:case 13:return"pending";case 0:case 3:case 9:case 10:case 11:return"error";default:return"error"}},isConnected:function(){return this.statusType()==="ok"},is11ac:function(){return n.inArray(this.get("model"),["U7E","U7O","U7Ev2"])!==-1},lastSeen:function(){var e=this.get("last_seen"),t;return e?(t=(new Date).getTime()/1e3-parseInt(e,10),isNaN(t)?"":t<86400?i.Formatters.Duration.fromRaw(t)+" ago":u(e+"","X").format("YYYY/MM/DD HH:mm:ss")):s.G_Never},absoluteLastSeen:function(){var e=this.get("last_seen");return e?u(e+"","X").format("YYYY/MM/DD HH:mm:ss"):""},syncPortTable:function(e,i){this.collections.portTable||(this.collections.portTable=new(r.Collection.extend({model:t.extend({idAttribute:"port_idx"})}))),o.each(this.attributes.port_table,n.proxy(function(e){var t=o.filter(this.attributes.port_overrides,function(t){return t.port_idx==e.port_idx});t.length&&(e=o.extend(e,t[0])),e.device=this.get("mac"),this.collections.portTable.add(e,{merge:!0})},this)),this.trigger("syncPortTable")},upgrade:function(e){return this.sync("upgrade",this,e)},adopt:function(e){return this.sync("adopt",this,e)},advanceAdopt:function(e){return this.validationError=this.validate(e.data,o.extend({partial:"advance-adopt"},e)),this.validationError?!1:this.sync("advance-adopt",this,e)},forget:function(e){return this.sync("forget",this,e)},restart:function(e){return this.sync("restart",this,e)},powerCyclePort:function(e){return this.sync("power-cycle",this,e)},clearSwitchCounters:function(e){return this.sync("clear-switch-counters",this,e)},clearPortCounters:function(e){return this.sync("clear-switch-port-counters",this,e)},setVwireUplink:function(e){return this.sync("set-vwire-uplink",this,e)},unsetVwireUplink:function(e){return this.sync("unset-vwire-uplink",this,e)},move:function(e){return this.sync("move",this,e)},copyConfig:function(e){return this.sync("copy-config",this,e)},update:function(e){return this.sync("update",this,e)},locate:function(e){return this.sync("locate",this,e)},updateWlanGroup:function(e,t){var n={};return n["wlangroup_id_"+e]=t.wlangroup_id,n.wlan_overrides=o.reject(this.get("wlan_overrides"),function(t){return t.radio==e}),this.save(n,o.extend(t,{_method:"update-wlangroup-"+e}))},sync:function(e,t,n,i){n=n||{},n._method&&(e=n._method,delete n._method);switch(e){case"read":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/stat/device/"+t.get("mac"),n.type="GET";break;case"update":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/upd/device/"+t.id,n.type="POST",n.data=n.data?JSON.stringify(n.data):JSON.stringify(t.changed);break;case"adopt":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"adopt"}));break;case"advance-adopt":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"adv-adopt"}));break;case"power-cycle":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"power-cycle"}));break;case"clear-switch-counters":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"clear-switch-counters"}));break;case"clear-switch-port-counters":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"clear-switch-port-counters"}));break;case"set-vwire-uplink":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{cmd:"set-vwire-uplink"}));break;case"unset-vwire-uplink":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{cmd:"unset-vwire-uplink"}));break;case"forget":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/sitemgr",n.type="POST",n.data=JSON.stringify({mac:t.get("mac"),cmd:"delete-device"});break;case"restart":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify({mac:t.get("mac"),cmd:"restart"});break;case"upgrade":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify({mac:t.get("mac"),cmd:"upgrade"});break;case"move":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/sitemgr/",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"move-device"}));break;case"copy-config":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr/",n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{mac:t.get("mac"),cmd:"clone-config",origin:n.selectedMac}));break;case"add-device":n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/sitemgr/",n.type="POST",n.data=JSON.stringify({macid:n.macidqr,cmd:"add-device"});break;case"locate":t.get("adopted")?t.set({locating:!t.get("locating")}):t.set({locating:!1}),n.contentType="application/json; charset=utf-8",n.url="/api/s/"+SITE.name+"/cmd/devmgr",n.type="POST",n.data=JSON.stringify({mac:t.get("mac"),cmd:t.get("adopted")?t.get("locating")?"set-locate":"unset-locate":"locate"});break;case"update-wlangroup-ng":n.contentType="application/json",n.url="/api/s/"+SITE.name+"/upd/device/"+t.id,n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{wlangroup_id_ng:t.get("wlangroup_id_ng"),wlan_overrides:t.get("wlan_overrides")}));break;case"update-wlangroup-na":n.contentType="application/json",n.url="/api/s/"+SITE.name+"/upd/device/"+t.id,n.type="POST",n.data=JSON.stringify(o.extend(n.data||{},{wlangroup_id_na:t.get("wlangroup_id_na"),wlan_overrides:t.get("wlan_overrides")}))}return r.sync.call(this,e,t,n)}})}),define("unifi/collection/Devices",["unifi/collection/Collection","underscore","backbone","unifi/model/Device"],function(e,t,n,r){"use strict";return e.extend({model:r,bySite:!0,initialize:function(t){e.prototype.initialize.call(this,t),this.typeMap=(new this.model).typeMap},get:function(n){var r=e.prototype.get.call(this,n);return!r&&t.isObject(n)&&!n.id&&n.get("mac")&&(r=this.getDeviceFromMac(n.get("mac"))),r},getInformIP:function(){var e=this.find(function(e){return e.get("adopted")&&e.get("state")==1&&e.get("inform_ip")});return e===undefined?"":e.get("inform_ip")},hasUpgradableAP:function(){var e=this.find(function(e){return e.get("type")=="uap"&&e.get("state")==1&&e.get("upgradable")});return e?!0:!1},hasUpgradablePhone:function(){var e=this.find(function(e){return e.get("type")=="uph"&&e.get("state")==1&&e.get("upgradable")});return e?!0:!1},isUpgradingDevices:function(){var e=this.find(function(e){return e.get("rollupgrade")});return e?!0:!1},getDeviceFromMac:function(e){return this.find(function(t){return t.get("mac")==e})},sortByBytes:function(){var e=this.sortBy(function(e){return-1*(e.get("bytes")||0)});return e},sortByBytesOnlyAps:function(){var e=this.sortByBytes();return t.filter(e,function(e){return e.get("type")==="uap"})},url:function(){return"/api/s/"+SITE.name+"/stat/device"},all:function(e){return this.fetch(t.extend(e,{_method:"read-all"}))},discover:function(){return this.fetch({_method:"discover"})},scanUplink:function(e){return this.sync("scan-uplink",this,e)},upgradeAPs:function(e){return this.sync("upgrade-aps",this,e)},upgradePhones:function(e){return this.sync("upgrade-phones",this,e)},sync:function(e,r,i){i=i||{},i._method&&(e=i._method,delete i._method);switch(e){case"read-all":i.contentType="application/json; charset=utf-8",i.url="/api/stat/device",i.type="POST",i.data=JSON.stringify(i.data||{});break;case"discover":i.contentType="application/json; charset=utf-8",i.url="/api/stat/device",i.type="POST",i.data=JSON.stringify({state:2,"default":!0});break;case"read":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/stat/device",i.type="GET";break;case"scan-uplink":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/cmd/devmgr",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{},{cmd:"scan-uplink"}));break;case"upgrade-aps":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/cmd/devmgr",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{},{cmd:this.isUpgradingDevices()?"unset-rollupgrade":"set-rollupgrade"}));break;case"upgrade-phones":i.contentType="application/json; charset=utf-8",i.url="/api/s/"+SITE.name+"/cmd/devmgr",i.type="POST",i.data=JSON.stringify(t.extend(i.data||{},{cmd:"upgrade-all",type:"uph"}))}return n.sync.call(this,e,r,i)}})}),define("unifi/model/WizardModel",["underscore","backbone","unifi/collection/Devices","msg/Msg"],function(e,t,n,r){"use strict";return t.Model.extend({idAttribute:"_id",urlRoot:"/api/",defaults:{step:"welcome",country:840,language:"en_us",timezone:"",guest:!1,ssid:"",guest_ssid:"",securityKey:"",admin:"",up:!0},steps:{welcome:{p:!1,n:"discover"},discover:{p:"welcome",n:"wireless"},wireless:{p:"discover",n:"password"},password:{p:"wireless",n:"finish"},finish:{p:"password",n:!1}},validate:function(t,n){n=n||{};var i=n.v||{password:!0,ssid:!0,guest_ssid:!0,securityKey:!0,admin:!0};if(i.password&&!t.password)return r.Wizard.E_PasswordRequired;if(i.password&&t.password!==t["password-confirm"])return r.Wizard.E_PasswordsDontMatch;if(t.ssid){if(i.ssid&&!/^([\x20-\x7E]){1,32}$/.test(t.ssid))return r.Wizard.E_SsidAlphanumeric;if(i.guest_ssid&&t.guest&&!/^([\x20-\x7E]){1,32}$/.test(t.ssid))return r.Wizard.E_SsidAlphanumeric;if(i.securityKey&&!/(^([\x20-\x7E]){8,63}$)/.test(t.securityKey))return r.Wizard.E_SsidPasswordLength}if(i.admin&&!/^[_.A-Za-z0-9][-\@_.A-Za-z0-9]*\$?$/.test(t.admin))return r.Wizard.E_AdminNameAlphanumeric},step:function(){return this.set({step:this.steps[this.get("step")].n})},stepBack:function(){return this.set({step:this.steps[this.get("step")].p})},resetStep:function(t){switch(t){case"wireless":this.unset("ssid"),this.unset("securityKey"),this.unset("guest"),this.unset("guest_ssid")}},set:function(r,i,s){var o=i,u=s;return typeof r=="object"?o=e.defaults({},i,{validate:!1}):u=e.defaults({},s,{validate:!1}),t.Model.prototype.set.call(this,r,i,s)},getTimezoneOffset:function(){var e=new Date,t=new Date(e.getFullYear(),0,1),n=new Date(e.getFullYear(),6,1),r=Math.max(t.getTimezoneOffset(),n.getTimezoneOffset()),i=e.getTimezoneOffset()<r,s=e.toString().match(/GMT([-|+]\d{2})/),o;return s&&s.length>1&&(o=parseInt(s[1],10),i&&(o-=1)),o},fetchWlanGroupId:function(n){var r=this;return n.url="/api/list/wlangroup",n.data={json:JSON.stringify({name:"Default"})},n.success=function(t){r.set({id:t.data[0]._id})},t.ajax(n)},fetchSysInfo:function(r){var i=this;return r.url="/api/stat/sysinfo",r.data={json:JSON.stringify({})},r.success=function(n){i.set({ccodes:e.map(n.data[0].ccodes,function(t){return e.pick(t,"code","name")})})},t.ajax(r)},fetchDeviceStatus:function(t){return this.get("devices")||this.set({devices:new n}),this.get("devices").discover()},fetch:function(r){r=r?e.clone(r):{},r.parse===void 0&&(r.parse=!0);var i=this,s=r.success;return r=e.defaults(r,{type:"POST"}),t.$.when(this.fetchWlanGroupId(r),this.fetchSysInfo(r),this.fetchDeviceStatus(r)).then(function(e,t,n){s&&s(i,null,r),i.trigger("sync",i,null,r)})},_saveSetting:function(n){return n.data={json:JSON.stringify(n.data)},n.success=!1,n.type="POST",t.ajax(n)},cmdSiteMgr:function(){var t={};return t.url="/api/cmd/sitemgr",t.data={name:this.get("admin"),lang:this.get("language"),timezone:this.get("timezone"),x_password:this.get("password"),cmd:"add-default-admin"},this._saveSetting(t)},addWlanConf:function(){if(!this.get("ssid"))return!0;var t={};t.url="/api/add/wlanconf",t.data={wlangroup_id:this.get("id"),enabled:!0,name:this.get("ssid"),security:"wpapsk",x_passphrase:this.get("securityKey")};var n={url:"/api/add/wlanconf",data:{wlangroup_id:this.get("id"),is_guest:!0,enabled:!0,name:this.get("guest_ssid"),security:"open"}},r=this._saveSetting(t),i=this;return this.get("guest")?r.then(function(){return i._saveSetting(n)}):r},cmdAdopt:function(){var r={};r.url="/api/cmd/devmgr";var i=new t.Collection(e.values(this.get("devices").selectedDevices));return r.data={cmd:"adopt",macs:i.pluck("mac")},this._saveSetting(r)},setCountry:function(){var t={};return t.url="/api/set/setting/country",t.data={code:parseInt(this.get("country"),10)},this._saveSetting(t)},setTimezone:function(){var t={};return t.url="/api/set/setting/locale",t.data={timezone:this.get("timezone")},this._saveSetting(t)},cmdInstalled:function(){var t={};return t.url="/api/cmd/system",t.data={cmd:"set-installed"},this._saveSetting(t)},cmdRestore:function(){this.set("up",!1);var t={};return t.url="/api/s/default/cmd/system",t.data={cmd:"restore"},this._saveSetting(t)},pollServer:function(){var n=this;t.$.getJSON("/status").done(function(e){e.meta.rc==="ok"&&e.meta.up?n.set("up",e.meta.up):window.setTimeout(function(){n.pollServer()},1500)}).fail(function(e,t,r){window.setTimeout(function(){n.pollServer()},1500)})},initialize:function(n){e.bindAll(this,"cmdInstalled","cmdAdopt","cmdSiteMgr","setCountry","setTimezone","addWlanConf")},sync:function(t){var n=t.success,r=this;return this.cmdSiteMgr(t).then(this.addWlanConf).then(this.cmdAdopt).then(this.setCountry).then(this.setTimezone).then(this.cmdInstalled).done(function(){n?n(r,null,t):window.location.href="/login"})}})}),define("wizard",["jquery","backbone","unifi/view/wizard/ChromeView","unifi/model/WizardModel","foundation"],function(e,t,n,r){"use strict";e(function(){e(document).foundation();var i=new r,s=new n({model:i});i.fetch({wait:!0}).done(function(){s.render()})})});