var g_notesEMWidth=40,g_notesRowCount=8,g_arrProductTerms;function submitReorderP(c){var e=c.arrReorderedIds,d=c.reorderCommandName,a=c.reorderIdsPropertyName||"arrIds",b=c.reorderParamsObject||{},f=c.reorderObjectName||"";if(!e){consoleLog('Missing "arrReorderedIds" submitting re-order dialog. Objects being re-ordered: '+JSON.stringify(f));return}if(!d){consoleLog('Missing "reorderCommandName" submitting re-order dialog. Objects being re-ordered: '+JSON.stringify(f));return}b[a]=e.join(",");jsrsExecuteWithErrorP(d,rsCallbackHandleStandardJSONResponseWithHideAndRefresh,trim("Re-ordering "+f),b)}function jtcrmHasAccess(a,b){if(null!==a){if(g_jtcrmIsAdmin){return true}}return checkSecurityProfileString(a,b,g_JTCRMAccessRights)}function getDateAsDisplayString(d){var c=d.getFullYear(),a=d.getMonth(),b=d.getDate(),e=(a+1)+"/"+b+"/"+c;return e}function rsCallbackHideDialog(a){if(checkResponseForError(a)){hideDialog();return true}return false}function buildQuantityComboboxRow(){return cdBuildReadOnlyFieldRowP({rawLabel:"Quantity",valueHTML:''})}function buildPageSizeRow(a){return cdBuildTextFieldRowP("txtPageSize","Rows per Page",{fieldValue:""+a,maxLength:10,styleWidth:"7em",isNumber:1})}function validateEmailAddress(a){var b=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;return b.test(a)}function rsCallbackGetAboutInfo(e,c,i){enableDialogButtons();if(checkResponseForError(e)){var f=JSON.parse(e),b=f.lastBackupDate,d=b?b:"",g=f.lastLogBackupDate,j=g?g:"",h=f.isTimeForFullBackup,a="";if(h){a+=''}a+="";showInfoDialog("
Time for a Full Backup!

Last Full Backup: "+d+"
Last Log Backup: "+j+"
"+a+"
","About JTCRM")}}function showPWValidationError(b,a){showInfoDialog(b,"Error Setting Password",1)}function submitChangePassword(a,c){var d=a.txtOldPW.value,b=a.txtNewPW,f=b.value,e=a.txtConfirmPW.value;if(f!==e){showInfoDialog("Passwords don't match!","Mismatched Passwords",1,"txtConfirmPW");return}if(!validateClientSidePasswordVals(a.txtUserName,b,showPWValidationError)){return}jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_ChangePassword",[escape(d),escape(f)],enableDialogButtons);displayTimedMessage("Updating Password...");disableDialogButtons()}function rsCallbackGetStatus(m,d,o){try{var b=getObj(o.strStatusSectionId),h=o.processKey,q=o.objAsynchUpdaterTimeoutHolder,a,l=o.strStatusSectionId,c=o.fnAsynchUpdate,g=JSON.parse(m),n=g?g.arrProgress:0,f,p,j="";if(b){if(n&&b&&c){j='\n\n';for(f=0;f\n'}j+='\n"}j+="
'+Math.round(100*p.status/p.max)+'%['+p.status+"/"+p.max+']:'+htmlMultilineEncode(p.description)+"
\n";a=setTimeout(function(){c(h,l,q)},100);if(q){q.asynchUpdaterTimeoutId=a}}else{j="There's no longer any status being reported, so it looks like we're done!";enableDialogButtons()}b.innerHTML=j}}catch(k){}}function asynchUpdateWithProcessStatus(c,b,a){jsrsExecute(rsCallbackGetStatus,"Admin_GetStatus",[escape(c)],enableDialogButtons,{processKey:c,strStatusSectionId:b,fnAsynchUpdate:asynchUpdateWithProcessStatus,objAsynchUpdaterTimeoutHolder:a})}function showChangePasswordDialog(){var b="frmChangePW",a=new ClientDialogBuilder({formId:b,formTitle:"Change Password",okButtonDisplayText:"Save",focusFieldName:"txtOldPW",focusFieldOnMobile:1,fnSubmit:submitChangePassword});a.addTextFieldRow("txtOldPW",{rawLabel:"Old Password",isPasswordField:1,maxLength:80});a.addTextFieldRow("txtNewPW",{rawLabel:"New Password",isPasswordField:1,maxLength:80});a.addTextFieldRow("txtConfirmPW",{rawLabel:"Confirm Password",isPasswordField:1,maxLength:80});a.addTextFieldRow("txtUserName",{fieldValue:g_username,hideRow:1});a.showClientDialog()}function submitEditOrAddTaxRate(){var d="frmNewTaxRate",e=getObj(d),b=mjtElemData(e,"taxRateId"),a=new FormValidator(),c={taxRateId:b||"",taxRateName:e.txtName.value,taxRatePercent:trim(e.txtRate.value),state:trim(e.txtState.value)};if(!a.CSValidateRequiredField(e.txtName,"Please enter a Name")){return}if(!a.CSValidateNumberField(e.txtRate,"Rate",false)){return}jsrsExecuteWithErrorP(b?"Admin2_UpdateTaxRate2":"Admin2_CreateTaxRate2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,b?"Creating Tax Rate":"Updating Tax Rate",c)}function carefullyDisplayEventLog(b,a){hideDialogP({callback:function(){window.location=pageEventLog+b+"/"+a}})}function carefullyDisplayTaxRateEventLog(a){carefullyDisplayEventLog(EventObjectType_Enum.eotTaxRate,a)}function carefullyDisplayStateTaxAgencyEventLog(a){carefullyDisplayEventLog(EventObjectType_Enum.eotStateTaxAgency,a)}function carefullyDisplayEmailTemplateEventLog(a){carefullyDisplayEventLog(EventObjectType_Enum.eotEmailTemplate,a)}function carefullyDisplayProductEventLog(a){carefullyDisplayEventLog(EventObjectType_Enum.eotProduct,a)}function carefullyDisplayPricingStructureEventLog(a){carefullyDisplayEventLog(EventObjectType_Enum.eotPricingStructure,a)}function carefullyDisplayDatabasePricingStructureEventLog(a){carefullyDisplayEventLog(EventObjectType_Enum.eotDatabasePricingStructure,a)}function carefullyDisplayUserEventLog(a){hideDialogP({callback:function(){window.location=pageUserEventLog+a}})}function showTaxRateDialog(f,b,e,a){var g="frmNewTaxRate",h,c=jtcrmHasAccess(JTCRMSecuredObject_Enum.soTaxRates,AccessRight_Enum.mjtARDelete),d=new ClientDialogBuilder({formId:g,formTitle:f?"Edit Tax Rate":"New Tax Rate",focusFieldName:"txtName",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitEditOrAddTaxRate()"}),fnSubmit:submitEditOrAddTaxRate,arrExtraHeaderButtons:f?[c?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedOnClickJS:"confirmDeleteTaxRate("+f+",unescape('"+escape(b)+"'))",doubleQuoteEncodedTitle:"Delete Tax Rate"}):"",c?'':"",cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayTaxRateEventLog("+f+")"})]:0});d.addTextFieldRow("txtName",{rawLabel:"Name",mnemonicChar:"n",fieldValue:b||"",maxLength:80});d.addTextFieldRow("txtRate",{rawLabel:"Rate",mnemonicChar:"r",fieldValue:""+(e||0),maxLength:8,isNumber:1});d.addTextFieldRow("txtState",{rawLabel:"State",mnemonicChar:"t",fieldValue:a||"",maxLength:80});h=d.showClientDialog();if(h){mjtElemData(h,"taxRateId",f)}}function showNewTaxRateDialog(){showTaxRateDialog()}function doDeleteStateTaxAgency(a){jsrsExecuteWithErrorP("Admin2_DeleteStateTaxAgency",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting State Tax Agency",{stateTaxAgencyId:a.stateTaxAgencyId})}function confirmDeleteStateTaxAgency(b,a){hideDialog();displaySimpleConfirmationDialog(doDeleteStateTaxAgency,'Are you sure you want to delete "'+htmlEncode(a)+'"',"Delete State Tax Agency",{stateTaxAgencyId:b,stateTaxAgencyName:a})}function submitEditOrAddStateTaxAgency(){var g="frmAgency",h=getObj(g),a=mjtElemData(h,"stateTaxAgencyId"),b=new FormValidator(),f=h.cboState,e=trim(f.value),d={stateTaxAgencyId:a||"",stateTaxAgencyName:trim(h.txtName.value),state:e},c=b.CSValidateRequiredField(h.txtName,"Please enter a Name");if(!c){return}if(!e){showInfoDialog('
Please select a state
',"Missing State",1,f.name);return}jsrsExecuteWithErrorP(a?"Admin2_UpdateStateTaxAgency":"Admin2_CreateStateTaxAgency",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,a?"Creating State Tax Agency":"Updating State Tax Agency",d)}function rsCallbackGetStatesForStateTaxAgencyDialog(h,b){var g=b.originalOptions,j=g.params||{},f=h.arrStateNames,m=f.map(function(n){return{cboValue:n,rawContent:n}}),k="frmAgency",i,d=j.id,c=j.name,a=j.state,e=jtcrmHasAccess(JTCRMSecuredObject_Enum.soTaxRates,AccessRight_Enum.mjtARDelete),l=new ClientDialogBuilder({formId:k,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?[e?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedOnClickJS:"confirmDeleteStateTaxAgency("+d+",unescape('"+escape(c)+"'))",doubleQuoteEncodedTitle:"Delete Tax Rate"}):"",e?'':"",cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayStateTaxAgencyEventLog("+d+")"})]:0});l.addTextFieldRow("txtName",{rawLabel:"Agency Name",mnemonicChar:"n",fieldValue:c||"",maxLength:80});if(!d){m.unshift({cboValue:"",rawContent:"-Select State-"})}l.addDropdown({fieldName:"cboState",rawLabel:"State",arrAvailableOptions:m,objSelectedValue:a?{cboValue:a,rawContent:a}:null});i=l.showClientDialog();if(i){mjtElemData(i,"stateTaxAgencyId",d)}}function showStateTaxAgencyDialog(a){jsrsExecuteWithErrorP("Admin2_GetStatesWithTaxRates",rsCallbackHandleStandardJSONResponse,"Retrieving New Product Info",{excludeStatesWithAssignedStateTaxAgency:1},{fnOnSuccess:rsCallbackGetStatesForStateTaxAgencyDialog,params:a})}function submitTaxJarTransReportOptions(){var i="frmOptions",e=getObj(i),a=new FormValidator(),f=pageTaxJarTransReport,g=e.dtFrom,h=e.dtTo,d=e.txtPageSize,b=trim(d.value),c=a.CSValidateIntegerFieldP({field:d,label:"Page Size",isNullable:true,minValue:1,maxValue:2000})&&a.CSValidateDateFieldP({field:g,label:"From"})&&a.CSValidateDateFieldP({field:h,label:"To"});if(!c){return}if(b){f+="&pageSize="+b}f+="&from="+trim(getDateForUrlParam(g.value));f+="&to="+trim(getDateForUrlParam(h.value));hideDialog();window.location=f;displayTimedMessage("Reloading page...")}function showTaxJarTransReportOptions(a){var c="frmOptions",b=new ClientDialogBuilder({formId:c,formTitle:"Tax Jar Transactions Report Options",focusFieldName:"dtFrom",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitTaxJarTransReportOptions()"}),fnSubmit:submitTaxJarTransReportOptions});b.addDatePickerRow(c,"dtFrom",{rawLabel:"From",strValue:a.fromDate,autofocus:1});b.addDatePickerRow(c,"dtTo",{rawLabel:"To",strValue:a.toDate});b.addTextFieldRow("txtPageSize",{rawLabel:"Rows per Page",fieldValue:""+a.pageSize,mnemonicChar:"r",maxLength:10,styleWidth:"7em",isNumber:1});b.showClientDialog()}function submitEditOrAddProduct(){var m="frmNewProduct",l=getObj(m),b=new FormValidator(),e=l.cboEdition.options[l.cboEdition.selectedIndex].value,a=e!=="",o=l.cboTerm.options[l.cboTerm.selectedIndex].value,d=l.cboPricingStructure.options[l.cboPricingStructure.selectedIndex].value,n=d!==""?parseInt(d,10):null,f=l.priceGenerations.options[l.priceGenerations.selectedIndex].value,i=f!==""?parseInt(f,10):null,k=(i===g_flexPricingProductGenerationId),p=l.productTypes.options[l.productTypes.selectedIndex].value,q=p!==""?parseInt(p,10):null,h=q===CRMProductType_Enum.crmptCounterGo,g=q===CRMProductType_Enum.crmptNVInventory,c=mjtElemData(l,"productId"),j={productId:c||"",productName:l.txtName.value,jtUserCount:trim(l.txtJTCount.value),cgUserCount:trim(l.txtCGCount.value),nvUserCount:trim(l.txtNVCount.value),fileSize:trim(l.txtFileSize.value),editionId:e,term:o,price:trim(l.txtPrice.value),notes:cdGetExpandingTextFieldValue("txtNotes"),isDiscountable:l.chkDiscountable.checked?1:0,isJobTrackerSubscription:l.chkJTSubscription.checked?1:0,displayedProductGroupId:l.cboDisplayGroup.options[l.cboDisplayGroup.selectedIndex].value,priceGenerations:i,pricingStructureId:n,productType:q,isDeprecated:(l.chkDeprecated&&l.chkDeprecated.checked)?1:0};if(!b.CSValidateRequiredField(l.txtName,"Please enter a Name")){return}if(!b.CSValidateNumberField(l.txtJTCount,"Job Tracker User Count",false)){return}if(!b.CSValidateNumberField(l.txtCGCount,"CounterGo User Count",false)){return}if(!b.CSValidateNumberField(l.txtNVCount,"Inventory User Count",false)){return}if(!b.CSValidateNumberField(l.txtFileSize,"File Size",false)){return}if(k){if(!n&&(h||g||a)){showInfoDialog("Please select a pricing structure.","Select Pricing Structure",true,"cboPricingStructure");return}}else{if(!b.CSValidateNumberField(l.txtPrice,"Price",false)){return}}jsrsExecuteWithErrorP(c?"Admin2_UpdateProduct2":"Admin2_CreateProduct2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,c?"Creating Product":"Updating Product",j)}function buildAnOption(c,d,e,f,b){var a=(f||e==c);if(a&&b){b.didSelect=1}return'"}function buildDropdownContent(j){var a=j.name,c=j.valueLookup,g=j.textLookup,l=j.selectedValue,e=j.arrValues,b=j.onChangeCode?' onchange="'+j.onChangeCode+'"':"",k=j.disabled?" disabled":"",d,f="";for(d=0;d"+f+""}function buildDropdownRow(a){return cdBuildReadOnlyFieldRowP({labelHTML:a.label,valueHTML:buildDropdownContent({name:a.name,valueLookup:a.valueLookup,textLookup:a.textLookup,selectedValue:a.selectedValue,arrValues:a.values,onChangeCode:a.onChangeCode,disabled:a.disabled}),rowId:a.rowId,valueCellId:a.valueCellId})}function submitPricingStructureDialog(){var f="frmPricingStructure",r=getObj(f),n=mjtElemData(r,"pricingStructureId"),e=new FormValidator(),j=r.cboProductType.options[r.cboProductType.selectedIndex].value,g=j?parseInt(j,10):null,a=r.cboEdition.options[r.cboEdition.selectedIndex].value,l=a?parseInt(a,10):null,b=r.chkIsInactive&&r.chkIsInactive.checked?1:0,d=trim(r.txtTier2StartUserCount.value),k=d!==""?parseInt(d,10):null,c=trim(r.txtTier2PerUserPrice.value),m=c!==""?parseFloat(c):null,o=g===CRMProductType_Enum.crmptCounterGo,p=g===CRMProductType_Enum.crmptNVInventory,q={pricingStructureId:n,isInactive:b,productTypeId:g,editionId:l,editionPrice:r.txtEditionPrice.value,additionalUserPrice:r.txtAdditionalUserPrice.value,tier2StartUserCount:k,tier2PerUserPrice:m},i={minValue:0,maxDecimalPlaces:2},s=[{field:r.txtAdditionalUserPrice,label:"Additional User Price"},{field:r.txtTier2PerUserPrice,label:"Tier 2 Per-User Price",isNullable:true},{field:r.txtTier2StartUserCount,label:"Tier 2 Start",isNullable:true,maxDecimalPlaces:0}];if(!g){showInfoDialog("Please select your product type.","Select Product Type",true,"cboProductType");return}for(var h in s){Object.assign(i,s[h]);if(!e.CSValidateNumberFieldP(i)){return}}if(m&&!k){showInfoDialog('
Please set the Tier 2 Start User # or clear the Tier 2 Per-User Price
',"Invalid Tier 2 Price Settings",true,r.txtTier2StartUserCount);return}if(k&&!m&&m!==0){showInfoDialog('
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,r.txtTier2StartUserCount);return}jsrsExecuteWithErrorP(n?"Admin2_UpdatePricingStructureInactiveInd":"Admin2_CreatePricingStructure",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Saving Pricing Structure",q)}function productTypeSupportsEdition(a){return a===CRMProductType_Enum.crmptJobTracker||a===CRMProductType_Enum.crmptSystemize}function showHideApplyPricingStructureEditionId(g){var f=g?g:"frmPricingStructure",h=getObj(f),e=h.cboProductType,b=e[e.selectedIndex].value,c=parseInt(b,10),d=getObj("trEditionSelector"),a=getObj("trEditionPrice");if(productTypeSupportsEdition(c)){d.style.display="";if(a){a.style.display=""}}else{d.style.display="none";if(a){a.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(a){return buildDropdownRow({name:a.name,label:a.label,valueLookup:"editionId",textLookup:"editionName",values:getEditionOptions(),selectedValue:a.selectedValue,onChangeCode:a.onChangeCode,rowId:a.rowId,disabled:a.disabled})}function removeJobTrackerFromProductArray(b){var c=b,a=undefined;for(var d in c){if(c[d].productTypeId===CRMProductType_Enum.crmptJobTracker){a=d;break}}if(a!==undefined){c.splice(a,1)}return c}function showPricingStructureDialog(i){var d=100000,c=1,m=i.pricingStructureId,e=i.editionPrice,g=i.additionalUserPrice,o=i.tier2StartUserCount,k=i.tier2PerUserPrice,a=i.pricingStructureName,n=removeJobTrackerFromProductArray(i.arrProductTypes),b="6em",l="frmPricingStructure",f=jtcrmHasAccess(JTCRMSecuredObject_Enum.soProducts,AccessRight_Enum.mjtARDelete),h=buildDropdownRow({name:"cboProductType",label:"Product Type",valueLookup:"productTypeId",textLookup:"productTypeName",values:n,selectedValue:i.productTypeId,onChangeCode:"showHideApplyPricingStructureEditionId()",disabled:m})+buildEditionDropdownRow({name:"cboEdition",label:"Edition",selectedValue:i.editionId,rowId:"trEditionSelector",disabled:m}),p=new ClientDialogBuilder({formId:l,formTitle:(m?"Edit":"Create")+" Pricing Structure",focusFieldName:"cboProductType",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitPricingStructureDialog()"}),fnSubmit:submitPricingStructureDialog,arrExtraHeaderButtons:m?[f?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Pricing Structure",doubleQuoteEncodedOnClickJS:"confirmDeletePricingStructure("+m+", unescape('"+escape(a)+"'))"}):null,f?'':null,cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayPricingStructureEventLog("+m+")"})]:0});p.addDialogInteriorRows(h);p.addTextFieldRow("txtEditionPrice",{rawLabel:"Base Price ($)",mnemonicChar:"b",fieldValue:""+e,placeholder:"e.g. 600",strStyleWidth:b,isNumber:true,minValue:0,maxValue:d,step:c,rowId:"trEditionPrice",disabled:m});p.addTextFieldRow("txtAdditionalUserPrice",{rawLabel:"Additional User Price ($)",mnemonicChar:"a",fieldValue:""+g,placeholder:"e.g. 50",strStyleWidth:b,isNumber:true,minValue:0,maxValue:d,step:c,disabled:m});p.addTextFieldRow("txtTier2StartUserCount",{rawLabel:"Tier 2 Starts with User #",mnemonicChar:"s",fieldValue:""+(o||""),placeholder:"(optional)",strStyleWidth:b,isNumber:true,minValue:0,maxValue:1000,step:c,disabled:m});p.addTextFieldRow("txtTier2PerUserPrice",{rawLabel:"Tier 2 Per-User Price ($)",mnemonicChar:"p",fieldValue:""+(k||""),placeholder:"(optional)",strStyleWidth:b,isNumber:true,minValue:0,maxValue:d,step:c,disabled:m});if(m){p.addCheckboxRow("chkIsInactive",{rawLabel:"Inactive",mnemonicChar:"i",checked:i.isInactive})}var j=p.showClientDialog();if(j){mjtElemData(j,"pricingStructureId",m);showHideApplyPricingStructureEditionId()}}function refreshPricingStructureSelector(o){var q=getObj(o.strFormId),p=getObj(o.pricingStructureValueCellId),d=o.arrPricingStructures,a=o.pricingStructureSelectorName,k=o.selectedProductTypeId,e=o.selectedEditionId,b=q.cboPricingStructure,i=b[b.selectedIndex],f=i?i.value:null,m=f===null?null:parseInt(f,10),j=[d[0]];for(var l in d){var c=d[l],n=c.productTypeId===k,g=isNaN(e)&&!c.editionId,h=c.editionId===e,r=!c.isInactive||c.pricingStructureId===m;if(r&&n&&(g||h)){j.push(c)}}p.innerHTML=buildDropdownContent({name:a,valueLookup:"pricingStructureId",textLookup:"pricingStructureName",selectedValue:f,arrValues:j})}function showHideProductFlexPricing(){var n="frmNewProduct",i=getObj(n),k=mjtElemData(i,"arrPricingStructures"),p=JSON.parse(k),c=i.priceGenerations,d=c[c.selectedIndex].value,g=parseInt(d,10),j=(g===g_flexPricingProductGenerationId),a=i.productTypes,f=a[a.selectedIndex].value,l=parseInt(f,10),o=i.cboEdition,q=o[o.selectedIndex].value,e=parseInt(q,10),m=getObj("trPrice"),b=getObj("trPricingStructure");if(j){var h={strFormId:n,selectedProductTypeId:l,selectedEditionId:e,arrPricingStructures:p,pricingStructureValueCellId:"tdPricingStructure",pricingStructureSelectorName:"cboPricingStructure"};refreshPricingStructureSelector(h);m.style.display="none";b.style.display=""}else{m.style.display="";b.style.display="none"}}function showProductDialog(k){var p=k.id,g=k.name,b=k.price,q=k.jtUserCount,D=k.cgUserCount,d=k.nvUserCount,v=k.fileSize,s=k.editionId,o=k.term,l=k.isDeprecated,B=k.isDiscountable,n=k.isJTSubscription,x=k.notes,w=k.displayedProductGroupId,e=k.displayedProductGroupName,u=k.priceGenerationId,r=k.priceGenerations,m=k.productTypeId,j=k.productTypes,i=k.pricingStructures,t=k.pricingStructureId;if(!p){l=1}var a="",c="",A={};c+=buildAnOption(DisplayedProductGroup_Enum.dpgSubscription,"Subscription",""+w,0,A);c+=buildAnOption(DisplayedProductGroup_Enum.dpgJTDownload,"JT Download",""+w,0,A);c+=buildAnOption(DisplayedProductGroup_Enum.dpgLegacy,"Legacy",""+w,0,A);if(w&&!A.didSelect){c+=buildAnOption(""+w,"Unknown Group: ["+htmlEncode(e)+"]",""+w,0,A)}a+=buildAnOption(Term_Enum.trmMonthly,"Monthly",o);a+=buildAnOption(Term_Enum.trmQuarterly,"Quarterly",o);a+=buildAnOption(Term_Enum.trmAnnual,"Annual",o);if(u===""){u=-1}var h="frmNewProduct",z,f=jtcrmHasAccess(JTCRMSecuredObject_Enum.soProducts,AccessRight_Enum.mjtARCreate),y=jtcrmHasAccess(JTCRMSecuredObject_Enum.soProducts,AccessRight_Enum.mjtARDelete),C=cdBuildTextFieldRowP("txtName","Name",{fieldValue:g||"",maxlength:80})+buildDropdownRow({name:"productTypes",label:"Product Type",valueLookup:"productTypeId",textLookup:"productTypeName",selectedValue:m,values:j,onChangeCode:"showHideProductFlexPricing()"})+cdBuildReadOnlyFieldRowP({rawLabel:"Display Group",valueHTML:'"})+buildEditionDropdownRow({name:"cboEdition",label:"Edition",selectedValue:s,onChangeCode:"showHideProductFlexPricing()"})+cdBuildReadOnlyFieldRowP({rawLabel:"Term",valueHTML:'"});if(p){C+=cdBuildCheckboxRowP("chkDeprecated","Deprecated",{checked:l})}C+=cdBuildCheckboxRowP("chkDiscountable","Discountable",{checked:B})+cdBuildCheckboxRowP("chkJTSubscription","JT Subscription",{checked:n})+cdBuildTextFieldRowP("txtJTCount","Systemize User Count",{fieldValue:(q||"0")+"",maxLength:8})+cdBuildTextFieldRowP("txtCGCount","CounterGo User Count",{fieldValue:(D||"0")+"",maxLength:8})+cdBuildTextFieldRowP("txtNVCount","Inventory User Count",{fieldValue:(d||"0")+"",maxLength:8})+cdBuildTextFieldRowP("txtFileSize","File Size MB",{fieldValue:(v||"0")+"",maxLength:8})+buildDropdownRow({name:"priceGenerations",label:"Price Generation",valueLookup:"priceGenerationId",textLookup:"priceGenerationName",selectedValue:u,values:r,onChangeCode:"showHideProductFlexPricing()"})+buildDropdownRow({name:"cboPricingStructure",label:"Default Pricing Structure",valueLookup:"pricingStructureId",textLookup:"pricingStructureName",selectedValue:t,values:i,rowId:"trPricingStructure",valueCellId:"tdPricingStructure"})+cdBuildTextFieldRowP("txtPrice","Price",{fieldValue:(b||"0")+"",maxLength:8,rowId:"trPrice"})+cdBuildExpandingTextFieldRowsP("txtNotes","Description",{value:x});z=showDialogP(C,h,{formTitle:(p?"Edit":"New")+" Product",focusFieldName:"txtName",arrExtraHeaderButtons:p?[y?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Product",doubleQuoteEncodedOnClickJS:"confirmDeleteProduct("+p+",unescape('"+escape(g)+"'),1)"}):null,y?'':null,f?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowDuplicateDocument,doubleQuoteEncodedTitle:"Duplicate Product",doubleQuoteEncodedOnClickJS:"showDuplicateProductDialog("+p+",unescape('"+escape(g)+"'),1)"}):null,cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayProductEventLog("+p+")"})]:0,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitEditOrAddProduct()"}),contextDetailOrFnSubmit:{fnSubmit:submitEditOrAddProduct,callbackData:{id:p}}});if(z){mjtElemData(z,"productId",p);mjtElemData(z,"arrPricingStructures",JSON.stringify(i));showHideProductFlexPricing()}}function showEditProductDialog(a,b){jsrsExecuteWithErrorP("Admin2_GetProductDetails",rsCallbackHandleStandardJSONResponse,'Retrieving info for product, "'+htmlEncode(b)+'"...',{productId:a},{fnOnSuccess:showProductDialog})}function rsCallbackDuplicateProduct(b){var a=b;a.name="Copy of "+b.name;a.id=null;showProductDialog(a)}function showDuplicateProductDialog(b,c,d){var a=function(){jsrsExecuteWithErrorP("Admin2_GetProductDetails",rsCallbackHandleStandardJSONResponse,'Retrieving info for product, "'+htmlEncode(c)+'"...',{productId:b},{fnOnSuccess:rsCallbackDuplicateProduct})};if(d){hideDialogP({callback:a})}else{a()}}function rsCallbackShowNewPricingStructureDialog(a){var b={arrProductTypes:a};showPricingStructureDialog(b)}function rsCallbackShowNewProduct(a){var b={productTypes:a.arrProductTypes,priceGenerations:a.arrPriceGenerations,pricingStructures:a.arrPricingStructures};showProductDialog(b)}function showNewPricingStructureDialog(){jsrsExecuteWithErrorP("Admin2_GetNewPricingStructureInfo",rsCallbackHandleStandardJSONResponse,"Retrieving New Pricing Structure Info",{},{fnOnSuccess:rsCallbackShowNewPricingStructureDialog})}function showEditPricingStructureDialog(a){jsrsExecuteWithErrorP("Admin2_GetPricingStructure",rsCallbackHandleStandardJSONResponse,"Retrieving Pricing Structure Info",{pricingStructureId:a},{fnOnSuccess:showPricingStructureDialog})}function showNewProductDialog(){jsrsExecuteWithErrorP("Admin2_GetNewProductInfo2",rsCallbackHandleStandardJSONResponse,"Retrieving New Product Info",{},{fnOnSuccess:rsCallbackShowNewProduct})}function buildOptionHTML(d,b,a){var c="";if((b+"")==(a+"")){c=' selected="selected"'}return'"}function updatePricingStructureOptions(){var c="frmSettings",d=getObj(c),b=pagePricingStructure,a=d.cboDeprecationStatus.value;if(a!=DeprecationStatus_Enum.dsNonDeprecatedOnly){b+="&"+pageFilterDeprecationStatus+"="+a}hideDialog();window.location=b}function updateProductSettingsOptions(){var f="frmSettings",g=getObj(f),e=pageSystemSettingsProducts,b=g.cboEdition.value,a=g.cboSubscriptionStatus.value,d=g.cboDeprecationStatus.value,c=mwGetCompoundSelectionValueForBase(g,"terms");if(b!=EditionFilter_Enum.efAny){e+="&edFilt="+b}if(a!=SubscriptionStatus_Enum.ssAny){e+="&ssFilt="+a}if(d!=DeprecationStatus_Enum.dsNonDeprecatedOnly){e+="&dsFilt="+d}if(c){e+="&trmFilt="+c}hideDialog();window.location=e}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(b){var a=b.deprecationStatus||DeprecationStatus_Enum.dsNonDeprecatedOnly,d="frmSettings",c=new ClientDialogBuilder({formId:d,formTitle:"Pricing Structure Options",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"updatePricingStructureOptions()"}),focusFieldName:"cboDeprecationStatus",focusFieldOnMobile:1,fnSubmit:updatePricingStructureOptions});c.addFlexibleFieldRow({rawLabel:"Deprecation Status",valueHTML:'"});c.showClientDialog()}function showProductSettingsOptions(c){var b=c.edition||EditionFilter_Enum.efAny,f=c.subscriptionStatus||SubscriptionStatus_Enum.ssAny,a=c.deprecationStatus||DeprecationStatus_Enum.dsAny,e="frmSettings",d=new ClientDialogBuilder({formId:e,formTitle:"Products Options",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"updateProductSettingsOptions()"}),focusFieldName:"cboEdition",focusFieldOnMobile:1,fnSubmit:updateProductSettingsOptions});d.addFlexibleFieldRow({rawLabel:"Deprecation Status",valueHTML:'"});d.addFlexibleFieldRow({rawLabel:"Filter Edition",valueHTML:'"});d.addFlexibleFieldRow({rawLabel:"Subscription Status",valueHTML:'"});d.addCompoundSelectionFieldRowP({fieldNameBase:"terms",autofocus:1,whatSingular:"Term",arrSelectedIds:c.arrTermIds,arrObjects:getProductTermList().arrTerms,fnRSCallSubstitute:getProductTermList,objectArrayName:"arrTerms",simpleIdPropertyName:"termId",simpleNameDisplayPropertyName:"termName"});d.showClientDialog()}function showUserPreferencesDialog(){showInfoDialog("TODO: showUserPreferencesDialog","showUserPreferencesDialog")}function rsCallbackGetDatabaseItemAssociationDialog(e,b){var k=e.arrDatabases,g=k.length,i=(g===1?"":"s"),h=false,f,a=new ClientDialogBuilder({formTitle:b.originalOptions.dialogTitle}),d=new MWClientTable({noDataMessage:"No "+b.originalOptions.dialogTitle,fnAdditionalRowAttrs:function(l){var m=JSON.parse(JSON.stringify(l));if(b.originalOptions.itemDetailIsDate){m.itemDetail=parseDateString(m.itemDetail)}return"data-rowData='"+escape(JSON.stringify(m))+"'"}});a.addFlexibleFieldRow({rawLabel:b.originalOptions.itemLabel,rawValue:b.originalOptions.itemName});d.addColumn(new MWColumn({columnName:"Customer",simpleDisplayColumnPropertyName:"customerName",sortInfo:{}}));d.addColumn(new MWColumn({columnName:"Database",simpleDisplayColumnPropertyName:"subdomain",sortInfo:{},fnBuildCellLinkDetail:function(o,m,l,n){return mwBuildSimpleLink(pageDatabaseDetail+o.databaseId,1)}}));for(var j in k){var c=parseInt(k[j].itemDetail,10);if(isNaN(c)||c>1){h=true;break}}if(h){d.addColumn(new MWColumn({columnName:b.originalOptions.itemDetailColumnName,simpleDisplayColumnPropertyName:"itemDetail",sortInfo:{isNumber:!b.originalOptions.itemDetailIsDate},additionalCellClasses:"rightAlign"}))}f="
"+d.buildTableForArray(k)+"
";if(g>0){f+='
('+g+" Database"+i+")
"}a.addFlexibleRow({valueHTML:f});a.showClientDialog()}function showDBsWithSubscriptionDialog(b,a){jsrsExecuteWithErrorP("Admin2_GetDBsWithSubscription2",rsCallbackHandleStandardJSONResponse,'Retrieving info for product, "'+a+'"',{productId:b},{fnOnSuccess:rsCallbackGetDatabaseItemAssociationDialog,dialogTitle:"Active Subscriptions",itemDetailColumnName:"# of Subscriptions",itemLabel:"Product",itemName:a})}function showDBsWithPricingStructureDialog(a,b){jsrsExecuteWithErrorP("Admin2_GetDatabasesWithPricingStructureApplied",rsCallbackHandleStandardJSONResponse,"Retrieving databases",{pricingStructureId:a},{fnOnSuccess:rsCallbackGetDatabaseItemAssociationDialog,dialogTitle:"Databases Applying Pricing Structure",itemDetailColumnName:"Effective Date",itemLabel:"Pricing Structure",itemName:b,itemDetailIsDate:true})}function showDBsWithTaxRateDialog(b,a){jsrsExecuteWithErrorP("Admin2_GetDatabasesWithTaxRate",rsCallbackHandleStandardJSONResponse,"Retrieving databases",{taxRateId:b},{fnOnSuccess:rsCallbackGetDatabaseItemAssociationDialog,dialogTitle:"Databases with Tax Rate",itemDetailColumnName:"Next Invoice Amount",itemLabel:"Tax Rate",itemName:a})}function submitCreateUser(){var i="frmCreateUser",e=getObj(i),a=new FormValidator(),b=e.txtEmail,f=b.value,g=e.txtPassword,j=g.value,d=e.txtConfirmPassword.value,h=e.txtCardMember.value,c=e.cboAnyOrUserPermissions[e.cboAnyOrUserPermissions.selectedIndex].value;if(!a.CSValidateRequiredField(e.txtEmail,"Please enter an email address")){return}if(!validateEmailAddress(f)){showInfoDialog("Invalid email address.","Invalid Email",1,"txtEmail");return}if(j!==d){showInfoDialog("Passwords don't match!","Mismatched Passwords",1,"txtConfirmPassword");return}if(!validateClientSidePasswordVals(b,g,showPWValidationError)){return}jsrsExecuteWithErrorP("Admin2_CreateUser2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Creating User",{emailAddress:f,password:j,fullName:trim(e.txtFullName.value),cardMemberName:h,isAdmin:c==="1"?1:0,roleId:c==="1"?"":e.cboRoles[e.cboRoles.selectedIndex].value})}function onRoleSelectChanged(){var b=getObj("frmCreateUser");if(b){var a=b.cboAnyOrUserPermissions[b.cboAnyOrUserPermissions.selectedIndex].value;if(a==="1"){b.cboRoles.style.display="none"}else{b.cboRoles.style.display=""}}}function showCreateUser(c,a){var e="frmCreateUser",d,b=new ClientDialogBuilder({formId:e,formTitle:"Create User",focusFieldName:"txtEmail",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitCreateUser()"}),fnSubmit:submitCreateUser});b.addTextFieldRow("txtEmail",{rawLabel:"Email Address",maxLength:200,autofocus:1,isEmail:1});b.addTextFieldRow("txtFullName",{rawLabel:"Full Name",maxLength:80,autofocus:1});b.addTextFieldRow("txtPassword",{rawLabel:"Password",maxLength:80,isPasswordField:1});b.addTextFieldRow("txtConfirmPassword",{rawLabel:"Confirm Password",maxLength:80,isPasswordField:1});b.addTextFieldRow("txtCardMember",{rawLabel:"Card Member",maxLength:80});b.addDialogInteriorRows(buildDialogDoubleColumnRow("
Permissions
","dialogFieldSectionHeaderRow"));b.addFlexibleFieldRow({valueHTML:'"});b.showClientDialog()}function submitUpdateUser(){var d="frmCreateUser",e=getObj(d),a=mjtElemData(e,"userId"),b=e.cboAnyOrUserPermissions[e.cboAnyOrUserPermissions.selectedIndex].value,c=!e.chkIsLocked.disabled&&!e.chkIsLocked.checked;jsrsExecuteWithErrorP("Admin2_UpdateUser2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating user",{userId:a,fullName:trim(e.txtFullName.value),isTaskUser:e.chkTaskUser.checked?1:0,cardMember:trim(e.txtCardMember.value),isInactive:e.chkIsInactive.checked?1:0,unlockUser:c?1:0,isAdmin:b==="1"?1:0,role:b==="1"?null:e.cboRoles[e.cboRoles.selectedIndex].value})}function showUserDialogP(h){var g="frmCreateUser",e,b=h.userId,f=h.email,a=h.cardMember,c=h.isAdmin,d=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUserSettings,AccessRight_Enum.mjtARDelete),i=new ClientDialogBuilder({formId:g,formTitle:"Edit User",focusFieldName:"txtFullName",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitUpdateUser()"}),fnSubmit:submitUpdateUser,arrExtraHeaderButtons:[d?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete User",doubleQuoteEncodedOnClickJS:"confirmDeleteUser("+b+",unescape('"+escape(f)+"'),1)"}):null,d?'':null,cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Changes Made By "+f,doubleQuoteEncodedOnClickJS:"carefullyDisplayUserEventLog("+b+")"})]});i.addFlexibleFieldRow({rawLabel:"Email Address",rawValue:f||""});i.addTextFieldRow("txtFullName",{rawLabel:"Full Name",fieldValue:h.fullName||"",maxLength:80,autofocus:1});i.addTextFieldRow("txtCardMember",{rawLabel:"Card Member",fieldValue:a||"",maxLength:80,autofocus:1});i.addCheckboxRow("chkTaskUser",{rawLabel:"Task User",checked:h.isTaskUser});i.addCheckboxRow("chkIsInactive",{rawLabel:"Inactive",mnemonicChar:"i",checked:h.isInactive});i.addCheckboxRow("chkIsLocked",{rawLabel:"Locked",checked:h.isLocked,disabled:!h.isLocked});i.addSectionHeaderRow({rawTitle:"Permissions"});i.addFlexibleFieldRow({valueHTML:'"});e=i.showClientDialog();if(e){mjtElemData(e,"userId",b)}}function doDeleteUser(a){jsrsExecuteWithErrorP("Admin2_DeleteUser2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting User",{userId:a.userId})}function confirmDeleteUser(a,b,c){if(c){hideDialog()}displaySimpleConfirmationDialog(doDeleteUser,'Are you sure you want to delete "'+htmlEncode(b)+'"',"Delete User",{userId:a,email:b})}function submitUpdateOrCreateRole(){var d="editRole",e=getObj(d),a=mjtElemData(e,"roleId"),b=e.txtRoleName,c=new FormValidator();if(!c.CSValidateRequiredField(b,"Please enter a Role Name")){return}jsrsExecuteWithErrorP(a?"Admin2_UpdateRole":"Admin2_CreateRole",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Getting Role Info",{roleId:a||"",roleName:trim(b.value),roleDescription:cdGetExpandingTextFieldValue("txtRoleDescription"),securityProfile:computeSecurityProfile({minSecuredObjectId:JTCRMSecuredObject_Enum.mjtMinSecuredObjectId,maxSecuredObjectId:JTCRMSecuredObject_Enum.mjtMaxSecuredObjectId})})}function doDeleteRole(a){jsrsExecuteWithErrorP("Admin2_DeleteRole",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting Role",{roleId:a.roleId})}function confirmDeleteRole(a){hideDialogP({callback:function(){displaySimpleConfirmationDialog(doDeleteRole,"Are you sure you want to delete the role?","Delete Role",{roleId:a})}})}function doShowUpdateOrCreateRole(b){b=b||{};var i=b.roleId,d=b.arrSecuritySections,e,a,f="editRole",c,g=pageEventLog+EventObjectType_Enum.eotJTCRMRole+"/"+i,h=new ClientDialogBuilder({formId:f,formTitle:i?"Edit Role":"Create Role",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitUpdateOrCreateRole()"}),focusFieldName:"txtRoleName",focusFieldOnMobile:1,arrExtraHeaderButtons:i?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Role",doubleQuoteEncodedOnClickJS:"hideDialog();confirmDeleteRole("+i+")"}),'',cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowDuplicateDocument,doubleQuoteEncodedTitle:"Duplicate Role",doubleQuoteEncodedOnClickJS:"promptDuplicateRole('"+i+"');"}),cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"Change Log",doubleQuoteEncodedOnClickJS:"clickedDialogLink('"+g+"');"})]:null,fnSubmit:submitUpdateOrCreateRole});h.addTextFieldRow("txtRoleName",{rawLabel:"Role Name",mnemonicChar:"n",fieldValue:b.roleName||""});h.addExpandingTextFieldRows("txtRoleDescription",{rawLabel:"Description",mnemonicChar:"c",value:b.roleDescription||""});for(a=0;a'+b+"","Delete Pricing Structure",{pricingStructureId:a})}function submitReorderProducts(a){submitReorderP({arrReorderedIds:a,reorderCommandName:"Admin2_ReorderProducts2",reorderObjectName:"Products",reorderIdsPropertyName:"productIds"})}function rsCallbackGetObjectsForReorder(c,d){var e=d.originalOptions,b=c[e.arrayAttrName],a=e.fnSubmit;mwShowGenericReorderDialog(b,a,"Re-Order "+e.strReorderWhat,{idAttrName:e.idAttrName,nameAttrName:e.nameAttrName,highlightedId:e.highlightedId})}function showReorderProductsDialog(a){jsrsExecuteWithErrorP("Admin2_GetProductsForReorder",rsCallbackGetObjectsForReorder,"Getting list of products for re-order",{},{arrayAttrName:"arrProducts",fnSubmit:submitReorderProducts,strReorderWhat:"Products",highlightedId:a})}function showCustomerPage(a,b){displayTimedMessage("Loading Customer Details...");window.location=pageCustomerDetail+a}function rsCallbackCreatedCustomer(a){hideDialog();showCustomerPage(a.customerId)}function doSubmitEditOrAddCustomer(a,d){var c=new FormValidator(),g=d.id,e={customerName:trim(a.txtName.value),discountPercent:trim(a.txtDiscountPct.value)},b=a.chkDisablePortalUpdate,f=b?(b.checked?1:0):0;if(!c.CSValidateNumberField(a.txtDiscountPct,"Discount %",true)){return}if(g){e.customerId=g;e.disablePortalUpdate=f?1:0}jsrsExecuteWithErrorP(g?"Admin2_UpdateCustomer2":"Admin2_CreateCustomer2",g?rsCallbackHandleStandardJSONResponseWithHideAndRefresh:rsCallbackHandleStandardJSONResponse,g?"Updating Customer":"Creating Customer",e,{fnOnSuccess:g?null:rsCallbackCreatedCustomer})}function rsCallbackGetCustomerByName(d,b,c){enableDialogButtons();if(checkResponseForError(d)){var a=JSON.parse(d);if(a.name&&((!c.id)||(a.id!=c.id))){showInfoDialog('There is already a "'+htmlEncode(a.name)+'" customer',"Duplicate Customer",1,"txtName");return}doSubmitEditOrAddCustomer(getObj("frmCustomer"),c)}}function submitEditOrAddCustomer(a,c){var b=new FormValidator();if(!b.CSValidateRequiredField(a.txtName,"Please enter a Customer Name")){return}jsrsExecute(rsCallbackGetCustomerByName,"Admin_GetCustomerByName",[escape(a.txtName.value)],enableDialogButtons,c);displayTimedMessage("Checking for duplicate Customer Name...");disableDialogButtons()}function getSelectedTaxInfo(c){var a=c.options[c.selectedIndex].value,b=a?JSON.parse(a):0;return b}function buildTaxRateDropdownRow(e,a,d,b,h){var f="",c,j,g;if(a.length===0||d===0||b!==h){f+=''}for(c=0;c"+htmlEncode(g.name)+" ("+g.percent+"%)"}e.addFlexibleFieldRow({rawLabel:"Tax Rate",mnemonicChar:"t",mnemonicFocusFieldName:"cboTaxRate",valueHTML:'"})}function showCustomerDialog(c){var g=c.id,b=c.name,a=c.discountPct,f="frmCustomer",e=cdBuildTextFieldRowP("txtName","Name",{autofocus:!g,maxLength:80,fieldValue:b||""})+cdBuildTextFieldRowP("txtDiscountPct","Discount %",{maxLength:8,fieldValue:""+(a||""),isNumber:1,hideRow:!a}),d;if(g&&jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete)){d=[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Customer",doubleQuoteEncodedOnClickJS:"hideDialog();confirmDeleteCustomer("+g+",unescape('"+escape(b)+"'))"})];e+=cdBuildCheckboxRow("chkDisablePortalUpdate","chkDisablePortalUpdate","Disable Customer Portal",c.disablePortalUpdate)}showDialogP(e,f,{formTitle:(g?"Edit":"New")+" Customer",focusFieldName:"txtName",arrExtraHeaderButtons:d,contextDetailOrFnSubmit:{fnSubmit:submitEditOrAddCustomer,callbackData:{id:g}}})}function rsCallbackGetCustomerInfoForAddEditCustomer(c,a,b){enableDialogButtons();if(checkResponseForError(c)){var d=JSON.parse(c);d.id=b.id;if(b.duplicate){delete d.id}showCustomerDialog(d)}}function getCustomerInfoForAddEditCustomer(a){jsrsExecute(rsCallbackGetCustomerInfoForAddEditCustomer,"Admin_GetCustomerInfo",[a.id?a.id:""],enableDialogButtons,a);displayTimedMessage("Retrieving Customer Info...");disableDialogButtons()}function showCreateCustomerDialog(){getCustomerInfoForAddEditCustomer({})}function showEditCustomerDialog(a,b){getCustomerInfoForAddEditCustomer({id:a,name:b})}function showDuplicateCustomerDialog(a,b){getCustomerInfoForAddEditCustomer({id:a,name:b,duplicate:1})}function doDeleteCustomer(b){var a=b.name;if(a){a=htmlEncode(a)}else{a="Customer"}jsrsExecuteWithErrorP("Admin2_DeleteCustomer2",rsCallbackHandleStandardJSONResponse,"Deleting "+a,{customerId:b.id},{fnOnSuccess:rsCallbackSaveSettingsAndNavigateTo2,url:pageCustomers})}function confirmDeleteCustomer(a,b){displaySimpleConfirmationDialog(doDeleteCustomer,'Are you sure you want to delete "'+htmlEncode(b)+'"',"Delete Customer",{id:a,name:b})}function rsCallbackDeleteDB(a){if(a.customerId){window.location=pageCustomerDetail+a.customerId}else{window.location=pageDatabases}}function doDeleteDatabase(a){jsrsExecuteWithErrorP("Admin2_DeleteDatabase",rsCallbackDeleteDB,"Deleting Database...",{databaseId:a.id})}function confirmDeleteDatabase(a){var b=new ClientDialogBuilder({formTitle:"Delete Database",okButtonDisplayText:"Delete",focusFieldName:"btnOk",fnSubmit:function(c){hideDialog();doDeleteDatabase({id:a})}});b.addFlexibleRow({rawValue:"Are you sure you want to delete the database?"});b.showClientDialog()}function rsCallbackViewNewDatabase(a){hideDialog();window.location=pageDatabaseDetail+a.id}function submitEditDatabase(){var k="frmEditDatabase",f=getObj(k),b=new FormValidator(),l=getSelectedTaxInfo(f.cboTaxRate),d=mjtElemData(f,"databaseId"),e=cdGetExpandingTextFieldValue("txtNotes"),m=l?l.id:"",c=f.txtDiscountPct,a=f.txtJobId,g=f.txtHubspotCompanyId,i=g?trim(g.value):null;var h=b.CSValidateIntegerFieldP({field:a,label:"Job Id",isNullable:false,minValue:1,suppressErrorMessage:true});if(!h&&!i){showErrorMessageAndFocus("Job Id and Hubspot Company Id cannot both be empty","Error saving database",a,{subdialog:1});return false}if(c&&!b.CSValidateNumberField(c,"Discount %",true)){return}var j={databaseId:d,subdomain:trim(f.txtSubdomain.value),jobId:trim(a.value),hubspotCompanyId:i,notes:e,discountPercent:c?trim(c.value):"",taxRateId:m,suppressAutoAddBillingUsers:f.chkSuppressAutoAdd.checked?1:0};jsrsExecuteWithErrorP("Admin2_UpdateDatabase",refreshPageAndScrollPos,"Updating Database",j)}var dateFormatString="M/d/yyyy";function showEditDatabaseDialogGivenObject(j,a){var i=j.id,p=j.discountPct,f=j.taxRateId,o=j.arrTaxRates,c=j.addressState,g=j.taxRateState,n=a.originalPayload.taxLookupAllowedForState,m=j.customerId?"txtSubdomain":"txtCustomerName",e="frmEditDatabase",h=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),r=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARUpdate),k=h?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Database",doubleQuoteEncodedOnClickJS:"hideDialog();confirmDeleteDatabase("+i+")"}):null,l=r&&n?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiCheck,doubleQuoteEncodedTitle:"Lookup Tax Rate",doubleQuoteEncodedOnClickJS:"hideDialog();promptLookupTaxRate({ databaseId: "+i+" })",htmlContent:"Tax"}):null,b=[k,cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiMoveTo,doubleQuoteEncodedTitle:"Assign To Other Customer",doubleQuoteEncodedOnClickJS:"hideDialogP({callback:function(){showAssignDBToCustomerDialog("+i+","+(j.customerId?j.customerId:"null")+")}});"}),l],d=new ClientDialogBuilder({formId:e,formTitle:"Edit Database",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitEditDatabase()"}),focusFieldName:m,focusFieldOnMobile:1,arrExtraHeaderButtons:b,fnSubmit:submitEditDatabase}),q;if(!j.customerId){d.addTextFieldRow("txtCustomerName",{rawLabel:"Customer Name",autofocus:1})}d.addTextFieldRow("txtSubdomain",{rawLabel:"Subdomain Name",mnemonicChar:"b",fieldValue:j.subdomain});d.addTextFieldRow("txtJobId",{rawLabel:"Job Id",mnemonicChar:"j",fieldValue:(j.internalJobId?j.internalJobId:"")+"",maxLength:10,isNumber:1});d.addTextFieldRow("txtHubspotCompanyId",{rawLabel:"Hubspot Company Id",mnemonicChar:"h",fieldValue:(j.hubspotCompanyId?j.hubspotCompanyId:"")+""});buildTaxRateDropdownRow(d,o,f,g,c);d.addTextFieldRow("txtDiscountPct",{rawLabel:"Discount %",mnemonicChar:"u",fieldValue:""+(p||""),maxLength:10});d.addCheckboxRow("chkSuppressAutoAdd",{rawLabel:"Don't Automatically Add Additional Users To Billing",checked:j.suppressAutoAddBillingUsers});d.addExpandingTextFieldRows("txtNotes",{rawLabel:"Notes",mnemonicChar:"n",value:j.notes||""});q=d.showClientDialog();if(q){mjtElemData(q,"databaseId",i)}}function showEditDatabaseDialog(a){jsrsExecuteWithErrorP("Admin2_GetDatabaseInfo2",rsCallbackHandleStandardJSONResponse,"Getting Database Info for Edit",a,{fnOnSuccess:showEditDatabaseDialogGivenObject})}function rsCallbackSubmitCreateInstance(f,b){var h="frmCreateInstanceResults",a=f.deployedToServer,g=b.originalPayload.subdomain,e=b.originalPayload.instanceUrlPrefix,c=b.originalPayload.instanceUrlPostfix,d=e+g+c;var i=new ClientDialogBuilder({formId:h,formTitle:"New Instance Created",hideCancelButton:true,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"OK",mnemonicChar:"o",mnemonicActionJS:"refreshPageAndScrollPos"}),fnSubmit:refreshPageAndScrollPos});i.addFlexibleFieldRow({rawLabel:"New Instance Link",valueHTML:''+d+""});i.addFlexibleFieldRow({rawLabel:"Instance Created on Server",valueHTML:a});i.showClientDialog()}function submitCreateInstance(){var f="frmNewInstance",e=getObj(f),h=e.txtSubdomainName,a=e.cboCounterGo.value,d=e.cboNVInventory.value,g=e.cboSystemize.value,c=mjtElemData(e,"formElemData"),i=c.databaseId,b=new FormValidator();if(!b.CSValidateRequiredField(h,"Please enter a Subdomain Name")){return}jsrsExecuteWithErrorP("Admin2_CreateInstance",rsCallbackSubmitCreateInstance,"Creating Instance",{databaseId:i,subdomain:trim(h.value),cgUserCount:a,nvUserCount:d,sysUserCount:g,instanceUrlPrefix:c.instanceUrlPrefix,instanceUrlPostfix:c.instanceUrlPostfix})}function showCreateInstanceDialog(e,i,f,d){var g="frmNewInstance",a=new ClientDialogBuilder({formId:g,formTitle:"New Instance",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Create Instance",mnemonicChar:"c",mnemonicActionJS:"submitCreateInstance()"}),fnSubmit:submitCreateInstance}),b=[],c="";a.addTextFieldRow("txtSubdomainName",{rawLabel:"Subdomain Name",fieldValue:e,strPreFieldHTML:f,strPostFieldHTML:d,disabled:true});for(var h=1;h<11;++h){b.push({cboValue:h,rawContent:h+" User"+c})}a.addDropdown({labelHTML:"Systemize Users",fieldId:"cboSystemize",arrAvailableOptions:b,objNoneOption:{cboValue:"0",rawContent:"-None-"}});a.addDropdown({labelHTML:"CounterGo Users",fieldId:"cboCounterGo",arrAvailableOptions:b,objNoneOption:{cboValue:"0",rawContent:"-None-"}});a.addDropdown({labelHTML:"Inventory Users",fieldId:"cboNVInventory",arrAvailableOptions:b,objNoneOption:{cboValue:"0",rawContent:"-None-"}});a.showClientDialog({formElemData:{databaseId:i,instanceUrlPrefix:f,instanceUrlPostfix:d}})}function submitNewDatabase(){var j="frmNewDB",e=getObj(j),b=new FormValidator(),p=e.txtCustomerName,n=e.txtCustomerId,f=n?n.value:"",o=e.txtSubdomainName,d=e.taxRateIdSelect,l=e.taxRateId,c=mjtElemData(e,"address"),a=l?l.value:(d?d.value:""),i=e.cboSystemize.value,k=e.cboCounterGo.value==="1",m=e.cboNVInventory.value==="1",h=e.txtJobId?trim(e.txtJobId.value):"",g=e.txtHubspotCompanyId?trim(e.txtHubspotCompanyId.value):"";if(p&&!b.CSValidateRequiredField(p,"Please enter a Customer Name")){return}if(!b.CSValidateRequiredField(o,"Please enter a Subdomain Name")){return}if(d&&!a){showInfoDialog("Please select a tax rate.","Select Tax Rate",1,"taxRateIdSelect");return}if(a==="0"){a=""}jsrsExecuteWithErrorP("Admin2_CreateCustomerAndDatabase",rsCallbackHandleStandardJSONResponse,"Creating Database",{customerId:f,customerName:trim(p?p.value:""),subdomain:trim(o.value),address:c,jobId:h,hubspotCompanyId:g,taxRateId:a,includeCGProduct:k?1:0,includeNVProduct:m?1:0,sysEditionId:i},{fnOnSuccess:rsCallbackViewNewDatabase})}function showInvalidAddressDialog(a){var b=a.validationResults,c=htmlMultilineEncode(a.displayAddress||"");ClientDialogModule.showDialogWithConsequence({formTitle:"The Hubspot address is invalid",fnConstructDialog:function(d){var e=d.cdBuilder;e.addFlexibleFieldRow({rawLabel:"Address",valueHTML:c,additionalCellClasses:"clsNarrowField"});e.addFlexibleFieldRow({rawLabel:"Issue",rawValue:b.description,additionalCellClasses:"clsNarrowField"});e.addFlexibleFieldRow({rawLabel:"Details",valueHTML:b.detailHtml});e.addFlexibleFieldRow({rawLabel:b.tableLabel,valueHTML:b.tableHtml})}})}function rsCallbackGetHubspotInfoForNewDB(k){var f="frmNewDB",m=k.hubspotInfo||[],e=m.displayAddress,r=m.address,s=m.customerId,w=m.customerName,p=m.newDBTaxOptions,q=m.hubspotCompanyId,u=m.email,h=m.validationResults||"[]",b=JSON.parse(h),n,o,g=p.taxWarningMessage,l=p.webLinkToDetermineTaxRate,v=p.availableTaxRates,a=v?v.length:0,j=p.singleMatchedTaxCode,t=j?j.nameMatchingTaxCodeId:0,c="",i;if(!b.isValid){showInvalidAddressDialog({validationResults:b,displayAddress:e});return}var d=new ClientDialogBuilder({formId:f,formTitle:"New Database",focusFieldName:s?"txtSubdomainName":"txtCustomerName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitNewDatabase()"}),fnSubmit:submitNewDatabase});d.addFlexibleFieldRow({rawLabel:"Hubspot Company Id",valueHTML:q+''});d.addFlexibleFieldRow({rawLabel:"Address",valueHTML:htmlMultilineEncode(e||"")});d.addFlexibleFieldRow({rawLabel:"Email",rawValue:u});if(s){d.addFlexibleFieldRow({rawLabel:"Customer Name",valueHTML:htmlEncode(w)+''})}else{d.addTextFieldRow("txtCustomerName",{rawLabel:"Customer Name",fieldValue:w})}d.addTextFieldRow("txtSubdomainName",{rawLabel:"Subdomain Name",fieldValue:n,strPreFieldHTML:"https://",strPostFieldHTML:".moraware.net"});if(g){d.addFlexibleFieldRow({rawLabel:"",valueHTML:htmlMultilineEncode(g),additionalValueCellClasses:"errorText"})}if(a>1){c+='";if(j){if(t){c+='
On lookup, found matching tax code "'+htmlEncode(j.taxCodeName)+'"
with Rate='+j.taxRatePercent+"%
"}else{c+='
Required Tax Code: "'+htmlEncode(j.taxCodeName)+'" ('+j.taxRatePercent+"%)
"}}}else{if(a>0){c=htmlEncode(v[0].name)+''}else{c='(No Tax Required)'}}d.addFlexibleFieldRow({rawLabel:"Tax Rate",valueHTML:c});if(l){d.addFlexibleFieldRow({valueHTML:'Tax Rate Lookup'})}d.addSectionHeaderRow({rawTitle:"Order Products"});d.addFlexibleFieldRow({rawLabel:"CounterGo",valueHTML:''});d.addFlexibleFieldRow({rawLabel:"Inventory",valueHTML:''});d.addFlexibleFieldRow({rawLabel:"Systemize",valueHTML:'"});o=d.showClientDialog();if(o){mjtElemData(o,"address",r)}}function submitNewDatabaseFromHubspot(){var b="frmNewDBFromHubspot",e=getObj(b),d=e.txtCustomerId,a=e.txtHubspotCompanyId,c=!a.value;if(c){return false}jsrsExecuteWithErrorP("Admin2_GetHubspotCompanyInfo",rsCallbackGetHubspotInfoForNewDB,"Getting Hubspot Info",{hubspotCompanyId:trim(a.value),customerId:d?d.value:"",createMissingTaxCodeIfPossible:1})}function showNewDatabaseFromHubspotDialog(a,d){var c="frmNewDBFromHubspot",b=new ClientDialogBuilder({formId:c,formTitle:"New Database (Hubspot)",focusFieldName:"txtHubspotCompanyId",okButtonDisplayText:"Get Hubspot Company Info",fnSubmit:submitNewDatabaseFromHubspot});if(d&&a){b.addFlexibleFieldRow({rawLabel:"Customer",valueHTML:htmlEncode(d)+''})}b.addTextFieldRow("txtHubspotCompanyId",{rawLabel:"Hubspot Company Id"});b.showClientDialog()}function submitAssignDBToCustomer(a,d){var c=a.cboCustomer,b=c.options[c.selectedIndex].value;hideDialog();jsrsExecuteWithErrorP("Admin2_AssignDatabaseToCustomer2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Assigning Database to Customer",{databaseId:d.databaseId,customerId:b})}function rsCallbackCustomerNamesForDB(e,a,d){enableDialogButtons();if(checkResponseForError(e)){var c=JSON.parse(e),g=c.arrCustomers,f="",b,h;if(!g.length){showInfoDialog("There are no customers defined","No Customers");return}for(b=0;b"+htmlEncode(g[b].name)+""}showDialogP(cdBuildReadOnlyFieldRowP({rawLabel:"Customer",valueHTML:'"}),"frmAssignDBToCustomer",{formTitle:"Assign Database To Customer",focusFieldName:"cboCustomer",okButtonDisplayText:"Save",contextDetailOrFnSubmit:{fnSubmit:submitAssignDBToCustomer,callbackData:d}})}}function showAssignDBToCustomerDialog(b,a){if(isDialogShowing()){return}jsrsExecute(rsCallbackCustomerNamesForDB,"Admin_GetCustomerNames",[],enableDialogButtons,{databaseId:b,customerId:a});displayTimedMessage("Retrieving list of customers...");disableDialogButtons()}function submitAddOrUpdateDBProduct(m){var d=m.cboQty,f=m.cboProduct,l=f?f.options[f.selectedIndex].value:"",k=l?JSON.parse(unescape(l)):0,i=cdGetExpandingTextFieldValue("txtNotes"),c=new FormValidator(),e,j=mjtElemData(m,"databaseProductId"),n=mjtElemData(m,"databaseId"),h,b,a=null,g=(!j||!m.txtPrice||c.CSValidateNumberFieldP({field:m.txtPrice,label:"Price"}))&&c.CSValidateDateFieldP({field:m.dtStartDate,label:"Start Date",isNullable:true})&&c.CSValidateDateFieldP({field:m.dtEndDate,label:"End Date",isNullable:true});if(!g){return}if(m.priceGenerations){a=m.priceGenerations.options[m.priceGenerations.selectedIndex].value}else{if(k&&k.priceGenerationId){a=k.priceGenerationId}}h=getDateForUrlParam(m.dtStartDate.value);b=getDateForUrlParam(m.dtEndDate.value);if(h&&b&&parseDateString(b)'+h+""});o.addDialogInteriorRows(buildQuantityComboboxRow());o.addDatePickerRow(l,"dtStartDate",{rawLabel:"Start Date",strValue:k,suppressAutocomplete:1});o.addDatePickerRow(l,"dtEndDate",{rawLabel:"End Date",suppressAutocomplete:1});o.addExpandingTextFieldRows("txtNotes",{rawLabel:"Notes",suppressAutocomplete:1});g=o.showClientDialog();if(g){mjtElemData(g,"databaseId",c.originalPayload.databaseId)}}function createOrAddToErrorInfo(a,c,b){if(!a){a={errorMessageHTML:"",onDismissFocusFieldName:b}}else{a.errorMessageHTML+="
"}a.errorMessageHTML+=c;return a}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(b,e){var d=0;for(var c=0;c0||c>0;d.style.display=l?"":"none";if(l){i+=j;if(g||e){i+=" = ";if(b){i+=b}if(g){if(b){i+=" + "}i+=g+" on order"}if(e){if(b+g){if(k){i+=" - "}else{i+=" + "}}if(k){i+=(-e)+" cancelled users"}else{i+=e+" new users"}}}h.innerHTML=i}}function calculateAdditionalUserCost(j,i,e){var c=0,l=parseFloat(j.getAttribute("data-pricePer")),g=j.getAttribute("data-tier2StartUserCount"),a=j.getAttribute("data-tier2PerUserPrice");if(g&&a){var h=parseInt(g,10),d=parseFloat(a),f=e+i;if(f=(h-1)){d=c*e}else{if(i0;j.style.display=q?"":"none";a.innerHTML=""+r;k.setAttribute("max",r);if(isNaN(o)||o<0){k.className="invalidTextField";t=createOrAddToErrorInfo(t,'Invalid User Count "'+htmlEncode(y)+'"',k.name)}else{if(o>r){k.className="invalidTextField";t=createOrAddToErrorInfo(t,"You have exceeded the max number of users ("+r+") available to be cancelled.",k.name)}else{k.className="";if(o){s=v.item(l);c=getOriginalTotalUserCount(A,s);B+=calculateCancelledUserValue(u,c,o);w={productTypeId:l,userCount:o};n.push(w);f[s]=w}}}if(q&&m){m=0;var z=k;setTimeout(function(){setFocus(z)},0)}getObj("spnCostReduction").innerHTML=padAndPrefixSignedDollars((B),1);getObj("spnNewTotalCost").innerHTML=padAndPrefixSignedDollars((g-B),1)}updateAddRemoveUserDlgUserCountCell(A,f,"CG",1);updateAddRemoveUserDlgUserCountCell(A,f,"NV",1);updateAddRemoveUserDlgUserCountCell(A,f,"JT",1);updateAddRemoveUserDlgUserCountCell(A,f,"Sys",1);if(h&&t){showInfoDialog(t.errorMessageHTML,"Invalid User Count",1,t.onDismissFocusFieldName);return}return n}function submitCancelUsers(){var c=new FormValidator(),f=updateCancelUserDialogForCount(1),d="frmCancelUsers",e=getObj(d),b=getCallbackDataOfDialog(e),a=e.changeUserDate;if(!f){return}if(!f.length){showInfoDialog("You haven't indicated how many users to cancel.","No Cancelled Users",1,"txtAddUserCount.0");return}if(!c.CSValidateDateField(a,"Cancel Date",false,a.name)){return}jsrsExecuteWithErrorP("Admin2_CancelUsers",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Cancelling Users",{databaseId:b.databaseId,cancelDate:getDateForUrlParam(a.value),productTypeCounts:f})}function updateAddUserDialogForCount(e){var o,n,u=0,q,i,f,a,k,s=0,j=getObj("spnNewTotalCost"),r=mjtElemData(j,"userCountInfoForAddRemoveUsers"),c=getObj("spnAdditionalCost"),d=j.getAttribute("data-termName"),h=parseFloat(j.getAttribute("data-totalCurrentCost"))||0,t,g=[],p,b={},m=getMapCRMProductTypeToInfix(),l;while(true){o=getObj("txtAddUserCount."+u);if(!o){break}n=getObj("spnUserCountAddendum."+u);q=o.value||"0";i=parseInt(q,10);if(isNaN(i)||i<0||q.indexOf(".")>-1){o.className="invalidTextField";l=createOrAddToErrorInfo(l,'Invalid User Count "'+htmlEncode(q)+'"',o.name)}else{o.className="";if(i){f=parseInt(n.getAttribute("data-productTypeId"),10);k=m.item(f);a=getOriginalTotalUserCount(r,k);s+=calculateAdditionalUserCost(n,a,i);p={productTypeId:f,userCount:i};g.push(p);b[k]=p}}++u}t=h+s;c.innerHTML=padAndPrefixSignedDollars(s,1);j.innerHTML=padAndPrefixSignedDollars(t,1);updateAddRemoveUserDlgUserCountCell(r,b,"CG");updateAddRemoveUserDlgUserCountCell(r,b,"NV");updateAddRemoveUserDlgUserCountCell(r,b,"JT");updateAddRemoveUserDlgUserCountCell(r,b,"Sys");if(e&&l){showInfoDialog(l.errorMessageHTML,"Invalid User Count",1,l.onDismissFocusFieldName);return}return g}function submitAddUsers(a,c){var d=a.changeUserDate,b=new FormValidator(),e=updateAddUserDialogForCount(1);if(!e){return}if(!e.length){showInfoDialog("You haven't indicated how many users to add.","No New Users",1,"txtAddUserCount.0");return}if(!b.CSValidateDateFieldP({field:d,label:"Add Date"})){return}jsrsExecuteWithErrorP("Admin2_AddUsers",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Adding Users...",{arrProductTypeCounts:e,databaseId:c.databaseId,addDate:getDateForUrlParam(d.value)})}function getSelectedProductForUpgradeOrRollback(a,b){var c=getListOfCheckedRowValuesWithParams({form:a,buildRCArray:1,clientDlgParams:{subdialogDismisalFocusFieldName:"chkCheckAllRows",subdialog:1},fnTransformValueForArray:function(e){var f=unescape(e),d=JSON.parse(f);return d}}).arrValues;if(!(c&&c.length)){showInfoDialog("Please select the product to which you'd like to "+(b?"upgrade":"roll back")+".","No Product Selected",1);return}if(c.length>1){showInfoDialog("You can only select a single product when "+(b?"upgrading":"rolling back")+".",b?"Upgrade":"Rollback",1);return}return c[0]}function submitUpgradeProduct(){var b="upgradeForm",c=getObj(b),a=getSelectedProductForUpgradeOrRollback(c,1);if(!a){return}hideDialog();jsrsExecuteWithErrorP("Admin2_UpgradeProduct",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Upgrading Products",{productId:a.productId,databaseId:mjtElemData(c,"databaseId"),effectiveDate:c.upgradeDate.value,pricingStructureId:a.pricingStructureId})}function onSelectProduct(a){if(a.checked){a.parentNode.parentNode.style.backgroundColor="rgb(255, 255, 204)"}else{a.parentNode.parentNode.style.backgroundColor=null}}function getJobTrackerSystemizeEditionIncludedUserCount(a){return parseInt(a.includedUsers!==undefined?a.includedUsers:a.jtUserCount,10)}function getAdditionalUserCount(b){var a=parseInt(b.editionUsers?b.editionUsers.length:b.requiredAdditionalUsers,10);a=isNaN(a)?0:a;return a}function priceFromPriceGeneration(c){var a;if(c&&c.length>1){var b=c.indexOf("/");if(b>0){a=c.substring(1,b)}}return parseFloat(a)}function writeProductTable(h){var c=new MWClientTable({noDataMessage:"No products"}),f,d=0,b=h.arrProducts,e=h.includeCheckboxColumn,i=h.databaseId,a=h.selectedPricingStructure,g=h.pricingStructureProductId;b=b.filter(function(k,l,j){return !!k});c.addColumn(new MWColumn({columnName:"Name",fnCustomRenderCellContents:function(m,l,k,j){return htmlEncode(m.productName)}}));if(e){c.setCheckboxFunction(function(l,j,k){return{value:escape(JSON.stringify({databaseProductId:l.databaseProductId,productId:l.productId,disabled:l.disabled,pricingStructureId:l.productId===g?a.pricingStructureId:l.pricingStructureId})),checked:l.productId===g}})}c.addColumn(new MWColumn({columnName:"Base Price",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(n,m,l,k){var o,j=n.productTypeId!==undefined?n.productTypeId:n.productType;if(j===CRMProductType_Enum.crmptCounterGo||j===CRMProductType_Enum.crmptNVInventory){return""}if(n.isFlexPricing){if(a&&g===n.productId){o=a.editionPrice}else{o=n.editionPrice}}else{o=n.databaseProductPrice!==undefined?n.databaseProductPrice:n.price}return padAndPrefixSignedDollars(o,1)}}));c.addColumn(new MWColumn({columnName:"Included Users",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(n,m,l,k){var j=n.productTypeId!==undefined?n.productTypeId:n.productType;if(j===CRMProductType_Enum.crmptCounterGo||j===CRMProductType_Enum.crmptNVInventory){return""}return getJobTrackerSystemizeEditionIncludedUserCount(n)}}));c.addColumn(new MWColumn({columnName:"Additional Users",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(m,l,k,j){return getAdditionalUserCount(m)}}));c.addColumn(new MWColumn({columnName:"Price Per Additional User",fnCustomRenderCellContents:function(q,n,m,k){var l,j=q.tier2StartUserCount,p=q.tier2PerUserPrice;if(q.isFlexPricing){if(a&&g===parseInt(q.productId,10)){j=a.tier2StartUserCount;p=a.tier2PerUserPrice;l=parseFloat(a.additionalUserPrice)}else{l=parseFloat(q.additionalUserPrice)}}else{if(q.legacyProductPerUserPrice!==undefined){l=parseFloat(q.legacyProductPerUserPrice)}else{l=priceFromPriceGeneration(q.priceGenerationName)}}var o=isNaN(l)?"N/A":(padAndPrefixSignedDollars(l,1)+"/"+q.termName+"/User");if(j){o+=", "+padAndPrefixSignedDollars(p,1)+" for users "+j+"+"}return o}}));c.addColumn(new MWColumn({columnName:"Cost",fnCustomRenderCellContents:function(n,l,k,j){var m=n.totalCost;d+=m;return padAndPrefixSignedDollars(m,1)+" "+n.termName}}));if(e){c.addColumn(new MWColumn({columnName:"",fnCustomRenderCellContents:function(o,n,m,l){var k="";if(o.isFlexPricing){var j={databaseId:i,productId:o.productId,productTypeName:o.productTypeName,productTypeId:o.productTypeId,editionName:o.editionName,editionId:o.editionId};k=cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiUSD,doubleQuoteEncodedTitle:"Change Pricing",doubleQuoteEncodedOnClickJS:"doSelectPricingStructureDialog(JSON.parse(unescape('"+escape(JSON.stringify(j))+"')))"})}return k}}))}f=c.buildTableForArray(b);if((!e)&&b.length>1){f+='
Current Total: '+padAndPrefixSignedDollars(d,1)+"
"}return f}function toggleEnableAddProductUsers(a){var b=a.getAttribute("data-idxUserType"),c=getObj("txtAddUserCount."+b);c.disabled=false;a.style.display="none";setFocus(c)}function addRowsForUserTypesForAddUsersDialog(k,m,i,b,r,n,d,o,c){var a,q,l="changeUserDate",f,g,j,h="",e,p;for(q in m){a=m[q];j=htmlEncode(a.productName)+" Count";g=n&&a.productTypeName=="CounterGo"||o&&a.productTypeName=="Inventory"||c&&a.productTypeName=="Systemize";if(g){j='"}p=a.price?a.price:a.additionalUserPrice;f=padAndPrefixSignedDollars(p,1)+"/"+a.termName;if(a.tier2StartUserCount!==undefined&&a.tier2StartUserCount!==null){h='data-tier2StartUserCount="'+a.tier2StartUserCount+'" data-tier2PerUserPrice="'+a.tier2PerUserPrice+'" ';f+=", "+padAndPrefixSignedDollars(a.tier2PerUserPrice,1)+" for users "+a.tier2StartUserCount+"+"}k.addTextFieldRow("txtAddUserCount."+q,{fieldId:"txtAddUserCount."+q,isNumber:1,minValue:1,maxValue:999,disabled:g,suppressAutocomplete:1,autofocus:(!e)&&!g,labelHTML:j,onChangeCode:"updateAddUserDialogForCount()",strPostFieldHTML:' '+f+""});if((!g)&&!e){e=1;if(d){d.focusFieldName="txtAddUserCount."+q}}}if(b){k.addFlexibleFieldRow({rawLabel:"Add Date",valueHTML:''})}else{k.addDatePickerRow(k.getFormId(),l,{rawLabel:"Add Date",strValue:getDateAsDisplayString(new Date())})}}function copyPricingStructureDetails(a,b){a.editionPrice=b.editionPrice;a.additionalUserPrice=b.additionalUserPrice;a.tier2StartUserCount=b.tier2StartUserCount;a.tier2PerUserPrice=b.tier2PerUserPrice}function rsCallbackGetProductsForAddUser(l){var c=l.totalSystemizeCost,h=l.totalCounterGoCost,v=l.totalNVInventoryCost,d=l.activeCounterGoUsers,k=l.activeNVInventoryUsers,u=l.activeSystemizeUsers,y=l.availableUserProducts,g=l.termName,x=l.databaseId,w=l.orderDate,a=h+v+c,n=l.userCountInfoForAddRemoveUsers,q=l.counterGoUserProduct,s=l.nvInventoryUserProduct,m=l.activeSystemizeProduct,e=n.onOrderJTUserCount||n.onOrderCGUserCount||n.onOrderNVUserCount||n.onOrderSysUserCount,j="changeUserForm",r=1,p=1,o=1,b={focusFieldName:"txtAddUserCount.0"},f=new ClientDialogBuilder({formId:j,formTitle:"Add Users",okButtonDisplayText:"Add Users",fnSubmit:submitAddUsers,suppressDialogConfirmer:1,callbackData:{databaseId:x}});for(var t in y){if(y[t].productTypeName==="CounterGo"){y[t].activeUsers=d;if(d&&d.length){r=0;copyPricingStructureDetails(y[t],q)}}else{if(y[t].productTypeName==="Inventory"){y[t].activeUsers=k;if(k&&k.length){p=0;copyPricingStructureDetails(y[t],s)}}else{if(y[t].productTypeName==="Systemize"){y[t].activeUsers=u;if(u&&u.length){o=0;copyPricingStructureDetails(y[t],m)}}}}}addRowsForUserTypesForAddUsersDialog(f,y,h+v+c,w,a,r,b,p,o);f.setFocusFieldName(b.focusFieldName);f.addSectionHeaderRow({rawTitle:"New Totals"});f.addFlexibleFieldRow({rawLabel:"CounterGo Users",valueCellId:"cellCGUserTotalCount",rowId:"rowCGUserTotalCount"});f.addFlexibleFieldRow({rawLabel:"Inventory Users",valueCellId:"cellNVUserTotalCount",rowId:"rowNVUserTotalCount"});f.addFlexibleFieldRow({rawLabel:"JobTracker Users",valueCellId:"cellJTUserTotalCount",rowId:"rowJTUserTotalCount"});f.addFlexibleFieldRow({rawLabel:"Systemize Users",valueCellId:"cellSysUserTotalCount",rowId:"rowSysUserTotalCount"});f.addFlexibleFieldRow({rawLabel:"Additional "+g+" Cost",valueHTML:'$0.00'});f.addFlexibleFieldRow({rawLabel:"New Total ("+g+")",valueHTML:''+padAndPrefixSignedDollars(a,1)+""+(e?(' (+ on order total)'):"")});f.showClientDialog();mjtElemData(getObj("spnNewTotalCost"),"userCountInfoForAddRemoveUsers",n);updateAddUserDialogForCount()}function rsCallbackGetProductsForCancelUsers(o,d){var k="frmCancelUsers",y=o.databaseId,c=d.originalOptions,B=o.availableUserProducts,j=o.totalCounterGoCost,w=o.totalNVInventoryCost,A=o.totalSystemizeCost,q=o.userCountInfoForAddRemoveUsers,e=o.activeCounterGoUsers,m=o.activeNVInventoryUsers,u=o.activeSystemizeUsers,r=c.defaultJTUserCount,b=c.defaultCGUserCount,s=c.defaultNVUserCount,x,l,p,f=new ClientDialogBuilder({formId:k,formTitle:"Cancel Users",okButtonDisplayText:"Cancel Users",focusFieldName:"txtCancelUserCount.0",suppressDialogConfirmer:1,fnSubmit:submitCancelUsers,callbackData:{databaseId:y}}),g=o.termName,a,h=j+w+A,t,z=new Date();c=c||{};z.setDate(z.getDate()-1);for(t=0;t)',rowId:"rowCancelUserCount."+t,onChangeCode:"updateCancelUserDialogForCount()",autofocus:!t,strPostFieldHTML:' '+l+""})}f.addSectionHeaderRow({rawTitle:"New Totals"});f.addFlexibleFieldRow({rawLabel:g+" Cost Reduction",valueHTML:'$0.00'});f.addFlexibleFieldRow({rawLabel:"New Total ("+g+")",valueHTML:''+padAndPrefixSignedDollars(h,1)+""});f.addFlexibleFieldRow({rawLabel:"CounterGo Users",valueCellId:"cellCGUserTotalCount",rowId:"rowCGUserTotalCount"});f.addFlexibleFieldRow({rawLabel:"Inventory Users",valueCellId:"cellNVUserTotalCount",rowId:"rowNVUserTotalCount"});f.addFlexibleFieldRow({rawLabel:"JobTracker Users",valueCellId:"cellJTUserTotalCount",rowId:"rowJTUserTotalCount"});f.addFlexibleFieldRow({rawLabel:"Systemize Users",valueCellId:"cellSysUserTotalCount",rowId:"rowSysUserTotalCount"});for(t=0;t[Next Invoice Date]"}return c}function calculateProductTotalCost(i){var b=i.editionPrice,d=i.editionUserCount,a=i.tier1PerUserPrice,g=i.tier2PerUserPrice,k=i.tier2StartUserCount,e=i.additionalUserCount,j=(d||0)+e,c,h,f=0;if(b){f+=b}if(k&&k<=j){h=j-k+1;c=e-h}else{h=0;c=e}if(a&&c>0){f+=a*c}if(g&&h>0){f+=g*h}return f}function rsCallbackGetProductsForDBForUpgradeProducts(o,C){var j=o.databaseId,M=o.activeDatabaseProducts,D=o.activeEditionInstanceManagerUsers,J=o.activeEditionInstanceManagerExternalUsers,h=o.activeEditionInstanceManagerShopUsers,K=o.activeEditionDatabaseProduct,L=o.selectedPricingStructure,y=C.originalPayload.pricingStructureProductId,A=C.originalPayload.upgradeEffectiveDate,g=o.upgradeProducts,E=o.activeCounterGoUsers,u=E?E.length:0,I=o.activeNVInventoryUsers,p=I?I.length:0,r=o.activeSystemizeUsers,f=r?r.length:0,b=!K&&f>0,z=o.nextInvoiceDate,k="upgradeForm",w=new ClientDialogBuilder({formId:k,formTitle:"Upgrade",okButtonDisplayText:"Upgrade"}),G,q=function(O){var N=O.product,Q=O.productUserCount,P=O.perUserPrice,i=O.tier2StartUserCount!==undefined?O.tier2StartUserCount:N.tier2StartUserCount,R=O.tier2PerUserPrice!==undefined?O.tier2PerUserPrice:N.tier2PerUserPrice;N.requiredAdditionalUsers=Q;if(P===undefined){if(N.isFlexPricing){P=N.additionalUserPrice}else{if(N.legacyProductPerUserPrice!==undefined){P=N.legacyProductPerUserPrice}else{P=priceFromPriceGeneration(N.priceGenerationName)}}}N.totalCost=calculateProductTotalCost({editionPrice:N.editionPrice,editionUserCount:0,tier1PerUserPrice:P,tier2PerUserPrice:R,tier2StartUserCount:i,additionalUserCount:Q})};if(M.length>0){w.addSectionHeaderRow({rawTitle:"Current Products"});for(var H=0;H0){for(H=0;H(K.includedUsers+K.editionUsers.length)){s=true}}}}var m={arrProducts:g,includeCheckboxColumn:"upgrade",databaseId:j,selectedPricingStructure:L,pricingStructureProductId:y};w.addFlexibleRow({valueHTML:writeProductTable(m)});var l="upgradeDate";var F={nextInvoiceDate:z,formId:k,dateFieldId:l};var n=getNextInvoiceDateLink(F);var a=A?A:getDateAsDisplayString(new Date());w.addFlexibleFieldRow({rawLabel:"Upgrade Effective Date",valueHTML:cdBuildDatePickerField(k,l,a)+n});w.setFnSubmit(submitUpgradeProduct);w.setFormFieldFocusName("ChkRow0")}else{w.addFlexibleRow({valueHTML:'
There are no products to which you may upgrade.
'})}if(s){w.addFlexibleRow({valueHTML:'
Warning - Active user count from instance manager is '+D+" but current active edition users are "+(K.includedUsers+K.editionUsers.length)+(t>0?(", external users are "+t):"")+(e>0?(", shop users are "+e):"")+". Upgrading will result in billing for "+(D+t+e)+" users.
"})}}else{w.addFlexibleRow({rawValue:'There are no active "Edition" products to be upgraded.',additionalCellClasses:"dlgErrorPanel"})}G=w.showClientDialog();if(G){mjtElemData(G,"databaseId",j)}}function showUpgradeDialog(a){jsrsExecuteWithErrorP("Admin2_GetProductsForUpgrade",rsCallbackHandleStandardJSONResponse,"Getting upgrade information...",{databaseId:a.databaseId,pricingStructureProductId:a.pricingStructureProductId,pricingStructureId:a.pricingStructureId,upgradeEffectiveDate:a.upgradeEffectiveDate},{fnOnSuccess:rsCallbackGetProductsForDBForUpgradeProducts})}function enableDisableOpenOrderDialog(b){var c=getObj("frmOpenOrder"),a=c?c.parentNode:0;if(a){if(b){enableDialogButtonsOfDialog(a)}else{disableDialogButtonsOfDialog(a)}}}function disableOpenOrderDialog(){enableDisableOpenOrderDialog(0)}function enableOpenOrderDialog(){enableDisableOpenOrderDialog(1)}function doCancelOrder(a){jsrsExecuteWithErrorP("Admin2_CancelProductOrder2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Cancelling Order",{productOrderId:a.productOrderId});disableOpenOrderDialog()}function showCancelUserDialog(b,d,c,a){jsrsExecuteWithErrorP("Admin2_GetProductsForCancelUser",rsCallbackGetProductsForCancelUsers,"Getting cancel user information...",{databaseId:b},{defaultJTUserCount:d,defaultCGUserCount:c,defaultNVUserCount:a})}function showAddUserDialog(a){jsrsExecuteWithErrorP("Admin2_GetProductsForAddUser",rsCallbackHandleStandardJSONResponse,"Getting add user information...",{databaseId:a},{fnOnSuccess:rsCallbackGetProductsForAddUser})}function submitAddAdditionalUsersToDB(){var b="frmAddAdditionalUsersToDB",c=getObj(b),a=mjtElemData(c,"addAdditionalUserInfo");hideDialog();jsrsExecuteWithErrorP("Admin2_AddAdditionalUsersToDB",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Adding and invoicing Additional Users",a)}function buildAddUserTotalRow(b){var c=b.cdBuilder,e=b.userTypeName,f=b.initialCount,d=b.additionalCount,a;if(f+d){if(d){a=''+(f+d)+" = "+f+" + "+d+" New User"+(d===1?"":"s")}else{a=""+f}c.addFlexibleFieldRow({rawLabel:e+" Users",valueHTML:a})}}function rsCallbackGetInfoForAddAdditionalUsersToDB(k,c){var b=c.originalOptions,l=b.suppressAutoAddBillingUsers,h="frmAddAdditionalUsersToDB",v,a=k.productOrderId,r={productOrderId:a},g=new ClientDialogBuilder({formId:h,formTitle:"Add Additional Users",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Create Invoice",mnemonicChar:"c",mnemonicActionJS:"submitAddAdditionalUsersToDB()"}),fnSubmit:submitAddAdditionalUsersToDB,fnCancelOrClose:function(){doCancelOrder(r)}}),n=k.additionalJTUserCount,t=k.additionalCGUserCount,x=k.additionalNVUserCount,e=k.currentBillingCGUserCount,i=k.currentBillingNVUserCount,p=k.currentBillingJTSysUserCount,u=k.arrAdditionalUsers,j=k.initialProrateTotalTaxedAmountDetail,o=k.ongoingTotalTaxedAmountDetail,f=k.zeroOutProrate,d=k.zeroOutProrateMessage,s,w=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})]}),q=[];g.addFlexibleFieldRow({rawLabel:"Database",rawValue:k.subdomainName});g.addFlexibleFieldRow({rawLabel:"Order Start Date",rawValue:k.orderStartDate,additionalCellClasses:"clsNarrowField"});g.addFlexibleFieldRow({rawLabel:"First Term End Date",rawValue:k.firstTermEndDate});if(l){g.addBubbleMessageRow({rawMessage:'This Database has been marked "Don\'t Automatically Add Additional Users To Billing"',isError:1})}if(u){for(s in u){var m=u[s];q.push({quantity:m.quantity,productName:m.productName,unitPrice:padAndPrefixSignedDollars(m.unitPrice,1),totalPrice:padAndPrefixSignedDollars(m.totalPrice,1),proratedUnitPrice:padAndPrefixSignedDollars(m.proratedUnitPrice,1),initialTermTotalPrice:padAndPrefixSignedDollars(m.initialTermTotalPrice,1),notes:m.notes})}}g.addSectionHeaderRow({rawTitle:t+x+n==1?"Additional User":"Additional Users"});g.addFlexibleRow({valueHTML:w.buildTableForArray(q)});g.addSectionHeaderRow({rawTitle:"New Totals"});if(f){g.addBubbleMessageRow({rawMessage:htmlEncode(d)})}g.addFlexibleFieldRow({rawLabel:"Initial Prorated Total",valueHTML:htmlEncode(j.formattedTotalString)+(j.supplementalTaxBreakdownHint?'
'+htmlEncode(j.supplementalTaxBreakdownHint)+"":""),additionalCellClasses:"topAlign"});g.addFlexibleFieldRow({rawLabel:"Ongoing Additional Monthly Amount",valueHTML:htmlEncode(o.formattedTotalString)+(o.supplementalTaxBreakdownHint?'
'+htmlEncode(o.supplementalTaxBreakdownHint)+"":""),additionalCellClasses:"topAlign"});buildAddUserTotalRow({cdBuilder:g,userTypeName:"CounterGo",initialCount:e,additionalCount:t});buildAddUserTotalRow({cdBuilder:g,userTypeName:"Inventory",initialCount:i,additionalCount:x});buildAddUserTotalRow({cdBuilder:g,userTypeName:"Systemize",initialCount:p,additionalCount:n});v=g.showClientDialog();if(v){mjtElemData(v,"addAdditionalUserInfo",{productOrderId:a})}}function showAddAdditionalUsersToDBDialog(a){jsrsExecuteWithErrorP("Admin2_GetInfoForAddAdditionalUsersToDB",rsCallbackHandleStandardJSONResponse,"Getting Additional User Info...",{databaseId:a.databaseId||"",metricBatchId:a.metricBatchId,additionalCGUserCount:a.additionalCGUserCount||0,additionalNVUserCount:a.additionalNVUserCount||0,additionalJTUserCount:a.additionalJTUserCount||0,expectedActiveCGUserCount:a.activeCGUserCount,expectedActiveNVUserCount:a.activeNVUserCount,expectedActiveJTUserCount:a.activeJTUserCount,expectedBillingCGUserCount:a.billingCGUserCount,expectedBillingNVUserCount:a.billingNVUserCount,expectedBillingJTUserCount:a.billingJTUserCount},{fnOnSuccess:rsCallbackGetInfoForAddAdditionalUsersToDB,suppressAutoAddBillingUsers:a.suppressAutoAddBillingUsers,systemizeOrJobTracker:a.systemizeOrJobTracker})}function submitAddAdditionalStorageToDB(){var b="frmAddAdditionalStorageToDB",c=getObj(b),a=mjtElemData(c,"addAdditionalStorageInfo");hideDialog();jsrsExecuteWithErrorP("Admin2_CompleteOrder2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Adding and invoicing Additional Storage",a)}function rsCallbackGetInfoForAddAdditionalStorageToDB(d,b){var g="frmAddAdditionalStorageToDB",e=d.productOrderId,h={productOrderId:e},a=d.initialProrateTotalTaxedAmountDetail,f=d.ongoingTotalTaxedAmountDetail,i=new ClientDialogBuilder({formId:g,formTitle:"Add Additional Storage",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Create Invoice",mnemonicChar:"c",mnemonicActionJS:"submitAddAdditionalStorageToDB()"}),fnSubmit:submitAddAdditionalStorageToDB,fnCancelOrClose:function(){doCancelOrder(h)}}),k=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})]}),j=[];if(d.order){var c=d.order;j.push({quantity:c.quantity,productName:c.productName,unitPrice:padAndPrefixSignedDollars(c.unitPrice,1),totalPrice:padAndPrefixSignedDollars(c.totalPrice,1),proratedUnitPrice:padAndPrefixSignedDollars(c.initialTermUnitPrice,1),initialTermTotalPrice:padAndPrefixSignedDollars(c.initialTermTotalPrice,1),notes:c.notes})}i.addFlexibleFieldRow({rawLabel:"Database",rawValue:d.subdomainName});i.addFlexibleFieldRow({rawLabel:"Order Start Date",rawValue:d.formattedOrderStartDate,additionalCellClasses:"clsNarrowField"});i.addFlexibleFieldRow({rawLabel:"First Term End Date",rawValue:d.formattedFirstTermEndDate});i.addSectionHeaderRow({rawTitle:"Additional Storage"});i.addFlexibleRow({valueHTML:k.buildTableForArray(j)});i.addSectionHeaderRow({rawTitle:"New Totals"});i.addFlexibleFieldRow({rawLabel:"Initial Prorated Total",valueHTML:htmlEncode(a.formattedTotalString)+(a.supplementalTaxBreakdownHint?'
'+htmlEncode(a.supplementalTaxBreakdownHint)+"":""),additionalCellClasses:"topAlign"});i.addFlexibleFieldRow({rawLabel:"Ongoing Additional Monthly Amount",valueHTML:htmlEncode(f.formattedTotalString)+(f.supplementalTaxBreakdownHint?'
'+htmlEncode(f.supplementalTaxBreakdownHint)+"":""),additionalCellClasses:"topAlign"});i.showClientDialog({formElemData:{addAdditionalStorageInfo:{productOrderId:e}}})}function showAddAdditionalStorageToDBDialog(a){jsrsExecuteWithErrorP("Admin2_CreateProductOrderToAddAdditionalStorage",rsCallbackHandleStandardJSONResponse,"Getting Additional Storage Info...",{databaseId:a.databaseId||"",additionalStorageInMb:a.additionalStorageInMb,totalProductFileSizeInMb:a.totalProductFileSizeInMb},{fnOnSuccess:rsCallbackGetInfoForAddAdditionalStorageToDB})}function rsCallbackDisplayAddStorageToInstancesResults(f){hideDialog();var g=f.results||[],b=g.length,c=f.instancesWithProductOrders,i=f.instancesWithInvoices,h="frmShowResultsOfAddingStorageToInstances",a=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:h,formTitle:"Add Storage to Instances",fnCancelOrClose:function(){hideDialog();refreshPageAndScrollPos()}}),e=new MWClientTable({});a.addFlexibleFieldRow({rawLabel:"Instances",rawValue:""+b});a.addFlexibleFieldRow({rawLabel:"Product Orders (Created)",rawValue:""+c});a.addFlexibleFieldRow({rawLabel:"Invoices (Created)",rawValue:""+i});a.addSectionHeaderRow({rawTitle:"Instances"});e.addColumn(new MWColumn({columnName:"Customer",fnCustomRenderCellContents:function(m,l,k,j){return htmlEncode(m.instance.customerName)}}));e.addColumn(new MWColumn({columnName:"Database",fnCustomRenderCellContents:function(m,l,k,j){return htmlEncode(m.instance.subdomain)},fnBuildCellLinkDetail:function(m,k,j,l){return mwBuildSimpleLink(pageDatabaseDetail+m.instance.databaseId,1)}}));e.addColumn(new MWColumn({columnName:"Product Order Prorated Total",fnCustomRenderCellContents:function(m,l,k,j){return padAndPrefixSignedDollarsP({dollarValue:m.productOrderProratedTotal,forceDecimalsWhenNone:1})}}));e.addColumn(new MWColumn({columnName:"Status",fnCustomRenderCellContents:function(n,l,k,j){var m="Could not create Product Order";if(n.createdInvoices){m="Success"}else{if(n.createdProductOrders){m="Product Order Created but not Invoiced"}}return m}}));e.addColumn(new MWColumn({columnName:"Status Message",simpleDisplayColumnPropertyName:"statusMessage",simpleDisplayColumnNeedsMultilineEncoding:true}));var d=e.buildTableForArray(g);a.addFlexibleRow({valueHTML:d});a.showClientDialog()}function confirmedAddStorageToSpecificInstances(a,b){var e=getListOfCheckedRowValuesWithParams({form:a,buildRCArray:1,minSelected:1,tooFewWarning:"Please select an Instance",clientDlgParams:{subdialogDismisalFocusFieldName:"chkCheckAllRows",subdialog:1},unescapeValues:1,fnTransformValueForArray:function(f){return JSON.parse(f)}}),c=e.arrValues,d=e.selectedCount;if(!d){return}jsrsExecuteWithErrorP("Admin2_AddAdditionalStorageToInstances",rsCallbackHandleStandardJSONResponse,"Adding Additional Storage to Selected Instances",{arrInstancesWithStorageOverage:c},{fnOnSuccess:rsCallbackDisplayAddStorageToInstancesResults})}function rsCallbackGetInstancesWithStorageOverages(e){var i=e.instances||[],b=i.length,h="frmPromptAddStorageToInstances",a=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:h,formTitle:"Add Storage to Instances",focusFieldName:"btnOk",okButtonDisplayText:"Create Invoices",fnSubmit:confirmedAddStorageToSpecificInstances}),d=new MWClientTable({fnGetCheckDetailsForRow:function(l,j,k){return{value:htmlEncode(JSON.stringify(l))}}});if(!b){showInfoDialog("There are currently no instances with storage overages.","No Instances To Be Updated");return}a.addFlexibleFieldRow({rawLabel:"Instances with overages",rawValue:""+b});a.addSectionHeaderRow({rawTitle:"Instances To Update"});d.addColumn(new MWColumn({columnName:"Customer",simpleDisplayColumnPropertyName:"customerName"}));d.addColumn(new MWColumn({columnName:"Database",simpleDisplayColumnPropertyName:"subdomain",fnBuildCellLinkDetail:function(m,k,j,l){return mwBuildSimpleLink(pageDatabaseDetail+m.databaseId,1)}}));d.addColumn(new MWColumn({columnName:"Next Invoice Date",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(n,l,k,j){var m=new Date(n.nextInvoiceDate);return getLocalDateString(m)}}));var g=d.addColumn(new MWColumn({columnName:"Attached Files",additionalHeaderClasses:"centerAlign"}));g.addSubColumn(new MWColumn({columnName:"Overage",simpleDisplayColumnPropertyName:"formattedExcessAttachedFileAmount",additionalCellClasses:"rightAlign"}));g.addSubColumn(new MWColumn({columnName:"Monthly Usage",simpleDisplayColumnPropertyName:"formattedLastMonthsUploadAmount",additionalCellClasses:"rightAlign"}));var c=d.buildTableForArray(i);a.addFlexibleRow({valueHTML:c});var f=a.showClientDialog();if(f){f.chkCheckAllRows.checked=true;checkAllRows(f.chkCheckAllRows)}}function addStorageToJTInstances(){jsrsExecuteWithErrorP("Admin2_GetInstancesWithStorageOverages",rsCallbackGetInstancesWithStorageOverages,"Getting Instances With Storage Overages")}function showAddProductToDB(a){jsrsExecuteWithErrorP("Admin2_GetDatabaseProductOptions2",rsCallbackHandleStandardJSONResponse,"Getting database product to edit",{databaseId:a.databaseId},{fnOnSuccess:rsCallbackGetDatabaseProductOptions})}function doDeleteDBProduct(a){var b="Deleting Database Product";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteDatabaseProduct",[a.databaseProductId],rsErrorCallbackShowErrorDialogAndRefresh,{errorDialogTitle:"Error "+b},0,1);displayTimedMessage(b+"...");disableDialogButtons()}function rsCallbackImportExpenses(a){hideDialog();if(checkResponseForError(a)){var c=JSON.parse(a),b=new ClientDialogBuilder({formTitle:"Import Completed"}),d=new MWClientTable({arrColumns:[new MWColumn({columnName:"User",simpleDisplayColumnPropertyName:"cardMember"}),new MWColumn({columnName:"Description",simpleDisplayColumnPropertyName:"description"}),new MWColumn({columnName:"Amount",simpleDisplayColumnPropertyName:"amount",additionalCellClasses:"rightAlign"})]});b.addFlexibleFieldRow({rawLabel:"Expenses Retrieved From Amex",rawValue:""+c.expensesRetrievedFromAmex,additionalCellClasses:"clsNarrowField"});b.addFlexibleFieldRow({rawLabel:"New Expenses Added",rawValue:""+c.expensesAdded});b.addFlexibleFieldRow({rawLabel:"Expenses Filtered By Blocklist",rawValue:""+c.filteredOut.length});if(c.filteredOut.length>0){b.addFlexibleFieldRow({});b.addSectionHeaderRow({rawTitle:"Filtered Expenses"});b.addFlexibleRow({valueHTML:d.buildTableForArray(c.filteredOut)})}b.showClientDialog()}}function doImportExpenses(){var a="Importing Expenses...";jsrsExecute(rsCallbackImportExpenses,"Admin_ImportExpenses",[],rsErrorCallbackShowErrorDialogAndRefresh,{errorDialogTitle:"Error "+a},0,1);displayTimedMessage(a+"...");disableDialogButtons()}function confirmImportExpensesDialog(){displaySimpleConfirmationDialog(doImportExpenses,"Are you sure you want to import expenses?","Import Expenses",{})}function confirmDeleteDatabaseProduct(b,a,c){displaySimpleConfirmationDialog(doDeleteDBProduct,'Are you sure you want to delete "'+htmlEncode(c)+'"?',"Delete Database Product",{databaseProductId:a,productName:c})}function hideDialogAndEnableOpenOrderDialog(){hideDialog();enableOpenOrderDialog()}function rsCallbackGetOrderedProducts(d,g){enableOpenOrderDialog();var f=d,a=f.arrOrderedProducts,e=a?a.length:0,c=g.originalPayload,b={productOrderId:c.productOrderId};if(e){displaySimpleConfirmationDialog(doCancelOrder,"Are you sure you want to cancel this entire order for "+e+" product"+(e===1?"":"s")+"?
","Cancel Order",b,0,0,"Cancel Order",hideDialogAndEnableOpenOrderDialog);disableOpenOrderDialog()}else{doCancelOrder(b)}}function confirmCancelOrder(a){jsrsExecuteWithErrorP("Admin2_GetOrderedProducts2",rsCallbackHandleStandardJSONResponse,"Checking contents of order",{productOrderId:a},{fnOnSuccess:rsCallbackGetOrderedProducts});disableOpenOrderDialog()}function doCompleteOrder(a){jsrsExecuteWithErrorP("Admin2_CompleteOrder2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Completing Order",{productOrderId:a.productOrderId});disableOpenOrderDialog()}function completeOrder(b,c){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:c},0,0,"Complete Order",hideDialogAndEnableOpenOrderDialog);disableOpenOrderDialog()}function doZeroInitialProrate(a){jsrsExecuteWithErrorP("Admin2_ZeroOutProrate",refreshPageAndScrollPos,"Zeroing Out Prorate",{databaseId:a.databaseId})}function confirmZeroOutInitialProrate(b,a){displaySimpleConfirmationDialogP(doZeroInitialProrate,'Are you sure you want to zero out the Initial Prorated Total of "'+padAndPrefixSignedDollars(a)+'"?',{formTitle:"Zero Out Prorate",okButtonDisplayText:"Zero Prorate",contextDetail:{databaseId:b}})}function submitEditProductOrderItem(){var g=getObj("frmProductOrderItemDetails"),c=mjtElemData(g,"productOrderItemId"),a=new FormValidator(),f=g.txtPrice,d=cdGetExpandingTextFieldValue("txtNotes"),b=g.txtFirstPrice,e=(!f||a.CSValidateNumberField(f,"Price",false))&&a.CSValidateNumberField(b,"First Term Invoiced Price",false);if(!e){return}jsrsExecuteWithErrorP("Admin2_UpdateProductOrderItemDetails2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Item Details",{productOrderItemId:c,price:trim(f?f.value:""),notes:d,firstTermPrice:trim(b.value)})}function rsCallbackGetProductOrderItemDetailsForEdit(f){var j=f,i="frmProductOrderItemDetails",g,d=j.productName,a=j.id,n=j.basePrice,h=j.isFlexPricing,k="firstTermInvoicedPrice",m=j.hasOwnProperty(k),b=m?j[k]:"",e=j.notes,c=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),l=new ClientDialogBuilder({formId:i,formTitle:"Edit Order",focusFieldName:"txtFirstPrice",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitEditProductOrderItem()"}),arrExtraHeaderButtons:[c?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Order For '"+htmlEncode(d)+"'",doubleQuoteEncodedOnClickJS:"hideDialog();confirmDeleteProductOrderItem("+a+",unescape('"+escape(d)+"'))"}):null],fnSubmit:submitEditProductOrderItem});l.addFlexibleFieldRow({rawLabel:"Product",rawValue:d});l.addTextFieldRow("txtFirstPrice",{rawLabel:"First Term Invoiced Price ($)",fieldValue:padDollars(""+b),maxLength:8});if(!h){l.addTextFieldRow("txtPrice",{rawLabel:"Base Price ($)",fieldValue:padDollars(""+n),maxLength:8})}l.addExpandingTextFieldRows("txtNotes",{rawLabel:"Notes",value:e});g=l.showClientDialog();if(g){mjtElemData(g,"productOrderItemId",a)}}function showEditDBProductProductOrderItemDialog(a,b){jsrsExecuteWithErrorP("Admin2_GetProductOrderItemDetails2",rsCallbackHandleStandardJSONResponse,"Getting Order Item Details",{productOrderItemId:b},{fnOnSuccess:rsCallbackGetProductOrderItemDetailsForEdit})}function doDeleteProductOrderItem(a){jsrsExecuteWithErrorP("Admin2_DeleteProductOrderItem2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting order for "+a.productName,{productOrderItemId:a.productOrderItemId})}function confirmDeleteProductOrderItem(b,a){displaySimpleConfirmationDialog(doDeleteProductOrderItem,'Are you sure you want to delete the order for "'+htmlEncode(a)+'"?',"Delete Order",{productOrderItemId:b,productName:a})}function addSpecificProductAndQtyToOrder(b,a){jsrsExecuteWithErrorP("Admin2_AddProductToProductOrder2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Adding product to order",{productOrderId:b.productOrderId,productId:b.productId,pricingStructureId:b.pricingStructureId,quantity:a})}function submitAddSpecificProduct(){var d=getObj("frmAddProduct"),c=getCallbackDataOfDialog(d),b=d.cboQty,a=parseInt(b.options[b.selectedIndex].value,10);addSpecificProductAndQtyToOrder(c,a)}function rsCallbackGetProductDetailsForAddSpecificProduct(g,c){var d=c.originalPayload,e=g.arrProducts,b=e[0],h="frmAddProduct",f=b.termName,j=b.price,a=b.productTypeId===CRMProductType_Enum.crmptCounterGo?"":"$"+padDollars(j)+" "+htmlEncode(f),i=new ClientDialogBuilder({formId:h,formTitle:"Add Product",focusFieldName:"cboQty",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitAddSpecificProduct()"}),focusFieldOnMobile:1,fnSubmit:submitAddSpecificProduct,callbackData:{productOrderId:d.productOrderId,productId:d.productId}});i.addFlexibleFieldRow({rawLabel:"Product",rawValue:b.name});if(b.editionName){i.addFlexibleFieldRow({rawLabel:"Edition",rawValue:b.editionName})}i.addFlexibleFieldRow({rawLabel:"Base Price",rawValue:a});i.addFlexibleRow({valueHTML:"
"});i.addDialogInteriorRows(buildQuantityComboboxRow());i.showClientDialog()}function showAddSpecificProductToOrder(a){jsrsExecuteWithErrorP("Admin2_GetProductDetailsForAddToOrder2",rsCallbackHandleStandardJSONResponse,'Retrieving info for product, "'+a.productName,{productOrderId:a.productOrderId,productId:a.productId},{fnOnSuccess:rsCallbackGetProductDetailsForAddSpecificProduct})}function showAddSpecificProductCountSubmenu(d,c){var a=new ContextMenu(),b;a.AddMenuItemP({rawText:'Custom Quantity of "'+c.productName+'"',inactive:1,isHeader:1});for(b=2;b<=10;++b){a.AddMenuItemP({rawText:""+b,leadItemIconId:FontIconId_Enum.fiiPlusInCircle,doubleQuoteReadyScript:"addSpecificProductAndQtyToOrder("+htmlEncode(JSON.stringify(c))+","+b+")"})}a.AddSeparatorIfNecessary();a.AddMenuItemP({rawText:"...",doubleQuoteReadyScript:"showAddSpecificProductToOrder("+htmlEncode(JSON.stringify(c))+")"});a.ShowSubmenu(d)}function buildPricingInfoText(d){var b=d.price,h=d.editionPrice,c=d.additionalUserPrice,g=d.tier2PerUserPrice,f=d.tier2StartUserCount,e=[];if(h){e.push("$"+padDollars(h)+" Base")}if(c){var a=h?" per Additional User":" per User";e.push("$"+padDollars(c)+a)}if(f&&g){e.push("$"+padDollars(g)+" for Users "+f+"+")}if(e.length===0&&b){e.push("$"+padDollars(b))}return e.join(", ")}function buildProductPricingSuffix(b){var a=buildPricingInfoText(b),c="";if(a){c=" ("+a+")"}else{if(b.priceGenerationName){c=" - "+b.priceGenerationName}}return c}function buildRestartProductItemsForMenu(h){var b=h.restartProducts,e=h.productOrderId,j=[];for(var d=0;d",o=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),n=h.notes;if(l){q=b}else{q=b+' '}r=cdBuildReadOnlyFieldRowP({rawLabel:"Invoice Number",valueHTML:q})+cdBuildDatePickerRow(e,"dtInvoiceDate","Invoice Date",cdCarefullyLocalizeDateValue(h.invoiceDate?h.invoiceDate:p),k)+cdBuildDatePickerRow(e,"dtStartDate","Start Date",cdCarefullyLocalizeDateValue(c),k)+cdBuildDatePickerRow(e,"dtEndDate","End Date",cdCarefullyLocalizeDateValue(j),k);if(a){r+=cdBuildReadOnlyFieldRowP({rawLabel:"Tax Rate To Use",valueHTML:'"})+cdBuildReadOnlyFieldRowP({rawLabel:"",valueHTML:'(Invoice and Database Tax Rates Differ)'})+""}r+=cdBuildExpandingTextFieldRowsP("txtNotes","Notes",{value:n||""});showDialogP(r,e,{formTitle:l?"Edit Invoice":"New Invoice",focusFieldName:l?"txtInvoiceNumber":"dtInvoiceDate",arrExtraHeaderButtons:l&&o?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Invoice",doubleQuoteEncodedOnClickJS:"hideDialog();confirmDeleteInvoice(event,"+l+",unescape('"+escape(g)+"'))"})]:0,contextDetailOrFnSubmit:{fnSubmit:submitCreateOrUpdateInvoice,callbackData:{id:h.id,databaseId:h.databaseId,optionalAlternateTaxInfo:a}}});changedInvSpecType()}function rsCallbackGetInvoiceForEdit2(a){showInvoiceDialog(a.invoiceInfo,a.invoiceTaxRateDiffersFromDB?{dbTaxRateName:a.dbTaxRateName,dbTaxRateAmount:a.dbTaxRateAmount}:undefined)}function showCreateInvoiceDialog(b,a){jsrsExecuteWithErrorP("Admin2_GetDefaultInvoiceInfo2",rsCallbackGetInvoiceForEdit2,"Retrieving Database Info For New Invoice...",{databaseId:a})}function showEditInvoiceDialog(b,a){jsrsExecuteWithErrorP("Admin2_GetInvoiceInfo",rsCallbackGetInvoiceForEdit2,"Retrieving Invoice Info...",{invoiceId:a})}function doToggleShowOnHomepage(a){jsrsExecuteWithErrorP("Admin2_ToggleHideUnpaidInvoiceOnHomepage",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Toggling display on Homepage",{invoiceId:a.invoiceId,showOnHomepage:a.showOnHomepage})}function confirmToggleShowOnHomepage(a){hideDialogP({callback:function(){var b=a.showOnHomepage?"Show ":"Hide";displaySimpleConfirmationDialogP(function(){doToggleShowOnHomepage(a)},"Are you sure you want to "+b.toLowerCase()+" this invoice on the Homepage?",{formTitle:b+" Invoice On Homepage",okButtonDisplayText:b+" Invoice"})}})}function submitEmailInvoice(a,d){var b=d.invoice,c=new FormValidator();if(!c.CSValidateRequiredField(a.txtEmailFrom,'Please enter a sender name in the "From" field.')){return}if(!c.CSValidateRequiredField(a.txtEmailTo,'Please enter a recipient in the "To" field.')){return}if(!c.CSValidateRequiredField(a.txtEmailSubject,"Please enter a Subject.")){return}if(!c.CSValidateRequiredField(a.txtBillTo,"Please enter a Bill To value.")){return}jsrsExecuteWithErrorP("Admin2_EmailInvoiceToCustomer",refreshPageAndScrollPos,"Retrieving Invoice Info",{invoiceId:b.id,emailFromName:a.txtEmailFrom.value,customerEmailAddress:a.txtEmailTo.value,subject:a.txtEmailSubject.value,billTo:a.txtBillTo.value})}var g_invoiceChangeTimeout=null;function rsCallbackUpdateInvoicePreview(a){var b=getObj("cnrEmailInvoicePreview");if(b){b.innerHTML=a.preview}}function updateInvoicePreview(a){var c=getObj("frmEmailInvoice"),b=c?c.txtBillTo:null;g_invoiceChangeTimeout=null;if(b){jsrsExecuteWithErrorP("Admin2_GetEmailInvoiceInfo2",rsCallbackHandleStandardJSONResponse,"",{invoiceId:a,billTo:b.value,useDefaultBillTo:0},{fnOnSuccess:rsCallbackUpdateInvoicePreview,skipDisableDialogButtons:1,skipInfoMessage:1})}}function onChangeInvoicePreview(a){if(g_invoiceChangeTimeout){window.clearTimeout(g_invoiceChangeTimeout)}g_invoiceChangeTimeout=window.setTimeout(function(){updateInvoicePreview(a)},250)}function getInvoiceDateFormat(c){if(!c){return""}var b=c.getFullYear(),d=c.getMonth()+1,a=c.getDate();return b+"-"+(d<10?"0":"")+d+"-"+(a<10?"0":"")+a}function getInvDateRangeFromDates(a,e){var d=parseDateString(a),b=parseDateString(e),c=getInvoiceDateFormat(d)+" - "+getInvoiceDateFormat(b);return c}function showInvoicePreviewDialog(a){var e=a.invoice.id,d="frmEmailInvoice",b=getInvDateRangeFromDates(a.invoice.startDate,a.invoice.endDate),c=cdBuildTextFieldRowP("txtEmailFrom","Email From Name",{fieldValue:"Moraware Support"})+cdBuildTextFieldRowP("txtEmailTo","Email Invoice to",{fieldValue:a.customer.email||"",isEmail:1})+cdBuildTextFieldRowP("txtEmailSubject","Subject",{fieldValue:"Moraware Invoice for "+b,isEmail:1})+cdBuildTextAreaFieldRowP("txtBillTo","Bill To",{unencodedText:a.defaultBillTo,fieldId:"txtLicense",onChangeDoubleQuotedContent:"onChangeInvoicePreview("+e+")"})+'
Preview:'+a.preview+"";showDialogP(c,d,{formTitle:"Email Invoice",focusFieldName:"txtEmailTo",okButtonDisplayText:"Send Email",contextDetailOrFnSubmit:{fnSubmit:submitEmailInvoice,callbackData:a}})}function rsCallbackGetInvoiceForEmail(a){showInvoicePreviewDialog(a)}function showEmailInvoiceDialog(b,a){if(isDialogShowing()){return}jsrsExecuteWithErrorP("Admin2_GetEmailInvoiceInfo2",rsCallbackHandleStandardJSONResponse,"Retrieving Invoice Info",{invoiceId:a,billTo:"",useDefaultBillTo:1},{fnOnSuccess:rsCallbackGetInvoiceForEmail})}function rsCallbackDeleteInvoice(c){var a=c.databaseId,b=c.subdomainName;if(a){displayTimedMessage("Loading Database"+(b?(' "'+htmlEncode(b)+'"'):""));window.location=pageDatabaseDetail+a}else{refreshPageShowingMessage()}}function doDeleteInvoice(a){jsrsExecuteWithErrorP("Admin2_DeleteInvoice",rsCallbackDeleteInvoice,"Deleting Invoice",{invoiceId:a.invoiceId})}function confirmDeleteInvoice(c,b,a){displaySimpleConfirmationDialog(doDeleteInvoice,"Are you sure you want to delete Invoice #"+a+"?","Delete Invoice",{invoiceId:b,invoiceNumber:a})}function doGenerateInvoices(){jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_GenerateInvoices",[],enableDialogButtons);showInfoDialog("Generating invoices...","Generating Invoices");disableDialogButtons();displayTimedMessage("Generating Invoices...")}function submitGenerateNextInvoice(){var c="frmGenerateNextInvoice",d=getObj(c),b=mjtElemData(d,"databaseId"),a=mjtElemData(d,"nextInvoiceDate");hideDialog();jsrsExecuteWithErrorP("Admin2_GenerateNextInvoice2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Generating Next Invoice",{databaseId:b,nextInvoiceDate:a})}function rsCallbackGetNextInvoiceInfo(b){enableDialogButtons();var d="frmGenerateNextInvoice",a=b.displayedNextInvoiceDate,c=new ClientDialogBuilder({formId:d,formTitle:"Generate Next Invoice",focusFieldName:"btnOk",focusFieldOnMobile:1,fnSubmit:submitGenerateNextInvoice}),e;c.addFlexibleRow({rawValue:"This will generate invoices for the "+b.termName+" subscription up to and\nincluding the Next Invoice Date of "+a+".\n\nAre you sure you want to generate the next invoice?"});e=c.showClientDialog();if(e){mjtElemData(e,"databaseId",b.databaseId);mjtElemData(e,"nextInvoiceDate",b.nextInvoiceDate)}}function showGenerateNextInvoiceDialog(a){if(isDialogShowing()){return}jsrsExecuteWithErrorP("Admin2_GetNextInvoiceInfoForDB",rsCallbackGetNextInvoiceInfo,"Getting Next Invoice Info for Subscription",{databaseId:a})}function showSubscriptionExtraMenu(e){var c=e.arrMenuInfos,a,d,b=new ContextMenu();for(d=0;d'+a+""});h.addDatePickerRow(f,"dtNextInvoiceDate",{rawLabel:"Next Invoice Date",strValue:cdCarefullyLocalizeDateValue(e||"")});h.addTextFieldRow("txtQBId",{rawLabel:"QuickBooks Id",fieldValue:(g.qbId||"")+"",maxLength:209,hideRow:!i});c=h.showClientDialog();if(c){mjtElemData(c,"databaseId",i)}}function showEditSubscriptionDialog(a){jsrsExecuteWithErrorP("Admin2_GetSubscription",rsCallbackHandleStandardJSONResponse,"Retrieving Subscription For Edit",{databaseId:a},{fnOnSuccess:rsCallbackGetSubscriptionForEdit})}function rsCallbackGetSubscriptionForCreateOrder(b){var f=b,e="frmCreateOrder",d=new Date(),a=getDateAsDisplayString(d),c=new ClientDialogBuilder({formId:e,formTitle:"New Order",okButtonDisplayText:"Create",focusFieldName:"dtStartDate",focusFieldOnMobile:1,fnSubmit:submitCreateOrder}),g;c.addDatePickerRow(e,"dtStartDate",{rawLabel:"StartDate",strValue:a});c.addFlexibleFieldRow({rawLabel:"Billing Term",rawValue:f.termName});g=c.showClientDialog();if(g){mjtElemData(g,"subscription",f)}}function showCreateOrderDialog(a){jsrsExecuteWithErrorP("Admin2_GetSubscription",rsCallbackHandleStandardJSONResponse,"Retrieving Subscriptions",{databaseId:a},{fnOnSuccess:rsCallbackGetSubscriptionForCreateOrder,databaseId:a})}function rsCallbackCreatedPayment(a){hideDialog();window.location=pagePaymentDetail+a.paymentId}function getPaymentTransactionLabel(){var c=getObj("frmPayment"),a=c.cboPaymentMethod,b=a&&(a.options[a.selectedIndex].value==="Check");return b?"Check #":"Transaction Id"}function postTransIdValidationSubmitEditOrAddPayment(a){if(a.paymentId){jsrsExecuteWithErrorP("Admin2_UpdatePayment2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Payment",a)}else{jsrsExecuteWithErrorP("Admin2_CreatePayment2",rsCallbackCreatedPayment,"Creating Payment",a)}}function submitEditOrAddPayment(u,A){var h=new FormValidator(),v=A.id,t=A.forceDiscount,d=A.isChargeback,x=u.txtAmount,s=u.cboPaymentMethod,l=t?"Discount":s.options[s.selectedIndex].value,p=l==="Discount",g=A.creditMemoId||"",q=u.txtProcessor,B=v?q.value:"",n=u.txtTransactionId,k=p?"":trim(n.value),y=u.txtBillingProcessorCustomerId,C=(v||d)?y.value:"",f=u.cboPaymentType,i=d?PaymentType_Enum.ptCredit:(v?f.options[f.selectedIndex].value:(""+PaymentType_Enum.ptSale)),c=v?getDateForUrlParam(u.dtCardExpirationDate.value):"",r=v?u.txtCardDigits.value:"",b=cdGetExpandingTextFieldValue("txtComment1"),a=cdGetExpandingTextFieldValue("txtComment2"),j=l==="Check",z=l==="Wire Transfer",e=j?"Check #":"Transaction Id",D=!(p||j||z||d),m=(!k)&&((A.wasTransactionId||!v)&&(j||z||d)),w={};if(!h.CSValidateNumberFieldP({field:x,label:"Amount",isNullable:false,resultValueHolder:w})){return}if(!trim(l)){showInfoDialog("Please select a payment method.","Missing Payment Method",1,"cboPaymentMethod");return}if(v&&!h.CSValidateRequiredField(q,"Please enter a Payment Processor")){return}if(D&&!h.CSValidateRequiredField(n,"Please enter a "+getPaymentTransactionLabel())){return}var o={paymentId:v||"",amount:w.rc,paymentMethod:l,paymentProcessor:B,transactionId:k,billingProcessorCustomerId:C,paymentType:i,comment1:b,comment2:a,ccExpiration:c,ccDigits:r,creditMemoId:g,invoiceId:(g?"":A.invoiceId)||""};if(m){displaySimpleConfirmationDialog(postTransIdValidationSubmitEditOrAddPayment,"Are you sure you don't want to enter a "+e+"?","Omit "+e,o,1,"txtTransactionId");return}postTransIdValidationSubmitEditOrAddPayment(o)}function buildDBSelector(e,a){var d='"}function buildPaymentTypeDropdownRow(c){var b={},a='";return cdBuildReadOnlyFieldRowP({rawLabel:"Payment Type",valueHTML:a})}function updatePaymentTransactionLabel(){var a=getObj("spnPaymentTransactionLabel");if(a){a.innerHTML=getPaymentTransactionLabel()}}function buildPaymentMethodDropdownRow(c,b){var d={},a=''+htmlEncode(" "+h.creditMemoNumber)+""}}));if(b){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(g,f,e,d){return"$"+padDollars(g.totalDueToBeCredited,1,1)}}));a.addColumn(new MWColumn({columnName:"Total Uncredited",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(g,f,e,d){return"$"+padDollars(g.totalUncredited,1,1)}}));return''+a.buildTableForArray(c)+""}function asynchRefreshRBRowHighlights(){var f,b,d,c,g,a,e;for(f=0;true;++f){b=getObj("rbPaymentTarget"+f);if(!b){break}e=b.parentNode;while(e&&e.nodeName!="TR"){e=e.parentNode}if(e){c=e.className;g=c.indexOf(" highlightRow")>-1;if(b.checked&&!g){e.className=c+" highlightRow"}else{if(g&&!b.checked){e.className=c.replace(" highlightRow","")}}}}}var g_refreshRBRowsTimerId;function refreshRBRowHighlights(a){if(g_refreshRBRowsTimerId){clearTimeout(g_refreshRBRowsTimerId);g_refreshRBRowsTimerId=0}if(a){asynchRefreshRBRowHighlights()}else{g_refreshRBRowsTimerId=setTimeout(asynchRefreshRBRowHighlights,100)}}function buildUnmatchedPaymentSelectionRow(a){var b=new MWClientTable({noDataMessage:"No Payments!"});b.addColumn(new MWColumn({columnName:"Billing - Transaction Id",fnCustomRenderCellContents:function(h,g,f,e){var d={id:h.id,totalUncredited:h.totalUncredited},c="rbPaymentTarget"+e;return'"}}));b.addColumn(new MWColumn({columnName:"Comment1",simpleDisplayColumnPropertyName:"comment1"}));b.addColumn(new MWColumn({columnName:"Amount",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(f,e,d,c){return"$"+padDollars(f.amount,1,1)}}));b.addColumn(new MWColumn({columnName:"Unmatched Amount",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(f,e,d,c){return"$"+padDollars(f.unmatchedAmount,1)}}));return''+b.buildTableForArray(a)+""}function buildInvoiceSelectionRow(b,c){var a=new MWClientTable({noDataMessage:"No Invoices!"});a.addColumn(new MWColumn({columnName:"Invoice #",fnCustomRenderCellContents:function(i,g,f,e){var d="rbPaymentTarget"+e,h={id:i.id,totalUnpaid:i.totalUnpaid};return'"}}));if(c){a.addColumn(new MWColumn({columnName:"Customer Name",simpleDisplayColumnPropertyName:"customerName"}));a.addColumn(new MWColumn({columnName:"Database",simpleDisplayColumnPropertyName:"subdomain"}))}a.addColumn(new MWColumn({columnName:"Total Due",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(g,f,e,d){return"$"+padDollars(g.totalDue,1,1)}}));a.addColumn(new MWColumn({columnName:"Total Unpaid",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(g,f,e,d){return"$"+padDollars(g.totalUnpaid,1,1)}}));return''+a.buildTableForArray(b)+""}function rsCallbackGetInfoForApplyPayment(g,d){var k=g.payment,f=d.originalPayload,b=k.paymentTypeId,j=b==PaymentType_Enum.ptCredit,e=b==PaymentType_Enum.ptSale,i=g.arrUnpaidInvoices,n=g.arrUncreditedCreditMemos,h=g.arrUnmatchedSalePayments,m=k.availableAmount,c=f.applyCreditToPayment,l="frmApply",a=cdBuildReadOnlyFieldRowP({rawLabel:"Timestamp",rawValue:k.timestamp})+cdBuildReadOnlyFieldRowP({rawLabel:"Billing Id",rawValue:k.billingProcessorCustomerId})+cdBuildReadOnlyFieldRowP({rawLabel:"Payment Amount",rawValue:"$"+padDollars(k.amount,0,1)})+cdBuildReadOnlyFieldRowP({rawLabel:"Available Amount",rawValue:"$"+padDollars(m,0,1)});if(k.comment1){a+=cdBuildReadOnlyFieldRowP({rawLabel:"Comment 1",valueHTML:htmlMultilineEncode(k.comment1)})}if(k.comment2){a+=cdBuildReadOnlyFieldRowP({rawLabel:"Comment 2",valueHTML:htmlMultilineEncode(k.comment2)})}if(c){a+=buildUnmatchedPaymentSelectionRow(h)}else{if(e){a+=buildInvoiceSelectionRow(i,!f.databaseId)}else{if(j){a+=buildCreditMemoSelectionRow(n,!f.databaseId)}}}showDialogP(a,l,{formTitle:"Apply Payment",focusFieldName:"btnOk",okButtonDisplayText:"Save",contextDetailOrFnSubmit:{fnSubmit:submitApplyPaymentToDB,callbackData:{payment:k,isCredit:j?1:0,isSale:e?1:0,applyCreditToPayment:c}}});refreshRBRowHighlights()}function showApplyPaymentDialog(b,c,a){jsrsExecuteWithErrorP("Admin2_GetInfoForApplyPayment2",rsCallbackGetInfoForApplyPayment,"Retrieving Payment Info",{paymentId:b,databaseId:c||"",applyCreditToPayment:a?1:0})}function submitUpdatePaymentTimestamp(a,c){var d=a.dtTimestamp,b=new FormValidator();if(!b.CSValidateDateField(d,"Timestamp",false,"dtTimestamp")){return}jsrsExecuteWithErrorP("Admin2_UpdatePaymentTimestamp",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Payment Timestamp",{paymentId:c.paymentId,timeStamp:getDateForUrlParam(d.value)})}function rsCallbackGetInfoForEditPaymentTimestamp(b){var f="frmEditPaymentTS",a=b.timestamp,d=a.split(" ")[0],e=b.id,c=new ClientDialogBuilder({formId:f,formTitle:"Update Payment Timestamp",focusFieldName:"dtTimestamp",okButtonDisplayText:"Save",fnSubmit:submitUpdatePaymentTimestamp,callbackData:{paymentId:e}});c.addFlexibleFieldRow({rawLabel:"Original Timestamp",rawValue:b.timestamp});c.addDatePickerRow(f,"dtTimestamp",{rawLabel:"Timestamp",strValue:d});c.showClientDialog()}function showEditPaymentTimestampDialog(a){jsrsExecuteWithErrorP("Admin2_GetPaymentTimestamp2",rsCallbackHandleStandardJSONResponse,"Retrieving Payment Info",{paymentId:a},{fnOnSuccess:rsCallbackGetInfoForEditPaymentTimestamp})}function doDeletePaymentRefund(a){jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeletePaymentRefund",[a.paymentRefundId],enableDialogButtons);displayTimedMessage("Deleting Refund...");disableDialogButtons()}function confirmDeletePaymentRefund(b,a,c){displaySimpleConfirmationDialog(doDeletePaymentRefund,"Are you sure you want to delete this "+padAndPrefixSignedDollars(c,1)+" refund?","Delete Refund",{paymentRefundId:a})}function buildDialogRow(b,a,c){var d="";if(c){d=' style="text-align:'+c+'"'}return""+b+""+a+""}function buildDialogDoubleColumnRow(b,a){return"'+b+""}function buildDialogSeparatorRow(){return'
'}function rsCallbackImportFromPaymentProcessors(l,d){var i=d.originalOptions||{},m=l.arrNewOrUpdatedPayments,p=m.length,b=l.reportRecordCount,e=l.newSucessfulImportCount,k=l.newFailureCount,h=l.changedCount,j=l.unchangedCount,o=l.ignoredRecordCount,c=k+e+h+j+o,n="frmInfo",a=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:n,formTitle:"Payments Imported",fnCancelOrClose:function(){hideDialog();if(p||i.forceRefresh){refreshPageShowingMessage()}}});if(c){if(b!==c){a.addFlexibleRow({rawValue:'# of records in the Report doesn\'t match the # of payments found!'});a.addFlexibleFieldRow({rawLabel:"Total Records In Report",rawValue:""+l.reportRecordCount});a.addFlexibleRow({rawValue:"
"});if(e){a.addFlexibleFieldRow({rawLabel:"Successful",rawValue:""+e})}if(h){a.addFlexibleFieldRow({rawLabel:"Updated",rawValue:""+h})}if(j){a.addFlexibleFieldRow({rawLabel:"Unchanged",rawValue:""+j})}if(k){a.addFlexibleFieldRow({rawLabel:"Failed",rawValue:""+k})}if(o){a.addFlexibleFieldRow({rawLabel:"Ignored",rawValue:""+o})}a.addFlexibleFieldRow({rawLabel:"Total Payments Found",rawValue:""+c});a.addFlexibleRow({rawValue:"
"})}else{if(j===c){a.addFlexibleFieldRow({rawLabel:"Total Payments",rawValue:""+c+(j===c?" (Unchanged)":"")})}}if(e||k){if(e){a.addFlexibleFieldRow({rawLabel:"New (Successful) Imports",rawValue:""+e})}if(k){a.addFlexibleFieldRow({rawLabel:"New (Failed) Imports",rawValue:""+k})}}if(h){a.addFlexibleFieldRow({rawLabel:"Updated",rawValue:""+h})}if(o){a.addFlexibleFieldRow({rawLabel:"Imports Ignored Due To Result Code",rawValue:""+o})}if(p){a.addSectionHeaderRow({rawTitle:"New/Updated Payments"});var g=new MWClientTable({});g.addColumn(new MWColumn({columnName:"Transaction",simpleDisplayColumnPropertyName:"transactionId"}));g.addColumn(new MWColumn({columnName:"Timestamp",simpleDisplayColumnPropertyName:"timestamp"}));if(h){g.addColumn(new MWColumn({columnName:"Change/Discrepancy Description",simpleDisplayColumnPropertyName:"changeDescription",simpleDisplayColumnNeedsMultilineEncoding:1}))}g.addColumn(new MWColumn({columnName:"Amount",simpleDisplayColumnPropertyName:"amount",additionalCellClasses:"rightAlign",additionalHeaderClasses:"rightAlign"}));var f=g.addColumn(new MWColumn({columnName:"Credit Card",additionalHeaderClasses:"centerAlign"}));f.addSubColumn(new MWColumn({columnName:"Expires",simpleDisplayColumnPropertyName:"ccExp",additionalCellClasses:"rightAlign",additionalHeaderClasses:"rightAlign"}));f.addSubColumn(new MWColumn({columnName:"Digits",simpleDisplayColumnPropertyName:"ccDigits",additionalCellClasses:"rightAlign",additionalHeaderClasses:"rightAlign"}));g.addColumn(new MWColumn({columnName:"Method",simpleDisplayColumnPropertyName:"method",additionalCellClasses:"centerAlign",additionalHeaderClasses:"centerAlign"}));g.addColumn(new MWColumn({columnName:"Type",simpleDisplayColumnPropertyName:"type",additionalCellClasses:"centerAlign",additionalHeaderClasses:"centerAlign"}));g.addColumn(new MWColumn({columnName:"Result",simpleDisplayColumnPropertyName:"resultMessage",additionalCellClasses:"centerAlign",additionalHeaderClasses:"centerAlign",fnAdditionalCellClasses:function(t,r,q,s){if(t.resultCode){return"errorText"}return""}}));g.addColumn(new MWColumn({columnName:"Comment",simpleDisplayColumnPropertyName:"comment1",simpleDisplayColumnNeedsMultilineEncoding:1}));a.addFlexibleRow({valueHTML:g.buildTableForArray(m)})}}else{a.addFlexibleRow({rawValue:"No payments"})}hideDialog();a.showClientDialog()}function submitImportPaymentProcessorPayments(a,c){hideDialog();c=c||{};var b=new FormValidator(),f,e=c.useSpecificDate,d="";if(a&&e){f=a.dtDate;if(!b.CSValidateDateField(f,"Date",false,"dtDate")){return}d=getDateForUrlParam(f.value)}jsrsExecuteWithErrorP("Admin2_ImportFromPaymentProcessors",rsCallbackHandleStandardJSONResponse,"Importing Payments",{transactionDate:d},{fnOnSuccess:rsCallbackImportFromPaymentProcessors,forceRefresh:c.forceRefreshOnCancel})}function rsCallbackGeneratePaymentDates(a){if(!a.count){showInfoDialog("No payment dates were generated","Generate Payment Dates",0,null);return}var b=new ClientDialogBuilder({formId:"generatePaymentDates",formTitle:"Generate Payment Dates",focusFieldOnMobile:1,suppressDialogConfirmer:1,fnCancelOrClose:refreshPageAndScrollPos});b.addFlexibleFieldRow({rawLabel:"# of Generated Automated Payment Status Records",rawValue:""+a.count});b.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 a=new ClientDialogBuilder({formTitle:"Run Automated Payments",okButtonDisplayText:"Run",focusFieldName:"btnOk",fnSubmit:function(){hideDialog();jsrsExecuteWithErrorP("Admin2_RunAutomatedPayments",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Run Automated Payments")}});a.addFlexibleRow({valueHTML:"Are you sure you want to run automated payments?

(Payments will only be applied up through the Last Bulk Invoice Generation Date)
"});a.showClientDialog()}function promptGenerateInvoices(){var a=new ClientDialogBuilder({formTitle:"Generate Invoices",okButtonDisplayText:"Generate",focusFieldName:"btnOk",fnSubmit:function(){hideDialog();doGenerateInvoices()}});a.addFlexibleRow({valueHTML:"Are you sure you want to Generate Invoices?"});a.showClientDialog()}function rsCallbackSimulateGeneratePaymentDates(g){var e=g.initialValues,d=g.generationDates||"",b=g.arrAutopayStatusCounts,h=g.arrUpdatedDBDates,i=b?b.length:0,a,f,j=new ClientDialogBuilder({formTitle:"Simulated Payment Date Generation"}),c=new MWClientTable({fnAdditionalRowAttrs:function(k){return"data-rowData='"+escape(JSON.stringify(k))+"'"}});delete g.initialValues;delete g.generationDates;delete g.arrAutopayStatusCounts;delete g.arrUpdatedDBDates;c.addColumn(new MWColumn({columnName:"Database",simpleDisplayColumnPropertyName:"subdomainName",additionalHeaderClasses:"centerAlign",sortInfo:{},fnBuildCellLinkDetail:function(k){if(k.databaseId){return new MWCellLinkDetail({simpleLink:pageDatabaseDetail+k.databaseId,dialogLink:1})}return null}}));c.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:{}})]}));c.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:{}})]}));j.addSectionHeaderRow({rawTitle:"Generated Payment Dates"});j.addFlexibleRow({valueHTML:c.buildTableForArray(h)});j.addSectionHeaderRow({rawTitle:"Factors Considered During Generation"});j.addFlexibleFieldRow({rawLabel:"Min Minutes Between Autopay Attempts",rawValue:""+e.minMinutesBetweenAutopayAttempts,additionalCellClasses:"clsNarrowField"});j.addFlexibleFieldRow({rawLabel:"Last Invoice Generation",rawValue:e.lastInvoiceGenerationDate});j.addFlexibleFieldRow({rawLabel:"First Payment Date To Generate",rawValue:e.firstPaymentDateToGenerate});j.addFlexibleFieldRow({rawLabel:"Latest Date To Generate Payments For",rawValue:e.latestDateToGeneratePaymentsFor});j.addFlexibleFieldRow({rawLabel:"Old Last Generated Payment Date",rawValue:e.oldLastGeneratedPaymentDate});for(a=0;a(Import all payments posted on a single, specific date)
'});a.addDatePickerRow(e,"dtDate",{rawLabel:"Payment Transaction Date",strValue:c});a.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.
'});a.showClientDialog()}else{submitImportPaymentProcessorPayments(null,{forceRefreshOnCancel:d})}}function submitUpdateTaxes(){var e="frmUpdateTaxes",f=getObj(e),d=mjtElemData(f,"arrChanged"),c=[],a,b;for(b=0;b(The following rates will remain unchanged)':'
(None of the existing tax rates have changed)
',additionalCellClasses:"leftAlign"});n.addFlexibleRow({valueHTML:h.buildTableForArray(b)})}e=n.showClientDialog();if(e){mjtElemData(e,"arrChanged",g)}}function screenTaxesForUpdate(){var d="frmUpdateTaxesStep1",q=getObj(d),g=mjtElemData(q,"state"),k=q.txtTaxes.value,a=String.fromCharCode(9),m=k.split("\n"),n="",o,e,b=[],p,t,s,h,r,f,j,l,c=1;if(g==="Utah"){j="UT-";r=1;f=0;l=null}else{if(g==="Washington"){j="WA-";r=3;f=0;l=null;c=100}else{if(g==="Ohio"){j="OH-";r=2;f=0;l=1}}}for(o=0;o1){t=p[f];s=trim(p[r]);if(t){t=j+t.replace("-","");if(null!==l){t+="-";t+=parseInt(p[l],10).toString()}if(s.length&&s.substring(s.length-1)==="%"){s=trim(s.substring(0,s.length-1))}h=parseFloat(s)*c;b[b.length]={name:t,rate:h}}else{n="\n"+e}}else{n="\n"+e}}}if(!b.length){if(n){showInfoDialog("There was no valid data found.
The following text could not be parsed (Is it tab-delimited?):

"+htmlMultilineEncode(n),"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:b},{fnOnSuccess:rsCallbackCheckBatchTaxesForUpdate})}function showUpdateTaxesDialog(a){var d="";if(a==="Utah"){d='
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-3132.5%
03-5615.5%
03-6005.4%
...
'}else{if(a==="Washington"){d='
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.)
14010.02130.0650.0863
01000.0120.0650.077
32010.0240.0650.089
...
'}else{if(a==="Ohio"){d='
Enter three, tab-delimitted columns with the Name, Code and Rate (%)
as found on the Ohio Department of Taxation Website: e.g.)
Butler096.50%
Clermont136.75%
Delaware217.00%
...
'}}}var c="frmUpdateTaxesStep1",e,b=new ClientDialogBuilder({formId:c,formTitle:"Update "+a+" Tax Rates",focusFieldName:"txtTaxes",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"screenTaxesForUpdate()"}),fnSubmit:screenTaxesForUpdate});b.addFlexibleRow({valueHTML:d});b.addTextAreaFieldRow("txtTaxes",{rawLabel:"Taxes",mnemonicChar:"t",labelAbove:1,rowCount:18,autofocus:1});e=b.showClientDialog();if(e){mjtElemData(e,"state",a)}}function showUserEventLog(d,c,b,f,a){var e="";if(c){e+="pageSize="+c}if(b){e+="&from="+trim(getDateForUrlParam(b))}if(f){e+="&to="+trim(getDateForUrlParam(f))}if(a){e+="&dateCount="+trim(a)}window.location=pageUserEventLog+d+(e?"?":"")+e}function submitChangeLogOptions(){var l="frmChangeLogOptions",n=getObj(l),m=n.cboUsers,g=m.options[m.selectedIndex].value,a=new FormValidator(),e=n.pageSize,b=getObj("rbDateRange"),c=b&&b.checked,k=n.dtFrom,f=n.dtTo,d=n.txtDateCount,j="",i="",h="";if(!a.CSValidateIntegerField(e,"Page Size",true,1,2000)){return}if(c){if(!a.CSValidateDateField(k,"From",true)){return}if(!a.CSValidateDateField(f,"To",true)){return}if((!trim(k.value))&&(!trim(f.value))){showInfoDialog("Please specify a Range of Dates.","Missing Date Range",1,"dtFrom");return}j=k.value;i=f.value}else{if(!a.CSValidateIntegerField(d,"Number of Days",false,1,9999)){return}h=d.value}hideDialog();showUserEventLog(g,parseInt(trim(e.value),10),j,i,h)}function elDateRangeChanged(){var c=getObj("frmChangeLogOptions"),a=getObj("rbDateRange"),b=a&&a.checked;if(c){c.dtFrom.disabled=!b;c.dtTo.disabled=!b;c.txtDateCount.disabled=b}}function rsCallbackGetUsersForOptions(p,j,r){enableDialogButtons();if(checkResponseForError(p)){var b=r.userId,u=r.pageSize,g="frmChangeLogOptions",n=" onkeypress=\"return submitClientDialogOnEnter('"+g+"',event);\"",m="",q,d=JSON.parse(p),h=d.arrUsers,k,w,t=cdBuildDatePickerField(g,"dtFrom",r.dateFrom,n,""),l=cdBuildDatePickerField(g,"dtTo",r.dateTo,n,""),e,o,c=r.dateCount,v="Last "+buildTextField("txtDateCount",""+(c?c:7),n,4,"4em")+" Days",a=!c,f=new ClientDialogBuilder({formId:g,formTitle:"Change Log Options",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"alert('Hello')"}),focusFieldName:"cboUsers",focusFieldOnMobile:1,fnSubmit:submitChangeLogOptions}),s;for(q=0;q"+htmlEncode(k.email)+""}e="elDateRangeChanged()";o='
From:'+t+'
To:'+l+"
";f.addFlexibleFieldRow({rawLabel:"User",valueHTML:'"});f.addFlexibleFieldRow({labelHTML:cdBuildRBP("rbDateType","rbDateRange","Range of Dates ",{checked:a,onClickCode:e,forceLabelOnTheLeft:1}),valueHTML:o,suppressLabelColon:1});f.addFlexibleFieldRow({labelHTML:cdBuildRBP("rbDateType","rbDateCount","Number of Days ",{checked:!a,onClickCode:e,forceLabelOnTheLeft:1}),valueHTML:v,suppressLabelColon:1});f.addTextFieldRow("pageSize",{rawLabel:"Events/Page",fieldValue:""+u,isNumber:1,maxValue:2000});f.showClientDialog();elDateRangeChanged()}}function showChangeLogOptions(d,f,b,c,a,e){jsrsExecute(rsCallbackGetUsersForOptions,"Admin_GetUsers",[],enableDialogButtons,{userId:f?f:0,pageSize:b,dateCount:c,dateFrom:a,dateTo:e})}function eventLogObjectMenu(d,c,f,a){var b=new ContextMenu(),e;if(g_isDoubleClickEvent){window.location=pageEventLog+c+"/"+f;return}if(c==EventObjectType_Enum.eotUser){e='View changes to "'+a+'"'}else{e='View Change Log for "'+a+'"'}b.AddLinkItem(e,pageEventLog+c+"/"+f,"",1);switch(c){case EventObjectType_Enum.eotInvoice:b.AddSeparatorIfNecessary();b.AddLinkItem('View Invoice "'+a+'"',pageInvoiceDetail+f);break;case EventObjectType_Enum.eotCreditMemo:b.AddSeparatorIfNecessary();b.AddLinkItem('View Credit Memo "'+a+'"',pageCreditMemoDetail+f);break;case EventObjectType_Enum.eotPayment:b.AddSeparatorIfNecessary();b.AddLinkItem('View Payment "'+a+'"',pagePaymentDetail+f);break;case EventObjectType_Enum.eotDatabase:b.AddSeparatorIfNecessary();b.AddLinkItem('View Database "'+a+'"',pageDatabaseDetail+f);break;case EventObjectType_Enum.eotCustomer:b.AddSeparatorIfNecessary();b.AddLinkItem('View Customer "'+a+'"',pageCustomerDetail+f);break;case EventObjectType_Enum.eotProduct:b.AddSeparatorIfNecessary();b.AddLinkItem("View Products",pageSystemSettingsProducts);break;case EventObjectType_Enum.eotUser:b.AddSeparatorIfNecessary();b.AddLinkItem("View changes made by "+htmlEncode(a),pageUserEventLog+f);break;case EventObjectType_Enum.eotDatabaseProduct:break}b.Show(d)}function systemEventLogMenu(b){var a=new ContextMenu();if(g_isDoubleClickEvent){window.location=pageSystemEventLog;return}a.AddLinkItem("View changes made by the system",pageSystemEventLog,"",1);a.Show(b)}function jtUserEventLogMenu(d,f,b,c,e){var a=new ContextMenu();if(g_isDoubleClickEvent){window.location=pageJTUserEventLog+c+"/"+f;return}a.AddLinkItem("View changes made by "+b+" of DB "+e,pageJTUserEventLog+c+"/"+f,"",1);a.Show(d)}function userEventLogMenu(b,c,d){var a=new ContextMenu();if(g_isDoubleClickEvent){showUserEventLog(c);return}a.AddLinkItem("View changes made by "+d,pageUserEventLog+c,"",1);a.AddSeparatorIfNecessary();a.AddLinkItem("View changes to "+d,pageEventLog+EventObjectType_Enum.eotUser+"/"+c);a.Show(b)}function submitUpdateJTIManLKInfo(){var b="frmUpdateLK",c=getObj(b),a=getCallbackDataOfDialog(c);jsrsExecuteWithErrorP("Admin2_UpdateJTIManLKInfo2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating License",{databaseId:a.databaseId,newLicense:a.license})}function rsCallbackTestUpdateJTIManLKInfo(f,b){var c=b.originalPayload,j=f.arrDiffs,h=j.length>0,d=f.userCountWarnings,a="",e,k,i="frmUpdateLK",g=new ClientDialogBuilder({formId:i,formTitle:"Update License Key",fnSubmit:submitUpdateJTIManLKInfo,callbackData:{license:c.newLicense,databaseId:c.databaseId},okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Update License Key",mnemonicChar:"u",mnemonicActionJS:"submitUpdateJTIManLKInfo()"})});g.addFlexibleRow({rawValue:"Instance Name: "+f.instanceName});g.addSectionHeaderRow();if(d){g.addBubbleMessageRow({rawMessage:d})}if(h){a='';for(k=0;k"}a+="
'+htmlEncode(e.valueDisplayName)+':
'+(e.valueOnLic1?htmlMultilineEncode(e.valueOnLic1):"")+'
-
'+(e.valueOnLic2?htmlMultilineEncode(e.valueOnLic2):"")+"
";g.addFlexibleRow({valueHTML:'Updating the license key will result in the following changes:
'+a+"
"})}else{g.addFlexibleRow({rawValue:"Updating the license key will result in no changes.\n\n"})}g.addFlexibleRow({rawValue:"Are you sure you want to update the license key?"});g.showClientDialog()}function testUpdateJTIManLKInfo(){var e=getObj("frmLicense"),a=getCallbackDataOfDialog(e),d=e.txtLicense,c=trim(d.value),b=new FormValidator();if(!b.CSValidateRequiredField(d,"Please enter a License")){return}jsrsExecuteWithErrorP("Admin2_TestUpdateJTIManLKInfo2",rsCallbackHandleStandardJSONResponse,"Checking For Differences In The Proposed License",{databaseId:a.databaseId,newLicense:c},{fnOnSuccess:rsCallbackTestUpdateJTIManLKInfo})}function rsCallbackGenerateLicenseForDB(c,g){var b=g.originalPayload,e=c.licenseText,a=c.instanceName,f="frmLicense",d=new ClientDialogBuilder({formId:f,formTitle:"Update License Key",focusFieldName:"btnOk",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Analyze Changes",mnemonicChar:"a",mnemonicActionJS:"testUpdateJTIManLKInfo()"}),fnSubmit:testUpdateJTIManLKInfo,callbackData:{databaseId:b.databaseId}});if(a){d.addFlexibleRow({rawValue:"Instance Name: "+a});d.addSectionHeaderRow()}d.addTextAreaFieldRow("txtBody",{rawLabel:"License",unencodedText:e,fieldId:"txtLicense",emWidth:"30",labelAbove:1});d.showClientDialog()}function generateLicense(b,a){jsrsExecuteWithErrorP("Admin2_GenerateLicenseForDB2",rsCallbackHandleStandardJSONResponse,"Generating License",{databaseId:b,productExpirationDate:a?a:""},{fnOnSuccess:rsCallbackGenerateLicenseForDB})}function submitGenerateExpiringLicense(a,d){var c=new FormValidator(),e=a.dtExpiration,g,f=new Date(),b;f=new Date(f.getFullYear(),f.getMonth(),f.getDate());if(!c.CSValidateDateField(e,"Expiration Date",false,e.name)){return}g=getDateForUrlParam(e.value);b=parseDateString(g);if(f>b){showInfoDialog("You can't push out an expired license.","Invalid Expiration Date",1,"dtExpiration");return}generateLicense(d.databaseId,g)}function buildDefaultExpirationDate(){var d=new Date(),c=new Date(d.getFullYear(),d.getMonth(),d.getDate()+16),e=0,b=6,a=0;switch(c.getDay()){case b:a=2;break;case e:a=1;break}if(a){c=c=new Date(c.getFullYear(),c.getMonth(),c.getDate()+a)}return getLocalDateString(c)}function generateExpiringLicense(c){var b="dtExpiration",d="frmGenLicense",a=new ClientDialogBuilder({formId:d,formTitle:"Generate Expiring License",focusFieldName:b,fnSubmit:submitGenerateExpiringLicense,callbackData:{databaseId:c}});a.addDatePickerRow(d,b,{rawLabel:"Expiration Date",strValue:buildDefaultExpirationDate()});a.showClientDialog()}function showHomepage(){window.location=pageWelcome}function showPaypalInNewWindow(a){window.open("https://manager.paypal.com/viewProfile.do?selectedProfileId="+a+"&subaction=viewRbProfile","_blank")}function showJTJobInNewWindow(a){window.open("https://internal.moraware.net/sys/job/"+a,"_blank")}function submitPaymentOptions(){var g=pagePayments,f=getObj("frmPaymentOptions"),i=f.chkIncFailed.checked,m=f.chkIncSuccess.checked,b=getObj("rbSingleDate"),h=b.checked,c=getObj("rbDateRange"),d=c.checked,o=f.cboMethod,n=o.options[o.selectedIndex].value,a=new FormValidator(),k="",e="";if(i){g+="&incFail=1"}if(!m){g+="&incSuccess=0"}if(n){g+="&methods="+escape(n)}if(!(i||m)){showInfoDialog('Select at least one of "Include Successful" or "Include Failed",

Otherwise no records will be shown.',"All Records Filtered Out",1);return}if(d||h){if(!a.CSValidateDateField(f.dtFrom,"Date",false,"dtFrom")){return}k=getDateForUrlParam(f.dtFrom.value);g+="&date="+k;if(d){if(!a.CSValidateDateField(f.dtTo,"Date (To)",false,"dtTo")){return}e=getDateForUrlParam(f.dtTo.value);var l=new Date(k),j=new Date(e);if(l==j){}else{if(l>j){showInfoDialog("The Start Date preceeds the End Date.","Invalid Date Range",1,"dtTo");return}else{g+="&dateTo="+e}}}}hideDialog();window.location=g;displayTimedMessage("Reloading page...")}function toggledFailedPaymentOption(a){var b=getObj("chkIncArch");if(!a.checked){b.checked=false}}function updatePaymentTimeframe(){var c=getObj("rbToday"),f=getObj("rbSingleDate"),d=getObj("rbDateRange"),e=getObj("secSingleDate"),b=getObj("secDateRange"),a=d.checked;e.style.visibility=(f.checked||(d&&d.checked))?"":"hidden";if(b){b.style.visibility=d.checked?"":"hidden"}}function rsCallbackGetPaymentMethods(q,m,t){enableDialogButtons();if(checkResponseForError(q)){var p=t.strPaymentMethods,c=JSON.parse(q),g=c.arrPaymentMethods,r,h,w={},v=buildAnOption("","[Any]",p,0,w);for(r=0;r'+v+""}),f=new Date(),a=getDateAsDisplayString(f),o=t.dispDate,n=t.dispDateTo,b=o?o:a,d=n?n:a,u=''+cdBuildDatePickerField(e,"dtFrom",b,l)+' - '+cdBuildDatePickerField(e,"dtTo",d,l)+"";x+=cdBuildRBRowP("rbDateRange","rbSingleDate","Single Date",{rawRowLabel:"Timeframe:",checked:o&&!n,onClickCode:s})+''+cdBuildRB("rbDateRange","rbDateRange","Date Range",o&&n,0,s)+''+u+"";showDialogP(x,e,{formTitle:"Payment Options",focusFieldName:k,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitPaymentOptions()"}),contextDetailOrFnSubmit:{fnSubmit:submitPaymentOptions}});if(getObj(e)){updatePaymentTimeframe()}}}function showPaymentOptionsDialog(c,d,a,f,b,e){jsrsExecute(rsCallbackGetPaymentMethods,"Admin_GetPaymentMethods",[],enableDialogButtons,{includeSuccess:d,includeFailed:a,dispDate:f,dispDateTo:b,strPaymentMethods:e});displayTimedMessage("Retrieving Payment Methods...");disableDialogButtons()}function submitPaymentTotalsOptions(a,d){var g=pagePaymentTotals,c,b=new FormValidator(),f=a.txtMinDays,e="";if(!b.CSValidateDateField(a.dtDateTo,"Date",true,"dtDateTo")){return}e=getDateForUrlParam(a.dtDateTo.value);if(e){g+="&date="+e}hideDialog();window.location=g;displayTimedMessage("Reloading page...")}function showPaymentTotalsOptionsDialog(a,d){var c="frmOptions",b=new ClientDialogBuilder({formId:c,formTitle:"Payment Totals Options",okButtonDisplayText:"Apply",focusFieldName:"dtDateTo",focusFieldOnMobile:1,suppressDialogConfirmer:1,fnSubmit:submitPaymentTotalsOptions});b.addDatePickerRow(c,"dtDateTo",{rawLabel:"Month To",strValue:d});b.showClientDialog()}function submitDatabasesOptions(b,d){var c=new FormValidator(),h=pageDatabases,f=b.txtPageSize,e=trim(f.value),a="databaseListsort",g=getUrlParamValueIfThere(""+window.location,a);if(!c.CSValidateIntegerField(f,"Page Size",true,1,2000)){return}if(g){h+="&"+a+"="+g}if(e){h+="&pageSize="+e}hideDialog();window.location=h;displayTimedMessage("Reloading page...")}function showDatabasesOptionsDialog(b,a){var d="frmDatabasesOptions",c=new ClientDialogBuilder({formId:d,formTitle:"Databases Options",fnSubmit:submitDatabasesOptions,focusFieldName:"txtPageSize"});c.addDialogInteriorRows([buildPageSizeRow(a)]);c.showClientDialog()}function submitSystemSettings(m,l){var a=new FormValidator(),k=m.txtCCWarningDays,j=m.txtLKWarningDays,f=m.txtTaskWarningDays,c={},h=m.txtTrivialProrateThreshold,i=m.txtSessionTimeoutMinutes,e=m.txtFailedLoginCountThreshold,d=m.txtAutoUnlockIntervalMinutes,g=m.chkDisableJTPortalAccess.checked,b=!a.CSValidateIntegerField(k,"CC Warning Threshold",false,1,1000)||!a.CSValidateNumberFieldP({resultValueHolder:c,field:h,minValue:0,maxValue:9999,maxDecimalPlaces:2,label:"Trivial Prorate Threshold"})||!a.CSValidateIntegerField(f,"Task Deadline Warning Threshold",false,1,1000)||!a.CSValidateIntegerField(j,"LK Warning Threshold",false,1,1000)||!a.CSValidateIntegerField(i,"Session Timeout Minutes",false,5,1000)||!a.CSValidateIntegerField(e,"Lock After Failed Login Count",false,1,99)||!a.CSValidateIntegerField(d,"Auto-Unlock Interval Minutes",false,1,999);if(b){return}jsrsExecuteWithErrorP("Admin2_UpdateSystemSettings2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating System Settings",{ccExpirationWarningDays:trim(k.value),taskWarningDays:trim(f.value),lkExpirationWarningDays:trim(j.value),sessionTimeoutMinutes:trim(i.value),disableJTAccessToPortal:g?1:0,trivialProrateThresholdDollars:c.rc,failedLoginCountThreshold:trim(e.value),autoUnlockIntervalMinutes:trim(d.value)})}function rsCallbackGetSystemSettingsInfo(a){var e="frmSettings",b="txtCCWarningDays",d="txtLKWarningDays",c=cdBuildTextFieldRowP(b,"Credit Card Warning Threshold (Days)",{fieldValue:""+a.ccExpirationWarningDays,isNumber:1,maxLength:10})+cdBuildTextFieldRowP("txtTrivialProrateThreshold","Trivial Prorate Threshold ($)",{fieldValue:""+a.trivialProrateThresholdDollars,isNumber:1,maxLength:10})+cdBuildTextFieldRowP("txtTaskWarningDays","Task Deadline Warning Threshold (Days)",{fieldValue:""+a.taskDeadlineWarningDays,isNumber:1,maxLength:10})+cdBuildTextFieldRowP(d,"License Key Warning Threshold (Days)",{fieldValue:""+a.lkExpirationWarningDays,isNumber:1,maxLength:10})+cdBuildTextFieldRowP("txtSessionTimeoutMinutes","Session Timeout (Minutes)",{fieldValue:""+a.sessionTimeoutMinutes,isNumber:1,maxLength:10})+cdBuildTextFieldRowP("txtFailedLoginCountThreshold","Failed Login Count Threshold",{fieldValue:""+a.failedLoginCountThreshold,isNumber:1,fieldSize:2,maxLength:2,minValue:1,maxValue:10})+cdBuildTextFieldRowP("txtAutoUnlockIntervalMinutes","Auto-Unlock Interval Minutes",{fieldValue:""+a.autoUnlockIntervalMinutes,isNumber:1,fieldSize:3,maxLength:3,minValue:1,maxValue:999})+cdBuildCheckboxRowP("chkDisableJTPortalAccess","Disable Customer Portal",{checked:a.disableJTPortalAccess})+cdBuildReadOnlyFieldRowP({valueHTML:'(For Systemize & CounterGo users)'});showDialogP(c,e,{formTitle:"System Settings",focusFieldName:b,contextDetailOrFnSubmit:{fnSubmit:submitSystemSettings}})}function showSystemSettingsDialog(){jsrsExecuteWithErrorP("Admin2_GetSystemSettingsInfo",rsCallbackGetSystemSettingsInfo,"Retrieving System Settings Info")}var ChurnDetailSortColumns_Enum={cdscCustomer:0,cdscSubdomain:1,cdscProductCount:2,cdscProduct:3,cdscMonthEndMonthlyRevenue:4,cdscProductCountDelta:5,cdscContribution:6,cdscAmount:7};function getChurnDBMaxValue(h,b,j,e,d){var k=h[b],g,c=h.arrDBProducts,a=c?c.length:0,f,i;if(typeof k=="undefined"){k=e;for(f=0;f0){k=g}}h[b]=k}return k}function getChurnDBTotalValue(e,b,i){var g=e[b],d,c=e.arrDBProducts,a=c?c.length:0,f,h;if(typeof g=="undefined"){g=0;for(f=0;f0?"+":"";return b+a}function getRevenueCategoryText(b){var a=b.revenueCategoryId;switch(a){case (ChurnReportRevenueCategory_Enum.crrcNew):return"New";case (ChurnReportRevenueCategory_Enum.crrcCancel):return"Cancel";case (ChurnReportRevenueCategory_Enum.crrcDecrease):return"Decrease";case (ChurnReportRevenueCategory_Enum.crrcIncrease):return"Increase";default:return"Net"}}function rebuildChurnReportDetailTable(i){var f=i.filters,a=getObj("divChurnDetailTable"),b=getObj("divChurnDetailDatabaseCount"),d=getObj("frmTmpMessage"),j=typeof i.sortAscending!="undefined"?i.sortAscending:d.currentSortAscending,k=typeof i.sortColumnId!="undefined"?i.sortColumnId:d.currentSortColumnId,c=d.databases,e=d.revenueCategoryText,h=d.periodTypeId,g=sortAndBuildChurnReportDetailTable({databases:c,sortColumnId:k,sortAscending:j,periodTypeId:h,revenueCategoryText:e,filters:f});d.currentSortAscending=j;d.currentSortColumnId=k;a.innerHTML=g.strHTML;b.innerHTML=g.strCountHtml;g.objClientTable.linkTableObjectsToElement(a);scrollDialogIfNecessary("frmTmpMessage",1,1)}function buildChurnReportDetailSortInfo(c){var a=c.columnId,d=c.currentSortColumnId,b=c.ascending,e=c.filters,f=0;if(a==d){f=b?1:-1}return{initialSortDir:f,fnCustomSort:function(g,i,h){rebuildChurnReportDetailTable({filters:e,sortAscending:i,sortColumnId:a})}}}function getDatabaseCrossSellData(h){var f=h.database,c=f.arrDBProducts||[],i=[],k=[];for(var b=0;b0){g.countOfProductTypesWithNonZeroProductCount++}if(j.priorMonthEndProductCountTotal>0){g.countOfProductTypesWithNonZeroProductCountInPriorMonth++}if(j.monthEndProductCountTotal===0&&j.priorMonthEndProductCountTotal>0){g.countOfCancelledProductTypes++}if(j.priorMonthEndProductCountTotal===0&&j.monthEndProductCountTotal>0){g.countOfStartedProductTypes++}}return{hasCrossSell:k.findIndex(function(l){return l.countOfProductTypesWithNonZeroProductCountInPriorMonth>0&&l.countOfStartedProductTypes>0})!==-1,hasCrossCancel:k.findIndex(function(l){return l.countOfProductTypesWithNonZeroProductCount>0&&l.countOfCancelledProductTypes>0})!==-1}}function getDatabaseCountText(c){var d=c.databaseCount,b=d===1?"":"s",a="("+d+" Database"+b+")";return a}function sortAndBuildChurnReportDetailTable(p){var k=p.databases,x=p.sortColumnId,v=p.sortAscending,f=p.periodTypeId,a=p.revenueCategoryText,y=p.filters||{},j=y.onlyShowCrossSells,t=y.onlyShowCrossCancels,g=0,e=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARRead),w,b,o,c,q,l,s=0,n,d=0,u=new MWClientTable({tableId:"tblChurnDetail",fnOverrideGetRowClass:function(C,A,B){return C.idxDistinctDB%2?"evenRow":"oddRow"}}),i=[],h=new MJTDictionary(),r=function(B){var A=B.contributionAmount;if(A>0){return"plusContrib"}if(A<0){return"minusContrib"}return"zeroContrib"},z=function(D){var B=D.contributionAmount,C=getChurnDBMonthEndProductCount(D),A=getChurnDBProductCountChange(D);if(C===A&&B>0){return"plusContrib"}if(C===0&&B<0){return"minusContrib"}if(B===0){return"zeroContrib"}return""};k=k.sort(buildChurnDetailDBCompareFunction(x,v));for(n=0;n"+cdBuildRBP("rbChurnDetailsFilter","rbChurnDetailsFilter_All","All",{onChangeCode:"filterChurnReportDetails()",checked:true})+''+cdBuildRBP("rbChurnDetailsFilter","rbChurnDetailsFilter_CrossSellsOnly","Cross-Sells Only",{onChangeCode:"filterChurnReportDetails()"})+''+cdBuildRBP("rbChurnDetailsFilter","rbChurnDetailsFilter_CrossCancelsOnly","Cross-Cancels Only",{onChangeCode:"filterChurnReportDetails()"})+""}return c}function rsCallbackGetChurnReportDetails(e,b){var c=b.originalOptions,h=c.revenueCategoryText,a=c.revenueCategoryId,i=c.periodTitle,k=c.periodTypeId,n=c.productTypeId,d=e.databases,g="",j,l;if(d&&d.length){l=getChurnReportDetailsFilterOptions({productTypeId:n,revenueCategoryId:a});j=sortAndBuildChurnReportDetailTable({databases:d,sortColumnId:0,sortAscending:1,revenueCategoryText:h,periodTypeId:k,includeProductCount:true});g+=l+'
'+j.strHTML+'
'+j.strCountHtml+"
"}else{g="No Data!"}showInfoDialog(g,'"'+h+'" Details For '+i);var m=getObj("divChurnDetailTable"),f=getObj("frmTmpMessage");if(m){m.onclick=doClick;f.databases=d;f.revenueCategoryText=h;f.periodTypeId=k;if(j){j.objClientTable.linkTableObjectsToElement(m)}}scrollDialogIfNecessary("frmTmpMessage",1,1)}function drillIntoChurnReportCell(h){var e=h.periodTitle,g=h.startDate,i=h.endDate,b=h.revenueCategoryId,a=h.periodTypeId,f=h.productTypeId,c=getRevenueCategoryText({revenueCategoryId:b}),d='Retrieving "'+c+'" details for '+e;jsrsExecuteWithErrorP("Admin2_GetChurnReportDetails",rsCallbackHandleStandardJSONResponse,d,{startDate:g,endDate:i,productTypeId:f,revenueCategoryId:b},{fnOnSuccess:rsCallbackGetChurnReportDetails,revenueCategoryText:c,periodTitle:e,periodTypeId:a,revenueCategoryId:b,productTypeId:f})}function getPeriodText(b){var a=b.periodType;switch(a){case (ChurnReportPeriodType_Enum.crptMonth):return"Month";case (ChurnReportPeriodType_Enum.crptQuarter):return"Quarter";case (ChurnReportPeriodType_Enum.crptYear):return"Year";default:return"Unknown - "+a}}function submitChangeChurnReportOptions(a,d){var g=a.txtPeriodCount,c=new FormValidator(),e=trim(g.value),b=parseInt(a.cboPeriodType.value,10),f=(getPeriodText({periodType:b})||"Month")+"s",h=a.cboProductType.value;if(!c.CSValidateIntegerField(g,"Number of "+f,false,1,120)){return}hideDialog();showWorking("Reloading...");window.location=pageChurnReport+"&periodCount="+e+"&periodType="+b+"&productType="+h}function setChurnReportPeriodTypeLabels(c){var a=c.periodType,d=(getPeriodText({periodType:a})||"Month")+"s",b=getObj("churnReportPeriodLabel");b.innerHTML=d}function churnReportPeriodTypeChanged(){var b=getObj("churnReportPeriodType"),a=parseInt(b.value,10);setChurnReportPeriodTypeLabels({periodType:a})}function showChurnReportOptions(e,d){var c=d.periodCount,b=d.periodType,f=d.productType,h="frmOptions",a="txtPeriodCount",g=new ClientDialogBuilder({formId:h,formTitle:"Churn Report Options",okButtonDisplayText:"Apply",focusFieldName:a,focusFieldOnMobile:1,fnSubmit:submitChangeChurnReportOptions});g.addDropdown({fieldName:"cboProductType",rawLabel:"Product",arrAvailableOptions:[{cboValue:CRMProductType_Enum.crmptCounterGo,rawContent:"CounterGo"},{cboValue:CRMProductType_Enum.crmptNVInventory,rawContent:"Inventory"},{cboValue:CRMProductType_Enum.crmptSystemize,rawContent:"Systemize"}],objNoneOption:{cboValue:"",rawContent:"-All-"},objSelectedValue:{cboValue:f},additionalCellClasses:"clsNarrowField"});g.addDropdown({fieldName:"cboPeriodType",fieldId:"churnReportPeriodType",onClickChangeJS:"churnReportPeriodTypeChanged()",rawLabel:"Period",arrAvailableOptions:[{cboValue:ChurnReportPeriodType_Enum.crptMonth,rawContent:"Month"},{cboValue:ChurnReportPeriodType_Enum.crptQuarter,rawContent:"Quarter"},{cboValue:ChurnReportPeriodType_Enum.crptYear,rawContent:"Year"}],objSelectedValue:{cboValue:b},additionalCellClasses:"clsNarrowField"});g.addTextFieldRow(a,{rawLabel:"Show Last",fieldValue:""+c,isNumber:1,maxLength:4,autofocus:1,strPostFieldHTML:' ',additionalCellClasses:"clsNarrowField"});g.showClientDialog();setChurnReportPeriodTypeLabels({periodType:b})}function submitCohortReportOptions(a,c){var d=a.txtMaxMonths,e=a.cboProductType.value,b=new FormValidator();if(!b.CSValidateIntegerField(d,"Max # of Months to Report",false,1,CommonConstants_Enum.ccMAX_REPORTING_MONTHS_COUNT)){return}hideDialog();window.location=pageCohortAnalysisReport+"maxMonths="+trim(d.value)+"&productType="+e;displayTimedMessage("Reloading page...")}function showCohortReportOptions(d,c){var g="frmOptions",b=c.maxMonths,e=c.productType,a="txtMaxMonths",f=new ClientDialogBuilder({formId:g,formTitle:"Cohort Analysis Report Options",okButtonDisplayText:"Apply",focusFieldName:a,focusFieldOnMobile:1,fnSubmit:submitCohortReportOptions});f.addTextFieldRow(a,{rawLabel:"Max # of Months to Report",fieldValue:""+b,isNumber:1,maxLength:10,autofocus:1,additionalCellClasses:"clsNarrowField"});f.addDropdown({fieldName:"cboProductType",rawLabel:"Product",arrAvailableOptions:[{cboValue:CRMProductType_Enum.crmptCounterGo,rawContent:"CounterGo"},{cboValue:CRMProductType_Enum.crmptNVInventory,rawContent:"Inventory"},{cboValue:CRMProductType_Enum.crmptSystemize,rawContent:"Systemize"}],objNoneOption:{cboValue:"",rawContent:"-All-"},objSelectedValue:{cboValue:e},additionalCellClasses:"clsNarrowField"});f.showClientDialog()}function submitLicenseReconciliationReportOptions(){var g="frmOptions",h=getObj(g),a=getCallbackDataOfDialog(h),f=a.strSortAddendum,c=new FormValidator(),e=h.cboBatch,b=e.options[e.selectedIndex].value,d=h.txtPageSize;if(!c.CSValidateIntegerField(d,"Page Size",true,1,2000)){return}hideDialog();window.location=pageLicenseReconciliationReport+(b?"&batchId="+b:"")+"&pageSize="+d.value+f;displayTimedMessage("Reloading page...")}function rsCallbackGetServerMetricBatches(h,c,n){enableDialogButtons();if(checkResponseForError(h)){var f=JSON.parse(h),o=f.arrBatches,b,j=n.strSortAddendum,l="frmOptions",g='',e,k=n.batchId,d=n.pageSize,m,a=new ClientDialogBuilder({formId:l,formTitle:"License Reconciliation Report Options",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitLicenseReconciliationReportOptions()"}),focusFieldName:"cboBatch",focusFieldOnMobile:1,suppressDialogConfirmer:1,callbackData:{strSortAddendum:j},fnSubmit:submitLicenseReconciliationReportOptions});for(e=0;e'+htmlEncode(b.timestamp)+""}a.addFlexibleFieldRow({rawLabel:"Batch",valueHTML:'"});a.addTextFieldRow("txtPageSize",{rawLabel:"Rows/Page",fieldValue:""+(d||30),maxLength:4,isNumber:1});a.showClientDialog()}}function showLicenseReconciliationReportOptions(b,d,a,c){jsrsExecute(rsCallbackGetServerMetricBatches,"Admin_GetServerMetricBatches",[],enableDialogButtons,{batchId:d,strSortAddendum:c,pageSize:a});displayTimedMessage("Getting Available Batches...");disableDialogButtons()}function toggleExpandServerMetricInfo(){var a=getObj("imgServerMetricsExpander.expand"),b=!a.style.display;a.style.display=b?"none":"";getObj("imgServerMetricsExpander.collapse").style.display=b?"":"none";getObj("divServerMetrics").style.display=b?"":"none"}function toggleExpandTaskSection(){saveScrollPos();var a=getObj("imgTaskSectionExpander.expand"),b=!a.style.display,c=addRemoveOrReplaceURLParameter(window.location,"expandTasks",b?"1":"");window.location=c}function submitServerMetricReportOptions(){var h="frmOptions",g=getObj(h),a=new FormValidator(),c=g.cboBatch,d=c.options[c.selectedIndex].value,e=g.txtPageSize,j=parseInt(g.cboUsage.value,10),i=parseInt(g.cboBillingDBStatus.value,10),b=parseInt(g.cboExpirationStatus.value,10),f=pageServerMetricReport+"&pageSize="+e.value;if(!a.CSValidateIntegerField(e,"Page Size",true,1,2000)){return}hideDialog();if(d){f+="&batchId="+d}if(j!==SMREditionUsage_Enum.seuAll){f+="&smro="+j}if(b!==SMRExpirationStatus_Enum.sesAll){f+="&estat="+b}if(i!==SMRBillingDBStatus_Enum.bdbsAll){f+="&bdbs="+i}window.location=f;displayTimedMessage("Reloading page...")}function rsCallbackGetServerMetricBatchesForServerMetricReport(e,a){var d=a.originalOptions,g="frmOptions",i=d.serverMetricReportOption,b=d.expirationStatus,h=d.billingDBStatus,c=d.pageSize,f=new ClientDialogBuilder({formId:g,formTitle:"Server Metric Report Options",focusFieldName:"cboBatch",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitServerMetricReportOptions()"}),fnSubmit:submitServerMetricReportOptions});f.addDropdown({arrAvailableOptions:e.arrBatches.map(function(j){return{cboValue:j.id,rawContent:j.timestamp}}),rawLabel:"Bulk-Batch",fieldName:"cboBatch",objNoneOption:{cboValue:"",rawContent:"-Latest-"},objSelectedValue:{cboValue:d.batchId||""}});f.addDropdown({fieldName:"cboUsage",rawLabel:"Usage",arrAvailableOptions:[{cboValue:SMREditionUsage_Enum.seuAll,rawContent:"All"},{cboValue:SMREditionUsage_Enum.seuCGUsage,rawContent:"CounterGo"},{cboValue:SMREditionUsage_Enum.seuJTUsage,rawContent:"Systemize"}],objSelectedValue:{cboValue:i}});f.addDropdown({fieldName:"cboBillingDBStatus",rawLabel:"Billing DB Status",arrAvailableOptions:[{cboValue:SMRBillingDBStatus_Enum.bdbsAll,rawContent:"All"},{cboValue:SMRBillingDBStatus_Enum.bdbsHasBillingDB,rawContent:"Has Billing DB"},{cboValue:SMRBillingDBStatus_Enum.bdbsNoBillingDB,rawContent:"No Billing DB"}],objSelectedValue:{cboValue:h}});f.addDropdown({fieldName:"cboExpirationStatus",rawLabel:"Expiration Status",arrAvailableOptions:[{cboValue:SMRExpirationStatus_Enum.sesAll,rawContent:"All"},{cboValue:SMRExpirationStatus_Enum.sesNotExpired,rawContent:"Not Expired"},{cboValue:SMRExpirationStatus_Enum.sesExpired,rawContent:"Expired"}],objSelectedValue:{cboValue:b}});f.addTextFieldRow("txtPageSize",{rawLabel:"Rows/Page",fieldValue:""+(c||30),maxLength:4,isNumber:1});f.showClientDialog()}function showServerMetricReportOptions(a){a.fnOnSuccess=rsCallbackGetServerMetricBatchesForServerMetricReport;jsrsExecuteWithErrorP("Admin2_GetServerMetricBatches2",rsCallbackHandleStandardJSONResponse,"Getting Available Batches",{},a)}function getNewProcessKey(){var a=new Date();return Math.random()+">..<"+a.getTime()}function rsCallbackGenerateServerMetrics(e,c,d){if(checkResponseForError(e)){var b=getObj(d.statusSectionId),a=d.asynchUpdaterTimeoutId;if(b){b.innerHTML="Completed Server Metrics"}if(a){clearTimeout(a)}refreshPageAndScrollPos()}}function rsErrorCallbackBuildServerMetrics(d,b,c){var a=getObj(c.statusSectionId);if(c.requestContextId==b&&a){a.innerHTML='
Encountered the following error generating server metrics:

'+htmlMultilineEncode(d)+"

"+a.innerHTML;if(c.asynchUpdaterTimeoutId){clearTimeout(c.asynchUpdaterTimeoutId)}c.refreshOnClose=1}}function doBuildServerMetrics(c){hideDialog();var a=getNewProcessKey(),g="frmServerMetricsProgress",d="serverMetricsStatus",f='Status:',b={statusSectionId:d},e=new ClientDialogBuilder({formId:g,formTitle:"Generating Server Metrics",fnCancelOrClose:function(){if(!b.refreshOnClose){return 1}refreshPageAndScrollPos();hideDialog()}});e.addFlexibleRow({cellId:d});e.showClientDialog();b.requestContextId=jsrsExecute(rsCallbackGenerateServerMetrics,"Admin_GenerateServerMetrics",[escape(a)],rsErrorCallbackBuildServerMetrics,b,0,1);b.asynchUpdaterTimeoutId=setTimeout(function(){asynchUpdateWithProcessStatus(a,d,b)},125)}function confirmBuildServerMetricsDialog(a){var b=new ClientDialogBuilder({formTitle:"Server Metrics",okButtonDisplayText:"Generate",focusFieldName:"btnOk",fnSubmit:doBuildServerMetrics});b.addFlexibleRow({rawValue:"Are you sure you want to generate server metrics?"});b.showClientDialog()}function showLicenseText(a,c,b){showInfoDialog(cdBuildTextAreaFieldRowP("txtNotes","License",{unencodedText:unescape(c),labelAbove:1}),(b?"Expected":"Actual")+' License for Instance "'+htmlEncode(a)+'"',isDialogShowing())}function showLicenseDifferences(d,j,b,g,i){var e=j?j.arrDifferences:0,c=e?e.map(function(k){return{rawRowHeader:k[0],rawDeployedValue:k[1],rawBillingValue:k[2]}}):0,f=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"})]}),a=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formTitle:"Actual Vs. Expected License"});var h=htmlEncode(unescape(d));if(i){h=''+h+""}a.addFlexibleFieldRow({rawLabel:"Instance",valueHTML:h});if(b){a.addFlexibleFieldRow({valueHTML:'Expected License..."})}if(g){a.addFlexibleFieldRow({valueHTML:'Actual License..."})}a.addFlexibleRow({valueHTML:f.buildTableForArray(c)});a.showClientDialog()}function showLicenseMenu(d){var f=d.databaseId,b=escape(d.instanceName),g=d.actualLicenseText,e=d.expectedLicenseText,c=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARRead),a=new ContextMenu();a.AddScriptItem("Show actual license...","showLicenseText('"+b+"','"+escape(g)+"',0);");a.AddScriptItem("Show expected license...","showLicenseText('"+b+"','"+escape(e)+"',1);");if(f&&c){a.AddSeparatorIfNecessary();a.AddLinkItem("View Database",pageDatabaseDetail+f)}a.Show(event)}function submitAddOrUpdateTask(){var f="frmAddTask",g=getObj(f),b=new FormValidator(),a=mjtElemData(g,"taskId"),c=cdGetExpandingTextFieldValue("txtNotes"),e=mjtElemData(g,"databaseId"),d=b.CSValidateRequiredField(g.txtName,"Please enter a Name")&&b.CSValidateDateField(g.dtDeadline,"Deadline",false,"dtDeadline");if(d){jsrsExecuteWithErrorP(a?"Admin2_UpdateTask2":"Admin2_CreateTask2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,a?"Updating Task":"Creating Task",{taskId:a||"",databaseId:e||"",taskName:trim(g.txtName.value),taskNotes:trim(c),taskDeadline:getDateForUrlParam(g.dtDeadline.value)})}}function showAddOrUpdateTask(j){var a=j.id,b=j.statusId,h="frmAddTask",f,l="txtName",g=j.name,d=j.notes,c=j.subdomain,i=a?b===TaskStatus_Enum.tsComplete?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiLightningBolt,doubleQuoteEncodedTitle:"Re-Activate Task",doubleQuoteEncodedOnClickJS:"carefullyActivateTask("+a+")"}):b===TaskStatus_Enum.tsActive?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiCheck,doubleQuoteEncodedTitle:"Mark Task Complete",doubleQuoteEncodedOnClickJS:"confirmSetTaskStatus("+a+","+TaskStatus_Enum.tsComplete+",'Complete',unescape('"+escape(g)+"'),1)"}):"":"",e=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),k=new ClientDialogBuilder({formId:h,formTitle:a?"Update Task":"Add Task To Database",focusFieldName:l,focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitAddOrUpdateTask()"}),arrExtraHeaderButtons:a?[e?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Task",doubleQuoteEncodedOnClickJS:"confirmDeleteTask("+a+",unescape('"+escape(g)+"'),1)"})+'':"",i,buildHeaderChangeLogAnchorButton({eventObjectTypeId:EventObjectType_Enum.eotTask,eventObjectId:a})]:0,fnSubmit:submitAddOrUpdateTask});if(c){k.addFlexibleFieldRow({rawLabel:"Subdomain",rawValue:c})}k.addTextFieldRow(l,{rawLabel:"Name",mnemonicChar:"n",fieldValue:g,autofocus:1,maxLength:80});k.addDatePickerRow(h,"dtDeadline",{rawLabel:"Task Deadline",mnemonicChar:"t",strValue:cdCarefullyLocalizeDateValue(j.deadline)});k.addExpandingTextFieldRows("txtNotes",{rawLabel:"Description",value:d||""});f=k.showClientDialog();if(f){mjtElemData(f,"databaseId",j.databaseId);mjtElemData(f,"taskId",j.id)}}function showAddTaskToDatabase(b,a,c){showAddOrUpdateTask({databaseId:a,subdomain:c})}function rsCallbackGetTaskDetails(a){showAddOrUpdateTask(a)}function showEditTaskDialog(b,a){jsrsExecuteWithErrorP("Admin2_GetTaskDetails2",rsCallbackHandleStandardJSONResponse,'Retrieving info for task, "'+a+'"',{taskId:b},{fnOnSuccess:rsCallbackGetTaskDetails})}function doDeleteTask(a){jsrsExecuteWithErrorP("Admin2_DeleteTask2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting Task",{taskId:a.taskId})}function confirmDeleteTask(b,a,c){if(c){hideDialog()}displaySimpleConfirmationDialog(doDeleteTask,'Are you sure you want to delete "'+htmlEncode(a)+'"',"Delete Task",{taskId:b,taskName:a})}function setTaskStatus(a){jsrsExecuteWithErrorP("Admin2_SetTaskStatus2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Task Status",{taskId:a.taskId,taskStatus:a.status})}function carefullyActivateTask(a){hideDialogP({callback:function(){setTaskStatus({taskId:a,status:TaskStatus_Enum.tsActive})}})}function confirmSetTaskStatus(d,a,b,c,f){var e=function(){displaySimpleConfirmationDialog(setTaskStatus,"Are you sure you want to mark the task "+htmlEncode(b)+'?

Task: '+htmlEncode(unescape(c))+"","Set task status",{taskId:d,status:a})};if(f){hideDialogP({callback:e})}else{e()}}function submitTaskReportOptions(){var h="frmOptions",f=getObj(h),a=new FormValidator(),g=pageTaskReport,e=f.txtPageSize,b=trim(e.value),c=mjtElemData(f,"defaultStatusFilter"),i=parseInt(f.cboTaskStatusFilter.value,10),d=a.CSValidateIntegerFieldP({field:e,label:"Page Size",isNullable:true,minValue:1,maxValue:2000});if(!d){return}if(b){g+="&pageSize="+b}if(i!==c){g+="&status="+i}hideDialog();window.location=g;displayTimedMessage("Reloading page...")}function showTaskReportOptions(a){consoleLogBlockOpen("showTaskReportOptions()");consoleLog(JSON.stringify({params_:a},null,2));var c="frmOptions",d,b=new ClientDialogBuilder({formId:c,formTitle:"Task Report Options",focusFieldName:"cboTaskStatusFilter",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitTaskReportOptions()"}),fnSubmit:submitTaskReportOptions});b.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:a.taskStatusFilter}});b.addTextFieldRow("txtPageSize",{rawLabel:"Rows per Page",fieldValue:""+a.pageSize,mnemonicChar:"r",maxLength:10,styleWidth:"7em",isNumber:1});d=b.showClientDialog();if(d){mjtElemData(d,"defaultStatusFilter",a.defaultStatusFilter)}consoleLogBlockClose()}function doDeleteEmailTemplate(a){jsrsExecuteWithErrorP("Admin2_DeleteEmailTemplate2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting Email Template",{emailTemplateId:a.emailTemplateId})}function confirmDeleteEmailTemplate(b,a,c){if(c){hideDialog()}displaySimpleConfirmationDialog(doDeleteEmailTemplate,'Are you sure you want to delete "'+htmlEncode(a)+'"',"Delete Email Template",{emailTemplateName:a,emailTemplateId:b})}function rsCallbackCreatedEmailTemplate(){}function validateCommonEmail(d,a,f){var e=a.txtSubject,c=a.txtBody,b=c.value;if(!d.CSValidateRequiredField(e,"Please enter a Subject")){return}if(!d.CSValidateRequiredField(c,"Please enter a Body")){return}f.subject=trim(e.value);f.body=b;return 1}function submitCreateOrEditEmailTemplate(){var f="frmEmailTemplate",g=getObj(f),a=mjtElemData(g,"emailTemplateId"),b=new FormValidator(),e=g.txtFromName,d=g.chkDunning.checked,c={};if(!b.CSValidateRequiredField(g.txtName,"Please enter a Name for the Email Template")){return}if(!b.CSValidateRequiredField(e,"Please enter a From Name")){return}if(!validateCommonEmail(b,g,c)){return}jsrsExecuteWithErrorP("Admin2_CreateOrUpdateEmailTemplate2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Submitting Email Template",{emailTemplateId:a||"",emailTemplateName:g.txtName.value,fromName:e.value,messageSubject:c.subject,messageBody:c.body,isDunningEmail:d?1:0},{postMessageFocusFieldName:"txtBody"})}function insertTextIntoTextField(c,b){var a=getObj(c);insertAtCursor(a,b)}function showTextSubstitutionOptions(a,b){show_staticTextInsertPicker(getObj("btnInsertSubstitutionString"),null,false,"insertTextIntoTextField",b,{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(c,g){var e="frmEmailTemplate",f,b=c.id,a=jtcrmHasAccess(JTCRMSecuredObject_Enum.soEmailTemplates,AccessRight_Enum.mjtARDelete),d=new ClientDialogBuilder({formId:e,formTitle:b?"Edit Email Template":"Create Email Template",focusFieldName:"txtName",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitCreateOrEditEmailTemplate()"}),fnSubmit:submitCreateOrEditEmailTemplate,arrExtraHeaderButtons:b?[a?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Email Template",doubleQuoteEncodedOnClickJS:"confirmDeleteEmailTemplate("+b+",unescape('"+escape(c.name)+"'),1)"}):"",a?'':"",cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayEmailTemplateEventLog("+b+")"})]:0});d.addTextFieldRow("txtName",{rawLabel:"Template Name",mnemonicChar:"n",fieldValue:c.name});d.addFlexibleFieldRow({labelHTML:"From Email",rawValue:c.fromEmailAddress});d.addTextFieldRow("txtFromName",{labelHTML:"From Name",fieldValue:c.fromName});d.addTextFieldRow("txtSubject",{rawLabel:"Subject",mnemonicChar:"j",fieldValue:c.subject});d.addTextAreaFieldRow("txtBody",{rawLabel:"Body",mnemonicChar:"b",unencodedText:c.body,fieldId:"txtBody",textAreaClasses:"largeTextArea"});d.addFlexibleFieldRow({valueHTML:'"});d.addCheckboxRow("chkDunning",{rawLabel:"Dunning Email",mnemonicChar:"l",checked:c.dunning});f=d.showClientDialog();if(f){mjtElemData(f,"emailTemplateId",b)}}function showCreateOrEditEmailTemplateDialog(a){jsrsExecuteWithErrorP("Admin2_GetInfoForCreateOrEditEmailTemplate",rsCallbackGetInfoForCreateOrEditEmailTemplate,"Getting info for Email Template",{emailTemplateId:a.emailTemplateId?a.emailTemplateId:""},a)}function showNewEmailTemplateDialog(){showCreateOrEditEmailTemplateDialog({})}function showEditEmailTemplateDialog(b,a){showCreateOrEditEmailTemplateDialog({emailTemplateId:b,emailTemplateName:a})}function submitReorderEmailTemplatesDialog(a){submitReorderP({arrReorderedIds:a,reorderCommandName:"Admin2_ReorderEmailTemplates2",reorderObjectName:"Email Templates",reorderIdsPropertyName:"emailTemplateIds"})}function showReorderEmailTemplatesDialog(a){jsrsExecuteWithErrorP("Admin2_GetEmailTemplatesForReorder",rsCallbackGetObjectsForReorder,"Getting list of Email Templates for re-order",{},{arrayAttrName:"arrEmailTemplates",fnSubmit:submitReorderEmailTemplatesDialog,strReorderWhat:"Email Templates",highlightedId:a})}function getEmailTemplateSelectionOption(a){var f=a?a.cboTemplates:0,c=f.options[f.selectedIndex].value,e=!!c,b=e?JSON.parse(unescape(c)):{subject:"",fromName:"",body:""},d={isTemplateSelected:e,objET:b};return d}function submitEmail(g,f){var a=new FormValidator(),b=getEmailTemplateSelectionOption(g),c=b.objET,i=g.txtMessageRecipient,e=g.txtFromName,d=g.txtSubject,h=g.txtBody;if(!b.isTemplateSelected){showInfoDialog("Please select an email template","No Email Template Selected",1,"cboTemplate");return}if(!a.CSValidateRequiredField(e,'Please enter a sender name in the "From" field.')){return}if(!a.CSValidateRequiredField(i,'Please enter a recipient in the "To" field.')){return}if(!a.CSValidateRequiredField(d,"Please enter a Subject.")){return}if(!a.CSValidateRequiredField(h,"Please enter a message body.")){return}jsrsExecuteWithErrorP("Admin2_SendInvoiceEmail2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Sending email",{invoiceId:f.invoiceId,emailTemplateId:c.id,fromName:e.value,recipient:i.value,subject:d.value,body:h.value})}function updateEmailForTemplate(){var b=getObj("frmEmail"),a=getEmailTemplateSelectionOption(b);if(b){b.txtSubject.value=a.objET.subject;b.txtFromName.value=a.objET.fromName;b.txtBody.value=a.objET.body}}function rsCallbackGetInfoToCreateInvoiceEmail(g,c){var f=c.originalOptions,m=g.arrEmailTemplates,j=m.length,d,k="frmEmail",h="",e,b=g.defaultEmailTemplateId,a="",l;for(e=0;e"+htmlEncode(d.name)+""}l="";if(!j){h+='';l=' selected="selected"'}a+=cdBuildReadOnlyFieldRowP({rawLabel:"Customer",rawValue:g.customerName})+cdBuildReadOnlyFieldRowP({rawLabel:"Database",rawValue:g.subdomain})+cdBuildReadOnlyFieldRowP({rawLabel:"Invoice #",rawValue:""+g.invoiceNumber});if(g.resultMessage){a+=cdBuildReadOnlyFieldRowP({rawLabel:"Last Payment Result",rawValue:g.resultMessage+" (Code="+g.resultCode+")"})}a+=cdBuildReadOnlyFieldRowP({rawLabel:"Templates",valueHTML:'"})+'
'+cdBuildTextFieldRowP("txtFromName","From")+cdBuildTextFieldRowP("txtMessageRecipient","To",{isEmail:1,fieldValue:f.toEmailAddress||""})+cdBuildTextFieldRowP("txtSubject","Subject")+cdBuildTextAreaFieldRowP("txtBody","Body",{textAreaClasses:"largeTextArea"});showDialogP(a,k,{formTitle:"Email",focusFieldName:"txtMessageRecipient",okButtonDisplayText:"Send",contextDetailOrFnSubmit:{fnSubmit:submitEmail,callbackData:{invoiceId:f.invoiceId}}});updateEmailForTemplate();forceRescanDialogForNewNodes(k)}function showComposeEmailForInvoiceDialog(c,b,a){jsrsExecuteWithErrorP("Admin2_GetInfoToCreateInvoiceEmail2",rsCallbackHandleStandardJSONResponse,"Retrieving Info to email about Invoice #"+b+"...",{invoiceId:c},{fnOnSuccess:rsCallbackGetInfoToCreateInvoiceEmail,invoiceId:c,toEmailAddress:a})}function buildBouncedEmailDetailRows(a){var b=a.length,d="",e;if(b==1){e=a[0];d='Email Address:'+htmlEncode(e.emailAddress)+'Bounce Type:'+htmlEncode(e.bounceType)+'Details:'+htmlEncode(e.details)+""}else{if(b>1){d='';for(var c=0;c\n"}d+="
Email AddressBounce TypeDetails
'+htmlEncode(e.emailAddress)+""+htmlEncode(e.bounceType)+""+htmlEncode(e.details)+"
"}}return d}function rsCallbackDisplaySentEmailDialog(f,c,i){enableDialogButtons();if(checkResponseForError(f)){var g=JSON.parse(f),b=g.arrBouncedEmails,e=b.length,h=g.isBounced||e,j=g.body!=g.bodyPreSubstition,a=cdBuildReadOnlyFieldRowP({rawLabel:"Sent",rawValue:g.createdTS})+cdBuildReadOnlyFieldRowP({rawLabel:"Created By",rawValue:g.createdBy})+cdBuildReadOnlyFieldRowP({rawLabel:"Recipient",rawValue:g.recipient});if(h){var d=e?2:1;a+='
&#'+getRawFontId(FontIconId_Enum.fiiExclamationInFilledTriangle)+';
Bounced'+(e?''+buildBouncedEmailDetailRows(b)+"
":"")}a+=cdBuildReadOnlyFieldRowP({rawLabel:"From Name",rawValue:g.fromName})+cdBuildReadOnlyFieldRowP({rawLabel:"From Email",rawValue:g.fromEmailAddress})+cdBuildReadOnlyFieldRowP({rawLabel:"Subject",rawValue:g.subject});if(g.bodyIsLikelyHTML){a+=cdBuildSectionHeaderRow({rawTitle:"Body"})+'
'+g.body+"
";if(j){a+=cdBuildSectionHeaderRow({rawTitle:"Body (Pre-Substitution)"})+'
'+g.bodyPreSubstition+"
"}}else{a+=cdBuildSectionHeaderRow({rawTitle:"Body"})+'
'+htmlMultilineEncode(g.body)+"
";if(j){a+=cdBuildSectionHeaderRow({rawTitle:"Body (Pre-Substitution)"})+'
'+htmlMultilineEncode(g.bodyPreSubstition)+"
"}}showDialogP(a,"frmEmailDetails",{formTitle:"Sent Email Details",hideOkButton:1,dialogRowsTableClasses:"limitedFieldWidthDialog"})}}function showSentEmailDialog(a){jsrsExecute(rsCallbackDisplaySentEmailDialog,"Admin_GetSentEmailInfo",[a],hideTimedMessage);displayTimedMessage("Looking up sent email...")}function checkForBouncedEmails(){jsrsExecuteWithErrorP("Admin2_CheckForBouncedEmails",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Checking for bounced emails")}function jtcrmViewDatabaseDetails(a){g_bSkipNavWarning=true;hidePicker();disableDialogButtons();displayTimedMessage("Loading Database...");window.location=pageDatabaseDetail+a}function jtcrmViewAccountDetails(a){g_bSkipNavWarning=true;hidePicker();disableDialogButtons();displayTimedMessage("Loading Account...");window.location=pageCustomerDetail+a}function jtcrmViewInvoiceDetails(a){g_bSkipNavWarning=true;hidePicker();disableDialogButtons();displayTimedMessage("Loading Invoice...");window.location=pageInvoiceDetail+a}function jtcrmViewCreditMemoDetails(a){g_bSkipNavWarning=true;hidePicker();disableDialogButtons();displayTimedMessage("Loading Credit Memo...");window.location=pageCreditMemoDetail+a}function jtcrmViewPaymentDetails(a){g_bSkipNavWarning=true;hidePicker();disableDialogButtons();displayTimedMessage("Loading Payment...");window.location=pagePaymentDetail+a}function submitSearch(a){var b=new FormValidator(),g=a.txtSearchText,c=g.value,d=a.cboSearchTarget,e=d?d.options[d.selectedIndex].value:"",f=pageSearch+"&target="+e+"&search="+mjt_EncodeURIComponent(escape(c));if(!b.CSValidateRequiredField(g,"Please enter a value to search for.")){return}disableDialogButtons();displayTimedMessage("Searching...");g_bSkipNavWarning=true;window.location=f}function submitSearchFromDialog(){var a="frmSearchDlg";submitSearch(getObj(a))}function submitV2JTCRMSearchOnEnter(c,b){var a;if(window.event){a=window.event.keyCode}else{if(c){a=c.which}else{return true}}if(a==13){submitSearch(getObj(b));return false}else{return true}}function quickBooksCustomerGetTypeAheadData(a,c){var b={expectedContextId:null,extraHTMLColumnIndex:2,isInactiveColumnIndex:3,inactiveMeansCompleteColumnIndex:4};b.expectedContextId=jsrsExecute(rsCallbackGetTypeAheadSearchText,"Admin_GetTopQuickbooksCustomerInfosGivenPrefix",[escape(c)],hideTimedMessage,b)}function searchGetTypeAheadData(b,d){var a=b.cboSearchTarget,c={expectedContextId:null,extraHTMLColumnIndex:2,isInactiveColumnIndex:3,inactiveMeansCompleteColumnIndex:4},e=a?a.options[a.selectedIndex].value:"";c.expectedContextId=jsrsExecuteWithErrorP("Admin2_GetTopSearchInfosGivenPrefix2",rsCallbackGetTypeAheadSearchTextJSON,"Retrieving Search Typeahead Info",{searchText:d,searchTargets:e},{idHolder:c,arrayPropertyName:"arrSearchResults",extraHTMLPropertyName:"extraHTML",skipDisableDialogButtons:1})}function searchHandleExplicitSelection(b,a){selectedSearchItemInTypeAhead(b,a)}function buildSearchAreaOption(b,a,d){var c=(a==d?' selected="selected"':"");return'"}function buildSecuredSearchOptions(c){var b="",a=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARRead);if(a){b+=buildSearchAreaOption("Database",SearchSubjectAreas_Enum.ssjDatabase,c)+buildSearchAreaOption("Customer",SearchSubjectAreas_Enum.ssjCustomer,c)+buildSearchAreaOption("Invoice",SearchSubjectAreas_Enum.ssjInvoice,c)+buildSearchAreaOption("Braintree Customer Id",SearchSubjectAreas_Enum.ssjBillingCustomerProcessorId,c)}return b}function showCRMSearchDialog(d,c){if(isDialogShowing()){return}var g="frmSearchDlg",e=''+buildSecuredSearchOptions(c),f='",a="txtSearchText",b=a+".id",h={formId:g,idFieldName:b,handlingEnter:1,stringifiedParams:'{ textFieldName: "'+a+'", formId: "'+g+'", idFieldName: "'+b+'", fnGetTypeAheadData: searchGetTypeAheadData, fnHandleExplicitSelection: searchHandleExplicitSelection}'},i=new ClientDialogBuilder({formId:g,formTitle:"Search",focusFieldName:a,focusFieldOnMobile:1,suppressDialogConfirmer:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Search",mnemonicChar:"s",mnemonicActionJS:"submitSearchFromDialog()"}),fnSubmit:submitSearchFromDialog});i.addTextFieldRow(a,{rawLabel:"Search For",fieldValue:d,typeaheadInfo:h,autofocus:1,suppressAutocomplete:1});i.addFlexibleFieldRow({rawLabel:"Search In",valueHTML:f});i.showClientDialog()}function showV2SearchDialog(){showCRMSearchDialog("","")}function fnAppOverrideDoKeyDown(c){g_lastUserActivityTime=new Date();if(!g_enableKeyboardShortcuts){return}var f;var g=false;try{if(window.event){if(window.event.altKey&&!window.event.ctrlKey&&!window.event.shiftKey){f=window.event.keyCode}else{if(!window.event.altKey&&!window.event.ctrlKey&&!window.event.shiftKey&&(window.event.keyCode==27)){g=true}}}else{if(c){if(c.altKey&&!c.ctrlKey&&!c.shiftKey){f=c.which}else{if(!c.altKey&&!c.ctrlKey&&!c.shiftKey&&(c.which==27)){g=true}}}}}catch(l){return}if(g){if(typeof fnHandleEscapeKey=="function"){fnHandleEscapeKey();return}}if(!f&&!(g&&isDialogShowing())){if(g){hideContextMenu()}return}var j=true;if(isDialogShowing()){if(g){if((g_clientDialogStack&&g_clientDialogStack.length>0)||(g_subdialogStack&&g_subdialogStack.length>0)){if(g_clientDialogStack&&g_clientDialogStack.length){var b=g_clientDialogStack[g_clientDialogStack.length-1],i=b.formId;doCloseOrCancelClientDialog(i,b.isSubdialog)}else{hideSubdialog()}}else{hideDialogP({callback:function(){}})}}else{if(57==f){var h=document.activeElement;if(h){if(h.nodeName=="INPUT"){if(h.type.toUpperCase()!="TEXT"){return}}else{if(h.nodeName!="TEXTAREA"){return}}if(h.readOnly||h.disabled){return}var d=new Date();var k=getLocalDateString(d)+" "+getLocalTimeString(d);if(document.selection&&document.selection.createRange){var a=document.selection.createRange();a.text=k}}}else{if(f){if(czCheckForDialogMnemonics(f)){cancelEvent(c);return 1}}else{j=false}}}}else{switch(f){case 48:break;case 67:break;case 73:break;case 74:break;case 80:break;case 81:break;case 83:showCRMSearchDialog();break;default:j=false}}if(j){cancelEvent(c)}}function drawLine(d,a,c){if(a.length>1){d.beginPath();d.moveTo(a[0][0],a[0][1]);for(var b=1;bw.length){showInfoDialog("Cannot specify more instances than there are datbase product ids. "+c+" instances specified but only "+w.length+" instance(s) on the invoice","Too Many Instances",1,"btnOk");return}for(var t=0;t0){v=v+(v*(a/100))}if(r"+padAndPrefixSignedDollars(v)+" and the invoice is for "+padAndPrefixSignedDollars(r)+".
Are you sure this is what you want?","Confirm Create Credit Memo",{},true,null,"Create Credit Memo");return}}if(!s.length){showInfoDialog("Please select a Product to refund","No Products Selected",1,"btnOk");return}jsrsExecuteWithErrorP("Admin2_CreateCreditMemo2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Creating Credit Memo",{invoiceId:j,creditMemoNumber:o,creditMemoDate:getDateForUrlParam(u.dtCreditMemoDate.value),notes:cdGetExpandingTextFieldValue("txtNotes"),refundsJSON:JSON.stringify({arrRefunds:s})})}function updateNewBulkCreditMemoTotal(){var g=getObj("cellCreditMemoTotal"),d=0,h,b=0;while(1){h=getObj("chkRow"+d);if(!h){break}highlightOneCheckedRow(h);var e="chkRow"+d;if(h.checked){var a=getObj(e+"-data-instances");var c=parseInt(a.value.trim(),10);var f=getObj(e+"-data-amount");var l=getObj(e+"-database-product-ids").value.split(",");var k=parseFloat(f.value.trim().substring(0));var j=getObj(e+"-data-total");if(!isNaN(c)&&!isNaN(k)||c<0||k<0){var m=k*c;j.innerHTML=padAndPrefixSignedDollars(""+m,1);b+=m;f.style.border="none";a.style.border="none"}if(isNaN(k)||k<0){f.style.border="solid 3px #FF0000";j.innerHTML=padAndPrefixSignedDollars("0",1)}if(isNaN(c)||c>l.length||c<0){a.style.border="solid 3px #FF0000";j.innerHTML=padAndPrefixSignedDollars("0",1)}}++d}g.innerHTML=padAndPrefixSignedDollars(b,1);g.setAttribute("data-total",b)}function updateNewCreditMemoTotal(){var b=getObj("cellCreditMemoTotal"),e=0,d,c=0;while(1){d=getObj("chkRow"+e);if(!d){break}highlightOneCheckedRow(d);if(d.checked){var a=getObj("chkRow"+e+"data-amount");var f=parseFloat(a.value);if(!isNaN(f)||f<0){c+=f;a.style.border="none"}else{a.style.border="solid 3px #ff0000"}}++e}b.innerHTML=padAndPrefixSignedDollars(c,1);b.setAttribute("data-total",c)}function writeInvoiceProduct(h,g,e){var a,c=g.refundedAmount?"":' checked="checked"',k=g.refundedAmount?' disabled="disabled"':"",d=g.refundedAmount?" disabled ":"",j="chkRow"+e,b=g.refundedAmount?"":' style="cursor:pointer"',f=g.refundedAmount?g.refundedAmount:g.productInvoicedPrice;if(g.refundedAmount){a="disabledItem"}else{a=(e%2?"oddRow":"evenRow")}h+=' $ x  = '+padAndPrefixSignedDollars(g.count*f,1)+' ';return h}function rsCallbackGetCreateBulkCreditMemoInfo(h,a){var e="frmCreditMemo",l=h.creditMemoNumber,b=h.invoice,u=b.totalDueBeforeTax,k=b.invoiceNumber,n=b.taxRateName,t=b.taxRatePercent,g=t?'(Not Including '+t+"% "+htmlEncode(n)+" Tax)":"",f=new Date(),m=f.getFullYear(),c=f.getMonth(),o=f.getDate(),p="",r=(c+1)+"/"+o+"/"+m,q,j="",s,d=new ClientDialogBuilder({formId:e,formTitle:"New Credit Memo",focusFieldName:"txtCreditMemoNumber",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitCreateBulkCreditMemo()"}),fnSubmit:submitCreateBulkCreditMemo});if(!b.arrProducts.length){showInfoDialog("There are no invoiced products.","No Invoiced Products");return}j+='';for(q=0;q";d.addFlexibleFieldRow({hideRow:1,rawLabel:"",valueHTML:''});d.addFlexibleFieldRow({rawLabel:"Invoice Number",rawValue:""+k});if(t){d.addFlexibleFieldRow({rawLabel:"Tax Rate",valueHTML:htmlEncode(n)+" ("+t+"%)"})}d.addFlexibleFieldRow({rawLabel:"Total Due (Before Tax)",valueHTML:padAndPrefixSignedDollars(u,1)});d.addFlexibleRow({valueHTML:"
"});d.addTextFieldRow("txtCreditMemoNumber",{rawLabel:"Credit Memo Number",fieldValue:l,maxLength:11});d.addDatePickerRow(e,"dtCreditMemoDate",{rawLabel:"Credit Memo Date",strValue:r});d.addSectionHeaderRow({rawTitle:"Products To Refund"});d.addFlexibleRow({valueHTML:j});d.addFlexibleFieldRow({labelHTML:"Total Refund",valueCellId:"cellCreditMemoTotal"});if(g){d.addFlexibleFieldRow({valueHTML:g})}d.addFlexibleRow({valueHTML:"
"});d.addExpandingTextFieldRows("txtNotes",{rawLabel:"Notes",value:p});s=d.showClientDialog();if(s){mjtElemData(s,"invoiceId",a.originalPayload.invoiceId);updateNewBulkCreditMemoTotal()}}function showCreateBulkCreditMemoDialog(a){jsrsExecuteWithErrorP("Admin2_GetCreateBulkCreditMemoInfo2",rsCallbackHandleStandardJSONResponse,"Retrieving Bulk Credit Memo Initialization Info",{invoiceId:a},{fnOnSuccess:rsCallbackGetCreateBulkCreditMemoInfo})}function submitUpdateCreditMemo(i,h){var b=i.txtInvoiceNumber,e=h.id,g="Updating Credit Memo",d=i.dtCreditMemoDate,f=i.txtCreditMemoNumber,c=cdGetExpandingTextFieldValue("txtCreditMemoNotes"),a=new FormValidator();if(!a.CSValidateRequiredField(f,"Please enter a Credit Memo Number")){return}if(!a.CSValidateDateField(d,"Credit Memo Date",false,d.id)){return}jsrsExecuteWithErrorP("Admin2_UpdateCreditMemo",rsCallbackRefreshPageAndScrollPos,g,{creditMemoId:e,creditMemoNumber:trim(f.value),creditMemoDate:getDateForUrlParam(d.value),notes:c})}function rsCallbackGetCreditMemoForEdit(i,d,k){enableDialogButtons();if(checkResponseForError(i)){var f=JSON.parse(i),b=f.id,h="dtCreditMemoDate",j="frmCreditMemo",e=f.creditMemoDate,g=f.creditMemoNumber,c=f.creditMemoNotes,a=cdBuildTextFieldRowP("txtCreditMemoNumber","Credit Memo Number",{fieldValue:g,maxLength:11})+cdBuildDatePickerRow(j,h,"Credit Memo Date",cdCarefullyLocalizeDateValue(e))+cdBuildExpandingTextFieldRowsP("txtCreditMemoNotes","Notes",{value:c});showDialogP(a,j,{formTitle:"Edit Credit Memo",focusFieldName:h,okButtonDisplayText:"Save",arrExtraHeaderButtons:[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedOnClickJS:"hideDialog();confirmDeleteCreditMemo(event,"+b+",unescape('"+escape(g)+"'))",doubleQuoteEncodedTitle:"Delete Credit Memo"})],contextDetailOrFnSubmit:{fnSubmit:submitUpdateCreditMemo,callbackData:{id:b}}})}}function showEditCreditMemoDialog(c,b,d){if(isDialogShowing()){return}var a="Retrieving Credit Memo Info";jsrsExecute(rsCallbackGetCreditMemoForEdit,"Admin_GetCreditMemoInfo",[b],rsErrorCallbackShowErrorDialogAndRefresh,{errorDialogTitle:"Error "+a,skipCenteringEditCMDialog:d?1:0},0,1);displayTimedMessage(a+"...");disableDialogButtons()}function showCreditMemoPage(a){window.location=pageCreditMemoDetail+a}function rsCallbackDeleteCM(a){var b=a.invoiceId;if(b){showInvoicePage(b)}else{refreshPageAndScrollPos()}}function doDeleteCreditMemo(a){jsrsExecuteWithErrorP("Admin2_DeleteCreditMemo",rsCallbackDeleteCM,"Deleting Credit Memo",{creditMemoId:a.creditMemoId})}function confirmDeleteCreditMemo(c,b,a){displaySimpleConfirmationDialog(doDeleteCreditMemo,"Are you sure you want to delete Credit Memo #"+a+"?","Delete Credit Memo",{creditMemoId:b,creditMemoNumber:a})}function doDeleteAllProductsFromInvoice(a){jsrsExecuteWithErrorP("Admin2_DeleteAllInvoiceProducts",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting All Invoice Products",{invoiceId:a.invoiceId})}function doDeleteAllCreditMemoRefunds(a){jsrsExecuteWithErrorP("Admin2_DeleteAllCreditMemoRefunds",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Deleting All Refunds",{creditMemoId:a.creditMemoId})}function doDeleteRefund(a){var b="Deleting Refund";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteCreditMemoRefund",[a.creditMemoRefundId],rsErrorCallbackShowErrorDialog,{errorDialogTitle:"Error "+b},0,1);displayTimedMessage(b+"...")}function submitEditCreditMemoRefund(){var d="frmEditCreditMemoRefund",e=getObj(d),c={},b=mjtElemData(e,"creditMemoRefundId"),a=new FormValidator();if(!a.CSValidateNumberFieldP({field:e.txtRefundAmount,label:"Amount",minValue:0.01,resultValueHolder:c})){return}jsrsExecuteWithErrorP("Admin2_UpdateCreditMemoRefund",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Credit Memo Refund",{creditMemoRefundId:b,amount:c.rc})}function rsCallbackGetCreditMemoRefundForEdit(b){var d=b.creditMemoRefundId,e=b.productName,a=b.amount,f="frmEditCreditMemoRefund",g,c=new ClientDialogBuilder({formId:f,formTitle:"Edit Credit Memo Refund",focusFieldName:"txtRefundAmount",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitEditCreditMemoRefund()"}),fnSubmit:submitEditCreditMemoRefund,arrExtraHeaderButtons:[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedOnClickJS:"hideDialog();confirmDeleteRefund(event,"+d+",unescape('"+escape(e)+"'))",doubleQuoteEncodedTitle:"Delete Credit Memo Refund"})]});c.addFlexibleFieldRow({rawLabel:"Product",rawValue:e});c.addTextFieldRow("txtRefundAmount",{rawLabel:"Amount ($)",fieldValue:""+(a||""),isNumber:1});g=c.showClientDialog();if(g){mjtElemData(g,"creditMemoRefundId",d)}}function showEditCreditMemoRefund(a){jsrsExecuteWithErrorP("Admin2_GetCreditMemoRefundInfo",rsCallbackHandleStandardJSONResponse,"Getting Credit Memo Refund Info",{creditMemoRefundId:a},{fnOnSuccess:rsCallbackGetCreditMemoRefundForEdit})}function confirmDeleteRefund(b,a,c){displaySimpleConfirmationDialog(doDeleteRefund,'Are you sure you want to delete the "'+htmlEncode(c)+'" refund from this Credit Memo?',"Delete Refund",{creditMemoRefundId:a})}function getUpgradeCostUserCountHtml(c,b){var a=c?c:"";if(c!==b){a=""+a+""}return a}function getUpgradeCostProductName(b,d){var c=getUpgradeCostUserCountHtml(b,d);var a="s";if(b===1){a=""}if(b){c="+ "+c+" Additional User"+a}return c}function rsCallbackGetUpgradeCost(c){var b=c.arrLines[0],g="s",h=b.v1ProductName+" Edition",f="= $"+padDollars(b.v1InvoiceAmount,2,1),d="= $"+padDollars(b.v2InvoiceAmount,2,1),i=new ClientDialogBuilder({formTitle:"V2 Upgrade Cost"}),j,a='
';j=!b.counterGoUserQuantity&&!b.v1AdditionalUserCount&&!b.v2AdditionalUserCount;a+='";if(b.v1AdditionalUserCount||b.v2AdditionalUserCount){j=!b.counterGoUserQuantity;a+='"}if(b.counterGoUserQuantity){if(b.counterGoUserQuantity===1){g=""}var e="+ "+b.counterGoUserQuantity+" CounterGo User"+g;a+='"}a+='";if(b.jtSunsettingSpecialPriceActive){a+=''}a+="
Invoice Term: '+b.termName+'
V1 Cost:
   
V2 Cost:
'+h+''+(j?f:"")+''+h+''+(j?d:"")+"
'+getUpgradeCostProductName(b.v1AdditionalUserCount,b.v2AdditionalUserCount)+''+(j?f:"")+''+getUpgradeCostProductName(b.v2AdditionalUserCount,b.v1AdditionalUserCount)+''+(j?d:"")+"
'+e+''+f+''+e+''+d+"
Upgrade Cost= $'+padDollars(b.monthlyUpgradeAmount,2,1)+"
* Note: Receiving Special JT Sunsetting Pricing *
";i.addFlexibleRow({valueHTML:a});i.showClientDialog()}function rsCallbackGetUserCountHistoryForDB(l,d,o){enableDialogButtons();if(checkResponseForError(l)){var f=JSON.parse(l);var j=f.userCounts;var k=[];var c=[];var e=[];var q=[];var b=[];var m=[];for(var h=0;h");for(var s=0;s");u.push('    ');if(t.data.datasets[s].label){u.push(t.data.datasets[s].label)}u.push("")}u.push("");return u.join("")},legend:{display:false},tooltips:{mode:"nearest",intersect:false}};showInfoDialog('',"Users Count History");var p=document.getElementById("userCountHistoryChart").getContext("2d");var a=new Chart(p,{type:"line",data:g,options:r});var n=a.generateLegend();document.getElementById("userCountHistoryChartLegend").innerHTML=n}else{showInfoDialog('
Failed to retrieve the user history count
',"Users Count History")}}function buildCGUserTypeString(a,d){var c=a.isDisabled?0:1,b="";if(a.isCGAdmin){b="Admin";if(d){d.cgInternalUserCount+=c}}else{if(a.isCGAccountUser){b="Account";if(d){d.cgAccountUserCount+=c}}else{if(a.isInternalCGUser){b="Internal";if(d){d.cgInternalUserCount+=c}}}}return b}function buildNVUserTypeString(a,d){var c=a.isDisabled?0:1,b="";if(a.isNVAdmin){b="Admin";if(d){d.nvInternalUserCount+=c}}else{if(a.isInternalNVUser){b="Internal";if(d){d.nvInternalUserCount+=c}}}return b}function buildJTUserTypeString(c,e){var b=c.isDisabled?0:1,a=c.username.toLowerCase()=="moraware",d="";if(c.isJTAdmin){d="Admin";if(e){e.jtInternalUserCount+=a?0:b}}else{if(c.isInternalJTUser){d="Internal";if(e){e.jtInternalUserCount+=a?0:b}}else{if(c.isShopUser){d="Shop";if(e){e.jtShopUserCount+=b}}else{if(c.isExternalJTUser){d="External";if(e){e.jtExternalUserCount+=b}}}}}return d}function rsCallbackGetUserListForDB(l,e,o){enableDialogButtons();if(checkResponseForError(l)){var h=JSON.parse(l),m=h.subdomain,d=o.isCGLicensed,c=o.isNVLicensed,k=o.isJTLicensed,f=h.arrUsers,p,b=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formTitle:m+" Users"}),g=new MWClientTable({tableId:"tblDBUserList",noDataMessage:"No Users Defined!",fnAdditionalRowAttrs:function(t,r,s){var q=t;return"data-rowData='"+escape(JSON.stringify(q))+"'"},fnAdditionalRowClasses:function(s,q,r){if(s.isDisabled){return"inactiveItem"}}}),i={cgInternalUserCount:0,cgAccountUserCount:0,nvInternalUserCount:0,jtInternalUserCount:0,jtShopUserCount:0,jtExternalUserCount:0};f.forEach(function(q){q.cgUserType=buildCGUserTypeString(q,i);q.nvUserType=buildNVUserTypeString(q,i);q.jtUserType=buildJTUserTypeString(q,i);p=p||(q.isDisabled||q.isLocked)});g.addColumn(new MWColumn({columnName:"Username",simpleDisplayColumnPropertyName:"username",sortInfo:{}}));g.addColumn(new MWColumn({columnName:"Email",simpleDisplayColumnPropertyName:"emailAddress",sortInfo:{}}));g.addColumn(new MWColumn({columnName:"Full Name",simpleDisplayColumnPropertyName:"fullName",sortInfo:{}}));var n=g.addColumn(new MWColumn({columnName:"User Type",additionalHeaderClasses:"centerAlign"}));n.addSubColumn(new MWColumn({columnName:"CG",simpleDisplayColumnPropertyName:"cgUserType",sortInfo:{}}));n.addSubColumn(new MWColumn({columnName:"Inv",simpleDisplayColumnPropertyName:"nvUserType",sortInfo:{}}));n.addSubColumn(new MWColumn({columnName:"Sys",simpleDisplayColumnPropertyName:"jtUserType",sortInfo:{}}));var j=function(u,s,r,q){var t=u[s.simpleDisplayColumnPropertyName];if(t){return'&#'+getRawFontId(FontIconId_Enum.fiiCheck)+";"}return""};g.addColumn(new MWColumn({columnName:"Disabled",fnCustomRenderCellContents:j,simpleDisplayColumnPropertyName:"isDisabled",additionalCellClasses:"centerAlign",sortInfo:{}}));g.addColumn(new MWColumn({columnName:"Locked",fnCustomRenderCellContents:j,simpleDisplayColumnPropertyName:"isLocked",additionalCellClasses:"centerAlign",sortInfo:{}}));g.addColumn(new MWColumn({columnName:"Last Login",simpleDisplayColumnPropertyName:"lastLogin",sortInfo:{}}));if(i.cgInternalUserCount+i.cgAccountUserCount>0){b.addSectionHeaderRow({rowClasses:d?"":"inactiveItem",rawTitle:"Enabled Users - CounterGo"+(d?"":" (Not Licensed)")});b.addFlexibleFieldRow({rawLabel:"Internal",rawValue:i.cgInternalUserCount.toString(),additionalRowClasses:(d?"":"inactiveItem ")+(i.cgAccountUserCount?"":"mainUserTotalRow")});if(i.cgAccountUserCount){b.addFlexibleFieldRow({rawLabel:"Account",rawValue:i.cgAccountUserCount.toString(),additionalRowClasses:d?"":"inactiveItem"});b.addFlexibleFieldRow({rawLabel:"Total",rawValue:(i.cgInternalUserCount+i.cgAccountUserCount).toString(),additionalRowClasses:(d?"":"inactiveItem ")+"mainUserTotalRow"})}}if(i.nvInternalUserCount>0){b.addSectionHeaderRow({rowClasses:c?"":"inactiveItem",rawTitle:"Enabled Users - Inventory"+(c?"":" (Not Licensed)")});b.addFlexibleFieldRow({rawLabel:"Internal",rawValue:i.nvInternalUserCount.toString(),additionalRowClasses:(c?"":"inactiveItem ")+"mainUserTotalRow"})}if(i.jtInternalUserCount+i.jtShopUserCount+i.jtExternalUserCount>0){b.addSectionHeaderRow({rowClasses:k?"":"inactiveItem",rawTitle:"Enabled Users - Systemize"+(k?"":" (Not Licensed)")});var a=(i.jtExternalUserCount?1:0)+(i.jtShopUserCount>0?1:0)+(i.jtInternalUserCount>0?1:0)>1;b.addFlexibleFieldRow({rawLabel:"Internal",rawValue:i.jtInternalUserCount.toString(),additionalRowClasses:(k?"":"inactiveItem ")+(a?"":"mainUserTotalRow")});if(i.jtShopUserCount>0){b.addFlexibleFieldRow({rawLabel:"Shop",rawValue:i.jtShopUserCount.toString(),additionalRowClasses:k?"":"inactiveItem "})}if(i.jtExternalUserCount>0){b.addFlexibleFieldRow({rawLabel:"External",rawValue:i.jtExternalUserCount.toString(),additionalRowClasses:k?"":"inactiveItem "})}if(a){b.addFlexibleFieldRow({rawLabel:"Total",rawValue:(i.jtExternalUserCount+i.jtInternalUserCount+i.jtShopUserCount).toString(),additionalRowClasses:(k?"":"inactiveItem ")+"mainUserTotalRow"})}}b.addSectionHeaderRow({titleHTML:"User Detail"+(p?(' '):"")});b.addFlexibleRow({valueHTML:g.buildTableForArray(f)});b.showClientDialog()}}function toggleActiveOnly(){var a=getObj("tblDBUserList"),b=getObj("chkActiveOnly").checked;mwFilterTableRows(a,function(e){var c=1,d=e.getAttribute("data-rowData"),f=d?JSON.parse(unescape(d)):null;if(f){c=!(b&&(f.isDisabled||f.isLocked))}return c})}function getAndShowUserHistory(b){if(isDialogShowing()){return}var a="Retrieving user history";jsrsExecute(rsCallbackGetUserCountHistoryForDB,"Admin_GetUserCountHistoryForDB",[b,512],rsErrorCallbackShowErrorDialog,{errorDialogTitle:"Error "+a},0,1);displayTimedMessage(a+"...")}function getAndShowUserListP(a){if(isDialogShowing()){return}var b="Retrieving user list";jsrsExecute(rsCallbackGetUserListForDB,"Admin_GetUserListForDB",[a.databaseId],rsErrorCallbackShowErrorDialog,{errorDialogTitle:"Error "+b,isCGLicensed:a.isCGLicensed,isNVLicensed:a.isNVLicensed,isJTLicensed:a.isJTLicensed},0,1);displayTimedMessage(b+"...")}function confirmedUpdateSpecificJTJobs(a,b){var e=getListOfCheckedRowValuesWithParams({form:a,buildRCArray:1,minSelected:1,tooFewWarning:"Please select a Job to update",clientDlgParams:{subdialogDismisalFocusFieldName:"chkCheckAllRows",subdialog:1},unescapeValues:1,fnTransformValueForArray:function(f){return JSON.parse(f)}}),c=e.arrValues,d=e.selectedCount;if(!d){return}jsrsExecuteWithErrorP("Admin2_UpdateDatabasesRequiringSynch",rsCallbackHandleStandardJSONResponse,"Updating info in Billing, Internal/Hubspot",{arrDatabases:c},{fnOnSuccess:function(){hideDialog()}})}function buildChangeEntry(c,a,b){return'
'+htmlEncode(c)+' from: '+htmlMultilineEncode(""+(a?a:"None"))+' to: '+htmlMultilineEncode(""+(b?b:"None"))+"
"}function getExternalLinkCellHtml(b){var d=b.hubspotCompanyId,a=b.hubspotCompanyLinkPrefix,c=''+d+"";return c}function getDatabaseDifferencesCellHtml(a){var c=a.databaseInfo,b="";b+="";if(c.deploymentServerDiffers){b+=buildChangeEntry("Hosted Server",c.jtListedDeploymentServer,c.actualDeploymentServer)}if(c.billingLinkDiffers){b+=buildChangeEntry("Billing Link",c.jtListedBillingLink,c.actualBillingLink)}if(c.cgUserCountDiffers){b+=buildChangeEntry("CG User Count",c.jtListedCGUserCount,c.actualCGUserCount)}if(c.nvUserCountDiffers){b+=buildChangeEntry("Inv User Count",c.jtListedNVUserCount,c.actualNVUserCount)}if(c.sysUserCountDiffers){b+=buildChangeEntry("Sys User Count",c.jtListedSysUserCount,c.actualSysUserCount)}if(c.requiresUpdateDueToEdition){b+=buildChangeEntry("Edition",c.jtListedEditionName+" (Id="+c.jtListedEditionId+")",c.actualEditionName+" (Id="+c.actualEditionId+")")}if(c.serverDatabaseLinkDiffers){b+=buildChangeEntry("Server Database Link",c.jtListedServerDatabaseLink,c.actualServerDatabaseLink)}if(c.counterGoActivity.activityStatesDiffer){b+=buildChangeEntry("CG Activity Status",c.counterGoActivity.internalActivityStatusFieldText,c.counterGoActivity.actualActivityStatusText)}if(c.nvInventoryActivity.activityStatesDiffer){b+=buildChangeEntry("Inv Activity Status",c.nvInventoryActivity.internalActivityStatusFieldText,c.nvInventoryActivity.actualActivityStatusText)}if(c.systemizeActivity.activityStatesDiffer){b+=buildChangeEntry("Sys Activity Status",c.systemizeActivity.internalActivityStatusFieldText,c.systemizeActivity.actualActivityStatusText)}if(c.customerStatusDiffers){b+=buildChangeEntry("Lifecycle",c.crmCompanyStatus,c.actualCustomerStatus)}b+="";return b}function rsCallbackGetAllDatabasesRequiringSynch(h){var f=h.databasesWithChanges,q=h.hubspotCompanyLinkPrefix,c=f.arrDatabasesWithChanges,p=c.length,m="frmPromptUpdateJTFields",a=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:m,formTitle:"Synch Database Fields",focusFieldName:"btnOk",fnSubmit:confirmedUpdateSpecificJTJobs}),n="",e,g,i=[["Billing Link",f.billingLinkMismatchTally],["Deployment Server",f.deploymentServerMismatchTally],["CG User Count",f.cgUserCountMismatchTally],["Inv User Count",f.nvUserCountMismatchTally],["Sys User Count",f.sysUserCountMismatchTally],["Edition",f.editionMismatchTally],["Address",f.addressMismatchCount],["Server Database Link",f.serverDatabaseLinkMismatchCount],["CG Activity Status",f.cgActivityStatusMismatchTally],["Inv Activity Status",f.nvActivityStatusMismatchTally],["Sys Activity Status",f.sysActivityStatusMismatchTally]],d,l;if(!p){showInfoDialog("There are currently no databases that require an update.","No Databases To Be Updated");return}a.addFlexibleFieldRow({rawLabel:"Databases Requiring An Update",rawValue:""+p});a.addSectionHeaderRow({rawTitle:"# of Mismatches"});for(d=0;d';var k=e.subdomainName,o=e.jtListedEditionName,b=e;n+=''+htmlEncode(k)+"";n+=getExternalLinkCellHtml({isHubspotChange:e.isHubspotChange,hubspotCompanyId:e.hubspotCompanyId,hubspotCompanyLinkPrefix:q,jobId:e.jobId});if(e.isHubspotCompanyValid){n+=getDatabaseDifferencesCellHtml({databaseInfo:e})}else{n+="Hubpost Company is no longer present by Id"}n+="";if(e.addressesDiffer&&e.isHubspotCompanyValid){n+=buildChangeEntry("Database Address",e.crmListedDBAddress,e.jtListedJobAddress)}else{if(!e.isHubspotCompanyValid){n+="Marking Hubspot Company Id as Invalid (update manually to fix)"}}n+="";n+=""}n+="";n+="";a.addFlexibleRow({valueHTML:n});a.showClientDialog();var j=getObj("chkCheckAllRows");if(j){checkAllRows(j)}}function updateJTFields(){jsrsExecuteWithErrorP("Admin2_GetAllDatabasesRequiringSynch",rsCallbackGetAllDatabasesRequiringSynch,"Getting Databases Requiring An Update")}function rsCallbackDisplayAddUsersToInstancesResults(f){hideDialog();var g=f.results||[],b=g.length,c=f.instancesWithProductOrders,i=f.instancesWithInvoices,j=f.instancesWithChargedInvoices,h="frmShowResultsOfAddingUsersToInstances",a=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:h,formTitle:"Add Users to Instances",fnCancelOrClose:function(){hideDialog();refreshPageAndScrollPos()}}),e=new MWClientTable({});a.addFlexibleFieldRow({rawLabel:"Instances",rawValue:""+b});a.addFlexibleFieldRow({rawLabel:"Product Orders (Created)",rawValue:""+c});a.addFlexibleFieldRow({rawLabel:"Invoices (Created)",rawValue:""+i});a.addFlexibleFieldRow({rawLabel:"Invoices (Charged)",rawValue:""+j});a.addSectionHeaderRow({rawTitle:"Instances"});e.addColumn(new MWColumn({columnName:"Customer",fnCustomRenderCellContents:function(n,m,l,k){return htmlEncode(n.instance.customerName)}}));e.addColumn(new MWColumn({columnName:"Database",fnCustomRenderCellContents:function(n,m,l,k){return htmlEncode(n.instance.subdomain)},fnBuildCellLinkDetail:function(n,l,k,m){return mwBuildSimpleLink(pageDatabaseDetail+n.instance.databaseId,1)}}));e.addColumn(new MWColumn({columnName:"Product Order Prorated Total",fnCustomRenderCellContents:function(n,m,l,k){return padAndPrefixSignedDollarsP({dollarValue:n.productOrderProratedTotal,forceDecimalsWhenNone:1})}}));e.addColumn(new MWColumn({columnName:"Unpaid Invoices Total",fnCustomRenderCellContents:function(n,m,l,k){return padAndPrefixSignedDollarsP({dollarValue:n.unpaidInvoicesTotal,forceDecimalsWhenNone:1})}}));e.addColumn(new MWColumn({columnName:"Status",fnCustomRenderCellContents:function(o,m,l,k){var n="Could not create Product Order";if(o.chargedInvoices){n="Success"}else{if(o.createdInvoices){n="Invoices Created but not Charged"}else{if(o.createdProductOrders){n="Product Order Created but not Invoiced"}}}return n}}));e.addColumn(new MWColumn({columnName:"Status Message",simpleDisplayColumnPropertyName:"statusMessage",simpleDisplayColumnNeedsMultilineEncoding:true}));var d=e.buildTableForArray(g);a.addFlexibleRow({valueHTML:d});a.showClientDialog()}function confirmedAddUsersToSpecificInstances(a,b){var e=getListOfCheckedRowValuesWithParams({form:a,buildRCArray:1,minSelected:1,tooFewWarning:"Please select an Instance",clientDlgParams:{subdialogDismisalFocusFieldName:"chkCheckAllRows",subdialog:1},unescapeValues:1,fnTransformValueForArray:function(f){return JSON.parse(f)}}),c=e.arrValues,d=e.selectedCount;if(!d){return}jsrsExecuteWithErrorP("Admin2_AddAdditionalUsersToInstances",rsCallbackHandleStandardJSONResponse,"Adding Additional Users to Selected Instances",{arrInstancesWithAddedUsers:c},{fnOnSuccess:rsCallbackDisplayAddUsersToInstancesResults})}function rsCallbackGetInstancesWithAdditionalUsers(f){var c=f.instances||[],k=c.length,h=f.nextInvoiceDate,i="frmPromptAddUsersToInstances",a=new ClientDialogBuilder({dialogRowsTableClasses:"limitedFieldWidthDialog",formId:i,formTitle:"Add Users to Instances",focusFieldName:"btnOk",okButtonDisplayText:"Create & Pay Invoices",fnSubmit:confirmedAddUsersToSpecificInstances}),d=new MWClientTable({fnGetCheckDetailsForRow:function(n,l,m){return{value:htmlEncode(JSON.stringify(n))}}});if(!k){showInfoDialog("There are currently no instances with additional users added outside the time period.","No Instances To Be Updated");return}a.addFlexibleFieldRow({rawLabel:"Instances with additional users",rawValue:""+k});if(h){a.addFlexibleFieldRow({rawLabel:"Filtered to Next Invoice Date",rawValue:getLocalDateString(new Date(h))})}a.addSectionHeaderRow({rawTitle:"Instances To Update"});d.addColumn(new MWColumn({columnName:"Customer",simpleDisplayColumnPropertyName:"customerName"}));d.addColumn(new MWColumn({columnName:"Database",simpleDisplayColumnPropertyName:"subdomain",fnBuildCellLinkDetail:function(o,m,l,n){return mwBuildSimpleLink(pageDatabaseDetail+o.databaseId,1)}}));var e=d.addColumn(new MWColumn({columnName:"Additional Users",additionalHeaderClasses:"centerAlign"}));e.addSubColumn(new MWColumn({columnName:"CounterGo",simpleDisplayColumnPropertyName:"additionalCounterGoUserCount"}));e.addSubColumn(new MWColumn({columnName:"Inventory",simpleDisplayColumnPropertyName:"additionalNVInventoryUserCount"}));e.addSubColumn(new MWColumn({columnName:"Systemize",simpleDisplayColumnPropertyName:"additionalSystemizeUserCount"}));var j=d.addColumn(new MWColumn({columnName:"Last Change",additionalHeaderClasses:"centerAlign"}));j.addSubColumn(new MWColumn({columnName:"Time",fnCustomRenderCellContents:function(p,n,m,l){var o=new Date(p.lastChangeTime);return getLocalDateString(o)+" - "+getLocalTimeString(o)}}));j.addSubColumn(new MWColumn({columnName:"Hours",simpleDisplayColumnPropertyName:"stableAgeInHours"}));d.addColumn(new MWColumn({columnName:"Next Invoice Date",fnCustomRenderCellContents:function(p,n,m,l){var o=new Date(p.nextInvoiceDate);return getLocalDateString(o)}}));var b=d.buildTableForArray(c);a.addFlexibleRow({valueHTML:b});a.showClientDialog();var g=getObj(i);if(g){g.chkCheckAllRows.checked=true;checkAllRows(g.chkCheckAllRows)}}function addUsersToJTInstances(b){b=b||{};var a=b.requireNextInvoiceDateBeTomorrow;jsrsExecuteWithErrorP("Admin2_GetInstancesWithAdditionalUsers",rsCallbackGetInstancesWithAdditionalUsers,"Getting Instances With Additional Users",{requireNextInvoiceDateBeTomorrow:a})}var InvoicePaymentOption_Enum={ipoOverall:1,ipoSingleInvoice:2};function submitMakePaymentOnInvoices(){var e="frmMakePaymentOnInvoices",h=getObj(e),b=parseInt(getSelectedRBValue(h,"rbPaymentOption"),10),g=b===InvoicePaymentOption_Enum.ipoOverall,c=getCallbackDataOfDialog(h),a=c.amountOutstanding,f=c.databaseBalanceInfo,d=c.invoiceId;hideDialog();jsrsExecuteWithErrorP("Admin2_MakePaymentOnInvoices",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Making Payment",{billingProcessorCustomerId:c.billingProcessorCustomerId,databaseId:c.databaseId,amount:g?f.databaseBalance:a,arrInvoiceAmounts:g?f.arrInvoiceAmounts:[{invoiceId:d,amount:a}],paymentProviderType:PaymentProcessorType_Enum.pptBraintree})}function doPromptMakePaymentOnInvoices(g,e){enableDialogButtons();var f=e.originalPayload.invoiceId,d=g.databaseBalanceInfo,c=g.billingProcessorCustomerId,b=g.invoiceNumber,j=g.databaseId,i="frmMakePaymentOnInvoices",h=g.amountOutstanding,a=new ClientDialogBuilder({formId:i,formTitle:"Make Payment",focusFieldName:d?"rbPaymentOption_Overall":"",focusFieldOnMobile:1,suppressDialogConfirmer:1,okButtonDisplayText:"Make Payment",fnSubmit:submitMakePaymentOnInvoices,callbackData:{billingProcessorCustomerId:c,databaseId:j,invoiceId:f,amountOutstanding:h,databaseBalanceInfo:d}});a.addFlexibleFieldRow({rawLabel:"Braintree Id",rawValue:c});a.addFlexibleFieldRow({rawLabel:"Invoice #",rawValue:""+b});a.addFlexibleFieldRow({rawLabel:"Invoice Total",rawValue:"$"+padDollars(g.invoiceTotal,1,0)});if(g.amountPaid){a.addFlexibleFieldRow({rawLabel:"Amount Paid",rawValue:"$"+padDollars(g.amountPaid,1,0)});a.addFlexibleFieldRow({rawLabel:"Amount Outstanding",rawValue:"$"+padDollars(g.amountOutstanding,1,0)})}a.addSectionHeaderRow();if(d){a.addRadioButtonRow({rawRowLabel:"Payment Amount:",labelHTML:'Total Balance: $'+padDollars(d.databaseBalance,1,1)+"",fieldName:"rbPaymentOption",fieldId:"rbPaymentOption_Overall",fieldValue:""+InvoicePaymentOption_Enum.ipoOverall,checked:true});a.addRadioButtonRow({labelHTML:'Just this invoice: $'+padDollars(h,1,1)+"",fieldName:"rbPaymentOption",fieldId:"rbPaymentOption_Invoice",fieldValue:""+InvoicePaymentOption_Enum.ipoSingleInvoice})}else{a.addFlexibleFieldRow({rawLabel:"Payment Amount",rawValue:"$"+padDollars(h,1,1),additionalRowClasses:"bold"})}a.showClientDialog()}function promptMakePaymentOnInvoices(a){jsrsExecuteWithErrorP("Admin2_GetInfoToPayInvoice",doPromptMakePaymentOnInvoices,"Retrieving Invoice Info To Make Payment",{invoiceId:a})}function toggleExpandAddressExtras(){var a=getObj("imgAddressExtrasExpander.expand"),b=!a.style.display;a.style.display=b?"none":"";getObj("imgAddressExtrasExpander.collapse").style.display=b?"":"none";getObj("divAddressExtras").style.display=b?"":"none"}function rsCallbackInitSession(c,a,b){enableDialogButtons();if(checkResponseForError(c)){window.open(b.url,"_blank")}}function rsCallbackOpenedCustomerPortal(g,c,k){enableDialogButtons();if(checkResponseForError(g)){var e=JSON.parse(g),a=e.error;if(a){var d=a.errorMessage,h=a.errorTitle,l=a.requiresRefresh;showInfoDialogWithConsequenceP({formTitle:h,rawValue:d,fnConsequence:l?rsCallbackRefreshPageAndScrollPos:0})}else{var b=e.userId,f=e.url,j=e.sessionId,i="Initializing Session";jsrsExecute(rsCallbackInitSession,"Portal_InitSession",[b,escape(j)],rsErrorCallbackShowErrorDialogAndRefresh,{url:f,errorDialogTitle:"Error "+i},0,1,f);displayTimedMessage(i+"...");disableDialogButtons()}}}function launchCustomerPortal(b){var a="Connecting to Customer Portal...";jsrsExecute(rsCallbackOpenedCustomerPortal,"Admin_OpenCustomerPortal",[b],rsErrorCallbackShowErrorDialogAndRefresh,{errorDialogTitle:"Error "+a},0,1);displayTimedMessage(a+"...");disableDialogButtons()}function showPortalUsageReportOptions(){showInfoDialog("Options?

We don't need no stinkin' options!","TODO: showPortalUsageReportOptions()")}function rsCallbackShowDBsWithUngeneratedNonMonthlyTotals(d,b,c){enableDialogButtons();if(checkResponseForError(d)){var e=JSON.parse(d),a=new MWClientTable({noDataMessage:"No Databases With Ungenerated Invoices"});a.addColumn(new MWColumn({columnName:"Customer",fnCustomRenderCellContents:function(i,h,g,f){return htmlEncode(i.database[0].gdCustomerName)}}));a.addColumn(new MWColumn({columnName:"Database",fnCustomRenderCellContents:function(j,i,h,g){var f=j.database[0].gdSubdomainName;if(!f){f="Non-Hosted DB (Id="+j.database[0].gdDatabaseId+")"}return htmlEncode(f)},fnBuildCellLinkDetail:function(i,g,f,h){return mwBuildSimpleLink(pageDatabaseDetail+i.database[0].gdDatabaseId,1)}}));a.addColumn(new MWColumn({columnName:"Invoice Amount",fnCustomRenderCellContents:function(i,h,g,f){return padAndPrefixSignedDollars(i.amount,1)}}));a.addColumn(new MWColumn({columnName:"Invoice Date",fnCustomRenderCellContents:function(i,h,g,f){return getDateAsDisplayString(new Date(e[0].date))}}));a.addColumn(new MWColumn({columnName:"Term",fnCustomRenderCellContents:function(i,h,g,f){return c.Term}}));showInfoDialog(a.buildTableForArray(e),"Databases With Ungenerated Invoices");scrollDialogIfNecessary("frmTmpMessage",1,1)}}function showDBsWithUngeneratedNonMonthlyTotals(b,a){var c="Finding databases...";jsrsExecute(rsCallbackShowDBsWithUngeneratedNonMonthlyTotals,"Admin_GetDatabasesWithUngeneratedTotals",[b,a],rsErrorCallbackShowErrorDialogAndRefresh,{errorDialogTitle:"Error "+c,DayOfMonth:a,Term:b},0,1);displayTimedMessage(c+"...");disableDialogButtons()}function registerChartPlugins(){Chart.plugins.register({afterDatasetsDraw:function(b,c){if(!b.data.showPointLabels){return}var a=b.chart.ctx;b.data.datasets.forEach(function(f,d){var e=b.getDatasetMeta(d);if(!e.hidden){e.data.forEach(function(j,i){a.fillStyle="rgb(0, 0, 0)";var l=12;var n="normal";var h="arial, helvetica, sans-serif";a.font=Chart.helpers.fontString(l,n,h);var k=f.data[i].toString();a.textAlign="center";a.textBaseline="middle";var m=5;var g=j.tooltipPosition();a.fillText(k,g.x,g.y-(l/2)-m)})}})}})}function submitVoidPayment(a,b){jsrsExecuteWithErrorP("Admin2_PerformVoidPayment",refreshPageAndScrollPos,"Retrieving Payment Info for Void Payment...",{paymentId:b.paymentId,amount:b.amount})}function rsCallbackGetInfoForVoidPayment(c,e){var b=e.originalPayload,d="frmConfirmVoidPayment",a=new ClientDialogBuilder({formId:d,formTitle:"Void Payment",okButtonDisplayText:"Void Payment",fnSubmit:submitVoidPayment,callbackData:c});a.addFlexibleFieldRow({rawLabel:"Payment Timestamp",rawValue:c.strPaymentTS});a.addFlexibleFieldRow({rawLabel:"Transaction Id",rawValue:c.transactionId});a.addFlexibleFieldRow({rawLabel:"Amount",valueHTML:padAndPrefixSignedDollars(c.amount,1)});a.showClientDialog()}function showCreateVoidingPaymentDialog(a){jsrsExecuteWithErrorP("Admin2_GetInfoForVoidPayment",rsCallbackGetInfoForVoidPayment,"Retrieving Payment Info for Void Payment...",{paymentId:a})}function submitRefundPayment(a,b){jsrsExecuteWithErrorP("Admin2_PerformRefundPayment",refreshPageAndScrollPos,"Retrieving Payment Info for Refund Payment...",{paymentId:b.paymentId,amount:b.amount})}function rsCallbackGetInfoForRefundPayment(b,e){var d=b.amount,c="frmConfirmRefundPayment",a=new ClientDialogBuilder({formId:c,formTitle:"Refund Payment",okButtonDisplayText:"Refund Payment",fnSubmit:submitRefundPayment,callbackData:b});a.addFlexibleFieldRow({rawLabel:"Payment Timestamp",rawValue:b.strPaymentTS});a.addFlexibleFieldRow({rawLabel:"Transaction Id",rawValue:b.transactionId});a.addFlexibleFieldRow({rawLabel:"Amount",valueHTML:padAndPrefixSignedDollars(d,1)});a.showClientDialog()}function showCreateRefundPaymentDialog(a){jsrsExecuteWithErrorP("Admin2_GetInfoForRefundPayment",rsCallbackGetInfoForRefundPayment,"Retrieving Payment Info for Refund Payment...",{paymentId:a})}function submitCreateCreditMemoRefund(){var g="frmRefund",e=getObj(g),b=getCallbackDataOfDialog(e),d=b.creditMemoId,c=getSelectedRB(e,"rbPayment"),f=c.getAttribute("data-paymentId"),i=e.txtRefundAmount,h={},a=new FormValidator();if(!a.CSValidateNumberFieldP({field:i,label:"Refund Amount",resultValueHolder:h})){return}jsrsExecuteWithErrorP("Admin2_ProcessCreditMemoCredit",refreshPageAndScrollPos,"Processing Refund",{paymentId:f,creditMemoId:d,amount:h.rc})}function rsCallbackGetPaymentsForCreditMemoRefund(i,d){var e=d.originalPayload,b=i.creditMemoAmount,a=i.amountCredited,l=i.remainingAmount,m=i.arrPayments,h=m?m.length:0,g=h?m[0]:0,c=h?Math.min(l,g.amount):l,k="frmRefund",f=new MWClientTable({noDataMessage:"No Payments"}),j=new ClientDialogBuilder({formId:k,formTitle:"New Refund",focusFieldName:h?"txtRefundAmount":"",okButtonDisplayText:"Process Refund",fnSubmit:submitCreateCreditMemoRefund,callbackData:{creditMemoId:e.creditMemoId}});if(!h){showInfoDialog("No payments available","No Payments");return}f.addColumn(new MWColumn({columnName:"Transaction Id",fnCustomRenderCellContents:function(q,p,o,n){return'"}}));f.addColumn(new MWColumn({columnName:"Timestamp",simpleDisplayColumnPropertyName:"paymentTS"}));f.addColumn(new MWColumn({columnName:"Amount",additionalCellClasses:"rightAlign",fnCustomRenderCellContents:function(q,p,o,n){return padAndPrefixSignedDollars(q.amount,1)}}));j.addFlexibleFieldRow({rawLabel:"Credit Memo Amount",rawValue:padAndPrefixSignedDollars(b,1)});if(a){j.addFlexibleFieldRow({rawLabel:"Amount Credited",rawValue:padAndPrefixSignedDollars(a,1)})}j.addSectionHeaderRow({rawTitle:"Payment"});j.addFlexibleRow({valueHTML:f.buildTableForArray(m),hideRow:h==1});if(h==1){j.addFlexibleFieldRow({rawLabel:"Payment Transaction Id",rawValue:g.transactionId});j.addFlexibleFieldRow({rawLabel:"Timestamp",rawValue:g.paymentTS});j.addFlexibleFieldRow({rawLabel:"Amount",rawValue:padAndPrefixSignedDollars(g.amount,1)})}j.addTextFieldRow("txtRefundAmount",{rawLabel:"Refund Amount ($)",fieldValue:padDollars(c,1)});j.showClientDialog()}function showCreateRefundDialog(a){jsrsExecuteWithErrorP("Admin2_GetPaymentsForCreditMemoRefund",rsCallbackGetPaymentsForCreditMemoRefund,"Getting Payments available for a refund",{creditMemoId:a})}function buildTaxStateSelectionDropdown(a,c,b){return'"}function doBuildTaxRateBatch(){var c=getObj("frmBuildTaxRateBatch"),a=c.cboState,b=a.value;if(!b){showInfoDialog("Please select a state","No State Selected",1,a.name);return}jsrsExecuteWithErrorP("Admin2_BuildTaxRateBatch",refreshPageAndScrollPos,"Building Tax Rate Batch",{state:b})}function buildTaxRateBatch(a){var b="cboState",c=new ClientDialogBuilder({formId:"frmBuildTaxRateBatch",formTitle:"Build Tax Rate Batch",suppressDialogConfirmer:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Build Batch",mnemonicChar:"b",mnemonicActionJS:"doBuildTaxRateBatch()"}),fnSubmit:doBuildTaxRateBatch,focusFieldName:b});c.addFlexibleFieldRow({rawLabel:"State",valueHTML:buildTaxStateSelectionDropdown(a,b,"-Select a State-")});c.showClientDialog()}function submitTaxRateReconciliationReportOptions(){var e="frmOptions",g=getObj(e),a=new FormValidator(),c=g.txtPageSize,b=trim(c.value),d=trim(g.cboState.value),f="";if(!a.CSValidateIntegerField(c,"Page Size",true,1,2000)){return}if(b){f+="&pageSize="+b}if(d){f+="&state="+d}if(g.chkIncludeValidRows.checked){f+="&includeValidRows=1"}if(f){f=f.substring(1)}hideDialog();window.location=pageTaxRateReconciliationReport+f}function showTaxRateReconciliationReportOptions(b){var d="frmOptions",a="cboState",c=new ClientDialogBuilder({formId:d,formTitle:"Report Options",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitTaxRateReconciliationReportOptions()"}),focusFieldName:a,focusFieldOnMobile:1,fnSubmit:submitTaxRateReconciliationReportOptions});c.addFlexibleFieldRow({rawLabel:"State",valueHTML:buildTaxStateSelectionDropdown(b.state,a,"-Any-")});c.addFlexibleFieldRow({valueHTML:cdBuildCheckboxAndLabel("chkIncludeValidRows","chkIncludeValidRows","Include Valid Rows",b.includeValidRows)});c.addSectionHeaderRow();c.addTextFieldRow("txtPageSize",{rawLabel:"Rows per Page",fieldValue:""+(b.pageSize||""),maxLength:10,isNumber:1,suppressAutocomplete:1});c.showClientDialog()}function submitEditAttachedFile(){var e=getObj("editAttachFile"),d=null,a=e.objectId.value,b=e.fileId.value,c="Updating File";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_UpdateAttachedFile",[a,b,escape(d)],enableDialogButtons);displayTimedMessage(c+"...");disableDialogButtons()}function confirmDeleteAttachedFile(b,a,c){promptConfirmDeleteFile(b,a,null,c,"Admin_DeleteAttachedFile",true)}function submitAttachFile(){if(g_arrFileDragDropFileInfos.length){doUploadFiles(getObj("attachFile"))}else{hideDialog()}}function showAttachFile(b,c,d,a){var f="attachFile",e=new ClientDialogBuilder({formId:f,formTitle:"Attach File",formAction:pageUploadAttachedFile,focusFieldName:"fileName",isSubdialog:a?1:0,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Attach",mnemonicChar:"a",mnemonicActionJS:a?a:"submitAttachFile()"}),fnSubmit:a?a:submitAttachFile});e.addFileUploadRow({fileLimit:1,isIMage:1,fileType:d,objectId:c,includeLabelForImage:false,existingImageUrl:null,uploadLabel:"Drag or paste file here"});e.showClientDialog()}function deleteExpenseQuickbooksCustomer(a){var b="Deleting Quickbooks Vendor...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseQuickbooksCustomer",[a.expenseQuickbooksCustomerId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(b+"...");disableDialogButtons()}function deleteExpenseVendor(a){var b="Deleting Expense Vendor...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseVendor",[a.expenseVendorId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(b+"...");disableDialogButtons()}function deleteBusinessReason(a){var b="Deleting Business Reason...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteBusinessReason",[a.expenseDetailId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(b+"...");disableDialogButtons()}function deleteExpenseReport(a){jsrsExecuteWithErrorP("Admin2_DeleteExpenseReport",function(b){hideDialog();window.location=pageExpenses},"Deleting Expense Report...",{expenseReportId:a.expenseReportId})}function deleteImporBlocklist(a){var b="Deleting from Import Blocklist...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseImportBlocklist",[a.expenseImportBlocklistId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(b+"...");disableDialogButtons()}function confirmDeleteExpenseReport(a){displaySimpleConfirmationDialogP(deleteExpenseReport,'Are you sure you want to delete this Expense Report"?',{formTitle:"Delete Expense Report",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseReportId:a}})}function confirmDeleteExpenseImportBlocklist(a,b){displaySimpleConfirmationDialogP(deleteImporBlocklist,'Are you sure you want to delete Import Blocklist entry "'+b+'"?',{formTitle:"Delete From Expense Import Blocklist",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseImportBlocklistId:a}})}function confirmDeleteQuickbooksCustomer(a,b){displaySimpleConfirmationDialogP(deleteExpenseQuickbooksCustomer,'Are you sure you want to delete the Quickbooks Vendor "'+htmlEncode(b)+'"?',{formTitle:"Delete Quickbooks Vendor",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseQuickbooksCustomerId:a}})}function confirmDeleteExpenseVendor(a,b){displaySimpleConfirmationDialogP(deleteExpenseVendor,'Are you sure you want to delete Vendor "'+htmlEncode(b)+'"?',{formTitle:"Delete Expense Vendor",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseVendorId:a}})}function confirmDeleteBusinessReason(c,a){var b=getObj("txtSummary");if(b){b=b.innerHTML}displaySimpleConfirmationDialogP(deleteBusinessReason,'Are you sure you want to delete the Business Reason "'+b+'"?',{formTitle:"Delete Business Reason",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseDetailId:c}})}function confirmDeleteExpenseReportDetail(b){var a=getObj("txtSummary");if(a){a=a.innerHTML}displaySimpleConfirmationDialogP(function(){var c="Deleting Expense Report Detail...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseReportDetail",[b],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(c+"...");disableDialogButtons()},'Are you sure you want to delete the Expense Report Detail "'+a+'"?',{formTitle:"Delete Expense Report Detail",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{expenseReportDetailId:b}})}function deleteExpenseType(a){var b="Deleting Expense Type...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseType",[a.typeId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(b+"...");disableDialogButtons()}function confirmDeleteExpenseType(a,b){displaySimpleConfirmationDialogP(deleteExpenseType,'Are you sure you want to delete the type "'+b+'"?',{formTitle:"Delete Expense Type",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{typeId:a}})}function deleteExpenseTrip(a){var b="Deleting Expense Trip...";jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_DeleteExpenseTrip",[a.tripId],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(b+"...");disableDialogButtons()}function confirmDeleteExpenseTrip(b,a){displaySimpleConfirmationDialogP(deleteExpenseTrip,'Are you sure you want to delete the trip "'+htmlEncode(a)+'" trip?',{formTitle:"Delete Expense Trip",okButtonDisplayText:"Delete",isSubdialog:true,contextDetail:{tripId:b}})}function submitaddOrUpdateExpenseTrip(){var f=getObj("addOrUpdateExpenseTrip"),b=f.txtLocation.value,d=f.year.value,h=f.cboMonth[f.cboMonth.selectedIndex].value,g=parseInt(d,10),e=f.tripId.value,a=f.chkIsDisabled.checked,c="Adding Trip...";if(""===b){showInfoDialog("Location is required","Missing Field",1,"txtLocation");return}if(isNaN(g)||g<=2017){showInfoDialog("Year must be a whole number greater than 2017","Missing Field",1,"year");return}jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_AddOrUpdateExpenseTrip",[e,d,h,escape(b),a?1:0],enableDialogButtons);displayTimedMessage(c+"...");disableDialogButtons()}function getMonthOptionElements(d){var b="";var c=new Date();var a="en-us";for(var e=0;e<12;e++){b+=buildOptionHTML((new Date(2018,e)).toLocaleString(a,{month:"long"}),e,d)}return b}function addOrUpdateExpenseTrip(d,b,h,g,c,a){var f="addOrUpdateExpenseTrip",e=new ClientDialogBuilder({formId:f,formTitle:d?"Edit Trip":"Add Trip",focusFieldName:"year",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:d?"Save":"Add",mnemonicChar:d?"s":"a",mnemonicActionJS:"submitaddOrUpdateExpenseTrip()"}),fnSubmit:submitaddOrUpdateExpenseTrip,arrExtraHeaderButtons:d?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseTrip("+d+", unescape('"+escape(c)+"'))"})]:null});e.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});e.addFlexibleFieldRow({additionalValueCellClasses:"clsNarrowField",rawLabel:"Year",valueHTML:''});e.addFlexibleFieldRow({rawLabel:"Month",valueHTML:'"});e.addTextFieldRow("txtLocation",{rawLabel:"Name & Location",maxLength:80,fieldValue:g,additionalFieldCellClasses:"tripNameAndLocation"});e.addCheckboxRow("chkIsDisabled",{labelHTML:"Disabled",checked:a,hideRow:d?false:true});e.showClientDialog()}function submitAddOrUpdateExpenseType(){var e=getObj("addOrUpdateExpenseType"),c=e.txtName.value,d=e.txtAccountingId.value,a=e.typeId.value,b=e.chkIsDisabled.checked;if(""===c){showInfoDialog("Name is required","Missing Field",1,"name");return}if(""===d){showInfoDialog("Quickbooks Id is required","Missing Field",1,"txtAccountingId");return}jsrsExecuteWithErrorP("Admin2_AddOrUpdateExpenseType2",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,a?"Updating Expense Type":"Adding Expense Type",{expenseTypeId:a,expenseTypeName:c,quickbooksId:d,isDisabled:b?1:0})}function addOrUpdateExpenseType(b,c,d,a){var f="addOrUpdateExpenseType",e=new ClientDialogBuilder({formId:f,formTitle:b?"Edit Expense Type":"Add Expense Type",focusFieldName:"txtName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:b?"Save":"Add",mnemonicChar:b?"s":"a",mnemonicActionJS:"submitAddOrUpdateExpenseType()"}),fnSubmit:submitAddOrUpdateExpenseType,arrExtraHeaderButtons:b?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseType("+b+", unescape('"+escape(c)+"'))"})]:null});e.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});e.addTextFieldRow("txtName",{rawLabel:"Name",maxLength:80,fieldValue:c});e.addTextFieldRow("txtAccountingId",{rawLabel:"Quickbooks Id",maxLength:80,fieldValue:d});e.addCheckboxRow("chkIsDisabled",{labelHTML:"Disabled",checked:a,hideRow:b?false:true});e.showClientDialog()}function submitAddOrUpdateExpenseVendor(k,f,c){var b=getObj("frmExpenseVendor"),m=b.expenseVendorId.value,r=b.txtName.value,n=b.quickbooksCustomerId.value,j=b.txtQuickbooksCustomer.value,p=b.txtReason.value,a=b.cboAmexDescriptionMatchType[b.cboAmexDescriptionMatchType.selectedIndex].value,e=b.cboAmexAppearsOnStatementAsMatchType[b.cboAmexAppearsOnStatementAsMatchType.selectedIndex].value,l=b.txtAmexAppearsOnStatementAs.value,o=b.txtAmexDescription.value,d=b.cboType[b.cboType.selectedIndex].value,i=b.chkIsDisabled.checked,g=b.chkIsGeneric.checked,h=b.chkIncludeOnMemo.checked,q=m?"Updating Expense Vendor...":"Adding Expense Vendor...";if(!n&&c){n=c}if(!n){if(""===j){showInfoDialog("Quickbooks Vendor is required","Missing Field",1,"year");return}if(f){displaySimpleConfirmationDialog(function(){jsrsExecute(function(s){if(checkResponseForError(s)){var t=JSON.parse(s);submitAddOrUpdateExpenseVendor(k,true,t.quickbooksCustomerId);return}},"Admin_AddOrUpdateExpenseQuickbooksCustomer",[null,j,0],rsErrorCallbackShowErrorDialog,{},0,1)},'The Quickbooks Vendor "'+htmlEncode(j)+'" 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(s){if(checkResponseForError(s)){var t=JSON.parse(s);n=t.quickbooksCustomerId}submitAddOrUpdateExpenseVendor(k,true,n)},"Admin_GetQuickbooksVendorByName",[escape(j)],function(){});return}}if(""===r){showInfoDialog("Name is required","Missing Field",1,"year");return}if(""!==l&&""===e){showInfoDialog("You must specify a match type for Amex Appears on statement as","Missing Field",1,"year");return}if(""!==o&&""===a){showInfoDialog("You must specify a match type for Amex Description","Missing Field",1,"year");return}if(e!==""&&l===""){e=""}if(a!==""&&o===""){a=""}jsrsExecute(function(w,u,t){var x=getObj("frmApproveExpense");if(isDialogShowing()&&x){var z=JSON.parse(w),y=z.expenseVendorId,s=z.expenseVendorName;var v=document.createElement("option");v.value=y;v.innerHTML=s;v.selected=true;x.cboVendor.appendChild(v);hideTimedMessage();hideSubdialog();enableDialogButtons()}else{rsCallbackRefreshPageAndScrollPos(w)}},"Admin_AddOrUpdateExpenseVendor",[m,r,n,a,escape(o),e,escape(l),d,p,h?1:0,i?1:0,g?1:0],enableDialogButtons);displayTimedMessage(q+"...");disableDialogButtons()}function submitAddOrUpdateQuickbooksCustomer(){var d=getObj("addOrUpdateQuickbooksCustomer"),e=d.expenseQuickbooksCustomerId.value,b=d.txtName.value,a=d.chkIsDisabled.checked,c=e?"Updating Quickbooks Vendor...":"Adding Quickbooks Vendor...";if(""===b){showInfoDialog("Name is required","Missing Field",1,"year");return}jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_AddOrUpdateExpenseQuickbooksCustomer",[e,b,a?1:0],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(c+"...");disableDialogButtons()}function addOrUpdateQuickbooksCustomer(b,c,a){var e="addOrUpdateQuickbooksCustomer",d=new ClientDialogBuilder({formId:e,formTitle:b?"Edit Quickbooks Vendor":"Add Quickbooks Vendor",focusFieldName:"txtName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:b?"Save":"Add",mnemonicChar:b?"s":"a",mnemonicActionJS:"submitAddOrUpdateQuickbooksCustomer()"}),fnSubmit:submitAddOrUpdateQuickbooksCustomer,arrExtraHeaderButtons:b?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteQuickbooksCustomer("+b+", unescape('"+escape(c)+"'))"})]:null});d.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});d.addTextFieldRow("txtName",{rawLabel:"Name",maxLength:80,fieldValue:c});d.addCheckboxRow("chkIsDisabled",{labelHTML:"Disabled",checked:a,hideRow:b?false:true});d.showClientDialog()}function editExpenseReport(b){var f="exitExpenseReport",e=new ClientDialogBuilder({formId:f,formTitle:"Edit Expense Report",focusFieldName:"null",arrExtraHeaderButtons:b.expenseReportId?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseReport("+b.expenseReportId+")"})]:null,fnSubmit:function(g){var h=g.cboPayableTo[g.cboPayableTo.selectedIndex].value;jsrsExecuteWithErrorP("Admin2_UpdateExpenseReport",function(i){hideDialog();refreshPageAndScrollPos()},"Updating Expense Report...",{expenseReportId:b.expenseReportId,payableToVendor:parseInt(h,10),vendorId:null})}}),d=b.vendorName||"Vendor",a=b.payableToVendor?1:0,c=buildOptionHTML(htmlEncode(b.userName),0,a)+buildOptionHTML(htmlEncode(d),1,a);e.addFlexibleFieldRow({rawLabel:"Payable To",valueHTML:'",additionalCellClasses:"clsVeryNarrowField"});e.showClientDialog()}function showAddOrUpdateExpenseVendor(t){var n=t.expenseVendorId,b=t.arrExpenseTypes,c=t.expenseVendorName,s=t.quickbooksCustomerName,u=t.quickbooksCustomerId,m=t.amexDescriptionMatchType,h=t.amexDescription,o=t.amexAppearsOnStatementAsMatchType,k=t.amexAppearsOnStatementAs,p=t.expenseType,f=t.reason,l=t.includeOnMemo,q=t.isDisabled,a=t.isGeneric,j="frmExpenseVendor",e=new ClientDialogBuilder({formId:j,formTitle:n?"Edit Expense Vendor":"Add Expense Vendor",focusFieldName:"txtName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:n?"Save":"Add",mnemonicChar:n?"s":"a",mnemonicActionJS:"submitAddOrUpdateExpenseVendor()"}),fnSubmit:submitAddOrUpdateExpenseVendor,arrExtraHeaderButtons:n?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseVendor("+n+", unescape('"+escape(c)+"'))"})]:null});var d=buildOptionHTML("","",false);for(var r=0;r'});var g={formId:j,idFieldName:"quickbooksCustomerId",handlingEnter:1,initialValue:u,stringifiedParams:'{ textFieldName: "txtQuickbooksCustomer", formId: "'+j+'", idFieldName: "quickbooksCustomerId", fnGetTypeAheadData: quickBooksCustomerGetTypeAheadData, fnHandleExplicitSelection: function(){}}'};e.addTextFieldRow("txtName",{rawLabel:"Name",maxLength:80,fieldValue:c});e.addDialogInteriorRows(cdBuildTextFieldRowP("txtQuickbooksCustomer","Quickbooks Vendor",{fieldValue:s,typeaheadInfo:g,autofocus:1,suppressAutocomplete:1}));e.addCheckboxRow("chkIncludeOnMemo",{labelHTML:"Include Amex Vendor On Memo",checked:l});e.addCheckboxRow("chkIsGeneric",{labelHTML:"Generic",checked:a});e.addCheckboxRow("chkIsDisabled",{hideRow:n?false:true,labelHTML:"Disabled",checked:q});e.addFlexibleRow({valueHTML:"
"});e.addFlexibleFieldRow({rawLabel:"Default Type",valueHTML:'"});e.addTextFieldRow("txtReason",{rawLabel:"Default Reason",maxLength:80,fieldValue:f});e.addFlexibleFieldRow({labelHTML:"Amex Description",valueHTML:' '});e.addFlexibleFieldRow({labelHTML:"Amex Appears On
Statement As",valueHTML:' '});e.showClientDialog()}function showEditExpenseVendorDialog(a){jsrsExecuteWithErrorP("Admin2_GetExpenseVendorInfo",rsCallbackHandleStandardJSONResponse,"Retrieving Vendor Info",{expenseVendorId:a,includeExpenseTypes:1},{fnOnSuccess:showAddOrUpdateExpenseVendor})}function submitAddOrUpdateExpenseReportDetail(l,i){var a=getObj("addOrUpdateExpenseReportDetailOrBusinessReason"),c=a.expenseId.value,n=a.expenseDetailId.value,p=a.txtBusinessJustification.value,m=a.cboTrip[a.cboTrip.selectedIndex].value,d=a.cboState[a.cboState.selectedIndex].value,b=a.cboType[a.cboType.selectedIndex].value,k=mwGetCompoundSelectionValueForBase(a,"participant"),o=a.chkSalesTaxWithheld.checked,g=a.amount.value,q=parseFloat(g),f=getObj("txtSummary"),h=a.Date,e=new FormValidator(),j=getObj("receiptFileId").value,r=n?"Updating Expense Report Detail...":"Adding Expense Report Detail...";q=parseFloat(g);if(isNaN(q)){showInfoDialog('"Amount" must be a valid numeric value',"Invalid Amount Value",1,"amount");return}if(!e.CSValidateDateFieldP({field:h,label:"Expense Date",isNullable:false})){return}if(q===0){showInfoDialog('"Amount" cannot be zero',"Invalid Amount Value",1,"amount");return}if(""===b){showInfoDialog('A value for "Type" must be supplied',"Missing Field",1,"cboType");return}if(""===m&&""===p){showInfoDialog('A value for "Trip" or "Additional Information" must be supplied',"Missing Field",1,"txtBusinessJustification");return}if(""===k){showInfoDialog('At least one "Participant" is required',"Missing Field",1,"participantSelect");return}if(o&&d===""){showInfoDialog("A state must be selected if use tax needs to be paid","Missing Field",1,"cboState");return}if(!i&&(""===j&&g_arrFileDragDropFileInfos.length===0)){displaySimpleConfirmationDialog(function(){submitAddOrUpdateExpenseReportDetail(a,true)},"You are saving an Export Report Detail without a receipt. Are you sure you want to continue?","Confirm Save Without Receipt",{},1);return}jsrsExecute(function(s){var u=JSON.parse(s).expenseReportDetailId;if(u+""!==n&&g_arrFileDragDropFileInfos.length>0){a.objectId.value=u}if(g_arrFileDragDropFileInfos.length){var t=getObj("addOrUpdateExpenseReportDetailOrBusinessReason");doUploadFiles(t)}else{hideDialog();rsCallbackRefreshPageAndScrollPos()}},"Admin_AddOrUpdateExpenseReportDetail",[c,n,escape(p),escape(m),escape(b),escape(k),o?1:0,q,escape(f.innerText),o?d:"",h.value],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(r+"...");disableDialogButtons()}function submitAddOrUpdateBusinessReason(){var d=getObj("addOrUpdateExpenseReportDetailOrBusinessReason"),k=d.expenseId.value,p=d.expenseDetailId.value,q=parseInt(d.isCredit.value,10),h=d.txtBusinessJustification.value,e=d.cboTrip[d.cboTrip.selectedIndex].value,b=d.cboState[d.cboState.selectedIndex].value,m=d.cboType[d.cboType.selectedIndex].value,c=mwGetCompoundSelectionValueForBase(d,"participant"),i=d.chkSalesTaxWithheld.checked,g=d.amount.value,o=parseFloat(d.amountLeft.value),f=d.originalSelectedAmount.value,a=parseFloat(f),j=getObj("txtSummary"),l,n=p?"Updating Business Reason...":"Adding Business Reason...";l=parseFloat(g);if(isNaN(l)||l<=0){showInfoDialog('"Amount" must be a valid numeric value that is greater than zero',"Invalid Amount Value",1,"amount");return}if(!isNaN(a)&&a>0){o+=a}if(q){if((l)>Math.abs(o)){showInfoDialog('"Amount" must be less than the remaining expense amount of '+Math.abs(o),"Invalid Amount Value",1,"amount");return}}else{if((l)>o){showInfoDialog('"Amount" must be less than the remaining expense amount of '+o,"Invalid Amount Value",1,"amount");return}}if(""===m){showInfoDialog('A value for "Type" must be supplied',"Missing Field",1,"participantSelect");return}if(""===e&&""===h){showInfoDialog('A value for "Trip" or "Additional Information" must be supplied',"Missing Field",1,"txtBusinessJustification");return}if(""===c){showInfoDialog('At least one "Participant" is required',"Missing Field",1,"participantSelect");return}if(i&&b===""){showInfoDialog("A state must be selected if use tax needs to be paid","Missing Field",1,"cboState");return}jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_AddOrUpdateExpenseDetail",[k,p,escape(h),escape(e),escape(m),escape(c),i?1:0,l,escape(j.innerText),i?b:""],rsErrorCallbackShowErrorDialog,{},0,1);displayTimedMessage(n+"...");disableDialogButtons()}function updateIRSMilageLink(){var c=getObj("addOrUpdateExpenseReportDetailOrBusinessReason");if(c){var b=getObj("irsMileageRatesLink");if(b){var a=c.cboType?c.cboType[c.cboType.selectedIndex].text:"";if(a==="Mileage"){b.style.display=""}else{b.style.display="none"}}}}function formatSummary(){var a=getObj("addOrUpdateExpenseReportDetailOrBusinessReason"),h=getObj("txtSummary"),b="",d="",k="",g="",f=false,e="",j=[],l=null,i;if(!h){return}if(a){b=a.txtBusinessJustification?a.txtBusinessJustification.value:"";d=a.cboTrip?a.cboTrip[a.cboTrip.selectedIndex].text:"";k=a.cboType?a.cboType[a.cboType.selectedIndex].text:"";f=a.chkSalesTaxWithheld?a.chkSalesTaxWithheld.checked:"";l=getObj("stateSelectRow");e=a.amount?a.amount.value:"";i=parseFloat(e);if(f){l.style.display=""}else{l.style.display="none"}var c=a.participantSelect;if(c.style.display!=="none"){g=c[c.selectedIndex].text}else{g=a.participantName.value}}else{h.innerHTML="";return}if(k!==""){j.push(htmlEncode(k))}if(g!==""){j.push("("+htmlEncode(g)+")")}if(b!==""){j.push(htmlEncode(b))}if(d!==""){j.push("for "+htmlEncode(d))}if(f===true){}h.innerHTML=j.join(" ")}function getUseTaxYearBoundaries(){return{useTaxYearMinimum:2018,useTaxYearMaximum:(new Date()).getYear()+1900}}function addUseTaxStateOptions(h){var j=h.objCDBuilder,c=h.fieldName,f=h.strPreFieldHTML,g=h.strPostFieldHTML,b=h.selectedState,e=h.includeEmpty,a=h.rowId,i=h.rawLabel,d=["CA","MI","NV","OR","TX","UT","WA","WI"].map(function(k){return{cboValue:k,rawContent:k}});j.addDropdown({rawLabel:i,fieldName:c,arrAvailableOptions:d,objSelectedValue:b?{cboValue:b,rawContent:b}:undefined,objNoneOption:{cboValue:"",rawContent:""},omitNoneWhenNotSelected:!e,strPreFieldHTML:f,strPostFieldHTML:g,rowId:a})}function submitCreateExpenseReport(){jsrsExecuteWithErrorP("Admin_CreateExpenseReport",function(a){var b=a.id;window.location=pageExpenseReportDetail+b},"Creating Expense Report...",{})}function doDeleteExpenseReportImage(a){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:a.fileId,expenseReportDetailId:a.expenseReportDetailId})}function confirmDeleteExpenseReportDetailReceiptImage(a,c,b){displaySimpleConfirmationDialog(doDeleteExpenseReportImage,'Are you sure you want to remove the receipt "'+c+'" from this Expense Report Detail?',"Delete Expense Report Detail Image",{fileId:a,expenseReportDetailId:b},1)}function addOrUpdateExpenseReportDetail(c){var g="addOrUpdateExpenseReportDetailOrBusinessReason",f,d=[cdBuildFAFontIconButton({additionalButtonClasses:"textDialogButton",htmlContent:"Add Trip",fontId:FontIconId_Enum.fiiPlusInCircle,doubleQuoteEncodedTitle:"Add Trip",doubleQuoteEncodedOnClickJS:"hideDialog(0, 0, 0, function() { window.location=pageExpenseTrips; });"})];if(c.expenseReportDetailId){d.push(cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,additionalButtonClasses:"textDialogButton",doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseReportDetail("+c.expenseReportDetailId+")"}))}f=new ClientDialogBuilder({formId:g,formAction:pageUploadAttachedFile,formTitle:c.expenseReportDetailId?"Edit Expense Report Detail":"Add Expense Report Detail",focusFieldName:"Date",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:c.expenseReportDetailId?"Save":"Add",mnemonicChar:c.expenseReportDetailId?"s":"a",mnemonicActionJS:"submitAddOrUpdateExpenseReportDetail()"}),fnSubmit:submitAddOrUpdateExpenseReportDetail,fnCancelOrClose:function(){var h=0;if(getObj("receiptRemoved").value==="1"){h=1}hideDialogP({callback:function(){if(h){refreshPageAndScrollPos()}}})},arrExtraHeaderButtons:d});var e=buildOptionHTML("","",false);for(var b=0;b'});f.addDatePickerRow(f.getFormId(),"Date",{rawLabel:"Expense Date",strValue:c.date});f.addFlexibleFieldRow({rawLabel:"Amount",onChangeCode:"formatSummary()",valueHTML:' '});f.addFlexibleFieldRow({rawLabel:"Type",onChangeCode:"formatSummary();updateIRSMilageLink();",valueHTML:'"});f.addCompoundSelectionFieldRowP({fieldNameBase:"participant",onChangeCode:"formatSummary()",whatSingular:"Participant",arrSelectedIds:c.selectedUsers,arrObjects:c.users,fnRSCallSubstitute:function(){return{arrUsers:c.users}},objectArrayName:"arrUsers",simpleIdPropertyName:"id",simpleNameDisplayPropertyName:"name"});f.addTextFieldRow("txtBusinessJustification",{rawLabel:"Additional Information",maxLength:256,onChangeCode:"formatSummary()",fieldValue:c.reason});f.addFlexibleFieldRow({rawLabel:"Trip",onChangeCode:"formatSummary()",valueHTML:'"});f.addCheckboxRow("chkSalesTaxWithheld",{labelHTML:"Does Use Tax need to be paid?",checked:c.salesTaxNotPaid,onClickCode:"formatSummary()"});addUseTaxStateOptions({objCDBuilder:f,fieldName:"cboState",strPreFieldHTML:'In what state is the use tax owed?  ',rowId:"stateSelectRow",selectedState:c.state,includeEmpty:true});f.addFlexibleFieldRow({labelHTML:"Receipt",rowId:"removeReceiptRow",hideRow:c.fileId?0:1,valueHTML:' &#'+getRawFontId(c.fileIcon)+" "+c.fileName+""+cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete Receipt Image",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseReportDetailReceiptImage("+c.fileId+",'"+c.fileName+"',"+c.expenseReportDetailId+")"})});f.addFileUploadRow({fileLimit:1,fileType:15,objectId:c.expenseReportDetailId?c.expenseReportDetailId:-1,customLabel:"Receipt",rowId:"addReceiptRow",customAlign:"middleAlign",hideRow:c.fileId?1:0,acceptContentTypeHint:"image/*, .pdf"});f.addSectionHeaderRow({rawTitle:"Summary"});f.addFlexibleFieldRow({rawLabel:"",valueHTML:'
'});f.showClientDialog();setTimeout(function(){formatSummary()},0)}function addOrUpdateBusinessReason(o,j,w,l,g,m,n,k,q,a,s,h,v,b,u,c){var f="addOrUpdateExpenseReportDetailOrBusinessReason",e,r=[cdBuildFAFontIconButton({additionalButtonClasses:"textDialogButton",htmlContent:"Add Trip",fontId:FontIconId_Enum.fiiPlusInCircle,doubleQuoteEncodedTitle:"Add Trip",doubleQuoteEncodedOnClickJS:"hideDialog(0, 0, 0, function() { window.location=pageExpenseTrips; });"})];if(w){r.push(cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,additionalButtonClasses:"textDialogButton",doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteBusinessReason("+w+", "+k+")"}))}e=new ClientDialogBuilder({formId:f,formTitle:w?"Edit Business Reason":"Add Business Reason",focusFieldName:"amount",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:w?"Save":"Add",mnemonicChar:w?"s":"a",mnemonicActionJS:"submitAddOrUpdateBusinessReason()"}),fnSubmit:submitAddOrUpdateBusinessReason,arrExtraHeaderButtons:r});var t=buildOptionHTML("","",false);for(var p=0;p'});e.addFlexibleFieldRow({rawLabel:"Amount",onChangeCode:"formatSummary()",valueHTML:''});e.addFlexibleFieldRow({rawLabel:"Type",onChangeCode:"formatSummary()",valueHTML:'"});e.addCompoundSelectionFieldRowP({fieldNameBase:"participant",onChangeCode:"formatSummary()",whatSingular:"Participant",arrSelectedIds:s,arrObjects:l,fnRSCallSubstitute:function(){return{arrUsers:l}},objectArrayName:"arrUsers",simpleIdPropertyName:"id",simpleNameDisplayPropertyName:"name"});e.addTextFieldRow("txtBusinessJustification",{rawLabel:"Additional Information",maxLength:256,onChangeCode:"formatSummary()",fieldValue:h});e.addFlexibleFieldRow({rawLabel:"Trip",onChangeCode:"formatSummary()",valueHTML:'"});e.addCheckboxRow("chkSalesTaxWithheld",{labelHTML:"Does Use Tax need to be paid?",checked:v,onClickCode:"formatSummary()"});addUseTaxStateOptions({objCDBuilder:e,fieldName:"cboState",strPreFieldHTML:'In what state is the use tax owed?  ',rowId:"stateSelectRow",selectedState:c,includeEmpty:true});e.addSectionHeaderRow({});e.addFlexibleFieldRow({rawLabel:"Summary",valueHTML:'
'});e.showClientDialog();setTimeout(function(){formatSummary()},0)}function submitReordeExpenseTypesDialog(a){submitReorderP({arrReorderedIds:a,reorderCommandName:"Admin2_ReorderExpenseTypes2",reorderIdsPropertyName:"expenseTypeIds",reorderObjectName:"Expense Types"})}function showReorderExpenseTypesDialog(a,b){rsCallbackGetObjectsForReorder({types:b},{originalOptions:{arrayAttrName:"types",fnSubmit:submitReordeExpenseTypesDialog,strReorderWhat:"Expense Types",highlightedId:a}})}function submitExpenseOptions(){var g="frmOptions",h=getObj(g),f=pageExpenses,c=h.cboExpenseViewOptions[h.cboExpenseViewOptions.selectedIndex].value,a="sort",e=h.cboAmexDescriptionMatchType[h.cboAmexDescriptionMatchType.selectedIndex].value,b=h.txtAmexDescription.value,d=getUrlParamValueIfThere(""+window.location,a);if(d){f+="&"+a+"="+d}f+="&expenseViewType="+c;if(c===(""+ExpensesSummaryViews_Enum.esvAll)){f+="&daysBack="+h.txtDaysBack.value}if(b&&b.length>0&&e>=0){f+="&amexVendor="+escape(b);f+="&amexVendorFilterType="+e}hideDialog();window.location=f;displayTimedMessage("Reloading page...")}function onExpenseViewTypeChanged(){var b=getObj("frmOptions");if(b){var a=b.cboExpenseViewOptions[b.cboExpenseViewOptions.selectedIndex].value;if(a===(""+ExpensesSummaryViews_Enum.esvAll)){b.txtDaysBack.parentNode.parentNode.style.display=""}else{b.txtDaysBack.parentNode.parentNode.style.display="none"}}}function submitUseTaxOptions(){var i="frmOptions",d=getObj(i),a=new FormValidator(),e,f=parseInt(d.cboUseTaxTimePeriod.value,10),j=d.cboUseTaxMonth.value,c=d.cboUseTaxQuarter.value,h=d.txtUseTaxYear.value,g=getUseTaxYearBoundaries(),b=a.CSValidateNumberFieldP({field:d.txtUseTaxYear,label:"Year",isNullable:false,minValue:g.useTaxYearMinimum,maxValue:g.useTaxYearMaximum});if(!b){return}e=pageExpenseSettingsUseTax+"timePeriod="+f+"&year="+h;switch(f){case TimePeriodTypeFilter_Enum.tptfMonth:e+="&month="+j;break;case TimePeriodTypeFilter_Enum.tptfQuarter:e+="&quarter="+c;break}hideDialog();window.location=e;displayTimedMessage("Reloading page...")}function changeUseTaxTimePeriod(){var d="frmOptions",e=getObj(d),b=parseInt(e.cboUseTaxTimePeriod.value,10),c=b===TimePeriodTypeFilter_Enum.tptfMonth,a=b===TimePeriodTypeFilter_Enum.tptfQuarter;getObj("useTaxMonth").style.display=c?"":"none";getObj("useTaxQuarter").style.display=a?"":"none"}function showUseTaxOptionsDialog(c){var a=c.timePeriodType,b=c.year,f="frmOptions",e=new ClientDialogBuilder({formId:f,formTitle:"Use Tax - Options",focusFieldName:"cboUseTaxTimePeriod",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitUseTaxOptions()"}),fnSubmit:submitUseTaxOptions,arrExtraHeaderButtons:null}),d=getUseTaxYearBoundaries();e.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(g){g.isSelectedOption=g.cboValue===a;return g}),onClickChangeJS:"changeUseTaxTimePeriod()"});e.addTextFieldRow("txtUseTaxYear",{rawLabel:"Year",mnemonicChar:"y",fieldValue:""+b,isNumber:1,step:1,minValue:d.useTaxYearMinimum,maxValue:d.useTaxYearMaximum});e.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(g){g.isSelectedOption=g.cboValue===c.month;return g}),hideRow:1,rowId:"useTaxMonth"});e.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(g){g.isSelectedOption=g.cboValue===c.quarter;return g}),hideRow:1,rowId:"useTaxQuarter"});if(e.showClientDialog()){changeUseTaxTimePeriod()}}function showExpensesOptionsDialog(d,b,a){var h="frmOptions",c=getUrlParamValueIfThere(window.location,"expenseViewType"),g=parseInt(c,10);if(isNaN(g)||g<0||g>3){g=ExpensesSummaryViews_Enum.esvRequiresInput}var f=new ClientDialogBuilder({formId:h,formTitle:"Expenses View Options",focusFieldName:"cboExpenseViewOptions",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"A",mnemonicActionJS:"submitExpenseOptions()"}),fnSubmit:submitExpenseOptions,arrExtraHeaderButtons:null});var e=buildOptionHTML("Require User Input",ExpensesSummaryViews_Enum.esvRequiresInput,g);e+=buildOptionHTML("All Expenses",ExpensesSummaryViews_Enum.esvAll,g);f.addFlexibleFieldRow({rawLabel:"Filter Expenses",valueHTML:'"});f.addTextFieldRow("txtDaysBack",{rawLabel:"Days Back",fieldValue:d,isNumber:1,hideRow:g!==ExpensesSummaryViews_Enum.esvAll});f.addFlexibleFieldRow({labelHTML:"Amex Vendor",valueHTML:''});f.showClientDialog()}function toggleExpandExpenseInfoExtras(){var b=getObj("imgExpenseInfoExtrasExpander.expand"),c=getObj("imgExpenseInfoExtrasExpander.collapse"),a=document.querySelectorAll(".expense-details");if(c.style.display==="none"){b.style.display="none";c.style.display="inline";a.forEach(function(g,d,f){g.style.display="table-cell"})}else{b.style.display="inline";c.style.display="none";a.forEach(function(g,d,f){g.style.display="none"})}}function doSubmitExpenseForApproval(b){var a="Submitting for approval...";jsrsExecute(function(){hideDialog();window.location=pageExpenses},"Admin_SubmitExpenseOrExpenseReportForApproval",[b.expenseId,b.expenseType],rsErrorCallbackShowErrorDialogAndRefresh,null,null,true);displayTimedMessage(a+"...");disableDialogButtons()}function expenseTypeNameFromId(a){return a===EventObjectType_Enum.eotExpense?"Expense":"Expense Report"}function confirmSubmitExpenseForApproval(a,b){displaySimpleConfirmationDialog(doSubmitExpenseForApproval,"Are you sure you want to submit this "+expenseTypeNameFromId(b)+" for approval?

Once submitted for approval you will not be able to make further changes.","Submit "+expenseTypeNameFromId(b)+" For Approval",{expenseId:a,expenseType:b})}function submitUpdateExpenseOrExpenseReport(c,b,a,f,e,d){jsrsExecuteWithErrorP("Admin2_UpdateApprovalState",d,"Updating Approval Status",{id:c,type:b,status:a,reason:f,vendor:e})}function submitRejectExpense(){var b=getObj("rejectExpense"),d=b.id.value,a=b.type.value,c=b.txtRejectionReason.value;if(""===c){showInfoDialog("A reason must be supplied when rejecting an expense","Missing Field",1,"txtRejectionReason");return}submitUpdateExpenseOrExpenseReport(d,a,Expense_Approval_Status_Enum.easRejected,c,null,function(){hideDialog();window.location=pageExpenseApprovals})}function submitApproveExpenseReport(b,a){submitUpdateExpenseOrExpenseReport(b,a,Expense_Approval_Status_Enum.easApproved,null,null,function(){hideDialog();window.location=pageExpenseApprovals})}function submitApproveExpense(){var b=getObj("frmApproveExpense"),d=b.id.value,a=b.type.value,c=b.cboVendor?b.cboVendor[b.cboVendor.selectedIndex].value:null;if(""===c&&b.cboVendor){showInfoDialog("A vendor must be supplied when approving an expense","Missing Field",1,"txtRejectionReason");return}submitUpdateExpenseOrExpenseReport(d,a,Expense_Approval_Status_Enum.easApproved,"",c,function(){hideDialog();window.location=pageExpenseApprovals})}function submitUnapproveExpense(a){submitUpdateExpenseOrExpenseReport(a.id,a.type,Expense_Approval_Status_Enum.easWaitingForApproval,"",null,function(){hideDialog();window.location=pageExpenseApprovals})}function unapproveExpense(b,a){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:b,type:a}})}function rejectExpense(b,a){var d="rejectExpense",c=new ClientDialogBuilder({formId:d,formTitle:"Reject Expense",focusFieldName:"txtRejectionReason",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Save",mnemonicChar:"s",mnemonicActionJS:"submitRejectExpense()"}),fnSubmit:submitRejectExpense,arrExtraHeaderButtons:null});c.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});c.addTextFieldRow("txtRejectionReason",{rawLabel:"Rejection Reason",maxLength:256,fieldValue:""});c.showClientDialog()}function promptApproveExpenseReport(a,b){displaySimpleConfirmationDialogP(function(){hideDialog();submitApproveExpenseReport(a,b)},"Are you sure you want to approve the Expense Report?",{formTitle:"Approve Expense Report",okButtonDisplayText:"Approve"})}function approveExpense(c){if(c.expenseType===EventObjectType_Enum.eotExpenseReport&&!c.payableToVendor){promptApproveExpenseReport(c.id,c.expenseType);return}var e="frmApproveExpense",f={arrExpenseTypes:JSON.parse(c.types),expenseVendorName:c.description,amexDescriptionMatchType:0,amexDescription:c.description,amexAppearsOnStatementAsMatchType:0,amexAppearsOnStatementAs:c.appearsOnStatementAs,expenseType:c.defaultVendorTypeId,reason:c.defaultReason},d=new ClientDialogBuilder({formId:e,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(f))+")"})]});d.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});var a=buildOptionHTML("","",false);for(var b=0;b'+a+""});d.showClientDialog()}function rsCallbackResolveApprovalError(c,a,b){if(checkResponseForError(c)){hideDialog();window.location=pageExpenses}}function submitResolveApprovalError(a){var b="Resolving Expense Issue...";jsrsExecute(rsCallbackResolveApprovalError,"Admin_ResolveExpenseError",[a.id,a.type],rsErrorCallbackShowErrorDialogAndRefresh,null,null,true);displayTimedMessage(b+"...");disableDialogButtons()}function resolveApprovalError(b,a){displaySimpleConfirmationDialog(submitResolveApprovalError,"Do you want to resolve the issue with this "+expenseTypeNameFromId(a)+"?

Resolving will re-submit the "+expenseTypeNameFromId(a)+" for approval.","Resolve Expense Error",{id:b,type:a})}function submitAddOrUpdateExpenseImportBlocklist(){var f=getObj("addOrUpdateExpenseImportBlocklist"),h=f.expenseImportBlocklistId.value,c=f.txtName.value,b=f.cboAmexDescriptionMatchType[f.cboAmexDescriptionMatchType.selectedIndex].value,a=f.cboAmexAppearsOnStatementAsMatchType[f.cboAmexAppearsOnStatementAsMatchType.selectedIndex].value,g=f.txtAmexAppearsOnStatementAs.value,e=f.txtAmexDescription.value,d=h?"Updating Expense Import Blocklist...":"Adding To Expense Import Blocklist...";if(""===c){showInfoDialog("Name is required","Missing Field",1,"year");return}if(""!==g&&""===a){showInfoDialog("You must specify a match type for Amex Appears on statement as","Missing Field",1,"year");return}if(""!==a&&g===""){showInfoDialog("You must specify a value for Appears On Statement As","Invalid Value",1,"year");return}if(""!==e&&""===b){showInfoDialog("You must specify a match type for Amex Description","Missing Field",1,"year");return}if(""!==b&&""===e){showInfoDialog("You must specify a match type for Amex Description","Missing Field",1,"year");return}jsrsExecute(rsCallbackRefreshPageAndScrollPos,"Admin_AddOrUpdateExpenseImportBlocklist",[h,c,b,escape(e),a,escape(g)],enableDialogButtons);displayTimedMessage(d+"...");disableDialogButtons()}function addOrUpdateExpenseImportBlocklist(d,f,b,e,a,c){var h="addOrUpdateExpenseImportBlocklist",g=new ClientDialogBuilder({formId:h,formTitle:d?"Edit Expense Import Blocklist":"Add To Expense Import Blocklist",focusFieldName:"txtName",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:d?"Save":"Add",mnemonicChar:d?"s":"a",mnemonicActionJS:"submitAddOrUpdateExpenseImportBlocklist()"}),fnSubmit:submitAddOrUpdateExpenseImportBlocklist,arrExtraHeaderButtons:d?[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedTitle:"Delete",doubleQuoteEncodedOnClickJS:"confirmDeleteExpenseImportBlocklist("+d+", unescape('"+escape(f)+"'))"})]:null});g.addFlexibleFieldRow({rawLabel:"",hideRow:1,valueHTML:''});g.addTextFieldRow("txtName",{rawLabel:"Name",maxLength:80,fieldValue:f});g.addFlexibleFieldRow({labelHTML:"Amex Description",valueHTML:''});g.addFlexibleFieldRow({labelHTML:"Amex Appears On
Statement As",valueHTML:''});g.showClientDialog()}function setDatabaseCompanyAddressAsNeedsConfirmation(a){jsrsExecuteWithErrorP("Admin2_SetDatabaseCompanyAddressAsNeedsConfirmation",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating company address to require confirmation",{databaseId:a})}function confirmSetDatabaseCompanyAddressAsNeedsConfirmation(a){displaySimpleConfirmationDialog(setDatabaseCompanyAddressAsNeedsConfirmation,"Are you sure you want to prompt the user to review their company address?","Prompt User to Review Company Address",a,null,null,"Yes")}function setDatabaseContactAsNeedsConfirmation(a){jsrsExecuteWithErrorP("Admin2_SetDatabaseContactAsNeedsConfirmation",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating contact to require confirmation",{databaseContactId:a})}function confirmSetDatabaseContactAsNeedsConfirmation(a){displaySimpleConfirmationDialog(setDatabaseContactAsNeedsConfirmation,"Are you sure you want to prompt the user to review this contact?","Prompt User to Review Contact",a,null,null,"Yes")}function rsCallbackSentDunningEmails(d){var c=d.arrFailures,a=d.arrHandledInvoices,f=a?a.length:0,g=c?c.length:0,e=new ClientDialogBuilder({formTitle:"Sent Dunning Emails",fnCancelOrClose:function(){hideDialog();saveScrollPos();refreshPageShowingMessage()}}),b;if(f){e.addSectionHeaderRow({rawTitle:f===1?"Processed 1 Invoice":("Processed "+f+" Invoice")});b=new MWClientTable({additionalTableClasses:"unsetTableWidth100"});b.addColumn(new MWColumn({columnName:"Subdomain",simpleDisplayColumnPropertyName:"subDomainName"}));b.addColumn(new MWColumn({columnName:"Invoice #",simpleDisplayColumnPropertyName:"invoiceNumber"}));b.addColumn(new MWColumn({columnName:"Email Address",simpleDisplayColumnPropertyName:"targetEmailAddress"}));b.addColumn(new MWColumn({columnName:"DB Id",simpleDisplayColumnPropertyName:"databaseId"}));e.addFlexibleRow({valueHTML:b.buildTableForArray(a)})}if(g){e.addSectionHeaderRow({rawTitle:g===1?"1 Failure":(g+" Failures")});b=new MWClientTable({additionalTableClasses:"unsetTableWidth100"});b.addColumn(new MWColumn({columnName:"Error",simpleDisplayColumnPropertyName:"errorMessage",simpleDisplayColumnNeedsMultilineEncoding:1,additionalCellClasses:"errorText"}));b.addColumn(new MWColumn({columnName:"Subdomain",simpleDisplayColumnPropertyName:"subDomainName"}));b.addColumn(new MWColumn({columnName:"Invoice #",simpleDisplayColumnPropertyName:"invoiceNumber",additionalCellClasses:"rightAlign"}));b.addColumn(new MWColumn({columnName:"Email Address",simpleDisplayColumnPropertyName:"targetEmailAddress"}));b.addColumn(new MWColumn({columnName:"DB Id",simpleDisplayColumnPropertyName:"databaseId",additionalCellClasses:"rightAlign"}));e.addFlexibleRow({valueHTML:b.buildTableForArray(c)})}e.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"})});e.addFlexibleRow({valueHTML:htmlEncode(JSON.stringify(d,null,2)),additionalCellClasses:"JSONViewer",rowId:"rowRawResults",hideRow:1});e.showClientDialog()}function sendDunningEmails(){hideDialog();jsrsExecuteWithErrorP("Admin2_SendDunningEmails",rsCallbackHandleStandardJSONResponse,"Sending Dunning Emails",{},{fnOnSuccess:rsCallbackSentDunningEmails})}function promptSendDunningEmails(a){var b=new ClientDialogBuilder({formTitle:"Send Dunning Emails",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Send Emails",mnemonicChar:"s",mnemonicActionJS:"sendDunningEmails()"}),fnSubmit:sendDunningEmails});b.addFlexibleRow({rawValue:"Are you sure you want to send the Dunning Emails?"});b.showClientDialog()}function submitSalesByStateOptions(){var f="frmOptions",h=getObj(f),e=pageSalesByState,c=parseInt(h.cboTimeSelection.value,10),d,g,b=h.txtPageSize,a=new FormValidator();if(!a.CSValidateDateFieldP({field:h.dtStartDate,label:"Start Date",isNullable:false})){return}if(!a.CSValidateDateFieldP({field:h.dtEndDate,label:"End Date",isNullable:false})){return}d=getDateForUrlParam(h.dtStartDate.value);g=getDateForUrlParam(h.dtEndDate.value);if(d&&g&&parseDateString(g)1?"AutopayStatusName":"AutopayStatusSelect",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitAutopayReportOptions()"}),fnSubmit:submitAutopayReportOptions});c.addCompoundSelectionFieldRowP({fieldNameBase:"AutopayStatus",whatSingular:"Autopay Status",whatPlural:"Autopay Statuses",arrSelectedIds:a,objectArrayName:"arrAutopayStatuses",autofocus:1,fnRSCallSubstitute:function(){return{arrAutopayStatuses:d}},arrObjects:d});c.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:b.activeStatusFilter||ActiveStatusFilter_Enum.asfActiveOnly}});c.addTextFieldRow("txtNextInvoiceDayOfMonth",{rawLabel:"Next Invoice Day of Month",fieldValue:b.nextInvoiceDayOfMonth?""+b.nextInvoiceDayOfMonth:"",mnemonicChar:"n",maxLength:2,styleWidth:"7em",isNumber:1});c.addTextFieldRow("txtPageSize",{rawLabel:"Rows per Page",fieldValue:""+b.pageSize,mnemonicChar:"r",maxLength:10,styleWidth:"7em",isNumber:1});c.showClientDialog()}function submitCustomerPortalReportOptions(){var k="frmOptions",h=getObj(k),b=new FormValidator(),i=pagePortalUsageReport,g=h.txtPageSize,e=trim(g.value),j=h.txtMaxDaysOld,f=trim(j.value),a="PUsageListsort",d=getUrlParamValueIfThere(""+window.location,a),c=h.cboUserType.value;if(!b.CSValidateIntegerField(g,"Page Size",true,1,2000)){return}if(!b.CSValidateIntegerField(j,"Max Days Old",true,1,2000)){return}if(d){i+="&"+a+"="+d}if(e){i+="&pageSize="+e}if(f){i+="&maxDaysOld="+f}if(c!==""+FilteredVUserType_Enum.fvutJTOnly){i+="&userType="+c}hideDialog();window.location=i;displayTimedMessage("Reloading page...")}function showCustomerPortalReportOptionsDialog(a){var c="frmOptions",b=new ClientDialogBuilder({formId:c,formTitle:"Customer Portal Report Options",focusFieldName:"cboUserType",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitCustomerPortalReportOptions()"}),fnSubmit:submitCustomerPortalReportOptions});b.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:a.filteredVUserType||FilteredVUserType_Enum.fvutAny}});b.addTextFieldRow("txtPageSize",{rawLabel:"Rows per Page",fieldValue:""+a.pageSize,maxLength:10,styleWidth:"7em",isNumber:1});b.addTextFieldRow("txtMaxDaysOld",{rawLabel:"Show Last",fieldValue:""+a.maxDaysOld,maxLength:10,styleWidth:"7em",isNumber:1,strPostFieldHTML:" Days"});b.showClientDialog()}function submitLegacyPricingReportOptions(){var e="frmOptions",f=getObj(e),d=pageLegacyPricingReport,a="legacyPricingReportTablesort",c=getUrlParamValueIfThere(""+window.location,a),b=f.cboNewPriceTarget.value;if(c){d+="&"+a+"="+c}if(b!==""+NewPriceTargetFilterOption_Enum.nptfoAll){d+="&newPriceTarget="+b}hideDialog();window.location=d;displayTimedMessage("Reloading page...")}function showLegacyPricingReportOptionsDialog(a){var c="frmOptions",b=new ClientDialogBuilder({formId:c,formTitle:"Report Options",focusFieldName:"cboNewPriceTarget",focusFieldOnMobile:1,okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitLegacyPricingReportOptions()"}),fnSubmit:submitLegacyPricingReportOptions});b.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:a.newPriceTarget||NewPriceTargetFilterOption_Enum.nptfoAll}});b.showClientDialog()}function toggleDisplayImportDisbursementResults(){var c=getObj("icoExpand"),a=c.style.display==="none",b=!a;c.style.display=b?"none":"";getObj("icoCollapse").style.display=b?"":"none";getObj("rowImportDisbursementResultsJson").style.display=b?"":"none"}function rsCallbackImportDisbursements(f){hideDialog();var h="frmImportDisbursementResults",k=new ClientDialogBuilder({formId:h,formTitle:"Import Disbursements",fnCancelOrClose:function(){refreshPageAndScrollPos()}}),b=f.arrImportInfos,e=b?b.length:0,d,i,c,g,j,a;for(c=0;c
'+cdBuildFontIconElem({fontId:FontIconId_Enum.fiiRightChevron,terseFontIcon:1,fontIconElemId:"icoExpand"})+cdBuildFontIconElem({fontId:FontIconId_Enum.fiiDownChevron,terseFontIcon:1,fontIconElemId:"icoCollapse",hideIcon:1})+" Raw JSON
"});k.addFlexibleRow({valueHTML:htmlEncode(JSON.stringify(f,null,2)),additionalCellClasses:"JSONViewer",rowId:"rowImportDisbursementResultsJson",hideRow:1});k.showClientDialog()}function submitImportBTDisbursements(){var d="frmImport",e=getObj(d),c=e.dtDate,a=new FormValidator(),b;if(!a.CSValidateDateField(c,"Date",true,"dtDate")){return}b=getDateForUrlParam(c.value);jsrsExecuteWithErrorP("Admin2_ImportDisbursements",rsCallbackHandleStandardJSONResponse,"Importing Disbursements",{disbursementDate:b},{fnOnSuccess:rsCallbackImportDisbursements})}function promptImportDisbursements(){var b="frmImport",a=new ClientDialogBuilder({formId:b,formTitle:"Import Disbursements",focusFieldName:"dtDate",fnSubmit:submitImportBTDisbursements,okButtonDisplayText:"Import"});a.addDatePickerRow(b,"dtDate",{rawLabel:"Payment Transaction Date"});a.showClientDialog()}function submitUpdateDisbursementDate(){var c="frmEditDisbursementDate",d=getObj(c),b=d.dtDate,a=new FormValidator();if(!a.CSValidateDateField(b,"Deposit Date",false,"dtDate")){return}jsrsExecuteWithErrorP("Admin2_UpdateBTDisbursementDate",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Disbursement Date",{disbursementDate:mjtElemData(d,"disbursementDate"),depositDate:getDateForUrlParam(b.value)})}function showEditDisbursementDateDialog(c){var d="frmEditDisbursementDate",e,b=c.disbursementDate,a=new ClientDialogBuilder({formId:d,formTitle:"Update Disbursement Date",focusFieldName:"dtDate",fnSubmit:submitUpdateDisbursementDate});a.addFlexibleFieldRow({rawLabel:"Disbursement Date",rawValue:b});a.addDatePickerRow(d,"dtDate",{rawLabel:"Deposit Date",strValue:c.depositDate||""});e=a.showClientDialog();if(e){mjtElemData(e,"disbursementDate",b)}}function submitUpdateDBTaxRate(){var c="frmLookupTaxRate",d=getObj(c),b=mjtElemData(d,"databaseId"),a=mjtElemData(d,"matchingTaxCodeId");jsrsExecuteWithErrorP("Admin2_UpdateDBTaxInfo",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Updating Tax Info",{databaseId:b,taxRateId:a})}function buildRawAddressFromAddrObject(f){var h=f.street||"",d=trim(f.city||""),g=trim(f.state||""),c=trim(f.zip||""),b=trim(f.country||""),a=d&&g?d+", "+g:(d+g),e=trim(a+" "+c);return h+"\n"+(e&&b?e+"\n"+b:e+b)}function rsCallbackGetDBTaxInfo(i){hideDialog();var e="frmLookupTaxRate",q,o=i.currentAddress||{},l=i.newDBTaxOptions,p=i.arrAPIMultiMatchMinInfos,c=p?p.length:0,n=i.currentTaxOptions,h=n?n.taxRateId||0:0,j=l.singleMatchedTaxCode,r=j?j.nameMatchingTaxCodeId:0,k=r&&(r!==h),f=l.taxWarningMessage,d=new ClientDialogBuilder({formId:e,formTitle:"Lookup Tax Rate",focusFieldName:"txtStreet",arrExtraHeaderButtons:[cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiEdit,doubleQuoteEncodedOnClickJS:"promptToUpdateTaxLookupAddress()",doubleQuoteEncodedTitle:"Change Lookup Address"})],okButtonDisplayText:k?cdBuildMnemonicLabelHTML({rawLabel:"Update Tax Rate",mnemonicChar:"u",mnemonicActionJS:"submitUpdateDBTaxRate()"}):null,fnSubmit:k?submitUpdateDBTaxRate:null});d.addFlexibleFieldRow({rawLabel:"Lookup Address",valueHTML:htmlMultilineEncode(buildRawAddressFromAddrObject(o)),valueCellId:"cellLookupAddress",additionalCellClasses:"topAlign"});d.addSectionHeaderRow({rawTitle:"Tax Info"});if(n){var a='-None-';if(n.taxRateId){a=htmlEncode(n.taxRateName)+" ("+n.taxRatePercent+"%)"}d.addFlexibleFieldRow({rawLabel:"Current Tax Rate",valueHTML:a})}if(f){d.addFlexibleFieldRow({rawLabel:"",valueHTML:htmlMultilineEncode(f),additionalValueCellClasses:"errorText"})}if(c){d.addFlexibleFieldRow({rawLabel:"Multiple Matches",valueHTML:htmlEncode(JSON.stringify(p,null,2)),additionalValueCellClasses:"JSONViewer errorText",additionalCellClasses:"topAlign"})}if(r){var b=k?cdBuildFontIconElem({fontId:FontIconId_Enum.fiiExclamationInFilledTriangle,terseFontIcon:1,additionalFontIconClasses:"warningIcon"}):cdBuildFontIconElem({fontId:FontIconId_Enum.fiiCheck,terseFontIcon:1,additionalFontIconClasses:"goodNewsIcon"}),g=k?'The tax rate will be updated':"There is no need to update the Tax Rate",m=htmlEncode(j.taxCodeName)+" ("+j.taxRatePercent+"%)";if(k){m=''+m+""}d.addFlexibleFieldRow({rawLabel:"New Tax Rate",valueHTML:b+" "+m+'
('+g+")",additionalCellClasses:"topAlign"})}q=d.showClientDialog();if(q){mjtElemData(q,"databaseId",i.databaseId);mjtElemData(q,"matchingTaxCodeId",r);mjtElemData(q,"lookupAddress",o)}}function promptLookupTaxRate(a){jsrsExecuteWithErrorP("Admin2_GetDBTaxInfo",rsCallbackHandleStandardJSONResponse,"Looking up Tax Info",{databaseId:a.databaseId},{fnOnSuccess:rsCallbackGetDBTaxInfo})}function submitUpdateTaxLookupAddress(){var d="frmAddress",e=getObj(d),a="frmLookupTaxRate",c=getObj(a),b=mjtElemData(c,"databaseId");jsrsExecuteWithErrorP("Admin2_GetDBTaxInfo",rsCallbackHandleStandardJSONResponse,"Looking up Tax Info",{databaseId:b,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:rsCallbackGetDBTaxInfo})}function promptToUpdateTaxLookupAddress(){var e="frmAddress",a="frmLookupTaxRate",d=getObj(a),c=mjtElemData(d,"lookupAddress"),b=new ClientDialogBuilder({formId:e,formTitle:"Update Lookup Address",focusFieldName:"txtStreet",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Lookup Address",mnemonicChar:"l",mnemonicActionJS:"submitUpdateTaxLookupAddress()"}),fnSubmit:submitUpdateTaxLookupAddress});b.addTextFieldRow("txtStreet",{rawLabel:"Street",fieldValue:c.street||""});b.addTextFieldRow("txtCity",{rawLabel:"City",fieldValue:c.city||""});b.addTextFieldRow("txtState",{rawLabel:"State",fieldValue:c.state||""});b.addTextFieldRow("txtZip",{rawLabel:"Zip",fieldValue:c.zip||""});b.addTextFieldRow("txtCountry",{rawLabel:"Country",fieldValue:c.country||""});b.showClientDialog()}function submitStopRetryingPayments(){var b="frmCeaseRetry",c=getObj(b),a=mjtElemData(c,"databaseId");hideDialog();jsrsExecuteWithErrorP("Admin2_SetAutomatedPaymentStatusPermanentFailure",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Marking Permanent Failure",{databaseId:a})}function showUpdateCustomerPaymentDate(a){var c="frmCeaseRetry",d,b=new ClientDialogBuilder({formId:c,formTitle:"Temporarily Stop Retrying",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Stop Retrying",mnemonicChar:"s",mnemonicActionJS:"submitStopRetryingPayments()"}),fnSubmit:submitStopRetryingPayments});b.addFlexibleRow({valueHTML:"Are you sure you want to stop retrying payments until the next pay period?"});d=b.showClientDialog();if(d){mjtElemData(d,"databaseId",a)}}function submitReconcileBTProfile(){var a="frmReconcile",c=getObj(a),b=mjtElemData(c,"billingProcessorCustomerId");hideDialog();jsrsExecuteWithErrorP("Admin2_ReconcileBTBillingProfile",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Reconciling Braintree Profile",{billingProcessorCustomerId:b})}function reconcileBTProfile(a){var c="frmReconcile",d,b=new ClientDialogBuilder({formId:c,formTitle:"Reconcile Braintree Profile",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Reconcile",mnemonicChar:"r",mnemonicActionJS:"submitReconcileBTProfile()"}),fnSubmit:submitReconcileBTProfile});b.addFlexibleRow({rawValue:'Are you sure you want to reconcile billing id "'+a.billingProcessorCustomerId+'"?'});d=b.showClientDialog();if(d){mjtElemData(d,"billingProcessorCustomerId",a.billingProcessorCustomerId)}}function submitUpdateDatabasePricingStructureDialog(){var f="frmUpdateDatabasePricingStructure",h=getObj(f),c=new FormValidator(),a=getDateForUrlParam(h.dtEffectiveDate.value),b,e=new Date(),g=mjtElemData(h,"databasePricingStructureId"),d;if(!c.CSValidateDateFieldP({field:h.dtEffectiveDate,label:"Effective Date"})){return}e=new Date(e.getFullYear(),e.getMonth(),e.getDate());b=parseDateString(a);if(b'+htmlEncode(a.pricingStructureName)+"
"+htmlEncode(a.productTypeName)+"
Effective "+cdCarefullyLocalizeDateValue(a.effectiveDate)+"","Remove Database Pricing Structure",{databasePricingStructureId:a.databasePricingStructureId})}function doShowUpdateDatabasePricingStructureDialog(i,b){var f="frmUpdateDatabasePricingStructure",q,g=i.pricingStructure,d=i.nextInvoiceInfo,n=g.databasePricingStructureId,r=g.effectiveDate,p=g.productTypeName,c=g.pricingStructureName,l=b.originalPayload.subdomain,m=cdCarefullyLocalizeDateValue(d.nextInvoiceDate),j="dtEffectiveDate",h={nextInvoiceDate:m,formId:f,dateFieldId:j},a=getNextInvoiceDateLink(h),k={subdomain:l,pricingStructureName:c,productTypeName:p,effectiveDate:r,databasePricingStructureId:n},o=jtcrmHasAccess(JTCRMSecuredObject_Enum.soUnexportedDatabaseObjects,AccessRight_Enum.mjtARDelete),e=new ClientDialogBuilder({formId:f,formTitle:"Change Pricing Structure Effective Date",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Update",mnemonicChar:"u",mnemonicActionJS:"submitUpdateDatabasePricingStructureDialog()"}),fnSubmit:submitUpdateDatabasePricingStructureDialog,arrExtraHeaderButtons:[o?cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiHollowTrash,doubleQuoteEncodedOnClickJS:"confirmRemoveDatabasePricingStructure(JSON.parse(unescape('"+escape(JSON.stringify(k))+"')))",doubleQuoteEncodedTitle:"Remove Database Pricing Structure"}):null,o?'':null,cdBuildFAFontIconButton({fontId:FontIconId_Enum.fiiBook,doubleQuoteEncodedTitle:"View Change Log",doubleQuoteEncodedOnClickJS:"carefullyDisplayDatabasePricingStructureEventLog("+n+")"})]});e.addFlexibleFieldRow({rawLabel:"Product Type",rawValue:p});e.addFlexibleFieldRow({rawLabel:"Pricing Structure",rawValue:c});e.addDatePickerRow(f,j,{rawLabel:"Effective Date",strValue:cdCarefullyLocalizeDateValue(r),strPostPickerHTML:a});q=e.showClientDialog();if(q){mjtElemData(q,"databasePricingStructureId",n)}}function showUpdateDatabasePricingStructureDialog(a){jsrsExecuteWithErrorP("Admin2_GetDatabasePricingStructure",doShowUpdateDatabasePricingStructureDialog,"Getting Database Pricing Structure",a)}function submitMissingPricingStructureSelectionDialog(){var h="frmApplyPricingStructure",g=getObj(h),a=new FormValidator(),d=mjtElemData(g,"databaseId"),b=g.cboPricingStructure.options[g.cboPricingStructure.selectedIndex].value,i=b!==""?parseInt(b,10):null,c=getDateForUrlParam(g.dtEffectiveDate.value),e=parseDateString(c),f={databaseId:d,pricingStructureId:i,effectiveDate:e};if(!i){showInfoDialog("Please select a pricing structure.","Select Pricing Structure",true,"cboPricingStructure");return}if(!a.CSValidateDateFieldP({field:g.dtEffectiveDate,label:"Effective Date"})){return}jsrsExecuteWithErrorP("Admin2_ApplyDatabasePricingStructure",rsCallbackHandleStandardJSONResponseWithHideAndRefresh,"Applying Database Pricing Structure",f)}function doShowMissingPricingStructureSelectionDialog(g,c){var k="frmApplyPricingStructure",i,o=g.arrPricingStructures,f=c.originalPayload.productName,d=c.originalPayload.databaseId,n=c.originalPayload.productTypeId,p=parseInt(n,10),l=c.originalPayload.editionId,j=l?parseInt(l,10):null,b="cboPricingStructure",e="tdPricingStructure",a=buildDropdownRow({name:b,label:"Pricing Structure",valueLookup:"pricingStructureId",textLookup:"pricingStructureName",values:o,valueCellId:e}),m=new ClientDialogBuilder({formId:k,formTitle:"Select Pricing Structure",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitMissingPricingStructureSelectionDialog()"}),fnSubmit:submitMissingPricingStructureSelectionDialog});m.addFlexibleFieldRow({rawLabel:"Product",rawValue:f});m.addDialogInteriorRows(a);m.addDatePickerRow(k,"dtEffectiveDate",{rawLabel:"Effective Date"});i=m.showClientDialog();if(i){mjtElemData(i,"databaseId",d);var h={strFormId:k,selectedProductTypeId:p,selectedEditionId:j,arrPricingStructures:o,pricingStructureValueCellId:e,pricingStructureSelectorName:b};refreshPricingStructureSelector(h)}}function showMissingPricingStructureSelectionDialog(a){jsrsExecuteWithErrorP("Admin2_GetPricingStructures",doShowMissingPricingStructureSelectionDialog,"Retrieving Pricing Structures",a)}function submitApplyDatabasePricingStructureSelectionDialog(){var i="frmApplyPricingStructure",h=getObj(i),e=mjtElemData(h,"databaseId"),b=new FormValidator(),d=getDateForUrlParam(h.dtEffectiveDate.value),f,a=new Date(),c=h.cboPricingStructure.options[h.cboPricingStructure.selectedIndex].value,g;if(!c){showInfoDialog("Please select a pricing structure.","Select Pricing Structure",true,"cboPricingStructure");return}if(!b.CSValidateDateFieldP({field:h.dtEffectiveDate,label:"Effective Date"})){return}a=new Date(a.getFullYear(),a.getMonth(),a.getDate());f=parseDateString(d);if(f";for(var d in e){var a=e[d];if(a.isDeprecated){continue}if(b!==a.productName){if(b!==undefined){c+=""}c+='';b=a.productName}c+=buildAnOption(a.pricingStructureId,htmlEncode(a.productName+": "+a.pricingStructureName))}if(c){c+=""}return'"}function doShowApplyDatabasePricingStructureSelectionDialog(f,a){var j="frmApplyPricingStructure",h,m=f.arrPricingStructures,c=a.originalPayload.databaseId,k=f.nextInvoiceInfo,i=cdCarefullyLocalizeDateValue(k.nextInvoiceDate),b="dtEffectiveDate",d={nextInvoiceDate:i,formId:j,dateFieldId:b},e=getNextInvoiceDateLink(d),g=createPricingStructureSelector(m),l=new ClientDialogBuilder({formId:j,formTitle:"Select Pricing Structure",okButtonDisplayText:cdBuildMnemonicLabelHTML({rawLabel:"Apply",mnemonicChar:"a",mnemonicActionJS:"submitApplyDatabasePricingStructureSelectionDialog()"}),fnSubmit:submitApplyDatabasePricingStructureSelectionDialog});l.addFlexibleFieldRow({rawLabel:"Pricing Structure",valueHTML:g});l.addDatePickerRow(j,b,{rawLabel:"Effective Date",strPostPickerHTML:e});h=l.showClientDialog();if(h){mjtElemData(h,"databaseId",c)}}function showApplyDatabasePricingStructureSelectionDialog(a){jsrsExecuteWithErrorP("Admin2_GetPricingStructuresForSelection",doShowApplyDatabasePricingStructureSelectionDialog,"Retrieving Available Pricing Structures",a)};function convertJobInfoToUpdateJobAndDBInfo(a){return{databaseId:a.databaseId,updateDeploymentServer:a.deploymentServerDiffers,updateBillingLink:a.billingLinkDiffers,updateServerDatabaseLink:a.serverDatabaseLinkDiffers,updateCGUserCount:a.cgUserCountDiffers,updateNVUserCount:a.nvUserCountDiffers,updateSysUserCount:a.sysUserCountDiffers,updateDatabaseAddress:a.addressesDiffer,requiresUpdateDueToEdition:a.requiresUpdateDueToEdition,actualCGUserCount:a.actualCGUserCount,actualNVUserCount:a.actualNVUserCount,actualSysUserCount:a.actualSysUserCount,actualEditionId:a.actualEditionId,jtListedJobAddress:a.jtListedJobAddress,jtAddress:a.addressesDiffer?a.jtAddress:0,updateCGActivityStatus:a.counterGoActivity.activityStatesDiffer,updateNVActivityStatus:a.nvInventoryActivity.activityStatesDiffer,updateSysActivityStatus:a.systemizeActivity.activityStatesDiffer,actualCGActivityStatusText:a.counterGoActivity.actualActivityStatusText,actualNVActivityStatusText:a.nvInventoryActivity.actualActivityStatusText,actualSysActivityStatusText:a.systemizeActivity.actualActivityStatusText}};