\n";r=setTimeout(function(){d(o,l,n)},100);if(n){n.asynchUpdaterTimeoutId=r}}else{p="There's no longer any status being reported, so it looks like we're done!";enableDialogButtons()}i.innerHTML=p}}catch(f){}}function asynchUpdateWithProcessStatus(e,t,a){jsrsExecute(rsCallbackGetStatus,"Admin_GetStatus",[escape(e)],enableDialogButtons,{processKey:e,strStatusSectionId:t,fnAsynchUpdate:asynchUpdateWithProcessStatus,objAsynchUpdaterTimeoutHolder:a})}function showChangePasswordDialog(){var e="frmChangePW",t=new ClientDialogBuilder({formId:e,formTitle:"Change Password",okButtonDisplayText:"Save",focusFieldName:"txtOldPW",focusFieldOnMobile:1,fnSubmit:submitChangePassword});t.addTextFieldRow("txtOldPW",{rawLabel:"Old Password",isPasswordField:1,maxLength:80});t.addTextFieldRow("txtNewPW",{rawLabel:"New Password",isPasswordField:1,maxLength:80});t.addTextFieldRow("txtConfirmPW",{rawLabel:"Confirm Password",isPasswordField:1,maxLength:80});t.addTextFieldRow("txtUserName",{fieldValue:g_username,hideRow:1});t.showClientDialog()}function submitEditOrAddTaxRate(){var e="frmNewTaxRate",t=getObj(e),a=mjtElemData(t,"taxRateId"),i=new FormValidator,o={taxRateId:a||"",taxRateName:t.txtName.value,taxRatePercent:trim(t.txtRate.value),state:trim(t.txtState.value)};if(!i.CSValidateRequiredField(t.txtName,"Please enter a Name")){return}if(!i.CSValidateNumberField(t.txtRate,"Rate",false)){return}jsrsExecuteWithErrorP(a?"Admin2_UpdateTaxRate2":"Admin2_CreateTaxRate2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,a?"Creating Tax Rate":"Updating Tax Rate",o)}function carefullyDisplayEventLog(e,t){hideDialogP({callback:function(){window.location=pageEventLog+e+"/"+t}})}function carefullyDisplayTaxRateEventLog(e){carefullyDisplayEventLog(EventObjectType_Enum.eotTaxRate,e)}function carefullyDisplayStateTaxAgencyEventLog(e){carefullyDisplayEventLog(EventObjectType_Enum.eotStateTaxAgency,e)}function carefullyDisplayEmailTemplateEventLog(e){carefullyDisplayEventLog(EventObjectType_Enum.eotEmailTemplate,e)}function carefullyDisplayProductEventLog(e){carefullyDisplayEventLog(EventObjectType_Enum.eotProduct,e)}function carefullyDisplayPricingStructureEventLog(e){carefullyDisplayEventLog(EventObjectType_Enum.eotPricingStructure,e)}function carefullyDisplayDatabasePricingStructureEventLog(e){carefullyDisplayEventLog(EventObjectType_Enum.eotDatabasePricingStructure,e)}function carefullyDisplayUserEventLog(e){hideDialogP({callback:function(){window.location=pageUserEventLog+e}})}function showTaxRateDialog(e,t,a,i){var o="frmNewTaxRate",n,r=jtcrmHasAccess(JTCRMSecuredObject_Enum.soTaxRates,AccessRight_Enum.mjtARDelete),l=new ClientDialogBuilder({formId:o,formTitle:e?"Edit Tax Rate":"New Tax Rate",focusFieldName:"txtName",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitEditOrAddTaxRate()"}),fnSubmit:submitEditOrAddTaxRate,arrExtraHeaderButtons:e?[r?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedOnClickJS:"confirmDeleteTaxRate("+e+",unescape('"+escape(t)+"'))",doubleQuoteEncodedTitle:"Delete Tax Rate"}):"",r?'':"",cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayTaxRateEventLog("+e+")"})]:0});l.addTextFieldRow("txtName",{rawLabel:"Name",mnemonicChar:"n",fieldValue:t||"",maxLength:80});l.addTextFieldRow("txtRate",{rawLabel:"Rate",mnemonicChar:"r",fieldValue:""+(a||0),maxLength:8,isNumber:1});l.addTextFieldRow("txtState",{rawLabel:"State",mnemonicChar:"t",fieldValue:i||"",maxLength:80});n=l.showClientDialog();if(n){mjtElemData(n,"taxRateId",e)}}function showNewTaxRateDialog(){showTaxRateDialog()}function doDeleteStateTaxAgency(e){jsrsExecuteWithErrorP("Admin2_DeleteStateTaxAgency",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting State Tax Agency",{stateTaxAgencyId:e.stateTaxAgencyId})}function confirmDeleteStateTaxAgency(e,t){hideDialog();displaySimpleConfirmationDialog(doDeleteStateTaxAgency,'Are you sure you want to delete "'+htmlEncode(t)+'"',"Delete State Tax Agency",{stateTaxAgencyId:e,stateTaxAgencyName:t})}function submitEditOrAddStateTaxAgency(){var e="frmAgency",t=getObj(e),a=mjtElemData(t,"stateTaxAgencyId"),i=new FormValidator,o=t.cboState,n=trim(o.value),r={stateTaxAgencyId:a||"",stateTaxAgencyName:trim(t.txtName.value),state:n},l=i.CSValidateRequiredField(t.txtName,"Please enter a Name");if(!l){return}if(!n){showInfoDialog('
Please select a state
',"Missing State",1,o.name);return}jsrsExecuteWithErrorP(a?"Admin2_UpdateStateTaxAgency":"Admin2_CreateStateTaxAgency",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,a?"Creating State Tax Agency":"Updating State Tax Agency",r)}function rsCallbackGetStatesForStateTaxAgencyDialog(e,t){var a=t.originalOptions,i=a.params||{},o=e.arrStateNames,n=o.map(function(e){return{cboValue:e,rawContent:e}}),r="frmAgency",l,d=i.id,s=i.name,u=i.state,c=jtcrmHasAccess(JTCRMSecuredObject_Enum.soTaxRates,AccessRight_Enum.mjtARDelete),m=new ClientDialogBuilder({formId:r,formTitle:d?"Edit State Tax Agency":"New State Tax Agency",focusFieldName:"txtName",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitEditOrAddStateTaxAgency()"}),fnSubmit:submitEditOrAddStateTaxAgency,arrExtraHeaderButtons:d?[c?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedOnClickJS:"confirmDeleteStateTaxAgency("+d+","+"unescape('"+escape(s)+"'))",doubleQuoteEncodedTitle:"Delete Tax Rate"}):"",c?'':"",cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayStateTaxAgencyEventLog("+d+")"})]:0});m.addTextFieldRow("txtName",{rawLabel:"Agency Name",mnemonicChar:"n",fieldValue:s||"",maxLength:80});if(!d){n.unshift({cboValue:"",rawContent:"-Select State-"})}m.addDropdown({fieldName:"cboState",rawLabel:"State",arrAvailableOptions:n,objSelectedValue:u?{cboValue:u,rawContent:u}:null});l=m.showClientDialog();if(l){mjtElemData(l,"stateTaxAgencyId",d)}}function showStateTaxAgencyDialog(e){jsrsExecuteWithErrorP("Admin2_GetStatesWithTaxRates",rsCallbackHandleStandardJSONResponse,"Retrieving New Product Info",{excludeStatesWithAssignedStateTaxAgency:1},{fnOnSuccess:rsCallbackGetStatesForStateTaxAgencyDialog,params:e})}function submitTaxJarTransReportOptions(){var e="frmOptions",t=getObj(e),a=new FormValidator,i=pageTaxJarTransReport,o=t.dtFrom,n=t.dtTo,r=t.txtPageSize,l=trim(r.value),d=a.CSValidateIntegerFieldP({field:r,label:"Page Size",isNullable:true,minValue:1,maxValue:2e3})&&a.CSValidateDateFieldP({field:o,label:"From"})&&a.CSValidateDateFieldP({field:n,label:"To"});if(!d){return}if(l){i+="&pageSize="+l}i+="&from="+trim(getDateForUrlParam(o.value));i+="&to="+trim(getDateForUrlParam(n.value));hideDialog();window.location=i;displayTimedMessage("Reloading page...")}function showTaxJarTransReportOptions(e){var t="frmOptions",a=new ClientDialogBuilder({formId:t,formTitle:"Tax Jar Transactions Report Options",focusFieldName:"dtFrom",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitTaxJarTransReportOptions()"}),fnSubmit:submitTaxJarTransReportOptions});a.addDatePickerRow(t,"dtFrom",{rawLabel:"From",strValue:e.fromDate,autofocus:1});a.addDatePickerRow(t,"dtTo",{rawLabel:"To",strValue:e.toDate});a.addTextFieldRow("txtPageSize",{rawLabel:"Rows per Page",fieldValue:""+e.pageSize,mnemonicChar:"r",maxLength:10,styleWidth:"7em",isNumber:1});a.showClientDialog()}function submitEditOrAddProduct(){var e="frmNewProduct",t=getObj(e),a=new FormValidator,i=t.cboEdition.options[t.cboEdition.selectedIndex].value,o=i!=="",n=t.cboTerm.options[t.cboTerm.selectedIndex].value,r=t.cboPricingStructure.options[t.cboPricingStructure.selectedIndex].value,l=r!==""?parseInt(r,10):null,d=t.priceGenerations.options[t.priceGenerations.selectedIndex].value,s=d!==""?parseInt(d,10):null,u=s===g_flexPricingProductGenerationId,c=t.productTypes.options[t.productTypes.selectedIndex].value,m=c!==""?parseInt(c,10):null,p=m===CRMProductType_Enum.crmptCounterGo,f=m===CRMProductType_Enum.crmptNVInventory,b=mjtElemData(t,"productId"),g={productId:b||"",productName:t.txtName.value,jtUserCount:trim(t.txtJTCount.value),cgUserCount:trim(t.txtCGCount.value),nvUserCount:trim(t.txtNVCount.value),fileSize:trim(t.txtFileSize.value),editionId:i,term:n,price:trim(t.txtPrice.value),notes:cdGetExpandingTextFieldValue("txtNotes"),isDiscountable:t.chkDiscountable.checked?1:0,isJobTrackerSubscription:t.chkJTSubscription.checked?1:0,displayedProductGroupId:t.cboDisplayGroup.options[t.cboDisplayGroup.selectedIndex].value,priceGenerations:s,pricingStructureId:l,productType:m,isDeprecated:t.chkDeprecated&&t.chkDeprecated.checked?1:0};if(!a.CSValidateRequiredField(t.txtName,"Please enter a Name")){return}if(!a.CSValidateNumberField(t.txtJTCount,"Job Tracker User Count",false)){return}if(!a.CSValidateNumberField(t.txtCGCount,"CounterGo User Count",false)){return}if(!a.CSValidateNumberField(t.txtNVCount,"Inventory User Count",false)){return}if(!a.CSValidateNumberField(t.txtFileSize,"File Size",false)){return}if(u){if(!l&&(p||f||o)){showInfoDialog("Please select a pricing structure.","Select Pricing Structure",true,"cboPricingStructure");return}}else{if(!a.CSValidateNumberField(t.txtPrice,"Price",false)){return}}jsrsExecuteWithErrorP(b?"Admin2_UpdateProduct2":"Admin2_CreateProduct2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,b?"Creating Product":"Updating Product",g)}function buildAnOption(e,t,a,i,o){var n=i||a==e;if(n&&o){o.didSelect=1}return'"}function buildDropdownContent(e){var t=e.name,a=e.valueLookup,i=e.textLookup,o=e.selectedValue,n=e.arrValues,r=e.onChangeCode?' onchange="'+e.onChangeCode+'"':"",l=e.disabled?" disabled":"",d,s="";for(d=0;d"+s+""}function buildDropdownRow(e){return cdBuildReadOnlyFieldRowP({labelHTML:e.label,valueHTML:buildDropdownContent({name:e.name,valueLookup:e.valueLookup,textLookup:e.textLookup,selectedValue:e.selectedValue,arrValues:e.values,onChangeCode:e.onChangeCode,disabled:e.disabled}),rowId:e.rowId,valueCellId:e.valueCellId})}var MAX_VALUE_PRICING_STRUCTURE_MIN_USERS=99,MIN_VALUE_PRICING_STRUCTURE_MIN_USERS=2;function submitPricingStructureDialog(){var e="frmPricingStructure",t=getObj(e),a=mjtElemData(t,"pricingStructureId"),i=new FormValidator,o=t.cboProductType.options[t.cboProductType.selectedIndex].value,n=o?parseInt(o,10):null,r=t.cboEdition.options[t.cboEdition.selectedIndex].value,l=r?parseInt(r,10):null,d=t.chkIsInactive&&t.chkIsInactive.checked?1:0,s=trim(t.txtTier2StartUserCount.value),u=s!==""?parseInt(s,10):null,c=trim(t.txtTier2PerUserPrice.value),m=c!==""?parseFloat(c):null,p=trim(t.txtMinUserCount.value),f=p?parseInt(p,10):null,b=n===CRMProductType_Enum.crmptCounterGo,g=n===CRMProductType_Enum.crmptNVInventory,C={pricingStructureId:a,isInactive:d,productTypeId:n,editionId:l,editionPrice:t.txtEditionPrice.value,additionalUserPrice:t.txtAdditionalUserPrice.value,tier2StartUserCount:u,tier2PerUserPrice:m,minUserCount:f||""},D={minValue:0,maxDecimalPlaces:2},h=[{field:t.txtAdditionalUserPrice,label:"Additional User Price"},{field:t.txtTier2PerUserPrice,label:"Tier 2 Per-User Price",isNullable:true},{field:t.txtTier2StartUserCount,label:"Tier 2 Start",isNullable:true,maxDecimalPlaces:0},{field:t.txtMinUserCount,label:"Minimum # of Users",isNullable:true,maxDecimalPlaces:0,minValue:MIN_VALUE_PRICING_STRUCTURE_MIN_USERS,maxValue:MAX_VALUE_PRICING_STRUCTURE_MIN_USERS}];if(!n){showInfoDialog("Please select your product type.","Select Product Type",true,"cboProductType");return}for(var w in h){Object.assign(D,h[w]);if(!i.CSValidateNumberFieldP(D)){return}}if(m&&!u){showInfoDialog('
Please set the Tier 2 Start User # or clear the Tier 2 Per-User Price
Please set the Tier 2 Per-User Price (which could be 0) or clear the Tier 2 Start User #
',"Invalid Tier 2 Price Settings",true,t.txtTier2StartUserCount);return}jsrsExecuteWithErrorP(a?"Admin2_UpdatePricingStructureInactiveInd":"Admin2_CreatePricingStructure",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Saving Pricing Structure",C)}function productTypeSupportsEdition(e){return e===CRMProductType_Enum.crmptJobTracker||e===CRMProductType_Enum.crmptSystemize}function showHideApplyPricingStructureEditionId(e){var t=e?e:"frmPricingStructure",a=getObj(t),i=a.cboProductType,o=i[i.selectedIndex].value,n=parseInt(o,10),r=getObj("trEditionSelector"),l=getObj("trEditionPrice");if(productTypeSupportsEdition(n)){r.style.display="";if(l){l.style.display=""}}else{r.style.display="none";if(l){l.style.display="none"}}}function getEditionOptions(){return[{editionId:"",editionName:"-None-"},{editionId:Edition_Enum.edBasic,editionName:"Basic"},{editionId:Edition_Enum.edStandard,editionName:"Standard"},{editionId:Edition_Enum.edInventory,editionName:"Inventory"},{editionId:Edition_Enum.edEnterprise,editionName:"Enterprise"}]}function buildEditionDropdownRow(e){return buildDropdownRow({name:e.name,label:e.label,valueLookup:"editionId",textLookup:"editionName",values:getEditionOptions(),selectedValue:e.selectedValue,onChangeCode:e.onChangeCode,rowId:e.rowId,disabled:e.disabled})}function removeJobTrackerFromProductArray(e){var t=e,a=undefined;for(var i in t){if(t[i].productTypeId===CRMProductType_Enum.crmptJobTracker){a=i;break}}if(a!==undefined){t.splice(a,1)}return t}function showPricingStructureDialog(t){var e=1e5,a=1,i=t.pricingStructureId,o=t.editionPrice,n=t.additionalUserPrice,r=t.tier2StartUserCount,l=t.tier2PerUserPrice,d=t.pricingStructureName,s=t.minUserCount,u=removeJobTrackerFromProductArray(t.arrProductTypes),c="6em",m="frmPricingStructure",p=jtcrmHasAccess(JTCRMSecuredObject_Enum.soProducts,AccessRight_Enum.mjtARDelete),f=new ClientDialogBuilder({formId:m,formTitle:(i?"Edit":"Create")+" Pricing Structure",focusFieldName:"cboProductType",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitPricingStructureDialog()"}),fnSubmit:submitPricingStructureDialog,arrExtraHeaderButtons:i?[p?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Pricing Structure",doubleQuoteEncodedOnClickJS:"confirmDeletePricingStructure("+i+", unescape('"+escape(d)+"'))"}):null,p?'':null,cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayPricingStructureEventLog("+i+")"})]:0});f.addDropdown({fieldName:"cboProductType",rawLabel:"Product Type",arrAvailableOptions:u.map(function(e){return{cboValue:e.productTypeId,rawContent:e.productTypeName,isSelectedOption:e.productTypeId===t.productTypeId}}),onClickChangeJS:"showHideApplyPricingStructureEditionId()",disableDropdown:i,fieldClasses:"clsSkipFormNormalization",additionalCellClasses:"clsNarrowField"});f.addDropdown({fieldName:"cboEdition",rawLabel:"Edition",arrAvailableOptions:getEditionOptions().map(function(e){return{cboValue:e.editionId,rawContent:e.editionName,isSelectedOption:e.editionId===t.editionId}}),onClickChangeJS:"showHideApplyPricingStructureEditionId()",disableDropdown:i,rowId:"trEditionSelector",fieldClasses:"clsSkipFormNormalization"});f.addTextFieldRow("txtEditionPrice",{rawLabel:"Base Price ($)",mnemonicChar:"b",fieldValue:""+o,placeholder:"e.g. 600",strStyleWidth:c,isNumber:true,minValue:0,maxValue:e,step:a,rowId:"trEditionPrice",disabled:i});f.addTextFieldRow("txtAdditionalUserPrice",{rawLabel:"Additional User Price ($)",mnemonicChar:"a",fieldValue:""+n,placeholder:"e.g. 50",strStyleWidth:c,isNumber:true,minValue:0,maxValue:e,step:a,disabled:i});f.addTextFieldRow("txtTier2StartUserCount",{rawLabel:"Tier 2 Starts with User #",mnemonicChar:"t",fieldValue:""+(r||""),placeholder:"(optional)",strStyleWidth:c,isNumber:true,minValue:0,maxValue:1e3,step:a,disabled:i});f.addTextFieldRow("txtTier2PerUserPrice",{rawLabel:"Tier 2 Per-User Price ($)",mnemonicChar:"p",fieldValue:""+(l||""),placeholder:"(optional)",strStyleWidth:c,isNumber:true,minValue:0,maxValue:e,step:a,disabled:i});f.addTextFieldRow("txtMinUserCount",{rawLabel:"Minimum # of Users",mnemonicChar:"m",fieldValue:""+(s||""),placeholder:"(optional)",strStyleWidth:c,isNumber:true,minValue:MIN_VALUE_PRICING_STRUCTURE_MIN_USERS,maxValue:MAX_VALUE_PRICING_STRUCTURE_MIN_USERS,disabled:i});if(i){f.addCheckboxRow_deprecated("chkIsInactive",{rawLabel:"Inactive",mnemonicChar:"i",checked:t.isInactive})}var b=f.showClientDialog();if(b){mjtElemData(b,"pricingStructureId",i);showHideApplyPricingStructureEditionId()}}function refreshPricingStructureSelector(e){var t=getObj(e.strFormId),a=getObj(e.pricingStructureValueCellId),i=e.arrPricingStructures,o=e.pricingStructureSelectorName,n=e.selectedProductTypeId,r=e.selectedEditionId,l=t.cboPricingStructure,d=l[l.selectedIndex],s=d?d.value:null,u=s===null?null:parseInt(s,10),c=[i[0]];for(var m in i){var p=i[m],f=p.productTypeId===n,b=isNaN(r)&&!p.editionId,g=p.editionId===r,C=!p.isInactive||p.pricingStructureId===u;if(C&&f&&(b||g)){c.push(p)}}a.innerHTML=buildDropdownContent({name:o,valueLookup:"pricingStructureId",textLookup:"pricingStructureName",selectedValue:s,arrValues:c})}function showHideProductFlexPricing(){var e="frmNewProduct",t=getObj(e),a=mjtElemData(t,"arrPricingStructures"),i=JSON.parse(a),o=t.priceGenerations,n=o[o.selectedIndex].value,r=parseInt(n,10),l=r===g_flexPricingProductGenerationId,d=t.productTypes,s=d[d.selectedIndex].value,u=parseInt(s,10),c=t.cboEdition,m=c[c.selectedIndex].value,p=parseInt(m,10),f=getObj("trPrice"),b=getObj("trPricingStructure");if(l){var g={strFormId:e,selectedProductTypeId:u,selectedEditionId:p,arrPricingStructures:i,pricingStructureValueCellId:"tdPricingStructure",pricingStructureSelectorName:"cboPricingStructure"};refreshPricingStructureSelector(g);f.style.display="none";b.style.display=""}else{f.style.display="";b.style.display="none"}}function showProductDialog(e){var t=e.id,a=e.name,i=e.price,o=e.jtUserCount,n=e.cgUserCount,r=e.nvUserCount,l=e.fileSize,d=e.editionId,s=e.term,u=e.isDeprecated,c=e.isDiscountable,m=e.isJTSubscription,p=e.notes,f=e.displayedProductGroupId,b=e.displayedProductGroupName,g=e.priceGenerationId,C=e.priceGenerations,D=e.productTypeId,h=e.productTypes,w=e.pricingStructures,T=e.pricingStructureId;if(!t){u=1}var S="",y="",I={};y+=buildAnOption(DisplayedProductGroup_Enum.dpgSubscription,"Subscription",""+f,0,I);y+=buildAnOption(DisplayedProductGroup_Enum.dpgJTDownload,"JT Download",""+f,0,I);y+=buildAnOption(DisplayedProductGroup_Enum.dpgLegacy,"Legacy",""+f,0,I);if(f&&!I.didSelect){y+=buildAnOption(""+f,"Unknown Group: ["+htmlEncode(b)+"]",""+f,0,I)}S+=buildAnOption(Term_Enum.trmMonthly,"Monthly",s);S+=buildAnOption(Term_Enum.trmQuarterly,"Quarterly",s);S+=buildAnOption(Term_Enum.trmAnnual,"Annual",s);if(g===""){g=-1}var x="frmNewProduct",v,P=jtcrmHasAccess(JTCRMSecuredObject_Enum.soProducts,AccessRight_Enum.mjtARCreate),R=jtcrmHasAccess(JTCRMSecuredObject_Enum.soProducts,AccessRight_Enum.mjtARDelete),E=cdBuildTextFieldRowP("txtName","Name",{fieldValue:a||"",maxlength:80})+buildDropdownRow({name:"productTypes",label:"Product Type",valueLookup:"productTypeId",textLookup:"productTypeName",selectedValue:D,values:h,onChangeCode:"showHideProductFlexPricing()"})+cdBuildReadOnlyFieldRowP({rawLabel:"Display Group",valueHTML:'"})+buildEditionDropdownRow({name:"cboEdition",label:"Edition",selectedValue:d,onChangeCode:"showHideProductFlexPricing()"})+cdBuildReadOnlyFieldRowP({rawLabel:"Term",valueHTML:'"});if(t){E+=cdBuildCheckboxRowP_deprecated("chkDeprecated","Deprecated",{checked:u})}E+=cdBuildCheckboxRowP_deprecated("chkDiscountable","Discountable",{checked:c})+cdBuildCheckboxRowP_deprecated("chkJTSubscription","JT Subscription",{checked:m})+cdBuildTextFieldRowP("txtJTCount","Systemize User Count",{fieldValue:(o||"0")+"",maxLength:8})+cdBuildTextFieldRowP("txtCGCount","CounterGo User Count",{fieldValue:(n||"0")+"",maxLength:8})+cdBuildTextFieldRowP("txtNVCount","Inventory User Count",{fieldValue:(r||"0")+"",maxLength:8})+cdBuildTextFieldRowP("txtFileSize","File Size MB",{fieldValue:(l||"0")+"",maxLength:8})+buildDropdownRow({name:"priceGenerations",label:"Price Generation",valueLookup:"priceGenerationId",textLookup:"priceGenerationName",selectedValue:g,values:C,onChangeCode:"showHideProductFlexPricing()"})+buildDropdownRow({name:"cboPricingStructure",label:"Default Pricing Structure",valueLookup:"pricingStructureId",textLookup:"pricingStructureName",selectedValue:T,values:w,rowId:"trPricingStructure",valueCellId:"tdPricingStructure"})+cdBuildTextFieldRowP("txtPrice","Price",{fieldValue:(i||"0")+"",maxLength:8,rowId:"trPrice"})+cdBuildExpandingTextFieldRowsP("txtNotes","Description",{value:p});v=showDialogP(E,x,{formTitle:(t?"Edit":"New")+" Product",focusFieldName:"txtName",arrExtraHeaderButtons:t?[R?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Product",doubleQuoteEncodedOnClickJS:"confirmDeleteProduct("+t+",unescape('"+escape(a)+"'),1)"}):null,R?'':null,P?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowDuplicateDocument,doubleQuoteEncodedTitle:"Duplicate Product",doubleQuoteEncodedOnClickJS:"showDuplicateProductDialog("+t+",unescape('"+escape(a)+"'),1)"}):null,cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayProductEventLog("+t+")"})]:0,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitEditOrAddProduct()"}),contextDetailOrFnSubmit:{fnSubmit:submitEditOrAddProduct,callbackData:{id:t}}});if(v){mjtElemData(v,"productId",t);mjtElemData(v,"arrPricingStructures",JSON.stringify(w));showHideProductFlexPricing()}}function showEditProductDialog(e,t){jsrsExecuteWithErrorP("Admin2_GetProductDetails",rsCallbackHandleStandardJSONResponse,'Retrieving info for product, "'+htmlEncode(t)+'"...',{productId:e},{fnOnSuccess:showProductDialog})}function rsCallbackDuplicateProduct(e){var t=e;t.name="Copy of "+e.name;t.id=null;showProductDialog(t)}function showDuplicateProductDialog(e,t,a){var i=function(){jsrsExecuteWithErrorP("Admin2_GetProductDetails",rsCallbackHandleStandardJSONResponse,'Retrieving info for product, "'+htmlEncode(t)+'"...',{productId:e},{fnOnSuccess:rsCallbackDuplicateProduct})};if(a){hideDialogP({callback:i})}else{i()}}function rsCallbackShowNewPricingStructureDialog(e){var t={arrProductTypes:e};showPricingStructureDialog(t)}function rsCallbackShowNewProduct(e){var t={productTypes:e.arrProductTypes,priceGenerations:e.arrPriceGenerations,pricingStructures:e.arrPricingStructures};showProductDialog(t)}function showNewPricingStructureDialog(){jsrsExecuteWithErrorP("Admin2_GetNewPricingStructureInfo",rsCallbackHandleStandardJSONResponse,"Retrieving New Pricing Structure Info",{},{fnOnSuccess:rsCallbackShowNewPricingStructureDialog})}function showEditPricingStructureDialog(e){jsrsExecuteWithErrorP("Admin2_GetPricingStructure",rsCallbackHandleStandardJSONResponse,"Retrieving Pricing Structure Info",{pricingStructureId:e},{fnOnSuccess:showPricingStructureDialog})}function showNewProductDialog(){jsrsExecuteWithErrorP("Admin2_GetNewProductInfo2",rsCallbackHandleStandardJSONResponse,"Retrieving New Product Info",{},{fnOnSuccess:rsCallbackShowNewProduct})}function buildOptionHTML(e,t,a){var i="";if(t+""===a+""){i=' selected="selected"'}return'"}function updatePricingStructureOptions(){var e="frmSettings",t=getObj(e),a=pagePricingStructure,i=t.cboDeprecationStatus.value;if(i!=DeprecationStatus_Enum.dsNonDeprecatedOnly){a+="&"+pageFilterDeprecationStatus+"="+i}hideDialog();window.location=a}function updateProductSettingsOptions(){var e="frmSettings",t=getObj(e),a=pageSystemSettingsProducts,i=t.cboEdition.value,o=t.cboSubscriptionStatus.value,n=t.cboDeprecationStatus.value,r=mwGetCompoundSelectionValueForBase(t,"terms");if(i!=EditionFilter_Enum.efAny){a+="&edFilt="+i}if(o!=SubscriptionStatus_Enum.ssAny){a+="&ssFilt="+o}if(n!=DeprecationStatus_Enum.dsNonDeprecatedOnly){a+="&dsFilt="+n}if(r){a+="&trmFilt="+r}hideDialog();window.location=a}function getProductTermList(){if(!g_arrProductTerms){g_arrProductTerms=[{termId:Term_Enum.trmMonthly,termName:"Monthly"},{termId:Term_Enum.trmQuarterly,termName:"Quarterly"},{termId:Term_Enum.trmAnnual,termName:"Annual"}]}return{arrTerms:g_arrProductTerms}}function showPricingStructureOptions(e){var t=e.deprecationStatus||DeprecationStatus_Enum.dsNonDeprecatedOnly,a="frmSettings",i=new ClientDialogBuilder({formId:a,formTitle:"Pricing Structure Options",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"updatePricingStructureOptions()"}),focusFieldName:"cboDeprecationStatus",focusFieldOnMobile:1,fnSubmit:updatePricingStructureOptions});i.addFlexibleFieldRow({rawLabel:"Deprecation Status",valueHTML:'"});i.showClientDialog()}function showProductSettingsOptions(e){var t=e.edition||EditionFilter_Enum.efAny,a=e.subscriptionStatus||SubscriptionStatus_Enum.ssAny,i=e.deprecationStatus||DeprecationStatus_Enum.dsAny,o="frmSettings",n=new ClientDialogBuilder({formId:o,formTitle:"Products Options",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"updateProductSettingsOptions()"}),focusFieldName:"cboEdition",focusFieldOnMobile:1,fnSubmit:updateProductSettingsOptions});n.addFlexibleFieldRow({rawLabel:"Deprecation Status",valueHTML:'"});n.addFlexibleFieldRow({rawLabel:"Filter Edition",valueHTML:'"});n.addFlexibleFieldRow({rawLabel:"Subscription Status",valueHTML:'"});n.addCompoundSelectionFieldRowP({fieldNameBase:"terms",autofocus:1,whatSingular:"Term",arrSelectedIds:e.arrTermIds,arrObjects:getProductTermList().arrTerms,fnRSCallSubstitute:getProductTermList,objectArrayName:"arrTerms",simpleIdPropertyName:"termId",simpleNameDisplayPropertyName:"termName"});n.showClientDialog()}function showUserPreferencesDialog(){showInfoDialog("TODO: showUserPreferencesDialog","showUserPreferencesDialog")}function rsCallbackGetDatabaseItemAssociationDialog(e,a){var t=e.arrDatabases,i=t.length,o=i===1?"":"s",n=false,r,l=new ClientDialogBuilder({formTitle:a.originalOptions.dialogTitle}),d=new MWClientTable({noDataMessage:"No "+a.originalOptions.dialogTitle,fnAdditionalRowAttrs:function(e){var t=JSON.parse(JSON.stringify(e));if(a.originalOptions.itemDetailIsDate){t.itemDetail=parseDateString(t.itemDetail)}return"data-rowData='"+escape(JSON.stringify(t))+"'"}});l.addFlexibleFieldRow({rawLabel:a.originalOptions.itemLabel,rawValue:a.originalOptions.itemName});d.addColumn(new MWColumn({columnName:"Customer",simpleDisplayColumnPropertyName:"customerName",sortInfo:{}}));d.addColumn(new MWColumn({columnName:"Database",simpleDisplayColumnPropertyName:"subdomain",sortInfo:{},fnBuildCellLinkDetail:function(e,t,a,i){return mwBuildSimpleLink(pageDatabaseDetail+e.databaseId,1)}}));for(var s in t){var u=parseInt(t[s].itemDetail,10);if(isNaN(u)||u>1){n=true;break}}if(n){d.addColumn(new MWColumn({columnName:a.originalOptions.itemDetailColumnName,simpleDisplayColumnPropertyName:"itemDetail",sortInfo:{isNumber:!a.originalOptions.itemDetailIsDate},additionalCellClasses:"rightAlign"}))}r="
"+d.buildTableForArray(t)+"
";if(i>0){r+='
('+i+" Database"+o+")
"}l.addFlexibleRow({valueHTML:r});l.showClientDialog()}function showDBsWithSubscriptionDialog(e,t){jsrsExecuteWithErrorP("Admin2_GetDBsWithSubscription2",rsCallbackHandleStandardJSONResponse,'Retrieving info for product, "'+t+'"',{productId:e},{fnOnSuccess:rsCallbackGetDatabaseItemAssociationDialog,dialogTitle:"Active Subscriptions",itemDetailColumnName:"# of Subscriptions",itemLabel:"Product",itemName:t})}function showDBsWithPricingStructureDialog(e,t){jsrsExecuteWithErrorP("Admin2_GetDatabasesWithPricingStructureApplied",rsCallbackHandleStandardJSONResponse,"Retrieving databases",{pricingStructureId:e},{fnOnSuccess:rsCallbackGetDatabaseItemAssociationDialog,dialogTitle:"Databases Applying Pricing Structure",itemDetailColumnName:"Effective Date",itemLabel:"Pricing Structure",itemName:t,itemDetailIsDate:true})}function showDBsWithTaxRateDialog(e,t){jsrsExecuteWithErrorP("Admin2_GetDatabasesWithTaxRate",rsCallbackHandleStandardJSONResponse,"Retrieving databases",{taxRateId:e},{fnOnSuccess:rsCallbackGetDatabaseItemAssociationDialog,dialogTitle:"Databases with Tax Rate",itemDetailColumnName:"Next Invoice Amount",itemLabel:"Tax Rate",itemName:t})}function submitUpdateOrCreateRole(){var e="editRole",t=getObj(e),a=mjtElemData(t,"roleId"),i=t.txtRoleName,o=new FormValidator;if(!o.CSValidateRequiredField(i,"Please enter a Role Name")){return}jsrsExecuteWithErrorP(a?"Admin2_UpdateRole":"Admin2_CreateRole",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Getting Role Info",{roleId:a||"",roleName:trim(i.value),roleDescription:cdGetExpandingTextFieldValue("txtRoleDescription"),securityProfile:computeSecurityProfile({minSecuredObjectId:JTCRMSecuredObject_Enum.mjtMinSecuredObjectId,maxSecuredObjectId:JTCRMSecuredObject_Enum.mjtMaxSecuredObjectId})})}function doDeleteRole(e){jsrsExecuteWithErrorP("Admin2_DeleteRole",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting Role",{roleId:e.roleId})}function confirmDeleteRole(e){hideDialogP({callback:function(){displaySimpleConfirmationDialog(doDeleteRole,"Are you sure you want to delete the role?","Delete Role",{roleId:e})}})}function doShowUpdateOrCreateRole(e){e=e||{};var t=e.roleId,a=e.arrSecuritySections,i,o,n="editRole",r,l=pageEventLog+EventObjectType_Enum.eotJTCRMRole+"/"+t,d=new ClientDialogBuilder({formId:n,formTitle:t?"Edit Role":"Create Role",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitUpdateOrCreateRole()"}),focusFieldName:"txtRoleName",focusFieldOnMobile:1,arrExtraHeaderButtons:t?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Role",doubleQuoteEncodedOnClickJS:"hideDialog();"+"confirmDeleteRole("+t+")"}),'',cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowDuplicateDocument,doubleQuoteEncodedTitle:"Duplicate Role",doubleQuoteEncodedOnClickJS:"promptDuplicateRole('"+t+"');"}),cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"Change Log",doubleQuoteEncodedOnClickJS:"clickedDialogLink('"+l+"');"})]:null,fnSubmit:submitUpdateOrCreateRole});d.addTextFieldRow("txtRoleName",{rawLabel:"Role Name",mnemonicChar:"n",fieldValue:e.roleName||""});d.addExpandingTextFieldRows("txtRoleDescription",{rawLabel:"Description",mnemonicChar:"c",value:e.roleDescription||""});for(o=0;o'+t+"","Delete Pricing Structure",{pricingStructureId:e})}function submitReorderProducts(e){submitReorderP({arrReorderedIds:e,reorderCommandName:"Admin2_ReorderProducts2",reorderObjectName:"Products",reorderIdsPropertyName:"productIds"})}function rsCallbackGetObjectsForReorder(e,t){var a=t.originalOptions,i=e[a.arrayAttrName],o=a.fnSubmit;mwShowGenericReorderDialog(i,o,"Re-Order "+a.strReorderWhat,{idAttrName:a.idAttrName,nameAttrName:a.nameAttrName,highlightedId:a.highlightedId})}function showReorderProductsDialog(e){jsrsExecuteWithErrorP("Admin2_GetProductsForReorder",rsCallbackGetObjectsForReorder,"Getting list of products for re-order",{},{arrayAttrName:"arrProducts",fnSubmit:submitReorderProducts,strReorderWhat:"Products",highlightedId:e})}function showCustomerPage(e,t){displayTimedMessage("Loading Customer Details...");window.location=pageCustomerDetail+e}function rsCallbackCreatedCustomer(e){hideDialog();showCustomerPage(e.customerId)}function doSubmitEditOrAddCustomer(e,t){var a=new FormValidator,i=t.id,o={customerName:trim(e.txtName.value),discountPercent:trim(e.txtDiscountPct.value)},n=e.chkDisablePortalUpdate,r=n?n.checked?1:0:0;if(!a.CSValidateNumberField(e.txtDiscountPct,"Discount %",true)){return}if(i){o.customerId=i;o.disablePortalUpdate=r?1:0}jsrsExecuteWithErrorP(i?"Admin2_UpdateCustomer2":"Admin2_CreateCustomer2",i?rsCallbackHandleStandardJSONResponseWithHideAndRefresh:rsCallbackHandleStandardJSONResponse,i?"Updating Customer":"Creating Customer",o,{fnOnSuccess:i?null:rsCallbackCreatedCustomer})}function rsCallbackGetCustomerByName(e,t,a){enableDialogButtons();if(checkResponseForError(e)){var i=JSON.parse(e);if(i.name&&(!a.id||i.id!=a.id)){showInfoDialog('There is already a "'+htmlEncode(i.name)+'" customer',"Duplicate Customer",1,"txtName");return}doSubmitEditOrAddCustomer(getObj("frmCustomer"),a)}}function submitEditOrAddCustomer(e,t){var a=new FormValidator;if(!a.CSValidateRequiredField(e.txtName,"Please enter a Customer Name")){return}jsrsExecute(rsCallbackGetCustomerByName,"Admin_GetCustomerByName",[escape(e.txtName.value)],enableDialogButtons,t);displayTimedMessage("Checking for duplicate Customer Name...");disableDialogButtons()}function showCustomerDialog(e){var t=e.id,a=e.name,i=e.discountPct,o="frmCustomer",n=cdBuildTextFieldRowP("txtName","Name",{autofocus:!t,maxLength:80,fieldValue:a||""})+cdBuildTextFieldRowP("txtDiscountPct","Discount %",{maxLength:8,fieldValue:""+(i||""),isNumber:1,hideRow:!i}),r;if(t&&jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete)){r=[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Customer",doubleQuoteEncodedOnClickJS:"hideDialog();"+"confirmDeleteCustomer("+t+",unescape('"+escape(a)+"'))"})];n+=cdBuildCheckboxRow_deprecated("chkDisablePortalUpdate","chkDisablePortalUpdate","Disable Customer Portal",e.disablePortalUpdate)}showDialogP(n,o,{formTitle:(t?"Edit":"New")+" Customer",focusFieldName:"txtName",arrExtraHeaderButtons:r,contextDetailOrFnSubmit:{fnSubmit:submitEditOrAddCustomer,callbackData:{id:t}}})}function rsCallbackGetCustomerInfoForAddEditCustomer(e,t,a){enableDialogButtons();if(checkResponseForError(e)){var i=JSON.parse(e);i.id=a.id;if(a.duplicate){delete i.id}showCustomerDialog(i)}}function getCustomerInfoForAddEditCustomer(e){jsrsExecute(rsCallbackGetCustomerInfoForAddEditCustomer,"Admin_GetCustomerInfo",[e.id?e.id:""],enableDialogButtons,e);displayTimedMessage("Retrieving Customer Info...");disableDialogButtons()}function showCreateCustomerDialog(){getCustomerInfoForAddEditCustomer({})}function showEditCustomerDialog(e,t){getCustomerInfoForAddEditCustomer({id:e,name:t})}function showDuplicateCustomerDialog(e,t){getCustomerInfoForAddEditCustomer({id:e,name:t,duplicate:1})}function doDeleteCustomer(e){var t=e.name;if(t){t=htmlEncode(t)}else{t="Customer"}jsrsExecuteWithErrorP("Admin2_DeleteCustomer2",rsCallbackHandleStandardJSONResponse,"Deleting "+t,{customerId:e.id},{fnOnSuccess:rsCallbackSaveSettingsAndNavigateTo2,url:pageCustomers})}function confirmDeleteCustomer(e,t){displaySimpleConfirmationDialog(doDeleteCustomer,'Are you sure you want to delete "'+htmlEncode(t)+'"',"Delete Customer",{id:e,name:t})}var dateFormatString="M/d/yyyy";function rsCallbackSubmitCreateInstance(e,t){var a="frmCreateInstanceResults",i=e.deployedToServer,o=t.originalPayload.subdomain,n=t.originalPayload.instanceUrlPrefix,r=t.originalPayload.instanceUrlPostfix,l=n+o+r;var d=new ClientDialogBuilder({formId:a,formTitle:"New Instance Created",hideCancelButton:true,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"OK",mnemonicChar:"o",mnemonicActionJS:"refreshPageAndScrollPos"}),fnSubmit:refreshPageAndScrollPos});d.addFlexibleFieldRow({rawLabel:"New Instance Link",valueHTML:''+l+""});d.addFlexibleFieldRow({rawLabel:"Instance Created on Server",valueHTML:i});d.showClientDialog()}function submitCreateInstance(){var e="frmNewInstance",t=getObj(e),a=t.txtSubdomainName,i=t.cboCounterGo.value,o=t.cboNVInventory.value,n=t.cboSystemize.value,r=mjtElemData(t,"formElemData"),l=r.databaseId,d=new FormValidator;if(!d.CSValidateRequiredField(a,"Please enter a Subdomain Name")){return}jsrsExecuteWithErrorP("Admin2_CreateInstance",rsCallbackSubmitCreateInstance,"Creating Instance",{databaseId:l,subdomain:trim(a.value),cgUserCount:i,nvUserCount:o,sysUserCount:n,instanceUrlPrefix:r.instanceUrlPrefix,instanceUrlPostfix:r.instanceUrlPostfix})}function showCreateInstanceDialog(e,t,a,i){var o="frmNewInstance",n=new ClientDialogBuilder({formId:o,formTitle:"New Instance",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Create Instance",mnemonicChar:"c",mnemonicActionJS:"submitCreateInstance()"}),fnSubmit:submitCreateInstance}),r=[],l="";n.addTextFieldRow("txtSubdomainName",{rawLabel:"Subdomain Name",fieldValue:e,strPreFieldHTML:a,strPostFieldHTML:i,disabled:true});for(var d=1;d<11;++d){r.push({cboValue:d,rawContent:d+" User"+l})}n.addDropdown({labelHTML:"Systemize Users",fieldId:"cboSystemize",arrAvailableOptions:r,objNoneOption:{cboValue:"0",rawContent:"-None-"}});n.addDropdown({labelHTML:"CounterGo Users",fieldId:"cboCounterGo",arrAvailableOptions:r,objNoneOption:{cboValue:"0",rawContent:"-None-"}});n.addDropdown({labelHTML:"Inventory Users",fieldId:"cboNVInventory",arrAvailableOptions:r,objNoneOption:{cboValue:"0",rawContent:"-None-"}});n.showClientDialog({formElemData:{databaseId:t,instanceUrlPrefix:a,instanceUrlPostfix:i}})}function submitAddOrUpdateDBProduct(e){var t=e.cboQty,a=e.cboProduct,i=a?a.options[a.selectedIndex].value:"",o=i?JSON.parse(unescape(i)):0,n=cdGetExpandingTextFieldValue("txtNotes"),r=new FormValidator,l,d=mjtElemData(e,"databaseProductId"),s=mjtElemData(e,"databaseId"),u,c,m=null,p=(!d||!e.txtPrice||r.CSValidateNumberFieldP({field:e.txtPrice,label:"Price"}))&&r.CSValidateDateFieldP({field:e.dtStartDate,label:"Start Date",isNullable:true})&&r.CSValidateDateFieldP({field:e.dtEndDate,label:"End Date",isNullable:true});if(!p){return}if(e.priceGenerations){m=e.priceGenerations.options[e.priceGenerations.selectedIndex].value}else if(o&&o.priceGenerationId){m=o.priceGenerationId}u=getDateForUrlParam(e.dtStartDate.value);c=getDateForUrlParam(e.dtEndDate.value);if(u&&c&&parseDateString(c)'+l+""});u.addDialogInteriorRows(buildQuantityComboboxRow());u.addDatePickerRow(i,"dtStartDate",{rawLabel:"Start Date",strValue:s,suppressAutocomplete:1});u.addDatePickerRow(i,"dtEndDate",{rawLabel:"End Date",suppressAutocomplete:1});u.addExpandingTextFieldRows("txtNotes",{rawLabel:"Notes",suppressAutocomplete:1});o=u.showClientDialog();if(o){mjtElemData(o,"databaseId",t.originalPayload.databaseId)}}function createOrAddToErrorInfo(e,t,a){if(!e){e={errorMessageHTML:"",onDismissFocusFieldName:a}}else{e.errorMessageHTML+=" "}e.errorMessageHTML+=t;return e}var g_mapCRMProductTypeToInfix;function getMapCRMProductTypeToInfix(){if(!g_mapCRMProductTypeToInfix){g_mapCRMProductTypeToInfix=new MJTDictionary;g_mapCRMProductTypeToInfix.add(CRMProductType_Enum.crmptCounterGo,"CG");g_mapCRMProductTypeToInfix.add(CRMProductType_Enum.crmptNVInventory,"NV");g_mapCRMProductTypeToInfix.add(CRMProductType_Enum.crmptJobTracker,"JT");g_mapCRMProductTypeToInfix.add(CRMProductType_Enum.crmptSystemize,"Sys")}return g_mapCRMProductTypeToInfix}function maxUsersToCancelFromDate(e,t){var a=0;for(var i=0;i0||c>0;o.style.display=p?"":"none";if(p){u+=m;if(l||s){u+=" = ";if(r){u+=r}if(l){if(r){u+=" + "}u+=l+" on order"}if(s){if(r+l){if(i){u+=" - "}else{u+=" + "}}if(i){u+=-s+" cancelled users"}else{u+=s+" new users"}}}n.innerHTML=u}}function calculateAdditionalUserCost(e,t,a){var i,o=parseFloat(e.getAttribute("data-pricePer")),n=e.getAttribute("data-tier2StartUserCount"),r=e.getAttribute("data-tier2PerUserPrice");if(n&&r){var l=parseInt(n,10),d=parseFloat(r),s=a+t;if(s=l-1){i=a*d}else if(t0;v.style.display=E?"":"none";P.innerHTML=""+R;S.setAttribute("max",R);if(isNaN(x)||x<0){S.className="invalidTextField";p=createOrAddToErrorInfo(p,'Invalid User Count "'+htmlEncode(I)+'"',S.name)}else{if(x>R){S.className="invalidTextField";p=createOrAddToErrorInfo(p,"You have exceeded the max number of users ("+R+") available to be cancelled.",S.name)}else{S.className="";if(x){h=m.item(D);w=getOriginalTotalUserCount({userCountInfoForAddUsers:n,productTypeInfix:h});l+=calculateCancelledUserValue(y,w,x);u={productTypeId:D,userCount:x};s.push(u);c[h]=u}}}if(E&&f){f=0;var A=S;setTimeout(function(){setFocus(A)},0)}getObj("spnCostReduction").innerHTML=padAndPrefixSignedDollars(l,1);getObj("spnNewTotalCost").innerHTML=padAndPrefixSignedDollars(r-l,1)}updateAddRemoveUserDlgUserCountCell(n,c,"CG",1);updateAddRemoveUserDlgUserCountCell(n,c,"NV",1);updateAddRemoveUserDlgUserCountCell(n,c,"JT",1);updateAddRemoveUserDlgUserCountCell(n,c,"Sys",1);if(e&&p){showInfoDialog(p.errorMessageHTML,"Invalid User Count",1,p.onDismissFocusFieldName);return}return s}function submitCancelUsers(){var e=new FormValidator,t=updateCancelUserDialogForCount(1),a="frmCancelUsers",i=getObj(a),o=getCallbackDataOfDialog(i),n=i.changeUserDate;if(!t){return}if(!t.length){showInfoDialog("You haven't indicated how many users to cancel.","No Cancelled Users",1,"txtAddUserCount.0");return}if(!e.CSValidateDateField(n,"Cancel Date",false,n.name)){return}jsrsExecuteWithErrorP("Admin2_CancelUsers",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Cancelling Users",{databaseId:o.databaseId,cancelDate:getDateForUrlParam(n.value),productTypeCounts:t})}var FORM_ID_CHANGE_USER="changeUserForm";function createUndersubscibedUserCountError(e){var t=e.existingErrorInfo,a=e.newTotalUserCount,i=e.minUserCount,o=e.productTypeName,n=e.focusFieldName,r=" Too few "+o+" users.\n"+"\n"+"(A minimum of "+i+" are required,"+" but the total is only "+a+" )",l='
'+htmlEncode(r)+"
";return createOrAddToErrorInfo(t,l,n)}function updateAddUserDialogForCount(e){var t=0,a=0,i=getObj(FORM_ID_CHANGE_USER),o=getObj("spnNewTotalCost"),n=mjtElemData(i,"userCountInfoForAddRemoveUsers"),r=parseFloat(o.getAttribute("data-totalCurrentCost"))||0,l=[],d,s={},u=getMapCRMProductTypeToInfix(),c;while(true){var m=getObj("txtAddUserCount."+t);if(!m){break}var p=getObj("spnUserCountAddendum."+t),f=m.value||"0",b=parseInt(f,10);if(isNaN(b)||b<0||f.indexOf(".")>-1){m.className="invalidTextField";c=createOrAddToErrorInfo(c,'Invalid User Count "'+htmlEncode(f)+'"',m.name)}else{m.className="";if(b){var g=parseInt(p.getAttribute("data-productTypeId"),10),C=parseInt(p.getAttribute("data-minUserCount"),10),D=u.item(g),h=getOriginalTotalUserCount({userCountInfoForAddUsers:n,productTypeInfix:D}),w=h+b,T=C&&w&&w1){showInfoDialog("You can only select a single product when "+(t?"upgrading":"rolling back")+".",t?"Upgrade":"Rollback",1);return}return a[0]}function submitUpgradeProduct(){var e="upgradeForm",t=getObj(e),a=getSelectedProductForUpgradeOrRollback(t,1);if(!a){return}hideDialog();jsrsExecuteWithErrorP("Admin2_UpgradeProduct",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Upgrading Products",{productId:a.productId,databaseId:mjtElemData(t,"databaseId"),effectiveDate:t.upgradeDate.value,pricingStructureId:a.pricingStructureId})}function onSelectProduct(e){if(e.checked){e.parentNode.parentNode.style.backgroundColor="rgb(255, 255, 204)"}else{e.parentNode.parentNode.style.backgroundColor=null}}function getJobTrackerSystemizeEditionIncludedUserCount(e){return parseInt(e.includedUsers!==undefined?e.includedUsers:e.jtUserCount,10)}function getAdditionalUserCount(e){var t=parseInt(e.editionUsers?e.editionUsers.length:e.requiredAdditionalUsers,10);t=isNaN(t)?0:t;return t}function priceFromPriceGeneration(e){var t;if(e&&e.length>1){var a=e.indexOf("/");if(a>0){t=e.substring(1,a)}}return parseFloat(t)}function writeProductTable(e){var t=new MWClientTable({noDataMessage:"No products"}),a,n=0,i=e.arrProducts,o=e.includeCheckboxColumn,r=e.databaseId,d=e.selectedPricingStructure,s=e.pricingStructureProductId;i=i.filter(function(e,t,a){return!!e});t.addColumn(new MWColumn({columnName:"Name",fnCustomRenderCellContents:function(e,t,a,i){return htmlEncode(e.productName)}}));if(o){t.setCheckboxFunction(function(e,t,a){return{value:escape(JSON.stringify({databaseProductId:e.databaseProductId,productId:e.productId,disabled:e.disabled,pricingStructureId:e.productId===s?d.pricingStructureId:e.pricingStructureId})),checked:e.productId===s}})}t.addColumn(new MWColumn({columnName:"Base Price",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(e,t,a,i){var o,n=e.productTypeId!==undefined?e.productTypeId:e.productType;if(n===CRMProductType_Enum.crmptCounterGo||n===CRMProductType_Enum.crmptNVInventory){return""}if(e.isFlexPricing){if(d&&s===e.productId){o=d.editionPrice}else{o=e.editionPrice}}else{o=e.databaseProductPrice!==undefined?e.databaseProductPrice:e.price}return padAndPrefixSignedDollars(o,1)}}));t.addColumn(new MWColumn({columnName:"Included Users",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(e,t,a,i){var o=e.productTypeId!==undefined?e.productTypeId:e.productType;if(o===CRMProductType_Enum.crmptCounterGo||o===CRMProductType_Enum.crmptNVInventory){return""}return getJobTrackerSystemizeEditionIncludedUserCount(e)}}));t.addColumn(new MWColumn({columnName:"Additional Users",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(e,t,a,i){return getAdditionalUserCount(e)}}));t.addColumn(new MWColumn({columnName:"Price Per Additional User",fnCustomRenderCellContents:function(e,t,a,i){var o,n=e.tier2StartUserCount,r=e.tier2PerUserPrice;if(e.isFlexPricing){if(d&&s===parseInt(e.productId,10)){n=d.tier2StartUserCount;r=d.tier2PerUserPrice;o=parseFloat(d.additionalUserPrice)}else{o=parseFloat(e.additionalUserPrice)}}else{if(e.legacyProductPerUserPrice!==undefined){o=parseFloat(e.legacyProductPerUserPrice)}else{o=priceFromPriceGeneration(e.priceGenerationName)}}var l=isNaN(o)?"N/A":padAndPrefixSignedDollars(o,1)+"/"+e.termName+"/User";if(n){l+=", "+padAndPrefixSignedDollars(r,1)+" for users "+n+"+"}return l}}));t.addColumn(new MWColumn({columnName:"Cost",fnCustomRenderCellContents:function(e,t,a,i){var o=e.totalCost;n+=o;return padAndPrefixSignedDollars(o,1)+" "+e.termName}}));if(o){t.addColumn(new MWColumn({columnName:"",fnCustomRenderCellContents:function(e,t,a,i){var o="";if(e.isFlexPricing){var n={databaseId:r,productId:e.productId,productTypeName:e.productTypeName,productTypeId:e.productTypeId,editionName:e.editionName,editionId:e.editionId};o=cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiUSD,doubleQuoteEncodedTitle:"Change Pricing",doubleQuoteEncodedOnClickJS:"doSelectPricingStructureDialog(JSON.parse(unescape('"+escape(JSON.stringify(n))+"')))"})}return o}}))}a=t.buildTableForArray(i);if(!o&&i.length>1){a+='
'+"Warning - Active user count from instance manager is "+o+" "+"but current active edition users are "+(l.includedUsers+l.editionUsers.length)+(v>0?", external users are "+v:"")+(P>0?", shop users are "+P:"")+"."+" Upgrading will result in billing for "+(o+v+P)+" users."+"
"})}}else{T.addFlexibleRow({rawValue:'There are no active "Edition" products to be upgraded.',additionalCellClasses:"dlgErrorPanel"})}S=T.showClientDialog();if(S){mjtElemData(S,"databaseId",a)}}function showUpgradeDialog(e){jsrsExecuteWithErrorP("Admin2_GetProductsForUpgrade",rsCallbackHandleStandardJSONResponse,"Getting upgrade information...",{databaseId:e.databaseId,pricingStructureProductId:e.pricingStructureProductId,pricingStructureId:e.pricingStructureId,upgradeEffectiveDate:e.upgradeEffectiveDate},{fnOnSuccess:rsCallbackGetProductsForDBForUpgradeProducts})}function enableDisableOpenOrderDialog(e){var t=getObj("frmOpenOrder"),a=t?t.parentNode:0;if(a){if(e){enableDialogButtonsOfDialog(a)}else{disableDialogButtonsOfDialog(a)}}}function disableOpenOrderDialog(){enableDisableOpenOrderDialog(0)}function enableOpenOrderDialog(){enableDisableOpenOrderDialog(1)}function doCancelOrder(e){jsrsExecuteWithErrorP("Admin2_CancelProductOrder2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Cancelling Order",{productOrderId:e.productOrderId});disableOpenOrderDialog()}function showCancelUserDialog(e,t,a,i){jsrsExecuteWithErrorP("Admin2_GetProductsForCancelUser",rsCallbackGetProductsForCancelUsers,"Getting cancel user information...",{databaseId:e},{defaultJTUserCount:t,defaultCGUserCount:a,defaultNVUserCount:i})}function showAddUserDialog(e){jsrsExecuteWithErrorP("Admin2_GetProductsForAddUser",rsCallbackHandleStandardJSONResponse,"Getting add user information...",{databaseId:e},{fnOnSuccess:rsCallbackGetProductsForAddUser})}function submitAddAdditionalUsersToDB(){var e="frmAddAdditionalUsersToDB",t=getObj(e),a=mjtElemData(t,"addAdditionalUserInfo");hideDialog();jsrsExecuteWithErrorP("Admin2_AddAdditionalUsersToDB",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Adding and invoicing Additional Users",a)}function buildAddUserTotalRow(e){var t=e.cdBuilder,a=e.userTypeName,i=e.initialCount,o=e.additionalCount,n;if(i+o){if(o){n=''+(i+o)+""+" = "+i+" + "+o+" New User"+(o===1?"":"s")}else{n=""+i}t.addFlexibleFieldRow({rawLabel:a+" Users",valueHTML:n})}}function rsCallbackGetInfoForAddAdditionalUsersToDB(e,t){var a=t.originalOptions,i=a.suppressAutoAddBillingUsers,o="frmAddAdditionalUsersToDB",n,r=e.productOrderId,l={productOrderId:r},d=new ClientDialogBuilder({formId:o,formTitle:"Add Additional Users",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Create Invoice",mnemonicChar:"c",mnemonicActionJS:"submitAddAdditionalUsersToDB()"}),fnSubmit:submitAddAdditionalUsersToDB,fnCancelOrClose:function(){doCancelOrder(l)}}),s=e.additionalJTUserCount,u=e.additionalCGUserCount,c=e.additionalNVUserCount,m=e.currentBillingCGUserCount,p=e.currentBillingNVUserCount,f=e.currentBillingJTSysUserCount,b=e.arrAdditionalUsers,g=e.initialProrateTotalTaxedAmountDetail,C=e.ongoingTotalTaxedAmountDetail,D=e.zeroOutProrate,h=e.zeroOutProrateMessage,w,T=new MWClientTable({arrColumns:[new MWColumn({columnName:"Quantity",simpleDisplayColumnPropertyName:"quantity",additionalCellClasses:"rightAlign"}),new MWColumn({columnName:"Product",simpleDisplayColumnPropertyName:"productName"}),new MWColumn({columnName:"Prorated Unit Price",simpleDisplayColumnPropertyName:"proratedUnitPrice",additionalCellClasses:"rightAlign"}),new MWColumn({columnName:"Initial Term Total Price",simpleDisplayColumnPropertyName:"initialTermTotalPrice",additionalCellClasses:"rightAlign"}),new MWColumn({columnName:"Unit Price",simpleDisplayColumnPropertyName:"unitPrice",additionalCellClasses:"rightAlign"}),new MWColumn({columnName:"Total Price",simpleDisplayColumnPropertyName:"totalPrice",additionalCellClasses:"rightAlign"}),new MWColumn({columnName:"Notes",simpleDisplayColumnPropertyName:"notes",simpleDisplayColumnNeedsMultilineEncoding:1})]}),S=[];d.addFlexibleFieldRow({rawLabel:"Database",rawValue:e.subdomainName});d.addFlexibleFieldRow({rawLabel:"Order Start Date",rawValue:e.orderStartDate,additionalCellClasses:"clsNarrowField"});d.addFlexibleFieldRow({rawLabel:"First Term End Date",rawValue:e.firstTermEndDate});if(i){d.addBubbleMessageRow({rawMessage:'This Database has been marked "Don\'t Automatically Add Additional Users To Billing"',isError:1})}if(b){for(w in b){var y=b[w];S.push({quantity:y.quantity,productName:y.productName,unitPrice:padAndPrefixSignedDollars(y.unitPrice,1),totalPrice:padAndPrefixSignedDollars(y.totalPrice,1),proratedUnitPrice:padAndPrefixSignedDollars(y.proratedUnitPrice,1),initialTermTotalPrice:padAndPrefixSignedDollars(y.initialTermTotalPrice,1),notes:y.notes})}}d.addSectionHeaderRow({rawTitle:u+c+s===1?"Additional User":"Additional Users"});d.addFlexibleRow({valueHTML:T.buildTableForArray(S)});d.addSectionHeaderRow({rawTitle:"New Totals"});if(D){d.addBubbleMessageRow({rawMessage:htmlEncode(h)})}d.addFlexibleFieldRow({rawLabel:"Initial Prorated Total",valueHTML:htmlEncode(g.formattedTotalString)+(g.supplementalTaxBreakdownHint?" "+''+htmlEncode(g.supplementalTaxBreakdownHint)+"":""),additionalCellClasses:"topAlign"});d.addFlexibleFieldRow({rawLabel:"Ongoing Additional Monthly Amount",valueHTML:htmlEncode(C.formattedTotalString)+(C.supplementalTaxBreakdownHint?" "+''+htmlEncode(C.supplementalTaxBreakdownHint)+"":""),additionalCellClasses:"topAlign"});buildAddUserTotalRow({cdBuilder:d,userTypeName:"CounterGo",initialCount:m,additionalCount:u});buildAddUserTotalRow({cdBuilder:d,userTypeName:"Inventory",initialCount:p,additionalCount:c});buildAddUserTotalRow({cdBuilder:d,userTypeName:"Systemize",initialCount:f,additionalCount:s});n=d.showClientDialog();if(n){mjtElemData(n,"addAdditionalUserInfo",{productOrderId:r})}}function showAddAdditionalUsersToDBDialog(e){jsrsExecuteWithErrorP("Admin2_GetInfoForAddAdditionalUsersToDB",rsCallbackHandleStandardJSONResponse,"Getting Additional User Info...",{databaseId:e.databaseId||"",metricBatchId:e.metricBatchId,additionalCGUserCount:e.additionalCGUserCount||0,additionalNVUserCount:e.additionalNVUserCount||0,additionalJTUserCount:e.additionalJTUserCount||0,expectedActiveCGUserCount:e.activeCGUserCount,expectedActiveNVUserCount:e.activeNVUserCount,expectedActiveJTUserCount:e.activeJTUserCount,expectedBillingCGUserCount:e.billingCGUserCount,expectedBillingNVUserCount:e.billingNVUserCount,expectedBillingJTUserCount:e.billingJTUserCount},{fnOnSuccess:rsCallbackGetInfoForAddAdditionalUsersToDB,suppressAutoAddBillingUsers:e.suppressAutoAddBillingUsers,systemizeOrJobTracker:e.systemizeOrJobTracker})}function submitAddAdditionalStorageToDB(){var e="frmAddAdditionalStorageToDB",t=getObj(e),a=mjtElemData(t,"addAdditionalStorageInfo");hideDialog();jsrsExecuteWithErrorP("Admin2_CompleteOrder2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Adding and invoicing Additional Storage",a)}function rsCallbackGetInfoForAddAdditionalStorageToDB(e,t){var a="frmAddAdditionalStorageToDB",i=e.productOrderId,o={productOrderId:i},n=e.initialProrateTotalTaxedAmountDetail,r=e.ongoingTotalTaxedAmountDetail,l=new ClientDialogBuilder({formId:a,formTitle:"Add Additional Storage",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Create Invoice",mnemonicChar:"c",mnemonicActionJS:"submitAddAdditionalStorageToDB()"}),fnSubmit:submitAddAdditionalStorageToDB,fnCancelOrClose:function(){doCancelOrder(o)}}),d=new MWClientTable({arrColumns:[new MWColumn({columnName:"Quantity",simpleDisplayColumnPropertyName:"quantity",additionalCellClasses:"rightAlign"}),new MWColumn({columnName:"Product",simpleDisplayColumnPropertyName:"productName"}),new MWColumn({columnName:"Prorated Unit Price",simpleDisplayColumnPropertyName:"proratedUnitPrice",additionalCellClasses:"rightAlign"}),new MWColumn({columnName:"Initial Term Total Price",simpleDisplayColumnPropertyName:"initialTermTotalPrice",additionalCellClasses:"rightAlign"}),new MWColumn({columnName:"Unit Price",simpleDisplayColumnPropertyName:"unitPrice",additionalCellClasses:"rightAlign"}),new MWColumn({columnName:"Total Price",simpleDisplayColumnPropertyName:"totalPrice",additionalCellClasses:"rightAlign"}),new MWColumn({columnName:"Notes",simpleDisplayColumnPropertyName:"notes",simpleDisplayColumnNeedsMultilineEncoding:1})]}),s=[];if(e.order){var u=e.order;s.push({quantity:u.quantity,productName:u.productName,unitPrice:padAndPrefixSignedDollars(u.unitPrice,1),totalPrice:padAndPrefixSignedDollars(u.totalPrice,1),proratedUnitPrice:padAndPrefixSignedDollars(u.initialTermUnitPrice,1),initialTermTotalPrice:padAndPrefixSignedDollars(u.initialTermTotalPrice,1),notes:u.notes})}l.addFlexibleFieldRow({rawLabel:"Database",rawValue:e.subdomainName});l.addFlexibleFieldRow({rawLabel:"Order Start Date",rawValue:e.formattedOrderStartDate,additionalCellClasses:"clsNarrowField"});l.addFlexibleFieldRow({rawLabel:"First Term End Date",rawValue:e.formattedFirstTermEndDate});l.addSectionHeaderRow({rawTitle:"Additional Storage"});l.addFlexibleRow({valueHTML:d.buildTableForArray(s)});l.addSectionHeaderRow({rawTitle:"New Totals"});l.addFlexibleFieldRow({rawLabel:"Initial Prorated Total",valueHTML:htmlEncode(n.formattedTotalString)+(n.supplementalTaxBreakdownHint?" "+''+htmlEncode(n.supplementalTaxBreakdownHint)+"":""),additionalCellClasses:"topAlign"});l.addFlexibleFieldRow({rawLabel:"Ongoing Additional Monthly Amount",valueHTML:htmlEncode(r.formattedTotalString)+(r.supplementalTaxBreakdownHint?" "+''+htmlEncode(r.supplementalTaxBreakdownHint)+"":""),additionalCellClasses:"topAlign"});l.showClientDialog({formElemData:{addAdditionalStorageInfo:{productOrderId:i}}})}function showAddAdditionalStorageToDBDialog(e){jsrsExecuteWithErrorP("Admin2_CreateProductOrderToAddAdditionalStorage",rsCallbackHandleStandardJSONResponse,"Getting Additional Storage Info...",{databaseId:e.databaseId||"",additionalStorageInMb:e.additionalStorageInMb,totalProductFileSizeInMb:e.totalProductFileSizeInMb},{fnOnSuccess:rsCallbackGetInfoForAddAdditionalStorageToDB})}function rsCallbackDisplayAddStorageToInstancesResults(e){hideDialog();var t=e.results||[],a=t.length,i=e.instancesWithProductOrders,o=e.instancesWithInvoices,n="frmShowResultsOfAddingStorageToInstances",r=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:n,formTitle:"Add Storage to Instances",fnCancelOrClose:function(){hideDialog();refreshPageAndScrollPos()}}),l=new MWClientTable({});r.addFlexibleFieldRow({rawLabel:"Instances",rawValue:""+a});r.addFlexibleFieldRow({rawLabel:"Product Orders (Created)",rawValue:""+i});r.addFlexibleFieldRow({rawLabel:"Invoices (Created)",rawValue:""+o});r.addSectionHeaderRow({rawTitle:"Instances"});l.addColumn(new MWColumn({columnName:"Customer",fnCustomRenderCellContents:function(e,t,a,i){return htmlEncode(e.instance.customerName)}}));l.addColumn(new MWColumn({columnName:"Database",fnCustomRenderCellContents:function(e,t,a,i){return htmlEncode(e.instance.subdomain)},fnBuildCellLinkDetail:function(e,t,a,i){return mwBuildSimpleLink(pageDatabaseDetail+e.instance.databaseId,1)}}));l.addColumn(new MWColumn({columnName:"Product Order Prorated Total",fnCustomRenderCellContents:function(e,t,a,i){return padAndPrefixSignedDollarsP({dollarValue:e.productOrderProratedTotal,forceDecimalsWhenNone:1})}}));l.addColumn(new MWColumn({columnName:"Status",fnCustomRenderCellContents:function(e,t,a,i){var o="Could not create Product Order";if(e.createdInvoices){o="Success"}else if(e.createdProductOrders){o="Product Order Created but not Invoiced"}return o}}));l.addColumn(new MWColumn({columnName:"Status Message",simpleDisplayColumnPropertyName:"statusMessage",simpleDisplayColumnNeedsMultilineEncoding:true}));var d=l.buildTableForArray(t);r.addFlexibleRow({valueHTML:d});r.showClientDialog()}function confirmedAddStorageToSpecificInstances(e,t){var a=getListOfCheckedRowValuesWithParams({form:e,buildRCArray:1,minSelected:1,tooFewWarning:"Please select an Instance",clientDlgParams:{subdialogDismisalFocusFieldName:"chkCheckAllRows",subdialog:1},unescapeValues:1,fnTransformValueForArray:function(e){return JSON.parse(e)}}),i=a.arrValues,o=a.selectedCount;if(!o){return}jsrsExecuteWithErrorP("Admin2_AddAdditionalStorageToInstances",rsCallbackHandleStandardJSONResponse,"Adding Additional Storage to Selected Instances",{arrInstancesWithStorageOverage:i},{fnOnSuccess:rsCallbackDisplayAddStorageToInstancesResults})}function rsCallbackGetInstancesWithStorageOverages(e){var t=e.instances||[],a=t.length,i="frmPromptAddStorageToInstances",o=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:i,formTitle:"Add Storage to Instances",focusFieldName:"btnOk",okButtonDisplayText:"Create Invoices",fnSubmit:confirmedAddStorageToSpecificInstances}),n=new MWClientTable({fnGetCheckDetailsForRow:function(e,t,a){return{value:htmlEncode(JSON.stringify(e))}}});if(!a){showInfoDialog("There are currently no instances with storage overages.","No Instances To Be Updated");return}o.addFlexibleFieldRow({rawLabel:"Instances with overages",rawValue:""+a});o.addSectionHeaderRow({rawTitle:"Instances To Update"});n.addColumn(new MWColumn({columnName:"Customer",simpleDisplayColumnPropertyName:"customerName"}));n.addColumn(new MWColumn({columnName:"Database",simpleDisplayColumnPropertyName:"subdomain",fnBuildCellLinkDetail:function(e,t,a,i){return mwBuildSimpleLink(pageDatabaseDetail+e.databaseId,1)}}));n.addColumn(new MWColumn({columnName:"Next Invoice Date",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(e,t,a,i){var o=new Date(e.nextInvoiceDate);return getLocalDateString(o)}}));var r=n.addColumn(new MWColumn({columnName:"Attached Files",additionalHeaderClasses:"centerAlign"}));r.addSubColumn(new MWColumn({columnName:"Overage",simpleDisplayColumnPropertyName:"formattedExcessAttachedFileAmount",additionalCellClasses:"rightAlign"}));r.addSubColumn(new MWColumn({columnName:"Monthly Usage",simpleDisplayColumnPropertyName:"formattedLastMonthsUploadAmount",additionalCellClasses:"rightAlign"}));var l=n.buildTableForArray(t);o.addFlexibleRow({valueHTML:l});var d=o.showClientDialog();if(d){d.chkCheckAllRows.checked=true;checkAllRows(d.chkCheckAllRows)}}function addStorageToJTInstances(){jsrsExecuteWithErrorP("Admin2_GetInstancesWithStorageOverages",rsCallbackGetInstancesWithStorageOverages,"Getting Instances With Storage Overages")}function showAddProductToDB(e){jsrsExecuteWithErrorP("Admin2_GetDatabaseProductOptions2",rsCallbackHandleStandardJSONResponse,"Getting database product to edit",{databaseId:e.databaseId},{fnOnSuccess:rsCallbackGetDatabaseProductOptions})}function doDeleteDBProduct(e){var t="Deleting Database Product";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteDatabaseProduct",[e.databaseProductId],rsErrorCallbackShowErrorDialogAndRefresh,{errorDialogTitle:"Error "+t},0,1);displayTimedMessage(t+"...");disableDialogButtons()}function rsCallbackImportExpenses(e){hideDialog();if(checkResponseForError(e)){var t=JSON.parse(e),a=new ClientDialogBuilder({formTitle:"Import Completed"}),i=new MWClientTable({arrColumns:[new MWColumn({columnName:"User",simpleDisplayColumnPropertyName:"cardMember"}),new MWColumn({columnName:"Description",simpleDisplayColumnPropertyName:"description"}),new MWColumn({columnName:"Amount",simpleDisplayColumnPropertyName:"amount",additionalCellClasses:"rightAlign"})]});a.addFlexibleFieldRow({rawLabel:"Expenses Retrieved From Amex",rawValue:""+t.expensesRetrievedFromAmex,additionalCellClasses:"clsNarrowField"});a.addFlexibleFieldRow({rawLabel:"New Expenses Added",rawValue:""+t.expensesAdded});a.addFlexibleFieldRow({rawLabel:"Expenses Filtered By Blocklist",rawValue:""+t.filteredOut.length});if(t.filteredOut.length>0){a.addFlexibleFieldRow({});a.addSectionHeaderRow({rawTitle:"Filtered Expenses"});a.addFlexibleRow({valueHTML:i.buildTableForArray(t.filteredOut)})}a.showClientDialog()}}function confirmDeleteDatabaseProduct(e,t,a){displaySimpleConfirmationDialog(doDeleteDBProduct,'Are you sure you want to delete "'+htmlEncode(a)+'"?',"Delete Database Product",{databaseProductId:t,productName:a})}function hideDialogAndEnableOpenOrderDialog(){hideDialog();enableOpenOrderDialog()}function rsCallbackGetOrderedProducts(e,t){enableOpenOrderDialog();var a=e,i=a.arrOrderedProducts,o=i?i.length:0,n=t.originalPayload,r={productOrderId:n.productOrderId};if(o){displaySimpleConfirmationDialog(doCancelOrder,"Are you sure you want to cancel this entire order for "+o+" product"+(o===1?"":"s")+"? ","Cancel Order",r,0,0,"Cancel Order",hideDialogAndEnableOpenOrderDialog);disableOpenOrderDialog()}else{doCancelOrder(r)}}function confirmCancelOrder(e){jsrsExecuteWithErrorP("Admin2_GetOrderedProducts2",rsCallbackHandleStandardJSONResponse,"Checking contents of order",{productOrderId:e},{fnOnSuccess:rsCallbackGetOrderedProducts});disableOpenOrderDialog()}function doCompleteOrder(e){jsrsExecuteWithErrorP("Admin2_CompleteOrder2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Completing Order",{productOrderId:e.productOrderId});disableOpenOrderDialog()}function completeOrder(e,t){var a="Are you sure you want to complete this order? "+" "+"Doing so will convert these orders into subscribed products and an invoice.";displaySimpleConfirmationDialog(doCompleteOrder,a,"Complete Order",{productOrderId:t},0,0,"Complete Order",hideDialogAndEnableOpenOrderDialog);disableOpenOrderDialog()}function doZeroInitialProrate(e){jsrsExecuteWithErrorP("Admin2_ZeroOutProrate",refreshPageAndScrollPos,"Zeroing Out Prorate",{databaseId:e.databaseId})}function confirmZeroOutInitialProrate(e,t){displaySimpleConfirmationDialogP(doZeroInitialProrate,'Are you sure you want to zero out the Initial Prorated Total of "'+padAndPrefixSignedDollars(t)+'"?',{formTitle:"Zero Out Prorate",okButtonDisplayText:"Zero Prorate",contextDetail:{databaseId:e}})}function submitEditProductOrderItem(){var e=getObj("frmProductOrderItemDetails"),t=mjtElemData(e,"productOrderItemId"),a=new FormValidator,i=e.txtPrice,o=cdGetExpandingTextFieldValue("txtNotes"),n=e.txtFirstPrice,r=(!i||a.CSValidateNumberField(i,"Price",false))&&a.CSValidateNumberField(n,"First Term Invoiced Price",false);if(!r){return}jsrsExecuteWithErrorP("Admin2_UpdateProductOrderItemDetails2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Item Details",{productOrderItemId:t,price:trim(i?i.value:""),notes:o,firstTermPrice:trim(n.value)})}function rsCallbackGetProductOrderItemDetailsForEdit(e){var t=e,a="frmProductOrderItemDetails",i,o=t.productName,n=t.id,r=t.basePrice,l=t.isFlexPricing,d="firstTermInvoicedPrice",s=Object.prototype.hasOwnProperty.call(t,d),u=s?t[d]:"",c=t.notes,m=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),p=new ClientDialogBuilder({formId:a,formTitle:"Edit Order",focusFieldName:"txtFirstPrice",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitEditProductOrderItem()"}),arrExtraHeaderButtons:[m?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Order For '"+htmlEncode(o)+"'",doubleQuoteEncodedOnClickJS:"hideDialog();confirmDeleteProductOrderItem("+n+","+"unescape('"+escape(o)+"'))"}):null],fnSubmit:submitEditProductOrderItem});p.addFlexibleFieldRow({rawLabel:"Product",rawValue:o});p.addTextFieldRow("txtFirstPrice",{rawLabel:"First Term Invoiced Price ($)",fieldValue:padDollars(""+u),maxLength:8});if(!l){p.addTextFieldRow("txtPrice",{rawLabel:"Base Price ($)",fieldValue:padDollars(""+r),maxLength:8})}p.addExpandingTextFieldRows("txtNotes",{rawLabel:"Notes",value:c});i=p.showClientDialog();if(i){mjtElemData(i,"productOrderItemId",n)}}function showEditDBProductProductOrderItemDialog(e,t){jsrsExecuteWithErrorP("Admin2_GetProductOrderItemDetails2",rsCallbackHandleStandardJSONResponse,"Getting Order Item Details",{productOrderItemId:t},{fnOnSuccess:rsCallbackGetProductOrderItemDetailsForEdit})}function doDeleteProductOrderItem(e){jsrsExecuteWithErrorP("Admin2_DeleteProductOrderItem2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting order for "+e.productName,{productOrderItemId:e.productOrderItemId})}function confirmDeleteProductOrderItem(e,t){displaySimpleConfirmationDialog(doDeleteProductOrderItem,'Are you sure you want to delete the order for "'+htmlEncode(t)+'"?',"Delete Order",{productOrderItemId:e,productName:t})}function addSpecificProductAndQtyToOrder(e,t){jsrsExecuteWithErrorP("Admin2_AddProductToProductOrder2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Adding product to order",{productOrderId:e.productOrderId,productId:e.productId,pricingStructureId:e.pricingStructureId,quantity:t})}function submitAddSpecificProduct(){var e=getObj("frmAddProduct"),t=getCallbackDataOfDialog(e),a=e.cboQty,i=parseInt(a.options[a.selectedIndex].value,10);addSpecificProductAndQtyToOrder(t,i)}function rsCallbackGetProductDetailsForAddSpecificProduct(e,t){var a=t.originalPayload,i=e.arrProducts,o=i[0],n="frmAddProduct",r=o.termName,l=o.price,d=o.productTypeId===CRMProductType_Enum.crmptCounterGo?"":"$"+padDollars(l)+" "+htmlEncode(r),s=new ClientDialogBuilder({formId:n,formTitle:"Add Product",focusFieldName:"cboQty",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitAddSpecificProduct()"}),focusFieldOnMobile:1,fnSubmit:submitAddSpecificProduct,callbackData:{productOrderId:a.productOrderId,productId:a.productId}});s.addFlexibleFieldRow({rawLabel:"Product",rawValue:o.name});if(o.editionName){s.addFlexibleFieldRow({rawLabel:"Edition",rawValue:o.editionName})}s.addFlexibleFieldRow({rawLabel:"Base Price",rawValue:d});s.addFlexibleRow({valueHTML:""});s.addDialogInteriorRows(buildQuantityComboboxRow());s.showClientDialog()}function showAddSpecificProductToOrder(e){jsrsExecuteWithErrorP("Admin2_GetProductDetailsForAddToOrder2",rsCallbackHandleStandardJSONResponse,'Retrieving info for product, "'+e.productName,{productOrderId:e.productOrderId,productId:e.productId},{fnOnSuccess:rsCallbackGetProductDetailsForAddSpecificProduct})}function showAddSpecificProductCountSubmenu(e,t){var a=new ContextMenu,i;a.AddMenuItemP({rawText:'Custom Quantity of "'+t.productName+'"',inactive:1,isHeader:1});for(i=2;i<=10;++i){a.AddMenuItemP({rawText:""+i,leadItemIconId:FontIconId_Enum.fiiPlusInCircle,doubleQuoteReadyScript:"addSpecificProductAndQtyToOrder("+htmlEncode(JSON.stringify(t))+","+i+")"})}a.AddSeparatorIfNecessary();a.AddMenuItemP({rawText:"...",doubleQuoteReadyScript:"showAddSpecificProductToOrder("+htmlEncode(JSON.stringify(t))+")"});a.ShowSubmenu(e)}function buildPricingInfoText(e){var t=e.price,a=e.editionPrice,i=e.additionalUserPrice,o=e.tier2PerUserPrice,n=e.tier2StartUserCount,r=e.minUserCount,l=[];if(a){l.push("$"+padDollars(a)+" Base")}if(i){var d=a?" per Additional User":" per User";l.push("$"+padDollars(i)+d)}if(n&&o){l.push("$"+padDollars(o)+" for Users "+n+"+")}if(r){l.push("Minimum "+r+" Users")}if(l.length===0&&t){l.push("$"+padDollars(t))}return l.join(", ")}function buildProductPricingSuffix(e){var t=buildPricingInfoText(e),a="";if(t){a=" ("+t+")"}else if(e.priceGenerationName){a=" - "+e.priceGenerationName}return a}function buildRestartProductItemsForMenu(e){var t=e.restartProducts,a=e.productOrderId,i=[];for(var o=0;o",g=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),C=e.notes;if(a){f=b}else{f=b+' "}n=cdBuildReadOnlyFieldRowP({rawLabel:"Invoice Number",valueHTML:f})+cdBuildDatePickerRow(i,"dtInvoiceDate","Invoice Date",cdCarefullyLocalizeDateValue(e.invoiceDate?e.invoiceDate:m),o)+cdBuildDatePickerRow(i,"dtStartDate","Start Date",cdCarefullyLocalizeDateValue(u),o)+cdBuildDatePickerRow(i,"dtEndDate","End Date",cdCarefullyLocalizeDateValue(c),o);if(t){n+=cdBuildReadOnlyFieldRowP({rawLabel:"Tax Rate To Use",valueHTML:'"})+cdBuildReadOnlyFieldRowP({rawLabel:"",valueHTML:'(Invoice and Database Tax Rates Differ)'})+""}n+=cdBuildExpandingTextFieldRowsP("txtNotes","Notes",{value:C||""});showDialogP(n,i,{formTitle:a?"Edit Invoice":"New Invoice",focusFieldName:a?"txtInvoiceNumber":"dtInvoiceDate",arrExtraHeaderButtons:a&&g?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Invoice",doubleQuoteEncodedOnClickJS:"hideDialog();confirmDeleteInvoice(event,"+a+",unescape('"+escape(p)+"'))"})]:0,contextDetailOrFnSubmit:{fnSubmit:submitCreateOrUpdateInvoice,callbackData:{id:e.id,databaseId:e.databaseId,optionalAlternateTaxInfo:t}}});changedInvSpecType()}function rsCallbackGetInvoiceForEdit2(e){showInvoiceDialog(e.invoiceInfo,e.invoiceTaxRateDiffersFromDB?{dbTaxRateName:e.dbTaxRateName,dbTaxRateAmount:e.dbTaxRateAmount}:undefined)}function showCreateInvoiceDialog(e,t){jsrsExecuteWithErrorP("Admin2_GetDefaultInvoiceInfo2",rsCallbackGetInvoiceForEdit2,"Retrieving Database Info For New Invoice...",{databaseId:t})}function showEditInvoiceDialog(e,t){jsrsExecuteWithErrorP("Admin2_GetInvoiceInfo",rsCallbackGetInvoiceForEdit2,"Retrieving Invoice Info...",{invoiceId:t})}function doToggleShowOnHomepage(e){jsrsExecuteWithErrorP("Admin2_ToggleHideUnpaidInvoiceOnHomepage",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Toggling display on Homepage",{invoiceId:e.invoiceId,showOnHomepage:e.showOnHomepage})}function confirmToggleShowOnHomepage(t){hideDialogP({callback:function(){var e=t.showOnHomepage?"Show ":"Hide";displaySimpleConfirmationDialogP(function(){doToggleShowOnHomepage(t)},"Are you sure you want to "+e.toLowerCase()+" this invoice on the Homepage?",{formTitle:e+" Invoice On Homepage",okButtonDisplayText:e+" Invoice"})}})}function submitEmailInvoice(e,t){var a=t.invoice,i=new FormValidator;if(!i.CSValidateRequiredField(e.txtEmailFrom,'Please enter a sender name in the "From" field.')){return}if(!i.CSValidateRequiredField(e.txtEmailTo,'Please enter a recipient in the "To" field.')){return}if(!i.CSValidateRequiredField(e.txtEmailSubject,"Please enter a Subject.")){return}if(!i.CSValidateRequiredField(e.txtBillTo,"Please enter a Bill To value.")){return}jsrsExecuteWithErrorP("Admin2_EmailInvoiceToCustomer",refreshPageAndScrollPos,"Retrieving Invoice Info",{invoiceId:a.id,emailFromName:e.txtEmailFrom.value,customerEmailAddress:e.txtEmailTo.value,subject:e.txtEmailSubject.value,billTo:e.txtBillTo.value})}var g_invoiceChangeTimeout=null;function rsCallbackUpdateInvoicePreview(e){var t=getObj("cnrEmailInvoicePreview");if(t){t.innerHTML=e.preview}}function updateInvoicePreview(e){var t=getObj("frmEmailInvoice"),a=t?t.txtBillTo:null;g_invoiceChangeTimeout=null;if(a){jsrsExecuteWithErrorP("Admin2_GetEmailInvoiceInfo2",rsCallbackHandleStandardJSONResponse,"",{invoiceId:e,billTo:a.value,useDefaultBillTo:0},{fnOnSuccess:rsCallbackUpdateInvoicePreview,skipDisableDialogButtons:1,skipInfoMessage:1})}}function onChangeInvoicePreview(e){if(g_invoiceChangeTimeout){window.clearTimeout(g_invoiceChangeTimeout)}g_invoiceChangeTimeout=window.setTimeout(function(){updateInvoicePreview(e)},250)}function getInvoiceDateFormat(e){if(!e){return""}var t=e.getFullYear(),a=e.getMonth()+1,i=e.getDate();return t+"-"+(a<10?"0":"")+a+"-"+(i<10?"0":"")+i}function getInvDateRangeFromDates(e,t){var a=parseDateString(e),i=parseDateString(t),o=getInvoiceDateFormat(a)+" - "+getInvoiceDateFormat(i);return o}function showInvoicePreviewDialog(e){var t=e.invoice.id,a="frmEmailInvoice",i=getInvDateRangeFromDates(e.invoice.startDate,e.invoice.endDate),o=cdBuildTextFieldRowP("txtEmailFrom","Email From Name",{fieldValue:"Moraware Support"})+cdBuildTextFieldRowP("txtEmailTo","Email Invoice to",{fieldValue:e.customer.email||"",isEmail:1})+cdBuildTextFieldRowP("txtEmailSubject","Subject",{fieldValue:"Moraware Invoice for "+i,isEmail:1})+cdBuildTextAreaFieldRowP("txtBillTo","Bill To",{unencodedText:e.defaultBillTo,fieldId:"txtLicense",onChangeDoubleQuotedContent:"onChangeInvoicePreview("+t+")"})+'
'+'
Preview:
'+'
'+e.preview+"
";showDialogP(o,a,{formTitle:"Email Invoice",focusFieldName:"txtEmailTo",okButtonDisplayText:"Send Email",contextDetailOrFnSubmit:{fnSubmit:submitEmailInvoice,callbackData:e}})}function rsCallbackGetInvoiceForEmail(e){showInvoicePreviewDialog(e)}function showEmailInvoiceDialog(e,t){if(isDialogShowing()){return}jsrsExecuteWithErrorP("Admin2_GetEmailInvoiceInfo2",rsCallbackHandleStandardJSONResponse,"Retrieving Invoice Info",{invoiceId:t,billTo:"",useDefaultBillTo:1},{fnOnSuccess:rsCallbackGetInvoiceForEmail})}function rsCallbackDeleteInvoice(e){var t=e.databaseId,a=e.subdomainName;if(t){displayTimedMessage("Loading Database"+(a?' "'+htmlEncode(a)+'"':""));window.location=pageDatabaseDetail+t}else{refreshPageShowingMessage()}}function doDeleteInvoice(e){jsrsExecuteWithErrorP("Admin2_DeleteInvoice",rsCallbackDeleteInvoice,"Deleting Invoice",{invoiceId:e.invoiceId})}function confirmDeleteInvoice(e,t,a){displaySimpleConfirmationDialog(doDeleteInvoice,"Are you sure you want to delete Invoice #"+a+"?","Delete Invoice",{invoiceId:t,invoiceNumber:a})}function doGenerateInvoices(){jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_GenerateInvoices",[],enableDialogButtons);showInfoDialog("Generating invoices...","Generating Invoices");disableDialogButtons();displayTimedMessage("Generating Invoices...")}function submitGenerateNextInvoice(){var e="frmGenerateNextInvoice",t=getObj(e),a=mjtElemData(t,"databaseId"),i=mjtElemData(t,"nextInvoiceDate");hideDialog();jsrsExecuteWithErrorP("Admin2_GenerateNextInvoice2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Generating Next Invoice",{databaseId:a,nextInvoiceDate:i})}function rsCallbackGetNextInvoiceInfo(e){enableDialogButtons();var t="frmGenerateNextInvoice",a=e.displayedNextInvoiceDate,i=new ClientDialogBuilder({formId:t,formTitle:"Generate Next Invoice",focusFieldName:"btnOk",focusFieldOnMobile:1,fnSubmit:submitGenerateNextInvoice}),o;i.addFlexibleRow({rawValue:"This will generate invoices for the "+e.termName+" subscription up to and\n"+"including the Next Invoice Date of "+a+".\n"+"\n"+"Are you sure you want to generate the next invoice?"});o=i.showClientDialog();if(o){mjtElemData(o,"databaseId",e.databaseId);mjtElemData(o,"nextInvoiceDate",e.nextInvoiceDate)}}function showGenerateNextInvoiceDialog(e){if(isDialogShowing()){return}jsrsExecuteWithErrorP("Admin2_GetNextInvoiceInfoForDB",rsCallbackGetNextInvoiceInfo,"Getting Next Invoice Info for Subscription",{databaseId:e})}function showSubscriptionExtraMenu(e){var t=e.arrMenuInfos,a,i,o=new ContextMenu;for(i=0;i'+n+""});l.addDatePickerRow(t,"dtNextInvoiceDate",{rawLabel:"Next Invoice Date",strValue:cdCarefullyLocalizeDateValue(r||"")});l.addTextFieldRow("txtQBId",{rawLabel:"QuickBooks Id",fieldValue:(a.qbId||"")+"",maxLength:209,hideRow:!i});d=l.showClientDialog();if(d){mjtElemData(d,"databaseId",i)}}function showEditSubscriptionDialog(e){jsrsExecuteWithErrorP("Admin2_GetSubscription",rsCallbackHandleStandardJSONResponse,"Retrieving Subscription For Edit",{databaseId:e},{fnOnSuccess:rsCallbackGetSubscriptionForEdit})}function rsCallbackGetSubscriptionForCreateOrder(e){var t=e,a="frmCreateOrder",i=new Date,o=getDateAsDisplayString(i),n=new ClientDialogBuilder({formId:a,formTitle:"New Order",okButtonDisplayText:"Create",focusFieldName:"dtStartDate",focusFieldOnMobile:1,fnSubmit:submitCreateOrder}),r;n.addDatePickerRow(a,"dtStartDate",{rawLabel:"StartDate",strValue:o});n.addFlexibleFieldRow({rawLabel:"Billing Term",rawValue:t.termName});r=n.showClientDialog();if(r){mjtElemData(r,"subscription",t)}}function showCreateOrderDialog(e){jsrsExecuteWithErrorP("Admin2_GetSubscription",rsCallbackHandleStandardJSONResponse,"Retrieving Subscriptions",{databaseId:e},{fnOnSuccess:rsCallbackGetSubscriptionForCreateOrder,databaseId:e})}function rsCallbackCreatedPayment(e){hideDialog();window.location=pagePaymentDetail+e.paymentId}function getPaymentTransactionLabel(){var e=getObj("frmPayment"),t=e.cboPaymentMethod,a=t&&t.options[t.selectedIndex].value==="Check";return a?"Check #":"Transaction Id"}function postTransIdValidationSubmitEditOrAddPayment(e){if(e.paymentId){jsrsExecuteWithErrorP("Admin2_UpdatePayment2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Payment",e)}else{jsrsExecuteWithErrorP("Admin2_CreatePayment2",rsCallbackCreatedPayment,"Creating Payment",e)}}function submitEditOrAddPayment(e,t){var a=new FormValidator,i=t.id,o=t.forceDiscount,n=t.isChargeback,r=e.txtAmount,l=e.cboPaymentMethod,d=o?"Discount":l.options[l.selectedIndex].value,s=d==="Discount",u=t.creditMemoId||"",c=e.txtProcessor,m=i?c.value:"",p=e.txtTransactionId,f=s?"":trim(p.value),b=e.txtBillingProcessorCustomerId,g=i||n?b.value:"",C=e.cboPaymentType,D=n?PaymentType_Enum.ptCredit:i?C.options[C.selectedIndex].value:""+PaymentType_Enum.ptSale,h=i?getDateForUrlParam(e.dtCardExpirationDate.value):"",w=i?e.txtCardDigits.value:"",T=cdGetExpandingTextFieldValue("txtComment1"),S=cdGetExpandingTextFieldValue("txtComment2"),y=d==="Check",I=d==="Wire Transfer",x=y?"Check #":"Transaction Id",v=!(s||y||I||n),P=!f&&((t.wasTransactionId||!i)&&(y||I||n)),R={};if(!a.CSValidateNumberFieldP({field:r,label:"Amount",isNullable:false,resultValueHolder:R})){return}if(!trim(d)){showInfoDialog("Please select a payment method.","Missing Payment Method",1,"cboPaymentMethod");return}if(i&&!a.CSValidateRequiredField(c,"Please enter a Payment Processor")){return}if(v&&!a.CSValidateRequiredField(p,"Please enter a "+getPaymentTransactionLabel())){return}var E={paymentId:i||"",amount:R.rc,paymentMethod:d,paymentProcessor:m,transactionId:f,billingProcessorCustomerId:g,paymentType:D,comment1:T,comment2:S,ccExpiration:h,ccDigits:w,creditMemoId:u,invoiceId:(u?"":t.invoiceId)||""};if(P){displaySimpleConfirmationDialog(postTransIdValidationSubmitEditOrAddPayment,"Are you sure you don't want to enter a "+x+"?","Omit "+x,E,1,"txtTransactionId");return}postTransIdValidationSubmitEditOrAddPayment(E)}function buildDBSelector(e,t){var a='"}function buildPaymentTypeDropdownRow(e){var t={},a='";return cdBuildReadOnlyFieldRowP({rawLabel:"Payment Type",valueHTML:a})}function updatePaymentTransactionLabel(){var e=getObj("spnPaymentTransactionLabel");if(e){e.innerHTML=getPaymentTransactionLabel()}}function buildPaymentMethodDropdownRow(e,t){var a={},i='";return cdBuildReadOnlyFieldRowP({rawLabel:"Payment Method",valueHTML:i})}function showPaymentDialog(e){var t=e.isDiscount,a=e.id,i="frmPayment",o=e.processor?e.processor:a?"":"Manual",n=e.subdomain,r=e.customerName,l=e.databaseId,d=e.invoiceNumber,s=e.invoiceTotalDue,u=e.invoiceTotalPaid,c=e.creditMemoTotalWithTax,m=e.creditMemoTotalCredited,p=e.invoiceDate,f=e.creditMemoDate,b=e.creditMemoNumber,g=e.isChargeback,C=e.transactionId&&!t?""+e.transactionId:"",D=(a?"Edit":"New")+(t?" Discount":" Payment"),h=new ClientDialogBuilder({formId:i,formTitle:D,fnSubmit:submitEditOrAddPayment,focusFieldName:"txtAmount",arrExtraHeaderButtons:[a&&!t?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Payment",doubleQuoteEncodedOnClickJS:"confirmDeletePayment("+a+")"}):null],callbackData:{id:a,databaseId:l,invoiceId:e.invoiceId,creditMemoId:e.creditMemoId,forceDiscount:t?1:0,wasTransactionId:C?1:0,isChargeback:g?1:0}});if(g&&!a){h.addDialogInteriorRows("
"+'
'+"WARNING: If you are not entering a Chargeback, you do not want this dialog! "+" "+'(This is NOT how you issue a credit!)'+"
')}h.addTextFieldRow("txtAmount",{labelHTML:"Amount ($)",fieldValue:""+(e.amount?e.amount:""),maxLength:10});if(!t){h.addDialogInteriorRows(buildPaymentMethodDropdownRow(g?"":e.method,g))}if(a){h.addTextFieldRow("txtProcessor",{labelHTML:"Payment Processor",fieldValue:o,maxLength:20})}if(!t){h.addTextFieldRow("txtTransactionId",{labelHTML:'Transaction Id',fieldValue:C,maxLength:20})}if(a||g){h.addTextFieldRow("txtBillingProcessorCustomerId",{labelHTML:"Billing Id",fieldValue:e.billingProcessorCustomerId||"",maxLength:12})}if(a){h.addDialogInteriorRows(buildPaymentTypeDropdownRow(e.paymentTypeId)+cdBuildDatePickerRow(i,"dtCardExpirationDate","Card Expires",cdCarefullyLocalizeDateValue(e.ccExpiration||"")));h.addTextFieldRow("txtCardDigits",{labelHTML:"Last 4 Digits of CC",fieldValue:e.ccDigits,maxLength:4})}h.addDialogInteriorRows(cdBuildExpandingTextFieldRowsP("txtComment1","Comments",{value:e.comment1||""})+cdBuildExpandingTextFieldRowsP("txtComment2","Comments 2",{value:e.comment2||"",hideRow:!a}));if(a){h.addFlexibleFieldRow({rawLabel:"Bulk Import",rawValue:e.bulkImport?"Yes":"No"})}h.showClientDialog();updatePaymentTransactionLabel()}function submitAddProductsToInvoice(){var e="frmInvoiceProduct",t=getObj(e),a=getListOfCheckedRowValuesWithParams({form:t,buildRCArray:1,minSelected:1,tooFewWarning:"Please select a DB Product",clientDlgParams:{subdialogDismisalFocusFieldName:"chkCheckAllRows",subdialog:1}}),i=a.arrValues;if(!i.length){return}jsrsExecuteWithErrorP("Admin2_AssignMultipleProductsToInvoice",refreshPageAndScrollPos,"Adding Invoiced Products",{invoiceId:mjtElemData(t,"invoiceId"),arrDBProducts:i.map(function(e){return JSON.parse(e)})})}function showAddProductsToInvoiceDialog(e){var t="Add Product To Invoice",a="frmInvoiceProduct",i=e.arrProducts,o=new MWClientTable({fnGetCheckDetailsForRow:function(e,t,a){return{value:htmlEncode(JSON.stringify({databaseProductId:e.id,price:e.price}))}}}),n=new ClientDialogBuilder({formId:a,formTitle:t,okButtonDisplayText:"Add",focusFieldName:"chkCheckAllRows",focusFieldOnMobile:1,fnSubmit:submitAddProductsToInvoice}),r;if(!i.length){showInfoDialog("There are no Products available to be added.","No Products");return}o.addColumn(new MWColumn({columnName:"Product",simpleDisplayColumnPropertyName:"productName"}));o.addColumn(new MWColumn({columnName:"Price",fnCustomRenderCellContents:function(e,t,a,i){return padAndPrefixSignedDollars(e.price)},additionalCellClasses:"rightAlign"}));o.addColumn(new MWColumn({columnName:"DB Product Id",simpleDisplayColumnPropertyName:"id",additionalCellClasses:"rightAlign"}));n.addFlexibleRow({valueHTML:o.buildTableForArray(i)});r=n.showClientDialog();if(r){consoleLog("Trying to set invoice id...params_=\n"+JSON.stringify(e,null,2));mjtElemData(r,"invoiceId",e.invoiceId)}}function submitUpdateInvoiceProduct(e,t){var a=new FormValidator,i=cdGetExpandingTextFieldValue("txtNotes"),o=a.CSValidateNumberField(e.txtPrice,"Price",false);if(!o){return}jsrsExecuteWithErrorP("Admin2_UpdateInvoiceProduct2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Invoiced Product",{invoiceId:t.invoiceId,databaseProductId:t.databaseProductId,price:trim(e.txtPrice.value),notes:i})}function showEditInvoiceProductDialogForObj(e){var t=e.databaseProductId,a="frmInvoiceProduct",i=""+(e.price||""),o=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),n=new ClientDialogBuilder({formId:a,formTitle:"Update Invoiced Product Price",okButtonDisplayText:"Save",focusFieldName:"txtPrice",focusFieldOnMobile:1,arrExtraHeaderButtons:[o?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Invoice Product",doubleQuoteEncodedOnClickJS:"hideDialog();"+"confirmDeleteInvoiceProduct("+t+","+e.invoiceId+","+"unescape('"+escape(e.productName)+"'))"}):null],fnSubmit:submitUpdateInvoiceProduct,callbackData:e});n.addFlexibleFieldRow({rawLabel:"Product",rawValue:e.productName});n.addTextFieldRow("txtPrice",{rawLabel:"Price ($)",fieldValue:i,maxLength:8});n.addExpandingTextFieldRows("txtNotes",{rawLabel:"Notes",value:e.invoiceDBProductNotes});n.showClientDialog()}function rsCallbackGetProductsForInvoiceProductDialog(e,t,a){enableDialogButtons();if(checkResponseForError(e)){var i=JSON.parse(e),o=i.arrProducts;a.arrProducts=o?o:0;showAddProductsToInvoiceDialog(a)}}function getProductsForInvoiceProductDialog(e){jsrsExecute(rsCallbackGetProductsForInvoiceProductDialog,"Admin_GetDatabaseProducts",[e.databaseId,e.invoiceId],enableDialogButtons,e);displayTimedMessage("Getting products for the invoice");disableDialogButtons()}function showAddProductToInvoice(e,t,a){if(isDialogShowing()){return}getProductsForInvoiceProductDialog({databaseId:t?t:0,invoiceId:a?a:0})}function rsCallbackGetInvoiceProductForEdit(e,t,a){enableDialogButtons();if(checkResponseForError(e)){var i=JSON.parse(e);showEditInvoiceProductDialogForObj(i)}}function showEditInvoiceProductDialog(e,t){jsrsExecute(rsCallbackGetInvoiceProductForEdit,"Admin_GetInvoiceProduct",[t,e],enableDialogButtons,{});displayTimedMessage("Getting invoice product to edit...");disableDialogButtons()}function doDeleteInvoiceProduct(e){jsrsExecuteWithErrorP("Admin2_DeleteInvoiceProduct2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting product from invoice",{invoiceId:e.invoiceId,databaseProductId:e.databaseProductId})}function confirmDeleteInvoiceProduct(e,t,a){displaySimpleConfirmationDialog(doDeleteInvoiceProduct,'Are you sure you want to delete "'+htmlEncode(a)+'" from the invoice?',"Delete Product",{invoiceId:t,databaseProductId:e})}function rsCallbackGetInvoiceInfoForNewPayment(e){var t=e.database,a=e.invoice;showPaymentDialog({databaseId:t.id,subdomain:t.subdomain,customerName:t.customerName,invoiceId:a.id,invoiceNumber:a.invoiceNumber,invoiceTotalDue:a.totalDue,invoiceTotalPaid:a.totalPaid,invoiceDate:a.invoiceDate})}function showCreatePaymentDialog(e){jsrsExecuteWithErrorP("Admin2_GetInvoiceInfoForNewPayment2",rsCallbackGetInvoiceInfoForNewPayment,"Getting Invoice Info For New Payment",{invoiceId:e})}function rsCallbackGetCreditMemoInfoForNewPayment(e){var t=e.database,a=e.creditMemo;showPaymentDialog({databaseId:t.id,subdomain:t.subdomain,customerName:t.customerName,invoiceNumber:a.invoiceNumber,isChargeback:1,comment1:"This is a chargeback.",creditMemoId:a.id,creditMemoNumber:a.creditMemoNumber,creditMemoDate:a.creditMemoDate,creditMemoTotalDue:a.totalBeforeTax,creditMemoTotalCredited:a.totalCredited,creditMemoTotalWithTax:a.totalWithTax,amount:a.totalWithTax-a.totalCredited,billingProcessorCustomerId:e.billingProcessorCustomerId,processor:"Manual"})}function showCreateCreditMemoChargebackPaymentDialog(e){jsrsExecuteWithErrorP("Admin2_GetCreditMemoInfoForNewPayment2",rsCallbackHandleStandardJSONResponse,"Getting Credit Memo Info For New Payment",{creditMemoId:e},{fnOnSuccess:rsCallbackGetCreditMemoInfoForNewPayment})}function rsCallbackGetPaymentInfoForEdit(e){showPaymentDialog(e)}function showEditPaymentDialog(e){jsrsExecuteWithErrorP("Admin2_GetPaymentInfo",rsCallbackHandleStandardJSONResponse,"Retrieving Payment",{paymentId:e},{fnOnSuccess:rsCallbackGetPaymentInfoForEdit})}function doDeletePayment(e){jsrsExecuteWithErrorP("Admin2_DeletePayment2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting Payment",{paymentId:e.paymentId})}function confirmDeletePayment(e){hideDialogP({callback:function(){displaySimpleConfirmationDialog(doDeletePayment,"Are you sure you want to delete the payment?","Delete Payment",{paymentId:e})}})}function submitApplyPaymentToDB(e,t){var a=0,i,o,n,r,l,d=t.isCredit,s=t.applyCreditToPayment;while(!n){i=getObj("rbPaymentTarget"+a);if(i.checked){o=i.value;n=JSON.parse(unescape(o))}++a}if(s){r="Admin2_ApplyCreditToPayment2";l={creditId:t.payment.id,paymentId:n.id}}else if(d){r="Admin2_ApplyPaymentToCreditMemo2";l={paymentId:t.payment.id,creditMemoId:n.id}}else{r="Admin2_ApplyPaymentToInvoice2";l={paymentId:t.payment.id,invoiceId:n.id}}jsrsExecuteWithErrorP(r,rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Applying Payment",l)}function buildCreditMemoSelectionRow(e,t){var a=new MWClientTable({noDataMessage:"No Credit Memos!"});a.addColumn(new MWColumn({columnName:"Credit Memo #",fnCustomRenderCellContents:function(e,t,a,i){var o={id:e.id,totalUncredited:e.totalUncredited},n="rbPaymentTarget"+i;return'"}}));if(t){a.addColumn(new MWColumn({columnName:"Customer Name",simpleDisplayColumnPropertyName:"customerName"}));a.addColumn(new MWColumn({columnName:"Database",simpleDisplayColumnPropertyName:"subdomain"}))}a.addColumn(new MWColumn({columnName:"Total Due To Be Credited",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(e,t,a,i){return"$"+padDollars(e.totalDueToBeCredited,1,1)}}));a.addColumn(new MWColumn({columnName:"Total Uncredited",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(e,t,a,i){return"$"+padDollars(e.totalUncredited,1,1)}}));return'
'}function rsCallbackImportFromPaymentProcessors(e,t){var a=t.originalOptions||{},i=e.arrNewOrUpdatedPayments,o=i.length,n=e.reportRecordCount,r=e.newSucessfulImportCount,l=e.newFailureCount,d=e.changedCount,s=e.unchangedCount,u=e.ignoredRecordCount,c=l+r+d+s+u,m="frmInfo",p=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:m,formTitle:"Payments Imported",fnCancelOrClose:function(){hideDialog();if(o||a.forceRefresh){refreshPageShowingMessage()}}});if(c){if(n!==c){p.addFlexibleRow({rawValue:'# of records in the Report doesn\'t match the # of payments found!'});p.addFlexibleFieldRow({rawLabel:"Total Records In Report",rawValue:""+e.reportRecordCount});p.addFlexibleRow({rawValue:""});if(r){p.addFlexibleFieldRow({rawLabel:"Successful",rawValue:""+r})}if(d){p.addFlexibleFieldRow({rawLabel:"Updated",rawValue:""+d})}if(s){p.addFlexibleFieldRow({rawLabel:"Unchanged",rawValue:""+s})}if(l){p.addFlexibleFieldRow({rawLabel:"Failed",rawValue:""+l})}if(u){p.addFlexibleFieldRow({rawLabel:"Ignored",rawValue:""+u})}p.addFlexibleFieldRow({rawLabel:"Total Payments Found",rawValue:""+c});p.addFlexibleRow({rawValue:""})}else if(s===c){p.addFlexibleFieldRow({rawLabel:"Total Payments",rawValue:""+c+(s===c?" (Unchanged)":"")})}if(r||l){if(r){p.addFlexibleFieldRow({rawLabel:"New (Successful) Imports",rawValue:""+r})}if(l){p.addFlexibleFieldRow({rawLabel:"New (Failed) Imports",rawValue:""+l})}}if(d){p.addFlexibleFieldRow({rawLabel:"Updated",rawValue:""+d})}if(u){p.addFlexibleFieldRow({rawLabel:"Imports Ignored Due To Result Code",rawValue:""+u})}if(o){p.addSectionHeaderRow({rawTitle:"New/Updated Payments"});var f=new MWClientTable({});f.addColumn(new MWColumn({columnName:"Transaction",simpleDisplayColumnPropertyName:"transactionId"}));f.addColumn(new MWColumn({columnName:"Timestamp",simpleDisplayColumnPropertyName:"timestamp"}));if(d){f.addColumn(new MWColumn({columnName:"Change/Discrepancy Description",simpleDisplayColumnPropertyName:"changeDescription",simpleDisplayColumnNeedsMultilineEncoding:1}))}f.addColumn(new MWColumn({columnName:"Amount",simpleDisplayColumnPropertyName:"amount",additionalCellClasses:"rightAlign",additionalHeaderClasses:"rightAlign"}));var b=f.addColumn(new MWColumn({columnName:"Credit Card",additionalHeaderClasses:"centerAlign"}));b.addSubColumn(new MWColumn({columnName:"Expires",simpleDisplayColumnPropertyName:"ccExp",additionalCellClasses:"rightAlign",additionalHeaderClasses:"rightAlign"}));b.addSubColumn(new MWColumn({columnName:"Digits",simpleDisplayColumnPropertyName:"ccDigits",additionalCellClasses:"rightAlign",additionalHeaderClasses:"rightAlign"}));f.addColumn(new MWColumn({columnName:"Method",simpleDisplayColumnPropertyName:"method",additionalCellClasses:"centerAlign",additionalHeaderClasses:"centerAlign"}));f.addColumn(new MWColumn({columnName:"Type",simpleDisplayColumnPropertyName:"type",additionalCellClasses:"centerAlign",additionalHeaderClasses:"centerAlign"}));f.addColumn(new MWColumn({columnName:"Result",simpleDisplayColumnPropertyName:"resultMessage",additionalCellClasses:"centerAlign",additionalHeaderClasses:"centerAlign",fnAdditionalCellClasses:function(e,t,a,i){if(e.resultCode){return"errorText"}return""}}));f.addColumn(new MWColumn({columnName:"Comment",simpleDisplayColumnPropertyName:"comment1",simpleDisplayColumnNeedsMultilineEncoding:1}));p.addFlexibleRow({valueHTML:f.buildTableForArray(i)})}}else{p.addFlexibleRow({rawValue:"No payments"})}hideDialog();p.showClientDialog()}function submitImportPaymentProcessorPayments(e,t){hideDialog();t=t||{};var a=new FormValidator,i,o=t.useSpecificDate,n="";if(e&&o){i=e.dtDate;if(!a.CSValidateDateField(i,"Date",false,"dtDate")){return}n=getDateForUrlParam(i.value)}jsrsExecuteWithErrorP("Admin2_ImportFromPaymentProcessors",rsCallbackHandleStandardJSONResponse,"Importing Payments",{transactionDate:n},{fnOnSuccess:rsCallbackImportFromPaymentProcessors,forceRefresh:t.forceRefreshOnCancel})}function rsCallbackGeneratePaymentDates(e){if(!e.count){showInfoDialog("No payment dates were generated","Generate Payment Dates",0,null);return}var t=new ClientDialogBuilder({formId:"generatePaymentDates",formTitle:"Generate Payment Dates",focusFieldOnMobile:1,suppressDialogConfirmer:1,fnCancelOrClose:refreshPageAndScrollPos});t.addFlexibleFieldRow({rawLabel:"# of Generated Automated Payment Status Records",rawValue:""+e.count});t.showClientDialog()}function showGeneratePaymentDatesDialog(){displaySimpleConfirmationDialog(function(){hideDialog();jsrsExecuteWithErrorP("Admin_GeneratePaymentDates",refreshPageAndScrollPos,"Generate Payment Dates",{})},"Are you sure you want to generate payment dates? "+" "+"NOTE: This action can't be undone.","Generate Payment Dates",{})}function promptPayInvoicesForPaymentDates(){var e=new ClientDialogBuilder({formTitle:"Run Automated Payments",okButtonDisplayText:"Run",focusFieldName:"btnOk",fnSubmit:function(){hideDialog();jsrsExecuteWithErrorP("Admin2_RunAutomatedPayments",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Run Automated Payments")}});e.addFlexibleRow({valueHTML:"Are you sure you want to run automated payments? "+" "+"
(Payments will only be applied up through the Last Bulk Invoice Generation Date)
"});e.showClientDialog()}function promptGenerateInvoices(){var e=new ClientDialogBuilder({formTitle:"Generate Invoices",okButtonDisplayText:"Generate",focusFieldName:"btnOk",fnSubmit:function(){hideDialog();doGenerateInvoices()}});e.addFlexibleRow({valueHTML:"Are you sure you want to Generate Invoices?"});e.showClientDialog()}function rsCallbackSimulateGeneratePaymentDates(e){var t=e.initialValues,a=e.generationDates||"",i=e.arrAutopayStatusCounts,o=e.arrUpdatedDBDates,n=i?i.length:0,r,l,d=new ClientDialogBuilder({formTitle:"Simulated Payment Date Generation"}),s=new MWClientTable({fnAdditionalRowAttrs:function(e){return"data-rowData='"+escape(JSON.stringify(e))+"'"}});delete e.initialValues;delete e.generationDates;delete e.arrAutopayStatusCounts;delete e.arrUpdatedDBDates;s.addColumn(new MWColumn({columnName:"Database",simpleDisplayColumnPropertyName:"subdomainName",additionalHeaderClasses:"centerAlign",sortInfo:{},fnBuildCellLinkDetail:function(e){if(e.databaseId){return new MWCellLinkDetail({simpleLink:pageDatabaseDetail+e.databaseId,dialogLink:1})}return null}}));s.addColumn(new MWColumn({columnName:"Autopay Date",simpleDisplayColumnPropertyName:"oldDate",additionalHeaderClasses:"centerAlign",arrSubColumns:[new MWColumn({columnName:"Old",simpleDisplayColumnPropertyName:"oldDate",additionalHeaderClasses:"centerAlign",sortInfo:{}}),new MWColumn({columnName:"New",simpleDisplayColumnPropertyName:"newDate",additionalHeaderClasses:"centerAlign",sortInfo:{}})]}));s.addColumn(new MWColumn({columnName:"Autopay Status",additionalHeaderClasses:"centerAlign",arrSubColumns:[new MWColumn({columnName:"Old",simpleDisplayColumnPropertyName:"oldStateHtml",simpleDisplayColumnIsAlreadyEncoded:true,additionalHeaderClasses:"centerAlign",sortInfo:{}}),new MWColumn({columnName:"New",simpleDisplayColumnPropertyName:"newStateHtml",simpleDisplayColumnIsAlreadyEncoded:true,additionalHeaderClasses:"centerAlign",sortInfo:{}})]}));d.addSectionHeaderRow({rawTitle:"Generated Payment Dates"});d.addFlexibleRow({valueHTML:s.buildTableForArray(o)});d.addSectionHeaderRow({rawTitle:"Factors Considered During Generation"});d.addFlexibleFieldRow({rawLabel:"Min Minutes Between Autopay Attempts",rawValue:""+t.minMinutesBetweenAutopayAttempts,additionalCellClasses:"clsNarrowField"});d.addFlexibleFieldRow({rawLabel:"Last Invoice Generation",rawValue:t.lastInvoiceGenerationDate});d.addFlexibleFieldRow({rawLabel:"First Payment Date To Generate",rawValue:t.firstPaymentDateToGenerate});d.addFlexibleFieldRow({rawLabel:"Latest Date To Generate Payments For",rawValue:t.latestDateToGeneratePaymentsFor});d.addFlexibleFieldRow({rawLabel:"Old Last Generated Payment Date",rawValue:t.oldLastGeneratedPaymentDate});for(r=0;r(Import all payments posted on a single, specific date)'+" "});n.addDatePickerRow(o,"dtDate",{rawLabel:"Payment Transaction Date",strValue:t});n.addFlexibleRow({valueHTML:""+'
CAUTION:
'+" "+'
'+"If you proceed to import payments occurring on this "+"specific date, you will no longer be able to automatically "+"import payments from an earlier date! "+" "+"Unless you have good reason to do otherwise, you should "+'always choose to simply <Import Payments> instead.'+"
"});n.showClientDialog()}else{submitImportPaymentProcessorPayments(null,{forceRefreshOnCancel:a})}}function submitUpdateTaxes(){var e="frmUpdateTaxes",t=getObj(e),a=mjtElemData(t,"arrChanged"),i=[],o,n;for(n=0;n(The following rates will remain unchanged)':'
(None of the existing tax rates have changed)
',additionalCellClasses:"leftAlign"});m.addFlexibleRow({valueHTML:u.buildTableForArray(i)})}s=m.showClientDialog();if(s){mjtElemData(s,"arrChanged",o)}}function screenTaxesForUpdate(){var e="frmUpdateTaxesStep1",t=getObj(e),a=mjtElemData(t,"state"),i=t.txtTaxes.value,o=String.fromCharCode(9),n=i.split("\n"),r="",l,d,s=[],u,c,m,p,f,b,g,C,D=1;if(a==="Utah"){g="UT-";f=1;b=0;C=null}else if(a==="Washington"){g="WA-";f=3;b=0;C=null;D=100}else if(a==="Ohio"){g="OH-";f=2;b=0;C=1}for(l=0;l1){c=u[b];m=trim(u[f]);if(c){c=g+c.replace("-","");if(null!==C){c+="-";c+=parseInt(u[C],10).toString()}if(m.length&&m.substring(m.length-1)==="%"){m=trim(m.substring(0,m.length-1))}p=parseFloat(m)*D;s[s.length]={name:c,rate:p}}else{r="\n"+d}}else{r="\n"+d}}}if(!s.length){if(r){showInfoDialog("There was no valid data found. "+"The following text could not be parsed (Is it tab-delimited?): "+" "+htmlMultilineEncode(r),"No Usable Data",1,"txtTaxes")}else{showInfoDialog("There is nothing to submit!","No Data",1,"txtTaxes")}return}jsrsExecuteWithErrorP("Admin2_CheckBatchTaxesForUpdate2",rsCallbackHandleStandardJSONResponse,"Checking to see which taxes need updating",{arrNewRates:s},{fnOnSuccess:rsCallbackCheckBatchTaxesForUpdate})}function showUpdateTaxesDialog(e){var t="";if(e==="Utah"){t='
'+"Enter two, tab-delimitted columns with the County/City Code and the Tax Rate (%) "+" "+'as found on the Utah State Tax Commission Website: e.g.)'+"
"+'
'+"
01-313
2.5%
"+"
03-561
5.5%
"+"
03-600
5.4%
"+'
...
'+"
"}else if(e==="Washington"){t='
'+"Enter four, tab-delimitted columns with the Location Code, Local Rate, State Rate and the Combined Sales Tax(%) "+'as found on the Washington State Department of Revenue Website: eg.)'+"
"}var a="frmUpdateTaxesStep1",i,o=new ClientDialogBuilder({formId:a,formTitle:"Update "+e+" Tax Rates",focusFieldName:"txtTaxes",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"screenTaxesForUpdate()"}),fnSubmit:screenTaxesForUpdate});o.addFlexibleRow({valueHTML:t});o.addTextAreaFieldRow("txtTaxes",{rawLabel:"Taxes",mnemonicChar:"t",labelAbove:1,rowCount:18,autofocus:1});i=o.showClientDialog();if(i){mjtElemData(i,"state",e)}}function showUserEventLog(e,t,a,i,o){var n="";if(t){n+="pageSize="+t}if(a){n+="&from="+trim(getDateForUrlParam(a))}if(i){n+="&to="+trim(getDateForUrlParam(i))}if(o){n+="&dateCount="+trim(o)}window.location=pageUserEventLog+e+(n?"?":"")+n}function submitChangeLogOptions(){var e="frmChangeLogOptions",t=getObj(e),a=t.cboUsers,i=a.options[a.selectedIndex].value,o=new FormValidator,n=t.pageSize,r=getObj("rbDateRange"),l=r&&r.checked,d=t.dtFrom,s=t.dtTo,u=t.txtDateCount,c="",m="",p="";if(!o.CSValidateIntegerField(n,"Page Size",true,1,2e3)){return}if(l){if(!o.CSValidateDateField(d,"From",true)){return}if(!o.CSValidateDateField(s,"To",true)){return}if(!trim(d.value)&&!trim(s.value)){showInfoDialog("Please specify a Range of Dates.","Missing Date Range",1,"dtFrom");return}c=d.value;m=s.value}else{if(!o.CSValidateIntegerField(u,"Number of Days",false,1,9999)){return}p=u.value}hideDialog();showUserEventLog(i,parseInt(trim(n.value),10),c,m,p)}function elDateRangeChanged(){var e=getObj("frmChangeLogOptions"),t=getObj("rbDateRange"),a=t&&t.checked;if(e){e.dtFrom.disabled=!a;e.dtTo.disabled=!a;e.txtDateCount.disabled=a}}function rsCallbackGetUsersForOptions(e,t,a){enableDialogButtons();if(checkResponseForError(e)){var i=a.userId,o=a.pageSize,n="frmChangeLogOptions",r=" onkeypress=\"return submitClientDialogOnEnter('"+n+"',event);\"",l="",d,s=JSON.parse(e),u=s.arrUsers,c,m,p=cdBuildDatePickerField(n,"dtFrom",a.dateFrom,r,""),f=cdBuildDatePickerField(n,"dtTo",a.dateTo,r,""),b,g,C=a.dateCount,D="Last "+buildTextField("txtDateCount",""+(C?C:7),r,4,"4em")+" Days",h=!C,w=new ClientDialogBuilder({formId:n,formTitle:"Change Log Options",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"alert('Hello')"}),focusFieldName:"cboUsers",focusFieldOnMobile:1,fnSubmit:submitChangeLogOptions}),T;for(d=0;d"+htmlEncode(c.email)+""}b="elDateRangeChanged()";g="
"+"
"+'
From:
'+"
"+"
"+p+"
"+"
"+"
"+'
To:
'+"
"+"
"+f+"
"+"
"+"
";w.addFlexibleFieldRow({rawLabel:"User",valueHTML:'"});w.addFlexibleFieldRow({labelHTML:cdBuildRBP("rbDateType","rbDateRange","Range of Dates ",{checked:h,onClickCode:b,forceLabelOnTheLeft:1}),valueHTML:g,suppressLabelColon:1});w.addFlexibleFieldRow({labelHTML:cdBuildRBP("rbDateType","rbDateCount","Number of Days ",{checked:!h,onClickCode:b,forceLabelOnTheLeft:1}),valueHTML:D,suppressLabelColon:1});w.addTextFieldRow("pageSize",{rawLabel:"Events/Page",fieldValue:""+o,isNumber:1,maxValue:2e3});w.showClientDialog();elDateRangeChanged()}}function showChangeLogOptions(e,t,a,i,o,n){jsrsExecute(rsCallbackGetUsersForOptions,"Admin_GetUsers",[],enableDialogButtons,{userId:t?t:0,pageSize:a,dateCount:i,dateFrom:o,dateTo:n})}function eventLogObjectMenu(e,t,a,i){var o=new ContextMenu,n;if(g_isDoubleClickEvent){window.location=pageEventLog+t+"/"+a;return}if(t===EventObjectType_Enum.eotUser){n='View changes to "'+i+'"'}else{n='View Change Log for "'+i+'"'}o.AddLinkItem(n,pageEventLog+t+"/"+a,"",1);switch(t){case EventObjectType_Enum.eotInvoice:o.AddSeparatorIfNecessary();o.AddLinkItem('View Invoice "'+i+'"',pageInvoiceDetail+a);break;case EventObjectType_Enum.eotCreditMemo:o.AddSeparatorIfNecessary();o.AddLinkItem('View Credit Memo "'+i+'"',pageCreditMemoDetail+a);break;case EventObjectType_Enum.eotPayment:o.AddSeparatorIfNecessary();o.AddLinkItem('View Payment "'+i+'"',pagePaymentDetail+a);break;case EventObjectType_Enum.eotDatabase:o.AddSeparatorIfNecessary();o.AddLinkItem('View Database "'+i+'"',pageDatabaseDetail+a);break;case EventObjectType_Enum.eotCustomer:o.AddSeparatorIfNecessary();o.AddLinkItem('View Customer "'+i+'"',pageCustomerDetail+a);break;case EventObjectType_Enum.eotProduct:o.AddSeparatorIfNecessary();o.AddLinkItem("View Products",pageSystemSettingsProducts);break;case EventObjectType_Enum.eotUser:o.AddSeparatorIfNecessary();o.AddLinkItem("View changes made by "+htmlEncode(i),pageUserEventLog+a);break;case EventObjectType_Enum.eotDatabaseProduct:break;case EventObjectType_Enum.eotSalesperson:case EventObjectType_Enum.eotOnboarder:break}o.Show(e)}function systemEventLogMenu(e){var t=new ContextMenu;if(g_isDoubleClickEvent){window.location=pageSystemEventLog;return}t.AddLinkItem("View changes made by the system",pageSystemEventLog,"",1);t.Show(e)}function jtUserEventLogMenu(e,t,a,i,o){var n=new ContextMenu;if(g_isDoubleClickEvent){window.location=pageJTUserEventLog+i+"/"+t;return}n.AddLinkItem("View changes made by "+a+" of DB "+o,pageJTUserEventLog+i+"/"+t,"",1);n.Show(e)}function userEventLogMenu(e,t,a){var i=new ContextMenu;if(g_isDoubleClickEvent){showUserEventLog(t);return}i.AddLinkItem("View changes made by "+a,pageUserEventLog+t,"",1);i.AddSeparatorIfNecessary();i.AddLinkItem("View changes to "+a,pageEventLog+EventObjectType_Enum.eotUser+"/"+t);i.Show(e)}function submitUpdateJTIManLKInfo(){var e="frmUpdateLK",t=getObj(e),a=getCallbackDataOfDialog(t);jsrsExecuteWithErrorP("Admin2_UpdateJTIManLKInfo2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating License",{databaseId:a.databaseId,newLicense:a.license})}function rsCallbackTestUpdateJTIManLKInfo(e,t){var a=t.originalPayload,i=e.arrDiffs,o=i.length>0,n=e.userCountWarnings,r,l,d="frmUpdateLK",s=new ClientDialogBuilder({formId:d,formTitle:"Update License Key",fnSubmit:submitUpdateJTIManLKInfo,callbackData:{license:a.newLicense,databaseId:a.databaseId},okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Update License Key",mnemonicChar:"u",mnemonicActionJS:"submitUpdateJTIManLKInfo()"})});s.addFlexibleRow({rawValue:"Instance Name: "+e.instanceName});s.addSectionHeaderRow();if(n){s.addBubbleMessageRow({rawMessage:n})}if(o){var u='
";s.addFlexibleRow({valueHTML:"Updating the license key will result in the following changes: "+'
'+u+"
"})}else{s.addFlexibleRow({rawValue:"Updating the license key will result in no changes.\n"+"\n"})}s.addFlexibleRow({rawValue:"Are you sure you want to update the license key?"});s.showClientDialog()}function testUpdateJTIManLKInfo(){var e=getObj("frmLicense"),t=getCallbackDataOfDialog(e),a=e.txtLicense,i=trim(a.value),o=new FormValidator;if(!o.CSValidateRequiredField(a,"Please enter a License")){return}jsrsExecuteWithErrorP("Admin2_TestUpdateJTIManLKInfo2",rsCallbackHandleStandardJSONResponse,"Checking For Differences In The Proposed License",{databaseId:t.databaseId,newLicense:i},{fnOnSuccess:rsCallbackTestUpdateJTIManLKInfo})}function rsCallbackGenerateLicenseForDB(e,t){var a=t.originalPayload,i=e.licenseText,o=e.instanceName,n="frmLicense",r=new ClientDialogBuilder({formId:n,formTitle:"Update License Key",focusFieldName:"btnOk",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Analyze Changes",mnemonicChar:"a",mnemonicActionJS:"testUpdateJTIManLKInfo()"}),fnSubmit:testUpdateJTIManLKInfo,callbackData:{databaseId:a.databaseId}});if(o){r.addFlexibleRow({rawValue:"Instance Name: "+o});r.addSectionHeaderRow()}r.addTextAreaFieldRow("txtBody",{rawLabel:"License",unencodedText:i,fieldId:"txtLicense",emWidth:"30",labelAbove:1});r.showClientDialog()}function generateLicense(e,t){jsrsExecuteWithErrorP("Admin2_GenerateLicenseForDB2",rsCallbackHandleStandardJSONResponse,"Generating License",{databaseId:e,productExpirationDate:t?t:""},{fnOnSuccess:rsCallbackGenerateLicenseForDB})}function submitGenerateExpiringLicense(e,t){var a=new FormValidator,i=e.dtExpiration,o,n=new Date,r;n=new Date(n.getFullYear(),n.getMonth(),n.getDate());if(!a.CSValidateDateField(i,"Expiration Date",false,i.name)){return}o=getDateForUrlParam(i.value);r=parseDateString(o);if(n>r){showInfoDialog("You can't push out an expired license.","Invalid Expiration Date",1,"dtExpiration");return}generateLicense(t.databaseId,o)}function buildDefaultExpirationDate(){var e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()+16),a=0,i=6,o=0;switch(t.getDay()){case i:o=2;break;case a:o=1;break}if(o){t=new Date(t.getFullYear(),t.getMonth(),t.getDate()+o)}return getLocalDateString(t)}function generateExpiringLicense(e){var t="dtExpiration",a="frmGenLicense",i=new ClientDialogBuilder({formId:a,formTitle:"Generate Expiring License",focusFieldName:t,fnSubmit:submitGenerateExpiringLicense,callbackData:{databaseId:e}});i.addDatePickerRow(a,t,{rawLabel:"Expiration Date",strValue:buildDefaultExpirationDate()});i.showClientDialog()}function showHomepage(){window.location=pageWelcome}function showPaypalInNewWindow(e){window.open("https://manager.paypal.com/viewProfile.do?selectedProfileId="+e+"&subaction=viewRbProfile","_blank")}function showJTJobInNewWindow(e){window.open("https://internal.moraware.net/sys/job/"+e,"_blank")}function submitPaymentOptions(){var e=pagePayments,t=getObj("frmPaymentOptions"),a=t.chkIncFailed.checked,i=t.chkIncSuccess.checked,o=getObj("rbSingleDate"),n=o.checked,r=getObj("rbDateRange"),l=r.checked,d=t.cboMethod,s=d.options[d.selectedIndex].value,u=new FormValidator;if(a){e+="&incFail=1"}if(!i){e+="&incSuccess=0"}if(s){e+="&methods="+escape(s)}if(!(a||i)){showInfoDialog('Select at least one of "Include Successful" or "Include Failed",
Otherwise no records will be shown.',"All Records Filtered Out",1);return}if(l||n){if(!u.CSValidateDateField(t.dtFrom,"Date",false,"dtFrom")){return}var c=getDateForUrlParam(t.dtFrom.value);e+="&date="+c;if(l){if(!u.CSValidateDateField(t.dtTo,"Date (To)",false,"dtTo")){return}var m=getDateForUrlParam(t.dtTo.value),p=new Date(c),f=new Date(m);if(p==f){}else if(p>f){showInfoDialog("The Start Date preceeds the End Date.","Invalid Date Range",1,"dtTo");return}else{e+="&dateTo="+m}}}hideDialog();window.location=e;displayTimedMessage("Reloading page...")}function toggledFailedPaymentOption(e){var t=getObj("chkIncArch");if(!e.checked){t.checked=false}}function updatePaymentTimeframe(){var e=getObj("rbSingleDate"),t=getObj("rbDateRange"),a=getObj("secSingleDate"),i=getObj("secDateRange"),o=t.checked;a.style.visibility=e.checked||o?"":"hidden";if(i){i.style.visibility=t.checked?"":"hidden"}}function rsCallbackGetPaymentMethods(e,t,a){enableDialogButtons();if(checkResponseForError(e)){var i=a.strPaymentMethods,o=JSON.parse(e),n=o.arrPaymentMethods,r,l,d={},s=buildAnOption("","[Any]",i,0,d);for(r=0;r'+s+""}),g=new Date,C=getDateAsDisplayString(g),D=a.dispDate,h=a.dispDateTo,w=D?D:C,T=h?h:C,S=''+cdBuildDatePickerField(u,"dtFrom",w,f)+""+''+" - "+cdBuildDatePickerField(u,"dtTo",T,f)+""+"";b+=cdBuildRBRowP("rbDateRange","rbSingleDate","Single Date",{rawRowLabel:"Timeframe:",checked:D&&!h,onClickCode:p})+"
',n={statusSectionId:i},r=new ClientDialogBuilder({formId:a,formTitle:"Generating Server Metrics",fnCancelOrClose:function(){if(!n.refreshOnClose){return 1}refreshPageAndScrollPos();hideDialog()}});r.addFlexibleRow({cellId:i});r.showClientDialog();n.requestContextId=jsrsExecute(rsCallbackGenerateServerMetrics,"Admin_GenerateServerMetrics",[escape(t)],rsErrorCallbackBuildServerMetrics,n,0,1);n.asynchUpdaterTimeoutId=setTimeout(function(){asynchUpdateWithProcessStatus(t,i,n)},125)}function confirmBuildServerMetricsDialog(e){var t=new ClientDialogBuilder({formTitle:"Server Metrics",okButtonDisplayText:"Generate",focusFieldName:"btnOk",fnSubmit:doBuildServerMetrics});t.addFlexibleRow({rawValue:"Are you sure you want to generate server metrics?"});t.showClientDialog()}function showLicenseText(e,t,a){showInfoDialog(cdBuildTextAreaFieldRowP("txtNotes","License",{unencodedText:unescape(t),labelAbove:1}),(a?"Expected":"Actual")+' License for Instance "'+htmlEncode(e)+'"',isDialogShowing())}function showLicenseDifferences(e,t,a,i,o){var n=t?t.arrDifferences:0,r=n?n.map(function(e){return{rawRowHeader:e[0],rawDeployedValue:e[1],rawBillingValue:e[2]}}):0,l=new MWClientTable({noDataMessage:"There Are No Differences",arrColumns:[new MWColumn({columnName:"",additionalCellClasses:"deltaItemPropertyHeader",simpleDisplayColumnPropertyName:"rawRowHeader"}),new MWColumn({columnName:"Deployed Value",simpleDisplayColumnPropertyName:"rawDeployedValue"}),new MWColumn({columnName:"Billing Value",simpleDisplayColumnPropertyName:"rawBillingValue"})]}),d=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formTitle:"Actual Vs. Expected License"});var s=htmlEncode(unescape(e));if(o){s=''+s+""}d.addFlexibleFieldRow({rawLabel:"Instance",valueHTML:s});if(a){d.addFlexibleFieldRow({valueHTML:"'+"Expected License..."+""})}if(i){d.addFlexibleFieldRow({valueHTML:"'+"Actual License..."+""})}d.addFlexibleRow({valueHTML:l.buildTableForArray(r)});d.showClientDialog()}function showLicenseMenu(e){var t=e.databaseId,a=escape(e.instanceName),i=e.actualLicenseText,o=e.expectedLicenseText,n=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARRead),r=new ContextMenu;r.AddScriptItem("Show actual license...","showLicenseText('"+a+"','"+escape(i)+"',0);");r.AddScriptItem("Show expected license...","showLicenseText('"+a+"','"+escape(o)+"',1);");if(t&&n){r.AddSeparatorIfNecessary();r.AddLinkItem("View Database",pageDatabaseDetail+t)}r.Show(event)}function submitAddOrUpdateTask(){var e="frmAddTask",t=getObj(e),a=new FormValidator,i=mjtElemData(t,"taskId"),o=cdGetExpandingTextFieldValue("txtNotes"),n=mjtElemData(t,"databaseId"),r=a.CSValidateRequiredField(t.txtName,"Please enter a Name")&&a.CSValidateDateField(t.dtDeadline,"Deadline",false,"dtDeadline");if(r){jsrsExecuteWithErrorP(i?"Admin2_UpdateTask2":"Admin2_CreateTask2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,i?"Updating Task":"Creating Task",{taskId:i||"",databaseId:n||"",taskName:trim(t.txtName.value),taskNotes:trim(o),taskDeadline:getDateForUrlParam(t.dtDeadline.value)})}}function showAddOrUpdateTask(e){var t=e.id,a=e.statusId,i="frmAddTask",o,n="txtName",r=e.name,l=e.notes,d=e.subdomain,s=t?a===TaskStatus_Enum.tsComplete?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiLightningBolt,doubleQuoteEncodedTitle:"Re-Activate Task",doubleQuoteEncodedOnClickJS:"carefullyActivateTask("+t+")"}):a===TaskStatus_Enum.tsActive?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiCheck,doubleQuoteEncodedTitle:"Mark Task Complete",doubleQuoteEncodedOnClickJS:"confirmSetTaskStatus("+t+","+TaskStatus_Enum.tsComplete+","+"'Complete',"+"unescape('"+escape(r)+"'),"+"1)"}):"":"",u=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),c=new ClientDialogBuilder({formId:i,formTitle:t?"Update Task":"Add Task To Database",focusFieldName:n,focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitAddOrUpdateTask()"}),arrExtraHeaderButtons:t?[u?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Task",doubleQuoteEncodedOnClickJS:"confirmDeleteTask("+t+","+"unescape('"+escape(r)+"'),"+"1)"})+'':"",s,buildHeaderChangeLogAnchorButton({eventObjectTypeId:EventObjectType_Enum.eotTask,eventObjectId:t})]:0,fnSubmit:submitAddOrUpdateTask});if(d){c.addFlexibleFieldRow({rawLabel:"Subdomain",rawValue:d})}c.addTextFieldRow(n,{rawLabel:"Name",mnemonicChar:"n",fieldValue:r,autofocus:1,maxLength:80});c.addDatePickerRow(i,"dtDeadline",{rawLabel:"Task Deadline",mnemonicChar:"t",strValue:cdCarefullyLocalizeDateValue(e.deadline)});c.addExpandingTextFieldRows("txtNotes",{rawLabel:"Description",value:l||""});o=c.showClientDialog();if(o){mjtElemData(o,"databaseId",e.databaseId);mjtElemData(o,"taskId",e.id)}}function showAddTaskToDatabase(e,t,a){showAddOrUpdateTask({databaseId:t,subdomain:a})}function rsCallbackGetTaskDetails(e){showAddOrUpdateTask(e)}function showEditTaskDialog(e,t){jsrsExecuteWithErrorP("Admin2_GetTaskDetails2",rsCallbackHandleStandardJSONResponse,'Retrieving info for task, "'+t+'"',{taskId:e},{fnOnSuccess:rsCallbackGetTaskDetails})}function doDeleteTask(e){jsrsExecuteWithErrorP("Admin2_DeleteTask2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting Task",{taskId:e.taskId})}function confirmDeleteTask(e,t,a){if(a){hideDialog()}displaySimpleConfirmationDialog(doDeleteTask,'Are you sure you want to delete "'+htmlEncode(t)+'"',"Delete Task",{taskId:e,taskName:t})}function setTaskStatus(e){jsrsExecuteWithErrorP("Admin2_SetTaskStatus2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Task Status",{taskId:e.taskId,taskStatus:e.status})}function carefullyActivateTask(e){hideDialogP({callback:function(){setTaskStatus({taskId:e,status:TaskStatus_Enum.tsActive})}})}function confirmSetTaskStatus(e,t,a,i,o){var n=function(){displaySimpleConfirmationDialog(setTaskStatus,"Are you sure you want to mark the task "+htmlEncode(a)+"? "+" "+'Task: '+htmlEncode(unescape(i))+"","Set task status",{taskId:e,status:t})};if(o){hideDialogP({callback:n})}else{n()}}function submitTaskReportOptions(){var e="frmOptions",t=getObj(e),a=new FormValidator,i=pageTaskReport,o=t.txtPageSize,n=trim(o.value),r=mjtElemData(t,"defaultStatusFilter"),l=parseInt(t.cboTaskStatusFilter.value,10),d=a.CSValidateIntegerFieldP({field:o,label:"Page Size",isNullable:true,minValue:1,maxValue:2e3});if(!d){return}if(n){i+="&pageSize="+n}if(l!==r){i+="&status="+l}hideDialog();window.location=i;displayTimedMessage("Reloading page...")}function showTaskReportOptions(e){consoleLogBlockOpen("showTaskReportOptions()");consoleLog(JSON.stringify({params_:e},null,2));var t="frmOptions",a,i=new ClientDialogBuilder({formId:t,formTitle:"Task Report Options",focusFieldName:"cboTaskStatusFilter",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitTaskReportOptions()"}),fnSubmit:submitTaskReportOptions});i.addDropdown({rawLabel:"Task Status",fieldName:"cboTaskStatusFilter",arrAvailableOptions:[{cboValue:TaskStatusFilter_Enum.tsfActiveOnly,rawContent:"Active Only"},{cboValue:TaskStatusFilter_Enum.tsfCompleteOnly,rawContent:"Complete Only"},{cboValue:TaskStatusFilter_Enum.tsfActiveOrComplete,rawContent:"Any"}],objSelectedValue:{cboValue:e.taskStatusFilter}});i.addTextFieldRow("txtPageSize",{rawLabel:"Rows per Page",fieldValue:""+e.pageSize,mnemonicChar:"r",maxLength:10,styleWidth:"7em",isNumber:1});a=i.showClientDialog();if(a){mjtElemData(a,"defaultStatusFilter",e.defaultStatusFilter)}consoleLogBlockClose()}function doDeleteEmailTemplate(e){jsrsExecuteWithErrorP("Admin2_DeleteEmailTemplate2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting Email Template",{emailTemplateId:e.emailTemplateId})}function confirmDeleteEmailTemplate(e,t,a){if(a){hideDialog()}displaySimpleConfirmationDialog(doDeleteEmailTemplate,'Are you sure you want to delete "'+htmlEncode(t)+'"',"Delete Email Template",{emailTemplateName:t,emailTemplateId:e})}function rsCallbackCreatedEmailTemplate(){}function validateCommonEmail(e,t,a){var i=t.txtSubject,o=t.txtBody,n=o.value;if(!e.CSValidateRequiredField(i,"Please enter a Subject")){return}if(!e.CSValidateRequiredField(o,"Please enter a Body")){return}a.subject=trim(i.value);a.body=n;return 1}function submitCreateOrEditEmailTemplate(){var e="frmEmailTemplate",t=getObj(e),a=mjtElemData(t,"emailTemplateId"),i=new FormValidator,o=t.txtFromName,n=t.chkDunning.checked,r={};if(!i.CSValidateRequiredField(t.txtName,"Please enter a Name for the Email Template")){return}if(!i.CSValidateRequiredField(o,"Please enter a From Name")){return}if(!validateCommonEmail(i,t,r)){return}jsrsExecuteWithErrorP("Admin2_CreateOrUpdateEmailTemplate2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Submitting Email Template",{emailTemplateId:a||"",emailTemplateName:t.txtName.value,fromName:o.value,messageSubject:r.subject,messageBody:r.body,isDunningEmail:n?1:0},{postMessageFocusFieldName:"txtBody"})}function insertTextIntoTextField(e,t){var a=getObj(e);insertAtCursor(a,t)}function showTextSubstitutionOptions(e,t){show_staticTextInsertPicker(getObj("btnInsertSubstitutionString"),null,false,"insertTextIntoTextField",t,{arrValueNameDescription:[[g_emailSubstStrDigits,"Credit Card #","The last for digits of the credit card used with the last payment."],[g_emailSubstStrCCType,"Card Type","The type of credit card used for the last payment."],[g_emailSubstStrInvAmount,"Invoice Amount","Amount of invoice."],[g_emailSubstStrInvDate,"Invoice Date","Date of the invoice."],[g_emailSubstStrBillingURL,"Billing URL","Link to the billing page for this instance."]],strHelpHTML:"The following values will be replaced when you compose an email off of an invoice."})}function rsCallbackGetInfoForCreateOrEditEmailTemplate(e,t){var a="frmEmailTemplate",i,o=e.id,n=jtcrmHasAccess(JTCRMSecuredObject_Enum.soEmailTemplates,AccessRight_Enum.mjtARDelete),r=new ClientDialogBuilder({formId:a,formTitle:o?"Edit Email Template":"Create Email Template",focusFieldName:"txtName",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitCreateOrEditEmailTemplate()"}),fnSubmit:submitCreateOrEditEmailTemplate,arrExtraHeaderButtons:o?[n?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Email Template",doubleQuoteEncodedOnClickJS:"confirmDeleteEmailTemplate("+o+",unescape('"+escape(e.name)+"'),1)"}):"",n?'':"",cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayEmailTemplateEventLog("+o+")"})]:0});r.addTextFieldRow("txtName",{rawLabel:"Template Name",mnemonicChar:"n",fieldValue:e.name});r.addFlexibleFieldRow({labelHTML:"From Email",rawValue:e.fromEmailAddress});r.addTextFieldRow("txtFromName",{labelHTML:"From Name",fieldValue:e.fromName});r.addTextFieldRow("txtSubject",{rawLabel:"Subject",mnemonicChar:"j",fieldValue:e.subject});r.addTextAreaFieldRow("txtBody",{rawLabel:"Body",mnemonicChar:"b",unencodedText:e.body,fieldId:"txtBody",textAreaClasses:"largeTextArea"});r.addFlexibleFieldRow({valueHTML:""});r.addCheckboxRow_deprecated("chkDunning",{rawLabel:"Dunning Email",mnemonicChar:"l",checked:e.dunning});i=r.showClientDialog();if(i){mjtElemData(i,"emailTemplateId",o)}}function showCreateOrEditEmailTemplateDialog(e){jsrsExecuteWithErrorP("Admin2_GetInfoForCreateOrEditEmailTemplate",rsCallbackGetInfoForCreateOrEditEmailTemplate,"Getting info for Email Template",{emailTemplateId:e.emailTemplateId?e.emailTemplateId:""},e)}function showNewEmailTemplateDialog(){showCreateOrEditEmailTemplateDialog({})}function showEditEmailTemplateDialog(e,t){showCreateOrEditEmailTemplateDialog({emailTemplateId:e,emailTemplateName:t})}function submitReorderEmailTemplatesDialog(e){submitReorderP({arrReorderedIds:e,reorderCommandName:"Admin2_ReorderEmailTemplates2",reorderObjectName:"Email Templates",reorderIdsPropertyName:"emailTemplateIds"})}function showReorderEmailTemplatesDialog(e){jsrsExecuteWithErrorP("Admin2_GetEmailTemplatesForReorder",rsCallbackGetObjectsForReorder,"Getting list of Email Templates for re-order",{},{arrayAttrName:"arrEmailTemplates",fnSubmit:submitReorderEmailTemplatesDialog,strReorderWhat:"Email Templates",highlightedId:e})}function getEmailTemplateSelectionOption(e){var t=e?e.cboTemplates:0,a=t.options[t.selectedIndex].value,i=!!a,o=i?JSON.parse(unescape(a)):{subject:"",fromName:"",body:""},n={isTemplateSelected:i,objET:o};return n}function submitEmail(e,t){var a=new FormValidator,i=getEmailTemplateSelectionOption(e),o=i.objET,n=e.txtMessageRecipient,r=e.txtFromName,l=e.txtSubject,d=e.txtBody;if(!i.isTemplateSelected){showInfoDialog("Please select an email template","No Email Template Selected",1,"cboTemplate");return}if(!a.CSValidateRequiredField(r,'Please enter a sender name in the "From" field.')){return}if(!a.CSValidateRequiredField(n,'Please enter a recipient in the "To" field.')){return}if(!a.CSValidateRequiredField(l,"Please enter a Subject.")){return}if(!a.CSValidateRequiredField(d,"Please enter a message body.")){return}jsrsExecuteWithErrorP("Admin2_SendInvoiceEmail2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Sending email",{invoiceId:t.invoiceId,emailTemplateId:o.id,fromName:r.value,recipient:n.value,subject:l.value,body:d.value})}function updateEmailForTemplate(){var e=getObj("frmEmail"),t=getEmailTemplateSelectionOption(e);if(e){e.txtSubject.value=t.objET.subject;e.txtFromName.value=t.objET.fromName;e.txtBody.value=t.objET.body}}function rsCallbackGetInfoToCreateInvoiceEmail(e,t){var a=t.originalOptions,i=e.arrEmailTemplates,o=i.length,n,r="frmEmail",l="",d,s=e.defaultEmailTemplateId,u="",c;for(d=0;d"+htmlEncode(n.name)+""}if(!o){l+=''}u+=cdBuildReadOnlyFieldRowP({rawLabel:"Customer",rawValue:e.customerName})+cdBuildReadOnlyFieldRowP({rawLabel:"Database",rawValue:e.subdomain})+cdBuildReadOnlyFieldRowP({rawLabel:"Invoice #",rawValue:""+e.invoiceNumber});if(e.resultMessage){u+=cdBuildReadOnlyFieldRowP({rawLabel:"Last Payment Result",rawValue:e.resultMessage+" (Code="+e.resultCode+")"})}u+=cdBuildReadOnlyFieldRowP({rawLabel:"Templates",valueHTML:'"})+'
'+cdBuildTextFieldRowP("txtFromName","From")+cdBuildTextFieldRowP("txtMessageRecipient","To",{isEmail:1,fieldValue:a.toEmailAddress||""})+cdBuildTextFieldRowP("txtSubject","Subject")+cdBuildTextAreaFieldRowP("txtBody","Body",{textAreaClasses:"largeTextArea"});showDialogP(u,r,{formTitle:"Email",focusFieldName:"txtMessageRecipient",okButtonDisplayText:"Send",contextDetailOrFnSubmit:{fnSubmit:submitEmail,callbackData:{invoiceId:a.invoiceId}}});updateEmailForTemplate();forceRescanDialogForNewNodes(r)}function showComposeEmailForInvoiceDialog(e,t,a){jsrsExecuteWithErrorP("Admin2_GetInfoToCreateInvoiceEmail2",rsCallbackHandleStandardJSONResponse,"Retrieving Info to email about Invoice #"+t+"...",{invoiceId:e},{fnOnSuccess:rsCallbackGetInfoToCreateInvoiceEmail,invoiceId:e,toEmailAddress:a})}function buildBouncedEmailDetailRows(e){var t=e.length,a="",i;if(t===1){i=e[0];a='
";if(t.deploymentServerDiffers){a+=buildChangeEntry("Hosted Server",t.crmListedDeploymentServer,t.actualDeploymentServer)}if(t.billingLinkDiffers){a+=buildChangeEntry("Billing Link",t.crmListedBillingLink,t.actualBillingLink)}if(t.cgUserCountDiffers){a+=buildChangeEntry("CG User Count",t.crmListedCGUserCount,t.actualCGUserCount)}if(t.nvUserCountDiffers){a+=buildChangeEntry("Inv User Count",t.crmListedNVUserCount,t.actualNVUserCount)}if(t.sysUserCountDiffers){a+=buildChangeEntry("Sys User Count",t.crmListedSysUserCount,t.actualSysUserCount)}if(t.requiresUpdateDueToEdition){a+=buildChangeEntry("Edition",t.crmListedEditionName+" (Id="+t.crmListedEditionId+")",t.actualEditionName+" (Id="+t.actualEditionId+")")}if(t.serverDatabaseLinkDiffers){a+=buildChangeEntry("Server Database Link",t.crmListedServerDatabaseLink,t.actualServerDatabaseLink)}if(t.counterGoActivity.activityStatesDiffer){a+=buildChangeEntry("CG Activity Status",t.counterGoActivity.crmActivityStatusFieldText,t.counterGoActivity.actualActivityStatusText)}if(t.nvInventoryActivity.activityStatesDiffer){a+=buildChangeEntry("Inv Activity Status",t.nvInventoryActivity.crmActivityStatusFieldText,t.nvInventoryActivity.actualActivityStatusText)}if(t.systemizeActivity.activityStatesDiffer){a+=buildChangeEntry("Sys Activity Status",t.systemizeActivity.crmActivityStatusFieldText,t.systemizeActivity.actualActivityStatusText)}if(t.customerStatusDiffers){a+=buildChangeEntry("Lifecycle",t.crmCompanyStatus,t.actualCustomerStatus)}if(t.serverMetricsDiffer){a+="Server Metrics Differ"}a+=buildCompanyNewCustomerActivityChangeEntryIfNecessary({actualCompanyNewCustomerActivity:t.actualSysCompanyNewCustomerActivity,crmCompanyNewCustomerActivity:t.crmSysCompanyNewCustomerActivity,productName:"Systemize"})+buildCompanyNewCustomerActivityChangeEntryIfNecessary({actualCompanyNewCustomerActivity:t.actualCGCompanyNewCustomerActivity,crmCompanyNewCustomerActivity:t.crmCGCompanyNewCustomerActivity,productName:"CounterGo"})+buildCompanyNewCustomerActivityChangeEntryIfNecessary({actualCompanyNewCustomerActivity:t.actualNVCompanyNewCustomerActivity,crmCompanyNewCustomerActivity:t.crmNVCompanyNewCustomerActivity,productName:"Moraware Inventory"});a+="
";return a}function rsCallbackGetAllDatabasesRequiringSynch(e){var t=e.databasesWithChanges,a=e.hubspotCompanyLinkPrefix,i=t.arrDatabasesWithChanges,o=i.length,n="frmPromptUpdateJTFields",r=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:n,formTitle:"Synch Database Fields",focusFieldName:"btnOk",fnSubmit:confirmedUpdateSpecificJTJobs}),l="",d,s,u=[["Billing Link",t.billingLinkMismatchTally],["Deployment Server",t.deploymentServerMismatchTally],["CG User Count",t.cgUserCountMismatchTally],["Inv User Count",t.nvUserCountMismatchTally],["Sys User Count",t.sysUserCountMismatchTally],["Edition",t.editionMismatchTally],["Address",t.addressMismatchCount],["Server Database Link",t.serverDatabaseLinkMismatchCount],["CG Activity Status",t.cgActivityStatusMismatchTally],["Inv Activity Status",t.nvActivityStatusMismatchTally],["Sys Activity Status",t.sysActivityStatusMismatchTally],["Server Metrics",t.serverMetricsStatusMismatchTally]],c,m;if(!o){showInfoDialog("There are currently no databases that require an update.","No Databases To Be Updated");return}r.addFlexibleFieldRow({rawLabel:"Databases Requiring An Update",rawValue:""+o});r.addSectionHeaderRow({rawTitle:"# of Mismatches"});for(c=0;c'+''+"
";if(d.addressesDiffer&&d.isHubspotCompanyValid){l+=buildChangeEntry("Database Address",d.actualAddressDisplayString,d.crmAddressDisplayString)}else if(!d.isHubspotCompanyValid){l+="Marking Hubspot Company Id as Invalid (update manually to fix)"}l+="
";l+=""}l+="
";r.addFlexibleRow({valueHTML:l});r.showClientDialog();var g=getObj("chkCheckAllRows");if(g){checkAllRows(g)}}function synchHubspotPreview(){jsrsExecuteWithErrorP("Admin2_GetAllDatabasesRequiringSynch",rsCallbackGetAllDatabasesRequiringSynch,"Getting Databases Requiring An Update")}function rsCallbackDisplayAddUsersToInstancesResults(e){hideDialog();var t=e.results||[],a=t.length,i=e.instancesWithProductOrders,o=e.instancesWithInvoices,n=e.instancesWithChargedInvoices,r="frmShowResultsOfAddingUsersToInstances",l=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:r,formTitle:"Add Users to Instances",fnCancelOrClose:function(){hideDialog();refreshPageAndScrollPos()}}),d=new MWClientTable({});l.addFlexibleFieldRow({rawLabel:"Instances",rawValue:""+a});l.addFlexibleFieldRow({rawLabel:"Product Orders (Created)",rawValue:""+i});l.addFlexibleFieldRow({rawLabel:"Invoices (Created)",rawValue:""+o});l.addFlexibleFieldRow({rawLabel:"Invoices (Charged)",rawValue:""+n});l.addSectionHeaderRow({rawTitle:"Instances"});d.addColumn(new MWColumn({columnName:"Customer",fnCustomRenderCellContents:function(e,t,a,i){return htmlEncode(e.instance.customerName)}}));d.addColumn(new MWColumn({columnName:"Database",fnCustomRenderCellContents:function(e,t,a,i){return htmlEncode(e.instance.subdomain)},fnBuildCellLinkDetail:function(e,t,a,i){return mwBuildSimpleLink(pageDatabaseDetail+e.instance.databaseId,1)}}));d.addColumn(new MWColumn({columnName:"Product Order Prorated Total",fnCustomRenderCellContents:function(e,t,a,i){return padAndPrefixSignedDollarsP({dollarValue:e.productOrderProratedTotal,forceDecimalsWhenNone:1})}}));d.addColumn(new MWColumn({columnName:"Unpaid Invoices Total",fnCustomRenderCellContents:function(e,t,a,i){return padAndPrefixSignedDollarsP({dollarValue:e.unpaidInvoicesTotal,forceDecimalsWhenNone:1})}}));d.addColumn(new MWColumn({columnName:"Status",fnCustomRenderCellContents:function(e,t,a,i){var o="Could not create Product Order";if(e.chargedInvoices){o="Success"}else if(e.createdInvoices){o="Invoices Created but not Charged"}else if(e.createdProductOrders){o="Product Order Created but not Invoiced"}return o}}));d.addColumn(new MWColumn({columnName:"Status Message",simpleDisplayColumnPropertyName:"statusMessage",simpleDisplayColumnNeedsMultilineEncoding:true}));var s=d.buildTableForArray(t);l.addFlexibleRow({valueHTML:s});l.showClientDialog()}function confirmedAddUsersToSpecificInstances(e,t){var a=getListOfCheckedRowValuesWithParams({form:e,buildRCArray:1,minSelected:1,tooFewWarning:"Please select an Instance",clientDlgParams:{subdialogDismisalFocusFieldName:"chkCheckAllRows",subdialog:1},unescapeValues:1,fnTransformValueForArray:function(e){return JSON.parse(e)}}),i=a.arrValues,o=a.selectedCount;if(!o){return}jsrsExecuteWithErrorP("Admin2_AddAdditionalUsersToInstances",rsCallbackHandleStandardJSONResponse,"Adding Additional Users to Selected Instances",{arrInstancesWithAddedUsers:i},{fnOnSuccess:rsCallbackDisplayAddUsersToInstancesResults})}function rsCallbackGetInstancesWithAdditionalUsers(e){var t=e.instances||[],a=t.length,i=e.nextInvoiceDate,o="frmPromptAddUsersToInstances",n=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:o,formTitle:"Add Users to Instances",focusFieldName:"btnOk",okButtonDisplayText:"Create & Pay Invoices",fnSubmit:confirmedAddUsersToSpecificInstances}),r=new MWClientTable({fnGetCheckDetailsForRow:function(e,t,a){return{value:htmlEncode(JSON.stringify(e))}}});if(!a){showInfoDialog("There are currently no instances with additional users added outside the time period.","No Instances To Be Updated");return}n.addFlexibleFieldRow({rawLabel:"Instances with additional users",rawValue:""+a});if(i){n.addFlexibleFieldRow({rawLabel:"Filtered to Next Invoice Date",rawValue:getLocalDateString(new Date(i))})}n.addSectionHeaderRow({rawTitle:"Instances To Update"});r.addColumn(new MWColumn({columnName:"Customer",simpleDisplayColumnPropertyName:"customerName"}));r.addColumn(new MWColumn({columnName:"Database",simpleDisplayColumnPropertyName:"subdomain",fnBuildCellLinkDetail:function(e,t,a,i){return mwBuildSimpleLink(pageDatabaseDetail+e.databaseId,1)}}));var l=r.addColumn(new MWColumn({columnName:"Additional Users",additionalHeaderClasses:"centerAlign"}));l.addSubColumn(new MWColumn({columnName:"CounterGo",simpleDisplayColumnPropertyName:"additionalCounterGoUserCount"}));l.addSubColumn(new MWColumn({columnName:"Inventory",simpleDisplayColumnPropertyName:"additionalNVInventoryUserCount"}));l.addSubColumn(new MWColumn({columnName:"Systemize",simpleDisplayColumnPropertyName:"additionalSystemizeUserCount"}));var d=r.addColumn(new MWColumn({columnName:"Last Change",additionalHeaderClasses:"centerAlign"}));d.addSubColumn(new MWColumn({columnName:"Time",fnCustomRenderCellContents:function(e,t,a,i){var o=new Date(e.lastChangeTime);return getLocalDateString(o)+" - "+getLocalTimeString(o)}}));d.addSubColumn(new MWColumn({columnName:"Hours",simpleDisplayColumnPropertyName:"stableAgeInHours"}));r.addColumn(new MWColumn({columnName:"Next Invoice Date",fnCustomRenderCellContents:function(e,t,a,i){var o=new Date(e.nextInvoiceDate);return getLocalDateString(o)}}));var s=r.buildTableForArray(t);n.addFlexibleRow({valueHTML:s});n.showClientDialog();var u=getObj(o);if(u){u.chkCheckAllRows.checked=true;checkAllRows(u.chkCheckAllRows)}}function addUsersToJTInstances(e){e=e||{};var t=e.requireNextInvoiceDateBeTomorrow;jsrsExecuteWithErrorP("Admin2_GetInstancesWithAdditionalUsers",rsCallbackGetInstancesWithAdditionalUsers,"Getting Instances With Additional Users",{requireNextInvoiceDateBeTomorrow:t})}var InvoicePaymentOption_Enum={ipoOverall:1,ipoSingleInvoice:2};function submitMakePaymentOnInvoices(){var e="frmMakePaymentOnInvoices",t=getObj(e),a=parseInt(getSelectedRBValue(t,"rbPaymentOption"),10),i=a===InvoicePaymentOption_Enum.ipoOverall,o=getCallbackDataOfDialog(t),n=o.amountOutstanding,r=o.databaseBalanceInfo,l=o.invoiceId;hideDialog();jsrsExecuteWithErrorP("Admin2_MakePaymentOnInvoices",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Making Payment",{billingProcessorCustomerId:o.billingProcessorCustomerId,databaseId:o.databaseId,amount:i?r.databaseBalance:n,arrInvoiceAmounts:i?r.arrInvoiceAmounts:[{invoiceId:l,amount:n}],paymentProviderType:PaymentProcessorType_Enum.pptBraintree})}function doPromptMakePaymentOnInvoices(e,t){enableDialogButtons();var a=t.originalPayload.invoiceId,i=e.databaseBalanceInfo,o=e.billingProcessorCustomerId,n=e.invoiceNumber,r=e.databaseId,l="frmMakePaymentOnInvoices",d=e.amountOutstanding,s=new ClientDialogBuilder({formId:l,formTitle:"Make Payment",focusFieldName:i?"rbPaymentOption_Overall":"",focusFieldOnMobile:1,suppressDialogConfirmer:1,okButtonDisplayText:"Make Payment",fnSubmit:submitMakePaymentOnInvoices,callbackData:{billingProcessorCustomerId:o,databaseId:r,invoiceId:a,amountOutstanding:d,databaseBalanceInfo:i}});s.addFlexibleFieldRow({rawLabel:"Braintree Id",rawValue:o});s.addFlexibleFieldRow({rawLabel:"Invoice #",rawValue:""+n});s.addFlexibleFieldRow({rawLabel:"Invoice Total",rawValue:"$"+padDollars(e.invoiceTotal,1,0)});if(e.amountPaid){s.addFlexibleFieldRow({rawLabel:"Amount Paid",rawValue:"$"+padDollars(e.amountPaid,1,0)});s.addFlexibleFieldRow({rawLabel:"Amount Outstanding",rawValue:"$"+padDollars(e.amountOutstanding,1,0)})}s.addSectionHeaderRow();if(i){s.addRadioButtonRow({rawRowLabel:"Payment Amount:",labelHTML:"Total Balance: "+''+"$"+padDollars(i.databaseBalance,1,1)+"",fieldName:"rbPaymentOption",fieldId:"rbPaymentOption_Overall",fieldValue:""+InvoicePaymentOption_Enum.ipoOverall,checked:true});s.addRadioButtonRow({labelHTML:"Just this invoice: "+''+"$"+padDollars(d,1,1)+"",fieldName:"rbPaymentOption",fieldId:"rbPaymentOption_Invoice",fieldValue:""+InvoicePaymentOption_Enum.ipoSingleInvoice})}else{s.addFlexibleFieldRow({rawLabel:"Payment Amount",rawValue:"$"+padDollars(d,1,1),additionalRowClasses:"bold"})}s.showClientDialog()}function promptMakePaymentOnInvoices(e){jsrsExecuteWithErrorP("Admin2_GetInfoToPayInvoice",doPromptMakePaymentOnInvoices,"Retrieving Invoice Info To Make Payment",{invoiceId:e})}function toggleExpandAddressExtras(){var e=getObj("imgAddressExtrasExpander.expand"),t=!e.style.display;e.style.display=t?"none":"";getObj("imgAddressExtrasExpander.collapse").style.display=t?"":"none";getObj("divAddressExtras").style.display=t?"":"none"}function rsCallbackInitSession(e,t,a){enableDialogButtons();if(checkResponseForError(e)){window.open(a.url,"_blank")}}function rsCallbackOpenedCustomerPortal(e,t,a){enableDialogButtons();if(checkResponseForError(e)){var i=JSON.parse(e),o=i.error;if(o){var n=o.errorMessage,r=o.errorTitle,l=o.requiresRefresh;showInfoDialogWithConsequenceP({formTitle:r,rawValue:n,fnConsequence:l?rsCallbackRefreshPageAndScrollPos:0})}else{var d=i.userId,s=i.url,u=i.sessionId,c="Initializing Session";jsrsExecute(rsCallbackInitSession,"Portal_InitSession",[d,escape(u)],rsErrorCallbackShowErrorDialogAndRefresh,{url:s,errorDialogTitle:"Error "+c},0,1,s);displayTimedMessage(c+"...");disableDialogButtons()}}}function launchCustomerPortal(e){var t="Connecting to Customer Portal...";jsrsExecute(rsCallbackOpenedCustomerPortal,"Admin_OpenCustomerPortal",[e],rsErrorCallbackShowErrorDialogAndRefresh,{errorDialogTitle:"Error "+t},0,1);displayTimedMessage(t+"...");disableDialogButtons()}function showPortalUsageReportOptions(){showInfoDialog("Options?
We don't need no stinkin' options!","TODO: showPortalUsageReportOptions()")}function rsCallbackShowDBsWithUngeneratedNonMonthlyTotals(e,t,o){enableDialogButtons();if(checkResponseForError(e)){var n=JSON.parse(e),a=new MWClientTable({noDataMessage:"No Databases With Ungenerated Invoices"});a.addColumn(new MWColumn({columnName:"Customer",fnCustomRenderCellContents:function(e,t,a,i){return htmlEncode(e.database[0].gdCustomerName)}}));a.addColumn(new MWColumn({columnName:"Database",fnCustomRenderCellContents:function(e,t,a,i){var o=e.database[0].gdSubdomainName;if(!o){o="Non-Hosted DB (Id="+e.database[0].gdDatabaseId+")"}return htmlEncode(o)},fnBuildCellLinkDetail:function(e,t,a,i){return mwBuildSimpleLink(pageDatabaseDetail+e.database[0].gdDatabaseId,1)}}));a.addColumn(new MWColumn({columnName:"Invoice Amount",fnCustomRenderCellContents:function(e,t,a,i){return padAndPrefixSignedDollars(e.amount,1)}}));a.addColumn(new MWColumn({columnName:"Invoice Date",fnCustomRenderCellContents:function(e,t,a,i){return getDateAsDisplayString(new Date(n[0].date))}}));a.addColumn(new MWColumn({columnName:"Term",fnCustomRenderCellContents:function(e,t,a,i){return o.Term}}));showInfoDialog(a.buildTableForArray(n),"Databases With Ungenerated Invoices");scrollDialogIfNecessary("frmTmpMessage",1,1)}}function showDBsWithUngeneratedNonMonthlyTotals(e,t){var a="Finding databases...";jsrsExecute(rsCallbackShowDBsWithUngeneratedNonMonthlyTotals,"Admin_GetDatabasesWithUngeneratedTotals",[e,t],rsErrorCallbackShowErrorDialogAndRefresh,{errorDialogTitle:"Error "+a,DayOfMonth:t,Term:e},0,1);displayTimedMessage(a+"...");disableDialogButtons()}function registerChartPlugins(){Chart.plugins.register({afterDatasetsDraw:function(a,e){if(!a.data.showPointLabels){return}var s=a.chart.ctx;a.data.datasets.forEach(function(d,e){var t=a.getDatasetMeta(e);if(!t.hidden){t.data.forEach(function(e,t){s.fillStyle="rgb(0, 0, 0)";var a=12;var i="normal";var o="arial, helvetica, sans-serif";s.font=Chart.helpers.fontString(a,i,o);var n=d.data[t].toString();s.textAlign="center";s.textBaseline="middle";var r=5;var l=e.tooltipPosition();s.fillText(n,l.x,l.y-a/2-r)})}})}})}function submitVoidPayment(e,t){jsrsExecuteWithErrorP("Admin2_PerformVoidPayment",refreshPageAndScrollPos,"Retrieving Payment Info for Void Payment...",{paymentId:t.paymentId,amount:t.amount})}function rsCallbackGetInfoForVoidPayment(e,t){var a=t.originalPayload,i="frmConfirmVoidPayment",o=new ClientDialogBuilder({formId:i,formTitle:"Void Payment",okButtonDisplayText:"Void Payment",fnSubmit:submitVoidPayment,callbackData:e});o.addFlexibleFieldRow({rawLabel:"Payment Timestamp",rawValue:e.strPaymentTS});o.addFlexibleFieldRow({rawLabel:"Transaction Id",rawValue:e.transactionId});o.addFlexibleFieldRow({rawLabel:"Amount",valueHTML:padAndPrefixSignedDollars(e.amount,1)});o.showClientDialog()}function showCreateVoidingPaymentDialog(e){jsrsExecuteWithErrorP("Admin2_GetInfoForVoidPayment",rsCallbackGetInfoForVoidPayment,"Retrieving Payment Info for Void Payment...",{paymentId:e})}function submitRefundPayment(e,t){jsrsExecuteWithErrorP("Admin2_PerformRefundPayment",refreshPageAndScrollPos,"Retrieving Payment Info for Refund Payment...",{paymentId:t.paymentId,amount:t.amount})}function rsCallbackGetInfoForRefundPayment(e,t){var a=e.amount,i="frmConfirmRefundPayment",o=new ClientDialogBuilder({formId:i,formTitle:"Refund Payment",okButtonDisplayText:"Refund Payment",fnSubmit:submitRefundPayment,callbackData:e});o.addFlexibleFieldRow({rawLabel:"Payment Timestamp",rawValue:e.strPaymentTS});o.addFlexibleFieldRow({rawLabel:"Transaction Id",rawValue:e.transactionId});o.addFlexibleFieldRow({rawLabel:"Amount",valueHTML:padAndPrefixSignedDollars(a,1)});o.showClientDialog()}function showCreateRefundPaymentDialog(e){jsrsExecuteWithErrorP("Admin2_GetInfoForRefundPayment",rsCallbackGetInfoForRefundPayment,"Retrieving Payment Info for Refund Payment...",{paymentId:e})}function submitCreateCreditMemoRefund(){var e="frmRefund",t=getObj(e),a=getCallbackDataOfDialog(t),i=a.creditMemoId,o=getSelectedRB(t,"rbPayment"),n=o.getAttribute("data-paymentId"),r=t.txtRefundAmount,l={},d=new FormValidator;if(!d.CSValidateNumberFieldP({field:r,label:"Refund Amount",resultValueHolder:l})){return}jsrsExecuteWithErrorP("Admin2_ProcessCreditMemoCredit",refreshPageAndScrollPos,"Processing Refund",{paymentId:n,creditMemoId:i,amount:l.rc})}function rsCallbackGetPaymentsForCreditMemoRefund(e,t){var a=t.originalPayload,i=e.creditMemoAmount,o=e.amountCredited,n=e.remainingAmount,r=e.arrPayments,l=r?r.length:0,d=l?r[0]:0,s=l?Math.min(n,d.amount):n,u="frmRefund",c=new MWClientTable({noDataMessage:"No Payments"}),m=new ClientDialogBuilder({formId:u,formTitle:"New Refund",focusFieldName:l?"txtRefundAmount":"",okButtonDisplayText:"Process Refund",fnSubmit:submitCreateCreditMemoRefund,callbackData:{creditMemoId:a.creditMemoId}});if(!l){showInfoDialog("No payments available","No Payments");return}c.addColumn(new MWColumn({columnName:"Transaction Id",fnCustomRenderCellContents:function(e,t,a,i){return'"}}));c.addColumn(new MWColumn({columnName:"Timestamp",simpleDisplayColumnPropertyName:"paymentTS"}));c.addColumn(new MWColumn({columnName:"Amount",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(e,t,a,i){return padAndPrefixSignedDollars(e.amount,1)}}));m.addFlexibleFieldRow({rawLabel:"Credit Memo Amount",rawValue:padAndPrefixSignedDollars(i,1)});if(o){m.addFlexibleFieldRow({rawLabel:"Amount Credited",rawValue:padAndPrefixSignedDollars(o,1)})}m.addSectionHeaderRow({rawTitle:"Payment"});m.addFlexibleRow({valueHTML:c.buildTableForArray(r),hideRow:l===1});if(l===1){m.addFlexibleFieldRow({rawLabel:"Payment Transaction Id",rawValue:d.transactionId});m.addFlexibleFieldRow({rawLabel:"Timestamp",rawValue:d.paymentTS});m.addFlexibleFieldRow({rawLabel:"Amount",rawValue:padAndPrefixSignedDollars(d.amount,1)})}m.addTextFieldRow("txtRefundAmount",{rawLabel:"Refund Amount ($)",fieldValue:padDollars(s,1)});m.showClientDialog()}function showCreateRefundDialog(e){jsrsExecuteWithErrorP("Admin2_GetPaymentsForCreditMemoRefund",rsCallbackGetPaymentsForCreditMemoRefund,"Getting Payments available for a refund",{creditMemoId:e})}function buildTaxStateSelectionDropdown(e,t,a){return'"}function doBuildTaxRateBatch(){var e=getObj("frmBuildTaxRateBatch"),t=e.cboState,a=t.value;if(!a){showInfoDialog("Please select a state","No State Selected",1,t.name);return}jsrsExecuteWithErrorP("Admin2_BuildTaxRateBatch",refreshPageAndScrollPos,"Building Tax Rate Batch",{state:a})}function buildTaxRateBatch(e){var t="cboState",a=new ClientDialogBuilder({formId:"frmBuildTaxRateBatch",formTitle:"Build Tax Rate Batch",suppressDialogConfirmer:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Build Batch",mnemonicChar:"b",mnemonicActionJS:"doBuildTaxRateBatch()"}),fnSubmit:doBuildTaxRateBatch,focusFieldName:t});a.addFlexibleFieldRow({rawLabel:"State",valueHTML:buildTaxStateSelectionDropdown(e,t,"-Select a State-")});a.showClientDialog()}function submitTaxRateReconciliationReportOptions(){var e="frmOptions",t=getObj(e),a=new FormValidator,i=t.txtPageSize,o=trim(i.value),n=trim(t.cboState.value),r="";if(!a.CSValidateIntegerField(i,"Page Size",true,1,2e3)){return}if(o){r+="&pageSize="+o}if(n){r+="&state="+n}if(t.chkIncludeValidRows.checked){r+="&includeValidRows=1"}if(r){r=r.substring(1)}hideDialog();window.location=pageTaxRateReconciliationReport+r}function showTaxRateReconciliationReportOptions(e){var t="frmOptions",a="cboState",i=new ClientDialogBuilder({formId:t,formTitle:"Report Options",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitTaxRateReconciliationReportOptions()"}),focusFieldName:a,focusFieldOnMobile:1,fnSubmit:submitTaxRateReconciliationReportOptions});i.addFlexibleFieldRow({rawLabel:"State",valueHTML:buildTaxStateSelectionDropdown(e.state,a,"-Any-")});i.addFlexibleFieldRow({valueHTML:ClientDialogModule.buildCheckboxAndLabel({fieldName:"chkIncludeValidRows",fieldId:"chkIncludeValidRows",rawFieldLabel:"Include Valid Rows",mnemonicChar:"v",checked:e.includeValidRows})});i.addSectionHeaderRow();i.addTextFieldRow("txtPageSize",{rawLabel:"Rows per Page",fieldValue:""+(e.pageSize||""),maxLength:10,isNumber:1,suppressAutocomplete:1});i.showClientDialog()}function submitEditAttachedFile(){var e=getObj("editAttachFile"),t=null,a=e.objectId.value,i=e.fileId.value,o="Updating File";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_UpdateAttachedFile",[a,i,escape(t)],enableDialogButtons);displayTimedMessage(o+"...");disableDialogButtons()}function confirmDeleteAttachedFile(e,t,a){promptConfirmDeleteFile(e,t,null,a,"Admin_DeleteAttachedFile",true)}function deleteExpenseQuickbooksCustomer(e){var t="Deleting Quickbooks Vendor...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseQuickbooksCustomer",[e.expenseQuickbooksCustomerId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(t+"...");disableDialogButtons()}function deleteExpenseVendor(e){var t="Deleting Expense Vendor...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseVendor",[e.expenseVendorId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(t+"...");disableDialogButtons()}function deleteExpenseReport(e){jsrsExecuteWithErrorP("Admin2_DeleteExpenseReport",function(e){hideDialog();window.location=pageExpenses},"Deleting Expense Report...",{expenseReportId:e.expenseReportId})}function deleteImporBlocklist(e){var t="Deleting from Import Blocklist...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseImportBlocklist",[e.expenseImportBlocklistId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(t+"...");disableDialogButtons()}function confirmDeleteExpenseReport(e){displaySimpleConfirmationDialogP(deleteExpenseReport,'Are you sure you want to delete this Expense Report"?',{formTitle:"Delete Expense Report",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseReportId:e}})}function confirmDeleteExpenseImportBlocklist(e,t){displaySimpleConfirmationDialogP(deleteImporBlocklist,'Are you sure you want to delete Import Blocklist entry "'+t+'"?',{formTitle:"Delete From Expense Import Blocklist",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseImportBlocklistId:e}})}function confirmDeleteQuickbooksCustomer(e,t){displaySimpleConfirmationDialogP(deleteExpenseQuickbooksCustomer,'Are you sure you want to delete the Quickbooks Vendor "'+htmlEncode(t)+'"?',{formTitle:"Delete Quickbooks Vendor",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseQuickbooksCustomerId:e}})}function confirmDeleteExpenseVendor(e,t){displaySimpleConfirmationDialogP(deleteExpenseVendor,'Are you sure you want to delete Vendor "'+htmlEncode(t)+'"?',{formTitle:"Delete Expense Vendor",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseVendorId:e}})}function confirmDeleteExpenseReportDetail(t){var e=getObj("txtSummary");if(e){e=e.innerHTML}displaySimpleConfirmationDialogP(function(){var e="Deleting Expense Report Detail...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseReportDetail",[t],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(e+"...");disableDialogButtons()},'Are you sure you want to delete the Expense Report Detail "'+e+'"?',{formTitle:"Delete Expense Report Detail",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseReportDetailId:t}})}function deleteExpenseType(e){var t="Deleting Expense Type...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseType",[e.typeId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(t+"...");disableDialogButtons()}function confirmDeleteExpenseType(e,t){displaySimpleConfirmationDialogP(deleteExpenseType,'Are you sure you want to delete the type "'+t+'"?',{formTitle:"Delete Expense Type",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{typeId:e}})}function deleteExpenseTrip(e){var t="Deleting Expense Trip...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseTrip",[e.tripId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(t+"...");disableDialogButtons()}function confirmDeleteExpenseTrip(e,t){displaySimpleConfirmationDialogP(deleteExpenseTrip,'Are you sure you want to delete the trip "'+htmlEncode(t)+'" trip?',{formTitle:"Delete Expense Trip",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{tripId:e}})}function submitaddOrUpdateExpenseTrip(){var e=getObj("addOrUpdateExpenseTrip"),t=e.txtLocation.value,a=e.year.value,i=e.cboMonth[e.cboMonth.selectedIndex].value,o=parseInt(a,10),n=e.tripId.value,r=e.chkIsDisabled.checked,l="Adding Trip...";if(""===t){showInfoDialog("Location is required","Missing Field",1,"txtLocation");return}if(isNaN(o)||o<=2017){showInfoDialog("Year must be a whole number greater than 2017","Missing Field",1,"year");return}jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_AddOrUpdateExpenseTrip",[n,a,i,escape(t),r?1:0],enableDialogButtons);displayTimedMessage(l+"...");disableDialogButtons()}function getMonthOptionElements(e){var t="";var a=new Date;var i="en-us";for(var o=0;o<12;o++){t+=buildOptionHTML(new Date(2018,o).toLocaleString(i,{month:"long"}),o,e)}return t}function addOrUpdateExpenseTrip(e,t,a,i,o,n){var r="addOrUpdateExpenseTrip",l=new ClientDialogBuilder({formId:r,formTitle:e?"Edit Trip":"Add Trip",focusFieldName:"year",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:e?"Save":"Add",mnemonicChar:e?"s":"a",mnemonicActionJS:"submitaddOrUpdateExpenseTrip()"}),fnSubmit:submitaddOrUpdateExpenseTrip,arrExtraHeaderButtons:e?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseTrip("+e+", unescape('"+escape(o)+"'))"})]:null});l.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});l.addFlexibleFieldRow({additionalValueCellClasses:"clsNarrowField",rawLabel:"Year",valueHTML:''});l.addFlexibleFieldRow({rawLabel:"Month",valueHTML:'"});l.addTextFieldRow("txtLocation",{rawLabel:"Name & Location",maxLength:80,fieldValue:i,additionalFieldCellClasses:"tripNameAndLocation"});l.addCheckboxRow_deprecated("chkIsDisabled",{labelHTML:"Disabled",checked:n,hideRow:e?false:true});l.showClientDialog()}function submitAddOrUpdateExpenseType(){var e=getObj("addOrUpdateExpenseType"),t=e.txtName.value,a=e.txtAccountingId.value,i=e.typeId.value,o=e.chkIsDisabled.checked;if(""===t){showInfoDialog("Name is required","Missing Field",1,"name");return}if(""===a){showInfoDialog("Quickbooks Id is required","Missing Field",1,"txtAccountingId");return}jsrsExecuteWithErrorP("Admin2_AddOrUpdateExpenseType2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,i?"Updating Expense Type":"Adding Expense Type",{expenseTypeId:i,expenseTypeName:t,quickbooksId:a,isDisabled:o?1:0})}function addOrUpdateExpenseType(e,t,a,i){var o="addOrUpdateExpenseType",n=new ClientDialogBuilder({formId:o,formTitle:e?"Edit Expense Type":"Add Expense Type",focusFieldName:"txtName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:e?"Save":"Add",mnemonicChar:e?"s":"a",mnemonicActionJS:"submitAddOrUpdateExpenseType()"}),fnSubmit:submitAddOrUpdateExpenseType,arrExtraHeaderButtons:e?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseType("+e+", unescape('"+escape(t)+"'))"})]:null});n.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});n.addTextFieldRow("txtName",{rawLabel:"Name",maxLength:80,fieldValue:t});n.addTextFieldRow("txtAccountingId",{rawLabel:"Quickbooks Id",maxLength:80,fieldValue:a});n.addCheckboxRow_deprecated("chkIsDisabled",{labelHTML:"Disabled",checked:i,hideRow:e?false:true});n.showClientDialog()}function submitAddOrUpdateExpenseVendor(a,e,t){var i=getObj("frmExpenseVendor"),o=i.expenseVendorId.value,n=i.txtName.value,r=i.quickbooksCustomerId.value,l=i.txtQuickbooksCustomer.value,d=i.txtReason.value,s=i.cboAmexDescriptionMatchType[i.cboAmexDescriptionMatchType.selectedIndex].value,u=i.cboAmexAppearsOnStatementAsMatchType[i.cboAmexAppearsOnStatementAsMatchType.selectedIndex].value,c=i.txtAmexAppearsOnStatementAs.value,m=i.txtAmexDescription.value,p=i.cboType[i.cboType.selectedIndex].value,f=i.chkIsDisabled.checked,b=i.chkIsGeneric.checked,g=i.chkIncludeOnMemo.checked,C=o?"Updating Expense Vendor...":"Adding Expense Vendor...";if(!r&&t){r=t}if(!r){if(""===l){showInfoDialog("Quickbooks Vendor is required","Missing Field",1,"year");return}if(e){displaySimpleConfirmationDialog(function(){jsrsExecute(function(e){if(checkResponseForError(e)){var t=JSON.parse(e);submitAddOrUpdateExpenseVendor(a,true,t.quickbooksCustomerId);return}},"Admin_AddOrUpdateExpenseQuickbooksCustomer",[null,l,0],rsErrorCallbackShowErrorDialog,{},0,1)},'The Quickbooks Vendor "'+htmlEncode(l)+'" does not exist. Do you want to create a new Quickbooks Vendor with this name?',"Create Quickbooks Vendor",{},1,null,"Create Quickbooks Vendor");return}else{jsrsExecute(function(e){if(checkResponseForError(e)){var t=JSON.parse(e);r=t.quickbooksCustomerId}submitAddOrUpdateExpenseVendor(a,true,r)},"Admin_GetQuickbooksVendorByName",[escape(l)],function(){});return}}if(""===n){showInfoDialog("Name is required","Missing Field",1,"year");return}if(""!==c&&""===u){showInfoDialog("You must specify a match type for Amex Appears on statement as","Missing Field",1,"year");return}if(""!==m&&""===s){showInfoDialog("You must specify a match type for Amex Description","Missing Field",1,"year");return}if(u!==""&&c===""){u=""}if(s!==""&&m===""){s=""}jsrsExecute(function(e,t,a){var i=getObj("frmApproveExpense");if(isDialogShowing()&&i){var o=JSON.parse(e),n=o.expenseVendorId,r=o.expenseVendorName;var l=document.createElement("option");l.value=n;l.innerHTML=r;l.selected=true;i.cboVendor.appendChild(l);hideTimedMessage();hideSubdialog();enableDialogButtons()}else{rsCallbackRefreshPageAndScrollPos(e)}},"Admin_AddOrUpdateExpenseVendor",[o,n,r,s,escape(m),u,escape(c),p,d,g?1:0,f?1:0,b?1:0],enableDialogButtons);displayTimedMessage(C+"...");disableDialogButtons()}function submitAddOrUpdateQuickbooksCustomer(){var e=getObj("addOrUpdateQuickbooksCustomer"),t=e.expenseQuickbooksCustomerId.value,a=e.txtName.value,i=e.chkIsDisabled.checked,o=t?"Updating Quickbooks Vendor...":"Adding Quickbooks Vendor...";if(""===a){showInfoDialog("Name is required","Missing Field",1,"year");return}jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_AddOrUpdateExpenseQuickbooksCustomer",[t,a,i?1:0],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(o+"...");disableDialogButtons()}function addOrUpdateQuickbooksCustomer(e,t,a){var i="addOrUpdateQuickbooksCustomer",o=new ClientDialogBuilder({formId:i,formTitle:e?"Edit Quickbooks Vendor":"Add Quickbooks Vendor",focusFieldName:"txtName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:e?"Save":"Add",mnemonicChar:e?"s":"a",mnemonicActionJS:"submitAddOrUpdateQuickbooksCustomer()"}),fnSubmit:submitAddOrUpdateQuickbooksCustomer,arrExtraHeaderButtons:e?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteQuickbooksCustomer("+e+", unescape('"+escape(t)+"'))"})]:null});o.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});o.addTextFieldRow("txtName",{rawLabel:"Name",maxLength:80,fieldValue:t});o.addCheckboxRow_deprecated("chkIsDisabled",{labelHTML:"Disabled",checked:a,hideRow:e?false:true});o.showClientDialog()}function editExpenseReport(a){var e="exitExpenseReport",t=new ClientDialogBuilder({formId:e,formTitle:"Edit Expense Report",focusFieldName:"null",arrExtraHeaderButtons:a.expenseReportId?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseReport("+a.expenseReportId+")"})]:null,fnSubmit:function(e){var t=e.cboPayableTo[e.cboPayableTo.selectedIndex].value;jsrsExecuteWithErrorP("Admin2_UpdateExpenseReport",function(e){hideDialog();refreshPageAndScrollPos()},"Updating Expense Report...",{expenseReportId:a.expenseReportId,payableToVendor:parseInt(t,10),vendorId:null})}}),i=a.vendorName||"Vendor",o=a.payableToVendor?1:0,n=buildOptionHTML(htmlEncode(a.userName),0,o)+buildOptionHTML(htmlEncode(i),1,o);t.addFlexibleFieldRow({rawLabel:"Payable To",valueHTML:'",additionalCellClasses:"clsVeryNarrowField"});t.showClientDialog()}function showAddOrUpdateExpenseVendor(e){var t=e.expenseVendorId,a=e.arrExpenseTypes,i=e.expenseVendorName,o=e.quickbooksCustomerName,n=e.quickbooksCustomerId,r=e.amexDescriptionMatchType,l=e.amexDescription,d=e.amexAppearsOnStatementAsMatchType,s=e.amexAppearsOnStatementAs,u=e.expenseType,c=e.reason,m=e.includeOnMemo,p=e.isDisabled,f=e.isGeneric,b="frmExpenseVendor",g=new ClientDialogBuilder({formId:b,formTitle:t?"Edit Expense Vendor":"Add Expense Vendor",focusFieldName:"txtName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:t?"Save":"Add",mnemonicChar:t?"s":"a",mnemonicActionJS:"submitAddOrUpdateExpenseVendor()"}),fnSubmit:submitAddOrUpdateExpenseVendor,arrExtraHeaderButtons:t?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseVendor("+t+", unescape('"+escape(i)+"'))"})]:null});g.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});var C={formId:b,idFieldName:"quickbooksCustomerId",handlingEnter:1,initialValue:n,stringifiedParams:'{ textFieldName: "'+"txtQuickbooksCustomer"+'", '+' formId: "'+b+'", '+' idFieldName: "'+"quickbooksCustomerId"+'",'+" fnGetTypeAheadData: quickBooksCustomerGetTypeAheadData,"+" fnHandleExplicitSelection: function(){}"+"}"};g.addTextFieldRow("txtName",{rawLabel:"Name",maxLength:80,fieldValue:i});g.addDialogInteriorRows(cdBuildTextFieldRowP("txtQuickbooksCustomer","Quickbooks Vendor",{fieldValue:o,typeaheadInfo:C,autofocus:1,suppressAutocomplete:1}));g.addCheckboxRow_deprecated("chkIncludeOnMemo",{labelHTML:"Include Amex Vendor On Memo",checked:m});g.addCheckboxRow_deprecated("chkIsGeneric",{labelHTML:"Generic",checked:f});g.addCheckboxRow_deprecated("chkIsDisabled",{hideRow:t?false:true,labelHTML:"Disabled",checked:p});g.addSectionHeaderRow();JTCRMExpense.addExpenseTypeDropdown({cdBuilder:g,rawLabelOverride:"Default Type",mnemonicForLabelOverride:"t",arrExpenseTypes:a,selectedExpenseType:u});g.addTextFieldRow("txtReason",{rawLabel:"Default Reason",maxLength:80,fieldValue:c});g.addFlexibleFieldRow({labelHTML:"Amex Description",valueHTML:'"+" "+"'});g.addFlexibleFieldRow({labelHTML:"Amex Appears On Statement As",valueHTML:'"+" "+"'});g.showClientDialog()}function showEditExpenseVendorDialog(e){jsrsExecuteWithErrorP("Admin2_GetExpenseVendorInfo",rsCallbackHandleStandardJSONResponse,"Retrieving Vendor Info",{expenseVendorId:e,includeExpenseTypes:1},{fnOnSuccess:showAddOrUpdateExpenseVendor})}function getUseTaxYearBoundaries(){return{useTaxYearMinimum:2018,useTaxYearMaximum:(new Date).getYear()+1900}}function submitCreateExpenseReport(){jsrsExecuteWithErrorP("Admin_CreateExpenseReport",function(e){var t=e.id;window.location=pageExpenseReportDetail+t},"Creating Expense Report...",{})}function doDeleteExpenseReportImage(e){jsrsExecuteWithErrorP("Admin2_DeleteExpenseReportDetailImage",function(){getObj("receiptFileId").value="";getObj("receiptRemoved").value=1;getObj("removeReceiptRow").style.display="none";getObj("addReceiptRow").style.display=""},"Deleting Expense Report Detail image...",{fileId:e.fileId,expenseReportDetailId:e.expenseReportDetailId})}function confirmDeleteExpenseReportDetailReceiptImage(e){var t=e.fileId,a=e.fileName,i=e.expenseReportDetailId;displaySimpleConfirmationDialog(doDeleteExpenseReportImage,'Are you sure you want to remove the receipt "'+a+'" from this Expense Report Detail?',"Delete Expense Report Detail Image",{fileId:t,expenseReportDetailId:i},1)}function submitReordeExpenseTypesDialog(e){submitReorderP({arrReorderedIds:e,reorderCommandName:"Admin2_ReorderExpenseTypes2",reorderIdsPropertyName:"expenseTypeIds",reorderObjectName:"Expense Types"})}function showReorderExpenseTypesDialog(e,t){rsCallbackGetObjectsForReorder({types:t},{originalOptions:{arrayAttrName:"types",fnSubmit:submitReordeExpenseTypesDialog,strReorderWhat:"Expense Types",highlightedId:e}})}function submitExpenseOptions(){var e="frmOptions",t=getObj(e),a=pageExpenses,i=t.cboExpenseViewOptions[t.cboExpenseViewOptions.selectedIndex].value,o="sort",n=t.cboAmexDescriptionMatchType[t.cboAmexDescriptionMatchType.selectedIndex].value,r=t.txtAmexDescription.value,l=getUrlParamValueIfThere(""+window.location,o);if(l){a+="&"+o+"="+l}a+="&expenseViewType="+i;if(i===""+ExpensesSummaryViews_Enum.esvAll){a+="&daysBack="+t.txtDaysBack.value}if(r&&r.length>0&&n>=0){a+="&amexVendor="+escape(r);a+="&amexVendorFilterType="+n}hideDialog();window.location=a;displayTimedMessage("Reloading page...")}function onExpenseViewTypeChanged(){var e=getObj("frmOptions");if(e){var t=e.cboExpenseViewOptions[e.cboExpenseViewOptions.selectedIndex].value;if(t===""+ExpensesSummaryViews_Enum.esvAll){e.txtDaysBack.parentNode.parentNode.style.display=""}else{e.txtDaysBack.parentNode.parentNode.style.display="none"}}}function submitUseTaxOptions(){var e="frmOptions",t=getObj(e),a=new FormValidator,i,o=parseInt(t.cboUseTaxTimePeriod.value,10),n=t.cboUseTaxMonth.value,r=t.cboUseTaxQuarter.value,l=t.txtUseTaxYear.value,d=getUseTaxYearBoundaries(),s=a.CSValidateNumberFieldP({field:t.txtUseTaxYear,label:"Year",isNullable:false,minValue:d.useTaxYearMinimum,maxValue:d.useTaxYearMaximum});if(!s){return}i=pageExpenseSettingsUseTax+"timePeriod="+o+"&year="+l;switch(o){case TimePeriodTypeFilter_Enum.tptfMonth:i+="&month="+n;break;case TimePeriodTypeFilter_Enum.tptfQuarter:i+="&quarter="+r;break}hideDialog();window.location=i;displayTimedMessage("Reloading page...")}function changeUseTaxTimePeriod(){var e="frmOptions",t=getObj(e),a=parseInt(t.cboUseTaxTimePeriod.value,10),i=a===TimePeriodTypeFilter_Enum.tptfMonth,o=a===TimePeriodTypeFilter_Enum.tptfQuarter;getObj("useTaxMonth").style.display=i?"":"none";getObj("useTaxQuarter").style.display=o?"":"none"}function showUseTaxOptionsDialog(t){var a=t.timePeriodType,e=t.year,i="frmOptions",o=new ClientDialogBuilder({formId:i,formTitle:"Use Tax - Options",focusFieldName:"cboUseTaxTimePeriod",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitUseTaxOptions()"}),fnSubmit:submitUseTaxOptions,arrExtraHeaderButtons:null}),n=getUseTaxYearBoundaries();o.addDropdown({fieldName:"cboUseTaxTimePeriod",rawLabel:"Time Period",mnemonicChar:"t",additionalCellClasses:"clsNarrowField",arrAvailableOptions:[{rawContent:"Month",cboValue:TimePeriodTypeFilter_Enum.tptfMonth},{rawContent:"Quarter",cboValue:TimePeriodTypeFilter_Enum.tptfQuarter},{rawContent:"Year",cboValue:TimePeriodTypeFilter_Enum.tptfYear}].map(function(e){e.isSelectedOption=e.cboValue===a;return e}),onClickChangeJS:"changeUseTaxTimePeriod()"});o.addTextFieldRow("txtUseTaxYear",{rawLabel:"Year",mnemonicChar:"y",fieldValue:""+e,isNumber:1,step:1,minValue:n.useTaxYearMinimum,maxValue:n.useTaxYearMaximum});o.addDropdown({fieldName:"cboUseTaxMonth",rawLabel:"Month",mnemonicChar:"m",arrAvailableOptions:[{rawContent:"January",cboValue:1},{rawContent:"February",cboValue:2},{rawContent:"March",cboValue:3},{rawContent:"April",cboValue:4},{rawContent:"May",cboValue:5},{rawContent:"June",cboValue:6},{rawContent:"July",cboValue:7},{rawContent:"August",cboValue:8},{rawContent:"September",cboValue:9},{rawContent:"October",cboValue:10},{rawContent:"November",cboValue:11},{rawContent:"December",cboValue:12}].map(function(e){e.isSelectedOption=e.cboValue===t.month;return e}),hideRow:1,rowId:"useTaxMonth"});o.addDropdown({fieldName:"cboUseTaxQuarter",rawLabel:"Quarter",mnemonicChar:"q",arrAvailableOptions:[{rawContent:"Q1",cboValue:TimePeriodQuarters_Enum.tpqFirst},{rawContent:"Q2",cboValue:TimePeriodQuarters_Enum.tpqSecond},{rawContent:"Q3",cboValue:TimePeriodQuarters_Enum.tpqThird},{rawContent:"Q4",cboValue:TimePeriodQuarters_Enum.tpqFourth}].map(function(e){e.isSelectedOption=e.cboValue===t.quarter;return e}),hideRow:1,rowId:"useTaxQuarter"});if(o.showClientDialog()){changeUseTaxTimePeriod()}}function showExpensesOptionsDialog(e,t,a){var i="frmOptions",o=getUrlParamValueIfThere(window.location,"expenseViewType"),n=parseInt(o,10);if(isNaN(n)||n<0||n>3){n=ExpensesSummaryViews_Enum.esvRequiresInput}var r=new ClientDialogBuilder({formId:i,formTitle:"Expenses View Options",focusFieldName:"cboExpenseViewOptions",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"A",mnemonicActionJS:"submitExpenseOptions()"}),fnSubmit:submitExpenseOptions,arrExtraHeaderButtons:null});var l=buildOptionHTML("Require User Input",ExpensesSummaryViews_Enum.esvRequiresInput,n);l+=buildOptionHTML("All Expenses",ExpensesSummaryViews_Enum.esvAll,n);r.addFlexibleFieldRow({rawLabel:"Filter Expenses",valueHTML:'"});r.addTextFieldRow("txtDaysBack",{rawLabel:"Days Back",fieldValue:e,isNumber:1,hideRow:n!==ExpensesSummaryViews_Enum.esvAll});r.addFlexibleFieldRow({labelHTML:"Amex Vendor",valueHTML:'"+''});r.showClientDialog()}function toggleExpandExpenseInfoExtras(){var e=getObj("imgExpenseInfoExtrasExpander.expand"),t=getObj("imgExpenseInfoExtrasExpander.collapse"),a=document.querySelectorAll(".expense-details");if(t.style.display==="none"){e.style.display="none";t.style.display="inline";a.forEach(function(e,t,a){e.style.display="table-cell"})}else{e.style.display="inline";t.style.display="none";a.forEach(function(e,t,a){e.style.display="none"})}}function doSubmitExpenseForApproval(e){var t="Submitting for approval...";jsrsExecute(function(){hideDialog();window.location=pageExpenses},"Admin_SubmitExpenseOrExpenseReportForApproval",[e.expenseId,e.expenseType],rsErrorCallbackShowErrorDialogAndRefresh,null,null,true);displayTimedMessage(t+"...");disableDialogButtons()}function expenseTypeNameFromId(e){return e===EventObjectType_Enum.eotExpense?"Expense":"Expense Report"}function confirmSubmitExpenseForApproval(e,t){displaySimpleConfirmationDialog(doSubmitExpenseForApproval,"Are you sure you want to submit this "+expenseTypeNameFromId(t)+" for approval?
Once submitted for approval you will not be able to make further changes.","Submit "+expenseTypeNameFromId(t)+" For Approval",{expenseId:e,expenseType:t})}function submitUpdateExpenseOrExpenseReport(e,t,a,i,o,n){jsrsExecuteWithErrorP("Admin2_UpdateApprovalState",n,"Updating Approval Status",{id:e,type:t,status:a,reason:i,vendor:o})}function submitRejectExpense(){var e=getObj("rejectExpense"),t=e.id.value,a=e.type.value,i=e.txtRejectionReason.value;if(""===i){showInfoDialog("A reason must be supplied when rejecting an expense","Missing Field",1,"txtRejectionReason");return}submitUpdateExpenseOrExpenseReport(t,a,Expense_Approval_Status_Enum.easRejected,i,null,function(){hideDialog();window.location=pageExpenseApprovals})}function submitApproveExpenseReport(e,t){submitUpdateExpenseOrExpenseReport(e,t,Expense_Approval_Status_Enum.easApproved,null,null,function(){hideDialog();window.location=pageExpenseApprovals})}function submitApproveExpense(){var e=getObj("frmApproveExpense"),t=e.id.value,a=e.type.value,i=e.cboVendor?e.cboVendor[e.cboVendor.selectedIndex].value:null;if(""===i&&e.cboVendor){showInfoDialog("A vendor must be supplied when approving an expense","Missing Field",1,"txtRejectionReason");return}submitUpdateExpenseOrExpenseReport(t,a,Expense_Approval_Status_Enum.easApproved,"",i,function(){hideDialog();window.location=pageExpenseApprovals})}function submitUnapproveExpense(e){submitUpdateExpenseOrExpenseReport(e.id,e.type,Expense_Approval_Status_Enum.easWaitingForApproval,"",null,function(){hideDialog();window.location=pageExpenseApprovals})}function unapproveExpense(e,t){displaySimpleConfirmationDialogP(submitUnapproveExpense,"Are you certain you want to unapprove this expense? "+"If unapproved it will no longer be eligible to be exported until it is re-approved",{formTitle:"Unapprove Expense",okButtonDisplayText:"Unapprove",contextDetail:{id:e,type:t}})}function rejectExpense(e,t){var a="rejectExpense",i=new ClientDialogBuilder({formId:a,formTitle:"Reject Expense",focusFieldName:"txtRejectionReason",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitRejectExpense()"}),fnSubmit:submitRejectExpense,arrExtraHeaderButtons:null});i.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});i.addTextFieldRow("txtRejectionReason",{rawLabel:"Rejection Reason",maxLength:256,fieldValue:""});i.showClientDialog()}function promptApproveExpenseReport(e,t){displaySimpleConfirmationDialogP(function(){hideDialog();submitApproveExpenseReport(e,t)},"Are you sure you want to approve the Expense Report?",{formTitle:"Approve Expense Report",okButtonDisplayText:"Approve"})}function approveExpense(e){if(e.expenseType===EventObjectType_Enum.eotExpenseReport&&!e.payableToVendor){promptApproveExpenseReport(e.id,e.expenseType);return}var t="frmApproveExpense",a={arrExpenseTypes:JSON.parse(e.types),expenseVendorName:e.description,amexDescriptionMatchType:0,amexDescription:e.description,amexAppearsOnStatementAsMatchType:0,amexAppearsOnStatementAs:e.appearsOnStatementAs,expenseType:e.defaultVendorTypeId,reason:e.defaultReason},i=new ClientDialogBuilder({formId:t,formTitle:"Approve Expense",focusFieldName:"cboVendor",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitApproveExpense()"}),fnSubmit:submitApproveExpense,arrExtraHeaderButtons:[cdBuildFAFontIconButton({additionalButtonClasses:"textDialogButton",htmlContent:"Add Vendor",fontId:FontIconId_Enum.fiiPlusInCircle,doubleQuoteEncodedTitle:"Add Vendor",doubleQuoteEncodedOnClickJS:"showAddOrUpdateExpenseVendor("+htmlEncode(JSON.stringify(a))+")"})]});i.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});var o=buildOptionHTML("","",false);for(var n=0;n'+o+""});i.showClientDialog()}function rsCallbackResolveApprovalError(e,t,a){if(checkResponseForError(e)){hideDialog();window.location=pageExpenses}}function submitResolveApprovalError(e){var t="Resolving Expense Issue...";jsrsExecute(rsCallbackResolveApprovalError,"Admin_ResolveExpenseError",[e.id,e.type],rsErrorCallbackShowErrorDialogAndRefresh,null,null,true);displayTimedMessage(t+"...");disableDialogButtons()}function resolveApprovalError(e,t){displaySimpleConfirmationDialog(submitResolveApprovalError,"Do you want to resolve the issue with this "+expenseTypeNameFromId(t)+"?
Resolving will re-submit the "+expenseTypeNameFromId(t)+" for approval.","Resolve Expense Error",{id:e,type:t})}function submitAddOrUpdateExpenseImportBlocklist(){var e=getObj("addOrUpdateExpenseImportBlocklist"),t=e.expenseImportBlocklistId.value,a=e.txtName.value,i=e.cboAmexDescriptionMatchType[e.cboAmexDescriptionMatchType.selectedIndex].value,o=e.cboAmexAppearsOnStatementAsMatchType[e.cboAmexAppearsOnStatementAsMatchType.selectedIndex].value,n=e.txtAmexAppearsOnStatementAs.value,r=e.txtAmexDescription.value,l=t?"Updating Expense Import Blocklist...":"Adding To Expense Import Blocklist...";if(""===a){showInfoDialog("Name is required","Missing Field",1,"year");return}if(""!==n&&""===o){showInfoDialog("You must specify a match type for Amex Appears on statement as","Missing Field",1,"year");return}if(""!==o&&n===""){showInfoDialog("You must specify a value for Appears On Statement As","Invalid Value",1,"year");return}if(""!==r&&""===i){showInfoDialog("You must specify a match type for Amex Description","Missing Field",1,"year");return}if(""!==i&&""===r){showInfoDialog("You must specify a match type for Amex Description","Missing Field",1,"year");return}jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_AddOrUpdateExpenseImportBlocklist",[t,a,i,escape(r),o,escape(n)],enableDialogButtons);displayTimedMessage(l+"...");disableDialogButtons()}function addOrUpdateExpenseImportBlocklist(e,t,a,i,o,n){var r="addOrUpdateExpenseImportBlocklist",l=new ClientDialogBuilder({formId:r,formTitle:e?"Edit Expense Import Blocklist":"Add To Expense Import Blocklist",focusFieldName:"txtName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:e?"Save":"Add",mnemonicChar:e?"s":"a",mnemonicActionJS:"submitAddOrUpdateExpenseImportBlocklist()"}),fnSubmit:submitAddOrUpdateExpenseImportBlocklist,arrExtraHeaderButtons:e?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseImportBlocklist("+e+", unescape('"+escape(t)+"'))"})]:null});l.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});l.addTextFieldRow("txtName",{rawLabel:"Name",maxLength:80,fieldValue:t});l.addFlexibleFieldRow({labelHTML:"Amex Description",valueHTML:'"+''});l.addFlexibleFieldRow({labelHTML:"Amex Appears On Statement As",valueHTML:'"+''});l.showClientDialog()}function setDatabaseCompanyAddressAsNeedsConfirmation(e){jsrsExecuteWithErrorP("Admin2_SetDatabaseCompanyAddressAsNeedsConfirmation",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating company address to require confirmation",{databaseId:e})}function confirmSetDatabaseCompanyAddressAsNeedsConfirmation(e){displaySimpleConfirmationDialog(setDatabaseCompanyAddressAsNeedsConfirmation,"Are you sure you want to prompt the user to review their company address?","Prompt User to Review Company Address",e,null,null,"Yes")}function setDatabaseContactAsNeedsConfirmation(e){jsrsExecuteWithErrorP("Admin2_SetDatabaseContactAsNeedsConfirmation",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating contact to require confirmation",{databaseContactId:e})}function confirmSetDatabaseContactAsNeedsConfirmation(e){displaySimpleConfirmationDialog(setDatabaseContactAsNeedsConfirmation,"Are you sure you want to prompt the user to review this contact?","Prompt User to Review Contact",e,null,null,"Yes")}function rsCallbackSentDunningEmails(e){var t=e.arrFailures,a=e.arrHandledInvoices,i=a?a.length:0,o=t?t.length:0,n=new ClientDialogBuilder({formTitle:"Sent Dunning Emails",fnCancelOrClose:function(){hideDialog();saveScrollPos();refreshPageShowingMessage()}}),r;if(i){n.addSectionHeaderRow({rawTitle:i===1?"Processed 1 Invoice":"Processed "+i+" Invoice"});r=new MWClientTable({additionalTableClasses:"unsetTableWidth100"});r.addColumn(new MWColumn({columnName:"Subdomain",simpleDisplayColumnPropertyName:"subDomainName"}));r.addColumn(new MWColumn({columnName:"Invoice #",simpleDisplayColumnPropertyName:"invoiceNumber"}));r.addColumn(new MWColumn({columnName:"Email Address",simpleDisplayColumnPropertyName:"targetEmailAddress"}));r.addColumn(new MWColumn({columnName:"DB Id",simpleDisplayColumnPropertyName:"databaseId"}));n.addFlexibleRow({valueHTML:r.buildTableForArray(a)})}if(o){n.addSectionHeaderRow({rawTitle:o===1?"1 Failure":o+" Failures"});r=new MWClientTable({additionalTableClasses:"unsetTableWidth100"});r.addColumn(new MWColumn({columnName:"Error",simpleDisplayColumnPropertyName:"errorMessage",simpleDisplayColumnNeedsMultilineEncoding:1,additionalCellClasses:"errorText"}));r.addColumn(new MWColumn({columnName:"Subdomain",simpleDisplayColumnPropertyName:"subDomainName"}));r.addColumn(new MWColumn({columnName:"Invoice #",simpleDisplayColumnPropertyName:"invoiceNumber",additionalCellClasses:"rightAlign"}));r.addColumn(new MWColumn({columnName:"Email Address",simpleDisplayColumnPropertyName:"targetEmailAddress"}));r.addColumn(new MWColumn({columnName:"DB Id",simpleDisplayColumnPropertyName:"databaseId",additionalCellClasses:"rightAlign"}));n.addFlexibleRow({valueHTML:r.buildTableForArray(t)})}n.addSectionHeaderRow({titleHTML:"Raw Results "+cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiRightChevron,terseFontIcon:1,doubleQuoteEncodedTitle:"Display Raw Results",doubleQuoteEncodedOnClickJS:"getObj('rowRawResults').style.display='';"+"getObj('btnDisplayRawResults').style.display='none'",buttonId:"btnDisplayRawResults"})});n.addFlexibleRow({valueHTML:htmlEncode(JSON.stringify(e,null,2)),additionalCellClasses:"JSONViewer",rowId:"rowRawResults",hideRow:1});n.showClientDialog()}function sendDunningEmails(){hideDialog();jsrsExecuteWithErrorP("Admin2_SendDunningEmails",rsCallbackHandleStandardJSONResponse,"Sending Dunning Emails",{},{fnOnSuccess:rsCallbackSentDunningEmails})}function promptSendDunningEmails(e){var t=new ClientDialogBuilder({formTitle:"Send Dunning Emails",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Send Emails",mnemonicChar:"s",mnemonicActionJS:"sendDunningEmails()"}),fnSubmit:sendDunningEmails});t.addFlexibleRow({rawValue:"Are you sure you want to send the Dunning Emails?"});t.showClientDialog()}function submitSalesByStateOptions(){var e="frmOptions",t=getObj(e),a=pageSalesByState,i=parseInt(t.cboTimeSelection.value,10),o,n,r=t.txtPageSize,l=new FormValidator;if(!l.CSValidateDateFieldP({field:t.dtStartDate,label:"Start Date",isNullable:false})){return}if(!l.CSValidateDateFieldP({field:t.dtEndDate,label:"End Date",isNullable:false})){return}o=getDateForUrlParam(t.dtStartDate.value);n=getDateForUrlParam(t.dtEndDate.value);if(o&&n&&parseDateString(n)1?"AutopayStatusName":"AutopayStatusSelect",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitAutopayReportOptions()"}),fnSubmit:submitAutopayReportOptions});n.addCompoundSelectionFieldRowP({fieldNameBase:"AutopayStatus",whatSingular:"Autopay Status",whatPlural:"Autopay Statuses",arrSelectedIds:i,objectArrayName:"arrAutopayStatuses",autofocus:1,fnRSCallSubstitute:function(){return{arrAutopayStatuses:o}},arrObjects:o});n.addDropdown({fieldName:"cboActiveStatusFilter",rawLabel:"Product Status",mnemonicChar:"p",mnemonicFocusFieldName:"cboActiveStatusFilter",autofocus:1,arrAvailableOptions:[{cboValue:ActiveStatusFilter_Enum.asfAny,rawContent:"Any"},{cboValue:ActiveStatusFilter_Enum.asfActiveOnly,rawContent:"Active Products Only"},{cboValue:ActiveStatusFilter_Enum.asfInactiveOnly,rawContent:"No Active Products"}],objSelectedValue:{cboValue:e.activeStatusFilter||ActiveStatusFilter_Enum.asfActiveOnly}});n.addTextFieldRow("txtNextInvoiceDayOfMonth",{rawLabel:"Next Invoice Day of Month",fieldValue:e.nextInvoiceDayOfMonth?""+e.nextInvoiceDayOfMonth:"",mnemonicChar:"n",maxLength:2,styleWidth:"7em",isNumber:1});n.addTextFieldRow("txtPageSize",{rawLabel:"Rows per Page",fieldValue:""+e.pageSize,mnemonicChar:"r",maxLength:10,styleWidth:"7em",isNumber:1});n.showClientDialog()}function submitCustomerPortalReportOptions(){var e="frmOptions",t=getObj(e),a=new FormValidator,i=pagePortalUsageReport,o=t.txtPageSize,n=trim(o.value),r=t.txtMaxDaysOld,l=trim(r.value),d="PUsageListsort",s=getUrlParamValueIfThere(""+window.location,d),u=t.cboUserType.value;if(!a.CSValidateIntegerField(o,"Page Size",true,1,2e3)){return}if(!a.CSValidateIntegerField(r,"Max Days Old",true,1,2e3)){return}if(s){i+="&"+d+"="+s}if(n){i+="&pageSize="+n}if(l){i+="&maxDaysOld="+l}if(u!==""+FilteredVUserType_Enum.fvutJTOnly){i+="&userType="+u}hideDialog();window.location=i;displayTimedMessage("Reloading page...")}function showCustomerPortalReportOptionsDialog(e){var t="frmOptions",a=new ClientDialogBuilder({formId:t,formTitle:"Customer Portal Report Options",focusFieldName:"cboUserType",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitCustomerPortalReportOptions()"}),fnSubmit:submitCustomerPortalReportOptions});a.addDropdown({fieldName:"cboUserType",rawLabel:"User Type",autofocus:1,arrAvailableOptions:[{cboValue:FilteredVUserType_Enum.fvutAny,rawContent:"Any"},{cboValue:FilteredVUserType_Enum.fvutJTOnly,rawContent:"JobTracker Users Only"},{cboValue:FilteredVUserType_Enum.fvutBillingOnly,rawContent:"Billing Users Only"}],objSelectedValue:{cboValue:e.filteredVUserType||FilteredVUserType_Enum.fvutAny}});a.addTextFieldRow("txtPageSize",{rawLabel:"Rows per Page",fieldValue:""+e.pageSize,maxLength:10,styleWidth:"7em",isNumber:1});a.addTextFieldRow("txtMaxDaysOld",{rawLabel:"Show Last",fieldValue:""+e.maxDaysOld,maxLength:10,styleWidth:"7em",isNumber:1,strPostFieldHTML:" Days"});a.showClientDialog()}function submitLegacyPricingReportOptions(){var e="frmOptions",t=getObj(e),a=pageLegacyPricingReport,i="legacyPricingReportTablesort",o=getUrlParamValueIfThere(""+window.location,i),n=t.cboNewPriceTarget.value;if(o){a+="&"+i+"="+o}if(n!==""+NewPriceTargetFilterOption_Enum.nptfoAll){a+="&newPriceTarget="+n}hideDialog();window.location=a;displayTimedMessage("Reloading page...")}function showLegacyPricingReportOptionsDialog(e){var t="frmOptions",a=new ClientDialogBuilder({formId:t,formTitle:"Report Options",focusFieldName:"cboNewPriceTarget",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitLegacyPricingReportOptions()"}),fnSubmit:submitLegacyPricingReportOptions});a.addDropdown({fieldName:"cboNewPriceTarget",rawLabel:"New Price Target",autofocus:1,arrAvailableOptions:[{cboValue:NewPriceTargetFilterOption_Enum.nptfoAll,rawContent:"CG/JT/Sys"},{cboValue:NewPriceTargetFilterOption_Enum.nptfoCGOnly,rawContent:"CG Only"},{cboValue:NewPriceTargetFilterOption_Enum.nptfoJTSysOnly,rawContent:"JT/Sys Only"}],objSelectedValue:{cboValue:e.newPriceTarget||NewPriceTargetFilterOption_Enum.nptfoAll}});a.showClientDialog()}function toggleDisplayImportDisbursementResults(){var e=getObj("icoExpand"),t=e.style.display==="none",a=!t;e.style.display=a?"none":"";getObj("icoCollapse").style.display=a?"":"none";getObj("rowImportDisbursementResultsJson").style.display=a?"":"none"}function rsCallbackImportDisbursements(e){hideDialog();var t="frmImportDisbursementResults",a=new ClientDialogBuilder({formId:t,formTitle:"Import Disbursements",fnCancelOrClose:function(){refreshPageAndScrollPos()}}),i=e.arrImportInfos,o=i?i.length:0,n,r,l,d,s,u;for(l=0;l"+'
'+cdBuildFontIconElem({fontId:FontIconId_Enum.fiiRightChevron,terseFontIcon:1,fontIconElemId:"icoExpand"})+cdBuildFontIconElem({fontId:FontIconId_Enum.fiiDownChevron,terseFontIcon:1,fontIconElemId:"icoCollapse",hideIcon:1})+" Raw JSON"+"
"});a.addFlexibleRow({valueHTML:htmlEncode(JSON.stringify(e,null,2)),additionalCellClasses:"JSONViewer",rowId:"rowImportDisbursementResultsJson",hideRow:1});a.showClientDialog()}function submitImportBTDisbursements(){var e="frmImport",t=getObj(e),a=t.dtDate,i=new FormValidator,o;if(!i.CSValidateDateField(a,"Date",true,"dtDate")){return}o=getDateForUrlParam(a.value);jsrsExecuteWithErrorP("Admin2_ImportDisbursements",rsCallbackHandleStandardJSONResponse,"Importing Disbursements",{disbursementDate:o},{fnOnSuccess:rsCallbackImportDisbursements})}function promptImportDisbursements(){var e="frmImport",t=new ClientDialogBuilder({formId:e,formTitle:"Import Disbursements",focusFieldName:"dtDate",fnSubmit:submitImportBTDisbursements,okButtonDisplayText:"Import"});t.addDatePickerRow(e,"dtDate",{rawLabel:"Payment Transaction Date"});t.showClientDialog()}function submitUpdateDisbursementDate(){var e="frmEditDisbursementDate",t=getObj(e),a=t.dtDate,i=new FormValidator;if(!i.CSValidateDateField(a,"Deposit Date",false,"dtDate")){return}jsrsExecuteWithErrorP("Admin2_UpdateBTDisbursementDate",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Disbursement Date",{disbursementDate:mjtElemData(t,"disbursementDate"),depositDate:getDateForUrlParam(a.value)})}function showEditDisbursementDateDialog(e){var t="frmEditDisbursementDate",a,i=e.disbursementDate,o=new ClientDialogBuilder({formId:t,formTitle:"Update Disbursement Date",focusFieldName:"dtDate",fnSubmit:submitUpdateDisbursementDate});o.addFlexibleFieldRow({rawLabel:"Disbursement Date",rawValue:i});o.addDatePickerRow(t,"dtDate",{rawLabel:"Deposit Date",strValue:e.depositDate||""});a=o.showClientDialog();if(a){mjtElemData(a,"disbursementDate",i)}}function submitStopRetryingPayments(){var e="frmCeaseRetry",t=getObj(e),a=mjtElemData(t,"databaseId");hideDialog();jsrsExecuteWithErrorP("Admin2_SetAutomatedPaymentStatusPermanentFailure",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Marking Permanent Failure",{databaseId:a})}function showUpdateCustomerPaymentDate(e){var t="frmCeaseRetry",a,i=new ClientDialogBuilder({formId:t,formTitle:"Temporarily Stop Retrying",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Stop Retrying",mnemonicChar:"s",mnemonicActionJS:"submitStopRetryingPayments()"}),fnSubmit:submitStopRetryingPayments});i.addFlexibleRow({valueHTML:"Are you sure you want to stop retrying payments until the next pay period?"});a=i.showClientDialog();if(a){mjtElemData(a,"databaseId",e)}}function submitReconcileBTProfile(){var e="frmReconcile",t=getObj(e),a=mjtElemData(t,"billingProcessorCustomerId");hideDialog();jsrsExecuteWithErrorP("Admin2_ReconcileBTBillingProfile",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Reconciling Braintree Profile",{billingProcessorCustomerId:a})}function reconcileBTProfile(e){var t="frmReconcile",a,i=new ClientDialogBuilder({formId:t,formTitle:"Reconcile Braintree Profile",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Reconcile",mnemonicChar:"r",mnemonicActionJS:"submitReconcileBTProfile()"}),fnSubmit:submitReconcileBTProfile});i.addFlexibleRow({rawValue:'Are you sure you want to reconcile billing id "'+e.billingProcessorCustomerId+'"?'});a=i.showClientDialog();if(a){mjtElemData(a,"billingProcessorCustomerId",e.billingProcessorCustomerId)}}function submitUpdateDatabasePricingStructureDialog(){var e="frmUpdateDatabasePricingStructure",t=getObj(e),a=new FormValidator,i=getDateForUrlParam(t.dtEffectiveDate.value),o,n=new Date,r=mjtElemData(t,"databasePricingStructureId"),l;if(!a.CSValidateDateFieldP({field:t.dtEffectiveDate,label:"Effective Date"})){return}n=new Date(n.getFullYear(),n.getMonth(),n.getDate());o=parseDateString(i);if(o'+htmlEncode(e.pricingStructureName)+" "+htmlEncode(e.productTypeName)+" Effective "+cdCarefullyLocalizeDateValue(e.effectiveDate)+"","Remove Database Pricing Structure",{databasePricingStructureId:e.databasePricingStructureId})}function doShowUpdateDatabasePricingStructureDialog(e,t){var a="frmUpdateDatabasePricingStructure",i,o=e.pricingStructure,n=e.nextInvoiceInfo,r=o.databasePricingStructureId,l=o.effectiveDate,d=o.productTypeName,s=o.pricingStructureName,u=t.originalPayload.subdomain,c=cdCarefullyLocalizeDateValue(n.nextInvoiceDate),m="dtEffectiveDate",p={nextInvoiceDate:c,formId:a,dateFieldId:m},f=getNextInvoiceDateLink(p),b={subdomain:u,pricingStructureName:s,productTypeName:d,effectiveDate:l,databasePricingStructureId:r},g=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),C=new ClientDialogBuilder({formId:a,formTitle:"Change Pricing Structure Effective Date",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Update",mnemonicChar:"u",mnemonicActionJS:"submitUpdateDatabasePricingStructureDialog()"}),fnSubmit:submitUpdateDatabasePricingStructureDialog,arrExtraHeaderButtons:[g?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedOnClickJS:"confirmRemoveDatabasePricingStructure(JSON.parse(unescape('"+escape(JSON.stringify(b))+"')))",doubleQuoteEncodedTitle:"Remove Database Pricing Structure"}):null,g?'':null,cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayDatabasePricingStructureEventLog("+r+")"})]});C.addFlexibleFieldRow({rawLabel:"Product Type",rawValue:d});C.addFlexibleFieldRow({rawLabel:"Pricing Structure",rawValue:s});C.addDatePickerRow(a,m,{rawLabel:"Effective Date",strValue:cdCarefullyLocalizeDateValue(l),strPostPickerHTML:f});i=C.showClientDialog();if(i){mjtElemData(i,"databasePricingStructureId",r)}}function showUpdateDatabasePricingStructureDialog(e){jsrsExecuteWithErrorP("Admin2_GetDatabasePricingStructure",doShowUpdateDatabasePricingStructureDialog,"Getting Database Pricing Structure",e)}function submitMissingPricingStructureSelectionDialog(){var e="frmApplyPricingStructure",t=getObj(e),a=new FormValidator,i=mjtElemData(t,"databaseId"),o=t.cboPricingStructure.options[t.cboPricingStructure.selectedIndex].value,n=o!==""?parseInt(o,10):null,r=getDateForUrlParam(t.dtEffectiveDate.value),l=parseDateString(r),d={databaseId:i,pricingStructureId:n,effectiveDate:l};if(!n){showInfoDialog("Please select a pricing structure.","Select Pricing Structure",true,"cboPricingStructure");return}if(!a.CSValidateDateFieldP({field:t.dtEffectiveDate,label:"Effective Date"})){return}jsrsExecuteWithErrorP("Admin2_ApplyDatabasePricingStructure",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Applying Database Pricing Structure",d)}function doShowMissingPricingStructureSelectionDialog(e,t){var a="frmApplyPricingStructure",i,o=e.arrPricingStructures,n=t.originalPayload.productName,r=t.originalPayload.databaseId,l=t.originalPayload.productTypeId,d=parseInt(l,10),s=t.originalPayload.editionId,u=s?parseInt(s,10):null,c="cboPricingStructure",m="tdPricingStructure",p=buildDropdownRow({name:c,label:"Pricing Structure",valueLookup:"pricingStructureId",textLookup:"pricingStructureName",values:o,valueCellId:m}),f=new ClientDialogBuilder({formId:a,formTitle:"Select Pricing Structure",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitMissingPricingStructureSelectionDialog()"}),fnSubmit:submitMissingPricingStructureSelectionDialog});f.addFlexibleFieldRow({rawLabel:"Product",rawValue:n});f.addDialogInteriorRows(p);f.addDatePickerRow(a,"dtEffectiveDate",{rawLabel:"Effective Date"});i=f.showClientDialog();if(i){mjtElemData(i,"databaseId",r);var b={strFormId:a,selectedProductTypeId:d,selectedEditionId:u,arrPricingStructures:o,pricingStructureValueCellId:m,pricingStructureSelectorName:c};refreshPricingStructureSelector(b)}}function showMissingPricingStructureSelectionDialog(e){jsrsExecuteWithErrorP("Admin2_GetPricingStructures",doShowMissingPricingStructureSelectionDialog,"Retrieving Pricing Structures",e)}function submitApplyDatabasePricingStructureSelectionDialog(){var e="frmApplyPricingStructure",t=getObj(e),a=mjtElemData(t,"databaseId"),i=new FormValidator,o=getDateForUrlParam(t.dtEffectiveDate.value),n,r=new Date,l=t.cboPricingStructure.options[t.cboPricingStructure.selectedIndex].value,d;if(!l){showInfoDialog("Please select a pricing structure.","Select Pricing Structure",true,"cboPricingStructure");return}if(!i.CSValidateDateFieldP({field:t.dtEffectiveDate,label:"Effective Date"})){return}r=new Date(r.getFullYear(),r.getMonth(),r.getDate());n=parseDateString(o);if(n";for(var i in e){var o=e[i];if(o.isDeprecated){continue}if(t!==o.productName){if(t!==undefined){a+=""}a+='"}return'"}function doShowApplyDatabasePricingStructureSelectionDialog(e,t){var a="frmApplyPricingStructure",i,o=e.arrPricingStructures,n=t.originalPayload.databaseId,r=e.nextInvoiceInfo,l=cdCarefullyLocalizeDateValue(r.nextInvoiceDate),d="dtEffectiveDate",s={nextInvoiceDate:l,formId:a,dateFieldId:d},u=getNextInvoiceDateLink(s),c=createPricingStructureSelector(o),m=new ClientDialogBuilder({formId:a,formTitle:"Select Pricing Structure",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitApplyDatabasePricingStructureSelectionDialog()"}),fnSubmit:submitApplyDatabasePricingStructureSelectionDialog});m.addFlexibleFieldRow({rawLabel:"Pricing Structure",valueHTML:c});m.addDatePickerRow(a,d,{rawLabel:"Effective Date",strPostPickerHTML:u});i=m.showClientDialog();if(i){mjtElemData(i,"databaseId",n)}}function showApplyDatabasePricingStructureSelectionDialog(e){jsrsExecuteWithErrorP("Admin2_GetPricingStructuresForSelection",doShowApplyDatabasePricingStructureSelectionDialog,"Retrieving Available Pricing Structures",e)}var JTCRMUtils=function(){function e(){SummaryOptionsFilter.setRSCommandToUse({commandId:FilterFrameworkRemoteScriptingCommands_Enum.ffrscGetFilterControlInfoForPage,rsCommandString:"Admin2_GetFilterControlInfoForPage"});SummaryOptionsFilter.setRSCommandToUse({commandId:FilterFrameworkRemoteScriptingCommands_Enum.ffrscGetFilterPropertyOptionsForPage,rsCommandString:"Admin2_GetFilterPropertyOptionsForPage"})}function x(e){var t=e.product,a=e.arrProductMenuItems,i=e.productOrderId,o=e.lastDisplayedProductGroupIdHolder,n=t.name,r=t.id,l=buildProductPricingSuffix(t),d=t.displayedProductGroupName,s=t.displayedProductGroupId,u=!!t.editionId,c={productOrderId:i},m=htmlEncode(n)+htmlEncode(l);if(s!=o.lastDisplayedProductGroupId){o.lastDisplayedProductGroupId=s;a.push({rawText:d,inactive:1,isHeader:1})}c.productId=r;c.productName=n;c.pricingStructureId=t.pricingStructureId;var p=htmlEncode(JSON.stringify(c));a.push({itemHTML:m,leadItemIconId:FontIconId_Enum.fiiPlusInCircle,altSubmenu:u?0:{fontId:FontIconId_Enum.fiiRightChevron,doubleQuoteEncodedTitle:"Custom Quantity",doubleQuoteEncodedOnClickJS:"showAddSpecificProductCountSubmenu("+"event,"+p+");"+"cancelEvent(event);"+"return false;"},doubleQuoteReadyScript:"addSpecificProductAndQtyToOrder("+p+","+"1)"})}function o(e,t){var a=e.upgradeDowngradeInfo,i=e.arrProducts,o=e.arrRestartProducts||[],n=t.originalPayload,r=(a||{}).arrProducts,l=r||[],d=l.length,s=n.productOrderId,u,c,m=[],p,f=new ContextMenu;if(d){var b=0,g=0,C=a.existingProductName,D={productOrderId:s,originalProductName:C};for(u=0;u1&&o>0){--o;var r=t[o].targetMonth;while(r1){--n;E({arrKPIGoals:t,idxArrayTarget:0,targetYear:a,targetMonth:n})}return t}function F(){var e=new MWColumn({columnName:"Goal",additionalHeaderClasses:"centerAlign"}),t=new MWClientTable({arrColumns:[new MWColumn({columnName:"Month",simpleDisplayColumnPropertyName:"targetMonthName"}),e]});e.addSubColumn(new MWColumn({columnName:"# of Products Sold",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(e,t,a,i){var o=e.productsSoldGoal,n=o?""+o:"",r=v+i,l=cdBuildTextFieldP(r,{fieldValue:n,fieldClasses:"clsSkipFormNormalization",maxLength:4,fieldSize:4});return l}}));e.addSubColumn(new MWColumn({columnName:"Activity %",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(e,t,a,i){var o=e.activityPercentSoldGoal,n=o?""+o:"",r=P+i,l=cdBuildTextFieldP(r,{fieldValue:n,fieldClasses:"clsSkipFormNormalization",maxLength:4,fieldSize:4})+" %";return l}}));return t}function N(e){var t=e.arrKPIGoals,a=e.targetYear,i=A({arrKPIGoals:t,targetYear:a}),o=new ClientDialogBuilder({formId:I,formTitle:"Set Goals - "+a,focusFieldOnMobile:1,focusFieldName:v+0,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"JTCRMUtils.PROTECTED.submitUpdateKPIGoals()"}),arrExtraHeaderButtons:[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiCalendar,doubleQuoteEncodedTitle:"Select Year",doubleQuoteEncodedOnClickJS:"JTCRMUtils.PROTECTED.promptSelectDateForEditGoals()"})],fnSubmit:R}),n={arrKPIGoals:i,targetYear:a},r={formElemData:n},l=F({});o.addFlexibleRow({valueHTML:l.buildTableForArray(i)});o.showClientDialog(r)}function O(e){var t=(e||{}).year,a=t||(new Date).getFullYear();jsrsExecuteWithErrorP("Admin2_GetKPIGoals",rsCallbackHandleStandardJSONResponse,"Getting list of product options",{year:a},{fnOnSuccess:N})}function M(){var e=getObj(I),t=mjtElemData(e,"targetYear");hideDialogP({callback:function(){DatePicker.promptEnterYear({initialYear:t,fnSelectedYear:function(e){hideDialog();O({year:e.selectedYear})}})}})}function k(){if(g_arrFileDragDropFileInfos.length){doUploadFiles(getObj("attachFile"))}else{hideDialog()}}function L(e){var t=e.cdBuilder,a=JTCRMExpense.buildReceiptCaveatHtml();t.addFlexibleRow({valueHTML:a})}function U(e){var t=e.objectId,a=e.fileTypeId,i=e.isExpenseDetailReceipt,o="attachFile",n=new ClientDialogBuilder({formId:o,formTitle:"Attach File",formAction:pageUploadAttachedFile,focusFieldName:"fileName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Attach",mnemonicChar:"a",mnemonicActionJS:"JTCRMUtils.PROTECTED.submitAttachFile()"}),fnSubmit:k});n.addFileUploadRow({fileLimit:1,fileType:a,objectId:t,acceptContentTypeHint:"image/*, .pdf",uploadLabel:"Drag or paste file here"});if(i){L({cdBuilder:n})}n.showClientDialog()}return{wireUpClientFilterRSCalls:e,showAddToOrderDropdown:t,promptAddSalesperson:a,promptEditSalesperson:i,promptAddOnboarder:C,promptEditOnboarder:D,mapSalespersonOnboarderToProductSale:w,displayProductSalesOptions:S,displayEditGoalsDialog:O,showAttachFile:U,PROTECTED:{submitUpdateProductSalesMapping:h,submitUpdateKPIGoals:R,promptSelectDateForEditGoals:M,navToProductSalesReport:y,submitAttachFile:k}}}();var JTCRMExpense=function(){var u="uploadAmexCSV",o="stateSelectRow",w="addOrUpdateExpenseReportDetailOrBusinessReason",T="participant",d="cboTrip",c="txtBusinessJustification",S="cboType",l="chkSalesTaxWithheld",s="cboState",m=128;function p(){var e=getObj(l),t=getObj(o),a=e.checked;t.style.display=a?"":"none"}function e(){var e=getObj(l),t=getObj(s),a=e.checked,i=!a;e.checked=i;p();if(i){setFocusIfFocusable(t)}}function n(e){var t=e.objCDBuilder,a=e.selectedState,i=["CA","MI","NV","OR","TX","UT","WA","WI"].map(function(e){return{cboValue:e,rawContent:e}});t.addDropdown({fieldName:s,fieldId:s,arrAvailableOptions:i,objSelectedValue:a?{cboValue:a,rawContent:a}:undefined,objNoneOption:{cboValue:""},fieldClasses:"clsSkipFormNormalization marginLeftLarge",strPreFieldHTML:''+"In what state is the use tax owed?"+" ",rowId:o})}function r(e){var t=e.objCDBuilder,a=e.salesTaxNotPaid;t.addCheckboxRow_deprecated(l,{rawLabel:"Does Use Tax need to be paid?",mnemonicChar:"x",mnemonicActionJS:"JTCRMExpense.PROTECTED.toggleUseTaxStateCB()",checked:a,onClickCode:"JTCRMExpense.PROTECTED.showHideTaxStateDropdown()"})}function y(e){var t=e.objCDBuilder,a=e.selectedState,i=e.salesTaxNotPaid;r({objCDBuilder:t,salesTaxNotPaid:i});n({objCDBuilder:t,selectedState:a})}function I(e){var t=e.arrAllIdNames,a=e.arrSelectedIds||[],i=t.filter(function(t){var e=true;if(t.isInactive){e=a.find(function(e){return""+t.id===""+e})}return e}).map(function(e){return{id:e.id,name:e.name+(e.isInactive?" (Inactive)":"")}});return i}function t(){var e=getObj("addOrUpdateExpenseReportDetailOrBusinessReason");if(e){var t=getObj("irsMileageRatesLink");if(t){var a=e.cboType?e.cboType[e.cboType.selectedIndex].text:"";if(a==="Mileage"){t.style.display=""}else{t.style.display="none"}}}}function x(){var e=getObj("addOrUpdateExpenseReportDetailOrBusinessReason"),t=getObj("txtSummary");if(!t){return}if(!e){t.innerHTML="";return}var a="",i="",o="",n="",r=[];if(e){var l=e[c],d=e.cboTrip,s=e.cboType;a=(l||{}).value||"";i=d?d[d.selectedIndex].text:"";o=s?s[s.selectedIndex].text:"";n=ClientDialogModule.getCompoundSelectionDisplayValueForBase({form:e,fieldNameBase:T});p()}if(o){r.push(htmlEncode(o))}if(n){r.push("("+htmlEncode(n)+")")}if(a){r.push(htmlEncode(a))}if(i!==""){r.push("for "+htmlEncode(i))}t.innerHTML=r.join(" ")}function v(e){var t=e.cdBuilder,a=e.selectedTripId,i=I({arrAllIdNames:g_arrTrips,arrSelectedIds:a?[a]:[]}),o=""+a,n=i.map(function(e){var t=""+e.id;return{cboValue:e.id,rawContent:e.name,isSelectedOption:t===o}}),r=ClientDialogModule.insertDropdownOption({arrOptions:n});t.addDropdown({fieldName:d,rawLabel:"Trip",onChangeJS:"JTCRMExpense.PROTECTED.formatSummary()",arrAvailableOptions:r})}function P(e){var t=e.cdBuilder,a=e.onChangeJS,i=I({arrAllIdNames:g_arrExpenseTypes,arrSelectedIds:e.selectedExpenseType?[e.selectedExpenseType]:[]}),o=e.selectedExpenseType,n=e.rawLabelOverride,r=e.mnemonicForLabelOverride,l=n||"Type",d=n?r:"t",s=""+o,u=i.map(function(e){var t=""+e.id;return{cboValue:e.id,rawContent:e.name,isSelectedOption:t===s}}),c=ClientDialogModule.insertDropdownOption({arrOptions:u});t.addDropdown({fieldName:S,rawLabel:l,mnemonicChar:d,onChangeJS:a,arrAvailableOptions:c})}function R(e){var t=e.form,a=e.resultValueHolder,i=ClientDialogModule.getCompoundSelectionValueForBase({form:t,fieldNameBase:T}),o=!!i;a.participantIds=i;if(!o){ClientDialogModule.showErrorMessageAndFocus({formTitle:"Missing Field",messageText:'At least one "Participant" is required',subdialogDismisalFocusFieldName:"participantSelect"})}return o}function E(e){var t=e.form,a=e.resultValueHolder,i=t[c].value,o=i.length,n=t[d],r=n[n.selectedIndex].value,l=1;a.tripId=r;a.reason=i;if(!(r||i)){ClientDialogModule.showErrorMessageAndFocus({formTitle:"Missing Field",messageText:'A value for "Trip" or "Additional Information" must be supplied',subdialogDismisalFocusFieldName:c});l=0}else if(o>m){ClientDialogModule.showErrorMessageAndFocus({formTitle:"Invalid Additional Info",messageText:'"Additional Information" can be at most '+m+" characters\n"+"\n"+"(Currently @ "+o+" characters)",subdialogDismisalFocusFieldName:c});l=0}return l}function g(e){var t=e.form,a=e.resultValueHolder,i=parseInt(t.isCredit.value,10),o=t.amount.value,n=parseFloat(o),r=parseFloat(t.amountLeft.value),l=t.originalSelectedAmount.value,d=parseFloat(l),s,u=1;a.floatAmount=n;if(isNaN(n)||n<=0){s='"Amount" must be a valid numeric value that is greater than zero'}else{if(!isNaN(d)&&d>0){if(i){r-=d}else{r+=d}}if(i){if(n>Math.abs(r)){s='"Amount" must be less than the remaining expense amount of $'+Math.abs(r)}}else{if(n>r){s='"Amount" must be less than the remaining expense amount of $'+r}}}if(s){u=0;ClientDialogModule.showErrorMessageAndFocus({formTitle:"Invalid Amount Value",messageText:s,subdialogDismisalFocusFieldName:"amount"})}return u}function A(e){var t=e.form,a=e.resultValueHolder,i=t[s],o=i[i.selectedIndex].value,n=t[l].checked,r=1;a.salesTaxNotPaid=n;a.stateId=o;if(n&&o===""){ClientDialogModule.showErrorMessageAndFocus({formTitle:"Missing Field",messageText:"A state must be selected if use tax needs to be paid",subdialogDismisalFocusFieldName:s});r=0}return r}function F(){var e=getObj(w),t=e.expenseId.value,a=e.expenseDetailId.value,i=e[S],o=i[i.selectedIndex].value,n=getObj("txtSummary"),r=a?"Updating Business Reason...":"Adding Business Reason...",l=new FormValidator,d={},s=g({form:e,resultValueHolder:d})&&l.CSValidateRequiredFieldP({field:i,rawMessage:'A value for "Type" must be supplied'})&&E({form:e,resultValueHolder:d})&&R({form:e,resultValueHolder:d})&&A({form:e,resultValueHolder:d}),u=d.floatAmount,c=d.tripId,m=d.reason,p=d.participantIds,f=d.salesTaxNotPaid,b=d.stateId;if(!s){return}jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_AddOrUpdateExpenseDetail",[t,a,escape(m),escape(c),escape(o),escape(p),f?1:0,u,escape(n.innerText),f?b:""],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(r+"...");disableDialogButtons()}function N(e){var t=e.cdBuilder,a=e.reason;t.addTextFieldRow(c,{rawLabel:"Additional Information",maxLength:m,mnemonicChar:"i",onChangeCode:"JTCRMExpense.PROTECTED.formatSummary()",fieldValue:a})}function a(e){var t=e.expenseId,a=e.expenseDetailId,i=e.amountLeft,o=e.selectedAmount,n=e.selectedType,r=e.selectedTripId,l=e.arrSelectedUserIds,d=e.reason,s=e.salesTaxNotPaid,u=e.amexVendor,c=e.isCredit,m=e.useTaxState,p=e.originalSummary,f=I({arrAllIdNames:g_arrUsers,arrSelectedIds:l}),b=w,g,C=[cdBuildFAFontIconButton({additionalButtonClasses:"textDialogButton",htmlContent:"Add Trip",fontId:FontIconId_Enum.fiiPlusInCircle,doubleQuoteEncodedTitle:"Add Trip",doubleQuoteEncodedOnClickJS:"hideDialog(0, 0, 0, function() { window.location=pageExpenseTrips; });"})];if(a){C.push(DialogHeaderDeleteButton.buildDialogHeaderDeleteButton({remoteScriptingFunctionName:"Admin2_DeleteBusinessReason2",deletePayload:{businessReasonId:e.expenseDetailId},rawButtonTitle:"Delete Business Reason",rawConfirmationMessageText:'Are you sure you want to delete the Business Reason,\n"'+p+'"?',displayNameOfObjectToDelete:"Business Reason",additionalButtonClasses:"textDialogButton"}))}g=new ClientDialogBuilder({formId:b,formTitle:a?"Edit Business Reason":"Add Business Reason",focusFieldName:"amount",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:a?"Save":"Add",mnemonicChar:a?"s":"a",mnemonicActionJS:"JTCRMExpense.PROTECTED.submitAddOrUpdateBusinessReason()"}),fnSubmit:F,arrExtraHeaderButtons:C});g.addFlexibleFieldRow({rawLabel:"Amex Vendor",rawValue:u});g.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''+''+''+''+''});var D=Math.abs(o||i),h=(D||"").toString();g.addTextFieldRow("amount",{rawLabel:"Amount",mnemonicChar:"u",isNumber:1,fieldValue:h});P({cdBuilder:g,onChangeJS:"JTCRMExpense.PROTECTED.formatSummary()",selectedExpenseType:n});g.addCompoundSelectionFieldRowP({fieldNameBase:T,onChangeCode:"JTCRMExpense.PROTECTED.formatSummary()",whatSingular:"Participant",arrSelectedIds:l,arrObjects:f,fnRSCallSubstitute:function(){return{arrUsers:f}},objectArrayName:"arrUsers",simpleIdPropertyName:"id",simpleNameDisplayPropertyName:"name"});N({cdBuilder:g,reason:d});v({cdBuilder:g,selectedTripId:r});y({objCDBuilder:g,salesTaxNotPaid:s,selectedState:m});g.addSectionHeaderRow({rawTitle:"Summary"});g.addFlexibleRow({valueHTML:''});if(g.showClientDialog()){setTimeout(function(){x()},0)}}function f(e){e=e||{};var t=e.isForExpenseReport,a=t?"
Payment method
":"",i="
A valid receipt should include:
"+'
'+"
Date of the transaction
"+"
Name of the vendor, with contact information
"+"
Itemized list of items purchased
"+"
Cost of each item
"+"
Total amount
"+"
Sales tax amount
"+a+"
";return i}function b(e){var t=e.cdBuilder,a=e.fileId,i=e.fileAltText,o=e.fileIcon,n=e.fileName,r=e.expenseReportDetailId,l=pageDownloadAttachedFile+"&inline=1&fileId="+a,d=cdBuildFontIconElem({fontId:o}),s="'+" "+d+"",u={fileId:a,fileName:n,expenseReportDetailId:r},c=ClientDialogModule.encodeFunction({functionName:"confirmDeleteExpenseReportDetailReceiptImage",functionParams:u});t.addFlexibleFieldRow({labelHTML:"Receipt",rowId:"removeReceiptRow",hideRow:a?0:1,valueHTML:''+''+s+''+n+""+cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Receipt Image",doubleQuoteEncodedOnClickJS:c})})}function O(e){var t,a=1;if(isNaN(e)){t='"Amount" must be a valid numeric value'}else if(e===0){t='"Amount" cannot be zero'}if(t){ClientDialogModule.showErrorMessageAndFocus({formTitle:"Invalid Amount Value",messageText:t,subdialogDismisalFocusFieldName:"amount"});a=0}return a}function i(){JTCRMExpense.PROTECTED.submitAddOrUpdateExpenseReportDetailP({ignoreReceiptCheck:true})}function M(){var e=getObj("receiptFileId").value,t=1;if(""===e&&g_arrFileDragDropFileInfos.length===0){t=0;ClientDialogModule.showDialogWithConsequence({formTitle:"Confirm Save Without Receipt",fnConstructDialog:function(e){var t=e.cdBuilder;t.addBubbleMessageRow({rawMessage:"You are saving an Expense Report Detail without a receipt.\n"+"\n"+"Are you sure you want to continue?"})},fnSubmit:function(){i()},okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"JTCRMExpense.PROTECTED.submitAddOrUpdateExpenseReportDetailWithoutReceiptCheck()"})})}return t}function C(e){e=e||{};var t=e.ignoreReceiptCheck,i=getObj("addOrUpdateExpenseReportDetailOrBusinessReason"),a=i.expenseId.value,o=i.expenseDetailId.value,n=i[S],r=n[n.selectedIndex].value,l=i.amount.value,d=parseFloat(l),s=getObj("txtSummary"),u=i.Date,c=new FormValidator,m=o?"Updating Expense Report Detail...":"Adding Expense Report Detail...",p={},f=c.CSValidateDateFieldP({field:u,label:"Expense Date",isNullable:false})&&O(d)&&c.CSValidateRequiredFieldP({field:n,rawMessage:'A value for "Type" must be supplied'})&&E({form:i,resultValueHolder:p})&&R({form:i,resultValueHolder:p})&&A({form:i,resultValueHolder:p})&&(t||M()),b=p.tripId,g=p.reason,C=p.participantIds,D=p.salesTaxNotPaid,h=p.stateId;if(f){jsrsExecute(function(e){var t=JSON.parse(e).expenseReportDetailId;if(t+""!==o&&g_arrFileDragDropFileInfos.length>0){i.objectId.value=t}if(g_arrFileDragDropFileInfos.length){var a=getObj("addOrUpdateExpenseReportDetailOrBusinessReason");doUploadFiles(a)}else{hideDialog();rsCallbackRefreshPageAndScrollPos()}},"Admin_AddOrUpdateExpenseReportDetail",[a,o,escape(g),escape(b),escape(r),escape(C),D?1:0,d,escape(s.innerText),D?h:"",u.value],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(m+"...");disableDialogButtons()}}function D(){C()}function L(e){var t=e.selectedType,a=e.amount,i=e.salesTaxNotPaid,o=e.state,n=e.selectedCategory,r=e.selectedUsers,l=I({arrAllIdNames:g_arrUsers,arrSelectedIds:r}),d=f({isForExpenseReport:1}),s=(a||"").toString(),u="addOrUpdateExpenseReportDetailOrBusinessReason",c,m=[cdBuildFAFontIconButton({additionalButtonClasses:"textDialogButton",htmlContent:"Add Trip",fontId:FontIconId_Enum.fiiPlusInCircle,doubleQuoteEncodedTitle:"Add Trip",doubleQuoteEncodedOnClickJS:"hideDialog(0, 0, 0, function() { window.location=pageExpenseTrips; });"})];if(e.expenseReportDetailId){m.push(cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,additionalButtonClasses:"textDialogButton",doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseReportDetail("+e.expenseReportDetailId+")"}))}c=new ClientDialogBuilder({formId:u,formAction:pageUploadAttachedFile,formTitle:e.expenseReportDetailId?"Edit Expense Report Detail":"Add Expense Report Detail",focusFieldName:"Date",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:e.expenseReportDetailId?"Save":"Add",mnemonicChar:e.expenseReportDetailId?"s":"a",mnemonicActionJS:"JTCRMExpense.PROTECTED.submitAddOrUpdateExpenseReportDetail()"}),fnSubmit:D,fnCancelOrClose:function(){var e=0;if(getObj("receiptRemoved").value==="1"){e=1}hideDialogP({callback:function(){if(e){refreshPageAndScrollPos()}}})},arrExtraHeaderButtons:m});c.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''+''+''});c.addDatePickerRow(c.getFormId(),"Date",{rawLabel:"Expense Date",strValue:e.date});c.addFlexibleFieldRow({rawLabel:"Amount",valueHTML:' IRS Mileage rates'});P({cdBuilder:c,onChangeJS:"JTCRMExpense.PROTECTED.formatSummary();JTCRMExpense.PROTECTED.updateIRSMilageLink();",selectedExpenseType:t});c.addCompoundSelectionFieldRowP({fieldNameBase:T,onChangeCode:"JTCRMExpense.PROTECTED.formatSummary()",whatSingular:"Participant",arrSelectedIds:r,arrObjects:l,fnRSCallSubstitute:function(){return{arrUsers:l}},objectArrayName:"arrUsers",simpleIdPropertyName:"id",simpleNameDisplayPropertyName:"name"});N({cdBuilder:c,reason:e.reason});v({cdBuilder:c,selectedTripId:n});y({objCDBuilder:c,salesTaxNotPaid:i,selectedState:o});b({cdBuilder:c,fileId:e.fileId,fileAltText:e.fileAltText,fileIcon:e.fileIcon,fileName:e.fileName,expenseReportDetailId:e.expenseReportDetailId});c.addFileUploadRow({fileLimit:1,fileType:15,objectId:e.expenseReportDetailId?e.expenseReportDetailId:-1,customLabel:"Receipt",rowId:"addReceiptRow",customAlign:"middleAlign",hideRow:e.fileId?1:0,acceptContentTypeHint:"image/*, .pdf"});c.addFlexibleFieldRow({valueHTML:d});c.addSectionHeaderRow({rawTitle:"Summary"});c.addFlexibleRow({valueHTML:''});c.showClientDialog();setTimeout(function(){x()},0)}function U(){var e=g_arrFileDragDropFileInfos.length===1;if(!e){ClientDialogModule.showErrorMessageAndFocus({formTitle:"Missing CSV",messageText:"An Amex CSV File is required",subdialogDismisalFocusFieldName:"fileName"})}return e}function h(e){var t=e.file,a=e.fileSaved,i=e.importSucceeded,o=e.errorMessage,n=e.totalNumberOfExpensesAdded||0,r=e.totalNumberOfExpensesInFile||0,l=e.totalNumberOfExpensesBlocked||0,d=e.totalNumberOfExpensesAlreadyInDB||0,s=e.totalNumberOfExpensesWithErrors||0;hideTimedMessage();hideDialogP({callback:function(){var e=new ClientDialogBuilder({formId:u,formAction:pageUploadAttachedFile,formTitle:"AMEX CSV File Import Results",fnCancelOrClose:function(){hideDialog();refreshPageShowingMessage()}});e.addFlexibleFieldRow({labelHTML:"File",rawValue:t.name+" ("+formatFileSize(t.size)+")",additionalCellClasses:"clsVeryNarrowField"});e.addFlexibleFieldRow({labelHTML:"File Saved",rawValue:a?"Yes":"No"});e.addFlexibleFieldRow({labelHTML:"Total Number Of Expenses In File",rawValue:r.toString()});e.addFlexibleFieldRow({labelHTML:"Total Number Of Blocked Expenses",rawValue:l.toString()});e.addFlexibleFieldRow({labelHTML:"Total Number Of Expenses Already In DB",rawValue:d.toString()});e.addFlexibleFieldRow({labelHTML:"Total Number Of Expenses Added",rawValue:n.toString()});e.addFlexibleFieldRow({labelHTML:"Total Number Of Expenses With Errors",rawValue:s.toString()});if(!i){e.addFlexibleRow({valueHTML:'
'+htmlMultilineEncode(o)+"
"})}e.showClientDialog()}})}function B(e,t){var a=t.responseText,i=JSON.parse(a),o=i.arrFileDetails||[],n=o[0]||{},r=n.additionalOperations,l=r.success,d=r.errorMessage,s=r.totalNumberOfExpensesAdded||0,u=r.totalNumberOfExpensesInFile||0,c=r.totalNumberOfExpensesAlreadyInDB||0,m=r.totalNumberOfExpensesWithErrors||0,p=r.totalNumberOfExpensesBlocked||0;h({file:e,fileSaved:1,importSucceeded:l,errorMessage:d,totalNumberOfExpensesAdded:s,totalNumberOfExpensesInFile:u,totalNumberOfExpensesAlreadyInDB:c,totalNumberOfExpensesWithErrors:m,totalNumberOfExpensesBlocked:p})}function V(e,t,a){h({file:e,fileSaved:0,importSucceeded:0,errorMessage:a,totalNumberOfExpensesAdded:0,totalNumberOfExpensesInFile:0,totalNumberOfExpensesAlreadyInDB:0,totalNumberOfExpensesWithErrors:0,totalNumberOfExpensesBlocked:0})}function k(){var e=getObj(u),t=U();if(t){uploadFile(g_arrFileDragDropFileInfos[0],null,e,B,V)}}function H(){var e=new ClientDialogBuilder({formId:u,formAction:pageUploadAttachedFile,formTitle:"Upload AMEX CSV File",focusFieldName:"Date",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Upload",mnemonicChar:"u",mnemonicActionJS:"JTCRMExpense.PROTECTED.submitUploadAmexCSVDialog()"}),fnSubmit:k});e.addFlexibleRow({valueHTML:"Upload a CSV file containing AMEX expense transactions"});e.addFlexibleRow({valueHTML:"CSV file can be obtained from www.americanexpress.com"});e.addFlexibleRow({valueHTML:"
"+"
Navigate to Statements & Activity
"+"
Choose the time period (default of Last 30 Days is fine)
"+"
Click the Download button
"+"
Choose CSV file type
"+'
Check the "Include all additional transaction details" checkbox
'+"
Download
"+"
"});e.addFileUploadRow({fileLimit:1,fileType:16,rowId:"amexCSVRow",customAlign:"middleAlign",acceptContentTypeHint:".csv",acceptedDragDropFileTypes:"csv",invalidDragDropMimeTypeMessage:"Please select a file with a .csv file extension"});e.showClientDialog()}return{addOrUpdateBusinessReason:a,addOrUpdateExpenseReportDetail:L,addExpenseTypeDropdown:P,showUploadAmexCSVDialog:H,buildReceiptCaveatHtml:f,PROTECTED:{submitAddOrUpdateBusinessReason:F,toggleUseTaxStateCB:e,formatSummary:x,updateIRSMilageLink:t,submitAddOrUpdateExpenseReportDetail:D,submitAddOrUpdateExpenseReportDetailP:C,submitAddOrUpdateExpenseReportDetailWithoutReceiptCheck:i,submitUploadAmexCSVDialog:k}}}();function convertJobInfoToUpdateJobAndDBInfo(e){return{databaseId:e.databaseId,updateDeploymentServer:e.deploymentServerDiffers,updateBillingLink:e.billingLinkDiffers,updateServerDatabaseLink:e.serverDatabaseLinkDiffers,updateCGUserCount:e.cgUserCountDiffers,updateNVUserCount:e.nvUserCountDiffers,updateSysUserCount:e.sysUserCountDiffers,updateDatabaseAddress:e.addressesDiffer,requiresUpdateDueToEdition:e.requiresUpdateDueToEdition,actualCGUserCount:e.actualCGUserCount,actualNVUserCount:e.actualNVUserCount,actualSysUserCount:e.actualSysUserCount,actualEditionId:e.actualEditionId,jtListedJobAddress:e.CRMAddressDisplayString,jtAddress:e.addressesDiffer?e.jtAddress:0,updateCGActivityStatus:e.counterGoActivity.activityStatesDiffer,updateNVActivityStatus:e.nvInventoryActivity.activityStatesDiffer,updateSysActivityStatus:e.systemizeActivity.activityStatesDiffer,actualCGActivityStatusText:e.counterGoActivity.actualActivityStatusText,actualNVActivityStatusText:e.nvInventoryActivity.actualActivityStatusText,actualSysActivityStatusText:e.systemizeActivity.actualActivityStatusText}}var JTCRMDatabase=function(){var c="frmDatabasesOptions",u="frmAssignDBToCustomer",m="cboCustomer",v="Subdomain Name",o=63,e="a-zA-Z0-9\\-",p="[^"+e+"]+",t="a-zA-Z0-9",f="^["+t+"]"+".*"+"["+t+"]$",w="frmEditDatabase";function b(e){var t,a={},i,o,n=[];for(t=0;t'+a+""}return a}).join(""),d=r.length===1?"character":"characters",s="",u;if(o.length){s="Invalid "+d+" "+'"'+l+'"'+" in "+v+"."}else{var c=new RegExp(f,"g"),m=!c.test(a);if(m){s=v+" must start and end with an alpha-numeric character (a-z or 0-9)."}}if(s){ClientDialogModule.showDialogWithConsequence({formTitle:"Invalid "+v,simpleRowContentHtml:'
'+s+"
",subdialogDismisalFocusFieldName:t.name,subdialogDismisalFocusFieldId:t.id})}else{u=1}return u}function g(e){var t=e.subdomainNameField,a=new FormValidator,i=a.ValidateTextField({textFieldElem:t,isRequiredField:1,maxTextLength:o,fieldDisplayName:v})&&n({subdomainNameField:t});return i}function l(){var e=getObj(c),t=new FormValidator,a=pageDatabases,i=e.txtPageSize,o="databaseListsort",n=getUrlParamValueIfThere(""+window.location,o),r={},l={},d=SummaryOptionsFilter.validateFilterDefinitionUrlParamValueFromForm({formId:e.id,resultValueHolder:l}),s=d&&t.CSValidateNumberFieldP({field:i,label:"Page Size",isNullable:1,maxDecimalPlaces:0,maxValue:2e3,resultValueHolder:r}),u=l.filterUrlParam;if(!s){return}if(n){a+="&"+o+"="+n}if(u){a+="&"+SummaryOptionsFilter.combineUrlComponentsIntoFilterParam({fullyComposedUrlComponents:u})}if(r.rc){a+="&pagesize="+r.rc}hideDialog();window.location=a;displayTimedMessage("Reloading page...")}function a(e){var t=e.pageSize,a=c,i=new ClientDialogBuilder({formId:a,formTitle:"Databases Options",fnSubmit:l,focusFieldName:SummaryOptionsFilter.BUTTON_ID_ADD_FILTER,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"JTCRMDatabase.PROTECTED.submitDatabasesOptions()"})}),o,n={},r={formElemData:n};JTCRMUtils.wireUpClientFilterRSCalls();SummaryOptionsFilter.addFilterContainerRow({cdBuilder:i,formElemData:n,filterWhat:"Slabs"});i.addDialogInteriorRows([buildPageSizeRow(t)]);o=i.showClientDialog(r);if(o){SummaryOptionsFilter.initializeDisplayedFilters({targetFormId:a})}}function P(e){var a=e.validationResults,i=htmlMultilineEncode(e.displayAddress||"");ClientDialogModule.showDialogWithConsequence({formTitle:"The Hubspot address is invalid",fnConstructDialog:function(e){var t=e.cdBuilder;t.addFlexibleFieldRow({rawLabel:"Address",valueHTML:i,additionalCellClasses:"clsNarrowField"});t.addFlexibleFieldRow({rawLabel:"Issue",rawValue:a.description,additionalCellClasses:"clsNarrowField"});t.addFlexibleFieldRow({rawLabel:"Details",valueHTML:a.detailHtml});t.addFlexibleFieldRow({rawLabel:a.tableLabel,valueHTML:a.tableHtml})}})}function C(e){hideDialog();window.location=pageDatabaseDetail+e.id}function R(){var e="frmNewDB",t=getObj(e),a=new FormValidator,i=t.txtCustomerName,o=t.txtCustomerId,n=o?o.value:"",r=t.txtSubdomainName,l=t.taxRateIdSelect,d=t.taxRateId,s=mjtElemData(t,"address"),u=d?d.value:l?l.value:"",c=t.cboSystemize.value,m=t.cboCounterGo.value==="1",p=t.cboNVInventory.value==="1",f=t.txtJobId?trim(t.txtJobId.value):"",b=t.txtHubspotCompanyId?trim(t.txtHubspotCompanyId.value):"";if(i&&!a.CSValidateRequiredField(i,"Please enter a Customer Name")){return}if(!g({subdomainNameField:r})){return}if(l&&!u){showInfoDialog("Please select a tax rate.","Select Tax Rate",1,"taxRateIdSelect");return}if(u==="0"){u=""}jsrsExecuteWithErrorP("Admin2_CreateCustomerAndDatabase",rsCallbackHandleStandardJSONResponse,"Creating Database",{customerId:n,customerName:trim(i?i.value:""),subdomain:trim(r.value),address:s,jobId:f,hubspotCompanyId:b,taxRateId:u,includeCGProduct:m?1:0,includeNVProduct:p?1:0,sysEditionId:c},{fnOnSuccess:C})}function r(e){var t="frmNewDB",a=e.hubspotInfo||[],i=a.displayAddress,o=a.address,n=a.customerId,r=a.customerName,l=a.newDBTaxOptions,d=a.hubspotCompanyId,s=a.email,u=a.validationResults||"[]",c=JSON.parse(u),m,p,f=l.taxWarningMessage,b=l.webLinkToDetermineTaxRate,g=l.availableTaxRates,C=g?g.length:0,D=l.singleMatchedTaxCode,h=D?D.nameMatchingTaxCodeId:0,w="",T;if(!c.isValid){P({validationResults:c,displayAddress:i});return}var S=new ClientDialogBuilder({formId:t,formTitle:"New Database",focusFieldName:n?"txtSubdomainName":"txtCustomerName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"JTCRMDatabase.PROTECTED.submitNewDatabase()"}),fnSubmit:R});S.addFlexibleFieldRow({rawLabel:"Hubspot Company Id",valueHTML:d+''});S.addFlexibleFieldRow({rawLabel:"Address",valueHTML:htmlMultilineEncode(i||"")});S.addFlexibleFieldRow({rawLabel:"Email",rawValue:s});if(n){S.addFlexibleFieldRow({rawLabel:"Customer Name",valueHTML:htmlEncode(r)+''})}else{S.addTextFieldRow("txtCustomerName",{rawLabel:"Customer Name",fieldValue:r})}S.addTextFieldRow("txtSubdomainName",{rawLabel:v,fieldValue:m,strPreFieldHTML:"https://",strPostFieldHTML:".moraware.net"});if(f){S.addFlexibleFieldRow({rawLabel:"",valueHTML:htmlMultilineEncode(f),additionalValueCellClasses:"errorText"})}if(C>1){w+='";if(D){if(h){w+='
'+'On lookup, found matching tax code "'+htmlEncode(D.taxCodeName)+'" '+"with Rate="+D.taxRatePercent+"%"+"
"}}}else if(C>0){w=htmlEncode(g[0].name)+''}else{w='(No Tax Required)'}S.addFlexibleFieldRow({rawLabel:"Tax Rate",valueHTML:w});if(b){S.addFlexibleFieldRow({valueHTML:'Tax Rate Lookup'})}S.addSectionHeaderRow({rawTitle:"Order Products"});S.addFlexibleFieldRow({rawLabel:"CounterGo",valueHTML:'"});S.addFlexibleFieldRow({rawLabel:"Inventory",valueHTML:'"});S.addFlexibleFieldRow({rawLabel:"Systemize",valueHTML:'"});p=S.showClientDialog();if(p){mjtElemData(p,"address",o)}}function d(){var e="frmNewDBFromHubspot",t=getObj(e),a=t.txtCustomerId,i=t.txtHubspotCompanyId,o=!i.value;if(o){return false}jsrsExecuteWithErrorP("Admin2_GetHubspotCompanyInfo",r,"Getting Hubspot Info",{hubspotCompanyId:trim(i.value),customerId:a?a.value:"",createMissingTaxCodeIfPossible:1})}function i(e,t){var a="frmNewDBFromHubspot",i=new ClientDialogBuilder({formId:a,formTitle:"New Database (Hubspot)",focusFieldName:"txtHubspotCompanyId",okButtonDisplayText:"Get Hubspot Company Info",fnSubmit:d});if(t&&e){i.addFlexibleFieldRow({rawLabel:"Customer",valueHTML:htmlEncode(t)+''})}i.addTextFieldRow("txtHubspotCompanyId",{rawLabel:"Hubspot Company Id",additionalLabelCellClasses:"clsNarrowField"});i.showClientDialog()}function D(){var e=getObj(u),t=mjtElemData(e,"databaseId"),a=e[m],i=a.options[a.selectedIndex].value;hideDialog();jsrsExecuteWithErrorP("Admin2_AssignDatabaseToCustomer2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Assigning Database to Customer",{databaseId:t,customerId:i})}function s(e,t){var a=e.arrCustomers,i=t.originalOptions,o=i.databaseId,n=i.customerId;if(!a.length){showInfoDialog("There are no customers defined","No Customers");return}var r={databaseId:o},l={formElemData:r},d=a.map(function(e){return{rawContent:e.name,cboValue:e.id,isSelectedOption:e.id===n}}),s=new ClientDialogBuilder({formId:u,formTitle:"Assign Database To Customer",focusFieldName:m,focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"JTCRMDatabase.PROTECTED.submitAssignDBToCustomer()"}),fnSubmit:D});s.addDropdown({fieldName:m,rawLabel:"Customer",mnemonicChar:"c",arrAvailableOptions:d,additionalCellClasses:"clsVeryNarrowField"});s.showClientDialog(l)}function h(e,t){jsrsExecuteWithErrorP("Admin2_GetCustomerNames2",rsCallbackHandleStandardJSONResponse,"Retrieving list of customers",{},{fnOnSuccess:s,databaseId:e,customerId:t})}function T(){var e=getObj(w),t=mjtElemData(e,"databaseId"),a=mjtElemData(e,"customerId");hideDialogP({callback:function(){h(t,a||null)}})}var S="frmLookupTaxRate",y="frmAddress";function I(){var e=getObj(S),t=mjtElemData(e,"databaseId"),a=mjtElemData(e,"matchingTaxCodeId");jsrsExecuteWithErrorP("Admin2_UpdateDBTaxInfo",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Tax Info",{databaseId:t,taxRateId:a})}function x(e){var t=e.street||"",a=trim(e.city||""),i=trim(e.state||""),o=trim(e.zip||""),n=trim(e.country||""),r=a&&i?a+", "+i:a+i,l=trim(r+" "+o);return t+"\n"+(l&&n?l+"\n"+n:l+n)}function E(e){hideDialog();var t,a=e.currentAddress||{},i=e.newDBTaxOptions,o=e.arrAPIMultiMatchMinInfos,n=o?o.length:0,r=e.currentTaxOptions,l=r?r.taxRateId||0:0,d=r?r.taxRatePercent:undefined,s=i.singleMatchedTaxCode,u=s?s.nameMatchingTaxCodeId:0,c=s&&s.taxRatePercent!==d,m=u&&u!==l,p=i.taxWarningMessage,f=new ClientDialogBuilder({formId:S,formTitle:"Lookup Tax Rate",focusFieldName:"txtStreet",arrExtraHeaderButtons:[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiEdit,doubleQuoteEncodedOnClickJS:"JTCRMDatabase.PROTECTED.promptToUpdateTaxLookupAddress()",doubleQuoteEncodedTitle:"Change Lookup Address"})],okButtonDisplayText:m?cdBuildMnemonicLabelHTML({rawLabel:"Update Tax Rate",mnemonicChar:"u",mnemonicActionJS:"JTCRMDatabase.PROTECTED.submitUpdateDBTaxRate()"}):null,fnSubmit:m?I:null});f.addFlexibleFieldRow({rawLabel:"Lookup Address",valueHTML:htmlMultilineEncode(x(a)),valueCellId:"cellLookupAddress",additionalCellClasses:"topAlign"});f.addSectionHeaderRow({rawTitle:"Tax Info"});if(r){var b='-None-';if(r.taxRateId){b=htmlEncode(r.taxRateName)+" ("+r.taxRatePercent+"%)"}f.addFlexibleFieldRow({rawLabel:"Current Tax Rate",valueHTML:b})}if(p){f.addFlexibleFieldRow({rawLabel:"",valueHTML:htmlMultilineEncode(p),additionalValueCellClasses:"errorText"})}if(n){f.addFlexibleFieldRow({rawLabel:"Multiple Matches",valueHTML:htmlEncode(JSON.stringify(o,null,2)),additionalValueCellClasses:"JSONViewer errorText",additionalCellClasses:"topAlign"})}if(u){var g=m?cdBuildFontIconElem({fontId:FontIconId_Enum.fiiExclamationInFilledTriangle,terseFontIcon:1,additionalFontIconClasses:"warningIcon"}):cdBuildFontIconElem({fontId:FontIconId_Enum.fiiCheck,terseFontIcon:1,additionalFontIconClasses:"goodNewsIcon"}),C=c?cdBuildFontIconElem({fontId:FontIconId_Enum.fiiExclamationInFilledTriangle,terseFontIcon:1,additionalFontIconClasses:"warningIcon paddingRightXSmall"}):"",D=m?'
(The tax rate will be updated)
':c?'
(The Tax Code matches, but the Rate differs!)
':'
(There is no need to update the Tax Rate)
',h=htmlEncode(s.taxCodeName)+" ("+C+s.taxRatePercent+"%"+")";if(m){h=''+h+""}f.addFlexibleFieldRow({rawLabel:"New Tax Rate",valueHTML:g+" "+h+D,additionalCellClasses:"topAlign"})}t=f.showClientDialog();if(t){mjtElemData(t,"databaseId",e.databaseId);mjtElemData(t,"matchingTaxCodeId",u);mjtElemData(t,"lookupAddress",a)}}function A(){var e=getObj(y),t=getObj(S),a=mjtElemData(t,"databaseId");jsrsExecuteWithErrorP("Admin2_GetDBTaxInfo",rsCallbackHandleStandardJSONResponse,"Looking up Tax Info",{databaseId:a,overrideAddress:1,street:trim(e.txtStreet.value),city:trim(e.txtCity.value),zip:trim(e.txtZip.value),state:trim(e.txtState.value),country:trim(e.txtCountry.value)},{fnOnSuccess:E})}function F(){var e=getObj(S),t=mjtElemData(e,"lookupAddress"),a=new ClientDialogBuilder({formId:y,formTitle:"Update Lookup Address",focusFieldName:"txtStreet",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Lookup Address",mnemonicChar:"l",mnemonicActionJS:"JTCRMDatabase.PROTECTED.submitUpdateTaxLookupAddress()"}),fnSubmit:A});a.addTextFieldRow("txtStreet",{rawLabel:"Street",fieldValue:t.street||""});a.addTextFieldRow("txtCity",{rawLabel:"City",fieldValue:t.city||""});a.addTextFieldRow("txtState",{rawLabel:"State",fieldValue:t.state||""});a.addTextFieldRow("txtZip",{rawLabel:"Zip",fieldValue:t.zip||""});a.addTextFieldRow("txtCountry",{rawLabel:"Country",fieldValue:t.country||""});a.showClientDialog()}function N(e){var t=e.options[e.selectedIndex].value,a=t?JSON.parse(t):0;return a}function O(){var e=getObj(w),t=new FormValidator,a=N(e.cboTaxRate),i=mjtElemData(e,"databaseId"),o=cdGetExpandingTextFieldValue("txtNotes"),n=a?a.id:"",r=e.txtDiscountPct,l=e.txtJobId,d=e.txtHubspotCompanyId,s=d?trim(d.value):null,u=g({subdomainNameField:e.txtSubdomain}),c=u&&t.CSValidateIntegerFieldP({field:l,label:"Job Id",isNullable:false,minValue:1,suppressErrorMessage:true});if(!u){return}if(!c&&!s){showErrorMessageAndFocus("Job Id and Hubspot Company Id cannot both be empty","Error saving database",l,{subdialog:1});return false}if(r&&!t.CSValidateNumberField(r,"Discount %",true)){return}var m={databaseId:i,subdomain:trim(e.txtSubdomain.value),jobId:trim(l.value),hubspotCompanyId:s,notes:o,discountPercent:r?trim(r.value):"",taxRateId:n,suppressAutoAddBillingUsers:e.chkSuppressAutoAdd.checked?1:0};jsrsExecuteWithErrorP("Admin2_UpdateDatabase",refreshPageAndScrollPos,"Updating Database",m)}function M(e){var t=e.cdBuilder,a=e.arrTaxRates,i=e.selectedTaxRateId,o=e.taxRateState,n=e.state,r="",l,d,s;if(a.length===0||i===0||o!==n){r+=''}for(l=0;l"+htmlEncode(s.name)+" ("+s.percent+"%)"+""}t.addFlexibleFieldRow({rawLabel:"Tax Rate",mnemonicChar:"t",mnemonicFocusFieldName:"cboTaxRate",valueHTML:'"})}function k(e){jsrsExecuteWithErrorP("Admin2_GetDBTaxInfo",rsCallbackHandleStandardJSONResponse,"Looking up Tax Info",{databaseId:e.databaseId},{fnOnSuccess:E})}function L(e,t){var a=e.id,i=e.customerId,o=e.discountPct,n=e.taxRateId,r=e.arrTaxRates,l=e.addressState,d=e.taxRateState,s=e.subdomain,u=t.originalPayload.taxLookupAllowedForState,c=i?"txtSubdomain":"txtCustomerName",m=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),p=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARUpdate),f=m?DialogHeaderDeleteButton.buildDialogHeaderDeleteButton({remoteScriptingFunctionName:"Admin2_DeleteDatabase",deletePayload:{databaseId:a},rawButtonTitle:"Delete Database",rawConfirmationMessageText:'Are you sure you want to delete the Database, "'+s+'"?',displayNameOfObjectToDelete:"Database",urlOnSuccess:i?pageCustomerDetail+i:pageDatabases}):null,b=cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiMoveTo,doubleQuoteEncodedTitle:"Assign To Other Customer",doubleQuoteEncodedOnClickJS:"JTCRMDatabase.PROTECTED.promptAssignDBToCustomer()"}),g=p&&u?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiCheck,doubleQuoteEncodedTitle:"Lookup Tax Rate",doubleQuoteEncodedOnClickJS:"hideDialog();"+"JTCRMDatabase.PROTECTED.promptLookupTaxRate("+htmlEncode(JSON.stringify({databaseId:a}))+")",htmlContent:''+cdBuildMnemonicLabelHTML({rawLabel:"Tax",mnemonicChar:"x",mnemonicActionJS:"hideDialog();"+"JTCRMDatabase.PROTECTED.promptLookupTaxRate("+htmlEncode(JSON.stringify({databaseId:a}))+")"})+""}):null,C=[f,b,g],D=new ClientDialogBuilder({formId:w,formTitle:"Edit Database",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"JTCRMDatabase.PROTECTED.submitEditDatabase()"}),focusFieldName:c,focusFieldOnMobile:1,arrExtraHeaderButtons:C,fnSubmit:O}),h;if(!i){D.addTextFieldRow("txtCustomerName",{rawLabel:"Customer Name",autofocus:1})}D.addTextFieldRow("txtSubdomain",{rawLabel:v,mnemonicChar:"b",fieldValue:s});D.addTextFieldRow("txtJobId",{rawLabel:"Job Id",mnemonicChar:"j",fieldValue:(e.internalJobId?e.internalJobId:"")+"",maxLength:10,isNumber:1});D.addTextFieldRow("txtHubspotCompanyId",{rawLabel:"Hubspot Company Id",mnemonicChar:"h",fieldValue:(e.hubspotCompanyId?e.hubspotCompanyId:"")+""});M({cdBuilder:D,arrTaxRates:r,selectedTaxRateId:n,taxRateState:d,state:l});D.addTextFieldRow("txtDiscountPct",{rawLabel:"Discount %",mnemonicChar:"u",fieldValue:""+(o||""),maxLength:10});D.addCheckboxRow_deprecated("chkSuppressAutoAdd",{rawLabel:"Don't Automatically Add Additional Users To Billing",checked:e.suppressAutoAddBillingUsers});D.addExpandingTextFieldRows("txtNotes",{rawLabel:"Notes",mnemonicChar:"n",value:e.notes||""});h=D.showClientDialog();if(h){mjtElemData(h,"databaseId",a);mjtElemData(h,"customerId",i)}}function U(e){jsrsExecuteWithErrorP("Admin2_GetDatabaseInfo2",rsCallbackHandleStandardJSONResponse,"Getting Database Info for Edit",e,{fnOnSuccess:L})}return{showDatabasesOptionsDialog:a,showNewDatabaseFromHubspotDialog:i,showEditDatabaseDialog:U,PROTECTED:{submitDatabasesOptions:l,submitNewDatabase:R,submitEditDatabase:O,promptLookupTaxRate:k,promptAssignDBToCustomer:T,submitAssignDBToCustomer:D,submitUpdateDBTaxRate:I,submitUpdateTaxLookupAddress:A,promptToUpdateTaxLookupAddress:F}}}();