var PF=PF||{},noOp,topLocation,trackClose,JSEncryptExports,JSEncrypt,Account,AccountModuleOption,AccountPayout,AccountUnderwritingInfo,AdditionalInfo,AdditionalInfoOption,AdditionalInfoResponse,AdditionalInfoBooking,AdditionalInfoGoodPurchase,AdditionalInfoGoodVariant,AddOn,AddOnBooking,AddOnImage,AddOnSpace,Alert,AlertNotification,Billing,BillingAccount,BitcoinTransaction,BitcoinWallet,Booking,BookingDetail,BookingsRequest,timeOut,CustomerLead,CustomGroup,DriversLicense,EmailNotification,EmailNotificationDetail,GeoVariable,Good,GoodAttribute,GoodImage,GoodPurchase,GoodVariant,Gratuity,GratuityOptionsByAccount,Listing,ListingCategory,Log,Module,ModuleOption,PaymentInstrument,PendingSubscription,PromotionCode,PromotionCodeGroup,GoodPurchaseRefundRequest,RateRule,Referral,UserReferralQuestion,RentalRate,Report,ReportCategory,ReportParameter,RangeDatePickerOptionValues,ReportResult,ReportView,Resource,ResourceSpace,ResourceBooking,ResourceBookingGroup,Role,SimpleCalendarAvailability,SiteProperty,SMTPQueueDetail,Space,SpaceAvailability,SpaceDepositTimeTable,SpaceImage,SubscriptionBilling,Terms,Tier,Url,User,VariableObject,EditListingViewModel;PF.checkBrowserCompat=function(){function e(n,t){var i=document.createElement("script");i.type="text/javascript";i.readyState?i.onreadystatechange=function(){(i.readyState=="loaded"||i.readyState=="complete")&&(i.onreadystatechange=null,t())}:i.onload=function(){t()};i.src=n;document.getElementsByTagName("head")[0].appendChild(i)}var t,u,f=navigator.userAgent,i,n=f.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i)||[],r;return(/trident/i.test(n[1])?(i=/\brv[ :]+(\d+(\.\d+)?)/g.exec(f)||[],t="IE "+(i[1]||""),u=i[1]):(n=n[2]?[n[1],n[2]]:[navigator.appName,navigator.appVersion,"-?"],(i=f.match(/version\/([\.\d]+)/i))!=null&&(n[2]=i[1]),t=n.join(" "),u=n[2]),!window.addEventListener||(t.indexOf("IE")>=0||t.indexOf("msie")>=0)&&parseFloat(u)<=8)?(r='<div id="dialog-message" style="z-index:20000 !important;"><div style="float:left;margin-right:5%;width:25%;"><img src="/content/images/dino-browser.gif" /><\/div>',r+='<div style="float:left;width:65%">',r+='We recommend you upgrade to have a better experience. You can also try any of the following modern browsers:<p/><ul><li><a href="https://www.google.com/chrome/">Chrome<\/a> (our favorite!)<\/li><li><a href="http://www.mozilla.org/en-US/firefox/new/">Firefox<\/a><\/li><li><a href="http://www.apple.com/safari/">Safari<\/a><\/li><li><a href="http://windows.microsoft.com/en-us/internet-explorer/download-ie">Internet Explorer<\/a> (Latest version, v9 or above)<\/li><\/ul><\/div><\/div>',window.jQuery?PF.Modals.Generic.Show({title:"You're Using an Unsupported Browser!",description:r}):(document.body.innerHTML+=r,e("https://code.jquery.com/jquery-1.11.2.min.js",function(){e("/Scripts/external/jquery-ui-1.11.2.custom.min.js",function(){$("#dialog-message").dialog({modal:!0,title:"You are using an unsupported browser!",width:500})})})),pf_dataLayer.push({event:"Unsupported Browser: "+t,eventCategory:"Internal"}),!1):!0};PF=PF==null?{}:PF;PF={Views:{},Controls:{},PartialViews:{},WS:{},Modals:{},Controls:{},Moment:PF&&PF.Moment==null?PF.moment:PF.Moment,checkBrowserCompat:PF.checkBrowserCompat};window.console||(noOp=function(){},console={log:noOp,warn:noOp,error:noOp});String.prototype.includes||(String.prototype.includes=function(n,t){"use strict";return typeof t!="number"&&(t=0),t+n.length>this.length?!1:this.indexOf(n,t)!==-1});PF.Views.Master=function(){var r={Init:function(){return u(),this}},t=0,u=function(){o();e();PF.User.Init();i();$(self).trigger("pfinit");PF&&PF.Modals&&PF.Modals.Location&&f()},f=function(){if(PF.Controls&&PF.Controls.LocationDropdown){var n=new PF.Controls.LocationDropdown,t=new PF.Modals.Location({onSave:function(t){n.selectRegion(t)}});n.init();t.init();PF.User.addLoginListener(function(t){var i=t.DefaultSearchRegion||PF.defaultRegionCookie.getCookieValue();i?n.selectRegion(t.DefaultSearchRegion):PF.DataProxy.updateUserRegion({region:i})})}},e=function(){var n=$("#divError").hide();n.length>0&&n.html().length>3&&PF.Modals.Generic.Show({title:"Error",description:n.html()});PF.Tooltips.Init();$("input[placeholder],textarea[placeholder]").each(function(){var n=$(this);n.attr("title",n.attr("placeholder"))});window.console&&window.console.log||(window.console={log:function(){try{}catch(n){}}},a());$(".pf-tabs").each(function(){var n=$(this);n.find("#tab"+n.find("ul.tabstrip li.active").text().replace(/\s/g,"")).show()});v();$("#feedback_tab_text").text("Concierge");$("#zenbox_tab").attr("title","Try our concierge service").click(function(){pf_dataLayer.push({event:"TabConciergeClicked",eventCategory:"Communication"})})},o=function(){$(document).on("keyup",s);$("ul.tabstrip li").on("click",h);$(".dropdown-menu.select-behavior li").click(c);$(self).on("resize",i);$("textarea[caption], input[caption], select[caption]").on("focus",PF.showCaption);$("textarea[caption], input[caption], select[caption]").on("blur",PF.hideCaption);$("input[format]").on("change",l)},s=function(n){var t=n.keyCode||n.which},i=function(){var n=$(".container").first().width(),r,i;n!=t&&(r=n==1170?"xwide":n==940?"wide":n<940&&n>724?"normal":n<=724&&n>640?"small":n<=640?"extrasmall":"extrasmall",i={resolution:r,width:n},PF.currentRes=i,$(self).trigger($.Event("reschange",i)),$("#loginModal").width("auto"));t=n},h=function(){var n=$(this),t=n.parent().parent();t.find(".tab-container").hide();t.find("#tab"+n.text().replace(/\s/g,"")).show();n.hasClass("active")||(t.find("ul.tabstrip li").removeClass("active"),n.addClass("active"));n.text()=="Calendar"&&$("#calendar").find("span.fc-button-content").last().click()},c=function(){var t=$(this),i=t.find("a"),n=t.parent().parent(),r=n.find(".dropdown-label");r.text(i.text());n.attr("val",i.attr("val"));n.trigger("change")},l=function(){var n=$(this),t=n.pVal(),i=n.attr("format");i=="currency"&&(t=PF.formatCurrency(t,!0));n.pVal(t)},y=function(n){var t=parseFloat(n);return isNaN(t)?n=0:t*2%1!=0&&(t=Math.round(t*2)/2),t},a=function(){$("[placeholder]").focus(function(){var n=$(this);n.val()==n.attr("placeholder")&&(n.val(""),n.removeClass("placeholder"))}).blur(function(){var n=$(this);(n.val()==""||n.val()==n.attr("placeholder"))&&(n.addClass("placeholder"),n.val(n.attr("placeholder")))}).blur();$("[placeholder]").parents("form").submit(function(){$(this).find("[placeholder]").each(function(){var n=$(this);n.val()==n.attr("placeholder")&&n.val("")})})},n=PF.Views,v=function(){var t,u;if(!n.MyListingsCalendar&&!n.CreateEditSpace&&!n.Generic_Subpages&&!n.SpaceDetails&&!n.Favorites&&!n.BirthdayBuilder&&!n.Checkout&&!n.NewHomePage){var f=$(document.body).children(".container:visible"),i=$(window).height(),r=0;f.each(function(){var n=$(this);n.hasClass("container")&&(r+=n.outerHeight(!0))});r<i&&(t=$(".main-container"),t.height(t.outerHeight()+(i-r)),u=document.body.scrollHeight,u>i&&t.height(t.outerHeight()-(u-i)))}};return r}();$(document).ajaxError(function(n,t){t&&t.status===401&&window.location.reload()});$(document).ajaxComplete(function(n,t){if(t&&t.responseText)try{var i=JSON.parse(t.responseText);i&&i.Redirect&&window.location.replace(i.Redirect)}catch(r){}});$(document).ajaxStart(function(){$("html").addClass("busy")});$(document).ajaxStop(function(){$("html").removeClass("busy")});jQuery.ajaxSetup({beforeSend:function(n){n.setRequestHeader("X-Requested-With","XMLHttpRequest")}});$(function(){var i=0,r=0,n=[],t;$(".row-blocks .blocks, .equalize .boxed-in").each(function(){if(t=$(this),topPostion=t.position().top,r!=topPostion){for(currentDiv=0;currentDiv<n.length;currentDiv++)n[currentDiv].height(i);n.length=0;r=topPostion;i=t.height();n.push(t)}else n.push(t),i=i<t.height()?t.height():i;for(currentDiv=0;currentDiv<n.length;currentDiv++)n[currentDiv].height(i)})});PF=PF||{};PF.createGlobalNamespace=function(n){var t=window,i,r=function(n){return typeof n=="undefined"};t=window;n.forEach(function(n){var u=t[n];i?t=t[n]={}:r(u)?(t=t[n]={},i=!0):t=u})};PF.defaultRegionCookie=new function(){var n="placefull.geo.user_location";this.setCookieIfNecessary=function(t){var i=PF.User.DefaultSearchRegion||t||$.cookie(n);return i!==$.cookie(n)&&$.cookie(n,i,{path:"/",expires:90}),i};this.getCookieValue=function(){return $.cookie(n)}};PF.ordinalSuffix=function(n){if(isNaN(n))return n+"";var t=n%10;return t==1&&n!=11?n+"st":t==2&&n!=12?n+"nd":t==3&&n!=13?n+"rd":n+"th"};PF.PublicKey2048="-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAykWkBWcjTol0c2L1j/DA8umjb7jg6TqQA7kIzBQmxG5gShp7HeLIUdGf56RyDmdCTNIfP69C7t3H/ncFh27qlqk5o+7/FFBCrkGslxicOua/pc6YdMFR5dDHGRIqo6ZtY6Aoo+VAcRa6H5lwuj4dRowFxtACObyG/PlbO3rjIqU+xQnRHOrRhQZkR7h8Wb/VvkvSRQFxLA8HWguRs24bV50uq7rvBMziLy9TBfYJWZ8KWNf7JF2zygPaSLup6N50dVFe4H4bZI7ZpKcqhrMhclLE0y1Qa6yg1kgiFHarB05a8B0qvAsGLKHkZPJgzMWtk5XizvMmlhbisWt+mM7AewIDAQAB -----END PUBLIC KEY-----";PF.Moment=PF.Moment==null?PF.moment:PF.Moment;PF.HoursArray=["12:00 am","1:00 am","2:00 am","3:00 am","4:00 am","5:00 am","6:00 am","7:00 am","8:00 am","9:00 am","10:00 am","11:00 am","12:00 pm","1:00 pm","2:00 pm","3:00 pm","4:00 pm","5:00 pm","6:00 pm","7:00 pm","8:00 pm","9:00 pm","10:00 pm","11:00 pm"];PF.formatDate=function(n,t){if(typeof n=="string"&&(n=PF.parseMVCDate(n)),!n||!n.getMonth)return"";if(typeof n=="string"&&(n=PF.parseMVCDate(n)),t)return PF.Moment(n).format(t);var i=n.getMonth()+1;return i==13&&(i=1),i<10&&(i="0"+i),i+"/"+n.getDate()+"/"+n.getFullYear()};PF.formatDateTime=function(n,t){return t=t||" ",PF.formatDate(n)+t+PF.formatPrettyTime(n)};PF.formatShortPrettyDate=function(n){typeof n=="string"&&(n=PF.parseMVCDate(n));var t=(new Date).getYear()==n.getYear()?"":" "+n.getFullYear();return["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"][n.getMonth()]+" "+n.getDate()+t};PF.formatPrettyTime=function(n,t,i){var u,r,e,f;return!n||!n.getMonth?"":(u=n.getHours(),r=n.getMinutes(),t=t===undefined?!0:t,i=i===undefined?!0:i,u==23&&r==59&&(u=0,r=0),e=u>12?u-12:u,e==0&&(e=12),r<10&&(r="0"+r),f=e,(i||r!=0)&&(f=f+":"+r),t&&(f=f+(u>=12?"pm":"am")),f)};PF.formatPrettyDate=function(n,t){if(typeof n=="string"&&(n=PF.parseMVCDate(n)),t)return PF.Moment(n).format(t);return["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"][n.getMonth()]+" "+PF.ordinalSuffix(n.getDate())+" "+n.getFullYear()};PF.formatPrettyDuration=function(n){var t,i;return n?(t=PF.Moment.duration(n,"minutes"),n>60)?(i=t.hours()+" hr ",i+(t.minutes()>0?t.minutes()+" min":"")):t.asMinutes()+" min":null};PF.cleanDate=function(n){if(n.indexOf("Date(")==-1)return n;n=n.split("(")[1].split(")")[0];var i=new Date(parseInt(n)),t=i.getMonth()+1;return t==13&&(t=1),t<10&&(t="0"+t),t+"/"+i.getDate()+"/"+i.getFullYear()};PF.cleanTime=function(n){if(n.indexOf("Date(")==-1)return n;n=n.split("(")[1].split(")")[0];var t=new Date(parseInt(n)),i=t.getHours()+":"+t.getMinutes();return t.getMinutes()==0&&(i+="0"),i};PF.imgError=function(n){return n.onerror="",$(n).attr("src","/Content/images/no-space-image.png"),!0};PF.getReferrerHost=function(n){var t=n||!1,i=t?PF.stripSubdomain():window.location.hostname;return window.location.protocol+"//"+i};PF.stripSubdomain=function(){var n=window.location.hostname,t=n.split(".");return t.length===3&&(n=t[1]+"."+t[2]),n};PF.parseMVCDate=function(n){return n==null||typeof n=="undefined"?n:PF.Moment(n).toDate()};PF.getDuration=function(n,t,i){var n=PF.Moment(n,["hh:mm a","H:mm"]),t;return datePortion=(t=="12:00 AM"?PF.Moment().add("days",1):PF.Moment()).format("MM/DD/YYYY"),correctMidnight=datePortion+" "+t,t=PF.Moment(correctMidnight,["MM/DD/YYYY hh:mm a","MM/DD/YYYY H:mm"]),i?t.diff(n,"minutes"):t.diff(n,"hours")};PF.formatCurrency=function(n,t,i,r){var o,u,f,e;for((n==null||typeof n=="undefined")&&(n="0"),n=n.toString().replace(/\$|\,/g,""),isNaN(n)&&(n="0"),o=n==(n=Math.abs(n)),n=Math.floor(n*100+.50000000001),u=n%100,n=Math.floor(n/100).toString(),u===0&&r?u="00":u===0?u="":u<10&&(u="0"+u),u&&(u="."+u),i&&(u=""),f=0;f<Math.floor((n.length-(1+f))/3);f++)n=n.substring(0,n.length-(4*f+3))+","+n.substring(n.length-(4*f+3));return e=(o?"":"-")+(t?"":"$")+n+u,t?e.replace(/\$/g,""):e};PF.getCurrency=function(n){return n.toString().replace(/\$|\,/g,"")};PF.formatTime=function(n){var t,i,r;return!n||!n.getMonth?"":(t=n.getHours(),i=n.getMinutes(),t==23&&i==59&&(t=0,i=0),r="AM",t>11&&(r="PM"),t>12&&(t=t-12),t==0&&(t=12),i<10&&(i="0"+i),t+":"+i+" "+r)};PF.formatTimeMilitary=function(n){if(typeof n=="string"&&(n=PF.parseMVCDate(n)),!n||!n.getMonth)return"";var i=n.getHours(),t=n.getMinutes();return i==23&&t==59&&(i=0,t=0),t<10&&(t="0"+t),i+":"+t};PF.formatMilTimeString=function(n){return PF.formatTime(new Date("12/21/2012 "+n))};PF.convertTimeZone=function(n,t,i){var r=PF.Moment(n);return t?(i=i?PF.Moment.tz.getZoneSet(i):PF.Moment.tz.getZoneSet(jstz.determine().name()),t=PF.Moment.tz.getZoneSet(t),t.zones.length>0?r.add("minutes",i.offset(r)-t.offset(r)):r.add("minutes",-i.offset(r)),r.toDate()):r.toDate()};PF.convertTimeZoneToUTC=function(n){var t=PF.Moment(n);return sourceTZ=PF.Moment.tz.getZoneSet(jstz.determine().name()),t.add("minutes",sourceTZ.offset(t)),t.toDate()};PF.timeZoneAbbr=function(n,t){return t?(tzZones=PF.Moment.tz.getZoneSet(t).zones,tzZones&&tzZones.length>0)?(abbr=tzZones[tzZones.length-1].letters,PF.Moment(n).isDST()?"("+abbr.replace("%s","D")+") - "+t:"("+abbr.replace("%s","S")+") - "+t):null:t};PF.isSameDay=function(n,t){try{return n.getFullYear()==t.getFullYear()&&n.getMonth()==t.getMonth()&&n.getDate()==t.getDate()}catch(i){return!1}};PF.getDayName=function(n){typeof n=="string"&&(n=new Date(n));return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][n.getDay()]};PF.betweenDates=function(n,t,i){if(i.valueOf()-n.valueOf()<0)return!1;var r=i.valueOf(),u=t.valueOf();return i.valueOf()-t.valueOf()>0?!1:!0};PF.getHoursBetween=function(n,t){var i=t.valueOf()-n.valueOf(),r=i/1e3,u=r/60;return u/60};PF.getMonthsBetween=function(n,t){var i=n.getFullYear(),r=t.getFullYear(),u=n.getMonth(),f=t.getMonth(),e=r-i;return f-u+e*12};PF.isValidDate=function(n){var t=n.getTime();return t===t};PF.getCssVal=function(n,t){var i=n.css(t);return parseFloat(i.replace(/px/g,""))};PF.confirm=function(n){n.title||(n.title="Please Confirm");PF.Modals.Generic.Show(n)};PF.showError=function(n,t){var i={title:"Error encountered",description:n};t||(i.duration=3333);PF.Modals.Generic.Show(i)};PF.clone=function(n){return $.parseJSON(JSON.stringify(n))};PF.getCookie=function(n){var r=n+"=",u="",t,i;return document.cookie.length>0&&(t=document.cookie.indexOf(r),t!=-1&&(t+=r.length,i=document.cookie.indexOf(";",t),i==-1&&(i=document.cookie.length),u=unescape(document.cookie.substring(t,i)))),u};PF.showCaption=function(){var t=$(this),i,u,n;if(t.attr("isrich")&&(t=t.prev()),i=$(this).attr("caption"),u=$(this).attr("reposition"),typeof i!="undefined")i.indexOf(" ")==-1?n=$("#"+i):(n=$("<div class=caption-bubble><div class=caption-content><p>"+i+"<\/p><\/div><div class=nose><\/div><\/div>"),t.after(n));else return;$(this).data("captionEl",n);var r=n.find(".caption-content"),o=n.find(".nose"),f=r.height()*.3,e=t.attr("captionPositionElement")?$("#"+t.attr("captionPositionElement")).position():t.position(),s=r.height()/2;u!="no"?(n.css({height:r.height(),top:e.top+(f-s),left:20+e.left+t.width(),display:"none",visibility:"visible",zIndex:10010}),n.css("display")!="none"&&o.css("top",f)):n.css({height:r.height(),display:"none",visibility:"visible",zIndex:10010});n.fadeIn()};PF.hideCaption=function(){try{$(this).data("captionEl").fadeOut()}catch(n){}};PF.showProgress=function(n){PF.Modals.ProgressIndicator.Show({message:n})};PF.setPageCategoryForTagManager=function(n){n&&(typeof pf_dataLayer=="undefined"?pf_dataLayer=[{pageCategory:n}]:pf_dataLayer.push({pageCategory:n}))};PF.PrivateLabel=function(){var n=!1,t=!1;typeof PF.PrivateLabel!="undefined"&&(n=PF.PrivateLabel.Site,n=PF.PrivateLabel.Merchant);var r=function(r){r&&(n=r.Site,t=r.Merchant);typeof PF.PrivateLabel=="undefined"||r||(n=PF.PrivateLabel.Site,n=PF.PrivateLabel.Merchant);i.Site=n;i.Merchant=t},u=function(n){return n?(n=n.concat(PF.PrivateLabel.Site?"?privatelabel=true":""),PF.PrivateLabel.Site?n.concat(PF.FaceBook.Site?"&facebook=true":""):n.concat(PF.FaceBook.Site?"?facebook=true":"")):n},i={Site:n,Merchant:t,CreatePrivateLabelFaceBookURL:function(n){return u(n)},Init:function(n){return r(n),this}};return i}();PF.FaceBook=function(){var n=!1,i,t;return typeof PF.FaceBook!="undefined"&&(n=!1),i=function(i){i&&(n=i.Site);typeof PF.PrivateLabel=="undefined"||i||(n=PF.PrivateLabel.Site);t.Site=n},t={Site:n,Init:function(n){return i(n),this}},t}();PF.SiteProperty=function(){var t=window.location.hostname,n=t.split(".");return n.length===3&&(n[1]==="placefull"||n[1]==="yourplacefull"||n[1]==="pf")?n[1]:n.length===2&&(n[0]==="placefull"||n[0]==="yourplacefull"||n[0]==="pf")?n[0]:n.length===1&&n[0]==="localhost"?n[0]:null};PF.hasStringMatch=function(n,t){var i,r,u;if(!n)return!1;if(!t)return!0;n=n.toLowerCase();t=t.toLowerCase();i=!0;r=t.split(" ");for(u in r)i=i&&n.indexOf(r[u])!=-1;return i};PF.StringFormat=function(){for(var i,t=arguments[0],n=0;n<arguments.length-1;n++)i=new RegExp("\\{"+n+"\\}","gm"),t=t.replace(i,arguments[n+1]);return t};PF.PopupCenter=function(n,t,i,r){var u=window.screenLeft!=undefined?window.screenLeft:screen.left,f=window.screenTop!=undefined?window.screenTop:screen.top,e=window.innerWidth?window.innerWidth:document.documentElement.clientWidth?document.documentElement.clientWidth:screen.width,o=window.innerHeight?window.innerHeight:document.documentElement.clientHeight?document.documentElement.clientHeight:screen.height,s=e/2-i/2+u,h=o/2-r/2+f,c=window.open(n,t,"width="+i+", height="+r+", top="+h+", left="+s);window.focus&&c.focus()};PF.getTextWithoutHTML=function(n,t){var r=!1,u="",i;if(n)for(t&&(n=n.replace(new RegExp("<br>","g"),"\n")),n=n.replace(new RegExp("&nbsp;","g")," "),i=0;i<n.length;i++)n.charAt(i)==="<"?r=!0:n.charAt(i)===">"?r=!1:r||(u+=n.charAt(i));return u};PF.getURLParameterValue=function(n){return decodeURIComponent((new RegExp("[?|&]"+n+"=([^&;]+?)(&|#|;|$)").exec(location.search)||[,""])[1].replace(/\+/g,"%20"))||null};PF.detectTagTypeInString=function(n,t){var i=n.valueOf(),r;return i=i.replace(/&#060;/g,"<"),i=i.replace(/&#062;/g,">"),i=i.replace(/&lt;/g,"<"),i=i.replace(/&gt;/g,">"),r=new RegExp("<[/]?"+t+">","gi"),r.test(i)};PF.detectKnownBadTagsInString=function(n){for(var o,r,t,u,s,f=["script","iframe","object","embed","applet","frame","frameset"],e=!1,h=new RegExp("<iframe.*?src=[\"'](.+?)[\"'].*?>.*?<\/iframe>","gi"),c=new RegExp("src=[\"'](.+?)[\"']","gi"),l=new RegExp("https://(www.)?youtube.com"),a=new RegExp("https://(www.)?vimeo.com"),v=new RegExp("http://","gi"),i=0;i<f.length;i++)if(PF.detectTagTypeInString(n,f[i]))if(f[i]==="iframe"){for(o=n.match(h),r=0;r<o.length;r++)if(t=o[r].match(c),t!==null&&t!==undefined&&t.length>0)for(u=0;u<t.length;u++)s=t[u],s.search(l)===-1&&s.search(a)===-1&&(e=!0)}else e=!0;return e};PF.logFrontEndError=function(n,t,i,r,u,f){$.ajax({type:"POST",url:"/Api/Logging/Log",data:JSON.stringify({Item:n,UserAgent:navigator.userAgent,LineNumber:i,ColumnNumber:r,ErrorObj:u,FileName:t,LogType:f}),contentType:"application/json; charset=utf-8"})};PF.hasDownloadAttribute=function(){var n=document.createElement("a");return typeof n.download!="undefined"?!0:!1};PF.getBootstrapVersion=function(){return $.fn.tooltip.Constructor.VERSION!=null?$.fn.tooltip.Constructor.VERSION.substring(0,1):"2"};window.onerror=function(n,t,i,r,u){PF.logFrontEndError(n,t,i,r,u,PF.LogType.Error)};PF.copyElementInnerTextToClipboard=function(n){try{var i=document.getElementById(n),t=document.createElement("textarea");return t.value=i.innerText,t.readOnly=!0,t.style.contain="strict",t.style.position="absolute",t.style.left="-9999px",t.style.fontSize="12pt",document.body.appendChild(t),t.select(),t.selectionStart=0,t.selectionEnd=i.innerText.length,document.execCommand("copy"),t.parentNode.removeChild(t),!0}catch(r){return alert("This web browser does not support Copy to Clipboard;"),!1}};PF.roundToTwoByMathRound=function(n){return Math.round(n*100)/100};PF.checkBookingHasPromotionCode=function(n){return n.promotionCode()||n.rentalRate()&&n.rentalRate().rateRule().ruleName()===PF.RateRule.Promotion};PF=PF||{};PF.Tooltips=function(){var f={Init:function(){o();e(t)}},n,t,i=!1,e=function(){t.find(".pficon.pftooltip").on("click",r).css({"user-select":"none","-moz-user-select":"none","-khtml-user-select":"none","-webkit-user-select":"none","-o-user-select":"none"}).each(function(){});t.find(".pficon.pftooltip div.tooltip-html").on("dragstart selectstart",function(n){n.preventDefault()}).each(function(){var n=$(this);n.find("p").length==0&&n.html("<p>"+n.html()+"<\/p>")});t.find(".pficon.pftooltip div.tooltip-html").append('<div class="nose"><\/div>')},o=function(){t==undefined&&(t=$(document));t.find(".pficon.pftooltip").off("click",r)},r=function(t){if(!i){i=!0;try{}catch(r){}n&&n.hide();$(this).attr("title","")[0].focus();n=$(this).find("div.tooltip-html");n.css({top:30,left:-30}).fadeIn();t.stopPropagation();$(document).on("click",u);setTimeout(function(){i=!1},300)}},s=function(){$(document).off("click",u)},u=function(){n&&(n.parent().attr("title",$.trim(n.text())),n.hide(),n=null);s()};return f}();PF=PF||{};PF.FormValidator=function(){var t={IsValid:!1,IsDirty:!1,Validate:function(){return f(),this.IsValid},Reset:function(n){w(n)},Init:function(n){return y(n),this},Destroy:function(){p()}},n,v,r,i,o="validation-required",s={expiry:function(n){n=n||"";var t=!(n.length===4&&n.replace(/[^\d]/g,"").length===4&&!isNaN(+n)),i;return t||(i=n.substring(0,2),t=+i>12),t},req:function(n){return n.trim().length==0},"min-length":function(n,t){return n.length<parseInt(t.attr("min-length"))},"max-length":function(n,t){return n.length>parseInt(t.attr("max-length"))},state:function(n){return(temp=n.trim(),temp.length<2)?!0:temp.length>2},email:function(n){return!l(n)},number:function(n,t){if(!n)return!1;var f=parseFloat(t.attr("min"))||-Infinity,e=parseFloat(t.attr("max"))||Infinity,u=parseFloat(t.attr("divisable"))||-11,i=parseFloat(n.replace(/\$|\,/g,"")),r=!0;return!isNaN(i)&&i>=f&&i<=e?t.attr("valueType")&&t.attr("valueType")=="currency"&&t.pVal(i.toFixed(2)):r=!1,u==-11||i%u==0||isNaN(i)||(r=!1),!r},pwd:function(n){return n.length<5},pwd2:function(t){var i=n.find("input[validation=pwd]").last().pVal();return t!=i},http:function(n){return n.indexOf("http://")===-1},select:function(n,t){return t.is(":visible")&&t.prop("selectedIndex")===0},checked:function(n,t){return!t.prop("checked")},"min-select":function(n,t){var i=parseInt(t.attr("min-select"));return t.find("input:checked").length<i},"max-select":function(n,t){var i=parseInt(t.attr("max-select"));return t.find("input:checked").length>i},phone:function(n,t){var i=n.replace(/[^0-9]/g,""),r=i.length>=10&&i.length<25,u=!!t.data("required");return u?!r:i.length>0&&!r},date:function(n){return n.length>0&&a(n)==null},"credit-card":function(n,t){var i;return t.validateCreditCard(function(n){t.data("result",n);i=!n.length_valid||!n.luhn_valid}),i},cvc:function(n){n=n||"";var t=parseInt(n);return n.length<3||n.length>5||isNaN(t)||t<0||t>1e4},"positive-number":function(n){n=n||"";var t=Number(n);return t<=0},"positive-number-alow-zero":function(n){n=n||"";var t=Number(n);return t<0},zipcode:function(n){n=n||"";var t=parseInt(n),i=new RegExp("^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]","i");return isNaN(t)?n.length<6||n.length>7||!i.test(n):n.length<5||n.length>7||t<1e3||t>99999},zipcodePlus4:function(n){n=n||"";var t=parseInt(n),i=new RegExp("^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]","i");return isNaN(t)?n.length<6||n.length>7||!i.test(n):n.length<5||n.length>9||t<1e3||t>999999999},stopJunkData:function(n){var t=new RegExp("^([0-9])\\1*$");return t.test(n)},time:function(n){var t=new RegExp("^([1-9]|1[0-2]):([0-5][0-9])s*(?:[AP]M)?$/i"),i=new RegExp("^([01]?[0-9]|2[0-3]):([0-5][0-9])"),r=t.test(n),u=i.test(n);return!(r||u)}},e,a;t.isInvalid=s;var y=function(e){t.IsValid=!0;n=e.container;v=e.messageContainer;r=e.proceedButton;i=n.find("input[validation], select[validation], textarea[validation], div[validation], input[data-validation], select[data-validation], textarea[data-validation], div[data-validation]");r&&r.click(f);n.prop("errors",0);n.prop("valid",!1);i.on("change",u);i.last().on("keyup",c);e.editMode||i.each(function(){$(this).attr("type")=="text"&&$(this).pVal()!=""&&u.call(this)});var o=n.find("input, textarea, select");o.change(h)},p=function(){i.off("change",u);i.last().on("keyup",c);r&&r.off("click",f);var e=n.find("input, textarea, select");e.off("change",h);t=null},h=function(){t.IsDirty=!0},f=function(){i.each(function(){u.call(this)})},c=function(n){var i=n.keyCode?n.keyCode:n.which;i==13&&(u.call(this),t.IsValid&&r&&r.click())},u=function(){var r=$(this),f=r.attr("validation")||r.attr("data-validation"),i,u,o;f?(f.indexOf("-select")!=-1?i=r:(i=r.parents(".control-group").first(),i.length||(i=r.parents(".form-group").first())),u=i.find(".help-inline, .help-block"),o=t.IsValid=b(f.split(" "),r)):(o=t.IsValid=!0,i=r);o?((i.hasClass("error")||i.hasClass("has-error"))&&(n.prop("errors",Math.max(0,n.prop("errors")-1)),u.hide().addClass("hide")),r.is(":visible")&&i.removeClass("error has-error"),r.attr("valid","true"),e()):(u.show().removeClass("hide"),u.hasClass("help-block")?u.css("display","block"):u.css("display","inline-block"),i.addClass("error has-error").removeClass("success"),n.prop("errors",n.prop("errors")+1),r.attr("valid","false"),e());i.find("label").css("color","#333")},w=function(n){i.each(function(){var t=$(this),i=t.attr("validation")||t.attr("data-validation"),r;r=i?i.indexOf("-select")!=-1?t:t.parents(".control-group").length?t.parents(".control-group"):t.parents(".form-group"):t;n||t.pVal("");r.removeClass("error success")})},b=function(n,t){if(t.is(":hidden"))return!0;var i=!0,r=$.trim(t.pVal())||"";return $.each(n,function(n,u){var f=s[u],e;typeof f=="function"&&(e=typeof t.data(o)=="undefined"||t.data(o)==="true",(e||r.length>0)&&f(r,t)&&(i=!1))}),i},l=function(n){if(n==null||n=="")return!0;var t=new RegExp(/^((([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);return t.test(n)};return t.isValidEmailAddress=l,e=function(){n.prop("valid",n.find("input[valid=true],textarea[valid=true],select[valid=true],div[valid=true]").length==i.length);t.IsValid=n.prop("valid")},a=function(n){var t=n.match(/^([1-9]|0[1-9]|1[012])[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$/),i;return t?(i=new Date(t[3],t[2]-1,t[1]),!i)?null:!0:null},t};PF=PF||{};PF.ScannerReaderDecoder=function(n){var t=PF.ScannerReaderDecoder;return t.paymentInstrument=null,t.dLicense=null,t.BTCwallet=null,t.reinsertCapturedCharacter=null,t.capsLockWarningCallback=null,t.dLicenseParseErrorCallback=null,t.ccErrorCallback=null,t.scanningLicense=function(){return t.dLicense?t.dLicense.scan():!1},t.scanningWallet=function(){return t.BTCwallet?t.BTCwallet.scan:!1},t.reset=function(){$(document).off("keydown.DL101");$(document).off("keydown.CC101");t.interceptKeypressesCCandWallet();t.interceptKeypressesDLicense()},t.interceptKeypressesCCandWallet=function(){$(document).on("keydown.CC101",function(n){var i=t.convertKeyCodeToASCIIChars(n),u=(new Date).getTime(),r;if(t.paymentInstrument){if(i=="%")return t.paymentInstrument.swipe=!0,t.paymentInstrument.swipeData=i,t.paymentInstrument.swipeStartTime=u,$(".cardReader").blur(),!1;if(t.paymentInstrument.swipe)return t.captureCCData(i),!1}if(t.BTCwallet){if(t.BTCwallet.scan)return t.captureQRCodeData(i),!1;if(r=new RegExp("^1|^5|^L|^K"),t.BTCwallet.testNet&&(r=new RegExp("^m|^n|^c")),!t.scanningLicense()&&!t.BTCwallet.scan&&i&&i.match(r))return t.BTCwallet.scan=!0,t.BTCwallet.scanData(i),t.BTCwallet.scanStartTime=u,reinsertCapturedCharacter=setTimeout(function(){t.BTCwallet.scan=!1;$(n.target).val($(n.target).val()+i).change()},150),setTimeout(function(){t.BTCwallet.scan=!1},2e3),!1}})},t.interceptKeypressesDLicense=function(){if(t.dLicense!=null){$(document).on("keydown.DL101",function(n){var i=t.convertKeyCodeToASCIIChars(n),r,u;return t.dLicense.scan()&&(r=(new Date).getTime()-t.dLicense.scanStartTime(),r<100?(i!=null&&t.dLicense.scanData(t.dLicense.scanData()+i),t.dLicense.scanStartTime((new Date).getTime()),clearTimeout(reinsertCapturedCharacter),$(n.target).blur()):(t.dLicense.scan(!1),t.dLicense.scanStartTime(null),t.dLicense.scanData(null))),u=new RegExp("@"),t.scanningWallet()||t.dLicense.scan()||i!="@"||(reinsertCapturedCharacter=setTimeout(function(){$(n.target).val($(n.target).val()+"@").change()},150),$(document).keydown(function(n){if(n.ctrlKey&&n.which==17)return n.preventDefault(),n.stopPropagation(),!1}),t.dLicense.parseCallback=t.DLparseCallback,t.dLicense.scan(!0),t.dLicense.scanData(i),t.dLicense.scanStartTime((new Date).getTime())),(new Date).getTime()-t.dLicense.scanStartTime()<1e3?!1:void 0});$(document).keypress(function(n){if(n.ctrlKey&&n.which==17)return n.preventDefault(),n.stopPropagation(),!1})}},t.convertKeyCodeToASCIIChars=function(n){if(!n)return null;var t=String.fromCharCode(n.which),r=n.shiftKey,u=n.ctrlKey,i=n.which;return(i==13||i==74)&&u?"\n":(!r&&t&&(t=t.toLowerCase()),i==191&&(t=r?"?":"/"),i==186&&(t=r?":":";"),i==188&&(t=r?"<":","),i==48&&(t=r?")":"0"),i==49&&(t=r?"!":"1"),i==50&&(t=r?"@":"2"),i==51&&(t=r?"#":"3"),i==52&&(t=r?"$":"4"),i==53&&(t=r?"%":"5"),i==54&&(t=r?"^":"6"),i==55&&(t=r?"&":"7"),i==56&&(t=r?"*":"8"),i==57&&(t=r?"(":"9"),i==16&&r&&(t=null),i==17&&u&&(t=null),i==0&&r&&(t=null),i==0&&u&&(t=null),t)},t.captureCCData=function(n){var i=(new Date).getTime()-t.paymentInstrument.swipeStartTime;i<100?(n!=null&&(t.paymentInstrument.swipeData+=n),t.paymentInstrument.swipeData.indexOf(";")>-1&&n=="?"&&(t.paymentInstrument.swipe=!1,t.creditCardParse(t.paymentInstrument.swipeData),typeof pf_dataLayer!="undefined"&&pf_dataLayer.push({eventLabel:"none",event:"CardSwipe",eventCategory:"POS"})),t.paymentInstrument.swipeStartTime=(new Date).getTime()):(t.paymentInstrument.swipe=!1,t.paymentInstrument.input=null)},t.creditCardParse=function(n){if(n)try{n=n.replace("%B","");n=n.replace("%b","");var r=n.split("^"),i=r[1].split(" "),e=i.length,u=r[2].substring(2,4),f=r[2].substring(0,2);t.paymentInstrument.accountNumber(r[0]);t.paymentInstrument.expiry(u+f);i=r[1].split("/");t.paymentInstrument.firstName($.trim(i[1].charAt(0).toUpperCase()+i[1].toLowerCase().slice(1)));t.paymentInstrument.lastName($.trim(i[0].charAt(0).toUpperCase()+i[0].toLowerCase().slice(1)))}catch(o){PF&&PF.Modals.Generic&&PF.Modals.Generic.Show({title:"Card read error",description:"Error reading the card. Please try swiping again or enter the information manually."});t.ccErrorCallback&&t.ccErrorCallback.call(t,"Error reading the card. Please try swiping again.")}},t.captureQRCodeData=function(n){var i=(new Date).getTime()-t.BTCwallet.scanStartTime;i<100?(n!=null&&t.BTCwallet.scanData(t.BTCwallet.scanData()+n),t.BTCwallet.scanStartTime=(new Date).getTime(),clearTimeout(reinsertCapturedCharacter)):(t.BTCwallet.scan=!1,t.BTCwallet.scanStartTime=null,t.BTCwallet.scanData(null))},t.DLparseCallback=function(){if($(document).off("keydown.DL101"),!t.dLicense.validate()&&t.dLicenseParseErrorCallback){t.dLicenseParseErrorCallback.call(t,"An error occurred when parsing the drivers license. Please scan again.");t.dLicense.update({});return}t.paymentInstrument&&t.dLicense.state()&&(t.dLicense.zipCode()&&t.paymentInstrument.zipCode(t.dLicense.zipCode().substring(0,5)),t.paymentInstrument.address(t.dLicense.address()),t.paymentInstrument.city(t.dLicense.city()),t.paymentInstrument.stateOrProvince(t.dLicense.state()),t.paymentInstrument.firstName()||(t.paymentInstrument.firstName(t.dLicense.givenNames()),t.paymentInstrument.lastName(t.dLicense.lastName())))},t.capsLockOn=function(n){var i=t.convertKeyCodeToASCIIChars(n),r;return i==null?null:n.keyCode>=112&&n.keyCode<=123?!1:i=="CapsLock"?(t.reset(),null):i.toUpperCase()===i&&i.toLowerCase()!==i&&!n.shiftKey?!0:(r=new RegExp("^[A-z]+$"),!i.match(r))?null:!1},n&&(n.paymentInstrument&&(t.paymentInstrument=n.paymentInstrument),n.driversLicense&&(t.dLicense=n.driversLicense),n.wallet&&(t.BTCwallet=n.wallet),n.capsLockWarningCallback&&(t.capsLockWarningCallback=n.capsLockWarningCallback),n.driversLicenseParseErrorCallback&&(t.dLicenseParseErrorCallback=n.driversLicenseParseErrorCallback),n.creditCardErrorCallback&&(t.ccErrorCallback=n.creditCardErrorCallback),t.reset()),t};PF=PF||{};PF.Modals=typeof PF.createGlobalNameSpace=="function"?PF.createGlobalNameSpace(["PF","Modals"]):{};PF.Modal=!1;PF.ModalOverlay=!1;PF.ModalObj=null;PF.SecondModal=null;PF.SecondModalObj=null;topLocation=100;trackClose=!1;PF.ShowModal=function(n){var t,i,r;if(n.Top&&(topLocation=n.Top),n.TrackClose&&(trackClose=n.TrackClose),t=n.Container?n.Container:$.isPlainObject(n)?n.el:n,$.isPlainObject(n)||(n={}),n.SecondModal){PF.SecondModal=t;PF.ModalOverlay.off("mousedown",PF.HideModal);PF.ModalOverlay.on("mousedown",PF.HideSecondModal);r=$('<a href=javascript:void(0) class="closebutton"><i class=icon-remove><\/i><\/a>');PF.isIE&&r.css("filter","none");t.append(r);r.on("click",PF.HideSecondModal)}else{try{PF.ModalOverlay.is(":visible")&&PF.HideModal()}catch(h){}if(!PF.ModalOverlay){if(PF.ModalOverlay=$("<div><\/div>").css({height:"100%",width:"100%",position:"fixed",top:0,left:0,background:"#666",zIndex:10001,opacity:.5}),!n.noAutoHide)PF.ModalOverlay.on("mousedown",PF.HideModal);$(document.body).append(PF.ModalOverlay)}PF.Modal=t;i=t.find(".pficon.closebutton");i.length==0&&(i=$('<a href=javascript:void(0) class="closebutton"><i class=icon-remove><\/i><\/a>'),t.append(i));PF.isIE&&i.css("filter","none");i.click(PF.HideModal)}var e=$(document).width(),o=t.outerWidth(!0),s=t.outerHeight(!0),u=$(window).height()-s-100,f=e/2-o/2;if($(window).width()<768&&(topLocation=50,f=0),$(window).width()<400?(topLocation=10,f=0,t.css({maxWidth:"250px",padding:"10px"})):t.css({height:"auto",width:"auto"}),u<0&&(u=$(window).height()-75,topLocation>50&&(topLocation=50),t.css({maxHeight:u.toString()+"px",paddingTop:"10px",paddingBottom:"20px",overflow:"auto"}),t.find(".closebutton").css({top:"5px",right:"10px"})),t.css({position:"fixed",top:topLocation,left:f,zIndex:10002}),n.SecondModal){t.css("z-index",10003);PF.SecondModal.show();$(window).on("resize",PF.ResizeSecondModal);PF.SecondModalObj=PF.Modal.data("modal")}else{PF.ModalOverlay.show();PF.Modal.show();$(window).on("resize",PF.ResizeModal);PF.ModalObj=PF.Modal.data("modal");PF.Tooltips.Init(t)}PF.Tooltips.Init(t);PF.checkBrowserCompat()||PF.Modal.find("[placeholder]").blur()};PF.HideSecondModal=function(){PF.SecondModal.data("modal").Reset();PF.SecondModal.hide();PF.SecondModal=null;$(window).off("resize",PF.ResizeSecondModal)};PF.HideModal=function(n){var t,r;if(trackClose){for(t=1,cks=document.cookie.split(";"),i=0;i<cks.length;i++)parts=cks[i].split("="),parts[0].indexOf("MCEvilPopupClosed")!=-1&&(t=parseInt(parts[1])+1);r=new Date("12/31/2020");document.cookie="MCEvilPopupClosed="+t+";expires="+r.toGMTString()+";"}if(PF.SecondModal){PF.HideSecondModal();return}if(PF.ModalOverlay&&(PF.ModalOverlay.remove(),PF.ModalOverlay=null),$(".modal").is(":visible")&&$(".modal:visible").each(function(){if(typeof n!="undefined")$(this).on("hidden",function(){$(this).off("hidden");n.call()});$(this).modal("hide")}),PF.Modal){PF.Modal.hide();PF.Modal.data("modal").Reset();$(window).off("resize",PF.ResizeModal);typeof n!="undefined"&&n.call();return}};PF.FadeOutModal=function(){PF.ModalOverlay.fadeOut(function(){PF.ModalOverlay&&(PF.ModalOverlay.remove(),PF.ModalOverlay=null)});PF.Modal.fadeOut();PF.Modal.data("modal").Reset();$(window).off("resize",PF.ResizeModal)};PF.ResizeModal=function(){var n=PF.Modal;PF.ModalObj.Resize!=undefined&&PF.ModalObj.Resize();n.css({left:$(document).width()/2-n.outerWidth()/2})};PF.ResizeSecondModal=function(){PF.SecondModal.css({left:$(document).width()/2-el.outerWidth()/2})};$.fn.pVal=function(n){return n==undefined?this.hasClass("placeholder")?"":this.val():(this.val(n).removeClass("placeholder"),this)};$.fn.setDisabled=function(n){return n||n==undefined?this.addClass("disabled").prop("disabled",!0):this.removeClass("disabled").prop("disabled",!1)},function(n,t){function u(){return new Date(Date.UTC.apply(Date,arguments))}function e(){var n=new Date;return u(n.getFullYear(),n.getMonth(),n.getDate())}function c(n){return function(){return this[n].apply(this,arguments)}}function y(t,i){function s(n,t){return t.toLowerCase()}var u=n(t).data(),f={},e,o=new RegExp("^"+i.toLowerCase()+"([A-Z])"),r;i=new RegExp("^"+i.toLowerCase());for(r in u)i.test(r)&&(e=r.replace(o,s),f[e]=u[r]);return f}function p(t){var u={},i;if(r[t]||(t=t.split("-")[0],r[t]))return i=r[t],n.each(v,function(n,t){t in i&&(u[t]=i[t])}),u}var s=n(window),l=function(){var t={get:function(n){return this.slice(n)[0]},contains:function(n){for(var i=n&&n.valueOf(),t=0,r=this.length;t<r;t++)if(this[t].valueOf()===i)return t;return-1},remove:function(n){this.splice(n,1)},replace:function(t){t&&(n.isArray(t)||(t=[t]),this.clear(),this.push.apply(this,t))},clear:function(){this.splice(0)},copy:function(){var n=new l;return n.replace(this),n}};return function(){var i=[];return i.push.apply(i,arguments),n.extend(i,t),i}}(),f=function(t,r){this.dates=new l;this.viewDate=e();this.focusDate=null;this._process_options(r);this.element=n(t);this.isInline=!1;this.isInput=this.element.is("input");this.component=this.element.is(".date")?this.element.find(".add-on, .input-group-addon, .btn"):!1;this.hasInput=this.component&&this.element.find("input").length;this.component&&this.component.length===0&&(this.component=!1);this.picker=n(i.template);this._buildEvents();this._attachEvents();this.isInline?this.picker.addClass("datepicker-inline").appendTo(this.element):this.picker.addClass("datepicker-dropdown dropdown-menu");this.o.rtl&&this.picker.addClass("datepicker-rtl");this.viewMode=this.o.startView;this.o.calendarWeeks&&this.picker.find("tfoot th.today").attr("colspan",function(n,t){return parseInt(t)+1});this._allow_update=!1;this.setStartDate(this._o.startDate);this.setEndDate(this._o.endDate);this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);this.fillDow();this.fillMonths();this._allow_update=!0;this.update();this.showMode();this.isInline&&this.show()},h,a,o,v,r,i;f.prototype={constructor:f,_process_options:function(t){var u,e,h,f,s;this._o=n.extend({},this._o,t);u=this.o=n.extend({},this._o);e=u.language;r[e]||(e=e.split("-")[0],r[e]||(e=o.language));u.language=e;switch(u.startView){case 2:case"decade":u.startView=2;break;case 1:case"year":u.startView=1;break;default:u.startView=0}switch(u.minViewMode){case 1:case"months":u.minViewMode=1;break;case 2:case"years":u.minViewMode=2;break;default:u.minViewMode=0}if(u.startView=Math.max(u.startView,u.minViewMode),u.multidate!==!0&&(u.multidate=Number(u.multidate)||!1,u.multidate=u.multidate!==!1?Math.max(0,u.multidate):1),u.multidateSeparator=String(u.multidateSeparator),u.weekStart%=7,u.weekEnd=(u.weekStart+6)%7,h=i.parseFormat(u.format),u.startDate!==-Infinity&&(u.startDate=u.startDate?u.startDate instanceof Date?this._local_to_utc(this._zero_time(u.startDate)):i.parseDate(u.startDate,h,u.language):-Infinity),u.endDate!==Infinity&&(u.endDate=u.endDate?u.endDate instanceof Date?this._local_to_utc(this._zero_time(u.endDate)):i.parseDate(u.endDate,h,u.language):Infinity),u.daysOfWeekDisabled=u.daysOfWeekDisabled||[],n.isArray(u.daysOfWeekDisabled)||(u.daysOfWeekDisabled=u.daysOfWeekDisabled.split(/[,\s]*/)),u.daysOfWeekDisabled=n.map(u.daysOfWeekDisabled,function(n){return parseInt(n,10)}),f=String(u.orientation).toLowerCase().split(/\s+/g),s=u.orientation.toLowerCase(),f=n.grep(f,function(n){return/^auto|left|right|top|bottom$/.test(n)}),u.orientation={x:"auto",y:"auto"},s&&s!=="auto")if(f.length===1)switch(f[0]){case"top":case"bottom":u.orientation.y=f[0];break;case"left":case"right":u.orientation.x=f[0]}else s=n.grep(f,function(n){return/^left|right$/.test(n)}),u.orientation.x=s[0]||"auto",s=n.grep(f,function(n){return/^top|bottom$/.test(n)}),u.orientation.y=s[0]||"auto"},_events:[],_secondaryEvents:[],_applyEvents:function(n){for(var i=0,f,r,u;i<n.length;i++){f=n[i][0];n[i].length===2?(r=t,u=n[i][1]):n[i].length===3&&(r=n[i][1],u=n[i][2]);f.on(u,r)}},_unapplyEvents:function(n){for(var i=0,f,r,u;i<n.length;i++)f=n[i][0],n[i].length===2?(u=t,r=n[i][1]):n[i].length===3&&(u=n[i][1],r=n[i][2]),f.off(r,u)},_buildEvents:function(){this.isInput?this._events=[[this.element,{focus:n.proxy(this.show,this),keyup:n.proxy(function(t){n.inArray(t.keyCode,[27,37,39,38,40,32,13,9])===-1&&this.update()},this),keydown:n.proxy(this.keydown,this)}]]:this.component&&this.hasInput?this._events=[[this.element.find("input"),{focus:n.proxy(this.show,this),keyup:n.proxy(function(t){n.inArray(t.keyCode,[27,37,39,38,40,32,13,9])===-1&&this.update()},this),keydown:n.proxy(this.keydown,this)}],[this.component,{click:n.proxy(this.show,this)}]]:this.element.is("div")?this.isInline=!0:this._events=[[this.element,{click:n.proxy(this.show,this)}]];this._events.push([this.element,"*",{blur:n.proxy(function(n){this._focused_from=n.target},this)}],[this.element,{blur:n.proxy(function(n){this._focused_from=n.target},this)}]);this._secondaryEvents=[[this.picker,{click:n.proxy(this.click,this)}],[n(window),{resize:n.proxy(this.place,this)}],[n(document),{"mousedown touchstart":n.proxy(function(n){this.element.is(n.target)||this.element.find(n.target).length||this.picker.is(n.target)||this.picker.find(n.target).length||this.hide()},this)}]]},_attachEvents:function(){this._detachEvents();this._applyEvents(this._events)},_detachEvents:function(){this._unapplyEvents(this._events)},_attachSecondaryEvents:function(){this._detachSecondaryEvents();this._applyEvents(this._secondaryEvents)},_detachSecondaryEvents:function(){this._unapplyEvents(this._secondaryEvents)},_trigger:function(t,r){var u=r||this.dates.get(-1),f=this._utc_to_local(u);this.element.trigger({type:t,date:f,dates:n.map(this.dates,this._utc_to_local),format:n.proxy(function(n,t){arguments.length===0?(n=this.dates.length-1,t=this.o.format):typeof n=="string"&&(t=n,n=this.dates.length-1);t=t||this.o.format;var r=this.dates.get(n);return i.formatDate(r,t,this.o.language)},this)})},show:function(){this.isInline||this.picker.appendTo("body");this.picker.show();this.place();this._attachSecondaryEvents();this._trigger("show")},hide:function(){this.isInline||this.picker.is(":visible")&&(this.focusDate=null,this.picker.hide().detach(),this._detachSecondaryEvents(),this.viewMode=this.o.startView,this.showMode(),this.o.forceParse&&(this.isInput&&this.element.val()||this.hasInput&&this.element.find("input").val())&&this.setValue(),this._trigger("hide"))},remove:function(){this.hide();this._detachEvents();this._detachSecondaryEvents();this.picker.remove();delete this.element.data().datepicker;this.isInput||delete this.element.data().date},_utc_to_local:function(n){return n&&new Date(n.getTime()+n.getTimezoneOffset()*6e4)},_local_to_utc:function(n){return n&&new Date(n.getTime()-n.getTimezoneOffset()*6e4)},_zero_time:function(n){return n&&new Date(n.getFullYear(),n.getMonth(),n.getDate())},_zero_utc_time:function(n){return n&&new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()))},getDates:function(){return n.map(this.dates,this._utc_to_local)},getUTCDates:function(){return n.map(this.dates,function(n){return new Date(n)})},getDate:function(){return this._utc_to_local(this.getUTCDate())},getUTCDate:function(){return new Date(this.dates.get(-1))},setDates:function(){var t=n.isArray(arguments[0])?arguments[0]:arguments;this.update.apply(this,t);this._trigger("changeDate");this.setValue()},setUTCDates:function(){var t=n.isArray(arguments[0])?arguments[0]:arguments;this.update.apply(this,n.map(t,this._utc_to_local));this._trigger("changeDate");this.setValue()},setDate:c("setDates"),setUTCDate:c("setUTCDates"),setValue:function(){var n=this.getFormattedDate();this.isInput?this.element.val(n).change():this.component&&this.element.find("input").val(n).change()},getFormattedDate:function(r){r===t&&(r=this.o.format);var u=this.o.language;return n.map(this.dates,function(n){return i.formatDate(n,r,u)}).join(this.o.multidateSeparator)},setStartDate:function(n){this._process_options({startDate:n});this.update();this.updateNavArrows()},setEndDate:function(n){this._process_options({endDate:n});this.update();this.updateNavArrows()},setDaysOfWeekDisabled:function(n){this._process_options({daysOfWeekDisabled:n});this.update();this.updateNavArrows()},place:function(){var i,v,o;if(!this.isInline){var u=this.picker.outerWidth(),f=this.picker.outerHeight(),h=10,c=s.width(),y=s.height(),l=s.scrollTop(),p=parseInt(this.element.parents().filter(function(){return n(this).css("z-index")!=="auto"}).first().css("z-index"))+10,t=this.component?this.component.parent().offset():this.element.offset(),a=this.component?this.component.outerHeight(!0):this.element.outerHeight(!1),w=this.component?this.component.outerWidth(!0):this.element.outerWidth(!1),r=t.left,e=t.top;this.picker.removeClass("datepicker-orient-top datepicker-orient-bottom datepicker-orient-right datepicker-orient-left");this.o.orientation.x!=="auto"?(this.picker.addClass("datepicker-orient-"+this.o.orientation.x),this.o.orientation.x==="right"&&(r-=u-w)):(this.picker.addClass("datepicker-orient-left"),t.left<0?r-=t.left-h:t.left+u>c&&(r=c-u-h));i=this.o.orientation.y;i==="auto"&&(v=-l+t.top-f,o=l+y-(t.top+a+f),i=Math.max(v,o)===o?"top":"bottom");this.picker.addClass("datepicker-orient-"+i);i==="top"?e+=a:e-=f+parseInt(this.picker.css("padding-top"));this.picker.css({top:e,left:r,zIndex:p})}},_allow_update:!0,update:function(){if(this._allow_update){var r=this.dates.copy(),t=[],u=!1;arguments.length?(n.each(arguments,n.proxy(function(n,i){i instanceof Date&&(i=this._local_to_utc(i));t.push(i)},this)),u=!0):(t=this.isInput?this.element.val():this.element.data("date")||this.element.find("input").val(),t=t&&this.o.multidate?t.split(this.o.multidateSeparator):[t],delete this.element.data().date);t=n.map(t,n.proxy(function(n){return i.parseDate(n,this.o.format,this.o.language)},this));t=n.grep(t,n.proxy(function(n){return n<this.o.startDate||n>this.o.endDate||!n},this),!0);this.dates.replace(t);this.dates.length?this.viewDate=new Date(this.dates.get(-1)):this.viewDate<this.o.startDate?this.viewDate=new Date(this.o.startDate):this.viewDate>this.o.endDate&&(this.viewDate=new Date(this.o.endDate));u?this.setValue():t.length&&String(r)!==String(this.dates)&&this._trigger("changeDate");!this.dates.length&&r.length&&this._trigger("clearDate");this.fill()}},fillDow:function(){var i=this.o.weekStart,n="<tr>",t;for(this.o.calendarWeeks&&(t='<th class="cw">&nbsp;<\/th>',n+=t,this.picker.find(".datepicker-days thead tr:first-child").prepend(t));i<this.o.weekStart+7;)n+='<th class="dow">'+r[this.o.language].daysMin[i++%7]+"<\/th>";n+="<\/tr>";this.picker.find(".datepicker-days thead").append(n)},fillMonths:function(){for(var n="",t=0;t<12;)n+='<span class="month">'+r[this.o.language].monthsShort[t++]+"<\/span>";this.picker.find(".datepicker-months td").html(n)},setRange:function(t){t&&t.length?this.range=n.map(t,function(n){return n.valueOf()}):delete this.range;this.fill()},getClassNames:function(t){var i=[],r=this.viewDate.getUTCFullYear(),f=this.viewDate.getUTCMonth(),u=new Date;return t.getUTCFullYear()<r||t.getUTCFullYear()===r&&t.getUTCMonth()<f?i.push("old"):(t.getUTCFullYear()>r||t.getUTCFullYear()===r&&t.getUTCMonth()>f)&&i.push("new"),this.focusDate&&t.valueOf()===this.focusDate.valueOf()&&i.push("focused"),this.o.todayHighlight&&t.getUTCFullYear()===u.getFullYear()&&t.getUTCMonth()===u.getMonth()&&t.getUTCDate()===u.getDate()&&i.push("today"),this.dates.contains(t)!==-1&&i.push("active"),(t.valueOf()<this.o.startDate||t.valueOf()>this.o.endDate||n.inArray(t.getUTCDay(),this.o.daysOfWeekDisabled)!==-1)&&i.push("disabled"),this.range&&(t>this.range[0]&&t<this.range[this.range.length-1]&&i.push("range"),n.inArray(t.valueOf(),this.range)!==-1&&i.push("selected")),i},fill:function(){var d=new Date(this.viewDate),f=d.getUTCFullYear(),g=d.getUTCMonth(),y=this.o.startDate!==-Infinity?this.o.startDate.getUTCFullYear():-Infinity,ut=this.o.startDate!==-Infinity?this.o.startDate.getUTCMonth():-Infinity,p=this.o.endDate!==Infinity?this.o.endDate.getUTCFullYear():Infinity,ft=this.o.endDate!==Infinity?this.o.endDate.getUTCMonth():Infinity,et=r[this.o.language].today||r.en.today||"",ot=r[this.o.language].clear||r.en.clear||"",w,e,b,c,s,h,o,a,it,rt,l,v;for(this.picker.find(".datepicker-days thead th.datepicker-switch").text(r[this.o.language].months[g]+" "+f),this.picker.find("tfoot th.today").text(et).toggle(this.o.todayBtn!==!1),this.picker.find("tfoot th.clear").text(ot).toggle(this.o.clearBtn!==!1),this.updateNavArrows(),this.fillMonths(),e=u(f,g-1,28),b=i.getDaysInMonth(e.getUTCFullYear(),e.getUTCMonth()),e.setUTCDate(b),e.setUTCDate(b-(e.getUTCDay()-this.o.weekStart+7)%7),c=new Date(e),c.setUTCDate(c.getUTCDate()+42),c=c.valueOf(),s=[];e.valueOf()<c;){if(e.getUTCDay()===this.o.weekStart&&(s.push("<tr>"),this.o.calendarWeeks)){var nt=new Date(+e+(this.o.weekStart-e.getUTCDay()-7)%7*864e5),tt=new Date(Number(nt)+(11-nt.getUTCDay())%7*864e5),k=new Date(Number(k=u(tt.getUTCFullYear(),0,1))+(11-k.getUTCDay())%7*864e5),st=(tt-k)/6048e5+1;s.push('<td class="cw">'+st+"<\/td>")}h=this.getClassNames(e);h.push("day");this.o.beforeShowDay!==n.noop&&(o=this.o.beforeShowDay(this._utc_to_local(e)),o===t?o={}:typeof o=="boolean"?o={enabled:o}:typeof o=="string"&&(o={classes:o}),o.enabled===!1&&h.push("disabled"),o.classes&&(h=h.concat(o.classes.split(/\s+/))),o.tooltip&&(w=o.tooltip));h=n.unique(h);s.push('<td class="'+h.join(" ")+'"'+(w?' title="'+w+'"':"")+">"+e.getUTCDate()+"<\/td>");e.getUTCDay()===this.o.weekEnd&&s.push("<\/tr>");e.setUTCDate(e.getUTCDate()+1)}for(this.picker.find(".datepicker-days tbody").empty().append(s.join("")),a=this.picker.find(".datepicker-months").find("th:eq(1)").text(f).end().find("span").removeClass("active"),n.each(this.dates,function(n,t){t.getUTCFullYear()===f&&a.eq(t.getUTCMonth()).addClass("active")}),(f<y||f>p)&&a.addClass("disabled"),f===y&&a.slice(0,ut).addClass("disabled"),f===p&&a.slice(ft+1).addClass("disabled"),s="",f=parseInt(f/10,10)*10,it=this.picker.find(".datepicker-years").find("th:eq(1)").text(f+"-"+(f+9)).end().find("td"),f-=1,rt=n.map(this.dates,function(n){return n.getUTCFullYear()}),v=-1;v<11;v++)l=["year"],v===-1?l.push("old"):v===10&&l.push("new"),n.inArray(f,rt)!==-1&&l.push("active"),(f<y||f>p)&&l.push("disabled"),s+='<span class="'+l.join(" ")+'">'+f+"<\/span>",f+=1;it.html(s)},updateNavArrows:function(){if(this._allow_update){var t=new Date(this.viewDate),n=t.getUTCFullYear(),i=t.getUTCMonth();switch(this.viewMode){case 0:this.o.startDate!==-Infinity&&n<=this.o.startDate.getUTCFullYear()&&i<=this.o.startDate.getUTCMonth()?this.picker.find(".prev").css({visibility:"hidden"}):this.picker.find(".prev").css({visibility:"visible"});this.o.endDate!==Infinity&&n>=this.o.endDate.getUTCFullYear()&&i>=this.o.endDate.getUTCMonth()?this.picker.find(".next").css({visibility:"hidden"}):this.picker.find(".next").css({visibility:"visible"});break;case 1:case 2:this.o.startDate!==-Infinity&&n<=this.o.startDate.getUTCFullYear()?this.picker.find(".prev").css({visibility:"hidden"}):this.picker.find(".prev").css({visibility:"visible"});this.o.endDate!==Infinity&&n>=this.o.endDate.getUTCFullYear()?this.picker.find(".next").css({visibility:"hidden"}):this.picker.find(".next").css({visibility:"visible"})}}},click:function(t){var r,e,f,o,c,s,l,h;if(t.preventDefault(),r=n(t.target).closest("span, td, th"),r.length===1)switch(r[0].nodeName.toLowerCase()){case"th":switch(r[0].className){case"datepicker-switch":this.showMode(1);break;case"prev":case"next":c=i.modes[this.viewMode].navStep*(r[0].className==="prev"?-1:1);switch(this.viewMode){case 0:this.viewDate=this.moveMonth(this.viewDate,c);this._trigger("changeMonth",this.viewDate);break;case 1:case 2:this.viewDate=this.moveYear(this.viewDate,c);this.viewMode===1&&this._trigger("changeYear",this.viewDate)}this.fill();break;case"today":s=new Date;s=u(s.getFullYear(),s.getMonth(),s.getDate(),0,0,0);this.showMode(-2);l=this.o.todayBtn==="linked"?null:"view";this._setDate(s,l);break;case"clear":this.isInput?h=this.element:this.component&&(h=this.element.find("input"));h&&h.val("").change();this.update();this._trigger("changeDate");this.o.autoclose&&this.hide()}break;case"span":r.is(".disabled")||(this.viewDate.setUTCDate(1),r.is(".month")?(o=1,f=r.parent().find("span").index(r),e=this.viewDate.getUTCFullYear(),this.viewDate.setUTCMonth(f),this._trigger("changeMonth",this.viewDate),this.o.minViewMode===1&&this._setDate(u(e,f,o))):(o=1,f=0,e=parseInt(r.text(),10)||0,this.viewDate.setUTCFullYear(e),this._trigger("changeYear",this.viewDate),this.o.minViewMode===2&&this._setDate(u(e,f,o))),this.showMode(-1),this.fill());break;case"td":r.is(".day")&&!r.is(".disabled")&&(o=parseInt(r.text(),10)||1,e=this.viewDate.getUTCFullYear(),f=this.viewDate.getUTCMonth(),r.is(".old")?f===0?(f=11,e-=1):f-=1:r.is(".new")&&(f===11?(f=0,e+=1):f+=1),this._setDate(u(e,f,o)))}this.picker.is(":visible")&&this._focused_from&&n(this._focused_from).focus();delete this._focused_from},_toggle_multidate:function(n){var t=this.dates.contains(n);if(n?t!==-1?this.dates.remove(t):this.dates.push(n):this.dates.clear(),typeof this.o.multidate=="number")while(this.dates.length>this.o.multidate)this.dates.remove(0)},_setDate:function(n,t){t&&t!=="date"||this._toggle_multidate(n&&new Date(n));t&&t!=="view"||(this.viewDate=n&&new Date(n));this.fill();this.setValue();this._trigger("changeDate");var i;this.isInput?i=this.element:this.component&&(i=this.element.find("input"));i&&i.change();this.o.autoclose&&(!t||t==="date")&&this.hide()},moveMonth:function(n,i){var e;if(!n)return t;if(!i)return n;var r=new Date(n.valueOf()),o=r.getUTCDate(),s=r.getUTCMonth(),h=Math.abs(i),u,f;if(i=i>0?1:-1,h===1)f=i===-1?function(){return r.getUTCMonth()===s}:function(){return r.getUTCMonth()!==u},u=s+i,r.setUTCMonth(u),(u<0||u>11)&&(u=(u+12)%12);else{for(e=0;e<h;e++)r=this.moveMonth(r,i);u=r.getUTCMonth();r.setUTCDate(o);f=function(){return u!==r.getUTCMonth()}}while(f())r.setUTCDate(--o),r.setUTCMonth(u);return r},moveYear:function(n,t){return this.moveMonth(n,t*12)},dateWithinRange:function(n){return n>=this.o.startDate&&n<=this.o.endDate},keydown:function(n){var o,t,i,u,r,f;if(this.picker.is(":not(:visible)")){n.keyCode===27&&this.show();return}o=!1;r=this.focusDate||this.viewDate;switch(n.keyCode){case 27:this.focusDate?(this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.fill()):this.hide();n.preventDefault();break;case 37:case 39:if(!this.o.keyboardNavigation)break;t=n.keyCode===37?-1:1;n.ctrlKey?(i=this.moveYear(this.dates.get(-1)||e(),t),u=this.moveYear(r,t),this._trigger("changeYear",this.viewDate)):n.shiftKey?(i=this.moveMonth(this.dates.get(-1)||e(),t),u=this.moveMonth(r,t),this._trigger("changeMonth",this.viewDate)):(i=new Date(this.dates.get(-1)||e()),i.setUTCDate(i.getUTCDate()+t),u=new Date(r),u.setUTCDate(r.getUTCDate()+t));this.dateWithinRange(i)&&(this.focusDate=this.viewDate=u,this.setValue(),this.fill(),n.preventDefault());break;case 38:case 40:if(!this.o.keyboardNavigation)break;t=n.keyCode===38?-1:1;n.ctrlKey?(i=this.moveYear(this.dates.get(-1)||e(),t),u=this.moveYear(r,t),this._trigger("changeYear",this.viewDate)):n.shiftKey?(i=this.moveMonth(this.dates.get(-1)||e(),t),u=this.moveMonth(r,t),this._trigger("changeMonth",this.viewDate)):(i=new Date(this.dates.get(-1)||e()),i.setUTCDate(i.getUTCDate()+t*7),u=new Date(r),u.setUTCDate(r.getUTCDate()+t*7));this.dateWithinRange(i)&&(this.focusDate=this.viewDate=u,this.setValue(),this.fill(),n.preventDefault());break;case 13:r=this.focusDate||this.dates.get(-1)||this.viewDate;this._toggle_multidate(r);o=!0;this.focusDate=null;this.viewDate=this.dates.get(-1)||this.viewDate;this.setValue();this.fill();this.picker.is(":visible")&&(n.preventDefault(),this.o.autoclose&&this.hide());break;case 9:this.focusDate=null;this.viewDate=this.dates.get(-1)||this.viewDate;this.fill();this.hide()}o&&(this.dates.length?this._trigger("changeDate"):this._trigger("clearDate"),this.isInput?f=this.element:this.component&&(f=this.element.find("input")),f&&f.change())},showMode:function(n){n&&(this.viewMode=Math.max(this.o.minViewMode,Math.min(2,this.viewMode+n)));this.picker.find(">div").hide().filter(".datepicker-"+i.modes[this.viewMode].clsName).css("display","block");this.updateNavArrows()}};h=function(t,i){this.element=n(t);this.inputs=n.map(i.inputs,function(n){return n.jquery?n[0]:n});delete i.inputs;n(this.inputs).datepicker(i).bind("changeDate",n.proxy(this.dateUpdated,this));this.pickers=n.map(this.inputs,function(t){return n(t).data("datepicker")});this.updateDates()};h.prototype={updateDates:function(){this.dates=n.map(this.pickers,function(n){return n.getUTCDate()});this.updateRanges()},updateRanges:function(){var t=n.map(this.dates,function(n){return n.valueOf()});n.each(this.pickers,function(n,i){i.setRange(t)})},dateUpdated:function(t){if(!this.updating){this.updating=!0;var u=n(t.target).data("datepicker"),r=u.getUTCDate(),i=n.inArray(t.target,this.inputs),f=this.inputs.length;if(i!==-1){if(n.each(this.pickers,function(n,t){t.getUTCDate()||t.setUTCDate(r)}),r<this.dates[i])while(i>=0&&r<this.dates[i])this.pickers[i--].setUTCDate(r);else if(r>this.dates[i])while(i<f&&r>this.dates[i])this.pickers[i++].setUTCDate(r);this.updateDates();delete this.updating}}},remove:function(){n.map(this.pickers,function(n){n.remove()});delete this.element.data().datepicker}};a=n.fn.datepicker;n.fn.datepicker=function(i){var u=Array.apply(null,arguments),r;return u.shift(),this.each(function(){var s=n(this),e=s.data("datepicker"),l=typeof i=="object"&&i,v;if(!e){var a=y(this,"date"),w=n.extend({},o,a,l),b=p(w.language),c=n.extend({},o,b,a,l);s.is(".input-daterange")||c.inputs?(v={inputs:c.inputs||s.find("input").toArray()},s.data("datepicker",e=new h(this,n.extend(c,v)))):s.data("datepicker",e=new f(this,c))}if(typeof i=="string"&&typeof e[i]=="function"&&(r=e[i].apply(e,u),r!==t))return!1}),r!==t?r:this};o=n.fn.datepicker.defaults={autoclose:!1,beforeShowDay:n.noop,calendarWeeks:!1,clearBtn:!1,daysOfWeekDisabled:[],endDate:Infinity,forceParse:!0,format:"mm/dd/yyyy",keyboardNavigation:!0,language:"en",minViewMode:0,multidate:!1,multidateSeparator:",",orientation:"auto",rtl:!1,startDate:-Infinity,startView:0,todayBtn:!1,todayHighlight:!1,weekStart:0};v=n.fn.datepicker.locale_opts=["format","rtl","weekStart"];n.fn.datepicker.Constructor=f;r=n.fn.datepicker.dates={en:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],daysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun"],daysMin:["Su","Mo","Tu","We","Th","Fr","Sa","Su"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],today:"Today",clear:"Clear"}};i={modes:[{clsName:"days",navFnc:"Month",navStep:1},{clsName:"months",navFnc:"FullYear",navStep:1},{clsName:"years",navFnc:"FullYear",navStep:10}],isLeapYear:function(n){return n%4==0&&n%100!=0||n%400==0},getDaysInMonth:function(n,t){return[31,i.isLeapYear(n)?29:28,31,30,31,30,31,31,30,31,30,31][t]},validParts:/dd?|DD?|mm?|MM?|yy(?:yy)?/g,nonpunctuation:/[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,parseFormat:function(n){var t=n.replace(this.validParts,'\0').split('\0'),i=n.match(this.validParts);if(!t||!t.length||!i||i.length===0)throw new Error("Invalid date format.");return{separators:t,parts:i}},parseDate:function(e,o,s){function tt(){var n=this.slice(0,c[h].length),t=c[h].slice(0,n.length);return n===t}var nt,c,v,y,h,a,it,d,w;if(!e)return t;if(e instanceof Date)return e;if(typeof o=="string"&&(o=i.parseFormat(o)),nt=/([\-+]\d+)([dmwy])/,c=e.match(/([\-+]\d+)([dmwy])/g),/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(e)){for(e=new Date,h=0;h<c.length;h++){v=nt.exec(c[h]);y=parseInt(v[1]);switch(v[2]){case"d":e.setUTCDate(e.getUTCDate()+y);break;case"m":e=f.prototype.moveMonth.call(f.prototype,e,y);break;case"w":e.setUTCDate(e.getUTCDate()+y*7);break;case"y":e=f.prototype.moveYear.call(f.prototype,e,y)}}return u(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,0)}c=e&&e.match(this.nonpunctuation)||[];e=new Date;var b={},g=["yyyy","yy","M","MM","m","mm","d","dd"],l={yyyy:function(n,t){return n.setUTCFullYear(t)},yy:function(n,t){return n.setUTCFullYear(2e3+t)},m:function(n,t){if(isNaN(n))return n;for(t-=1;t<0;)t+=12;for(t%=12,n.setUTCMonth(t);n.getUTCMonth()!==t;)n.setUTCDate(n.getUTCDate()-1);return n},d:function(n,t){return n.setUTCDate(t)}},p,k;if(l.M=l.MM=l.mm=l.m,l.dd=l.d,e=u(e.getFullYear(),e.getMonth(),e.getDate(),0,0,0),a=o.parts.slice(),c.length!==a.length&&(a=n(a).filter(function(t,i){return n.inArray(i,g)!==-1}).toArray()),c.length===a.length){for(h=0,it=a.length;h<it;h++){if(p=parseInt(c[h],10),v=a[h],isNaN(p))switch(v){case"MM":k=n(r[s].months).filter(tt);p=n.inArray(k[0],r[s].months)+1;break;case"M":k=n(r[s].monthsShort).filter(tt);p=n.inArray(k[0],r[s].monthsShort)+1}b[v]=p}for(h=0;h<g.length;h++)w=g[h],w in b&&!isNaN(b[w])&&(d=new Date(e),l[w](d,b[w]),isNaN(d)||(e=d))}return e},formatDate:function(t,u,f){var e,s,o,h;if(!t)return"";for(typeof u=="string"&&(u=i.parseFormat(u)),e={d:t.getUTCDate(),D:r[f].daysShort[t.getUTCDay()],DD:r[f].days[t.getUTCDay()],m:t.getUTCMonth()+1,M:r[f].monthsShort[t.getUTCMonth()],MM:r[f].months[t.getUTCMonth()],yy:t.getUTCFullYear().toString().substring(2),yyyy:t.getUTCFullYear()},e.dd=(e.d<10?"0":"")+e.d,e.mm=(e.m<10?"0":"")+e.m,t=[],s=n.extend([],u.separators),o=0,h=u.parts.length;o<=h;o++)s.length&&t.push(s.shift()),t.push(e[u.parts[o]]);return t.join("")},headTemplate:'<thead><tr><th class="prev">&laquo;<\/th><th colspan="5" class="datepicker-switch"><\/th><th class="next">&raquo;<\/th><\/tr><\/thead>',contTemplate:'<tbody><tr><td colspan="7"><\/td><\/tr><\/tbody>',footTemplate:'<tfoot><tr><th colspan="7" class="today"><\/th><\/tr><tr><th colspan="7" class="clear"><\/th><\/tr><\/tfoot>'};i.template='<div class="datepicker"><div class="datepicker-days"><table class=" table-condensed">'+i.headTemplate+"<tbody><\/tbody>"+i.footTemplate+'<\/table><\/div><div class="datepicker-months"><table class="table-condensed">'+i.headTemplate+i.contTemplate+i.footTemplate+'<\/table><\/div><div class="datepicker-years"><table class="table-condensed">'+i.headTemplate+i.contTemplate+i.footTemplate+"<\/table><\/div><\/div>";n.fn.datepicker.DPGlobal=i;n.fn.datepicker.noConflict=function(){return n.fn.datepicker=a,this};n(document).on("focus.datepicker.data-api click.datepicker.data-api",'[data-provide="datepicker"]',function(t){var i=n(this);i.data("datepicker")||(t.preventDefault(),i.datepicker("show"))});n(function(){n('[data-provide="datepicker-inline"]').datepicker()})}(window.jQuery);!function(){var n,r,t,i,u,f={}.hasOwnProperty,e=function(n,t){function r(){this.constructor=n}for(var i in t)f.call(t,i)&&(n[i]=t[i]);return r.prototype=t.prototype,n.prototype=new r,n.__super__=t.prototype,n};i=function(){function n(){this.options_index=0;this.parsed=[]}return n.prototype.add_node=function(n){return"OPTGROUP"===n.nodeName.toUpperCase()?this.add_group(n):this.add_option(n)},n.prototype.add_group=function(n){var i,f,t,e,r,u;for(i=this.parsed.length,this.parsed.push({array_index:i,group:!0,label:this.escapeExpression(n.label),children:0,disabled:n.disabled,classes:n.className}),r=n.childNodes,u=[],t=0,e=r.length;e>t;t++)f=r[t],u.push(this.add_option(f,i,n.disabled));return u},n.prototype.add_option=function(n,t,i){if("OPTION"===n.nodeName.toUpperCase())return(""!==n.text?(null!=t&&(this.parsed[t].children+=1),this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:n.value,text:n.text,html:n.innerHTML,selected:n.selected,disabled:i===!0?i:n.disabled,group_array_index:t,classes:n.className,style:n.style.cssText})):this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:!0}),this.options_index+=1)},n.prototype.escapeExpression=function(n){var t,i;return null==n||n===!1?"":/[\&\<\>\"\'\`]/.test(n)?(t={"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},i=/&(?!\w+;)|[\<\>\"\'\`]/g,n.replace(i,function(n){return t[n]||"&amp;"})):n},n}();i.select_to_array=function(n){var f,r,t,e,u;for(r=new i,u=n.childNodes,t=0,e=u.length;e>t;t++)f=u[t],r.add_node(f);return r.parsed};r=function(){function n(t,i){this.form_field=t;this.options=null!=i?i:{};n.browser_is_supported()&&(this.is_multiple=this.form_field.multiple,this.set_default_text(),this.set_default_values(),this.setup(),this.set_up_html(),this.register_observers(),this.on_ready())}return n.prototype.set_default_values=function(){var n=this;return this.click_test_action=function(t){return n.test_active_click(t)},this.activate_action=function(t){return n.activate_field(t)},this.active_field=!1,this.mouse_on_container=!1,this.results_showing=!1,this.result_highlighted=null,this.allow_single_deselect=null!=this.options.allow_single_deselect&&null!=this.form_field.options[0]&&""===this.form_field.options[0].text?this.options.allow_single_deselect:!1,this.disable_search_threshold=this.options.disable_search_threshold||0,this.disable_search=this.options.disable_search||!1,this.enable_split_word_search=null!=this.options.enable_split_word_search?this.options.enable_split_word_search:!0,this.group_search=null!=this.options.group_search?this.options.group_search:!0,this.search_contains=this.options.search_contains||!1,this.single_backstroke_delete=null!=this.options.single_backstroke_delete?this.options.single_backstroke_delete:!0,this.max_selected_options=this.options.max_selected_options||1/0,this.inherit_select_classes=this.options.inherit_select_classes||!1,this.display_selected_options=null!=this.options.display_selected_options?this.options.display_selected_options:!0,this.display_disabled_options=null!=this.options.display_disabled_options?this.options.display_disabled_options:!0},n.prototype.set_default_text=function(){return this.default_text=this.form_field.getAttribute("data-placeholder")?this.form_field.getAttribute("data-placeholder"):this.is_multiple?this.options.placeholder_text_multiple||this.options.placeholder_text||n.default_multiple_text:this.options.placeholder_text_single||this.options.placeholder_text||n.default_single_text,this.results_none_found=this.form_field.getAttribute("data-no_results_text")||this.options.no_results_text||n.default_no_result_text},n.prototype.mouse_enter=function(){return this.mouse_on_container=!0},n.prototype.mouse_leave=function(){return this.mouse_on_container=!1},n.prototype.input_focus=function(){var n=this;if(this.is_multiple){if(!this.active_field)return setTimeout(function(){return n.container_mousedown()},50)}else if(!this.active_field)return this.activate_field()},n.prototype.input_blur=function(){var n=this;if(!this.mouse_on_container)return(this.active_field=!1,setTimeout(function(){return n.blur_test()},100))},n.prototype.results_option_build=function(n){var r,t,i,f,u;for(r="",u=this.results_data,i=0,f=u.length;f>i;i++)t=u[i],r+=t.group?this.result_add_group(t):this.result_add_option(t),(null!=n?n.first:void 0)&&(t.selected&&this.is_multiple?this.choice_build(t):t.selected&&!this.is_multiple&&this.single_set_selected_text(t.text));return r},n.prototype.result_add_option=function(n){var t,i;return n.search_match?this.include_option_in_results(n)?(t=[],n.disabled||n.selected&&this.is_multiple||t.push("active-result"),!n.disabled||n.selected&&this.is_multiple||t.push("disabled-result"),n.selected&&t.push("result-selected"),null!=n.group_array_index&&t.push("group-option"),""!==n.classes&&t.push(n.classes),i=document.createElement("li"),i.className=t.join(" "),i.style.cssText=n.style,i.setAttribute("data-option-array-index",n.array_index),i.innerHTML=n.search_text,this.outerHTML(i)):"":""},n.prototype.result_add_group=function(n){var t,i;return n.search_match||n.group_match?n.active_options>0?(t=[],t.push("group-result"),n.classes&&t.push(n.classes),i=document.createElement("li"),i.className=t.join(" "),i.innerHTML=n.search_text,this.outerHTML(i)):"":""},n.prototype.results_update_field=function(){return this.set_default_text(),this.is_multiple||this.results_reset_cleanup(),this.result_clear_highlight(),this.results_build(),this.results_showing?this.winnow_results():void 0},n.prototype.reset_single_select_options=function(){var i,n,u,r,t;for(r=this.results_data,t=[],n=0,u=r.length;u>n;n++)i=r[n],i.selected?t.push(i.selected=!1):t.push(void 0);return t},n.prototype.results_toggle=function(){return this.results_showing?this.results_hide():this.results_show()},n.prototype.results_search=function(){return this.results_showing?this.winnow_results():this.results_show()},n.prototype.winnow_results=function(){var e,n,h,u,t,i,r,o,c,f,l,s;for(this.no_results_clear(),u=0,i=this.get_search_text(),e=i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),c=new RegExp(e,"i"),h=this.get_search_regex(e),s=this.results_data,f=0,l=s.length;l>f;f++)n=s[f],n.search_match=!1,t=null,this.include_option_in_results(n)&&(n.group&&(n.group_match=!1,n.active_options=0),null!=n.group_array_index&&this.results_data[n.group_array_index]&&(t=this.results_data[n.group_array_index],0===t.active_options&&t.search_match&&(u+=1),t.active_options+=1),(!n.group||this.group_search)&&(n.search_text=n.group?n.label:n.text,n.search_match=this.search_string_match(n.search_text,h),n.search_match&&!n.group&&(u+=1),n.search_match?(i.length&&(r=n.search_text.search(c),o=n.search_text.substr(0,r+i.length)+"<\/em>"+n.search_text.substr(r+i.length),n.search_text=o.substr(0,r)+"<em>"+o.substr(r)),null!=t&&(t.group_match=!0)):null!=n.group_array_index&&this.results_data[n.group_array_index].search_match&&(n.search_match=!0)));return this.result_clear_highlight(),1>u&&i.length?(this.update_results_content(""),this.no_results(i)):(this.update_results_content(this.results_option_build()),this.winnow_results_set_highlight())},n.prototype.get_search_regex=function(n){var t;return t=this.search_contains?"":"^",new RegExp(t+n,"i")},n.prototype.search_string_match=function(n,t){var u,i,r,f;if(t.test(n))return!0;if(this.enable_split_word_search&&(n.indexOf(" ")>=0||0===n.indexOf("["))&&(i=n.replace(/\[|\]/g,"").split(" "),i.length))for(r=0,f=i.length;f>r;r++)if(u=i[r],t.test(u))return!0},n.prototype.choices_count=function(){var i,n,r,t;if(null!=this.selected_option_count)return this.selected_option_count;for(this.selected_option_count=0,t=this.form_field.options,n=0,r=t.length;r>n;n++)i=t[n],i.selected&&(this.selected_option_count+=1);return this.selected_option_count},n.prototype.choices_click=function(n){return n.preventDefault(),this.results_showing||this.is_disabled?void 0:this.results_show()},n.prototype.keyup_checker=function(n){var t,i;switch(t=null!=(i=n.which)?i:n.keyCode,this.search_field_scale(),t){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices_count()>0)return this.keydown_backstroke();if(!this.pending_backstroke)return this.result_clear_highlight(),this.results_search();break;case 13:if(n.preventDefault(),this.results_showing)return this.result_select(n);break;case 27:return this.results_showing&&this.results_hide(),!0;case 9:case 38:case 40:case 16:case 91:case 17:break;default:return this.results_search()}},n.prototype.clipboard_event_checker=function(){var n=this;return setTimeout(function(){return n.results_search()},50)},n.prototype.container_width=function(){return null!=this.options.width?this.options.width:""+this.form_field.offsetWidth+"px"},n.prototype.include_option_in_results=function(n){return this.is_multiple&&!this.display_selected_options&&n.selected?!1:!this.display_disabled_options&&n.disabled?!1:n.empty?!1:!0},n.prototype.search_results_touchstart=function(n){return this.touch_started=!0,this.search_results_mouseover(n)},n.prototype.search_results_touchmove=function(n){return this.touch_started=!1,this.search_results_mouseout(n)},n.prototype.search_results_touchend=function(n){if(this.touch_started)return this.search_results_mouseup(n)},n.prototype.outerHTML=function(n){var t;return n.outerHTML?n.outerHTML:(t=document.createElement("div"),t.appendChild(n),t.innerHTML)},n.browser_is_supported=function(){return"Microsoft Internet Explorer"===window.navigator.appName?document.documentMode>=8:/iP(od|hone)/i.test(window.navigator.userAgent)?!1:/Android/i.test(window.navigator.userAgent)&&/Mobile/i.test(window.navigator.userAgent)?!1:!0},n.default_multiple_text="Select Some Options",n.default_single_text="Select an Option",n.default_no_result_text="No results match",n}();n=jQuery;n.fn.extend({chosen:function(i){return r.browser_is_supported()?this.each(function(){var u,r;u=n(this);r=u.data("chosen");"destroy"===i&&r instanceof t?r.destroy():r instanceof t||u.data("chosen",new t(this,i))}):this}});t=function(t){function r(){return u=r.__super__.constructor.apply(this,arguments)}return e(r,t),r.prototype.setup=function(){return this.form_field_jq=n(this.form_field),this.current_selectedIndex=this.form_field.selectedIndex,this.is_rtl=this.form_field_jq.hasClass("chosen-rtl")},r.prototype.set_up_html=function(){var t,i;return t=["chosen-container"],t.push("chosen-container-"+(this.is_multiple?"multi":"single")),this.inherit_select_classes&&this.form_field.className&&t.push(this.form_field.className),this.is_rtl&&t.push("chosen-rtl"),i={"class":t.join(" "),style:"width: "+this.container_width()+";",title:this.form_field.title},this.form_field.id.length&&(i.id=this.form_field.id.replace(/[^\w]/g,"_")+"_chosen"),this.container=n("<div />",i),this.is_multiple?this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="'+this.default_text+'" class="default" autocomplete="off" style="width:25px;" /><\/li><\/ul><div class="chosen-drop"><ul class="chosen-results"><\/ul><\/div>'):this.container.html('<a class="chosen-single chosen-default" tabindex="-1"><span>'+this.default_text+'<\/span><div><b><\/b><\/div><\/a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /><\/div><ul class="chosen-results"><\/ul><\/div>'),this.form_field_jq.hide().after(this.container),this.dropdown=this.container.find("div.chosen-drop").first(),this.search_field=this.container.find("input").first(),this.search_results=this.container.find("ul.chosen-results").first(),this.search_field_scale(),this.search_no_results=this.container.find("li.no-results").first(),this.is_multiple?(this.search_choices=this.container.find("ul.chosen-choices").first(),this.search_container=this.container.find("li.search-field").first()):(this.search_container=this.container.find("div.chosen-search").first(),this.selected_item=this.container.find(".chosen-single").first()),this.results_build(),this.set_tab_index(),this.set_label_behavior()},r.prototype.on_ready=function(){return this.form_field_jq.trigger("chosen:ready",{chosen:this})},r.prototype.register_observers=function(){var n=this;return this.container.bind("touchstart.chosen",function(t){n.container_mousedown(t)}),this.container.bind("touchend.chosen",function(t){n.container_mouseup(t)}),this.container.bind("mousedown.chosen",function(t){n.container_mousedown(t)}),this.container.bind("mouseup.chosen",function(t){n.container_mouseup(t)}),this.container.bind("mouseenter.chosen",function(t){n.mouse_enter(t)}),this.container.bind("mouseleave.chosen",function(t){n.mouse_leave(t)}),this.search_results.bind("mouseup.chosen",function(t){n.search_results_mouseup(t)}),this.search_results.bind("mouseover.chosen",function(t){n.search_results_mouseover(t)}),this.search_results.bind("mouseout.chosen",function(t){n.search_results_mouseout(t)}),this.search_results.bind("mousewheel.chosen DOMMouseScroll.chosen",function(t){n.search_results_mousewheel(t)}),this.search_results.bind("touchstart.chosen",function(t){n.search_results_touchstart(t)}),this.search_results.bind("touchmove.chosen",function(t){n.search_results_touchmove(t)}),this.search_results.bind("touchend.chosen",function(t){n.search_results_touchend(t)}),this.form_field_jq.bind("chosen:updated.chosen",function(t){n.results_update_field(t)}),this.form_field_jq.bind("chosen:activate.chosen",function(t){n.activate_field(t)}),this.form_field_jq.bind("chosen:open.chosen",function(t){n.container_mousedown(t)}),this.form_field_jq.bind("chosen:close.chosen",function(t){n.input_blur(t)}),this.search_field.bind("blur.chosen",function(t){n.input_blur(t)}),this.search_field.bind("keyup.chosen",function(t){n.keyup_checker(t)}),this.search_field.bind("keydown.chosen",function(t){n.keydown_checker(t)}),this.search_field.bind("focus.chosen",function(t){n.input_focus(t)}),this.search_field.bind("cut.chosen",function(t){n.clipboard_event_checker(t)}),this.search_field.bind("paste.chosen",function(t){n.clipboard_event_checker(t)}),this.is_multiple?this.search_choices.bind("click.chosen",function(t){n.choices_click(t)}):this.container.bind("click.chosen",function(n){n.preventDefault()})},r.prototype.destroy=function(){return n(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.search_field[0].tabIndex&&(this.form_field_jq[0].tabIndex=this.search_field[0].tabIndex),this.container.remove(),this.form_field_jq.removeData("chosen"),this.form_field_jq.show()},r.prototype.search_field_disabled=function(){return this.is_disabled=this.form_field_jq[0].disabled,this.is_disabled?(this.container.addClass("chosen-disabled"),this.search_field[0].disabled=!0,this.is_multiple||this.selected_item.unbind("focus.chosen",this.activate_action),this.close_field()):(this.container.removeClass("chosen-disabled"),this.search_field[0].disabled=!1,this.is_multiple?void 0:this.selected_item.bind("focus.chosen",this.activate_action))},r.prototype.container_mousedown=function(t){if(!this.is_disabled&&(t&&"mousedown"===t.type&&!this.results_showing&&t.preventDefault(),null==t||!n(t.target).hasClass("search-choice-close")))return(this.active_field?this.is_multiple||!t||n(t.target)[0]!==this.selected_item[0]&&!n(t.target).parents("a.chosen-single").length||(t.preventDefault(),this.results_toggle()):(this.is_multiple&&this.search_field.val(""),n(this.container[0].ownerDocument).bind("click.chosen",this.click_test_action),this.results_show()),this.activate_field())},r.prototype.container_mouseup=function(n){if("ABBR"===n.target.nodeName&&!this.is_disabled)return this.results_reset(n)},r.prototype.search_results_mousewheel=function(n){var t;return n.originalEvent&&(t=n.originalEvent.deltaY||-n.originalEvent.wheelDelta||n.originalEvent.detail),null!=t?(n.preventDefault(),"DOMMouseScroll"===n.type&&(t=40*t),this.search_results.scrollTop(t+this.search_results.scrollTop())):void 0},r.prototype.blur_test=function(){if(!this.active_field&&this.container.hasClass("chosen-container-active"))return this.close_field()},r.prototype.close_field=function(){return n(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.active_field=!1,this.results_hide(),this.container.removeClass("chosen-container-active"),this.clear_backstroke(),this.show_search_field_default(),this.search_field_scale()},r.prototype.activate_field=function(){return this.container.addClass("chosen-container-active"),this.active_field=!0,this.search_field.val(this.search_field.val()),this.search_field.focus()},r.prototype.test_active_click=function(t){var i;return i=n(t.target).closest(".chosen-container"),i.length&&this.container[0]===i[0]?this.active_field=!0:this.close_field()},r.prototype.results_build=function(){return this.parsing=!0,this.selected_option_count=null,this.results_data=i.select_to_array(this.form_field),this.is_multiple?this.search_choices.find("li.search-choice").remove():this.is_multiple||(this.single_set_selected_text(),this.disable_search||this.form_field.options.length<=this.disable_search_threshold?(this.search_field[0].readOnly=!0,this.container.addClass("chosen-container-single-nosearch")):(this.search_field[0].readOnly=!1,this.container.removeClass("chosen-container-single-nosearch"))),this.update_results_content(this.results_option_build({first:!0})),this.search_field_disabled(),this.show_search_field_default(),this.search_field_scale(),this.parsing=!1},r.prototype.result_do_highlight=function(n){var t,i,r,f,u;if(n.length){if(this.result_clear_highlight(),this.result_highlight=n,this.result_highlight.addClass("highlighted"),r=parseInt(this.search_results.css("maxHeight"),10),u=this.search_results.scrollTop(),f=r+u,i=this.result_highlight.position().top+this.search_results.scrollTop(),t=i+this.result_highlight.outerHeight(),t>=f)return this.search_results.scrollTop(t-r>0?t-r:0);if(u>i)return this.search_results.scrollTop(i)}},r.prototype.result_clear_highlight=function(){return this.result_highlight&&this.result_highlight.removeClass("highlighted"),this.result_highlight=null},r.prototype.results_show=function(){return this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.container.addClass("chosen-with-drop"),this.results_showing=!0,this.search_field.focus(),this.search_field.val(this.search_field.val()),this.winnow_results(),this.form_field_jq.trigger("chosen:showing_dropdown",{chosen:this}))},r.prototype.update_results_content=function(n){return this.search_results.html(n)},r.prototype.results_hide=function(){return this.results_showing&&(this.result_clear_highlight(),this.container.removeClass("chosen-with-drop"),this.form_field_jq.trigger("chosen:hiding_dropdown",{chosen:this})),this.results_showing=!1},r.prototype.set_tab_index=function(){var n;if(this.form_field.tabIndex)return(n=this.form_field.tabIndex,this.form_field.tabIndex=-1,this.search_field[0].tabIndex=n)},r.prototype.set_label_behavior=function(){var t=this;return this.form_field_label=this.form_field_jq.parents("label"),!this.form_field_label.length&&this.form_field.id.length&&(this.form_field_label=n("label[for='"+this.form_field.id+"']")),this.form_field_label.length>0?this.form_field_label.bind("click.chosen",function(n){return t.is_multiple?t.container_mousedown(n):t.activate_field()}):void 0},r.prototype.show_search_field_default=function(){return this.is_multiple&&this.choices_count()<1&&!this.active_field?(this.search_field.val(this.default_text),this.search_field.addClass("default")):(this.search_field.val(""),this.search_field.removeClass("default"))},r.prototype.search_results_mouseup=function(t){var i;return i=n(t.target).hasClass("active-result")?n(t.target):n(t.target).parents(".active-result").first(),i.length?(this.result_highlight=i,this.result_select(t),this.search_field.focus()):void 0},r.prototype.search_results_mouseover=function(t){var i;return i=n(t.target).hasClass("active-result")?n(t.target):n(t.target).parents(".active-result").first(),i?this.result_do_highlight(i):void 0},r.prototype.search_results_mouseout=function(t){if(n(t.target).hasClass("active-result"))return this.result_clear_highlight()},r.prototype.choice_build=function(t){var i,r,u=this;return i=n("<li />",{"class":"search-choice"}).html("<span>"+t.html+"<\/span>"),t.disabled?i.addClass("search-choice-disabled"):(r=n("<a />",{"class":"search-choice-close","data-option-array-index":t.array_index}),r.bind("click.chosen",function(n){return u.choice_destroy_link_click(n)}),i.append(r)),this.search_container.before(i)},r.prototype.choice_destroy_link_click=function(t){return t.preventDefault(),t.stopPropagation(),this.is_disabled?void 0:this.choice_destroy(n(t.target))},r.prototype.choice_destroy=function(n){if(this.result_deselect(n[0].getAttribute("data-option-array-index")))return(this.show_search_field_default(),this.is_multiple&&this.choices_count()>0&&this.search_field.val().length<1&&this.results_hide(),n.parents("li").first().remove(),this.search_field_scale())},r.prototype.results_reset=function(){return this.reset_single_select_options(),this.form_field.options[0].selected=!0,this.single_set_selected_text(),this.show_search_field_default(),this.results_reset_cleanup(),this.form_field_jq.trigger("change"),this.active_field?this.results_hide():void 0},r.prototype.results_reset_cleanup=function(){return this.current_selectedIndex=this.form_field.selectedIndex,this.selected_item.find("abbr").remove()},r.prototype.result_select=function(n){var i,t;if(this.result_highlight)return(i=this.result_highlight,this.result_clear_highlight(),this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.is_multiple?i.removeClass("active-result"):this.reset_single_select_options(),t=this.results_data[i[0].getAttribute("data-option-array-index")],t.selected=!0,this.form_field.options[t.options_index].selected=!0,this.selected_option_count=null,this.is_multiple?this.choice_build(t):this.single_set_selected_text(t.text),(n.metaKey||n.ctrlKey)&&this.is_multiple||this.results_hide(),this.search_field.val(""),(this.is_multiple||this.form_field.selectedIndex!==this.current_selectedIndex)&&this.form_field_jq.trigger("change",{selected:this.form_field.options[t.options_index].value}),this.current_selectedIndex=this.form_field.selectedIndex,this.search_field_scale()))},r.prototype.single_set_selected_text=function(n){return null==n&&(n=this.default_text),n===this.default_text?this.selected_item.addClass("chosen-default"):(this.single_deselect_control_build(),this.selected_item.removeClass("chosen-default")),this.selected_item.find("span").text(n)},r.prototype.result_deselect=function(n){var t;return t=this.results_data[n],this.form_field.options[t.options_index].disabled?!1:(t.selected=!1,this.form_field.options[t.options_index].selected=!1,this.selected_option_count=null,this.result_clear_highlight(),this.results_showing&&this.winnow_results(),this.form_field_jq.trigger("change",{deselected:this.form_field.options[t.options_index].value}),this.search_field_scale(),!0)},r.prototype.single_deselect_control_build=function(){if(this.allow_single_deselect)return(this.selected_item.find("abbr").length||this.selected_item.find("span").first().after('<abbr class="search-choice-close"><\/abbr>'),this.selected_item.addClass("chosen-single-with-deselect"))},r.prototype.get_search_text=function(){return this.search_field.val()===this.default_text?"":n("<div/>").text(n.trim(this.search_field.val())).html()},r.prototype.winnow_results_set_highlight=function(){var n,t;return t=this.is_multiple?[]:this.search_results.find(".result-selected.active-result"),n=t.length?t.first():this.search_results.find(".active-result").first(),null!=n?this.result_do_highlight(n):void 0},r.prototype.no_results=function(t){var i;return i=n('<li class="no-results">'+this.results_none_found+' "<span><\/span>"<\/li>'),i.find("span").first().html(t),this.search_results.append(i),this.form_field_jq.trigger("chosen:no_results",{chosen:this})},r.prototype.no_results_clear=function(){return this.search_results.find(".no-results").remove()},r.prototype.keydown_arrow=function(){var n;return this.results_showing&&this.result_highlight?(n=this.result_highlight.nextAll("li.active-result").first())?this.result_do_highlight(n):void 0:this.results_show()},r.prototype.keyup_arrow=function(){var n;return this.results_showing||this.is_multiple?this.result_highlight?(n=this.result_highlight.prevAll("li.active-result"),n.length?this.result_do_highlight(n.first()):(this.choices_count()>0&&this.results_hide(),this.result_clear_highlight())):void 0:this.results_show()},r.prototype.keydown_backstroke=function(){var n;return this.pending_backstroke?(this.choice_destroy(this.pending_backstroke.find("a").first()),this.clear_backstroke()):(n=this.search_container.siblings("li.search-choice").last(),n.length&&!n.hasClass("search-choice-disabled")?(this.pending_backstroke=n,this.single_backstroke_delete?this.keydown_backstroke():this.pending_backstroke.addClass("search-choice-focus")):void 0)},r.prototype.clear_backstroke=function(){return this.pending_backstroke&&this.pending_backstroke.removeClass("search-choice-focus"),this.pending_backstroke=null},r.prototype.keydown_checker=function(n){var t,i;switch(t=null!=(i=n.which)?i:n.keyCode,this.search_field_scale(),8!==t&&this.pending_backstroke&&this.clear_backstroke(),t){case 8:this.backstroke_length=this.search_field.val().length;break;case 9:this.results_showing&&!this.is_multiple&&this.result_select(n);this.mouse_on_container=!1;break;case 13:this.results_showing&&n.preventDefault();break;case 32:this.disable_search&&n.preventDefault();break;case 38:n.preventDefault();this.keyup_arrow();break;case 40:n.preventDefault();this.keydown_arrow()}},r.prototype.search_field_scale=function(){var t,u,h,f,e,o,i,r,s;if(this.is_multiple){for(h=0,i=0,e="position:absolute; left: -1000px; top: -1000px; display:none;",o=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"],r=0,s=o.length;s>r;r++)f=o[r],e+=f+":"+this.search_field.css(f)+";";return t=n("<div />",{style:e}),t.text(this.search_field.val()),n("body").append(t),i=t.width()+25,t.remove(),u=this.container.outerWidth(),i>u-10&&(i=u-10),this.search_field.css({width:i+"px"})}},r}(r)}.call(this);JSEncryptExports={},function(n){function t(n,t,i){n!=null&&("number"==typeof n?this.fromNumber(n,t,i):t==null&&"string"!=typeof n?this.fromString(n,256):this.fromString(n,t))}function i(){return new t(null)}function ui(n,t,i,r,u,f){while(--f>=0){var e=t*this[n++]+i[r]+u;u=Math.floor(e/67108864);i[r++]=e&67108863}return u}function fi(n,t,i,r,u,f){for(var o=t&32767,s=t>>15;--f>=0;){var e=this[n]&32767,h=this[n++]>>15,c=s*e+h*o;e=o*e+((c&32767)<<15)+i[r]+(u&1073741823);u=(e>>>30)+(c>>>15)+s*h+(u>>>30);i[r++]=e&1073741823}return u}function ei(n,t,i,r,u,f){for(var o=t&16383,s=t>>14;--f>=0;){var e=this[n]&16383,h=this[n++]>>14,c=s*e+h*o;e=o*e+((c&16383)<<14)+i[r]+u;u=(e>>28)+(c>>14)+s*h;i[r++]=e&268435455}return u}function c(n){return bt.charAt(n)}function kt(n,t){var i=nt[n.charCodeAt(t)];return i==null?-1:i}function oi(n){for(var t=this.t-1;t>=0;--t)n[t]=this[t];n.t=this.t;n.s=this.s}function si(n){this.t=1;this.s=n<0?-1:0;n>0?this[0]=n:n<-1?this[0]=n+this.DV:this.t=0}function a(n){var t=i();return t.fromInt(n),t}function hi(n,i){var u,f;if(i==16)u=4;else if(i==8)u=3;else if(i==256)u=8;else if(i==2)u=1;else if(i==32)u=5;else if(i==4)u=2;else{this.fromRadix(n,i);return}this.t=0;this.s=0;for(var e=n.length,o=!1,r=0;--e>=0;){if(f=u==8?n[e]&255:kt(n,e),f<0){n.charAt(e)=="-"&&(o=!0);continue}o=!1;r==0?this[this.t++]=f:r+u>this.DB?(this[this.t-1]|=(f&(1<<this.DB-r)-1)<<r,this[this.t++]=f>>this.DB-r):this[this.t-1]|=f<<r;r+=u;r>=this.DB&&(r-=this.DB)}u==8&&(n[0]&128)!=0&&(this.s=-1,r>0&&(this[this.t-1]|=(1<<this.DB-r)-1<<r));this.clamp();o&&t.ZERO.subTo(this,this)}function ci(){for(var n=this.s&this.DM;this.t>0&&this[this.t-1]==n;)--this.t}function li(n){var t;if(this.s<0)return"-"+this.negate().toString(n);if(n==16)t=4;else if(n==8)t=3;else if(n==2)t=1;else if(n==32)t=5;else if(n==4)t=2;else return this.toRadix(n);var o=(1<<t)-1,u,f=!1,e="",r=this.t,i=this.DB-r*this.DB%t;if(r-->0)for(i<this.DB&&(u=this[r]>>i)>0&&(f=!0,e=c(u));r>=0;)i<t?u=(this[r]&(1<<i)-1)<<t-i|this[--r]>>(i+=this.DB-t):(u=this[r]>>(i-=t)&o,i<=0&&(i+=this.DB,--r)),u>0&&(f=!0),f&&(e+=c(u));return f?e:"0"}function ai(){var n=i();return t.ZERO.subTo(this,n),n}function vi(){return this.s<0?this.negate():this}function yi(n){var t=this.s-n.s,i;if(t!=0)return t;if(i=this.t,t=i-n.t,t!=0)return this.s<0?-t:t;while(--i>=0)if((t=this[i]-n[i])!=0)return t;return 0}function ut(n){var i=1,t;return(t=n>>>16)!=0&&(n=t,i+=16),(t=n>>8)!=0&&(n=t,i+=8),(t=n>>4)!=0&&(n=t,i+=4),(t=n>>2)!=0&&(n=t,i+=2),(t=n>>1)!=0&&(n=t,i+=1),i}function pi(){return this.t<=0?0:this.DB*(this.t-1)+ut(this[this.t-1]^this.s&this.DM)}function wi(n,t){for(var i=this.t-1;i>=0;--i)t[i+n]=this[i];for(i=n-1;i>=0;--i)t[i]=0;t.t=this.t+n;t.s=this.s}function bi(n,t){for(var i=n;i<this.t;++i)t[i-n]=this[i];t.t=Math.max(this.t-n,0);t.s=this.s}function ki(n,t){for(var u=n%this.DB,e=this.DB-u,o=(1<<e)-1,r=Math.floor(n/this.DB),f=this.s<<u&this.DM,i=this.t-1;i>=0;--i)t[i+r+1]=this[i]>>e|f,f=(this[i]&o)<<u;for(i=r-1;i>=0;--i)t[i]=0;t[r]=f;t.t=this.t+r+1;t.s=this.s;t.clamp()}function di(n,t){var i,r;if(t.s=this.s,i=Math.floor(n/this.DB),i>=this.t){t.t=0;return}var u=n%this.DB,f=this.DB-u,e=(1<<u)-1;for(t[0]=this[i]>>u,r=i+1;r<this.t;++r)t[r-i-1]|=(this[r]&e)<<f,t[r-i]=this[r]>>u;u>0&&(t[this.t-i-1]|=(this.s&e)<<f);t.t=this.t-i;t.clamp()}function gi(n,t){for(var r=0,i=0,u=Math.min(n.t,this.t);r<u;)i+=this[r]-n[r],t[r++]=i&this.DM,i>>=this.DB;if(n.t<this.t){for(i-=n.s;r<this.t;)i+=this[r],t[r++]=i&this.DM,i>>=this.DB;i+=this.s}else{for(i+=this.s;r<n.t;)i-=n[r],t[r++]=i&this.DM,i>>=this.DB;i-=n.s}t.s=i<0?-1:0;i<-1?t[r++]=this.DV+i:i>0&&(t[r++]=i);t.t=r;t.clamp()}function nr(n,i){var u=this.abs(),f=n.abs(),r=u.t;for(i.t=r+f.t;--r>=0;)i[r]=0;for(r=0;r<f.t;++r)i[r+u.t]=u.am(0,f[r],i,r,0,u.t);i.s=0;i.clamp();this.s!=n.s&&t.ZERO.subTo(i,i)}function tr(n){for(var i=this.abs(),t=n.t=2*i.t,r;--t>=0;)n[t]=0;for(t=0;t<i.t-1;++t)r=i.am(t,i[t],n,2*t,0,1),(n[t+i.t]+=i.am(t+1,2*i[t],n,2*t+1,r,i.t-t-1))>=i.DV&&(n[t+i.t]-=i.DV,n[t+i.t+1]=1);n.t>0&&(n[n.t-1]+=i.am(t,i[t],n,2*t,0,1));n.s=0;n.clamp()}function ir(n,r,u){var s=n.abs(),l,e,a,y;if(!(s.t<=0)){if(l=this.abs(),l.t<s.t){r!=null&&r.fromInt(0);u!=null&&this.copyTo(u);return}u==null&&(u=i());var f=i(),p=this.s,b=n.s,c=this.DB-ut(s[s.t-1]);if(c>0?(s.lShiftTo(c,f),l.lShiftTo(c,u)):(s.copyTo(f),l.copyTo(u)),e=f.t,a=f[e-1],a!=0){var w=a*(1<<this.F1)+(e>1?f[e-2]>>this.F2:0),k=this.FV/w,d=(1<<this.F1)/w,g=1<<this.F2,h=u.t,v=h-e,o=r==null?i():r;for(f.dlShiftTo(v,o),u.compareTo(o)>=0&&(u[u.t++]=1,u.subTo(o,u)),t.ONE.dlShiftTo(e,o),o.subTo(f,f);f.t<e;)f[f.t++]=0;while(--v>=0)if(y=u[--h]==a?this.DM:Math.floor(u[h]*k+(u[h-1]+g)*d),(u[h]+=f.am(0,y,u,v,0,e))<y)for(f.dlShiftTo(v,o),u.subTo(o,u);u[h]<--y;)u.subTo(o,u);r!=null&&(u.drShiftTo(e,r),p!=b&&t.ZERO.subTo(r,r));u.t=e;u.clamp();c>0&&u.rShiftTo(c,u);p<0&&t.ZERO.subTo(u,u)}}}function rr(n){var r=i();return this.abs().divRemTo(n,null,r),this.s<0&&r.compareTo(t.ZERO)>0&&n.subTo(r,r),r}function p(n){this.m=n}function ur(n){return n.s<0||n.compareTo(this.m)>=0?n.mod(this.m):n}function fr(n){return n}function er(n){n.divRemTo(this.m,null,n)}function or(n,t,i){n.multiplyTo(t,i);this.reduce(i)}function sr(n,t){n.squareTo(t);this.reduce(t)}function hr(){var t,n;return this.t<1?0:(t=this[0],(t&1)==0)?0:(n=t&3,n=n*(2-(t&15)*n)&15,n=n*(2-(t&255)*n)&255,n=n*(2-((t&65535)*n&65535))&65535,n=n*(2-t*n%this.DV)%this.DV,n>0?this.DV-n:-n)}function w(n){this.m=n;this.mp=n.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<n.DB-15)-1;this.mt2=2*n.t}function cr(n){var r=i();return n.abs().dlShiftTo(this.m.t,r),r.divRemTo(this.m,null,r),n.s<0&&r.compareTo(t.ZERO)>0&&this.m.subTo(r,r),r}function lr(n){var t=i();return n.copyTo(t),this.reduce(t),t}function ar(n){for(var i,t,r;n.t<=this.mt2;)n[n.t++]=0;for(i=0;i<this.m.t;++i)for(t=n[i]&32767,r=t*this.mpl+((t*this.mph+(n[i]>>15)*this.mpl&this.um)<<15)&n.DM,t=i+this.m.t,n[t]+=this.m.am(0,r,n,i,0,this.m.t);n[t]>=n.DV;)n[t]-=n.DV,n[++t]++;n.clamp();n.drShiftTo(this.m.t,n);n.compareTo(this.m)>=0&&n.subTo(this.m,n)}function vr(n,t){n.squareTo(t);this.reduce(t)}function yr(n,t,i){n.multiplyTo(t,i);this.reduce(i)}function pr(){return(this.t>0?this[0]&1:this.s)==0}function wr(n,r){var s;if(n>4294967295||n<1)return t.ONE;var u=i(),f=i(),e=r.convert(this),o=ut(n)-1;for(e.copyTo(u);--o>=0;)r.sqrTo(u,f),(n&1<<o)>0?r.mulTo(f,e,u):(s=u,u=f,f=s);return r.revert(u)}function br(n,t){var i;return i=n<256||t.isEven()?new p(t):new w(t),this.exp(n,i)}function kr(){var n=i();return this.copyTo(n),n}function dr(){if(this.s<0){if(this.t==1)return this[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this[0];if(this.t==0)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]}function gr(){return this.t==0?this.s:this[0]<<24>>24}function nu(){return this.t==0?this.s:this[0]<<16>>16}function tu(n){return Math.floor(Math.LN2*this.DB/Math.log(n))}function iu(){return this.s<0?-1:this.t<=0||this.t==1&&this[0]<=0?0:1}function ru(n){if(n==null&&(n=10),this.signum()==0||n<2||n>36)return"0";var o=this.chunkSize(n),f=Math.pow(n,o),e=a(f),t=i(),r=i(),u="";for(this.divRemTo(e,t,r);t.signum()>0;)u=(f+r.intValue()).toString(n).substr(1)+u,t.divRemTo(e,t,r);return r.intValue().toString(n)+u}function uu(n,i){var u,e;this.fromInt(0);i==null&&(i=10);var o=this.chunkSize(i),h=Math.pow(i,o),s=!1,f=0,r=0;for(u=0;u<n.length;++u){if(e=kt(n,u),e<0){n.charAt(u)=="-"&&this.signum()==0&&(s=!0);continue}r=i*r+e;++f>=o&&(this.dMultiply(h),this.dAddOffset(r,0),f=0,r=0)}f>0&&(this.dMultiply(Math.pow(i,f)),this.dAddOffset(r,0));s&&t.ZERO.subTo(this,this)}function fu(n,i,r){if("number"==typeof i)if(n<2)this.fromInt(1);else for(this.fromNumber(n,r),this.testBit(n-1)||this.bitwiseTo(t.ONE.shiftLeft(n-1),ft,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(i);)this.dAddOffset(2,0),this.bitLength()>n&&this.subTo(t.ONE.shiftLeft(n-1),this);else{var u=[],f=n&7;u.length=(n>>3)+1;i.nextBytes(u);f>0?u[0]&=(1<<f)-1:u[0]=0;this.fromString(u,256)}}function eu(){var i=this.t,u=[],n,t,r;if(u[0]=this.s,n=this.DB-i*this.DB%8,r=0,i-->0)for(n<this.DB&&(t=this[i]>>n)!=(this.s&this.DM)>>n&&(u[r++]=t|this.s<<this.DB-n);i>=0;)n<8?t=(this[i]&(1<<n)-1)<<8-n|this[--i]>>(n+=this.DB-8):(t=this[i]>>(n-=8)&255,n<=0&&(n+=this.DB,--i)),(t&128)!=0&&(t|=-256),r==0&&(this.s&128)!=(t&128)&&++r,(r>0||t!=this.s)&&(u[r++]=t);return u}function ou(n){return this.compareTo(n)==0}function su(n){return this.compareTo(n)<0?this:n}function hu(n){return this.compareTo(n)>0?this:n}function cu(n,t,i){for(var u,f=Math.min(n.t,this.t),r=0;r<f;++r)i[r]=t(this[r],n[r]);if(n.t<this.t){for(u=n.s&this.DM,r=f;r<this.t;++r)i[r]=t(this[r],u);i.t=this.t}else{for(u=this.s&this.DM,r=f;r<n.t;++r)i[r]=t(u,n[r]);i.t=n.t}i.s=t(this.s,n.s);i.clamp()}function lu(n,t){return n&t}function au(n){var t=i();return this.bitwiseTo(n,lu,t),t}function ft(n,t){return n|t}function vu(n){var t=i();return this.bitwiseTo(n,ft,t),t}function dt(n,t){return n^t}function yu(n){var t=i();return this.bitwiseTo(n,dt,t),t}function gt(n,t){return n&~t}function pu(n){var t=i();return this.bitwiseTo(n,gt,t),t}function wu(){for(var n=i(),t=0;t<this.t;++t)n[t]=this.DM&~this[t];return n.t=this.t,n.s=~this.s,n}function bu(n){var t=i();return n<0?this.rShiftTo(-n,t):this.lShiftTo(n,t),t}function ku(n){var t=i();return n<0?this.lShiftTo(-n,t):this.rShiftTo(n,t),t}function du(n){if(n==0)return-1;var t=0;return(n&65535)==0&&(n>>=16,t+=16),(n&255)==0&&(n>>=8,t+=8),(n&15)==0&&(n>>=4,t+=4),(n&3)==0&&(n>>=2,t+=2),(n&1)==0&&++t,t}function gu(){for(var n=0;n<this.t;++n)if(this[n]!=0)return n*this.DB+du(this[n]);return this.s<0?this.t*this.DB:-1}function nf(n){for(var t=0;n!=0;)n&=n-1,++t;return t}function tf(){for(var t=0,i=this.s&this.DM,n=0;n<this.t;++n)t+=nf(this[n]^i);return t}function rf(n){var t=Math.floor(n/this.DB);return t>=this.t?this.s!=0:(this[t]&1<<n%this.DB)!=0}function uf(n,i){var r=t.ONE.shiftLeft(n);return this.bitwiseTo(r,i,r),r}function ff(n){return this.changeBit(n,ft)}function ef(n){return this.changeBit(n,gt)}function of(n){return this.changeBit(n,dt)}function sf(n,t){for(var r=0,i=0,u=Math.min(n.t,this.t);r<u;)i+=this[r]+n[r],t[r++]=i&this.DM,i>>=this.DB;if(n.t<this.t){for(i+=n.s;r<this.t;)i+=this[r],t[r++]=i&this.DM,i>>=this.DB;i+=this.s}else{for(i+=this.s;r<n.t;)i+=n[r],t[r++]=i&this.DM,i>>=this.DB;i+=n.s}t.s=i<0?-1:0;i>0?t[r++]=i:i<-1&&(t[r++]=this.DV+i);t.t=r;t.clamp()}function hf(n){var t=i();return this.addTo(n,t),t}function cf(n){var t=i();return this.subTo(n,t),t}function lf(n){var t=i();return this.multiplyTo(n,t),t}function af(){var n=i();return this.squareTo(n),n}function vf(n){var t=i();return this.divRemTo(n,t,null),t}function yf(n){var t=i();return this.divRemTo(n,null,t),t}function pf(n){var t=i(),r=i();return this.divRemTo(n,t,r),[t,r]}function wf(n){this[this.t]=this.am(0,n-1,this,0,0,this.t);++this.t;this.clamp()}function bf(n,t){if(n!=0){while(this.t<=t)this[this.t++]=0;for(this[t]+=n;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}}function tt(){}function ni(n){return n}function kf(n,t,i){n.multiplyTo(t,i)}function df(n,t){n.squareTo(t)}function gf(n){return this.exp(n,new tt)}function ne(n,t,i){var r=Math.min(this.t+n.t,t),u;for(i.s=0,i.t=r;r>0;)i[--r]=0;for(u=i.t-this.t;r<u;++r)i[r+this.t]=this.am(0,n[r],i,r,0,this.t);for(u=Math.min(n.t,t);r<u;++r)this.am(0,n[r],i,r,0,t-r);i.clamp()}function te(n,t,i){--t;var r=i.t=this.t+n.t-t;for(i.s=0;--r>=0;)i[r]=0;for(r=Math.max(t-this.t,0);r<n.t;++r)i[this.t+r-t]=this.am(t-r,n[r],i,0,0,this.t+r-t);i.clamp();i.drShiftTo(1,i)}function d(n){this.r2=i();this.q3=i();t.ONE.dlShiftTo(2*n.t,this.r2);this.mu=this.r2.divide(n);this.m=n}function ie(n){if(n.s<0||n.t>2*this.m.t)return n.mod(this.m);if(n.compareTo(this.m)<0)return n;var t=i();return n.copyTo(t),this.reduce(t),t}function re(n){return n}function ue(n){for(n.drShiftTo(this.m.t-1,this.r2),n.t>this.m.t+1&&(n.t=this.m.t+1,n.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);n.compareTo(this.r2)<0;)n.dAddOffset(1,this.m.t+1);for(n.subTo(this.r2,n);n.compareTo(this.m)>=0;)n.subTo(this.m,n)}function fe(n,t){n.squareTo(t);this.reduce(t)}function ee(n,t,i){n.multiplyTo(t,i);this.reduce(i)}function oe(n,t){var r=n.bitLength(),l,u=a(1),e,b;if(r<=0)return u;l=r<18?1:r<48?3:r<144?4:r<768?5:6;e=r<8?new p(t):t.isEven()?new d(t):new w(t);var h=[],f=3,v=l-1,k=(1<<l)-1;if(h[1]=e.convert(this),l>1)for(b=i(),e.sqrTo(h[1],b);f<=k;)h[f]=i(),e.mulTo(b,h[f-2],h[f]),f+=2;var o=n.t-1,c,g=!0,s=i(),y;for(r=ut(n[o])-1;o>=0;){for(r>=v?c=n[o]>>r-v&k:(c=(n[o]&(1<<r+1)-1)<<v-r,o>0&&(c|=n[o-1]>>this.DB+r-v)),f=l;(c&1)==0;)c>>=1,--f;if((r-=f)<0&&(r+=this.DB,--o),g)h[c].copyTo(u),g=!1;else{while(f>1)e.sqrTo(u,s),e.sqrTo(s,u),f-=2;f>0?e.sqrTo(u,s):(y=u,u=s,s=y);e.mulTo(s,h[c],u)}while(o>=0&&(n[o]&1<<r)==0)e.sqrTo(u,s),y=u,u=s,s=y,--r<0&&(r=this.DB-1,--o)}return e.revert(u)}function se(n){var i=this.s<0?this.negate():this.clone(),t=n.s<0?n.negate():n.clone(),f,u,r;if(i.compareTo(t)<0&&(f=i,i=t,t=f),u=i.getLowestSetBit(),r=t.getLowestSetBit(),r<0)return i;for(u<r&&(r=u),r>0&&(i.rShiftTo(r,i),t.rShiftTo(r,t));i.signum()>0;)(u=i.getLowestSetBit())>0&&i.rShiftTo(u,i),(u=t.getLowestSetBit())>0&&t.rShiftTo(u,t),i.compareTo(t)>=0?(i.subTo(t,i),i.rShiftTo(1,i)):(t.subTo(i,t),t.rShiftTo(1,t));return r>0&&t.lShiftTo(r,t),t}function he(n){var r,t,i;if(n<=0)return 0;if(r=this.DV%n,t=this.s<0?n-1:0,this.t>0)if(r==0)t=this[0]%n;else for(i=this.t-1;i>=0;--i)t=(r*t+this[i])%n;return t}function ce(n){var s=n.isEven();if(this.isEven()&&s||n.signum()==0)return t.ZERO;for(var u=n.clone(),f=this.clone(),e=a(1),r=a(0),o=a(0),i=a(1);u.signum()!=0;){while(u.isEven())u.rShiftTo(1,u),s?(e.isEven()&&r.isEven()||(e.addTo(this,e),r.subTo(n,r)),e.rShiftTo(1,e)):r.isEven()||r.subTo(n,r),r.rShiftTo(1,r);while(f.isEven())f.rShiftTo(1,f),s?(o.isEven()&&i.isEven()||(o.addTo(this,o),i.subTo(n,i)),o.rShiftTo(1,o)):i.isEven()||i.subTo(n,i),i.rShiftTo(1,i);u.compareTo(f)>=0?(u.subTo(f,u),s&&e.subTo(o,e),r.subTo(i,r)):(f.subTo(u,f),s&&o.subTo(e,o),i.subTo(r,i))}if(f.compareTo(t.ONE)!=0)return t.ZERO;if(i.compareTo(n)>=0)return i.subtract(n);if(i.signum()<0)i.addTo(n,i);else return i;return i.signum()<0?i.add(n):i}function le(n){var t,i=this.abs(),r,u;if(i.t==1&&i[0]<=e[e.length-1]){for(t=0;t<e.length;++t)if(i[0]==e[t])return!0;return!1}if(i.isEven())return!1;for(t=1;t<e.length;){for(r=e[t],u=t+1;u<e.length&&r<ti;)r*=e[u++];for(r=i.modInt(r);t<u;)if(r%e[t++]==0)return!1}return i.millerRabin(n)}function ae(n){var u=this.subtract(t.ONE),f=u.getLowestSetBit(),h,o,s,r,c;if(f<=0)return!1;for(h=u.shiftRight(f),n=n+1>>1,n>e.length&&(n=e.length),o=i(),s=0;s<n;++s)if(o.fromInt(e[Math.floor(Math.random()*e.length)]),r=o.modPow(h,this),r.compareTo(t.ONE)!=0&&r.compareTo(u)!=0){for(c=1;c++<f&&r.compareTo(u)!=0;)if(r=r.modPowInt(2,this),r.compareTo(t.ONE)==0)return!1;if(r.compareTo(u)!=0)return!1}return!0}function ct(){this.i=0;this.j=0;this.S=[]}function ve(n){for(var i,r,t=0;t<256;++t)this.S[t]=t;for(i=0,t=0;t<256;++t)i=i+this.S[t]+n[t%n.length]&255,r=this.S[t],this.S[t]=this.S[i],this.S[i]=r;this.i=0;this.j=0}function ye(){var n;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,n=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=n,this.S[n+this.S[this.i]&255]}function pe(){return new ct}function we(){if(et==null){for(et=pe();h<lt;){var n=Math.floor(65536*Math.random());y[h++]=n&255}for(et.init(y),h=0;h<y.length;++h)y[h]=0;h=0}return et.next()}function be(n){for(var t=0;t<n.length;++t)n[t]=we()}function ht(){}function f(n,i){return new t(n,i)}function ke(n,i){var r,e,u,o,f;if(i<n.length+11)return console.error("Message too long for RSA"),null;for(r=[],e=n.length-1;e>=0&&i>0;)u=n.charCodeAt(e--),u<128?r[--i]=u:u>127&&u<2048?(r[--i]=u&63|128,r[--i]=u>>6|192):(r[--i]=u&63|128,r[--i]=u>>6&63|128,r[--i]=u>>12|224);for(r[--i]=0,o=new ht,f=[];i>2;){for(f[0]=0;f[0]==0;)o.nextBytes(f);r[--i]=f[0]}return r[--i]=2,r[--i]=0,new t(r)}function u(){this.n=null;this.e=0;this.d=null;this.p=null;this.q=null;this.dmp1=null;this.dmq1=null;this.coeff=null}function de(n,t){n!=null&&t!=null&&n.length>0&&t.length>0?(this.n=f(n,16),this.e=parseInt(t,16)):console.error("Invalid RSA public key")}function ge(n){return n.modPowInt(this.e,this.n)}function no(n){var r=ke(n,this.n.bitLength()+7>>3),i,t;return r==null?null:(i=this.doPublic(r),i==null)?null:(t=i.toString(16),(t.length&1)==0?t:"0"+t)}function to(n,t){for(var r=n.toByteArray(),i=0,f,u;i<r.length&&r[i]==0;)++i;if(r.length-i!=t-1||r[i]!=2)return null;for(++i;r[i]!=0;)if(++i>=r.length)return null;for(f="";++i<r.length;)u=r[i]&255,u<128?f+=String.fromCharCode(u):u>191&&u<224?(f+=String.fromCharCode((u&31)<<6|r[i+1]&63),++i):(f+=String.fromCharCode((u&15)<<12|(r[i+1]&63)<<6|r[i+2]&63),i+=2);return f}function io(n,t,i){n!=null&&t!=null&&n.length>0&&t.length>0?(this.n=f(n,16),this.e=parseInt(t,16),this.d=f(i,16)):console.error("Invalid RSA private key")}function ro(n,t,i,r,u,e,o,s){n!=null&&t!=null&&n.length>0&&t.length>0?(this.n=f(n,16),this.e=parseInt(t,16),this.d=f(i,16),this.p=f(r,16),this.q=f(u,16),this.dmp1=f(e,16),this.dmq1=f(o,16),this.coeff=f(s,16)):console.error("Invalid RSA private key")}function uo(n,i){var u=new ht,f=n>>1,r,e;for(this.e=parseInt(i,16),r=new t(i,16);;){for(;;)if(this.p=new t(n-f,1,u),this.p.subtract(t.ONE).gcd(r).compareTo(t.ONE)==0&&this.p.isProbablePrime(10))break;for(;;)if(this.q=new t(f,1,u),this.q.subtract(t.ONE).gcd(r).compareTo(t.ONE)==0&&this.q.isProbablePrime(10))break;this.p.compareTo(this.q)<=0&&(e=this.p,this.p=this.q,this.q=e);var o=this.p.subtract(t.ONE),s=this.q.subtract(t.ONE),h=o.multiply(s);if(h.gcd(r).compareTo(t.ONE)==0){this.n=this.p.multiply(this.q);this.d=r.modInverse(h);this.dmp1=this.d.mod(o);this.dmq1=this.d.mod(s);this.coeff=this.q.modInverse(this.p);break}}}function fo(n){if(this.p==null||this.q==null)return n.modPow(this.d,this.n);for(var t=n.mod(this.p).modPow(this.dmp1,this.p),i=n.mod(this.q).modPow(this.dmq1,this.q);t.compareTo(i)<0;)t=t.add(this.p);return t.subtract(i).multiply(this.coeff).mod(this.p).multiply(this.q).add(i)}function eo(n){var i=f(n,16),t=this.doPrivate(i);return t==null?null:to(t,this.n.bitLength()+7>>3)}function vt(n){for(var i,r="",t=0;t+3<=n.length;t+=3)i=parseInt(n.substring(t,t+3),16),r+=b.charAt(i>>6)+b.charAt(i&63);for(t+1==n.length?(i=parseInt(n.substring(t,t+1),16),r+=b.charAt(i<<2)):t+2==n.length&&(i=parseInt(n.substring(t,t+2),16),r+=b.charAt(i>>2)+b.charAt((i&3)<<4));(r.length&3)>0;)r+=at;return r}function ii(n){for(var t="",i=0,r,u=0;u<n.length;++u){if(n.charAt(u)==at)break;(v=b.indexOf(n.charAt(u)),v<0)||(i==0?(t+=c(v>>2),r=v&3,i=1):i==1?(t+=c(r<<2|v>>4),r=v&15,i=2):i==2?(t+=c(r),t+=c(v>>2),r=v&3,i=3):(t+=c(r<<2|v>>4),t+=c(v&15),i=0))}return i==1&&(t+=c(r<<2)),t}var l,wt=(0xdeadbeefcafe&16777215)==15715070,rt,bt,nt,k,o,e,ti,lt,et,y,h,ot,st,it,b,at,r,g,s;for(wt&&navigator.appName=="Microsoft Internet Explorer"?(t.prototype.am=fi,l=30):wt&&navigator.appName!="Netscape"?(t.prototype.am=ui,l=26):(t.prototype.am=ei,l=28),t.prototype.DB=l,t.prototype.DM=(1<<l)-1,t.prototype.DV=1<<l,rt=52,t.prototype.FV=Math.pow(2,rt),t.prototype.F1=rt-l,t.prototype.F2=2*l-rt,bt="0123456789abcdefghijklmnopqrstuvwxyz",nt=[],k="0".charCodeAt(0),o=0;o<=9;++o)nt[k++]=o;for(k="a".charCodeAt(0),o=10;o<36;++o)nt[k++]=o;for(k="A".charCodeAt(0),o=10;o<36;++o)nt[k++]=o;if(p.prototype.convert=ur,p.prototype.revert=fr,p.prototype.reduce=er,p.prototype.mulTo=or,p.prototype.sqrTo=sr,w.prototype.convert=cr,w.prototype.revert=lr,w.prototype.reduce=ar,w.prototype.mulTo=yr,w.prototype.sqrTo=vr,t.prototype.copyTo=oi,t.prototype.fromInt=si,t.prototype.fromString=hi,t.prototype.clamp=ci,t.prototype.dlShiftTo=wi,t.prototype.drShiftTo=bi,t.prototype.lShiftTo=ki,t.prototype.rShiftTo=di,t.prototype.subTo=gi,t.prototype.multiplyTo=nr,t.prototype.squareTo=tr,t.prototype.divRemTo=ir,t.prototype.invDigit=hr,t.prototype.isEven=pr,t.prototype.exp=wr,t.prototype.toString=li,t.prototype.negate=ai,t.prototype.abs=vi,t.prototype.compareTo=yi,t.prototype.bitLength=pi,t.prototype.mod=rr,t.prototype.modPowInt=br,t.ZERO=a(0),t.ONE=a(1),tt.prototype.convert=ni,tt.prototype.revert=ni,tt.prototype.mulTo=kf,tt.prototype.sqrTo=df,d.prototype.convert=ie,d.prototype.revert=re,d.prototype.reduce=ue,d.prototype.mulTo=ee,d.prototype.sqrTo=fe,e=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],ti=67108864/e[e.length-1],t.prototype.chunkSize=tu,t.prototype.toRadix=ru,t.prototype.fromRadix=uu,t.prototype.fromNumber=fu,t.prototype.bitwiseTo=cu,t.prototype.changeBit=uf,t.prototype.addTo=sf,t.prototype.dMultiply=wf,t.prototype.dAddOffset=bf,t.prototype.multiplyLowerTo=ne,t.prototype.multiplyUpperTo=te,t.prototype.modInt=he,t.prototype.millerRabin=ae,t.prototype.clone=kr,t.prototype.intValue=dr,t.prototype.byteValue=gr,t.prototype.shortValue=nu,t.prototype.signum=iu,t.prototype.toByteArray=eu,t.prototype.equals=ou,t.prototype.min=su,t.prototype.max=hu,t.prototype.and=au,t.prototype.or=vu,t.prototype.xor=yu,t.prototype.andNot=pu,t.prototype.not=wu,t.prototype.shiftLeft=bu,t.prototype.shiftRight=ku,t.prototype.getLowestSetBit=gu,t.prototype.bitCount=tf,t.prototype.testBit=rf,t.prototype.setBit=ff,t.prototype.clearBit=ef,t.prototype.flipBit=of,t.prototype.add=hf,t.prototype.subtract=cf,t.prototype.multiply=lf,t.prototype.divide=vf,t.prototype.remainder=yf,t.prototype.divideAndRemainder=pf,t.prototype.modPow=oe,t.prototype.modInverse=ce,t.prototype.pow=gf,t.prototype.gcd=se,t.prototype.isProbablePrime=le,t.prototype.square=af,ct.prototype.init=ve,ct.prototype.next=ye,lt=256,y==null){if(y=[],h=0,window.crypto&&window.crypto.getRandomValues)for(st=new Uint32Array(256),window.crypto.getRandomValues(st),ot=0;ot<st.length;++ot)y[h++]=st[ot]&255;it=function(n){if(this.count=this.count||0,this.count>=256||h>=lt){window.removeEventListener?window.removeEventListener("mousemove",it):window.detachEvent&&window.detachEvent("onmousemove",it);return}this.count+=1;var t=n.x+n.y;y[h++]=t&255};window.addEventListener?window.addEventListener("mousemove",it):window.attachEvent&&window.attachEvent("onmousemove",it)}ht.prototype.nextBytes=be;u.prototype.doPublic=ge;u.prototype.setPublic=de;u.prototype.encrypt=no;u.prototype.doPrivate=fo;u.prototype.setPrivate=io;u.prototype.setPrivateEx=ro;u.prototype.generate=uo;u.prototype.decrypt=eo,function(){var f=function(n,r,u){var o=new ht,s=n>>1;this.e=parseInt(r,16);var e=new t(r,16),f=this,h=function(){var l=function(){var n;f.p.compareTo(f.q)<=0&&(n=f.p,f.p=f.q,f.q=n);var i=f.p.subtract(t.ONE),r=f.q.subtract(t.ONE),o=i.multiply(r);o.gcd(e).compareTo(t.ONE)==0?(f.n=f.p.multiply(f.q),f.d=e.modInverse(o),f.dmp1=f.d.mod(i),f.dmq1=f.d.mod(r),f.coeff=f.q.modInverse(f.p),setTimeout(function(){u()},0)):setTimeout(h,0)},r=function(){f.q=i();f.q.fromNumberAsync(s,1,o,function(){f.q.subtract(t.ONE).gcda(e,function(n){n.compareTo(t.ONE)==0&&f.q.isProbablePrime(10)?setTimeout(l,0):setTimeout(r,0)})})},c=function(){f.p=i();f.p.fromNumberAsync(n-s,1,o,function(){f.p.subtract(t.ONE).gcda(e,function(n){n.compareTo(t.ONE)==0&&f.p.isProbablePrime(10)?setTimeout(r,0):setTimeout(c,0)})})};setTimeout(c,0)};setTimeout(h,0)},n,r;u.prototype.generateAsync=f;n=function(n,t){var r=this.s<0?this.negate():this.clone(),i=n.s<0?n.negate():n.clone(),o,f,u,e;if(r.compareTo(i)<0&&(o=r,r=i,i=o),f=r.getLowestSetBit(),u=i.getLowestSetBit(),u<0){t(r);return}f<u&&(u=f);u>0&&(r.rShiftTo(u,r),i.rShiftTo(u,i));e=function(){(f=r.getLowestSetBit())>0&&r.rShiftTo(f,r);(f=i.getLowestSetBit())>0&&i.rShiftTo(f,i);r.compareTo(i)>=0?(r.subTo(i,r),r.rShiftTo(1,r)):(i.subTo(r,i),i.rShiftTo(1,i));r.signum()>0?setTimeout(e,0):(u>0&&i.lShiftTo(u,i),setTimeout(function(){t(i)},0))};setTimeout(e,10)};t.prototype.gcda=n;r=function(n,i,r,u){var f,o,e,s;"number"==typeof i?n<2?this.fromInt(1):(this.fromNumber(n,r),this.testBit(n-1)||this.bitwiseTo(t.ONE.shiftLeft(n-1),ft,this),this.isEven()&&this.dAddOffset(1,0),f=this,o=function(){f.dAddOffset(2,0);f.bitLength()>n&&f.subTo(t.ONE.shiftLeft(n-1),f);f.isProbablePrime(i)?setTimeout(function(){u()},0):setTimeout(o,0)},setTimeout(o,0)):(e=[],s=n&7,e.length=(n>>3)+1,i.nextBytes(e),s>0?e[0]&=(1<<s)-1:e[0]=0,this.fromString(e,256))};t.prototype.fromNumberAsync=r}();b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";at="=";r=r||{};r.env=r.env||{};var yt=r,pt=Object.prototype,oo="[object Function]",ri=["toString","valueOf"];r.env.parseUA=function(n){var u=function(n){var t=0;return parseFloat(n.replace(/\./g,function(){return t++==1?"":"."}))},f=navigator,i={ie:0,opera:0,gecko:0,webkit:0,chrome:0,mobile:null,air:0,ipad:0,iphone:0,ipod:0,ios:null,android:0,webos:0,caja:f&&f.cajaVersion,secure:!1,os:null},r=n||navigator&&navigator.userAgent,e=window&&window.location,o=e&&e.href,t;return i.secure=o&&o.toLowerCase().indexOf("https")===0,r&&(/windows|win32/i.test(r)?i.os="windows":/macintosh/i.test(r)?i.os="macintosh":/rhino/i.test(r)&&(i.os="rhino"),/KHTML/.test(r)&&(i.webkit=1),t=r.match(/AppleWebKit\/([^\s]*)/),t&&t[1]&&(i.webkit=u(t[1]),/ Mobile\//.test(r)?(i.mobile="Apple",t=r.match(/OS ([^\s]*)/),t&&t[1]&&(t=u(t[1].replace("_","."))),i.ios=t,i.ipad=i.ipod=i.iphone=0,t=r.match(/iPad|iPod|iPhone/),t&&t[0]&&(i[t[0].toLowerCase()]=i.ios)):(t=r.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/),t&&(i.mobile=t[0]),/webOS/.test(r)&&(i.mobile="WebOS",t=r.match(/webOS\/([^\s]*);/),t&&t[1]&&(i.webos=u(t[1]))),/ Android/.test(r)&&(i.mobile="Android",t=r.match(/Android ([^\s]*);/),t&&t[1]&&(i.android=u(t[1])))),t=r.match(/Chrome\/([^\s]*)/),t&&t[1]?i.chrome=u(t[1]):(t=r.match(/AdobeAIR\/([^\s]*)/),t&&(i.air=t[0]))),i.webkit||(t=r.match(/Opera[\s\/]([^\s]*)/),t&&t[1]?(i.opera=u(t[1]),t=r.match(/Version\/([^\s]*)/),t&&t[1]&&(i.opera=u(t[1])),t=r.match(/Opera Mini[^;]*/),t&&(i.mobile=t[0])):(t=r.match(/MSIE\s([^;]*)/),t&&t[1]?i.ie=u(t[1]):(t=r.match(/Gecko\/([^\s]*)/),t&&(i.gecko=1,t=r.match(/rv:([^\s\)]*)/),t&&t[1]&&(i.gecko=u(t[1]))))))),i};r.env.ua=r.env.parseUA();r.isFunction=function(n){return typeof n=="function"||pt.toString.apply(n)===oo};r._IEEnumFix=r.env.ua.ie?function(n,t){for(var r,u,i=0;i<ri.length;i=i+1)r=ri[i],u=t[r],yt.isFunction(u)&&u!=pt[r]&&(n[r]=u)}:function(){};r.extend=function(n,t,i){if(!t||!n)throw new Error("extend failed, please check that all dependencies are included.");var u=function(){},r;if(u.prototype=t.prototype,n.prototype=new u,n.prototype.constructor=n,n.superclass=t.prototype,t.prototype.constructor==pt.constructor&&(t.prototype.constructor=t),i){for(r in i)yt.hasOwnProperty(i,r)&&(n.prototype[r]=i[r]);yt._IEEnumFix(n.prototype,i)}};typeof KJUR!="undefined"&&KJUR||(KJUR={});typeof KJUR.asn1!="undefined"&&KJUR.asn1||(KJUR.asn1={});KJUR.asn1.ASN1Util=new function(){this.integerToByteHex=function(n){var t=n.toString(16);return t.length%2==1&&(t="0"+t),t};this.bigIntToMinTwosComplementsHex=function(n){var i=n.toString(16),e,r,u,f,o,s;if(i.substr(0,1)!="-")i.length%2==1?i="0"+i:i.match(/^[0-7]/)||(i="00"+i);else{for(e=i.substr(1),r=e.length,r%2==1?r+=1:i.match(/^[0-7]/)||(r+=2),u="",f=0;f<r;f++)u+="f";o=new t(u,16);s=o.xor(n).add(t.ONE);i=s.toString(16).replace(/^-/,"")}return i};this.getPEMStringFromHex=function(n,t){var r=CryptoJS.enc.Hex.parse(n),u=CryptoJS.enc.Base64.stringify(r),i=u.replace(/(.{64})/g,"$1\r\n");return i=i.replace(/\r\n$/,""),"-----BEGIN "+t+"-----\r\n"+i+"\r\n-----END "+t+"-----\r\n"}};KJUR.asn1.ASN1Object=function(){var n="";this.getLengthHexFromValue=function(){var i,t,r,u;if(typeof this.hV=="undefined"||this.hV==null)throw"this.hV is null or undefined.";if(this.hV.length%2==1)throw"value hex must be even length: n="+n.length+",v="+this.hV;if(i=this.hV.length/2,t=i.toString(16),t.length%2==1&&(t="0"+t),i<128)return t;if(r=t.length/2,r>15)throw"ASN.1 length too long to represent by 8x: n = "+i.toString(16);return u=128+r,u.toString(16)+t};this.getEncodedHex=function(){return(this.hTLV==null||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV};this.getValueHex=function(){return this.getEncodedHex(),this.hV};this.getFreshValueHex=function(){return""}};KJUR.asn1.DERAbstractString=function(n){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);this.getString=function(){return this.s};this.setString=function(n){this.hTLV=null;this.isModified=!0;this.s=n;this.hV=stohex(this.s)};this.setStringHex=function(n){this.hTLV=null;this.isModified=!0;this.s=null;this.hV=n};this.getFreshValueHex=function(){return this.hV};typeof n!="undefined"&&(typeof n.str!="undefined"?this.setString(n.str):typeof n.hex!="undefined"&&this.setStringHex(n.hex))};r.extend(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object);KJUR.asn1.DERAbstractTime=function(){KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);this.localDateToUTC=function(n){utc=n.getTime()+n.getTimezoneOffset()*6e4;return new Date(utc)};this.formatDate=function(n,t){var r=this.zeroPadding,i=this.localDateToUTC(n),u=String(i.getFullYear());t=="utc"&&(u=u.substr(2,2));var f=r(String(i.getMonth()+1),2),e=r(String(i.getDate()),2),o=r(String(i.getHours()),2),s=r(String(i.getMinutes()),2),h=r(String(i.getSeconds()),2);return u+f+e+o+s+h+"Z"};this.zeroPadding=function(n,t){return n.length>=t?n:new Array(t-n.length+1).join("0")+n};this.getString=function(){return this.s};this.setString=function(n){this.hTLV=null;this.isModified=!0;this.s=n;this.hV=stohex(this.s)};this.setByDateValue=function(n,t,i,r,u,f){var e=new Date(Date.UTC(n,t-1,i,r,u,f,0));this.setByDate(e)};this.getFreshValueHex=function(){return this.hV}};r.extend(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object);KJUR.asn1.DERAbstractStructured=function(n){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);this.setByASN1ObjectArray=function(n){this.hTLV=null;this.isModified=!0;this.asn1Array=n};this.appendASN1Object=function(n){this.hTLV=null;this.isModified=!0;this.asn1Array.push(n)};this.asn1Array=[];typeof n!="undefined"&&typeof n.array!="undefined"&&(this.asn1Array=n.array)};r.extend(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object);KJUR.asn1.DERBoolean=function(){KJUR.asn1.DERBoolean.superclass.constructor.call(this);this.hT="01";this.hTLV="0101ff"};r.extend(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object);KJUR.asn1.DERInteger=function(n){KJUR.asn1.DERInteger.superclass.constructor.call(this);this.hT="02";this.setByBigInteger=function(n){this.hTLV=null;this.isModified=!0;this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(n)};this.setByInteger=function(n){var i=new t(String(n),10);this.setByBigInteger(i)};this.setValueHex=function(n){this.hV=n};this.getFreshValueHex=function(){return this.hV};typeof n!="undefined"&&(typeof n.bigint!="undefined"?this.setByBigInteger(n.bigint):typeof n.int!="undefined"?this.setByInteger(n.int):typeof n.hex!="undefined"&&this.setValueHex(n.hex))};r.extend(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object);KJUR.asn1.DERBitString=function(n){KJUR.asn1.DERBitString.superclass.constructor.call(this);this.hT="03";this.setHexValueIncludingUnusedBits=function(n){this.hTLV=null;this.isModified=!0;this.hV=n};this.setUnusedBitsAndHexValue=function(n,t){if(n<0||7<n)throw"unused bits shall be from 0 to 7: u = "+n;var i="0"+n;this.hTLV=null;this.isModified=!0;this.hV=i+t};this.setByBinaryString=function(n){var i,u,t,f,r;for(n=n.replace(/0+$/,""),i=8-n.length%8,i==8&&(i=0),t=0;t<=i;t++)n+="0";for(u="",t=0;t<n.length-1;t+=8)f=n.substr(t,8),r=parseInt(f,2).toString(16),r.length==1&&(r="0"+r),u+=r;this.hTLV=null;this.isModified=!0;this.hV="0"+i+u};this.setByBooleanArray=function(n){for(var i="",t=0;t<n.length;t++)i+=n[t]==!0?"1":"0";this.setByBinaryString(i)};this.newFalseArray=function(n){for(var i=new Array(n),t=0;t<n;t++)i[t]=!1;return i};this.getFreshValueHex=function(){return this.hV};typeof n!="undefined"&&(typeof n.hex!="undefined"?this.setHexValueIncludingUnusedBits(n.hex):typeof n.bin!="undefined"?this.setByBinaryString(n.bin):typeof n.array!="undefined"&&this.setByBooleanArray(n.array))};r.extend(KJUR.asn1.DERBitString,KJUR.asn1.ASN1Object);KJUR.asn1.DEROctetString=function(n){KJUR.asn1.DEROctetString.superclass.constructor.call(this,n);this.hT="04"};r.extend(KJUR.asn1.DEROctetString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERNull=function(){KJUR.asn1.DERNull.superclass.constructor.call(this);this.hT="05";this.hTLV="0500"};r.extend(KJUR.asn1.DERNull,KJUR.asn1.ASN1Object);KJUR.asn1.DERObjectIdentifier=function(n){var i=function(n){var t=n.toString(16);return t.length==1&&(t="0"+t),t},r=function(n){var s="",h=new t(n,10),u=h.toString(2),e=7-u.length%7,o,r,f;for(e==7&&(e=0),o="",r=0;r<e;r++)o+="0";for(u=o+u,r=0;r<u.length-1;r+=7)f=u.substr(r,7),r!=u.length-7&&(f="1"+f),s+=i(parseInt(f,2));return s};KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);this.hT="06";this.setValueHex=function(n){this.hTLV=null;this.isModified=!0;this.s=null;this.hV=n};this.setValueOidString=function(n){var u;if(!n.match(/^[0-9.]+$/))throw"malformed oid string: "+n;var f="",t=n.split("."),e=parseInt(t[0])*40+parseInt(t[1]);for(f+=i(e),t.splice(0,2),u=0;u<t.length;u++)f+=r(t[u]);this.hTLV=null;this.isModified=!0;this.s=null;this.hV=f};this.setValueName=function(n){if(typeof KJUR.asn1.x509.OID.name2oidList[n]!="undefined"){var t=KJUR.asn1.x509.OID.name2oidList[n];this.setValueOidString(t)}else throw"DERObjectIdentifier oidName undefined: "+n;};this.getFreshValueHex=function(){return this.hV};typeof n!="undefined"&&(typeof n.oid!="undefined"?this.setValueOidString(n.oid):typeof n.hex!="undefined"?this.setValueHex(n.hex):typeof n.name!="undefined"&&this.setValueName(n.name))};r.extend(KJUR.asn1.DERObjectIdentifier,KJUR.asn1.ASN1Object);KJUR.asn1.DERUTF8String=function(n){KJUR.asn1.DERUTF8String.superclass.constructor.call(this,n);this.hT="0c"};r.extend(KJUR.asn1.DERUTF8String,KJUR.asn1.DERAbstractString);KJUR.asn1.DERNumericString=function(n){KJUR.asn1.DERNumericString.superclass.constructor.call(this,n);this.hT="12"};r.extend(KJUR.asn1.DERNumericString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERPrintableString=function(n){KJUR.asn1.DERPrintableString.superclass.constructor.call(this,n);this.hT="13"};r.extend(KJUR.asn1.DERPrintableString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERTeletexString=function(n){KJUR.asn1.DERTeletexString.superclass.constructor.call(this,n);this.hT="14"};r.extend(KJUR.asn1.DERTeletexString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERIA5String=function(n){KJUR.asn1.DERIA5String.superclass.constructor.call(this,n);this.hT="16"};r.extend(KJUR.asn1.DERIA5String,KJUR.asn1.DERAbstractString);KJUR.asn1.DERUTCTime=function(n){KJUR.asn1.DERUTCTime.superclass.constructor.call(this,n);this.hT="17";this.setByDate=function(n){this.hTLV=null;this.isModified=!0;this.date=n;this.s=this.formatDate(this.date,"utc");this.hV=stohex(this.s)};typeof n!="undefined"&&(typeof n.str!="undefined"?this.setString(n.str):typeof n.hex!="undefined"?this.setStringHex(n.hex):typeof n.date!="undefined"&&this.setByDate(n.date))};r.extend(KJUR.asn1.DERUTCTime,KJUR.asn1.DERAbstractTime);KJUR.asn1.DERGeneralizedTime=function(n){KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this,n);this.hT="18";this.setByDate=function(n){this.hTLV=null;this.isModified=!0;this.date=n;this.s=this.formatDate(this.date,"gen");this.hV=stohex(this.s)};typeof n!="undefined"&&(typeof n.str!="undefined"?this.setString(n.str):typeof n.hex!="undefined"?this.setStringHex(n.hex):typeof n.date!="undefined"&&this.setByDate(n.date))};r.extend(KJUR.asn1.DERGeneralizedTime,KJUR.asn1.DERAbstractTime);KJUR.asn1.DERSequence=function(n){KJUR.asn1.DERSequence.superclass.constructor.call(this,n);this.hT="30";this.getFreshValueHex=function(){for(var i,t="",n=0;n<this.asn1Array.length;n++)i=this.asn1Array[n],t+=i.getEncodedHex();return this.hV=t,this.hV}};r.extend(KJUR.asn1.DERSequence,KJUR.asn1.DERAbstractStructured);KJUR.asn1.DERSet=function(n){KJUR.asn1.DERSet.superclass.constructor.call(this,n);this.hT="31";this.getFreshValueHex=function(){for(var i,n=[],t=0;t<this.asn1Array.length;t++)i=this.asn1Array[t],n.push(i.getEncodedHex());return n.sort(),this.hV=n.join(""),this.hV}};r.extend(KJUR.asn1.DERSet,KJUR.asn1.DERAbstractStructured);KJUR.asn1.DERTaggedObject=function(n){KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);this.hT="a0";this.hV="";this.isExplicit=!0;this.asn1Object=null;this.setASN1Object=function(n,t,i){this.hT=t;this.isExplicit=n;this.asn1Object=i;this.isExplicit?(this.hV=this.asn1Object.getEncodedHex(),this.hTLV=null,this.isModified=!0):(this.hV=null,this.hTLV=i.getEncodedHex(),this.hTLV=this.hTLV.replace(/^../,t),this.isModified=!1)};this.getFreshValueHex=function(){return this.hV};typeof n!="undefined"&&(typeof n.tag!="undefined"&&(this.hT=n.tag),typeof n.explicit!="undefined"&&(this.isExplicit=n.explicit),typeof n.obj!="undefined"&&(this.asn1Object=n.obj,this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)))};r.extend(KJUR.asn1.DERTaggedObject,KJUR.asn1.ASN1Object),function(n){"use strict";var i={},t;i.decode=function(i){var r,f,o,u;if(t===n){for(f="0123456789ABCDEF",o=" \f\n\r\t \u2028\u2029",t=[],r=0;r<16;++r)t[f.charAt(r)]=r;for(f=f.toLowerCase(),r=10;r<16;++r)t[f.charAt(r)]=r;for(r=0;r<o.length;++r)t[o.charAt(r)]=-1}var s=[],e=0,h=0;for(r=0;r<i.length;++r){if(u=i.charAt(r),u=="=")break;if(u=t[u],u!=-1){if(u===n)throw"Illegal character at offset "+r;e|=u;++h>=2?(s[s.length]=e,e=0,h=0):e<<=4}}if(h)throw"Hex encoding incomplete: 4 bits missing";return s};window.Hex=i}(),function(n){"use strict";var t={},i;t.decode=function(t){var r,h,o,e;if(i===n){for(h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o="= \f\n\r\t \u2028\u2029",i=[],r=0;r<64;++r)i[h.charAt(r)]=r;for(r=0;r<o.length;++r)i[o.charAt(r)]=-1}var u=[],f=0,s=0;for(r=0;r<t.length;++r){if(e=t.charAt(r),e=="=")break;if(e=i[e],e!=-1){if(e===n)throw"Illegal character at offset "+r;f|=e;++s>=4?(u[u.length]=f>>16,u[u.length]=f>>8&255,u[u.length]=f&255,f=0,s=0):f<<=6}}switch(s){case 1:throw"Base64 encoding incomplete: at least 2 bits missing";case 2:u[u.length]=f>>10;break;case 3:u[u.length]=f>>16;u[u.length]=f>>8&255}return u};t.re=/-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/;t.unarmor=function(n){var i=t.re.exec(n);if(i)if(i[1])n=i[1];else if(i[2])n=i[2];else throw"RegExp out of sync";return t.decode(n)};window.Base64=t}(),function(n){"use strict";function i(n,t){n instanceof i?(this.enc=n.enc,this.pos=n.pos):(this.enc=n,this.pos=t)}function t(n,t,i,r,u){this.stream=n;this.header=t;this.length=i;this.tag=r;this.sub=u}var u=100,f="…",r={tag:function(n,t){var i=document.createElement(n);return i.className=t,i},text:function(n){return document.createTextNode(n)}};i.prototype.get=function(t){if(t===n&&(t=this.pos++),t>=this.enc.length)throw"Requesting byte offset "+t+" on a stream of length "+this.enc.length;return this.enc[t]};i.prototype.hexDigits="0123456789ABCDEF";i.prototype.hexByte=function(n){return this.hexDigits.charAt(n>>4&15)+this.hexDigits.charAt(n&15)};i.prototype.hexDump=function(n,t,i){for(var r="",u=n;u<t;++u)if(r+=this.hexByte(this.get(u)),i!==!0)switch(u&15){case 7:r+="  ";break;case 15:r+="\n";break;default:r+=" "}return r};i.prototype.parseStringISO=function(n,t){for(var r="",i=n;i<t;++i)r+=String.fromCharCode(this.get(i));return r};i.prototype.parseStringUTF=function(n,t){for(var i,u="",r=n;r<t;)i=this.get(r++),u+=i<128?String.fromCharCode(i):i>191&&i<224?String.fromCharCode((i&31)<<6|this.get(r++)&63):String.fromCharCode((i&15)<<12|(this.get(r++)&63)<<6|this.get(r++)&63);return u};i.prototype.parseStringBMP=function(n,t){for(var u,f,r="",i=n;i<t;i+=2)u=this.get(i),f=this.get(i+1),r+=String.fromCharCode((u<<8)+f);return r};i.prototype.reTime=/^((?:1[89]|2\d)?\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;i.prototype.parseTime=function(n,t){var r=this.parseStringISO(n,t),i=this.reTime.exec(r);return i?(r=i[1]+"-"+i[2]+"-"+i[3]+" "+i[4],i[5]&&(r+=":"+i[5],i[6]&&(r+=":"+i[6],i[7]&&(r+="."+i[7]))),i[8]&&(r+=" UTC",i[8]!="Z"&&(r+=i[8],i[9]&&(r+=":"+i[9]))),r):"Unrecognized time: "+r};i.prototype.parseInteger=function(n,t){var i=t-n,r,u,f;if(i>4){if(i<<=3,r=this.get(n),r===0)i-=8;else while(r<128)r<<=1,--i;return"("+i+" bit)"}for(u=0,f=n;f<t;++f)u=u<<8|this.get(f);return u};i.prototype.parseBitString=function(n,t){var e=this.get(n),o=(t-n-1<<3)-e,u="("+o+" bit)",f,i,s,r;if(o<=20)for(f=e,u+=" ",i=t-1;i>n;--i){for(s=this.get(i),r=f;r<8;++r)u+=s>>r&1?"1":"0";f=0}return u};i.prototype.parseOctetString=function(n,t){var r=t-n,e="("+r+" byte) ",i;for(r>u&&(t=n+u),i=n;i<t;++i)e+=this.hexByte(this.get(i));return r>u&&(e+=f),e};i.prototype.parseOID=function(n,t){for(var e,o,r="",i=0,u=0,f=n;f<t;++f)e=this.get(f),i=i<<7|e&127,u+=7,e&128||(r===""?(o=i<80?i<40?0:1:2,r=o+"."+(i-o*40)):r+="."+(u>=31?"bigint":i),i=u=0);return r};t.prototype.typeName=function(){if(this.tag===n)return"unknown";var i=this.tag>>6,r=this.tag>>5&1,t=this.tag&31;switch(i){case 0:switch(t){case 0:return"EOC";case 1:return"BOOLEAN";case 2:return"INTEGER";case 3:return"BIT_STRING";case 4:return"OCTET_STRING";case 5:return"NULL";case 6:return"OBJECT_IDENTIFIER";case 7:return"ObjectDescriptor";case 8:return"EXTERNAL";case 9:return"REAL";case 10:return"ENUMERATED";case 11:return"EMBEDDED_PDV";case 12:return"UTF8String";case 16:return"SEQUENCE";case 17:return"SET";case 18:return"NumericString";case 19:return"PrintableString";case 20:return"TeletexString";case 21:return"VideotexString";case 22:return"IA5String";case 23:return"UTCTime";case 24:return"GeneralizedTime";case 25:return"GraphicString";case 26:return"VisibleString";case 27:return"GeneralString";case 28:return"UniversalString";case 30:return"BMPString";default:return"Universal_"+t.toString(16)}case 1:return"Application_"+t.toString(16);case 2:return"["+t+"]";case 3:return"Private_"+t.toString(16)}};t.prototype.reSeemsASCII=/^[ -~]+$/;t.prototype.content=function(){var r;if(this.tag===n)return null;var e=this.tag>>6,o=this.tag&31,t=this.posContent(),i=Math.abs(this.length);if(e!==0)return this.sub!==null?"("+this.sub.length+" elem)":(r=this.stream.parseStringISO(t,t+Math.min(i,u)),this.reSeemsASCII.test(r)?r.substring(0,2*u)+(r.length>2*u?f:""):this.stream.parseOctetString(t,t+i));switch(o){case 1:return this.stream.get(t)===0?"false":"true";case 2:return this.stream.parseInteger(t,t+i);case 3:return this.sub?"("+this.sub.length+" elem)":this.stream.parseBitString(t,t+i);case 4:return this.sub?"("+this.sub.length+" elem)":this.stream.parseOctetString(t,t+i);case 6:return this.stream.parseOID(t,t+i);case 16:case 17:return"("+this.sub.length+" elem)";case 12:return this.stream.parseStringUTF(t,t+i);case 18:case 19:case 20:case 21:case 22:case 26:return this.stream.parseStringISO(t,t+i);case 30:return this.stream.parseStringBMP(t,t+i);case 23:case 24:return this.stream.parseTime(t,t+i)}return null};t.prototype.toString=function(){return this.typeName()+"@"+this.stream.pos+"[header:"+this.header+",length:"+this.length+",sub:"+(this.sub===null?"null":this.sub.length)+"]"};t.prototype.print=function(t){if(t===n&&(t=""),document.writeln(t+this),this.sub!==null){t+="  ";for(var i=0,r=this.sub.length;i<r;++i)this.sub[i].print(t)}};t.prototype.toPrettyString=function(t){var i,r,u;if(t===n&&(t=""),i=t+this.typeName()+" @"+this.stream.pos,this.length>=0&&(i+="+"),i+=this.length,this.tag&32?i+=" (constructed)":(this.tag==3||this.tag==4)&&this.sub!==null&&(i+=" (encapsulates)"),i+="\n",this.sub!==null)for(t+="  ",r=0,u=this.sub.length;r<u;++r)i+=this.sub[r].toPrettyString(t);return i};t.prototype.toDOM=function(){var t=r.tag("div","node"),f,n,i,o,s,u,h,e,c;if(t.asn1=this,f=r.tag("div","head"),n=this.typeName().replace(/_/g," "),f.innerHTML=n,i=this.content(),i!==null&&(i=String(i).replace(/</g,"&lt;"),o=r.tag("span","preview"),o.appendChild(r.text(i)),f.appendChild(o)),t.appendChild(f),this.node=t,this.head=f,s=r.tag("div","value"),n="Offset: "+this.stream.pos+"<br/>",n+="Length: "+this.header+"+",n+=this.length>=0?this.length:-this.length+" (undefined)",this.tag&32?n+="<br/>(constructed)":(this.tag==3||this.tag==4)&&this.sub!==null&&(n+="<br/>(encapsulates)"),i!==null&&(n+="<br/>Value:<br/><b>"+i+"<\/b>",typeof oids=="object"&&this.tag==6&&(u=oids[i],u&&(u.d&&(n+="<br/>"+u.d),u.c&&(n+="<br/>"+u.c),u.w&&(n+="<br/>(warning!)")))),s.innerHTML=n,t.appendChild(s),h=r.tag("div","sub"),this.sub!==null)for(e=0,c=this.sub.length;e<c;++e)h.appendChild(this.sub[e].toDOM());return t.appendChild(h),f.onclick=function(){t.className=t.className=="node collapsed"?"node":"node collapsed"},t};t.prototype.posStart=function(){return this.stream.pos};t.prototype.posContent=function(){return this.stream.pos+this.header};t.prototype.posEnd=function(){return this.stream.pos+this.header+Math.abs(this.length)};t.prototype.fakeHover=function(n){this.node.className+=" hover";n&&(this.head.className+=" hover")};t.prototype.fakeOut=function(n){var t=/ ?hover/;this.node.className=this.node.className.replace(t,"");n&&(this.head.className=this.head.className.replace(t,""))};t.prototype.toHexDOM_sub=function(n,t,i,u,f){if(!(u>=f)){var e=r.tag("span",t);e.appendChild(r.text(i.hexDump(u,f)));n.appendChild(e)}};t.prototype.toHexDOM=function(t){var i=r.tag("span","hex"),f,e,u,o;if(t===n&&(t=i),this.head.hexNode=i,this.head.onmouseover=function(){this.hexNode.className="hexCurrent"},this.head.onmouseout=function(){this.hexNode.className="hex"},i.asn1=this,i.onmouseover=function(){var n=!t.selected;n&&(t.selected=this.asn1,this.className="hexCurrent");this.asn1.fakeHover(n)},i.onmouseout=function(){var n=t.selected==this.asn1;this.asn1.fakeOut(n);n&&(t.selected=null,this.className="hex")},this.toHexDOM_sub(i,"tag",this.stream,this.posStart(),this.posStart()+1),this.toHexDOM_sub(i,this.length>=0?"dlen":"ulen",this.stream,this.posStart()+1,this.posContent()),this.sub===null)i.appendChild(r.text(this.stream.hexDump(this.posContent(),this.posEnd())));else if(this.sub.length>0){for(f=this.sub[0],e=this.sub[this.sub.length-1],this.toHexDOM_sub(i,"intro",this.stream,this.posContent(),f.posStart()),u=0,o=this.sub.length;u<o;++u)i.appendChild(this.sub[u].toHexDOM(t));this.toHexDOM_sub(i,"outro",this.stream,e.posEnd(),this.posEnd())}return i};t.prototype.toHexString=function(){return this.stream.hexDump(this.posStart(),this.posEnd(),!0)};t.decodeLength=function(n){var t=n.get(),i=t&127,r;if(i==t)return i;if(i>3)throw"Length over 24 bits not supported at position "+(n.pos-1);if(i===0)return-1;for(t=0,r=0;r<i;++r)t=t<<8|n.get();return t};t.hasContent=function(n,r,u){var f,e,o;if(n&32)return!0;if(n<3||n>4||(f=new i(u),n==3&&f.get(),e=f.get(),e>>6&1))return!1;try{return o=t.decodeLength(f),f.pos-u.pos+o==r}catch(s){return!1}};t.decode=function(n){var f,o,s;n instanceof i||(n=new i(n,0));var h=new i(n),e=n.get(),r=t.decodeLength(n),c=n.pos-h.pos,u=null;if(t.hasContent(e,r,n))if(f=n.pos,e==3&&n.get(),u=[],r>=0){for(o=f+r;n.pos<o;)u[u.length]=t.decode(n);if(n.pos!=o)throw"Content size is not correct for container starting at offset "+f;}else try{for(;;){if(s=t.decode(n),s.tag===0)break;u[u.length]=s}r=f-n.pos}catch(l){throw"Exception while decoding undefined length content: "+l;}else n.pos+=r;return new t(h,c,r,e,u)};t.test=function(){for(var r=[{value:[39],expected:39},{value:[129,201],expected:201},{value:[131,254,220,186],expected:16702650}],n=0,f=r.length;n<f;++n){var e=new i(r[n].value,0),u=t.decodeLength(e);u!=r[n].expected&&document.write("In test["+n+"] expected "+r[n].expected+" got "+u+"\n")}};window.ASN1=t}();ASN1.prototype.getHexStringValue=function(){var n=this.toHexString(),t=this.header*2,i=this.length*2;return n.substr(t,i)};u.prototype.parseKey=function(n){var e,o,s,h,c,l,a,u;try{var i=0,r=0,v=/^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/.test(n)?Hex.decode(n):Base64.unarmor(n),t=ASN1.decode(v);if(t.sub.length===3&&(t=t.sub[2].sub[0]),t.sub.length===9)i=t.sub[1].getHexStringValue(),this.n=f(i,16),r=t.sub[2].getHexStringValue(),this.e=parseInt(r,16),e=t.sub[3].getHexStringValue(),this.d=f(e,16),o=t.sub[4].getHexStringValue(),this.p=f(o,16),s=t.sub[5].getHexStringValue(),this.q=f(s,16),h=t.sub[6].getHexStringValue(),this.dmp1=f(h,16),c=t.sub[7].getHexStringValue(),this.dmq1=f(c,16),l=t.sub[8].getHexStringValue(),this.coeff=f(l,16);else if(t.sub.length===2)a=t.sub[1],u=a.sub[0],i=u.sub[0].getHexStringValue(),this.n=f(i,16),r=u.sub[1].getHexStringValue(),this.e=parseInt(r,16);else return!1;return!0}catch(y){return!1}};u.prototype.getPrivateBaseKey=function(){var n={array:[new KJUR.asn1.DERInteger({int:0}),new KJUR.asn1.DERInteger({bigint:this.n}),new KJUR.asn1.DERInteger({int:this.e}),new KJUR.asn1.DERInteger({bigint:this.d}),new KJUR.asn1.DERInteger({bigint:this.p}),new KJUR.asn1.DERInteger({bigint:this.q}),new KJUR.asn1.DERInteger({bigint:this.dmp1}),new KJUR.asn1.DERInteger({bigint:this.dmq1}),new KJUR.asn1.DERInteger({bigint:this.coeff})]},t=new KJUR.asn1.DERSequence(n);return t.getEncodedHex()};u.prototype.getPrivateBaseKeyB64=function(){return vt(this.getPrivateBaseKey())};u.prototype.getPublicBaseKey=function(){var n={array:[new KJUR.asn1.DERObjectIdentifier({oid:"1.2.840.113549.1.1.1"}),new KJUR.asn1.DERNull]},u=new KJUR.asn1.DERSequence(n),t,i,r;return n={array:[new KJUR.asn1.DERInteger({bigint:this.n}),new KJUR.asn1.DERInteger({int:this.e})]},t=new KJUR.asn1.DERSequence(n),n={hex:"00"+t.getEncodedHex()},i=new KJUR.asn1.DERBitString(n),n={array:[u,i]},r=new KJUR.asn1.DERSequence(n),r.getEncodedHex()};u.prototype.getPublicBaseKeyB64=function(){return vt(this.getPublicBaseKey())};u.prototype.wordwrap=function(n,t){if(t=t||64,!n)return n;var i="(.{1,"+t+"})( +|$\n?)|(.{1,"+t+"})";return n.match(RegExp(i,"g")).join("\n")};u.prototype.getPrivateKey=function(){var n="-----BEGIN RSA PRIVATE KEY-----\n";return n+=this.wordwrap(this.getPrivateBaseKeyB64())+"\n",n+"-----END RSA PRIVATE KEY-----"};u.prototype.getPublicKey=function(){var n="-----BEGIN PUBLIC KEY-----\n";return n+=this.wordwrap(this.getPublicBaseKeyB64())+"\n",n+"-----END PUBLIC KEY-----"};u.prototype.hasPublicKeyProperty=function(n){return n=n||{},n.hasOwnProperty("n")&&n.hasOwnProperty("e")};u.prototype.hasPrivateKeyProperty=function(n){return n=n||{},n.hasOwnProperty("n")&&n.hasOwnProperty("e")&&n.hasOwnProperty("d")&&n.hasOwnProperty("p")&&n.hasOwnProperty("q")&&n.hasOwnProperty("dmp1")&&n.hasOwnProperty("dmq1")&&n.hasOwnProperty("coeff")};u.prototype.parsePropertiesFrom=function(n){this.n=n.n;this.e=n.e;n.hasOwnProperty("d")&&(this.d=n.d,this.p=n.p,this.q=n.q,this.dmp1=n.dmp1,this.dmq1=n.dmq1,this.coeff=n.coeff)};g=function(n){u.call(this);n&&(typeof n=="string"?this.parseKey(n):(this.hasPrivateKeyProperty(n)||this.hasPublicKeyProperty(n))&&this.parsePropertiesFrom(n))};g.prototype=new u;g.prototype.constructor=g;s=function(n){n=n||{};this.default_key_size=parseInt(n.default_key_size)||1024;this.default_public_exponent=n.default_public_exponent||"010001";this.log=n.log||!1;this.key=null};s.prototype.setKey=function(n){this.log&&this.key&&console.warn("A key was already set, overriding existing.");this.key=new g(n)};s.prototype.setPrivateKey=function(n){this.setKey(n)};s.prototype.setPublicKey=function(n){this.setKey(n)};s.prototype.decrypt=function(n){try{return this.getKey().decrypt(ii(n))}catch(t){return!1}};s.prototype.encrypt=function(n){try{return vt(this.getKey().encrypt(n))}catch(t){return!1}};s.prototype.getKey=function(n){if(!this.key){if(this.key=new g,n&&{}.toString.call(n)==="[object Function]"){this.key.generateAsync(this.default_key_size,this.default_public_exponent,n);return}this.key.generate(this.default_key_size,this.default_public_exponent)}return this.key};s.prototype.getPrivateKey=function(){return this.getKey().getPrivateKey()};s.prototype.getPrivateKeyB64=function(){return this.getKey().getPrivateBaseKeyB64()};s.prototype.getPublicKey=function(){return this.getKey().getPublicKey()};s.prototype.getPublicKeyB64=function(){return this.getKey().getPublicBaseKeyB64()};n.JSEncrypt=s}(JSEncryptExports);JSEncrypt=JSEncryptExports.JSEncrypt;PF=PF||{};PF.DataProxy=function(){var t="/User/DefaultRegion",i={Call:function(t){n(t)},SetListingStatus:function(n){r(n)},EditImage:function(n){u(n)},GetListing:function(n,t){f(n,t)},updateUserRegion:function(n){$.ajax({type:"POST",url:t,data:{region:n.region},success:n.success,error:n.error})},getCurrentUserRegion:function(n){var t;$.get("/User/CurrentDefaultRegion",t,n.success)}},r=function(t){var i=function(){PF.Modals.ProgressIndicator.Show();n({url:"/My/Space/Status",data:t.data,success:function(n){n.Success?PF.Modals.ProgressIndicator.HideModal(function(){t.success(n)}):t.fail&&PF.Modals.ProgressIndicator.HideModal(function(){t.fail(n)})}})};t.confirm?PF.confirm({description:t.confirm,confirm:i}):i()},u=function(t){n({url:"/My/Listings/SaveImage",data:t.data,success:function(n){n.Success&&t.success?t.success.call(n):n.Error&&PF.showError("There was an error saving changes to the image:<br>"+n.Error,!0)}})},f=function(t,i){n({url:"/Space/Edit/"+t,type:"GET",data:"",success:function(n){n.Success?i.call(n):PF.showError("There was an error getting listing data:<br>"+data.Error)}})},n=function(n){var t=n.queue||"noCacheQueue",i=n.type||"POST",r=JSON.stringify(n.data);$.manageAjax.add(t,{url:n.url,type:i,cache:!1,data:r,dataType:n.dataType||"json",contentType:n.contentType||"application/json; charset=utf-8",success:n.success,error:n.error||function(n,t,i){PF.showError("A general error was encountered with your last action. If you continue to see this error, contact support.");console.log({xhr:n,ajaxOptions:t,error:i});PF.HideModal()}})};return i}();Account=function(n){var t=this;t.cache=function(){};this.deleted=ko.observable(!1);this.id=ko.observable();this.address1=ko.observable();this.address2=ko.observable();this.baseCurrency=ko.observable();this.city=ko.observable();this.country=ko.observable();this.rentalNotificationEmail=ko.observable();this.alternateBillingEmail=ko.observable();this.organizationName=ko.observable();this.condensedName=ko.observable();this.phone=ko.observable();this.postalOrZipCode=ko.observable();this.stateOrProvince=ko.observable();this.timeZone=ko.observable();this.providerType=ko.observable();this.subscriptionFrequency=ko.observable();this.dateCreated=ko.observable();this.facebookPageId=ko.observable();this.yelpPageId=ko.observable();this.long=ko.observable();this.lat=ko.observable();this.imageUrl=ko.observable();this.externalWebsiteUrl=ko.observable();this.taxRate=ko.observable();this.siteProperties=ko.observableArray();this.users=ko.observableArray();this.settings=ko.observableArray();this.isProPayEnabled=ko.observable();this.autoUnpublishListings=ko.observable();this.isSinglePageCheckout=ko.observable();this.tier=ko.observable();this.moduleOptions=ko.observableArray();this.isTrxEnabled=ko.observableArray();this.trxLeadGuid=ko.observableArray();this.trxLeadActive=ko.observableArray();this.trxLeadState=ko.observableArray();this.trxStorageSafeGuid=ko.observableArray();this.trxStorageAccountAchGuid=ko.observableArray();this.trxStorageAccountCreditGuid=ko.observableArray();this.trxStorageShippingGuid=ko.observableArray();this.trxStorageCustomerGuid=ko.observableArray();this.trxClientId=ko.observableArray();this.trxSourceId=ko.observableArray();this.trxAlgorithmKey=ko.observableArray();this.trxAlgorithmIv=ko.observableArray();this.externalBillingKey=ko.observable();this.proPayMerchantProfileId=ko.observable();this.transactionRate=ko.observable();this.fixedTransactionFee=ko.observable();this.upcomingBookings=ko.observableArray(null);this.previousBookings=ko.observableArray(null);this.metrics=ko.observableArray(null);this.sitePropertiesAll=ko.computed(function(){if(t.siteProperties().length>0){var n="";return ko.utils.arrayForEach(t.siteProperties(),function(t){n+=t.condensedName()+" "}),n}return null});this.trialEndDate=ko.observable();this.nextBillingDate=ko.observable();this.providerTypeFullName=ko.computed(function(){return PF&&PF.ProviderTypeFullName?PF.ProviderTypeFullName(t.providerType()):null});t.medallion=ko.computed(function(){return t.metrics()&&t.metrics().MedallionStatus===1?"/Content/images/SmartFull/badges/25k_lifetime_revenue.png":""});t.getSetting=function(n){var i=null;return $.each(t.settings(),function(t,r){if(r.Key===n)return i=r,!1}),i};t.updateSetting=function(n,i){var r=t.getSetting(n);r?r.Value=i:t.settings.push({Key:n,Value:i})};t.addModuleOption=function(n){return(typeof t.moduleOptions()=="undefined"&&(t.moduleOptions=ko.observableArray()),t.moduleOptions().map(function(t){if(t.moduleOption.moduleId==n.moduleOption().moduleId())return t}).length>0)?!1:(t.moduleOptions.push(n),!0)};t.removeModuleOption=function(n){t.moduleOptions(t.moduleOptions.remove(function(t){return t.moduleOption().id()==n.id()}))};n&&this.update(n)};ko.utils.extend(Account.prototype,{update:function(n){n=n||{};this.id(n.id);this.address1(n.address1||"");this.address2(n.address2||"");this.baseCurrency(n.baseCurrency);this.city(n.city);this.country(n.country);this.rentalNotificationEmail(n.rentalNotificationEmail);this.alternateBillingEmail(n.alternateBillingEmail);this.organizationName(n.organizationName);this.condensedName(n.condensedName);this.phone(n.phone);this.postalOrZipCode(n.postalOrZipCode);this.stateOrProvince(n.stateOrProvince);this.timeZone(n.timeZone);this.taxRate(n.taxRate);this.providerType(n.providerType);this.subscriptionFrequency(n.subscriptionFrequency);this.dateCreated(n.dateCreated);this.facebookPageId(n.facebookPageId);this.yelpPageId(n.yelpPageId);this.long(n.long);this.lat(n.lat);this.imageUrl(n.imageUrl);this.externalWebsiteUrl(n.externalWebsiteUrl);this.users(n.users);this.isProPayEnabled(n.isProPayEnabled);this.autoUnpublishListings(n.autoUnpublishListings);this.isSinglePageCheckout(n.isSinglePageCheckout);this.isTrxEnabled(n.isTrxEnabled);this.trxLeadGuid(n.trxLeadGuid);this.trxLeadActive(n.trxLeadActive);this.trxLeadState(n.trxLeadState);this.trxStorageSafeGuid(n.trxStorageSafeGuid);this.trxStorageAccountAchGuid(n.trxStorageAccountAchGuid);this.trxStorageAccountCreditGuid(n.trxStorageAccountCreditGuid);this.trxStorageShippingGuid(n.trxStorageShippingGuid);this.trxStorageCustomerGuid(n.trxStorageCustomerGuid);this.trxClientId(n.trxClientId);this.trxSourceId(n.trxSourceId);this.trxAlgorithmKey(n.trxAlgorithmKey);this.trxAlgorithmIv(n.trxAlgorithmIv);this.externalBillingKey(n.externalBillingKey);this.proPayMerchantProfileId(n.proPayMerchantProfileId);this.transactionRate(n.transactionRate);this.fixedTransactionFee(n.fixedTransactionFee);n.tier&&this.tier(n.tier);n.moduleOptions&&this.moduleOptions(n.moduleOptions);n.siteProperties&&this.siteProperties(n.siteProperties);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,address1:n.AddressLine1,address2:n.AddressLine2,baseCurrency:n.BaseCurrency,city:n.City,country:n.Country,rentalNotificationEmail:n.RentalNotificationEmail,alternateBillingEmail:n.AlternateBillingEmail,organizationName:n.OrganizationName,condensedName:n.CondensedName,phone:n.PhoneNumber,postalOrZipCode:n.PostalOrZipCode,stateOrProvince:n.StateOrProvince,timeZone:n.TimeZone,taxRate:n.TaxRate,providerType:n.ProviderType,subscriptionFrequency:n.SubscriptionFrequency,dateCreated:n.DateCreated,facebookPageId:n.FacebookPageId,yelpPageId:n.YelpPageId,long:n.Long,lat:n.Lat,imageUrl:n.ImageURL,isProPayEnabled:n.IsProPayEnabled,externalWebsiteUrl:n.ExternalWebSiteURL,autoUnpublishListings:n.AutoUnpublishListings,isSinglePageCheckout:n.IsSinglePageCheckout,isTrxEnabled:n.IsTrxEnabled,trxLeadGuid:n.TrxLeadGuid,trxLeadActive:n.TrxLeadActive,trxLeadState:n.TrxLeadState,trxStorageSafeGuid:n.TrxStorageSafeGuid,trxStorageAccountAchGuid:n.TrxStorageAccountAchGuid,trxStorageAccountCreditGuid:n.TrxStorageAccountCreditGuid,trxStorageShippingGuid:n.TrxStorageShippingGuid,trxStorageCustomerGuid:n.TrxStorageCustomerGuid,trxClientId:n.TrxClientId,trxSourceId:n.TrxSourceId,trxAlgorithmKey:n.TrxAlgorithmKey,trxAlgorithmIv:n.TrxAlgorithmIv,externalBillingKey:n.ExternalBillingKey,proPayMerchantProfileId:n.ProPayMerchantProfileId,transactionRate:n.TransactionRate,fixedTransactionFee:n.FixedTransactionFee};return n.SiteProperties&&(t.siteProperties=n.SiteProperties.map(function(n){return(new SiteProperty).fromServerModel(n)})),n.Users&&(t.users=n.Users.map(function(n){return(new Role).fromServerModel(n)})),n.Tier&&(t.tier=(new Tier).fromServerModel(n.Tier)),n.ModuleOptions&&(t.moduleOptions=n.ModuleOptions.map(function(n){return(new AccountModuleOption).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),AddressLine1:this.address1(),AddressLine2:this.address2(),BaseCurrency:this.baseCurrency(),City:this.city(),Country:this.country(),RentalNotificationEmail:this.rentalNotificationEmail(),AlternateBillingEmail:this.alternateBillingEmail(),OrganizationName:this.organizationName(),CondensedName:this.condensedName(),PhoneNumber:this.phone(),PostalOrZipCode:this.postalOrZipCode(),StateOrProvince:this.stateOrProvince(),TimeZone:this.timeZone(),TaxRate:this.taxRate()==0?null:this.taxRate(),ProviderType:this.providerType(),DateCreated:this.dateCreated(),FacebookPageId:this.facebookPageId(),YelpPageId:this.yelpPageId(),Long:this.long(),Lat:this.lat(),ImageURL:this.imageUrl(),ExternalWebSiteURL:this.externalWebsiteUrl(),IsProPayEnabled:this.isProPayEnabled(),AutoUnpublishListings:this.autoUnpublishListings(),IsSinglePageCheckout:this.isSinglePageCheckout(),IsTrxEnabled:this.isTrxEnabled(),TrxLeadGuid:this.trxLeadGuid(),TrxLeadActive:this.trxLeadActive(),TrxLeadState:this.trxLeadState(),TrxStorageSafeGuid:this.trxStorageSafeGuid(),TrxStorageAccountAchGuid:this.trxStorageAccountAchGuid(),TrxStorageAccountCreditGuid:this.trxStorageAccountCreditGuid(),TrxStorageShippingGuid:this.trxStorageShippingGuid(),TrxStorageCustomerGuid:this.trxStorageCustomerGuid(),TrxClientId:this.trxClientId(),TrxSourceId:this.trxSourceId(),TrxAlgorithmKey:this.trxAlgorithmKey(),TrxAlgorithmIv:this.trxAlgorithmIv(),ExternalBillingKey:this.externalBillingKey(),ProPayMerchantProfileId:this.proPayMerchantProfileId(),TransactionRate:this.transactionRate(),FixedTransactionFee:this.fixedTransactionFee()};return this.siteProperties()&&(n.SiteProperties=this.siteProperties().map(function(n){return n.toServerModel()})),this.users()&&(n.Users=this.users().map(function(n){return n.toServerModel()})),this.tier()!=null&&(n.Tier=this.tier().toServerModel()),this.moduleOptions()&&(n.ModuleOptions=this.moduleOptions().map(function(n){return n.toServerModel()})),n}});AccountModuleOption=function(n){var t=this;this.dateCreated=ko.observable();this.dateModified=ko.observable();this.accountId=ko.observable();this.moduleOption=ko.observable();this.expireDate=ko.observable();this.id=ko.observable();n&&this.update(n)};ko.utils.extend(AccountModuleOption.prototype,{update:function(n){n=n||{};this.dateCreated(n.dateCreated);this.dateModified(n.dateModified);this.accountId(n.accountId);this.expireDate(n.expireDate);this.id(n.id);n.moduleOption&&this.moduleOption(n.moduleOption)},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={accountId:n.AccountId,dateCreated:n.DateCreated,dateModified:n.DateModified,expireDate:n.ExpireDate,id:n.Id};return n.ModuleOption&&(t.moduleOption=(new Module).fromServerModel(n.ModuleOption)),this.update(t),this},toServerModel:function(){var n={AccountId:this.accountId(),ExpireDate:this.expireDate(),Id:this.id()};return this.moduleOption()!=null&&(n.ModuleOption=this.moduleOption().toServerModel()),n}});AccountPayout=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.dateCreated=ko.observable();this.payoutDate=ko.observable();this.totalAmount=ko.observable();this.transactionRate=ko.observable();this.payoutAmount=ko.observable();this.accountId=ko.observable();this.fixedTransactionFee=ko.observable();this.totalFeeAmount=ko.observable();this.billings=ko.observableArray();this.subscriptionBillings=ko.observableArray();t.refundBillings=ko.pureComputed(function(){return $.grep(t.billings(),function(n){return n.PaymentType==PF.PaymentType.CreditCard_Refund||n.PaymentType==PF.PaymentType.CreditCard_Refund_SecurityDeposit})},t);t.purchaseBillings=ko.pureComputed(function(){return $.grep(t.billings(),function(n){return n.PaymentType==PF.PaymentType.CreditCard_Funding||n.PaymentType==PF.PaymentType.Bitcoin_Funding})},t);t.chargeBackFeeBillings=ko.pureComputed(function(){return $.grep(t.billings(),function(n){return n.PaymentType==PF.PaymentType.CreditCard_ChargeBackFee})},t);t.chargeBackBillings=ko.pureComputed(function(){return $.grep(t.billings(),function(n){return n.PaymentType==PF.PaymentType.CreditCard_ChargeBack})},t);t.totalRefunds=ko.pureComputed(function(){return t.refundBillings().reduce(function(n,t){return n+t.Amount},0)},t);t.totalChargeBacks=ko.pureComputed(function(){return t.chargeBackBillings().reduce(function(n,t){return n+t.Amount},0)},t);t.totalChargeBackFees=ko.pureComputed(function(){return t.chargeBackFeeBillings().reduce(function(n,t){return n+t.Amount},0)},t);n&&this.update(n)};ko.utils.extend(AccountPayout.prototype,{update:function(n){n=n||{};this.id(n.id);this.dateCreated(n.dateCreated);this.payoutDate(n.payoutDate);this.totalAmount(n.totalAmount);this.transactionRate(n.transactionRate);this.payoutAmount(n.payoutAmount);this.accountId(n.accountId);this.fixedTransactionFee(n.fixedTransactionFee);this.totalFeeAmount(n.totalFeeAmount);this.billings(n.billings||[]);this.subscriptionBillings(n.subscriptionBillings||[]);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,dateCreated:n.DateCreated,payoutDate:new Date(n.PayoutDate.slice(0,-1)).toDateString(),totalAmount:n.TotalAmount,transactionRate:n.TransactionRate,payoutAmount:n.PayoutAmount,totalFeeAmount:n.TotalFeeAmount,fixedTransactionFee:n.FixedTransactionFee};return n.Billings&&(t.billings=n.Billings.map(function(n){return n})),n.SubscriptionBillings&&(t.subscriptionBillings=n.SubscriptionBillings.map(function(n){return n})),this.update(t),this},toServerModel:function(){return null}});AccountUnderwritingInfo=function(){var n=this;this.id=ko.observable();this.account=ko.observable();this.employerIdentificationNumber=ko.observable();this.doingBusinessAs=ko.observable();this.creditCardDescriptor=ko.observable();this.ownerFirstName1=ko.observable();this.ownerLastName1=ko.observable();this.ownerFirstName2=ko.observable();this.ownerLastName2=ko.observable();this.ownerDateOfBirth1=ko.observable();this.ownerDateOfBirth2=ko.observable();this.ownerSocial1=ko.observable();this.ownerSocial2=ko.observable();this.typeOfBusiness=ko.observable();this.typeOfBusinessOther=ko.observable();this.classification=ko.observable();this.onlineRevenue=ko.observable();this.offlineRevenue=ko.observable();this.currentCCProcessor=ko.observable();this.chargebackPercentage=ko.observable();this.chargebackPercentage.subscribe(function(){});this.estOnlineVolume=ko.observable();this.routingNumber=ko.observable();this.accountNumber=ko.observable();this.bankName=ko.observable();this.month=ko.observable();this.year=ko.observable();this.yearBusinessStarted=ko.computed({read:function(){return n.month()===-1||n.year()===-1?"":n.month()+""+n.year()},write:function(t){t&&t.length===6&&(n.month(t.substring(0,2)),n.year(t.substring(2)))}});this.bankAccountType=ko.observable();this.bankAccountOwnership=ko.observable();this.bankAccountOwnerName=ko.observable();this.agreedToProPayTerms=ko.observable();this.legalName=ko.observable();this.agreedToTrxTerms=ko.observable();this.merchantCategoryCode=ko.observable();this.ownerRole1=ko.observable();this.ownerRole2=ko.observable();this.ownershipPercent1=ko.observable();this.ownershipPercent2=ko.observable();this.businessHours=ko.observable();this.returnPolicy=ko.observable();this.settlementPolicy=ko.observable();this.shareSensitiveData=ko.observable();this.monthlyVolume=ko.observable();this.monthlyCount=ko.observable();this.monthlyVolumeRefunds=ko.observable();this.monthlyCountRefunds=ko.observable();this.dailyVolume=ko.observable();this.averageTicket=ko.observable();this.maximumTicket=ko.observable();this.driversLicenseNumber1=ko.observable();this.driversLicenseNumber2=ko.observable();this.driversLicenseRegion1=ko.observable();this.driversLicenseRegion2=ko.observable();this.driversLicenseExpiration1=ko.observable();this.driversLicenseExpiration2=ko.observable();this.showSecondOwnerFields=ko.observable(!1)};ko.utils.extend(AccountUnderwritingInfo.prototype,{update:function(n){n=n||{};this.id(n.id);this.employerIdentificationNumber(n.employerIdentificationNumber);this.doingBusinessAs(n.doingBusinessAs);this.creditCardDescriptor(n.creditCardDescriptor);this.ownerFirstName1(n.ownerFirstName1);this.ownerLastName1(n.ownerLastName1);this.ownerFirstName2(n.ownerFirstName2);this.ownerLastName2(n.ownerLastName2);this.ownerDateOfBirth1(n.ownerDateOfBirth1);this.ownerDateOfBirth2(n.ownerDateOfBirth2);this.ownerSocial1(n.ownerSocial1);this.ownerSocial2(n.ownerSocial2);this.typeOfBusiness(n.typeOfBusiness);this.typeOfBusinessOther(n.typeOfBusinessOther);this.yearBusinessStarted(n.yearBusinessStarted);this.classification(n.classification);this.onlineRevenue(n.onlineRevenue);this.offlineRevenue(n.offlineRevenue);this.currentCCProcessor(n.currentCCProcessor);this.chargebackPercentage(n.chargebackPercentage);this.estOnlineVolume(n.estOnlineVolume);this.routingNumber(n.routingNumber);this.accountNumber(n.accountNumber);this.bankName(n.bankName);this.bankAccountType(n.bankAccountType);this.bankAccountOwnership(n.bankAccountOwnership);this.bankAccountOwnerName(n.bankAccountOwnerName);this.agreedToProPayTerms(n.agreedToProPayTerms);this.legalName(n.legalName);this.agreedToTrxTerms(n.agreedToTrxTerms);this.merchantCategoryCode(n.merchantCategoryCode);this.ownerRole1(n.ownerRole1);this.ownerRole2(n.ownerRole2);this.ownershipPercent1(n.ownershipPercent1);this.ownershipPercent2(n.ownershipPercent2);this.businessHours(n.businessHours);this.returnPolicy(n.returnPolicy);this.settlementPolicy(n.settlementPolicy);this.shareSensitiveData(n.shareSensitiveData);this.monthlyVolume(n.monthlyVolume);this.monthlyCount(n.monthlyCount);this.monthlyVolumeRefunds(n.monthlyVolumeRefunds);this.monthlyCountRefunds(n.monthlyCountRefunds);this.dailyVolume(n.dailyVolume);this.averageTicket(n.averageTicket);this.maximumTicket(n.maximumTicket);this.driversLicenseNumber1(n.driversLicenseNumber1);this.driversLicenseNumber2(n.driversLicenseNumber2);this.driversLicenseRegion1(n.driversLicenseRegion1);this.driversLicenseRegion2(n.driversLicenseRegion2);this.driversLicenseExpiration1(n.driversLicenseExpiration1);this.driversLicenseExpiration2(n.driversLicenseExpiration2);n.account&&this.account(n.account)},fromServerModel:function(n){var t={id:n.Id,employerIdentificationNumber:n.EmployerIdentificationNumber,doingBusinessAs:n.DoingBusinessAs,creditCardDescriptor:n.CreditCardDescriptor,ownerFirstName1:n.OwnerFirstName1,ownerLastName1:n.OwnerLastName1,ownerFirstName2:n.OwnerFirstName2,ownerLastName2:n.OwnerLastName2,ownerDateOfBirth1:n.OwnerDateOfBirth1,ownerDateOfBirth2:n.OwnerDateOfBirth2,ownerSocial1:n.OwnerSocial1,ownerSocial2:n.OwnerSocial2,typeOfBusiness:n.TypeOfBusiness,typeOfBusinessOther:n.TypeOfBusinessOther,yearBusinessStarted:n.YearBusinessStarted,classification:n.Classification,onlineRevenue:n.OnlineRevenue,offlineRevenue:n.OfflineRevenue,currentCCProcessor:n.CurrentCCProcessor,chargebackPercentage:n.ChargebackPercentage,estOnlineVolume:n.EstOnlineVolume,routingNumber:n.RoutingNumber,accountNumber:n.AccountNumber,bankName:n.BankName,bankAccountType:n.BankAccountType,bankAccountOwnership:n.BankAccountOwnership,bankAccountOwnerName:n.BankAccountOwnerName,agreedToProPayTerms:n.AgreedToProPayTerms,legalName:n.LegalName,agreedToTrxTerms:n.AgreedToTrxTerms,merchantCategoryCode:n.MerchantCategoryCode,ownerRole1:n.OwnerRole1,ownerRole2:n.OwnerRole2,ownershipPercent1:n.OwnershipPercent1,ownershipPercent2:n.OwnershipPercent2,businessHours:n.BusinessHours,returnPolicy:n.ReturnPolicy,settlementPolicy:n.SettlementPolicy,shareSensitiveData:n.ShareSensitiveData,monthlyVolume:n.MonthlyVolume,monthlyCount:n.MonthlyCount,monthlyVolumeRefunds:n.MonthlyVolumeRefunds,monthlyCountRefunds:n.MonthlyCountRefunds,dailyVolume:n.DailyVolume,averageTicket:n.AverageTicket,maximumTicket:n.MaximumTicket,driversLicenseNumber1:n.DriversLicenseNumber1,driversLicenseNumber2:n.DriversLicenseNumber2,driversLicenseRegion1:n.DriversLicenseRegion1,driversLicenseRegion2:n.DriversLicenseRegion2,driversLicenseExpiration1:n.DriversLicenseExpiration1,driversLicenseExpiration2:n.DriversLicenseExpiration2};return n.Account&&(t.account=(new Account).fromServerModel(n.Account)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),EmployerIdentificationNumber:this.employerIdentificationNumber(),DoingBusinessAs:this.doingBusinessAs(),CreditCardDescriptor:this.creditCardDescriptor(),OwnerFirstName1:this.ownerFirstName1(),OwnerLastName1:this.ownerLastName1(),OwnerFirstName2:this.ownerFirstName2(),OwnerLastName2:this.ownerLastName2(),OwnerDateOfBirth1:this.ownerDateOfBirth1(),OwnerDateOfBirth2:this.ownerDateOfBirth2(),OwnerSocial1:this.ownerSocial1(),OwnerSocial2:this.ownerSocial2(),TypeOfBusiness:this.typeOfBusiness(),TypeOfBusinessOther:this.typeOfBusinessOther(),YearBusinessStarted:this.yearBusinessStarted(),Classification:this.classification(),OnlineRevenue:this.onlineRevenue(),OfflineRevenue:this.offlineRevenue(),CurrentCCProcessor:this.currentCCProcessor(),ChargebackPercentage:typeof this.chargebackPercentage()=="string"?this.chargebackPercentage().replace("%",""):this.chargebackPercentage(),EstOnlineVolume:this.estOnlineVolume(),RoutingNumber:this.routingNumber(),AccountNumber:this.accountNumber(),BankAccountType:this.bankAccountType(),BankAccountOwnership:this.bankAccountOwnership(),BankAccountOwnerName:this.bankAccountOwnerName(),BankName:this.bankName(),AgreedToProPayTerms:this.agreedToProPayTerms(),LegalName:this.legalName(),AgreedToTrxTerms:this.agreedToTrxTerms(),MerchantCategoryCode:this.merchantCategoryCode(),OwnerRole1:this.ownerRole1(),OwnerRole2:this.ownerRole2(),OwnershipPercent1:this.ownershipPercent1(),OwnershipPercent2:this.ownershipPercent2(),BusinessHours:this.businessHours(),ReturnPolicy:this.returnPolicy(),SettlementPolicy:this.settlementPolicy(),ShareSensitiveData:this.shareSensitiveData(),MonthlyVolume:this.monthlyVolume(),MonthlyCount:this.monthlyCount(),MonthlyVolumeRefunds:this.monthlyVolumeRefunds(),MonthlyCountRefunds:this.monthlyCountRefunds(),DailyVolume:this.dailyVolume(),AverageTicket:this.averageTicket(),MaximumTicket:this.maximumTicket(),DriversLicenseNumber1:this.driversLicenseNumber1(),DriversLicenseNumber2:this.driversLicenseNumber2(),DriversLicenseRegion1:this.driversLicenseRegion1(),DriversLicenseRegion2:this.driversLicenseRegion2(),DriversLicenseExpiration1:this.driversLicenseExpiration1(),DriversLicenseExpiration2:this.driversLicenseExpiration2()};return this.account()&&(n.Account=this.account().toServerModel()),n}});AdditionalInfo=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.label=ko.observable();t.helpText=ko.observable();t.inputType=ko.observable();t.required=ko.observable(!0);t.maxLength=ko.observable();t.category=ko.observable();t.selected=ko.observable();t.options=ko.observableArray();t.order=ko.observable();t.labelComputed=ko.computed(function(){return t.label()+(t.required()==null||t.required()==!0?"":" (optional)")});t.requiredComputed=ko.computed(function(){return t.required()==!1?"No":"Yes"});t.categoryComputed=ko.computed(function(){return t.category()?t.category():"(No category)"});t.helpComputed=ko.computed(function(){return t.helpText()?t.helpText():"This info is required"});n&&this.update(n)};ko.utils.extend(AdditionalInfo.prototype,{update:function(n){n=n||{};this.id(n.id);this.label(n.label);this.helpText(n.helpText);this.inputType(n.inputType);this.required(n.required);this.maxLength(n.maxLength);this.category(n.category);this.selected(n.selected);this.options(n.options);this.order(n.order);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){info=null;select=!1;typeof n.Selected!="undefined"?(info=n.Info,select=n.Selected):info=n;var t={id:info.Id,label:info.Label,helpText:info.HelpText,inputType:info.InputType,required:info.Required,maxLength:info.MaxLength,category:info.CategoryName,order:info.Order,selected:select};return info.Options&&info.Options.length>0&&(t.options=info.Options.map(function(n){return(new AdditionalInfoOption).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Label:this.label(),HelpText:this.helpText(),InputType:this.inputType(),Required:this.required(),MaxLength:this.maxLength(),CategoryName:this.category(),Order:this.order()};return this.options()&&this.options().length>0&&(n.Options=this.options().map(function(n){return n.toServerModel()})),n}});AdditionalInfoOption=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.order=ko.observable();this.value=ko.observable();n&&this.update(n)};ko.utils.extend(AdditionalInfoOption.prototype,{update:function(n){n=n||{};this.id(n.id);this.order(n.order);this.value(n.value);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,order:n.Order,value:n.Value};return this.update(t),this},toServerModel:function(){return{Id:this.id(),Order:this.order(),Value:this.value()}}});AdditionalInfoResponse=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.additionalInfoId=ko.observable();this.userResponse=ko.observable();this.additionalInfo=ko.observable();n&&this.update(n)};ko.utils.extend(AdditionalInfoResponse.prototype,{update:function(n){n=n||{};this.id(n.id);this.additionalInfoId(n.additionalInfoId);this.userResponse(n.userResponse);this.additionalInfo(n.additionalInfo);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,additionalInfoId:n.AdditionalInfoId,userResponse:n.UserResponse};return n.AdditionalInfo&&(t.additionalInfo=(new AdditionalInfo).fromServerModel(n.AdditionalInfo)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),AdditionalInfoId:this.additionalInfoId(),UserResponse:this.userResponse()};return this.additionalInfo()&&(n.AdditionalInfo=this.additionalInfo().toServerModel()),n}});AdditionalInfoBooking=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.additionalInfo=ko.observable();t.userResponse=ko.observable();t.label=ko.computed({read:function(){return t.additionalInfo()?t.additionalInfo().label():t.additionalInfo()},write:function(n){t.additionalInfo()&&t.additionalInfo().label(n)},owner:t});t.userResponseComputed=ko.computed(function(){return!t.userResponse()||t.userResponse()==""?"(Intentionally left blank)":t.userResponse()});t.helpText=ko.computed({read:function(){return t.additionalInfo()?t.additionalInfo().helpText():t.additionalInfo()},write:function(n){t.additionalInfo()&&t.additionalInfo().helpText(n)},owner:t});n&&this.update(n)};ko.utils.extend(AdditionalInfoBooking.prototype,{update:function(n){n=n||{};this.id(n.id);this.additionalInfo(n.additionalInfo);this.userResponse(n.userResponse);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,additionalInfo:(new AdditionalInfo).fromServerModel(n.AdditionalInfo),userResponse:n.UserResponse};return this.update(t),this},toServerModel:function(){return{Id:this.id(),UserResponse:this.userResponse(),AdditionalInfo:this.additionalInfo().toServerModel()}}});AdditionalInfoGoodPurchase=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.additionalInfo=ko.observable();t.userResponse=ko.observable();t.label=ko.computed({read:function(){return t.additionalInfo()?t.additionalInfo().label():t.additionalInfo()},write:function(n){t.additionalInfo()&&t.additionalInfo().label(n)},owner:t});t.userResponseComputed=ko.computed(function(){return!t.userResponse()||t.userResponse()==""?"(Intentionally left blank)":t.userResponse()});t.helpText=ko.computed({read:function(){return t.additionalInfo()?t.additionalInfo().helpText():t.additionalInfo()},write:function(n){t.additionalInfo()&&t.additionalInfo().helpText(n)},owner:t});n&&this.update(n)};ko.utils.extend(AdditionalInfoGoodPurchase.prototype,{update:function(n){n=n||{};this.id(n.id);this.additionalInfo(n.additionalInfo);this.userResponse(n.userResponse);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t;return t=n.AdditionalInfo!==null?{id:n.Id,additionalInfo:(new AdditionalInfo).fromServerModel(n.AdditionalInfo),userResponse:n.UserResponse}:{id:n.Id,userResponse:n.UserResponse},this.update(t),this},toServerModel:function(){return{Id:this.id(),UserResponse:this.userResponse(),AdditionalInfo:this.additionalInfo().toServerModel()}}});AdditionalInfoGoodVariant=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.dateCreated=ko.observable();t.goodVariant_Id=ko.observable();t.order=ko.observable();t.additionalInfo_Id=ko.observable();t.additionalInfo=ko.observable();n&&this.update(n)};ko.utils.extend(AdditionalInfoGoodVariant.prototype,{update:function(n){n=n||{};this.id(n.id);this.dateCreated(n.dateCreated);this.goodVariant_Id(n.goodVariant_Id);this.order(n.order);this.additionalInfo_Id(n.additionalInfo_Id);this.additionalInfo(n.additionalInfo);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,dateCreated:n.DateCreated,goodVariant_Id:n.GoodVariant_Id,order:n.Order,additionalInfo_Id:n.AdditionalInfo_Id};return n.AdditionalInfo&&(t.additionalInfo=(new AdditionalInfo).fromServerModel(n.AdditionalInfo)),this.update(t),this},toServerModel:function(){return{Id:this.id(),DateCreated:this.dateCreated(),GoodVariant_Id:this.goodVariant_Id(),Order:this.order(),AdditionalInfo_Id:this.additionalInfo_Id()}}});AddOn=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.label=ko.observable();t.helpText=ko.observable();t.category=ko.observable();t.description=ko.observable();t.account_id=ko.observable();t.dateCreated=ko.observable();t.defaultImage=ko.observable();t.images=ko.observableArray(null);n&&this.update(n)};ko.utils.extend(AddOn.prototype,{update:function(n){n=n||{};this.id(n.id);this.label(n.label);this.helpText(n.helpText);this.category(n.category);this.description(n.description);this.account_id(n.account_id);this.dateCreated(n.dateCreated);this.defaultImage(n.defaultImage);this.images(n.images);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,label:n.Label,helpText:n.HelpText,category:n.CategoryName,description:n.Description,account_id:n.Account_Id,dateCreated:n.DateCreated};return n.DefaultImage&&(t.defaultImage=(new AddOnImage).fromServerModel(n.DefaultImage)),n.AddOnImages&&(t.images=n.AddOnImages.map(function(n){return(new AddOnImage).fromServerModel(n)})),this.update(t),this},toServerModel:function(){return{Id:this.id(),Label:this.label(),HelpText:this.helpText(),CategoryName:this.category(),Description:this.description(),Account_Id:this.account_id(),DateCreated:this.dateCreated()}}});AddOnBooking=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.addOnSpace=ko.observable();t.rate=ko.observable();t.qtyPurchased=ko.observable();n&&this.update(n)};ko.utils.extend(AddOnBooking.prototype,{update:function(n){n=n||{};this.id(n.id);this.addOnSpace(n.addOnSpace);this.rate(n.rate);this.qtyPurchased(n.qtyPurchased);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,addOnSpace:(new AddOnSpace).fromServerModel(n.AddOnSpace),rate:n.Rate,qtyPurchased:n.QtyPurchased};return this.update(t),this},toServerModel:function(){return{Id:this.id(),AddOnSpace:this.addOnSpace().toServerModel(),Rate:this.rate(),QtyPurchased:this.qtyPurchased()}}});AddOnImage=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.fileUrl=ko.observable();t.tooltip=ko.observable();t.isDeleted=ko.observable();t.size=ko.observable("full");t.isDefault=ko.observable();t.addOn=ko.observable();t.thumbnails=ko.observableArray();t.thumbnail=function(n){return ko.computed({read:function(){return ko.utils.arrayFirst(t.thumbnails(),function(t){return t.size()===n})}},this)};n&&this.update(n)};ko.utils.extend(AddOnImage.prototype,{update:function(n){n=n||{};this.id(n.id);this.fileUrl(n.fileUrl);this.tooltip(n.tooltip);this.isDeleted(n.isDeleted);this.size(n.size);this.isDefault(n.isDefault);this.addOn(n.addOn);this.thumbnails(n.thumbnails);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t=null;if(n)try{t={id:n.Id,fileUrl:n.FileURL,tooltip:n.Tooltip,isDeleted:n.IsDeleted,size:n.ThumbnailSetting||"full",isDefault:n.IsDefaultImage};n.AddOn&&(t.addOn=(new AddOn).fromServerModel(n.AddOn));n.Thumbnails&&(t.thumbnails=n.Thumbnails.map(function(n){return(new AddOnImage).fromServerModel(n)}))}catch(i){}return this.update(t),this},toServerModel:function(n){var t={Id:this.id(),FileURL:this.fileUrl(),Tooltip:this.tooltip(),IsDeleted:this.isDeleted(),ThumbnailSetting:this.size(),IsDefaultImage:this.isDefault()};return this.addOn()&&(t.AddOn=this.addOn().toServerModel()),n&&(t.Thumbnails=this.thumbnails().map(function(n){return n.toServerModel()})),t}});AddOnSpace=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.addOn=ko.observable(null);t.rate=ko.observable();t.space_id=ko.observable();t.editable=ko.observable(!1);t.dateCreated=ko.observable();t.order=ko.observable();t.rateComputed=ko.computed(function(){return t.rate()==null?"0.00":t.rate()});t.label=ko.computed({read:function(){return t.addOn()?$("<div />").html(t.addOn().label()).text():t.addOn()},write:function(n){t.addOn()&&t.addOn().label(n)},owner:t});t.helpText=ko.computed({read:function(){return t.addOn()?t.addOn().helpText():t.addOn()},write:function(n){t.addOn()&&t.addOn().helpText(n)},owner:t});t.description=ko.computed({read:function(){return t.addOn()?$("<div />").html(t.addOn().description()).text():t.addOn()},write:function(n){t.addOn()&&t.addOn().description(n)},owner:t});t.onCurrentSpace=ko.computed(function(){return t.space_id()==null||typeof t.space_id()=="undefined"?!1:!0});n&&this.update(n)};ko.utils.extend(AddOnSpace.prototype,{update:function(n){n=n||{};this.id(n.id);this.addOn(n.addOn);this.rate(n.rate);this.space_id(n.space_id);this.order(n.order);this.dateCreated(n.dateCreated);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){if(n!==null){var t={id:n.Id,addOn:(new AddOn).fromServerModel(n.AddOn),rate:n.Rate,space_id:n.Space_Id,dateCreated:n.DateCreated,order:n.Order};this.update(t)}return this},toServerModel:function(){if(!this.addOn())return null;return{Id:this.id(),AddOn:this.addOn().toServerModel(),Rate:this.rate(),Space_Id:this.space_id(),DateCreated:this.dateCreated(),Order:this.order()}}});Alert=function(n){var t=this;t.fieldMoniker=ko.observable("XXPFXX");t.listingPickerMonicker=ko.observable("XXPFLISTXX");t.id=ko.observable();t.account_id=ko.observable();t.account=ko.observable();t.dateCreated=ko.observable();t.dateActivated=ko.observable();t.isActive=ko.observable();t.isDeleted=ko.observable();t.isHidden=ko.observable();t.displayName=ko.observable();t.lastRunDateTime=ko.observable();t.nextRunDateTime=ko.observable();t.priority=ko.observable();t.alertType=ko.observable();t.frequency=ko.observable();t.startHour=ko.observable();t.variables=ko.observable();t.previousRunResult=ko.observable();t.dayOfWeekValue=ko.observable();t.monthInterval=ko.observable();t.isRunning=ko.observable(!1);t.runButtonImgSrc=ko.computed(function(){return"/Content/images/"+(t.isRunning()?"loading.gif":"SmartFull/run.png")});t.runButtonAltTxt=ko.computed(function(){return t.isRunning()?"Running Alert...":"Run Alert"});t.prioritySelections=ko.observableArray([{name:"High",value:5},{name:"Medium",value:3},{name:"Low",value:0}]);t.priorityComputedText=ko.computed({read:function(){var n=t.prioritySelections().map(function(n){return n.value});return t.priority()||t.priority(0),t.prioritySelections()[n.indexOf(t.priority())].name}});t.description=ko.observable();t.firstDescription=ko.computed({read:function(){if(t.description()){var n=t.description().split(t.fieldMoniker());if(n.length>0)return n[0].replace(t.listingPickerMonicker(),"")}return""}});t.secondDescription=ko.computed({read:function(){if(t.description()){var n=t.description().split(t.fieldMoniker());if(n.length>1)return n[1].replace(t.listingPickerMonicker(),"")}return""}});t.canPickListings=ko.computed({read:function(){return t.description()?t.description().indexOf(t.listingPickerMonicker())>-1:!1}});t.isActiveText=ko.computed({read:function(){return t.isActive()!==undefined&&t.isActive()?"Yes":"No"}});t.nextRunDateTimePretty=ko.computed({read:function(){return t.nextRunDateTime()==null?"Never":new Date(t.nextRunDateTime())<new Date?"Soon":t.nextRunDateTime()}});n&&this.update(n)};ko.utils.extend(Alert.prototype,{update:function(n){n=n||{};this.id(n.id);this.account_id(n.account_id);this.account(n.account);this.dateCreated(n.dateCreated);this.dateActivated(n.dateActivated);this.isActive(n.isActive);this.isDeleted(n.isDeleted);this.isHidden(n.isHidden);this.displayName(n.displayName);this.lastRunDateTime(n.lastRunDateTime);this.nextRunDateTime(n.nextRunDateTime);this.priority(n.priority);this.alertType(n.alertType);this.frequency(n.frequency);this.dayOfWeekValue(n.dayOfWeekValue);this.startHour(n.startHour);this.variables(n.variables);this.previousRunResult(n.previousRunResult);this.monthInterval(n.monthInterval);this.description(n.description)},fromServerModel:function(n){var t={id:n.Id,account_id:n.Account_Id,dateCreated:n.DateCreated,dateActivated:n.DateActivated,isActive:n.IsActive,isDeleted:n.IsDeleted,isHidden:n.IsHidden,displayName:n.DisplayName,lastRunDateTime:n.LastRunDateTime,nextRunDateTime:n.NextRunDateTime,priority:n.Priority,alertType:n.Type,frequency:n.Frequency,dayOfWeekValue:n.DayOfWeekValue,monthInterval:n.MonthInterval,startHour:n.StartHour,previousRunResult:n.PreviousRunResult,description:n.Description};return n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.Variables&&(t.variables=(new VariableObject).fromServerModel(n.Variables)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Account_Id:this.account_id(),DateCreated:this.dateCreated(),DateActivated:this.dateActivated(),IsActive:this.isActive(),IsDeleted:this.isDeleted(),IsHidden:this.isHidden(),DisplayName:this.displayName(),LastRunDateTime:this.lastRunDateTime(),NextRunDateTime:this.nextRunDateTime(),Priority:this.priority(),Type:this.alertType(),Frequency:this.frequency(),DayOfWeekValue:this.dayOfWeekValue(),MonthInterval:this.monthInterval(),StartHour:this.startHour(),PreviousRunResult:this.previousRunResult(),Description:this.description()};return this.account()&&(n.Account={Id:this.account().id(),CondensedName:this.account().condensedName()}),this.variables()&&(n.Variables=this.variables().toServerModel()),n}});AlertNotification=function(n){var t=this;t.id=ko.observable();t.account=ko.observable();t.account_id=ko.observable();t.dateCreated=ko.observable();t.dateViewed=ko.observable();t.isDismissed=ko.observable();t.isNoLongerValid=ko.observable();t.titleText=ko.observable();t.messageText=ko.observable();t.alert=ko.observable();t.contextId=ko.observable();t.priority=ko.observable();t.takeActionLink=ko.observable();t.showDetailsOfNotification=ko.observable(!1);t.titleTextFormatted=ko.computed({read:function(){var n="";return t.titleText()&&(n=PF.getTextWithoutHTML(t.titleText()).length>90?t.titleText().substring(0,90):t.titleText()),n}});t.titleTextForNotificationModal=ko.computed({read:function(){return PF.getTextWithoutHTML(t.titleText())}});t.notificationStyle=ko.computed({read:function(){return t.titleText()===undefined||t.titleText()===""?"nonactive-alert":"active-alert"}});n&&this.update(n)};ko.utils.extend(AlertNotification.prototype,{update:function(n){n=n||{};this.id(n.id);this.account(n.account);this.account_id(n.account_id);this.dateCreated(n.dateCreated);this.dateViewed(n.dateViewed);this.isDismissed(n.isDismissed);this.isNoLongerValid(n.isNoLongerValid);this.titleText(n.titleText);this.messageText(n.messageText);this.alert(n.alert);this.contextId(n.contextId);this.priority(n.priority);this.takeActionLink(n.takeActionLink)},fromServerModel:function(n){var t={id:n.Id,account_id:n.Account_Id,dateCreated:n.DateCreated,dateViewed:n.DateViewed,isDismissed:n.IsDismissed,isNoLongerValid:n.IsNoLongerValid,titleText:n.TitleText,messageText:n.MessageText,contextId:n.ContextId,priority:n.Priority,takeActionLink:n.TakeActionLink};return n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.Alert&&(t.alert=(new Alert).fromServerModel(n.Alert)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Account_Id:this.account_id(),DateCreated:this.dateCreated(),DateViewed:this.dateViewed(),IsDismissed:this.isDismissed(),IsNoLongerValid:this.isNoLongerValid(),TitleText:this.titleText(),MessageText:this.messageText(),ContextId:this.contextId(),Priority:this.priority(),TakeActionLink:this.takeActionLink()};return this.account()&&(n.Account={Id:this.account().id(),CondensedName:this.account().condensedName()}),this.alert()&&(n.Alert={Id:this.alert().id()}),n}});Billing=function(n){var t=this;t.id=ko.observable();t.payout=ko.observable();t.bookingId=ko.observable();t.booking=ko.observable();t.amount=ko.observable();t.isApproved=ko.observable();t.invoiceNumber=ko.observable();t.paymentTypeDescription=ko.observable();t.bookingName=ko.observable();t.bookingDate=ko.observable();t.billingDate=ko.observable();t.paymentType=ko.observable();t.depositCharged=ko.observable();t.amountToCharge=ko.observable();t.chargeMode=ko.observable();t.minutesBeforeToChargeCustomer=ko.observable();t.isInitialDeposit=ko.observable();t.isFinalDeposit=ko.observable();n&&this.update(n)};ko.utils.extend(Billing.prototype,{update:function(n){n=n||{};this.id(n.id);this.payout(n.payout);this.bookingId(n.bookingId);this.booking(n.booking);this.amount(n.amount);this.isApproved(n.isApproved);this.invoiceNumber(n.invoiceNumber);this.paymentTypeDescription(n.paymentTypeDescription);this.bookingName(n.bookingName);this.bookingDate(n.bookingDate);this.billingDate(n.billingDate);this.paymentType(n.paymentType);this.depositCharged(n.depositCharged);this.minutesBeforeToChargeCustomer(n.minutesBeforeToChargeCustomer);this.amountToCharge(n.amountToCharge);this.chargeMode(n.chargeMode);this.isInitialDeposit(n.isInitialDeposit);this.isFinalDeposit(n.isFinalDeposit)},fromServerModel:function(n){var t={id:n.Id,amount:n.Amount,bookingId:n.Booking_Id,paymentTypeDescription:n.PaymentTypeDescription,paymentType:n.PaymentType,minutesBeforeToChargeCustomer:n.MinutesBeforeToChargeCustomer,amountToCharge:n.AmountToCharge,chargeMode:n.ChargeMode,isInitialDeposit:n.IsInitialDeposit,isFinalDeposit:n.IsFinalDeposit};return n.Booking&&(t.booking=(new Booking).fromServerModel(n.Booking)),n.Payout&&(t.payout=(new AccountPayout).fromServerModel(n.AccountPayout)),this.update(t),this},toServerModel:function(){return{Id:this.id(),Amount:this.amount(),Booking_id:this.bookingId(),PaymentTypeDescription:this.paymentTypeDescription(),PaymentType:this.paymentType(),InvoiceNumber:this.invoiceNumber(),MinutesBeforeToChargeCustomer:this.minutesBeforeToChargeCustomer(),AmountToCharge:this.amountToCharge(),ChargeMode:this.chargeMode(),IsInitialDeposit:this.isInitialDeposit(),IsFinalDeposit:this.isFinalDeposit()}}});BillingAccount=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.type=ko.observable();this.name=ko.observable();this.accountNumber=ko.observable();this.customerId=ko.observable();this.routingNumber=ko.observable();this.bankName=ko.observable();this.isSavings=ko.observable();this.creditCardName=ko.observable();this.expiration=ko.observable();this.cvv=ko.observable();this.zip=ko.observable();this.dateCreated=ko.observable();this.dateModified=ko.observable();this.accountCountryCode=ko.observable();this.creditCardBrand=ko.observable();this.nameOnBankAccount=ko.observable();this.spaceProvider=ko.observable();this.savingsSelect=ko.computed({read:function(){return this.isSavings()?"true":"false"},write:function(n){this.isSavings(n==="true")},owner:this});n&&this.update(n)};ko.utils.extend(BillingAccount.prototype,{update:function(n){n=n||{};this.id(n.id);this.type(n.type);this.name(n.name);this.accountNumber(n.accountNumber);this.customerId(n.customerId);this.routingNumber(n.routingNumber);this.bankName(n.bankName);this.isSavings(n.isSavings);this.creditCardName(n.creditCardName);this.expiration(n.expiration);this.cvv(n.cvv);this.zip(n.zip);this.dateCreated(n.dateCreated);this.dateModified(n.dateModified);this.accountCountryCode(n.accountCountryCode);this.creditCardBrand(n.creditCardBrand);this.nameOnBankAccount(n.nameOnBankAccount);this.spaceProvider(n.spaceProvider);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,type:n.Type,name:n.Name,accountNumber:n.AccountNumber,customerId:n.CustomerId,routingNumber:n.RoutingNumber,bankName:n.BankName,isSavings:n.IsSavings,creditCardName:n.CreditCardName,expiration:n.Expiration,cvv:n.Cvv,zip:n.Zip,dateCreated:n.DateCreated,dateModified:n.DateModified,accountCountryCode:n.AccountCountryCode,creditCardBrand:n.CreditCardBrand,nameOnBankAccount:n.NameOnBankAccount};return n.Account&&(t.spaceProvider=(new Account).fromServerModel(n.Account)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Type:this.type(),Name:this.name(),AccountNumber:this.accountNumber(),CustomerId:this.customerId(),RoutingNumber:this.routingNumber(),BankName:this.bankName(),IsSavings:this.isSavings(),CreditCardName:this.creditCardName(),Expiration:this.expiration(),Cvv:this.cvv(),Zip:this.zip(),DateCreated:this.dateCreated(),DateModified:this.dateModified(),AccountCountryCode:this.accountCountryCode(),CreditCardBrand:this.creditCardBrand(),NameOnBankAccount:this.nameOnBankAccount()};return this.spaceProvider()&&(n.Account=this.spaceProvider().toServerModel()),n}});BitcoinTransaction=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.amountBTCTransferred=ko.observable();t.amountUSDTransferred=ko.observable();t.bTCExchangeRateAtPurchase=ko.observable();t.fromWalletAddress=ko.observable();t.toWalletAddress=ko.observable();t.account=ko.observable();t.buyer=ko.observable();t.employee=ko.observable();t.account_Id=ko.observable();t.buyer_Id=ko.observable();t.employee_Id=ko.observable();t.consumerWallet=ko.observable();t.description=ko.observable();t.customerConfirmationCode=ko.observable();t.driversLicense=ko.observable();t.amountExcludingTip=ko.observable();t.tip={amount:ko.observable(),custom:ko.observable(),percentage:ko.observable(),tenPercent:ko.computed(function(){return t.amountExcludingTip()*.1}),fifteenPercent:ko.computed(function(){return t.amountExcludingTip()*.15}),twentyPercent:ko.computed(function(){return t.amountExcludingTip()*.2})};t.tip.description=ko.computed(function(){if(!t.tip.amount())return null;var n=t.tip.percentage()?t.tip.percentage()+"%":"$"+t.tip.amount();return"$"+t.amountExcludingTip()+" + "+n+" tip"});t.tip.percentage.subscribe(function(n){if(t.amountExcludingTip()){var i=parseFloat(t.amountExcludingTip())*(n/100);t.tip.amount(parseFloat(i.toFixed(2)))}});t.tip.amount.subscribe(function(n){if(t.amountExcludingTip()){var i=parseFloat(t.amountExcludingTip())+parseFloat(n);t.amountUSDTransferred(parseFloat(i.toFixed(2)))}else t.amountUSDTransferred(n)});t.amountExcludingTip.subscribe(function(n){t.tip&&t.tip.amount()&&n?t.amountUSDTransferred(parseFloat(n)+t.tip.amount()):t.amountUSDTransferred(parseFloat(n))});n&&this.update(n)};ko.utils.extend(BitcoinTransaction.prototype,{update:function(n){n=n||{};this.id(n.id);this.account_Id(n.accountId);this.buyer_Id(n.buyer_Id);this.employee_Id(n.employee_Id);this.account_Id(n.account_Id);this.amountBTCTransferred(n.amountBTCTransferred);this.amountUSDTransferred(n.amountUSDTransferred);this.bTCExchangeRateAtPurchase(n.bTCExchangeRateAtPurchase);this.fromWalletAddress(n.fromWalletAddress);this.toWalletAddress(n.toWalletAddress);this.description(n.description);this.customerConfirmationCode(n.customerConfirmationCode);this.driversLicense(n.driversLicense);this.account(n.account);this.buyer(n.buyer);this.employee(n.employee);this.consumerWallet(n.consumerWallet);this.amountExcludingTip(n.amountExcludingTip);n.tip?(this.tip.amount(n.tip.amount),this.tip.custom(n.tip.custom)):(this.tip.amount(null),this.tip.percentage(null),this.tip.custom(!1));this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,amountBTCTransferred:n.AmountBTCTransferred,amountUSDTransferred:n.AmountUSDTransferred,bTCExchangeRateAtPurchase:n.BTCExchangeRateAtPurchase,fromWalletAddress:n.FromWalletAddress,toWalletAddress:n.ToWalletAddress,account_Id:n.Account_Id,buyer_Id:n.Buyer_Id,employee_Id:n.Employee_Id,description:n.Description,customerConfirmationCode:n.CustomerConfirmationCode};return n.Tip&&(t.tip.amount=n.Tip),n.ConsumerWallet&&(t.consumerWallet=(new BitcoinWallet).fromServerModel(n.ConsumerWallet)),n.DriversLicense&&(t.driversLicense=(new DriversLicense).fromServerModel(n.DriversLicense)),n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.Buyer&&(t.buyer=(new User).fromServerModel(n.Buyer)),n.Employee&&(t.employee=(new User).fromServerModel(n.Employee)),t.amountUSDTransferred&&(t.amountExcludingTip=t.amountUSDTransferred-(t.tip.amount?t.tip.amount:0)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),AmountBTCTransferred:this.amountBTCTransferred(),AmountUSDTransferred:this.amountUSDTransferred(),BTCExchangeRateAtPurchase:this.bTCExchangeRateAtPurchase(),FromWalletAddress:this.fromWalletAddress(),ToWalletAddress:this.toWalletAddress(),Account_Id:this.account_Id(),Buyer_Id:this.buyer_Id(),Employee_Id:this.employee_Id(),Description:this.description(),CustomerConfirmationCode:this.customerConfirmationCode()};return this.tip&&(n.Tip=this.tip.amount()),this.consumerWallet()&&(n.ConsumerWallet=this.consumerWallet().toServerModel()),this.driversLicense()&&(n.DriversLicense=this.driversLicense().toServerModel()),n}});BitcoinWallet=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.address=ko.observable();t.encryptedPrivateKey=ko.observable();t.privateKey=ko.observable();t._balanceBTC=ko.observable();t.balanceBTC=ko.computed({read:function(){return t._balanceBTC()?t._balanceBTC():0},write:function(n){t._balanceBTC(n)}});t._balanceUSD=ko.observable();t.balanceUSD=ko.computed({read:function(){return t._balanceUSD()?t._balanceUSD():0},write:function(n){t._balanceUSD(n)}});t.account_Id=ko.observable();t.user_Id=ko.observable();t.fundingBillingId=ko.observable();t.scanData=ko.observable();t.scan=!1;t.scanStartTime=null;t.scanStop=null;t.errorMessage=null;t.testNet=!1;t.address.subscribe(function(){});t.privateKey.subscribe(function(n){if(n&&n.length>40){var i=new JSEncrypt;i.setPublicKey(PF.PublicKey2048);t.encryptedPrivateKey(i.encrypt(n))}n==null&&t.encryptedPrivateKey(null)});t.scanData.subscribe(function(n){n&&n.length>25&&(clearTimeout(t.scanStop),t.scanStop=setTimeout(function(){t.parseScanData(t.scanData())},500))});t.getWalletBalance=function(){$.ajax({type:"POST",url:"/Api/Bitcoin/GetWalletBalance",data:JSON.stringify(t.toServerModel()),contentType:"application/json; charset=utf-8",dataType:"json",success:function(n){n.Success&&t.balanceUSD(n.Item.WalletBalance[1].Value);t.errorMessage!=null&&ko.isObservable(t.errorMessage)&&n.Error!=null&&t.errorMessage(t.errorMessage()+n.Error)}})};t.parseScanData=function(n){if(n&&(n=n.replace(String.fromCharCode(13),"")),t.checkWIFValid(n)){t.scan=!1;t.scanStartTime=null;t.scanData(null);t.privateKey(null);var i=Bitcoin.ECPair.fromWIF(n,t.testNet?Bitcoin.networks.testnet:Bitcoin.networks.bitcoin);t.address(i.getAddress().toString());i=null;t.privateKey(n)}t.checkAddressValid(n)&&(t.address(n),t.encryptedPrivateKey(null),t.privateKey(null),t.scan=!1,t.scanStartTime=null,t.scanData(null))};t.checkAddressValid=function(n){try{Bitcoin.address.fromBase58Check(n)}catch(t){return!1}return!0};t.checkWIFValid=function(n){try{Bitcoin.ECPair.fromWIF(n,t.testNet?Bitcoin.networks.testnet:Bitcoin.networks.bitcoin)}catch(i){return!1}return!0};t.printWalletCoupon=function(n,i,r){var s,e,o,h,f;i||(i=t);var u=new epson.ePOSBuilder;u.addTextLang("en").addTextSmooth(!0);s=$("#canvas").get(0);e=s.getContext("2d");e.drawImage($("#posabitlogo").get(0),0,0);u.addTextAlign(u.ALIGN_CENTER);u.addImage(e,0,0,450,374);u.addFeedLine(3);u.addText("Here are your new account details.\nFor security reasons, this is the ONLY\ncopy. Do not lose it or your account\nbalance is lost!");u.addFeedLine(2);u.addTextSize(2,2);u.addTextStyle(!1,!1,!1);u.addText("Spend\n\n");u.addTextSize(1,1);u.addTextStyle(!1,!1,!0);u.addText("Secret Key\n\n");u.addSymbol(i.privateKey(),u.SYMBOL_QRCODE_MODEL_2,u.LEVEL_DEFAULT,7);u.addFeedLine(1);u.addText(i.privateKey()+"\n");u.addTextStyle(!1,!1,!1);u.addFeedLine(2);u.addFeedLine(2);u.addTextSize(2,2);u.addTextStyle(!1,!1,!1);u.addText("Account Balance\n\n");u.addTextSize(1,1);u.addTextStyle(!1,!1,!0);u.addText(PF.formatCurrency(i.balanceUSD(),!1,!1)+"\n");u.addFeedLine(1);u.addTextStyle(!1,!1,!1);u.addFeedLine(4);u.addTextSize(1,1);u.addTextStyle(!1,!1,!0);u.addText("To learn more about Bitcoin, visit \n"+PF.getReferrerHost()+"/About/Bitcoin");u.addFeedLine(4);o=new Date;u.addText(o.toDateString()+" "+o.toTimeString().slice(0,8)+"\n");u.addFeedLine(2);u.addText("Example Legal Terms");u.addFeedLine(2);u.addTextFont(u.FONT_B);u.addText("Information You Provide: You provide us information about yourself, such as your name and e-mail address, if you register for an account with the Service, including by connecting with the Service via a third-party service, or by “following,” “becoming a fan,” adding the application, etc., on a third party website or network.");u.addFeedLine(2);u.addCut();h="http://"+n+"/cgi-bin/epos/service.cgi?devid=local_printer";f=new epson.ePOSPrint(h);f.timeout="10000";f.mode=f.MODE_GRAY16;f.onreceive=function(n){var t="Printer Error Occurred\n\n",u;n.success||(u=n.status,u&f.ASB_NO_RESPONSE&&(t+=" No printer response\n"),u&f.ASB_PRINT_SUCCESS&&(t+=" Print complete\n"),u&f.ASB_COVER_OPEN&&(t+=" Cover is open\n"),u&f.ASB_PAPER_FEED&&(t+=" Paper feed switch is feeding paper\n"),u&f.ASB_WAIT_ON_LINE&&(t+=" Waiting for online recovery\n"),u&f.ASB_PANEL_SWITCH&&(t+=" Panel switch is ON\n"),u&f.ASB_MECHANICAL_ERR&&(t+=" Mechanical error generated\n"),u&f.ASB_AUTOCUTTER_ERR&&(t+=" Auto cutter error generated\n"),u&f.ASB_UNRECOVER_ERR&&(t+=" Unrecoverable error generated\n"),u&f.ASB_AUTORECOVER_ERR&&(t+=" Auto recovery error generated\n"),u&f.ASB_RECEIPT_END?t+=" Paper roll in printer is empty. Please change.\n":u&f.ASB_RECEIPT_NEAR_END&&(t+=" Paper roll in printer is getting near the end. Change soon!\n"),u&f.ASB_SPOOLER_IS_STOPPED&&(t+=" Stop the spooler\n"),u&f.ASB_OFF_LINE&&(t+=" Offline status\n"),i.address(null),i.encryptedPrivateKey(null),alert(t));r&&typeof r=="function"&&r.call()};f.onerror=function(n){i.address(null);i.privateKey(null);alert("Print error. \n\nIs your printer turned on, wifi connected and correct printer IP?");console.log(n);r&&typeof r=="function"&&r.call()};f.send(u.toString())};t.printPurchaseReceipt=function(n,t,i,r,u,f){var e=new epson.ePOSBuilder,c,s,h,l,o;e.addTextLang("en").addTextSmooth(!0);c=$("#canvas").get(0);s=c.getContext("2d");s.drawImage($("#posabitlogo").get(0),0,0);e.addTextAlign(e.ALIGN_CENTER);e.addImage(s,0,0,450,374);e.addFeedLine(3);e.addText("Purchase Receipt\n");e.addFeedLine(3);e.addTextSize(2,2);e.addText("Purchase Confirmation\n\n");e.addTextSize(1,1);e.addTextStyle(!1,!1,!0);e.addText("Your Creditcard ending in "+n+"\n has been charged.\n");e.addFeedLine(3);e.addTextSize(2,2);e.addTextStyle(!1,!1,!1);e.addText("Purchase Amount\n\n");e.addTextSize(1,1);e.addTextStyle(!1,!1,!0);e.addText(PF.formatCurrency(t,!1,!1)+"\n");e.addText(i+" BTC\n");e.addFeedLine(3);e.addText("Account Balance: "+PF.formatCurrency(r,!1,!1)+"\n");e.addFeedLine(1);e.addTextStyle(!1,!1,!1);e.addFeedLine(3);h=new Date;e.addText(h.toDateString()+" "+h.toTimeString().slice(0,8)+"\n");e.addFeedLine(2);e.addText("Example Legal Terms");e.addFeedLine(2);e.addTextFont(e.FONT_B);e.addText("Information You Provide: You provide us information about yourself, such as your name and e-mail address, if you register for an account with the Service, including by connecting with the Service via a third-party service, or by “following,” “becoming a fan,” adding the application, etc., on a third party website or network.");e.addFeedLine(2);e.addCut();l="http://"+u+"/cgi-bin/epos/service.cgi?devid=local_printer";o=new epson.ePOSPrint(l);o.timeout="10000";o.mode=o.MODE_GRAY16;o.onreceive=function(n){var t="Printer Error Occurred\n\n",i;n.success?f&&typeof f=="function"&&f.call():(i=n.status,i&o.ASB_NO_RESPONSE&&(t+=" No printer response\n"),i&o.ASB_PRINT_SUCCESS&&(t+=" Print complete\n"),i&o.ASB_COVER_OPEN&&(t+=" Cover is open\n"),i&o.ASB_PAPER_FEED&&(t+=" Paper feed switch is feeding paper\n"),i&o.ASB_WAIT_ON_LINE&&(t+=" Waiting for online recovery\n"),i&o.ASB_PANEL_SWITCH&&(t+=" Panel switch is ON\n"),i&o.ASB_MECHANICAL_ERR&&(t+=" Mechanical error generated\n"),i&o.ASB_AUTOCUTTER_ERR&&(t+=" Auto cutter error generated\n"),i&o.ASB_UNRECOVER_ERR&&(t+=" Unrecoverable error generated\n"),i&o.ASB_AUTORECOVER_ERR&&(t+=" Auto recovery error generated\n"),i&o.ASB_RECEIPT_END?t+=" Paper roll in printer is empty. Please change.\n":i&o.ASB_RECEIPT_NEAR_END&&(t+=" Paper roll in printer is getting near the end. Change soon!\n"),i&o.ASB_SPOOLER_IS_STOPPED&&(t+=" Stop the spooler\n"),i&o.ASB_OFF_LINE&&(t+=" Offline status\n"),alert(t))};o.onerror=function(){alert("Print error. Verify that your printer is turned on, is connected to Wi-Fi, and that you have the printer's IP in your settings.")};o.send(e.toString())};n&&this.update(n)};ko.utils.extend(BitcoinWallet.prototype,{update:function(n){n=n||{};this.id(n.id);this.address(n.address);this.encryptedPrivateKey(n.encryptedPrivateKey);this.privateKey(n.privateKey);this.account_Id(n.account_Id);this.balanceUSD(n.balanceUSD);this.balanceBTC(n.balanceBTC);this.user_Id(n.user_Id);this.scan=n.scan;this.scanData(n.scanData);this.fundingBillingId(n.fundingBillingId);this.scanStartTime=n.scanStartTime;this.testNet=n.testNet;this.errorMessage=n.errorMessage;this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,address:n.Address,account_Id:n.Account_Id,user_Id:n.User_Id,fundingBillingId:n.FundingBillingId,testNet:this.testNet,privateKey:this.privateKey()};return n.WalletBalance&&(t.balanceUSD=n.WalletBalance[1].Value),this.update(t),this},toServerModel:function(){if(this.encryptedPrivateKey()&&this.encryptedPrivateKey().length<75){var n=new JSEncrypt;n.setPublicKey(PF.PublicKey2048);this.encryptedPrivateKey(n.encrypt(this.encryptedPrivateKey()))}return{Id:this.id(),Address:this.address(),EncryptedPrivateKey:this.encryptedPrivateKey(),Account_Id:this.account_Id(),User_Id:this.user_Id(),FundingBillingId:this.fundingBillingId()}}});Booking=function(n){var t=this;t.cache=function(){};this.deleted=ko.observable(!1);this.id=ko.observable();this.bookingName=ko.observable();this.bookingFirstName=ko.observable();this.bookingLastName=ko.observable();this.bookingEmail=ko.observable();this.bookingPhone=ko.observable();this.startTime=ko.observable();this.startDate=ko.observable();this.endDate=ko.observable();this.endTime=ko.observable();this.bookingDate=ko.observable();this.bookingOverride=ko.observable();this.calendarType=ko.observable();this.totalSecurityDepositHold=ko.observable();this.totalAdditionalFee=ko.observable();this.totalAddOnFee=ko.observable();this.totalResourceFee=ko.observable();this.totalBooking=ko.observable();this.totalBilling=ko.observable();this.totalTaxes=ko.observable();this.taxRate=ko.observable();this.total=ko.observable();this.confirmationCode=ko.observable();this.discountCode=ko.observable();this.availabilityQtyBooked=ko.observable();this.fundingSource=ko.observable();this.totalBillingRefund=ko.observable();this.paidFully=ko.observable();this.hasSecurityDepositBillings=ko.observable();this.notes=ko.observable();this.billings=ko.observableArray();this.totalBilled=ko.observable(0);t.resources=ko.observableArray([]);t.selectedResourceOption=ko.observable();this.space=ko.observable();this.spaceId=ko.observable();this.bookingDetails=ko.observableArray();this.additionalInfo=ko.observableArray();this.addOns=ko.observableArray();this.errorMessage=ko.observable();this.originalStartDate=ko.observable();this.originalEndDate=ko.observable();this.spaceAvailabilityStartDate=ko.observable();this.spaceAvailabilityEndDate=ko.observable();this.spaceAvailabilityCalendarTypeId=ko.observable();this.bookingEmailFixed=ko.computed({read:function(){return t.bookingEmail()},write:function(n){n&&(n=n.replace(/ /g,""));t.bookingEmail(n)}});this.calculatedInitialDepositTotal=ko.computed(function(){var r,n,i;if(t.space()&&t.space().hasDepositPricing()&&t.space().computedInitialDeposit()){if(r=t.totalBilling(),n=$.grep(t.bookingDetails(),function(n){return n.promotionCode()}),n.length>0)for(i=0;i<n.length;i++)r+=n[i].netBooking();return t.space().computedInitialDeposit().chargeMode()==1?t.space().computedInitialDeposit().amountToCharge():t.space().computedInitialDeposit().amountToCharge()/100*r}return null});this.hasPromotionCode=ko.computed(function(){for(var i=!1,n=0;n<t.bookingDetails().length;n++)t.bookingDetails()[n].promotionCode()!==null&&t.bookingDetails()[n].promotionCode()!==undefined&&(i=!0);return i});this.additionalInfoAnswered=ko.computed(function(){var n=[];return $.each(t.additionalInfo(),function(t,i){i&&i.userResponse()&&i.userResponse().length>0&&n.push(i)}),n});this.rateRuleName=ko.computed({read:function(){return t.bookingDetails()&&t.bookingDetails().length>0&&t.bookingDetails()[0].rentalRate()&&t.bookingDetails()[0].rentalRate().rateRule()?t.bookingDetails()[0].rentalRate().rateRule().ruleName():t.space()&&t.space().defaultRate()&&t.space().defaultRate().rateRule()?t.space().defaultRate().rateRule().ruleName():null}});this.totalBillingPlusAddOnResource=ko.computed({read:function(){return t.totalBilling()+t.totalAddOnFee()+t.totalResourceFee()}});this.totalPlusAddOnResource=ko.computed({read:function(){return t.total()+t.totalAddOnFee()+t.totalResourceFee()}});this.totalBookingPlusResource=ko.computed({read:function(){return t.totalBooking()+t.totalResourceFee()}});this.totalWithoutTaxes=ko.computed({read:function(){return t.total()-t.totalTaxes()}});this.startDateTime=ko.computed(function(){return new Date(t.startDate()+" "+t.startTime())});this.endDateTime=ko.computed(function(){var n=new Date(t.endDate()+" "+t.endTime());return(n.getHours()!==0||n.getMinutes()!==30)&&(n=new Date(n.getTime()+18e5)),n});this.totalResourceFee.subscribe(function(){t.recalcuate()});this.totalAddOnFee.subscribe(function(){t.recalcuate()});t.groupedResources=ko.computed(function(){var n=[];return $.each(t.resources(),function(i,r){var u=$.grep(n,function(n){return n.nameComputed()===r.categoryNameComputed()&&n.children()[0].resource().usageType()===r.resource().usageType()});u.length===0&&(u=[new ResourceBookingGroup(r,t.availabilityQtyBooked())],n.push(u[0]));u[0].children.push(r)}),n},t,{deferEvaluation:!0});t.groupedResourcesContainsHiddenResourceForBuyer=ko.computed(function(){return(new ResourceBookingGroup).groupedResourcesContainsHiddenResourceForBuyer(t.groupedResources())});t.selectedResourceOption.subscribe(function(n){t.resources()&&n!=null&&$.each(t.resources(),function(i,r){r.categoryNameComputed()==n.categoryNameComputed()&&(n.id()==r.id()?r.quantityPurchased(t.availabilityQtyBooked()):r.quantityPurchased(0))})});t.maxAvailableResourceQtyAllowed=ko.computed(function(){var n=null;return $.each(t.groupedResources(),function(t,i){var r=i.maxAvailableQtyToBeBookedInGroup();(n==null||n>r)&&(n=r)}),n==null?1e11:n});t.primaryBookingDetail=ko.computed(function(){if(t.bookingDetails()){if(t.bookingDetails().length===1)return t.bookingDetails()[0];if(t.bookingDetails().length>1)for(var n=0;n<t.bookingDetails().length;n++)if(t.bookingDetails()[n].promotionCode()==null&&t.bookingDetails()[n].rentalRate()!=null)return t.bookingDetails()[n]}return null});this.subscribeAddOnUpdates=function(n){$.each(this.addOns(),function(t,i){i.qtyPurchased.subscribe(function(){n.call()})})};this.subscribeResourceUpdates=function(n){$.each(this.resources(),function(t,i){i.quantityPurchased.subscribe(function(){n.call()})})};t.validateResources=function(){var n=!0;return $.each(t.groupedResources(),function(t,i){if(!i.validate())return n=!1,!1}),n};t.recalcuate=function(){var n=t.totalBooking()+t.totalAdditionalFee()+t.totalAddOnFee()+t.totalResourceFee(),i=0,r;t.taxRate()&&(i=PF.roundToTwoByMathRound(n*t.taxRate()/100));t.totalTaxes(i);t.totalBilling(n+t.totalTaxes());r=t.totalSecurityDepositHold()?t.totalSecurityDepositHold():0;t.total(t.totalBilling()+r)};n&&this.update(n)};ko.utils.extend(Booking.prototype,{update:function(n){n=n||{};this.id(n.id);this.bookingName(n.bookingName||"");this.bookingFirstName(n.bookingFirstName);this.bookingLastName(n.bookingLastName);this.bookingEmail(n.bookingEmail);this.bookingPhone(n.bookingPhone);this.startTime(n.startTime);this.startDate(n.startDate);this.endDate(n.endDate);this.endTime(n.endTime);this.calendarType(n.calendarType);this.bookingDate(n.bookingDate);this.taxRate(n.taxRate);this.total(n.total);this.totalBooking(n.totalBooking);this.totalBilling(n.totalBilling);this.totalBillingRefund(n.totalBillingRefund);this.totalAdditionalFee(n.totalAdditionalFee);this.totalAddOnFee(n.totalAddOnFee);this.totalSecurityDepositHold(n.totalSecurityDepositHold);this.totalTaxes(n.totalTaxes);this.bookingOverride(n.bookingOverride);this.confirmationCode(n.confirmationCode);this.discountCode(n.discountCode);this.availabilityQtyBooked(n.availabilityQtyBooked);this.spaceId(n.spaceId);this.fundingSource(n.fundingSource);this.paidFully(n.paidFully);this.notes(n.notes);this.totalResourceFee(n.totalResourceFee);this.hasSecurityDepositBillings(n.hasSecurityDepositBillings);this.resources(n.resources||[]);this.originalStartDate(n.originalStartDate);this.originalEndDate(n.originalEndDate);this.spaceAvailabilityStartDate(n.spaceAvailabilityStartDate);this.spaceAvailabilityEndDate(n.spaceAvailabilityEndDate);this.spaceAvailabilityCalendarTypeId(n.spaceAvailabilityCalendarTypeId);n.space&&this.space(n.space);n.bookingDetails&&this.bookingDetails(n.bookingDetails);n.additionalInfo&&this.additionalInfo(n.additionalInfo);n.addOns&&this.addOns(n.addOns);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,bookingName:n.BookingName,bookingFirstName:n.BookingFirstName,bookingLastName:n.BookingLastName,bookingEmail:n.BookingEmail,bookingPhone:n.BookingPhoneNumber,calendarType:n.CalendarType,startTime:n.StartTime,startDate:n.StartDate,endTime:n.EndTime,endDate:n.EndDate,bookingDate:n.BookingDate,taxRate:n.TaxRate,total:n.Total,totalAdditionalFee:n.TotalAdditionalFees,totalAddOnFee:n.TotalAddOnFees,totalResourceFee:n.TotalResourceFees,totalSecurityDepositHold:n.TotalSecurityDepositHold,totalTaxes:n.TotalTaxes,totalBooking:n.TotalBooking,totalBilling:n.TotalBilling,totalBillingRefund:n.TotalBillingRefund,bookingOverride:n.BookingOverride,confirmationCode:n.CustomerConfirmationCode,discountCode:n.DiscountCode,availabilityQtyBooked:n.AvailabilityQtyBooked,spaceId:n.Space_Id,fundingSource:n.FundingSource,paidFully:n.PaidFully,notes:n.Notes,hasSecurityDepositBillings:n.HasSecurityDepositBillings,originalStartDate:n.OriginalStartDate,originalEndDate:n.OriginalEndDate,spaceAvailabilityStartDate:n.SpaceAvailabilityStartDate,spaceAvailabilityEndDate:n.SpaceAvailabilityEndDate,spaceAvailabilityCalendarTypeId:n.SpaceAvailabilityCalendarTypeId},r,i;return t.space=n.Space?(new Space).fromServerModel(n.Space):(new Space).fromServerModel({Id:n.SpaceId||n.Space_Id,Name:n.SpaceName,PublicUrl:n.SpacePublicUrl,TimeZone:n.SpaceTimeZone,DefaultImage:n.DefaultImage}),n.BookingDetails&&(t.bookingDetails=n.BookingDetails.map(function(n){return(new BookingDetail).fromServerModel(n)})),n.AdditionalInfoBooking&&(t.additionalInfo=n.AdditionalInfoBooking.map(function(n){return(new AdditionalInfoResponse).fromServerModel(n)})),n.AddOnBooking&&(t.addOns=n.AddOnBooking.map(function(n){return(new AddOnBooking).fromServerModel(n)})),n.Billings&&n.Billings.length>0&&(r=$.grep(n.Billings,function(n){return n.PaymentType==PF.PaymentType.CreditCard_Funding||n.PaymentType==PF.PaymentType.Bitcoin_Funding}),t.fundingSource=n.Billings[0].PaymentTypeDescription),n.Resources&&(t.resources=n.Resources.map(function(n){return(new ResourceBooking).fromServerModel(n)}),i=this,$.each(t.resources,function(n,t){t.booking(i)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),BookingName:this.bookingName(),BookingFirstName:this.bookingFirstName(),BookingLastName:this.bookingLastName(),BookingEmail:this.bookingEmail(),BookingPhoneNumber:this.bookingPhone(),CalendarType:this.calendarType(),StartTime:this.startTime(),StartDate:this.startDate(),EndTime:this.endTime(),EndDate:this.endDate(),BookingDate:this.bookingDate(),TaxRate:this.taxRate(),Total:this.total(),TotalAdditionalFees:this.totalAdditionalFee(),TotalResourceFees:this.totalResourceFee(),TotalSecurityDepositHold:this.totalSecurityDepositHold(),TotalTaxes:this.totalTaxes(),TotalBooking:this.totalBooking(),TotalBilling:this.totalBilling(),BookingOverride:this.bookingOverride(),CustomerConfirmationCode:this.confirmationCode(),DiscountCode:this.discountCode(),AvailabilityQtyBooked:this.availabilityQtyBooked(),PaidFully:this.paidFully(),Notes:this.notes(),SpaceAvailabilityStartDate:this.spaceAvailabilityStartDate(),SpaceAvailabilityEndDate:this.spaceAvailabilityEndDate(),SpaceAvailabilityCalendarTypeId:this.spaceAvailabilityCalendarTypeId()};return n.Space_Id=this.space().id()?this.space().id():this.spaceId(),this.bookingDetails()&&(n.BookingDetails=this.bookingDetails().map(function(n){return n.toServerModel()})),this.additionalInfo()&&(n.AdditionalInfoBooking=this.additionalInfo().map(function(n){return n.toServerModel()})),this.addOns()&&(n.AddOnBooking=this.addOns().map(function(n){return n.toServerModel()})),this.resources()&&(n.Resources=this.resources().map(function(n){return n.toServerModel()})),n}});BookingDetail=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.availabilityRate=ko.observable();this.billingUnits=ko.observable();this.calendarType=ko.observable();this.endDate=ko.observable();this.endTime=ko.observable();this.hasCalculated=ko.observable();this.netBooking=ko.observable();this.rateRule=ko.observable();this.startDate=ko.observable();this.startTime=ko.observable();this.space=ko.observable();this.rentalRate=ko.observable();this.promotionCode=ko.observable();n&&this.update(n)};ko.utils.extend(BookingDetail.prototype,{update:function(n){n=n||{};this.id(n.id);this.availabilityRate(n.availabilityRate);this.billingUnits(n.billingUnits);this.calendarType(n.calendarType);this.endDate(n.endDate);this.endTime(n.endTime);this.hasCalculated(n.hasCalculated);this.netBooking(n.netBooking);this.rateRule(n.rateRule);this.startDate(n.startDate);this.startTime(n.startTime);n.rentalRate&&this.rentalRate(n.rentalRate);n.space&&this.space(n.space);n.promotionCode&&this.promotionCode(n.promotionCode);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,availabilityRate:n.AvailabilityRate,billingUnits:n.BillingUnits,calendarType:n.CalendarType,endDate:n.EndDate,endTime:n.EndTime,hasCalculated:n.HasCalculated,netBooking:n.NetBooking,rateRule:n.RateRule,startDate:n.StartDate,startTime:n.StartTime};return n.RentalRate&&(t.rentalRate=(new RentalRate).fromServerModel(n.RentalRate)),n.Space&&(t.space=(new Space).fromServerModel(n.Space)),n.PromotionCode&&(t.promotionCode=(new PromotionCode).fromServerModel(n.PromotionCode)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),AvailabilityRate:this.availabilityRate(),BillingUnits:this.billingUnits(),CalendarType:this.calendarType(),EndDate:this.endDate(),EndTime:this.endTime(),HasCalculated:this.hasCalculated(),NetBooking:this.netBooking(),RateRule:this.rateRule(),StartDate:this.startDate(),StartTime:this.startTime()};return n.RentalRate=this.rentalRate()?this.rentalRate().toServerModel():null,this.space()&&(n.Space_Id=this.space().id()),this.promotionCode()&&(n.PromotionCode=this.promotionCode().toServerModel()),n}});BookingsRequest=function(n){var t=this;t.cache=function(){};this.item=ko.observable();this.startDate=ko.observable();this.endDate=ko.observable();this.fullBooking=ko.observable();this.properties=ko.observable();this.removalMode=ko.observable(!1);n&&this.update(n)};ko.utils.extend(BookingsRequest.prototype,{update:function(n){n=n||{};this.item(n.item);this.startDate(n.startDate);this.endDate(n.endDate);this.fullBooking(n.fullBooking);this.properties(n.properties);this.removalMode(n.removalMode)},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={item:n.Item,startDate:n.StartDate,endDate:n.EndDate,fullBooking:n.FullBooking,properties:n.properties,removalMode:n.removalMode};return this.update(t),this},toServerModel:function(){return{Item:this.item(),StartDate:this.startDate(),EndDate:this.endDate(),FullBooking:this.fullBooking(),Properties:this.properties(),RemovalMode:this.removalMode()}}});PF=PF||{};PF.ProviderType={Invalidated:-2,SinglePager:-1,Basic:0,Team:2,TeamGold:3,TeamPlus:4,TeamPlusGold:5,TeamLeader:6,TeamLeaderGold:7};PF.ProviderTypeFullName=function(n){var t="";switch(n){case-2:t="Invalidated";break;case-1:t="Single Pager";break;case 0:t="Basic";break;case 2:t="Team";break;case 3:t="Team Gold";break;case 4:t="Team Plus";break;case 5:t="Team Plus Gold";break;case 6:t="Team Leader";break;case 7:t="Team Leader Gold";break;case 8:t="Team Leader Bitcoin"}return t};PF.UsageType={BuyerQty:0,BuyerDropdown:1};PF.RateType={Hourly:0,PerUse:1,Daily:2,PerPerson:3};PF.RoleType={Staff:0,Supervisor:2,Manager:4,LocationAdmin:6,FranchiseAdmin:8};PF.AccountType={Ach:1,CreditCard:2};PF.SpaceCategory={Package:"C2CEE8AC-31F5-4A0D-8F4A-930C436CE17A",Service:"0776F577-23B3-4D0B-966F-6317E03E03ED",Space:"F14D3A4A-0178-4616-ABDA-F8740094F9A2"};PF.RateRule={Default:"Default",SpecialPackage:"SpecialPackage",Referral:"Referral",Security:"Security",Cleaning:"Cleaning",Promotion:"Promotion",Appointment:"DefaultAppointment",DefaultPackage:"DefaultPackage"};PF.PaymentType={CreditCard_Funding:0,CashCheck_Funding:1,Appointment_Funding:2,Bitcoin_Funding:3,FreeAfterDiscounts_Funding:4,CreditCard_Void:6,CreditCard_Refund:8,CreditCard_SecurityDeposit:10,CreditCard_Refund_SecurityDeposit:12,CreditCard_ChargeBack:14,CreditCard_ChargeBackFee:16,CreditCard_Gratuity:17,CreditCard_Refund_Gratuity:18};PF.Publish={Facebook:"publish-facebook",Web_Calendar:"publish-web-calendar",Web_Listing:"publish-web-listing",OnePager:"publish-onepager",MarketPlace:"publish-marketplac"};PF.CalendarType={Booking:{Id:"9D1BA308-1F7F-444E-BAC5-1CD7B3D5419E",CalendarTypeName:"Booking"},InternalBooking:{Id:"51B51584-8F6A-47AD-A6D2-5A9772466342",CalendarTypeName:"Internal Booking"},PrivateBooking:{Id:"36F2BDA5-1928-4F91-94D2-C0575FDF49EF",CalendarTypeName:"Private Booking"},Availability:{Id:"29F0F9A0-9D78-40BC-8637-FFA2FCC264E5",CalendarTypeName:"Availability"},Unavailability:{Id:"729531E4-3333-4BAE-A174-3D5664D128AB",CalendarTypeName:"Unavailable"},Referral:{Id:"83F91D50-0CC7-4DF5-9283-1CDF599E83BA",CalendarTypeName:"Referral"},MultiDayAvailability:{Id:"9e6fb1a4-df6a-4c23-9825-db65afa534f0",CalendarTypeName:"MultiDay Availability"},NoteExternal:{Id:"1802CE4C-F37A-4645-BEC9-0B5DADC2AF2D",CalendarTypeName:"Note External"},NoteInternal:{Id:"DA5717E5-EB45-4339-AF44-000F0949EBCC",CalendarTypeName:"Note Internal"},Resource:{Id:"7537EC64-6DC4-4E5F-8C76-91AAF738A4C1",CalendarTypeName:"Resource"}};PF.Factory={RentalRate:{createPerUsePricingRate:function(){return new RentalRate({rateRule:new RateRule({ruleName:PF.RateRule.SpecialPackage}),rateTypeId:PF.RateType.PerUse,availabilityQtyUsed:1})},createPerPersonPricingRate:function(n){if(n){var t=n.defaultRate().maxAvailabilityQty()+1;return $.each(n.specialRates(),function(n,i){i.maxAvailabilityQty()>t&&(t=i.maxAvailabilityQty()+1)}),t>n.packageQuantity()&&(t=n.packageQuantity()),new RentalRate({rateRule:new RateRule({ruleName:PF.RateRule.SpecialPackage}),rateTypeId:PF.RateType.PerPerson,minAvailabilityQty:t,maxAvailabilityQty:n.packageQuantity(),initialMaxAvailabilityQty:n.packageQuantity(),initialMinAvailabilityQty:1})}return new RentalRate({rateRule:new RateRule({ruleName:PF.RateRule.SpecialPackage}),rateTypeId:PF.RateType.PerPerson})},createHourlyPricingRate:function(){return new RentalRate({rateRule:new RateRule({ruleName:PF.RateRule.SpecialPackage}),rateTypeId:PF.RateType.Hourly})},createSecurityRate:function(){return new RentalRate({rateRule:new RateRule({ruleName:PF.RateRule.Security}),rateTypeId:PF.RateType.PerUse})},createCleaningRate:function(){return new RentalRate({rateRule:new RateRule({ruleName:PF.RateRule.Cleaning}),rateTypeId:PF.RateType.PerUse})}},Availability:{createAvailability:function(n){return new SpaceAvailability($.extend({},{calendarType:PF.CalendarType.Availability},n))},createUnavailability:function(n){return new SpaceAvailability($.extend({},{calendarType:PF.CalendarType.Unavailability},n))},createMultiDayAvailability:function(n){return new SpaceAvailability($.extend({},{calendarType:PF.CalendarType.MultiDayAvailability},n))},createReferral:function(n){return new SpaceAvailability($.extend({},{calendarType:PF.CalendarType.Referral},n))},createResource:function(n){return new SpaceAvailability($.extend({},{calendarType:PF.CalendarType.Resource},n))}}};PF.LogType={Debug:0,Info:1,Warning:2,Error:3};PF.ReportParameterType={Listing:0,DatePicker:1,RangeDatePicker:2,Month:3,Year:4,StringInput:5,DateTimePicker:6,FranchiseAccountPicker:7,RangeDateTimePicker:8,ProviderTypePicker:9,RoleTypePicker:10,ProviderTypePickerMultiple:11,RoleTypePickerMultiple:12,AddOn:13,PaymentFrequency:14};PF.Booking={Account:{This:"Account",AccountUnderwritingInfo:"Account.AccountUnderwritingInfo",AddressLine1:"Account.AddressLine1",AddressLine2:"Account.AddressLine2",AlternateBillingEmail:"Account.AlternateBillingEmail",BaseCurrency:"Account.BaseCurrency",City:"Account.City",CondensedName:"Account.CondensedName",Country:"Account.Country",CustomGroups:"Account.CustomGroups",DateCreated:"Account.DateCreated",Email:"Account.Email",EmailBlackListDate:"Account.EmailBlackListDate",EmailBlackListReason:"Account.EmailBlackListReason",ExternalWebSiteURL:"Account.ExternalWebSiteURL",FacebookPageId:"Account.FacebookPageId",FirstName:"Account.FirstName",Id:"Account.Id",ImageURL:"Account.ImageURL",IsProPayEnabled:"Account.IsProPayEnabled",IsTrial:"Account.IsTrial",LastName:"Account.LastName",Lat:"Account.Lat",Long:"Account.Long",OrganizationName:"Account.OrganizationName",PhoneNumber:"Account.PhoneNumber",PostalOrZipCode:"Account.PostalOrZipCode",ProPayMerchantProfileId:"Account.ProPayMerchantProfileId",ProviderType:"Account.ProviderType",ProviderTypeId:"Account.ProviderTypeId",RentalNotificationEmail:"Account.RenterNotificationEmail",SiteProperties:"Account.SiteProperties",StateOrProvince:"Account.StateOrProvince",TaxRate:"Account.TaxRate",TimeZone:"Account.TimeZone",Users:"Account.Users",YelpPageId:"Account.YelpPageId",IsTrxEnabled:"Account.IsTrxEnabled",TrxLeadGuid:"Account.TrxLeadGuid",TrxLeadActive:"Account.TrxLeadActive",TrxLeadState:"Account.TrxLeadState",TrxStorageSafeGuid:"Account.TrxStorageSafeGuid",TrxStorageAccountAchGuid:"Account.TrxStorageAccountAchGuid",TrxStorageAccountCreditGuid:"Account.TrxStorageAccountCreditGuid",TrxStorageShippingGuid:"Account.TrxStorageShippingGuid",TrxStorageCustomerGuid:"Account.TrxStorageCustomerGuid",TrxClientId:"Account.TrxClientId",TrxSourceId:"Account.TrxSourceId",TrxAlgorithmKey:"Account.TrxAlgorithmKey",TrxAlgorithmIv:"Account.TrxAlgorithmIv"},Account_Id:"Account_Id",AddonBooking:"AddOnBooking",AdditionalInfoBooking:"AdditionalInfoBooking",AvailabilityQtyBooked:"AvailabilityQtyBooked",Billings:"Billings",Billings_Funding:"Billings_Funding",BookingDate:"BookingDate",BookingDetails:"BookingDetails",BookingEmail:"BookingEmail",BookingFirstName:"BookingFirstName",BookingLastName:"BookingLastName",BookingOverride:"BookingOVerride",BookingPhoneNumber:"BookingPhoneNumber",CalendarType:"CalendarType",CalendarTypeId:"CalendarType_Id",CustomerConfirmationCode:"CustomerConfirmationCode",DateCreated:"DateCreated",DiscountCode:"DiscountCode",EndDate:"EndDate",EndDateTimeObj:"EndDateTimeObj",EndDateTimeUTCObj:"EndDateTimeUTCObj",EndTime:"EndTime",GetPackageName:"GetPackageName",HasCalculated:"HasCalculated",HasSecurityDepositBillings:"HasSecurityDepositBillings",Id:"Id",IsDeleted:"IsDeleted",Notes:"Notes",PaidFully:"PaidFully",PostRentalBuffer:"PostRentalBuffer",ProPayPaymentMethodId:"ProPayPaymentMethodId",RateRuleName:"RateRuleName",RefundDate:"RefundDate",Resources:"Resources",SitePromotionCode:"SitePromotionCode",SitePromotionDiscount:"SitePromotionDiscount",SitePromotionDiscountAmt:"SitePromotionDiscountAmt",Space:{This:"Space",AddressLine1:"Space.AddressLine1",AddressLine2:"Space.AddressLine2",AllowDepositToBePaidInFull:"Space.AllowDepositToBePaidInFull",Amenitites:"Space.Amenities",Availabilities:"Space.Availabilities",AvailabilityQty:"Space.AvailabilityQty",AverageReview:"Space.AverageReview",CanPreviewSpace:"Space.CanPreviewSpace",Capacity:"Space.Capacity",City:"Space.City",CleaningRate:"Space.CleaningRate",CondensedName:"Space.CondensedName",Country:"Space.Country",DateCreated:"Space.DateCreated",DefaultImage:"Space.DefaultImage",DefaultRate:"Space.DefaultRate",DepositTimeTable:"Space.DepositTimeTable",Description:"Space.Description",DisplayAddress:"Space.DisplayAddress",EmailNotice:"Space.EmailNotice",ExcludeFromPromotions:"Space.ExcludeFromPromotions",Favorite:"Space.Favorite",GiftedPageUrl:"Space.GiftedPageUrl",HasDepositPricing:"Space.HasDepositPricing",HasPassword:"Space.HasPassword",Id:"Space.Id",IsPreferredSpace:"Space.IsPreferreSpace",IsReferralSpace:"Space.IsReferralSpace",LastKnownVersion:"Space.LastKnownVersion",Lat:"Space.Lat",Long:"Space.Long",MinimumNotice:"Space.MinimumNotice",MinimumRental:"Space.MinimumRental",MinimumRentalFee:"Space.MinimumRentalFee",MinimumRentalInHours:"Space.MinimumRentalInHours",Name:"Space.Name",PackageQty:"Space.PackageQty",PercentComplete:"Space.PercentComplete",PhoneNumber:"Space.PhoneNumber",PostalCode:"Space.PostalCode",PromotionCodeGroups:"Space.PromotionCodeGroups",Promotionrates:"Space.PromotionRates",PublicUrl:"Space.PublicUrl",PublishedToFacebook:"Space.PublishedToFacebook",PublishedToMarketplace:"Space.PublishedToMarketplace",PublishedToWeb:"Space.PublishedToWeb",PublishedToWebCalendar:"Space.PublishedToWebCalendar",ResourcesSpaces:"Space.ResourceSpaces",ReviewCount:"Space.ReviewCount",SecurityRate:"Space.SecurityRate",SortOrder:"Space.SortOrder",SpaceCategory:"Space.SpaceCategory",SpaceEventType:"Space.SpaceEventTypes",SpaceImages:"Space.SpaceImages",SpaceProvider:"Space.SpaceProvider",SpaceType:"Space.SpaceType",SpecialFlags:"Space.SpecialFlags",SpecialRates:"Space.SpecialRates",StateOrProvince:"Space.SpaceOrProvince",Status:"Space.Status",StatusId:"Space.StatusId",Taxable:"Space.Taxable",Terms:"Space.Terms",TimeZone:"Space.TimeZone",Url:"Space.Url",UserId:"Space.UserId"},Space_Id:"Space_Id",StartDate:"StartDate",StartDateTimeObj:"StartDateTimeObj",StartDateTimeUTCObj:"StartDateTimeUTCObj",StartTime:"StartTime",TaxRate:"TaxRate",Total:"Total",TotalAddOnFess:"TotalAddOnFess",TotalBilling:"TotalBilling",TotalResourcesFees:"TotalResourceFess",TotalSecurityDepositHold:"TotalSecurityDepositHold",TotalTaxes:"TotalTaxes",User:{This:"User",AccountIsValidated:"User.AccountIsValidated",AccountType:"User.AccountType",Accounts:"User.Accounts",AgreeToTerms:"User.AgreeToTerms",CreatedBy:"User.CreatedBy",DateTimeCreated:"User.DateTimeCreated",DefaultSearchRegion:"User.DefaultSearchRegion",Email:"User.Email",EmailBlackListDate:"User.EmailBlackListDate",EmailBlackListReason:"User.EmailBlackListReason",EmailIsValidated:"User.EmailIsValidated",ExternalBillingId:"User.ExternalBillingId",FacebookAccessCode:"User.FacebookAccessCode",FacebookId:"User.FacebookId",FirstName:"User.FirstName",Id:"User.Id",LastName:"User.LastName",LoginType:"User.LoginType",LoginTypeId:"User.LoginTypeId",MerchantType:"User.MerchantType",PhoneNumber:"User.PhoneNumber",RememberMe:"User.RememberMe",SendNewsLetter:"User.SendNewsLetter",SpaceProvider:"User.SpaceProvider"},User_Id:"User_Id"};PF.SpaceSpecialFlags={IsGiftedListing:1};PF.CountryList=[{name:"United States",value:"US"},{name:"Canada",value:"CA"}];PF.ProvinceList=["AB","BC","MB","NB","NL","NT","NS","NU","ON","PE","QC","SK","YT"];PF.ProvinceMap=[{Name:"Alberta",Code:"AB"},{Name:"British Columbia",Code:"BC"},{Name:"Manitoba",Code:"MB"},{Name:"New Brunswick",Code:"NB"},{Name:"Newfoundland and Labrador",Code:"NL"},{Name:"Northwest Territories",Code:"NT"},{Name:"Nova Scotia",Code:"NS"},{Name:"Nunavut",Code:"NU"},{Name:"Ontario",Code:"ON"},{Name:"Prince Edward Island",Code:"PE"},{Name:"Quebec",Code:"QC"},{Name:"Saskatchewan",Code:"SK"},{Name:"Yukon",Code:"YT"},];PF.StateMap={Alabama:"AL",Alaska:"AK","American Samoa":"AS",Arizona:"AZ",Arkansas:"AR",California:"CA",Colorado:"CO",Connecticut:"CT","District Of Columbia":"DC",Delaware:"DE","Federated States Of Micronesia":"FM",Florida:"FL",Georgia:"GA",Guam:"GU",Hawaii:"HI",Idaho:"ID",Illinois:"IL",Indiana:"IN",Iowa:"IA",Kansas:"KS",Kentucky:"KY",Louisiana:"LA",Maine:"ME","Marshall Islands":"MH",Maryland:"MD",Massachusetts:"MA",Michigan:"MI",Minnesota:"MN",Mississippi:"MS",Missouri:"MO",Montana:"MT",Nebraska:"NE",Nevada:"NV","New Hampshire":"NH","New Jersey":"NJ","New Mexico":"NM","New York":"NY","North Carolina":"NC","North Dakota":"ND","Northern Mariana Islands":"MP",Ohio:"OH",Oklahoma:"OK",Oregon:"OR",Palau:"PW",Pennsylvania:"PA","Puerto Rico":"PR","Rhode Island":"RI","South Carolina":"SC","South Dakota":"SD",Tennessee:"TN",Texas:"TX",Utah:"UT",Vermont:"VT","Virgin Islands":"VI",Virginia:"VA",Washington:"WA","West Virginia":"WV",Wisconsin:"WI",Wyoming:"WY",Alberta:"AB","British Columbia":"BC",Manitoba:"MB","New Brunswick":"NB","Newfoundland and Labrador":"NL","Northwest Territories":"NT","Nova Scotia":"NS",Nunavut:"NU",Ontario:"ON","Prince Edward Island":"PE",Quebec:"QC",Saskatchewan:"SK",Yukon:"YT"};PF.StateList=["AL","AK","AZ","AR","CA","CO","CT","DC","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"];PF.scrollToTop=function(){document.body.scrollTop!=0||document.documentElement.scrollTop!=0?(window.scrollBy(0,-50),timeOut=setTimeout("PF.scrollToTop()",10)):clearTimeout(timeOut)};PF.DepositChargeMode={Percent:0,Dollar:1};PF.SnippetViewType={List:"list",Calendar:"calendar",Goods:"goods",GoodsGrid:"goods-grid",Details:"details"};PF.ListingType={Space:0,GiftCard:2,Good:4};CustomerLead=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.firstName=ko.observable();this.lastName=ko.observable();this.address1=ko.observable();this.address2=ko.observable();this.city=ko.observable();this.country=ko.observable();this.organizationName=ko.observable();this.phone=ko.observable();this.stateOrProvince=ko.observable();this.dateCreated=ko.observable();this.externalWebsiteUrl=ko.observable();this.source=ko.observable();this.email=ko.observable();this.note=ko.observable();this.blacklistDate=ko.observable();this.blacklistReason=ko.observable();this.user=ko.observable();this.tags=ko.observableArray();this.preferredContactTime=ko.observable("9:00");this.preferredContactDay=ko.observable("Monday");this.preferredContactTimeZone=ko.observable("PST");this.hasPreferredContactTime=ko.observable("no");this.customGroups=ko.observableArray();this.fullName=ko.computed(function(){return(t.firstName()?t.firstName():"")+" "+(t.lastName()?t.lastName():"")});n&&this.update(n)};ko.utils.extend(CustomerLead.prototype,{update:function(n){n=n||{};this.id(n.id);this.firstName(n.firstName);this.lastName(n.lastName);this.address1(n.address1||"");this.address2(n.address2||"");this.city(n.city);this.country(n.country);this.email(n.email);this.organizationName(n.organizationName);this.phone(n.phone);this.stateOrProvince(n.stateOrProvince);this.dateCreated(n.dateCreated);this.blacklistDate(n.blacklistDate);this.blacklistReason(n.blacklistReason);this.externalWebsiteUrl(n.externalWebsiteUrl);this.source(n.source);this.note(n.note);this.user(n.user);this.preferredContactTime(n.preferredContactTime);this.preferredContactDay(n.preferredContactDay);this.preferredContactTimeZone(n.preferredContactTimeZone);this.customGroups(n.customGroups);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,firstName:n.FirstName,lastName:n.LastName,address1:n.AddressLine1,address2:n.AddressLine2,city:n.City,country:n.Country,email:n.Email,organizationName:n.OrganizationName,phone:n.PhoneNumber,stateOrProvince:n.StateOrProvince,dateCreated:n.DateCreated,externalWebsiteUrl:n.ExternalWebSiteURL,source:n.Source,note:n.Note,blacklistDate:n.EmailBlackListDate,blacklistReason:n.EmailBlackListReason,preferredContactTime:n.PreferredContactTime,preferredContactTimeZone:n.PreferredContactTimeZone};return n.User&&(t.user=(new User).fromServerModel(n.User)),n.CustomGroups&&(t.customGroups=n.CustomGroups.map(function(n){return(new CustomGroup).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),FirstName:this.firstName(),LastName:this.lastName(),AddressLine1:this.address1(),AddressLine2:this.address2(),City:this.city(),Country:this.country(),Email:this.email(),OrganizationName:this.organizationName(),PhoneNumber:this.phone(),StateOrProvince:this.stateOrProvince(),DateCreated:this.dateCreated(),ExternalWebSiteURL:this.externalWebsiteUrl(),Source:this.source(),Note:this.note(),EmailBlackListDate:this.blacklistDate(),EmailBlackListReason:this.blacklistReason(),PreferredContactTime:this.hasPreferredContactTime()==="yes"?this.preferredContactTime():"N/A",PreferredContactDay:this.hasPreferredContactTime()==="yes"?this.preferredContactDay():"N/A",PreferredContactTimeZone:this.hasPreferredContactTime()==="yes"?this.preferredContactTimeZone():"N/A"};return this.user()&&(n.User=this.user().toServerModel()),this.customGroups()&&(n.CustomGroups=this.customGroups().map(function(n){return n.toServerModel()})),n}});CustomGroup=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.name=ko.observable();this.account_Id=ko.observable();this.totalLeads=ko.observable();this.emailNotifications=ko.observableArray();this.spaces=ko.observableArray();this.users=ko.observableArray();this.customerLeads=ko.observableArray();this.sendToAllCustomers=ko.observable(!1);this.users=ko.observableArray();n&&this.update(n)};ko.utils.extend(CustomGroup.prototype,{update:function(n){n=n||{};this.id(n.id);this.name(n.name);this.account_Id(n.account_Id);this.totalLeads(n.totalLeads);this.spaces(ko.utils.unwrapObservable(n.spaces)||[]);this.users(ko.utils.unwrapObservable(n.users)||[]);this.customerLeads(ko.utils.unwrapObservable(n.customerLeads)||[]);this.sendToAllCustomers(n.sendToAllCustomers);this.emailNotifications(ko.utils.unwrapObservable(n.emailNotifications)||[]);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,name:n.Name,account_Id:n.Account_Id,totalLeads:n.TotalLeads,sendToAllCustomers:n.SendToAllPlaceFullCustomers};return n.Spaces&&(t.spaces=n.Spaces.map(function(n){return(new Space).fromServerModel(n)})),n.Users&&(t.users=n.Users.map(function(n){return(new User).fromServerModel(n)})),n.CustomerLeads&&(t.customerLeads=n.CustomerLeads.map(function(n){return(new CustomerLead).fromServerModel(n)})),n.EmailNotifications&&(t.emailNotifications=n.EmailNotifications.map(function(n){return(new EmailNotification).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Name:this.name(),Account_Id:this.account_Id(),SendToAllPlaceFullCustomers:this.sendToAllCustomers()};return this.spaces()&&(n.Spaces=this.spaces().map(function(n){return n.toServerModel()})),this.users()&&(n.Users=this.users().map(function(n){return n.toServerModel()})),this.customerLeads()&&(n.CustomerLeads=this.customerLeads().map(function(n){return n.toServerModel()})),this.emailNotifications()&&(n.EmailNotifications=this.emailNotifications().map(function(n){return n.toServerModel()})),n}});DriversLicense=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.licenseNumber=ko.observable();t.expiry=ko.observable();t.givenNames=ko.observable();t.lastName=ko.observable();t.address=ko.observable();t.city=ko.observable();t.state=ko.observable();t.country=ko.observable();t.birthDate=ko.observable();t.zipCode=ko.observable();t.user_Id=ko.observable();t.rawData=ko.observable();t.scanData=ko.observable();t.console=ko.observable();t.scan=ko.observable(!1);t.parseCallback=null;t.scanStartTime=ko.observable();t.scanTimeOut=null;t.scanStartTime.subscribe(function(n){n&&(clearTimeout(t.scanTimeOut),t.scanTimeOut=setTimeout(t.parseScanData,300))});t.over21=ko.computed(function(){if(t.birthDate()){var n=PF.Moment(t.birthDate(),["MM DD YY","MM DD YYYY","MMDDYYYY","YYYYMMDD"]);return n.isValid()?n.add(21,"years").isBefore(new Date):!1}});t.birthDatePretty=ko.computed(function(){if(t.birthDate()){var n=PF.Moment(t.birthDate(),["MM DD YY","MM DD YYYY","MMDDYYYY","YYYYMMDD"]);return n.isValid()?n.format("MMMM D YYYY"):t.birthDate()}});t.validate=function(){return t.givenNames()&&t.lastName()&&t.address()&&t.state()&&t.city()&&t.licenseNumber()&&t.birthDate()?!0:!1};t.parseScanData=function(){var i,r,n;t.scanData()&&(t.rawData(t.scanData()),i=t.scanData().split("\n"),$.each(i,function(n,i){if(i&&i.length>0&&(i=i.trim()),i.indexOf("DCS")===0&&t.lastName(i.substring(3,i.length)),i.indexOf("DCT")===0&&t.givenNames(i.substring(3,i.length)),i.indexOf("DAG")===0&&t.address(i.substring(3,i.length)),i.indexOf("DAI")===0&&t.city(i.substring(3,i.length)),i.indexOf("DAJ")===0&&t.state(i.substring(3,i.length)),i.indexOf("DAK")===0&&t.zipCode(i.substring(3,i.length)),i.indexOf("DCG")===0&&t.country(i.substring(3,i.length)),i.indexOf("DBB")===0&&t.birthDate(i.substring(3,i.length)),i.indexOf("DBA")===0&&t.expiry(i.substring(3,i.length)),i.indexOf("DAQ")===0&&t.licenseNumber(i.substring(3,i.length)),i.indexOf("DAA")===0){var r=i.substring(3,i.length).split(",");r&&r.length==2&&(t.lastName(r[0].trim()),t.givenNames(r[1].trim()))}i.indexOf("DAL")===0&&t.address(i.substring(3,i.length));i.indexOf("DAN")===0&&t.city(i.substring(3,i.length));i.indexOf("DAO")===0&&t.state(i.substring(3,i.length));i.indexOf("DAP")===0&&t.zipCode(i.substring(3,i.length));i.indexOf("DBB")===0&&t.birthDate(i.substring(3,i.length));i.indexOf("DBA")===0&&t.expiry(i.substring(3,i.length));i.indexOf("DAQ")===0&&t.licenseNumber(i.substring(3,i.length))}),t.lastName()||(r=i[1],n=r.split("DCS"),n!=null&&t.lastName(n[n.length-1])),t.scan(!1),t.scanStartTime(null),t.scanData(null),t.parseCallback&&t.parseCallback())};n&&this.update(n)};ko.utils.extend(DriversLicense.prototype,{update:function(n){n=n||{};this.id(n.id);this.licenseNumber(n.licenseNumber);this.expiry(n.expiry);this.givenNames(n.givenNames);this.lastName(n.lastName);this.address(n.address);this.city(n.city);this.state(n.state);this.country(n.country);this.zipCode(n.zipCode);this.birthDate(n.birthDate);this.user_Id(n.user_Id);this.scan(n.scan);this.scanData(n.scanData);this.rawData(n.rawData);this.scanStartTime(n.scanStartTime);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id};return this.update(t),this},toServerModel:function(){var n=new JSEncrypt;return n.setPublicKey(PF.PublicKey2048),{Id:this.id(),LicenseNumber:this.licenseNumber()?n.encrypt(this.licenseNumber()):null,ExpiryDate:this.expiry()?n.encrypt(this.expiry()):null,LastName:this.lastName(),GivenNames:this.givenNames(),Address:this.address(),City:this.city(),State:this.state(),Country:this.country(),BirthDate:this.birthDate()?n.encrypt(this.birthDate()):null,User_Id:this.user_Id(),PostalOrZipCode:this.zipCode()}}});EmailNotification=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.campaign=ko.observable();t.fromName=ko.observable();t.fromEmail=ko.observable();t.to=ko.observable();t.subject=ko.observable();t.template=ko.observable();t.seq=ko.observable();t.type=ko.observable();t.timeBetweenSeq=ko.observable();t.sendHour=ko.observable();t.sendDelay=ko.observable();t.dateCreated=ko.observable();t.accountId=ko.observable();t.dayOfWeek=ko.observable();t.description=ko.observable();t.siteProperty=ko.observable();t.objectType=ko.observable();t.mandrill=ko.observable();t.isDeleted=ko.observable();t.emailNotificationDetail=ko.observable();t.customGroups=ko.observableArray();t.sendDelayInDays=ko.computed({read:function(){return this.sendDelay()&&this.sendDelay()<0?this.sendDelay()/-1440:this.sendDelay()?this.sendDelay()/1440:0},write:function(n){if(this.sendDelay()&&this.sendDelay()<0)return this.sendDelay(n*-1440);this.sendDelay(n*1440)},owner:this});t.listingsInGroups=ko.computed({read:function(){var n=ko.observableArray();return t.customGroups()&&typeof t.customGroups()!="undefined"&&t.customGroups().length>0&&$.each(t.customGroups(),function(t,i){i.spaces().map(function(t){n.push(t)})}),n().length==0&&n.push({name:"No Listings Found in Email Groups"}),n()}});t.totalLeads=ko.computed({read:function(){var n=0;return t.customGroups()&&typeof t.customGroups()!="undefined"&&$.each(t.customGroups(),function(t,i){n+=i.totalLeads()}),n}});t.sendTimingDescribed=ko.computed({read:function(){var r=t.sendHour()?" at ~"+t.sendHour()+":00 PST":"",i="Sent immediately",n;return t.sendDelay()&&!t.timeBetweenSeq()&&(i=t.sendDelay()>480?"Sent "+t.sendDelay()/1440+" days delayed"+r:"Sent "+t.sendDelay()+" minutes delayed"+r),t.timeBetweenSeq()&&(i=t.timeBetweenSeq()>480?"Sent "+t.timeBetweenSeq()/1440+" days later":"Sent "+t.timeBetweenSeq()+" minutes later"),r!=""&&(i=t.timeBetweenSeq()?i+r:"Only "+r),typeof t.dayOfWeek()!="undefined"&&t.dayOfWeek()!=null&&(n=new Array(7),n[0]="Sunday",n[1]="Monday",n[2]="Tuesday",n[3]="Wednesday",n[4]="Thursday",n[5]="Friday",n[6]="Saturday",i=r!=""?i+" on "+n[t.dayOfWeek()]:"Only on "+n[t.dayOfWeek()]),i}});n&&this.update(n)};ko.utils.extend(EmailNotification.prototype,{update:function(n){n=n||{};this.id(n.id);this.campaign(n.campaign);this.fromName(n.fromName);this.fromEmail(n.fromEmail);this.to(n.to);this.subject(n.subject);this.template(n.template);this.seq(n.seq);this.type(n.type);this.timeBetweenSeq(n.timeBetweenSeq);this.sendHour(n.sendHour);this.sendDelay(n.sendDelay);this.dayOfWeek(n.dayOfWeek);this.description(n.description);this.siteProperty(n.siteProperty);this.objectType(n.objectType);this.mandrill(n.mandrill);this.dateCreated(n.dateCreated);this.accountId(n.accountId);this.isDeleted(n.isDeleted);n.emailNotificationDetail&&this.emailNotificationDetail(n.emailNotificationDetail);n.customGroups&&this.customGroups(n.customGroups);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,campaign:n.Campaign,fromName:n.FromName,fromEmail:n.FromEmail,to:n.To,subject:n.Subject,template:n.Template,seq:n.Seq,type:n.Type,timeBetweenSeq:n.TimeBetweenSeq,sendHour:n.SendHour,sendDelay:n.SendDelay,dayOfWeek:n.DayOfWeek,description:n.Description,objectType:n.ObjectType,mandrill:n.Mandrill,dateCreated:n.DateCreated,accountId:n.Account_Id,isDeleted:n.isDeleted};return n.EmailNotificationDetail&&(t.emailNotificationDetail=(new EmailNotificationDetail).fromServerModel(n.EmailNotificationDetail)),n.CustomGroups&&(t.customGroups=n.CustomGroups.map(function(n){return(new CustomGroup).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Campaign:this.campaign(),FromName:this.fromName(),FromEmail:this.fromEmail(),To:this.to(),Subject:this.subject(),Template:this.template(),Seq:this.seq(),Type:this.type(),TimeBetweenSeq:this.timeBetweenSeq(),SendHour:this.sendHour(),SendDelay:this.sendDelay(),DayOfWeek:this.dayOfWeek(),Description:this.description(),ObjectType:this.objectType(),Mandrill:this.mandrill(),DateCreated:this.dateCreated(),Account_Id:this.accountId(),IsDeleted:this.isDeleted()};return this.emailNotificationDetail()&&(n.EmailNotificationDetail=this.emailNotificationDetail().toServerModel()),this.customGroups()&&(n.CustomGroups=this.customGroups().map(function(n){return n.toServerModel()})),n}});EmailNotificationDetail=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.bodyText=ko.observable();t.ctr=ko.observable();t.clicks=ko.observable();t.earliestDate=ko.observable();t.latestDate=ko.observable();t.hardBounces=ko.observable();t.openRate=ko.observable();t.opens=ko.observable();t.rejects=ko.observable();t.softBounces=ko.observable();t.spamComplaints=ko.observable();t.totalEmailsAggregated=ko.observable();t.unsubs=ko.observable();t.emailTriggerType=ko.observable();t.singleDate=ko.observable();t.dateSent=ko.computed({read:function(){return t.singleDate()?t.singleDate():"Never"}});t.singleDatePretty=ko.computed({read:function(){return t.singleDate()?PF.formatDate(t.singleDate()):PF.formatDate(new Date)},write:function(n){t.singleDate(PF.parseMVCDate(n))},owner:this});n&&this.update(n)};ko.utils.extend(EmailNotificationDetail.prototype,{update:function(n){n=n||{};this.id(n.id);this.bodyText(n.bodyText);this.ctr(n.ctr);this.clicks(n.clicks);this.earliestDate(n.earliestDate);this.latestDate(n.latestDate);this.hardBounces(n.hardBounces);this.openRate(n.openRate);this.opens(n.opens);this.rejects(n.rejects);this.softBounces(n.softBounces);this.spamComplaints(n.spamComplaints);this.totalEmailsAggregated(n.totalEmailsAggregated);this.unsubs(n.unsubs);this.singleDate(n.singleDate);this.emailTriggerType(n.emailTriggerType);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,bodyText:n.BodyText,ctr:n.CTR,clicks:n.Clicks,earliestDate:n.EarliestEmailDateInStats,latestDate:n.LatestEmailDateInStats,hardBounces:n.HardBounces,openRate:n.OpenRate,opens:n.Opens,rejects:n.Rejects,softBounces:n.SoftBounces,spamComplaints:n.SpamComplaints,totalEmailsAggregated:n.TotalEmailsAggregatedForStats,unsubs:n.UnSubs,singleDate:n.SingleDate,emailTriggerType:n.EmailTriggerType};return this.update(t),this},toServerModel:function(){return{Id:this.id(),BodyText:this.bodyText(),EmailTriggerType:this.emailTriggerType(),SingleDate:this.singleDate()}}});GeoVariable=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.category=ko.observable();this.defaultRegion=ko.observable();this.order=ko.observable();this.spaceName=ko.observable();this.imageUrl=ko.observable();this.linkUrl=ko.observable();this.titleCaption=ko.observable();this.description=ko.observable();this.spaceId=ko.observable();n&&this.update(n)};ko.utils.extend(GeoVariable.prototype,{update:function(n){n=n||{};this.id(n.id);this.category(n.category);this.defaultRegion(n.defaultRegion);this.order(n.order);this.spaceName(n.spaceName);this.imageUrl(n.imageUrl);this.linkUrl(n.linkUrl);this.titleCaption(n.titleCaption);this.description(n.description);this.spaceId(n.spaceId);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,category:n.Category,defaultRegion:n.DefaultRegion,order:n.Order,spaceName:n.SpaceNameOverride,imageUrl:n.ImageURL,linkUrl:n.LinkUrl,titleCaption:n.TitleCaption,description:n.Description,spaceId:n.Space_Id};return this.update(t),this},toServerModel:function(){var n={Id:this.id(),Category:this.category(),DefaultRegion:this.defaultRegion(),Order:this.order(),SpaceNameOverride:this.spaceName(),ImageURL:this.imageUrl(),LinkUrl:this.linkUrl(),TitleCaption:this.titleCaption(),Description:this.description()};return this.spaceId()&&(n.Space={Id:this.spaceId()}),n}});Good=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.name=ko.observable();t.description=ko.observable();t.account=ko.observable();t.dateCreated=ko.observable();t.status=ko.observable();t.defaultVariant=ko.observable();n&&this.update(n)};ko.utils.extend(Good.prototype,{update:function(n){n=n||{};this.id(n.id);this.name(n.name);this.description(n.description);this.account(n.account);this.dateCreated(n.dateCreated);this.status(n.status);this.defaultVariant(n.defaultVariant);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,name:n.Name,description:n.Description,dateCreated:n.DateCreated,status:n.Status};return n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.DefaultVariant&&(t.defaultVariant=(new GoodVariant).fromServerModel(n.DefaultVariant)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Name:this.name(),Description:this.description(),Status:this.status()};return this.account()&&(n.Account=this.account().toServerModel()),this.defaultVariant()&&(n.DefaultVariant=this.defaultVariant().toServerModel()),n}});GoodAttribute=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.name=ko.observable();n&&this.update(n)};ko.utils.extend(GoodAttribute.prototype,{update:function(n){n=n||{};this.id(n.id);this.name(n.name)},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,name:n.Name};return this.update(t),this},toServerModel:function(){return{Id:this.id(),Name:this.name()}}});GoodImage=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.order=ko.observable();t.goodVariantId=ko.observable();t.fileName=ko.observable();t.fileURL=ko.observable();t.imageTitle=ko.observable();t.imageDescription=ko.observable();n&&this.update(n)};ko.utils.extend(GoodImage.prototype,{update:function(n){n=n||{};this.id(n.id);this.order(n.order);this.goodVariantId(n.goodVariantId);this.fileName(n.fileName);this.fileURL(n.fileURL);this.imageTitle(n.imageTitle);this.imageDescription(n.imageDescription);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,order:n.Order,goodVariantId:n.GoodVariant_Id,fileName:n.FileName,fileURL:n.FileURL,imageTitle:n.imageTitle,imageDescription:n.imageDescription};return this.update(t),this},toServerModel:function(){return{Id:this.id(),Order:this.order(),GoodVariant_Id:this.goodVariantId(),FileName:this.fileName(),FileURL:this.fileURL(),ImageTitle:this.imageTitle(),imageDescription:this.imageDescription()}}});GoodPurchase=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.goodVariant=ko.observable();t.goodVariantId=ko.observable();t.isOrderCompleted=ko.observable();t.recipientFirstName=ko.observable();t.recipientLastName=ko.observable();t.recipientEmail=ko.observable();t.recipientPhone=ko.observable();t.quantity=ko.observable();t.goodName=ko.observable();t.dateCreated=ko.observable();t.dateModified=ko.observable();t.account=ko.observable();t.accountId=ko.observable();t.customerConfirmationCode=ko.observable();t.isDeleted=ko.observable();t.taxRate=ko.observable();t.totalTaxes=ko.observable();t.total=ko.observable();t.userId=ko.observable();t.user=ko.observable();t.refundDate=ko.observable();t.totalBillingRefund=ko.observable();t.billings=ko.observableArray();t.additionalInfoGoodPurchases=ko.observableArray();t.totalBilled=ko.observable(0);t.errorMessage=ko.observable();n&&this.update(n);this.additionalInfoAnswered=ko.computed(function(){var n=[];return $.each(t.additionalInfoGoodPurchases(),function(t,i){i&&i.userResponse()&&i.userResponse().length>0&&n.push(i)}),n})};ko.utils.extend(GoodPurchase.prototype,{update:function(n){n=n||{};this.id(n.id);this.goodVariant(n.goodVariant);this.goodVariantId(n.goodVariantId);this.isOrderCompleted(n.isOrderCompleted);this.recipientFirstName(n.recipientFirstName);this.recipientLastName(n.recipientLastName);this.recipientEmail(n.recipientEmail);this.recipientPhone(n.recipientPhone);this.quantity(n.quantity);this.goodName(n.goodName);this.dateCreated(n.dateCreated);this.dateModified(n.dateModified);this.account(n.account);this.accountId(n.accountId);this.customerConfirmationCode(n.customerConfirmationCode);this.isDeleted(n.isDeleted);this.taxRate(n.taxRate);this.totalTaxes(n.totalTaxes);this.total(n.total);this.userId(n.userId);this.user(n.user);this.refundDate(n.refundDate);this.totalBillingRefund(n.totalBillingRefund);n.additionalInfoGoodPurchases&&this.additionalInfoGoodPurchases(n.additionalInfoGoodPurchases);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,goodVariantId:n.GoodVariant_Id,isOrderCompleted:n.IsOrderCompleted,recipientFirstName:n.RecipientFirstName,recipientLastName:n.RecipientLastName,recipientEmail:n.RecipientEmail,recipientPhone:n.RecipientPhone,quantity:n.Quantity,goodName:n.GoodName,dateCreated:n.DateCreated,dateModified:n.DateModified,accountId:n.Account_Id,customerConfirmationCode:n.CustomerConfirmationCode,isDeleted:n.IsDeleted,taxRate:n.TaxRate,totalTaxes:n.TotalTaxes,total:n.Total,userId:n.User_Id,refundDate:n.RefundDate,totalBillingRefund:n.TotalBillingRefund};return n.GoodVariant&&(t.goodVariant=(new GoodVariant).fromServerModel(n.GoodVariant)),n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.User&&(t.user=(new User).fromServerModel(n.User)),n.AdditionalInfoGoodPurchases&&(t.additionalInfoGoodPurchases=n.AdditionalInfoGoodPurchases.map(function(n){return(new AdditionalInfoGoodPurchase).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),GoodVariant_Id:this.goodVariantId(),IsOrderCompleted:this.isOrderCompleted(),RecipientFirstName:this.recipientFirstName(),RecipientLastName:this.recipientLastName(),RecipientEmail:this.recipientEmail(),RecipientPhone:this.recipientPhone(),Quantity:this.quantity(),GoodName:this.goodName(),DateCreated:this.dateCreated(),DateModified:this.dateModified(),Account_Id:this.accountId(),CustomerConfirmationCode:this.customerConfirmationCode(),IsDeleted:this.isDeleted(),TaxRate:this.taxRate(),TotalTaxes:this.totalTaxes(),Total:this.total(),User_Id:this.userId(),RefundDate:this.refundDate(),TotalBillingRefund:this.totalBillingRefund()};return this.goodVariant()&&(n.GoodVariant=this.goodVariant().toServerModel()),this.account()&&(n.Account=this.account().toServerModel()),this.user()&&(n.User=this.user().toServerModel()),this.additionalInfoGoodPurchases()&&(n.AdditionalInfoGoodPurchases=this.additionalInfoGoodPurchases().map(function(n){return n.toServerModel()})),n}});GoodVariant=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.dateCreated=ko.observable();t.status=ko.observable();t.goodId=ko.observable();t.price=ko.observable();t.taxable=ko.observable();t.sku=ko.observable();t.additionalInfoGoodVariants=ko.observableArray();t.inventory=ko.observable();t.attributes=ko.observableArray();t.images=ko.observableArray();n&&this.update(n)};ko.utils.extend(GoodVariant.prototype,{update:function(n){n=n||{};this.id(n.id);this.dateCreated(n.dateCreated);this.status(n.status);this.goodId(n.goodId);this.price(n.price);this.taxable(n.taxable);this.sku(n.sku);this.additionalInfoGoodVariants(n.additionalInfoGoodVariants);this.inventory(n.inventory);this.attributes(n.attributes);this.images(n.images);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,dateCreated:n.DateCreated,status:n.Status,goodId:n.Good_Id,price:n.Price,taxable:n.Taxable,sku:n.Sku,inventory:n.Inventory};return n.Attributes&&n.Attributes.length>0&&(t.attributes=n.Attributes.map(function(n){return(new GoodAttribute).fromServerModel(n)})),n.Images&&n.Images.length>0&&(t.images=n.Images.map(function(n){return(new GoodImage).fromServerModel(n)})),n.AdditionalInfoGoodVariants&&n.AdditionalInfoGoodVariants.length>0&&(t.additionalInfoGoodVariants=n.AdditionalInfoGoodVariants.map(function(n){return(new AdditionalInfoGoodVariant).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Status:this.status(),Good_Id:this.goodId(),Price:this.price(),Taxable:this.taxable(),Sku:this.sku(),Inventory:this.inventory()};return this.attributes()&&(n.Attributes=this.attributes().map(function(n){return n.toServerModel()})),this.images()&&(n.Images=this.images().map(function(n){return n.toServerModel()})),this.images()&&(n.Images=this.images().map(function(n){return n.toServerModel()})),this.additionalInfoGoodVariants()&&(n.AdditionalInfoGoodVariants=this.additionalInfoGoodVariants().map(function(n){return n.toServerModel()})),n}});Gratuity=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.dateCreated=ko.observable();t.dateModified=ko.observable();t.account_Id=ko.observable();t.customerConfirmationCode=ko.observable();t.isDeleted=ko.observable();t.total=ko.observable();t.billings=ko.observableArray([]);t.user_Id=ko.observable();t.amount=ko.observable();t.gratuityType=ko.observable();n&&this.update(n)};ko.utils.extend(Gratuity.prototype,{update:function(n){n=n||{};this.id(n.id);this.dateCreated(n.dateCreated);this.dateModified(n.dateModified);this.account_Id(n.account_Id);this.customerConfirmationCode(n.customerConfirmationCode);this.isDeleted(n.isDeleted);this.total(n.total);this.billings(n.billings);this.user_Id(n.user_Id);this.amount(n.amount);this.gratuityType(n.gratuityType);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,dateCreated:n.DateCreated,dateModified:n.DateModified,account_Id:n.Account_Id,customerConfirmationCode:n.CustomerConfirmationCode,isDeleted:n.IsDeleted,total:n.Total,billings:n.Billings,user_Id:n.User_Id,amount:n.Amount,gratuityType:n.GratuityType};return this.update(t),this},toServerModel:function(){return{Id:this.id(),DateCreated:this.dateCreated(),DateModified:this.dateModified(),Account_Id:this.account_Id(),CustomerConfirmationCode:this.customerConfirmationCode(),IsDeleted:this.isDeleted(),Total:this.total(),Billings:this.billings(),User_Id:this.user_Id(),Amount:this.amount(),GratuityType:this.gratuityType()}}});GratuityOptionsByAccount=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.dateCreated=ko.observable();t.dateModified=ko.observable();t.account=ko.observable();t.account_Id=ko.observable();t.enabled=ko.observable();t.gratuityType=ko.observable();t.amountOption1=ko.observable();t.amountOption2=ko.observable();t.amountOption3=ko.observable();n&&this.update(n)};ko.utils.extend(GratuityOptionsByAccount.prototype,{update:function(n){n=n||{};this.id(n.id);this.dateCreated(n.dateCreated);this.dateModified(n.dateModified);this.account(n.account);this.account_Id(n.account_Id);this.enabled(n.enabled);this.gratuityType(n.gratuityType);this.amountOption1(n.amountOption1);this.amountOption2(n.amountOption2);this.amountOption3(n.amountOption3);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,dateCreated:n.DateCreated,dateModified:n.DateModified,account:n.Account,account_Id:n.Account_Id,enabled:n.Enabled,gratuityType:n.GratuityType,amountOption1:n.AmountOption1,amountOption2:n.AmountOption2,amountOption3:n.AmountOption3};return this.update(t),this},toServerModel:function(){return{Id:this.id(),DateCreated:this.dateCreated(),DateModified:this.dateModified(),Account:this.account(),Account_Id:this.account_Id(),Enabled:this.enabled()===0||this.enabled()==="0"?!1:!0,GratuityType:this.gratuityType(),AmountOption1:this.amountOption1(),AmountOption2:this.amountOption2(),AmountOption3:this.amountOption3()}}});Listing=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.account=ko.observable();t.accountId=ko.observable();t.listingType=ko.observable();t.objectId=ko.observable();t.isDeleted=ko.observable();t.description=ko.observable();t.isActive=ko.observable();t.dateCreated=ko.observable();t.condensedName=ko.observable();t.name=ko.observable();t.listingCategories=ko.observableArray();t.isPublished=function(n){return t.listingCategories()&&(arr=$.grep(t.listingCategories(),function(t){return t.condensedName==n}),arr.length>0)?!0:!1};n&&this.update(n)};ko.utils.extend(Listing.prototype,{update:function(n){n=n||{};this.id(n.id);this.account(n.account);this.accountId(n.accountId);this.listingType(n.listingType);this.objectId(n.objectId);this.description(n.description);this.isActive(n.isActive);this.isDeleted(n.isDeleted);this.name(n.name);this.condensedName(n.condensedName);this.dateCreated(n.dateCreated);this.listingCategories(n.listingCategories);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,accountId:n.Account_Id,name:n.Name,listingType:n.ListingType,objectId:n.Object_Id,description:n.Description,isActive:n.IsActive,isDeleted:n.IsDeleted,dateCreated:n.DateCreated,condensedName:n.CondensedName};return n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.ListingCategories&&(t.listingCategories=n.ListingCategories.map(function(n){return(new ListingCategory).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Account_Id:this.accountId(),ListingType:this.listingType(),Object_Id:this.objectId(),IsActive:this.isActive(),IsDeleted:this.isDeleted(),CondensedName:this.condensedName(),Description:this.description(),Name:this.name()};return this.listingCategories()&&(n.ListingCategories=this.listingCategories().map(function(n){return n.toServerModel()})),n}});ListingCategory=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.account=ko.observable();t.accountId=ko.observable();t.name=ko.observable();t.isVisibleToUser=ko.observable();t.description=ko.observable();t.dateCreated=ko.observable();t.condensedName=ko.observable();t.listings=ko.observableArray();t.checked=ko.observable();n&&this.update(n)};ko.utils.extend(ListingCategory.prototype,{update:function(n){n=n||{};this.id(n.id);this.account(n.account);this.accountId(n.accountId);this.name(n.name);this.isVisibleToUser(n.isVisibleToUser);this.description(n.description);this.condensedName(n.condensedName);this.dateCreated(n.dateCreated);this.listings(n.listings);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,accountId:n.Account_Id,name:n.Name,isVisibleToUser:n.IsVisibleToUser,description:n.Description,dateCreated:n.DateCreated,condensedName:n.CondensedName};return n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.Listings&&(t.listings=n.Listings.map(function(n){return(new Listing).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Account_Id:this.accountId(),Name:this.name(),IsVisibleToUser:this.isVisibleToUser(),CondensedName:this.condensedName(),Description:this.description()};return this.listings()&&(n.Listings=this.listings().map(function(n){return n.toServerModel()})),n}});Log=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.level=ko.observable();this.message=ko.observable();this.attribute=ko.observable();this.attribute2=ko.observable();this.date=ko.observable();this.exception=ko.observable();this.url=ko.observable();this.userId=ko.observable();n&&this.update(n)};ko.utils.extend(Log.prototype,{update:function(n){n=n||{};this.id(n.id);this.message(n.message);this.level(n.level);this.attribute(n.attribute);this.attribute2(n.attribute2);this.date(n.date);this.exception(n.exception);this.url(n.url);this.userId(n.userId);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,message:n.Message,level:n.Level,exception:n.ExceptionMessage,date:n.LogDate,attribute:n.Attribute,attribute2:n.Attribute2,url:n.RequestUrl,userId:n.UserId};return this.update(t),this},toServerModel:function(){return{Id:this.id()}}});Module=function(n){var t=this;this.dateCreated=ko.observable();this.dateModified=ko.observable();this.id=ko.observable();this.name=ko.observable();this.description=ko.observable();this.enabled=ko.observable();n&&this.update(n)};ko.utils.extend(Module.prototype,{update:function(n){n=n||{};this.name(n.name);this.dateCreated(n.dateCreated);this.dateModified(n.dateModified);this.id(n.id);this.description(n.description);this.enabled(n.enabled)},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,dateCreated:n.DateCreated,dateModified:n.DateModified,name:n.Name,description:n.Description,enabled:n.Enabled};return this.update(t),this},toServerModel:function(){return{Id:this.id(),Enabled:this.enabled(),Name:this.name(),Description:this.description()}}});ModuleOption=function(n){var t=this;this.dateCreated=ko.observable();this.dateModified=ko.observable();this.id=ko.observable();this.moduleId=ko.observable();this.limit=ko.observable();this.module=ko.observable();this.name=ko.observable();this.description=ko.observable();n&&this.update(n)};ko.utils.extend(ModuleOption.prototype,{update:function(n){n=n||{};this.dateCreated(n.dateCreated);this.dateModified(n.dateModified);this.id(n.id);this.moduleId(n.moduleId);this.limit(n.limit);this.name(n.name);this.description(n.description);n.module&&(this.module=n.module)},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,dateCreated:n.DateCreated,dateModified:n.DateModified,moduleId:n.Module_Id,limit:n.Limit,name:n.Name,description:n.Description};return n.Module&&(t.module=(new Module).fromServerModel(n.Module)),this.update(t),this},toServerModel:function(){return{Id:this.id(),Limit:this.limit(),Name:this.name(),Description:this.description(),Module_Id:this.moduleId()}}});PaymentInstrument=function(n){var t=this;t.cache=function(){};this.firstName=ko.observable();this.lastName=ko.observable();this.email=ko.observable();this.phone=ko.observable();this.accountNumber=ko.observable().extend({maskCreditCardDigits:"*"});this.accountNumber.masked=ko.observable();this.expiry=ko.observable();this.cvv=ko.observable();this.zipCode=ko.observable();this.discount=ko.observable();this.totalOverride=ko.observable();this.address=ko.observable();this.city=ko.observable();this.stateOrProvince=ko.observable();this.country=ko.observable();this.paymentType=ko.observable(PF.PaymentType.CreditCard_Funding);this.swipe=!1;this.swipeData;this.swipeStartTime;this.lastFour=ko.computed(function(){return t.accountNumber()?t.accountNumber().substring(t.accountNumber().length-4,t.accountNumber().length):""});this.anonymousLastFour=ko.computed(function(){return t.lastFour()?"**** **** **** "+t.lastFour():""});this.isAmex=ko.computed(function(){if(t.accountNumber()){var n=t.accountNumber().charAt(0);if(n==3)return!0}return!1});this.expiryMonth=ko.computed({read:function(){return t.expiry()?t.expiry().substr(0,2):null},write:function(n){n=n||"";n=n.toString();t.expiry()||t.expiry("0000");n.length>0?n.length===1&&(n="0"+n):n="00";t.expiry(n+t.expiry().substr(2,3))}});this.expiryYear=ko.computed({read:function(){return t.expiry()!=null?t.expiry().substr(2,3):null},write:function(n){n=n||"";n=n.toString();t.expiry()||t.expiry("0000");n.length>0?n.length===4&&(n=n.substr(2,3)):n="00";t.expiry(t.expiry().substr(0,2)+n)}});n&&this.update(n)};ko.utils.extend(PaymentInstrument.prototype,{update:function(n){n=n||{};this.firstName(n.firstName||"");this.lastName(n.lastName||"");this.expiry(n.expiry||"");this.cvv(n.cvv||"");this.zipCode(n.zipCode||"");this.accountNumber(n.accountNumber||"");this.email(n.email||"");this.phone(n.phone||"");this.discount(n.discount||"");this.totalOverride(n.totalOverride||"");this.paymentType(n.paymentType||"");this.country(n.country||"US");this.swipe=n.swipe;this.swipeData=n.swipeData;this.swipeStartTime=n.swipeStartTime;this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},toServerModel:function(){return{Issuer:null,Number:this.accountNumber(),Cvc:this.cvv(),ExpirationMonth:this.expiryMonth(),ExpirationYear:this.expiryYear(),LastName:this.lastName(),FirstName:this.firstName(),AddressLine:null,City:null,StateOrProvince:null,PostalCode:this.zipCode(),PaymentType:this.paymentType(),AddressLine:this.address(),City:this.city(),Country:this.country(),StateOrProvince:this.stateOrProvince(),Email:this.email(),Phone:this.phone()}}});ko.extenders.maskCreditCardDigits=function(n,t){return n.subscribe(function(i){var r=i.replace(/(?!\s)[^A-Z](?=[^A-Z\n]{4,})/gmi,t);n.masked(r)}),n};PendingSubscription=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.invoiceNumber=ko.observable();this.bookingName=ko.observable();this.billingDate=ko.observable();this.paymentTypeDescription=ko.observable();this.paymentType=ko.observable();this.amount=ko.observable();this.booking_Id=ko.observable();this.goodPurchase_Id=ko.observable();n&&this.update(n)};ko.utils.extend(PendingSubscription.prototype,{update:function(n){n=n||{};this.id(n.id);this.invoiceNumber(n.invoiceNumber);this.bookingName(n.bookingName);this.billingDate(n.billingDate);this.paymentTypeDescription(n.paymentTypeDescription);this.paymentType(n.paymentType);this.amount(n.amount);this.booking_Id(n.booking_Id);this.goodPurchase_Id(n.goodPurchase_Id);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,invoiceNumber:n.InvoiceNumber,bookingName:n.BookingName,billingDate:n.BillingDate,paymentTypeDescription:n.PaymentTypeDescription,paymentType:n.PaymentType,amount:n.Amount,booking_Id:n.Booking_Id,goodPurchase_Id:n.GoodPurchase_Id};return this.update(t),this},toServerModel:function(){return null}});PromotionCode=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.discountCode=ko.observable();t.isUsed=ko.observable();t.isDeleted=ko.observable();t.dateCreated=ko.observable();t.numberOfTimesUsed=ko.observable();t.securityCode=ko.observable();t.initialValue=ko.observable();t.currentValue=ko.observable();t.promotionCodeGroup=ko.observable();n&&this.update(n)};ko.utils.extend(PromotionCode.prototype,{update:function(n){n=n||{};this.id(n.id);this.discountCode(n.discountCode);this.isUsed(n.isUsed);this.isDeleted(n.isDeleted);this.dateCreated(n.dateCreated);this.numberOfTimesUsed(n.numberOfTimesUsed);this.securityCode(n.securityCode);this.initialValue(n.initialValue);this.currentValue(n.currentValue);this.promotionCodeGroup(n.promotionCodeGroup);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,discountCode:n.DiscountCode,isUsed:n.IsUsed,isDeleted:n.IsDeleted,dateCreated:n.DateCreated,numberOfTimesUsed:n.NumberOfTimesUsed,securityCode:n.SecurityCode,initialValue:n.InitialValue,currentValue:n.CurrentValue};return n.PromotionCodeGroup&&(t.promotionCodeGroup=(new PromotionCodeGroup).fromServerModel(n.PromotionCodeGroup)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),DiscountCode:this.discountCode(),IsUsed:this.isUsed(),IsDeleted:this.isDeleted(),NumberOfTimesUsed:this.numberOfTimesUsed(),SecurityCode:this.securityCode(),InitialValue:this.initialValue(),CurrentValue:this.currentValue(),DateCreated:this.dateCreated()};return this.promotionCodeGroup()&&(n.PromotionCodeGroup=this.promotionCodeGroup().toServerModel()),n}});PromotionCodeGroup=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.name=ko.observable();t.description=ko.observable();t.discountMode=ko.observable(0);t.discountApplicationMode=ko.observable();t.discountValidationMode=ko.observable();t.discountAmount=ko.observable();t.usageType=ko.observable();t.dateCreated=ko.observable();t.startDate=ko.observable();t.endDate=ko.observable();t.maxUses=ko.observable();t.isDeleted=ko.observable();t.buyX=ko.observable();t.getY=ko.observable();t.applicableListingStartDate=ko.observable();t.applicableListingEndDate=ko.observable();t.usageModeRestrictor=ko.observable();t.isFranchisePromotion=ko.observable();t.account=ko.observable();t.spaces=ko.observableArray();t.addOnSpaces=ko.observableArray();t.promotionCodes=ko.observableArray();t.maxUses.subscribe(function(n){(n||n===""||n==0)&&t.usageType(undefined)});t.defaultName=ko.computed({read:function(){return!t.spaces()||t.spaces().length===0?"":"$"+t.discountAmount()+" non-smartfull promo for "+t.spaces()[0].name()}});t.discountText=ko.computed({read:function(){return(t.discountMode()==0?"$":"")+t.discountAmount()+(t.discountMode()==1?"%":"")}});t.readableStartDate=ko.computed({read:function(){return t.startDate()?PF.formatDate(t.startDate()):""},write:function(n){t.startDate(n)}});t.readableEndDate=ko.computed({read:function(){return t.endDate()?PF.formatDate(t.endDate()):""},write:function(n){t.endDate(n)}});t.readableApplicableListingStartDate=ko.computed({read:function(){return t.applicableListingStartDate()?PF.formatDate(t.applicableListingStartDate()):""},write:function(n){t.applicableListingStartDate(n)}});t.readableApplicableListingEndDate=ko.computed({read:function(){return t.applicableListingEndDate()?PF.formatDate(t.applicableListingEndDate()):""},write:function(n){t.applicableListingEndDate(n)}});t.spacesCountText=ko.computed({read:function(){var n="";switch(t.discountValidationMode()){case 0:case"0":n=t.spaces().length;break;case 1:case"1":n="Public";break;case 2:case"2":n="Private";break;case 3:case"3":n="All"}return n}});n&&this.update(n)};ko.utils.extend(PromotionCodeGroup.prototype,{update:function(n){n=n||{};this.id(n.id);this.name(n.name);this.description(n.description);this.discountMode(n.discountMode);this.discountApplicationMode(n.discountApplicationMode);this.discountValidationMode(n.discountValidationMode);this.discountAmount(n.discountAmount);this.usageType(n.usageType);this.dateCreated(n.dateCreated);this.startDate(n.startDate?n.startDate:"");this.endDate(n.endDate?n.endDate:"");this.maxUses(n.maxUses);this.isDeleted(n.isDeleted);this.buyX(n.buyX);this.getY(n.getY);this.applicableListingStartDate(n.applicableListingStartDate?n.applicableListingStartDate:"");this.applicableListingEndDate(n.applicableListingEndDate?n.applicableListingEndDate:"");this.usageModeRestrictor(n.usageModeRestrictor);this.isFranchisePromotion(n.isFranchisePromotion);this.promotionCodes(n.promotionCodes);this.account(n.account);this.spaces(ko.utils.unwrapObservable(n.spaces)||[]);this.addOnSpaces(ko.utils.unwrapObservable(n.addOnSpaces)||[]);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,name:n.Name,description:n.Description,discountMode:n.DiscountMode,discountApplicationMode:n.DiscountApplicationMode,discountValidationMode:n.DiscountValidationMode,discountAmount:n.DiscountAmount,usageType:n.UsageType,dateCreated:n.DateCreated,startDate:n.Account&&n.Account.TimeZone&&n.StartDate?PF.convertTimeZone(n.StartDate,n.Account.TimeZone):n.StartDate,endDate:n.Account&&n.Account.TimeZone&&n.EndDate?PF.convertTimeZone(n.EndDate,n.Account.TimeZone):n.EndDate,maxUses:n.MaxUses,isDeleted:n.IsDeleted,buyX:n.BuyX,getY:n.GetY,applicableListingStartDate:n.Account&&n.Account.TimeZone&&n.ApplicableListingStartDate?PF.convertTimeZone(n.ApplicableListingStartDate,n.Account.TimeZone):n.ApplicableListingStartDate,applicableListingEndDate:n.Account&&n.Account.TimeZone&&n.ApplicableListingEndDate?PF.convertTimeZone(n.ApplicableListingEndDate,n.Account.TimeZone):n.ApplicableListingEndDate,usageModeRestrictor:n.UsageModeRestrictor,isFranchisePromotion:n.IsFranchisePromotion};return n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.Spaces&&(t.spaces=n.Spaces.map(function(n){return(new Space).fromServerModel(n)})),n.AddOnSpaces&&(t.addOnSpaces=n.AddOnSpaces.map(function(n){return(new AddOnSpace).fromServerModel(n)})),n.PromotionCodes&&(t.promotionCodes=n.PromotionCodes.map(function(n){return(new PromotionCode).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Name:this.name(),Description:this.description(),DiscountMode:this.discountMode(),DiscountApplicationMode:this.discountApplicationMode(),DiscountValidationMode:this.discountValidationMode(),DiscountAmount:this.discountAmount(),UsageType:this.usageType(),DateCreated:this.dateCreated(),StartDate:this.startDate()&&PF.convertTimeZoneToUTC?PF.convertTimeZoneToUTC(this.startDate()):this.startDate(),EndDate:this.endDate()&&PF.convertTimeZoneToUTC?PF.convertTimeZoneToUTC(this.endDate()):this.endDate(),MaxUses:this.maxUses(),IsDeleted:this.isDeleted(),BuyX:this.buyX(),GetY:this.getY(),ApplicableListingStartDate:this.applicableListingStartDate()&&PF.convertTimeZoneToUTC?PF.convertTimeZoneToUTC(this.applicableListingStartDate()):this.applicableListingStartDate(),ApplicableListingEndDate:this.applicableListingEndDate()&&PF.convertTimeZoneToUTC?PF.convertTimeZoneToUTC(this.applicableListingEndDate()):this.applicableListingEndDate(),UsageModeRestrictor:this.usageModeRestrictor(),IsFranchisePromotion:this.isFranchisePromotion()};return this.account()&&(n.Account=this.account().toServerModel()),this.spaces()&&(n.Spaces=this.spaces().map(function(n){return n.toServerModel()})),this.addOnSpaces()&&(n.AddOnSpaces=this.addOnSpaces().map(function(n){return n.toServerModel()})),this.promotionCodes()&&(n.PromotionCodes=this.promotionCodes().map(function(n){return n.toServerModel()})),n}});GoodPurchaseRefundRequest=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.goodPurchase=ko.observable();t.refundAmount=ko.observable();t.depositRefundAmount=ko.observable();n&&this.update(n)};ko.utils.extend(GoodPurchaseRefundRequest.prototype,{update:function(n){n=n||{};this.id(n.id);this.goodPurchase(n.goodPurchase);this.refundAmount(n.refundAmount);this.depositRefundAmount(ko.observable);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,refundAmount:n.RefundAmount,depositRefundAmount:n.DepositRefundAmount};return n.Purchase&&(t.goodPurchase=(new GoodPurchase).fromServerModel(n.Item)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),RefundAmount:this.refundAmount(),DepositRefundAmount:this.depositRefundAmount()};return this.goodPurchase()&&(n.Item=this.goodPurchase().toServerModel()),n}});RateRule=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.ruleName=ko.observable();n&&this.update(n)};ko.utils.extend(RateRule.prototype,{update:function(n){n=n||{};this.id(n.id);this.ruleName(n.ruleName);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,ruleName:n.RuleName};return this.update(t),this},toServerModel:function(){return{Id:this.id(),RuleName:this.ruleName()}}});Referral=function(n){var t=this;t.cache=function(){};this.deleted=ko.observable(!1);this.id=ko.observable();this.firstName=ko.observable();this.lastName=ko.observable();this.email=ko.observable();this.phone=ko.observable();this.spaceId=ko.observable();this.contactMethod=ko.observable(0);this.eventDate=ko.observable();this.guestCount=ko.observable();this.budget=ko.observable();this.description=ko.observable();n&&this.update(n)};ko.utils.extend(Referral.prototype,{update:function(n){n=n||{};this.id(n.id);this.firstName(n.firstName);this.lastName(n.lastName);this.email(n.email);this.phone(n.phone);this.spaceId(n.spaceId);this.contactMethod(n.contactMethod);this.eventDate(n.eventDate);this.guestCount(n.guestCount);this.budget(n.budget);this.description(n.description);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,firstName:n.FirstName,lastName:n.LastName,email:n.EmailAddress,phone:n.PhoneNumber,spaceId:n.Space_Id,contactMethod:n.ReferralContactMethodId,eventDate:n.EventDate,guestCount:n.InAttendance,budget:n.Budget,description:n.AnythingElse};return n.SpaceProvider&&(t.account=(new Account).fromServerModel(n.SpaceProvider)),this.update(t),this},toServerModel:function(){return{Id:this.id(),FirstName:this.firstName(),LastName:this.lastName(),EmailAddress:this.email(),PhoneNumber:this.phone(),Space_Id:this.spaceId(),ReferralContactMethodId:this.contactMethod(),EventDate:this.eventDate(),InAttendance:this.guestCount(),Budget:this.budget(),AnythingElse:this.description()}}});UserReferralQuestion=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.question=ko.observable();t.response=ko.observable();n&&this.update(n)};ko.utils.extend(UserReferralQuestion.prototype,{update:function(n){n=n||{};this.id(n.id);this.question(n.question);this.response(n.response);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,question:n.Question,response:n.Response};return this.update(t),this},toServerModel:function(){return{Id:this.id(),Question:this.question(),Response:this.response()}}});RentalRate=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.availabilityQtyUsed=ko.observable();t.minAvailabilityQty=ko.observable();t.maxAvailabilityQty=ko.observable();t.dateCreated=ko.observable();t.isDeleted=ko.observable();t.lastKnownVersion=ko.observable();t.name=ko.observable();t.rateRuleId=ko.observable();t.rateTypeId=ko.observable();t.rate=ko.observable();t.startTime=ko.observable();t.startDate=ko.observable();t.endTime=ko.observable();t.endDate=ko.observable();t.ruleName=ko.observable();t.validationCode=ko.observable();t.initialMinAvailabilityQty=ko.observable(1);t.initialMaxAvailabilityQty=ko.observable();t.rateRule=ko.observable();t.rateType=ko.computed(function(){switch(t.rateTypeId()){case PF.RateType.PerUse:return"Per Use";case PF.RateType.Hourly:return"Per Hour";case PF.RateType.Daily:return"Per Day";case PF.RateType.PerPerson:return"Per Person"}return"Unknown"});t.personRangeLabel=ko.computed(function(){return t.minAvailabilityQty()&&t.maxAvailabilityQty()?t.minAvailabilityQty()+" to "+t.maxAvailabilityQty()+" people":"? to ? people"});t.personRangeChoices=ko.computed(function(){for(var r=t.initialMaxAvailabilityQty()-t.initialMinAvailabilityQty()+1,i=[],n=t.initialMinAvailabilityQty();n<=t.initialMaxAvailabilityQty();n++)i.push(n);return i});n&&this.update(n)};ko.utils.extend(RentalRate.prototype,{update:function(n){n=n||{};this.id(n.id);this.availabilityQtyUsed(n.availabilityQtyUsed);this.maxAvailabilityQty(n.maxAvailabilityQty);this.minAvailabilityQty(n.minAvailabilityQty);this.initialMaxAvailabilityQty(n.initialMaxAvailabilityQty);this.initialMinAvailabilityQty(n.initialMinAvailabilityQty);this.dateCreated(n.dateCreated);this.endDate(n.endDate);this.endTime(n.endTime);this.isDeleted(n.isDeleted);this.lastKnownVersion(n.lastKnownVersion);this.name(n.name);this.rate(n.rate);this.rateRuleId(n.rateRuleId);this.rateTypeId(n.rateTypeId);this.ruleName(n.ruleName);this.startDate(n.startDate);this.startTime(n.startTime);this.validationCode(n.validationCode);this.rateRule(n.rateRule);this.cache.latestData=n},revert:function(){this.cache.latestData.rateRule=new RateRule(this.cache.latestData.rateRule);this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},clone:function(){var n=this.toServerModel(!0);return(new RentalRate).fromServerModel(n)},fromServerModel:function(n){var t={id:n.Id,availabilityQtyUsed:n.AvailabilityQtyUsed,initialMinAvailabilityQty:1,maxAvailabilityQty:n.MaxAvailabilityQty,minAvailabilityQty:n.MinAvailabilityQty,dateCreated:PF.parseMVCDate(n.DateCreated),endDate:PF.parseMVCDate(n.EndDate),endTime:n.EndTime,isDeleted:n.IsDeleted,lastKnownVersion:PF.parseMVCDate(n.LastKnownVersion),name:n.Name,rate:n.Rate,rateRuleId:n.RateRuleId,rateType:n.RateType,rateTypeId:n.RateTypeId,ruleName:n.RuleName,startDate:PF.parseMVCDate(n.StartDate),startTime:n.StartTime,validationCode:n.ValidationCode};return n.RateRule&&(t.rateRule=(new RateRule).fromServerModel(n.RateRule)),this.update(t),this},toServerModel:function(){return{Id:this.id(),AvailabilityQtyUsed:this.availabilityQtyUsed(),MaxAvailabilityQty:this.maxAvailabilityQty(),MinAvailabilityQty:this.minAvailabilityQty(),DateCreated:this.dateCreated(),EndDate:this.endDate(),EndTime:this.endTime(),IsDeleted:this.isDeleted(),LastKnownVersion:this.lastKnownVersion(),Name:this.name(),Rate:this.rate(),RateRule:this.rateRule()!=null&&this.rateRule()!=undefined?this.rateRule().toServerModel():null,RateRuleId:this.rateRuleId(),RateTypeId:this.rateTypeId(),RuleName:this.ruleName(),StartDate:this.startDate(),StartTime:this.startTime(),ValidationCode:this.validationCode()}}});Report=function(n){var t=this;t.id=ko.observable();t.displayName=ko.observable();t.accessRole=ko.observable();t.roleLevel=ko.observable();t.providerType=ko.observable();t.reportParameters=ko.observableArray();t.reportCategories=ko.observableArray();n&&t.update(n)};ko.utils.extend(Report.prototype,{update:function(n){n=n||{};this.id(n.id);this.displayName(n.displayName);this.accessRole(n.accessRole);this.roleLevel(n.roleLevel);this.providerType(n.providerType);this.reportParameters(n.reportParameters);this.reportCategories(n.reportCategories)},fromServerModel:function(n){var t={id:n.Id,displayName:n.DisplayName,accessRole:n.AccessRole,roleLevel:n.RoleLevel,providerType:n.ProviderType};return n.ReportParameters&&(t.reportParameters=n.ReportParameters.map(function(n){return(new ReportParameter).fromServerModel(n)})),n.ReportCategories&&(t.reportCategories=n.ReportCategories.map(function(n){return(new ReportCategory).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),DisplayName:this.displayName(),AccessRole:this.accessRole(),RoleLevel:this.roleLevel(),ProviderType:this.providerType()};return this.reportParameters()&&(n.ReportParameters=this.reportParameters().map(function(n){return n.toServerModel()})),this.reportCategories()&&(n.ReportCategories=this.reportCategories().map(function(n){return n.toServerModel()})),n}});ReportCategory=function(n){var t=this;t.id=ko.observable();t.category=ko.observable();n&&t.update(n)};ko.utils.extend(ReportCategory.prototype,{update:function(n){n=n||{};this.id(n.id);this.category(n.category)},fromServerModel:function(n){var t={id:n.Id,category:n.Category};return this.update(t),this},toServerModel:function(){return{Id:this.id(),Category:this.category()}}});ReportParameter=function(n){var t=this;t.id=ko.observable();t.parameterType=ko.observable();t.label=ko.observable();t.reportLabel=ko.observable();t.order=ko.observable();t.optional=ko.observable();t.value=ko.observable();t.dateDirectionForward=ko.observable();t.shouldKeepOriginalValue=ko.observable();t.computedLabel=ko.computed(function(){return t.label()+(t.optional()?" (opt)":"")});n&&t.update(n)};ko.utils.extend(ReportParameter.prototype,{update:function(n){n=n||{};this.id(n.id);this.parameterType(n.parameterType);this.label(n.label);this.reportLabel(n.reportLabel);this.order(n.order);this.optional(n.optional);this.value(n.value);this.dateDirectionForward(n.dateDirectionForward);this.shouldKeepOriginalValue(n.shouldKeepOriginalValue)},fromServerModel:function(n){var t={id:n.Id,parameterType:n.ParameterType,label:n.Label,reportLabel:n.ReportLabel,order:n.Order,optional:n.Optional,value:n.Value,dateDirectionForward:n.DateDirectionForward,shouldKeepOriginalValue:n.ShouldKeepOriginalValue};return this.update(t),this},toServerModel:function(){var n={Id:this.id(),ParameterType:this.parameterType(),Label:this.label(),ReportLabel:this.reportLabel(),Order:this.order(),Value:this.value(),Optional:this.optional(),DateDirectionForward:this.dateDirectionForward(),ShouldKeepOriginalValue:this.shouldKeepOriginalValue()};return this.value()!=null&&this.value().constructor===Array&&(n.Value=this.value().join(",")),n}});RangeDatePickerOptionValues={ThirtyDays:0,SixtyDays:1,NinetyDays:2,Year:3,Custom:4};ReportResult=function(n){var t=this;t.columns=ko.observableArray();t.rows=ko.observableArray();n&&this.update(n)};ko.utils.extend(ReportResult.prototype,{update:function(n){var r,t,u,i;for(this.columns(n.columns),r=[],t=0;t<n.rows.length;t++){for(u=[],i=0;i<n.columns.length;i++)u.push(n.rows[t][n.columns[i]]);r.push(u)}this.rows(r)},fromServerModel:function(n){var t={columns:n.Columns,rows:n.Rows};return this.update(t),this}});ReportView=function(n){var t=this;t.id=ko.observable();t.name=ko.observable();t.viewData=ko.observable();t.account=ko.observable();t.report=ko.observable();n&&t.update(n)};ko.utils.extend(ReportView.prototype,{update:function(n){n=n||{};this.id(n.id);this.name(n.name);this.account(n.account);this.report(n.report);this.viewData(n.viewData)},fromServerModel:function(n){var t={id:n.Id,name:n.Name,viewData:n.ViewData};return n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.Report&&(t.report=(new Report).fromServerModel(n.Report)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Name:this.name(),ViewData:this.viewData()};return this.account()&&(n.Account=this.account().toServerModel()),this.report()&&(n.Report=this.report().toServerModel()),n}});Resource=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.name=ko.observable();t.description=ko.observable();t.imageUrl=ko.observable();t.account=ko.observable();t.resourceSpaces=ko.observableArray();t.availabilities=ko.observableArray();t.dateCreated=ko.observable();t.usageType=ko.observable();t.maxQuantityAvailable=ko.observable();t.peopleCapacity=ko.observable();t.remainingQuantityAvailable=ko.observable();n&&this.update(n)};ko.utils.extend(Resource.prototype,{update:function(n){n=n||{};this.id(n.id);this.name(n.name);this.resourceSpaces(n.resourceSpaces||[]);this.availabilities(n.availabilities||[]);this.description(n.description);this.imageUrl(n.imageUrl);this.remainingQuantityAvailable(n.remainingQuantityAvailable);this.maxQuantityAvailable(n.maxQuantityAvailable);this.peopleCapacity(n.peopleCapacity);this.account(n.account);this.dateCreated(n.dateCreated);this.usageType(n.usageType);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,name:n.Name,description:n.Description,imageUrl:n.ImageUrl,dateCreated:n.DateCreated,usageType:n.UsageType,remainingQuantityAvailable:n.RemainingQuantityAvailable,maxQuantityAvailable:n.MaxQuantityAvailable,peopleCapacity:n.PeopleCapacity};return n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.ResourceSpaces&&n.ResourceSpaces.length>0&&(t.resourceSpaces=n.ResourceSpaces.map(function(n){return(new ResourceSpace).fromServerModel(n)})),n.Availabilities&&n.Availabilities.length>0&&(t.availabilities=n.Availabilities.map(function(n){return(new SpaceAvailability).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Name:this.name(),ImageUrl:this.imageUrl(),Description:this.description(),UsageType:this.usageType(),MaxQuantityAvailable:this.maxQuantityAvailable(),PeopleCapacity:this.peopleCapacity()};return this.account()&&(n.Account=this.account().toServerModel()),this.resourceSpaces()&&(n.ResourceSpaces=this.resourceSpaces().map(function(n){return n.toServerModel()})),this.availabilities()&&(n.Availabilities=this.availabilities().map(function(n){return n.toServerModel()})),n}});ResourceSpace=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.categoryName=ko.observable();t.description=ko.observable();t.resource=ko.observable();t.space=ko.observable();t.spaceName=ko.observable();t.spaceId=ko.observable();t.resourceId=ko.observable();t.order=ko.observable();t.hideFromBuyer=ko.observable();t.chargeRateForAllResources=ko.observable();t.optional=ko.observable();t.usageDelay=ko.observable();t.usageLength=ko.observable();t.isDirty=ko.observable();t.rate=ko.observable();t.usageLengthComputed=ko.computed(function(){return t.space()?t.usageLength()?t.usageLength():t.space().minRentalDuration():null});t.usageDelayComputed=ko.computed(function(){return t.usageDelay()?t.usageDelay():0});t.addMinutesToUsageLength=function(n){t.usageLength(t.usageLengthComputed()+n)};t.addMinutesToUsageDelay=function(n){t.usageDelay(t.usageDelayComputed()+n)};n&&this.update(n)};ko.utils.extend(ResourceSpace.prototype,{update:function(n){n=n||{};this.id(n.id);this.categoryName(n.categoryName);this.description(n.description);this.order(n.order);this.resource(n.resource);this.space(n.space);this.spaceName(n.spaceName);this.spaceId(n.spaceId);this.resourceId(n.resourceId);this.usageLength(n.usageLength);this.usageDelay(n.usageDelay);this.hideFromBuyer(n.hideFromBuyer);this.chargeRateForAllResources(n.chargeRateForAllResources);this.optional(n.optional);this.rate(n.rate);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,categoryName:n.CategoryName,description:n.Description,spaceId:n.SpaceId,spaceName:n.SpaceName,resourceId:n.ResourceId,order:n.Order,usageLength:n.UsageLength,usageDelay:n.UsageDelay,hideFromBuyer:n.HideFromBuyer,chargeRateForAllResources:n.ChargeRateForAllResources,optional:n.Optional,rate:n.Rate};return n.Resource&&(t.resource=(new Resource).fromServerModel(n.Resource)),n.Space&&(t.space=(new Space).fromServerModel(n.Space)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),CategoryName:this.categoryName(),Description:this.description(),UsageLength:this.usageLength(),UsageDelay:this.usageDelay(),Order:this.order(),HideFromBuyer:this.hideFromBuyer(),ChargeRateForAllResources:this.chargeRateForAllResources(),SpaceId:this.spaceId(),ResourceId:this.resourceId(),Optional:this.optional(),Rate:this.rate()==""?null:this.rate()};return this.resource()&&(n.Resource=this.resource().toServerModel()),this.space()&&(n.Space=this.space().toServerModel()),n}});ResourceBooking=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.dateCreated=ko.observable();t.booking=ko.observable();t.resource=ko.observable();t.resourceName=ko.observable();t.categoryName=ko.observable();t.quantityPurchased=ko.observable();t.usageDelay=ko.observable();t.usageLength=ko.observable();t.hideFromBuyer=ko.observable();t.chargeRateForAllResources=ko.observable();t.optional=ko.observable();t.rate=ko.observable();t.quantityIncludedInBasePrice=ko.observable();t.extraQuantityPurchasedByBuyer=ko.computed({read:function(){var n=t.quantityPurchased()-t.quantityIncludedInBasePrice();return n>=0?n:0},write:function(n){var i=parseInt(n,10)||0;i<0&&(i=0);t.optional()?t.quantityPurchased(i):t.quantityPurchased(t.quantityIncludedInBasePrice()+i)},owner:t});t.totalPurchase=ko.computed(function(){return t.chargeRateForAllResources()?t.quantityPurchased()*t.rate():t.extraQuantityPurchasedByBuyer()<0?0:t.extraQuantityPurchasedByBuyer()*t.rate()});t.totalPriceOfQuantityIncludedInBasePrice=ko.computed(function(){return t.chargeRateForAllResources()?t.quantityIncludedInBasePrice()*t.rate():0});t.categoryNameComputed=ko.computed(function(){return t.categoryName()?t.categoryName().toLowerCase():t.id()});n&&this.update(n)};ko.utils.extend(ResourceBooking.prototype,{update:function(n){n=n||{};this.id(n.id);this.dateCreated(n.dateCreated);this.booking(n.booking);this.resource(n.resource);this.resourceName(n.resourceName);this.hideFromBuyer(n.hideFromBuyer);this.chargeRateForAllResources(n.chargeRateForAllResources);this.categoryName(n.categoryName);this.quantityPurchased(n.quantityPurchased);this.usageDelay(n.usageDelay);this.usageLength(n.usageLength);this.rate(n.rate);this.optional(n.optional);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,dateCreated:n.DateCreated,quantityPurchased:n.QuantityPurchased,usageDelay:n.UsageDelay,usageLength:n.UsageLength,resourceName:n.ResourceName,categoryName:n.CategoryName,hideFromBuyer:n.HideFromBuyer,chargeRateForAllResources:n.ChargeRateForAllResources,optional:n.Optional,rate:n.Rate};return n.Booking&&(t.booking=(new Booking).fromServerModel(n.Booking)),n.Resource&&(t.resource=(new Resource).fromServerModel(n.Resource)),this.update(t),this},toServerModel:function(n){var t={Id:this.id(),DateCreated:this.dateCreated(),QuantityPurchased:this.quantityPurchased(),UsageLength:this.usageLength(),UsageDelay:this.usageDelay(),ResourceName:this.resourceName(),CategoryName:this.categoryName(),HideFromBuyer:this.hideFromBuyer(),ChargeRateForAllResources:this.chargeRateForAllResources(),Optional:this.optional(),Rate:this.rate()};return this.resource()&&(t.Resource=this.resource().toServerModel()),n&&this.booking()&&(t.Booking=this.booking().toServerModel()),t}});ResourceBookingGroup=function(n,t){var i=this;i.name=ko.observable(n?n.categoryName():null);i.nameComputed=ko.observable(n?n.categoryNameComputed():null);i.children=ko.observableArray();i.valid=ko.observable(!0);i.availabilityQtyBooked=ko.observable(t);i.totalBookedInGroup=ko.observable();i.validateMessage=ko.observable();i.childrenNotHidden=ko.computed(function(){return $.grep(i.children(),function(n){return n.hideFromBuyer()==!1})});i.containsPricedResource=function(){var n=!1;return($.each(i.children(),function(t,i){return n=typeof i.rate()!=null&&i.rate()>0&&i.hideFromBuyer()==!1,n?!1:void 0}),i.children().length==1&&i.children()[0].optional()&&!i.children()[0].chargeRateForAllResources())?!1:n};i.groupedResourcesContainsHiddenResourceForBuyer=function(n){var t=[];return($.each(n,function(n,i){return t=$.grep(i.children(),function(n){return n.hideFromBuyer()==!0}),t.length>0?!1:void 0}),t.length>0)?!0:!1};i.maxAvailableQtyToBeBookedInGroup=function(){var n=null;return $.each(i.children(),function(t,i){var r=i.resource().peopleCapacity()?i.resource().peopleCapacity():1,u;if(i.resource().usageType()==PF.UsageType.BuyerDropdown){if(r==1)return!1;n<i.resource().remainingQuantityAvailable()&&(n=i.resource().remainingQuantityAvailable())}i.resource().usageType()!=PF.UsageType.BuyerQty||i.optional()||(u=Math.ceil(i.resource().remainingQuantityAvailable()*r),n+=u)}),n==null?1e11:n};i.validate=function(){return i.totalBookedInGroup(0),$.each(i.children(),function(n,t){var u,r,f;if(t.quantityPurchased()==""&&t.quantityPurchased(0),t.quantityPurchased()<0&&t.quantityPurchased(0),u=t.resource().peopleCapacity()?t.resource().peopleCapacity():1,r=Math.ceil((i.availabilityQtyBooked()-i.totalBookedInGroup())/u),i.availabilityQtyBooked()-i.totalBookedInGroup()>0?r>t.resource().remainingQuantityAvailable()?t.quantityIncludedInBasePrice(t.resource().remainingQuantityAvailable()):t.quantityIncludedInBasePrice(r||0):t.quantityIncludedInBasePrice(0),t.optional()&&(r=Math.ceil(i.availabilityQtyBooked()/u),r>t.resource().remainingQuantityAvailable()?t.quantityIncludedInBasePrice(t.resource().remainingQuantityAvailable()):t.quantityIncludedInBasePrice(r||0)),f=parseInt(t.quantityIncludedInBasePrice(),10)*u,i.totalBookedInGroup(i.totalBookedInGroup()+f),t.extraQuantityPurchasedByBuyer()>0&&t.quantityPurchased()>t.resource().remainingQuantityAvailable())return i.valid(!1),i.validateMessage("You cannot reserve more "+t.resourceName()+" than are available."),!1;i.valid(!0);i.validateMessage("")}),i.valid()};i.children.subscribe(function(n){n.forEach(function(n){n.status==="added"&&n.value.quantityPurchased.subscribe(function(){i.validate()})})},null,"arrayChange")};Role=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.account=ko.observable();t.user=ko.observable();t.type=ko.observable();t.isolated=ko.observable();t.sendBookingEmails=ko.observable();t.sendBillingEmails=ko.observable();t.typeName=ko.computed(function(){switch(t.type()){case PF.RoleType.Staff:return"Staff";case PF.RoleType.Supervisor:return"Supervisor";case PF.RoleType.Manager:return"Manager";case PF.RoleType.LocationAdmin:return"Location Admin";case PF.RoleType.FranchiseAdmin:return"Franchise Admin";default:return"None"}});n&&this.update(n)};ko.utils.extend(Role.prototype,{update:function(n){n=n||{};this.id(n.id);this.account(n.account);this.user(n.user);this.type(n.type);this.isolated(n.isolated);this.sendBookingEmails(n.sendBookingEmails);this.sendBillingEmails(n.sendBillingEmails);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,type:n.Type,isolated:n.Isolated.toString(),sendBookingEmails:n.SendBookingEmails,sendBillingEmails:n.SendBillingEmails};return n.Account&&(t.account=(new Account).fromServerModel(n.Account)),n.User&&(t.user=(new User).fromServerModel(n.User)),this.update(t),this},toServerModel:function(){var t=!1,n;return this.type()<PF.RoleType.LocationAdmin&&(this.isolated()=="1"||this.isolated()=="true")&&(t=!0),n={Id:this.id(),Type:this.type(),Isolated:t,SendBookingEmails:this.sendBookingEmails(),SendBillingEmails:this.sendBillingEmails()},this.account()&&(n.Account={Id:this.account().id(),CondensedName:this.account().condensedName()}),this.user()&&(n.User={Id:this.user().id(),Email:this.user().email(),FirstName:this.user().firstName(),LastName:this.user().lastName()}),n}});SimpleCalendarAvailability=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.startDateTime=ko.observable();t.endDateTime=ko.observable();t.spaceName=ko.observable();t.spaceCondensedName=ko.observable();t.spaceUserId=ko.observable();t.imageUrl=ko.observable();t.rateType=ko.observable();t.minimumRentalFee=ko.observable();t.rentalRate=ko.observable();t.description=ko.observable();t.timeSlotDetails=ko.observable();t.note=ko.observable();t.soldOut=ko.observable(!1);t.calendarEvent=function(){var n={start:t.startDateTime(),end:t.endDateTime(),id:t.id(),title:t.spaceName(),spaceName:t.spaceName(),description:t.description(),spaceCondensedName:t.spaceCondensedName(),spaceUserId:t.spaceUserId(),minimumRentalFee:t.minimumRentalFee(),imageUrl:t.imageUrl(),isHourly:t.rateType()==0,note:t.note(),soldOut:t.soldOut()};return n.note==!0&&(n.start.setHours(23,58,00),n.end.setHours(23,59,00)),n};n&&this.update(n)};ko.utils.extend(SimpleCalendarAvailability.prototype,{update:function(n){n=n||{};this.id(n.id);this.startDateTime(n.startDateTime);this.endDateTime(n.endDateTime);this.spaceName(n.spaceName);this.spaceCondensedName(n.spaceCondensedName);this.spaceUserId(n.spaceUserId);this.imageUrl(n.imageUrl);this.rateType(n.rateType);this.description(n.description);this.minimumRentalFee(n.minimumRentalFee);this.rentalRate(n.spaceNames);this.timeSlotDetails(n.timeSlotDetails);this.note(n.note);this.soldOut(n.soldOut);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,startDateTime:new Date(n.StartDateTimeUTC),endDateTime:new Date(n.EndDateTimeUTC),spaceName:n.SpaceName,spaceCondensedName:n.SpaceCondensedName,spaceUserId:n.SpaceUserId,imageUrl:n.ImageUrl,rateType:n.RateType,minimumRentalFee:n.MinimumRentalFee,description:n.Description,rentalRate:n.RentalRate,timeSlotDetails:n.TimeSlotDetails,note:n.Note==!0,soldOut:n.SoldOut==!0};return this.cache.latestServerData=n,this.update(t),this},toServerModel:function(){return{Id:this.id(),StartDateTimeUTC:this.startDateTime(),EndDateTimeUTC:this.endDateTime(),SpaceName:this.spaceName(),SpaceCondensedName:this.spaceCondensedName(),SpaceUserId:this.spaceUserId(),ImageUrl:this.imageUrl(),RateType:this.rateType(),MinimumRentalFee:this.minimumRentalFee(),RentalRate:this.rentalRate(),Description:this.description(),TimeSlotDetails:this.timeSlotDetails(),Note:this.note(),SoldOut:this.soldOut()}}});SiteProperty=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.condensedName=ko.observable();this.fullName=ko.observable();n&&this.update(n)};ko.utils.extend(SiteProperty.prototype,{update:function(n){n=n||{};this.id(n.id);this.condensedName(n.condensedName);this.fullName(n.fullName);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,condensedName:n.CondensedName,fullName:n.FullName};return this.update(t),this},toServerModel:function(){return{Id:this.id(),CondensedName:this.condensedName(),FullName:this.fullName()}}});SMTPQueueDetail=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.campaign=ko.observable();t.objectId=ko.observable();t.objectType=ko.observable();t.sendDate=ko.observable();t.template=ko.observable();t.sentDate=ko.observable();t.mandrillId=ko.observable();t.recipient=ko.observable();t.recipientEmail=ko.observable();t.recipientId=ko.observable();t.clicks=ko.observable();t.opens=ko.observable();t.fullName=ko.computed(function(){var n="";return t.recipient()?(t.recipient().firstName()&&(n=t.recipient().firstName()),t.recipient().lastName()&&(n=n+" "+t.recipient().lastName()),n):"Unknown Contact Name"});t.company=ko.computed(function(){return t.recipient()&&t.recipient().organizationName()?t.recipient().organizationName():""});n&&this.update(n)};ko.utils.extend(SMTPQueueDetail.prototype,{update:function(n){n=n||{};this.id(n.id);this.campaign(n.campaign);this.template(n.template);this.sendDate(n.sendDate);this.sentDate(n.sentDate);this.objectType(n.objectType);this.objectId(n.objectId);this.mandrillId(n.mandrillId);this.recipient(n.recipient);this.recipientEmail(n.recipientEmail);this.recipientId(n.recipientId);this.cache.latestData=n;this.clicks(n.clicks);this.opens(n.opens)},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,campaign:n.Campaign,template:n.Template,sentDate:n.SentDate,sendDate:n.SendDate,objectType:n.ObjectType,objectId:n.ObjectId,mandrillId:n.MandrillID,recipientId:n.RecipientId,recipientEmail:n.RecipientEmail,clicks:n.Clicks,opens:n.Opens};return n.RecipientUser&&(t.recipient=(new User).fromServerModel(n.RecipientUser)),n.RecipientLead&&(t.recipient=(new CustomerLead).fromServerModel(n.RecipientLead)),this.update(t),this},toServerModel:function(){return{Id:this.id(),Campaign:this.campaign(),Template:this.template(),SendDate:this.sendDate(),SentDate:this.sentDate(),ObjectType:this.objectType(),ObjectId:this.objectId(),MandrillID:this.mandrillId(),Clicks:this.clicks(),Opens:this.opens()}}});Space=function(n){var t=this;t.cache=function(){};this.deleted=ko.observable(!1);t.id=ko.observable();t.name=ko.observable();t.condensedName=ko.observable();t.description=ko.observable();t.shortDescription=ko.observable();t.url=ko.observable();t.packageQuantity=ko.observable();t.publicUrl=ko.observable();t.capacity=ko.observable();t.displayAddress=ko.observable();t.address1=ko.observable();t.address2=ko.observable();t.city=ko.observable();t.country=ko.observable();t.long=ko.observable();t.lat=ko.observable();t.phone=ko.observable();t.postalOrZipCode=ko.observable();t.stateOrProvince=ko.observable();t.dateCreated=ko.observable();t.minRentalDuration=ko.observable();t.minNotice=ko.observable();t.minRentalFee=ko.observable();t.rentalBuffer=ko.observable();t.isReferralSpace=ko.observable();t.publishedToMarketplace=ko.observable();t.publishedToFacebook=ko.observable();t.publishedToWeb=ko.observable();t.publishedToWebCalendar=ko.observable();t.sortOrder=ko.observable();t.taxable=ko.observable();t.customGroups=ko.observableArray();t.spacePassword=ko.observable();t.hasPassword=ko.computed(function(){return t.spacePassword()?t.spacePassword().trim().length?!0:!1:!1});t.excludeFromPromotions=ko.observable();t.hasDepositPricing=ko.observable();t.depositTimeTable=ko.observableArray();t.specialFlags=ko.observable();t.giftedPageUrl=ko.observable();t.spaceTypeId=ko.observable();t.spaceType=ko.observable();t.spaceCategoryId=ko.observable();t.availabilities=ko.observableArray();t.spaceEventTypes=ko.observableArray();t.amenities=ko.observableArray();t.resourceSpaces=ko.observableArray();t.promotionCodeGroups=ko.observableArray();t.defaultRate=ko.observable();t.specialRates=ko.observableArray();t.promoRates=ko.observableArray();t.cleaningRate=ko.observable();t.securityRate=ko.observable();t.timeZone=ko.observable();t.defaultImage=ko.observable();t.enteredPassword=ko.observable();t.account=ko.observable();t.images=ko.observableArray(null);t.terms=ko.observable();t.computedInitialDeposit=ko.computed({read:function(){if(t.hasDepositPricing()&&t.depositTimeTable()&&t.depositTimeTable().length){var n=$.grep(t.depositTimeTable(),function(n){return n.isInitialDeposit()});return n.length==1?n[0]:null}return null}});t.listOfMiddleDeposits=ko.computed({read:function(){if(t.hasDepositPricing()&&t.depositTimeTable()&&t.depositTimeTable().length){var n=$.grep(t.depositTimeTable(),function(n){return!n.isInitialDeposit()&&!n.isFinalDeposit()});return n.length?n:null}return null}});t.computedFinalDeposit=ko.computed({read:function(){if(t.hasDepositPricing()&&t.depositTimeTable()&&t.depositTimeTable().length){var n=$.grep(t.depositTimeTable(),function(n){return n.isFinalDeposit()});return n.length==1?n[0]:null}return null}});t.fullAddress=ko.computed({read:function(){return t.address1()+", "+(t.address2()?t.address2()+", ":"")+t.city()+", "+t.stateOrProvince()+" "+t.postalOrZipCode()}});t.isReferral=ko.computed(function(){return t.defaultRate()&&t.defaultRate().rateRule()&&t.defaultRate().rateRule().ruleName()?t.defaultRate().rateRule().ruleName()==="Referral":!1});t.isHourly=ko.computed(function(){return t.defaultRate()?t.defaultRate().rateType()==="Per Hour":!1});t.isGiftedListing=ko.computed(function(){return t.specialFlags()&&(t.specialFlags()&PF.SpaceSpecialFlags.IsGiftedListing)!=0});t.validRates=function(n,r){var u=[],o,e,f;if(!n||!t.defaultRate())return u;if(o=t.defaultRate().rateTypeId()==PF.RateType.PerPerson,e=n.maxAvailableResourceQtyAllowed(),o){for(i=t.defaultRate().minAvailabilityQty();i<=t.defaultRate().maxAvailabilityQty();i++)f=t.defaultRate().clone(),f.availabilityQtyUsed(i),r&&r.packagesRemaining?f.availabilityQtyUsed()<=r.packagesRemaining&&i<=e&&u.push(f):u.push(f);$.each(t.specialRates(),function(n,t){for(n=t.minAvailabilityQty();n<=t.maxAvailabilityQty();n++){var i=t.clone();if(i.availabilityQtyUsed(n),i.availabilityQtyUsed()>e)return!0;r&&r.packagesRemaining?i.availabilityQtyUsed()<=r.packagesRemaining&&u.push(i):u.push(i)}});u=u.sort(function(n,t){return n.availabilityQtyUsed()==t.availabilityQtyUsed()?0:n.availabilityQtyUsed()>t.availabilityQtyUsed()?1:-1})}else t.specialRates()&&($.each(t.specialRates(),function(n,t){if(t.availabilityQtyUsed()>e)return!0;r&&r.packagesRemaining?t.availabilityQtyUsed()<=r.packagesRemaining&&u.push(t):u.push(t)}),u=u.sort(function(n,t){return n.rate()==t.rate()?0:n.rate()>t.rate()?1:-1})),u.unshift(t.defaultRate());return u};n&&t.update(n)};ko.utils.extend(Space.prototype,{update:function(n){n=n||{};this.id(n.id);this.name(n.name);this.condensedName(n.condensedName);this.description(n.description||"");this.url(n.url||"");this.publicUrl(n.publicUrl||"");this.capacity(n.capacity);this.displayAddress(n.displayAddress);this.address1(n.address1||"");this.address2(n.address2||"");this.availabilities(ko.utils.unwrapObservable(n.availabilities)||[]);this.amenities(ko.utils.unwrapObservable(n.amenities)||[]);this.packageQuantity(n.packageQuantity);this.city(n.city);this.country(n.country);this.long(n.long);this.lat(n.lat);this.phone(n.phone);this.postalOrZipCode(n.postalOrZipCode);this.stateOrProvince(n.stateOrProvince);this.dateCreated(n.dateCreated);this.specialRates(n.specialRates);this.promoRates(n.promoRates);this.minNotice(n.minNotice||0);this.minRentalDuration(n.minRentalDuration);this.minRentalFee(n.minRentalFee);this.rentalBuffer(n.rentalBuffer);this.isReferralSpace(n.isReferralSpace);this.spaceTypeId(n.spaceTypeId);this.spaceType(n.spaceType);this.spaceCategoryId(n.spaceCategoryId);this.spaceEventTypes(n.spaceEventTypes||[]);this.timeZone(n.timeZone);this.defaultImage(n.defaultImage);this.resourceSpaces(n.resourceSpaces);this.promotionCodeGroups(n.promotionCodeGroups);this.publishedToMarketplace(n.publishedToMarketplace);this.publishedToFacebook(n.publishedToFacebook);this.publishedToWeb(n.publishedToWeb);this.publishedToWebCalendar(n.publishedToWebCalendar);this.sortOrder(n.sortOrder);this.taxable(n.taxable);this.customGroups(n.customGroups);this.spacePassword(n.spacePassword);this.excludeFromPromotions(n.excludeFromPromotions);this.hasDepositPricing(n.hasDepositPricing);this.specialFlags(n.specialFlags);this.giftedPageUrl(n.giftedPageUrl);this.shortDescription(n.shortDescription);n.defaultRate&&this.defaultRate(n.defaultRate);n.cleaningRate&&this.cleaningRate(n.cleaningRate);n.securityRate&&this.securityRate(n.securityRate);n.depositTimeTable&&this.depositTimeTable(n.depositTimeTable);this.account(n.account);this.images(n.images);this.terms(n.terms);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},clone:function(){var n=this.toServerModel(!0);return(new Space).fromServerModel(n)},fromServerModel:function(n){var t={id:n.Id,name:n.Name,condensedName:n.CondensedName,description:n.Description,url:n.Url,availabilities:n.Availabilities,packageQuantity:n.PackageQty===0?null:n.PackageQty,publicUrl:n.PublicUrl,capacity:n.Capacity,displayAddress:n.DisplayAddress,address1:n.AddressLine1,address2:n.AddressLine2,city:n.City,country:n.Country,long:n.Long,lat:n.Lat,phone:n.PhoneNumber,postalOrZipCode:n.PostalCode,stateOrProvince:n.StateOrProvince,specialRates:n.SpecialRates,minRentalDuration:n.MinimumRental,minNotice:n.MinimumNotice,minRentalFee:n.MinimumRentalFee,rentalBuffer:n.PostRentalBuffer,dateCreated:PF.parseMVCDate(n.DateCreated),isReferralSpace:n.IsReferralSpace,timeZone:n.TimeZone,publishedToMarketplace:n.PublishedToMarketplace,publishedToFacebook:n.PublishedToFacebook,publishedToWeb:n.PublishedToWeb,publishedToWebCalendar:n.PublishedToWebCalendar,sortOrder:n.SortOrder,taxable:n.Taxable!=null?n.Taxable:!1,spacePassword:n.SpacePassword,excludeFromPromotions:n.ExcludeFromPromotions,hasDepositPricing:n.HasDepositPricing,specialFlags:n.SpecialFlags,giftedPageUrl:n.GiftedPageUrl,shortDescription:n.ShortDescription};if(n.SpaceType&&(t.spaceTypeId=n.SpaceType.Id,t.spaceType=n.SpaceType.Name),t.spaceCategoryId=n.SpaceCategory?n.SpaceCategory.Id:n.SpaceCategoryId,n.SpaceProvider&&(t.account=(new Account).fromServerModel(n.SpaceProvider)),n.DefaultRate&&(t.defaultRate=(new RentalRate).fromServerModel(n.DefaultRate),t.defaultRate.initialMaxAvailabilityQty(t.packageQuantity),t.defaultRate.commit()),n.CleaningRate&&(t.cleaningRate=(new RentalRate).fromServerModel(n.CleaningRate)),n.SecurityRate&&(t.securityRate=(new RentalRate).fromServerModel(n.SecurityRate)),n.SpecialRates)for(t.specialRates=n.SpecialRates.map(function(n){return(new RentalRate).fromServerModel(n)}),i=0;i<t.specialRates.length;i++)t.specialRates[i].initialMaxAvailabilityQty(t.packageQuantity),t.specialRates[i].commit();return n.PromotionRates&&(t.promoRates=n.PromotionRates.map(function(n){return(new RentalRate).fromServerModel(n)})),n.SpaceEventTypes&&(t.spaceEventTypes=n.SpaceEventTypes.map(function(n){return{Id:n.Id}})),n.Amenities&&(t.amenities=n.Amenities.map(function(n){return{Id:n.Id}})),n.SpaceImages&&(t.images=n.SpaceImages.map(function(n){return(new SpaceImage).fromServerModel(n)})),n.DefaultImage&&(t.defaultImage=(new SpaceImage).fromServerModel(n.DefaultImage)),n.Availabilities&&(t.availabilities=n.Availabilities.map(function(n){return(new SpaceAvailability).fromServerModel(n)})),n.Terms&&(t.terms=(new Terms).fromServerModel(n.Terms)),n.CustomGroups&&(t.customGroups=n.CustomGroups.map(function(n){return(new CustomGroup).fromServerModel(n)})),n.ResourceSpaces&&(t.resourceSpaces=n.ResourceSpaces.map(function(n){return(new ResourceSpace).fromServerModel(n)})),n.PromotionCodeGroups&&(t.promotionCodeGroups=n.PromotionCodeGroups.map(function(n){return(new PromotionCodeGroup).fromServerModel(n)})),n.DepositTimeTable&&(t.depositTimeTable=n.DepositTimeTable.map(function(n){return(new SpaceDepositTimeTable).fromServerModel(n)})),this.cache.latestServerData=n,this.update(t),this},toServerModel:function(n){var t={Id:this.id(),Name:this.name(),CondensedName:this.condensedName(),Description:this.description(),PackageQty:this.packageQuantity(),Url:this.url(),PublicUrl:this.publicUrl(),Capacity:this.capacity(),DisplayAddress:this.displayAddress(),AddressLine1:this.address1(),AddressLine2:this.address2(),City:this.city(),Country:this.country(),Long:this.long(),Lat:this.lat(),PhoneNumber:this.phone(),PostalCode:this.postalOrZipCode(),StateOrProvince:this.stateOrProvince(),DateCreated:this.dateCreated(),IsReferralSpace:this.isReferralSpace(),PublishedToMarketplace:this.publishedToMarketplace(),PublishedToFacebook:this.publishedToFacebook(),PublishedToWeb:this.publishedToWeb(),PublishedToWebCalendar:this.publishedToWebCalendar(),SortOrder:this.sortOrder(),Taxable:this.taxable(),SpaceType:{Id:this.spaceTypeId()},SpaceCategory:{Id:this.spaceCategoryId()},MinimumRental:this.minRentalDuration(),MinimumNotice:this.minNotice(),MinimumRentalFee:this.minRentalFee(),PostRentalBuffer:this.rentalBuffer(),TimeZone:this.timeZone(),Amenities:this.amenities().map(function(n){return{Id:n.Id}}),SpaceEventTypes:this.spaceEventTypes().map(function(n){return{Id:n.Id}}),SpacePassword:this.spacePassword(),ExcludeFromPromotions:this.excludeFromPromotions(),HasDepositPricing:this.hasDepositPricing(),SpecialFlags:this.specialFlags(),GiftedPageUrl:this.giftedPageUrl(),ShortDescription:this.shortDescription()};return n&&(this.defaultImage()&&(t.DefaultImage=this.defaultImage().toServerModel()),this.defaultRate()&&(t.DefaultRate=this.defaultRate().toServerModel()),this.cleaningRate()&&(t.CleaningRate=this.cleaningRate().toServerModel()),this.securityRate()&&(t.SecurityRate=this.securityRate().toServerModel()),this.specialRates()&&(t.SpecialRates=this.specialRates().map(function(n){return n.toServerModel(!0)})),this.promoRates()&&(t.PromotionRates=this.promoRates().map(function(n){return n.toServerModel(!0)})),this.account()&&(t.SpaceProvider=this.account().toServerModel()),this.availabilities()&&(t.Availabilities=this.availabilities().map(function(n){return n.toServerModel(!0)})),this.images()&&this.images().length>0&&(t.SpaceImages=this.images().map(function(n){return n.toServerModel(!0)})),this.terms()&&(t.Terms=this.terms().toServerModel()),this.resourceSpaces()&&(t.ResourceSpaces=this.resourceSpaces().map(function(n){return n.toServerModel(!0)})),this.promotionCodeGroups()&&(t.PromotionCodeGroups=this.promotionCodeGroups().map(function(n){return n.toServerModel(!0)})),this.customGroups()&&(t.CustomGroups=this.customGroups().map(function(n){return n.toServerModel()})),this.depositTimeTable()&&this.hasDepositPricing()&&(t.DepositTimeTable=this.depositTimeTable().map(function(n){return n.toServerModel()}))),t}});SpaceAvailability=function(n){var t=this;t.cache=function(){};t.id=ko.observable();t.spaceId=ko.observable();t.startTime=ko.observable();t.startDate=ko.observable();t.endTime=ko.observable();t.endDate=ko.observable();t.availabilityRate=ko.observable();t.isDeleted=ko.observable();t.description=ko.observable();t.calendarType=ko.observable();t.calendarTypeId=ko.observable();t.days=ko.observableArray();t.resourceQuantityAffected=ko.observable();t.isGroupedId=ko.observable();t.isGrouped=ko.observable();t.resourceId=ko.observable();t.resource=ko.observable();t.dateCreated=ko.observable();t.isDaily=ko.computed({read:function(){return t.days()&&t.days().length===7?!0:!1},write:function(n){n?t.days(t.dailyArray()):t.days([])}});t.isContinous=ko.computed({read:function(){return t.calendarType()&&t.calendarType().CalendarTypeName==PF.CalendarType.MultiDayAvailability.CalendarTypeName?!0:!1},write:function(n){n?t.calendarType(PF.CalendarType.MultiDayAvailability):t.calendarType(PF.CalendarType.Availability)}});t.duration=ko.computed({read:function(){if(t.endTime()&&t.startTime()){var n=PF.Moment(t.endTime(),["H:mm","HH:mm","hh:mm a","hh:mm A"]),i=PF.Moment(t.startTime(),["H:mm","HH:mm","hh:mm a","hh:mm A"]);return t.isContinous()&&n<i&&(n=PF.Moment(t.endDate()+" "+t.endTime()),i=PF.Moment(t.startDate()+" "+t.startTime())),n.hour()==0&&n.minute()==0&&n.add("day",1),n.diff(i,"minutes")}return undefined}});t.daysAbbreviation=ko.computed(function(){if(!t.days()||t.days().length===0)return"";if(t.isDaily())return"Daily";var n="";for(i=0;i<t.days().length;i++)n.length>0&&(n+=", "),n+=t.days()[i].substring(0,3);return n});t.hasAvailabilityRate=ko.computed({read:function(){return t.availabilityRate()>0},write:function(n){n&&!t.hasAvailabilityRate()?t.availabilityRate(9.99):n||t.availabilityRate(null)}});t.dailyArray=ko.computed(function(){var n=[];return n.push("Monday"),n.push("Tuesday"),n.push("Wednesday"),n.push("Thursday"),n.push("Friday"),n.push("Saturday"),n.push("Sunday"),n});n&&this.update(n)};ko.utils.extend(SpaceAvailability.prototype,{update:function(n){n=n||{};this.id(n.id);this.spaceId(n.spaceId);this.startTime(n.startTime);this.startDate(n.startDate);this.endTime(n.endTime);this.endDate(n.endDate);this.availabilityRate(n.availabilityRate);this.isDeleted(n.isDeleted);this.description(n.description);this.calendarType(n.calendarType);this.calendarTypeId(n.calendarTypeId);this.days(n.days);this.isGroupedId(n.isGroupedId);this.isGrouped(n.isGrouped);this.resourceId(n.resourceId);this.resourceQuantityAffected(n.resourceQuantityAffected);this.resource(n.resource);this.dateCreated(n.dateCreated);n.isDaily&&this.days(this.dailyArray());this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,availabilityRate:n.AvailabilityRate,startDate:n.StartDate,startTime:n.StartTime&&n.StartTime.indexOf("0")==0&&n.StartTime.indexOf(":")!=1&&n.StartTime.indexOf("00:00")==-1?n.StartTime.substr(1):n.StartTime,endDate:n.EndDate,endTime:n.EndTime&&n.EndTime.indexOf("0")==0&&n.EndTime.indexOf(":")!=1&&n.EndTime.indexOf("00:00")==-1?n.EndTime.substr(1):n.EndTime,isDeleted:n.IsDeleted,spaceId:n.Space_Id,calendarTypeId:n.CalendarType_Id,calendarType:n.CalendarType,isGrouped:n.IsGrouped,isGroupedId:n.IsGroupedId,resourceId:n.Resource_Id,resourceQuantityAffected:n.ResourceQuantityAffected,dateCreated:n.DateCreated,days:[]};return n.Monday&&t.days.push("Monday"),n.Tuesday&&t.days.push("Tuesday"),n.Wednesday&&t.days.push("Wednesday"),n.Thursday&&t.days.push("Thursday"),n.Friday&&t.days.push("Friday"),n.Saturday&&t.days.push("Saturday"),n.Sunday&&t.days.push("Sunday"),this.cache.latestServerData=n,this.update(t),this},toServerModel:function(){var n={Id:this.id(),EndDate:this.endDate(),EndTime:this.endTime(),StartDate:this.startDate(),StartTime:this.startTime(),IsDeleted:this.isDeleted(),CalendarType:this.calendarType(),CalendarType_Id:this.calendarTypeId(),Space_Id:this.spaceId(),IsGroupedId:this.isGroupedId(),IsGrouped:this.isGrouped(),Resource_Id:this.resourceId(),Description:this.description(),AvailabilityRate:this.availabilityRate(),ResourceQuantityAffected:this.resourceQuantityAffected(),DateCreated:this.dateCreated(),Monday:!1,Tuesday:!1,Wednesday:!1,Thursday:!1,Friday:!1,Saturday:!1,Sunday:!1};return this.days()&&(this.days.indexOf("Monday")!=-1&&(n.Monday=!0),this.days.indexOf("Tuesday")!=-1&&(n.Tuesday=!0),this.days.indexOf("Wednesday")!=-1&&(n.Wednesday=!0),this.days.indexOf("Thursday")!=-1&&(n.Thursday=!0),this.days.indexOf("Friday")!=-1&&(n.Friday=!0),this.days.indexOf("Saturday")!=-1&&(n.Saturday=!0),this.days.indexOf("Sunday")!=-1&&(n.Sunday=!0)),n}});SpaceDepositTimeTable=function(n){var t=this;t.id=ko.observable();t.space=ko.observable();t.amountToCharge=ko.observable();t.chargeMode=ko.observable();t.minutesBeforeToChargeCustomer=ko.observable();t.isInitialDeposit=ko.observable();t.isFinalDeposit=ko.observable();n&&this.update(n)};ko.utils.extend(SpaceDepositTimeTable.prototype,{update:function(n){n=n||{};this.id(n.id);this.minutesBeforeToChargeCustomer(n.minutesBeforeToChargeCustomer);this.amountToCharge(n.amountToCharge);this.chargeMode(n.chargeMode);this.isInitialDeposit(n.isInitialDeposit);this.isFinalDeposit(n.isFinalDeposit);n.space&&this.space(n.space)},fromServerModel:function(n){var t={id:n.Id,minutesBeforeToChargeCustomer:n.MinutesBeforeToChargeCustomer,amountToCharge:n.AmountToCharge,chargeMode:n.ChargeMode,isInitialDeposit:n.IsInitialDeposit,isFinalDeposit:n.IsFinalDeposit};return n.Space&&(t.space=(new Space).fromServerModel(n.Space)),this.update(t),this},toServerModel:function(){var n={Id:this.id(),MinutesBeforeToChargeCustomer:this.minutesBeforeToChargeCustomer(),AmountToCharge:this.amountToCharge(),ChargeMode:this.chargeMode(),IsInitialDeposit:this.isInitialDeposit(),IsFinalDeposit:this.isFinalDeposit()};return this.space()&&(n.Space=this.space().toServerModel()),n}});SpaceImage=function(n){var t=this;t.cache=function(){};this.deleted=ko.observable(!1);this.id=ko.observable();this.fileUrl=ko.observable();this.isDefault=ko.observable();this.title=ko.observable();this.description=ko.observable();this.size=ko.observable("full");this.thumbnails=ko.observableArray();this.thumbnail=function(n){return ko.computed({read:function(){return ko.utils.arrayFirst(t.thumbnails(),function(t){return t.size()===n})}},this)};n&&this.update(n)};ko.utils.extend(SpaceImage.prototype,{update:function(n){n=n||{};this.id(n.id);this.fileUrl(n.fileUrl);this.isDefault(n.isDefault);this.title(n.title);this.description(n.description);this.size(n.size);this.thumbnails(n.thumbnails);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,fileUrl:n.FileURL,isDefault:n.IsDefaultImage,title:n.ImageTitle,description:n.ImageDescription,size:n.ThumbnailSetting||"full"};return n.Thumbnails&&(t.thumbnails=n.Thumbnails.map(function(n){return(new SpaceImage).fromServerModel(n)})),this.update(t),this},toServerModel:function(n){var t={Id:this.id(),FileURL:this.fileUrl(),IsDefaultImage:this.isDefault(),ImageTitle:this.title(),ImageDescription:this.description(),ThumbnailSetting:this.size()};return n&&(t.Thumbnails=this.thumbnails().map(function(n){return n.toServerModel()})),t}});SubscriptionBilling=function(n){var t=this;t.cache=function(){};this.id=ko.observable();this.billingDate=ko.observable();this.amount=ko.observable();this.externalKey=ko.observable();this.type=ko.observable();this.paid=ko.observable();n&&this.update(n)};ko.utils.extend(SubscriptionBilling.prototype,{update:function(n){n=n||{};this.id(n.id);this.billingDate(n.billingDate);this.amount(n.amount);this.externalKey(n.externalKey);this.type(n.type);this.paid(n.paid);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,billingDate:n.BillingDate,amount:n.Amount,externalKey:n.ExternalTransactionKey,type:n.AccountType,paid:n.Paid};return this.update(t),this},toServerModel:function(){return null}});Terms=function(n){var t=this;t.cache=function(){};this.deleted=ko.observable(!1);this.id=ko.observable();this.fileUrl=ko.observable();this.description=ko.observable();this.addOnPolicyTextToRenter=ko.observable();this.emailTextToRenter=ko.observable();this.file=ko.observable();this.type=ko.computed(function(){return t.fileUrl()?"file":"text"});n&&this.update(n)};ko.utils.extend(Terms.prototype,{update:function(n){n=n||{};this.id(n.id);this.fileUrl(n.fileUrl);this.description(n.description);this.addOnPolicyTextToRenter(n.addOnPolicyTextToRenter);this.emailTextToRenter(n.emailTextToRenter);this.file(n.file);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,fileUrl:n.TermsAndConditionsFileUrl,description:n.TermsAndConditions,addOnPolicyTextToRenter:n.AddOnPolicyTextToRenter,emailTextToRenter:n.EmailTextToRenter,file:n.TermsAndConditionsFile};return this.update(t),this},toServerModel:function(){return{Id:this.id(),TermsAndConditionsFileUrl:this.fileUrl(),TermsAndConditions:this.description(),AddOnPolicyTextToRenter:this.addOnPolicyTextToRenter(),EmailTextToRenter:this.emailTextToRenter(),TermsAndConditionsFile:this.file()}}});Tier=function(n){var t=this;this.dateCreated=ko.observable();this.dateModified=ko.observable();this.id=ko.observable();this.name=ko.observable();this.description=ko.observable();this.moduleOptionSet=ko.observableArray();this.addModuleOption=function(n){return this.moduleOptionSet()==null&&(this.moduleOptionSet=ko.observableArray()),this.moduleOptionSet.push(n),!0};this.removeModuleOption=function(n){this.moduleOptionSet.remove(n)};n&&this.update(n)};ko.utils.extend(Tier.prototype,{update:function(n){n=n||{};this.name(n.name);this.dateCreated(n.dateCreated);this.dateModified(n.dateModified);this.id(n.id);this.description(n.description);n.moduleOptionSet&&this.moduleOptionSet(n.moduleOptionSet)},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,dateCreated:n.DateCreated,dateModified:n.DateModified,name:n.Name,description:n.Description};return n.ModuleOptionSet&&(t.moduleOptionSet=n.ModuleOptionSet.map(function(n){return(new ModuleOption).fromServerModel(n)})),this.update(t),this},toServerModel:function(){var n={Id:this.id(),Name:this.name(),Description:this.description()};return this.moduleOptionSet()!=null&&(n.ModuleOptionSet=this.moduleOptionSet().map(function(n){return n.toServerModel()})),n}});Url=function(n){var t=this;t.cache=function(){};this.text=ko.observable();this.url=ko.observable();this.date=ko.observable();n&&this.update(n)};ko.utils.extend(Url.prototype,{update:function(n){n=n||{};this.text=n.text;this.url=n.url;this.date=n.date;this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={text:n.Text,url:n.Url,date:PF.parseMVCDate(n.PostDate)};return this.update(t),this}});User=function(n){var t=this;t.cache=function(){};this.deleted=ko.observable(!1);this.id=ko.observable();this.firstName=ko.observable();this.lastName=ko.observable();this.email=ko.observable();this.dateCreated=ko.observable();this.sendNewsletter=ko.observable();this.emailIsValidated=ko.observable();this.account=ko.observable();this.accounts=ko.observableArray();this.isTrial=ko.observable();this.blacklistDate=ko.observable();this.blacklistReason=ko.observable();this.customGroups=ko.observableArray();this.organizationName=ko.computed(function(){return t.account()?t.account().organizationName():null});this.fullName=ko.computed(function(){return(t.firstName()?t.firstName():"")+" "+(t.lastName()?t.lastName():"")});this.phone=ko.computed(function(){return t.account()?t.account().phone():null});this.address1=ko.computed(function(){return t.account()?t.account().address1():null});this.city=ko.computed(function(){return t.account()?t.account().city():null});this.stateOrProvince=ko.computed(function(){return t.account()?t.account().stateOrProvince():null});this.externalWebsiteUrl=ko.computed(function(){return t.account()?t.account().externalWebsiteUrl():null});n&&this.update(n)};ko.utils.extend(User.prototype,{update:function(n){n=n||{};this.id(n.id);this.firstName(n.firstName||"");this.lastName(n.lastName||"");this.email(n.email||"");this.dateCreated(n.dateCreated);this.emailIsValidated(n.emailIsValidated);this.blacklistDate(n.blacklistDate);this.blacklistReason(n.blacklistReason);this.sendNewsletter(n.sendNewsletter);this.account(n.account);this.accounts(n.accounts);this.customGroups(n.customGroups);this.cache.latestData=n},revert:function(){this.update(this.cache.latestData)},commit:function(){this.cache.latestData=ko.toJS(this)},fromServerModel:function(n){var t={id:n.Id,firstName:n.FirstName,lastName:n.LastName,email:n.Email,dateCreated:n.DateTimeCreated,sendNewsletter:n.SendNewsletter,emailIsValidated:n.EmailIsValidated,blacklistDate:n.EmailBlackListDate,blacklistReason:n.EmailBlackListReason};return n.SpaceProvider&&(t.account=(new Account).fromServerModel(n.SpaceProvider)),n.Accounts&&(t.accounts=n.Accounts.map(function(n){return(new Role).fromServerModel(n)})),n.CustomGroups&&(t.customGroups=n.CustomGroups.map(function(n){return(new CustomGroup).fromServerModel(n)})),this.update(t),this},toServerModel:function(n){var t={Id:this.id(),FirstName:this.firstName(),LastName:this.lastName(),Email:this.email(),SendNewsletter:this.sendNewsletter(),EmailBlackListDate:this.blacklistDate(),EmailBlackListReason:this.blacklistReason()};return this.customGroups()&&(t.CustomGroups=this.customGroups().map(function(n){return n.toServerModel()})),n&&(this.account()&&(t.SpaceProvider=this.account().toServerModel()),this.accounts()&&(t.Accounts=this.accounts().map(function(n){return n.toServerModel()}))),t}});VariableObject=function(n){var t=this;t.count=ko.observable();t.space_ids=ko.observableArray();n&&this.update(n)};ko.utils.extend(VariableObject.prototype,{update:function(n){n=n||{};this.count(n.count);this.space_ids(n.space_ids)},fromServerModel:function(n){var t=JSON.parse(n),i={count:t.count,space_ids:t.space_ids||[]};return this.update(i),this},toServerModel:function(){var n={count:this.count(),space_ids:this.space_ids()};return JSON.stringify(n)}});var ListingDetailViewModel=function(n,t,i){var r=this;r.view=t;r.loaded=ko.observable(!1);r.listing=ko.observable();r.booking=ko.observable(new Booking);r.selectedRentalRate=ko.observable();r.timeSlots=ko.observableArray([]);r.selectedTimeSlot=ko.observable();r.busy=ko.observable(!1);r.gettingBooking=ko.observable();r.curDay=ko.observable(i||new Date);r.firstDate=ko.observable();r.avails={};r.availGuids={};r.events=[];r.firstEvent=null;r.monthsAhead=0;r.soldOut=ko.observable(!1);r.expiredListing=ko.observable(!1);r.errorMessage=ko.observable();r.packageMode=!1;r.packageCategoryId="C2CEE8AC-31F5-4A0D-8F4A-930C436CE17A";r.timeControls;r.startTime=ko.observable();r.endTime=ko.observable();r.minDropdownTime=ko.observable();r.maxDropdownTime=ko.observable();r.enteredPassword=ko.observable();r.isPasswordValid=ko.observable(!1);r.passwordSubmitted=ko.observable(!1);r.isBeforeCutOffDate=ko.computed(function(){var n=new Date;return Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate())<Date.UTC(2015,11,15)});r.bookingDuration=ko.computed(function(){if(r.curDay()&&r.startTime()&&r.endTime()){var n=r.startTime(),t=r.endTime(),i=PF.getHoursBetween(new Date(PF.formatDate(r.curDay())+" "+n),new Date(PF.formatDate(r.curDay())+" "+t));return Math.ceil(i*2)/2}return null});r.validRates=ko.computed(function(){if(!r.listing())return[];const n=r.listing().validRates(r.booking(),r.selectedTimeSlot());return n.length==0?[new RentalRate({rateRule:new RateRule({})})]:n});r.bookNowButtonDisabled=ko.computed(function(){const n=r.selectedTimeSlot();if(n&&n.isContinousId&&n.createdBySpaceAvailability){const t=PF.Moment(n.createdBySpaceAvailability.StartDate+" "+n.start.getHours()+":"+n.start.getMinutes()),i=PF.Moment();if(i.isAfter(t)||n.start>t)return!0}return!r.booking().id()||r.busy()||r.errorMessage()});r.selectedRentalRate.subscribe(function(){if(r.booking()&&!r.booking().validateResources())return!1;r.getBooking()});r.load=function(t,i,u){i&&r.listing(i);n&&r.listing(n);u&&(r.view=u);r.init();r._viewEditListingAddOns||r.isBeforeCutOffDate()||r.listing().account().isProPayEnabled()||r.listing().account().isTrxEnabled()||r.listing().account().providerType()===0||!r.listing().defaultRate()||!r.listing().defaultRate().rateRule()||r.listing().defaultRate().rateRule().ruleName()===PF.RateRule.Appointment||r.listing().defaultRate().rateRule().ruleName()===PF.RateRule.Referral||r.errorMessage("Oops...looks like this listing is not available for online booking. Please contact the merchant directly"+(r.listing().account().phone()?" at "+r.listing().account().phone():"."));t&&t()};r.refresh=function(){r.avails={};r.availGuids={};r.events=[];r.firstEvent=null;r.monthsAhead=0;r.selectedTimeSlot("");$(".pf-sidebar-section-content",r.view).show();r.bindCalendar();r.goDate(r.curDay())};r.resetTimeSlotCalendarVars=function(){r.avails={};r.availGuids={};r.events=[];r.selectedTimeSlot("")};r.init=function(){r.bindCalendar();r.loaded(!0)};r.listing.subscribe(function(n){n.spaceCategoryId()===r.packageCategoryId&&(r.packageMode=!0);r.selectedRentalRate(n.defaultRate())});r.mapBound=ko.observable(!1);r.bindMap=function(){if(!r.mapBound()){r.mapBound(!0);var i=$("#map"),n=PF.Controls.ResultsMap,t=L.latLng(r.listing().lat(),r.listing().long());n.Init({mapEl:i,center:t});n.SetMarker({title:r.listing().name(),html:"<h4>"+r.listing().name()+"<\/h4><p>"+r.listing().fullAddress()+"<\/p>",position:t});$('a[data-toggle="tab"]').on("shown",function(){n.Resize()})}};r.bindCalendar=function(){$(".calendar",r.view).empty();$(".calendar",r.view).fullCalendar({header:{left:"prev",center:"title",right:"next"},titleFormat:{month:"MMMM"},dayNamesShort:["S","M","T","W","T","F","S"],allDaySlot:!1,defaultView:"month",editable:!1,selectable:!1,viewDisplay:function(){r.resetTimeSlotCalendarVars();r.calendarRender()},dayClick:function(n){r.goDate(n)},eventClick:function(n){r.goDate(n.start,n)},year:r.curDay().getFullYear(),month:r.curDay().getMonth(),date:r.curDay().getDate()})};r.addAvails=function(n){var i,t,u;if(r.expiredListing()){r.booking(new Booking);r.booking().id(null);r.gettingBooking(!1);return}if($(".pf-sidebar-section-content",r.view).show(),i=r.listing().minNotice(),t=new Date,t.setHours(t.getHours()+i),u=r.listing().minRentalDuration()/60||2,$.each(n,function(n,i){var f,o,e,c,s,h;r.availGuids["guid"+i.CalendarDate+""+i.ActualBlockStartTime+i.ActualEndTime]!=!0&&(f=new Date(i.CalendarDate+" "+i.ActualBlockStartTime),o=new Date(i.CalendarDate+" "+i.ActualEndTime),o<f&&o.setDate(o.getDate()+1),e=new Date(o.valueOf()),e.getMinutes()==59&&e.getHours()==23&&e.setMinutes(e.getMinutes()+1),e>t&&(f<t&&PF.isSameDay(f,t)&&(f=new Date(t.valueOf()),c=30-f.getMinutes()%30,f.setMinutes(f.getMinutes()+c)),PF.getHoursBetween(f,e)>=u&&(r.availGuids["guid"+i.CalendarDate+""+i.ActualBlockStartTime+i.ActualEndTime]=!0,s=[],$.each(i.SpaceAvailabilities,function(){var n,i,u;n=new Date(this.StartDate+" "+this.StartTime);i=new Date(this.StartDate+" "+this.EndTime);i.setMinutes(i.getMinutes()+30);i>t&&(n<t&&PF.isSameDay(n,t)&&(n=t,u=30-n.getMinutes()%30,n.setMinutes(n.getMinutes()+u)),n.setSeconds(0),s.push({rate:this.AvailabilityRate||r.listing().minRentalFee(),startTime:PF.formatTime(n),endTime:PF.formatTime(i)}))}),f.setSeconds(0),h={start:f,end:o,type:"available",title:"Available",allDay:!1,className:"available",color:"#51a351",textColor:"#000",guid:i.Id,rates:s,isContinousId:i.SpaceAvailabilities[0].CalendarType.CalendarTypeName==PF.CalendarType.MultiDayAvailability.CalendarTypeName?i.SpaceAvailabilities[0].Id:null,packagesRemaining:i.AvailabilityQtyNet,packagesTotal:i.AvailabilityQty,createdBySpaceAvailability:i.CreatedBySpaceAvailability},r.firstEvent||(r.firstEvent=h),r.events.push(h))))}),n.length>0&&r.events.length==0){r.booking(new Booking);r.booking().id(null);r.gettingBooking(!1);return}r.events.sort(r.compareEvents);r.paintEvents();!r.firstEvent&&r.monthsAhead<11&&!r.expiredListing()?($(".calendar .fc-button-next",r.view).click(),r.monthsAhead++):!r.firstEvent&&r.monthsAhead>=11&&(r.soldOut(!0),$(".pf-sidebar-section-content",r.view).hide())};r.calendarRender=function(){var n=$(".calendar",r.view),i,t,u;$(".calendar .fc-button-next").hide();$(".calendar .fc-button-prev").hide();i=n.fullCalendar("getDate");r.firstDate()&&(i=r.firstDate());t=new Date(i.getFullYear(),i.getMonth(),1);u=new Date(new Date(t.getFullYear(),t.getMonth()+1,1)-1);r.getCalendarAvailabilities(t,u,function(){var i,f,u;if(curView=n.fullCalendar("getView"),n.removeClass("month agendaWeek"),n.addClass(curView.name),n.find(".selected-day-column").removeClass("selected-day-column"),n.find(".fc-widget-content").removeClass("previous available"),n.find("td.fc-widget-content div.fc-day-number").each(function(){$(this).parent().parent().attr("date",$.trim($(this).text()))}),i=new Date,curView.end<i)n.find(".fc-widget-content").addClass("previous");else if(curView.start<i)for(f=i.getDate(),u=1;u<f;u++)n.find("td.fc-widget-content[date="+u+"]").addClass("previous");curView.name=="month"&&n.find("tr.fc-last td.fc-other-month").length==7?n.find("tbody tr.fc-last").hide():n.find("tr.fc-last").show();r.paintEvents();(r.curDay().getFullYear()!==t.getFullYear()||r.curDay().getMonth()!==t.getMonth())&&$.each(r.events,function(n,i){if(i.start.getMonth()==t.getMonth())return r.goDate(i.start),!1;n==r.events.length-1&&r.curDay(t)})})};r.paintEvents=function(){r.events&&r.events[0]&&(r.firstEvent=r.events[0]);var n=$(".calendar",r.view);n.fullCalendar("removeEvents");$.each(r.events,function(n,t){r.getCellByDate(t.start).addClass(t.type)});n.find(".fc-widget-content").each(function(){var n=$(this);n.hasClass("available")?n.attr("title","Listing has availability on this date."):n.hasClass("previous")?n.attr("title","Date occurs in the past."):n.attr("title","Listing is not available on this date.")});r.firstEvent&&!r.firstEvent.hasRendered?(r.firstEvent.hasRendered=!0,i&&i.getFullYear()===r.curDay().getFullYear()&&i.getMonth()===r.curDay().getMonth()?r.goDate(i):r.goDate(r.firstEvent.start)):(r.timeSlots([]),r.selectedTimeSlot(null),r.booking(new Booking),r.booking().id(null))};r.getCellByDate=function(n){var i=$(".calendar",r.view),u=i.fullCalendar("getView").start,t;return n.getFullYear()==u.getFullYear()&&n.getMonth()==u.getMonth()?(t=i.find("td.fc-widget-content[date="+n.getDate()+"]"),t.first().hasClass("fc-other-month")&&t.length==2)?t.last():t.first():i.find("null")};r.goDate=function(n,t){var u=$(".calendar",r.view),f=new Date,i;if(typeof t=="undefined"&&(t=r.getEventByDate(n)),$(".selected-day-column",u).removeClass("selected-day-column"),i=$.grep(r.events,function(n){return t&&t.isContinousId&&t.isContinousId==n.isContinousId}),$.each(i,function(i,u){r.getCellByDate(u.start).addClass("selected-day-column");u.start<n&&(n=u.start,t=r.getEventByDate(n))}),(n>f||PF.isSameDay(n,f))&&(!r.selectedTimeSlot()||!PF.isSameDay(n,r.curDay()))){if(r.curDay(n),r.timeSlots([]),r.selectedTimeSlot(null),r.booking(new Booking),r.booking().id(null),!t)return!1;u.fullCalendar("gotoDate",n);r.eventClick(t);r.timeSlots($.grep(r.events,function(t){return PF.isSameDay(n,t.start)}))}return i.length==0&&t&&r.getCellByDate(t.start).addClass("selected-day-column"),!0};r.getEventByDate=function(n){var t=null;return $.each(r.events,function(i,r){if(PF.isSameDay(n,r.start)&&(!t||PF.Moment(r.start).isBefore(t.start)))return t=r,!1}),t};r.compareEvents=function(n,t){return!n&&!t?0:n?t?n.start<t.start?-1:n.start>t.start?1:0:1:-1};r.selectTimeSlot=function(n){r.eventClick(n)};r.eventClick=function(n){if(r.selectedTimeSlot()!==n){var t=r.listing().minRentalDuration()/60||2;r.maxDropdownTime(PF.formatTime(n.end));r.minDropdownTime(PF.formatTime(n.start));r.gettingBooking(!0);r.endTime(r.maxDropdownTime());r.startTime(r.minDropdownTime());r.endTime(PF.Moment(r.startTime(),["H:mm","hh:mm a","hh:mm A"]).add("hours",t).format("H:mm"));r.gettingBooking(!1);r.selectedTimeSlot(n);r.selectedRentalRate(r.validRates()[0])}};r.getBooking=function(){r.busy(!0);r.requestBooking(function(n){n.Success?(r.errorMessage(null),r.booking().id()||r.goDate(r.curDay()),r.booking().fromServerModel(n.Item),r.booking().validateResources(),r.booking().subscribeResourceUpdates(r.resourcePricingQtyUpdate)):r.errorMessage("There was an error booking this space:<br>"+n.Error);r.busy(!1)})};r.setRentalRate=function(n){return r.selectedRentalRate(n),!0};r.verifyPassword=function(){r.busy(!0);$.ajax({url:"/api/listings/VerifyListingPassword",type:"POST",dataType:"json",data:JSON.stringify({Item:new Space({id:r.listing().id()}).toServerModel(),PasswordToVerify:r.enteredPassword()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){r.busy(!1);r.passwordSubmitted(!0);n.Success?r.isPasswordValid(n.Item):PF.Modals.Generic.Show({title:"Error verifying listing password",description:"Sorry, we hit a snag verifying the password you entered. Please try again. Error: "+n.Error})}).fail(function(n){r.busy(!1);PF.Modals.Generic.Show({title:"Error verifying listing password",description:"Sorry, we hit a snag verifying the password you entered. Please try again. "+n.Error})})};r.getCalendarAvailabilities=function(n,t,i){r.busy(!0);$.ajax({url:"/api/listings/getavailability",type:"POST",dataType:"json",data:JSON.stringify({account:r.id,listingId:r.listing().id(),startDate:PF.formatDateTime(n),endDate:PF.formatDateTime(t)}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(r.busy(!1),$(".calendar .fc-button-next").show(),$(".calendar .fc-button-prev").show(),r.firstDate(undefined),t.Success){const f=n.getMonth(),u="m"+f+"y"+n.getFullYear();r.avails[u]=t.Availabilities;r.avails[u]=r.avails[u].filter(n=>{const t=new Date(n.CalendarDate+" "+n.ActualBlockStartTime);return f===t.getMonth()});r.expiredListing(t.ExpiredListing);r.addAvails(r.avails[u]);i&&i()}else r.errorMessage(t.Error)}).fail(function(n){r.busy(!1);$(".calendar .fc-button-next").show();$(".calendar .fc-button-prev").show();r.firstDate(undefined);r.errorMessage(n.Error)})};r.resourcePricingQtyUpdate=function(){var n=0;$.each(r.booking().resources(),function(t,i){(isNaN(i.quantityPurchased())||i.quantityPurchased()<0)&&i.quantityPurchased(0);i.booking(r.booking());n+=i.totalPurchase()});r.booking().totalResourceFee(n)};r.requestBooking=function(n){var t={Item:r.listing().id(),StartDate:PF.formatDate(r.curDay()),StartTime:r.startTime(),EndDate:PF.formatDate(r.curDay()),EndTime:r.endTime(),SitePromotionCode:"",RateRuleName:r.selectedRentalRate().rateRule().ruleName(),CalendarType:{CalendarTypeName:PF.PrivateLabel.Site?"Private Booking":null},RateRuleId:r.selectedRentalRate().id(),AvailabilityQtyUsed:r.selectedRentalRate().availabilityQtyUsed()};const i=r.selectedTimeSlot();if(i&&i.isContinousId){const n=new Date(i.end);if(n.setHours(i.start.getHours(),i.start.getMinutes()),i.end<n){const n=new Date(r.curDay()),i=new Date(r.curDay());i.setHours(0,0,0);const u=new Date(r.curDay());u.setHours(0,0,0);i<=u&&n.setDate(r.curDay().getDate()+1);t.EndDate=PF.formatDate(n);t.StartTime=undefined}}const u=PF.Moment(t.StartDate+" "+t.StartTime),f=PF.Moment(t.EndDate+" "+t.EndTime);if(u.isAfter(f)){r.busy(!1);return}if(t.StartTime==null&&t.EndTime==null){r.busy(!1);return}r.gettingBooking()||(r.gettingBooking(!0),r.errorMessage(null),$.ajax({url:"/api/listings/requestbooking",type:"POST",dataType:"json",data:JSON.stringify(t),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){r.gettingBooking(!1);n&&n(t)}).fail(function(){r.errorMessage("An error has occurred. ")}),r._viewEditListingAddOns||r.isBeforeCutOffDate()||r.listing().account().isProPayEnabled()||r.listing().account().isTrxEnabled()||r.listing().account().providerType()===0||r.listing().defaultRate().rateRule().ruleName()===PF.RateRule.Appointment||r.listing().defaultRate().rateRule().ruleName()===PF.RateRule.Referral||r.errorMessage((r.errorMessage()?r.errorMessage()+"<br/>":"")+"Oops...looks like this listing is not available for online booking. Please contact the merchant directly"+(r.listing().account().phone()?" at "+r.listing().account().phone():".")))};r.book=function(){var i,n,t;if(r.bookNowButtonDisabled()||!r.booking().validateResources())return!1;r.booking().id()&&(i="/Payment/Checkout"+window.location.search,n=document.createElement("form"),n.setAttribute("method","POST"),n.setAttribute("action",i),t=document.createElement("input"),t.setAttribute("type","hidden"),t.setAttribute("name","booking"),t.setAttribute("value",JSON.stringify(r.booking().toServerModel())),n.appendChild(t),document.body.appendChild(n),n.submit())};r.bookReferral=function(){PF.Modals.ReferralInquiry.Show({spaceId:r.listing().id()})};r.back=function(){PF.wizard.pop()}},LoginViewModel=function(n,t){var i=this;i.container=n;i.email=ko.observable();i.password=ko.observable();i.remember=ko.observable(!0);i.errorMessage=ko.observable(t);i.load=function(){$(document).keyup(function(t){var r=t.keyCode?t.keyCode:t.which;r==13&&i.password()&&i.password().length>3&&i.email()&&i.email().length>=3&&n.find("#btnSignIn").click()}),function(n){var t,i="facebook-jssdk",r=n.getElementsByTagName("script")[0];n.getElementById(i)||(t=n.createElement("script"),t.id=i,t.async=!0,t.src="//connect.facebook.net/en_US/all.js",r.parentNode.insertBefore(t,r))}(document);i.errorMessage()&&PF.Modals.Generic.Show({title:"Error",description:i.errorMessage()})};i.clearErrorMessage=function(){i.errorMessage(null)};i.signIn=function(){var t=n.find("#frmLogin").data("action-url"),r;t?(r={FacebookAccessCode:n.find("#FacebookAccessCode").val(),RedirectUrl:n.find("#frmLogin").data("redirect-url"),"User.Id":n.find("#User.Id").val(),Email:i.email(),Password:i.password(),RememberMe:i.remember()},$.ajax({type:"POST",url:t,data:JSON.stringify(r),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){t.Success?t.Redirect&&window.location.replace(t.Redirect):(n.find("html, body").animate({scrollTop:0},500),i.errorMessage(t.Error))}})):n.find("#frmLogin").submit()};i.signInWithFacebook=function(){FB.login(function(n){n.authResponse&&($("#FacebookAccessCode").pVal(n.authResponse.accessToken),i.signIn())},{scope:"email"})}},MerchantClaimViewModel=function(n,t,i){var r=this,u=null;this.data=ko.observable(n);this.redirectUrl=t;this.sent=ko.observable(!1);this.faceBookConversionTracking={USAG:"6017780492205",HOMEINSPECTION:"6017797438805",CCSA:"6017780491205",ART:"6017797420405",ZIPLINE:"6017797421405",LASERTAG:"6017797423405",GOKART:"6017797425005",PAINTBALL:"6017797443005"};this.save=function(){(u==null&&(u=(new PF.FormValidator).Init({container:$("#demo-form")})),u.Validate())&&(pf_dataLayer.push({event:"sendVirtualPageview",vpv:"/Claim/?clickedSubmit&"+n.source().toUpperCase()}),$.ajax({url:"/Marketing/SendClaimToSales",type:"POST",dataType:"json",data:JSON.stringify(r.data().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(t.Success){r.sent(!0);pf_dataLayer.push({eventLabel:"Claim Page",event:"Claim - Click Request Info",eventCategory:"Self Sign Up"});var u=r.faceBookConversionTracking[n.source().toUpperCase()];u&&i.prepend('<img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?ev='+u+'&amp;cd[value]=0.00&amp;cd[currency]=USD&amp;noscript=1" />')}else console.log(t)}).fail(function(){console.log(results)}))};r.startTrial=function(){$.ajax({url:"/Properties/Merchant/StartTrial?id="+r.data().id(),type:"POST",dataType:"json",processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(t.Success){r.sent(!0);pf_dataLayer.push({eventLabel:"Claim Page",event:"Claim - Click Start Trial",eventCategory:"Self Sign Up"});var u=r.faceBookConversionTracking[n.source().toUpperCase()];u&&i.prepend('<img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?ev='+u+'&amp;cd[value]=0.00&amp;cd[currency]=USD&amp;noscript=1" />');console.log(t)}else console.log(t)}).fail(function(){console.log(results)})}},AsyncPagedListViewModel=function(n,t,i,r){var u=this,f;u.innerList=ko.observableArray(n);u.pageSize=ko.observable(10);u.pageIndex=ko.observable(0);u.selectedItem=ko.observable();u.filters=ko.observableArray(t||[]);u.conversionVar=ko.observable();u.filterProviderType=ko.observable();u.serverObjectType=null;u.isLoading=ko.observable(!0);u.isMoveToPage=ko.observable(!1);u.pageLoadCallback=i;u.args=r;u.totalCount=ko.observable(0);u.searchControl=ko.observable(!1);u.windowScrollPosition=0;u.loadData=function(n){if(u.isLoading(!0),u.innerList().length!=0&&u.innerList().length>=u.totalCount()){u.isLoading(!1);return}u.pageLoadCallback&&u.pageLoadCallback(function(t,i){u.isLoading(!1);var r=t.Item;n||u.innerList([]);u.serverObjectType=i;u.serverObjectType&&(r=t.Item.map(function(n){return(new i).fromServerModel(n)}));const f=[];$.each(r,function(n,t){f.push(t)});u.innerList(u.innerList().concat(f));u.windowScrollPosition!=0&&$(document).scrollTop(u.windowScrollPosition);u.pageIndex(t.PageNumber-1);u.totalCount(t.TotalCount)})};f=_.debounce(function(){u.windowScrollPosition=$(document).scrollTop();u.pageIndex(0);u.innerList([]);u.loadData()},1e3);u.load=function(){u.args&&u.args.PageSize&&u.pageSize(u.args.PageSize);u.loadData();u.findFilter("text")&&u.findFilter("text").value.subscribe(function(){f()});u.findFilter("providerType")&&u.findFilter("providerType").value.subscribe(function(){u.pageIndex(0);u.innerList([]);u.loadData()});u.findFilter("spaceId")&&u.findFilter("spaceId").value.subscribe(function(){u.windowScrollPosition=$(document).scrollTop();u.pageIndex(0);u.innerList([]);u.loadData()});u.findFilter("listingId")&&u.findFilter("listingId").value.subscribe(function(){u.windowScrollPosition=$(document).scrollTop();u.pageIndex(0);u.innerList([]);u.loadData()})};u.reload=function(){u.innerList([]);u.pageIndex(0);u.load()};u.reloadToPage=function(){var n=u.pageIndex(),t=u.innerList().slice(0,u.pageIndex()*u.pageSize());u.innerList(t);u.pageIndex(n);u.loadData()};u.reloadNotification=function(n){var t=u.pageIndex();u.innerList(n);u.pageIndex(t)};u.findFilter=function(n){var t="";return $.each(u.filters(),function(i,r){if(r.name===n)return t=r,!1}),t};u.applyFilter=function(n,t){var i=u.findFilter(n);i&&t(i)};u.getFilterText=function(n){var t="";return u.applyFilter(n,function(n){t=n.text()}),t};u.maxPageIndex=ko.dependentObservable(function(){return u.totalCount()?Math.ceil(u.totalCount()/u.pageSize())-1:0});u.previousPage=function(){u.pageIndex()>0&&(u.pageIndex(u.pageIndex()-1),u.windowScrollPosition=$(document).scrollTop())};u.nextPage=function(){u.pageIndex()<u.maxPageIndex()&&(u.windowScrollPosition=$(document).scrollTop(),u.pageIndex(u.pageIndex()+1),u.loadData(!0))};u.previousPageWithMovePage=function(){if(u.pageIndex()>0){const n=u.pageIndex()-1;u.moveToPage(n)}};u.nextPageWithMovePage=function(){if(u.pageIndex()<u.maxPageIndex()){const n=u.pageIndex()+1;u.moveToPage(n)}};u.allPages=ko.dependentObservable(function(){for(var i=[],t="",n=0;n<=u.maxPageIndex();n++)j=n+1,t=n==0||n==u.maxPageIndex()||Math.abs(n-u.pageIndex())<4?n==u.pageIndex()?j:j:t=="..."||t==""?"":"...",t!=""&&i.push({pageNumber:t,disabled:t==="..."});return i});u.moveToPage=function(n){u.windowScrollPosition=$(document).scrollTop();u.innerList([]);u.pageIndex(n);u.isMoveToPage(!0);u.loadData(!1)};u.pagedList=ko.dependentObservable(function(){var t=u.pageSize(),n;return u.isMoveToPage()?u.innerList():(u.pageIndex()>u.maxPageIndex()&&u.pageIndex(0),n=u.pageIndex()*t,u.innerList().slice(n,n+t))})},RequestDemoViewModel=function(n,t){var i=this,r=null;this.data=ko.observable(n);this.redirectUrl=t;this.save=function(){var n=document.getElementById("reCaptchaResponse"),t;(n&&(t=n.value),r==null&&(r=(new PF.FormValidator).Init({container:$("#demo-form")})),i.data().email()&&i.data().email(i.data().email().replace(/ /g,"")),r.Validate())&&(pf_dataLayer.push({event:"sendVirtualPageview",vpv:"/My/Welcome/Demo?clickedSubmit"}),$.ajax({url:"/Marketing/SendDataToSales",type:"POST",dataType:"json",data:JSON.stringify({leadDataSales:i.data().toServerModel(),reCaptchaResponse:t}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){if(n.Success)window.location.replace(i.redirectUrl);else if(n.Success||n.Error!="ReCaptchaError")console.log(n);else{var t=document.getElementById("reCaptchaHelp");t.classList.remove("hidden")}}).fail(function(n){console.log(n)}))}},Wizard=function(){return{viewStack:[],container:ko.observable(),progressPerc:0,init:function(n){var t=this;this.container(n)},_detachInactiveViews:function(){var n=this.activeView();_.each(this.viewStack,function(t){t!==n&&$(t.view).detach()})},_loadView:function(n,t){var i=this;$.ajax({type:"GET",url:n,cache:!1}).done(function(n){var i=$(n);typeof t=="function"&&t(i,n)}).fail(function(n){console.log(n.responseText)})},_render:function(n,t,i){var r=this;t.load&&typeof t.load=="function"?t.load(function(){ko.applyBindings(t,$(n)[0])}):ko.applyBindings(t,$(n)[0]);typeof i=="function"&&i($(n))},_popView:function(){var t=this.viewStack.pop(),n=_.last(this.viewStack);return t&&n&&(t.view.detach(),n.cleanView&&(n.view=$(n.cleanView),ko.applyBindings(n.viewModel,n.view[0])),n.view.appendTo($(".views",this.container())),n.viewModel.refresh&&typeof n.viewModel.refresh=="function"&&n.viewModel.refresh()),n},activeView:function(){return _.last(this.viewStack)},push:function(n,t,i){var r=this;$("html, body").animate({scrollTop:0},500);typeof n=="string"?this._loadView(n,function(n,u){r.viewStack.push({view:n,viewModel:t,cleanView:u});r._detachInactiveViews();$(".views",r.container()).append(n);r._render(n,t,i)}):(r.viewStack.push({view:n,viewModel:t}),r._detachInactiveViews(),$(".views",r.container()).append(n),r._render(n,t,i))},pop:function(n){if(n&&n.viewModel()){for(var t=this._popView();t&&t.viewModel!==n.viewModel();)t=this._popView();return t}return this._popView()}}},MerchantDashboardViewModel=function(n,t){var i=this;i.user=ko.observable(n);i.bitcoinMode=ko.observable(t=="True");i.dateDay1=ko.observable(new Date);i.bookingsDay1=ko.observableArray();i.dateDay2=ko.observable(new Date);i.bookingsDay2=ko.observableArray();i.dateDay3=ko.observable(new Date);i.bookingsDay3=ko.observableArray();i.selectedBookingGroup=ko.observable();i.bookingActivity=ko.observableArray();i.goodActivity=ko.observableArray();i.error=ko.observable();i.loadGoods=function(n){var t=new Date,r;t.setDate(t.getDate()+1);r=new Date;r.setDate(t.getDate()-30);$.get("/My/Dashboard/GetGoods",{startDate:PF.formatDate(r),endDate:PF.formatDate(t),page:1}).success(function(t){if(t.Success&&t.Item){var r=t.Item.map(function(n){return(new GoodPurchase).fromServerModel(n)});r=r.sort(function(n,t){return PF.parseMVCDate(n.dateCreated())>PF.parseMVCDate(t.dateCreated())?-1:1});i.goodActivity(r);n&&typeof n.success=="function"&&n.success()}})};i.loadBookings=function(n){var r=new Date,t;r.setDate(r.getDate()+1);t=new Date;t.setDate(t.getDate()-30);$.get("/My/Dashboard/GetBookings",{bookingStartDate:PF.formatDate(t),bookingEndDate:PF.formatDate(r),page:1,pageSize:100}).success(function(t){if(t.Success&&t.Item){var r=t.Item.map(function(n){return(new Booking).fromServerModel(n)});r=r.sort(function(n,t){return PF.parseMVCDate(n.bookingDate())>PF.parseMVCDate(t.bookingDate())?-1:1});i.bookingActivity(r);n&&typeof n.success=="function"&&n.success()}})};i.loadAgenda=function(n){var t=new Date(i.dateDay3());t.setDate(t.getDate()+1);$.get("/My/Dashboard/GetBookings",{startDate:PF.formatDate(i.dateDay1()),endDate:PF.formatDate(t),page:1,pageSize:100}).success(function(t){if(t.Success&&t.Item){var e=t.Item.map(function(n){return(new Booking).fromServerModel(n)}),r=[],u=[],f=[];$.each(e,function(n,t){var o=null,e=PF.parseMVCDate(t.originalStartDate()),s;e.getFullYear()===i.dateDay1().getFullYear()&&e.getMonth()===i.dateDay1().getMonth()&&e.getDate()===i.dateDay1().getDate()?o=r:e.getFullYear()===i.dateDay2().getFullYear()&&e.getMonth()===i.dateDay2().getMonth()&&e.getDate()===i.dateDay2().getDate()?o=u:e.getFullYear()===i.dateDay3().getFullYear()&&e.getMonth()===i.dateDay3().getMonth()&&e.getDate()===i.dateDay3().getDate()&&(o=f);o&&(s=$.grep(o,function(n){return n.space().id()===t.space().id()&&n.startDate()===t.startDate()}),s&&s.length!==0?s&&s.length>0&&s[0].bookings.push(t):o.push({space:t.space,startDate:t.startDate,endDate:t.endDate,bookings:[t],startTime:t.startTime,endTime:t.endTime}))});r=r.sort(function(n,t){return parseInt(PF.formatTimeMilitary(n.startDate()).replace(":",""))>parseInt(PF.formatTimeMilitary(t.startDate()).replace(":",""))?1:-1});u=u.sort(function(n,t){return parseInt(PF.formatTimeMilitary(n.startDate()).replace(":",""))>parseInt(PF.formatTimeMilitary(t.startDate()).replace(":",""))?1:-1});f=f.sort(function(n,t){return parseInt(PF.formatTimeMilitary(n.startDate()).replace(":",""))>parseInt(PF.formatTimeMilitary(t.startDate()).replace(":",""))?1:-1});i.bookingsDay1(r);i.bookingsDay2(u);i.bookingsDay3(f);n&&typeof n.success=="function"&&n.success()}})};i.loadMetrics=function(n){var t="/My/Dashboard/GetMetrics";i.bitcoinMode()&&(t="/api/Bitcoin/GetDashboardMetrics");$.get(t,{}).success(function(t){t.Success?(i.user().account().metrics(t),n&&typeof n.success=="function"&&n.success()):i.error("Account Metrics: "+t.Error)})};i.load=function(){const n=i.user().account().timeZone();i.dateDay1(new Date(window.PF.Moment().tz(n).format("YYYY-MM-DDTHH:mm:ss")));i.dateDay2(new Date(window.PF.Moment().tz(n).add(1,"days").format("YYYY-MM-DDTHH:mm:ss")));i.dateDay3(new Date(window.PF.Moment().tz(n).add(2,"days").format("YYYY-MM-DDTHH:mm:ss")));i.loadAgenda();i.loadBookings();i.loadGoods();i.loadMetrics({success:function(){var n=i.user().account().metrics();n&&(i.renderBookingsHeatMap(n.BookingsByTime),i.renderBooking12MonthChart(n),i.renderBitcoin30DayChart(n))}})};i.selectBookingGroup=function(n){i.selectedBookingGroup(n)};i.closeSelectedBookingGroup=function(){i.selectedBookingGroup(null)};i.renderBooking12MonthChart=function(n){var e;n.YtdBookingsByMonth||(n.YtdBookingsByMonth=[]);_.each([1,2,3,4,5,6,7,8,9,10,11,12],function(t){_.find(n.YtdBookingsByMonth,function(n){return n.Month===t})||n.YtdBookingsByMonth.push({Month:t,Count:0})});e=["J","F","M","A","M","J","J","A","S","O","N","D"];_.each(n.YtdBookingsByMonth,function(n){n.MonthText=e[n.Month-1]});var t={top:10,right:10,bottom:10,left:10},o=225-t.left-t.right,u=75-t.top-t.bottom,i=d3.scale.ordinal().rangeRoundBands([0,o],.1),r=d3.scale.linear().range([u,0]),s=d3.svg.axis().scale(i).orient("bottom"),h=d3.svg.axis().scale(r).orient("left"),f=d3.select("#chart-bookings-ytd-monthly").append("svg").attr("width",o+t.left+t.right).attr("height",u+t.top+t.bottom).append("g").attr("transform","translate("+t.left+","+t.top+")");i.domain([1,2,3,4,5,6,7,8,9,10,11,12]);r.domain([0,d3.max(n.YtdBookingsByMonth,function(n){return n.Count})]);f.selectAll(".bar").data(n.YtdBookingsByMonth).enter().append("rect").attr("class","bar").attr("x",function(n){return i(n.Month)}).attr("width",i.rangeBand()).attr("y",function(n){return r(n.Count)}).attr("height",function(n){return u-r(n.Count)});f.selectAll("text").data(n.YtdBookingsByMonth).enter().append("text").text(function(n){return n.Count?n.Count:""}).attr("x",function(n){return i(n.Month)+i.rangeBand()/2}).attr("y",function(n){return r(n.Count)-2}).attr("font-family","sans-serif").attr("font-size","11px").attr("fill","#cccccc").attr("text-anchor","middle");f.selectAll(".bartext").data(n.YtdBookingsByMonth).enter().append("text").text(function(n){return n.MonthText}).attr("x",function(n){return i(n.Month)+i.rangeBand()/2}).attr("y",function(){return u+10}).attr("font-family","sans-serif").attr("font-size","11px").attr("fill","#cccccc").attr("text-anchor","middle")};this.renderBookingsHeatMap=function(n){var h,o,s;if($("#chart-bookings-by-time").empty(),n&&n.length>0){let p=[];for(let t=0;t<n.length;t++){const i=n[t];if(i.Hour===0){let t=n.filter(n=>n.Day===i.Day);t=t.map(n=>({Day:n.Day,Hour:n.Hour,Count:n.Count}));t.forEach(n=>n.Hour--);const r=t[0];r.Hour=23;t.shift();t.push(r);p=p.concat(t)}else if(h=p.some(n=>n.Day===i.Day),!h){let t=n.filter(n=>n.Day===i.Day);t=t.map(n=>({Day:n.Day,Hour:n.Hour,Count:n.Count}));t.forEach(n=>n.Hour--);p=p.concat(t)}}n=p;$.each(n,function(n,t){t.Hour++;t.Day++});var i={top:20,right:0,bottom:30,left:25},c=560-i.left-i.right,u=251-i.top-i.bottom,t=Math.floor(c/24),f=t*2,a=5,e=["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"],v=["Mo","Tu","We","Th","Fr","Sa","Su"],y=["1a","2a","3a","4a","5a","6a","7a","8a","9a","10a","11a","12p","1p","2p","3p","4p","5p","6p","7p","8p","9p","10p","11p","12a"],l=d3.scale.quantile().domain([0,a-1,d3.max(n,function(n){return n.Count})]).range(e),r=d3.select("#chart-bookings-by-time").append("svg").data(n).attr("width",c+i.left+i.right).attr("height",u+i.top+i.bottom).append("g").attr("transform","translate("+i.left+","+i.top+")");r.selectAll(".dayLabel").data(v).enter().append("text").text(function(n){return n}).attr("x",0).attr("y",function(n,i){return i*t}).style("text-anchor","end").attr("transform","translate(-6,"+t/1.5+")").attr("class",function(n,t){return t>=0&&t<=4?"dayLabel mono axis axis-workweek":"dayLabel mono axis"});r.selectAll(".timeLabel").data(y).enter().append("text").text(function(n){return n}).attr("x",function(n,i){return i*t}).attr("y",0).style("text-anchor","middle").attr("transform","translate("+t/2+", -6)").attr("class",function(n,t){return t>=7&&t<=16?"timeLabel mono axis axis-worktime":"timeLabel mono axis"});o=r.selectAll(".hour").data(n).enter().append("rect").attr("x",function(n){return(n.Hour-1)*t}).attr("y",function(n){return(n.Day-1)*t}).attr("rx",4).attr("ry",4).attr("class","hour bordered").attr("width",t).attr("height",t).style("fill",e[0]);o.transition().duration(1e3).style("fill",function(n){return l(n.Count)});o.append("title").text(function(n){return n.Count});s=r.selectAll(".legend").data([0].concat(l.quantiles()),function(n){return n}).enter().append("g").attr("class","legend");s.append("rect").attr("x",function(n,t){return f*t}).attr("y",u).attr("width",f).attr("height",t/2).style("fill",function(n,t){return e[t]});s.append("text").attr("class","mono").text(function(n){return"≥ "+Math.round(n)}).attr("x",function(n,t){return f*t}).attr("y",u+t)}};i.renderBitcoin30DayChart=function(n){n.Last30DaysTransactions||(n.Last30DaysTransactions=[]);_.each(n.Last30DaysTransactions,function(n){n.Day=n.DayOfMonth.split("-")[0];n.DayText=n.DayOfMonth.split("-")[1]});_.each([30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0],function(t){_.find(n.Last30DaysTransactions,function(n){return n.Day===t})||n.Last30DaysTransactions.push({Day:t,Revenue:0,DayText:""})});var t={top:20,right:10,bottom:20,left:10},e=700-t.left-t.right,u=100-t.top-t.bottom,i=d3.scale.ordinal().rangeRoundBands([0,e],.1),r=d3.scale.linear().range([u,0]),o=d3.svg.axis().scale(i).orient("bottom"),s=d3.svg.axis().scale(r).orient("left"),f=d3.select("#chart-bitcoin-last30days").append("svg").attr("width",e+t.left+t.right).attr("height",u+t.top+t.bottom).append("g").attr("transform","translate("+t.left+","+t.top+")");i.domain([30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0]);r.domain([0,d3.max(n.Last30DaysTransactions,function(n){return n.Revenue})]);f.selectAll(".bar").data(n.Last30DaysTransactions).enter().append("rect").attr("class","bar").attr("x",function(n){return i(n.Day)}).attr("width",i.rangeBand()).attr("y",function(n){return r(n.Revenue)}).attr("height",function(n){return u-r(n.Revenue)});f.selectAll("text").data(n.Last30DaysTransactions).enter().append("text").text(function(n){return n.Revenue?"$"+n.Revenue:""}).attr("x",function(n){return i(n.Day)+i.rangeBand()/2}).attr("y",function(n){return r(n.Revenue)-3}).attr("font-family","sans-serif").attr("font-size","11px").attr("fill","#cccccc").attr("text-anchor","middle");f.selectAll(".bartext").data(n.Last30DaysTransactions).enter().append("text").text(function(n){return n.Day}).attr("x",function(n){return i(n.Day)+i.rangeBand()/2}).attr("y",function(){return u+12}).attr("font-family","sans-serif").attr("font-size","14px").attr("fill","#cccccc").attr("text-anchor","middle")}},MyPlaceFullSimpleListingViewModel=function(n,t,i,r,u,f,e){function s(n){return PF.getDuration(o.startTime(),o.endTime(),n)}function h(){return(o.timeUnit()||"").indexOf("Day")>-1}var o=this;o.listing=ko.observable(n);o.currentStep=ko.observable(0);o.template=ko.observable(r);o.templateName=ko.computed({read:function(){return o.template()=="Other"?"listing":o.template()?o.template().toLowerCase():""}});o.wizard=null;o.loaded=!1;o.validator=new PF.FormValidator;o.emailAddress=ko.observable();o.phone=ko.observable();o.isAuthenticated=ko.observable(e);o.availabilityRecurrence=ko.observable();o.simultaneousEvents=ko.observable();o.peopleAtOneTime=ko.observable();o.availabilityRecurrence.subscribe(function(n){var t=o.listing().availabilities()[0],i;n=="1"?t.days(t.dailyArray()):(t.days([]),i=o.templates[o.templateName()].Availabilities[0],$.each(t.dailyArray(),function(n,r){i[r]&&t.days.push(r)}))});o.listing().availabilities.push(new SpaceAvailability);o.address=ko.computed({read:function(){return o.listing().address1()},write:function(n){o.listing().address1(n);o.listing().account()&&!o.listing().account().address1()&&o.listing().account().address1(n)},owner:o});o.zip=ko.computed({read:function(){return o.listing().postalOrZipCode()},write:function(n){o.listing().postalOrZipCode(n);o.listing().account()&&!o.listing().account().postalOrZipCode()&&o.listing().account().postalOrZipCode(n)},owner:o});o.zip.subscribe(function(){o.getCityState()});o.city=ko.computed({read:function(){return o.listing().city()&&o.listing().stateOrProvince()?o.listing().city()+", "+o.listing().stateOrProvince().toUpperCase():null},write:function(n){var r,i,t;n&&n.indexOf(",")>=0&&(r=n.split(",")[0],i=n.split(",")[1].trim(),i&&(i=i.toUpperCase()));n&&n.indexOf(",")===-1&&(r=n.trim());t=o.listing();t.city(r);t.stateOrProvince(i);!t.account()||t.account().city()||t.account().stateOrProvince()||(t.account().city(r),t.account().stateOrProvince(i))},owner:o});o.timeUnit=ko.observable();o.lastTimeValue=o.timeUnit();o.timeUnit.subscribe(function(n){var i=o.listing().defaultRate(),t=parseFloat(i&&i.rate()),u,r,f=(o.lastTimeValue||"").indexOf("Day")>-1,e=(o.lastTimeValue||"").indexOf("Hour")>-1;u=!isNaN(t);u&&(f||e)&&(r=s(),f&&!h()?t*=r:e&&h&&(t/=r),i.rate(t));o.lastTimeValue=n});o.minRentalDurationPrecise=ko.computed(function(){var n=o.listing().minRentalDuration(),t;return n&&(t=n/60),t});o.minRentalDuration=ko.computed({read:function(){var n;return Math.round(o.minRentalDurationPrecise()*10)/10||n},write:function(n){var t=s();n=Math.round(n*2)/2;n>t&&(n=t);o.listing().minRentalDuration(n*60)}});o.minRentalDuration.extend({notify:"always"});o.listing().minRentalDuration.extend({notify:"always"});o.simultaneousEvents.subscribe(function(n){o.listing().packageQuantity(parseInt(n,10)*o.listing().defaultRate().availabilityQtyUsed())});o.peopleAtOneTime.subscribe(function(n){o.listing().defaultRate()&&(o.listing().defaultRate().availabilityQtyUsed(parseInt(n,10)),o.listing().packageQuantity(o.simultaneousEvents()*o.listing().defaultRate().availabilityQtyUsed()))});o.availability={start:{time:ko.observable("9:00"),date:ko.observable()},end:{time:ko.observable("17:00"),date:ko.observable()}};o.startTime=ko.computed(function(){var n=PF.Moment(o.availability.start.time(),["H:mm","HH:mm","hh:mm a","hh:mm A"]);return n.format("H:mm")});o.endTime=ko.computed(function(){var n=PF.Moment(o.availability.end.time(),["H:mm","HH:mm","hh:mm a","hh:mm A"]);return n.format("H:mm")});o.load=function(n){if(!o.loaded){o.wizard=new Wizard;o.wizard.init(t[0]);r&&o.selectTemplate(r);var i=1;r&&(i=2);u&&(i=u);f&&o.emailAddress(f);o.currentStep(i);o.loaded=!0}n&&typeof n=="function"&&n()};o.selectTemplate=function(n){var i,r;console.log("selecting template: "+n);pf_dataLayer.push({eventLabel:n,event:"Step 1 - SelectTemplate",eventCategory:"Self Sign Up"});o.template(n);var t=o.listing(),u=o.listing().account().organizationName(),f=n+" at "+u;t.name(f);i=o.templates[n.toLowerCase()];r=$.extend({},t.toServerModel(!0),i);t.fromServerModel(r)};o.saveAndNext=function(){o.save(function(){o.next()})};o.displayedRate=ko.computed({read:function(){var t=o.listing().defaultRate(),n=parseFloat(t&&t.rate()),i;return h()&&(n*=s()),!isNaN(n)&&n>0&&(n=n.toFixed(2)),n||i},write:function(n){var t=n;h()&&(t/=s());o.listing().defaultRate().rate(t)}});o.mergeAvailabilityWithTemplateValue=function(n,t){var r=o.templates[o.template().toLowerCase()],e=h()?s()*60:null,u=o.listing().availabilities()[0],i,f;return i=o.listing().availabilities().length!=0&&o.listing().availabilities()[0].id()?n:$.extend({},n,r.Availabilities[0]),i.StartTime=o.startTime()||u.startTime(),i.EndTime=o.endTime()||u.endTime(),i.StartDate=o.availability.start.date()||u.startDate(),i.EndDate=o.availabilityRecurrence()!=1?o.availability.end.date()||u.endDate():i.StartDate,i.AvailabilityQty=1,t.DefaultRate.Rate=o.listing().defaultRate().rate(),t.PackageQty=o.listing().packageQuantity(),f=ko.isObservable(r.MinimumRental)?r.MinimumRental():r.MinimumRental,t.MinimumRental=e||o.listing().minRentalDuration()||f,{camp:1,ticket:1,"class":1}[o.templateName()]&&(t.MinimumRental=f),ko.isObservable(t.MinimumRental)&&(t.MinimumRental=t.MinimumRental()),i};o.save=function(n){var r,t,i;if(o.currentStep()==3&&(!o.listing().images()||o.listing().images().length==0)&&(r=o.wizard.activeView().view.find(".carousel"),r)){var f=$(".active",r),i=f.data("image-url"),u=new SpaceImage;u.fileUrl(i);u.isDefault(!0);o.listing().images([u])}if(o.validator&&!o.validator.Validate())return o.error("Oops!  Make sure you fill everything out before continuing."),!1;t=o.listing().toServerModel(!0);t.Availabilities[0]=o.mergeAvailabilityWithTemplateValue(t.Availabilities[0],t);t={space:t,templateName:o.template()};i=o.wizard.activeView().view.data("save-url");i?$.ajax({url:i,type:"POST",dataType:"json",data:JSON.stringify(t),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(t)if(t.Success){if(t.Redirect)window.location.replace(t.Redirect);else if(o.listing().fromServerModel(t.Item),o.listing().address1()!=""&&(!o.listing().lat()||!o.listing().long())){var i=o.listing().address1()+" "+o.listing().address2()+", "+o.listing().city()+" "+o.listing().stateOrProvince()+" "+o.listing().postalOrZipCode();try{PF.Controls.GeoLookup.GetLatLngCityState(i,function(){o.listing().lat(this.lat);o.listing().long(this.lng);o.listing().city(this.city);o.listing().stateOrProvince(this.state);o.listing().postalOrZipCode(this.zip)})}catch(r){console.log(r)}}}else o.error(t.Error);n&&typeof n=="function"&&n()}):console.log("[ERROR] Attempting to save without URL.")};o.move=function(n){var t=o.currentStep();n==t+1?o.saveAndNext():n<t&&o.currentStep(n)};o.getCityState=function(){if(o.listing().postalOrZipCode().length!=0){var n=o.listing().postalOrZipCode();PF.Controls.GeoLookup.GetLatLngCityState(n,function(){typeof this.city!="undefined"&&this.country=="US"&&(o.listing().city(this.city),o.listing().stateOrProvince(this.state));typeof this.country!="undefined"&&this.country!=""&&this.country!="US"&&this.country!="CA"&&o.error("We are sorry but our booking service is only available to businesses in the United States and Canada")})}};o.validateStartAndEndTimes=function(){return PF.Moment(o.endTime(),["H:mm"]).isAfter(PF.Moment(o.startTime(),["H:mm"]))};o.next=function(){if(o.validateStartAndEndTimes())if(o.validator&&o.validator.Validate()){var n=o.currentStep();n++;n===2&&o.isAuthenticated()&&n++;o.currentStep(n)}else o.error("Oops!  Make sure you fill everything out before continuing.");else o.error("Oops! Your start time is after your end time. That really messes up our math."),o.availability.end.time(o.availability.start.time())};o.finish=function(n){var t,i;(o.emailAddress()&&o.emailAddress(o.emailAddress().replace(/ /g,"")),o.phone()&&o.phone(o.phone().replace(/ /g,"")),o.validator.Validate())&&(t=o.listing().toServerModel(!0),pf_dataLayer.push({event:"Step5 - EmailSubmit",eventCategory:"Self Sign Up"}),t={space:t,emailAddress:o.emailAddress(),phone:o.phone()},i=o.wizard.activeView().view.data("save-url"),i?$.ajax({url:i,type:"POST",dataType:"json",data:JSON.stringify(t),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){t&&(t.Success?t.Redirect&&window.location.replace(t.Redirect):o.error(t.Error));n&&typeof n=="function"&&n()}):console.log("[ERROR] Attempting to save without URL."))};o.currentStep.subscribe(function(n){var t=n-1,r=i[t];o.wizard.push(r,o,function(t){if(n==3){(function(){"use strict";var n=$("<button/>").addClass("btn btn-block btn-large button-singlefileupload").prop("disabled",!0).text("Processing...").on("click",function(){var n=$(this),t=n.data();n.off("click").text("Cancel").on("click",function(){n.remove();t.abort()});t.submit().always(function(){n.remove()})});$(".file-upload input[type=file]").fileupload({url:"/Handlers/Upload.ashx",dataType:"json",autoUpload:!1,acceptFileTypes:/(\.|\/)(gif|jpe?g|png)$/i,maxFileSize:5e7,disableImageResize:/Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),previewMaxWidth:125,previewMaxHeight:125,previewCrop:!0,sequentialUploads:!0,formData:{spaceid:o.listing().id(),spacecondensedname:o.listing().condensedName(),filetype:"image"}}).on("fileuploadadd",function(t,i){var f=this,r=$(this).data("blueimp-fileupload"),u;r.pf=r.pf||{queue:0,active:0};$(this).closest(".drop").children(".instructions").hide();u=$(this).closest(".drop").children(".previews");$.each(i.files,function(t,e){var h=$(".files-row:last-child",u),o,s;if(r.pf.queue%3==0&&(h=$('<div class="row-fluid files-row" />'),u.append(h)),o=i.context=$('<div class="span4 file-container"/>').appendTo(h),o.append('<div class="preview" />'),o.append($('<div class="title" />').text(e.name)),o.append("<div/>").append($("<small/>").text("("+Math.round(e.size*.000976562)+" KB)")),o.append('<div class="progress hide"><div class="bar bar-success"><\/div><\/div>'),t||o.append("<br>").append(n.clone(!0).data(i)),r.pf.queue++,r.pf.active++,r.pf.active>0&&(s=$(f).closest(".drop").children(".uploadall-button"),s.removeClass("hide"),!s.data("pf-uploadalleventattached"))){s.data("pf-uploadalleventattached",!0);const n=$("#image-upload-drop-container");s.on("click",function(){const t=n.find(".button-singlefileupload");if(t.length>0)for(let n=0;n<t.length;n++){const i=$(t[n]);i.text()==="Upload"&&i.click()}s.data("pf-uploadalleventattached",!1)})}})}).on("fileuploadprocessalways",function(n,t){var r=t.index,i=t.files[r],f=$(t.context.children()[r]),u=t.context;i.preview&&$(".preview",u).append(i.preview);i.error&&u.append("<br>").append($('<span class="text-danger"/>').text(i.error));r+1===t.files.length&&u.find("button").text("Upload").prop("disabled",!!t.files.error)}).on("fileuploadprogress",function(n,t){$(".progress",$(t.context)).removeClass("hide");var i=parseInt(t.loaded/t.total*100,10);$(".progress .bar",$(t.context)).css("width",i+"%")}).on("fileuploaddone",function(n,i){var r,u,f;i&&i.result&&i.result.Success&&i.result.Item&&i.result.Item.length>0&&($(".progress",i.context).hide(),$(i.context).append('<div class="text-success"><i class="fa fa-check fa-3x"><\/i><\/div>'),r=i.result.Item.map(function(n){return(new SpaceImage).fromServerModel(n)}),o.listing().images()||o.listing().images([]),$.each(r,function(n,t){o.listing().images.push(t)}),u=$(t).find(".carousel"),u&&u.carousel(o.listing().images.indexOf(r[0])),pf_dataLayer.push({event:"Step3 - ImageUploaded",eventCategory:"Self Sign Up"}),f=$(this).data("blueimp-fileupload"),f.pf.active--,f.pf.active<=0&&$(this).closest(".drop").children(".uploadall-button").addClass("hide"))}).on("fileuploadfail",function(n,t){$.each(t.files,function(n){var i=$('<span class="text-danger"/>').text("File upload failed.");$(t.context.children()[n]).append("<br>").append(i)})}).prop("disabled",!$.support.fileInput).parent().addClass($.support.fileInput?undefined:"disabled")})();var i=$(t).find(".carousel");i&&i.carousel({interval:!1})}else n==4&&(o.availabilityRecurrence()||o.availabilityRecurrence("1"));o.validator.Init({container:$(".views").children().first()})})});o.error=function(n){$("html, body").animate({scrollTop:0},500);var i=$(".alert-error",t);i.html(n);i.show();setTimeout(function(){i.addClass("in");setTimeout(function(){i.removeClass("in");setTimeout(function(){i.hide()},500)},5e3)})};o.categories={PACKAGE:"C2CEE8AC-31F5-4A0D-8F4A-930C436CE17A",SERVICE:"0776F577-23B3-4D0B-966F-6317E03E03ED",SPACE:"F14D3A4A-0178-4616-ABDA-F8740094F9A2"};o.listingTypes={SPACE:"EA24DA91-903D-4C6C-95F2-E37CCAC15E44",TICKET:"E78E4178-9391-47F7-B5EA-BB4D5B62BFCF",SERVICE:"4E7C51D4-F87F-4424-B525-F920CA699A30",MEMBER:"BB7BD3B8-B792-40E8-B30E-78EEB3A8105D",OTHER:"9BB0A249-9305-44B2-85BE-C56874FF9D69",CAMPSANDCLASSES:"413588A3-0460-4617-AB69-5A07A79B4EDA",PARTY_ROOM:"F42DF505-14A3-4530-95A5-E98E255C9DCE",MEETINGSPACE:"BFB6DDCB-2017-4076-BAE6-B6F532F1EEAA"};o.eventTypes={KIDS:"8B60D6F2-1256-4ECB-869A-6A33D961E675",EDUCATIONAL:"9463C226-2287-453E-86AC-8418EA1BD56D",WEDDING:"BE794237-9AFA-4832-8BAB-E18136A179E0",CORPORATE:"419C76E1-26F5-41BA-A75F-D6D45D0E677F",OTHER:"8F6259E2-58ED-4608-8BE1-F1A2DD69E969",FUN_OUTINGS:"64A475D4-B96C-40AB-B724-AF84FC1BA8AE",EVENT_SERVICES:"C0909C92-DB94-4CCD-91AC-1A385EDE17C8"};o.minimumNotice={DAY:24,HOUR:1};o.rateIds={hourly:0,perUse:1,daily:2};o.availableCalendarType={Id:"29F0F9A0-9D78-40BC-8637-FFA2FCC264E5",CalendarTypeName:"Availability"};o.moThruFri={Monday:!0,Tuesday:!0,Wednesday:!0,Thursday:!0,Friday:!0,Saturday:!1,Sunday:!1};o.everyday={Monday:!0,Tuesday:!0,Wednesday:!0,Thursday:!0,Friday:!0,Saturday:!0,Sunday:!0};o.monThruFriAvailability=$.extend({},o.moThruFri,{AvailabilityQty:1,CalendarType:o.availableCalendarType});o.everydayAvailability=$.extend({},o.everyday,{AvailabilityQty:1,CalendarType:o.availableCalendarType});o.defaultAvailability=[o.everydayAvailability];o.templates={referral:{SpaceType:{Id:o.listingTypes.MEETINGSPACE},SpaceCategory:{Id:o.categories.SPACE},SpaceEventTypes:[{Id:o.eventTypes.WEDDING},{Id:o.eventTypes.CORPORATE},{Id:o.eventTypes.EDUCATIONAL}],MinimumNotice:o.minimumNotice.DAY,MinimumRental:60,DefaultRate:{RateRule:{RuleName:PF.RateRule.Default},RateTypeId:o.rateIds.hourly,Name:PF.RateRule.Default},Availabilities:[$.extend({},o.everyday,{AvailabilityQty:1,CalendarType:{Id:"83F91D50-0CC7-4DF5-9283-1CDF599E83BA",CalendarTypeName:"Referral"}})],PackageQty:1},camp:{SpaceType:{Id:o.listingTypes.CAMPSANDCLASSES},SpaceCategory:{Id:o.categories.PACKAGE},SpaceEventTypes:[{Id:o.eventTypes.KIDS},{Id:o.eventTypes.EDUCATIONAL}],MinimumNotice:o.minimumNotice.DAY,DefaultRate:{RateRule:{RuleName:PF.RateRule.Default},RateTypeId:o.rateIds.perUse,Name:PF.RateRule.Default},MinimumRental:ko.computed(function(){return s(!0)}),Availabilities:o.defaultAvailability},"class":{SpaceType:{Id:o.listingTypes.CAMPSANDCLASSES},SpaceCategory:{Id:o.categories.PACKAGE},SpaceEventTypes:[{Id:o.eventTypes.KIDS},{Id:o.eventTypes.EDUCATIONAL}],MinimumNotice:o.minimumNotice.DAY,DefaultRate:{RateRule:{RuleName:PF.RateRule.Default},RateTypeId:o.rateIds.perUse,Name:PF.RateRule.Default},MinimumRental:ko.computed(function(){return s(!0)}),Availabilities:[o.monThruFriAvailability]},space:{SpaceType:{Id:o.listingTypes.MEETINGSPACE},SpaceCategory:{Id:o.categories.SPACE},SpaceEventTypes:[{Id:o.eventTypes.WEDDING},{Id:o.eventTypes.CORPORATE},{Id:o.eventTypes.EDUCATIONAL}],MinimumNotice:o.minimumNotice.DAY,MinimumRental:60,DefaultRate:{RateRule:{RuleName:PF.RateRule.Default},RateTypeId:o.rateIds.hourly,Name:PF.RateRule.Default},Availabilities:o.defaultAvailability,PackageQty:1},ticket:{SpaceType:{Id:o.listingTypes.TICKET},SpaceCategory:{Id:o.categories.PACKAGE},SpaceEventTypes:[{Id:o.eventTypes.EVENT_SERVICES}],MinimumNotice:o.minimumNotice.HOUR,DefaultRate:{RateRule:{RuleName:PF.RateRule.Default},RateTypeId:o.rateIds.perUse,Name:PF.RateRule.Default},Availabilities:[o.monThruFriAvailability],MinimumRental:ko.computed(function(){return s(!0)})},party:{SpaceType:{Id:o.listingTypes.PARTY_ROOM},SpaceCategory:{Id:o.categories.PACKAGE},SpaceEventTypes:[{Id:o.eventTypes.KIDS},{Id:o.eventTypes.CORPORATE},{Id:o.eventTypes.FUN_OUTINGS}],MinimumNotice:o.minimumNotice.DAY,DefaultRate:{RateRule:{RuleName:PF.RateRule.Default},RateTypeId:o.rateIds.perUse,Name:PF.RateRule.Default},Availabilities:o.defaultAvailability},appt:{SpaceType:{Id:o.listingTypes.SERVICE},SpaceCategory:{Id:o.categories.PACKAGE},SpaceEventTypes:[{Id:o.eventTypes.EVENT_SERVICES}],MinimumNotice:o.minimumNotice.DAY,DefaultRate:{RateRule:{RuleName:PF.RateRule.Appointment},RateTypeId:o.rateIds.perUse,Name:PF.RateRule.Appointment},Availabilities:o.defaultAvailability},service:{SpaceType:{Id:o.listingTypes.SERVICE},SpaceCategory:{Id:o.categories.SERVICE},SpaceEventTypes:[{Id:o.eventTypes.EVENT_SERVICES}],MinimumNotice:o.minimumNotice.DAY,MinimumRental:60,DefaultRate:{RateRule:{RuleName:PF.RateRule.Default},RateTypeId:o.rateIds.hourly,Name:PF.RateRule.Default},Availabilities:o.defaultAvailability,PackageQty:1},membership:{SpaceType:{Id:o.listingTypes.MEMBER},SpaceCategory:{Id:o.categories.PACKAGE},SpaceEventTypes:[{Id:o.eventTypes.EVENT_SERVICES}],MinimumNotice:o.minimumNotice.HOUR,DefaultRate:{RateRule:{RuleName:PF.RateRule.Default},RateTypeId:o.rateIds.perUse,Name:PF.RateRule.Default},Availabilities:[$.extend({},o.everyday,{StartTime:"9:00 AM",EndTime:"5:00 PM",AvailabilityQty:1,CalendarType:o.availableCalendarType})],MinimumRental:480,PackageQty:1e4},other:{SpaceType:{Id:o.listingTypes.OTHER},SpaceCategory:{Id:o.categories.PACKAGE},SpaceEventTypes:[{Id:o.eventTypes.WEDDING},{Id:o.eventTypes.CORPORATE},{Id:o.eventTypes.EDUCATIONAL}],MinimumNotice:o.minimumNotice.DAY,MinimumRental:60,DefaultRate:{RateRule:{RuleName:PF.RateRule.Default},RateTypeId:o.rateIds.hourly,Name:PF.RateRule.Default},Availabilities:o.defaultAvailability,PackageQty:1}}};PF.Controls.POSCalendar=function(){var d={Init:function(n){rt(n)},Reset:function(){et()}},n,g,nt=PF.isSameDay,tt=PF.getHoursBetween,s,l,a=!1,r=new Date,it=new Date,v=new Date,u=new Date,y,t=[],f=[],e=[],p=!1,h=!1,i,rt=function(n){y=n.spaceId;p=n.packageMode;s=n.minDuration/60||2;l=n.minNotice;r=new Date;i=n.viewModel;u=new Date;u.setHours(u.getHours()+l);ut();ft();ht()},ut=function(){n=$("#calendar");n.fullCalendar({header:{left:"prev",center:"title",right:"next"},allDaySlot:!1,defaultView:"month",editable:!1,selectable:!1,viewDisplay:b,dayClick:function(n){o(n)},eventClick:function(n){o(n.start,n)}});$(".fc-header-left span").hide();$(".fc-header-left").append($('<i class="icon-arrow-left green1" style=font-size:20px><\/i>').click(function(){n.fullCalendar("prev")}));$(".fc-header-right span").hide();$(".fc-header-right").append($('<i class="icon-arrow-right green1" style=font-size:20px><\/i>').click(function(){n.fullCalendar("next")}))},ft=function(){},et=function(){$("#calendar").empty();t=null;f=null;e=null;h=!1;t=[];f=[];e=[];$(".fc-widget-content").removeClass("available")},o=function(u,f){var o,e;return r=u,o=new Date,n.fullCalendar("gotoDate",u),f||(f=w(u)),f||(f={start:new Date(u.setHours(12,00)),end:new Date(u.setHours(12,30)),type:"unavailable"}),$("td.fc-widget-content.selected-day-column").removeClass("selected-day-column"),e=$.grep(t,function(n){return f.isContinousId&&f.isContinousId==n.isContinousId}),$.each(e,function(n,t){c(t.start).addClass("selected-day-column");t.start<u&&(u=t.start,f=w(u))}),i.selectedDateTimeSlots(null),i.selectedDateTimeSlots($.grep(t,function(n){return PF.isSameDay(u,n.start)})),i.startDate(PF.formatDate(f.start)),i.startTime(PF.formatTimeMilitary(f.start)),i.endTime(PF.formatTimeMilitary(f.end)),i.cardTimeSlotSelected(),i.calculateAvailableFromToTimeSelector(f),st(f),e.length==0&&c(f.start).addClass("selected-day-column"),!0},w=function(n){var i=null;return $.each(t,function(t,r){if(PF.isSameDay(n,r.start)&&(!i||PF.Moment(r.start).isBefore(i.start)))return i=r,!1}),i},ot=function(n,t){return!n&&!t?0:n?t?n.start<t.start?-1:n.start>t.start?1:0:1:-1},st=function(n){var t={start:n.start,end:n.end,timeBuffer:s};p&&(t.fixedMode=!0)},b=function(){it=r;r=n.fullCalendar("getDate");lt(function(){});g=n.fullCalendar("getView");n.find("td.fc-widget-content div.fc-day-number").each(function(){$(this).parent().parent().attr("date",$.trim($(this).text()))});$("tr.fc-last td.fc-other-month").length==7?$("tbody tr.fc-last").hide():$("tr.fc-last").show();k()},ht=function(){$("#calTab").hasClass("active")||$("#calTab").trigger("click");n.is(":visible")||b()},k=function(){n.fullCalendar("removeEvents");$.each(t,function(n,t){c(t.start).addClass(t.type)});n.find(".fc-widget-content").each(function(){var n=$(this);n.hasClass("available")?n.attr("title","Listing has availability on this date."):n.hasClass("previous")?n.attr("title","Date occurs in the past."):n.attr("title","Listing is not available on this date.")});$.each(t,function(n,t){if(t.start.getMonth()==r.getMonth())return h=!0,o(t.start),!1});t.length==0&&i.selectedDateTimeSlots([]);!h&&t&&t.length&&o(t[0].start)},ct=function(i){$.each(i,function(n,i){var r,o,f,h,c;e["guid"+i.CalendarDate+""+i.ActualBlockStartTime+i.ActualEndTime]!=!0&&(r=new Date(i.CalendarDate+" "+i.ActualBlockStartTime),o=new Date(i.CalendarDate+" "+i.ActualEndTime),o<r&&o.setDate(o.getDate()+1),f=new Date(o.valueOf()),f.getMinutes()==59&&f.getHours()==23&&f.setMinutes(f.getMinutes()+1),f>u&&(r<u&&nt(r,u)&&(r=new Date(u.valueOf()),h=30-r.getMinutes()%30,r.setMinutes(r.getMinutes()+h)),tt(r,f)>=s&&(e["guid"+i.CalendarDate+""+i.ActualBlockStartTime+i.ActualEndTime]=!0,r.setSeconds(0),c={start:r,end:o,type:"available",title:"Available",allDay:!1,className:"available",color:"#51a351",textColor:"#000",guid:i.Id,isContinousId:i.SpaceAvailabilities[0].CalendarType.CalendarTypeName==PF.CalendarType.MultiDayAvailability.CalendarTypeName?i.SpaceAvailabilities[0].Id:null,packagesRemaining:i.AvailabilityQtyNet,packagesTotal:i.AvailabilityQty},t.push(c))))});t.sort(ot);i.length>0?k():!a&&t.length==0&&r.getMonth()-v.getMonth()<6&&n.fullCalendar("next")},lt=function(n){var t=r.getFullYear(),i=r.getMonth(),u={Id:y,StartDate:PF.formatDate(v),EndDate:PF.formatDate(new Date(t,i,28))};f["m"+i+"y"+t]?n&&n.call():$.post("/Rental/Calendar",u).success(function(r){f["m"+i+"y"+t]=r.Availabilities;a=r.ExpiredListing;ct(f["m"+i+"y"+t]);n&&n.call()})},c=function(t){var r=n.fullCalendar("getView").start,i;return r||(r=new Date),t.getFullYear()==r.getFullYear()&&t.getMonth()==r.getMonth()?(i=n.find("td.fc-widget-content[date="+t.getDate()+"]"),i.first().hasClass("fc-other-month")&&i.length==2)?i.last():i.first():n.find("null")};return d}();var POSSaleViewModel=function(){function t(){n.selectedBooking.bookingOverride(null);n.selectedBooking.totalTaxesOverride(null);n.selectedBooking.totalBillingOverride(0);n.selectedBooking.totalBookingOverride(0);n.selectedBooking.subTotalOverride(null);n.dollarsOff(0)}var n=this;n.country=ko.observable();n.spaces=ko.observable(new AsyncPagedListViewModel([],[],null));n.paymentInstrument=new PaymentInstrument;n.selectedSpace=new Space;n.selectedRate=ko.observable();n.startDate=ko.observable();n.startTime=ko.observable();n.endTime=ko.observable();n.priceGuidance=ko.observable();n.selectedBooking=new Booking;n.addOnBooking=ko.observableArray(null);n.additionalInfoBooking=ko.observableArray(null);n.success=ko.observable(!1);n.selectedDateTimeSlots=ko.observableArray(null);n.editingDate=ko.observable(!1);n.showZipOrCvvError=ko.observable(!1);n.user=ko.observable();n.container=null;n.dollarsOff=ko.observable(0);n.spaceIsSelected=ko.observable(!1);n._viewEditBookingNote=ko.observable();n.selectedBooking.totalTaxesOverride=ko.observable(null);n.selectedBooking.totalBillingOverride=ko.observable(0);n.selectedBooking.totalBookingOverride=ko.observable(0);n.selectedBooking.bookingOverride=ko.observable(null);n.selectedBooking.subTotalOverride=ko.observable(null);n.selectedTimeSlot=ko.observable();n.minDropdownTime=ko.observable();n.maxDropdownTime=ko.observable();n.minRentalDuration=ko.observable();n.booking=ko.computed(function(){return n.selectedBooking});n.rateIsSelected=ko.computed(function(){return n.selectedRate()!=null});n.validRates=ko.computed(function(){if(!n.selectedSpace.id())return[];var t=n.selectedSpace.validRates(n.booking(),n.selectedTimeSlot());return t.length==0?[new RentalRate({rateRule:new RateRule({})})]:t});n.listingHasResources=ko.computed(function(){return n.selectedBooking&&n.selectedBooking.space()&&n.selectedBooking.space().resourceSpaces()?n.selectedBooking.space().resourceSpaces().length>0:!1});n.showCustomTime=ko.computed(function(){return n.selectedTimeSlot()&&n.selectedRate()&&n.selectedRate().rateTypeId()===PF.RateType.Hourly});n.showCustomTimeForPast=ko.computed(function(){return!n.selectedTimeSlot()&&new Date(n.startDate())<new Date});n.reset=function(){n.spaceIsSelected(!1);n.selectedRate(null);n.editingDate(!1);n.selectedDateTimeSlots(null);n.startDate(null);n.startTime(null);n.endTime(null);n.paymentInstrument.update();n.selectedSpace.update();n.selectedBooking.update();n.spaces=ko.observable(new AsyncPagedListViewModel([],[],null));n.success(!1)};n.loaded=ko.observable(!1);n.load=function(t){n.country(t.user.account().country());n.spaces(new AsyncPagedListViewModel([],[{name:"text",reset:function(){this.value("")},value:ko.observable(""),text:function(){return this.value()},apply:function(n){return this.value()?PF.hasStringMatch(n.firstName(),this.value())||PF.hasStringMatch(n.lastName(),this.value())||PF.hasStringMatch(n.email(),this.value()):!0}}],function(i){n.loadSpaces(i,t.spaceId)}));n.spaces().load();n.container=t.container;n.validator=new PF.FormValidator;n.validator.Init({container:t.container});n.user(t.user);PF.ScannerReaderDecoder({paymentInstrument:n.paymentInstrument});n.dollarsOff(0);n.loaded(!0)};n.loadSpaces=function(t,i){var r=n.spaces().findFilter("text");$.get("/My/Notification/Listings/",{PageSize:n.spaces().pageSize(),Page:n.spaces().pageIndex()+1,SpaceId:i,SearchText:r.value}).success(function(r){r.Success&&(t&&t(r),i&&n.cardSpaceSelected({Id:i},{target:n.container.find(".spaceRow")[0]}))})};n.successText=ko.computed({read:function(){return n.paymentInstrument.paymentType()==PF.PaymentType.CreditCard_Funding?"Credit card charged for":n.paymentInstrument.paymentType()==PF.PaymentType.CashCheck_Funding?"Cash/Check recorded for":n.paymentInstrument.paymentType()==PF.PaymentType.Appointment_Funding?"Appointment recorded for":"Unknown Payment Type"},owner:n});n.showExtraAsOption=ko.computed({read:function(){return n.rateIsSelected()?n.addOnBooking()&&n.addOnBooking().length>0?!0:!1:!1},owner:n});n.showResourceAsOption=ko.computed({read:function(){return n.spaceIsSelected()?n.selectedBooking&&n.selectedBooking.resources().length>0?!0:!1:!1},owner:n});n.showAdditionalInfoAsOption=ko.computed({read:function(){return n.rateIsSelected()?n.additionalInfoBooking()&&n.additionalInfoBooking().length>0?!0:!1:!1},owner:n});n.cardInitCalendar=function(n){PF.Controls.POSCalendar.Reset();PF.Controls.POSCalendar.Init(n)};n.cardShowPOS=function(){$("#view-merchant-dashboard-main").hide();$("#merchant-POS").show();pf_dataLayer.push({eventLabel:n.user().id(),event:"ConsoleShown",eventCategory:"POS"});n.startTime("12:00");n.endTime("12:30");n.startDate(PF.formatDate(new Date))};n.cardToggleDateEdit=function(){n.editingDate(!0);pf_dataLayer.push({eventLabel:n.user().id(),event:"DateEdit",eventCategory:"POS"});n.cardInitCalendar({packageMode:!1,minDuration:n.selectedSpace.minRentalDuration(),minNotice:n.selectedSpace.minNotice(),spaceId:n.selectedSpace.id(),viewModel:n})};n.cardSpaceSelected=function(t,i){n.spaceIsSelected(!0);PF.Controls.POSCalendar.Reset();var r={Id:t.Id};$(i.target).closest("ul").find("a").removeClass("selected");$(i.target).addClass("selected");n.selectedBooking.update();n.startTime("12:00");n.endTime("12:30");n.startDate(PF.formatDate(new Date));n.selectedRate(null);$.post("/My/Dashboard/Space",r).success(function(t){n.selectedSpace.fromServerModel(t);t.SpaceCategory.Name=="Space"?n.priceGuidance("Prices per hour with a "+t.MinimumRental/60+" hour minimum"):n.priceGuidance("Prices are for one, "+t.MinimumRental/60+" hour block");n.cardToggleDateEdit();n.selectedSpace.defaultRate().rateTypeId()==PF.RateType.PerPerson&&n.validRates().length>0&&n.selectedSpace.defaultRate(n.validRates()[0])}).fail(function(){PF.Modals.Generic.Show({title:errorTitle,description:"We weren't able to retrieve your listings. You can click back and try again. "+error})})};n.cardTimeSlotSelected=function(t,i){var r=i?i.target:null;t?(n.startTime(PF.formatTimeMilitary(t.start)),n.endTime(PF.formatTimeMilitary(t.end)),n.selectedTimeSlot(t)):n.selectedTimeSlot(n.selectedDateTimeSlots()[0]);n.selectedRate(n.selectedSpace.defaultRate());const f=n.selectedSpace.defaultRate().id(),u=n.container.find("#"+f);u.closest("ul").find("a").removeClass("selected");u.addClass("selected");r||(r=n.container.find(".POSCustomTime ul a:first-child"));$(r).closest("ul").find("a").removeClass("selected");$(r).addClass("selected");n.cardGetBookingTotal()};n.cardPriceSelected=function(t,i){n.selectedRate(t);$(i.target).closest("ul").find("a").removeClass("selected");$(i.target).closest("a").addClass("selected");n.selectedDateTimeSlots().length>0&&n.cardGetBookingTotal()};n.saveNote=function(){};n.resourcePricingQtyUpdate=function(){var t=0;$.each(n.selectedBooking.resources(),function(i,r){(isNaN(r.quantityPurchased())||r.quantityPurchased()<0)&&r.quantityPurchased(0);r.booking(n.booking());t+=r.totalPurchase()});n.selectedBooking.totalResourceFee(t)};n.cardGetBookingTotal=function(i,r){var f,e,o;if((i!=n||r||$("#timeSlotList").find("a").removeClass("selected"),n.selectedSpace.id()!=null&&n.selectedRate()!=null&&n.endTime()!=n.startTime())&&(f=n.startTime(),e=n.endTime(),n.showCustomTime()||(f=n.selectedTimeSlot()?PF.formatTimeMilitary(n.selectedTimeSlot().start):PF.formatTimeMilitary(n.selectedDateTimeSlots().start),e=n.selectedTimeSlot()?PF.formatTimeMilitary(n.selectedTimeSlot().end):PF.formatTimeMilitary(n.selectedDateTimeSlots().end)),f&&e)){var u=n.startDate(),s=PF.Moment(n.startDate()+" "+f),h=PF.Moment(n.startDate()+" "+e);s>h&&(u=new Date(n.startDate()),u.setDate(u.getDate()+1),u=PF.formatDate(u));o={Item:n.selectedSpace.id(),StartDate:n.startDate(),StartTime:f,EndDate:u,EndTime:e,RateRuleName:n.selectedRate().rateRule().ruleName(),RateRuleId:n.selectedRate().id(),AvailabilityQtyUsed:n.selectedRate().availabilityQtyUsed()};$.post("/My/Space/RequestBooking",o).success(function(i){var r,u;i.Success==!1?PF.Modals.Generic.Show({title:"Error During Purchase",description:"Unable to retrieve your booking details. Card has not been charged. Please Try again."+i.Error}):(n.selectedBooking.fromServerModel(i.Item),n.selectedBooking.bookingOverride(null),n.selectedBooking.subscribeResourceUpdates(n.resourcePricingQtyUpdate),n.selectedBooking.validateResources(),n.paymentInstrument.totalOverride(null),n.paymentInstrument.discount(null),t(),n.selectedBooking.rateRuleName()=="DefaultAppointment"&&n.paymentInstrument.paymentType(PF.PaymentType.Appointment_Funding),r=_.map(i.Item.AddOnBooking,function(t){var i=(new AddOnBooking).fromServerModel(t);return i.qtyPurchased.subscribe(function(){n.addOnQtyUpdate()}),i}),n.addOnBooking(r),u=_.map(i.Item.AdditionalInfoBooking,function(n){return(new AdditionalInfoBooking).fromServerModel(n)}),n.additionalInfoBooking(u),$("#extra-section").hasClass("in")&&$("#extra-section").collapse("hide"))})}};n.addOnQtyUpdate=function(){var t=0;$.each(n.addOnBooking(),function(n,i){(isNaN(i.qtyPurchased())||i.qtyPurchased()<0)&&i.qtyPurchased(0);t+=i.qtyPurchased()*i.rate()});n.selectedBooking.totalAddOnFee(t);n.paymentInstrument.discount(null);n.paymentInstrument.totalOverride(null);n.selectedBooking.bookingOverride(null);n.selectedBooking.totalTaxesOverride(null);n.selectedBooking.totalBillingOverride(0);n.selectedBooking.totalBookingOverride(0);n.selectedBooking.subTotalOverride(null);$("#percentOff").hide()};n.cardApplyDiscount=function(){if(n.selectedBooking.totalAddOnFee(n.selectedBooking.totalAddOnFee()),t(),n.paymentInstrument.discount()==null||n.paymentInstrument.discount()==0)t();else{n.dollarsOff(n.selectedBooking.totalBooking()*n.paymentInstrument.discount()/100);n.selectedBooking.totalBookingOverride(n.selectedBooking.totalBooking()-n.dollarsOff());var i=n.selectedBooking.totalBookingOverride()+(n.selectedBooking.totalAdditionalFee()||0)+n.selectedBooking.totalAddOnFee()+n.selectedBooking.totalResourceFee();if(n.selectedBooking.taxRate()){const t=i*(n.selectedBooking.taxRate()/100);n.selectedBooking.totalTaxesOverride(t);i+=n.selectedBooking.totalTaxesOverride()}n.selectedBooking.subTotalOverride(i);n.selectedBooking.bookingOverride(i+n.selectedBooking.totalSecurityDepositHold());n.paymentInstrument.totalOverride(null);return}if(n.paymentInstrument.totalOverride()==null){t();return}if(n.selectedBooking.bookingOverride(parseFloat(n.paymentInstrument.totalOverride())),n.dollarsOff(n.selectedBooking.totalBooking()-n.selectedBooking.bookingOverride()),n.selectedBooking.taxRate()){const t=n.selectedBooking.bookingOverride()*(n.selectedBooking.taxRate()/100);n.selectedBooking.totalTaxesOverride(t)}return};n.zipOrCvvHasValue=ko.computed(function(){return!!n.paymentInstrument.zipCode()||!!n.paymentInstrument.cvv()});n.zipOrCvvIsValid=ko.computed(function(){if(n.loaded()){var t=n.validator.isInvalid,i=n.paymentInstrument.zipCode(),r=n.paymentInstrument.cvv();return n.paymentInstrument.paymentType()==PF.PaymentType.CashCheck_Funding||n.paymentInstrument.paymentType()==PF.PaymentType.Appointment_Funding?!0:n.zipOrCvvHasValue()&&!(t.zipcode(i)&&t.cvc(r))}});n.cardPurchase=function(){var t,i,r,u,f,e,o;if(!n.selectedBooking.validateResources())return!1;n.validator.Validate()&&n.spaceIsSelected()&&n.rateIsSelected()&&n.zipOrCvvIsValid()?(n.showZipOrCvvError(!1),t=[],$(n.addOnBooking()).each(function(){t.push(this.toServerModel())}),i=[],$(n.additionalInfoBooking()).each(function(){i.push(this.toServerModel())}),r=[],$(n.selectedBooking.resources()).each(function(){r.push(this.toServerModel())}),u=n.selectedBooking.bookingOverride(),f=typeof n.paymentInstrument.totalOverride()=="undefined"||n.paymentInstrument.totalOverride()===null,f&&n.selectedBooking.bookingOverride()&&(u=n.selectedBooking.bookingOverride()-n.selectedBooking.totalSecurityDepositHold()),e={Id:n.selectedBooking.id(),BookingEmail:n.paymentInstrument.email(),BookingFirstName:n.paymentInstrument.firstName(),BookingLastName:n.paymentInstrument.lastName(),BookingPhoneNumber:n.paymentInstrument.phone(),BookingOverride:u,Notes:n.selectedBooking.notes(),AddOnBooking:t,AdditionalInfoBooking:i,Resources:r},o={Item:e,PaymentInstrument:n.paymentInstrument.toServerModel(),StartDate:null,EndDate:null,Renter:null},PF.Modals.ProgressIndicator.Show({message:"Purchasing..."}),$.ajax({type:"POST",url:"/My/Space/Purchase",data:JSON.stringify(o),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){PF.Modals.ProgressIndicator.HideModal(function(){t.Success==!1?PF.Modals.Generic.Show({title:"Error During Purchase",description:t.Error}):n.success(!0)})}})):(window.scrollTo(0,600),n.showZipOrCvvError(!0))};n.calculateAvailableFromToTimeSelector=function(t){if(n.showCustomTime()){var i=n.selectedSpace.minRentalDuration()/60||2;n.minRentalDuration(n.selectedSpace.minRentalDuration());n.maxDropdownTime(PF.formatTime(t.end));n.minDropdownTime(PF.formatTime(t.start));n.endTime(n.maxDropdownTime());n.startTime(n.minDropdownTime());n.endTime(PF.Moment(n.startTime(),["H:mm","hh:mm a","hh:mm A"]).add("hours",i).format("H:mm"))}}},ReportViewModel=function(n,t,i){var r=this,u=null;const f="62e9ec8e-4fa6-4c26-a4b9-97908841f1dd",e="e6967375-bd74-4e5a-a603-843148c28314";r.notificationVM=n;r.loadingReports=ko.observable(!1);r.loadingReportResult=ko.observable(!1);r.success=ko.observable();r.error=ko.observable();r.selectedCategory=ko.observable();r.accountId=ko.observable();r.reportSearchBox=ko.observable();r.reportList=ko.observableArray();r.reportsByCategory=ko.observableArray();r.reportResult=ko.observable();r.reportDataTable=ko.observable();r.reportViewList=ko.observableArray();r.selectedReportView=ko.observable();r.editableReportView=ko.observable();r.editReportViewState=ko.observable();r.localStorageDataKey=ko.observable();r.selectedReportExport=ko.observable("-1");r.selectedColumns=ko.observableArray();r.oldSelectedColumns=ko.observableArray();r.selectedColumns.subscribe(function(n){var u=$(r.oldSelectedColumns()).not(n).get(),f=$(n).not(r.oldSelectedColumns()).get(),t,i;if(u.length>0){for(t=0;t<r.reportDataTable().columns()[0].length;t++)for(i=0;i<u.length;i++)if($(r.reportDataTable().column(t).header()).text().replace(/ +(?= )/g,"")===u[i].replace(/ +(?= )/g,"")){r.reportDataTable().column(t).visible(!1);break}}else for(t=0;t<r.reportDataTable().columns()[0].length;t++)for(i=0;i<f.length;i++)if($(r.reportDataTable().column(t).header()).text().replace(/ +(?= )/g,"")===f[i].replace(/ +(?= )/g,"")){r.reportDataTable().column(t).visible(!0);break}r.oldSelectedColumns(n)});r.selectedReport=ko.observable(null);r.selectReport=function(n){r.reportResult(null);r.tearDownResultTable();r.selectedReport(n);r.resetDatePickers()};r.isSelectedReport=function(n){return r.selectedReport()!=null&&r.selectedReport().displayName()===n.displayName()};r.getReportList=function(){r.success(null);r.error(null);$.ajax({url:"/My/Reporting/GetReportsByRole",type:"GET",processData:!1}).success(function(n){if(n.Success){var t=n.Item.map(function(n){return(new Report).fromServerModel(n)});$.each(t,function(n,t){t.reportParameters.sort(function(n,t){return n.order()===t.order()?0:n.order()<t.order()?-1:1});r.reportList.push(t)});r.constructListByCategory()}else r.error(n.Error)})};r.constructListByCategory=function(){$.each(r.reportList(),function(n,t){$.each(t.reportCategories(),function(n,i){var u=$.grep(r.reportsByCategory(),function(n){return n.category===i.category()});u.length===0?(u={category:i.category(),item:ko.observableArray()},r.reportsByCategory.push(u)):u=u[0];u.item.push(t)})});r.reportsByCategory.sort(function(n,t){return n.category==="Advanced"?1:t.category==="Advanced"?-1:n.category===t.category?0:n.category<t.category?-1:1});$.each(r.reportsByCategory(),function(n,t){t.item().sort(function(n,t){return n.displayName()===t.displayName()?0:n.displayName()<t.displayName()?-1:1})});r.initializeData()};r.initializeData=function(){var n,u;r.selectedReport(null);r.selectedCategory(r.reportsByCategory()[0]);t&&(n=$.grep(r.reportList(),function(n){return n.id().toUpperCase()===t.Report.Id.toUpperCase()}),n&&n.length>0&&(u=$.grep(r.reportsByCategory(),function(t){return t.category.toUpperCase()===n[0].reportCategories()[0].category().toUpperCase()}),u&&u.length>0&&(r.selectCategory(u[0]),r.selectReport(n[0]))),r.setupReportResult(t,i))};r.setupReportResult=function(n,t){r.reportResult((new ReportResult).fromServerModel(n));r.constructTable(n);t!=null&&r.reportViewList(t.map(function(n){return(new ReportView).fromServerModel(n)}));r.editableReportView(null)};r.load=function(){r.getReportList()};r.executeReport=function(){if(u=null,u===null&&(u=(new PF.FormValidator).Init({container:$("#report-parameters-area")})),u.Validate()){const n=$("#submit-report-btn");n.css({pointerEvents:"none"});r.reportResult(null);r.success(null);r.error(null);$.ajax({url:"/My/Reporting/ExecuteReport",type:"POST",dateType:"JSON",data:JSON.stringify({Item:r.selectedReport().toServerModel()}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(t){t.Success?(r.sendAnalytics(),t.ReportResult!=null&&r.setupReportResult(t.ReportResult,t.ReportViews)):r.error(t.Error);n.css({pointerEvents:"initial"})}).error(function(t){r.error(t.error);n.css({pointerEvents:"initial"})})}};r.constructTable=function(n){var h,c,u,i,l,t,s,v;for(r.tearDownResultTable(),h=[],t=0;t<n.Rows.length;t++){for(c=[],u=0;u<n.Columns.length;u++)c.push(n.Rows[t][n.Columns[u]]);h.push(c)}for(i=[],l="",t=0;t<n.Columns.length;t++)i.push({title:n.Columns[t]}),l+="<td><\/td>";$("#reportDataContainer").append("<table id='reportData' class='display'><tfoot><tr>"+l+"<\/tr><\/tfoot><\/table>");const a=[],o=r.selectedReport().id();(o===f||o===e)&&(a.push({className:"class-list-report-td-limit",targets:13}),a.push({className:"class-list-report-td-limit",targets:14}));s=new Date;v=$("#reportData").DataTable({data:h,dom:"lfZBrtip",buttons:[{extend:"excel",title:r.selectedReport().displayName()+"-"+s.toLocaleString(),exportOptions:{columns:":visible"}},{extend:PF.hasDownloadAttribute()?"csvHtml5":"csvFlash",title:r.selectedReport().displayName()+"-"+s.toLocaleString(),exportOptions:{columns:":visible"}},{extend:"pdfHtml5",title:r.selectedReport().displayName()+"-"+s.toLocaleString(),exportOptions:{columns:":visible"},orientation:"landscape"},{extend:"print",exportOptions:{columns:":visible"}}],pageLength:25,columns:i,colReorder:!0,scrollX:!0,colResize:{handleWidth:10,tableWidthFixed:!1},stateSave:!0,stateSaveCallback:function(n,t){r.localStorageDataKey()==null&&r.localStorageDataKey("DataTables_"+n.sInstance);localStorage.setItem(r.localStorageDataKey(),JSON.stringify(t))},stateLoadCallback:function(n){r.localStorageDataKey()==null&&r.localStorageDataKey("DataTables_"+n.sInstance);var t=localStorage.getItem(r.localStorageDataKey());return JSON.parse(t)},footerCallback:function(){var t=this.api(),i,r=function(n){return typeof n=="string"?n.replace(/[\$,]/g,"")*1:typeof n=="number"?n:0};$.each(t.columns()[0],function(u){i=t.column(u).data().reduce(function(n,t){return r(n)+r(t)},0);!isNaN(i)&&i!==0&&Object.keys(n.Totals).includes(t.column(u).header().innerHTML)&&$(t.column(u).footer()).html(parseFloat(Math.round(i*100)/100).toFixed(2))})},columnDefs:a,rowCallback:function(n,t){if(o===f&&o===e){const r=i.findIndex(n=>n.title==="Resource Id"),u=i.findIndex(n=>n.title==="Resource Purchased");$("td",n).eq(r).attr("title",t[r]);$("td",n).eq(u).attr("title",t[u])}}});r.reportDataTable(v);r.resetDataTable();PF.hasDownloadAttribute()||($(".dt-buttons").show(),$("#pf-export-dropdown").hide());r.constructColumnFilterPicker();$(".paginate_button").on("click",function(){$("html, body").animate({scrollTop:"300px"})})};r.constructColumnFilterPicker=function(){$("#filterColumnSelector").selectpicker({liveSearch:!0,actionsBox:!0});$("#filterColumnSelector").selectpicker("selectAll");$(".bs-select-all").on("click",function(){r.selectedColumns(r.reportResult().columns())});$(".bs-deselect-all").on("click",function(){r.selectedColumns([])});r.oldSelectedColumns(r.reportResult().columns())};r.tearDownResultTable=function(){r.reportDataTable()!=null&&(r.reportDataTable().destroy(),r.reportDataTable(null));$("#reportData").length&&$("#reportData").remove()};r.resetDatePickers=function(){$("input[name='daterangepicker']").daterangepicker({locale:{separator:"-"},ranges:{Today:[moment(),moment()],Yesterday:[moment().subtract(1,"days"),moment().subtract(1,"days")],"Last 7 Days":[moment().subtract(6,"days"),moment()],"Last 30 Days":[moment().subtract(29,"days"),moment()],"This Month":[moment().startOf("month"),moment().endOf("month")],"Last Month":[moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")]},autoApply:!0,startDate:moment().subtract(29,"days"),endDate:moment(),opens:"center",alwaysShowCalendars:!0,autoUpdateInput:!0,showCustomRangeLabel:!1});$("input[name='forwarddaterangepicker']").daterangepicker({locale:{separator:"-"},ranges:{Today:[moment(),moment()],Tomorrow:[moment().add(1,"days"),moment().add(1,"days")],"Next 7 Days":[moment(),moment().add(6,"days")],"Next 30 Days":[moment(),moment().add(29,"days")],"This Month":[moment().startOf("month"),moment().endOf("month")],"Next Month":[moment().add(1,"month").startOf("month"),moment().add(1,"month").endOf("month")]},autoApply:!0,startDate:moment(),endDate:moment().add(29,"days"),opens:"center",alwaysShowCalendars:!0,autoUpdateInput:!0,showCustomRangeLabel:!1});$("input[name='singledaypicker']").daterangepicker({singleDatePicker:!0,showDropdowns:!0,autoApply:!0,autoUpdateInput:!0,startDate:moment(),opens:"center"});$("input[name='singledatetimepicker']").daterangepicker({singleDatePicker:!0,showDropdowns:!0,autoApply:!0,autoUpdateInput:!0,startDate:moment(),opens:"center",timePicker:!0,locale:{format:"MM/DD/YYYY h:mm A"}});$("input[name='datetimerangepicker']").daterangepicker({locale:{separator:"-"},ranges:{Today:[moment(),moment()],Yesterday:[moment().subtract(1,"days"),moment().subtract(1,"days")],"Last 7 Days":[moment().subtract(6,"days"),moment()],"Last 30 Days":[moment().subtract(29,"days"),moment()],"This Month":[moment().startOf("month"),moment().endOf("month")],"Last Month":[moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")]},autoApply:!0,startDate:moment().subtract(29,"days"),endDate:moment(),opens:"center",alwaysShowCalendars:!0,autoUpdateInput:!0,showCustomRangeLabel:!1,timePicker:!0,locale:{format:"MM/DD/YYYY h:mm A",separator:"-"}});$("input[name='forwarddatetimerangepicker']").daterangepicker({ranges:{Today:[moment(),moment()],Tomorrow:[moment().add(1,"days"),moment().add(1,"days")],"Next 7 Days":[moment(),moment().add(6,"days")],"Next 30 Days":[moment(),moment().add(29,"days")],"This Month":[moment().startOf("month"),moment().endOf("month")],"Next Month":[moment().add(1,"month").startOf("month"),moment().add(1,"month").endOf("month")]},autoApply:!0,startDate:moment(),endDate:moment().add(29,"days"),opens:"center",alwaysShowCalendars:!0,autoUpdateInput:!0,showCustomRangeLabel:!1,timePicker:!0,locale:{format:"MM/DD/YYYY h:mm A",separator:"-"}})};r.sendAnalytics=function(n){pf_dataLayer.push({event:"sendVirtualPageview",vpv:"/my/reporting/execute?account="+r.accountId()+"&reportId="+r.selectedReport().id()+(n!=null?"&format="+n:"")})};r.reportSearchBox.subscribe(function(n){n==null||n.trim().length===0?r.selectedCategory(r.reportsByCategory()[0]):r.selectedCategory().category!=="search"&&r.selectedCategory({category:"search",item:r.reportList()});var t=new RegExp(n,"i");$(".pf-report-name").filter(function(){return!t.test($(this).text())}).parent().hide();$(".pf-report-name").filter(function(){return t.test($(this).text())}).parent().show()});r.saveView=function(){r.editableReportView().report(r.selectedReport());r.reportDataTable().state.save();var n=localStorage.getItem(r.localStorageDataKey());r.editableReportView().viewData(n);r.success(null);r.error(null);$.ajax({url:"/My/Reporting/EditReportView",type:"POST",dateType:"JSON",data:JSON.stringify({Item:r.editableReportView().toServerModel(),IsDeleted:r.editReportViewState()===ReportEditViewState.Delete}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(n){n.Success?(r.reportViewList(n.Item.map(function(n){return(new ReportView).fromServerModel(n)})),r.editReportViewState(null),r.editableReportView(null)):r.error(n.Error)}).error(function(){})};r.saveReportViewClick=function(){r.reportDataTable().state.save();var n=localStorage.getItem(r.localStorageDataKey());r.editableReportView(new ReportView({name:"",report:r.selectedReport(),viewData:n}));r.editReportViewState(ReportEditViewState.New)};r.editReportViewClick=function(){r.reportDataTable().state.save();var n=localStorage.getItem(r.localStorageDataKey());r.editableReportView(r.selectedReportView());r.editableReportView().viewData(n);r.editReportViewState(ReportEditViewState.Edit)};r.cancelSaveView=function(){r.editableReportView(null);r.editReportViewState(null)};r.deleteViewClick=function(){r.editableReportView(r.selectedReportView());r.editReportViewState(ReportEditViewState.Delete)};r.selectedReportView.subscribe(function(n){var t,i;if(n!=null){for(t=JSON.parse(n.viewData()),r.reportDataTable().colReorder.reset(),i=0;i<r.reportDataTable().columns()[0].length;i++)r.reportDataTable().column(i).visible(t.columns[i].visible);r.reportDataTable().colReorder.order(t.ColReorder);r.reportDataTable().page.len(t.length);r.reportDataTable().order(t.order[0]);r.reportDataTable().draw()}});r.resetDataTable=function(){r.reportDataTable().state.clear();r.reportDataTable().colReorder.reset();for(var n=0;n<r.reportDataTable().columns()[0].length;n++)r.reportDataTable().column(n).visible(!0);r.reportDataTable().page.len(25);r.reportDataTable().order([0,"asc"]);r.reportDataTable().state.save();r.reportDataTable().draw()};r.selectCategory=function(n){r.selectedCategory(n);r.reportSearchBox(undefined);r.selectedReport(undefined);r.reportResult(undefined)};r.isSelectedCategory=function(n){return r.selectedCategory()!=null?n.category===r.selectedCategory().category:null};r.dateLeftButtonClicked=function(){var n=$(".pf-daterangepicker"),i,r,t;n!=null&&(i=n.data("daterangepicker").startDate,r=n.data("daterangepicker").endDate,n.data("daterangepicker").singleDatePicker?n.data("daterangepicker").startDate.subtract(t.asDays()+1,"days"):(t=moment.duration(r.diff(i)),n.data("daterangepicker").setStartDate(i.subtract(t.asDays(),"days")),n.data("daterangepicker").setEndDate(r.subtract(t.asDays(),"days"))))};r.dateRightButtonClicked=function(){var n=$(".pf-daterangepicker"),i,r,t;n!=null&&(i=n.data("daterangepicker").startDate,r=n.data("daterangepicker").endDate,n.data("daterangepicker").singleDatePicker?n.data("daterangepicker").startDate.add(t.asDays()+1,"days"):(t=moment.duration(r.diff(i)),n.data("daterangepicker").setStartDate(i.add(t.asDays(),"days")),n.data("daterangepicker").setEndDate(r.add(t.asDays(),"days"))))};r.selectedReportExport.subscribe(function(n){if(n!="-1")switch(n){case"0":r.exportExcel();break;case"1":r.exportCsv();break;case"2":r.exportPdf();break;case"3":r.exportPrint()}r.selectedReportExport("-1")});r.exportExcel=function(){r.sendAnalytics("excel");$(".buttons-excel").click()};r.exportCsv=function(){r.sendAnalytics("csv");$(".buttons-csv").click()};r.exportPdf=function(){r.sendAnalytics("pdf");$(".buttons-pdf").click()};r.exportPrint=function(){r.sendAnalytics("print");$(".buttons-print").click()}},ReportEditViewState={New:0,Edit:1,Delete:2},EditBookingNoteViewModel=function(n,t){var i=this;i.selectedBooking=ko.observable();i.callback=t;i.load=function(n){ko.isObservable(n)?i.booking(n):ko.isObservable(n.id)?i.selectedBooking(ko.observable(n)):i.selectedBooking((new Booking).fromServerModel(n))};i.saveNote=function(){var n={Item:i.selectedBooking().toServerModel()};n.Item.User=null;n.Item.Space=null;n.Item.BookingDetails=null;n.Item.Billings=null;$.ajax({url:"/Space/EditBookingNote/",data:JSON.stringify(n),type:"POST",contentType:"application/json; charset=UTF-8"}).done(function(n){n.Success?(i.selectedBooking().notes(n.Item.Notes),t&&t(i.selectedBooking().toServerModel())):i.error(n.Error)}).fail(function(n){n=JSON.parse(n.responseText);$(".alert").text(n.Error);i.error(n.responseText)})};i.cancel=function(){};i.load(n)},RefundViewModel=function(n,t,i){var r=this;r.selectedBooking=ko.observable();r.callback=i;r.refundAmount=ko.observable();r.depositRefundAmount=ko.observable();r.load=function(n){ko.isObservable(n)?r.selectedBooking(n):ko.isObservable(n.id)?r.selectedBooking(ko.observable(n)):r.selectedBooking((new Booking).fromServerModel(n));const t=n.Billings.find(n=>n.IsApproved&&n.IsInitialDeposit&&n.PaymentType==PF.PaymentType.CreditCard_Funding),i=n.Billings.find(n=>n.IsApproved&&n.IsFinalDeposit&&n.PaymentType==PF.PaymentType.CreditCard_Funding),f=i?i.Amount:0,e=n.Billings.filter(n=>n.IsApproved&&n.PaymentType==PF.PaymentType.CreditCard_Refund),u=e.reduce((n,t)=>n+t.Amount,0),o=t?t.Amount+n.TotalGratuity+f-u:n.TotalBilling+n.TotalGratuity-u,s=PF.roundToTwoByMathRound(o);if(r.refundAmount(s),r.selectedBooking().hasSecurityDepositBillings()){const t=n.Billings.filter(n=>n.IsApproved&&n.PaymentType==PF.PaymentType.CreditCard_Refund_SecurityDeposit),i=t.reduce((n,t)=>n+t.Amount,0),u=r.selectedBooking().totalSecurityDepositHold()-i,f=PF.roundToTwoByMathRound(u);r.depositRefundAmount(f)}else r.depositRefundAmount(0)};r.refund=function(){PF.Modals.ProgressIndicator.Show({message:"Refunding..."});var n={Item:r.selectedBooking().toServerModel(),RefundAmount:r.refundAmount(),DepositRefundAmount:r.depositRefundAmount()};$.ajax({url:"/Space/ProcessRefund",data:JSON.stringify(n),type:"POST",contentType:"application/json; charset=UTF-8"}).done(function(n){PF.Modals.ProgressIndicator.HideModal(function(){n.Success?PF.Modals.Generic.Show({title:"Refund Processing",description:"We've received your refund request and will process it shortly!"}):PF.Modals.Generic.Show({title:"Refund Unsuccessful",description:n.Error+" <br><br> Please send an email to support@placefull.com with your refund request or call your account manager. Sorry for the inconvenience!"});i&&i(r.selectedBooking(),n)})}).fail(function(n){n=JSON.parse(n.responseText);$(".alert").text(n.Error);r.error(n.responseText)})};r.cancel=function(){};r.load(n)},SwitchListingOnBookingViewModel=function(n,t){var i=this;i.spaces=ko.observableArray();i.booking=ko.observable();i.selectedSpace=ko.observable();i.load=function(n){ko.isObservable(n)?i.booking(n):i.booking((new Booking).fromServerModel(n));$.ajax({url:"/My/Space/GetListOfSpaces",type:"GET",contentType:"application/json; charset=UTF-8"}).done(function(n){n&&n.length&&i.spaces(n.map(function(n){return(new Space).fromServerModel(n)}))}).fail(function(){})};i.modifyBooking=function(){PF.Modals.ProgressIndicator.Show({message:"Modifying..."});var n={Item:i.booking().toServerModel()};$.ajax({url:"/My/Space/EditBookingSpace",data:JSON.stringify(n),type:"POST",contentType:"application/json; charset=UTF-8"}).done(function(n){PF.Modals.ProgressIndicator.HideModal(function(){n.Success?PF.Modals.Generic.Show({title:"Booking Moved Successfully",description:"We've successfully moved the booking to the new listing!",close:function(){t(n)}}):PF.Modals.Generic.Show({title:"Booking Move Failed",description:n.Error})})}).fail(function(n){PF.Modals.Generic.Show({title:"Booking Move Failed",description:n.Error})})};i.load(n)},MyAccountSettingsViewModel=function(n,t){var i=this,u=null,r={NORMAL:0,EDIT:1,ADD:2};i.data=ko.observable(n);i.busy=ko.observable(!1);i.errorMessage=ko.observable();i.isEditingExisting=!1;i.currentModificationState=r.NORMAL;i.customAdditionalInfo=ko.observableArray();i.selectedCustomAdditionalInfo=ko.observable();i.clearMessages=function(){$(".alert-success",t).hide();$(".alert-error",t).hide()};i.success=function(n){$(".alert-error",t).hide();$("html, body").animate({scrollTop:0},250);$(".alert-success",t).text(n||"Your changes were saved successfully!");$(".alert-success",t).show()};i.error=function(n){$(".alert-success",t).hide();i.errorMessage(n);$("html, body").animate({scrollTop:0},250);$(".alert-error",t).show()};i.load=function(){$.get("/my/account/getcustomadditionalinfo",{}).success(function(n){if(n.Success){var t=n.Item.map(function(n){return(new AdditionalInfo).fromServerModel(n)});i.customAdditionalInfo(t)}else i.error(n.Error)}).fail(function(n){i.busy(!1);n=JSON.parse(n.responseText);i.error(n.Error)})};i.addCustomAdditionalInfo=function(){var n=new AdditionalInfo;i.selectedCustomAdditionalInfo(n);i.customAdditionalInfo.push(n);i.currentModificationState=r.ADD};i.saveCustomAdditionalInfo=function(){if(u==null&&(u=(new PF.FormValidator).Init({container:$("#additional-info-form")})),u.Validate()){i.clearMessages();i.selectedCustomAdditionalInfo().label(i.selectedCustomAdditionalInfo().label().trim());var n=i.selectedCustomAdditionalInfo();i.busy(!0);i.currentModificationState=r.NORMAL;$.ajax({url:"/my/account/savecustomadditionalinfo",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){i.busy(!1);t.Success?(n.fromServerModel(t.Item),i.selectedCustomAdditionalInfo(null)):i.error()}).fail(function(n){i.busy(!1);n=JSON.parse(n.responseText);i.error(n.Error)})}};i.cancelCustomAdditionalInfo=function(){i.currentModificationState!=r.EDIT&&i.customAdditionalInfo.remove(i.selectedCustomAdditionalInfo());i.selectedCustomAdditionalInfo(null);i.currentModificationState=r.NORMAL};i.templateToUseCustomAdditionalInfo=function(n){return i.selectedCustomAdditionalInfo()===n?"editTmplCustomAdditionalInfo":"itemsTmplCustomAdditionalInfo"};i.editCustomAdditionalInfo=function(n){i.selectedCustomAdditionalInfo(n);i.currentModificationState=r.EDIT};i.deleteCustomAdditionalInfo=function(n){i.busy(!0);$.ajax({url:"/my/account/deletecustomadditionalinfo",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){i.busy(!1);t.Success?i.customAdditionalInfo.remove(n):i.error(t.Error)}).fail(function(n){i.busy(!1);n=JSON.parse(n.responseText);i.error(n.Error)})}},MyAccountViewModel=function(n,t,i){var r=this,u;r.country=ko.observable(typeof(n.account().country()!="undefined")?n.account().country():"United States");r.availableCountries=ko.observableArray(["United States","Canada"]);r.data=ko.observable(n);r.pager=ko.observable(new AsyncPagedListViewModel([],[],null));r.subscriptionPager=ko.observable(new AsyncPagedListViewModel([],[],null));r.pendingSubscriptionPager=ko.observable(new AsyncPagedListViewModel([],[],null));r.states=ko.observableArray(t);r.hasRentalNotificationEmail=ko.observable();r.busy=ko.observable(!1);r.errorMessage=ko.observable();r.accountUnderWriting=ko.observable(new AccountUnderwritingInfo);r.agreedToProPayTerms=ko.observable();r.agreedToTrxTerms=ko.observable();r.editor=ko.observable();r.basicsValidator=new PF.FormValidator;r.businessValidator=new PF.FormValidator;r.depositsValidator=new PF.FormValidator;r.billingValidator=new PF.FormValidator;r.disableYelp=ko.observable();r.disableFacebook=ko.observable();r.bookingConfirmationMessage=ko.observable();r.gratuityOptions=ko.observable(new GratuityOptionsByAccount);r.accountUsers=ko.observableArray();r.selectedItem=ko.observable();r.addedRole=ko.observable();r.roles=ko.observableArray();r.rolesForBillingEmails=ko.computed(function(){return r.accountUsers().filter(function(n){return n.sendBillingEmails()})});r.rolesForBookingEmails=ko.computed(function(){return r.accountUsers().filter(function(n){return n.sendBookingEmails()})});r.availableRolesForBillingEmails=ko.computed(function(){return r.accountUsers().filter(function(n){return!n.sendBillingEmails()&&n.isolated()=="false"})});r.availableRolesForBookingEmails=ko.computed(function(){return r.accountUsers().filter(function(n){return!n.sendBookingEmails()})});r.addBillingEmailUser=ko.observable(0);r.addBookingEmailUser=ko.observable(0);r.selectedBillingEmailUser=ko.observable();r.selectedBookingEmailUser=ko.observable();r.achAccount=ko.observable();r.creditCardAccount=ko.observable((new BillingAccount).fromServerModel({Type:PF.AccountType.CreditCard}));r.pendingBillings=ko.observableArray();r.expandedPayoutId=ko.observable();r.subscriptionTier=ko.observable();r.subscriptionFrequency=ko.observable();r.hasUnderWritingInfo=ko.observable(!1);r.lowPrice=ko.observable(59);r.country()=="Canada"?(r.subscriptionMonthlyPrice={Team:"Monthly $69",TeamPlus:"Monthly $99",TeamLeader:"Monthly $199"},r.subscriptionAnnualPrice={Team:"Annual $828",TeamPlus:"Annual $1188",TeamLeader:"Annual $2388"},r.lowPrice(69)):(r.subscriptionMonthlyPrice={Team:"Monthly $59",TeamPlus:"Monthly $79",TeamLeader:"Monthly $149"},r.subscriptionAnnualPrice={Team:"Annual $699",TeamPlus:"Annual $949",TeamLeader:"Annual $1749"},r.lowPrice(59));r.subscriptionPaymentSource=ko.observable(PF.AccountType.Ach);r.disableYelp.subscribe(function(){r.data().account().updateSetting("DisableYelp",r.disableYelp())});r.disableFacebook.subscribe(function(){r.data().account().updateSetting("DisableFacebook",r.disableFacebook())});r.subscriptionPaymentSource.subscribe(function(n){n==PF.AccountType.Ach&&r.creditCardAccount()&&r.creditCardAccount().id()&&$.ajax({url:"/My/Billing/DeleteBillingAccount",type:"POST",dataType:"json",data:JSON.stringify({accountId:r.data().account().id(),billingAccount:r.creditCardAccount().toServerModel()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){r.busy(!1);n.Success?(r.creditCardAccount((new BillingAccount).fromServerModel({Type:PF.AccountType.CreditCard})),r.success()):r.error()}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error);r.subscriptionPaymentSource(PF.AccountType.CreditCard)})});r.subscriptionTier.subscribe(function(n){$("[data-plan]").hide();$('[data-plan="'+n+'"]').show();$('option[value="Monthly"]').text(r.subscriptionMonthlyPrice[n]);$('option[value="Annually"]').text(r.subscriptionAnnualPrice[n])});r.loadPagerData=function(n){var t={PageSize:r.pager().pageSize(),Page:r.pager().pageIndex()+1,Item:r.data().account().toServerModel()};$.ajax({url:"/My/Billing/GetAccountPayouts",type:"POST",dataType:"json",data:JSON.stringify(t),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){t.Success&&n&&n(t,AccountPayout)}).fail(function(n){r.error(n.Error)})};r.loadSubPagerData=function(n){var t={PageSize:r.subscriptionPager().pageSize(),Page:r.subscriptionPager().pageIndex()+1,AccountId:r.data().account().id()};$.ajax({url:"/My/Billing/GetSubscriptionBillings",type:"POST",dataType:"json",data:JSON.stringify(t),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){t.Success&&n&&n(t,SubscriptionBilling)}).fail(function(n){r.error(n.Error)})};r.loadPendingSubPagerData=function(n){$.get("/My/Billing/GetPendingBillings",{PageSize:r.pendingSubscriptionPager().pageSize(),Page:r.pendingSubscriptionPager().pageIndex()+1,accountId:r.data().account().id()}).success(function(t){t.Success?n&&n(t,PendingSubscription):r.error(t.Error)}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error)})};r.load=function(){var t=$.grep(r.data().accounts(),function(n){return n.account().id()==r.data().account().id()});n.account().rentalNotificationEmail()&&r.hasRentalNotificationEmail(!0);r.subscriptionTier("Team Plus");r.subscriptionFrequency("Month");r.basicsValidator.Init({container:$("#basics")});r.hasRentalNotificationEmail.subscribe(function(n){n||r.data().account().rentalNotificationEmail(null)});r.editor=new MediumEditor(".editable",{placeholder:{text:"Type your message here"},autoLink:!0,buttonLabels:"fontawesome",toolbar:{buttons:["bold","italic","underline","anchor"],relativeContainer:$("#email-controls")[0]},anchorPreview:{showWhenToolbarIsVisible:!0}});$("#medium-editor-toolbar-1").css("visibility","visible");$.get("/My/Account/GetSettings",{id:r.data().account().id()}).success(function(n){if(n.Success){r.data().account().settings(n.Item);var t=r.data().account().getSetting("DisableYelp");r.disableYelp(t?t.Value.toLowerCase()==="true":!1);t=r.data().account().getSetting("DisableFacebook");r.disableFacebook(t?t.Value.toLowerCase()==="true":!1);t=r.data().account().getSetting("BookingConfirmation");r.bookingConfirmationMessage(t?t.Value:"");t!=null&&r.editor.setContent(t.Value)}});t.length>0&&t[0].type()>=PF.RoleType.LocationAdmin&&(t[0].type()>=PF.RoleType.Staff&&r.roles.push(new Role({name:"Staff",type:PF.RoleType.Staff})),t[0].type()>=PF.RoleType.Supervisor&&r.roles.push(new Role({name:"Supervisor",type:PF.RoleType.Supervisor})),t[0].type()>=PF.RoleType.Manager&&r.roles.push(new Role({name:"Manager",type:PF.RoleType.Manager})),t[0].type()>=PF.RoleType.LocationAdmin&&r.roles.push(new Role({name:"Location Admin",type:PF.RoleType.LocationAdmin})),$.get("/My/Account/GetUsers",{id:r.data().account().id()}).success(function(n){if(n.Success){var t=n.Item.map(function(n){return(new Role).fromServerModel(n)});r.accountUsers(t)}}));t.length>0&&t[0].type()>=PF.RoleType.LocationAdmin&&($.get("/My/Billing/GetBillingAccounts",{id:r.data().account().id()}).success(function(n){if(n.Success){var t=n.Item.map(function(n){return(new BillingAccount).fromServerModel(n)});t.length>0&&$.each(t,function(n,t){return t.type()==PF.AccountType.Ach&&r.achAccount(t),t.type()==PF.AccountType.CreditCard?(r.creditCardAccount(t),r.subscriptionPaymentSource(PF.AccountType.CreditCard),!1):void 0})}}),r.pager(new AsyncPagedListViewModel([],null,function(n){r.loadPagerData(n)})),r.pager().load(),r.subscriptionPager(new AsyncPagedListViewModel([],null,function(n){r.loadSubPagerData(n)},{PageSize:5})),r.subscriptionPager().load(),r.pendingSubscriptionPager(new AsyncPagedListViewModel([],null,function(n){r.loadPendingSubPagerData(n)},{PageSize:10})),r.pendingSubscriptionPager().load(),$.get("/My/Account/GetUnderwritingInfo",{accountId:r.data().account().id()}).success(function(n){n.Success?r.hasUnderWritingInfo(!0):r.hasUnderWritingInfo(!1);r.businessValidator.Init({container:$("#business")})}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error)}),$.get("/My/Account/GetGratuityPreferences",{account_Id:r.data().account().id()}).success(function(n){if(n.Success){var t=(new GratuityOptionsByAccount).fromServerModel(n.Item);r.gratuityOptions(t)}else r.error(n.Error)}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error)}));u=new PF.Modals.GoodDetails;ko.applyBindings(u,$("#good-details-modal")[0])};r.initPricingTiers=function(){};r.saveBasics=function(){if($(".alert-success",i).hide(),$(".alert-error",i).hide(),r.data().email()&&r.data().email(r.data().email().replace(/ /g,"")),r.basicsValidator.Validate()){r.busy(!0);var n=r.data().toServerModel(!0);$.ajax({url:"/My/Account/Save",type:"POST",dataType:"json",data:JSON.stringify(n),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){r.busy(!1);n.Success?(r.data().fromServerModel(n.Item),r.success()):r.error(n.Error)}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error)})}};r.saveBusiness=function(){var n,t;if($(".alert-success",i).hide(),$(".alert-error",i).hide(),!r.businessValidator.Validate()){PF.openAccordion("all");return}r.busy(!0);n=r.data().account().toServerModel(!0);$.ajax({url:"/my/account/saveaccount",type:"POST",dataType:"json",data:JSON.stringify(n),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){r.busy(!1);n.Success?(r.data().account().fromServerModel(n.Item),r.accountUnderWriting().accountNumber()==null&&r.success()):r.error(n.Error)});t=PF.getTextWithoutHTML($(".editable").html()).length>0?$(".editable").html():"";r.data().account().updateSetting("BookingConfirmation",t);$.each(r.data().account().settings(),function(n,t){var i={id:r.data().account().id(),key:t.Key,value:t.Value};$.ajax({url:"/My/Account/SaveSetting",type:"POST",dataType:"json",data:JSON.stringify(i),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){r.busy(!1);n.Success||r.error(n.Error)})});$.ajax({url:"/my/account/savegratuitypreferences",type:"POST",dataType:"json",data:JSON.stringify(r.gratuityOptions().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(){}).fail(function(){})};r.addAchAccount=function(){window.location.assign("/My/Account#go-business_additional-business-info")};r.showBooking=function(n){if(n.bookingId){PF.Modals.My_OpenBooking.Show({booking:{id:n.bookingId},mode:"readonly"});return}if(n.goodPurchaseId){const t={Item:{Id:n.goodPurchaseId}};$.post("/my/goods/GetGoodPurchaseById",t).success(function(n){if(n.Success){const t=(new GoodPurchase).fromServerModel(n.Item),i={purchase:t};u.load(i);$("#good-details-modal").modal("show")}else r.error(n.Error)}).fail(function(){r.error("Something went wrong, please try again or contact our support team.")})}};r.saveDeposits=function(){($(".alert-success",i).hide(),$(".alert-error",i).hide(),r.depositsValidator.Init({container:$("#deposits")}),r.depositsValidator.Validate())&&(r.busy(!0),$.ajax({url:"/My/Billing/SaveBillingAccount",type:"POST",dataType:"json",data:JSON.stringify({accountId:r.data().account().id(),billingAccount:r.achAccount().toServerModel()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){r.busy(!1);n.Success?(r.achAccount().fromServerModel(n.Item),r.success()):r.error(n.Error)}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error)}))};r.saveBilling=function(){if($(".alert-success",i).hide(),$(".alert-error",i).hide(),!r.achAccount())return!1;var n=r.data().isTrial()||r.data().account().providerType()<PF.ProviderType.Team;if(r.subscriptionPaymentSource()==PF.AccountType.CreditCard){if(r.billingValidator.Init({container:$("#billing")}),!r.billingValidator.Validate())return;r.busy(!0);$.ajax({url:"/My/Billing/SaveBillingAccount",type:"POST",dataType:"json",data:JSON.stringify({accountId:r.data().account().id(),billingAccount:r.creditCardAccount().toServerModel()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){r.busy(!1);t.Success?(r.creditCardAccount().fromServerModel(t.Item),r.success(),n&&r.subscribe()):r.error(t.Error)}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error)})}else n&&r.subscribe()};r.clearMessages=function(){$(".alert-success",i).hide();$(".alert-error",i).hide()};r.success=function(n){$(".alert-error",i).hide();$("html, body").animate({scrollTop:0},250);$(".alert-success",i).text(n||"Your changes were saved successfully!");$(".alert-success",i).show()};r.error=function(n){$(".alert-success",i).hide();r.errorMessage(n);$("html, body").animate({scrollTop:0},250);$(".alert-error",i).show()};r.impersonate=function(n){confirm("You are about to impersonate this user.  To get back to your account, you'll have to log out and log back in.  Shall we continue?")&&$.get("/My/Account/Impersonate",{userId:n.user().id(),roleId:n.id()}).success(function(){})};r.subscribe=function(){if(!r.achAccount().accountNumber()){r.error("You must provide your Bank's ACH information before continuing.");return}r.busy(!0);$.ajax({url:"/My/Billing/Subscribe",type:"POST",dataType:"json",data:JSON.stringify({accountId:r.data().account().id(),tier:r.subscriptionTier(),frequency:r.subscriptionFrequency()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){r.busy(!1);n.Success?(r.data().account().fromServerModel(n.SpaceProvider),r.data().account().trialEndDate()?r.data().account().nextBillingDate(r.data().account().trialEndDate()):r.data().account().nextBillingDate(n.NextSubscriptionBillingDate),r.data().account().subscriptionFrequency(r.subscriptionFrequency()),r.data().isTrial(!1),r.success("Welcome to PlaceFull "+r.data().account().providerTypeFullName()+" Private Label!"),$(".pf-top-banner").hide()):r.error(n.Error)}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error)})};r.add=function(){var n=new Role;n.account(r.data().account());n.user(new User);n.type(PF.RoleType.Staff);n.isolated("false");r.selectedItem(n);r.accountUsers.push(n);r.addedRole(r.selectedItem())};r.saveExistingUser=function(){r.clearMessages();var n=r.selectedItem();n.type(r.addedRole().type());r.busy(!0);$.ajax({url:"/my/account/saverole",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){r.busy(!1);t.Success?(r.success(),n.fromServerModel(t.Item),r.selectedItem(null)):r.error(t.Error)}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error)})};r.saveNewUser=function(){r.clearMessages();var n=r.selectedItem().user();r.busy(!0);$.ajax({url:"/my/account/saveuser",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){r.busy(!1);t.Success?(n.fromServerModel(t.Item),r.saveExistingUser()):r.error()}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error)})};r.cancelAddUser=function(){r.accountUsers.remove(r.selectedItem());r.selectedItem(null)};r.confirmRemoveRole=function(n){confirm("Are you sure you want to remove this user?")&&(r.clearMessages(),r.remove(n))};r.remove=function(n){r.busy(!0);$.ajax({url:"/my/account/deleterole",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){r.busy(!1);t.Success?(r.success(),r.accountUsers.remove(n)):r.error(t.Error)}).fail(function(n){r.busy(!1);n=JSON.parse(n.responseText);r.error(n.Error)})};r.templateToUse=function(n){return r.selectedItem()===n?"editTmpl":"itemsTmpl"};r.validateYelp=function(){$("#yelpCheckImage").removeClass("fa-spinner fa-check fa-times");r.busy(!0);$("#yelpCheckImage").addClass("fa-spinner");$.ajax({url:"/my/account/validateyelpid",type:"POST",dataType:"json",data:JSON.stringify(r.data().account().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){r.busy(!1);$("#yelpCheckImage").removeClass("fa-spinner fa-check fa-times");n.Success&&n.Item===!0?$("#yelpCheckImage").addClass("fa-check"):$("#yelpCheckImage").addClass("fa-times")}).fail(function(){r.busy(!1);$("#yelpCheckImage").removeClass("fa-spinner fa-check fa-times");$("#yelpCheckImage").addClass("fa-times")})};r.validateFacebook=function(){$("#fbCheckImage").removeClass("fa-spinner fa-check fa-times");r.busy(!0);$("#fbCheckImage").addClass("fa-spinner");$.ajax({url:"/my/account/ValidateFacebookId",type:"POST",dataType:"json",data:JSON.stringify(r.data().account().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){r.busy(!1);$("#fbCheckImage").removeClass("fa-spinner fa-check fa-times");n.Success&&n.Item===!0?$("#fbCheckImage").addClass("fa-check"):$("#fbCheckImage").addClass("fa-times")}).fail(function(){r.busy(!1);$("#fbCheckImage").removeClass("fa-spinner fa-check fa-times");$("#fbCheckImage").addClass("fa-times")})};r.removeBookingUser=function(n){var t=r.accountUsers().find(function(t){return t.user().email()===n.user().email()});t&&(t.sendBookingEmails(!1),r.editRole(t))};r.changeCountry=function(){r.error("To change your country please contact our support team at support@placefull.com")};r.removeBillingUser=function(n){var t=r.accountUsers().find(function(t){return t.user().email()===n.user().email()});t&&(t.sendBillingEmails(!1),r.editRole(t))};r.addBillingUser=function(){var n=r.availableRolesForBillingEmails().find(function(n){return n.user().email()===r.selectedBillingEmailUser().user().email()});n&&(n.sendBillingEmails(!0),r.editRole(n))};r.addBookingUser=function(){var n=r.availableRolesForBookingEmails().find(function(n){return n.user().email()===r.selectedBookingEmailUser().user().email()});n&&(n.sendBookingEmails(!0),r.editRole(n))};r.editRole=function(n){r.busy(!0);$.ajax({url:"/my/account/UpdateRole",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){r.busy(!1);n.Success?r.success():r.error(n.Error)}).fail(function(n){r.busy(!1);r.error(n.Error)})}},MyFranchisesViewModel=function(n,t){var i=this;i.country()=ko.observable();i.user=ko.observable(n);i.accounts=ko.observableArray();i.states=ko.observableArray();i.busy=ko.observable(!1);i.errorMessage=ko.observable();i.selectedItem=ko.observable();i.validator=new PF.FormValidator;i.success=function(n){$("html, body").animate({scrollTop:0},250);$(".alert-success",t).text(n||"Your changes were saved successfully!");$(".alert-success",t).show()};i.error=function(n){$(".alert-success",t).hide();i.errorMessage(n);$("html, body").animate({scrollTop:0},250);$(".alert-error",t).show()};i.load=function(){i.country(i.user().account().country());$.each(i.user().accounts(),function(n,t){i.accounts.push(t.account())});$.get("/api/geo/getstates").success(function(n){n.Success?i.states(n.Item):i.error(n.Error)}).fail(function(n){i.busy(!1);n=JSON.parse(n.responseText);i.error(n.Error)})};i.add=function(){var n=new Account;i.accounts.push(n);i.selectedItem(n);i.validator.Init({container:$(".edit-franchise",t)})};i.save=function(){if($(".alert-success",t).hide(),$(".alert-error",t).hide(),i.validator.Validate()){var n=i.selectedItem();i.busy(!0);$.ajax({url:"/my/account/createfranchise",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){i.busy(!1);t.Success?(n.fromServerModel(t.Item),i.selectedItem(null),window.location.reload()):i.error()}).fail(function(n){i.busy(!1);n=JSON.parse(n.responseText);i.error(n.Error)})}};i.remove=function(){};i.cancel=function(){var n=i.selectedItem();i.selectedItem(null);i.accounts.remove(n)};i.templateToUse=function(n){return i.selectedItem()===n?"editTmpl":"itemsTmpl"}},AdminAccountManagementViewModel=function(){var n=this;n.pager=ko.observable(new AsyncPagedListViewModel([],[],null));n.selectedItem=ko.observable();n.conversionVar=ko.observable();n.notificationTitle=ko.observable();n.notificationMessage=ko.observable();n.loadData=function(t){var i=n.pager().findFilter("text"),r=n.pager().findFilter("providerType");$.get("/Admin/Accounts/List",{PageSize:n.pager().pageSize(),Page:n.pager().pageIndex()+1,SearchText:i.value(),ProviderType:r.value()}).success(function(n){n.Success&&t&&t(n,Account)})};n.load=function(t){n.pager(new AsyncPagedListViewModel([],t,function(t){n.loadData(t)}));n.pager().load()};n.impersonate=function(t){n.selectedItem(t);$("#modal-admin-users-confirm-impersonate").modal("show")};n.confirmImpersonate=function(){$("#modal-admin-users-confirm-impersonate").modal("hide");$.get("/Admin/Users/Impersonate",{userId:n.selectedItem().id()}).success(function(n){console.log(n)})};n.confirmInvalidate=function(){$("#modal-admin-users-confirm-invalidate").modal("hide");$.get("/Admin/Users/InvalidateAccount",{userId:n.selectedItem().id()}).success(function(n){PF.Modals.Generic.Show({title:n.Success?"Success":"Error",description:n.Message,duration:5e3})})};n.confirmDelete=function(){$("#modal-admin-users-confirm-delete").modal("hide");$.get("/Admin/Users/DeleteAccount",{userId:n.selectedItem().id()}).success(function(t){n.load([{name:"text",reset:function(){this.value("")},value:ko.observable(""),text:function(){return this.value()},apply:function(n){return this.value()?PF.hasStringMatch(n.organizationName(),this.value())||PF.hasStringMatch(n.condensedName(),this.value())||PF.hasStringMatch(n.sitePropertiesAll(),this.value()):!0}},{name:"providerType",reset:function(){this.value("")},value:ko.observable(""),text:function(){return this.value()},apply:function(n){return this.value()?n.providerType()==this.value():!0}}]);PF.Modals.Generic.Show({title:t.Success?"Success":"Error",description:t.Message,duration:5e3})})};n.conversion=function(t){n.selectedItem(t);$("#modal-admin-users-confirm-conversion").modal("show")};n.invalidate=function(t){n.selectedItem(t);$("#modal-admin-users-confirm-invalidate").modal("show")};n.delete=function(t){n.selectedItem(t);$("#modal-admin-users-confirm-delete").modal("show")};n.confirmConversion=function(){$("#modal-admin-users-confirm-conversion").modal("hide");$.get("/Admin/Users/ConvertProperty",{userId:n.selectedItem().id(),attribute:n.conversionVar()}).success(function(n){PF.Modals.Generic.Show({title:n.Success?"Success":"Error",description:n.Message,duration:5e3})})};n.showUserReferralDialog=function(t){n.selectedItem(t);$("#modal-admin-user-referrals").modal("show")};n.showNotificationDialog=function(t){n.selectedItem(t);$("#modal-admin-notification").modal("show")};n.showNotificationDialog2=function(){$("#modal-admin-notification2").modal("show")};n.sendNotification=function(){$("#modal-admin-notification").modal("hide");$.get("/Admin/Accounts/SendNotification",{accountId:n.selectedItem().id(),notificationTitle:n.notificationTitle(),notificationMessage:n.notificationMessage()}).success(function(n){n.Success||PF.Modals.Generic.Show({title:"Error sending notification",description:n.Error})}).fail(function(){})};n.sendNotificationsAll=function(){$("#modal-admin-notification2").modal("hide");$.get("/Admin/Accounts/SendNotificationsAll",{notificationTitle:n.notificationTitle(),notificationMessage:n.notificationMessage()}).success(function(n){n.Success||PF.Modals.Generic.Show({title:"Error sending notification",description:n.Error})}).fail(function(){})};n.getUnencryptedEin=function(n){PF.Modals.ProgressIndicator.Show();$.ajax({url:"/admin/accounts/GetUnencryptedEIN/"+n.id(),type:"GET",processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){PF.Modals.ProgressIndicator.HideModal();PF.Modals.Generic.Show({title:"Unencrypted EIN",description:n.Success?n.Message:n.Error})}).error(function(n){PF.Modals.ProgressIndicator.HideModal();PF.Modals.Generic.Show({title:"Error",description:n.Error})})}},AdminAccountUsersViewModel=function(n){var t=this;t.data=ko.observable(n);t.selectedItem=ko.observable();t.busy=ko.observable(!1);t.errorMessage=ko.observable();t.roles=ko.observableArray();t.load=function(){t.roles.push({name:"Staff",value:PF.RoleType.Staff});t.roles.push({name:"Supervisor",value:PF.RoleType.Supervisor});t.roles.push({name:"Manager",value:PF.RoleType.Manager});t.roles.push({name:"Location Admin",value:PF.RoleType.LocationAdmin});t.roles.push({name:"Franchise Admin",value:PF.RoleType.FranchiseAdmin})};t.error=function(n){$(".alert-success").hide();t.errorMessage(n);$("html, body").animate({scrollTop:0},250);$(".alert-error").show()};t.impersonate=function(n){confirm("You are about to impersonate this user.  To get back to your account, you'll have to log out and log back in.  Shall we continue?")&&$.get("/My/Account/Impersonate",{userId:n.user().id(),roleId:n.id()}).success(function(n){console.log(n)})}},AdminTiersAndModulesViewModel=function(){var n=this;n.tiers=ko.observable();n.modules=ko.observable();n.selectedModule=ko.observable(!1);n.creatingModuleOption=ko.observable(!1);n.newModOpt=ko.observable();n.message=ko.observable();n.selectedModuleOptionDict=ko.observable();n.selectedModuleOptions=ko.observableArray();n.selectedModuleOptionId=ko.observable();n.selectedModuleOption=ko.observable();n.creatingTier=ko.observable(!1);n.newTier=ko.observable(new Tier({id:"new"}));n.tierDict={};n.selectedModule.subscribe(function(t){typeof t!="undefined"&&n.getModuleOptions(t)});n.selectedModuleOptionId.subscribe(function(t){typeof t!="undefined"&&n.selectedModuleOption(n.selectedModuleOptionDict[t])});n.load=function(){$.get("/Admin/Module/Tiers",function(t){t.Success?(n.addToTierDict(n.newTier().id()),n.tiers(t.Item.map(function(t){return n.addToTierDict(t.Id),(new Tier).fromServerModel(t)}))):n.message("Couldn't load tiers.")});$.get("/Admin/Module/Modules",function(t){t.Success?n.modules(t.Item.map(function(n){return(new Module).fromServerModel(n)})):n.message("Couldn't load modules.")});n.newModOpt=new ModuleOption;n.busy=!1};n.getModuleOptions=function(t){$.get("/Admin/Module/ModuleOptionsByModuleId",{id:t},function(t){t.Success?(n.selectedModuleOptionDict={},n.selectedModuleOptions(t.Item.map(function(t){return n.selectedModuleOptionDict[t.Id]=(new ModuleOption).fromServerModel(t),(new ModuleOption).fromServerModel(t)}))):n.message("Couldn't load module options.")})};n.toggleCreatingTier=function(){n.creatingTier(!n.creatingTier())};n.toggleCreatingModuleOption=function(){n.creatingModuleOption(!n.creatingModuleOption())};n.removeTierModuleOption=function(n){n.removeModuleOption(this)};n.addTierModuleOption=function(){var t=n.tierDict[this.id()].selectedModuleOptionDict[n.tierDict[this.id()].selectedModuleOptionId()];this.addModuleOption(t)};n.addToTierDict=function(t){n.tierDict[t]={selectedModuleOptionId:ko.observable(),selectedModuleOptions:ko.observableArray(),selectedModule:ko.observable(),selectedModuleOptionDict:ko.observable()};n.tierDict[t].selectedModule.subscribe(function(i){typeof i!="undefined"&&$.get("/Admin/Module/ModuleOptionsByModuleId",{id:i},function(i){i.Success?(n.tierDict[t].selectedModuleOptionDict={},n.tierDict[t].selectedModuleOptions(i.Item.map(function(i){return n.tierDict[t].selectedModuleOptionDict[i.Id]=(new ModuleOption).fromServerModel(i),(new ModuleOption).fromServerModel(i)}))):n.message("Error! Couldn't load Module Options")})})};n.saveTier=function(){$.post("/Admin/Module/SaveTier",this.toServerModel(),function(t){t.Success?(n.message("Tier successfully saved"),n.newTier(new Tier),n.creatingTier(!1)):n.message("Couldn't save Tier. "+t.Error)})};n.saveModOpt=function(){$.post("/Admin/Module/SaveModuleOption",this.toServerModel(),function(t){t.Success?(n.message("module option successfully created."),n.newModOpt=new ModuleOption,n.creatingModuleOption(!1)):n.message("Couldn't create module option "+t.Error)})}},AdminUserViewModel=function(n){function i(){$(".select-account").select2({ajax:{url:"/Admin/Accounts/List",dataType:"json",delay:250,data:function(n){return{SearchText:n.term,Page:n.page||1,PageSize:30}},processResults:function(n,t){t.page=t.page||1;const i=$.map(n.Item,function(n){return{text:n.OrganizationName,id:n.CondensedName}});return{results:i,pagination:{more:t.page*30<n.TotalCount}}},cache:!0},placeholder:"Search for a account",minimumInputLength:1})}var t=this;t.user=ko.observable(n);t.busy=ko.observable(!1);t.errorMessage=ko.observable();t.validator=new PF.FormValidator;t.addedAccountName=ko.observable();t.addedRole=ko.observable();t.roles=ko.observableArray();t.load=function(n){t.roles.push({name:"Staff",value:PF.RoleType.Staff});t.roles.push({name:"Supervisor",value:PF.RoleType.Supervisor});t.roles.push({name:"Manager",value:PF.RoleType.Manager});t.roles.push({name:"Location Admin",value:PF.RoleType.LocationAdmin});t.roles.push({name:"Franchise Admin",value:PF.RoleType.FranchiseAdmin});t.validator.Init({container:n});i()};t.save=function(){if(t.validator.Init({container:$("#view")}),!t.validator.Validate())return!1;t.busy(!0);const i=t.user().toServerModel(),r={condensedName:t.addedAccountName()},n={};n.type=t.addedRole();n.account=r;i.accounts=[n];$.ajax({url:"/admin/users/save",type:"POST",dataType:"json",data:JSON.stringify(i),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){t.busy(!1);n.Success?(t.user().fromServerModel(n.Item),t.success()):t.error(n)}).fail(function(n){t.busy(!1);n=JSON.parse(n.responseText);t.error(n.Error)})};t.success=function(n){$(".alert-error").hide();$("html, body").animate({scrollTop:0},250);$(".alert-success").text(n||"Your changes were saved successfully!");$(".alert-success").show()};t.error=function(n){$(".alert-success").hide();t.errorMessage(n);$("html, body").animate({scrollTop:0},250);$(".alert-error").show()}},CampaignBulkManagementViewModel=function(n){var t=this;t.availableTags=ko.observableArray();t.availableSiteProperities=ko.observableArray();t.selectedSiteProperty=ko.observable();t.selectedTag=ko.observable();t.selectedCampaign=ko.observable();t.templatesInCampaign=ko.observableArray();t.initialCampaign=n.Campaign;t.usersOrLeads=ko.observable();t.loadCampaign=function(n){var i=t.selectedCampaign()?t.selectedCampaign().campaign:t.initialCampaign;$.get("/Admin/Email/GetCampaign",{Campaign:i}).success(function(i){t.templatesInCampaign.removeAll();i.TemplatesInCampaign.map(function(n){t.templatesInCampaign.push((new EmailNotification).fromServerModel(n))});i.AvailableSiteProperities.map(function(n){t.availableSiteProperities.push((new SiteProperty).fromServerModel(n))});i.AvailableTags.map(function(n){t.availableTags.push((new CustomGroup).fromServerModel(n))});t.selectedCampaign(t.templatesInCampaign()[0]);n&&typeof n.success=="function"&&n.success()})};t.load=function(){t.loadCampaign()};t.preview=function(){t.save(!0)};t.save=function(n){var i={SelectedCampaign:t.selectedCampaign().toServerModel(),Tag:t.selectedTag()?t.selectedTag().toServerModel():null,SiteProperty:t.selectedSiteProperty()?t.selectedSiteProperty().toServerModel():null,Preview:n,RecipientType:t.usersOrLeads()};$.ajax({url:"/Admin/Email/BulkCampaignAssociation",type:"POST",dataType:"json",data:JSON.stringify(i),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n.Success?i.Preview?PF.Modals.Generic.Show({title:"Will Edit "+n.TotalRecipientsAssociatedWithCampaigns+" Recipients",description:"This will apply the "+t.selectedCampaign().campaign()+" Campaign to "+n.TotalRecipientsAssociatedWithCampaigns+" recipients with valid emails. The first emails will likely be sent immediately.  Are you sure?",confirm:function(){t.save(!1)}}):PF.Modals.Generic.Show({title:"Success",description:"Applied the "+t.selectedCampaign().campaign()+" Campaign to "+n.TotalRecipientsAssociatedWithCampaigns+" recipients."}):console.log(n)})}},CampaignManagementViewModel=function(n){var t=this;t.selectedItem=ko.observable();t.availableTags=ko.observableArray();t.availableCampaigns=ko.observableArray();t.selectedTags=ko.observableArray();t.selectedCampaign=ko.observable();t.selectedRecipientCampaigns=ko.observableArray();t.selectedRecipient=ko.observable();t.initialRecipientId=n.RecipientId;t.emailNotificationDetail=ko.observable();t.emailsYetToBeSent=ko.observableArray();t.emailsSent=ko.observableArray();t.recipientEmailsYetToBeSent=ko.observableArray();t.recipientEmailsSent=ko.observableArray();t.recipientEmailNotificationDetail=ko.observable();t.templatesInCampaign=ko.observableArray();t.selectedCampaign.subscribe(function(n){console.log("newValue: ",n);n&&t.loadCampaign()});t.loadCampaign=function(n){var i=t.selectedCampaign()?t.selectedCampaign().campaign:null;$.get("/Admin/Email/GetCampaign",{Campaign:i,AccountId:initialRecipientId}).success(function(i){t.selectedCampaign()||(t.availableCampaigns.removeAll(),i.AvailableEmailCampaigns.map(function(n){t.availableCampaigns.push((new EmailNotification).fromServerModel(n))}));t.loadRecipient();t.emailNotificationDetail((new EmailNotificationDetail).fromServerModel(i.EmailNotificationDetail));t.emailsYetToBeSent.removeAll();t.emailsSent.removeAll();t.templatesInCampaign.removeAll();i.EmailsYetToBeSent.map(function(n){t.emailsYetToBeSent.push((new SMTPQueueDetail).fromServerModel(n))});i.EmailsSent.map(function(n){t.emailsSent.push((new SMTPQueueDetail).fromServerModel(n))});i.TemplatesInCampaign.map(function(n){t.templatesInCampaign.push((new EmailNotification).fromServerModel(n))});n&&typeof n.success=="function"&&n.success()})};t.load=function(){t.loadCampaign()};t.loadRecipient=function(){t.initialRecipientId&&$.get("/Admin/Email/GetRecipient",{RecipientId:t.initialRecipientId}).success(function(n){n.Item!=null&&(typeof n.Item.LoginTypeId!="undefined"?t.selectedRecipient((new User).fromServerModel(n.Item)):t.selectedRecipient((new CustomerLead).fromServerModel(n.Item)),t.loadRecipientEmailHistory(),t.selectedRecipientCampaigns.removeAll(),t.selectedRecipient().emailCampaigns&&t.selectedRecipient().emailCampaigns()&&$.each(t.selectedRecipient().emailCampaigns(),function(n,i){$.each(t.availableCampaigns(),function(n,r){i.id()==r.id()&&t.selectedRecipientCampaigns.push(r)})}))})};t.loadRecipientEmailHistory=function(){t.initialRecipientId&&$.get("/Admin/Email/GetRecipientEmailHistory",{RecipientId:t.selectedRecipient().id()}).success(function(n){n.EmailsYetToBeSent.map(function(n){t.recipientEmailsYetToBeSent.push((new SMTPQueueDetail).fromServerModel(n))});n.EmailsSent.map(function(n){t.recipientEmailsSent.push((new SMTPQueueDetail).fromServerModel(n))});t.recipientEmailNotificationDetail((new EmailNotificationDetail).fromServerModel(n.EmailNotificationDetail))})};t.showTemplate=function(n){var t={Template:n.template()};$.ajax({url:"/Admin/Email/GetTemplateHTML",type:"POST",dataType:"json",data:JSON.stringify(t),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){PF.Modals.Generic.Show({init:function(){$("#modalMessage").html(n)}})})};t.save=function(){t.selectedRecipient().emailCampaigns=t.selectedRecipientCampaigns;var n=typeof t.selectedRecipient().isTrial!="undefined"?t.selectedRecipient().toServerModel():null,i=typeof t.selectedRecipient().source!="undefined"?t.selectedRecipient().toServerModel():null,r={Lead:i,User:n};t.recipientEmailsYetToBeSent.removeAll();t.recipientEmailsSent.removeAll();$.ajax({url:"/Admin/Email/SaveRecipient",type:"POST",dataType:"json",data:JSON.stringify(r),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n.Success?t.loadRecipientEmailHistory():console.log(n)})};t.templateToUse=function(n){return t.selectedItem()===n?"editTmpl":"itemsTmpl"}},EditAccountModuleViewModel=function(n){var t=this;t.account=ko.observable(n);t.busy=!1;t.tiers=ko.observableArray();t.modules=ko.observableArray();t.selectedTier=ko.observable();t.selectedModule=ko.observable(!1);t.selectedModuleOptionId=ko.observable(!1);t.selectedModuleOptions=ko.observable();t.selectedModuleOptionDict=ko.observable();t.message=ko.observable();t.selectedModule.subscribe(function(n){typeof n!="undefined"&&t.getModuleOptions(n)});t.load=function(){t.busy=!0;$.get("/Admin/Module/Tiers",function(n){n.Success?(t.tiers(n.Item.map(function(n){return(new Tier).fromServerModel(n)})),t.account().tier()?t.selectedTier(t.account().tier().id()):t.account().tier(new Tier)):t.message("Couldn't load tiers")});$.get("/Admin/Module/Modules",function(n){n.Success?t.modules(n.Item.map(function(n){return(new Module).fromServerModel(n)})):t.message("Couldn't load modules")});t.busy=!1};t.getModuleOptions=function(n){$.get("/Admin/Module/ModuleOptionsByModuleId",{id:n},function(n){n.Success?(t.selectedModuleOptionDict={},t.selectedModuleOptions(n.Item.map(function(n){return t.selectedModuleOptionDict[n.Id]=(new ModuleOption).fromServerModel(n),(new ModuleOption).fromServerModel(n)}))):t.message("Couldn't load module options.")})};t.removeModuleOption=function(n){t.account().removeModuleOption(n)};t.addModuleOption=function(){var n=new AccountModuleOption;n.accountId(t.account().id());n.moduleOption(t.selectedModuleOptionDict[t.selectedModuleOptionId()]);t.account().addModuleOption(n)};t.save=function(){var n=new Tier,i;n.id(t.selectedTier());i=new Account({id:t.account().id(),moduleOptions:t.account().moduleOptions(),tier:n});$.post("/Admin/Accounts/SaveAccount",i.toServerModel(),function(n){n.Success?t.message("Account saved"):t.message("Error while saving account")})}},EditAccountUnderWritingInfoViewModel=function(n,t,i){var r=this;r.busy=ko.observable(!1);r.errorMessage=ko.observable();r.accountUnderWriting=ko.observable();r.country=ko.observable(i);r.load=function(){r.accountUnderWriting((new AccountUnderwritingInfo).fromServerModel(t))};r.saveUnderwritingInfo=function(){return r.busy(!0),PF.Modals.ProgressIndicator.Show({message:"Modifying..."}),$.ajax({url:"/admin/accounts/SaveUnderWritingInfo",type:"POST",dataType:"json",data:JSON.stringify(r.accountUnderWriting().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){PF.Modals.ProgressIndicator.HideModal();r.busy(!1);n.Success?r.success():r.error(n.Error)}).fail(function(n){PF.Modals.ProgressIndicator.HideModal();r.busy(!1);r.error(n.Error)}),!0};r.saveUnderwritingInfoTrx=function(){return r.busy(!0),PF.Modals.ProgressIndicator.Show({message:"Modifying..."}),$.ajax({url:"/admin/accounts/SaveUnderWritingInfoTrx",type:"POST",dataType:"json",data:JSON.stringify(r.accountUnderWriting().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){PF.Modals.ProgressIndicator.HideModal();r.busy(!1);n.Success?r.success():r.error(n.Error)}).fail(function(n){PF.Modals.ProgressIndicator.HideModal();r.busy(!1);r.error(n.Error)}),!0};r.saveUnderwritingInfoOnly=function(){return r.busy(!0),PF.Modals.ProgressIndicator.Show({message:"Modifying..."}),$.ajax({url:"/admin/accounts/SaveUnderWritingInfoOnly",type:"POST",dataType:"json",data:JSON.stringify(r.accountUnderWriting().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){PF.Modals.ProgressIndicator.HideModal();r.busy(!1);n.Success?r.success():r.error(n.Error)}).fail(function(n){PF.Modals.ProgressIndicator.HideModal();r.busy(!1);r.error(n.Error)}),!0};r.SaveStorageSafeAchFromUnderwritingAchTrx=function(){return r.busy(!0),PF.Modals.ProgressIndicator.Show({message:"Modifying..."}),$.ajax({url:"/admin/accounts/SaveStorageSafeAchFromUnderwritingAchTrx",type:"POST",dataType:"json",data:JSON.stringify(r.accountUnderWriting().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){PF.Modals.ProgressIndicator.HideModal();r.busy(!1);n.Success?r.success():r.error(n.Error)}).fail(function(n){PF.Modals.ProgressIndicator.HideModal();r.busy(!1);r.error(n.Error)}),!0};r.success=function(n){$(".alert-error").hide();$("html, body").animate({scrollTop:0},250);$(".alert-success").text(n||"Your changes were saved successfully!");$(".alert-success").show()};r.error=function(n){$(".alert-success").hide();r.errorMessage(n);$("html, body").animate({scrollTop:0},250);$(".alert-error").text(n||"A general error was encountered saving underwriting info or creating the ProPay account.");$(".alert-error").show()};r.load(n)},LeadManagementViewModel=function(n){var t=this;t.pager=ko.observable(new AsyncPagedListViewModel([],[],null));t.innerList=ko.observableArray(n);t.selectedItem=ko.observable();t.availableTags=ko.observableArray();t.availableEmailCampaigns=ko.observableArray();t.selectedTags=ko.observableArray();t.filteredByCampaign=ko.observableArray();t.loadData=function(n){var i=t.pager().findFilter("text"),r=t.pager().findFilter("providerType");$.get("/Admin/Users/ListLeads",{PageSize:t.pager().pageSize(),Page:t.pager().pageIndex()+1,SearchText:i.value()}).success(function(i){i.Success&&(i.AvailableTags.map(function(n){t.availableTags.push((new CustomGroup).fromServerModel(n))}),i.AvailableEmailCampaigns.map(function(n){t.availableEmailCampaigns.push((new EmailNotification).fromServerModel(n))}),n&&n(i,CustomerLead))})};t.load=function(n){t.pager(new AsyncPagedListViewModel([],n,function(n){t.loadData(n)}));t.pager().load()};t.edit=function(n){t.selectedItem(n);t.selectedTags.removeAll();$.each(n.tags(),function(n,i){$.each(t.availableTags(),function(n,r){i.id()==r.id()&&t.selectedTags.push(r)})});t.filteredByCampaign()&&t.filteredByCampaign.removeAll();$.each(n.emailCampaigns(),function(n,i){$.each(t.availableEmailCampaigns(),function(n,r){i.id()==r.id()&&t.filteredByCampaign.push(r)})})};t.cancel=function(){t.selectedItem(null);t.pager().innerList.shift()};t.add=function(){var n=new CustomerLead;t.pager().innerList.unshift(n);t.selectedItem(n);t.selectedTags.removeAll()};t.remove=function(n){n.id()?confirm("Are you sure you wish to delete this item? Any queued emails will be removed.")&&$.ajax({url:"/Admin/Users/DeleteLead",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(i){i.Success?(t.pager().innerList.remove(n),t.pager().pageIndex()>t.pager().maxPageIndex()&&t.pager().moveToPage(t.pager().maxPageIndex())):PF.Modals.Generic.Show({description:i.Error,title:"Error Occurred"})}):(t.pager().innerList.remove(n),t.pager().pageIndex()>t.pager().maxPageIndex()&&t.pager().moveToPage(t.pager().maxPageIndex()))};t.save=function(){var n=t.selectedItem();n.tags=t.selectedTags;$.ajax({url:"/Admin/Users/SaveLead",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n.Success?(t.innerList.remove(t.selectedItem()),t.innerList.push((new CustomerLead).fromServerModel(n.Item)),t.selectedItem(null)):PF.Modals.Generic.Show({description:t.selectedItem().email()+" : "+n.Error+"<br><br> Edit that existing user instead.",title:"Error Occurred"})})};t.templateToUse=function(n){return t.selectedItem()===n?"editTmpl":"itemsTmpl"}},AdminLogsViewModel=function(){var n=this;n.pager=ko.observable(new AsyncPagedListViewModel([],[],null));n.selectedItem=ko.observable();n.loadData=function(t){var i=n.pager().findFilter("text"),r=n.pager().findFilter("level");$.get("/Admin/Logs/List",{PageSize:n.pager().pageSize(),Page:n.pager().pageIndex()+1,SearchText:i.value(),Level:r.value()}).success(function(n){n.Success&&t&&t(n,Log)})};n.load=function(t){n.pager(new AsyncPagedListViewModel([],t,function(t){n.loadData(t)}));n.pager().load()}},AdminUserManagementViewModel=function(n){var t=this;t.mode=n||"Users";t.pager=ko.observable(new AsyncPagedListViewModel([],[],null));t.selectedItem=ko.observable();t.conversionVar=ko.observable();t.loadData=function(n){var i=t.pager().findFilter("text"),r=t.pager().findFilter("providerType");$.get("/Admin/Users/List"+t.mode,{PageSize:t.pager().pageSize(),Page:t.pager().pageIndex()+1,SearchText:i.value(),NewProviderType:r.value()}).success(function(t){t.Success&&n&&n(t,User)})};t.load=function(n){t.pager(new AsyncPagedListViewModel([],n,function(n){t.loadData(n)}));t.pager().load()};t.impersonate=function(n){t.selectedItem(n);$("#modal-admin-users-confirm-impersonate").modal("show")};t.confirmImpersonate=function(){$("#modal-admin-users-confirm-impersonate").modal("hide");$.get("/Admin/Users/Impersonate",{userId:t.selectedItem().id()}).success(function(n){n.Success?console.log(n):PF.Modals.Generic.Show({title:"Impersonate Failed",description:n.Error})})};t.confirmInvalidate=function(){$("#modal-admin-users-confirm-invalidate").modal("hide");$.get("/Admin/Users/InvalidateAccount",{userId:t.selectedItem().id()}).success(function(n){PF.Modals.Generic.Show({title:n.Success?"Success":"Error",description:n.Message,duration:5e3})})};t.conversion=function(n){t.selectedItem(n);$("#modal-admin-users-confirm-conversion").modal("show")};t.invalidate=function(n){t.selectedItem(n);$("#modal-admin-users-confirm-invalidate").modal("show")};t.confirmConversion=function(){$("#modal-admin-users-confirm-conversion").modal("hide");$.get("/Admin/Users/ConvertProperty",{userId:t.selectedItem().id(),attribute:t.conversionVar()}).success(function(n){PF.Modals.Generic.Show({title:n.Success?"Success":"Error",description:n.Message,duration:5e3})})}},AdminUserRoleViewModel=function(n){function i(){$(".select-account").select2({ajax:{url:"/Admin/Accounts/List",dataType:"json",delay:250,data:function(n){return{SearchText:n.term,Page:n.page||1,PageSize:30}},processResults:function(n,t){t.page=t.page||1;const i=$.map(n.Item,function(n){return{text:n.OrganizationName,id:n.CondensedName}});return{results:i,pagination:{more:t.page*30<n.TotalCount}}},cache:!0},placeholder:"Search for a account",minimumInputLength:1})}var t=this;t.data=ko.observable(n);t.selectedItem=ko.observable();t.addedAccountName=ko.observable();t.addedRole=ko.observable();t.roles=ko.observableArray();t.load=function(){t.roles.push({name:"Staff",value:PF.RoleType.Staff});t.roles.push({name:"Supervisor",value:PF.RoleType.Supervisor});t.roles.push({name:"Manager",value:PF.RoleType.Manager});t.roles.push({name:"Location Admin",value:PF.RoleType.LocationAdmin});t.roles.push({name:"Franchise Admin",value:PF.RoleType.FranchiseAdmin})};t.add=function(){var n=new Role;n.user(t.data());n.account(new Account);n.type(PF.RoleType.Staff);t.selectedItem(n);t.data().accounts.push(n);i()};t.save=function(){var n=t.selectedItem();n.type(t.addedRole());n.account().condensedName(t.addedAccountName());$.ajax({url:"/admin/users/saverole",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(i){i.Success?(n.fromServerModel(i.Item),t.addedAccountName(null),t.selectedItem(null)):console.log(i)}).fail(function(n){console.log(n)})};t.cancel=function(){t.data().accounts.remove(t.selectedItem());t.selectedItem(null)};t.remove=function(n){n.user(t.data());$.ajax({url:"/admin/users/deleterole",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(i){i.Success?(console.log(i),t.data().accounts.remove(n)):console.log(i)}).fail(function(n){console.log(n)})};t.templateToUse=function(n){return t.selectedItem()===n?"editTmpl":"itemsTmpl"}},VariableManagementViewModel=function(n,t){var i=this;i.innerList=ko.observableArray(n);i.pageSize=ko.observable(10);i.pageIndex=ko.observable(0);i.selectedItem=ko.observable();i.filters=ko.observableArray(t||[]);i.selectedItem=ko.observable();i.loadData=function(n){$.get("/Admin/Manage/ListGeoVariables",{}).success(function(t){var r=t.Item.map(function(n){return(new GeoVariable).fromServerModel(n)});i.innerList(r);n&&typeof n.success=="function"&&n.success()})};i.load=function(){i.loadData()};i.edit=function(n){i.selectedItem(n)};i.cancel=function(){i.selectedItem(null)};i.add=function(){var n=new GeoVariable;i.innerList.push(n);i.selectedItem(n);i.moveToPage(i.maxPageIndex())};i.remove=function(n){n.id()?confirm("Are you sure you wish to delete this item?")&&$.ajax({url:"/Admin/Manage/DeleteGeoVariable",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){t.Success?(i.innerList.remove(n),i.pageIndex()>i.maxPageIndex()&&i.moveToPage(i.maxPageIndex())):console.log(t)}):(i.list.remove(n),i.pageIndex()>i.maxPageIndex()&&i.moveToPage(i.maxPageIndex()))};i.save=function(){var n=i.selectedItem();$.ajax({url:"/Admin/Manage/SaveGeoVariable",type:"POST",dataType:"json",data:JSON.stringify(n.toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n.Success&&n.Item.length>0?(i.selectedItem().fromServerModel(n.Item[0]),i.selectedItem(null)):console.log(n)})};i.templateToUse=function(n){return i.selectedItem()===n?"editTmpl":"itemsTmpl"};i.findFilter=function(n){var t=null;return $.each(i.filters(),function(i,r){if(r.name===n)return t=r,!1}),t};i.applyFilter=function(n,t){var r=i.findFilter(n);r&&t(r)};i.filteredList=ko.dependentObservable(function(){var n=[];return $.each(i.innerList(),function(t,r){var u=!0;$.each(i.filters(),function(n,t){t.apply(r)||(u=!1)});u&&n.push(r)}),n});i.getFilterText=function(n){var t="";return i.applyFilter(n,function(n){t=n.text()}),t};i.maxPageIndex=ko.dependentObservable(function(){return Math.ceil(i.filteredList().length/i.pageSize())-1});i.previousPage=function(){i.pageIndex()>0&&i.pageIndex(i.pageIndex()-1)};i.nextPage=function(){i.pageIndex()<i.maxPageIndex()&&i.pageIndex(i.pageIndex()+1)};i.allPages=ko.dependentObservable(function(){for(var r=[],t="",n=0;n<=i.maxPageIndex();n++)j=n+1,t=n==0||n==i.maxPageIndex()||Math.abs(n-i.pageIndex())<4?n==i.pageIndex()?j:j:t=="..."||t==""?"":"...",t!=""&&r.push({pageNumber:t,disabled:t==="..."});return r});i.moveToPage=function(n){i.pageIndex(n)};i.pagedList=ko.dependentObservable(function(){var t=i.pageSize(),n;return i.pageIndex()>i.maxPageIndex()&&i.pageIndex(0),n=i.pageIndex()*t,i.filteredList().slice(n,n+t)})},DesktopPOSBitcoinViewModel=function(){var n=this;n.testNet=!1;n.paymentInstrument=new PaymentInstrument;n.holdingArea=null;n.license=new DriversLicense;n.email=ko.observable();n.fundSuccess=ko.observable(!1);n.purchaseSuccess=ko.observable(!1);n.showZipOrCvvError=ko.observable(!1);n.user=ko.observable();n.container=null;n.printerIPAddress=ko.observable();n.product={scan:!1};n.transaction=new BitcoinTransaction;n.account=ko.observable();n.errorMessage=ko.observable();n.wallet=new BitcoinWallet({testNet:n.testNet,errorMessage:n.errorMessage});n.wallet.encryptedPrivateKey.subscribe(function(t){t&&t.length>=0&&n.setToPurchaseModeAfterFunding()});n.license.state.subscribe(function(t){t&&t!="WA"&&(n.paymentInstrument.update({}),n.license.update({}),n.errorMessage("We only accept Washington State drivers licenses"));t&&t=="WA"&&n.errorMessage("")});n.license.over21.subscribe(function(t){t==!1?n.errorMessage("Must be over 21 years old to proceed"):n.errorMessage("")});n.purchaseMode=ko.computed({read:function(){return n.wallet.encryptedPrivateKey()},write:function(t){t&&(n.wallet.encryptedPrivateKey("scan"),n.wallet.address(""),n.purchaseSuccess(!1))},owner:n});n.fundMode=ko.computed({read:function(){return n.wallet.address()?!n.wallet.encryptedPrivateKey():!1},write:function(t){t&&(n.reset(),n.wallet.address("scan"),n.wallet.encryptedPrivateKey(""))},owner:n});n.setToPurchaseModeAfterFunding=function(){n.paymentInstrument.accountNumber(null);n.wallet.encryptedPrivateKey()!==""&&n.wallet.address()!==""||(n.wallet.address(""),n.wallet.encryptedPrivateKey("scan"));n.fundSuccess(!1)};n.setToNoMode=function(){n.holdingArea=n.wallet.address();n.wallet.address("");n.wallet.encryptedPrivateKey("")};n.reset=function(){n.resetFields();n.transaction.update({});n.fundSuccess(!1);n.purchaseSuccess(!1);n.email(null);n.errorMessage("")};n.resetFields=function(){n.wallet.update({testNet:n.testNet,account_Id:n.account.id()});n.license.update({});n.paymentInstrument.update({})};n.loaded=ko.observable(!1);n.load=function(t){n.container=t.container;n.testNet=t.network=="TestNet"?!0:!1;n.account=t.account;n.wallet.testNet=n.testNet;n.wallet.account_Id(n.account.id());n.validator=new PF.FormValidator;n.validator.Init({container:t.container});PF.ScannerReaderDecoder({paymentInstrument:n.paymentInstrument,wallet:n.wallet,driversLicense:n.license,capsLockWarningCallback:function(t){t&&n.errorMessage("Hey Wait! Your Caps Lock key is on. The scanner does not work with it on!")}});n.loadSettingsModal();n.loaded(!0)};n.printCoupon=function(t,i){var r="http://"+window.location.host+"/My/Print?testNet="+n.testNet+"&printerIP="+n.printerIPAddress();window.open(r);$(i.target).blur();n.reset()};n.printFundingReceipt=function(){var t="http://"+window.location.host+"/My/Print?testNet="+n.testNet+"&printerIP="+n.printerIPAddress();t=t+"&lastFour="+n.paymentInstrument.lastFour()+"&fundingAmount="+n.transaction.amountUSDTransferred();t=t+"&balance="+n.wallet.balanceUSD()+"&address="+n.holdingArea;window.open(t);n.setToPurchaseModeAfterFunding()};n.transact=function(){n.license.over21()&&(n.purchaseMode()&&n.wallet.encryptedPrivateKey()&&n.wallet.encryptedPrivateKey()!="scan"?n.purchase():n.fundMode()&&n.wallet.address()&&n.wallet.address()!="scan"&&n.fund())};n.purchase=function(){if(n.validator.Validate()){n.showZipOrCvvError(!1);n.transaction.consumerWallet(n.wallet);n.transaction.fromWalletAddress(n.wallet.address());n.transaction.driversLicense(n.license);n.transaction.account_Id(n.account.id());var t={Item:n.transaction.toServerModel(),Email:n.email()};PF.Modals.ProgressIndicator.Show({message:"Purchasing..."});$.ajax({type:"POST",url:"/Api/Bitcoin/Purchase",data:JSON.stringify(t),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){PF.Modals.ProgressIndicator.HideModal(function(){t.Success==!1?PF.Modals.Generic.Show({title:"Error During Purchase",description:t.Error}):(n.purchaseSuccess(!0),n.wallet.getWalletBalance(),n.setToNoMode(),n.resetFields())})}})}else window.scrollTo(0,0),n.showZipOrCvvError(!0)};n.fund=function(){if(n.validator.Validate()){n.showZipOrCvvError(!1);n.paymentInstrument.email(n.email());var t={Item:n.wallet.toServerModel(),PaymentInstrument:n.paymentInstrument.toServerModel(),DriversLicense:n.license.toServerModel(),Amount:n.transaction.amountUSDTransferred(),Currency:"USD"};PF.Modals.ProgressIndicator.Show({message:"Purchasing..."});$.ajax({type:"POST",url:"/Api/Bitcoin/FundWallet",data:JSON.stringify(t),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){PF.Modals.ProgressIndicator.HideModal(function(){t.Success==!1?PF.Modals.Generic.Show({title:"Error During Purchase",description:t.Error}):(n.fundSuccess(!0),n.wallet.getWalletBalance(),n.setToNoMode())})}})}else window.scrollTo(0,0),n.showZipOrCvvError(!0)};n.loadSettingsModal=function(){var t=window.settingsModal=new BitcoinSettingsViewModel(n.printerIPAddress,$("#modal-bitcoinsettings"),null);ko.applyBindings(t,$("#modal-bitcoinsettings")[0]);t.load()}},POSBitcoinViewModel=function(){var n=this,t,i,r;n.testNet=!1;n.paymentInstrument=new PaymentInstrument;n.holdingArea=null;n.license=new DriversLicense;n.email=ko.observable("");n.emailIsValid=ko.observable(!1);n.showZipOrCvvError=ko.observable(!1);n.container=null;n.scannerDecoder=null;n.printerIPAddress=ko.observable();n.product={scan:!1};n.transaction=new BitcoinTransaction;n.account=ko.observable();n.firstName=ko.observable();n.errorMessage=ko.observable();n.retryDueToError=ko.observable(!1);n.validator=new PF.FormValidator;n.wallet=new BitcoinWallet({testNet:n.testNet,errorMessage:n.errorMessage});n.headerShown=ko.observable(!0);n.sideBarShown=ko.observable(!1);n.cancelButton=ko.observable(!1);n.signaturePad=null;n.signatureComplete=ko.observable(!1);n.purchaseComplete=ko.observable(!1);n.fundComplete=ko.observable(!1);n.licenseSwipeReady=ko.observable(!1);n.scanCodeReady=ko.observable(!1);n.savedEmail=ko.observable(!1);n.emailSent=ko.observable(!1);t=[];n.licenseSwipeReady.subscribe(function(n){n==!0&&window.scrollTo(0,54)});n.email.subscribe(function(t){n.emailIsValid(t==null||t==""?!1:n.validator.isValidEmailAddress(t))});n.errorMessage.subscribe(function(t){t&&n.gearsModal("hide")});n.paymentInstrument.accountNumber.subscribe(function(i){if(i&&i.length>=0&&n.page.current()=="swipeCard")if(n.transaction.amountExcludingTip()&&parseInt(n.transaction.amountExcludingTip())>0&&parseInt(n.transaction.amountExcludingTip())<250)n.errorMessage(null),n.page.cardResults();else{n.errorMessage(null);n.paymentInstrument.update({});var u=n.page.current(t.pop());u.current()&&(n.errorMessage("Please enter a correct amount"),r(u.current()))}else n.page.current()||(n.errorMessage(null),n.paymentInstrument.update({}))});n.license.state.subscribe(function(){});n.license.scan.subscribe(function(i){i==!1&&(n.page.current()=="cardResults"?(n.errorMessage(null),n.gearsModal("hide"),n.page.licenseResults(),n.checkDailyPurchaseAmount()):(n.errorMessage(null),n.license.update({}),r(t.pop())));i==!0&&(n.gearsModal("show"),n.errorMessage(null))});n.wallet.privateKey.subscribe(function(t){t&&t.length>=0&&n.signatureComplete()&&n.purchase()});n.fundComplete.subscribe(function(t){t==!0&&(n.savedEmail()==!0&&n.emailSent()!=!0&&(i(),n.emailSent(!0)),setTimeout(function(){n.gearsModal("hide")},300))});n.savedEmail.subscribe(function(t){t==!0&&n.fundComplete()==!0&&n.emailSent()!=!0&&(i(),n.emailSent(!0))});n.page={current:ko.observable(),swipeCard:function(){n.page.current("swipeCard");t.push(n.page.current());n.cancelButton(!0)},cardResults:function(){n.page.current("cardResults");t.push(n.page.current());n.cancelButton(!0);n.licenseSwipeReady(!0)},licenseResults:function(){n.page.current("licenseResults");t.push(n.page.current());n.cancelButton(!0);n.licenseSwipeReady(!1)},tipInput:function(){n.page.current("tipInput");t.push(n.page.current());n.cancelButton(!1);n.headerShown(!1)},signature:function(){n.page.current("signature");t.push(n.page.current());n.cancelButton(!1);n.headerShown(!1);n.signaturePad=new SignaturePad(document.querySelector("#signaturePanel"),{onEnd:function(){n.signatureComplete(!0)}});var i=document.querySelector("#signaturePanel").getContext("2d");i.beginPath();i.moveTo(20,275);i.lineTo(620,275);i.stroke();n.fund()},receipt:function(){n.page.current("receipt");t.push(n.page.current());n.cancelButton(!1);n.headerShown(!1)},thanks:function(){n.email()&&n.saveEmail();n.page.current("thanks");t.push(n.page.current());n.cancelButton(!1);n.headerShown(!1)},scancode:function(){n.page.current("scancode");t.push(n.page.current());n.cancelButton(!1);n.headerShown(!0);n.scanCodeReady(!0);window.scrollTo(0,100);n.fundComplete()||n.gearsModal("show");$("#qrSpend").qrcode({size:150,text:n.wallet.privateKey(),eLevel:"H"})},refundComplete:function(){n.page.current("refundComplete");t.push(n.page.current());n.cancelButton(!1);n.headerShown(!0)},walletReceipt:function(){n.page.current("walletReceipt");t.push(n.page.current());n.cancelButton(!1);n.headerShown(!1)},complete:function(){n.page.current("complete");t.push(n.page.current());n.cancelButton(!1);n.headerShown(!0)}};n.cancel=function(){n.page.current(null);n.headerShown(!0);n.cancelButton(!1);n.reset()};n.toggleSideBar=function(){return n.sideBarShown(!n.sideBarShown()),!0};n.reset=function(){n.wallet.update({testNet:n.testNet,account_Id:n.account().id()});n.license.update({});n.paymentInstrument.update({});n.transaction.update({});n.email("");n.errorMessage(null);n.scannerDecoder.reset();n.signatureComplete(!1);n.purchaseComplete(!1);n.retryDueToError(!1);n.savedEmail(!1);n.emailSent(!1);t=[];var i=document.querySelector("#qrSpend").getContext("2d");i.clearRect(0,0,canvas.width,canvas.height)};n.load=function(t){n.container=t.container;n.testNet=t.network=="TestNet"?!0:!1;n.account(t.account);n.firstName(t.firstName);n.wallet.testNet=n.testNet;n.wallet.account_Id(n.account().id());n.validator.Init({container:t.container});n.scannerDecoder=PF.ScannerReaderDecoder({paymentInstrument:n.paymentInstrument,wallet:n.wallet,driversLicense:n.license,capsLockWarningCallback:function(t){t?n.errorMessage("Hey Wait! Your Caps Lock key is on. The scanner does not work with it on!"):n.errorMessage(null)},creditCardErrorCallback:function(){},driversLicenseParseErrorCallback:function(){n.scannerDecoder.reset();n.errorMessage("License scan did not complete correctly. Please scan again.")}});n.loadSettingsModal()};n.printBTCWallet=function(){var t="http://"+window.location.host+"/My/Print?pAddress="+n.wallet.privateKey()+"&balance="+n.wallet.balanceUSD();window.open(t);n.page.walletReceipt()};n.saveEmail=function(){var t={Item:n.license.toServerModel(),Email:n.email()};$.ajax({type:"POST",url:"/Api/Bitcoin/AssociateEmailtoLicense",data:JSON.stringify(t),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){t.Success==!1&&n.errorMessage(t.Error)}});n.savedEmail(!0)};i=function(){var t={Mail:n.email(),Acct:n.account().toServerModel(),Ammt:n.transaction.amountUSDTransferred(),Trans:n.transaction.toServerModel(),Last:n.paymentInstrument.lastFour()};$.ajax({url:"/Api/Bitcoin/sendReceiptEmail",data:JSON.stringify(t),type:"POST",contentType:"application/json; charset=UTF-8"}).done(function(t){t.Success||n.error(t.Error)}).fail(function(t){t=JSON.parse(t.responseText);$(".alert").text(t.Error);n.error(t.responseText)})};n.checkDailyPurchaseAmount=function(){var t={DriversLicense:n.license.toServerModel(),Amount:n.transaction.amountUSDTransferred(),Currency:"USD"};$.ajax({type:"POST",url:"/Api/Bitcoin/CheckDailyPurchaseLimit",data:JSON.stringify(t),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){t.Success==!1&&n.errorMessage(t.Error)}})};n.purchase=function(){if(n.validator.Validate()){n.transaction.consumerWallet(n.wallet);n.transaction.fromWalletAddress(n.wallet.address());n.transaction.driversLicense(n.license);n.transaction.account_Id(n.account().id());var t={Item:n.transaction.toServerModel(),Email:n.email()};n.gearsModal("show");$.ajax({type:"POST",url:"/Api/Bitcoin/Purchase",data:JSON.stringify(t),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){n.gearsModal("hide");t.Success==!1?(n.errorMessage(t.Error),t.Retry==!0&&n.retryDueToError(!0)):(n.transaction.amountUSDTransferred(t.Item.AmountUSDTransferred),n.transaction.amountBTCTransferred(t.Item.AmountBTCTransferred),n.purchaseComplete(!0),n.page.complete())}})}else window.scrollTo(0,0)};n.printPurchaseReceipt=function(){if(n.purchaseComplete()){var t="http://"+window.location.host+"/My/Print?lastFour="+n.paymentInstrument.lastFour()+"&purchaseAmount="+n.transaction.amountUSDTransferred();t=t+"&btcAmount="+n.transaction.amountBTCTransferred()+"&balance=0";window.open(t);n.cancel()}else n.cancel()};n.fund=function(){var t,i;n.validator.Validate()?(n.fundComplete(!1),t=Bitcoin.ECPair.makeRandom(),t.network=n.testNet?Bitcoin.networks.testnet:Bitcoin.networks.Bitcoin,n.wallet.privateKey(t.toWIF()),n.wallet.address(t.getAddress().toString()),n.paymentInstrument.email(n.email()),i={Item:n.wallet.toServerModel(),PaymentInstrument:n.paymentInstrument.toServerModel(),DriversLicense:n.license.toServerModel(),Amount:n.transaction.amountUSDTransferred(),Currency:"USD"},$.ajax({type:"POST",url:"/Api/Bitcoin/FundWallet",data:JSON.stringify(i),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){t.Success==!1?n.errorMessage(t.Error):(n.fundComplete(!0),n.wallet.fromServerModel(t.Item))}})):window.scrollTo(0,0)};n.voidTransaction=function(){var t={Item:[{Id:n.wallet.fundingBillingId()}]};n.gearsModal("show");$.ajax({type:"POST",url:"/Api/Bitcoin/VoidCreditCardTransaction",data:JSON.stringify(t),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){n.gearsModal("hide");t.Success==!1?n.errorMessage(t.Error):(n.errorMessage(null),n.page.refundComplete())}})};n.gearsModal=function(t,i){var r=$("#modal-progress-gears");if(t=="hide"){if(r.find(".modal-body").is(":visible")){if(i&&typeof i=="function")r.on("hidden.bs.modal",function(){i.call()});r.modal("hide")}return}r.modal({keyboard:!1,backdrop:"static"});t!="show"||n.errorMessage()||r.modal("show")};n.loadSettingsModal=function(){var t=window.settingsModal=new BitcoinSettingsViewModel(n.printerIPAddress,$("#modal-bitcoinsettings"),null);ko.applyBindings(t,$("#modal-bitcoinsettings")[0]);t.load()};r=function(t){t=="swipeCard"?n.page.swipeCard():t=="cardResults"?n.page.cardResults():t=="licenseResults"?n.page.licenseResults():t=="tipInput"?n.page.tipInput():t=="signature"?n.page.signature():t=="receipt"?n.page.receipt():t=="scancode"?n.page.scancode():t=="refundComplete"?n.page.refundComplete():t=="walletReceipt"?n.page.walletReceipt():t=="complete"&&n.page.complete()}},POSPrintViewModel=function(n){var t=this;t.testNet=!0;t.wallet=new BitcoinWallet({testNet:t.testNet});t.license=new DriversLicense;t.email=ko.observable();t.fundSuccess=ko.observable(!1);t.purchaseSuccess=ko.observable(!1);t.showZipOrCvvError=ko.observable(!1);t.user=ko.observable();t.container=null;t.printerIPAddress=ko.observable(n.printerIP);t.product={scan:!1};t.transaction=new BitcoinTransaction;t.account=ko.observable();t.loaded=ko.observable(!1);t.load=function(){t.loaded(!0);t.getUrlParameter("purchaseAmount")?t.printPurchaseReceipt():t.printCoupon()};t.printCoupon=function(){tempWallet=new BitcoinWallet({privateKey:t.getUrlParameter("pAddress"),balanceUSD:t.getUrlParameter("balance")});tempWallet.printWalletCoupon(t.printerIPAddress(),null,function(){window.close()})};t.printPurchaseReceipt=function(){tempWallet=new BitcoinWallet;tempWallet.printPurchaseReceipt(t.getUrlParameter("lastFour"),t.getUrlParameter("purchaseAmount"),t.getUrlParameter("btcAmount"),t.getUrlParameter("balance"),t.printerIPAddress(),function(){window.close()})};t.getUrlParameter=function(n){for(var u=decodeURIComponent(window.location.search.substring(1)),r=u.split("&"),t,i=0;i<r.length;i++)if(t=r[i].split("="),t[0]===n)return t[1]===undefined?!0:t[1]}},ResourceCalendarViewModel=function(){var n=this;n.container=null;n.errorMessage=ko.observable();n.loaded=ko.observable(!1);n.title=ko.observable();n.datePicker=null;n.calendar=null;n.calendarViewType=ko.observable("agendaWeek");n.calendarTitle=ko.observable();n.currentCalendarDate=ko.observable();n.currentEvents=ko.observableArray();n.selectedResourceId=ko.observable();n.selectedResource=ko.observable(new Resource);n.resources=ko.observableArray();n.eventTimer=null;n.filters=ko.observableArray(["external","pos","Unavailable"]);n.unavailModalViewModel=null;n.calendarViewType.subscribe(function(t){n.calendarIsSetup()&&n.calendar.fullCalendar("changeView",t);n.updateCalendarTitle()});n.filters.subscribe(function(){n.calendar.fullCalendar("removeEvents");$.each(n.currentEvents(),function(){n.addEvent(this)})});n.currentCalendarDate.subscribe(function(t){if(n.calendarIsSetup()&&n.calendar.fullCalendar("getDate").getTime()!=t.getTime()){n.calendar.fullCalendar("gotoDate",t);return}n.datePicker.datepicker("setValue",t);n.updateCalendarTitle();n.getEventData()});n.selectedResource.subscribe(function(){n.calendarIsSetup()&&n.getEventData()});n.calendarIsSetup=function(){return n.calendar!=null&&n.calendar.is(":visible")&&n.calendar.hasClass("fc")};n.load=function(t){if(t!=null&&(n.container=t.container),n.loaded()){n.setupCalendar();return}n.datePicker=n.container.find(".icon-calendar");n.calendar=n.container.find("#resourceCalendar");n.loadAccountResources();n.loaded(!0)};n.loadAccountResources=function(){$.ajax({url:"/my/account/getresources",type:"GET",contentType:"application/json; charset=UTF-8"}).done(function(t){if(t.Success){var i=t.Item.map(function(n){return(new Resource).fromServerModel(n)});n.resources(i);n.unavailModalViewModel==null&&(n.unavailModalViewModel=window.resourceUnavailModal=new ResourceUnavailabilityViewModel($("#modal-resourceunavail"),n.resources(),function(){n.getEventData()}),ko.applyBindings(n.unavailModalViewModel,$("#modal-resourceunavail")[0]));n.container.find("#resourceCalendarPicker").trigger("chosen:updated")}else n.error(t.Error)}).fail(function(t){t=JSON.parse(t.responseText);$(".alert").text(t.Error);n.error(t.responseText)})};n.updateCalendarTitle=function(){if(n.calendarIsSetup()){var t=n.calendar.fullCalendar("getView").title;n.calendarViewType()=="agendaWeek"&&t&&(t=[t.slice(0,t.length-5),",",t.slice(t.length-5)].join(""));n.calendarTitle(t)}};n.setupCalendar=function(){n.calendarIsSetup()||(n.calendar.fullCalendar({header:{left:"",center:"title",right:""},allDaySlot:!0,defaultView:n.calendarViewType(),editable:!0,selectable:!0,selectHelper:!0,height:PF.currentRes&&PF.currentRes.resolution!="small"&&PF.currentRes.resolution!="extrasmall"?640:1150,eventClick:function(t){n.calendarEventClick(t)},select:function(t,i){n.calendarSelect(t,i)},eventAfterRender:function(){},viewDisplay:function(){n.currentCalendarDate(n.calendar.fullCalendar("getDate"))}}),n.container.find(".fc-header").hide())};n.getEventData=function(){var t={Item:n.selectedResource()?n.selectedResource().id():"",StartDate:n.calendar.fullCalendar("getView").start,EndDate:n.calendar.fullCalendar("getView").end};$.ajax({url:"/My/Space/CalendarRangeResources",type:"POST",dataType:"json",data:JSON.stringify(t),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){n.calendar.fullCalendar("removeEvents");n.currentEvents.removeAll();t.Success?(t.BookingAvailabilities&&$.each(t.BookingAvailabilities,function(){n.createBookingAvailabilityEvent(this)}),t.Unavailabilities&&$.each(t.Unavailabilities,function(){n.createUnavailabilityEvent(this)})):PF.Modals.Generic.Show({title:"Load Event Failure",description:"Unable to load your calendar. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com",error:t.Error})})};n.calendarSelect=function(t,i){n.unavailModalViewModel.addUnavailability(n.calendar,t,i,n.selectedResource()?n.selectedResource().id():"")};n.calendarEventClick=function(t){(t.type=="pos"||t.type=="external")&&(t.multiBooking?PF.Modals.ViewGroupedBookings.Show({event:t,curView:n.calendar.fullCalendar("getView")}):PF.Modals.My_OpenBooking.Show({event:t,curView:n.calendar.fullCalendar("getView")}));t.type=="Unavailable"&&n.unavailModalViewModel.editUnavailability(n.calendar,t)};n.datePickerChange=function(t,i){n.datePicker.datepicker("hide");n.currentCalendarDate(i.date)};n.addEvent=function(t){t.allDay=!1;t.editable=!1;t.className=t.type;switch(t.type){case"availability":if(n.filters.indexOf("availability")==-1)return;t.color="#5BAD27";t.textColor="#000";t.title="Available for booking";break;case"external":if(n.filters.indexOf("external")==-1)return;t.color="#F99D31";t.textColor="#000";t.title=t.Description||"Booking";break;case"pos":if(n.filters.indexOf("pos")==-1)return;t.color="#62bcd9";t.textColor="#000";t.title=t.Description||"POS Booking";break;case"Unavailable":if(n.filters.indexOf("Unavailable")==-1)return;t.color="#cccccc";t.textColor="#000";t.title=t.Description||"Unavailable"}n.calendar.fullCalendar("renderEvent",t)};n.blockOffTime=function(){};n.createBookingAvailabilityEvent=function(t){var r="",f,i;if(typeof t.Bookings[0]=="undefined")return null;switch(t.Bookings[0].CalendarType.CalendarTypeName){case"Booking":r="external";break;case"Private Booking":r="external";break;case"Internal Booking":r="pos"}t.EndTime=="23:29"&&(t.EndTime="23:30");var e=[],o=null,u={};return $.each(t.Bookings,function(){$.each(this.Resources,function(){u[this.ResourceName]?u[this.ResourceName]+=this.QuantityPurchased:u[this.ResourceName]=this.QuantityPurchased})}),$.each(t.Bookings,function(){$.each(this.Resources,function(){this.ResourceName&&e.indexOf(this.ResourceName)==-1&&e.push(this.ResourceName+" ("+u[this.ResourceName]+")");n.selectedResource()&&this.Resource&&this.Resource.Id==n.selectedResource().id()&&(o=this.Resource)})}),f="",t.MultiBooking&&(f=t.Bookings.length+" Bookings\n"),$.each(e,function(){f+=this+"\n"}),i={type:r,fullDate:t.CalendarDate,start:PF.parseMVCDate(t.CalendarDate+" "+t.StartTime),end:PF.parseMVCDate(t.CalendarDate+" "+t.ActualEndTime),bookings:t.Bookings,multiBooking:t.MultiBooking,Description:f,SpaceName:o==null?"":o.Name},i!=null&&(n.currentEvents.push(i),n.addEvent(i)),i};n.createUnavailabilityEvent=function(t){var o="",f=null,u=null,e="Unavailable",i,r;return typeof t.SpaceAvailabilities[0]!="undefined"&&(o=t.SpaceAvailabilities[0].Description,f=t.SpaceAvailabilities[0].Resource_Id,qtyBlocked=t.SpaceAvailabilities[0].ResourceQuantityAffected,u=t.ResourceNames[0],e="Unavailable\n"+u+"\n"+qtyBlocked+" blocked off\n"),i=PF.parseMVCDate(t.CalendarDate+" "+t.ActualBlockEndTime),i.getHours()==23&&i.getMinutes()==59&&(i=new Date(i.getTime()+6e4)),r={type:"Unavailable",start:PF.parseMVCDate(t.CalendarDate+" "+t.ActualBlockStartTime),end:i,id:t.SpaceAvailability_Id,Description:e,IsGrouped:t.IsGroupedId!=null,IsGroupedId:t.IsGroupedId,ResourceId:f,ResourceName:u,ResourceQuantityAffected:t.SpaceAvailabilities[0].ResourceQuantityAffected,NoteOnUnavailability:t.Description,spaceId:t.IsGroupedId?null:t.SpaceAvailabilities[0].Space_Id},n.currentEvents.push(r),n.addEvent(r),r}},ResourceUnavailabilityViewModel=function(n,t,i){var r=this;r.callback=i;r.container=n;r.resources=ko.observableArray(t);r.calendar=null;r.unAvailability=ko.observable(new SpaceAvailability);r.selectedResource=ko.observable(new Resource);r.event=null;r.modalTitle=ko.observable("Set Time as Unavailable");r.datepicker=null;r.selectedAvailability=ko.observable();r.selectedResource.subscribe(function(n){n&&n.id()&&r.unAvailability()&&r.unAvailability().resource(n)});r.load=function(){};r.addUnavailability=function(n,t,i,u){r.calendar=n;r.selectedResource($.grep(r.resources(),function(n){return n.id()==u})[0]);r.calendar.fullCalendar("getView").name=="month"&&(t.setHours(9),i.setHours(17));var f=PF.Factory.Availability.createUnavailability({startDate:PF.formatDate(t),endDate:PF.formatDate(i),endTime:PF.formatTime(i),startTime:PF.formatTime(t),calendarType:PF.CalendarType.Unavailability,calendarTypeId:PF.CalendarType.Unavailability.Id,description:"",resource:r.selectedResource()});r.unAvailability(f);r.container.modal("show");r.container.find(".datepicker").datepicker();$("#resourcePicker").trigger("chosen:updated")};r.datePickerChange=function(n,t){r.container.find(".datepicker").datepicker("hide");var i=PF.formatDate(t.date);r.unAvailability().startDate(i);r.unAvailability().endDate(i)};r.edit=function(){r.selectedAvailability(r.unAvailability())};r.cancelAvailability=function(){r.selectedAvailability(null)};r.editUnavailability=function(n,t){r.calendar=n;r.selectedResource($.grep(r.resources(),function(n){return n.id()==t.ResourceId})[0]);var i=PF.Factory.Availability.createUnavailability({id:t.id,startDate:PF.formatDate(t.start),endDate:PF.formatDate(t.end),endTime:PF.formatTime(t.end),startTime:PF.formatTime(t.start),calendarType:PF.CalendarType.Unavailability,calendarTypeId:PF.CalendarType.Unavailability.Id,description:t.NoteOnUnavailability,resourceQuantityAffected:t.ResourceQuantityAffected,resource:r.selectedResource()});r.unAvailability(i);r.container.modal("show");r.container.find(".datepicker").datepicker();$("#resourcePicker").trigger("chosen:updated")};r.recenterCalendarIfRequired=function(){var n=new Date(r.unAvailability().startDate()),t=r.calendar.fullCalendar("getView");PF.betweenDates(t.start,t.end,n)||r.calendar.fullCalendar("gotoDate",n)};r.save=function(){if(r.validator=(new PF.FormValidator).Init({container:r.container}),r.validator.Validate()){r.recenterCalendarIfRequired();r.unAvailability().resourceId(r.unAvailability().resource().id());var n=r.unAvailability().toServerModel(),t={Item:[n],CalendarType:n.CalendarType};$.ajax({url:"/My/Space/EditAvailabilities/",type:"POST",data:JSON.stringify(t),dataType:"json",processData:!1,contentType:"application/json; charset=utf-8"}).success(function(){r.callback&&r.callback.call();r.container.modal("hide")})}};r.deleteUnavail=function(){r.unAvailability().isDeleted(!0);r.save()};r.cancel=function(){}},CalendarExportViewModel=function(n){var t=this;t.message=ko.observable();t.error=ko.observable();t.busy=ko.observable(!1);t.condensedName=ko.observable(n);t.computedCalendarScriptUrl=ko.computed(function(){return"/api/assets/js/"+t.condensedName()+"?view=calendar&printableCalendar=true"});t.sendAnalytics=function(n){pf_dataLayer.push({event:"sendVirtualPageview",vpv:"/my/listings/calendarExport?account="+t.condensedName()+"&format="+n})};t.exportPdf=function(){t.sendAnalytics("pdf");t.message("Saving. This could take a bit...");t.busy(!0);html2canvas(document.getElementsByClassName("pf-embedded-maxi-cal")[0],{allowTaint:!0,taintTest:!0,onrendered:function(n){n.toBlob(function(n){var i=new XMLHttpRequest;i.open("POST","/My/Listings/GetCalendarPdf",!0);i.onreadystatechange=function(){var r,n;i.readyState===4&&i.status===200&&(t.message(undefined),t.busy(!1),r=JSON.parse(i.response),r.Success?(n=document.createElement("a"),n.id="downloadImageLink",n.download="Calendar.pdf",n.href=r.Uri,document.body.appendChild(n),n.click(),document.getElementById("downloadImageLink").remove()):t.error(r.Error))};i.send(n)},"image/png")}})};t.exportPng=function(){t.sendAnalytics("image");t.message("Saving. This could take a bit...");t.busy(!0);html2canvas(document.getElementsByClassName("pf-embedded-maxi-cal")[0],{allowTaint:!0,taintTest:!0,onrendered:function(n){n.toBlob(function(n){var i=new XMLHttpRequest;i.open("POST","/My/Listings/GetCalendarPng",!0);i.onreadystatechange=function(){var r,n;i.readyState===4&&i.status===200&&(t.message(undefined),t.busy(!1),r=JSON.parse(i.response),r.Success?(n=document.createElement("a"),n.id="downloadImageLink",n.download="Calendar.png",n.href=r.Uri,document.body.appendChild(n),n.click(),document.getElementById("downloadImageLink").remove()):t.error(r.Error))};i.send(n)},"image/png")}})}};let CategoriesViewModel=function(n,t){var i=this;i.validator=null;i.busy=ko.observable(!1);i.container=t;i.account=ko.observable((new Account).fromServerModel(n));i.viewTabName="view";i.createTabName="create";i.currentArea=ko.observable(i.viewTabName);i.categorySettingsTabName="settings";i.categoryEditTabName="edit";i.createSubArea=ko.observable(i.categorySettingsTabName);i.showAdvancedGroupSettings=ko.observable(!1);i.successMessage=ko.observable();i.errorMessage=ko.observable();i.messageTimeout=null;i.editableListingCategory=ko.observable();i.listing_ids=ko.observableArray();i.pager=ko.observable(new AsyncPagedListViewModel([],[],null));i.searchPager=ko.observable(new AsyncPagedListViewModel([],[],null));i.globalSearchBox=ko.observable();i.allListingForThisAccount=ko.observable();i.listingDropdownOptions=ko.observable();i.allSpaceListing=ko.observable();i.allGiftCardListing=ko.observable();i.allGoodListing=ko.observable();i.load=function(n){i.getAllListing();i.getAccountListingCategories(n);$('[data-toggle="tooltip"]').tooltip()};i.getAccountListingCategories=function(n){i.pager(new AsyncPagedListViewModel([],[n.groupNameFilter,n.groupListingFilter],function(n){i.getListingCategories(n)},{}));i.pager().load()};i.getListingCategories=function(n){i.busy(!0);$.ajax({url:"/My/ListingCategories/GetListingCategoriesForCategoriesPage",type:"POST",dataType:"JSON",data:JSON.stringify({PageSize:i.pager().pageSize(),Page:i.pager().pageIndex()+1,SearchText:i.pager().findFilter("text").value(),ListingId:i.pager().findFilter("listingId").value()}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(t){i.busy(!1);t.Success?n&&n(t,ListingCategory):PF.Modals.Generic.Show({title:"Error Loading Listing Categories",description:"An error occurred while loading your categories. Please try again or contact support@placefull.com.<br/><br/>Inquiring minds might find this helpful: "+t.Error})})};i.viewListingCategoryClick=function(){i.currentArea(i.viewTabName);i.createSubArea(i.categorySettingsTabName)};i.createListingCategoryClick=function(){i.editableListingCategory(new ListingCategory({isVisibleToUser:!0}));i.editableListingCategory().account((new Account).fromServerModel(i.account().toServerModel()));i.currentArea(i.createTabName);i.listing_ids.removeAll();$("#listingPick").trigger("change");$('[data-toggle="tooltip"]').tooltip()};i.viewSettingsClick=function(){i.createSubArea(i.categorySettingsTabName)};i.clearSuccessMessage=function(){i.successMessage("")};i.clearErrorMessage=function(){i.errorMessage("")};i.editListingCategory=function(n){i.editableListingCategory(n);i.listing_ids(i.editableListingCategory().listings().map(function(n){return n.id()}));$("#listingPick").trigger("change");i.currentArea(i.createTabName)};i.deleteListingCategoryConfirm=function(n){i.editableListingCategory(n);i.listing_ids(i.editableListingCategory().listings().map(function(n){return n.id()}));$("#listingPick").trigger("change");PF.Modals.Generic.Show({title:"Delete Group Confirm",description:"Are you sure you wish to delete this category? It will be removed from your website, if currently published.",labels:{confirm:"Yes",close:"No"},confirm:function(){i.busy()===!1&&(i.busy(!0),i.clearErrorMessage(),$.ajax({url:"/My/ListingCategories/DeleteListingCategory",type:"POST",dataType:"JSON",data:JSON.stringify({Item:[i.editableListingCategory().toServerModel()]}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(n){i.busy(!1);n.Success?(i.currentArea(i.viewTabName),i.getAccountListingCategories({groupNameFilter:groupNameFilter,groupListingFilter:groupListingFilter})):i.editErrorMessage("We were unable to delete your Listing Category. Please try again or contact support@placefull.com. "+(n.Error?"Inquiring minds might find this helpful: "+n.Error:""))}))}})};i.saveListingCategory=function(){(i.validator=(new PF.FormValidator).Init({container:$(i.container)}),i.validator.Validate())&&(i.editableListingCategory().listings(i.listing_ids().map(function(n){return new Listing({id:n})})),i.busy(!0),i.clearErrorMessage(),$.ajax({url:"/My/ListingCategories/SaveListingCategory",type:"POST",dataType:"JSON",data:JSON.stringify({Item:[i.editableListingCategory().toServerModel()]}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(n){i.busy(!1);n.Success?(i.editSuccessMessage("Successfully saved your Listing Category"),i.currentArea(i.viewTabName),i.getAccountListingCategories({groupNameFilter:groupNameFilter,groupListingFilter:groupListingFilter})):i.editErrorMessage("We were unable to save your Listing Category. Please try again or contact support@placefull.com. "+(n.Error?"Inquiring minds might find this helpful: "+n.Error:""))}))};i.cancelListingCategory=function(){i.getAccountListingCategories({groupNameFilter:groupNameFilter,groupListingFilter:groupListingFilter});i.currentArea(i.viewTabName)};i.editSuccessMessage=function(n){i.successMessage(n);i.messageTimeout=setTimeout(i.clearSuccessMessage,1e4)};i.editErrorMessage=function(n){i.errorMessage(n)};i.getAllListing=function(){i.busy(!0);$.ajax({url:"/My/ListingCategories/GetAllListingForCategoriesPage",type:"POST",dataType:"JSON",data:JSON.stringify({}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(n){i.busy(!1);n.Success?(i.allListingForThisAccount(n.Item),i.listingDropdownOptions(n.Item.map(n=>({text:n.Name,value:n.Id}))),i.allSpaceListing(n.Item.filter(n=>n.ListingType===PF.ListingType.Space)),i.allGiftCardListing(n.Item.filter(n=>n.ListingType===PF.ListingType.GiftCard)),i.allGoodListing(n.Item.filter(n=>n.ListingType===PF.ListingType.Good))):PF.Modals.Generic.Show({title:"Error Loading Listing Categories",description:"An error occurred while loading your categories. Please try again or contact support@placefull.com.<br/><br/>Inquiring minds might find this helpful: "+n.Error})})}};EditListingViewModel=function(){var n=this,i={},t,r;ListingDetailViewModel.apply(n);n.dirtyRates=ko.observable(!1);n.dirtyPromoCodeGroups=ko.observable(!1);n.busy=ko.observable(!1);n.editableListing=ko.observable();n.categories=ko.observableArray();n.eventTypes=ko.observableArray();n.editableImage=ko.observable();n.editedImages=ko.observableArray([]);n.editedAvailabilities=ko.observableArray([]);n.selectedAvailability=ko.observable();n.editedSpecialRates=ko.observableArray([]);n.selectedSpecialRate=ko.observable();n.editingDefaultRate=ko.observable(!1);n.editedPromoCodeGroups=ko.observableArray([]);n.selectedPromoCodeGroup=ko.observable();n.allSpaces=ko.observableArray();n.pricingValidator=new PF.FormValidator;n.pricingValidationError=ko.observable();n.availValidationError=ko.observable();n.increasePackageQtyError=ko.observable();n.selectedDepositTimeTable=ko.observable();n.initialDepositTimeTable=ko.computed(function(){if(n.editableListing()){if(n.editableListing().computedInitialDeposit())return n.editableListing().computedInitialDeposit();var t=new SpaceDepositTimeTable;return t.isInitialDeposit(!0),t}return null});n.finalDepositTimeTable=ko.computed(function(){if(n.editableListing()){if(n.editableListing().computedFinalDeposit())return n.editableListing().computedFinalDeposit();var t=new SpaceDepositTimeTable;return t.isFinalDeposit(!0),t}return null});n.depositChargeMode=ko.computed({read:function(){return n.initialDepositTimeTable()?n.initialDepositTimeTable().chargeMode():0},write:function(t){n.initialDepositTimeTable()&&n.initialDepositTimeTable().chargeMode(t);n.finalDepositTimeTable()&&n.finalDepositTimeTable().chargeMode(t)}});n.timeBeforeViewDropdown=ko.observable(0);n.timeBeforeViewValue=ko.computed({read:function(){return n.finalDepositTimeTable()&&n.finalDepositTimeTable().minutesBeforeToChargeCustomer()!=null?n.finalDepositTimeTable().minutesBeforeToChargeCustomer()*(1/(n.timeBeforeViewDropdown()===0?60:1440)):null},write:function(t){t=t.trim()===""?null:Number(t);t!=null?n.finalDepositTimeTable().minutesBeforeToChargeCustomer(t*(n.timeBeforeViewDropdown()===0?60:1440)):n.finalDepositTimeTable().minutesBeforeToChargeCustomer(null)}});n._viewEditListingResourcesLink=ko.observable();n._viewEditListingResourcesEdit=ko.observable();n._viewEditListingAdditionalInfo=ko.observable();n._viewEditListingAddOns=ko.observable();n._viewEditGeneral=ko.observable();n.error=function(n){console.log("[ERROR] "+n)};i.load=n.load;n.load=function(t,r,u,f){i.load(f,t,r);$.each(u.categories,function(t,i){if(i.Id===n.listing().spaceCategoryId())return n.categories(i.SpaceTypes),!1});n.eventTypes(u.eventTypes);n.isCanada=u.isCanada};n.book=function(){};n.bookReferral=function(){};n.defaultRateName=ko.computed({read:function(){return n.editableListing()&&n.editableListing().defaultRate()?n.editableListing().defaultRate().name()=="Default"?"Price":n.editableListing().defaultRate().name():null},write:function(t){t?n.editableListing().defaultRate().name(t):n.editableListing().defaultRate().name("Default")},owner:this});t=function(n){for(let t=0;t<n.length;t++){const i=n[t],r=i.fileUrl()+"?v="+(new Date).getTime();i.fileUrlWithTime=ko.observable();i.fileUrlWithTime(r)}};n.thumbnailImageGroups=ko.computed(function(){var f=[],r=[],i,u;if(f.push(r),n.listing().images())for(i=0;i<n.listing().images().length;i+=1)u=n.listing().images()[i].thumbnails(),u&&u.length&&t(u),r.push(n.listing().images()[i]),(i+1)%6==0&&(r=[],f.push(r));return f},n,{deferEvaluation:!0});n.sortedAvailabilities=ko.computed(function(){var t=n.editableListing().availabilities();return t=$.grep(t,function(n){return!n.calendarType()||n.calendarType().CalendarTypeName===PF.CalendarType.Availability.CalendarTypeName||n.calendarType().CalendarTypeName===PF.CalendarType.Referral.CalendarTypeName||n.calendarType().CalendarTypeName===PF.CalendarType.MultiDayAvailability.CalendarTypeName}),t.sort(function(n,t){if(n.startDate&&t.startDate){var i=new Date(n.startDate()),r=new Date(t.startDate());return i<r?-1:i>r?1:0}return 0}),t},n,{deferEvaluation:!0});n.initToolTips=function(){var n=$("i[data-toggle=tooltip]");$("i[data-toggle=tooltip]").tooltip({trigger:"click"})};r=function(t){$.each(t,function(t,i){i.calendarTypeId()==PF.CalendarType.MultiDayAvailability.Id&&(i.calendarTypeId(PF.CalendarType.Availability.Id),i.calendarType({AffectsAvailability:1,CalendarTypeName:PF.CalendarType.Availability.CalendarTypeName,Id:PF.CalendarType.Availability.Id}),n.editedAvailabilities().some(n=>n.id()==i.id())||n.editedAvailabilities.push(i))})};const f=function(n){return $.ajax({url:"/my/listings/save",type:"POST",dataType:"json",data:JSON.stringify(n),processData:!1,contentType:"application/json; charset=utf-8"})};i.save=n.save;n.save=function(){if(PF.detectKnownBadTagsInString(n.editableListing().description())){PF.Modals.Generic.Show({title:"Error Saving Listing",description:"There are some invalid tags in your description. We do not allow you to put the following tags in your description:<br/><br/>&#060;script&#062;, &#060;embed&#062;, &#060;object&#062;, &lt;video&gt;, &lt;applet&gt;, &lt;frame&gt;, &lt;frameset&gt;<br/><br/>For iFrames, we only allow source content from YouTube and Vimeo.<br/><br/>We also do not allow any non-HTTPS content.<br/><br/>Please remove the offending content and try again. Your listing changes have NOT been saved!<br/>If you need assistance, please contact support@placefull.com"});return}n.editableListing().defaultRate().rateTypeId()==PF.RateType.Hourly&&r(n.editedAvailabilities());n.listing().fromServerModel(n.editableListing().toServerModel(!0));var i={listing:n.listing().toServerModel(!0)};const t=[];f(i).then(function(i){if(i){if(i.Success){if(n.listing().fromServerModel(i.Item),n.saveImages(n.editedImages()),t.push(n.saveAvailabilities(n.editedAvailabilities())),n.dirtyRates()){var r=[];r.push(n.editableListing().defaultRate());$.each(n.editableListing().specialRates(),function(n,t){r.push(t)});$.each(n.editedSpecialRates(),function(n,t){t.isDeleted()&&r.push(t)});$.each(n.editableListing().promoRates(),function(n,t){r.push(t)});n.editableListing().cleaningRate()&&r.push(n.editableListing().cleaningRate());n.editableListing().securityRate()&&r.push(n.editableListing().securityRate());t.push(n.saveRates(r))}t.push(n.saveDepositTimeTable());t.push(n.savePromoCodeGroups());n._viewEditListingAdditionalInfo()&&n._viewEditListingAdditionalInfo().dirty()&&t.push(n.saveAdditionalInfo(n._viewEditListingAdditionalInfo().selectedInfo()));Promise.all(t).then(function(){n.bindMap();const t=new Date,i=new Date(t.getFullYear(),t.getMonth(),1);n.firstDate(i);n.refresh()})}}else return n.error(i.Error),!1})};n.saveDepositTimeTable=function(){if(n.editableListing().depositTimeTable()||n.editableListing().depositTimeTable([]),n.editableListing().hasDepositPricing()){if(n.editableListing().depositTimeTable().length<2){if(n.editableListing().depositTimeTable.removeAll(),!n.initialDepositTimeTable().amountToCharge()){PF.showError("Deposit pricing is enabled but no amount was input, pleace check the deposit inputs");return}n.editableListing().depositTimeTable.push(n.initialDepositTimeTable());n.editableListing().depositTimeTable.push(n.finalDepositTimeTable())}}else n.editableListing().depositTimeTable.removeAll();var t={Space_Id:n.listing().id(),Item:n.editableListing().depositTimeTable().map(function(n){return n.toServerModel()})};return $.ajax({type:"POST",url:"/my/listings/savedeposittimetable",data:JSON.stringify(t),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){return t.Success?(n.listing().depositTimeTable.removeAll(),n.listing().depositTimeTable($.map(t.Item,function(n){return(new SpaceDepositTimeTable).fromServerModel(n)})),!0):(PF.showError(t.Error),!1)}})};n.savePricing=function(t){var i=!0,r=n.rentalDurationMode()=="hours"?n.rentalDuration()*60:n.rentalDuration();return($.each(n.sortedAvailabilities(),function(t,u){r>u.duration()&&(n.editedAvailabilities.remove(u),i=!1)}),!i)?(n.availValidationError("Your minimum rental duration of "+n.rentalDuration()+" "+n.rentalDurationMode()+" is too long compared to one or more of your open available times!"),!1):n.saveAvailability(n.selectedAvailability())==!1?!1:parseInt(n.editableListing().packageQuantity())<parseInt(n.editableListing().defaultRate().availabilityQtyUsed())?(n.pricingValidationError("You do not have enough spots available per timeslot to use "+n.editableListing().defaultRate().availabilityQtyUsed()+" spots per booking"),!1):(n.pricingValidator=new PF.FormValidator,n.pricingValidator.Init({container:$("#modal-edit-availability")}),n.pricingValidator.Validate()?(n.pricingValidationError(null),n.availValidationError(null),n.selectedSpecialRate(null),t||n.save(),!0):(n.pricingValidationError("Oops!  Looks like you forgot something."),!1))};n.saveImages=function(t){t&&$.each(t,function(t,i){var r={Item:i.toServerModel(!0)};$.ajax({url:"/my/listings/saveimage",type:"POST",dataType:"json",data:JSON.stringify(r),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(t)return t.Success?!0:(n.error(t.Error),!1)})})};n.saveTerms=function(){var t={Item:n.editableListing().terms().toServerModel(),Space_Id:n.editableListing().id()};n.editableListing().terms().deleted()&&(t.DeleteTermsPDF=!0);$.ajax({type:"POST",url:"/my/listings/saveterms",data:JSON.stringify(t),contentType:"application/json; charset=utf-8",dataType:"json",success:function(t){t.Success?(n.editableListing().terms((new Terms).fromServerModel(t.Item)),n.save()):PF.showError(t.Error)}})};n.saveAvailabilities=function(t){if(t&&t.length>0){var i={Id:n.listing().id(),Item:t.map(function(n){return n.toServerModel(!0)})};return $.ajax({url:"/my/listings/saveavailabilities",async:!0,type:"POST",dataType:"json",data:JSON.stringify(i),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(t){if(t.Success){var i=t.Item.map(function(n){return(new SpaceAvailability).fromServerModel(n)});return n.listing().availabilities(i),!0}return n.error(t.Error),!1}})}};n.saveRates=function(t){if(t&&t.length>0){var i={Id:n.listing().id(),Item:t.map(function(n){return n.toServerModel(!0)})};return $.ajax({url:"/my/listings/saverates",async:!0,type:"POST",dataType:"json",data:JSON.stringify(i),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){var i,r;if(t)return t.Success?(i=t.Item.SpecialRates.map(function(n){return(new RentalRate).fromServerModel(n)}),n.listing().specialRates(i),r=t.Item.PromotionRates.map(function(n){return(new RentalRate).fromServerModel(n)}),n.listing().promoRates(r),t.Item.CleaningRate&&n.listing().cleaningRate((new RentalRate).fromServerModel(t.Item.CleaningRate)),t.Item.SecurityRate&&n.listing().securityRate((new RentalRate).fromServerModel(t.Item.SecurityRate)),t.Item.DefaultRate&&n.listing().defaultRate((new RentalRate).fromServerModel(t.Item.DefaultRate)),t.Item.MinimumRentalFee&&n.listing().minRentalFee(t.Item.MinimumRentalFee),!0):(n.error(t.Error),!1)})}};n.saveAdditionalInfo=function(t){var i={Space_Id:n.listing().id(),Item:t.map(function(n){return n.toServerModel(!0)})};return $.ajax({url:"/my/listings/saveadditionalinfo",async:!0,type:"POST",dataType:"json",data:JSON.stringify(i),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(t)return t.Success?!0:(n.error(t.Error),!1)})};n.saveAddOns=function(){if(!n._viewEditListingAddOns()||n._viewEditListingAddOns().dirty()){var t={Space_Id:n.listing().id(),Item:n._viewEditListingAddOns().selectedAddOns().map(function(n){return n.toServerModel(!0)})};$.ajax({url:"/my/listings/saveaddons",type:"POST",dataType:"json",data:JSON.stringify(t),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(t)return t.Success?(n.refresh(),!0):(n.error(t.Error),!1)})}};n.createEditableListing=function(){var i=n.listing().clone(),r=i.images(),u;return r&&r.length&&$.each(r,function(n,i){var r=i.thumbnails();r&&r.length&&t(r)}),n.editableListing(i),u=n.editableListing().specialRates().sort(function(n,t){return n.maxAvailabilityQty()>t.maxAvailabilityQty()?1:-1}),n.editableListing().specialRates(u),n.editableListing().packageQuantity.subscribe(function(){n.editableListing().defaultRate().rateTypeId()==PF.RateType.PerPerson&&(n.editableListing().defaultRate().initialMaxAvailabilityQty(n.editableListing().packageQuantity()),n.editableListing().defaultRate().availabilityQtyUsed(n.editableListing().packageQuantity()),$.each(n.editableListing().specialRates(),function(t,i){i.initialMaxAvailabilityQty(n.editableListing().packageQuantity())}))}),i};const e=$("<button/>").addClass("btn button-singlefileupload").prop("disabled",!0).text("Processing...").on("click",function(){}),u=function(){$("#modal-edit-images .file-upload input[type=file]").fileupload({url:"/Handlers/Upload.ashx",dataType:"json",autoUpload:!0,acceptFileTypes:/(\.|\/)(gif|jpe?g|png)$/i,maxFileSize:5e7,disableImageResize:/Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),previewMaxWidth:80,previewMaxHeight:80,previewCrop:!0,sequentialUploads:!0,formData:{spaceid:n.editableListing().id(),spacecondensedname:n.editableListing().condensedName(),filetype:"image"}}).on("fileuploadadd",function(n,t){var r=this,i=$(this).data("blueimp-fileupload"),u;i.pf=i.pf||{queue:0,active:0};$(this).closest(".drop").children(".instructions").hide();u=$(this).closest(".drop").children(".previews");$.each(t.files,function(n,f){var h=$('<div class="row-fluid files-row" />'),o,s;if(u.append(h),o=t.context=$('<div class="file-container"/>').appendTo(h),o.append('<div class="preview" />'),o.append($('<div class="title" />').text(f.name)),o.append($("<small/>").text("("+Math.round(f.size*.000976562)+" KB)")),o.append('<div class="progress hide"><div class="bar bar-success"><\/div><\/div>'),n||o.append("<br>").append(e.clone(!0).data(t)),i.pf.queue++,i.pf.active++,i.pf.active>0&&(s=$(r).closest(".drop").children(".uploadall-button"),s.removeClass("hide"),!s.data("pf-uploadalleventattached"))){s.data("pf-uploadalleventattached",!0);s.on("click",function(){$(".button-singlefileupload",$(r).closest(".drop")).click();s.data("pf-uploadalleventattached",!1)})}})}).on("fileuploadprocessalways",function(n,t){var r=t.index,i=t.files[r],f=$(t.context.children()[r]),u=t.context;i.preview&&$(".preview",u).append(i.preview);i.error&&u.append("<br>").append($('<span class="text-danger"/>').text(i.error));r+1===t.files.length&&u.find("button").prop("disabled",!!t.files.error)}).on("fileuploadprogress",function(n,t){$(".progress",$(t.context)).removeClass("hide");var i=parseInt(t.loaded/t.total*100,10);$(".progress .bar",$(t.context)).css("width",i+"%")}).on("fileuploaddone",function(i,r){var f,u,e;if(r&&r.result&&r.result.Success&&r.result.Item&&r.result.Item.length>0){$(".button-singlefileupload",r.context).hide();$(".progress",r.context).hide();$(r.context).append('<i class="fa fa-check-circle fa-2x pf-upload-success"><\/i>');f=r.result.Item.map(function(n){return(new SpaceImage).fromServerModel(n)});n.editableListing().images()||n.editableListing().images([]);for(let i=0;i<f.length;i++){const r=f[i];u=r.thumbnails();u&&u.length&&t(u);n.editableListing().images.push(r)}e=$(this).data("blueimp-fileupload");e.pf.active--;e.pf.active<=0&&($(this).closest(".drop").children(".uploadall-button").addClass("hide"),$(this).closest(".drop").children(".previews").empty(),$(this).closest(".drop").children(".instructions").removeClass("hide").show())}}).on("fileuploadfail",function(n,t){$.each(t.files,function(n){var i=$('<span class="text-danger"/>').text("File upload failed.");$(t.context.children()[n]).append("<br>").append(i)})}).prop("disabled",!$.support.fileInput).parent().addClass($.support.fileInput?undefined:"disabled")};n.editImages=function(){n.createEditableListing();n.editedImages([]);u()};n.editImage=function(t){n.editableImage(t);n.editedImages.push(t);t.isDefault.subscribe(function(i){if(i){var r=$.grep(n.editableListing().images(),function(n){return n.isDefault()&&n.id()!==t.id()});r&&r.length>0&&$.each(r,function(n,t){t.isDefault(!1)})}})};n.deleteImage=function(t){confirm("Permanently delete this image?")&&PF.DataProxy.EditImage({data:{Space_Id:n.editableListing().id(),Item:{Id:t.id(),IsDeleted:!0}},success:function(){var i=n.editableListing().images();$.each(i,function(i,r){r&&r.id()===t.id()&&n.editableListing().images.remove(r)});$.each(n.listing().images(),function(i,r){r&&r.id()===t.id()&&n.listing().images.remove(r)})}})};n.deleteAddOnImage=function(t){confirm("Permanently delete this image?")&&(t.isDeleted(!0),$.ajax({url:"/my/listings/saveaddonimage",type:"POST",dataType:"json",data:JSON.stringify({item:t.toServerModel()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(i){if(i)if(i.Success){var r=n._viewEditListingAddOns().selected().addOn().images();$.each(r,function(i,r){r&&r.id()===t.id()&&n._viewEditListingAddOns().selected().addOn().images.remove(r)});n._viewEditListingAddOns().editAddOnImages()}else return n.error(i.Error),!1;return!1}))};n.editDescription=function(){n.createEditableListing()};n.selectedSpaceEventTypes=ko.observableArray();n.editFastFacts=function(){var t=n.createEditableListing();n.selectedSpaceEventTypes($.map(t.spaceEventTypes(),function(n){return n.Id}));n.selectedSpaceEventTypes.subscribe(function(){t.spaceEventTypes($.map(n.selectedSpaceEventTypes(),function(n){return{Id:n}}))})};n.selectedSpaceEventTypeNames=ko.computed(function(){var t=[];return $.each(n.listing().spaceEventTypes(),function(i,r){var u=$.grep(n.eventTypes(),function(n){return n.Id===r.Id});u.length===1&&t.push(u[0].EventTypeName)}),t},n,{deferEvaluation:!0});n.selectedSpaceTypeName=ko.computed(function(){var t=$.grep(n.categories(),function(t){return t.Id==n.listing().spaceTypeId()});return t.length>0?t[0].Name:""},n,{deferEvaluation:!0});n.applyBindingsToTermsFileUpload=function(){var t=$("<button/>").addClass("btn btn-block btn-large button-singlefileupload").prop("disabled",!0).text("Processing...").on("click",function(){var n=$(this),t=n.data();n.off("click").text("Cancel").on("click",function(){n.remove();t.abort()});t.submit().always(function(){n.remove()})});$("#modal-edit-terms .file-upload input[type=file]").fileupload({url:"/Handlers/Upload.ashx",dataType:"json",autoUpload:!0,acceptFileTypes:/(\.|\/)(pdf)$/i,maxFileSize:5e7,sequentialUploads:!0,formData:{spaceid:n.editableListing().id(),filetype:"terms"}}).on("fileuploadadd",function(n,i){var f=this,r=$(this).data("blueimp-fileupload"),u;r.pf=r.pf||{queue:0,active:0};$(this).closest(".drop").children(".instructions").hide();u=$(this).closest(".drop").children(".previews");$.each(i.files,function(n,f){var o=$(".files-row:last-child",u),e;r.pf.queue%1==0&&(o=$('<div class="row-fluid files-row" />'),u.append(o));e=i.context=$('<div class="span12 file-container"/>').appendTo(o);e.append('<div class="preview pdf" />');e.append($('<div class="title" />').text(f.name));e.append("<div/>").append($("<small/>").text("("+Math.round(f.size*.000976562)+" KB)"));e.append('<div class="progress hide"><div class="bar bar-success"><\/div><\/div>');n||e.append("<br>").append(t.clone(!0).data(i));r.pf.queue++})}).on("fileuploadprocessalways",function(n,t){var r=t.index,i=t.files[r],f=$(t.context.children()[r]),u=t.context;i.preview&&$(".preview",u).append(i.preview);i.error&&u.append("<br>").append($('<span class="text-danger"/>').text(i.error));r+1===t.files.length&&u.find("button").text("Upload").prop("disabled",!!t.files.error)}).on("fileuploadprogress",function(n,t){$(".progress",$(t.context)).removeClass("hide");var i=parseInt(t.loaded/t.total*100,10);$(".progress .bar",$(t.context)).css("width",i+"%")}).on("fileuploaddone",function(t,i){i&&i.result&&i.result.Success&&i.result.Item&&($(".progress",i.context).hide(),$(i.context).append('<div class="text-success"><i class="fa fa-check fa-3x"><\/i><\/div>'),n.editableListing().terms((new Terms).fromServerModel(i.result.Item)),$("#section-terms-upload").collapse("hide"),$(i.context).remove())}).on("fileuploadfail",function(n,t){$.each(t.files,function(n){var i=$('<span class="text-danger"/>').text("File upload failed.");$(t.context.children()[n]).append("<br>").append(i)})}).prop("disabled",!$.support.fileInput).parent().addClass($.support.fileInput?undefined:"disabled")};n.editTerms=function(){var t=n.createEditableListing();t.terms()||t.terms(new Terms);n.applyBindingsToTermsFileUpload()};n.editPricing=function(){n.createEditableListing();n._viewEditListingAdditionalInfo(new EditListingAdditionalInfoViewModel(n.editableListing()));n.editedAvailabilities([]);n.dirtyRates(!1);n.initToolTips();n.editableListing().defaultRate().rate.subscribe(function(){n.dirtyRates(!0)});n.editableListing().defaultRate().rateTypeId.subscribe(function(){n.switchRateType()});n.editableListing().defaultRate().name.subscribe(function(){n.dirtyRates(!0)});n.editableListing().defaultRate().availabilityQtyUsed.subscribe(function(){n.dirtyRates(!0)});n.pricingValidator=new PF.FormValidator;n.pricingValidator.Init({container:$("#modal-edit-availability")})};n.switchRateType=function(){n.dirtyRates(!0);$.each(n.editableListing().specialRates(),function(t,i){i.rateTypeId(n.editableListing().defaultRate().rateTypeId());i.initialMaxAvailabilityQty(null);i.initialMinAvailabilityQty(null)});n.editableListing().defaultRate().initialMaxAvailabilityQty(null);n.editableListing().defaultRate().initialMinAvailabilityQty(null);switch(n.editableListing().defaultRate().rateTypeId()){case PF.RateType.Hourly:n.editableListing().defaultRate().availabilityQtyUsed(1);n.editableListing().packageQuantity(1);$.each(n.editableListing().specialRates(),function(n,t){t.availabilityQtyUsed(1)});r(n.editableListing().availabilities());break;case PF.RateType.PerPerson:n.editableListing().defaultRate().initialMaxAvailabilityQty(n.editableListing().packageQuantity());n.editableListing().defaultRate().initialMinAvailabilityQty(1);$.each(n.editableListing().specialRates(),function(t,i){i.initialMinAvailabilityQty(1);i.initialMaxAvailabilityQty(n.editableListing().packageQuantity())})}n.editableListing().defaultRate().commit();$.each(n.editableListing().specialRates(),function(n,t){t.commit()});n.pricingValidator=new PF.FormValidator;n.pricingValidator.Init({container:$("#modal-edit-availability")})};n.editAddons=function(){n.createEditableListing();n._viewEditListingAddOns(new EditListingAddOnsViewModel(n.editableListing()));n.initToolTips()};n.editResources=function(){n.createEditableListing();n._viewEditListingResourcesLink(new EditListingResourcesLinkViewModel(n.editableListing(),n));n._viewEditListingResourcesEdit(new EditListingResourcesEditViewModel(n.editableListing(),n));n.initToolTips()};n.editGeneral=function(){n.createEditableListing();n._viewEditGeneral(new EditListingGeneralViewModel(n.editableListing(),n));n.initToolTips()};n.rentalDurationMode=ko.observable("mins");n.rentalDuration=ko.computed({read:function(){if(n.editableListing()){var t=n.editableListing().minRentalDuration();return n.rentalDurationMode()==="hours"&&(t=t/60),t}return null},write:function(t){n.editableListing()&&(n.rentalDurationMode()==="hours"&&(t=parseFloat(t)*60),n.editableListing().minRentalDuration(t))}},n,{deferEvaluation:!0});n.minNoticeMode=ko.observable("hours");n.minNotice=ko.computed({read:function(){if(n.editableListing()){var t=n.editableListing().minNotice();return n.minNoticeMode()==="days"&&(t=t/24),t||null}return null},write:function(t){n.editableListing()&&(n.minNoticeMode()==="days"&&(t=parseFloat(t)*24),n.editableListing().minNotice(t))}},n,{deferEvaluation:!0});n.rentalBufferMode=ko.observable("hours");n.rentalBuffer=ko.computed({read:function(){if(n.editableListing()){var t=n.editableListing().rentalBuffer();return t&&n.rentalBufferMode()==="hours"&&(t=t/60),t||null}return null},write:function(t){n.editableListing()&&(t&&n.rentalBufferMode()==="hours"&&(t=parseFloat(t)*60),n.editableListing().rentalBuffer(t))}},n,{deferEvaluation:!0});n.appointment=ko.computed({read:function(){return n.editableListing()&&n.editableListing().defaultRate().rateRule()?n.editableListing().defaultRate().rateRule().ruleName()==="DefaultAppointment":!1},write:function(t){t?n.editableListing().defaultRate().rateRule().ruleName("DefaultAppointment"):n.editableListing().defaultRate().rateRule().ruleName("Default");n.dirtyRates(!0)}});n.isGiftedListing=ko.computed({read:function(){return n.editableListing()!=null&&(n.editableListing().specialFlags()&PF.SpaceSpecialFlags.IsGiftedListing)==1},write:function(t){if(t!=null){var i=~PF.SpaceSpecialFlags.IsGiftedListing,r=n.editableListing().specialFlags()&i;n.editableListing().specialFlags(r|t);t===!0?(n.appointment(!0),n.editableListing()!=null&&(n.minNoticeMode("days"),n.minNotice(14))):n.editableListing().giftedPageUrl(null)}}});n.addAvailability=function(){var r=new Date,t=null,i;i=n.editableListing().isReferral()?PF.Factory.Availability.createReferral({spaceId:n.editableListing().id(),startDate:r.toLocaleDateString(),startTime:"9:00",endDate:t==null?"":t.toLocaleDateString(),endTime:"17:00",isDaily:!0}):PF.Factory.Availability.createAvailability({spaceId:n.editableListing().id(),startDate:r.toLocaleDateString(),startTime:"9:00",endDate:t==null?"":t.toLocaleDateString(),endTime:"17:00",isDaily:!0});n.editableListing().availabilities.push(i);n.selectedAvailability(i);n.initToolTips()};n.flagContinousAvailability=function(){var t=n.editableListing().isReferral()?PF.Factory.Availability.createReferral({spaceId:n.editableListing().id(),startDate:startDate.toLocaleDateString(),startTime:"9:00",endDate:endDate==null?"":endDate.toLocaleDateString(),endTime:"17:00",isDaily:!0}):PF.Factory.Availability.createAvailability({spaceId:n.editableListing().id(),startDate:startDate.toLocaleDateString(),startTime:"9:00",endDate:endDate==null?"":endDate.toLocaleDateString(),endTime:"17:00",isDaily:!0})};n.editAvailability=function(t){n.editedAvailabilities.remove(t);n.selectedAvailability(t);n.initToolTips()};n.saveAvailability=function(t){if(!n.selectedAvailability())return!0;if(n.selectedAvailability().calendarType().CalendarTypeName!=PF.CalendarType.MultiDayAvailability.CalendarTypeName||n.selectedAvailability().endDate())n.availValidationError(null);else return n.availValidationError("You must have an end date for a multi day availability"),!1;if(!t)return!0;t.commit();n.editedAvailabilities.push(t);n.selectedAvailability(null);n.dirtyRates(!0)};n.cancelAvailability=function(t){t.id()||n.editableListing().availabilities.remove(t);n.availValidationError(null);t.revert();n.selectedAvailability(null)};n.deleteAvailability=function(t){t.isDeleted(!0);n.editedAvailabilities.push(t);n.editableListing().availabilities.remove(t);n.dirtyRates(!0)};n.addSpecialRate=function(){var t;if(n.editableListing().defaultRate().rateTypeId()==PF.RateType.Hourly&&(t=PF.Factory.RentalRate.createHourlyPricingRate()),n.editableListing().defaultRate().rateTypeId()==PF.RateType.PerUse&&(t=PF.Factory.RentalRate.createPerUsePricingRate()),n.editableListing().defaultRate().rateTypeId()==PF.RateType.PerPerson){if(t=PF.Factory.RentalRate.createPerPersonPricingRate(n.editableListing()),t.personRangeChoices().length==0){n.increasePackageQtyError(!0);return}n.increasePackageQtyError(!1)}n.editableListing().specialRates.push(t);n.selectedSpecialRate(t);n.pricingValidator=new PF.FormValidator;n.pricingValidator.Init({container:$("#modal-edit-availability")})};n.editSpecialRate=function(t){n.selectedSpecialRate(t);n.pricingValidator=new PF.FormValidator;n.pricingValidator.Init({container:$("#modal-edit-availability")})};n.saveSpecialRate=function(t){n.editableListing().defaultRate().rateTypeId()==PF.RateType.PerUse&&(!t.availabilityQtyUsed()||isNaN(t.availabilityQtyUsed())||t.availabilityQtyUsed()<=0)&&t.availabilityQtyUsed(1);n.editableListing().defaultRate().rateTypeId()==PF.RateType.Hourly&&(!t.rate()||isNaN(t.rate())||t.rate()<0)&&t.rate(0);t.name()||t.name("New Special Price");t.commit();t.rateTypeId(n.editableListing().defaultRate().rateTypeId());n.editedSpecialRates.push(t);$.each(n.editableListing().specialRates(),function(n,i){i.id()==t.id()&&(i=t)});n.selectedSpecialRate(null);n.dirtyRates(!0)};n.cancelSpecialRate=function(t){t.revert();t.id()||n.editableListing().specialRates.remove(t);n.selectedSpecialRate(null);n.pricingValidator=new PF.FormValidator;n.pricingValidator.Init({container:$("#modal-edit-availability")})};n.deleteSpecialRate=function(t){t.isDeleted(!0);n.editedSpecialRates.push(t);n.editableListing().specialRates.remove(t);n.dirtyRates(!0)};n.addPromoCodeGroup=function(){var t=new PromotionCodeGroup({promotionCodes:[new PromotionCode],spaces:[n.editableListing()]});n.editableListing().promotionCodeGroups.push(t);n.selectedPromoCodeGroup(t)};n.editPromoCodeGroup=function(t){n.selectedPromoCodeGroup(t)};n.savePromoCodeGroup=function(t){t.name()||t.name(t.defaultName());t.commit();n.editedPromoCodeGroups.push(t);n.selectedPromoCodeGroup(null);n.dirtyPromoCodeGroups(!0)};n.cancelPromoCodeGroup=function(t){t.revert();t.id()||n.editableListing().promotionCodeGroups.remove(t);n.selectedPromoCodeGroup(null)};n.deletePromoCodeGroup=function(t){t.isDeleted(!0);t.promotionCodes()[0].isDeleted(!0);n.editedPromoCodeGroups.push(t);n.editableListing().promotionCodeGroups.remove(t);n.dirtyPromoCodeGroups(!0)};n.savePromoCodeGroups=function(){if(n.editedPromoCodeGroups().length!=0){var t={Item:n.editedPromoCodeGroups().map(function(n){return n.toServerModel()})};return $.ajax({url:"/my/listings/savepromotioncodegroups",type:"POST",dataType:"json",data:JSON.stringify(t),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(t){if(t.Success){var i=t.Item.map(function(n){return(new PromotionCodeGroup).fromServerModel(n)});return n.listing().promotionCodeGroups(i),n.editedPromoCodeGroups.removeAll(),!0}return n.error(t.Error),!1}})}};n.activateListing=function(t){var i=n.listing().publishedToWeb()?{title:"Web Listing",confirmMessage:'Your listing is currently live on your website and the <a href="/'+n.listing().account().condensedName()+'" target="_blank">PlaceFull Directory<\/a>.<br> Do you want to unpublish it?',successMessage:"Your listing has been unpublished and is no longer visible on your website and the PlaceFull Directory.",successTitle:"Listing Inactive",action:"unpublish"}:{title:"Web Listing",confirmMessage:'Publish this listing to your website and the <a href="/'+n.listing().account().condensedName()+'" target="_blank">PlaceFull Directory<\/a> now?',successMessage:"Your listing has been published and is now visible on your website and PlaceFull Directory. ",successTitle:"Listing Active!",action:"publish"};t==PF.Publish.Facebook?i=n.listing().publishedToFacebook()?{title:"Facebook",confirmMessage:"Your listing is currently live on Facebook. Do you want to remove it?",successMessage:"Your listing has been removed from your Facebook page.",successTitle:"Listing Removed",action:"unpublish"}:{title:"Facebook",confirmMessage:"<p>Allow your customers to book this listing directly on your Facebook page.  To use PlaceFull's Facebook integration make sure you install the <a href='/My/Dashboard/Marketing#FB'>PlaceFull Facebook App<\/a>.<\/p><p> Are you ready to publish this listing to Facebook?<\/p>",successMessage:"Your listing has been published to your Facebook page.<a href='javascript:void(0)' onclick='location.reload()'>Reload this page<\/a> to view your calendar availability.",successTitle:"Listing Published",action:"publish"}:t==PF.Publish.Web_Calendar&&(i=n.listing().publishedToWebCalendar()?{title:"Web Calendar",confirmMessage:"Your listing is currently live on your website monthly calendar.<br> Do you want to unpublish it?",successMessage:"Your listing has been unpublished and is no longer visible on your website calendar.",successTitle:"Listing Inactive",action:"unpublish"}:{title:"Web Calendar",confirmMessage:"Publish this listing to your website monthly calendar now?",successMessage:"Your listing has been published and is now visible on your website calendar. ",successTitle:"Listing Active!",action:"publish"});n.busy()||(n.busy(!0),PF.Modals.Generic.Show({title:i.title,description:i.confirmMessage,confirm:function(){var r="/my/space/publish",u=new ListingCategory({condensedName:t}),f={Item:n.listing().id(),CondensedName:n.listing().condensedName(),PublishCategories:[u.toServerModel()]};i.action=="unpublish"&&(r="/my/space/unpublish");$.ajax({url:r,type:"POST",dataType:"json",data:JSON.stringify(f),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(r){n.busy(!1);r&&(r.Success?(n.listing().publishedToFacebook(r.Item.PublishedToFacebook),n.listing().publishedToWeb(r.Item.PublishedToWeb),n.listing().publishedToWebCalendar(r.Item.PublishedToWebCalendar),t==PF.Publish.Facebook&&i.action=="publish"&&n.confirmFacebookApp(),n.refresh()):PF.showError(r.Error))})},close:function(){n.busy(!1)}}))};n.confirmFacebookApp=function(){$("#btnActivateFacebook").hasClass("facebookInactive")&&$.ajax({type:"GET",url:"/my/space/renderpartial",data:{templateName:"_FacebookAppDialog"},cache:!1}).done(function(n){PF.Modals.Generic.Show({title:"Get the PlaceFull Facebook App",description:n,labels:{close:"Skip"}})}).fail(function(n){PF.showError(n.responseText)})};n.editImageDone=function(){n.editableImage(undefined);u()};n.generalTabClick=function(t,i){const r=n.savePricing(!0);r&&$(i.target).tab("show")};n.extrasTabClick=function(t,i){const r=n.savePricing(!0);r&&$(i.target).tab("show")}};$(function(){EditListingViewModel.prototype=Object.create(ListingDetailViewModel.prototype)});var ListingSettingsViewModel=function(n){var t=this;t.account=ko.observable();t.colors=ko.observableArray([{name:"Blue",value:"#0d6efd"},{name:"Indigo",value:"#6610f2"},{name:"Purple",value:"#6f42c1"},{name:"Pink",value:"#d63384"},{name:"Red",value:"#dc3545"},{name:"Teal",value:"#20c997"},{name:"Cyan",value:"#0dcaf0"}]);t.settings=ko.observable([]);t.success=ko.observable(!1);t.errorMessage=ko.observable();t.selectedColor=ko.observable();t.busy=ko.observable(!1);t.backgroundImage=function(n,t){t&&ko.applyBindingsToNode(n,{style:{background:t.value}},t)};n&&t.account(n);t.save=function(){function n(){$.ajax({url:"/my/listings/EditColorSetting",type:"POST",dataType:"json",data:JSON.stringify(t.selectedColor()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n&&(n.Success?t.setBusy(!1):(t.setBusy(!1),PF.showError(n.Error)))}).error(function(n){t.setBusy(!1);t.setupErrorMessage(n)})}t.setBusy(!0,"Saving settings...");$.ajax({url:"/My/Account/SaveAccount",type:"POST",dataType:"json",data:JSON.stringify(t.account().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(i){i.Success&&(t.account((new Account).fromServerModel(i.Item)),n(),t.setupSuccessMessage("Your changes were saved successfully!"))}).error(function(n){t.setBusy(!1);t.setupErrorMessage(n)})};t.load=function(){t.selectedColor({Class:undefined});$.ajax({url:"/my/listings/GetColorSetting",type:"POST",dataType:"json",data:JSON.stringify({AccountId:t.account().id()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n&&(n.Success?t.selectedColor(n):PF.showError(n.Error))})};t.setBusy=function(n,i){t.busy(n);n===!0?PF.Modals.ProgressIndicator.Show({message:i}):n===!1&&PF.Modals.ProgressIndicator.HideModal()};t.setupSuccessMessage=function(n){t.success(n);window.setTimeout(5e3,function(){t.success(null)})};t.setupErrorMessage=function(n){t.errorMessage(n);window.setTimeout(1e4,function(){t.errorMessage(null)})}},NotificationViewModel=function(n){var t=this;t.listing=ko.observable(n);t.description=ko.observable(t.listing().terms().emailTextToRenter());t.editor=new MediumEditor(".editable",{placeholder:{text:"Type your message here"},autoLink:!0,buttonLabels:"fontawesome",toolbar:{buttons:["bold","italic","underline","anchor"],relativeContainer:$("#email-controls")[0]},anchorPreview:{showWhenToolbarIsVisible:!0}});$("#medium-editor-toolbar-1").css("visibility","visible");t.editor.setContent(t.listing().terms().emailTextToRenter());t.save=function(){var i=PF.getTextWithoutHTML($(".editable").html()).length>0?$(".editable").html():"",n;t.listing().terms().emailTextToRenter(i);n={Item:t.listing().terms().toServerModel(),Space_Id:t.listing().id()};$.ajax({type:"POST",url:"/my/listings/saveterms",data:JSON.stringify(n),contentType:"application/json; charset=utf-8",dataType:"json",success:function(n){n.Success?t.success():t.error(n.Error)}})};t.success=function(){$(".alert-error").hide();$(".alert-success").show()};t.error=function(n){$(".alert-success").hide();$(".alert-error").html(n).show()}},EditListingAdditionalInfoViewModel=function(n){function i(n,t){this.name=ko.observable(n);this.children=ko.observableArray(t)}var t=this;t.editableListing=ko.observable(n);t.info=ko.observableArray();t.dirty=ko.observable(!1);t.selected=ko.observable();t.selectedOption=ko.observable();t.includeGlobalAdditionalQuestions=!1;t.init=function(){t.getAdditionalInfoOptions(t.includeGlobalAdditionalQuestions)};t.toggleGlobalAdditionalQuestions=function(n){if(t.dirty){var i={Space_Id:n,Item:t.selectedInfo().map(function(n){return n.toServerModel(!0)})};$.ajax({url:"/my/listings/saveadditionalinfo",type:"POST",dataType:"json",data:JSON.stringify(i),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(){t.includeGlobalAdditionalQuestions=t.includeGlobalAdditionalQuestions?!1:!0;t.getAdditionalInfoOptions(t.includeGlobalAdditionalQuestions)})}else t.includeGlobalAdditionalQuestions=t.includeGlobalAdditionalQuestions?!1:!0,t.getAdditionalInfoOptions(t.includeGlobalAdditionalQuestions)};t.getAdditionalInfoOptions=function(n){$.ajax({url:"/my/listings/getadditionalinfooptions",data:{id:t.editableListing().id(),includeGlobal:n},type:"GET",contentType:"application/json; charset=UTF-8"}).done(function(n){if(n.Success){var i=n.Item.map(function(n){return n.Selected||(n.Info.Order=-1),(new AdditionalInfo).fromServerModel(n)});t.info(i);t.selectedOption(t.info[0])}else t.error(n.Error)}).fail(function(n){n=JSON.parse(n.responseText);$(".alert").text(n.Error);t.error(n.responseText)})};t.selectedInfo=ko.computed(function(){var n=[];return $.each(t.info(),function(t,i){i.selected()&&n.push(i)}),n.sort(function(n,t){return n.order()>t.order()?1:n.order()<=t.order()?-1:0}),n},t,{deferEvaluation:!0});t.groupedInfo=ko.computed(function(){var n=[];return $.each(t.info(),function(t,r){if(!r.selected()){var u=$.grep(n,function(n){return n.name()===r.categoryComputed()});u.length===0&&(u=[new i(r.categoryComputed(),[])],n.push(u[0]));u[0].children.push(r)}}),n},t,{deferEvaluation:!0});t.add=function(){t.selected(!0)};t.save=function(){var n=t.selectedOption();n&&(n.order(t.selectedInfo().length),n.selected(!0));t.selected(null);t.dirty(!0)};t.cancel=function(){t.selected(null)};t.remove=function(n){n.selected(!1);t.dirty(!0)};t.moveInfoDownInOrdering=function(n){var r,u,i;if(n.order()+1!==t.selectedInfo().length){for(r=-1,u=-1,i=0;i<t.info().length;i++)if(t.info()[i].order()===n.order()&&(r=i),t.info()[i].order()===n.order()+1&&(u=i),r!==-1&&u!==-1)break;t.info()[u].order(n.order());t.info()[r].order(n.order()+1);t.dirty(!0)}};t.moveInfoUpInOrdering=function(n){var r,u,i;if(n.order()!==0){for(r=-1,u=-1,i=0;i<t.info().length;i++)if(t.info()[i].order()===n.order()&&(u=i),t.info()[i].order()===n.order()-1&&(r=i),r!==-1&&u!==-1)break;t.info()[r].order(n.order());t.info()[u].order(n.order()-1);t.dirty(!0)}};t.init()},EditListingAddOnsViewModel=function(n){var t=this,i;t.editableListing=ko.observable(n);t.dirty=ko.observable(!1);t.addOns=ko.observableArray();t.selectedAddOns=ko.observableArray();t.sortedSelectedAddOns=ko.computed(function(){return t.selectedAddOns().sort(function(n,t){return n.order()===t.order()?0:n.order()<t.order()?-1:1})});t.selected=ko.observable();t.selectedOption=ko.observable();t.imageChanged=ko.observable(!1);i=function(n){if(n&&n.length)for(let t=0;t<n.length;t++){const i=n[t],r=i.fileUrl()+"?v="+(new Date).getTime();i.fileUrlWithTime=ko.observable();i.fileUrlWithTime(r)}};t.init=function(){$.ajax({url:"/my/listings/getalladdons",data:{spaceId:t.editableListing().id()},type:"GET",contentType:"application/json; charset=UTF-8"}).done(function(n){if(n.Success){var r=n.Item.map(function(n){return(new AddOnSpace).fromServerModel(n)});t.addOns([]);t.selectedAddOns([]);$.each(r,function(n,r){const f=r.addOn().images();$.each(f,function(n,t){const r=t.thumbnails();i(r)});const u=r.addOn().defaultImage();if(u){const n=u.fileUrl()+"?v="+(new Date).getTime();u.fileUrlWithTime=ko.observable();u.fileUrlWithTime(n)}t.addOns.push(r.addOn());r.space_id()&&t.selectedAddOns.push(r)})}else t.error(n.Error)}).fail(function(n){n=JSON.parse(n.responseText);$(".alert").text(n.Error);t.error(n.responseText)})};t.edit=function(n){t.selectedOption(n.addOn());t.selected(n);t.editAddOnImages();t.selected().addOn().images.subscribe(function(){t.imageChanged(!0)})};t.add=function(){var n=new AddOnSpace;t.selectedAddOns.push(n);t.selected(n)};t.createCustom=function(n){t.selectedOption(undefined);n.addOn(new AddOn({account_id:t.editableListing().account().id()}));n.editable(!0)};t.editAddOnImages=function(){var n=$("<button/>").addClass("btn button-singlefileupload").prop("disabled",!0).text("Processing...").on("click",function(){var n=$(this),t=n.data();n.off("click").text("Cancel").on("click",function(){n.remove();t.abort()});t.submit().always(function(){n.remove()})});$("#modal-edit-addons .file-upload input[type=file]",t.view).fileupload({url:"/Handlers/Upload.ashx",dataType:"json",autoUpload:!0,acceptFileTypes:/(\.|\/)(gif|jpe?g|png)$/i,maxFileSize:5e7,disableImageResize:/Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),previewMaxWidth:80,previewMaxHeight:80,previewCrop:!0,sequentialUploads:!0,formData:{addonid:t.selected().addOn().id(),filetype:"image"}}).on("fileuploadadd",function(t,i){var f=this,r=$(this).data("blueimp-fileupload"),u;r.pf=r.pf||{queue:0,active:0};$(this).closest(".drop").children(".instructions").hide();u=$(this).closest(".drop").children(".previews");$.each(i.files,function(t,e){var h=$(".files-row:last-child",u),o,s;if(r.pf.queue%4==0&&(h=$('<div class="row-fluid files-row" />'),u.append(h)),o=i.context=$('<div class="file-container"/>').appendTo(h),o.append('<div class="preview" />'),o.append($('<div class="title" />').text(e.name)),o.append($("<small/>").text("("+Math.round(e.size*.000976562)+" KB)")),o.append('<div class="progress hide"><div class="bar bar-success"><\/div><\/div>'),t||o.append("<br>").append(n.clone(!0).data(i)),r.pf.queue++,r.pf.active++,r.pf.active>0&&(s=$(f).closest(".drop").children(".uploadall-button"),s.removeClass("hide"),!s.data("pf-uploadalleventattached"))){s.data("pf-uploadalleventattached",!0);s.on("click",function(){$(".button-singlefileupload",$(f).closest(".drop")).click();s.data("pf-uploadalleventattached",!1)})}})}).on("fileuploadprocessalways",function(n,t){var r=t.index,i=t.files[r],f=$(t.context.children()[r]),u=t.context;i.preview&&$(".preview",u).append(i.preview);i.error&&u.append("<br>").append($('<span class="text-danger"/>').text(i.error));r+1===t.files.length&&u.find("button").text("Upload").prop("disabled",!!t.files.error)}).on("fileuploadprogress",function(n,t){$(".progress",$(t.context)).removeClass("hide");var i=parseInt(t.loaded/t.total*100,10);$(".progress .bar",$(t.context)).css("width",i+"%")}).on("fileuploaddone",function(n,r){var u,f;r&&r.result&&r.result.Success&&r.result.Item&&r.result.Item.length>0&&($(".progress",r.context).hide(),$(r.context).append('<i class="fa fa-check-circle fa-2x pf-upload-success"><\/i>'),u=$(this).data("blueimp-fileupload"),u.pf.active--,u.pf.active<=0&&($(this).closest(".drop").children(".uploadall-button").addClass("hide"),$(this).closest(".drop").children(".previews").empty(),$(this).closest(".drop").children(".instructions").removeClass("hide").show()),f=r.result.Item.map(function(n){return(new AddOnImage).fromServerModel(n)}),$.each(f,function(n,r){const u=r.thumbnails();if(i(u),r.fileUrl){const n=r.fileUrl()+"?v="+(new Date).getTime();r.fileUrlWithTime=ko.observable();r.fileUrlWithTime(n)}t.selected().addOn().images.push(r)}))}).on("fileuploadfail",function(n,t){$.each(t.files,function(n){var i=$('<span class="text-danger"/>').text("File upload failed.");$(t.context.children()[n]).append("<br>").append(i)})}).prop("disabled",!$.support.fileInput).parent().addClass($.support.fileInput?undefined:"disabled")};t.save=function(){var n=t.selected(),i;n.space_id(t.editableListing().id());i=t.selectedOption();i&&(n.rate()||n.rate(0),n.addOn(i));t.selected(null);t.selectedOption(null);t.dirty(!0);t.imageChanged()&&(t.init(),t.imageChanged(!1))};t.cancel=function(n){n.space_id()||t.selectedAddOns.remove(n);t.selected(null);t.selectedOption(null);t.imageChanged()&&(t.init(),t.imageChanged(!1))};t.remove=function(n){n.space_id(null);t.selectedAddOns.remove(n);t.dirty(!0)};t.init()},EditListingGeneralViewModel=function(n,t){var i=this;i.editableSpace=ko.observable(n);i.listing=ko.observable();i.error=ko.observable();i.parentVM=t;i.dirty=ko.observable(!1);i.allCategories=ko.observableArray();i.selected_category_ids=ko.observableArray();i.init=function(){$.ajax({url:"/my/listingcategories/GetListingCategories",type:"POST",contentType:"application/json; charset=UTF-8"}).success(function(n){if(n.Success){var t=n.Item.map(function(n){return(new ListingCategory).fromServerModel(n)});$.each(t,function(n,t){i.allCategories.push(t)});$.ajax({url:"/my/listings/GetListings",data:JSON.stringify({ObjectId:i.editableSpace().id()}),type:"POST",contentType:"application/json; charset=UTF-8"}).success(function(n){n.Success&&n.Item[0]?(i.listing((new Listing).fromServerModel(n.Item[0])),i.selected_category_ids(i.listing().listingCategories().map(function(n){return n.id()})),$("#listingPick").trigger("change"),i.selected_category_ids.subscribe(function(){i.listing()&&i.dirty(!0)})):(n.Item[0]||n.Error||(n.Error="No category listing object found for this listing. Please contact PlaceFull support."),i.error(n.Error))})}else i.error(n.Error)})};i.save=function(){i.error(null);i.dirty()?(i.listing().listingCategories.remove(function(n){return n.isVisibleToUser()}),$.each(i.selected_category_ids(),function(){i.listing().listingCategories.push(new ListingCategory({id:this.toString()}))}),$.ajax({url:"/My/Listings/EditListings",type:"POST",dataType:"JSON",data:JSON.stringify({Item:[i.listing().toServerModel()]}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(n){n.Success?(i.parentVM.save(),$("#modal-edit-general").modal("hide")):i.error("We were unable to save your Listing. Please try again or contact support@placefull.com. "+(n.Error?"Inquiring minds might find this helpful: "+n.Error:""))})):(i.parentVM.save(),$("#modal-edit-general").modal("hide"))};i.cancel=function(){};i.init()},EditListingResourcesEditViewModel=function(n,t){var i=this;i.editableListing=ko.observable(n);i.parentVM=t;i.resources=ko.observableArray();i.selectedResource=ko.observable();i.resourceError=ko.observable();i.error=ko.observable();i.validator=null;i.init=function(){$.ajax({url:"/my/account/getresources",type:"GET",contentType:"application/json; charset=UTF-8"}).done(function(n){if(n.Success){var t=n.Item.map(function(n){return(new Resource).fromServerModel(n)});i.resources(t)}else i.error(n.Error)}).fail(function(n){n=JSON.parse(n.responseText);$(".alert").text(n.Error);i.error(n.responseText)})};i.refresh=function(){i.init();i.selectedResource(null);i.refreshMainListingEditView()};i.buildResourceSpaces=function(n){var t=[];return $.each(i.resources(),function(r,u){var f=$.grep(n,function(n){return n.resourceId()==u.id()});f&&f.length>0&&(f[0].resource(u),f[0].space(i.editableListing()),t.push(f[0]))}),t};i.addResource=function(){var n=new Resource({account:i.editableListing().account(),usageType:PF.UsageType.BuyerQty,peopleCapacity:1});i.selectedResource(n);i.resources.unshift(n)};i.editResource=function(n){i.selectedResource(n);$('#resourceEdit [data-toggle="tooltip"]').tooltip({html:!0,trigger:"click"})};i.saveResource=function(){if(i.error(""),i.validator=(new PF.FormValidator).Init({container:$("#resourceEdit")}),i.validator.Validate()){i.resourceError("");var n={Item:[i.selectedResource().toServerModel()]};$.ajax({url:"/my/listings/saveresources",type:"POST",dataType:"json",data:JSON.stringify(n),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n.Success?(i.refresh(),i.parentVM._viewEditListingResourcesLink().refresh()):(i.error(n.Error),PF.Modals.Generic.Show({title:"Error Saving Resource",description:n.Error}))}).fail(function(n){n=JSON.parse(n.responseText);i.error(n.Error)})}};i.cancelResource=function(){i.selectedResource().id()||i.resources.remove(i.selectedResource());i.selectedResource(null);i.resourceError("")};i.templateToUseResource=function(n){return i.selectedResource()===n?"tmpl-resource-edit":"tmpl-resource"};i.refreshMainListingEditView=function(){$.ajax({url:"/my/listings/getresourcespaces/"+i.editableListing().id(),type:"GET",dataType:"json",processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){if(n)if(n.Success){var t=n.Item.map(function(n){return(new ResourceSpace).fromServerModel(n)});t=i.buildResourceSpaces(t);i.parentVM.listing().resourceSpaces.removeAll();i.editableListing().resourceSpaces.removeAll();$.each(t,function(n,t){i.parentVM.listing().resourceSpaces.push(t);i.editableListing().resourceSpaces.push(t)});i.parentVM.refresh()}else i.error(n.Error)})};i.deleteResource=function(n){PF.Modals.Generic.Show({title:"Delete This Resource",description:"Are you sure you want to delete "+n.name()+"? It will be removed from all listings, but previous bookings will stay unedited",confirm:function(){var t={Item:[n.toServerModel()]};$.ajax({url:"/my/listings/deleteResource",type:"POST",dataType:"json",data:JSON.stringify(t),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){t.Success?(i.resources.remove(n),i.refresh(),i.parentVM._viewEditListingResourcesLink().refresh()):i.error(t.Error)}).fail(function(n){n=JSON.parse(n.responseText);i.error(n.Error)})}})};i.init()},EditListingResourcesLinkViewModel=function(n,t){var i=this;i.parentVM=t;i.editableListing=ko.observable(n);i.adding=ko.observable();i.editing=ko.observable();i.selectedResource=ko.observable();i.editedResourceSpace=ko.observable();i.allResources=ko.observableArray();i.searchFilter=ko.observable();i.calendar=null;i.validator=null;i.container=$("#resourceLink");i.calendarScaleFactor=ko.computed(function(){return i.editableListing()&&i.editableListing().minRentalDuration()<=120?2:1});i.calendarIsDirty=ko.observable(!1);i.calendarIsDirty.subscribe(function(n){n==!0&&(i.adding(!1),i.editing(!1))});i.calendarIsSetup=function(){return i.calendar!=null&&i.calendar.hasClass("fc")};i.error=function(n){console.log("[ERROR] "+n)};i.refresh=function(){i.calendarIsDirty(!1);i.init();i.refreshMainListingEditView()};i.init=function(){$.ajax({url:"/my/account/getresources",type:"GET",contentType:"application/json; charset=UTF-8"}).done(function(n){if(n.Success){var t=n.Item.map(function(n){return(new Resource).fromServerModel(n)});i.allResources(t);i.editableListing().resourceSpaces(i.buildResourceSpaces(i.editableListing().resourceSpaces()));i.setupCalendar()}else i.error(n.Error)}).fail(function(n){n=JSON.parse(n.responseText);$(".alert").text(n.Error);i.error(n.responseText)})};i.filteredResources=ko.computed(function(){var n=[];return $.each(i.allResources(),function(t,r){var u=$.grep(i.editableListing().resourceSpaces(),function(n){return n.resource().id()==r.id()});u&&u.length!=0||(i.searchFilter()?r.name().toLowerCase().indexOf(i.searchFilter().toLowerCase())>=0&&n.push(r):n.push(r))}),n},i,{deferEvaluation:!0});i.buildResourceSpaces=function(n){var t=[];return $.each(i.allResources(),function(r,u){var f=$.grep(n,function(n){return n.resourceId()==u.id()});f&&f.length>0&&(f[0].resource(u),f[0].space(i.editableListing()),t.push(f[0]))}),t};i.setupCalendar=function(){if(!i.calendarIsSetup()){if(i.calendar=i.container.find("#resourceLinkCalendar"),!i.calendar.is(":visible"))return;i.calendar.fullCalendar({header:{left:"",center:"",right:""},allDaySlot:!1,defaultView:"agendaDay",editable:!0,selectable:!0,selectHelper:!0,slotEventOverlap:!1,height:450,minTime:6,maxTime:8+i.editableListing().minRentalDuration()*i.calendarScaleFactor()/60,axisFormat:"",timeFormat:"",columnFormat:"",eventClick:function(n){n.type=="resource"&&(i.editedResourceSpace(n.resourceSpace),i.editing(!0),i.adding(!1),$("#modal-edit-resources-link").modal("show"))},select:function(){$("#modal-edit-resources-link").modal("show");i.adding(!0);i.editing(!1)},eventResize:function(n,t,r,u){if(n.end>n.maximumEnd||n.start<n.minimumStart){u();return}n.resourceSpace.addMinutesToUsageLength(r/i.calendarScaleFactor());n.resourceSpace.isDirty(!0);i.calendarIsDirty(!0);i.renderEvents()},eventDrop:function(n,t,r,u,f){if(n.end>n.maximumEnd||n.start<n.minimumStart){f();return}n.resourceSpace.addMinutesToUsageDelay(r/i.calendarScaleFactor());n.resourceSpace.isDirty(!0);i.calendarIsDirty(!0);i.renderEvents()},eventAfterRender:function(n,t){n.type=="listing"&&$(t).css("max-width","220px")}});i.renderEvents()}};i.renderEvents=function(){i.calendar.fullCalendar("removeEvents");i.createListingTimeSlotEvent();$.each(i.editableListing().resourceSpaces(),function(n,t){i.createLinkageEvent(t)})};i.createLinkageEvent=function(n){var r=PF.Moment(i.calendar.fullCalendar("getDate")).format("L"),u=PF.Moment(r+" 7:00").add(n.usageDelayComputed()*i.calendarScaleFactor(),"minutes"),o=PF.Moment(u).add(n.usageLengthComputed()*i.calendarScaleFactor(),"minutes"),f=PF.Moment(r+" 7:00"),e=n.resource().name()+"\n"+PF.formatPrettyDuration(n.usageLengthComputed()),t;return n.categoryName()&&(e+="\n["+n.categoryName()+"]"),t={type:"resource",start:u.toDate(),end:o.toDate(),minimumStart:f,maximumEnd:PF.Moment(f).add(i.editableListing().minRentalDuration()*i.calendarScaleFactor(),"minutes"),color:"#94DBFF",textColor:"#000",title:e,resourceSpace:n,allDay:!1},i.calendar.fullCalendar("renderEvent",t),t};i.createListingTimeSlotEvent=function(){var r=PF.Moment(i.calendar.fullCalendar("getDate")).format("L"),n=PF.Moment(r+" 7:00"),u=PF.Moment(n).add(i.editableListing().minRentalDuration()*i.calendarScaleFactor(),"minutes"),t={type:"listing",start:n.toDate(),end:u.toDate(),color:"#FF8080",textColor:"#000",title:"- "+i.editableListing().name()+"\n"+PF.formatPrettyDuration(i.editableListing().minRentalDuration()),allDay:!1,editable:!1};return i.calendar.fullCalendar("renderEvent",t),t};i.add=function(){i.adding(!0);i.editing(!1)};i.cancelEvents=function(){i.refresh()};i.closeLinkModal=function(){$("#modal-edit-resources-link").modal("hide");i.adding(null);i.editing(null);i.selectedResource(null);i.editedResourceSpace(null);i.searchFilter(null)};i.saveEvents=function(){var n={Item:[]};$.each(i.editableListing().resourceSpaces(),function(t,i){i.isDirty()&&n.Item.push(i.toServerModel())});$.ajax({url:"/my/listings/saveresourcespaces",type:"POST",dataType:"json",data:JSON.stringify(n),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n&&(n.Success?(i.editedResourceSpace(null),i.refresh(),i.parentVM._viewEditListingResourcesEdit().refresh()):i.error(n.Error))})};i.prepSave=function(){i.editedResourceSpace()!=null&&(i.validator=(new PF.FormValidator).Init({container:i.container}),i.validator.Validate())&&(i.editableListing().resourceSpaces.unshift(i.editedResourceSpace()),i.adding(null),i.editing(null),i.selectedResource(null),i.searchFilter(null),i.save())};i.save=function(){if(i.editedResourceSpace()){var n={Item:[]};n.Item.push(i.editedResourceSpace().toServerModel());$.ajax({url:"/my/listings/saveresourcespaces",type:"POST",dataType:"json",data:JSON.stringify(n),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n&&(n.Success?(i.closeLinkModal(),i.editedResourceSpace(null),i.refresh(),i.parentVM._viewEditListingResourcesEdit().refresh()):i.error(n.Error))})}};i.refreshMainListingEditView=function(){$.ajax({url:"/my/listings/getresourcespaces/"+i.editableListing().id(),type:"GET",dataType:"json",processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){if(n)if(n.Success){var t=n.Item.map(function(n){return(new ResourceSpace).fromServerModel(n)});t=i.buildResourceSpaces(t);i.parentVM.listing().resourceSpaces.removeAll();i.editableListing().resourceSpaces.removeAll();$.each(t,function(n,t){i.parentVM.listing().resourceSpaces.push(t);i.editableListing().resourceSpaces.push(t)});i.renderEvents();i.parentVM.refresh()}else i.error(n.Error)})};i.selectResource=function(n){i.editedResourceSpace(new ResourceSpace({space:i.editableListing(),resource:n,hideFromBuyer:!1,chargeRateForAllResources:!1}));i.selectedResource(n)};i.cancelAdding=function(){i.selectedResource(null);i.searchFilter(null);i.editedResourceSpace(null)};i.cancelEditing=function(){i.closeLinkModal()};i.remove=function(){i.editedResourceSpace()&&PF.Modals.Generic.Show({title:"Remove Resource",description:"Remove "+i.editedResourceSpace().resource().name()+" from this listing?",confirm:function(){i.editedResourceSpace().space(null);i.editedResourceSpace().spaceId(null);i.editableListing().resourceSpaces.remove(i.editedResourceSpace());i.save();i.closeLinkModal()}})};i.init()},AlertViewModel=function(n){var t=this,i=null;t.manageTabName="manage";t.editTabName="edit";t.notificationVM=n;t.currentArea=ko.observable(t.manageTabName);t.listOfPossibleAlerts=ko.observableArray();t.selectedAlert=ko.observable();t.pager=ko.observable(new AsyncPagedListViewModel([],[],null));t.selectedNewAlert=ko.observable();t.selectedNewAlertSubscription=t.selectedNewAlert.subscribe(function(n){n!==null&&n!==undefined?(t.selectedAlert((new Alert).fromServerModel(n.toServerModel())),t.selectedPriorityComputed(n.priority()),t.isActiveSelectionComputed(n.isActive()),n.canPickListings()&&t.allActiveListingsChecked(!0)):t.selectedAlert(n)});t.prioritySelections=ko.observableArray([{name:"High",value:5},{name:"Medium",value:3},{name:"Low",value:0}]);t.selectedPriority=ko.observable();t.selectedPriorityComputed=ko.computed({read:function(){return t.selectedPriority()===undefined?0:t.selectedPriority().value},write:function(n){var i=t.prioritySelections().map(function(n){return n.value}).indexOf(n);i===-1&&(i=0);t.selectedPriority(t.prioritySelections()[i])}});t.isActiveSelection=ko.observable("yes");t.isActiveSelectionComputed=ko.computed({read:function(){return t.isActiveSelection()!==undefined&&t.isActiveSelection()==="yes"?!0:!1},write:function(n){t.isActiveSelection(n?"yes":"no")}});t.loadAlerts=function(n){$.ajax({url:"/My/SmartFull/GetAlerts",type:"POST",dataType:"json",data:JSON.stringify({PageSize:t.pager().pageSize(),Page:t.pager().pageIndex()+1}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){t.Success?n&&n(t,Alert):PF.Modals.Generic.Show({title:"Load Alerts Failure",description:"Unable to load your alerts. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com <br/> "+(t.Error?"Developers might find this info useful: "+t.Error:"")})})};t.load=function(n){t.loadAccountAlerts(n);t.loadPossibleAlerts()};t.loadAccountAlerts=function(n){t.pager(new AsyncPagedListViewModel([],n,function(n){t.loadAlerts(n)},{}));t.pager().load()};t.loadPossibleAlerts=function(){$.ajax({url:"/My/SmartFull/GetListOfAlerts",type:"POST",dataType:"json",processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){if(n.Success){var i=n.Item.map(function(n){return(new Alert).fromServerModel(n)});t.listOfPossibleAlerts([]);$.each(i,function(n,i){t.listOfPossibleAlerts.push(i)})}else PF.Modals.Generic.Show({title:"Load Alerts Failure",description:"Unable to load alert list for creation. Please refresh the page and try again. If this happens repeatedly, please contact PlaceFull support at support@placefull.com <br/> "+(n.Error?"Developers might find this info useful: "+n.Error:"")})})};t.editAlert=function(n){t.selectedNewAlert(undefined);t.selectedAlert(n);t.selectedPriorityComputed(n.priority());t.isActiveSelectionComputed(n.isActive());t.currentArea(t.editTabName)};t.editSpecificAlert=function(n){$.ajax({url:"/My/SmartFull/GetSpecificAlert",type:"POST",dataType:"json",data:JSON.stringify({alertId:n}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(i){i.Success&&i.Item.length===1&&i.Item[0].Id.toLowerCase()===n.toLowerCase()?t.editAlert((new Alert).fromServerModel(i.Item[0])):PF.Modals.Generic.Show({title:"Error editing alert",description:"Error loading alert to edit. Please try again or try editing the alert from the 'Manage Alerts' tab. If this issue persists, please contact PlaceFull support at support@placefull.com. <br/> "+(i.Error?"Developers might find this info useful: "+i.Error:"")})})};t.manageAlertsClick=function(){t.currentArea(t.manageTabName);t.listOfPossibleAlerts().length===0&&t.load()};t.newAlertClick=function(){t.selectedAlert(undefined);t.selectedNewAlert(undefined);t.currentArea(t.editTabName);t.loadPossibleAlerts()};t.saveAlert=function(){(i=null,i===null&&(i=(new PF.FormValidator).Init({container:$(".configure-description")})),i.Validate())&&(t.selectedAlert().isActive(t.isActiveSelectionComputed()),t.selectedAlert().priority(t.selectedPriorityComputed()),$.ajax({url:"/My/SmartFull/UpdateAlert",type:"POST",dataType:"json",data:JSON.stringify(t.selectedAlert().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n.Success?(t.loadAccountAlerts(),t.currentArea(t.manageTabName),t.refreshNotifications()):PF.Modals.Generic.Show({title:"Save Alert Failure",description:"Unable to save alert. Please try again. If this happens repeatedly, please contact PlaceFull support at support@placefull.com. <br/> "+(n.Error?"Developers might find this info useful: "+n.Error:"")})}))};t.refreshNotifications=function(){t.notificationVM&&t.notificationVM.load()};t.deleteAlertConfirm=function(n){t.selectedAlert(n);PF.Modals.Generic.Show({title:"Delete Alert",description:"Are you sure you wish to delete the alert '"+t.selectedAlert().displayName()+"'?",labels:{confirm:"Yes",close:"No"},confirm:function(){t.selectedAlert().isDeleted(!0);$.ajax({url:"/My/SmartFull/UpdateAlert",type:"POST",dataType:"json",data:JSON.stringify(t.selectedAlert().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n.Success?(t.loadAccountAlerts(),t.currentArea(t.manageTabName)):PF.Modals.Generic.Show({title:"Delete Alert Failure",description:"Unable to delete alert. Please try again. If this issue persists, please contact PlaceFull support at suport@placefull.com. <br/> "+(n.Error?"Developers might find this info useful: "+n.Error:"")})})}})};t.runAlert=function(n){t.selectedAlert(n);t.selectedAlert().isRunning(!0);$.ajax({url:"/My/SmartFull/RunAlert",type:"POST",dataType:"json",data:JSON.stringify(t.selectedAlert().toServerModel()),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){if(t.selectedAlert().isRunning(!1),n.Success){t.refreshNotifications();var i='Your alert "'+n.Item.DisplayName+'" has ran and ';i+=n.NewNotifications.length?"generated a notification. Check your notification bar for more details!":"did not trigger.";PF.Modals.Generic.Show({title:"Run Alert Result",description:i})}else PF.Modals.Generic.Show({title:"Run Alert Failure",description:"Failed to run alert. <br/> "+(n.Error?"Developers might find this info useful: "+n.Error:"")})})};t.addListingsBySelector=function(n){for(var r=$(n),i=0;i<r.length;i++)t.selectedAlert().variables().space_ids.push(r[i].value)};t.allListingsCheckedPrivate=ko.observable();t.allListingsChecked=ko.computed({read:function(){return t.allListingsCheckedPrivate()},write:function(n){t.selectedAlert().variables().space_ids.removeAll();n&&t.addListingsBySelector("#lstSpaces option");t.allListingsCheckedPrivate(n);t.allActiveListingsCheckedPrivate(n);t.allInactiveListingsCheckedPrivate(n);$("#lstSpaces").trigger("change")}});t.allActiveListingsCheckedPrivate=ko.observable();t.allActiveListingsChecked=ko.computed({read:function(){return t.allActiveListingsCheckedPrivate()},write:function(n){t.selectedAlert().variables().space_ids.removeAll();n&&t.addListingsBySelector("#lstSpaces optgroup[label='Active Listings'] option");t.allInactiveListingsCheckedPrivate()&&t.addListingsBySelector("#lstSpaces optgroup[label='Inactive Listings'] option");t.allActiveListingsCheckedPrivate(n);t.allInactiveListingsCheckedPrivate()&&t.allListingsCheckedPrivate(n);$("#lstSpaces").trigger("change")}});t.allInactiveListingsCheckedPrivate=ko.observable();t.allInactiveListingsChecked=ko.computed({read:function(){return t.allInactiveListingsCheckedPrivate()},write:function(n){t.selectedAlert().variables().space_ids.removeAll();n&&t.addListingsBySelector("#lstSpaces optgroup[label='Inactive Listings'] option");t.allActiveListingsCheckedPrivate()&&t.addListingsBySelector("#lstSpaces optgroup[label='Active Listings'] option");t.allInactiveListingsCheckedPrivate(n);t.allActiveListingsCheckedPrivate()&&t.allListingsCheckedPrivate(n);$("#lstSpaces").trigger("change")}})},EmailAnalyticsViewModel=function(){var n=this;n.allEmailNotifications=ko.observableArray();n.selectedEmailNotification=ko.observable();n.emailsYetToSend=ko.observableArray();n.lastEmailsSent=ko.observableArray();n.selectedEmailNotificationFromList=ko.observable();n.selectedEmailNotificationFromListSubscription=n.selectedEmailNotificationFromList.subscribe(function(t){t?n.getAnalytics(t):n.selectedEmailNotification(undefined)});n.load=function(){$.ajax({url:"/My/SmartFull/GetEmailNotifications",type:"POST",dataType:"json",data:"",processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(t.Success){var i=t.Item.map(function(n){return(new EmailNotification).fromServerModel(n)});$.each(i,function(t,i){n.allEmailNotifications.push(i)})}else PF.Modals.Generic.Show({title:"Unable to load email campaigns",description:"Unable to load your email campaigns. Please try again. If this happens repeatedly, please contact PlaceFull support."})}).fail(function(){PF.Modals.Generic.Show({title:"Unable to load email campaigns",description:"Unable to load your email campaigns. Please try again. If this happens repeatedly, please contact PlaceFull support."})})};n.getAnalytics=function(t){$.get("/My/SmartFull/GetFullEmailNotification/"+t,{}).success(function(t){t.Success&&t.Item&&t.Item.length?(n.selectedEmailNotification((new EmailNotification).fromServerModel(t.Item[0])),$.ajax({url:"/My/SmartFull/GetAnalyticsForCampaign",type:"POST",dataType:"json",data:JSON.stringify(n.selectedEmailNotification().toServerModel()),contentType:"application/json; charset=utf-8"}).success(function(t){t.Success?(n.selectedEmailNotification().emailNotificationDetail((new EmailNotificationDetail).fromServerModel(t.EmailNotificationDetail)),n.emailsYetToSend.removeAll(),n.lastEmailsSent.removeAll(),t.EmailsYetToBeSent.map(function(t){n.emailsYetToSend.push((new SMTPQueueDetail).fromServerModel(t))}),t.EmailsSent.map(function(t){n.lastEmailsSent.push((new SMTPQueueDetail).fromServerModel(t))})):PF.Modals.Generic.Show({title:"Unable to load email analytics",description:"Unable to load analytics for your campaign '"+n.selectedEmailNotification().campaign()+"'. Please try again. If this happens repeatedly, please contact PlaceFull support."})})):PF.Modals.Generic.Show({title:"Unable to load email analytics",description:"Unable to load analytics for your campaign. Please try again. If this happens repeatedly, please contact PlaceFull support."})})}},EmailGroupsViewModel=function(n){var t=this;t.createAreaName="create";t.editAreaName="edit";t.groupAreaName="group";t.analyticsAreaName="analytics";t.emailManagerVM=n;t.account=n.account;t.editorActive=ko.observable();t.pager=ko.observable(new AsyncPagedListViewModel([],[],null));t.leadPager=ko.observable(new AsyncPagedListViewModel([],[],null));t.selectedCampaign=ko.observable();t.selectedGroup=ko.observable();t.selectedLead=ko.observable();t.availableSpaces=ko.observableArray();t.editingGroup=ko.observable(!1);t.addingGroup=ko.observable(!1);t.editingLeads=ko.observable(!1);t.importingLeads=ko.observable(!1);n.currentArea.subscribe(function(n){n==t.groupAreaName&&(t.reset(),t.load())});t.addingGroup.subscribe(function(n){n==!0?$(".new-group-content .collapse").on("shown.bs.collapse",function(){$('[data-bind*="chosen"]').trigger("change")}).collapse("show"):$(".new-group-content .collapse").collapse("hide")});t.editingGroup.subscribe(function(n){n==!0?$(".new-group-content .collapse").collapse("show"):$(".new-group-content .collapse").collapse("hide")});t.importingLeads.subscribe(function(n){n==!0&&t.editingLeads(!1)});t.editingLeads.subscribe(function(n){n==!0&&t.importingLeads(!1)});t.load=function(i){t.pager(new AsyncPagedListViewModel([],i,function(n){t.loadGroups(n)},{}));t.pager().load();t.loadAvailableSpaces();n.addGroup()&&t.addGroup()};t.loadAvailableSpaces=function(){t.availableSpaces.removeAll();$.ajax({url:"/My/SmartFull/GetSpaces",type:"POST",dataType:"json",data:null,processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n.Item.map(function(n){t.availableSpaces.push((new Space).fromServerModel(n))})}).fail(function(){PF.Modals.Generic.Show({title:"Load Listings Failure",description:"Unable to load your listings. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com"})})};t.loadGroups=function(n){$.ajax({url:"/My/SmartFull/GetCustomGroups",type:"POST",dataType:"json",data:JSON.stringify({PageSize:t.pager().pageSize(),Page:t.pager().pageIndex()+1}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){n&&n(t,CustomGroup)}).fail(function(){PF.Modals.Generic.Show({title:"Load Campaigns Failure",description:"Unable to load your campaigns. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com"})})};t.cancelGroup=function(){t.selectedGroup().id()||t.pager().innerList.shift();t.reset()};t.reset=function(){t.selectedGroup(null);t.addingGroup(!1);t.editingGroup(!1);t.editingLeads(!1);t.importingLeads(!1)};t.addGroup=function(){if(t.selectedGroup()){t.cancelGroup();return}var n=new CustomGroup({sendToAllCustomers:!0});t.pager().innerList.unshift(n);t.selectedGroup(n);t.leadPager().reload();t.addingGroup(!0);t.initCSVFileUpload();window.scrollTo(0,0)};t.editGroup=function(n){t.selectedGroup()&&t.cancelGroup();$.ajax({url:"/My/SmartFull/GetFullCustomGroup/"+n.id(),type:"POST",dataType:"json",data:null,processData:!1,contentType:"application/json; charset=utf-8"}).success(function(i){if(i.Success){t.selectedGroup(n);t.loadLeadPager();var r=(new CustomGroup).fromServerModel(i.Item[0]);t.selectedGroup().emailNotifications(r.emailNotifications());$.each(r.spaces(),function(i,r){var u=$.grep(t.availableSpaces(),function(n){return n.id()===r.id()});u[0]&&n.spaces.push(u[0])});t.editingGroup(!0);$('[data-bind*="chosen"]').trigger("change");t.initCSVFileUpload()}else PF.Modals.Generic.Show({title:"Load Campaigns Failure",description:"Unable to load your campaigns. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com",error:i.Error})})};t.deleteEmail=function(n){PF.Modals.Generic.Show({title:"Delete Email",description:"Are you sure you wish to delete the email <b>'"+n.email()+"'<\/b>? ",labels:{confirm:"Yes",close:"No"},confirm:function(){$.ajax({url:"/My/SmartFull/DeleteLead",type:"POST",dataType:"json",data:JSON.stringify({Item:n.toServerModel()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n.Success?t.loadLeadPager():PF.Modals.Generic.Show({title:"Delete Email Failure",description:"Unable to delete email. Please try again. If this issue persists, please contact PlaceFull support at suport@placefull.com.",error:n.Error})})}})};t.saveGroup=function(){$.ajax({url:"/My/SmartFull/SaveCustomGroup",type:"POST",dataType:"json",data:JSON.stringify({Item:t.selectedGroup().toServerModel()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(i){i.Success?(t.pager().innerList.remove(t.selectedGroup()),t.pager().innerList.unshift((new CustomGroup).fromServerModel(i.Item[0])),t.reset(),n.addGroup()&&(n.customGroupToStartWith((new CustomGroup).fromServerModel(i.Item[0])),n.currentArea(t.createAreaName)),t.pager().reload()):PF.Modals.Generic.Show({title:"Load Campaigns Failure",description:"Unable to save your campaign. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com",error:i.Error})})};t.loadLeads=function(n){var i=t.leadPager().findFilter("text"),r=t.leadPager().findFilter("providerType");$.get("/My/SmartFull/GetCustomerLeads",{PageSize:t.leadPager().pageSize(),Page:t.leadPager().pageIndex()+1,SearchText:i.value(),CustomGroupId:t.selectedGroup().id()}).success(function(t){t.Success&&n&&n(t,CustomerLead)})};t.initCSVFileUpload=function(){$("#fileupload").fileupload({dataType:"json",autoUpload:!0,acceptFileTypes:/(\.|\/)(csv|txt|xls|xlsx|doc)$/i,maxFileSize:1e7,sequentialUploads:!0,formData:{accountid:t.account().id(),filetype:"leads",customgroupid:t.selectedGroup().id()},done:function(n,i){t.importingLeads(!1);i.result.Success?(t.selectedGroup().id()||(t.selectedGroup().id(i.result.CustomGroupId),$(".new-group-content .collapse").collapse("show"),$('[data-bind*="chosen"]').trigger("change")),t.loadLeadPager()):PF.Modals.Generic.Show({title:"Import CSV Failure",description:"Unable to import CSV. <br><br>Are you trying to import an Excel file (xls, xlsx) or Text file (txt)? Please convert these to comma delimited CSV files to upload. <br><br>'File Save As..' if using Excel. If this issue persists, please contact PlaceFull support at support@placefull.com.",error:i.result.Error})}})};t.deleteGroup=function(n){PF.Modals.Generic.Show({title:"Delete Campaign",description:"Are you sure you wish to delete the email group <b>'"+n.name()+"'<\/b>? <br><br><br> All unsent emails in any campaign for members of this group will be stopped.",labels:{confirm:"Yes",close:"No"},confirm:function(){$.ajax({url:"/My/SmartFull/DeleteCustomGroup",type:"POST",dataType:"json",data:JSON.stringify({Item:n.toServerModel()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){n.Success?t.pager().reload():PF.Modals.Generic.Show({title:"Delete Group Failure",description:"Unable to delete group. Please try again. If this issue persists, please contact PlaceFull support at suport@placefull.com.",error:n.Error})})}})};t.loadLeadPager=function(){var n=[{name:"text",reset:function(){this.value("")},value:ko.observable(""),text:function(){return this.value()},apply:function(n){return this.value()?PF.hasStringMatch(n.firstName(),this.value())||PF.hasStringMatch(n.lastName(),this.value())||PF.hasStringMatch(n.email(),this.value()):!0}}];t.leadPager(new AsyncPagedListViewModel([],n,function(n){t.loadLeads(n)}));t.leadPager().load()};t.templateToUseGroup=function(n){return!t.selectedGroup()||t.selectedGroup().id()!=n.id()?"groupsTmpl":"editGroupTmpl"};t.templateToUseLead=function(n){return!t.selectedLead()||t.selectedLead().id()!=n.id()?"leadsTmpl":"editLeadTmpl"}},EmailManagerViewModel=function(){var n=this;n.createAreaName="create";n.editAreaName="edit";n.groupAreaName="group";n.analyticsAreaName="analytics";n.account=ko.observable(new Account);n.sendMode=ko.observable();n.showCampaign=ko.observable();n.addGroup=ko.observable(!1);n.currentArea=ko.observable(n.editAreaName);n.customGroupToStartWith=ko.observable();n.allCustomers=ko.observable();n.pager=ko.observable(new AsyncPagedListViewModel([],[],null));n.selectedNotification=ko.observable();n.selectedTemplate=ko.observable();n.availableGroups=ko.observableArray();n.availableTemplates=ko.observableArray();n.validator=new PF.FormValidator;n.currentArea.extend({notify:"always"});n.currentArea.subscribe(function(t){n.showCampaign(!1);t==n.createAreaName&&n.createNewCampaign();t!=n.groupAreaName&&n.addGroup(!1)});n.selectedTemplate.subscribe(function(t){n.selectedNotification().originalBodyText||(n.selectedNotification().originalBodyText=ko.observable(n.selectedNotification().emailNotificationDetail().bodyText()));t?n.selectedNotification().emailNotificationDetail().bodyText(t.emailNotificationDetail().bodyText()):n.selectedNotification().emailNotificationDetail().bodyText(n.selectedNotification().originalBodyText());$("#emailCampaignEditor").editable("setHTML",n.selectedNotification().emailNotificationDetail().bodyText())});n.sendTime=ko.computed({read:function(){return n.selectedNotification()?PF.Moment(n.selectedNotification().emailNotificationDetail().singleDate()).format("h:mm a"):"12:00 pm"},write:function(t){if(n.selectedNotification().emailNotificationDetail().singleDate()){var i=PF.Moment(t,"h:mm a"),r=PF.Moment(n.selectedNotification().emailNotificationDetail().singleDate()).hour(i.get("hour")).minute(i.get("minute"));n.selectedNotification().emailNotificationDetail().singleDate(r.toDate())}},owner:this});n.sendTimingDescribed=ko.computed({read:function(){var u;if(!n.selectedNotification()||!n.selectedNotification().emailNotificationDetail())return"";var r=n.selectedNotification().emailNotificationDetail().emailTriggerType(),i="Send ",t=n.allCustomers()?"all customers across all listings":'the <a data-toggle="collapse" href="#listings">listing(s)<\/a>',f=n.selectedNotification().sendDelayInDays()==1?" day ":" days ";return r=="EventDate"&&(i+=n.selectedNotification().sendDelayInDays()+f,i+=n.selectedNotification().sendDelay()>0?"after any event occurs for "+t:"before any event occurs for "+t,n.selectedNotification().sendDelay()||n.selectedNotification().sendDelay(0),n.selectedNotification().sendDelay()==0&&(i="Send the day any event occurs for "+t)),r=="BookingDate"&&(i+=n.allCustomers()?" "+t+" when they purchase.":" to anyone who will purchase "+t),r=="ManualDate"&&(u=PF.Moment(n.selectedNotification().emailNotificationDetail().singleDate()).format("MMM D YYYY, h:mm a"),i+=n.allCustomers()?" on "+u+" to "+t+" and all imported customers. ("+n.selectedNotification().totalLeads()+" imported)":" on "+u+" to anyone who purchased "+t+" and all imported customers. ("+n.selectedNotification().totalLeads()+" imported)"),i}});n.previewSendToDescribed=ko.computed({read:function(){if(!n.selectedNotification()||!n.selectedNotification().emailNotificationDetail())return"";var t=n.selectedNotification().emailNotificationDetail().emailTriggerType();return t==null&&(t="EventDate"),(t=="EventDate"||t=="BookingDate")&&(output=n.allCustomers()?"Anyone who will purchase any of your listings":"Anyone who will purchase the following listings"),t=="ManualDate"&&(output=n.allCustomers()?"Anyone who has ever purchased any of your listings and any customers you have imported in the email groups":"Anyone who has ever purchased the following listings and any customers you have imported in the email groups"),output}});n.previewSendAtDescribed=ko.computed({read:function(){var i,t,r;return!n.selectedNotification()||!n.selectedNotification().emailNotificationDetail()?"":(i=n.selectedNotification().emailNotificationDetail().emailTriggerType(),i==null&&(i="EventDate"),t="Send ",r=n.selectedNotification().sendDelayInDays()==1?" day ":" days ",i=="EventDate"&&(t+=n.selectedNotification().sendDelayInDays()+r,t+=n.selectedNotification().sendDelay()>0?"after the booked event":"before the booked event",n.selectedNotification().sendDelay()||n.selectedNotification().sendDelay(0),n.selectedNotification().sendDelay()==0&&(t="Send the day of the event")),i=="BookingDate"&&(t+=" immediately when any of the listings are purchased"),i=="ManualDate"&&(t+=" on "+PF.Moment(n.selectedNotification().emailNotificationDetail().singleDate()).format("ddd MMM D YYYY, h:mm a")),t)}});n.loadCampaigns=function(t){$.ajax({url:"/My/SmartFull/GetEmailNotifications",type:"POST",dataType:"json",data:JSON.stringify({PageSize:n.pager().pageSize(),Page:n.pager().pageIndex()+1}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(i){i.Success?(n.account((new Account).fromServerModel(i.Account)),t&&t(i,EmailNotification)):PF.Modals.Generic.Show({title:"Load Campaigns Failure",description:"Unable to load your campaigns. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com",error:response.Error})})};n.loadTemplates=function(){(n.selectedTemplate(undefined),n.availableTemplates().length>0)||$.ajax({url:"/My/SmartFull/GetEmailTemplates",type:"GET",dataType:"json",processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){t.Success?t.Item.map(function(t){n.availableTemplates.push((new EmailNotification).fromServerModel(t))}):PF.Modals.Generic.Show({title:"Load Templates Failure",description:"Unable to load PlaceFull templates. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com",error:response.Error})})};n.load=function(t){n.pager(new AsyncPagedListViewModel([],t,function(t){n.loadCampaigns(t)},{}));n.pager().load()};n.selectManualDate=function(){var t=PF.Moment(new Date).minute(0),i=n.selectedNotification().emailNotificationDetail().singleDate()?n.selectedNotification().emailNotificationDetail().singleDate():t.toDate();n.selectedNotification().emailNotificationDetail().singleDate(i);n.selectedNotification().emailNotificationDetail().emailTriggerType("ManualDate")};n.createNewCampaign=function(){var t=$("<div><\/div>").html(n.account().organizationName()).text(),i=new EmailNotification({emailNotificationDetail:new EmailNotificationDetail({emailTriggerType:"EventDate"}),fromName:t,fromEmail:"",sendDelay:-2880});n.selectedNotification(i);n.customGroupToStartWith()&&(n.selectedNotification().customGroups.push(n.customGroupToStartWith()),n.showCampaign(!0));n.loadGroups();n.loadTemplates();n.validator.Init({container:$("#create-edit-emails-content")})};n.createNewGroup=function(){n.currentArea(n.groupAreaName);n.addGroup(!0)};n.editCampaign=function(t){$.get("/My/SmartFull/GetFullEmailNotification/"+t.id(),{}).success(function(t){t.Success?(n.selectedNotification((new EmailNotification).fromServerModel(t.Item[0])),n.showCampaign(!0),n.allCustomers(!1),n.loadGroups(),n.loadTemplates(),n.validator.Init({container:$("#create-edit-emails-content")}),$.each(n.selectedNotification().customGroups(),function(t,i){i.sendToAllCustomers()&&n.allCustomers(!0)})):PF.Modals.Generic.Show({title:"Load Campaign Failure",description:"Unable to load your campaign. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com",error:t.Error})})};n.loadGroups=function(){$.ajax({url:"/My/SmartFull/GetCustomGroups",type:"POST",dataType:"json",data:null,processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){n.availableGroups.removeAll();t.Item.map(function(t){n.availableGroups.push((new CustomGroup).fromServerModel(t))});n.selectedNotification()&&$.each(n.availableGroups(),function(t,i){var r=$.grep(n.selectedNotification().customGroups(),function(n){return n.id()===i.id()});r[0]&&(n.selectedNotification().customGroups.remove(r[0]),n.selectedNotification().customGroups.push(i))})}).fail(function(){PF.Modals.Generic.Show({title:"Load Email Groups Failure",description:"Unable to load your groups. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com",error:response.Error})})};n.saveDraft=function(){if(!n.validator.Validate()){$("html, body").animate({scrollTop:450},250);return}n.saveCampaign(function(t){t.Success?(n.pager().reload(),n.currentArea(n.editAreaName)):PF.Modals.Generic.Show({title:"Save Campaign Failure",description:"Unable to load your campaign. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com",error:t.Error})})};n.saveSend=function(){if(!n.validator.Validate()){$("html, body").animate({scrollTop:450},250);return}n.saveCampaign(function(t){t.Success?$.ajax({url:"/My/SmartFull/SendEmailNotification",type:"POST",dataType:"json",data:JSON.stringify({Request:{Item:t.Item[0]},templateName:n.selectedTemplate()?n.selectedTemplate().campaign():null}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(t.Success){var i=(new EmailNotification).fromServerModel(t.Item[0]);$("#sendSummary").modal("hide");PF.Modals.Generic.Show({title:"Successfull Queued",description:"The emails for <b>"+i.campaign()+"<\/b> have been successfully queued up to send. <br><br>Would you like to see more details for the queued emails?",labels:{confirm:"Yes see email details",close:"No thanks"},confirm:function(){n.viewAnalytics(i)},close:function(){n.currentArea(n.editAreaName)}})}else PF.Modals.Generic.Show({title:"Send Campaign Failure",description:"Unable to send your campaign. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com",error:t.Error})}):PF.Modals.Generic.Show({title:"Save Campaign Failure",description:"Unable to send your campaign. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com",error:t.Error})})};n.saveCampaign=function(t){var i=n.selectedNotification().emailNotificationDetail().emailTriggerType(),r;i!="ManualDate"&&n.selectedNotification().emailNotificationDetail().singleDate(null);i!="EventDate"&&n.selectedNotification().sendDelay(null);r={Item:n.selectedNotification().toServerModel()};$.ajax({url:"/My/SmartFull/SaveEmailNotification",type:"POST",dataType:"json",data:JSON.stringify(r),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(n){t&&t(n)})};n.deleteCampaignConfirm=function(t){PF.Modals.Generic.Show({title:"Delete Campaign",description:"Are you sure you wish to delete the campaign <b>'"+t.campaign()+"'<\/b>? <br><br>Any emails that haven't yet been sent for this campaign will be stopped.",labels:{confirm:"Yes",close:"No"},confirm:function(){t.isDeleted(!0);$.ajax({url:"/My/SmartFull/SaveEmailNotification",type:"POST",dataType:"json",data:JSON.stringify({Item:t.toServerModel()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){t.Success?n.pager().reload():PF.Modals.Generic.Show({title:"Delete Campaign Failure",description:"Unable to delete campaign. Please try again. If this issue persists, please contact PlaceFull support at suport@placefull.com.",error:t.Error})})}})};n.viewAnalytics=function(t){n.emailAnalyticsVM&&($('select.btn option[value="'+t.id()+'"]').prop("selected",!0),n.emailAnalyticsVM.getAnalytics(t.id()),n.currentArea(n.analyticsAreaName))};n.cancelCampaignCreation=function(){PF.Modals.Generic.Show({title:"Campaign Creation Cancel",description:"Are you sure you want to cancel creation of this email campaign?",labels:{confirm:"Yes",close:"No"},confirm:function(){n.currentArea(n.editAreaName)}})}},PromosViewModel=function(n,t,i){var r=this;r.validator=null;r.busy=ko.observable(!1);r.account=ko.observable((new Account).fromServerModel(n));r.initialSpaceId=ko.observable(i);r.viewTabName="view";r.createTabName="create";r.searchTabName="search";r.currentArea=ko.observable(r.viewTabName);r.promoCodeGroupSettingsTabName="settings";r.promoCodeGroupViewCodesTabName="codes";r.createSubArea=ko.observable(r.promoCodeGroupSettingsTabName);r.showAdvancedGroupSettings=ko.observable(!1);r.successMessage=ko.observable();r.errorMessage=ko.observable();r.messageTimeout=null;r.editablePromotionCodeGroup=ko.observable(new PromotionCodeGroup);r.selectedPromoCode=ko.observable();r.space_ids=ko.observableArray();r.codesFilter=null;r.globalCodeFilter=null;r.pager=ko.observable(new AsyncPagedListViewModel([],[],null));r.codesPager=ko.observable(new AsyncPagedListViewModel([],[],null));r.searchPager=ko.observable(new AsyncPagedListViewModel([],[],null));r.globalSearchPager=ko.observable(new AsyncPagedListViewModel([],[],null));r.importingCodes=ko.observable();r.exportingCodes=ko.observable();r.exportMode=ko.observable(0);r.globalSearchBox=ko.observable();r.load=function(n){r.codesFilter=n.codesFilter;r.globalCodeFilter=n.globalCodeFilter;r.getAccountPromotionCodeGroups(n)};r.getAccountPromotionCodeGroups=function(n){r.pager(new AsyncPagedListViewModel([],[n.groupNameFilter,n.groupSpaceFilter],function(n){r.getPromotionCodeGroups(n)},{}));r.initialSpaceId()&&r.pager().findFilter("spaceId").value(r.initialSpaceId());r.pager().load()};r.getPromotionCodeGroups=function(n){$.ajax({url:"/My/Promos/GetPromotionCodeGroups",type:"POST",dataType:"JSON",data:JSON.stringify({PageSize:r.pager().pageSize(),Page:r.pager().pageIndex()+1,SearchText:r.pager().findFilter("text").value(),SpaceId:r.pager().findFilter("spaceId").value()}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(t){t.Success?n&&n(t,PromotionCodeGroup):PF.Modals.Generic.Show({title:"Error Loading Promotion Code Groups",description:"An error occurred while loading your promotions. Please try again or contact support@placefull.com.<br/><br/>Inquiring minds might find this helpful: "+t.Error})})};r.getPromotionCodes=function(n){var t=r.codesPager().findFilter("text");$.ajax({url:"/My/Promos/GetPromotionCodes",type:"POST",dataType:"JSON",data:JSON.stringify({PageSize:r.codesPager().pageSize(),Page:r.codesPager().pageIndex()+1,SearchText:t.value(),PromotionCodeGroup:r.editablePromotionCodeGroup().toServerModel()}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(t){t.Success?(t.Item=t.PromotionCodes,n&&n(t,PromotionCode)):PF.Modals.Generic.Show({title:"Error Loading Promotion Code Groups",description:"An error occurred while loading your promotions. Please try again or contact support@placefull.com.<br/><br/>Inquiring minds might find this helpful: "+t.Error})})};r.setupDatePickersAndTooltips=function(){r.pickers=$("input.datepicker").datepicker();r.pickers.datepicker().on("changeDate",function(n){$(this).datepicker("hide");$(n.currentTarget).trigger("change")});$('[data-toggle="tooltip"]').tooltip()};r.viewPromotionGroupsClick=function(){r.currentArea(r.viewTabName);r.createSubArea(r.promoCodeGroupSettingsTabName)};r.createPromotionGroupClick=function(){r.editablePromotionCodeGroup(new PromotionCodeGroup);r.editablePromotionCodeGroup().account((new Account).fromServerModel(r.account().toServerModel()));r.editablePromotionCodeGroup().discountValidationMode(3);r.currentArea(r.createTabName);r.codesPager().reload();r.setupDatePickersAndTooltips();r.space_ids.removeAll();$("#lstSpaces").trigger("change")};r.searchClick=function(){r.currentArea(r.searchTabName);r.globalSearchPager(new AsyncPagedListViewModel([],[r.globalCodeFilter],function(n){r.executeGlobalSearch(n)},{}));r.globalSearchPager().load()};r.viewSettingsClick=function(){r.createSubArea(r.promoCodeGroupSettingsTabName)};r.viewCodesClick=function(){r.createSubArea(r.promoCodeGroupViewCodesTabName)};r.clearSuccessMessage=function(){r.successMessage("")};r.clearErrorMessage=function(){r.errorMessage("")};r.editPromotion=function(n){r.setupEditPromotion(n);r.currentArea(r.createTabName);r.codesPager(new AsyncPagedListViewModel([],[r.codesFilter],function(n){r.getPromotionCodes(n)},{}));r.codesPager().load();r.initCSVFileUpload()};r.setupEditPromotion=function(n){r.editablePromotionCodeGroup(n);r.space_ids(r.editablePromotionCodeGroup().spaces().map(function(n){return n.id()}));$("#lstSpaces").trigger("change");r.setupDatePickersAndTooltips()};r.deletePromotionConfirm=function(n){r.setupEditPromotion(n);PF.Modals.Generic.Show({title:"Delete Group Confirm",description:"Are you sure you wish to delete this promotion? All promotion codes in this group will be unusable.",labels:{confirm:"Yes",close:"No"},confirm:function(){r.editablePromotionCodeGroup().isDeleted(!0);r.savePromotion()}})};r.savePromotion=function(){(r.validator=(new PF.FormValidator).Init({container:$("#promoSettingsArea")}),r.validator.Validate())&&(r.editablePromotionCodeGroup().discountMode()==1&&r.editablePromotionCodeGroup().discountAmount()>100||(r.editablePromotionCodeGroup().spaces(r.space_ids().map(function(n){return new Space({id:n})})),r.editablePromotionCodeGroup().promotionCodes()&&r.editablePromotionCodeGroup().promotionCodes().length===0&&r.editablePromotionCodeGroup().promotionCodes([new PromotionCode({discountCode:r.editablePromotionCodeGroup().name()})]),$.ajax({url:"/My/Promos/SavePromotionCodeGroup",type:"POST",dataType:"JSON",data:JSON.stringify({Item:[r.editablePromotionCodeGroup().toServerModel()]}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(n){n.Success?(r.editablePromotionCodeGroup().isDeleted()?(r.editSuccessMessage("Successfully deleted your promotion!"),r.editablePromotionCodeGroup(new PromotionCodeGroup)):r.editSuccessMessage("Successfully saved your promotion!"),r.currentArea(r.viewTabName),r.getAccountPromotionCodeGroups({groupNameFilter:groupNameFilter,groupSpaceFilter:groupSpaceFilter,codesFilter:codeFilter})):r.editErrorMessage("We were unable to save your promotion. Please try again or contact support@placefull.com. "+(n.Error?"Inquiring minds might find this helpful: "+n.Error:""))}).error(function(){PF.Modals.Generic.Show({title:"",description:""})})))};r.cancelPromotion=function(){r.currentArea(r.viewTabName)};r.editSuccessMessage=function(n){r.successMessage(n);r.messageTimeout=setTimeout(r.clearSuccessMessage,1e4)};r.editErrorMessage=function(n){r.errorMessage(n);r.messageTimeout=setTimeout(r.clearErrorMessage,1e4)};r.addPromotionCode=function(){r.importingCodes(!1);var n=new PromotionCode({promotionCodeGroup:r.editablePromotionCodeGroup()});r.selectedPromoCode(n);r.codesPager().innerList.unshift(n)};r.editPromotionCode=function(n){r.selectedPromoCode(n)};r.deletePromotionCode=function(n){PF.Modals.Generic.Show({title:"Delete Code Confirm",description:"Are you sure you wish to delete this promotion code? This code will no longer be usable.",labels:{confirm:"Yes",close:"No"},confirm:function(){n.isDeleted(!0);r.savePromotionCode(n)}})};r.savePromotionCode=function(n){(r.validator=(new PF.FormValidator).Init({container:$("#promoCodeEditArea")}),r.validator.Validate())&&$.ajax({url:"/My/Promos/SavePromotionCode",type:"POST",dataType:"JSON",data:JSON.stringify({PageSize:r.codesPager().pageSize(),Page:r.codesPager().pageIndex()+1,Item:[n.toServerModel()]}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(n){n.Success?(r.selectedPromoCode(null),r.codesPager().reload()):PF.Modals.Generic.Show({title:"Error Loading Promotion Code Groups",description:"An error occurred while saving. Please try again or contact support@placefull.com.<br/><br/>Inquiring minds might find this helpful: "+n.Error})})};r.cancelPromotionCode=function(n){n.id()==null&&r.codesPager().innerList.shift();r.selectedPromoCode(null)};r.initCSVFileUpload=function(){$("#fileupload").fileupload({dataType:"json",autoUpload:!0,acceptFileTypes:/(\.|\/)(csv|txt|xls|xlsx|doc)$/i,maxFileSize:1e7,sequentialUploads:!0,formData:{filetype:"promocodes",promotionCodeGroupId:r.editablePromotionCodeGroup().id()},done:function(n,t){r.importingCodes(!1);t.result.Success?r.codesPager().reload():PF.Modals.Generic.Show({title:"Import CSV Failure",description:"Unable to import CSV. <br><br>Are you trying to import an Excel file (xls, xlsx) or Text file (txt)? Please convert these to comma delimited CSV files to upload. <br><br>'File Save As..' if using Excel. If this issue persists, please contact PlaceFull support at support@placefull.com.",error:t.result.Error})}})};r.exportPromoCodes=function(){r.busy(!0);PF.Modals.ProgressIndicator.Show();$.ajax({url:"/My/Promos/GetPromotionCodes",type:"POST",dataType:"JSON",data:JSON.stringify({PromotionCodeGroup:r.editablePromotionCodeGroup().toServerModel(),ExportMode:r.exportMode()}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(n){var u,t,i;if(PF.Modals.ProgressIndicator.HideModal(),n.Success){u=encodeURI(n.Data);t="promo_code_export_"+r.editablePromotionCodeGroup().name()+"_";switch(r.exportMode()){case"0":t+="all";break;case"1":t+="expired";break;case"2":t+="active"}t+=".csv";i=document.createElement("a");i.setAttribute("href",u);i.setAttribute("download",t);document.body.appendChild(i);i.click();document.body.removeChild(i)}else r.editErrorMessage(n.Error)}).error(function(n){PF.Modals.ProgressIndicator.HideModal();r.editErrorMessage(n.Error)})};r.executeGlobalSearch=function(n){var t=r.globalSearchPager().findFilter("text");$.ajax({url:"/My/Promos/GetPromotionCodes",type:"POST",dataType:"JSON",data:JSON.stringify({PromotionCodeGroup:new PromotionCodeGroup({id:"00000000-0000-0000-0000-000000000000",account:r.account()}).toServerModel(),PageSize:r.globalSearchPager().pageSize(),Page:r.globalSearchPager().pageIndex()+1,SearchText:t.value()}),processData:!1,contentType:"application/json; charset=UTF-8"}).success(function(t){t.Success&&(t.Item=t.PromotionCodes,n&&n(t,PromotionCode))}).error(function(n){r.editErrorMessage(n.Error)})}},SmartFullNotificationsViewModel=function(){var n=this;n.notifications=ko.observableArray();n.selectedNotification=ko.observable();n.firstTwoNotifications=ko.observableArray();n.loaded=ko.observable(!1);n.notificationModal=ko.observable();n.notificationListModal=ko.observable();n.resetNotificationToggle=function(){$(".show-more").off("click");$(".show-more").on("click",function(){$(this).find(".click-alert").animate({width:"toggle"})})};n.firstTwoNotifications=ko.computed({read:function(){for(var i=[],t=0;t<2&&t<n.notifications().length;t++)i.push(n.notifications()[t]);for(t=n.notifications().length;t<2;t++)i.push(new AlertNotification);return n.resetNotificationToggle(),i}});n.notificationCountText=ko.computed({read:function(){return n.notifications().length+" active notification"+(n.notifications().length!==1?"s":"")}});n.load=function(){window.alertVM&&!window.alertVM.notificationVM&&(window.alertVM.notificationVM=n);n.loadNotifications()};n.loadNotifications=function(){$.ajax({url:"/My/SmartFull/GetNotifications",type:"POST",dataType:"json",data:JSON.stringify({GetFullList:!1}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){if(n.loaded(!0),t.Success){var i=t.Item.map(function(n){return(new AlertNotification).fromServerModel(n)});n.notifications.removeAll();$.each(i,function(t,i){n.notifications.push(i)});n.resetNotificationToggle()}else PF.Modals.Generic.Show({title:"Load Notifications Error",description:"Unable to load notifications. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com. <br/> Developers might find this info useful: "+t.Error})}).fail(function(){PF.Modals.Generic.Show({title:"Load Notifications Error",description:"Unable to load notifications. Please refresh the page and try again. If this issue persists, please contact PlaceFull support at support@placefull.com"})})};n.loadAllNotifications=function(){n.notificationListModal(new SmartFullNotificationListModal($("#modal-smartfull-notification-list"),n));n.notificationListModal().load()};n.manageAlertClick=function(t){n.selectedNotification(t);n.selectedNotification()&&n.selectedNotification().alert()&&(window.location.href="/My/SmartFull/Alerts?alertId="+n.selectedNotification().alert().id())};n.selectNotification=function(t){n.selectedNotification(t)};n.showDetails=function(t){n.selectNotification(t);n.markNotificationViewed();n.notificationModal(new SmartFullNotificationModalViewModel($("#smartfullNotificationModal")));n.notificationModal().load(n.selectedNotification().toServerModel())};n.showDetailsFromAllNotifications=function(t){n.selectNotification(t);n.markNotificationViewed()};n.markNotificationViewed=function(){$.ajax({url:"/My/SmartFull/MarkNotificationViewed",type:"POST",dataType:"json",data:JSON.stringify({id:n.selectedNotification().id()}),processData:!1,contentType:"application/json; charset=utf-8"})};n.dismissNotification=function(t){n.selectedNotification(t);n.selectedNotification().isDismissed(!0);$.ajax({url:"/My/SmartFull/MarkNotificationDismissed",type:"POST",dataType:"json",data:JSON.stringify({id:n.selectedNotification().id()}),processData:!1,contentType:"application/json; charset=utf-8"}).success(function(t){t.Success?t.Item===null||t.Item===undefined||t.Item.length!==1?PF.Modals.Generic.Show({title:"Dismiss Notification Error",description:"When dismissing notification, we didn't get back a proper response. Your notification was successfully dismissed."}):n.notifications.remove(function(t){return t.id().toLowerCase()===n.selectedNotification().id().toLowerCase()}):PF.Modals.Generic.Show({title:"Dismiss Notification Error",description:"When dismissing notification, we didn't get back a proper response. Your notification was successfully dismissed. <br/>Developers might find this info useful: "+t.Error})}).fail(function(){PF.Modals.Generic.Show({title:"Dismiss Notification Failure",description:"Unable to dismiss notification. Please try again. If this issue persists, please contact PlaceFull support at support@placefull.com."})})}},PF=PF||{};PF.User=function(){var n={LoggedIn:!1,LoginType:"Anonymous",SpaceProvider:!1,Guest:!1,UserId:"",Init:function(){r()},Edit:function(){u()},SetGuest:function(){document.cookie="guest=true";this.Guest=!0},Logout:function(n){PF.confirm({description:"Are you sure you want to log out?",confirm:function(){location.href=n||"/"}})},Login:function(n){t=n;PF.Modals.Login.Show()},LoginSuccess:function(n){f(n)},addLoginListener:function(n){i.push(n)}},t,i=[],r=function(){var t=$("#placefull-main-footer, footer");n.LoginType=t.attr("data-login-type");n.LoggedIn=n.LoginType!="NotAuthenticated";n.SpaceProvider=t.attr("data-space-provider")=="True";n.Guest=PF.getCookie("guest")=="true";n.UserId=t.attr("data-user-id")},u=function(){var t=function(){PF.showError("Edit account is not available until you reload the current page or navigate to another page.")};n.SpaceProvider?PF.Modals.EditAccount?PF.Modals.EditAccount.Show():t():PF.Modals.EditRenterAccount?PF.Modals.EditRenterAccount.Show():t()},f=function(r){var u=$("#accountDropdown"),f=n.DefaultSearchRegion=r.DefaultSearchRegion;u.parent().removeClass("none").addClass("iblock").next().hide();u.find("span").first().text(r.Email);PF.defaultRegionCookie.setCookieIfNecessary(f);n.LoggedIn=!0;n.Guest=!1;n.LoginType=r.FacebookAccessCode==null?"PlaceFull":"Facebook";n.SpaceProvider=r.SpaceProvider!=null;$(".navbar .nav-aux").hide();n.SpaceProvider?$(".navbar .btn-primary").text("My Listings").on("click",function(n){location.href="/My/Listings";n.preventDefault()}).attr("onclick",""):$(".navbar .btn-primary").hide().next().hide();PF.Modals.Login.HideModal();t&&t.call();i.forEach(function(t){t(n)});window.location.reload()};return n}();PF=PF||{};PF.Controls=PF.Controls||{};PF.Controls.GeoLookup=function(){var n=function(){return{geocode:function(n,t){n.limit=1;n.format="json";n.addressdetails=1;n.q.length==6&&(n.q=n.q.slice(0,3)+" "+n.q.slice(-3));$.get("https://nominatim.openstreetmap.org/search",n,t)}}}(),c={ZipBehavior:function(n){l(n)},GetLatLngCityState:function(n,t){s(n,t)}},i,u,f,t,e,r,l=function(n){i=n.addrEl;u=n.cityEl;f=n.stateEl;t=n.zipEl;e=n.countryEl;r=n.onLocationFound;t.on("keyup",a);i.on("change",o);t.val()&&t.val().length>=5&&o(r)},o=function(n){s(i.val()+", "+u.val()+", "+f.val()+", "+t.val(),n)},a=function(){var i=$(this),t=i.val().replace(/[^0-9]/g,"");t.length==5&&n.geocode({q:t},v)},v=function(t){var s,c,l,r,o;if(t){if(t.length<=0)return;r=t[0].address;r.country_code&&(country=r.country_code.toUpperCase());r.postcode&&(l=r.postcode);r.state&&(c=r.state);r.city&&(s=r.city);o=i.val()+" "+r.display_name;n.geocode({q:o},h);u.trigger("change");f.trigger("change");e.trigger("change")}},s=function(t,i){i&&(r=i);n==undefined&&(n=new google.maps.Geocoder);n.geocode({q:t},h)},h=function(n){var e,i,u,f,t;if(n)try{if(n.length<=0)return;t=n[0].address;t.country_code&&(e=t.country_code.toUpperCase());t.postcode&&(f=t.postcode);t.state&&(u=PF.StateMap[t.state]);t.city&&(i=t.city);r.call({lat:t.lat(),lng:t.lon(),city:i,state:u,zip:f,country:e})}catch(o){}};return c}();PF=PF||{};PF.Controls=PF.Controls||{};PF.Controls.TimeDropdowns=function(){var a={Init:function(n,t){return y(n,t),this},SetStart:function(n){return u&&c(n,t.data("options")),this},SetEnd:function(t){return u&&c(t,n.data("options")),this},GetStart:function(){return r},GetEnd:function(){return i},SetReadOnly:function(){u&&h()},SetEditable:function(n){u&&b(n)},SetStep:function(n){u&&p(n)},SetMinimumRentalTime:function(n){u&&w(n)},Reset:function(){r=i=s=v=null;i=null;e=null;u&&(t.find("option").remove(),n.find("option").remove(),t.parent(".timeHolder").find("input.start").remove(),n.parent(".timeHolder").find("input.end").remove(),t.off("change"),n.off("change"))},SetOptions:function(n){o=n}},r,i,s,v,n,t,u=!0,e,o,y=function(i,r){if(!i instanceof jQuery&&(i=$(i)),i.find("select[data-pickeroptions]").length==0){u=!1;return}e=i;i.find("select[data-pickeroptions]").each(function(n,t){$(t).parent(".timeHolder").length==0&&$(t).wrap('<div class="timeHolder"><\/div>')});$.each(i.find(".timeHolder"),function(){var u=$(this).find("select"),i=u.data("pickeroptions");u.parent(".timeHolder").css({position:"relative",marginRight:"10px"});u.css({position:"relative",padding:"0px"});u.addClass(i.type);u.parent(".timeHolder").append('<input type="text" class="'+i.type+'">');$inputEl=u.parent(".timeHolder").find("input");$inputEl.height(u.height()-7);u.css("width").indexOf("%")==-1?$inputEl.width(u.width()-30):$inputEl.width(u.width()-4+"%");$inputEl.css({position:"absolute",left:"0px",top:"24px"});i.inputCSS&&$inputEl.attr("style",$inputEl.attr("style")+i.inputCSS);i.selectCSS&&u.attr("style",u.attr("style")+i.selectCSS);i.step=i.step?i.step:30;i.readOnly=i.readOnly?i.readOnly:!1;i.change=r;u.change(k);$inputEl.change(d);$inputEl.click(function(n){$(n.currentTarget).select()});i.readOnly&&h();i.maxTime&&i.minTime&&(i.minMaxHTMLSet=!0);i.type=="start"?(t=u,t.data("options",i)):(n=u,n.data("options",i));i.minMaxHTMLSet&&(f(t),f(n))})},h=function(){n&&t&&(e.find("select[data-pickeroptions], .timeHolder input").prop("disabled",!0),$("#startDate").prop("disabled",!0))},p=function(i){t.data("options").step=i;n.data("options").step=i;f(t);f(n)},w=function(i){t.data("options").minRentalTime=i;n.data("options").minRentalTime=i},b=function(i){t.data("options").editable=i;n.data("options").editable=i},f=function(n){var i,r;if(n&&(i=n.data("options"),n&&i&&i.minTime&&i.maxTime)){var e=PF.Moment(i.minTime,["H:mm","HH:mm","hh:mm a","hh:mm A"]),u=PF.Moment(i.maxTime,["H:mm","HH:mm","hh:mm a","hh:mm A"]),o=i.minRentalTime?null:i.minRentalTime;for(i.type=="start"?u.subtract("minutes",o):e.add("minutes",o),n.find("option").remove(),r=e;r.isBefore(u)||r.isSame(u);)n.append($("<option>",{value:r.format("H:mm")}).text(r.format("h:mm a"))),r=r.add("minutes",i.step);!i.minMaxHTMLSet&&n.hasClass("end")&&f(t)}},c=function(u,e){u||(u="23:30");var o=u.getMonth?PF.Moment(u):PF.Moment(u,["H:mm","HH:mm","hh:mm a","hh:mm A"]);if(e.type=="start"){$inputEl=t.parent(".timeHolder").find("input."+e.type);$inputEl.val(o.format("h:mm a"));r=o.format("H:mm");e.minMaxHTMLSet||(t.data("options").minTime=r,n.data("options").minTime=r,t.data("options",s));f(t);t.val(o.format("H:mm"));return}$inputEl=n.parent(".timeHolder").find("input."+e.type);$inputEl.val(o.format("h:mm a"));i=o.format("H:mm");e.minMaxHTMLSet||(t.data("options").maxTime=i,n.data("options").maxTime=i);f(n);e.minRentalTime?n.val(PF.Moment(r,["H:mm","HH:mm","hh:mm a","hh:mm A"]).add("minutes",e.minRentalTime).format("H:mm")):n.val(i);n.change()},k=function(n){var t=$(n.currentTarget),u=t!=null&&t.val()!=null?PF.Moment(t.val(),"H:mm"):null;u&&(options=t.data("options"),t.hasClass("end")?i=u.format("H:mm"):r=u.format("H:mm"),$inputEl=t.parent(".timeHolder").find("input."+options.type),$inputEl.val(u.format("h:mm a")),l(t),typeof options.change=="function"&&options.change.call(null,n))},d=function(u){var f=$(u.currentTarget),o,e=PF.Moment(f.val(),["hh:mm a","hh:mm A"]),s;options=t.data("options");f.hasClass("end")?(options=n.data("options"),o=i,i=e.format("H:mm")):o=r;$selectEl=f.parent(".timeHolder").find("select."+options.type);s=$selectEl.find("option[value='"+e.format("H:mm")+"']").length!==0;s||options.editable?($selectEl.val(e.format("H:mm")),$selectEl.change(),f.val(e.format("h:mm a")),l($selectEl),typeof options.change=="function"&&options.change.call(null,u)):f.val(PF.Moment(o,["H:mm"]).format("h:mm a"));f.hasClass("end")?i=PF.Moment(f.val(),["hh:mm a","hh:mm A"]).format("H:mm"):r=PF.Moment(f.val(),["hh:mm a","hh:mm A"]).format("H:mm")},l=function(u){var f,e;o&&o.noAdjustTime||(f=u.data("options"),$inputEl=u.parent(".timeHolder").find("input."+f.type),datetime=u.val()?PF.Moment(u.val(),["H:mm"]):PF.Moment($inputEl.val(),["h:mm a"]),datetime=g(datetime,f),$otherSelect=f.type=="start"?n:t,$otherTimeInput=$($otherSelect.parent(".timeHolder").find("input")),$otherTimeInput.length!=0)&&(e=PF.Moment($otherTimeInput.val(),["hh:mm a","hh:mm A"]),e.isBefore(datetime.add("minutes",f.minRentalTime))&&f.type=="start"&&($otherTimeInput.val(datetime.format("h:mm a")),$otherSelect.val(datetime.format("H:mm")),i=datetime.format("H:mm")),e.isAfter(datetime.subtract("minutes",f.minRentalTime*2))&&f.type=="end"&&($otherTimeInput.val(datetime.format("h:mm a")),$otherSelect.val(datetime.format("H:mm")),r=datetime.format("H:mm")))},g=function(n,t){return n.hour()==0&&n.minute()==0&&t.type=="end"&&n.add("d",1),n};return a};PF=PF||{};PF.Controls=PF.Controls||{};PF.Controls.ResultsMap=function(){var n,t,i,u={Init:function(n){return f(n),this},SetMarkers:function(n){r(n)},SetMarker:function(n){r([n])},ClearMarkers:function(){},SetCenter:function(t,i){n.SetView(L.latLng(t,i))},SetViewport:function(){},Resize:function(){t.height(t.width()*.75);n.invalidateSize()},GeoInfo:function(){}},f=function(r){var u,f;r.markerClicked&&(i=r.markerClicked);u=r?r.mapEl[0]:$("#map")[0];t=$(u);f=t.parent().height();t.height(f?f:200);center=r.center?r.center:L.latLng(47.599362,-122.333282);n=L.map(u).setView(center,r.zoom?r.zoom:13);L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:'&copy; <a href="http://osm.org/copyright">OpenStreetMap<\/a> contributors'}).addTo(n)},r=function(t){t.map(function(t){L.marker(t.position).addTo(n).bindPopup("<h3>"+t.title+"<\/h3><br />"+t.html).on("click",function(){i!=undefined&&i.call();n.setView(t.position,15)})})};return u}()