2 lines
521 KiB
Plaintext
2 lines
521 KiB
Plaintext
var g_memberItemDelimiter="|",g_memberRowDelimiter="§",intMaxValue=2147483647,g_currentRowSelection=null;function updateSelectedRow(items,selectedItems,delegate){for(var i=0;i<items.length;i++){var ii=items[i].rowIndex,subitems=selectedItems[ii].split(g_memberItemDelimiter);delegate(subitems),selectedItems[ii]=subitems.join(g_memberItemDelimiter)}return selectedItems.join(g_memberRowDelimiter)}function copySelectedRows(sourceList,destinationArchiveControl,contactnameMDOSoId,hiddenFieldName){var list=sourceList.getSelectedRows(),items=new Array,sourceList=SuperOffice.SoHelper.getElementBySoId(contactnameMDOSoId+"_SearchBox"),elemKey=SuperOffice.SoHelper.getElementBySoId(contactnameMDOSoId+"_SelectedValue"),contactnameMDOSoId=SuperOffice.SoHelper.getElementBySoId(contactnameMDOSoId+"_SelectedType"),contactName="",contactId=0;if(null!=sourceList&&"person"!=contactnameMDOSoId.value.toLowerCase()&&(contactName=sourceList.value,contactId=elemKey.value),0==list.length)items.push(elemKey.value+g_memberItemDelimiter+elemKey.value+g_memberItemDelimiter+contactName+g_memberItemDelimiter);else for(var t=0;t<list.length;t++)items.push(list[t].attributes.primaryKey.value+g_memberItemDelimiter+contactId+g_memberItemDelimiter+contactName+g_memberItemDelimiter+list[t].attributes.primaryKey.value+g_memberItemDelimiter+UIHelper.GetInnerText(list[t]));var hiddenElem=SuperOffice.SoHelper.getElementBySoId(hiddenFieldName);if(null!=hiddenElem){for(var newitems=new Array,i=0;i<items.length;i++)-1==hiddenElem.value.indexOf(items[i])&&newitems.push(items[i]);0<newitems.length&&(""!=hiddenElem.value&&(hiddenElem.value+=g_memberRowDelimiter),hiddenElem.value+=newitems.join(g_memberRowDelimiter))}refreshSelectionMemberlist(destinationArchiveControl,hiddenFieldName)}function refreshSelectionMemberlist(destinationArchiveControl,hiddenFieldSoId){hiddenFieldSoId=SuperOffice.SoHelper.getElementBySoId(hiddenFieldSoId);destinationArchiveControl.RefreshList(hiddenFieldSoId.value)}function removeSelectedMemberRows(sourceArchiveControl,hiddenFieldSoId){for(var keys=sourceArchiveControl.getSelectedKeys(),hiddenFieldSoId=SuperOffice.SoHelper.getElementBySoId(hiddenFieldSoId),rows=hiddenFieldSoId.value.split(g_memberRowDelimiter),tmpArray=new Array,i=0;i<rows.length;i++){for(var keep=!0,t=0;t<keys.length;t++)if(0==rows[i].indexOf(keys[t])){keep=!1;break}keep&&tmpArray.push(rows[i])}hiddenFieldSoId.value=tmpArray.join(g_memberRowDelimiter),sourceArchiveControl.RefreshList(hiddenFieldSoId.value)}SuperOffice.Sale||(SuperOffice.Sale={__namespace:!0}),SuperOffice.Sale.AddMember=function(mdo_obj){var pub={},mdoObj=mdo_obj;return pub.removeSelectedMemberRowsByIndex=function(sourceArchiveControl,hiddenFieldSoId){for(var keys=sourceArchiveControl.getSelectedRows(),hiddenFieldSoId=SuperOffice.SoHelper.getElementBySoId(hiddenFieldSoId),rows=hiddenFieldSoId.value.split(g_memberRowDelimiter),tmpArray=new Array,i=0;i<rows.length;i++){for(var keep=!0,ii=0;ii<keys.length;ii++)if(keys[ii].rowIndex==i){keep=!1;break}keep&&tmpArray.push(rows[i])}hiddenFieldSoId.value=tmpArray.join(g_memberRowDelimiter),sourceArchiveControl.deSelectAll(),sourceArchiveControl.RefreshList(hiddenFieldSoId.value)},pub.setFromList=function(destinationArchiveControl){var items=destinationArchiveControl.getSelectedRows(),commentelem=SuperOffice.SoHelper.getElementBySoId("comment_textfield"),selectedItems=SuperOffice.SoHelper.getElementBySoId("selectionMemberHidden").value.split(g_memberRowDelimiter);commentelem.value="",mdoObj.setSearchBoxText(""),mdoObj.setSelectedValue(0);for(var i=0;i<items.length;i++){var ii=items[i].rowIndex,ii=UIHelper.Decode(selectedItems[ii]).split(g_memberItemDelimiter);commentelem.value=ii[7],mdoObj.setSearchBoxText(ii[6]),mdoObj.setSelectedValue(ii[5])}},pub},$(window).on("SCILInitialized",function(){window.PageEventHandler.addServerEvent("ONBATCHEVENT","StatusMonitorRegenereateAll","SuperOffice.Admin.Saint.OnBatchEvent(obj)"),window.PageEventHandler.addServerEvent("ONBATCHEVENT","PublishUserDefinedFields","SuperOffice.Admin.Fields.OnBatchEvent(obj)"),window.PageEventHandler.addServerEvent("ONBATCHEVENT","ImportBatchPlugin","SuperOffice.Admin.Import.OnBatchEvent(obj)"),window.PageEventHandler.addServerEvent("ONBATCHEVENT","SaintRegenBatchPlugin","SuperOffice.Admin.Saint.OnBatchEvent(obj)"),window.PageEventHandler.addServerEvent("ONBATCHEVENT","FreetextRegenBatchPlugin","SuperOffice.Admin.System.OnBatchEvent(obj)"),window.PageEventHandler.addServerEvent("ONBATCHEVENT","ErpForceResyncBatchPlugin","SuperOffice.Admin.ErpSync.OnBatchEvent(obj)")}),SuperOffice.Admin={},SuperOffice.Admin.Users=function(){var pub={enDis:function(id,soElement,associateId,personId){-1==associateId&&(associateId=parseInt(SuperOffice.SoHelper.getValueFromLinkHint(adminusersUsersArchiveArchiveControl.getSelectedKey(),"associate"),10)),(0==$.isNumeric(associateId)||associateId<=0)&&(!$("[soid='"+id+"']").is(":checked")?SuperOffice.SoHelper.disableElementBySoId(soElement):SuperOffice.SoHelper.enableElementBySoId(soElement)),0==associateId&&0==personId&&SuperOffice.SoHelper.disableElementBySoId(id)},onDeleteUserDialogCallback:function(res){var associateId,personId,msg;1==res.getStatus()&&(associateId=res.getContext().AssociateId,personId=res.getContext().PersonId,msg="",0<associateId?msg=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.DeleteUser","",res.getValue(),associateId,personId):0<personId&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.DeletePerson","",personId),""!=msg?Dialog.Information("Error",ResourceUtils.GetResourceText(msg),"error"):(QueuedPageUpdate("soprotocol:adminusers.main[refresh=true]?person_id="+g_clientOptions.LastValidHistoryItem),adminusersUsersArchiveArchiveControl.RefreshList()))},onDeleteOtherUserDialogCallback:function(res){1==res.getStatus()&&(0<(res=res.getContext().AssociateId)&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.DeleteAssociate","",res,0),QueuedPageUpdate("soprotocol:adminusers.adminotherusers[refresh=true]?associate_id=0"),AdminOtherUsersArchiveArchiveControl.RefreshList())},RemoveLoginForOtherUser:function(archiveControl){var rows=archiveControl.getSelectedRows();0<rows.length&&(rows=rows[0].attributes.rowtype.value,0<(rows=parseInt(SuperOffice.SoHelper.getValueFromLinkHint(rows,"associate"),10))&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.RemoveAllUserLicenses","",rows),QueuedPageUpdate("soprotocol:adminusers.adminotherusers[refresh=true]?associate_id=0"),archiveControl.RefreshList())},logoutUser:function(){var associateId=parseInt(SuperOffice.SoHelper.getValueFromLinkHint(adminusersUsersArchiveArchiveControl.getSelectedKey(),"associate"),10);0<associateId&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.LogoutUser","",associateId)},resetUserData:function(id,instance){0<instance.count()?instance.setFirstRowSelected():QueuedPageUpdate("soprotocol:?adminassociate_id=0&associate_id=0&person_id=0")},checkPassword:function(){var newPassword=SuperOffice.SoHelper.getElementBySoId("password_textfield").value,newPassword=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.CheckPassword","",newPassword);0<newPassword.length&&(Dialog.Information("Change password",newPassword,"error"),SuperOffice.SoHelper.getElementBySoId("password_textfield").value=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.GetCurrentPassword"))},openUserGroupDialog:function(){var groupsTitle=$.fromSoId("otherGroups");0<groupsTitle.length&&void 0===$(groupsTitle).data("initial_value")&&$(groupsTitle).data("initial_value",groupsTitle.text()),Dialog.open("usergroup","usergroup[dialog=stop]","SuperOffice.Admin.Users.openUserGroupDialogCallBack();")},openUserGroupDialogCallBack:function(){var groups=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.GetUserGroupsLink"),groupsTitle=$.fromSoId("otherGroups");0<groupsTitle.length&&groupsTitle.text(groups),$(groupsTitle).data("initial_value")!=groups&&SuperOffice.SoHelper.enableElementsBySoId("tempSave","tempCancel")},setPrimaryUserGroup:function(id){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.SetPrimaryGroup","",Number(id))},setRole:function(id){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.SetRole","",Number(id))},openAddRoleDialog:function(currentName,roleListObj){var clearScrollPosString="";""!=(roleListObj=void 0===roleListObj?"":roleListObj)&&(clearScrollPosString=roleListObj+"_List.ClearScrollPos();"),Dialog.open("admineditrole","admineditrole[dialog=stop]?adminrolecurrentname_name="+currentName,"QueuedPageUpdate('soprotocol:?"+currentName+"_id="+g_clientOptions.LastValidHistoryItem+"&adminrolecurrentname_id="+g_clientOptions.LastValidHistoryItem+"&"+currentName+"listentry_id="+g_clientOptions.LastValidHistoryItem+"'); "+clearScrollPosString)},openEditRoleDialog:function(listboxId,rowId,currentName){listboxId=SuperOffice.Gui.SoListBox.getPrimaryKeyFromRowId(listboxId,rowId);Dialog.open("admineditrole","admineditrole[dialog=stop]?"+currentName+"_id="+listboxId+"&adminrolecurrentname_id=1&adminrolecurrentname_name="+currentName+"&isedit=true","QueuedPageUpdate('soprotocol:?"+currentName+"_id="+g_clientOptions.LastValidHistoryItem+"&adminrolecurrentname_id="+g_clientOptions.LastValidHistoryItem+"'); ")},checkUsername:function(){var newUsername=SuperOffice.SoHelper.getElementBySoId("userId_textfield").value,newUsername=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.CheckUsername","",newUsername);0<newUsername.length&&(Dialog.Information("Change username",newUsername,"error"),SuperOffice.SoHelper.getElementBySoId("userId_textfield").value=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.GetCurrentUsername"))},addOwnerContact:function(){SuperOffice.Find.OpenFindInlineDialog({CriterionEntity:"findcontact",FindType:SuperOffice.Find.FindTypeEnum.Single,StaticOverride:"",MultiSelect:!1,IsSelectionAdd:!1,Callback:"SuperOffice.Admin.Users.addOwnerContactCallBack"})},addOwnerContactCallBack:function(res){var contactId;1==res.getStatus()&&(contactId=-1,0<(contactId=2==(res=/contact_id=(\d+)/.exec(res.getValue())).length?parseInt(res[1]):contactId))&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.AddOwnerContact","",contactId),QueuedPageUpdate("soprotocol:ownercontacts[refresh=true]?admincontact="+contactId))},removeOwnerContact:function(archiveControlId,archiveSelectedRowElements){for(var i=0;i<archiveSelectedRowElements.length;i++){var contactId=parseInt(archiveSelectedRowElements[i].getAttribute("primarykey"));AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.RemoveOwnerContact","",contactId)}archiveControlId.RefreshList()},updateRole:function(listboxId,rowId,currentName){var listboxId=SuperOffice.Gui.SoListBox.getPrimaryKeyFromRowId(listboxId,rowId),rowId=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRolesDataHandler.GetCurrentUserRole","")==listboxId,hasWriteAccess=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRolesDataHandler.HasRoleManagementWriteAccess","");rowId||!hasWriteAccess?SuperOffice.SoHelper.disableElementsBySoId("RolesReportsList_button1"):SuperOffice.SoHelper.enableElementsBySoId("RolesReportsList_button1"),QueuedPageUpdate("soprotocol:adminroles[noupdate=true]?"+currentName+"_id="+listboxId)},getPrimaryKeyFromListBoxRow:function(listboxId,rowId){rowId=rowId.split(";");return document.getElementById(rowId[0]).attributes.primaryKey.value},ChangeCheck:function(formId,btnSave,btnCancel){g_formIsValid&&(SuperOffice.SoHelper.disableElementsBySoId(btnSave,btnCancel),$("[soid="+formId+"] input[type=text],[soid="+formId+"] input[type=hidden],[soid="+formId+"] input[type=checkbox],[soid="+formId+"] input[type=password], [soid="+formId+"] textarea").each(function(i){$(this).data("initial_value",pub.getControlValue(this))}),$("[soid="+formId+"] input[type=text],[soid="+formId+"] input[type=password], [soid="+formId+"] textarea").keypress(function(){pub.getControlValue(this)!=$(this).data("initial_value")&&SuperOffice.SoHelper.enableElementsBySoId(btnSave,btnCancel)}),$("[soid="+formId+"] input[type=text],[soid="+formId+"] input[type=hidden],[soid="+formId+"] input[type=checkbox]").change(function(){pub.getControlValue(this)!=$(this).data("initial_value")&&SuperOffice.SoHelper.enableElementsBySoId(btnSave,btnCancel)}))},getControlValue:function(control){return"checkbox"==$(control).attr("type")?control.checked:$(control).valueOf()},saveClick:function(){SuperOffice.SoHelper.getElementBySoId("roleMDO_SearchBox").value.length<=0||SuperOffice.SoHelper.getElementBySoId("primaryGroupMDO_SearchBox").value.length<=0?Dialog.Information("SuperOffice","Cannot save user without selecting a role and primary group"):(SuperOffice.SoHelper.disableElementsBySoId("tempSave","tempCancel"),PageUpdate("soprotocol:adminusers.main[mode=save]?person_id="+g_clientOptions.LastValidHistoryItem,function(){adminusersUsersArchiveArchiveControl.RefreshList()}))},cancelClick:function(){QueuedPageUpdate("soprotocol:adminusers[noupdate=true].main[refresh=true]?person_id="+g_clientOptions.LastValidHistoryItem,"")},updateUserGroupsCurrent:function(){var selectedIds=SuperOffice.SoCheckedListBox("adminUserGroupsGroup").getIdsFromHighlightedRows(),rowId=0<selectedIds.length?selectedIds[0]:-1,selectedIds=selectedIds.join(",");QueuedPageUpdate("soprotocol:adminusers[noupdate=true].usergroups?adminusergroups_id="+rowId+"&adminusergroups_type="+selectedIds+"&adminusergroups_name="+selectedIds)},updateUserGroupsSelectAll:function(){SuperOffice.SoCheckedListBox("adminUserGroupsGroup").highlightAll(),this.updateUserGroupsCurrent()},updateUserGroupsUnselectAll:function(){SuperOffice.SoCheckedListBox("adminUserGroupsGroup").highlightNone(),this.updateUserGroupsCurrent()},showSelectCredentialsDialog:function(isImport,associateId,callback){associateId=Number.isInteger(associateId)?"?associate_id="+associateId:"";Dialog.open("selectcredential","selectcredentials[dialog=stop]"+associateId,"SuperOffice.Admin.Users.showLinkCredentialsDialog(0, "+isImport+", "+callback+");")},showSelectCredentialsDialogForType:function(associateId,credentialType,callback){Dialog.open("selectcredential","selectcredentials[dialog=stop]"+("?associate_id="+associateId+"&credentialType="+credentialType),"SuperOffice.Admin.Users.showLinkCredentialsDialog(0, 0, "+callback+");")},showAddCredentialsDialog:function(isImport){Dialog.open("selectcredential","selectcredentials[dialog=stop]&add_credentials=1&isImport="+(isImport=void 0===isImport?0:isImport),"SuperOffice.Admin.Users.showLinkCredentialsDialog(1, "+isImport+");")},showLinkCredentialsDialog:function(addCredentialsType,isImport,callback){void 0===callback&&(callback="QueuedPageUpdate('soprotocol:main[refresh=true]')");var retVal=Dialog.getReturnValue().split(";");"Link"==retVal[1]?"1"==isImport?Dialog.open("adminuserimportlinkcredentials","adminuserimportlinkcredentials[dialog=stop]?admincredentialuser_id=0&credentialType="+retVal[0]+"&add_credentials="+addCredentialsType+"&isImport="+isImport,callback):Dialog.open("adminusereditlinkcredential","adminusereditlinkcredential[dialog=stop]?admincredentialuser_id=0&credentialType="+retVal[0]+"&add_credentials="+addCredentialsType+"&isImport="+isImport,callback):"function"==typeof callback?callback():eval(callback)},changeLinkCredentialsDialog:function(credentialsType,callback){Dialog.open("adminusereditlinkcredential","adminusereditlinkcredential[dialog=stop]?admincredentialuser_id=0&credentialType="+credentialsType+"&add_credentials=0",callback=void 0===callback?"QueuedPageUpdate('soprotocol:main[refresh=true]')":callback)},searchInLinkCredentialsDialog:function(personNameElement,typeElement){QueuedPageUpdate("soprotocol:adminusereditlinkcredential[dialog=stop].main[refresh=true]?admincredentialuser_id=0&credentialType="+so(typeElement).value+"&add_credentials=0&searchString="+so(personNameElement).value)},deleteCredential:function(credType){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminAssociatesDataHandler.DeleteCredential","",credType),QueuedPageUpdate("soprotocol:main[refresh=true]")},importPersonCredentials:function(archiveControl,type,ownercontact,role,usergroup){if(void 0!==ownercontact&&void 0!==ownercontact.value){for(var selectedRows=archiveControl.getSelectedRows(),rows=new Array,i=0;i<selectedRows.length;i++)rows[i]=selectedRows[i].attributes.rowtype.value;AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminUserEditLinkCredentialDataHandler.ImportLinkCredentials","",JsonHelper.toJSON(rows),type.value,parseInt(ownercontact.value,10),parseInt(role.value,10),parseInt(usergroup.value,10))}}};return pub}(),SuperOffice.Admin.Roles=(()=>{var pub={onChangeDataRights:function(roleId,tableName,relationToOwnerPosition,value){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRolesDataHandler.OnChangeDataRights","",roleId,tableName,relationToOwnerPosition,value)},openDeleteRoleDialog:function(currentName){Dialog.open("admindeleterole","admindeleterole[dialog=stop]?adminrolecurrentname_name="+currentName,"QueuedPageUpdate('soprotocol:?"+currentName+"_id=0&"+currentName+"listentry_id=0&');")}};return pub})(),SuperOffice.Admin.Preferences=(()=>{var pub={ClearCache:function(){var selectedSection=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","selectedsection"),selectedKey=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","selectedpreference");null!=selectedSection.Type&&0<selectedSection.Type.length&&null!=selectedKey.Type&&0<selectedKey.Type.length&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditPreferenceDialogDataHandler.ClearUserPreferenceCache","",selectedSection.Type,selectedKey.Type)},openEditPreferenceDialog:function(){Dialog.open("admineditpreference","admineditpreference[dialog=stop]?adminuserpreference_id=0","QueuedPageUpdate('soprotocol:adminpreferences[noupdate=true].main[refresh=true]?selectedpreference_id="+g_clientOptions.LastValidHistoryItem+"');")},SetMaxLevelOnRadioButtons:function(maxLevel,minLevel){"SystemWide"==maxLevel?(SuperOffice.SoHelper.disableSoRadioButtonListItem("editPreferenceRadioButton",3),SuperOffice.SoHelper.disableSoRadioButtonListItem("editPreferenceRadioButton",2),SuperOffice.SoHelper.disableSoRadioButtonListItem("editPreferenceRadioButton",1)):"Database"==maxLevel?(SuperOffice.SoHelper.disableSoRadioButtonListItem("editPreferenceRadioButton",3),SuperOffice.SoHelper.disableSoRadioButtonListItem("editPreferenceRadioButton",2)):"Group"==maxLevel&&SuperOffice.SoHelper.disableSoRadioButtonListItem("editPreferenceRadioButton",3),"5"===minLevel&&(SuperOffice.SoHelper.disableSoRadioButtonListItem("editPreferenceRadioButton",0),SuperOffice.SoHelper.disableSoRadioButtonListItem("editPreferenceRadioButton",2),SuperOffice.SoHelper.disableSoRadioButtonListItem("editPreferenceRadioButton",1))},updateCurrent:function(listboxId,rowId,rowType,currentName){QueuedPageUpdate("soprotocol:adminpreferences[noupdate=true].main?"+currentName+"_id="+rowId+"&"+currentName+"_type="+rowType)},SetIndividualSettings:function(isChecked){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminPreferencesDataHandler.SetIndividualSettings","",isChecked)},searchBoxKeyPressed:function(textfield){SuperOffice.Throttle.run("searchBoxKeyPressed",1e3,function(){pub.searchBoxKeyPressedCallBack(textfield)})},searchBoxKeyPressedCallBack:function(textfield){QueuedPageUpdate("soprotocol:adminpreferences[noupdate=true].main?adminpreferencesearchbox_id=0&adminpreferencesearchbox_name="+textfield.value)},clearSearchBox:function(){QueuedPageUpdate("soprotocol:adminpreferences[noupdate=true].main?adminpreferencesearchbox_id=0&adminpreferencesearchbox_name=&adminpreferencesearchbox_type=")}};return pub})(),SuperOffice.Admin.Lists=function(){var pub={SetUseHeadingAndGrouping:function(enable){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminListsDataHandler.SetUseHeadingAndGrouping","",enable),QueuedPageUpdate("soprotocol:adminlists.main[refresh=true]?adminlist_id="+g_clientOptions.LastValidHistoryItem)},EnableDisableDeletedItemsAndHeadings:function(checkbox){checkbox.checked?QueuedPageUpdate("soprotocol:adminlists.main?adminshowdeleted_id=1"):QueuedPageUpdate("soprotocol:adminlists.main?adminshowdeleted_id=0"),adminlistitemssettingsArchiveControl.ChangeEntitySetting(checkbox,"deleted")},deleteCurrentList:function(){Dialog.YesNo("","[SR_ADMIN_LIST_CONFIRM_DELETE_LIST]","question","","SuperOffice.Admin.Lists.deleteCurrentListCallback","")},deleteCurrentListCallback:function(res){1==res.getStatus()&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminListsDataHandler.DeleteCurrentList"),QueuedPageUpdate("soprotocol:adminlists.main[refresh=true]?adminlist_id=0"))},openEditDialog:function(tableName,adminlistitemId){AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.SetCurrent","","adminlistitem",adminlistitemId,"","");var newItem=0,callBackString="";adminlistitemId<=0?(newItem=1,callBackString+="SuperOffice.Admin.Lists.setListItemsUserGroup(SuperOffice.SoCheckedListBox('visibleForUserGroups').getSimpleMdoItems(), true);QueuedPageUpdate('soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id=' + g_clientOptions.LastValidHistoryItem);"):callBackString+="QueuedPageUpdate('soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id=' + g_clientOptions.LastValidHistoryItem);","saletype"==tableName?pub.openEditSaleTypeDialog(newItem,callBackString):"associate"==tableName?pub.openEditResourceDialog(newItem,callBackString):"projtype"==tableName?pub.openEditProjectTypeDialog(newItem,callBackString):"currency"==tableName?pub.openEditCurrencyDialog(newItem,callBackString):"amountclass"==tableName?pub.openEditAmountClassDialog(newItem,callBackString):"task"==tableName?pub.openEditFollowUpDialog(newItem,callBackString):"prob"==tableName?pub.openEditSaleStageDialog(newItem,callBackString):"webpanel"==tableName?pub.openEditWebPanelDialog(newItem,callBackString):"extapp"==tableName?pub.openEditExtAppDialog(newItem,callBackString):"doctmpl"==tableName?pub.openAddTemplateDialog(newItem,callBackString,adminlistitemId):"relationdefinition"==tableName?pub.openEditRelationDialog(newItem,callBackString):"country"==tableName?pub.openEditCountryDialog(newItem,callBackString):"legalbase"==tableName?pub.openEditLegalBaseDialog(newItem,callBackString):"consentsource"==tableName?pub.openEditConsentSourceDialog(newItem,callBackString):"emailtemplate"==tableName||"mailhtmltemplate"==tableName?pub.openEmailTemplateDialog(newItem,callBackString):"usergroup"==tableName?pub.openEditUsergroupDialog(adminlistitemId,!0):"taskmenu"==tableName?pub.openEditTaskMenuDialog(adminlistitemId,!0):"mailingdomains"==tableName?pub.openEditMailingDomainsDialog(adminlistitemId,!0):"category"==tableName?pub.openEditCategoryListItemDialog(adminlistitemId):"mrmrs"===tableName||"chat"===tableName||"producttype"===tableName||"productfamily"===tableName||"productcategory"===tableName||"subscriptionunit"===tableName||"priceunit"===tableName?pub.openEditItemSingleLangDialog(callBackString):pub.openEditListItemDIalog(adminlistitemId,tableName)},setDeletedListItem:function(value,archiveControl){var id,historyItem=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","adminlist");"usergroup"==historyItem.Type?(id=(id=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","adminlistitem").Id)<=0?parseInt(archiveControl.getSelectedKeys(),10):id)<=0?Dialog.Information("SuperOffice","Please select a usergroup to delete."):Dialog.open("adminlistsedititem","adminlistsdeleteusergroup[dialog=stop]&id="+id,"adminlistitemssettingsArchiveControl.RefreshList();"):"doctmpl"==historyItem.Type&&1==AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditTemplateDataHandler.IsInUse")?(archiveControl=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditTemplateDataHandler.TemplateUsedBy"),Dialog.YesNo("SuperOffice",archiveControl,"question","","SuperOffice.Admin.Lists.deleteCurrentTemplateCallback","")):(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminListItemsDataHandlerBase.SetDeleted","",value),adminlistitemssettingsArchiveControl.RefreshList())},deleteCurrentTemplateCallback:function(res){1==res.getStatus()&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditTemplateDataHandler.DeleteCurrentTemplate"),adminlistitemssettingsArchiveControl.RefreshList())},setNavigationUrl:function(navTextbox,windowName,visibleIn,checkBoxSoId,checkBoxNeverSoId){visibleIn=parseInt(visibleIn,10),windowName=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminListsDataHandler.GenerateNavigationUrl","",visibleIn,windowName);navTextbox.value=windowName.Item1,windowName.Item2?($.fromSoId(checkBoxSoId).prop("checked",!1),SuperOffice.SoHelper.disableElementBySoId(checkBoxSoId)):SuperOffice.SoHelper.enableElementBySoId(checkBoxSoId),19===visibleIn?SuperOffice.SoHelper.enableElementBySoId(checkBoxNeverSoId):($.fromSoId(checkBoxNeverSoId).prop("checked",!1),SuperOffice.SoHelper.disableElementBySoId(checkBoxNeverSoId)),74!==visibleIn?(SuperOffice.SoHelper.hideElementBySoId("webPanelCustomObjectLbl"),SuperOffice.SoHelper.hideElementBySoId("webPanelCustomObjectMDO")):(SuperOffice.SoHelper.showElementBySoId("webPanelCustomObjectLbl"),SuperOffice.SoHelper.showElementBySoId("webPanelCustomObjectMDO"),so("webPanelCustomObjectMDO").style.display="inline-flex")},showHideByExtAppAddIn:function(addIn){2==addIn?SuperOffice.SoHelper.showElementBySoId("editExtAppIconDescriptionGroup"):SuperOffice.SoHelper.hideElementBySoId("editExtAppIconDescriptionGroup"),1==addIn?SuperOffice.SoHelper.showElementBySoId("editExtAppMenuGroup"):SuperOffice.SoHelper.hideElementBySoId("editExtAppMenuGroup"),0==addIn?SuperOffice.SoHelper.showElementBySoId("editExtAppEventGroup"):SuperOffice.SoHelper.hideElementBySoId("editExtAppEventGroup"),-1==addIn?SuperOffice.SoHelper.showElementBySoId("editExtAppTaskMdoGroup"):SuperOffice.SoHelper.hideElementBySoId("editExtAppTaskMdoGroup")},checkWindowName:function(e){65<=e.keyCode&&e.keyCode<=120||35<=e.keyCode&&e.keyCode<=40||8==e.keyCode||46==e.keyCode||e.preventDefault()},setListItemsUserGroup:function(userGroups,enable){for(var stringArray="",i=0;i<userGroups.length;i++)stringArray+=userGroups[i].Type+",";AjaxMethodDispatcher.CallASync(function(){SuperOffice.PageBuilder.refreshCurrent("adminlistitemusergroup")},null,null,"","SuperOffice.CRM.Web.Data.AdminListsDataHandler.SetVisible",stringArray,enable),SuperOffice.Admin.Lists.DisableApply(!1)},DisableApply:function(disable){disable?(SuperOffice.SoHelper.disableElementBySoId("visibleForUserGroups_button_0"),SuperOffice.SoHelper.disableElementBySoId("userGroupsListItems_button_0")):(SuperOffice.SoHelper.enableElementBySoId("visibleForUserGroups_button_0"),SuperOffice.SoHelper.enableElementBySoId("userGroupsListItems_button_0"))},SetListItemsForUsergroup:function(userGroups,enable){AjaxMethodDispatcher.CallASync(function(){SuperOffice.PageBuilder.refreshCurrent("adminlistitem")},null,null,"","SuperOffice.CRM.Web.Data.AdminListsDataHandler.SetListItemsForUsergroup",userGroups,enable),SuperOffice.Admin.Lists.DisableApply(!1)},SetListItemsForHeading:function(headings,enable){AjaxMethodDispatcher.CallASync(function(){SuperOffice.PageBuilder.refreshCurrent("adminlistitem")},null,null,"","SuperOffice.CRM.Web.Data.AdminListsDataHandler.SetListItemsForHeading",headings,enable)},searchBoxListKeyPressedCallBack:function(event,textfield,currentName){void 0===event&&QueuedPageUpdate("soprotocol:?"+currentName+"_id=0&"+currentName+"_name="+textfield.value),13===event.keyCode?QueuedPageUpdate("soprotocol:?"+currentName+"_id=0&"+currentName+"_name="+textfield.value):8!==event.keyCode||""!==textfield.value||(event=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","",currentName))&&""===event.Name||QueuedPageUpdate("soprotocol:?"+currentName+"_id=0&"+currentName+"_name=")},searchBoxListIconPressedCallBack:function(textfield,currentName){QueuedPageUpdate("soprotocol:?"+currentName+"_id=0&"+currentName+"_name="+textfield.value)},setDeletedUserGroup:function(mdoListId){SuperOffice.SoCheckedListBox(mdoListId).getSelectedRow()},setCheckBoxStateFromSelectedMdoList:function(mdoListId,checkBoxId){mdoListId=SuperOffice.SoCheckedListBox(mdoListId).getCheckedRows(),checkBoxId=$.fromSoId(checkBoxId);mdoListId.length<=0?(checkBoxId.attr("checked",!1),checkBoxId.attr("disabled",!0)):checkBoxId.attr("disabled",!1)},setListItemsHeading:function(headings,enable){for(var stringArray="",i=0;i<headings.length;i++)0<i&&(stringArray+=","),stringArray+=headings[i].Type;AjaxMethodDispatcher.CallASync("","","","","SuperOffice.CRM.Web.Data.AdminListsDataHandler.SetHeadings",stringArray,enable),SuperOffice.PageBuilder.refreshCurrent("adminlistitemheading")},sort:function(archiveControl){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminListsDataHandler.SortList",""),archiveControl.RefreshList()},moveUp:function(archiveControl){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminListsDataHandler.MoveListItem","",-1),archiveControl.RefreshList()},moveDown:function(archiveControl){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminListsDataHandler.MoveListItem","",1),archiveControl.RefreshList()},openAddDialog:function(){var historyItem=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","adminlist");pub.openEditDialog(historyItem.Type,0)},openEditListItemDIalog:function(listItemId,tableName){var list=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","adminlist");$dlgm.open(null,{id:"editListItemDialog",recipeName:"EditListItemDialog",caption:"[SR_ADMIN_LIST_EDIT_LIST_ITEM]",windowSetting:{width:"750",height:"440"}},function(ctx){ctx.set("listId",list.Id),ctx.set("listItemId",listItemId),ctx.set("listType",list.Type)},(ctx,state)=>{1==state&&QueuedPageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id="+ctx.state.listItemId)})},openEditItemDialog:function(callBackString){Dialog.open("adminlistsedititem","adminlistsedititem[dialog=stop]",callBackString)},openEditItemSingleLangDialog:function(callBackString){Dialog.open("adminlistsedititem","adminlistsedititemsinglelang[dialog=stop]",callBackString)},openEditSaleTypeDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditsaletype[dialog=stop]&newItem="+newItem,callBackString)},openEditProjectTypeDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditprojecttype[dialog=stop]&newItem="+newItem,callBackString)},openEditCurrencyDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditcurrency[dialog=stop]&newItem="+newItem,callBackString)},openEditLegalBaseDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditlegalbase[dialog=stop]&newItem="+newItem,callBackString)},openEditConsentSourceDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditconsentsource[dialog=stop]&newItem="+newItem,callBackString)},openEditAmountClassDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditamountclass[dialog=stop]&newItem="+newItem,callBackString)},openEditFollowUpDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditfollowup[dialog=stop]&newItem="+newItem,callBackString)},openEditWebPanelDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditwebpanel[dialog=stop]&newItem="+newItem,callBackString)},openEditExtAppDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditextapp[dialog=stop]&newItem="+newItem,callBackString)},openEditResourceDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditresource[dialog=stop]&newItem="+newItem,callBackString)},openEditSaleStageDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditsalestage[dialog=stop]&newItem="+newItem,callBackString)},openAddHeadingDialog:function(type,setHeadingCurrent){Dialog.open("adminlistsedititem","adminlistseditheading[dialog=stop]&id="+type,setHeadingCurrent?"QueuedPageUpdate('soprotocol:adminlists[noupdate=true].main[refresh=true]');":"SuperOffice.PageBuilder.refreshCurrent('adminlistitem');")},openEditRelationDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditrelation[dialog=stop]&newItem="+newItem,callBackString)},openAddTemplateDialog:function(newItem,callBackString,adminlistitemId){"1"==newItem?Dialog.open("adminlistsaddtemplate","adminlistsaddtemplate[dialog=stop]","SuperOffice.Admin.Lists.callCallBack();"):Dialog.open("adminlistsedititem","adminlistsedittemplate[dialog=stop]?adminlistitem_id="+adminlistitemId,callBackString)},openEmailTemplateDialog:function(newItem,callBackString){"1"==newItem?Dialog.open("adminlistsaddemailtemplate","adminlistsaddemailtemplate[dialog=stop]","SuperOffice.Admin.Lists.callEmailTemplateCallBack();"):Dialog.open("adminlistseditemailtemplate","adminlistseditemailtemplate[dialog=stop]",callBackString)},openEditCategoryListItemDialog:function(listItemId){$dlgm.open(null,{id:"editCategoryListItem",recipeName:"EditCategoryListItem",caption:"[SR_ADMIN_LIST_EDIT_LIST_ITEM]",windowSetting:{width:"700",height:"510"}},function(ctx){ctx.set("listItemId",listItemId)},(ctx,state)=>{1===state&&QueuedPageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id="+ctx.state.listItemId)})},openEditTaskMenuDialog:function(taskMenuId,refreshListItem){$dlgm.open(null,{id:"EditTaskMenu",recipeName:"EditTaskMenu",caption:"[SR_ADMIN_LIST_EDIT_LIST_ITEM]",windowSetting:{width:"710",height:"482"}},function(ctx){ctx.set("taskMenuId",taskMenuId)},function(ctx){var tm=ctx.state.taskMenu;!tm||"appointment"!==tm.TableName&&"document"!==tm.TableName&&"Quote"!==tm.TableName?refreshListItem?QueuedPageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id="+ctx.state.taskMenuId):QueuedPageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]"):QueuedPageUpdate("soprotocol:adminlists[flush=true].main[refresh=true]?adminlistitem_id="+ctx.state.taskMenuId)})},openEditMailingDomainsDialog:function(mailingDomainId,refreshListItem){$dlgm.open(null,{id:"EditMailingDomain",recipeName:"EditMailingDomain",caption:"[SR_ADMIN_LIST_EDIT_LIST_ITEM]",windowSetting:{width:"500",height:"240"}},function(ctx){ctx.set("mailingDomainId",mailingDomainId)},function(ctx){refreshListItem?QueuedPageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id="+ctx.state.taskMenuId):QueuedPageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]")})},openEditUsergroupDialog:function(usergroupId,refreshListItem){$dlgm.open(null,{id:"editUsergroupDialog",recipeName:"EditUsergroupDialog",caption:"[SR_ADMIN_LIST_EDIT_LIST_ITEM]",windowSetting:{width:"750",height:"440"}},function(ctx){ctx.set("usergroupId",usergroupId)},function(ctx){refreshListItem?QueuedPageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id="+ctx.state.usergroupId):QueuedPageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]")})},openEditCountryDialog:function(newItem,callBackString){Dialog.open("adminlistsedititem","adminlistseditcountry[dialog=stop]&newItem="+newItem,callBackString)},openAddDocumentTemplateLanguageDialog:function(callBackString){Dialog.open("adminlistsaddtemplatelanguage","adminlistsaddtemplatelanguage[dialog=stop]","editTemplateRegisteredLanguagesArchiveControl.RefreshList();")},openAddEmailTemplateLanguageDialog:function(callBackString){Dialog.open("adminlistaddlanguageemailtemplate","adminlistaddlanguageemailtemplate[dialog=stop]","editTemplateRegisteredLanguagesArchiveControl.RefreshList();")},setDocumentTemplateLanguageCreationMode:function(mode){""==mode&&(mode=$("[soid=addTemplateLanguageUploadOrCopy]").attr("value"));var controlGroups_upload=["addTemplateLanguageUpload"],controlGroups_copy=["addTemplateLanguageCopyFile"];$("[soid=addTemplateLanguageUploadOrCopy]").attr("value",mode),"upload"==mode?($("[soid=addTemplateLanguageUploadRadio]").attr("Checked","1"),SuperOffice.SoHelper.enableElementsBySoId(controlGroups_upload),SuperOffice.SoHelper.disableElementsBySoId(controlGroups_copy)):"copy"==mode?(SuperOffice.SoHelper.getElementBySoId("addTemplateLanguageUploadFile_textfield").style.color="",$("[soid=addTemplateLanguageCopyRadio]").attr("Checked","1"),SuperOffice.SoHelper.disableElementsBySoId(controlGroups_upload),SuperOffice.SoHelper.enableElementsBySoId(controlGroups_copy)):pub.setDocumentTemplateLanguageCreationMode("upload")},documentTemplateLanguage:function(title,soprotocol){$.fromSoId("addTemplateLanguageUploadFile_textfield").attr("value",decodeURIComponent((title+"").replace(/\+/g,"%20"))),defValue1=ResourceUtils.GetResourceText("[SR_SELECT_A_FILE]"),defValue2=ResourceUtils.GetResourceText("[SR_SELECT_A_HTMLFILE]"),curVal=SuperOffice.SoHelper.getElementBySoId("addTemplateLanguageUploadFile_textfield").value,defValue1===curVal||defValue2===curVal?SuperOffice.SoHelper.getElementBySoId("addTemplateLanguageUploadFile_textfield").style.color="red":SuperOffice.SoHelper.getElementBySoId("addTemplateLanguageUploadFile_textfield").style.color="",soprotocol?QueuedPageUpdate("soprotocol:adminlistsaddtemplatelanguage[dialog=stop].main[refresh=false]"):QueuedPageUpdate("soprotocol:"+soprotocol+"[dialog=stop].main[refresh=false]")},deleteDocumentTemplateLanguage:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.Admin.AdminEditTemplateDataHandler.DeleteDocumentTemplateLanguage",""),editTemplateRegisteredLanguagesArchiveControl.RefreshList()},saveDocumentTemplateLanguageCallback:function(title){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.Admin.AdminEditTemplateDataHandler.SaveDocumentTemplateLanguageWithCurrent","",title)},saveDocumentTemplateLanguage:function(){OpenFileDialog("document",0,"saveDocumentTemplateLanguage")},editDocumentTemplateLanguage:function(doRefresh){var languageCode=parseInt(editTemplateRegisteredLanguagesArchiveControl.getSelectedKey());SuperOffice.Admin.Lists.DownloadTemplate(languageCode,doRefresh)},callCallBack:function(){SuperOffice.Admin.Lists.setListItemsUserGroup(SuperOffice.SoCheckedListBox("visibleForUserGroups").getSimpleMdoItems(),!0),PageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id="+g_clientOptions.LastValidHistoryItem);Dialog.open("adminlistsedititem","adminlistsedittemplate[dialog=stop]","QueuedPageUpdate('soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id=' + g_clientOptions.LastValidHistoryItem);")},callEmailTemplateCallBack:function(){SuperOffice.Admin.Lists.setListItemsUserGroup(SuperOffice.SoCheckedListBox("visibleForUserGroups").getSimpleMdoItems(),!0),PageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id="+g_clientOptions.LastValidHistoryItem);var historyItem=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","adminlistItem");historyItem&&0<historyItem.Id&&Dialog.open("adminlistseditemailtemplate","adminlistseditemailtemplate[dialog=stop]","QueuedPageUpdate('soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id=' + g_clientOptions.LastValidHistoryItem);")},documentTemplate:function(title,soprotocol){$.fromSoId("addTemplateTitleLbl_textfield").attr("value",decodeURIComponent((title+"").replace(/\+/g,"%20"))),defaultEmailTemplateText=ResourceUtils.GetResourceText("[SR_SELECT_A_HTMLFILE]"),currentValue=SuperOffice.SoHelper.getElementBySoId("addTemplateTitleLbl_textfield").value,defaultEmailTemplateText===currentValue?SuperOffice.SoHelper.getElementBySoId("addTemplateTitleLbl_textfield").style.color="red":SuperOffice.SoHelper.getElementBySoId("addTemplateTitleLbl_textfield").style.color="",soprotocol?QueuedPageUpdate("soprotocol:"+soprotocol+"[dialog=stop].main[refresh=false]"):QueuedPageUpdate("soprotocol:adminlistsaddtemplate[dialog=stop].main[refresh=false]")},saveDocumentTemplate:function(title){$("[soid=editTemplateFileName_textfield]").attr("value",decodeURIComponent((title+"").replace(/\+/g,"%20"))),QueuedPageUpdate("soprotocol:adminlistsedittemplate[dialogwinname=adminlistsedititem&dialog=stop].footer[mode=save&responsemode=edit]")},setTemplateCreationMode:function(mode){""==mode&&(mode=$("[soid=addTemplateNewOrCopy]").attr("value"));var controlGroups_newTempl=["addTemplateStoreTypeMDO"],controlGroups_upload=["addTemplateFileUpload"],controlGroups_copy=["addTemplateCopyMDO"];$("[soid=addTemplateNewOrCopy]").attr("value",mode),$("[soid=addTemplateNewOrCopy]").attr("value",mode),"new"==mode?($("[soid=addTemplateRadioNew]").attr("Checked","1"),SuperOffice.SoHelper.getElementBySoId("addTemplateTitleLbl_textfield").style.color="",SuperOffice.SoHelper.enableElementsBySoId(controlGroups_newTempl),SuperOffice.SoHelper.disableElementsBySoId(controlGroups_upload),SuperOffice.SoHelper.disableElementsBySoId(controlGroups_copy)):"upload"==mode?($("[soid=addTemplateRadioUpload]").attr("Checked","1"),SuperOffice.SoHelper.disableElementsBySoId(controlGroups_newTempl),SuperOffice.SoHelper.enableElementsBySoId(controlGroups_upload),SuperOffice.SoHelper.disableElementsBySoId(controlGroups_copy)):"copy"==mode?($("[soid=addTemplateRadioCopy]").attr("Checked","1"),SuperOffice.SoHelper.getElementBySoId("addTemplateTitleLbl_textfield").style.color="",SuperOffice.SoHelper.disableElementsBySoId(controlGroups_newTempl),SuperOffice.SoHelper.disableElementsBySoId(controlGroups_upload),SuperOffice.SoHelper.enableElementsBySoId(controlGroups_copy)):pub.setTemplateCreationMode("upload")},EditHtmlTemplate:function(templateId,languageCodeName,refresh){UIHelper.GetMainPageWindow().$dlgm.open(null,{id:"EditDocumentTemplate",recipeName:"DocumentTemplateDialog",caption:ResourceUtils.GetResourceText("[SR_ADMIN_EDIT_TEMPLATE]")},function(ctx){ctx.set("templateProperties",{templateId:templateId,languageCode:languageCodeName})},function(){refresh&&pub.RefreshAfterEditingEmailTemplate()})},EditSoMailTemplate:function(templateId,languageCodeName){UIHelper.GetMainPageWindow().$dlgm.open(null,{id:"EditEmailTemplate",recipeName:"EmailTemplateDialog",caption:ResourceUtils.GetResourceText("[SR_ADMIN_EDIT_TEMPLATE]")},function(ctx){ctx.set("templateProperties",{templateId:templateId,languageCode:languageCodeName})},function(){pub.RefreshAfterEditingEmailTemplate()})},RefreshAfterEditingEmailTemplate:function(){var soProtocolParts=SuperOffice.Environment.SoProtocol.split(".");2===soProtocolParts.length?"details"!==soProtocolParts[1]&&PageUpdate("soprotocol:"+soProtocolParts[0]+"[dialog=stop]."+soProtocolParts[1]+"[mode=edit]?admintemplatelanguage_id="+g_clientOptions.LastValidHistoryItem,""):PageUpdate("soprotocol:adminlistseditemailtemplate[dialog=stop].languages[mode=edit]?admintemplatelanguage_id="+g_clientOptions.LastValidHistoryItem,"")},DownloadTemplate:function(languageCode,refresh){var historyItem=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","adminlistItem"),properties=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.GetDocumentTemplateProperties","",historyItem.Id,languageCode),filename=properties["file-name"],languageCodeName=properties.LanguageCode||"",res;0<filename.toLowerCase().indexOf(".htm")||0<filename.toLowerCase().indexOf(".html")?this.EditHtmlTemplate(historyItem.Id,languageCodeName,refresh):0<filename.toLowerCase().indexOf(".somail")||0<filename.toLowerCase().indexOf(".eml")?this.EditSoMailTemplate(historyItem.Id,languageCodeName):0<$.fromSoId("showNewEmailDialogCheckBox").length?filename.indexOf(".")<0&&($.fromSoId("showNewEmailDialogCheckBox")[0].disabled?this.EditHtmlTemplate(historyItem.Id,languageCodeName,refresh):this.EditSoMailTemplate(historyItem.Id,languageCodeName)):(res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.DownloadDocumentTemplate","",historyItem.Id,languageCode),eval(res))},getRelationWho:function(radioListName){var retVal="",radioListName=SuperOffice.SoHelper.getSoRadioButtonListSelectedValue(radioListName);return"Contact"==radioListName?retVal=ResourceUtils.GetResourceText("[SR_ADMIN_RELATION_CONTACT]"):"Person"==radioListName?retVal=ResourceUtils.GetResourceText("[SR_ADMIN_RELATION_PERSON]"):"Both"==radioListName&&(retVal=ResourceUtils.GetResourceText("[SR_ADMIN_RELATION_BOTH]")),retVal},RelationExample:function(){var activeWho=SuperOffice.Admin.Lists.getRelationWho("relationActiveRadio"),passiveWho=SuperOffice.Admin.Lists.getRelationWho("relationPassiveRadio"),active="",passive="";""!=$("[soid=relationName_textfield]").attr("value")&&(active=activeWho+" A <b><u>"+$("[soid=relationName_textfield]").attr("value")+"</u></b> "+passiveWho+" B"),""!=$("[soid=relationPassive_textfield]").attr("value")&&(passive+=passiveWho+" B <b><u>"+$("[soid=relationPassive_textfield]").attr("value")+"</u></b> "+activeWho+" A"),$("[soid=relationExample1]").html(active),$("[soid=relationExample2]").html(passive)},deleteHeading:function(ids){for(var stringArray="",i=0;i<ids.length;i++)0<i&&(stringArray+=","),stringArray+=ids[i];AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminListsDataHandler.DeleteHeading","",stringArray),QueuedPageUpdate("soprotocol:adminlists[noupdate=true].main[refresh=true]?adminlistitem_id="+g_clientOptions.LastValidHistoryItem)},rankHeadings:function(userGroups){for(var stringArray="",i=0;i<userGroups.length;i++)0<i&&(stringArray+=","),stringArray+=userGroups[i].Type;AjaxMethodDispatcher.CallASync("","","","","SuperOffice.CRM.Web.Data.AdminListsDataHandler.RankHeadings",stringArray)},EnableDisableAddressField:function(isLocation){"False"==isLocation?(SuperOffice.SoHelper.hideElementBySoId("resourceAddress_textfield"),SuperOffice.SoHelper.disableElementBySoId("resourceAddressLbl")):(SuperOffice.SoHelper.showElementBySoId("resourceAddress_textfield"),SuperOffice.SoHelper.enableElementBySoId("resourceAddressLbl"))},onNoRowsSelected:function(id,instance){instance.setFirstRowSelected()},ComputeCurrencyText:function(name,rate,unit,base,info){info.innerText=unit.value+" "+name.value+" = "+rate.value+" "+base.value},ComputeCountryCurrencyText:function(currencyId,info){info.value=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditCountryDialogDataHandler.GetCurrencyText","",parseInt(currencyId.value,10))}};return pub}(),SuperOffice.Admin.Workflow=(()=>{var pub={onNoRowsSelected:function(id,instance){instance.setFirstRowSelected()},openAddActivityDialog:function(id,type){Dialog.open("adminworkfloweditactivity","adminworkfloweditactivity[dialog=stop]&id="+id+"&type="+type,"QueuedPageUpdate('soprotocol:adminworkflow[noupdate=true]."+type+"[refresh=true]');")},openAddDocumentDialog:function(id,type){Dialog.open("adminworkfloweditdocument","adminworkfloweditdocument[dialog=stop]&id="+id+"&type="+type,"QueuedPageUpdate('soprotocol:adminworkflow[noupdate=true]."+type+"[refresh=true]');")},deleteActivities:function(ids,type){for(var idList="",i=0;i<ids.length;i++)idList+=ids[i]+",";AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminWorkflowEditActivityDataHandler.DeleteActivities","",idList),QueuedPageUpdate("soprotocol:adminworkflow[noupdate=true]."+type+"[refresh=true]")},deleteDocuments:function(ids,type){for(var idList="",i=0;i<ids.length;i++)idList+=ids[i]+",";AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminWorkflowEditDocumentDataHandler.DeleteDocuments","",idList),QueuedPageUpdate("soprotocol:adminworkflow[noupdate=true]."+type+"[refresh=true]")},setSaleStageCurrent:function(id,extrainfo){for(var vars=extrainfo.split("&"),i=0;i<vars.length;i++){var pair=vars[i].split("=");if(2==pair.length&&"SaleTypeStageLinkId"==pair[0]){QueuedPageUpdate("soprotocol:adminworkflow[noupdate=true].sales[refresh=true]?adminsaletypestagelink_id="+pair[1]+"&adminsalestage_id="+id);break}}},setProjectStatusCurrent:function(id,extrainfo){for(var vars=extrainfo.split("&"),i=0;i<vars.length;i++){var pair=vars[i].split("=");if(2==pair.length&&"ProjectTypeStatusLinkId"==pair[0]){QueuedPageUpdate("soprotocol:adminworkflow[noupdate=true].project[refresh=true]?adminprojecttypestatuslink_id="+pair[1]+"&adminprojectstatus_id="+id);break}}},EnableDisableDeletedItems:function(checkbox,protocol){checkbox.checked?QueuedPageUpdate("soprotocol:adminworkflow."+protocol+"?adminshowdeleted_id=1"):QueuedPageUpdate("soprotocol:adminworkflow."+protocol+"?adminshowdeleted_id=0")},rank:function(items,functionName){for(var stringArray="",i=0;i<items.length;i++)0<i&&(stringArray+=","),stringArray+=items[i].Id;AjaxMethodDispatcher.CallASync("","","","",functionName,stringArray)},editSaleTypeDialog:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminWorkflowSaleDataHandler.SetListItemCurrent",""),Dialog.open("adminlistseditsaletype","adminlistseditsaletype[dialog=stop]","QueuedPageUpdate('soprotocol:adminworkflow[noupdate=true].sales?adminsaletype_id="+g_clientOptions.LastValidHistoryItem+"')")},editProjectTypeDialog:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminWorkflowProjectDataHandler.SetListItemCurrent",""),Dialog.open("adminlistseditprojecttype","adminlistseditprojecttype[dialog=stop]","QueuedPageUpdate('soprotocol:adminworkflow[noupdate=true].project?adminprojecttype_id="+g_clientOptions.LastValidHistoryItem+"')")},enableSalesGuide:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminWorkflowSaleDataHandler.EnableGuide",""),QueuedPageUpdate("soprotocol:adminworkflow[noupdate=true].sales?adminsaletype_id="+g_clientOptions.LastValidHistoryItem)},enableProjectGuide:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminWorkflowProjectDataHandler.EnableGuide",""),QueuedPageUpdate("soprotocol:adminworkflow[noupdate=true].project?adminprojecttype_id="+g_clientOptions.LastValidHistoryItem)}};return pub})(),SuperOffice.Admin.Saint=function(){var pub={SetField:function(clientStateField,field,value,executeNow){var stateObj=$.parseJSON(so(clientStateField).value);stateObj[field]=value,so(clientStateField).value=JsonHelper.toJSON(stateObj),executeNow?(SuperOffice.Throttle.executeNow(clientStateField),pub.SaveFields(clientStateField),QueuedPageUpdate("soprotocol:?statusmonitor_id="+g_clientOptions.LastValidHistoryItem,"")):0<stateObj.MonitorId&&SuperOffice.Throttle.run(clientStateField,500,function(){SuperOffice.Admin.Saint.SaveFields(clientStateField)})},SaveFields:function(clientStateField){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSaintDataHandler.SaveFields","",so(clientStateField).value)},DeleteStatusMonitor:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSaintDataHandler.DeleteStatusMonitor",""),QueuedPageUpdate("soprotocol:?statusmonitor_id=0")},RefreshPicture:function(elemName){var returnedValue=Dialog.getReturnValue(),imageElementName="g_SoImage_"+elemName;eval(imageElementName).changeImageId(returnedValue),SuperOffice.SoHelper.getElementBySoId(elemName+"Id").value=returnedValue,SuperOffice.PageBuilder.save()},UpdateStatusMonitorPicture:function(imgElemSoId,binId){SuperOffice.SoHelper.getElementBySoId(imgElemSoId).value=binId,document.getElementById("ImageList_SelectedPrimaryKeys").value=binId,document.getElementById("ImageList_SelectedValues").value="",QueuedPageUpdate("soprotocol:adminsaintimage[dialog=stop].main?adminsaintimage_id="+binId+"&adminsaintimage_type="+binId)},openAddMonitorDialog:function(table){Dialog.open("adminsainteditmonitor","adminsainteditmonitor[dialog=stop]&table="+table,"QueuedPageUpdate('soprotocol:adminsaint.company[refresh=true]?statusmonitor_id="+g_clientOptions.LastValidHistoryItem+"');")},openEditMonitorDialog:function(id){Dialog.open("adminsainteditmonitor","adminsainteditmonitor[dialog=stop]&id="+id,"QueuedPageUpdate('soprotocol:adminsaint.company[refresh=true]?statusmonitor_id="+g_clientOptions.LastValidHistoryItem+"');")},setCriteriaGroup:function(groupId){SuperOffice.Find.CriteriaControlManager.saveRestrictions(SuperOffice.Find.CriteriaControlManager.CurrentCriteriaControl),SuperOffice.PageBuilder.setCurrent("adminsaintcriteriagroup",groupId)},openAddCriteriaGroupDialog:function(){AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.SetCurrent","","adminsaintcriteriagroup",-1,"",""),SuperOffice.Find.CriteriaControlManager.disableCurrentCriteriaControl(),Dialog.open("adminsainteditcriteriagroup","adminsainteditcriteriagroup[dialog=stop]","SuperOffice.Admin.Saint.AddGroupCallback();")},AddGroupCallback:function(){SuperOffice.PageBuilder.refresh()},deleteCriteriaGroup:function(){var currentGroup=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","adminsaintcriteriagroup");AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSaintDataHandler.DeleteCriteriaGroup",""),"Contact"==currentGroup.Type&&(currentGroup.Type="Company"),QueuedPageUpdate("soprotocol:?statusmonitor_id="+g_clientOptions.LastValidHistoryItem,SuperOffice.Gui.TabControl.OnTabClick("AdminSaint"+currentGroup.Type+"_tabgroup1",1,0))},openEditCriteriaGroupDialog:function(){Dialog.open("adminsainteditcriteriagroup","adminsainteditcriteriagroup[dialog=stop]?statusmonitor_id="+g_clientOptions.LastValidHistoryItem,"SuperOffice.PageBuilder.refresh()")},openMenuCriteriaGroup:function(event,entityType,rank){entityType="AdminSaint"+entityType;entityType+="_tabgroup1_tab_"+rank,AjaxMethodDispatcher.CallASync("MenuManager.menuCallBack","","",entityType,"SuperOffice.CRM.Web.AjaxMethods.ContextMenu.GetContextMenu","adminsaintmenu","tabmenu",rank)},rank:function(items,functionName,table){for(var stringArray="",i=0;i<items.length;i++)0<i&&(stringArray+=","),stringArray+=items[i].Id;AjaxMethodDispatcher.CallASync("","","","",functionName,table,stringArray)},savePeriodAndComputeDate:function(ownerTableHiddenField,entityName,periodNumber){var ownerTableHiddenField=parseInt(SuperOffice.SoHelper.getElementBySoId(ownerTableHiddenField).value),enabledValue=pub.getEnabledValue(entityName),soIdSource=pub.getPeriodNumberField(entityName,periodNumber),entityName=pub.getPeriodDateResultField(entityName,periodNumber);1==periodNumber&&pub.SavePeriods(ownerTableHiddenField,enabledValue,soIdSource.value),2==periodNumber&&pub.SavePeriods(ownerTableHiddenField,enabledValue,void 0,soIdSource.value),3==periodNumber&&pub.SavePeriods(ownerTableHiddenField,enabledValue,void 0,void 0,soIdSource.value),pub.computeDate(soIdSource,entityName)},getEnabledValue:function(entityName){return"true"===so("SaintMain"+entityName+"Switch_hiddenfield").value},getPeriodNumberField:function(entityName,periodNumber){return so("saintMain"+entityName+"Period"+periodNumber+"_textfield")},getPeriodDateResultField:function(entityName,periodNumber){return so("saintMain"+entityName+"PeriodDate"+periodNumber+"_textfield")},computeDate:function(soElementSource,soElementDest){var toDay=new Date,soElementSource=soElementSource.value;0<soElementSource?(toDay.setDate(toDay.getDate()-soElementSource),soElementDest.value=ResourceUtils.GetResourceText("[SR_LABEL_FROM]")+" "+toDay.toString("dd.MM.yyyy")):soElementDest.value=""},toggleConfiguration:function(value,soElementPeriods){value?SuperOffice.SoHelper.showElementBySoId(soElementPeriods):SuperOffice.SoHelper.hideElementBySoId(soElementPeriods),$(".saintcountertoggle").hasClass("on")?(SuperOffice.SoHelper.showElementBySoId("saintMainLastCounterGenerated_textfield"),SuperOffice.SoHelper.showElementBySoId("saintMainRegenerateCountersLink")):(SuperOffice.SoHelper.hideElementBySoId("saintMainLastCounterGenerated_textfield"),SuperOffice.SoHelper.hideElementBySoId("saintMainRegenerateCountersLink"))},onChangeConfiguration:function(value,ownerTableHiddenField,soElementPeriods){pub.toggleConfiguration(value,soElementPeriods);soElementPeriods=parseInt(SuperOffice.SoHelper.getElementBySoId(ownerTableHiddenField).value);pub.SavePeriods(soElementPeriods,value),SCIL.AxiosCacheManager.ClearCache()},SavePeriods:function(ownerTableId,enabled,period1,period2,period3){0<ownerTableId&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSaintDataHandler.SavePeriods","",ownerTableId,enabled,period1,period2,period3)},EnableDisableDeletedItemsAndHeadings:function(checkbox){checkbox.checked?QueuedPageUpdate("soprotocol:?adminshowdeleted_id=1"):QueuedPageUpdate("soprotocol:?adminshowdeleted_id=0&statusmonitor_id=-1")},EnableDisableRegenOneLinkAndSetNeedsUpdate:function(findInlineControl,regenLink){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSaintDataHandler.SetNeedsUpdate","")},RegenCounters:function(){pub.DisableWhileRegenerating(),SendWorkerCommand("AlarmWorker","CreateTempTask","SAINT"),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSaintDataHandler.RegenerateCounters","")},RegenerateStatusAllMonitors:function(){pub.DisableWhileRegenerating(),SendWorkerCommand("AlarmWorker","CreateTempTask","SAINT"),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSaintDataHandler.RegenerateStatusMonitors","")},RegenerateSelectedStatusMonitor:function(){pub.DisableWhileRegenerating(),SendWorkerCommand("AlarmWorker","CreateTempTask","SAINT"),SuperOffice.SoHelper.disableElementBySoId("AdminSaintCompany_AdminSaintStatusMonitorCriteriasControlGroup"),SuperOffice.SoHelper.disableElementBySoId("AdminSaintProject_AdminSaintStatusMonitorCriteriasControlGroup"),SuperOffice.SoHelper.disableElementBySoId("AdminSaintPerson_AdminSaintStatusMonitorCriteriasControlGroup"),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSaintDataHandler.RegenerateCurrentStatusMonitor","")},DisableWhileRegenerating:function(){SuperOffice.SoHelper.disableElementBySoId("saintMainRegenerateLink"),SuperOffice.SoHelper.disableElementBySoId("AdminSaintCompany_RegenerateLink"),SuperOffice.SoHelper.disableElementBySoId("AdminSaintProject_RegenerateLink"),SuperOffice.SoHelper.disableElementBySoId("saintMainRegenerateCountersLink")},OnBatchEvent:function(obj){if(g_debug.trace("OnBatchEvent("+obj+")","StatusMonitorRegenerate"),null!=obj.BatchTaskInfos&&0<obj.BatchTaskInfos.length)for(var t=0;t<obj.BatchTaskInfos.length;++t)try{var name=obj.BatchTaskInfos[t].Name;"StatusMonitorRegenerateBatchPlugin"!=name&&"SaintRegenBatchPlugin"!=name||4!=obj.BatchTaskInfos[t].State&&"Succeeded"!=obj.BatchTaskInfos[t].State&&5!=obj.BatchTaskInfos[t].State&&"Failed"!=obj.BatchTaskInfos[t].State||(SuperOffice.SoHelper.enableElementBySoId("saintMainRegenerateLink"),SuperOffice.SoHelper.enableElementBySoId("saintMainRegenerateCountersLink"),null==SuperOffice.SoHelper.getElementBySoId("AdminSaintCompany_RegenerateLink")&&null==SuperOffice.SoHelper.getElementBySoId("AdminSaintProject_RegenerateLink"))||QueuedPageUpdate("soprotocol:?statusmonitor_id="+g_clientOptions.LastValidHistoryItem,"")}catch(e){Dialog.Information("SuperOffice","An exeption ocurred: "+e)}}};return pub}(),SuperOffice.Admin.System=(()=>{var pub={setDeletedNumbersListItemCallback:function(context){1==context._status&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSystemNumberAllocationDataHandler.DeleteRefCount","",context._context),g_archiveadminusersNumbersArchive.RefreshList())},setDeletedNumbersListItem:function(row,value){Dialog.YesNo("SuperOffice","[SR_ADMIN_REMOVE_NUMBERING]","question","","SuperOffice.Admin.System.setDeletedNumbersListItemCallback",row.id)},setDeletedEventsListItemCallback:function(context){1==context._status&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSystemEventDataHandler.deleteSystemEvent","",context._context),g_archiveadmineventsArchive.Refresh())},addSystemEvent:function(){Dialog.open("admineditsystemevent","admineditsystemevent[dialog=stop]?adminsystemevent_id=0",'QueuedPageUpdate("soprotocol:adminlicense.main[refresh=true]?adminsystemevent=g_clientOptions.LastValidHistoryItem");')},setDeletedEventsListItem:function(row,value){Dialog.YesNo("SuperOffice","[SR_ADMIN_DELETE_SYSTEMEVENT]","question","","SuperOffice.Admin.System.setDeletedEventsListItemCallback",row.id)},EnableDisableNumberAllocTextFields:function(nextNumber,travel,satellite,allocCheckbox){"checked"==$("[soid='"+allocCheckbox+"']").attr("checked")?(SuperOffice.SoHelper.enableElementBySoId(nextNumber),SuperOffice.SoHelper.enableElementBySoId(travel),SuperOffice.SoHelper.enableElementBySoId(satellite)):(SuperOffice.SoHelper.disableElementBySoId(nextNumber),SuperOffice.SoHelper.disableElementBySoId(travel),SuperOffice.SoHelper.disableElementBySoId(satellite))},SaveNumberEachTemplate:function(elementName,buttonName){elementName=SuperOffice.SoHelper.getElementBySoId(elementName).checked;elementName?SuperOffice.SoHelper.enableElementBySoId(buttonName):SuperOffice.SoHelper.disableElementBySoId(buttonName),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSystemNumberAllocationDataHandler.SetNumberEachTemplate","",elementName)},openPreferredTimeZoneDialog:function(){Dialog.open("adminsystemeditpreferredtimezone","adminsystemeditpreferredtimezone[dialog=stop]?",'QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].timezones[refresh=true]");')},openBaseTimeZoneDialog:function(){Dialog.open("adminsystemeditbasetimezone","adminsystemeditbasetimezone[dialog=stop]?",'QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].timezones[refresh=true]");')},enableTimeZones:function(tz){Dialog.open("adminsystemedittimezone","adminsystemedittimezone[dialog=stop]?","SuperOffice.Admin.System.fetchTimeZones();")},openEnableTimezoneDialog:function(){SuperOffice.Admin.Fields.hideStuff(),setTimeout('AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminTimeZoneDataHandler.RetrieveTimeZoneData", "");SuperOffice.Admin.System.openEnableTimezoneDialog2();',1e3)},openEnableTimezoneDialog2:function(){Dialog.open("adminsystemedittimezone","adminsystemedittimezone[dialog=stop]?",'QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].timezones[refresh=true]");')},regenFreeTextIndex:function(){SendWorkerCommand("AlarmWorker","CreateTempTask","[SR_BATCH_FREETEXTREGENBATCHPLUGIN_NAME]"),SuperOffice.SoHelper.disableElementBySoId("adminFreetextRegenButt"),AjaxMethodDispatcher.CallASync("","","","","SuperOffice.CRM.Web.Data.AdminSystemFreetextSearchDataHandler.GenereateFreeTextIndex"),setTimeout(()=>SuperOffice.SoHelper.enableElementBySoId("adminFreetextRegenButt"),1e4)},fetchTimeZones:function(){SuperOffice.Admin.Fields.hideStuff(),setTimeout('AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminTimeZoneDataHandler.RetrieveTimeZoneData", "");QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].timezones[refresh=true]");',1e3)},updateGuiIfAvailableTimeZones:function(availablegroup,unavailablegroup){var timeZonesAvailable=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminTimeZoneDataHandler.CheckNewTimeZoneDataAvailable","");return AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminTimeZoneDataHandler.IsTimeZonesEnabled","")?timeZonesAvailable?(SuperOffice.SoHelper.hideElementBySoId(unavailablegroup),SuperOffice.SoHelper.showElementBySoId(availablegroup)):(SuperOffice.SoHelper.hideElementBySoId(availablegroup),SuperOffice.SoHelper.showElementBySoId(unavailablegroup)):(SuperOffice.SoHelper.hideElementBySoId(unavailablegroup),SuperOffice.SoHelper.hideElementBySoId(availablegroup)),timeZonesAvailable},timeZoneDataFromFileCallback:function(filename){filename=decodeURIComponent((filename+"").replace(/\+/g,"%20")),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminTimeZoneDataHandler.UploadTimeZoneDataFile","",filename),QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].timezones[refresh=true]")},timezonesFilterSearch:function(){var value=so("adminSystemTimeZonesSearchBox_textfield").value;AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.SetCurrent","","admintimezonesfilter",0,value,"source"),QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].timezones[refresh=true]")},searchBoxSourceKeyPressed:function(event){13==event.keyCode&&SuperOffice.Admin.System.timezonesFilterSearch()},toggleActiveTimeZoneRow:function(primaryKey){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminTimeZoneDataHandler.ToggleActiveTimeZoneRow","",parseInt(primaryKey,10))},deleteTimezones:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSystemEditTimezoneDataHandler.DeleteTimezones",""),Dialog.closeWithCallback()},setActiveTimeZonesByFilter:function(archive,active){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminTimeZoneDataHandler.SetActiveTimeZonesByFilter","",active),archive.RefreshList()},OnBatchEvent:function(obj){g_debug.trace("OnBatchEvent("+obj+")","FreetextRegenBatchPlugin")}};return pub})(),SuperOffice.Admin.Protocol=(()=>{var pub={tryExecuteHandler:function(protocol){var elemId="soTestProtocolElement",win=document.getElementById(elemId),elemId=(null==win&&((win=document.createElement("iframe")).setAttribute("id",elemId),win.setAttribute("style","height:0px;width:0px;visibility:hidden"),win=document.body.appendChild(win)),document.createElement("a")),elemId=(elemId.setAttribute("href",protocol),elemId.protocolLong);if(alert(elemId),"Unknown Protocol"!=elemId)try{win.contentWindow.location=protocol}catch(e){alert(e)}}};return pub})(),SuperOffice.Admin.Import=(()=>{var pub={},lastBatchJob=0;return new Array,pub.uploadExcelFile=function(filename){filename=decodeURIComponent((filename+"").replace(/\+/g,"%20")),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminImportFileUploadDataHandler.UploadFile","",filename)},pub.clearImportData=function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminImportDataHandler.ClearImportData","")},pub.checkGoogleDialog=function(){1==JsHelper.GetCookie("importDone")?PageUpdate("soprotocol:adminimportwizard.importfile[mode=edit]?stage=1&adminimportselectedsource_id=3",""):2!=JsHelper.GetCookie("importDone")&&setTimeout(pub.checkGoogleDialog,400)},pub.openGoogleDialog=function(){JsHelper.SetCookie("importDone",0,1),Dialog.openExt("adminimportgoogle","adminimportgoogle[dialog=stop]",""),setTimeout(pub.checkGoogleDialog,400)},pub.openErpDialog=function(){JsHelper.SetCookie("importDone",0,1),Dialog.open("adminimportselecterp","adminimporterp[dialog=stop&usersuperstatecopy=true]","SuperOffice.Admin.Import.OpenErpCallback();")},pub.OpenImportSettingsDialog=function(){var currentImportEntity=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","AdminImportEntityType");null!=currentImportEntity&&4==currentImportEntity.Id?Dialog.open("adminimportrules","adminimportproductrules[dialog=stop]","PageUpdate('soprotocol:importfile[refresh=true]', '')"):Dialog.open("adminimportrules","adminimportrules[dialog=stop]","PageUpdate('soprotocol:importfile[refresh=true]', '')")},pub.gotoErpStep=function(step){PageUpdate("soprotocol:adminimportwizard.importfile[mode=edit]?stage="+step+"&adminimportselectedsource_id=4","")},pub.OpenErpCallback=function(){var connection=Dialog.getReturnValue();Dialog.open("adminimporterpfind","adminimporterpfind[dialog=stop].findcontact?criterionentity_id=0&criterionentity_name=findcontact&findtype_id=1&findtype_type=single&connectionid="+connection.connection+"&erpactortype="+connection.actorType,'SuperOffice.Admin.Import.gotoErpStep("1")')},pub.startImport=function(){var elems=$('[soid="AdminImportWizardCard"]');1==elems.length&&elems.append("<div id='pleasewaitdimmer' class='pleasewaitdimmer whiteCurtain'> </div>"),PageUpdate("soprotocol:adminimportwizard[refresh=true].importdone[mode=save]?stage=last","")},pub.previewImport=function(){var elems=$('[soid="adminImportGridControlGroup"]'),elems=(1==elems.length&&elems.append("<div id='pleasewaitdimmer' class='pleasewaitdimmer whiteCurtain'> </div>"),$('[soid="adminImportComment_textfield"]'));1==elems.length&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserPreferences.SetAndSave","","GDPR","ImportConsentComment",elems[0].value),AjaxMethodDispatcher.CallASync("SuperOffice.Admin.Import.previewImportBeforeCallback","","","","SuperOffice.CRM.Web.AjaxMethods.Import.GetPreviewData")},pub.previewImportAll=function(){var elems=$('[soid="adminImportGridControlGroup"]'),elems=(1==elems.length&&elems.append("<div id='pleasewaitdimmer' class='pleasewaitdimmer whiteCurtain'> </div>"),$('[soid="adminImportComment_textfield"]'));1==elems.length&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserPreferences.SetAndSave","","GDPR","ImportConsentComment",elems[0].value),AjaxMethodDispatcher.CallASync("SuperOffice.Admin.Import.previewImportAllBeforeCallback","","","","SuperOffice.CRM.Web.AjaxMethods.Import.GetPreviewDataAll")},pub.previewImportAllBeforeCallback=function(){PageUpdate("soprotocol:importpreview[refresh=true]?stage=2","")},pub.previewImportBeforeCallback=function(){PageUpdate("soprotocol:importpreview?stage=2","")},pub.navigateToImportSelection=function(selectionId){0<selectionId&&(location.href="../default.aspx?selection.main?selection_id="+selectionId)},pub.selectOutlook=function(){SendWorkerCommand("WebToolsWorker","ImportFromOutlook")},pub.selectMac=function(){SendWorkerCommand("WebToolsWorker","ImportFromMacLink")},pub.googleImportRedirect=function(){var callBackUrl=window.location.href+"&backFromGoogle=true",callBackUrl=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminImportGoogleDataHandler.ImportFromGoogle","",callBackUrl,"");window.location=callBackUrl},pub.googleImportBack=function(code){""!=code?(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminImportGoogleDataHandler.ImportFromGoogle","","",code),JsHelper.SetCookie("importDone",1,1)):JsHelper.SetCookie("importDone",2,1),window.open("","_self",""),window.close()},pub.setSelectedColumn=function(index,value){index=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminImportDataHandler.SetSelectedColumns","",index,value);this.setRequiredColumnsUI(index)},pub.setRequiredColumnsUI=function(missingRequiredColumns){$.fromSoId("requiredColumns").html(missingRequiredColumns.Message),""!=missingRequiredColumns.Message?($.fromSoId("columnLabel").html(missingRequiredColumns.Label),$.fromSoId("columnLabel").show(),SuperOffice.SoHelper.disableElementBySoId("adminImportFileViewNextButton"),SuperOffice.SoHelper.disableElementBySoId("adminImportPreviewViewNextButton")):($.fromSoId("columnLabel").hide(),SuperOffice.SoHelper.enableElementBySoId("adminImportFileViewNextButton"),SuperOffice.SoHelper.enableElementBySoId("adminImportPreviewViewNextButton"))},pub.toggleImportRow=function(index){index=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminImportDataHandler.ToggleImportRow","",index);this.enableImportButton(index)},pub.toggleImportRows=function(checkstate){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminImportDataHandler.ToggleImportRows","",checkstate),this.enableImportButton(checkstate)},pub.enableImportButton=function(enable){enable?SuperOffice.SoHelper.enableElementBySoId("adminImportPreviewViewNextButton"):SuperOffice.SoHelper.disableElementBySoId("adminImportPreviewViewNextButton")},pub.OnBatchEvent=function(obj){if(g_debug.trace("OnBatchEvent("+obj+")","ImportFromOutlook"),null!=obj.BatchTaskInfos&&0<obj.BatchTaskInfos.length)for(var filename,t=0;t<obj.BatchTaskInfos.length;++t)try{"ImportBatchPlugin"!=obj.BatchTaskInfos[t].Name||4!=obj.BatchTaskInfos[t].State&&"Succeeded"!=obj.BatchTaskInfos[t].State&&5!=obj.BatchTaskInfos[t].State&&"Failed"!=obj.BatchTaskInfos[t].State||obj.BatchTaskInfos[t].Id==lastBatchJob||(filename=obj.BatchTaskInfos[t].Filename,lastBatchJob=obj.BatchTaskInfos[t].Id,AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminImportFileUploadDataHandler.UploadSerializedFile","",filename),PageUpdate("soprotocol:adminimportwizard.importfile[mode=edit]?stage=1&adminimportselectedsource_id=2",""))}catch(e){Dialog.Information("SuperOffice","An exception ocurred: "+e)}},pub.updateColumnArray=function(headerid){var output=new Array;$("#"+headerid).find(".SoDropDownControl").each(function(){null!=$(this).data("selecteditem")&&output.push($(this).data("selecteditem").Type)})},pub.SetSourceFileLabel=function(labelId){var elem=$.fromSoId("AdminImportWizardCard_header_container").find("ul li:first"),labelId=$.fromSoId("adminImport"+labelId+"IconControlGroup");labelId.css({paddingLeft:"35px"}),elem.append(labelId)},pub.SetCountLabel=function(){var elemCountHost=$.fromSoId("AdminImportWizardCard_header_container").find("ul li:first").next(),elemCount=$.fromSoId("adminImportPreviewCountControlGroup");elemCount.css({paddingLeft:"35px"}),elemCountHost.append(elemCount)},pub})(),SuperOffice.Admin.Fields=(()=>{var pub={entityTypeNumber:"0",entityTypeName:"",savePositions:function(fieldArray){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserDefinedFields.SetPosition","",this.entityTypeName,fieldArray),PageUpdate("soprotocol:?AdminAllowPageOnePerGroup_id=1","")},selectUdefFields:function(type){SuperOffice.Controls.Udef("admin"+this.entityTypeName+"udef").select(type)},openNewFieldDialog:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminUserDefinedField",0,"",""),Dialog.open("adminfieldseditfield","adminfieldseditfield[dialog=stop]?adminuserdefinedfieldentitytype_id="+this.entityTypeNumber+"&adminuserdefinedfieldentitytype_name="+this.entityTypeName,"QueuedPageUpdate('soprotocol:adminfields[noupdate=true&nocache=true].udef_"+this.entityTypeName+"[refresh=true]');")},openEditFieldDialog:function(rowid){var soprotocol;1==AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminUdefDataHandler.SelectedUdefHasAdminVersion","")&&(soprotocol="adminfieldseditfield[dialog=stop]?adminuserdefinedfieldentitytype_id="+this.entityTypeNumber+"&adminuserdefinedfieldentitytype_name="+this.entityTypeName,void 0!==rowid&&(soprotocol+="&AdminUserDefinedField_id="+rowid),Dialog.open("adminfieldseditfield",soprotocol,"QueuedPageUpdate('soprotocol:adminfields[noupdate=true&nocache=true].udef_"+this.entityTypeName+"[refresh=true]');"))},setPageOneGroup:function(groupId){PageUpdate("soprotocol:?AdminPageOneGroup_id="+groupId,"")},setGrouping:function(isSet){SuperOffice.SoHelper.disableElementsBySoId(this.pageoneCheckboxid),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserDefinedFields.SetUdefGrouping","",this.entityTypeName+"",isSet),PageUpdate("soprotocol:?AdminPageOneGroup_id=0&AdminAllowPageOnePerGroup_id="+(isSet?"1":"0"),"")},setFieldType:function(type){QueuedPageUpdate("soprotocol:adminfieldseditfield[dialog=stop].main[mode=edit]","")},changeIndex:function(){QueuedPageUpdate("soprotocol:adminfieldseditfield[dialog=stop].main[mode=edit]","")},changeIsMandatory:function(){var mandatoryCheckBox=so("MandatoryCheckbox"),readOnlyCheckBox=so("ReadOnlyCheckbox");mandatoryCheckBox.checked&&(readOnlyCheckBox.checked=!1),readOnlyCheckBox.disabled=mandatoryCheckBox.checked},changeIsReadOnly:function(){var mandatoryCheckBox=so("MandatoryCheckbox"),readOnlyCheckBox=so("ReadOnlyCheckbox");readOnlyCheckBox.checked&&(mandatoryCheckBox.checked=!1),mandatoryCheckBox.disabled=readOnlyCheckBox.checked},publish:function(){pub.hideStuff(function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserDefinedFields.CheckIfPublishNeedsBackupWarning","",pub.entityTypeName)?Dialog.YesNo("","[SR_UDEF_PUBLISHWARNING]","question","","SuperOffice.Admin.Fields.publishCallback",""):(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserDefinedFields.Publish","",pub.entityTypeName),pub.publishFinishedCallback())})},hideStuff:function(callback){$(so("whiteCurtain")).fadeTo(0,0,function(){$(so("whiteCurtain")).css({zIndex:999}).fadeTo(500,.75,callback)})},showStuff:function(){$(so("whiteCurtain")).fadeTo(0,.75).css({zIndex:999}).fadeTo(500,0,function(){$(so("whiteCurtain")).css({zIndex:-999})})},hideIfPublishing:function(){""!=pub.entityTypeName&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserDefinedFields.IsPublishEventActive","",pub.entityTypeName)&&$(so("whiteCurtain")).fadeTo(0,.75).css({zIndex:999})},publishCallback:function(res){1==res.getStatus()?(pub.hideIfPublishing(),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserDefinedFields.Publish","",pub.entityTypeName),SendWorkerCommand("AlarmWorker","CreateTempTask","SR_FIELDS_PUBLISH_STARTED")):pub.showStuff()},revert:function(){Dialog.YesNo("","[SR_UDEF_REVERT_TOOLTIP]","question","","SuperOffice.Admin.Fields.revertCallback","")},revertCallback:function(res){1==res.getStatus()&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserDefinedFields.Revert","",pub.entityTypeName),QueuedPageUpdate("soprotocol:adminfields[noupdate=true&nocache=true].udef_"+pub.entityTypeName+"[refresh=true]"))},setPageOneField:function(id,pageNo){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserDefinedFields.SetPageOneField","",pub.entityTypeName,Number(id),pageNo),PageUpdate("soprotocol:?AdminAllowPageOnePerGroup_id="+g_clientOptions.LastValidHistoryItem,"")},deleteSelectedField:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminUdefDataHandler.DeleteSelectedField",""),QueuedPageUpdate("soprotocol:adminfields[noupdate=true&nocache=true].udef_"+pub.entityTypeName+"[refresh=true]")},OnBatchEvent:function(obj){if(g_debug.trace("OnBatchEvent("+obj+")","PublishUserDefinedFields"),null!=obj.BatchTaskInfos&&0<obj.BatchTaskInfos.length)for(var t=0;t<obj.BatchTaskInfos.length;++t)try{"UdefPublishBatchPlugin"==obj.BatchTaskInfos[t].Name&&(4!=obj.BatchTaskInfos[t].State&&"Succeeded"!=obj.BatchTaskInfos[t].State||AjaxMethodDispatcher.CallASync("SuperOffice.Admin.Fields.publishFinishedCallback","","","","SuperOffice.CRM.Web.AjaxMethods.UserDefinedFields.ClearCachesAfterPublish"),5!=obj.BatchTaskInfos[t].State&&"Failed"!=obj.BatchTaskInfos[t].State||(alert("Publish failed: "+obj.BatchTaskInfos[t].Response),SuperOffice.Admin.Fields.publishFinishedCallback()),3!=obj.BatchTaskInfos[t].State&&"Started"!=obj.BatchTaskInfos[t].State||pub.hideIfPublishing())}catch(e){Dialog.Information("SuperOffice","An exeption ocurred: "+e)}},publishFinishedCallback:function(){pub.showStuff(),QueuedPageUpdate("soprotocol:adminfields[noupdate=true].udef_"+pub.entityTypeName+"[refresh=true]")},rankFields:function(){for(var listBox=SuperOffice.SoCheckedListBox(SuperOffice.Admin.Fields.listBoxSoId),fields=listBox.getSimpleMdoItems(),stringArray="",i=0;i<fields.length;i++)0<i&&(stringArray+=","),stringArray+=fields[i].Id;var selectedId=listBox.getIdsFromHighlightedRows();AjaxMethodDispatcher.CallASync(function(){QueuedPageUpdate("soprotocol:adminfields[noupdate=true].udef_"+pub.entityTypeName+"[refresh=true]",function(){SuperOffice.SoCheckedListBox(SuperOffice.Admin.Fields.listBoxSoId).onclick(selectedId[0])})},"","","","SuperOffice.CRM.Web.AjaxMethods.UserDefinedFields.SetRankOnFields",pub.entityTypeName,stringArray)}};return pub})(),SuperOffice.Admin.License=(()=>{var pub={reassignToId:0,setReassignToId:function(id){this.reassignToId=id},selectAll:function(archive){archive.selectAll()},markSelectedUsersForDeletion:function(archive){for(var rows=archive.getSelectedRows(),ids="",i=0;i<rows.length;i++)0<i&&(ids+=","),ids+=GetPrimaryKeyFromRow(rows[i]);archive.removeSelectedRows();archive=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRemoveExcessUserLicensesDataHandler.MarkSelectedUsersForDeletion","",ids);archive&&alert(archive),QueuedPageUpdate("soprotocol:adminremoveexcessuserlicenses[dialog=stop].main[refresh=false]?adminexcessmath_id="+g_clientOptions.LastValidHistoryItem)},markSelectedUsersForReassign:function(archive){for(var rows=archive.getSelectedRows(),ids=("AdminRemoveExcessUserLicensesDataHandler.ReassignTo.Id"==GetMDOInstanceFromSoId("adminusersUsersArchive_ArchiveToolbar_1_3").getSelectedValue()&&(this.reassignToId=0),""),i=0;i<rows.length;i++)0<i&&(ids+=","),ids+=GetPrimaryKeyFromRow(rows[i]);archive.removeSelectedRows();archive=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRemoveExcessUserLicensesDataHandler.MarkSelectedUsersForReassign","",this.reassignToId+","+ids);archive&&alert(archive),QueuedPageUpdate("soprotocol:adminremoveexcessuserlicenses[dialog=stop].main[refresh=true]?adminexcessmath_id="+g_clientOptions.LastValidHistoryItem)},excessUserSave:function(archive){archive.ShowProgressImage(),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRemoveExcessUserLicensesDataHandler.Save",""),archive.HideProgressImage(),Dialog.closeWithCallback()},excessUserCancel:function(archive){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRemoveExcessUserLicensesDataHandler.Cancel",""),Dialog.closeWithCallback()},activate:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminActivateNewLicenseDataHandler.Activate",""),Dialog.closeWithCallback()},markSelectedSitesForDeletion:function(checkedListBox){for(var listBoxIds=checkedListBox.getIdsFromHighlightedRows(),ids="",i=0;i<listBoxIds.length;i++)0<i&&(ids+=","),ids+=listBoxIds[i];checkedListBox.deleteHighlightedRows(),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRemoveExcessSiteLicensesDataHandler.MarkSelectedSitesForDeletion","",ids),QueuedPageUpdate("soprotocol:adminremoveexcesssitelicenses[dialog=stop].main[refresh=false]?adminexcessmath_id="+g_clientOptions.LastValidHistoryItem)},excessSiteSave:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRemoveExcessSiteLicensesDataHandler.Save",""),Dialog.closeWithCallback()},uploadLicenseFile:function(fileName,ownerName){fileName=decodeURIComponent((fileName+"").replace(/\+/g,"%20")),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminActivateNewLicenseDataHandler.UploadFile","",fileName,ownerName),QueuedPageUpdate("soprotocol:adminlicense[noupdate=true].company_"+ownerName+"[refresh=true]","")},openBuyMore:function(ownerId){var url="";null!=(url="SUPEROFFICE"===ownerId?getNs("SuperOffice.Util.UrlDispatcher").GetUrlWithSchemeTranslation("BuyMoreUrl"):url)&&""!==url||(url=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminLicenseDataHandler.GetShopUrl","",ownerId)),window.open(url,"SuperMarket","status=1,scrollbars=1, width=812, height=780")}};return pub})(),SuperOffice.Admin.SystemLabels=(()=>{var pub={searchBoxSourceKeyPressed:function(event){13==event.keyCode&&pub.searchBoxSourceSearch()},searchBoxSourceSetIcon:function(search){search?(so("AdminSystemLabelsSourceSearchBoxIcon").style.display="inline-block",so("AdminSystemLabelsSourceSearchBoxIcon").style.visibility="visible",so("AdminSystemLabelsSourceClearBoxIcon").style.display="none",so("AdminSystemLabelsSourceClearBoxIcon").style.visibility="hidden"):(so("AdminSystemLabelsSourceSearchBoxIcon").style.display="none",so("AdminSystemLabelsSourceSearchBoxIcon").style.visibility="hidden",so("AdminSystemLabelsSourceClearBoxIcon").style.display="inline-block",so("AdminSystemLabelsSourceClearBoxIcon").style.visibility="visible")},searchBoxSourceSearch:function(){var value;"InitText"!=so("AdminSystemLabelsSourceSearchBox_textfield").className&&(value=so("AdminSystemLabelsSourceSearchBox_textfield").value,pub.searchBoxSourceSetIcon(0==value.length),QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].labels?adminlabelssearchBox_id=0&adminlabelssearchBox_name="+value+"&adminlabelssearchBox_type=source"))},searchBoxSourceClear:function(){so("AdminSystemLabelsSourceSearchBox_textfield").value="",pub.searchBoxSourceSetIcon(!0),QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].labels?adminlabelssearchBox_id=0&adminlabelssearchBox_name="+so("AdminSystemLabelsSourceSearchBox_textfield").value+"&adminlabelssearchBox_type=source")},searchBoxSourceKeyDown:function(){so("AdminSystemLabelsTargetSearchBox_textfield").value="",pub.searchBoxSourceSetIcon(!0),pub.searchBoxTargetSetIcon(!0)},searchBoxTargetKeyPressed:function(event){13==event.keyCode&&pub.searchBoxTargetSearch()},searchBoxTargetSetIcon:function(search){search?(so("AdminSystemLabelsTargetSearchBoxIcon").style.display="inline-block",so("AdminSystemLabelsTargetSearchBoxIcon").style.visibility="visible",so("AdminSystemLabelsTargetClearBoxIcon").style.display="none",so("AdminSystemLabelsTargetClearBoxIcon").style.visibility="hidden"):(so("AdminSystemLabelsTargetSearchBoxIcon").style.display="none",so("AdminSystemLabelsTargetSearchBoxIcon").style.visibility="hidden",so("AdminSystemLabelsTargetClearBoxIcon").style.display="inline-block",so("AdminSystemLabelsTargetClearBoxIcon").style.visibility="visible")},searchBoxTargetSearch:function(){var value;"InitText"!=so("AdminSystemLabelsTargetSearchBox_textfield").className&&(value=so("AdminSystemLabelsTargetSearchBox_textfield").value,pub.searchBoxTargetSetIcon(0==value.length),QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].labels?adminlabelssearchBox_id=0&adminlabelssearchBox_name="+value+"&adminlabelssearchBox_type=target"))},searchBoxTargetClear:function(){so("AdminSystemLabelsTargetSearchBox_textfield").value="",pub.searchBoxTargetSetIcon(!0),QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].labels?adminlabelssearchBox_id=0&adminlabelssearchBox_name="+so("AdminSystemLabelsTargetSearchBox_textfield").value+"&adminlabelssearchBox_type=target")},searchBoxTargetKeyDown:function(){so("AdminSystemLabelsSourceSearchBox_textfield").value="",pub.searchBoxTargetSetIcon(!0),pub.searchBoxSourceSetIcon(!0)},clearSearchBox:function(){QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].labels?adminlabelssearchBox_id=0&adminlabelssearchBox_name=&adminlabelssearchBox_type=")},openEditLabelDialog:function(resourceName){Dialog.open("adminsystemeditlabel","adminsystemeditlabel[dialog=stop]?adminlabel_id=123&adminlabel_type="+resourceName,"QueuedPageUpdate('soprotocol:adminsystem[noupdate=true].labels[refresh=true]');")},deleteSelectedLabels:function(ids){for(var stringArray="",i=0;i<ids.length;i++)0<i&&(stringArray+=","),stringArray+=ids[i];AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSystemLabelsDataHandler.DeleteSelectedLabels","",stringArray),QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].labels[refresh=true]")},showAllTranslatedLabels:function(){QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].labels[refresh=true]?adminlabelssearchbox_id=1&adminlabelssearchbox_type=all")},selectAllLabels:function(listBox){listBox.highlightAll()},saveEnableLabelSubstitution:function(enableLabelSubstitution){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminSystemLabelsDataHandler.SaveEnableLabelSubstitution","",enableLabelSubstitution),QueuedPageUpdate("soprotocol:adminsystem[noupdate=true].labels[refresh=true]")}};return pub})(),SuperOffice.Admin.Privacy=(()=>{var pub={OpenAddConsentPurposeDialog:function(id,archiveControl){var isEdit=0<(id=parseInt(id,10));$sodlgm.open(null,{id:"AddConsentPurpose",recipeName:"AddConsentPurposeDialog",caption:isEdit?"[SR_ADMIN_CONSENT_PURPOSE_EDIT]":"[SR_ADMIN_CONSENT_PURPOSE_ADD]",windowSetting:{width:"700px",height:"570px"}},function(ctx){isEdit&&(ctx.set("purposeId",id),console.log(ctx))},function(){archiveControl.RefreshList()},"editconsentpurpose")},DeleteConsentPurposes:function(consentPurposeRows,archiveControl){consentPurposeRows=consentPurposeRows.map(function(r){return parseInt(r.id)});AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminPrivacyDataHandler.RemoveConsentPurposes","",consentPurposeRows),archiveControl.RefreshList()},RestoreConsentPurposes:function(consentPurposeRows,archiveControl){consentPurposeRows=consentPurposeRows.map(function(r){return parseInt(r.id)});AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminPrivacyDataHandler.RestoreConsentPurposes","",consentPurposeRows),archiveControl.RefreshList()},ToggleActive:function(selectedRows,archiveControl){selectedRows=selectedRows.map(function(r){return parseInt(r.id)});AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminPrivacyDataHandler.ToggleActive","",selectedRows),archiveControl.RefreshList()},sort:function(archiveControl){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminPrivacyDataHandler.SortList",""),archiveControl.RefreshList()},moveUp:function(archiveControl){var id=archiveControl.getSelectedRows().map(function(r){return parseInt(r.id)})[0];id<=0||(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminPrivacyDataHandler.MoveListItem","",id,-1),archiveControl.RefreshList())},moveDown:function(archiveControl){var id=archiveControl.getSelectedRows().map(function(r){return parseInt(r.id)})[0];id<=0||(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminPrivacyDataHandler.MoveListItem","",id,1),archiveControl.RefreshList())},setRestoreButtonState:function(id,archiveControl){for(var rows=archiveControl.getSelectedRows(),i=0;i<rows.length;i++){for(var canDelete=!1,rights=rows[i].attributes.rowrights.value.split(","),ii=0;ii<rights.length;ii++)if("D"==rights[ii]){canDelete=!0;break}if(!canDelete)break}canDelete?SuperOffice.SoHelper.disableElementBySoId(id):SuperOffice.SoHelper.enableElementBySoId(id)}};return pub})(),SuperOffice.Admin.ErpSync=(()=>{var pub={addConnector:function(callback){Dialog.open("adminediterpsyncconnector","adminediterpsyncconnector[dialog=stop]",callback)},addConnection:function(callback){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.IsErpSyncEngineOn","")?Dialog.Information("[SR_ADMIN_EIS]","[SR_EIS_ON]","error"):(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminErpConnection",0,"",""),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminErpSelectedConnector",0,"",""),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditErpConnectionDataHandler.ClearCachedErpConnection",""),Dialog.open("AdminEditErpConnection","adminediterpconnection[dialog=stop]?newItem=1",callback+"SuperOffice.PageBuilder.refreshCurrent('adminerpconnection');"))},adminEditErpConnection:function(erpConnectionId,isActive,callback){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.IsErpSyncEngineOn","")?Dialog.Information("[SR_ADMIN_EIS]","[SR_EIS_ON]","error"):(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditErpConnectionDataHandler.ClearCachedErpConnection",""),Dialog.open("AdminEditErpConnection","adminediterpconnection[dialog=stop]?connectionId="+erpConnectionId+"&adminerpconnection_id="+erpConnectionId,callback+" SuperOffice.PageBuilder.refreshCurrent('adminerpconnection');"))},SelectFirstRow:function(id,instance){0<instance.count()&&instance.setFirstRowSelected()},SaveConnectionRanks:function(){for(var fields=SuperOffice.SoCheckedListBox("adminErpConnections").getSimpleMdoItems(),stringArray="",i=0;i<fields.length;i++)0<i&&(stringArray+=","),stringArray+=fields[i].Id;AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRankErpConnectionDataHandler.SaveRanks","",stringArray)},editConnector:function(id,callback){Dialog.open("adminediterpsyncconnector","adminediterpsyncconnector[dialog=stop]?connector_id="+id,callback)},removeConnector:function(id,callback){id=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.CheckCanDeleteCurrentConnector","",parseInt(id,10));0==id?Dialog.YesNo("","[SR_ADMIN_EIS_CONFIRM_DELETE_CONNECTOR]","question","","SuperOffice.Admin.ErpSync.deleteCurrentConnectorCallback",""):1==id?Dialog.Information("[SR_ADMIN_EIS_DELETE_CONNECTOR]","[SR_ADMIN_EIS_CONNECTOR_HAS_CONNECTIONS]","error"):2==id?Dialog.Information("[SR_ADMIN_EIS_DELETE_CONNECTOR]","[SR_ADMIN_EIS_CONNECTOR_NOT_FOUND]","error"):Dialog.Information("[SR_ADMIN_EIS_DELETE_CONNECTOR]","[SR_ADMIN_EIS_CONNECTOR_DELETE_ERROR]","error")},hideOrShowScope:function(allAccess){"True"==allAccess?SuperOffice.SoHelper.hideElementBySoId("AdminEditQuoteConnectionScopeSpecificLink"):SuperOffice.SoHelper.showElementBySoId("AdminEditQuoteConnectionScopeSpecificLink")},setScope:function(specific){QueuedPageUpdate("soprotocol:adminediterpconnection[dialog=stop].main[refresh=true]&specificScope="+specific,"")},addDefaultValue:function(erpActorType){Dialog.open("AdminEditErpSyncDefaultValue","adminediterpsyncdefaultvalue[dialog=stop]&erpActorType="+erpActorType+"&newItem=true","SuperOffice.PageBuilder.refresh();")},editDefaultValue:function(id,archiveId){archiveId=archiveId.split("_"),archiveId=(archiveId=archiveId[archiveId.length-1]).substring(0,archiveId.indexOf("Archive"));Dialog.open("AdminEditErpSyncDefaultValue","adminediterpsyncdefaultvalue[dialog=stop]?adminerpfield_id="+id+"&erpActorType="+archiveId+"&newItem=false","SuperOffice.PageBuilder.refresh();")},removeDefaultValues:function(ids){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDefaultsDataHandler.RemoveDefaultValues","",ids.toString()),SuperOffice.PageBuilder.refresh()},editConnectionScope:function(){Dialog.open("AdminEditErpConnectionScope","adminediterpconnectionscope[dialog=stop]","QueuedPageUpdate('soprotocol:adminediterpconnection[dialog=stop].main[refresh=true]&specificScope=true', '');")},showAssociates:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminErpScopeAssociateOrUserGroup",0,"associates",""),QueuedPageUpdate("soprotocol:adminediterpconnectionscope[dialog=stop].main[refresh=true]")},showUserGroups:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminErpScopeAssociateOrUserGroup",0,"usergroups",""),QueuedPageUpdate("soprotocol:adminediterpconnectionscope[dialog=stop].main[refresh=true]")},deleteCurrentConnectorCallback:function(res){1==res.getStatus()&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.DeleteCurrentConnector"),g_archiveadminErpConnectors.RefreshList())},AdminConnectorListDblClick:function(id,callback){pub.editConnector(id,callback)},configureConnector:function(id,callback){pub.editConnector(id,callback)},testConnectorByRow:function(id){Dialog.open("AdminTestErpConnector","admintesterpconnector[dialog=stop]&testConnectorId="+id,"")},testConnector:function(name,url){Dialog.open("AdminTestErpConnector","admintesterpconnector[dialog=stop]&testConnectorUrl="+url+"&testConnectorName="+name,"")},removeConnection:function(){Dialog.YesNo("","[SR_ADMIN_EIS_SURE_DELETE]","question","","SuperOffice.Admin.ErpSync.removeConnectionCallback","")},removeConnectionCallback:function(res){1==res.getStatus()&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.DeleteCurrentConnection"),g_archiveadminErpConnections.RefreshList(),SuperOffice.PageBuilder.refreshCurrent("adminerpconnection"))},setSyncPriority:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.IsErpSyncEngineOn","")?Dialog.Information("[SR_ADMIN_EIS]","[SR_EIS_ON]","error"):Dialog.open("AdminRankErpConnection","adminrankerpconnections[dialog=stop].main","")},configureConnection:function(id,isActive,callback){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.IsErpSyncEngineOn","")?Dialog.Information("[SR_ADMIN_EIS]","[SR_EIS_ON]","error"):Dialog.open("AdminEditErpConnection","adminediterpconnection[dialogwinname=AdminEditErpConnection&dialog=stop]&connectionId="+id,callback)},disableEditConnectionOk:function(soElement){var testDone=$("[soid=AdminEditQuoteConnectionTestDone]").val();"true"!==(testDone=testDone&&testDone.toLowerCase())&&SuperOffice.SoHelper.disableElementBySoId(soElement+"_okButton"),"true"!==testDone&&$("[soid=ActiveCheckBox]")[0].checked?SuperOffice.SoHelper.disableElementBySoId(soElement+"_okButton"):SuperOffice.SoHelper.enableElementBySoId(soElement+"_okButton")},testConnection:function(){PageUpdate("soprotocol:adminediterpconnection[dialog=stop].main[mode=edit&test=true]",function(){Dialog.open("AdminTestErpConnection","admintesterpconnection[dialog=stop]","SuperOffice.Admin.ErpSync.testConnectionCallBack()")})},testConnectionByRow:function(row){var name=SuperOffice.SoHelper.getAnyValueFromLinkHint(row.attributes.rowtype.value,"erpconnection_name");Dialog.open("AdminTestErpConnection","admintesterpconnection[dialog=stop]&testConnectionId="+row.id+"&testConnectionName="+encodeURIComponent(name),"")},testConnectionCallBack:function(){"1"==Dialog.getReturnStatus()?($("[soid=AdminEditQuoteConnectionTestDone]").val("true"),QueuedPageUpdate("soprotocol:adminediterpconnection[dialog=stop].main[mode=edit&testOk=1]","")):($("[soid=AdminEditQuoteConnectionTestDone]").val("false"),QueuedPageUpdate("soprotocol:adminediterpconnection[dialog=stop].main[mode=edit&testOk=0]",""))},openMappingsDialog:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.IsErpSyncEngineOn","")?Dialog.Information("[SR_ADMIN_EIS]","[SR_EIS_ON]","error"):Dialog.open("ErpSyncMapping","adminerpsyncmapping[dialog=stop]?","QueuedPageUpdate('soprotocol:adminquote[noupdate=true].erpsync[refresh=true]');")},openListItemMappingsDialog:function(){var selectedConnection;AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.IsErpSyncEngineOn","")?Dialog.Information("[SR_ADMIN_EIS]","[SR_EIS_ON]","error"):(selectedConnection=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","AdminErpConnection"),$dlgm.open(null,{id:"ErpListItemMappings",recipeName:"ErpListItemMapping",caption:ResourceUtils.GetResourceText("[SR_ERP_LISTMAPPING]")},function(ctx){ctx.controller.init(selectedConnection.Id)}))},openDefaultsDialog:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.IsErpSyncEngineOn","")?Dialog.Information("[SR_ADMIN_EIS]","[SR_EIS_ON]","error"):Dialog.open("AdminErpSyncDefaults","adminerpsyncdefaults[dialog=stop]?","QueuedPageUpdate('soprotocol:adminquote[noupdate=true].erpsync[refresh=true]');")},openFieldRankDialog:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.IsErpSyncEngineOn","")?Dialog.Information("[SR_ADMIN_EIS]","[SR_EIS_ON]","error"):Dialog.open("AdminErpSyncRankFields","adminerpsyncrankfields[dialog=stop]?","QueuedPageUpdate('soprotocol:adminquote[noupdate=true].erpsync[refresh=true]');")},setMandatoryCheckboxes:function(setDefault,promptUser,mandatory,okButton){!$("[soid="+mandatory+"]")[0].checked||$("[soid="+promptUser+"]")[0].checked||$("[soid="+setDefault+"]")[0].checked?SuperOffice.SoHelper.enableElementBySoId(okButton):SuperOffice.SoHelper.disableElementBySoId(okButton)},openImportDialog:function(){QueuedPageUpdate("soprotocol:adminimportwizard.importselectsource","")},updateConnectionFields:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.UpdateConnectionFields"),alert("Connection fields updated")},changeEngineStatus:function(status){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.ChangeErpSyncEngineStatus","",status),QueuedPageUpdate("soprotocol:adminquote[noupdate=true].erpsync[refresh=true]")},changeEngineInterval:function(interval){alert(interval)},ToggleErpConnectionActive:function(id){id=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.ToggleConnectionActive","",parseInt(id,10));""!=id&&Dialog.Information("ERROR",id,"info"),adminErpConnectionsArchiveControl.RefreshList()},MoveErpField:function(id,direction,erpConnectionId,erpActorType){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminRankErpConnectionDataHandler.MoveListItem","",parseInt(id,10),direction,parseInt(erpActorType,10))},ResyncFromCrm:function(){Dialog.YesNo("","[SR_ADMIN_EIS_CONFIRM_FORCE_RESYNC_CRM]","question","","SuperOffice.Admin.ErpSync.StartResyncCallback","-1")},ResyncFromErp:function(id){Dialog.YesNo("","[SR_ADMIN_EIS_CONFIRM_FORCE_RESYNC_ERP]","question","","SuperOffice.Admin.ErpSync.StartResyncCallback",id)},SyncAll:function(id){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.SyncAll","")},ForceSyncAll:function(id){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.ForceSyncAll","")},StartResyncCallback:function(res){1==res.getStatus()&&(res=parseInt(res.getContext(),10),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncDataHandler.ForceResync","",res,null),SendWorkerCommand("AlarmWorker","CreateTempTask"))},searchLog:function(searchWord){(searchWord&&1<searchWord.length||0==searchWord.length)&&adminErpLogArchiveArchiveControl.setArchiveColumnFilter(null,searchWord,"oldvalue","string","contains","")},OnBatchEvent:function(obj){if(g_debug.trace("OnBatchEvent("+obj+")","ErpForceResync"),null!=obj.BatchTaskInfos&&0<obj.BatchTaskInfos.length)for(var t=0;t<obj.BatchTaskInfos.length;++t)try{"ErpForceResyncBatchPlugin"==obj.BatchTaskInfos[t].Name&&5==obj.BatchTaskInfos[t].State&&alert("Erp Force Resync failed: "+obj.BatchTaskInfos[t].Response)}catch(e){Dialog.Information("SuperOffice","An exeption ocurred: "+e)}}};return pub})(),SuperOffice.Admin.Quote=(()=>{var pub={setQuoteConnector:function(id,name){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminQuoteSelectedConnector",id,name,"")},saveSettings:function(fieldname,value){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminConfigureQuoteSettingsDataHandler.SaveSettings","",fieldname,value)&&SuperOffice.PageBuilder.refresh()},OpenSaleTypes:function(id){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","adminlist",id,"",""),QueuedPageUpdate("soprotocol:adminlists.main")},enableLabelSubstitution:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminConfigureQuoteLineDataHandler.EnableLabelSubstitution",""),SuperOffice.PageBuilder.refresh()},addConnection:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminQuoteConnection",0,"",""),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditQuoteConnectionDataHandler.ClearCachedQuoteConnection",""),Dialog.open("AdminEditQuoteConnection","admineditquoteconnection[dialog=stop]","QueuedPageUpdate('soprotocol:adminquote[noupdate=true].connections[refresh=true]');")},editConnection:function(id){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminQuoteConnection",id,"",""),Dialog.open("AdminEditQuoteConnection","admineditquoteconnection[dialog=stop]","adminquoteConnectionsControlArchiveControl.RefreshList();")},removeConnection:function(){Dialog.YesNo("","[SR_ADMIN_QUOTE_CONFIRM_DELETE_CONNECTION]","question","","SuperOffice.Admin.Quote.removeConnectionCallback","")},removeConnectionCallback:function(res){1==res.getStatus()&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditQuoteConnectionDataHandler.RemoveConnection",""),g_archiveadminquoteConnectionsControl.RefreshList())},restoreConnection:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditQuoteConnectionDataHandler.RestoreConnection",""),g_archiveadminquoteConnectionsControl.RefreshList()},testConnection:function(){PageUpdate("soprotocol:admineditquoteconnection[dialog=stop].main[mode=edit]?test=true",""),Dialog.open("AdminTestQuoteConnection","admintestquoteconnection[dialog=stop]","QueuedPageUpdate('soprotocol:admineditquoteconnection[dialog=stop].main[mode=edit]', '');")},testConnectionFromToolbar:function(){Dialog.open("AdminTestQuoteConnection","admintestquoteconnection[dialog=stop]?fromToolbar=true","")},disableEditConnectionOk:function(soElement){},editConnectionScope:function(){Dialog.open("AdminEditQuoteConnectionScope","admineditquoteconnectionscope[dialog=stop]","QueuedPageUpdate('soprotocol:admineditquoteconnection[dialog=stop].main[refresh=true]&specificScope=true', '');")},setScope:function(specific){QueuedPageUpdate("soprotocol:admineditquoteconnection[dialog=stop].main[refresh=true]&specificScope="+specific,"")},hideOrShowScope:function(allAccess){"True"==allAccess?SuperOffice.SoHelper.hideElementBySoId("AdminEditQuoteConnectionScopeSpecificLink"):SuperOffice.SoHelper.showElementBySoId("AdminEditQuoteConnectionScopeSpecificLink")},showAssociates:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminQuoteScopeAssociateOrUserGroup",0,"associates",""),QueuedPageUpdate("soprotocol:admineditquoteconnectionscope[dialog=stop].main[refresh=true]")},showUserGroups:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminQuoteScopeAssociateOrUserGroup",0,"usergroups",""),QueuedPageUpdate("soprotocol:admineditquoteconnectionscope[dialog=stop].main[refresh=true]")},addProduct:function(){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminProduct",0,"",""),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminProductImage",0,"","");var priceListId=so("adminquoteProductsPriceLists_SelectedValue").value;Dialog.open("AdminEditProduct","admineditproduct[dialog=stop]?priceListForProduct="+priceListId,"QueuedPageUpdate('soprotocol:adminquote[noupdate=true].products[refresh=true]?adminpricelist_id="+priceListId+"');")},editProduct:function(id){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminProduct",id,"",""),Dialog.open("AdminEditProduct","admineditproduct[dialog=stop]","QueuedPageUpdate('soprotocol:adminquote[noupdate=true].products[refresh=true]');")},saveProductAndCreateNew:function(){SuperOffice.PageBuilder.save(function(){Dialog.close(),UIHelper.GetOpener().Dialog.open("AdminEditProduct","admineditproduct[dialog=stop]?AdminProduct_id=0&AdminProductImage_id=0",'QueuedPageUpdate("soprotocol:adminquote[noupdate=true].products[refresh=true]", "");'),UIHelper.GetOpener().QueuedPageUpdate("soprotocol:adminquote[noupdate=true].products[refresh=true]","")})}};return pub._productsToDelete=new Array,pub.removeProductFromPriceList=function(products){pub._productsToDelete=products,SuperOffice.Admin.Quote.doRemoveProducts()},pub.doRemoveProducts=function(){var products=pub._productsToDelete,yesToAll=1<products.length,productId="0";0<products.length&&(productId=products[0].attributes.primaryKey.value),Dialog.ConfirmDelete("{nav=product&product_id="+productId+"}",yesToAll,"SuperOffice.Admin.Quote.removeProductFromPriceListCallback",!1)},pub.removeProductFromPriceListCallback=function(res){res=res.getStatus();if(0==res)pub._productsToDelete=new Array;else if(1==res)0<pub._productsToDelete.length&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminProductDataHandler.DeleteProduct","",pub._productsToDelete[0].attributes.primaryKey.value),pub._productsToDelete.shift());else if(2==res){for(var i=0;i<pub._productsToDelete.length;i++)AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminProductDataHandler.DeleteProduct","",pub._productsToDelete[i].attributes.primaryKey.value);pub._productsToDelete=new Array}else 3==res&&pub._productsToDelete.shift();0<pub._productsToDelete.length?SuperOffice.Admin.Quote.removeProductFromPriceList(pub._productsToDelete):SuperOffice.PageBuilder.refresh()},pub.importProducts=function(){alert("not implemented yet")},pub.toggleProductRights=function(state){for(var fieldNames=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditProductDataHandler.GetProductFieldNames",""),index=0;index<fieldNames.length;index++)so("AdminEditProduct"+fieldNames[index]+"Mandatory")&&(so("AdminEditProduct"+fieldNames[index]+"Mandatory").disabled=!state),so("AdminEditProduct"+fieldNames[index]+"Editable")&&(so("AdminEditProduct"+fieldNames[index]+"Editable").disabled=!state)},pub.toggleProductInAssortment=function(id){AjaxMethodDispatcher.CallSync("Superoffice.CRM.Web.Data.AdminProductDataHandler.ToggleProductInAssortment","",parseInt(id,10))},pub.changeProductImage=function(filename){alert("not implemented yet (filename is "+filename+")")},pub.removeProductImage=function(){console.log("removeProductImage call"),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditProductDataHandler.ChangeProductImage","",0),QueuedPageUpdate("soprotocol:admineditproduct[dialog=stop].main[refresh=true]?adminproductimage_id=0&adminproductimage_type=0")},pub.addPriceList=function(){var priceListCurrent=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","adminpricelist");priceListCurrent&&AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.SetCurrent","","adminoriginalpricelist",priceListCurrent.Id,priceListCurrent.Name,priceListCurrent.Type),Dialog.open("AdminEditPriceList","admineditpricelist[dialog=stop]?AdminPriceList_id=0","QueuedPageUpdate('soprotocol:adminquote[noupdate=true].products[refresh=true]');")},pub.editPriceList=function(){var selectedPriceListId=so("adminquoteProductsPriceLists_SelectedValue").value;Dialog.open("AdminEditPriceList","admineditpricelist[dialog=stop]?AdminPriceList_id="+selectedPriceListId,"QueuedPageUpdate('soprotocol:adminquote[noupdate=true].products[refresh=true]');")},pub.closePriceListDialog=function(){Dialog.close();var originalPriceListCurrent=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","adminoriginalpricelist");originalPriceListCurrent&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","adminpricelist",originalPriceListCurrent.Id,"","")},pub.deletePriceList=function(){Dialog.YesNo("","[SR_PRODUCT_DELETE_PRICELIST_CONFIRM]","question","","SuperOffice.Admin.Quote.deletePriceListConfirmed","")},pub.deletePriceListConfirmed=function(res){1==res.getStatus()&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditPriceListDataHandler.DeletePriceList",""),SuperOffice.PageBuilder.refresh())},pub.switchPriceList=function(id){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","AdminPriceList",id,"",""),QueuedPageUpdate("soprotocol:adminquote.products[refresh=true]?AdminPriceList_id="+id)},pub.switchPriceListLimitedValidity=function(state){state?(SuperOffice.SoHelper.enableElementBySoId("AdminEditPriceListValidFrom"),SuperOffice.SoHelper.enableElementBySoId("AdminEditPriceListValidTo")):(SuperOffice.SoHelper.disableElementBySoId("AdminEditPriceListValidFrom"),SuperOffice.SoHelper.disableElementBySoId("AdminEditPriceListValidTo"))},pub.setStateSubscriptionFields=function(){so("AdminEditProductIsSubscription").checked?(SuperOffice.SoHelper.enableElementBySoId("AdminEditProductDefaultSubscriptionQuantity_textfield"),SuperOffice.SoHelper.enableElementBySoId("AdminEditProductSubscriptionUnit")):(SuperOffice.SoHelper.disableElementBySoId("AdminEditProductDefaultSubscriptionQuantity_textfield"),SuperOffice.SoHelper.disableElementBySoId("AdminEditProductSubscriptionUnit"))},pub.editPriceListOnLoad=function(){SuperOffice.Admin.Quote.switchPriceListLimitedValidity(so("AdminEditPriceListLimitedValidity").checked),"Empty"==SuperOffice.SoHelper.getSoRadioButtonListSelectedValue("AdminEditPriceListEmptyOrCopyButton")?SuperOffice.Admin.Quote.SetEmptyPriceListChecked():SuperOffice.Admin.Quote.SetCopyPriceListChecked()},pub.SetEmptyPriceListChecked=function(){SuperOffice.SoHelper.hideElementBySoId("AdminEditPriceListCopyOptionsControlGroup")},pub.SetCopyPriceListChecked=function(){SuperOffice.SoHelper.showElementBySoId("AdminEditPriceListCopyOptionsControlGroup")},pub.checkPriceListValidFromTo=function(){var validFrom=so("AdminEditPriceListValidFrom_DateField_Date").value,validTo=so("AdminEditPriceListValidTo_DateField_Date").value;return AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditPriceListDataHandler.CheckPriceListValidFromTo","",validFrom,validTo)},pub.configureQuoteLine=function(){Dialog.open("AdminConfigureQuoteLine","adminconfigurequoteline[dialog=stop]","QueuedPageUpdate('soprotocol:adminquote[noupdate=true].settings[refresh=true]');")},pub.moveQuoteLineConfigurationUp=function(fieldName){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminConfigureQuoteLineDataHandler.MoveQuoteLineConfigurationUp","",fieldName);var originalScrollTop=so("AdminConfigureQuoteLineMainControlGroup").scrollTop;SuperOffice.PageBuilder.refresh(function(){so("AdminConfigureQuoteLineMainControlGroup").scrollTop=originalScrollTop})},pub.moveQuoteLineConfigurationDown=function(fieldName){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminConfigureQuoteLineDataHandler.MoveQuoteLineConfigurationDown","",fieldName);var originalScrollTop=so("AdminConfigureQuoteLineMainControlGroup").scrollTop;SuperOffice.PageBuilder.refresh(function(){so("AdminConfigureQuoteLineMainControlGroup").scrollTop=originalScrollTop})},pub.toggleQuoteLineConfigurationShowField=function(idBase){so(idBase+"_showField").checked?(SuperOffice.SoHelper.enableElementBySoId(idBase+"_label"),SuperOffice.SoHelper.enableElementBySoId(idBase+"_tooltip"),"False"===so(idBase+"_restrictEdit").value&&(SuperOffice.SoHelper.enableElementBySoId(idBase+"_Editable"),SuperOffice.SoHelper.enableElementBySoId(idBase+"_Mandatory"))):(SuperOffice.SoHelper.disableElementBySoId(idBase+"_label"),SuperOffice.SoHelper.disableElementBySoId(idBase+"_tooltip"),SuperOffice.SoHelper.disableElementBySoId(idBase+"_Editable"),SuperOffice.SoHelper.disableElementBySoId(idBase+"_Mandatory"))},pub.editQuoteLineConfigurationOnLoad=function(){for(var showFields=$("[soid$='_showField']"),i=0;i<showFields.length;i++)showFields[i].onclick()},pub.activateAllQuoteLineConfigurations=function(){for(var soid,showFields=$("[soid$='_showField']"),i=0;i<showFields.length;i++)showFields[i].disabled||(showFields[i].checked=!0,soid=(soid=showFields[i].attributes.soid.value).substring(0,soid.indexOf("_showField")),pub.toggleQuoteLineConfigurationShowField(soid))},pub.deactivateAllQuoteLineConfigurations=function(){for(var soid,showFields=$("[soid$='_showField']"),i=0;i<showFields.length;i++)showFields[i].disabled||(showFields[i].checked=!1,soid=(soid=showFields[i].attributes.soid.value).substring(0,soid.indexOf("_showField")),pub.toggleQuoteLineConfigurationShowField(soid))},pub.addSaleTypeQuoteDocument=function(){var saleTypeCurrent=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","adminlistitem");null==saleTypeCurrent||saleTypeCurrent.Id<=0?Dialog.Information("SuperOffice","[SR_QUOTE_SALETYPEDIALOG_MUSTSAVEBEFOREADDINGDOCUMENTS]"):SuperOffice.Find.OpenFindInlineDialog({FindType:SuperOffice.Find.FindTypeEnum.Single,CriterionEntity:"document",Callback:"SuperOffice.Admin.Quote.addSaleTypeQuoteDocumentCallback();"})},pub.addSaleTypeQuoteDocumentCallback=function(){if(1==Dialog.getReturnStatus()){for(var tmp=Dialog.getReturnValue().split("|,|"),i=0;i<tmp.length;i++){var selectedId=parseInt(tmp[i].substring(0,tmp[i].indexOf("|")),10);AjaxMethodDispatcher.CallSync("Superoffice.CRM.Web.Data.AdminEditSaletypeDialogDataHandler.AddSaleTypeQuoteAttachment","",selectedId)}QueuedPageUpdate("soprotocol:adminlistseditsaletype[dialog=stop].main[refresh=true]")}},pub.removeSaleTypeQuoteDocuments=function(selectedRows){if(0<selectedRows.length){for(var i=0;i<selectedRows.length;i++){selectedRows[i].attributes.rowEntityName.value;var primaryKey=parseInt(GetPrimaryKeyFromRow(selectedRows[i]),10);AjaxMethodDispatcher.CallSync("Superoffice.CRM.Web.Data.AdminEditSaletypeDialogDataHandler.DeleteSaleTypeQuoteAttachment","",primaryKey)}QueuedPageUpdate("soprotocol:adminlistseditsaletype[dialog=stop].main[refresh=true]")}},pub.ToggleSaleTypeQuoteAttachmentDefaultIncluded=function(id,archiveControl){AjaxMethodDispatcher.CallSync("Superoffice.CRM.Web.Data.AdminEditSaletypeDialogDataHandler.ToggleSaleTypeQuoteAttachmentDefaultIncluded","",id),archiveControl.RefreshList()},pub.SaleTypeQuoteDefaultsApprovalOnChange=function(selected){"NoApproval"==selected&&(SuperOffice.SoHelper.disableElementBySoId("AdminListsEditSaletypeQuoteDefaultsDiscountOverLimit_textfield"),SuperOffice.SoHelper.disableElementBySoId("AdminListsEditSaletypeQuoteDefaultsEarningBelowLimit_textfield")),"DiscountOver"==selected&&(SuperOffice.SoHelper.enableElementBySoId("AdminListsEditSaletypeQuoteDefaultsDiscountOverLimit_textfield"),SuperOffice.SoHelper.disableElementBySoId("AdminListsEditSaletypeQuoteDefaultsEarningBelowLimit_textfield")),"EarningBelow"==selected&&(SuperOffice.SoHelper.disableElementBySoId("AdminListsEditSaletypeQuoteDefaultsDiscountOverLimit_textfield"),SuperOffice.SoHelper.enableElementBySoId("AdminListsEditSaletypeQuoteDefaultsEarningBelowLimit_textfield"))},pub.setRestoreConnectionButtonState=function(id,archiveControl){for(var rows=archiveControl.getSelectedRows(),i=0;i<rows.length;i++){for(var canDelete=!1,rights=rows[i].attributes.rowrights.value.split(","),ii=0;ii<rights.length;ii++)if("D"==rights[ii]){canDelete=!0;break}if(!canDelete)break}canDelete?SuperOffice.SoHelper.disableElementBySoId(id):SuperOffice.SoHelper.enableElementBySoId(id)},pub.UpdateProductImage=function(imgElemSoId,binId){SuperOffice.SoHelper.getElementBySoId(imgElemSoId).value=binId,document.getElementById("ImageList_SelectedPrimaryKeys").value=binId,document.getElementById("ImageList_SelectedValues").value=binId,SuperOffice.PageBuilder.refresh(null,"adminproductimage_id="+binId+"&adminproductimage_type="+binId)},pub})(),extendNs("SuperOffice.UserCommand",function(ns){getNs("SuperOffice");ns.Execute=function(userCommands,userId){var userCommand=null;userCommands instanceof Array?userCommand=userCommands.shift():(userCommand=userCommands,userCommands=null),null!=userCommand&&(0==userCommand.Actions?ns._execute(userCommand,0,userCommands,userId):1==userCommand.Actions?$sodlgm.confirm(SCIL.Router.createUIContext(),{caption:"[SR_INFO_CAPTION]",message:userCommand.Description,height:256,okCaption:"Yes",cancelCaption:"No",ok:function(){ns._execute(userCommand,1,userCommands,userId)},cancel:function(){ns._execute(userCommand,3,userCommands,userId)}}):2==userCommand.Actions?$sodlgm.confirm(SCIL.Router.createUIContext(),{caption:"[SR_INFO_CAPTION]",message:userCommand.Description,height:256,ok:function(){ns._execute(userCommand,2,userCommands,userId)},cancel:function(){ns._execute(userCommand,4,userCommands,userId)}}):3==userCommand.Actions&&$sodlgm.info(SCIL.Router.createUIContext(),{caption:"[SR_INFO_CAPTION]",message:userCommand.Description,height:256,ok:function(){ns._execute(userCommand,2,userCommands,userId)}}))},ns._execute=function(userCommand,actionResult,commandArray,userId){$webapi.post("/User/"+userId+"/CustomCommand/"+userCommand.Name+"?actionResult="+actionResult).then(function(res){console.log("result",res),null==res||res.Success||$sodlgm.info(SCIL.Router.createUIContext(),{caption:"[SR_ERROR_CAPTION]",message:res.Message,height:256})}),null!=commandArray&&0!=commandArray.length&&ns.Execute(commandArray,userId)}}),SuperOffice.AlignmentHelper=(()=>{var pub={SetWidth:function(width,names){for(var i=0;i<names.length;i++)if("string"==typeof names[i]){var elem=so(names[i]);if(null!=elem)for(var ce,row=0;row<$(elem).children("table")[0].rows.length;row++){ce=$(elem).children("table")[0].rows[row].cells[0],$(ce).css("width",width+"px");for(var cell=1;cell<$(elem).children("table")[0].rows[row].cells.length;cell++)ce=$(elem).children("table")[0].rows[row].cells[cell],$(ce).css("width","")}}},AlignControlGroups:function(){var largestCellWidth=0;for(i=0;i<arguments.length;i++)if("string"==typeof arguments[i]){var elem=so(arguments[i]);if(null!=elem){if(0==elem.getElementsByTagName("table").length)return;elem=$(elem.getElementsByTagName("table")[0].rows[0].cells[0]).width();largestCellWidth<elem&&(largestCellWidth=elem)}}var args=Array.prototype.slice.call(arguments);pub.SetWidth(largestCellWidth,args)},AlignHeader:function(source,target){var cellWidth,elem2;null!=source&&null!=(source=so(source))&&0!=(cellWidth=$(source.getElementsByTagName("table")[0].rows[0].cells[0]).get(0).offsetWidth||0)&&null!=(elem2=so(target))&&($(elem2).children("table")[0].rows[0].cells[0].width=cellWidth)},ForcedAlignHeader:function(source,target,cellWidthIncrement){var cellWidth;null!=source&&null!=(source=so(source))&&(null!=cellWidthIncrement&&void 0!==cellWidthIncrement||(cellWidthIncrement=0),0!=(cellWidth=$(source.getElementsByTagName("table")[0].rows[0].cells[0]).get(0).offsetWidth||0))&&pub.SetWidth(cellWidth+=cellWidthIncrement,new Array(target))},AlignCostAndCurrency:function(spacerId){var currency=$("#CurrencyCell");0!=currency.length&&(0<currency[0].children.length?$("[soid="+spacerId+"]").parent().css("width",42):($("[soid=SaleDetailsAmount_SaleAmountSaleAmountClientID]").css("position","absolute"),$("[soid=SaleDetailsAmount_SaleAmountSaleAmountClientID]").css("right","5px"),$("[soid=SaleDetailsAmount_SaleAmountSaleAmountClientID]").css("top","0px"),$("[soid=SaleDetailsAmount_SaleAmountSaleAmountClientID]").css("width","180px")))}};return pub})();var ArchiveDelete=new _ArchiveDelete;function _ArchiveDelete(){this._archiveControl=null,this._index=0,this._callback="",this._rowArrayCollectionIndex=0,this._rowArrayCollection=new Array,this._navTypeArray=new Array,this._numberOfRowTypes=0,this._currentRecurrenceRuleId=0,this._hasDoneDelete=!1}function _AssignToProxy(currentAssociateId){this._currentAssociateId=currentAssociateId,this._childDataFieldSoId="AssignToProxyData",this._parentDataFieldSoId="ParticipantsProxyData",this._childContextFieldSoId="AssignToProxyContext",this._parentContextFieldSoId="ParticipantsProxyContext",this._childDataField=null,this._parentDataField=null,this._childContextField=null,this._parentContextField=null}function _AssignTo(){this._dataFieldSoId="AssignToProxyData",this._dataField=null,this._groupId=0}_ArchiveDelete.prototype.DeleteRows=function(archiveControl,rows,callback,noConfirm){if(null!=rows&&0!=rows.length){void 0!==noConfirm&&null!=noConfirm||(noConfirm=!1),ArchiveDelete._archiveControl=archiveControl,ArchiveDelete._rows=rows,ArchiveDelete._index=0,ArchiveDelete._callback=callback,ArchiveDelete._hasDoneDelete=!1,ArchiveDelete._rowArrayCollection=new Array,ArchiveDelete._rowArrayCollectionIndex=0,ArchiveDelete._navTypeArray=new Array,ArchiveDelete._numberOfRowTypes=0;for(var rowType,nav,navTypes=new Object,t=0;t<rows.length;++t)rowType=ArchiveDelete.extractLinkHint(rows[t]),navTypes[nav=ArchiveDelete.extractNav(rowType)]=!0,ArchiveDelete._navTypeArray.push(nav);for(key in navTypes)++ArchiveDelete._numberOfRowTypes;if(1==ArchiveDelete._numberOfRowTypes)ArchiveDelete._rowArrayCollection.push(rows);else for(var key in navTypes){for(var rowsArray=new Array,t=0;t<ArchiveDelete._navTypeArray.length;++t)ArchiveDelete._navTypeArray[t]==key&&rowsArray.push(rows[t]);ArchiveDelete._rowArrayCollection.push(rowsArray)}rowType=ArchiveDelete.extractLinkHint(ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex][ArchiveDelete._index]),"recurringappointment"==(nav=ArchiveDelete.extractNav(rowType))?(archiveControl=SuperOffice.Selection.getIdFromString("appointment_id=",rowType),Dialog.ConfirmDeleteRecurring(archiveControl,"delete",!1,!1,"ArchiveDelete.DeleteCallBack")):Dialog.ConfirmDelete("{"+rowType+"}",this.isMoreLeft(),"ArchiveDelete.DeleteCallBack",noConfirm)}},_ArchiveDelete.prototype.DeleteCallBack=function(res,checkBoxValues,radioValues){0==res.getStatus()&&(ArchiveDelete._index=ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex].length-1);var rowType=ArchiveDelete.extractLinkHint(ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex][ArchiveDelete._index]),nav=ArchiveDelete.extractNav(rowType),rowTypesToDelete=new Array,mode="",appId;if("RecurrenceConfirm"==res.getContext()&&(mode=res.getValue()),("sendemail"==res.getValue()||-1<radioValues.indexOf("sendemail"))&&(mode+="|sendemail"),1==res.getStatus())rowTypesToDelete.push(rowType),ArchiveDelete._archiveControl.removeRowByIndex?ArchiveDelete._archiveControl.removeRowByIndex(ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex][ArchiveDelete._index].rowIndex):ArchiveDelete._archiveControl([ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex][ArchiveDelete._index]]);else if(2==res.getStatus()){for(var t=ArchiveDelete._index;t<ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex].length;++t)rowTypesToDelete.push(ArchiveDelete.extractLinkHint(ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex][t])),ArchiveDelete._archiveControl.removeRowByIndex?ArchiveDelete._archiveControl.removeRowByIndex(ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex][t].rowIndex):ArchiveDelete._archiveControl([ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex][t]]);ArchiveDelete._index=ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex].length-1}if(0<rowTypesToDelete.length)try{var resDelete=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.ArchiveDelete.DeleteFromLinkHint","",rowTypesToDelete.join("|"),mode);ArchiveDelete._hasDoneDelete=!0,null!=resDelete&&""!=resDelete.ExecuteJs&&eval("UIHelper.SafeGetOpener()."+resDelete.ExecuteJs)}catch(ex){alert("Could not delete "+this.extractNav(rowType))}if(ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex].length==++ArchiveDelete._index){if(ArchiveDelete._rowArrayCollection.length==++ArchiveDelete._rowArrayCollectionIndex)return void(ArchiveDelete._callback instanceof Object&&ArchiveDelete._hasDoneDelete?ArchiveDelete._callback():""!=ArchiveDelete._callback&&ArchiveDelete._hasDoneDelete&&eval(ArchiveDelete._callback));ArchiveDelete._index=0}rowType=ArchiveDelete.extractLinkHint(ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex][ArchiveDelete._index]),nav=ArchiveDelete.extractNav(rowType),"recurringappointment"==nav?(appId=SuperOffice.Selection.getIdFromString("appointment_id=",rowType),Dialog.ConfirmDeleteRecurring(appId,"delete",!1,!1,"ArchiveDelete.DeleteCallBack")):Dialog.ConfirmDelete("{"+rowType+"}",this.isMoreLeft(),"ArchiveDelete.DeleteCallBack")},_ArchiveDelete.prototype.isMoreLeft=function(){return ArchiveDelete._index+1<ArchiveDelete._rowArrayCollection[ArchiveDelete._rowArrayCollectionIndex].length},_ArchiveDelete.prototype.extractLinkHint=function(row){return row.tagName&&"tr"===row.tagName.toLowerCase()?row.attributes.rowtype.value:row.LinkHint},_ArchiveDelete.prototype.extractNav=function(rowType){var endPos,nav="",startPos=(ArchiveDelete._currentRecurrenceRuleId=0,rowType.indexOf("nav="));return-1==startPos?"":("appointment"==(nav=-1<(endPos=rowType.indexOf("&",startPos))?rowType.substring(startPos+4,endPos):str.substr(startPos+4))&&-1==rowType.indexOf("recurrencerule_id=0")&&(nav="recurringappointment",ArchiveDelete._currentRecurrenceRuleId=SuperOffice.Selection.getIdFromString("recurrencerule_id",rowType)),nav)},_this=_AssignToProxy.prototype,_this.InitializeFromParent=function(){this._childDataField=SuperOffice.SoHelper.getInputElementBySoId(this._childDataFieldSoId),this._childContextField=SuperOffice.SoHelper.getInputElementBySoId(this._childContextFieldSoId),this._parentContextField=UIHelper.GetOpener().SuperOffice.SoHelper.getInputElementBySoId(this._parentContextFieldSoId),null!=this._parentContextField&&(this._childContextField.value=this._parentContextField.value),""==this._childDataField.value&&(this._parentDataField=UIHelper.GetOpener().SuperOffice.SoHelper.getInputElementBySoId(this._parentDataFieldSoId),null!=this._parentDataField)&&(this._childDataField.value=this._parentDataField.value)},_this.ReturnDataToParent=function(){var selectedAssociate=AssociateArchiveData.GetCurrentAssociateId();selectedAssociate+=";"+this._currentAssociateId,Dialog.setParentReturnObject(1,selectedAssociate,"AssignTo")},_this.GetReturnValue=function(){var selectedAssociateLink,retVal,selectedAssociate;"AssignTo"==Dialog.getReturnContext()&&1==Dialog.getReturnStatus()&&(selectedAssociate=SuperOffice.SoHelper.getInputElementBySoId("OwnerLnkValue"),selectedAssociateLink=SuperOffice.SoHelper.getAnchorElementBySoId("OwnerLnk"),null!=(retVal=Dialog.getReturnValue()))&&null!=selectedAssociate&&null!=selectedAssociateLink&&(selectedAssociate=(selectedAssociate.value=retVal).split(";"),UIHelper.SetInnerText(selectedAssociateLink,selectedAssociate[1]),UIHelper.GetMainPageWindow().$clientapi.post("/SuperState/AddHistoryItem",{id:selectedAssociate[0],name:selectedAssociate[1],type:"",entityName:"diaryowner",persistHistory:!0}),null!=ParticipantsArchiveData)&&(ParticipantsArchiveData.PopulateFromField(),ParticipantsArchiveData.PopulateToField())},_this=_AssignTo.prototype,_this.Initialize=function(){this._dataField=SuperOffice.SoHelper.getInputElementBySoId(this._dataFieldSoId)},_this.OnNoRowsSelected=function(res){SuperOffice.SoHelper.disableElementBySoId("DlgButtonBar_okButton")},_this.OnRowsSelected=function(res){SuperOffice.SoHelper.enableElementBySoId("DlgButtonBar_okButton")},_this.RefreshArchive=function(){AssociateArchiveData.PopulateToField(),0==this._groupId&&(this._groupId=SuperOffice.SoHelper.getInputElementBySoId("GroupMDO_SelectedValue").value);var restriction=this._dataField.value+";groupRestrictionId="+this._groupId;AssociateArchiveArchiveControl.RefreshList(restriction)},_this.getSelectedAssociate=function(){return SuperOffice.SoHelper.getInputElementBySoId("OwnerLnkValue").value.split(";")[0]},_this.OpenAssignToDialog=function(){Dialog.open("assignto","assignto[dialog=stop].main?assignToId="+this.getSelectedAssociate(),"AssignToProxy.GetReturnValue();",!0,!0)},_this.SelectGroup=function(){this._groupId=SuperOffice.SoHelper.getInputElementBySoId("GroupMDO_SelectedValue").value,this.RefreshArchive()},_this.SelectAssociate=function(selectedRows){var id;0<selectedRows.length&&(id=selectedRows[0].attributes.id.value,selectedRows=UIHelper.GetInnerText(selectedRows[0]),AssociateArchiveData.SetCurrentAssociateId(id+";"+selectedRows))},_this.SaveAssociate=function(selectedRows){this.SelectAssociate(selectedRows),this.Save()},_this.Save=function(){AssignToProxy.ReturnDataToParent(),Dialog.close()},_this.Cancel=function(){Dialog.close()},extendNs("SuperOffice.Controls.ConcentDialog",function(ns){function checkConfigurationCallback(showConcent){showConcent&&openDialog()}var $=jQuery,openDialog=function(){Dialog.open("consentagreementwindow","consentagreement[dialog=stop]",null)};ns.openDialog=openDialog,ns.checkConfiguration=function(){AjaxMethodDispatcher.CallASyncReadOnly(checkConfigurationCallback,null,null,null,"SuperOffice.CRM.Web.AjaxMethods.ConcentDialog.CheckConfiguration")},$(function(){var co=getNs("SuperOffice.Context").getClientOptions();co.IsDialog||"admin"!==co.SubClient||ns.checkConfiguration()})});var g_contactIdToDelete=0;function DeleteContact(contactId){0!=contactId&&(g_contactIdToDelete=contactId,Dialog.ConfirmDelete("{nav=contact&contact_id="+contactId+"}",!1,"DeleteContactCallBack"))}function DeleteContactCallBack(res){0!=g_contactIdToDelete&&(1!=res.getStatus()&&2!=res.getStatus()||(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Contact.DeleteContact","",g_contactIdToDelete),PageUpdate("soprotocol:?contact_id="+g_clientOptions.LastValidHistoryItem,"")),g_contactIdToDelete=0)}function ReturnArchiveRestrictionInfo(obj){Dialog.setParentReturnObject(1,obj),Dialog.close()}function bootstrapDataHandler(){$(document).initMvc()}function _DialogContext(){this.WindowName="",this.WindowPointer="",this.WindowInterval=null,this.OnCloseScript=""}extendNs("SuperOffice.Context",function(ns){ns.getClientOptions=function(){return"undefined"!=typeof g_clientOptions?g_clientOptions:{}},ns.getWindow=function(){return window}}),SuperOffice.Data=function(){var pub={setReturnData:function(dataHandlerId,returnData){"object"==typeof this[dataHandlerId]||eval("SuperOffice.Data."+dataHandlerId+" = {}"),this[dataHandlerId].soReturnData=returnData},hasDataHandler:function(dataHandlerId){return"object"==typeof this[dataHandlerId]&&"object"==typeof this[dataHandlerId]._soStateDataObject}};return pub}(),SuperOffice.Data.ObjectState=(()=>{var pub={},soStateDataObjectsObject=null;return pub.hasDataCarrier=function(dataCarrierId){return void 0!==this[dataCarrierId]},pub.updateServerState=function(fnRefresh){this.updateStateObject(),"function"==typeof fnRefresh?fnRefresh():QueuedPageUpdate("soprotocol:"+SuperOffice.Environment.SoProtocolPageAndView+"[Request=Callback&mode=edit]","")},pub.updateStateObject=function(){var dStart=new Date;null==soStateDataObjectsObject&&(soStateDataObjectsObject=$.fromSoId("sostatedata").jsonParse());for(var t=0;t<this._soStateDataObject.DataCarriers.length;++t){var data=this[this._soStateDataObject.DataCarriers[t].DataCarrierId];this._soStateDataObject.DataCarriers[t].Data=data}var dhIndex=(dataHandlerId=>{for(var t=0;t<soStateDataObjectsObject.DataHandlers.length;++t)if(dataHandlerId===soStateDataObjectsObject.DataHandlers[t].DataHandlerId)return t;return-1})(this._soStateDataObject.DataHandlerId),dhIndex=(-1===dhIndex?soStateDataObjectsObject.DataHandlers.push(this._soStateDataObject):soStateDataObjectsObject.DataHandlers[dhIndex]=this._soStateDataObject,this._soStateDataObject.Changed=!0,$.fromSoId("sostatedata").jsonStringifyAsBase64(soStateDataObjectsObject),new Date);return debug.trace(dhIndex.getTime()-dStart.getTime()+"ms","state"),soStateDataObjectsObject},pub.save=function(method){this._soStateDataObject.DataHandlerId;for(var assemblyName=this._soStateDataObject.AssemblyQualifiedName,t=0;t<this._soStateDataObject.DataCarriers.length;++t){var id=this._soStateDataObject.DataCarriers[t].DataCarrierId;this._soStateDataObject.DataCarriers[t].Data=this[id]}var that=this,fnCallback=arguments[arguments.length-1],methodArguments=("function"!=typeof fnCallback&&(fnCallback=null),[]);if(2<arguments.length)for(var a=1;a<arguments.length-1;a++)so_defined(arguments[a])?methodArguments.push("string"!=typeof arguments[a]?arguments[a]:AjaxMethodDispatcher.paramEncode(arguments[a])):methodArguments.push("");AjaxMethodDispatcher.ExecuteData(assemblyName,method,methodArguments,this._soStateDataObject.DataCarriers,function(res){var stateDataArray=res,res=stateDataArray.shift();if(0<stateDataArray.length){for(var i=0;i<stateDataArray.length;++i){var stateData=stateDataArray[i];that[stateData.DataCarrierId]=stateData.Data}$(document).mvcRefresh()}null!=fnCallback&&fnCallback(res)})},pub})(),SuperOffice.Dialog=(()=>{var pub={OpenFromScilRecipe:function(recipeName,caption,options,dialogOptions){dialogOptions=dialogOptions||{},$sodlgm.open(null,{id:recipeName,recipeName:recipeName,caption:caption,windowSetting:{resizable:dialogOptions.resizable,width:dialogOptions.width||"500px",height:dialogOptions.height||"570px"}},function(ctx){for(var propertyName in options)ctx.set(propertyName,options[propertyName])},function(ctx,state){if(99===state)return ctx.sendCommand("closeMyDialog",null).then(function(){return!0}).catch(function(){return!1})})},GetDialogCallbackFunction:function(){try{return opener.Dialog.getChildDialog(Dialog.getDialogName()).getCloseCallback()}catch(e){try{return UIHelper.SafeGetOpener().Dialog.getChildDialog(Dialog.getDialogName()).getCloseCallback()}catch(ex){return""}}},ShowOnlineLearning:function(){var sURL=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.GetOnlineLearningURL","");""!=sURL&&window.open(sURL,"CourseWindow","top=0,left=0,height=813,width=1515,scrollbars=yes, resizable=yes, status=no,toolbar=no,menubar=no,location=no")},ShowUrl:function(sURL){""!=(sURL=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.SubstituteTemplateVariablesInUrl","",sURL))&&window.open(sURL,"CourseWindow","top=0,left=0,height=810,width=1264,scrollbars=yes, resizable=yes, status=no,toolbar=no,menubar=no,location=no")},ShowUrlInNewTab:function(sURL){""!==(sURL=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.SubstituteTemplateVariablesInUrl","",sURL))&&window.open(sURL,void 0,"noopener")},SetFirstTimeDialogHookFunction:function(f){alert("OBSOLETE function SetFirstTimeDialogHookFunction called. This MUST be fixed. This applies to online only.")}};return pub})(),SuperOffice.Dialog.Size=(()=>{var pub={};return pub.pages=new Array,pub.GetDialogInfos=function(callback){var lPages=SuperOffice.Dialog.Size.GetPages();AjaxMethodDispatcher.CallASync(function(dialogInfo){for(var i=0;i<dialogInfo.length;i++)lPages[dialogInfo[i].Key]=dialogInfo[i];callback()},"","","","SuperOffice.CRM.Web.AjaxMethods.Dialog.GetDialogSizes")},pub.GetDialogInfo=function(pageId){var dialogInfo,lPages=SuperOffice.Dialog.Size.GetPages();return null!=lPages[pageId]?lPages[pageId]:(dialogInfo=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.GetDialogSize","",pageId),lPages[pageId]=dialogInfo)},pub.SetWindowSize=function(pageId,width,height){SuperOffice.Dialog.Size.GetPages()[pageId]={Width:width,Height:height},AjaxMethodDispatcher.CallASync("","","","","SuperOffice.CRM.Web.AjaxMethods.Dialog.SetDialogSize",pageId,width,height)},pub.GetPages=function(){return(null!=UIHelper.GetOpener()?UIHelper.GetMainPageWindow().SuperOffice:SuperOffice).Dialog.Size.pages},pub})();var _this=_DialogContext.prototype,dialogLock=!1,Dialog=new _Dialog;function _Dialog(){this._dialogWindow=window,this._childDialogs=new Array,this._dialogName=window.name,this._closeCallback="",this._modalWnd=null,this._modalReturnObject=null,this.lockLayer=null,this.lockLayerMain=null,this.focusWnd=null,this._disableWindowBusyIndicator=new BusyIndicator,this._disableWindowLockLayer=null,this._ajaxCallBack="",this._ajaxVal=null,this._ajaxContext=null,this._currentMsgBox=null,this._currentProgressBox=null,this._dialogsAlive=new SoCollection,this.currentInLineDialog=null,this._currentInlineModalDialog=null,this.dialogList={},this.preLoadLock=!1,this.scilDialogHeaderZIndex=null,this.scilLockLayerZIndex=null}function getIframeWindow(iframe_object){var doc;return iframe_object.contentWindow||iframe_object.window||((doc=!(doc=!doc&&iframe_object.contentDocument?iframe_object.contentDocument:doc)&&iframe_object.document?iframe_object.document:doc)&&doc.defaultView?doc.defaultView:doc&&doc.parentWindow?doc.parentWindow:void 0)}function SetConfirmCreateSuggestedAppointmentCallBack(returnObject,checkBoxValues,radioValues){checkBoxValues[0]&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserPreferences.Set","","Sale","ConfirmCreateSuggAppointment","0"),OpenAppointment(null,"appointment.main[new=true]?appointment_id=0&"+returnObject._context.dings,function(){eval(returnObject._context.callback)})}_this=_Dialog.prototype,_this.fadeDown=function(elem){0==this.getDialogLevel()&&this.unLockMainWindow(),$(elem).animate({opacity:"-=0.99"},400,function(){})},_this.fadeUp=function(elem){0==this.getDialogLevel()&&this.lockMainWindow(!0),$(elem).animate({opacity:"+=0.99"},400,function(){})},_this.getRootWindow=function(){return UIHelper.GetMainPageWindow()},_this.makecrumb=function(name,level){var minimizeImg,tName,crumb=$("<span class='DialogCrumb' id='crumb"+level+"' />"),that=this,name=$("<span>"+$("<span/>").text(name).html()+"</span>"),di=(g_clientOptions.Debug&&null!=(di=that.getRootWindow().Dialog.dialogList[level])&&name.attr("title",di.SoProtocol),$("<span/>").addClass("DialogCloseButton")),dialogInfo=(di.css({visibility:"visible"}),0==level?di.on("click",function(){Dialog.close(level)}):di.on("click",function(){getIframeWindow(that.getRootWindow().Dialog.dialogList[level].iframe).IFrameClose(level)}),this.getRootWindow().Dialog.dialogList[0]);return dialogInfo&&dialogInfo.Info?.Minimizable&&0==this.getRootWindow().$("[minimized='true']").length&&0==level&&((minimizeImg=$("<span/>").addClass("DialogMinimizeButton")).css({visibility:"visible"}),tName=dialogInfo.name+"",minimizeImg.on("click",function(){return that.getRootWindow().Dialog.minimize(tName),!1}),crumb.on("click",function(){that.getRootWindow().Dialog.maximize(tName)}),crumb.append(minimizeImg)),crumb.append(di),crumb.append(name),crumb},_this.removeCrumb=function(level){void 0===level&&(level=this.getDialogLevel());var elem=this.getRootWindow().$("#crumb"+(level-1));elem.fadeTo(400,0,"",function(){elem.remove()})},_this.setHeight=function(height){this.getRootWindow().Dialog._setHeight(height)},_this._setHeight=function(height){var headerDiv=$("#inlinedialogContainer"),rect=getWindowRectangle();headerDiv.css({top:(rect._y-height)/2+"px",height:height}),this.onFrameResize(height,32,32)},_this.onResize=function(doAnimation){var that=this,level=this.getRootWindow().Dialog.currentLevel,level=this.getRootWindow().Dialog.dialogList[level],headerDiv=$("#inlinedialogContainer"),rect=getWindowRectangle(),useRealSize=level.Info.Size.Width<=600||level.Info.ForceSize,height=Math.min(useRealSize?level.Info.Size.Height+34:.84*rect._y,1440,rect._y-100),useRealSize=Math.min(useRealSize?level.Info.Size.Width:.84*rect._x,2048,rect._x-100);this.onFrameResize(height,32,32),doAnimation?headerDiv.animate({top:(rect._y-height)/2+"px",left:(rect._x-useRealSize)/2+"px",width:useRealSize,height:height},200,function(){$(that.getRootWindow().Dialog.childDialog.iframe).css({width:"100%"})}):headerDiv.css({top:(rect._y-height)/2+"px",left:(rect._x-useRealSize)/2+"px",width:useRealSize,height:height})},_this.onFrameResize=function(headerHeight,top,bottom){Dialog.childDialog&&($(Dialog.childDialog.iframe).css({top:top+"px",height:headerHeight-bottom+"px"}),getIframeWindow(Dialog.childDialog.iframe).Dialog)&&getIframeWindow(Dialog.childDialog.iframe).Dialog.onFrameResize(headerHeight,0,32)},_this.maximize=function(name){var that,headerDiv=$("#minimized_"+name+"_inlinedialogContainer");0<headerDiv.length&&($("#inlinedialogContainer").remove(),headerDiv.attr("id","inlinedialogContainer"),this.maximizeId(headerDiv,name),headerDiv.find(".DialogMinimizeButton").show(),headerDiv.find(".DialogCloseButton").show(),this.getRootWindow().Dialog.lockMainWindow(!0),that=this,$(this.lockLayerMain).on("mousedown",function(){$(that.lockLayerMain).fadeTo(400,0),$("#inlinedialogContainer").fadeTo(400,.1)}),$(this.lockLayerMain).on("mouseup",function(){$(that.lockLayerMain).fadeTo(400,.3),$("#inlinedialogContainer").fadeTo(400,1)}),$(this.lockLayerMain).on("mouseout",function(){$(that.lockLayerMain).fadeTo(400,.3),$("#inlinedialogContainer").fadeTo(400,1)}),headerDiv.attr("minimized","false"),this.getRootWindow().Dialog.dialogList=jQuery.extend(!0,{},this.getRootWindow().Dialog.minimizedList),this.getRootWindow().Dialog.currentLevel=this.getRootWindow().Dialog.minimizedCurrentLevel,this.getRootWindow().Dialog.childDialog=this.getRootWindow().Dialog.minimizedChildDialog,headerDiv.css({zIndex:"199"}),this.onResize(!0))},_this.minimize=function(name){var w,headerDiv=$("#inlinedialogContainer");0<headerDiv.length&&(headerDiv.find(".DialogMinimizeButton").hide(),headerDiv.find(".DialogCloseButton").hide(),this.getRootWindow().Dialog.minimizedChildDialog=this.getRootWindow().Dialog.childDialog,this.getRootWindow().Dialog.minimizedList=jQuery.extend(!0,{},this.getRootWindow().Dialog.dialogList),this.getRootWindow().Dialog.minimizedCurrentLevel=this.getRootWindow().Dialog.currentLevel,headerDiv.attr("minimized","true"),this.minimizeId(headerDiv,name),name=getWindowRectangle(),headerDiv.css({overflow:"hidden",zIndex:"197"}),w=$(this.getRootWindow().Dialog.minimizedChildDialog.iframe).width(),$(this.getRootWindow().Dialog.minimizedChildDialog.iframe).css({width:w+"px"}),headerDiv.animate({bottom:"8px",right:"8px",width:"200px",height:"32px",left:name._x-208+"px",top:name._y-40+"px"},200),this.unLockMainWindow())},_this.minimizeId=function(elem,name){$(elem).find("[id]").add(elem).each(function(){this.id="minimized_"+name+"_"+this.id})},_this.maximizeId=function(elem,name){$(elem).find("[id]").add(elem).each(function(){this.id=this.id.replace("minimized_"+name+"_","")})},_this.openInline=function(name,caption,soprotocol,backgroundload){try{var elem,queryitems,callbackqueryItems,ifrm,primerSoprotocol,rect,that=this,dialogInfo=SuperOffice.Dialog.Size.GetDialogInfo(name),level=this.getDialogLevel(),headerDiv=$("#inlinedialogContainer"),captionDiv=this.getRootWindow().$("#inlinedialogCaption"),jIframe=(0==headerDiv.length&&((headerDiv=$("<div id='inlinedialogContainer'/>")).attr("class","dialogHeaderDiv"),0==level&&(captionDiv=$("<div id='inlinedialogCaption' class='dialogCaptionDiv'/>"),headerDiv.append(captionDiv)),0<level&&headerDiv.css({border:"solid 0px white"}),$("body").append(headerDiv)),$(headerDiv).append("<div class='SpinnerCenter'/>"),$("#inlinedialogfrm"+name));0!=jIframe.length&&dialogInfo.ClientCache?(null!=(elem=getIframeWindow(ifrm=jIframe[0]).getFromSoId("DialogCard"))&&(elem.innerHTML="",$(elem).append("<div/>")),headerDiv.find(".SpinnerCenter").remove(),getIframeWindow(ifrm).getPlaceholders().each(function(){this.innerHTML="",$(this).append("<div/>")}),queryitems=soprotocol.replace("soprotocol:",""),0===(callbackqueryItems=getIframeWindow(ifrm).$("#__CALLBACKQUERYITEMS")).length?getIframeWindow(ifrm).$("#aspnetForm").append("<input name='__CALLBACKQUERYITEMS' id='__CALLBACKQUERYITEMS' type=hidden value='"+queryitems+"'/>"):callbackqueryItems.val(queryitems),getIframeWindow(ifrm).IFramePageUpdate(soprotocol,""),getIframeWindow(ifrm).IFrameOnLoad("var crumb = Dialog.makecrumb(g_pageTitle,"+level+');crumb.appendTo( Dialog.getRootWindow().$("#inlinedialogCaption")); Dialog.getRootWindow().$("#inlinedialogContainer").find(".SpinnerCenter").remove();')):($("#inlinedialogfrm"+name).remove(),ifrm=document.createElement("IFRAME"),primerSoprotocol=soprotocol.replace("soprotocol:",""),$(ifrm).attr({name:"iframe_"+name,id:"inlinedialogfrm"+name,class:"dialogHeaderFrm",frameBorder:0,marginHeight:0,marginWidth:0,scrolling:"no",allow:"camera; microphone; display-capture",src:"default.aspx?"+primerSoprotocol}),$(ifrm).appendTo(headerDiv),backgroundload||$(ifrm).on("load",function(){that.makecrumb(getIframeWindow(ifrm).g_pageTitle,level,ifrm).appendTo(captionDiv),headerDiv.find(".SpinnerCenter").remove()})),backgroundload?($(ifrm).hide(),$(ifrm).load(function(){setTimeout("Dialog.getRootWindow().focus();",500)})):(g_isMainpage?this.lockMainWindow(!0):0==level?headerDiv.css({top:"0",left:"2px",right:"2px",bottom:"0px"}):(headerDiv.css({top:"0",left:"0px",right:"0px",bottom:"0px"}),$(ifrm).css({border:"solid 0px white"})),this.childDialog={name:name,container:headerDiv[0],iframe:ifrm,Dialog:that,Info:dialogInfo,SoProtocol:soprotocol},Dialog.scilDialogHeaderZIndex=$(".scilDialogHeader").last().css("z-index"),Dialog.scilLockLayerZIndex=$(".SCILLockLayerMain").last().css("z-index"),$(".scilDialogHeader").css({zIndex:198}),$(".SCILLockLayerMain").css({zIndex:198}),$(ifrm).show(),$(ifrm).siblings("iframe").hide(),$(headerDiv).show(),$("html").hasClass("k-ff")&&$(ifrm).on("load",function(){$(ifrm).contents().find("body").on("keydown",function(e){return e.target&&"BODY"===e.target.nodeName&&8===e.keyCode?(e.preventDefault(),!1):void 0})}),this.getRootWindow().Dialog.dialogList[level]=this.childDialog,(0==(this.getRootWindow().Dialog.currentLevel=level)?($(this.lockLayerMain).on("mousedown",function(){$(that.lockLayerMain).fadeTo(200,0),$("#inlinedialogContainer").fadeTo(200,.1)}),$(this.lockLayerMain).on("mouseup",function(){$(that.lockLayerMain).fadeTo(200,.3),$("#inlinedialogContainer").fadeTo(200,1)}),$(this.lockLayerMain).on("mouseout",function(){$(that.lockLayerMain).fadeTo(200,.3),$(that.lockLayerMain).is(":visible")&&$("#inlinedialogContainer").fadeTo(200,1)}),PageEventHandler.addEvent(EventType.ONPAGERESIZE,"dialogResize","Dialog.onResize()"),rect=getWindowRectangle(),headerDiv.css({top:rect._y/2+"px",left:rect._x/2+"px",width:"0px",height:"0px"}),this):this.getRootWindow().Dialog).onResize())}catch(ex){console.log("ERROR:"+ex.message)}},_this.preLoad=function(){if(""==g_clientOptions.SubClient)for(var preLoadItems=[{pageId:"appointment",soprotocol:"appointment[dialogwinname=appointment&dialog=stop&fakeGET=true&preload=true]?appoinment_id=0&appointment_type=1"},{pageId:"person",soprotocol:"person[dialogwinname=person&dialog=stop&fakeGET=true&superstatecopy=0&preload=true]?person_id=0"}],i=0;i<preLoadItems.length;i++)try{var pageId=preLoadItems[i].pageId,soprotocol=preLoadItems[i].soprotocol,winName=window.name,pageName=(""!=winName&&(winName+="-"),winName+=pageId,soprotocol.substring(0,soprotocol.indexOf("[")));Dialog._dialogName=pageName,Dialog.openInline(pageName,pageId,"soprotocol:"+soprotocol,!0)}catch(ex){Dialog.preLoadLock=!1,alert(ex)}Dialog.preLoadLock=!1},_this.open=function(pageId,soprotocol,closeCallback,isModal,isResizable,showMenu,showStatus){if("appointment"==(pageName=soprotocol.substring(0,soprotocol.indexOf("[")).toLowerCase())){var appIdIndex=soprotocol.indexOf("appointment_id=")+15;if(15<=appIdIndex){appIdIndex=+soprotocol.substring(appIdIndex).split("&")[0];if(0<appIdIndex)return void SuperOffice.CalendarManager.OpenAppointment(appIdIndex)}SuperOffice.CalendarManager.NewAppointment()}else{if(0<$("#minimized_"+pageName+"_inlinedialogContainer").length){if(!confirm(ResourceUtils.GetResourceText("[SR_DIALOG_ALREADY_OPEN]")))return;this.maximize(pageName),this.getRootWindow().Dialog.close(this.getRootWindow().Dialog.currentLevel)}else if($("#inlinedialogContainer").is(":visible")){if(!g_clientOptions.Debug)return;if(!confirm("(DEBUG): "+pageId+" would like to take over the dialog? (DEVELOPER): Please don't execute Dialog.close() after opening a new dialog using UIHelper.getOpener().Dialog.open... Close first, then open."))return}if(!dialogLock)try{dialogLock=!0;var winName=window.name,pageName=(""!=winName&&(winName+="-"),winName+=pageId,debug.trace("Dialog name: "+winName,"Dialog"),soprotocol.substring(0,soprotocol.indexOf("[")));soprotocol=(soprotocol=(soprotocol=soprotocol.replace("usesuperstatecopy=true","superstatecopy="+this.getDialogLevel())).replace("[dialog=stop","[dialogwinname="+winName+"&dialog=stop&SOUNIQUEID="+UIHelper.GetMainPageWindow().$("#SO_UNIQUE_ID").val()+"&fakeGET=true")).replace("&","&"),(this._isModal=isModal)&&(this._modalReturnObject=new ReturnObject(0,null,"")),this._closeCallback=closeCallback,this._dialogName=pageName,this.openInline(pageName,pageId,"soprotocol:"+soprotocol),dialogLock=!1}catch(ex){alert(ex),dialogLock=!1,Dialog.Information("[SR_FDLG_WARNING]",ex.message,"warning"),debug.trace("Dialog.open exception: "+ex.message,"Dialog")}}},_this.close=function(level){if(this.childDialog&&void 0!==level&&getIframeWindow(this.childDialog.iframe).IFrameClose(level),!(level>this.getDialogLevel())){this.removeCrumb();var level=UIHelper.GetOpener().$("#inlinedialogContainer");if(0!=level.length&&(level.find("#inlinedialogfrm"+UIHelper.GetOpener().Dialog._dialogName).hide(),level.find("#inlinedialogfrm"+UIHelper.GetOpener().Dialog._dialogName).siblings("iframe").hide(),level.hide(),$(window).trigger("unload"),g_isMainpage||PageEventHandler.clearAllEvents(),UIHelper.GetOpener().g_isMainpage&&UIHelper.GetOpener().Dialog.unLockMainWindow(),UIHelper.GetOpener().Dialog._isModal)){level=UIHelper.GetOpener().Dialog.getCloseCallback();try{UIHelper.GetOpener().Dialog.evalCallback(level)}catch(ex){alert("Dialog callback execution went horribly wrong: "+ex.message)}UIHelper.GetOpener().Dialog.clearCloseCallback()}1===this.getDialogLevel()&&(level=UIHelper.GetOpener().Dialog,UIHelper.GetMainPageWindow().$(".scilDialogHeader").last().css({zIndex:level.scilDialogHeaderZIndex}),UIHelper.GetMainPageWindow().$(".SCILLockLayerMain").last().css({zIndex:level.scilLockLayerZIndex})),this.getRootWindow().Dialog.currentLevel=this.getRootWindow().Dialog.currentLevel-1,-1<this.getRootWindow().Dialog.currentLevel&&this.getRootWindow().Dialog.onResize()}},_this.closeWithCallback=function(){try{Dialog.close(),UIHelper.GetOpener().Dialog._isModal||UIHelper.GetOpener().Dialog.evalCallback(UIHelper.GetOpener().Dialog.getCloseCallback())}catch(ex){}},_this.setDialogWindow=function(dialogWindow){this._dialogWindow=dialogWindow},_this.getDialogWindow=function(){return this._dialogWindow},_this.setDialogName=function(dialogName){this._dialogName=dialogName},_this.getDialogName=function(){return this._dialogName},_this.setDialogPageName=function(pageName){this._pageName=pageName},_this.getDialogPageName=function(){return this._pageName},_this.setChildDialogs=function(childDialogs){this._childDialogs=childDialogs},_this.getChildDialogs=function(){return this._childDialogs},_this.clearCloseCallback=function(){this._closeCallback=null},_this.setCloseCallback=function(func){this._closeCallback=func},_this.appendCloseCallback=function(func){null!=this._closeCallback&&"undefined"!=this._closeCallback?this._closeCallback+=func:this._closeCallback=func},_this.getCloseCallback=function(){return this._closeCallback},_this.getReturnValue=function(){return null!=this._modalReturnObject?this._modalReturnObject.getValue():null},_this.getReturnStatus=function(){return null!=this._modalReturnObject?this._modalReturnObject.getStatus():0},_this.getReturnContext=function(){var context;return null==this._modalReturnObject||null==(context=this._modalReturnObject.getContext())?"":context},_this.setReturnObject=function(status,val,context){this._modalReturnObject=new ReturnObject(status,val,context)},_this.setParentReturnObject=function(status,val,context){debug.trace("setParentReturnObject: "+val,"Dialog"),(this.inLineDialogIsOpen?Dialog:UIHelper.GetOpener().Dialog).setReturnObject(status,val,context)},_this.getWindowSize=function(pageId){return SuperOffice.Dialog.Size.GetWindowSize(pageId)},_this.getDialogLevel=function(){for(var count=0,tmp=window;tmp.self!==window.top;)try{tmp=tmp.parent,count++}catch(e){break}return count},_this.openInvitation=function(){setTimeout(SuperOffice.Notification.openNotifications,2e3)},window.IFramePageUpdate=function(arg,context){QueuedPageUpdate(arg,context)},window.IFrameClose=function(level){Dialog.close(level,!0)},window.IFrameRefresh=function(){location.reload(!0)},window.IFrameOnLoad=function(f){console.log("IFrameOnLoad fired"),PageEventHandler.addEvent(EventType.ONPAGELOAD,"iframeLoad",f)},_this.createInLineDialog=function(){this.currentInLineDialog=new ResizeableDialog({Title:"Test",Layout:{Class:"inlinedialog",Left:"50px",Top:"50px",Height:"600px",Width:"800px",MinHeight:150,MinWidth:270,MaxHeight:600,DisplayShadow:!0,MaxWidth:0},DialogStyle:{CloseButton:!0,MinimizeButton:!0},Content:{Source:"",Element:null},Callbacks:{OnClose:"Dialog.onInLineDialogClose"},HostElement:document.forms[0]})},_this.onInLineDialogClose=function(){},_this.ShowInLineDialog=function(html){this.currentInLineDialog.options.Content.Source=html,this.currentInLineDialog.Show(),this.inLineDialogIsOpen=!0},_this.UpdateInLineDialog=function(html){this.currentInLineDialog.contentLayer.innerHTML=html},_this.CheckOpenDialogs=function(){try{for(var dialogslength=Dialog._dialogsAlive.getLength(),i=dialogslength-1;0<=i;i--){var dc=Dialog._dialogsAlive.getByIdx(i);(null==dc&&void 0===dc||null!=dc.WindowPointer)&&void 0!==dc.WindowPointer&&!dc.WindowPointer.closed||(Dialog.RemoveDialogContext(dc.WindowName),window.clearInterval(this.intervalCode),eval(dc.OnCloseScript))}}catch(e){debug.trace("Warning: "+e.message,"Dialog")}},_this.SetOnCloseScript=function(script){var dc;this.inLineDialogIsOpen||null==UIHelper.GetOpener()||!UIHelper.GetOpener().Dialog||void 0===(dc=UIHelper.GetOpener().Dialog._dialogsAlive.get(window.name))&&null==dc||(dc.OnCloseScript=script)},_this.AddDialogContext=function(id,windowPointer){this._dialogsAlive.exist(id)&&this.RemoveDialogContext(id);var dialogContext=new _DialogContext;this._dialogsAlive.add(id,dialogContext),dialogContext.WindowName=id,dialogContext.WindowInterval=window.setInterval(Dialog.CheckOpenDialogs,250),debug.trace("AddedDialogContext: "+dialogContext.WindowInterval,"Dialog"),dialogContext.WindowPointer=windowPointer,dialogContext.OnCloseScript=""},_this.RemoveDialogContext=function(id){debug.trace("RemoveDialogContext: "+id,"Dialog");id=this._dialogsAlive.get(id);(null==id&&void 0===id||null!=id.WindowPointer)&&void 0!==id.WindowPointer&&!id.WindowPointer.closed||(window.clearInterval(id.WindowInterval),this._dialogsAlive.remove(id.WindowName))},_this.Information=function(title,text,dialogType){void 0===dialogType&&(dialogType="none");title=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.Information","",title,text,dialogType);Dialog.displayInlineModalDialog(title,"")},_this.OneButtonDialog=function(title,text,dialogType,callback){void 0===dialogType&&(dialogType="none");title=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.OneButtonDialog","",title,text,dialogType,callback,!1);Dialog.displayInlineModalDialog(title,"")},_this.OneButtonWithCancelDialog=function(title,text,dialogType,callback,useYesNo){void 0===dialogType&&(dialogType="none");title=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.OneButtonDialog","",title,text,dialogType,callback,!0,useYesNo);Dialog.displayInlineModalDialog(title,"")},_this.ConfirmSuggestNextStage=function(nextStageInfo,callback){var heading=(heading=ResourceUtils.GetResourceText("[SR_SALESGUIDE_FOR]")).replace("%s",nextStageInfo.SaleName),text=ResourceUtils.GetResourceText("[SR_SALE_WANNA_ADVANCE_SALE]"),newContext=(text=(text=(text=text.replace('"%s"?','"%x"?')).replace("%s",nextStageInfo.CurrentStageName)).replace("%x",nextStageInfo.NextStageName),new Object);newContext.callback=callback,newContext.nextStageInfo=nextStageInfo,Dialog.YesNoHeading(ResourceUtils.GetResourceText("[SR_SALESGUIDE_ADVANCE_STAGE_CAPTION]"),text,"Question","","NextStageCallback(res)",newContext,heading)},_this.ConfirmSuggestNextStatus=function(nextStatusInfo,callback){var heading=(heading=ResourceUtils.GetResourceText("[SR_PROJECT_GUIDE_FOR]")).replace("%s",nextStatusInfo.ProjectName),text=ResourceUtils.GetResourceText("[SR_PROJECT_WANNA_ADVANCE_PROJECT]"),newContext=(text=(text=(text=text.replace('"%s"?','"%x"?')).replace("%s",nextStatusInfo.CurrentStatusName)).replace("%x",nextStatusInfo.NextStatusName),new Object);newContext.callback=callback,newContext.nextStatusInfo=nextStatusInfo,Dialog.YesNoHeading(ResourceUtils.GetResourceText("[SR_PROJECTGUIDE_ADVANCE_STATUS_CAPTION]"),text,"Question","","SuperOffice.Guide.Project.NextStatusCallback(res)",newContext,heading)},_this.ConfirmCreateSuggestedAppointment=function(salesguidename,apptitle,date,suggestedappointmentId,saleId,callback){var src=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.ConfirmCreateSuggestedAppointment","",salesguidename,apptitle,date,"SetConfirmCreateSuggestedAppointmentCallBack"),newContext=new Object;newContext.callback=callback,newContext.dings="suggestedappointment_id="+suggestedappointmentId.toString()+"&sale_id="+saleId.toString(),""==src?OpenAppointment(null,"appointment.main[new=true]?appointment_id=0&"+newContext.dings,function(){callback&&eval("'"+callback+"'")}):Dialog.displayInlineModalDialog(src,newContext)},_this.openExt=function(pageId,soprotocol,closeCallback,isModal,isResizable,showMenu){if(!dialogLock)try{dialogLock=!0;var existingDialog,dialogInfo,newWin,childDialog,wnd,winName=window.name;""!=winName&&(winName+="_"),winName+=pageId,this.containsChildDialog(winName)&&this.removeChildDialog(winName),this.containsChildDialog(winName)?null!=(existingDialog=this.getChildDialog(winName))&&window.focus&&null!=(wnd=existingDialog.getDialogWindow()).focus&&wnd.focus():(debug.trace("Dialog name: "+winName,"Dialog"),null==isModal&&(isModal=!1),menu=(showMenu=null==showMenu?!1:showMenu)?"yes":"no",resizable=(isResizable=null==isResizable?!0:isResizable)?"yes":"no",dialogInfo=SuperOffice.Dialog.Size.GetDialogInfo(pageId),soprotocol=(soprotocol=(soprotocol=soprotocol.replace("usesuperstatecopy=true","superstatecopy="+this.getDialogLevel())).replace("[dialog=stop","[dialogwinname="+winName+"&dialog=stop")).replace("&","&"),newWin=window.open("Default.aspx?"+soprotocol,winName,"toolbar=no,location=no,directories=no,status=yes,menubar="+menu+",dependent=yes;scrollbars=auto,resizable="+resizable+",width="+dialogInfo.Size.Width+",height="+dialogInfo.Size.Height),isModal&&(this._closeCallback=closeCallback,this._modalReturnObject=new ReturnObject(0,null,""),this.modalWnd=newWin),(childDialog=new _Dialog).setDialogName(newWin.name),childDialog.setDialogWindow(newWin),childDialog.setCloseCallback(closeCallback),this.containsChildDialog(winName)||this._childDialogs.push(childDialog),debug.trace("Dialog is modal"+isModal,"Dialog"),isModal&&(this.intervalCode=window.setInterval(Dialog.WaitForClose,500)),window.focus&&null!=(wnd=childDialog.getDialogWindow())&&wnd.focus(),Dialog.AddDialogContext(winName,newWin)),dialogLock=!1}catch(ex){dialogLock=!1,Dialog.Information("[SR_FDLG_WARNING]","A pop-up blocker has been detected.<br/> Please allow pop-ups before continuing.","warning"),debug.trace("Dialog.open exception: "+ex.message,"Dialog")}},_this.ShowHelp=function(isMainPage){var pageId=SuperOffice.Environment.CurrentMainPageId===g_currentPageId?SuperOffice.Environment.SoProtocol:g_currentPageId,pageId=SuperOffice.Util.UrlDispatcher.GetHelpUrl(pageId);window.open(pageId,"SoHelpWindow","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=auto,resizable=yes,width=1024px,height=600px")},_this.ShowHelpFromIndex=function(index){index=SuperOffice.Util.UrlDispatcher.GetHelpUrlByIndex(index);window.open(index,"SoHelpWindow","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=auto,resizable=yes,width=1024px,height=600px")},_this.YesNo=function(title,text,dialogType,checkBoxText,callBack,context){title=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.YesNo","",title,text,dialogType,checkBoxText,callBack);Dialog.displayInlineModalDialog(title,context)},_this.YesNoHeading=function(title,text,dialogType,checkBoxText,callBack,context,heading){title=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.YesNoHeading","",title,text,dialogType,checkBoxText,callBack,heading);Dialog.displayInlineModalDialog(title,context)},_this.YesNoCancel=function(title,text,dialogType,callBack,context){title=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.YesNoCancel","",title,text,dialogType,callBack);Dialog.displayInlineModalDialog(title,context)},_this.ThreeButton=function(title,text,buttonText1,buttonText2,dialogType,context,callBack){title=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.ThreeButton","",title,text,buttonText1,buttonText2,dialogType,context,callBack);Dialog.displayInlineModalDialog(title,context)},_this.OkNormalButton=function(title,text,buttonText1,buttonText2,dialogType,context,callBack){title=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.OkNormalButton","",title,text,buttonText1,buttonText2,dialogType,context,callBack);Dialog.displayInlineModalDialog(title,context)},_this.OkNormalButtonWithCancel=function(title,text,buttonText1,buttonText2,dialogType,context,callBack){title=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.OkNormalButtonWithCancel","",title,text,buttonText1,buttonText2,dialogType,context,callBack);Dialog.displayInlineModalDialog(title,context)},_this.ButtonDialogWithCancel=function(title,text,dialogType,context,callBack){var buttonTexts="";if(4<arguments.length)for(var t=5;t<arguments.length;++t)5<t&&(buttonTexts+="|$|"),buttonTexts+=AjaxMethodDispatcher.paramEncode(arguments[t]);title=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.ButtonDialogWithCancel","",title,text,dialogType,context,callBack,buttonTexts);Dialog.displayInlineModalDialog(title,context)},_this.ConfirmDelete=function(linkHint,enableYesToAll,callBack,noConfirm){void 0!==noConfirm&&null!=noConfirm||(noConfirm=!1);var src=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.ConfirmDelete","",linkHint,enableYesToAll,callBack),returnObject,fn;"[MESSAGE]ForceConfirmation=false"==src||noConfirm?(returnObject=new ReturnObject(1,"",""),fn=callBack+"(returnObject, '', 'sendemail');",eval(fn)):"[MESSAGE]ERROR"==src?console.error("Error making dialog, let a grown-up know."):src.startsWith("[MESSAGE]")||Dialog.displayInlineModalDialog(src,"ConfirmDelete")},_this.DeleteUser=function(archiveControl,callBack){var aid,src,archiveControl=archiveControl.getSelectedRows();0<archiveControl.length&&(archiveControl=archiveControl[0].attributes.rowtype.value,aid=parseInt(SuperOffice.SoHelper.getValueFromLinkHint(archiveControl,"associate"),10),archiveControl=parseInt(SuperOffice.SoHelper.getValueFromLinkHint(archiveControl,"person"),10),0<aid?(src=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.DeleteUser","",aid,callBack),Dialog.displayInlineModalDialog(src,{AssociateId:aid,PersonId:archiveControl})):0<archiveControl&&Dialog.YesNo("[SR_ADMIN_DELETE_CONTACT_TITLE]","[SR_ADMIN_DELETE_CONTACT_DESCRIPTION]","warning","",callBack,{AssociateId:0,PersonId:archiveControl}))},_this.DeleteOtherUser=function(archiveControl,callBack){var userName,text,archiveControl=archiveControl.getSelectedRows();0<archiveControl.length&&(archiveControl=archiveControl[0].attributes.rowtype.value,archiveControl=parseInt(SuperOffice.SoHelper.getValueFromLinkHint(archiveControl,"associate"),10),userName=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.Admin.AdminOtherUserDataHandler.GetUserName","",archiveControl),text=(text=ResourceUtils.GetResourceText("[SR_ADMIN_DELETE_SYSTEMUSER_WARNING]")).replace("{0}",userName),0<archiveControl)&&Dialog.YesNo("[SR_ADMIN_DELETE_OTHER_USER]",text,"warning","",callBack,{AssociateId:archiveControl})},_this.ConfirmDeleteRecurring=function(appointmentId,task,enableYesToAll,ignoreEmail,callBack){appointmentId=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.ConfirmDeleteRecurringAppointment","",appointmentId,task,enableYesToAll,ignoreEmail,callBack);Dialog.displayInlineModalDialog(appointmentId,"RecurrenceConfirm")},_this.ConfirmDeleteRecurringWithContext=function(contextObject,task,enableYesToAll,ignoreEmail,callBack){task=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.ConfirmDeleteRecurringAppointment","",contextObject.AppointmentId,task,enableYesToAll,ignoreEmail,callBack);contextObject.DialogContext="RecurrenceConfirm",Dialog.displayInlineModalDialog(task,contextObject)},_this.ConfirmDeleteRecurringWithEmail=function(appointmentId,task,enableYesToAll,callBack){appointmentId=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.ConfirmDeleteRecurringAppointmentWithEmail","",appointmentId,task,enableYesToAll,callBack);Dialog.displayInlineModalDialog(appointmentId,"RecurrenceConfirm")},_this.ConfirmUpdateAppointmentSendEmail=function(appointmentId,task,enableYesToAll,isLoggedOnMailServer,context,callBack,displayNeverShowAgainCheckbox){appointmentId=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Dialog.ConfirmUpdateAppointmentSendEmail","",appointmentId,task,enableYesToAll,isLoggedOnMailServer,callBack,displayNeverShowAgainCheckbox);Dialog.displayInlineModalDialog(appointmentId,context)},_this.displayInlineModalDialog=function(src,context){if(""!=src){var inlineDialog=new InlineDialog;inlineDialog._context=context;try{(this._currentInlineModalDialog=inlineDialog).Display(src,"Dialog.onInlineDialogClose")}catch(e){}}},_this.inlineDialogCallback=function(dlg,callback,status,checkBoxValues,radioValues){var val=null,action=(void 0!==checkBoxValues&&null!=checkBoxValues||(checkBoxValues=""),void 0!==radioValues&&null!=radioValues||(radioValues=""),0<checkBoxValues.length&&(val=checkBoxValues[0]),0<radioValues.length&&(val=radioValues[0]),"object"==typeof dlg._context?dlg._context.Action:dlg._context),returnObject=("ConfirmDelete"==action&&"1"==status&&"true"==checkBoxValues&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserPreferences.ToggleBool","","Associates","DontAskAgainDeleteDialog"),new ReturnObject(status,val,dlg._context)),fn,fn=callback.endsWith(")")?callback:callback+"(returnObject, checkBoxValues, radioValues);";eval(fn)},_this.onInlineDialogClose=function(dlg){},_this.CloseMsgBox=function(){null!=Dialog._currentMsgBox&&Dialog._currentMsgBox.hide()},_this.confirmDeleteRecurring=function(text,task,appointmentId,callBack){this.openModal("./WebParts/Dialogs/Appointment/RecurrenceConfirm.aspx?task="+task+"&msgText="+escape(text)+"&appid="+appointmentId,"ConfirmRecurrence",callBack,"450px","230px")},_this.disableWindow=function(wnd){null==this._disableWindowLockLayer&&(this._disableWindowLockLayer=$(document.createElement("DIV")),this._disableWindowLockLayer.css("position","absolute"),this._disableWindowLockLayer.setClass("MMLockLayer"),this._disableWindowLockLayer.attr("id","MMLockLayer"),$(wnd.document.body).append(this._disableWindowLockLayer),this._disableWindowBusyIndicator.showBusyTextLayer())},_this.enableWindow=function(wnd){try{null!=this._disableWindowLockLayer&&(this._disableWindowBusyIndicator.hideBusyTextLayer(),$(this._disableWindowLockLayer).remove(),this._disableWindowLockLayer=null)}catch(e){}},_this.setDisableLayerSize=function(){null!=this._disableWindowLockLayer&&(this._disableWindowLockLayer.style.height=getWindowRectangle().getY()+"px")},_this.alert=function(){},_this.openModal=function(url,name,callBack,width,height){this._closeCallback=callBack,this._modalReturnObject=new ReturnObject(0,null,""),this.modalWnd=window.open(url,name,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=auto,resizable=yes,width="+width+",height="+height+",modal=yes"),this.intervalCode=window.setInterval(Dialog.WaitForClose,500),window.focus&&this.modalWnd.focus()},_this.openModalSoProtocol=function(soprotocol,name,callBack,width,height){this._closeCallback=callBack,this._modalReturnObject=new ReturnObject(0,null,""),this.modalWnd=window.open(soprotocol,name,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=auto,resizable=yes,width="+width+",height="+height+",modal=yes"),this.intervalCode=window.setInterval(Dialog.WaitForClose,500)};var g_lockLevel=0;function ReturnObject(status,value,context){this._status=status,this.setValue(value),this._context=context}_this.lockMainWindow=function(useDim){this.focusWnd=window,this.lockLayerMain=document.getElementById("SOLockLayerMain"),null==this.lockLayerMain&&(this.lockLayerMain=document.createElement("DIV"),this.lockLayerMain.style.zIndex=198,this.lockLayerMain.id="SOLockLayerMain",document.body.appendChild(this.lockLayerMain)),this.lockLayerMain.className=(1==useDim?"DialogDimLayer ":"")+"LockLayer",document.body.scroll="no"},_this.unLockMainWindow=function(){try{null!=this.lockLayerMain&&($(this.lockLayerMain).off("mousedown"),$(this.lockLayerMain).off("mouseup"),$(this.lockLayerMain).fadeOut(),document.body.removeChild(this.lockLayerMain),document.body.scroll="auto",this.lockLayerMain=null)}catch(e){}},_this.focusModalDialog=function(){try{window.focus&&this.focusWnd.focus()}catch(e){}},_this.WaitForClose=function(){try{Dialog.modalWnd.closed&&(window.clearInterval(Dialog.intervalCode),debug.trace("Dialog intervalcode:"+Dialog.intervalCode,"Dialog"),""!=Dialog._closeCallback?(debug.trace("Dialog._closeCallback: "+Dialog._closeCallback,"Dialog"),f=new Function("res",Dialog._closeCallback+"(res);"),Dialog._closeCallback="",f(Dialog._modalReturnObject)):""!=Dialog._ajaxCallBack&&(f=new Function("val","context",Dialog._ajaxCallBack+"(val, context);"))(Dialog._ajaxVal,Dialog._ajaxContext))}catch(e){var f;Debug.trace("WaitForClose failed: "+e.message,"Dialog"),window.clearInterval(Dialog.intervalCode),""!=Dialog._closeCallback&&(f=new Function("res",Dialog._closeCallback+"(res);"))(Dialog._modalReturnObject)}},_this.isAlive=function(){try{this._dialogWindow.getDialogName();return!0}catch(e){return!1}},_this.closeChilds=function(){for(var i=0;i<this._childDialogs.length;i++)this._childDialogs[i].getDialogWindow().close()},_this.closeOnReady=function(){null==UIHelper.GetOpener()||"unknown"==typeof UIHelper.GetOpener().g_pendingRequest||null!=UIHelper.GetOpener().PendingRequest&&UIHelper.GetOpener().PendingRequest.isReady()?(debug.trace("**close**","Dialog"),setTimeout("window.close();",0)):(debug.trace("**try again close...**","Dialog"),setTimeout("Dialog.closeOnReady();",100))},_this.getChildDialogCallback=function(){var opnertmp=UIHelper.GetOpener(),openerCallBack="";return openerCallBack=null!=opnertmp&&null!=(opnertmp=opnertmp.Dialog.getChildDialog(Dialog.getDialogName()))&&opnertmp.getCloseCallback()?opnertmp.getCloseCallback():openerCallBack},_this.evalCallback=function(callback,childDialogName){Debug.trace("Evaluates callback: "+callback,"Dialog"),"function"==typeof callback?callback():callback&&(null==Dialog._modalReturnObject||""==Dialog._modalReturnObject||callback.endsWith(")")||callback.endsWith(";")||(callback+="(res)"),new Function("res",callback)(Dialog._modalReturnObject))},_this.getChildDialog=function(childDialogName){for(var dialog,i=0;i<this._childDialogs.length;i++)if((dialog=this._childDialogs[i]).getDialogName()==childDialogName)return dialog;return null},_this.containsChildDialog=function(childDialogName){for(var i=0;i<this._childDialogs.length;i++)if(this._childDialogs[i].getDialogName()==childDialogName)return!0;return!1},_this.removeChildDialog=function(childDialogName){for(var dialog,newArr=new Array,i=0;i<this._childDialogs.length;i++)(dialog=this._childDialogs[i]).getDialogName()!=childDialogName&&newArr.push(dialog);this._childDialogs=newArr},_this.unload=function(){Debug.trace("Dialog unload: "+Dialog.name,"Dialog");try{var openerDialog;null!=UIHelper.GetOpener()&&null!=(openerDialog=UIHelper.GetOpener().Dialog)&&openerDialog.removeChildDialog(this._dialogName)}catch(ex){Debug.trace("Dialog unload error: "+ex,"Dialog")}},_this.toString=function(){for(var s=this._dialogName+"\n\t",i=0;i<this._childDialogs.length;i++)s+=this._childDialogs[i].toString();return s},_this.toHTML=function(){for(var s=this._dialogName+"<br/>",i=0;i<this._childDialogs.length;i++)s+=this._childDialogs[i].toHTML();return s},_this.resize=function(){try{var rect=getWindowRectangle(),container=$("#container");container.setTop(0),container.setLeft(0),container.setHeight(rect.getY()),container.setWidth(rect.getX())}catch(e){}},_this.resizeWidth=function(){var container=$("#container");if(null==container)return!1;var rect=getWindowRectangle();container.setTop(0),container.setLeft(0),container.setWidth(rect.getX()),"Firefox"==g_clientOptions.BrowserIdent&&container.setStyle({overflow:"auto",height:""})},_this=ReturnObject.prototype,_this.setStatus=function(status){this._status=status},_this.setValue=function(val){this._value=JsonHelper.toJSON(val)},_this.setContext=function(val){this._context=val},_this.getStatus=function(){return this._status},_this.getValue=function(){var json=this._value;return eval("("+json+")")},_this.getContext=function(){return this._context};class _DialogManager{constructor(){this._counter=0,this._dlgList=new Array,this._zIndex=199}initialize(){}getNextId(){return this._counter++,this._counter}getZindex(){return this._zIndex++,this._zIndex}addDialog(elem){this._dlgList.push(elem.id)}removeDialog(elem){for(var t=0;t<this._dlgList.length;++t)this._dlgList[t]==elem.id&&this._dlgList.splice(t,1)}getDialogCount(){return this._dlgList.length}moveToFront(elem){for(var dlgZIndex,zIndex=elem.getStyle("zIndex"),newZindex=zIndex,t=0;t<this._dlgList.length;++t)this._dlgList[t]!=elem.id&&null!=$(this._dlgList[t])&&newZindex<(dlgZIndex=$(this._dlgList[t]).getStyle("zIndex"))&&(newZindex=dlgZIndex);zIndex<newZindex&&(elem.setStyle({zIndex:parseInt(newZindex,10)+1}),this._zIndex=newZindex)}}var DialogManager=new _DialogManager;class DialogBase{constructor(options){this.options=options,this._idNumber=++g_dialogCounter,this.showCloseButton=!1,this.showMinimizeButton=!1,null!=options&&(this.onCloseCallback=this.getValue(options.Callbacks.OnClose,null),this.onOpenCallback=this.getValue(options.Callbacks.OnOpen,null),this.onResizeCallback=this.getValue(options.Callbacks.OnResize,null),this.onMinimizeCallback=this.getValue(options.Callbacks.OnMinimize,null),this.onRestoreCallback=this.getValue(options.Callbacks.OnRestore,null),this.onResizeDoneCallback=this.getValue(options.Callbacks.OnResizeDone,null),this.onMoveDoneCallback=this.getValue(options.Callbacks.OnMoveDone,null),this.className=this.getValue(this.options.Layout.Class,""),""==this.className&&(this.className="defaultdialog"),this.displayShadow=this.getValue(this.options.Layout.DisplayShadow,!1)),this.isMinimized=!1,this.restoreHeight=0,this.headerClassName=this.className+"_header",this.contentClassName=this.className+"_content",this.closeButtonClassName=this.className+"_closebutton",this.minimizeButtonClassName=this.className+"_minbutton",this.resizeGripClassName=this.className+"_resizegrip","admin"==g_clientOptions.SubClient?(this.closeImage="../Images/System/Web/Close.png",this.closeImageHover="../Images/System/Web/Close.png",this.minimizeImage="../Images/System/x_minimize.png",this.minimizeImageHover="../Images/System/x_minimize_hover.png"):(this.closeImage="Images/System/Web/Close.png",this.closeImageHover="Images/System/Web/Close.png",this.minimizeImage="Images/System/x_minimize.png",this.minimizeImageHover="Images/System/x_minimize_hover.png")}Show(title){this.dlgLayer=$(document.createElement("DIV")),this.dlgLayer.attr("id","dialogContainer"+DialogManager.getNextId()),this.dlgLayer.setClass(this.className),this.setPositionAndDimension(this.dlgLayer,this.getValue(this.options.Layout.Left,"10px"),this.getValue(this.options.Layout.Top,"10px"),this.getValue(this.options.Layout.Width,"200px"),this.getValue(this.options.Layout.Height,"200px")),this.createContentPlaceholder(),this.dlgLayer.setStyle({backgroundColor:"#AAAAAA",overflow:"hidden",zIndex:DialogManager.getZindex()});var that=this;this.dlgLayer.on("mousedown",function(e){DialogManager.moveToFront(that.dlgLayer)}),DialogManager.addDialog(this.dlgLayer)}setVisible(visible){visible?this.dlgLayer.show():this.dlgLayer.hide()}onClose(e){return this.Close(),JsHelper.CancelBubble(e)}Close(){null!=this.onCloseCallback&&("function"==typeof this.onCloseCallback?this.onCloseCallback.apply(null,[this.dlgLayer.attr("id")]):new Function("id",this.onCloseCallback+"(id)")(this.dlgLayer.attr("id"))),this.dlgLayer.hide(),DialogManager.removeDialog(this.dlgLayer),this.dlgLayer.remove(),this.dlgLayer=null}GetLeft(){return this.dlgLayer.getLeft()}GetTop(){return this.dlgLayer.getTop()}GetWidth(){return this.dlgLayer.getWidth()}GetHeight(){return this.dlgLayer.getHeight()}createContentPlaceholder(){var width=this.dlgLayer.getWidth();this.contentLayer=$(document.createElement("DIV")),this.contentLayer.setStyle({position:"absolute",overflow:"hidden",top:"0px",left:"0px",width:width+"px",height:this.dlgLayer.getHeight()+"px"}),this.contentLayer.attr("id","dialogContent"+this._idNumber),this.contentLayer.setClass(this.contentClassName),null!=this.getValue(this.options.Content.Source,null)?this.contentLayer.html(this.options.Content.Source):this.contentLayer.append(this.options.Content.Element),this.dlgLayer.append(this.contentLayer)}getContentLayer(){return this.contentLayer}getValue(obj,defaultValue){return null==obj?defaultValue:obj}setPositionAndDimension(elem,x,y,w,h){elem.setStyle({position:"absolute",top:this.getValue(this.options.Layout.Top,y),left:this.getValue(this.options.Layout.Left,x),width:this.getValue(this.options.Layout.Width,w),height:this.getValue(this.options.Layout.Height,h)})}setPosition(elem,x,y){elem.setStyle({position:"absolute",left:x,top:y})}setDimension(elem,width,height){elem.setStyle({width:width,height:height})}beforeDrag(){JsHelper.DisableSelectTextOnTarget(document),JsHelper.DisableSelectTextOnTarget(this.dlgLayer),JsHelper.DisableSelectTextOnTarget(this.contentLayer)}afterDrag(){JsHelper.EnableSelectTextOnTarget(document),JsHelper.EnableSelectTextOnTarget(this.dlgLayer),JsHelper.EnableSelectTextOnTarget(this.contentLayer)}}class HeaderDialog extends DialogBase{constructor(options){super(options),this._dragStartX=0,this._dragStartY=0,this._clientWidth=0,this._clientHeight=0,this.showCloseButton=this.getValue(this.options.DialogStyle.CloseButton,!0),this.showMinimizeButton=this.getValue(this.options.DialogStyle.MinimizeButton,!0)}Show(title){super.Show(title),this.dlgHeader=$(document.createElement("DIV")),this.dlgHeader.attr("id",this.dlgLayer.attr("id")+"Header"),this.dlgHeader.setClass(this.headerClassName),this.dlgHeader.setStyle({zIndex:10}),this.setPosition(this.dlgHeader,"0px","0px"),this.dlgLayer.append(this.dlgHeader);$(this.getValue(this.options.HostElement,document.body)).append(this.dlgLayer),this.setDimension(this.dlgHeader,this.dlgLayer.getWidth()-2+"px",this.getValue(this.options.Layout.HeaderHeight,"28px"));var title=this.dlgHeader.getHeight(),that=(this.setPosition(this.contentLayer,"0px",title+"px"),this.setDimension(this.contentLayer,this.dlgLayer.getWidth()+"px",this.dlgLayer.getHeight()-title+"px"),this.headerTitle=$(document.createElement("SPAN")),this.headerTitle.attr("id",this.dlgLayer.attr("id")+"HeaderTitle"),this.headerTitle.innerHTML=this.getValue(this.options.Title,""),this.dlgHeader.append(this.headerTitle),this);this.showCloseButton&&(this.closeButton=$(document.createElement("IMG")),this.closeButton.attr("id",this.dlgLayer.attr("id")+"CloseButton"),this.closeButton.attr("src",this.closeImage),this.closeButton.setClass(this.closeButtonClassName),this.closeButton.setStyle({position:"absolute"}),this.addElementToHeader(this.closeButton),this.closeButton.on("mouseup",function(event){that.onClose(event)}),UIHelper.setHoverImageOnElement($(this.closeButton),this.closeImage,this.closeImageHover,this.closeImage)),this.showMinimizeButton&&(title=10,this.showCloseButton&&(title=title+this.closeButton.getWidth()+2),this.minimizeButton=$(document.createElement("IMG")),this.minimizeButton.attr("id",this.dlgLayer.attr("id")+"MinButton"),this.minimizeButton.attr("src",this.minimizeImage),this.minimizeButton.setClass(this.minimizeButtonClassName),this.minimizeButton.setStyle({position:"absolute",right:title+"px"}),this.addElementToHeader(this.minimizeButton),this.minimizeButton.on("mouseup",function(){that.isMinimized?(that.isMinimized=!1,that.dlgLayer.setHeight(that.restoreHeight),that.contentLayer.show(),null!=that.dlgResizeGrip&&that.dlgResizeGrip.show(),null!=that.onRestoreCallback&&("function"==typeof that.onRestoreCallback?that.onRestoreCallback.apply(null,[that.dlgLayer.attr("id")]):new Function("id",that.onRestoreCallback+"(id)")(that.dlgLayer.attr("id")))):(that.restoreHeight=that.dlgLayer.getHeight(),that.isMinimized=!0,null!=that.dlgResizeGrip&&that.dlgResizeGrip.hide(),that.contentLayer.hide(),that.dlgLayer.setHeight(that.dlgHeader.getHeight()),null!=that.onMinimizeCallback&&("function"==typeof that.onMinimizeCallback?that.onMinimizeCallback.apply(null,[that.dlgLayer.attr("id")]):new Function("id",that.onMinimizeCallback+"(id)")(that.dlgLayer.attr("id"))))}),UIHelper.setHoverImageOnElement($(that.minimizeButton),that.minimizeImage,that.minimizeImageHover,that.minimizeImage)),JsHelper.DisableSelectTextOnTarget(this.dlgHeader),$(this.dlgHeader).on("mousedown",function(e){that.onInitDrag(e)})}addElementToHeader(elem){elem.noDrag=!0,this.dlgHeader.append(elem)}onInitDrag(e){if(this.beforeDrag(),so_defined($(JsHelper.GetHtmlElement(e)).noDrag))return!1;new DragDrop(this,{DragDropStartMethod:this.onDragStart,DragDropEndMethod:this.onDragEnd,DragDropMoveMethod:this.onDragMove,DragDropCancelMethod:this.onCancelDrag,DragElement:this.dlgLayer,UseDragCursor:!1},null).StartDrag(e)}onDragStart(data){var rect;this.dlgLayer?(this._dragStartX=this.dlgLayer.getLeft(),this._dragStartY=this.dlgLayer.getTop(),rect=UIHelper.getClientRectangle(),this._clientWidth=rect[0],this._clientHeight=rect[1]):data.cancelDragDrop()}onDragEnd(data){null!=this.onMoveDoneCallback&&("function"==typeof this.onMoveDoneCallback?this.onMoveDoneCallback.apply(null,[this,this.dlgLayer.attr("id"),this.contentLayer.getLeft(),this.contentLayer.getTop()]):new Function("thisObj","id","w","h",this.onMoveDoneCallback+"(thisObj,id,w,h)")(this,this.dlgLayer.attr("id"),this.contentLayer.getLeft(),this.contentLayer.getTop())),$(document).unbind(".dragdrop"),this.afterDrag()}onDragMove(data){var newPosX,newPosY;this.dlgLayer?(newPosX=this._dragStartX+data.getMouseDeltaX(),(newPosY=this._dragStartY+data.getMouseDeltaY())<0&&(newPosY=0),(newPosX=newPosX<0?0:newPosX)+this.dlgLayer.getWidth()>this._clientWidth&&(newPosX=this._clientWidth-this.dlgLayer.getWidth()),newPosY+this.dlgLayer.getHeight()>this._clientHeight&&(newPosY=this._clientHeight-this.dlgLayer.getHeight()),this.dlgLayer.setLeft(newPosX),this.dlgLayer.setTop(newPosY)):data.cancelDragDrop()}onCancelDrag(data){this.afterDrag()}}class ResizeableDialog extends HeaderDialog{constructor(options){super(options),this._resizeDragStartWidth=0,this._resizeDragStartHeight=0,this._minWidth=this.getValue(this.options.Layout.MinWidth,10),this._minHeight=this.getValue(this.options.Layout.MinHeight,10),this._maxWidth=this.getValue(this.options.Layout.MaxWidth,0),this._maxHeight=this.getValue(this.options.Layout.MaxHeight,0)}Show(title){super.Show(title),this.dlgResizeGrip=$(document.createElement("DIV")),this.dlgResizeGrip.attr("id",this.dlgLayer.attr("id")+"ResizeGrip"),this.dlgResizeGrip.setClass(this.resizeGripClassName),this.dlgResizeGrip.setStyle({position:"absolute",zIndex:99,cursor:"nw-resize"}),this.dlgLayer.append(this.dlgResizeGrip);var that=this;this.dlgResizeGrip.on("mousedown",function(event){that.beforeDrag(),new DragDrop(that,{DragDropStartMethod:that.onResizeDragStart,DragDropEndMethod:that.onResizeDragEnd,DragDropMoveMethod:that.onResizeDragMove,DragDropCancelMethod:that.onResizeCancelDrag,DragElement:that.dlgResizeGrip,UseDragCursor:!1},null).StartDrag(event)}),null!=this.onOpenCallback&&("function"==typeof this.onOpenCallback?this.onOpenCallback.apply(null,[this,this.dlgLayer.attr("id"),this.contentLayer.getWidth(),this.contentLayer.getHeight()]):new Function("this","id","w","h",this.onOpenCallback+"(this,id,w,h)")(this,this.dlgLayer.attr("id"),this.contentLayer.getWidth(),this.contentLayer.getHeight()))}onResizeDragStart(data){this._resizeDragStartWidth=this.dlgLayer.getWidth(),this._resizeDragStartHeight=this.dlgLayer.getHeight();var rect=UIHelper.getClientRectangle();this._clientWidth=rect[0],this._clientHeight=rect[1]}onResizeDragEnd(data){null!=this.onResizeDoneCallback&&("function"==typeof this.onResizeDoneCallback?this.onResizeDoneCallback.apply(null,[this,this.dlgLayer.attr("id"),this.contentLayer.getWidth(),this.contentLayer.getHeight()]):new Function("thisObj","id","w","h",this.onResizeDoneCallback+"(thisObj,id,w,h)")(this,this.dlgLayer.attr("id"),this.contentLayer.getWidth(),this.contentLayer.getHeight())),this.afterDrag()}onResizeDragMove(data){var newW=Math.max(this._minWidth,this._resizeDragStartWidth+data.getMouseDeltaX()),data=Math.max(this._minHeight,this._resizeDragStartHeight+data.getMouseDeltaY());0<this._maxWidth&&(newW=Math.min(this._maxWidth,newW)),0<this._maxHeight&&(data=Math.min(this._maxHeight,data)),newW+this.dlgLayer.getLeft()>this._clientWidth&&(newW=this._clientWidth-this.dlgLayer.getLeft()),data+this.dlgLayer.getTop()>this._clientHeight&&(data=this._clientHeight-this.dlgLayer.getTop()),newW==this.dlgLayer.getWidth()&&data==this.dlgLayer.getHeight()||(this.dlgLayer.setWidth(newW),this.dlgLayer.setHeight(data),this.setDimension(this.dlgHeader,this.dlgLayer.getWidth()-2+"px",this.getValue(this.options.Layout.HeaderHeight,"28px")),this.setDimension(this.contentLayer,this.dlgLayer.getWidth()+"px",this.dlgLayer.getHeight()-this.dlgHeader.getHeight()+"px"),null!=this.onResizeCallback&&("function"==typeof this.onResizeCallback?this.onResizeCallback.apply(null,[this,this.dlgLayer.attr("id"),this.contentLayer.getWidth(),this.contentLayer.getHeight()]):new Function("thisObj","id","w","h",this.onResizeCallback+"(thisObj,id,w,h)")(this,this.dlgLayer.attr("id"),this.contentLayer.getWidth(),this.contentLayer.getHeight())))}onResizeCancelDrag(data){JsHelper.EnableSelectTextOnTarget(document)}}var g_documentIdToDelete=0;function DeleteDocument(documentId){0!=documentId&&(documentId="{nav=document&document_id="+(g_documentIdToDelete=documentId)+"}",Dialog.ConfirmDelete(documentId,!1,"DeleteDocumentCallback"))}function DeleteDocumentCallback(res){0!=g_documentIdToDelete&&(1!=res.getStatus()&&2!=res.getStatus()||(res="{nav=document&document_id="+g_documentIdToDelete+"}",AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.ArchiveDelete.DeleteFromLinkHint","",res,""),Dialog.closeWithCallback(),PageUpdate("soprotocol:refresh","")),g_documentIdToDelete=0)}function CloseDocumentDialog(){""==UIHelper.GetOpener().Dialog.getCloseCallback()&&void 0===UIHelper.GetOpener().Dialog.isQuoteDialog&&(null==Dialog._closeCallback||void 0===Dialog._closeCallback||""==Dialog._closeCallback)?(UIHelper.GetMainPageWindow().RefreshCurrent("document","contact","project"),Dialog.close()):Dialog.closeWithCallback()}function CancelDocumentDialog(soid){DeleteTempDocument(soid),"true"===getQueryVariable("deleteoncancel")?(soid=getQueryVariable("document_id"),Dialog.YesNo("","[SR_L_DELETE]?","question","","_DeleteDocument",soid)):(CancelReport(),Dialog.close())}function DeleteTempDocument(soid){soid=$.fromSoId(soid).val();0<soid.length&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.DeleteTempDocument","",soid)}function SaveDocument(docId,soid,docTemplateSoid){g_additionalParams="[mode=save]";var title=$.fromSoId(soid).val(),docTemplateId=$.fromSoId(docTemplateSoid).val();if(0===title.length&&0<docTemplateId){var callback=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.GetCreateDocumentCallback","",parseInt(docTemplateId,10)),newCallback;if(null!=callback&&0<callback.length){let closeCallback=UIHelper.GetOpener().Dialog.getCloseCallback();"function"==typeof closeCallback?(newCallback=()=>{eval(callback),closeCallback()},UIHelper.GetOpener().Dialog.setCloseCallback(newCallback)):UIHelper.GetOpener().Dialog.setCloseCallback(callback+closeCallback)}}}function _DeleteDocument(res){null!=res&&1==res.getStatus()&&(res=res._context,AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.DeleteDocument","",Number(res)),null!=(res=UIHelper.GetOpener())?res.RefreshCurrent("document"):RefreshCurrent("document")),CancelReport(),Dialog.close()}function OpenCurrentDocument(){var res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.GetPreferredOpenScript","");setTimeout(()=>EvalDocumentDownload(res),100)}function OpenDocumentDialog(){OpenDocumentDialogWithCallback("document[dialog=stop]?document_id=0","RefreshDocumentCurrent();")}function OpenDocumentDialogWithCallback(dialog,callback){AjaxMethodDispatcher.GetData({ajaxMethod:"SuperOffice.CRM.Web.AjaxMethods.SuperStateCRM.IsRunningTestDrive",methodArguments:[],cacheoptions:{useCache:!0,duration:6e4,refresh:!1},fnCallback:function(data){data?Dialog.Information("SuperOffice","[SR_COMMON_TESTDRIVE_NODOCS]"):Dialog.open("document",dialog,callback)},readonlysession:!0})}function OpenDocumentDialogByIdWithCallback(docId,callback){var readOnlyString="",checkoutState=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.GetCheckOutState","",docId);OpenDocumentDialogWithCallback("document[dialog=stop]"+(readOnlyString=null!=checkoutState&&2===checkoutState.State?".details[display=readonly&mode=edit]":readOnlyString)+"?document_id="+docId,callback)}function DownloadCurrentDocument(){var res;PendingRequest.isReady()?(debug.trace("DownloadCurrentDocument","Document"),res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.DownloadCurrentDocument",""),setTimeout(()=>EvalDocumentDownload(res),100)):(debug.warning("DownloadCurrentDocument, try again","Document"),setTimeout("DownloadCurrentDocument()",100))}function EvalDocumentDownload(res){PendingRequest.isReady()?eval(res):(debug.warning("EvalDocumentDownload, try again","Document"),setTimeout(()=>EvalDocumentDownload(res),100))}function OnCloseDocumentDialog(documentId,docFileUploadId){debug.trace("OnCloseDocumentDialog executing","Document"),0<docFileUploadId.length&&AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.DeleteTempDocument","",docFileUploadId),ReportManager.DialogCancelCallBack()}function DocumentSetCompleted(){var isChecked="Images-LargeIcon-Complete_Unchecked"===$('[soid="CompletedIcon_Image"]').attr("normalsrc"),completedCbxState={};completedCbxState.value=isChecked?"1":"0","0"===completedCbxState.value?PageUpdate("soprotocol:document[dialog=stop].details[mode=edit]?setCompleted=0",""):"1"===completedCbxState.value&&PageUpdate("soprotocol:document[dialog=stop].details[mode=edit]?setCompleted=1","")}function SendDocumentAsMail(documentId){var method;0!=documentId&&(method=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetSendDocumentScript","",Number(documentId)),eval(method))}function SendDocumentAsMailToPerson(documentId,personId){var method;0!=documentId&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","mailto",personId,"",""),method=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetSendDocumentScript","",Number(documentId)),eval(method))}function SendDocumentAsFax(documentId){var method;0!=documentId&&(method=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetSendDocumentAsFaxScript","",Number(documentId)),eval(method))}function SendAppointmentAsMail(appointmentId){var script;0!=appointmentId&&(script=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetSendAppointmentScript","",Number(appointmentId)),eval(script))}function ForwardDocument(documentId){var method;0!=document&&(method=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetForwardDocumentScript","",Number(documentId)),eval(method))}function ReplyToDocument(documentId){var method;0!=documentId&&(method=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetReplyToDocumentScript","",Number(documentId)),eval(method))}function EMailResolver(id,obj){this._id=id,this._emailIds=new Array,this._unresolved="",this._labelConstant=ResourceUtils.GetResourceText("[SR_MAIL_RESOLVE_LABEL]"),this._labelVariable="",this._counter=0,this._unresolvedEmails=obj,this._unresolved="",this._label="",this._searchString="",this._tmpSelected=0,this._hasChanged=!1,this._resolvedEmails=new Array,this._allReturnValues=new Array,this.SetUp()}SuperOffice.Document=function(){var pubs={executeDocumentCommand:function(docId,command){var opener,docId=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.ExecuteDocumentCommand","",docId,command);docId.Success&&(1==docId.Type?Dialog.Information("SuperOffice",docId.Value,"information"):2==docId.Type?(-1==(command=-1<(command=docId.Value).indexOf("superoffice:")?command.replace("superoffice:","soprotocol:"):command).indexOf("soprotocol:")&&(command="soprotocol:"+command),(opener=UIHelper.GetOpener())?(CloseDocumentDialog(),opener.PageUpdate(command)):PageUpdate(command)):5==docId.Type&&window.open(docId.Value,"documentCommand"))},openForMailMerge:function(docId){SuperOffice.WebTools.isCompatibleVersion()?OpenDocument(docId):Dialog.open("document","document[dialog=stop]?document_id="+docId+"&mergedocument=true","RefreshMailMergeDocumentCurrent();")},openGeneral:(documentId,closeDocDialog)=>{var result=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.OpenDocumentGeneral","",documentId,closeDocDialog);eval(result)},openReadOnly:function(documentId,name,closeDocDialog){documentId=JSON.stringify({documentId:documentId,closeDocDialog:closeDocDialog,closeDocDialog:closeDocDialog}),closeDocDialog=ResourceUtils.GetResourceText("[SR_COMMON_CHECKEDOUTBY]").replace("{0}","<b>"+name+"</b>");Dialog.OkNormalButton("[SR_MENU_LIST_OPEN_DOCUMENT]",closeDocDialog,"[SR_COMMON_READ]","[SR_MB_CANCEL]","question",documentId,"SuperOffice.Document.ReadCallback")},openReadOnlySentryRestrict:function(documentId,dialogTitle,closeDocDialog){documentId=JSON.stringify({documentId:documentId,closeDocDialog:closeDocDialog,closeDocDialog:closeDocDialog});Dialog.OkNormalButton("[SR_MENU_LIST_OPEN_DOCUMENT]",dialogTitle,"[SR_COMMON_READ]","[SR_MB_CANCEL]","question",documentId,"SuperOffice.Document.ReadCallback")},tryOpenDocumentFromTaskMenu:function(documentId){pubs.openGeneral(documentId,!1)},openCheckOutOrReadDirect:function(documentId,closeDocDialog){documentId=JSON.stringify({documentId:documentId,closeDocDialog:closeDocDialog,closeDocDialog:closeDocDialog}),closeDocDialog=ResourceUtils.GetResourceText("[SR_MENU_LIST_OPEN_DOCUMENT]");this.hasTrayApp()&&(closeDocDialog="SuperOffice WebTools - "+closeDocDialog);Dialog.OkNormalButtonWithCancel(closeDocDialog,"[SR_COMMON_EDITORREAD]","[SR_MB_EDIT]","[SR_COMMON_READ]","question",documentId,"SuperOffice.Document.CheckOutOrReadCallback")},CheckOutOrReadCallback:function(returnObj){var context=JSON.parse(returnObj._context),result,res,res;1===returnObj._status?(result=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.CheckOutDocument","",context.documentId),result.Success?this.hasTrayApp()?(context.closeDialog&&$('[soid="DlgButtonBar_okButton"]').trigger("click"),res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.OpenDocumentWithTrayApp","",context.documentId),eval(res)):(PageUpdate("soprotocol:document[dialog=stop].details[mode=edit]?setCompleted=0",""),setTimeout(function(){DownloadDocument(context.documentId)},100)):Dialog.Information("[SR_FDLG_WARNING]","Unable to checkout the document. ","warning")):2===returnObj._status&&(this.hasTrayApp()?(res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.OpenDocumentWithTrayApp","",context.documentId),eval(res)):setTimeout(function(){pubs.DownloadReadOnlyDocumentFile(context.documentId)},100),context.closeDialog)&&$('[soid="DlgButtonBar_okButton"]').trigger("click")},ReadCallback:function(returnObj){var context=JSON.parse(returnObj._context),res,closeButton;1===returnObj._status&&(this.hasTrayApp()?(res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.OpenDocumentWithTrayApp","",context.documentId),eval(res)):(setTimeout(function(){pubs.DownloadReadOnlyDocumentFile(context.documentId)},100),context.closeDialog&&(closeButton=$('[soid="DlgButtonBar_okButton"]'),("disabled"!==closeButton.attr("disabled")?closeButton:$('[soid="DlgButtonBar_cancelButton"]')).trigger("click"))))},DownloadReadOnlyDocumentFile:function(docId){var res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.DownloadReadOnlyDocumentFile","",docId);eval(res)},hasTrayApp:function(){return 2===SuperOffice.DocumentHandler}};return pubs}(),SuperOffice.ejTicket=(()=>{var pub={setNewUrl:function(url){var iframes=document.getElementsByTagName("iframe");0<iframes.length&&(iframes[0].src=url)},openNewUrl:function(url){window.open(url,"ejTicket","width=1024,height=768"),window.close()}};return pub})(),_this=EMailResolver.prototype,_this.SetUp=function(){this._label=so("ResolverLabel"),this._unresolvedEmails.length>this._counter?(this._searchString=this._unresolvedEmails[this._counter],this._labelVariable=this._labelConstant,0<this._counter&&this.Refresh()):this.Finished()},_this.Refresh=function(){this._label&&(this._label.innerHTML=this._labelVariable.replace("%",this._searchString)),"undefined"!=typeof CheckNamesArchiveArchiveControl&&CheckNamesArchiveArchiveControl.RefreshList(this._searchString)},_this.SetSelectedUser=function(emailId){this._tmpSelected=emailId,this._hasChanged=!0},_this.SetSelectedUserPermanent=function(){this._hasChanged?(this._unresolved=this._searchString,this._emailIds.push(this._tmpSelected),this._allReturnValues.push(this._tmpSelected),this.GetNextUnresolvedEMail()):this.AddUnresolvedText()},_this.SubmitSelectedUser=function(emailId){this.SetSelectedUser(emailId),this.SetSelectedUserPermanent()},_this.AddUnresolvedText=function(){this._allReturnValues.push(this._unresolvedEmails[this._counter]),this.GetNextUnresolvedEMail()},_this.GetNextUnresolvedEMail=function(){this._counter++,this.SetUp(),this._hasChanged=!1},_this.Cancel=function(){for(;this._counter<this._unresolvedEmails.length;)this._allReturnValues.push(this._unresolvedEmails[this._counter]),this._counter++;this.Finished()},_this.Finished=function(){this._hasChanged=!1,this.ReplaceUnresolved(),Dialog.setParentReturnObject(1,this._allReturnValues,""),Dialog.closeWithCallback()},_this.ReplaceUnresolved=function(){this._resolvedEmails=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.ResolveEmails","",this._emailIds);for(var resolvedCounter=0,i=0;i<this._allReturnValues.length&&!(this.IsNumber(this._allReturnValues[i])&&(this._allReturnValues[i]=this._resolvedEmails[resolvedCounter],++resolvedCounter>=this._resolvedEmails.length));i++);},_this.IsNumber=function(possibleNumber){return"number"==typeof possibleNumber};var EMailResolveHelper=new _EMailResolveHelper;function _EMailResolveHelper(){this._to=null,this._cc=null,this._bcc=null,this._globalCounter=0,this._returnedValues=null}function OpenFileDialog(filetype,id,callbackscript){window.open("FileUpload.aspx?filetype="+filetype+"&id="+id+"&callbackscript="+callbackscript,"FileUpload","width=500,height=194,resizable=no,toolbar=no,location=no,directories=no,status=no,menubar=no")}function UpdateProjectPicture(imgElemSoId,binId){SuperOffice.SoHelper.getElementBySoId(imgElemSoId).value=binId,document.getElementById("ImageList_SelectedPrimaryKeys").value=binId,document.getElementById("ImageList_SelectedValues").value="",setTimeout(" QueuedPageUpdate('soprotocol:projectimage[dialog=stop]?projectimage_id="+binId+"&projectimage_type="+binId+"');",200)}function UpdateProductPicture(imgElemSoId,binId){binId=binId||Dialog.getReturnValue(),console.log("UpdateProductPicture id "+binId);SuperOffice.SoHelper.getElementBySoId(imgElemSoId);AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminEditProductDataHandler.ChangeProductImage","",parseInt(binId,10)),QueuedPageUpdate("soprotocol:admineditproduct[dialog=stop].main[refresh=true]")}_EMailResolveHelper.prototype.Clear=function(){this._globalCounter=0,this._returnedValues=null},_EMailResolveHelper.prototype.ShowDialog=function(to,cc,bcc){this._to=to,this._cc=cc,this._bcc=bcc;to=this.MakeRecipientString();0<this.CountNonEmails(to)?Dialog.open("mailchecknamesdialog","mailchecknamesdialog[dialog=stop]?recipients="+to,"EMailResolveHelper.ReplaceUnresolved()"):Dialog.Information("SuperOffice",ResourceUtils.GetResourceText("[SR_MAIL_CHECK_ADDRESSES_OK]"),"Info")},_EMailResolveHelper.prototype.CountNonEmails=function(urlString){for(var array=urlString.split(";"),count=0,i=0;i<array.length;i++){var string=this.Trim(array[i]);this.IsValidEmail(string)||this.IsEmpty(string)||count++}return count},_EMailResolveHelper.prototype.MakeRecipientString=function(){var retVal=this._to.getSearchBoxText();return";"!=retVal.charAt(retVal.length-1)&&(retVal+=";"),";"!=(retVal+=this._cc.getSearchBoxText()).charAt(length-1)&&(retVal+=";"),retVal+=this._bcc.getSearchBoxText()},_EMailResolveHelper.prototype.ReplaceUnresolved=function(){this.Clear(),this._returnedValues=Dialog.getReturnValue(),this.ResolveFieldValues(this._to),this.ResolveFieldValues(this._cc),this.ResolveFieldValues(this._bcc),this.Clear()},_EMailResolveHelper.prototype.IsValidEmail=function(email){return/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\b/.test(email)},_EMailResolveHelper.prototype.IsWhitespace=function(s){if(!this.IsEmpty(s))for(var i=0;i<s.length;i++){var c=s.charAt(i);if(-1==" \t\n\r".indexOf(c))return!1}return!0},_EMailResolveHelper.prototype.IsEmpty=function(s){if(null==s||0==s.length)return!0},_EMailResolveHelper.prototype.Trim=function(s){return this.IsWhitespace(s)?"":this.TrimEnd(this.TrimEnd(s),!0)},_EMailResolveHelper.prototype.TrimEnd=function(s,reverse){if(null!=reverse&&void 0!==reverse||(reverse=!1),this.IsWhitespace(s))return"";for(var i=0,c=(reverse&&(i=s.length-1),"");this.IsWhitespace(c);)c=s.charAt(i),reverse?i--:i++;return reverse?s.substr(0,i+2):s.substr(i-1)},_EMailResolveHelper.prototype.ResolveFieldValues=function(field){var sBoxText=field.getSearchBoxText();if(sBoxText&&""!=sBoxText){var completeArray=sBoxText.split(";"),resTextArray=new Array;for(i=0;i<completeArray.length;i++){var tmpText=this.Trim(completeArray[i]);this.IsEmpty(tmpText)||(this.IsValidEmail(tmpText)?resTextArray.push(tmpText):(resTextArray.push(this._returnedValues[this._globalCounter]),this._globalCounter++))}sBoxText="";";"!=(sBoxText=0<resTextArray.length?resTextArray.join(";"):sBoxText).charAt(sBoxText.length-1)&&(sBoxText+=";"),field.setSearchBoxText(sBoxText,!0)}},SuperOffice.ErpSync=(()=>{var pub={OpenDefaultDialog:function(connectionId,crmActorType,crmId,useSCIL){Dialog.open("connecttoerpdefaults","connecttoerpdefaults[dialog=stop]&connectionId="+connectionId+"&crmActorType="+crmActorType+"&crmId="+crmId,useSCIL?Dialog._closeCallback:"SuperOffice.PageBuilder.customPostback('edit','edit', true);")},OpenDefaultDialogFromFind:function(){Dialog.close(),UIHelper.GetOpener().SuperOffice.ErpSync.OpenDefaultDialog(SuperOffice.SoHelper.getElementValueBySoId("ConnectionId"),SuperOffice.SoHelper.getElementValueBySoId("CrmActorType"),SuperOffice.SoHelper.getElementValueBySoId("CrmId"))},OpenCreateInErpDialog:function(connectionId,crmActorType,erpActorType,crmId,useSCIL){Dialog.open("createinerp","createinerp[dialog=stop]&connectionId="+connectionId+"&crmActorType="+crmActorType+"&erpActorType="+erpActorType+"&crmId="+crmId,useSCIL?Dialog._closeCallback:"SuperOffice.PageBuilder.customPostback('edit','edit', true);")},ConnectToErpDialogGuiLogic:function(){$("[soid=noMatchChk]").is(":checked")?(g_archiveErpMatches.SetSelectedById(""),$("[soid=ErpActorType_SearchBox]").removeAttr("disabled"),$("[soid=ConnectButton]").parent().hide(),$("[soid=SearchButton]").attr("disabled","disabled"),$("[soid=CreateButton]").parent().show(),$("[soid=findBtn_Image]").hide()):($("[soid=ErpActorType_SearchBox]").attr("disabled","disabled"),$("[soid=ConnectButton]").parent().show(),$("[soid=SearchButton]").removeAttr("disabled"),$("[soid=CreateButton]").parent().hide(),$("[soid=findBtn_Image]").show()),0<g_archiveErpMatches.getSelectedRows().length?$("[soid=ConnectButton]").removeAttr("disabled"):$("[soid=ConnectButton]").attr("disabled","disabled")},ConnectToErpDialogEntityChosen:function(erpactortype,erpkey){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.SetCurrent","","ErpKey",0,erpkey,erpactortype),0<erpkey.length&&$("[soid=noMatchChk]").removeAttr("checked"),pub.ConnectToErpDialogGuiLogic()},OpenFindInlineErpDialog:function(){var context="connectionid="+$.fromSoId("ConnectionId").val()+"&erpactortype="+$.fromSoId("ErpActorType").val();Dialog.open("erpfindinline","erpfindinline[dialog=stop&usesuperstatecopy=true].findcontact?"+SuperOffice.Find.FindTypeEnum.Single+"&criterionentity_id=0&criterionentity_name=findcontact&findtype_id=1&findtype_type=single&"+context,"",!0)}};return pub})(),"undefined"==typeof Event&&(Event={}),Event.pointer=function(event){return{x:event.pageX||event.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft),y:event.pageY||event.clientY+(document.documentElement.scrollTop||document.body.scrollTop)}},Event.pointerX=function(event){return Event.pointer(event).x},Event.pointerY=function(event){return Event.pointer(event).y},Event.isLeftClick=function(event){return $.isLeftClick(event)},Event.element=function(event){return $.getElementFromEvent(event)},"undefined"==typeof addEvent&&(addEvent=function(o,evType,f,capture){if(null==o)return!1;if(o.addEventListener)return o.addEventListener(evType,f,capture),!0;if(o.attachEvent)return o.attachEvent("on"+evType,f);try{o["on"+evType]=f}catch(e){}}),"undefined"==typeof removeEvent&&(removeEvent=function(o,evType,f,capture){if(null==o)return!1;if(o.removeEventListener)return o.removeEventListener(evType,f,capture),!0;if(o.detachEvent)o.detachEvent("on"+evType,f);else try{o["on"+evType]=function(){}}catch(e){}}),(window=>{try{return new MouseEvent("test")}catch(e){}var MouseEvent=function(eventType,params){params=params||{bubbles:!1,cancelable:!1};var mouseEvent=document.createEvent("MouseEvent");return mouseEvent.initMouseEvent(eventType,params.bubbles,params.cancelable,window,0,0,0,0,0,!1,!1,!1,!1,0,null),mouseEvent};MouseEvent.prototype=Event.prototype,window.MouseEvent=MouseEvent})(window);var g_findtypeNormal="findtype_id=0&findtype_type=normal",g_findtypeSingle="findtype_id=1&findtype_type=single",g_findtypeNoResult="findtype_id=2&findtype_type=noresult",g_findtypeAttachment="findtype_id=3",g_currentCriterionFieldName="",g_currentCriterionPrimaryKey="",g_currentCriterionEntityName="",g_pageHasChanged=!1,g_externalFreetext=!0;function RedirectSearch(){CriterionProxy.refreshResults()}function OpenSingleFindDialog(callback,type,staticOverride,multiselect,isSelectionAdd){var type=getCriterionEntityName(type),multiSelectArgs=(so_defined(staticOverride)||(staticOverride=null),so_defined(isSelectionAdd)||(isSelectionAdd=!1),""),multiselect=((multiselect=so_defined(multiselect)?multiselect:!1)&&(multiSelectArgs="&multiselect=true"),"");null!=staticOverride&&(multiselect="&setCriteria="+staticOverride),""!=type&&Dialog.open("findsingle","findsingle[dialog=stop]."+type+"?"+g_findtypeSingle+multiSelectArgs+"&criterionentity_id=0&criterionentity_name="+type+"&find_id=0"+multiselect+"&isseladd="+isSelectionAdd,callback,!0)}function OpenSingleFindSelectionDialog(callback,selectionType,selectionMemberType,onlywriteable){var staticOverride="";return so_defined(onlywriteable)||(onlywriteable=!1),so_defined(selectionType)&&(staticOverride+="static"==selectionType?"kind,set,0,[SR_SELECTION_STATIC],true,true":"kind,set,1,[SR_SELECTION_DYNAMIC],true,true"),so_defined(selectionMemberType)&&(""!=staticOverride&&(staticOverride+="|"),staticOverride+="targetTableNumber,set,"+selectionMemberType+","+selectionMemberType+",true,true"),onlywriteable&&(""!=staticOverride&&(staticOverride+="|"),staticOverride+="onlywriteable,set,true, onlywriteable,true,true"),OpenSingleFindDialog(callback,"selection",staticOverride)}function getCriterionEntityName(type){var criterionentity="";switch(type){case"contact":criterionentity="findcontact";break;case"diary":case"appointment":criterionentity="findappointment";break;case"sale":criterionentity="findsale";break;case"project":criterionentity="findproject";break;case"selection":criterionentity="findselection";break;case"mail":case"maillogin":case"mergedocument":case"document":case"report":criterionentity="finddocument";break;default:criterionentity="findcontact"}return criterionentity}function GetValueAndReturn(){setSingleSelected(""),Dialog.close()}SuperOffice.Find=function(){var pub={DisplayInMainWindow:!1,CriteriaGuiName:"",OpenDialogOnShow:!0,findtypeNormal:"findtype_id=0&findtype_type=normal",findtypeSingle:"findtype_id=1&findtype_type=single",findtypeNoResult:"findtype_id=2&findtype_type=noresult",findtypeAttachment:"findtype_id=3",FindTypeEnum:{Normal:0,Single:1,NoResult:2,Attachment:3},OpenFindDialog:function(){var criterionentity=getCriterionEntityName(AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetPageName",""));""!=criterionentity&&Dialog.open("find","find[dialog=stop]."+criterionentity+"?"+g_findtypeNormal+"&criterionentity_id=0&criterionentity_name="+criterionentity+"&find_id=0")},OpenFindInlineDialog:function(findContext){var criterionentity="",findType="",findTypeEnum=(findContext=so_defined(findContext)?findContext:{}).FindType||this.FindTypeEnum.Normal,staticOverride=findContext.StaticOverride||null,multiSelectArgs="";!findContext.MultiSelect&&1||(multiSelectArgs="&multiselect=true");var isSelectionArgs="",isSelectionArgs=findContext.IsSelectionAdd||!1?"&isseladd=true":"&isseladd=false";switch(findTypeEnum){case this.FindTypeEnum.Normal:findType=this.findtypeNormal;break;case this.FindTypeEnum.Single:findType=this.findtypeSingle;break;case this.FindTypeEnum.NoResult:findType=this.findtypeNoResult;break;case this.FindTypeEnum.Attachment:findType=this.findtypeAttachment;break;default:findType=this.findtypeNormal}findTypeEnum=findContext.PageName||this.getPageName(),(criterionentity=findContext.CriterionEntity||getCriterionEntityName(findTypeEnum)).startsWith("find")||(criterionentity="find"+criterionentity);var staticFindArgs="";if(staticOverride)for(var staticFindArgs="&setCriteria=",t=0;t<staticOverride.length;++t)0<t&&(staticFindArgs+="|"),staticFindArgs=(staticFindArgs=(staticFindArgs=(staticFindArgs=(staticFindArgs=(staticFindArgs+=staticOverride[t].Name+",")+staticOverride[t].OperatorName+",")+staticOverride[t].Value+",")+staticOverride[t].DisplayValue+",")+staticOverride[t].Active+",")+staticOverride[t].ReadOnly;""!=criterionentity&&Dialog.open("findinline","findinline[dialog=stop&usesuperstatecopy=true]."+criterionentity+"?"+findType+"&criterionentity_id=0&criterionentity_name="+criterionentity+multiSelectArgs+isSelectionArgs+staticFindArgs,findContext.Callback||"",!0)},getPageName:function(){return AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetPageName","")},FindResultRowClicked:function(archiveId){debug.trace("FindResultRowClicked","Find");var control=eval(archiveId+"ArchiveControl");control&&0<control.getSelectedRows().length?(SuperOffice.SoHelper.enableElementBySoId(archiveId+"_ArchiveToolbar_1_0"),SuperOffice.SoHelper.enableElementBySoId(archiveId+"_ArchiveToolbar_1_1"),SuperOffice.SoHelper.enableElementBySoId(archiveId+"_ArchiveToolbar_1_2")):(SuperOffice.SoHelper.disableElementBySoId(archiveId+"_ArchiveToolbar_1_0"),SuperOffice.SoHelper.disableElementBySoId(archiveId+"_ArchiveToolbar_1_1"),SuperOffice.SoHelper.disableElementBySoId(archiveId+"_ArchiveToolbar_1_2"))},OnActiveRestrictions:function(hasActiveRestrictions){if(null==hasActiveRestrictions){if(hasActiveRestrictions=!1,null==SuperOffice.Find.CurrentCriterionArchive)return;0<SuperOffice.Find.CurrentCriterionArchive.getRowsByLinkHint("isActive=true").length&&(hasActiveRestrictions=!0)}debug.trace("hasActiveRestrictions: "+hasActiveRestrictions,"Find");var findBtn=SuperOffice.SoHelper.getElementBySoId("dofind");hasActiveRestrictions?so_defined(findBtn)?SuperOffice.SoHelper.enableElement(findBtn):SuperOffice.SoHelper.enableElementBySoId("DlgButtonBar_okButton"):so_defined(findBtn)?SuperOffice.SoHelper.disableElement(findBtn):SuperOffice.SoHelper.disableElementBySoId("DlgButtonBar_okButton"),null!=findBtn||hasActiveRestrictions||SuperOffice.SoHelper.disableElementBySoId("DlgButtonBar_okButton")},OnDisplayInMainChanged:function(soid){this.DisplayInMainWindow=SuperOffice.SoHelper.getSoCheckBoxState(soid),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserPreferences.ToggleBool","","FindResultDialog","DisplayInMain")},OnFindDialogResize:function(finddlg){var tabbedContainer=null,footerContainer=null,footerContainer="find"==finddlg?(tabbedContainer=$("[soid=FindDialogCard]"),$("[soid=FindDialogCard_footer]")):(tabbedContainer=$("[soid=FindSingleDialogCard]"),$("[soid=FindSingleDialogCard_footer]")),finddlg=UIHelper.getClientRectangle()[1]-280;footerContainer.css("height",finddlg+"px"),tabbedContainer.css("bottom",finddlg+"px")},FindResultArchiveColumnsRefresh:function(){-1<SuperOffice.Find.Current.QueryString.indexOf("findsingle")?QueuedPageUpdate("soprotocol:"+SuperOffice.Find.Current.QueryString,""):FindResultArchiveArchiveControl.Refresh("")}};return pub}();var g_freeTextBoxSoId=null;function FreeTextSearchWatch(soId,useDialog,rebindBlur){g_freeTextBoxSoId=soId;var textBox=$.fromSoId(soId+"_textfield");textBox.length&&(textBox.off("keyup"),rebindBlur||textBox.off("blur"),textBox.on("keyup",function(e){return ExecuteFreeTextSearch(e,soId+"_textfield",useDialog)}),textBox.on("keydown",function(e){if(13==e.which)return e.preventDefault,!1}))}function OnFreeTextSearchBlur(e,soId,useDialog){soId=SuperOffice.SoHelper.getElementBySoId(soId);soId&&AjaxMethodDispatcher.CallASync("","","","","SuperOffice.DCF.Web.AjaxMethods.SuperState.SetCurrent","freetext",0,GetSoTextFieldValue(soId.id),null)}function ExecuteFreeTextSearch(e,soId,useDialog){e&&(keypress=e.keyCode||e.which);e=SuperOffice.SoHelper.getElementBySoId(soId),soId=!1;return 13==keypress&&(soId=executeFreeTextSearch(e.value,useDialog),e.value=""),enableDisableViews(e,!1),soId}function enableDisableViews(txtBox,doCheckCurrent){var doDisable=!1;doDisable=doCheckCurrent?(doCheckCurrent=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","freetext"))&&doCheckCurrent.Name&&0<doCheckCurrent.Name.length:null!=(doCheckCurrent=txtBox.value)&&0<doCheckCurrent.length,safeEnableDisableElement(SuperOffice.SoHelper.getElementBySoId("FindCompanyDialogView"),doDisable),safeEnableDisableElement(SuperOffice.SoHelper.getElementBySoId("FindProjectDialogView"),doDisable),safeEnableDisableElement(SuperOffice.SoHelper.getElementBySoId("FindSelectionDialogView"),doDisable),safeEnableDisableElement(SuperOffice.SoHelper.getElementBySoId("FindActivityDialogView"),doDisable),safeEnableDisableElement(SuperOffice.SoHelper.getElementBySoId("FindSaleDialogView"),doDisable),safeEnableDisableElement(SuperOffice.SoHelper.getElementBySoId("FindDocumentDialogView"),doDisable)}function safeEnableDisableElement(elem,disabled){var curVal;if(elem&&(elem.disabled!=disabled&&3!=elem.nodeType&&(disabled?((curVal=elem.disabled)&&elem.setAttribute("olddisabledval",curVal),elem.disabled=disabled):(curVal=elem.getAttribute("olddisabledval"),elem.disabled=curVal||disabled),elem.childNodes)&&0<elem.childNodes.length))for(var i=0;i<elem.childNodes.length;i++)safeEnableDisableElement(elem.childNodes[i],disabled)}function executeFreeTextSearch(searchValue,useDialog){return isValidSearchValue(searchValue)&&PageUpdate("soprotocol:freetextresult.freetextcompany?freetext_name="+searchValue,""),!1}function canCloseFreetext(){g_externalFreetext?Dialog.close():returnToReferer()}function isValidSearchValue(searchValue){return""!=searchValue}function OpenCriterionDialog(entityname,fieldname,type,primaryKey){Debug.trace("Opening Criteria Dialog","Find"),Debug.trace(" entityname:"+entityname+", fieldname:"+fieldname+", type:"+type,"Find"),""!=SuperOffice.Find.CriteriaGuiName&&(entityname+="|"+SuperOffice.Find.CriteriaGuiName),Dialog.open("criterion","criterion[dialog=stop].main[mode=edit;new=true]?criterionentity_name="+entityname+"&criterionentity_type="+type+"&criterionfield_name="+fieldname+"&primaryKey="+primaryKey,"CriterionProxy.addCriterion",!0)}function OpenCriterionDialogForSelection(entityname,fieldname,type,primaryKey){Debug.trace("OpenCriterionDialogForSelection","Find"),Debug.trace(" entityname:"+entityname+", fieldname:"+fieldname+", type:"+type,"Find"),Dialog.open("criterion","criterion[dialog=stop].main[mode=edit;new=true]?criterionentity_name="+entityname+"&criterionentity_type="+type+"&criterionfield_name="+fieldname+"&primaryKey="+primaryKey,"CriterionProxy.addCriterionForSelection",!0)}function KeepUnchecked(checkBoxElem,e){var retVal=!0,e=(debug.trace("KeepUnchecked: "+checkBoxElem.id,"Find"),debug.trace("--event: "+e,"Find"),$(checkBoxElem).parent().children("[type=checkbox]")),checkBoxElem=$(checkBoxElem).parent().children("[type=checkbox]");return 1==e.length&&1==checkBoxElem.length&&(debug.trace("--checkbox id: "+e[0].id,"Find"),retVal="0"!=checkBoxElem[0].value,e[0].checked=!1),retVal}function setCurrentCriterionField(fieldName,primaryKey){Debug.trace("Setting current field name:"+fieldName+"("+primaryKey+")","Find"),g_currentCriterionFieldName=fieldName,g_currentCriterionPrimaryKey=primaryKey}function setCurrentCriterionEntityName(entityName){Debug.trace("Setting current criterion entity name:"+entityName,"Find"),g_currentCriterionEntityName=entityName}function returnToReferer(){PageUpdate("soprotocol:find[dialog=stop&noupdate=true]","")}function returnSingleToReferer(){PageUpdate("soprotocol:findsingle[dialog=stop&noupdate=true]","")}function removeReportCriteria(archiveControl){for(var rows=archiveControl.getSelectedRows(),keys=new Array,i=0;i<rows.length;i++){var key=SuperOffice.SoHelper.getAnyValueFromLinkHint(rows[i].attributes.rowtype.value,"criterionKey");keys.push(key)}CriterionProxy.removeCriterion(keys.join(","))}function removeCriteria(archiveControl,rowIds){0<rowIds.length&&(CriterionProxy.removeCriterion(rowIds.join(",")),archiveControl.alignColumns())}function removeCriteriaForSelection(archiveControl,rowIds){0<rowIds.length&&(CriterionProxy.removeCriterionForSelection(rowIds.join(",")),archiveControl.alignColumns())}function toggleCriteria(criterionName){debug.trace("toggleCriteria","Find"),CriterionProxy.toggleCriterion(criterionName)}function addMemberToggleCriteria(criterionName){debug.trace("addMemberToggleCriteria","Find"),CriterionProxy.addMemberToggleCriterion(criterionName)}var g_currentselected="",_currentDialogSoProtocol="",_currentDialogName="";function setSelectedAndClose(){Dialog.close(),SuperOffice.Find.OpenDialogOnShow&&""!=_currentDialogSoProtocol?OpenEditDialog():""!=g_currentselected&&setSelected(g_currentselected)}function setSelected(soprotocol){debug.trace("setSelected: "+soprotocol,"Find"),UIHelper.GetOpener().PageUpdate("soprotocol:"+soprotocol)}function setSingleSelected(){for(var row=FindResultArchiveArchiveControl.getSelectedRows(),retVal="",i=0;i<row.length;i++)""!=retVal&&(retVal+="|,|"),retVal+=GetPrimaryKeyFromRow(row[i])+"|%|"+UIHelper.GetInnerText(row[i].cells[1])+"|%|"+row[i].attributes.rowtype.value;var urlParams=location.search.substring(1),script;null!=urlParams&&"undefined"!=urlParams&&-1!=urlParams.indexOf(g_findtypeAttachment)?(script=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetAddAttachmentScript","",retVal),eval(script)):Dialog.setParentReturnObject(1,retVal)}function FindSingleOnSingleClick(soprotocol){g_currentselected=soprotocol,SuperOffice.SoHelper.enableElementsBySoId("DlgButtonBar_okButton")}function FindSingleOnDblClick(soprotocol){setSingleSelected(),setTimeout("Dialog.close()",500)}function FindOnSingleClick(soprotocol,bOpenDialog,dialogName,dialogSoProtocol,archiveControlName){var rows;!so_defined(archiveControlName)||!SuperOffice.Find.Current.GuiName.startsWith("findmodeless")||(rows=null,eval("rows="+archiveControlName+".getSelectedRows();"),1==rows.length)?SuperOffice.SoHelper.enableElementsBySoId("DlgButtonBar_okButton"):SuperOffice.SoHelper.disableElementsBySoId("DlgButtonBar_okButton"),bOpenDialog&&SuperOffice.SoHelper.enableElementBySoId(archiveControlName+"_0"),_currentDialogSoProtocol=dialogSoProtocol,_currentDialogName=dialogName,g_currentselected=soprotocol,SuperOffice.Find.DisplayInMainWindow&&setSelected(soprotocol)}function OpenEditDialog(){""!=_currentDialogSoProtocol&&UIHelper.GetOpener().Dialog.open(_currentDialogName,_currentDialogSoProtocol)}function FindOnDblClick(soprotocol){Dialog.close(),setSelected(soprotocol)}function FindWatchCheckBox(checkboxId){checkboxId=$.fromSoId(checkboxId);checkboxId.length&&checkboxId.mouseup(new Function("g_pageHasChanged=true;"))}function FindWatch(checkboxId,textBoxId,operatorId){var txtBox=$.fromSoId(textBoxId+"_textfield");null!=operatorId&&FindWatchOperator(operatorId),FindWatchCheckBox(checkboxId),txtBox.length&&txtBox.keyup(new Function("FindSetCheckbox('"+textBoxId+"_textfield','"+checkboxId+"');"))}function FindWatchOperator(operatorId){operatorId=$.fromSoId(operatorId+"_SearchBox");operatorId.length&&operatorId.blur(new Function("g_pageHasChanged=true;"))}function FindWatchMDO(checkboxId,mdoControlId){var mdoControl=$.fromSoId(mdoControlId+"_SearchBox");FindWatchCheckBox(checkboxId),mdoControl.length&&mdoControl.blur(new Function("FindSetCheckbox('"+mdoControlId+"_SearchBox','"+checkboxId+"');"))}function FindWatchDateTime(checkboxId,datebox1Id,datebox2Id,operatorId){FindWatchCheckBox(checkboxId);var operatorMDO=$.fromSoId(operatorId+"_SearchBox");operatorMDO.length&&operatorMDO.blur(new Function("FindSetDateTime('"+datebox1Id+"','"+datebox2Id+"','"+checkboxId+"','"+operatorId+"');")),FindSetDateTime(datebox1Id,datebox2Id,checkboxId,operatorId)}function FindSetDateTime(datebox1Id,datebox2Id,checkboxId,operatorId){operatorId=SuperOffice.SoHelper.getElementBySoId(operatorId+"_SelectedExtraInfo").value.split(";");0<operatorId.length&&(setDateTime(datebox1Id,getValueHint(operatorId[0])),SuperOffice.SoHelper.hideElementBySoId(datebox2Id+"_DateField_Date"),SuperOffice.SoHelper.hideElementBySoId(datebox2Id+"SearchButton")),2==operatorId.length&&(SuperOffice.SoHelper.showElementBySoId(datebox2Id+"_DateField_Date"),SuperOffice.SoHelper.showElementBySoId(datebox2Id+"SearchButton"),setDateTime(datebox2Id,getValueHint(operatorId[1]))),g_pageHasChanged=!0}function setDateTime(dateboxId,valueHint){dateboxId=SuperOffice.SoHelper.getElementBySoId(dateboxId+"_DateField_Date");valueHint.ReadOnly?(dateboxId.disabled=!0,dateboxId.value=valueHint.DefaultValue):dateboxId.disabled=!1,g_pageHasChanged=!0}function disableControl(soId){SuperOffice.SoHelper.getElementBySoId(soId).disabled=!0}function enableControl(soId){SuperOffice.SoHelper.getElementBySoId(soId).disabled=!1}function SetDisplayInMain(checkboxId){var checkboxId=document.getElementById(checkboxId),val="0";null!=checkboxId&&checkboxId.checked&&(val="1"),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.UserPreferences.Set","","FindResultDialog","DisplayInMain",val)}function ValueHint(){this.ReadOnly=!1,this.DefaultValue=""}function getValueHint(str){var tmpobj=new ValueHint,str=("R"==str.substring(0,1)?tmpobj.ReadOnly=!0:"W"==str.substring(0,1)&&(tmpobj.ReadOnly=!1),str.split(":"));return 1<str.length&&(tmpobj.DefaultValue=str[1]),tmpobj}function FindSetCheckbox(textboxId,checkboxId){textboxId=SuperOffice.SoHelper.getElementBySoId(textboxId),checkboxId=SuperOffice.SoHelper.getElementBySoId(checkboxId);""!=textboxId.value?checkboxId.checked=!0:checkboxId.checked=!1,g_pageHasChanged=!0}function CriterionResize(height){Dialog.setHeight(height+40);var height=$("#container"),rect=getWindowRectangle();height.resizeTo(rect.getX(),rect.getY())}function CheckResultCount(archiveControl){archiveControl.OnListReceived=new Function("o","CheckResultCount2(o);")}function CheckResultCount2(o){var row,script;so_defined(o)&&1==o.count()&&(o.selectAll(),row=FindResultArchiveArchiveControl.getSelectedRow(),script=row.attributes.ondblclick,eval(script.value))}function _CriterionProxy(soId,entityName){this._soId=soId,this._saveCallbackFunction="",g_currentCriterionEntityName=entityName}_this=ValueHint.prototype,_this=_CriterionProxy.prototype,_this.updatePage=function(proxy,findType,refreshResults){Debug.trace("updatePage","Find"),so_defined(findType)||(findType=""),so_defined(refreshResults)||(refreshResults="false");var proxy=FindSoProtocol(proxy.id),refreshfindresult=(Debug.trace("soprotocol:"+proxy,"Find"),""==findType&&(refreshfindresult=""),"");refreshfindresult+=refreshResults?"refreshfindresult_id=1":"refreshfindresult_id=0",QueuedPageUpdate("soprotocol:"+proxy+"[refresh=true]?"+findType+refreshfindresult,"javascript:SuperOffice.Find.OnActiveRestrictions(null);")},_this.updatePageForSelection=function(proxy,findType){so_defined(findType)||(findType=""),Debug.trace("Updating page for selection","Find");proxy=FindSoProtocol(proxy.id);Debug.trace("soprotocol:"+proxy,"Find"),QueuedPageUpdate("soprotocol:"+proxy+"[refresh=true]?"+findType,"javascript:SuperOffice.Find.OnActiveRestrictions(null);")},_this.savePageForSelection=function(){var soProtocol=FindSoProtocol(SuperOffice.SoHelper.getElementBySoId(this._soId+"_action").id);debug.trace("savePageForSelection: "+soProtocol,"Find"),QueuedPageUpdate("soprotocol:"+soProtocol+"[mode=save]")},_this.savePage=function(saveArg){debug.trace("savePage: "+saveArg,"Find"),saveArg=so_defined(saveArg)?"?"+saveArg:"";var soProtocol=FindSoProtocol(SuperOffice.SoHelper.getElementBySoId(this._soId+"_action").id);debug.trace("savePage: "+soProtocol+"("+saveArg+")","Find"),QueuedPageUpdate("soprotocol:"+soProtocol+"[mode=save]"+saveArg,"")},_this.refreshResults=function(){var proxy=SuperOffice.SoHelper.getElementBySoId(this._soId+"_action");this.updatePage(proxy,"",!0)},_this.executeSearch=function(){debug.trace("executeSearch","Find"),this.savePage()},_this.executeSingleSearch=function(){debug.trace("executeSingleSearch","Find"),this.executeSearch()},_this.saveSearch=function(single,updatePage){debug.trace("saveSearch, "+single+", "+updatePage,"Find"),void 0===updatePage&&(updatePage=!0),_findType=single?g_findtypeSingle:g_findtypeNormal,1==g_pageHasChanged&&(debug.trace("saveSearch, g_pageHasChanged == true","Find"),g_pageHasChanged=!1,(single=SuperOffice.SoHelper.getElementBySoId(this._soId+"_action")).value="save",updatePage)&&this.updatePage(single,_findType,!1),this.executeSearch()},_this.addCriterion=function(archiveRestrictionInfo){Debug.trace("Adding criterion","Find");var proxy,archiveRestrictionInfo=archiveRestrictionInfo.getValue();Debug.trace("joson string:"+archiveRestrictionInfo,"Find"),null!=archiveRestrictionInfo&&(proxy=SuperOffice.SoHelper.getElementBySoId(this._soId+"_add"),Debug.trace("Proxy ok? - "+proxy.id,"Find"),proxy.value=archiveRestrictionInfo,this.saveSearch(),this.updatePage(proxy,"",!1))},_this.addCriterionForSelection=function(archiveRestrictionInfo){Debug.trace("Adding criterion","Find");var proxy,archiveRestrictionInfo=archiveRestrictionInfo.getValue();Debug.trace("joson string:"+archiveRestrictionInfo,"Find"),null!=archiveRestrictionInfo&&(proxy=SuperOffice.SoHelper.getElementBySoId(this._soId+"_add"),Debug.trace("Proxy ok? - "+proxy.id,"Find"),proxy.value=archiveRestrictionInfo,this.updatePageForSelection(proxy))},_this.removeCriterion=function(id){var proxy=SuperOffice.SoHelper.getElementBySoId(this._soId+"_remove");proxy.value=id,this.saveSearch(),this.updatePage(proxy,"",!1)},_this.removeCriterionForSelection=function(id){var proxy=SuperOffice.SoHelper.getElementBySoId(this._soId+"_remove");proxy.value=id,this.updatePageForSelection(proxy)},_this.toggleCriterion=function(name){var proxy=SuperOffice.SoHelper.getElementBySoId(this._soId+"_toggle");proxy.value=name,debug.trace("toggleCriterion: "+proxy.id,"Find"),-1<this._soId.indexOf("StaticMemberCriterionProxy")&&this.saveSearch(),this.updatePage(proxy,"",!1)},_this.addMemberToggleCriterion=function(name){debug.trace("addMemberToggleCriterion: "+name,"Find");var proxy=SuperOffice.SoHelper.getElementBySoId(this._soId+"_toggle");proxy.value=name,debug.trace("addMemberToggleCriterion, proxy: "+proxy.id,"Find"),this.saveSearch()},_this.setActive=function(active){var proxy=SuperOffice.SoHelper.getElementBySoId(this._soId+"_toggle");proxy.value="set:"+active,-1<this._soId.indexOf("StaticMemberCriterionProxy")&&this.saveSearch(),this.updatePage(proxy,"",!1)},_this.SaveStaticAddMembers=function(){g_pageHasChanged=!0,this.saveSearch(!1,!1),this.savePage("addmemberdosave_name=dosave")},SuperOffice.BaseClass=(()=>{var pub=Object.create(Object.prototype);return pub.pubStr="Public string",pub.doTest=function(){console.log("BaseClass:privStr"),console.log("BaseClass:"+this.pubStr);var that=this;setTimeout(function(){console.log("BaseClass delayed:privStr"),console.log("BaseClass delayed:"+that.pubStr)},100)},pub})(),SuperOffice.DynamicListView=(()=>{var pub=Object.create(SuperOffice.BaseClass);return pub.dynamicStr="DynamicListView",pub.doAnotherTest=function(){return console.log("DynamicListView:"+this.dynamicStr),console.log("DynamicListView:"+this.pubStr),this.doTest(),!0},pub})(),SuperOffice.Find.CriteriaControlManager=Object.create(SuperOffice.DynamicListView),SuperOffice.Find.CriteriaControlManager.__class=!0,SuperOffice.Find.CriteriaControlManager.CriteriaControls={},SuperOffice.Find.CriteriaControlManager.OpenDialogOnShow=!0,SuperOffice.Find.CriteriaControlManager.CurrentSelected="",SuperOffice.Find.CriteriaControlManager.CurrentDialogSoProtocol="",SuperOffice.Find.CriteriaControlManager.CurrentDialogName="",SuperOffice.Find.CriteriaControlManager.CurrentCriteriaControl=null,SuperOffice.Find.CriteriaControlManager.add=function(criteriaControl){criteriaControl.onChangeEvent=function(cc,ari){SuperOffice.Find.CriteriaControlManager.criteriaChanged(criteriaControl,ari)},criteriaControl.onDeleteEvent=function(cc,ari){SuperOffice.Find.CriteriaControlManager.criteriaDeleted(criteriaControl,ari)},criteriaControl.onAddEvent=function(cc,ari){SuperOffice.Find.CriteriaControlManager.criteriaAdded(criteriaControl,ari)},criteriaControl.onCriteriaReplaceEvent=function(cc,ari){SuperOffice.Find.CriteriaControlManager.criteriaReplaced(criteriaControl,ari)},criteriaControl.onValueHintChanged=function(cc,ari){SuperOffice.Find.CriteriaControlManager.valueHintChanged(criteriaControl,ari)},criteriaControl.onDialogCallback=function(cc,ari){SuperOffice.Find.CriteriaControlManager.dialogCallback(criteriaControl,ari)},criteriaControl.onRowSelectEvent=function(cc){SuperOffice.Find.CriteriaControlManager.rowSelect(criteriaControl)},criteriaControl.onNoRowSelectEvent=function(cc){SuperOffice.Find.CriteriaControlManager.noRowSelect(criteriaControl)},this.CriteriaControls[criteriaControl.id]=criteriaControl,SuperOffice.Find.CriteriaControlManager.CurrentCriteriaControl=criteriaControl,$(document).on("keyup",function(event){"45"==event.keyCode&&SuperOffice.Find.CriteriaControlManager.getCriteriaControl(criteriaControl.id).onAddClick(criteriaControl.id),"114"==event.keyCode&&SuperOffice.Find.CriteriaControlManager.currentResultArchiveControl&&SuperOffice.Find.CriteriaControlManager.doFind()});var that=this;PageEventHandler.addEvent(EventType.ONBEFOREVIEWCHANGE,"findsavecriteriaonviewchange",function(){null!=that.CurrentCriteriaControl&&that.saveRestrictions(that.CurrentCriteriaControl)}),PageEventHandler.addEvent(EventType.ONPAGEUNLOAD,"findsavecriteriaonunload",function(){null!=that.CurrentCriteriaControl&&that.saveRestrictions(that.CurrentCriteriaControl)})},SuperOffice.Find.CriteriaControlManager.disableCurrentCriteriaControl=function(){null!=this.CurrentCriteriaControl&&this.CurrentCriteriaControl.disable()},SuperOffice.Find.CriteriaControlManager.saveRestrictions=function(criteriaControl,callback){var saveMethod;criteriaControl.isDirty?(this.updateStateObject(criteriaControl),debug.trace("saveRestrictions, len: "+criteriaControl.criteriaState.Restrictions.length,"CriteriaControlManager"),saveMethod=""!==criteriaControl.criteriaState.SaveMethod?criteriaControl.criteriaState.SaveMethod:"FindCriteriaList/SaveRestrictions",UIHelper.GetMainPageWindow().$clientapi.post(saveMethod,{criteriaState:criteriaControl.criteriaState},null,!0).then(function(){criteriaControl.isDirty=!1,callback&&callback()})):callback&&callback()},SuperOffice.Find.CriteriaControlManager.saveRestrictionsToSelection=function(criteriaControl){this.updateStateObject(criteriaControl);var membermode=SuperOffice.Util.getCurrentId("membermode");1===membermode?SuperOffice.Toast.show(ResourceUtils.GetResourceText("[SR_SELECTION_REMOVING_MEMBERS]"),SuperOffice.Toast.Wait):SuperOffice.Toast.show(ResourceUtils.GetResourceText("[SR_SELECTION_ADDING_MEMBERS]"),SuperOffice.Toast.Wait),UIHelper.GetMainPageWindow().$clientapi.post("FindCriteriaList/SaveRestrictionsToSelection",{criteriaState:criteriaControl.criteriaState},null,!0).then(function(res){SuperOffice.Toast.close();res=1!=membermode?ResourceUtils.GetResourceText("[SR_SELECTION_ADDED_MEMBERS]").replace("{0}",res):ResourceUtils.GetResourceText("[SR_SELECTION_REMOVED_MEMBERS]").replace("{0}",-1*res);UIHelper.GetMainPageWindow().SuperOffice.Toast.show(res,SuperOffice.Toast.Confirm),criteriaControl.isDirty=!1,Dialog.closeWithCallback()})},SuperOffice.Find.CriteriaControlManager.getCriteriaControl=function(id){return this.CriteriaControls[id]},SuperOffice.Find.CriteriaControlManager.valueHintChanged=function(criteriaControl,ari){criteriaControl.isDirty=!0,this.sendChangeEvent(criteriaControl),this.saveStateAndRefresh(criteriaControl,ari)},SuperOffice.Find.CriteriaControlManager.dialogCallback=function(criteriaControl,ari){null!=ari&&(debug.trace("dialogCallback: "+ari.UniqueHash,"FindInline"),criteriaControl.isDirty=!0,this.saveStateAndRefresh(criteriaControl,ari))},SuperOffice.Find.CriteriaControlManager.criteriaChanged=function(criteriaControl,ari){criteriaControl.isDirty=!0,this.sendChangeEvent(criteriaControl),this.setResultStatus(criteriaControl)},SuperOffice.Find.CriteriaControlManager.sendChangeEvent=function(criteriaControl){var fn;""!==criteriaControl.criteriaState.OnChangedEvent&&(fn=new Function("criteriaControl",criteriaControl.criteriaState.OnChangedEvent),SuperOffice.Throttle.run("onchange"+criteriaControl.id,1e3,function(){fn(criteriaControl)}))},SuperOffice.Find.CriteriaControlManager.hasActiveAndVisibleRows=function(criteriaControl){debug.trace("Number of Restrictions: "+criteriaControl.criteriaState.Restrictions.length,"FindInline");for(var t=0;t<criteriaControl.criteriaState.Restrictions.length;++t)if(criteriaControl.criteriaState.Restrictions[t].IsActive&&criteriaControl.criteriaState.Restrictions[t].IsVisible)return!0;return!1},SuperOffice.Find.CriteriaControlManager.setResultStatus=function(criteriaControl){debug.trace("setResultStatus","FindInline"),UIHelper.EnableToolButtonBySoId("FindButton");var that,toolButtonSoId,ac=this.currentResultArchiveControl;"object"==typeof ac?(that=this,SuperOffice.Find.CriteriaControlManager.hasActiveAndVisibleRows(criteriaControl)?(debug.trace("Active and Visible rows.","FindInline"),ac.ShowEmptyListLink({headingText:" ",linkText:ResourceUtils.GetResourceText("[SR_FT_SEARCH]"),link:function(){that.doFind()}}),toolButtonSoId=criteriaControl.id+"_2",UIHelper.EnableToolButtonBySoId(toolButtonSoId)):(debug.trace("No active and Visible rows.","FindInline"),ac.ShowEmptyListLink({headingText:" ",linkText:ResourceUtils.GetResourceText("[SR_SEARCH_FIX_CRITERIA]"),link:function(){that.CurrentCriteriaControl.selectOrAdd()}}),UIHelper.DisableToolButtonBySoId("FindButton"),toolButtonSoId=criteriaControl.id+"_2",UIHelper.DisableToolButtonBySoId(toolButtonSoId))):debug.trace("ArchiveControl not found.","FindInline")},SuperOffice.Find.CriteriaControlManager.addOnNoRowSelect=function(fn){this.fnNoRowSelectArray=this.fnNoRowSelectArray||[],this.fnNoRowSelectArray.push(fn)},SuperOffice.Find.CriteriaControlManager.noRowSelect=function(){$.each(this.fnNoRowSelectArray,function(i,v){v.call()})},SuperOffice.Find.CriteriaControlManager.addOnRowSelect=function(fn){this.fnRowSelectArray=this.fnRowSelectArray||[],this.fnRowSelectArray.push(fn)},SuperOffice.Find.CriteriaControlManager.rowSelect=function(){$.each(this.fnRowSelectArray,function(i,v){v.call()})},SuperOffice.Find.CriteriaControlManager.criteriaDeleted=function(criteriaControl,ari){criteriaControl.isDirty=!0,this.sendChangeEvent(criteriaControl),this.updateStateObject(criteriaControl);var ac=this.currentResultArchiveControl;ac&&(ac.ClearList(),this.setResultStatus(criteriaControl),this.noRowSelect(),-1===criteriaControl.getFirstVisibleCriteriaIndex())&&debug.trace("criteriaControl has empty restrictionlist","FindInline")},SuperOffice.Find.CriteriaControlManager.criteriaAdded=function(criteriaControl,ari){this.saveStateAndRefresh(criteriaControl,ari,!0)},SuperOffice.Find.CriteriaControlManager.criteriaReplaced=function(criteriaControl,ari){this.sendChangeEvent(criteriaControl),this.saveStateAndRefresh(criteriaControl,ari,!1)},SuperOffice.Find.CriteriaControlManager.setCurrent=function(id){this.currentId=id},SuperOffice.Find.CriteriaControlManager.doFind=function(){this.getCriteriaControl(this.currentId).onFindClick(this.currentResultArchiveControl)},SuperOffice.Find.CriteriaControlManager.setSelectedAndClose=function(){this.OpenDialogOnShow&&""!=this.CurrentDialogSoProtocol?this.openEditDialog():""!=this.CurrentSelected&&this.setSelected(this.CurrentSelected,this.CurrentIsDialog),Dialog.closeWithCallback()},SuperOffice.Find.CriteriaControlManager.openEditDialog=function(){""!=this.CurrentDialogSoProtocol&&UIHelper.GetOpener().Dialog.open(this.CurrentDialogName,this.CurrentDialogSoProtocol)},SuperOffice.Find.CriteriaControlManager.setSelected=function(soprotocol,isDialog){debug.trace("setSelected: "+soprotocol,"FindInline"),so_defined(UIHelper.GetOpener().QueuedPageUpdate)&&(UIHelper.GetOpener().QueuedPageUpdate("soprotocol:"+soprotocol),isDialog)&&this.openEditDialog()},SuperOffice.Find.CriteriaControlManager.FindOnSingleClick=function(mainPageSoProtocol,bOpenDialog,dialogName,dialogSoProtocol){debug.trace("FindOnSingleClick: "+mainPageSoProtocol,"FindInline"),this.CurrentDialogSoProtocol=dialogSoProtocol,this.CurrentDialogName=dialogName,this.CurrentSelected=mainPageSoProtocol,this.CurrentIsDialog=bOpenDialog,SuperOffice.Find.DisplayInMainWindow&&this.setSelected(mainPageSoProtocol,bOpenDialog)},SuperOffice.Find.CriteriaControlManager.FindOnDblClick=function(mainPageSoProtocol,bOpenDialog,dialogName,dialogSoProtocol){this.CurrentDialogSoProtocol=dialogSoProtocol,this.CurrentDialogName=dialogName,this.CurrentSelected=mainPageSoProtocol,this.CurrentIsDialog=bOpenDialog,SuperOffice.Find.DisplayInMainWindow||(debug.trace("FindOnDblClick: "+SuperOffice.Find.DisplayInMainWindow,"FindInline"),this.setSelected(mainPageSoProtocol,bOpenDialog)),setTimeout("Dialog.closeWithCallback()",250)},SuperOffice.Find.CriteriaControlManager.FindSingleOnSingleClick=function(soprotocol,archiveControl){for(var rows=archiveControl.getSelectedRows(),retVal="",i=0;i<rows.length;i++)""!=retVal&&(retVal+="|,|"),retVal+=GetPrimaryKeyFromRow(rows[i])+"|%|"+UIHelper.GetInnerText(rows[i].cells[1])+"|%|"+rows[i].attributes.rowtype.value;var urlParams=location.search.substring(1),script;null!=urlParams&&"undefined"!=urlParams&&-1!=urlParams.indexOf(g_findtypeAttachment)?(script=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetAddAttachmentScript","",retVal),eval(script)):Dialog.setParentReturnObject(1,retVal)},SuperOffice.Find.CriteriaControlManager.FindSingleOnDblClick=function(soprotocol,archiveControl){this.FindSingleOnSingleClick(soprotocol,archiveControl),setTimeout("Dialog.closeWithCallback()",500)},SuperOffice.Find.CriteriaControlManager.saveStateAndRefresh=function(criteriaControl,ari,isAdd){this.updateStateObject(criteriaControl),this.refresh(criteriaControl,isAdd)},SuperOffice.Find.CriteriaControlManager.refresh=function(criteriaControl,isAdd){var soProtocol=FindSoProtocol($("[soid="+criteriaControl.id+"]")[0].id),isAdd=1==(isAdd=so_defined(isAdd)?isAdd:!1)?"isAdd=true":"",scrollTop=$.fromSoId(criteriaControl.id).scrollTop();debug.trace("saveStateAndRefresh: "+soProtocol,"FindInline");PageUpdate("soprotocol:"+soProtocol+"[Request=Callback&mode=edit]?"+isAdd,function(){$.fromSoId(criteriaControl.id).scrollTop(scrollTop)})},SuperOffice.Find.CriteriaControlManager.resetRestrictions=function(criteriaControlId){debug.trace("Reset Restrictions","FindInline");var criteriaControl=this.getCriteriaControl(criteriaControlId),that=(criteriaControl.criteriaState.Restrictions=[],criteriaControl.isDirty=!0,this);this.saveRestrictions(criteriaControl,function(){criteriaControl.criteriaState="",that.updateStateObject(criteriaControl),that.refresh(criteriaControl,!1)})},SuperOffice.Find.CriteriaControlManager.updateStateObject=function(criteriaControl){var criteriaString=""==criteriaControl.criteriaState?"":JsonHelper.toJSON(criteriaControl.criteriaState);$("[soid="+(criteriaControl.entityName+"_state_"+criteriaControl.id)+"]")[0].value=criteriaString},SuperOffice.Find.CriteriaControlManager.toggleOkButton=function(ac){0<ac.getSelectedRows().length&&UIHelper.EnableToolButtonBySoId("DlgButtonBar_okButton")},SuperOffice.Find.CriteriaControl=Object.create(Object.prototype),SuperOffice.Find.CriteriaControl.__class=!0,SuperOffice.Find.CriteriaControl.id="",SuperOffice.Find.CriteriaControl.element=null,SuperOffice.Find.CriteriaControl.criteriaState=null,SuperOffice.Find.CriteriaControl.isDirty=!1,SuperOffice.Find.CriteriaControl.entityName="",SuperOffice.Find.CriteriaControl.scrollTop=0,SuperOffice.Find.CriteriaControl.hasBlankRow=!1,SuperOffice.Find.CriteriaControl.onChangeEvent=null,SuperOffice.Find.CriteriaControl.onDeleteEvent=null,SuperOffice.Find.CriteriaControl.onRowSelectEvent=null,SuperOffice.Find.CriteriaControl.onNoRowSelectEvent=null,SuperOffice.Find.CriteriaControl.onAddEvent=null,SuperOffice.Find.CriteriaControl.onCriteriaReplaceEvent=null,SuperOffice.Find.CriteriaControl.onValueHintChanged=null,SuperOffice.Find.CriteriaControl.onDialogCallback=null,SuperOffice.Find.CriteriaControl.lastRowIndexSelected=-1,SuperOffice.Find.CriteriaControl.controlCache={},SuperOffice.Find.CriteriaControl.controlCache.isActive={},SuperOffice.Find.CriteriaControl._getRowIsActiveCheckBox=function(uniqueHash){var elem,checkbox=null;return null==SuperOffice.Find.CriteriaControl.controlCache.isActive[uniqueHash]?0<(elem=$("[isactive_uniquehash="+uniqueHash+"] INPUT")).length&&(checkbox=elem[0]):(debug.trace("_getRowIsActiveCheckBox, using cache","FindInline"),checkbox=SuperOffice.Find.CriteriaControl.controlCache.isActive[uniqueHash]),checkbox},SuperOffice.Find.CriteriaControl.disable=function(){SuperOffice.SoHelper.disableElement($.fromSoId(this.id).parent().get(0)),$.fromSoId(this.id).parent().find("*").attr("onmousedown","return false").attr("onmousemove","return false").attr("onmouseup","return false").attr("onclick","return false").attr("ondblclick","return false").attr("disabled","disabled")},SuperOffice.Find.CriteriaControl._getRowValueTextBox=function(uniqueHash){var textbox=null,uniqueHash=$("[value_uniquehash="+uniqueHash+"]");return textbox=0<uniqueHash.length?uniqueHash[0]:textbox},SuperOffice.Find.CriteriaControl.getArchiveRestrictionInfoByName=function(name){for(var ari=null,t=0;t<this.criteriaState.Restrictions.length;++t)if(this.criteriaState.Restrictions[t].Name==name){ari=this.criteriaState.Restrictions[t];break}return ari},SuperOffice.Find.CriteriaControl.getArchiveRestrictionInfo=function(uniqueHash){for(var ari=null,t=0;t<this.criteriaState.Restrictions.length;++t)if(this.criteriaState.Restrictions[t].UniqueHash==uniqueHash){ari=this.criteriaState.Restrictions[t];break}return ari},SuperOffice.Find.CriteriaControl.setArchiveRestrictionInfo=function(ari){if(null==ari)return null;for(var t=0;t<this.criteriaState.Restrictions.length;++t)if(this.criteriaState.Restrictions[t].UniqueHash==ari.UniqueHash){this.criteriaState.Restrictions[t]=ari;break}return ari},SuperOffice.Find.CriteriaControl.openExternalDialog=function(uniqueHash){var ari=this.getArchiveRestrictionInfo(uniqueHash),script=AjaxMethodDispatcher.CallSync(" SuperOffice.CRM.Web.UI.Controls.FindCriteriaList.OpenCriteriaDialog","",this.id,this.entityName,ari.ColumnInfo.Name,this.criteriaState);eval(script)},SuperOffice.Find.CriteriaControl.externalDialogCallback=function(res){var ari=eval("("+res.getValue()+")");this.setArchiveRestrictionInfo(ari),null!=this.onDialogCallback&&this.onDialogCallback(this,ari)},SuperOffice.Find.CriteriaControl.doChange=function(ari,changeDelegate){this.isDirty=!0,changeDelegate(ari),null!=this.onChangeEvent&&this.onChangeEvent(this,ari)},SuperOffice.Find.CriteriaControl.deActivateAll=function(){for(var hash,t=0;t<this.criteriaState.Restrictions.length;++t)this.criteriaState.Restrictions[t].IsActive&&(hash=this.criteriaState.Restrictions[t].UniqueHash,this.setCheckedValue(hash,!1));return!1},SuperOffice.Find.CriteriaControl.setCheckedValue=function(uniqueHash,checked){this.setRowIsActive(uniqueHash,checked),this.toggleActive(uniqueHash)},SuperOffice.Find.CriteriaControl.toggleActive=function(uniqueHash){var isChecked=this.getRowIsActive(uniqueHash),ari=this.getArchiveRestrictionInfo(uniqueHash);null!=ari&&this.doChange(ari,function(){ari.IsActive=isChecked})},SuperOffice.Find.CriteriaControl.getRowIsActive=function(uniqueHash){var isChecked=!1,uniqueHash=this._getRowIsActiveCheckBox(uniqueHash);return isChecked=null!=uniqueHash?uniqueHash.checked:isChecked},SuperOffice.Find.CriteriaControl.setRowIsActive=function(uniqueHash,val){uniqueHash=this._getRowIsActiveCheckBox(uniqueHash);null!=uniqueHash&&(uniqueHash.checked=val)},SuperOffice.Find.CriteriaControl.getRowIndex=function(uniqueHash){for(var index=-1,t=0;t<this.criteriaState.Restrictions.length;++t)if(this.criteriaState.Restrictions[t].UniqueHash==uniqueHash){index=t;break}return index},SuperOffice.Find.CriteriaControl.getRowValue=function(uniqueHash){var valArray=new Array,ari=this.getArchiveRestrictionInfo(uniqueHash);if(null!=ari)switch(ari.ColumnInfo.RestrictionType){case"string":case"positiveString":case"stringorPK":case"date":case"datetime":case"reporterDate":case"int":case"decimal":for(var elem=$("[value_uniquehash="+uniqueHash+"]"),i=0;i<elem.length;i++)valArray.push(elem[i].value);break;case"boolean":case"bool":valArray.push($("[value_uniquehash="+uniqueHash+"] input:checked").val())}return valArray},SuperOffice.Find.CriteriaControl.getRowDisplayValue=function(uniqueHash){var valArray=new Array,ari=this.getArchiveRestrictionInfo(uniqueHash);if("stringorPK"===ari.ColumnInfo.RestrictionType)for(var elem=$("[displayvalue_uniquehash="+uniqueHash+"]"),i=0;i<elem.length;i++)valArray.push(elem[i].value);return valArray},SuperOffice.Find.CriteriaControl.updateCriteriaStateValue=function(uniqueHash){for(var val=this.getRowValue(uniqueHash),disVal=this.getRowDisplayValue(uniqueHash),i=0;i<val.length;i++){var ari=this.getArchiveRestrictionInfo(uniqueHash);null!=ari&&this.doChange(ari,function(){ari.Values[i]=val[i],disVal.length>i&&(ari.DisplayValues[i]=disVal[i])})}},SuperOffice.Find.CriteriaControl.onOperatorChange=function(uniqueHash,mdoControl){mdoControl.getSelectedValue();var operatorType=$("[soid=operator"+uniqueHash.replace("-","_")+"_SelectedType]")[0].value,ari=(mdoControl.getSelectedExtraInfo(),this.getArchiveRestrictionInfo(uniqueHash)),that=this;null!=ari&&this.doChange(ari,function(){var hasChangedValueType=ari.OperatorValueHint!=mdoControl.getSelectedExtraInfo();if(ari.Operator=operatorType,ari.OperatorValueHint=mdoControl.getSelectedExtraInfo(),ari.IsOperatorChange=!0,hasChangedValueType&&null!=that.onValueHintChanged){for(var i=0;i<ari.Values.length;i++)ari.Values[i]="";that.setCheckedValue(uniqueHash,!0),that.onValueHintChanged(ari)}})},SuperOffice.Find.CriteriaControl.onFindClick=function(archiveControl){archiveControl.OnListReceived||(archiveControl.OnListReceived=function(trp){0===trp.count()&&archiveControl.ShowEmptyListLink({headingText:ResourceUtils.GetResourceText("[SR_SEARCH_NOHITS]"),linkText:ResourceUtils.GetResourceText("[SR_FT_SEARCH]"),link:function(){SuperOffice.Find.CriteriaControlManager.doFind()}})}),archiveControl._archiveControlContext.ArchiveRestrictionInfo=this.criteriaState.Restrictions,archiveControl.RefreshList(),SuperOffice.Find.CriteriaControlManager.updateStateObject(this)},SuperOffice.Find.CriteriaControl.selectOrAdd=function(criteriaControlId){-1<this.getFirstVisibleCriteriaIndex()?this.setRowSelected(this.criteriaState.Restrictions[this.getFirstVisibleCriteriaIndex()].UniqueHash):this.onAddClick(criteriaControlId)},SuperOffice.Find.CriteriaControl.onAddClick=function(criteriaControlId){var insertedElem,uniqueHash,selector,that;this.hasBlankRow||(this.deselectRows(),(insertedElem=$("[soid="+this.id+"_emptyrow]").children().clone()).appendTo("[soid="+this.id+"]"),uniqueHash=this.criteriaState.EmptyRestriction.UniqueHash+"_",selector="[soid=field"+uniqueHash.replace("-","_")+"Field] [type=text]",that=this,$(selector).first().trigger("click"),setTimeout(function(){that.onRowClick(null,insertedElem,uniqueHash),$(selector).trigger("focus"),$(selector).mouseout()},50),$.fromSoId(this.id).scrollTop(9999),this.hasBlankRow=!0)},SuperOffice.Find.CriteriaControl.onAddCriteria=function(mdoObject,uniqueHash){mdoObject.getSelectedValue();mdoObject=SuperOffice.SoHelper.getInputElementBySoId("field"+uniqueHash.replace("-","_")+"_Field_SelectedType").value;this.criteriaState.EmptyRestriction.Name=mdoObject,this.criteriaState.Restrictions.push(this.criteriaState.EmptyRestriction),null!=this.onAddEvent&&this.onAddEvent(this,this.criteriaState.EmptyRestriction)},SuperOffice.Find.CriteriaControl.onChangeCriteria=function(mdoObject,uniqueHash){mdoObject.getSelectedValue();mdoObject=SuperOffice.SoHelper.getInputElementBySoId("field"+uniqueHash.replace("-","_")+"_Field_SelectedType").value,uniqueHash=this.getArchiveRestrictionInfo(uniqueHash);uniqueHash.UniqueHash=0,uniqueHash.Name=mdoObject,null!=this.onCriteriaReplaceEvent&&this.onCriteriaReplaceEvent(this,uniqueHash)},SuperOffice.Find.CriteriaControl.onValueEditKeyUp=function(event,uniqueHash){var isValueEmpty=""==this.getRowValue(uniqueHash).join();isValueEmpty==this.getRowIsActive(uniqueHash)&&this.setCheckedValue(uniqueHash,!isValueEmpty),null!=event&&13==event.keyCode&&(this.updateCriteriaStateValue(uniqueHash),SuperOffice.Find.CriteriaControlManager.doFind())},SuperOffice.Find.CriteriaControl.deselectRows=function(){$.fromSoId(this.id).children("TABLE").removeClass("findinlineselected"),this.lastRowIndexSelected=-1},SuperOffice.Find.CriteriaControl.onPanelClick=function(e,panelElement){return this.deselectRows(),null!=this.onNoRowSelectEvent&&this.onNoRowSelectEvent(this),JsHelper.CancelBubble(e)},SuperOffice.Find.CriteriaControl.setRowSelected=function(uniqueHash){var jQueryRows=$.fromSoId(this.id).children("[uniquehash="+uniqueHash+"]");0<jQueryRows.length&&($.fromSoId(this.id).scrollTop(jQueryRows[0].offsetTop),this.onRowClick(null,jQueryRows[0],uniqueHash))},SuperOffice.Find.CriteriaControl.onRowClick=function(e,rowElement,uniqueHash){if((e=null==e?{shiftKey:!1,ctrlKey:!1}:e).shiftKey){var index=this.getRowIndex(uniqueHash);if(-1<this.lastRowIndexSelected&&this.lastRowIndexSelected!=index){$(rowElement).parent().children("TABLE").removeClass("findinlineselected");for(var t=Math.min(this.lastRowIndexSelected,index);t<=Math.max(this.lastRowIndexSelected,index);++t)$(rowElement).parent().children("[uniquehash="+this.criteriaState.Restrictions[t].UniqueHash+"]").addClass("findinlineselected");return-1==this.lastRowIndexSelected&&(this.lastRowIndexSelected=index),null!=this.onRowSelectEvent&&this.onRowSelectEvent(this),JsHelper.CancelBubble(e)}}return e.ctrlKey||$(rowElement).parent().children("TABLE").removeClass("findinlineselected"),$(rowElement).toggleClass("findinlineselected",""),this.lastRowIndexSelected=this.getRowIndex(uniqueHash),null!=this.onRowSelectEvent&&this.onRowSelectEvent(this),JsHelper.CancelBubble(e)},SuperOffice.Find.CriteriaControl.onDeleteClick=function(){var that=this;$.fromSoId(this.id).children("TABLE").each(function(index){var uniqueHash;$(this).hasClass("findinlineselected")&&(uniqueHash=$(this).attr("uniquehash"),-1<(index=that.getRowIndex(parseInt(uniqueHash))))&&(uniqueHash=that.getArchiveRestrictionInfo(uniqueHash),that.criteriaState.Restrictions.splice(index,1),null!=that.onDeleteEvent)&&that.onDeleteEvent(that,uniqueHash)}),this.isIEmptyRowSelected()&&(this.hasBlankRow=!1),$.fromSoId(this.id).children("TABLE").remove(".findinlineselected")},SuperOffice.Find.CriteriaControl.isIEmptyRowSelected=function(){return!!$.fromSoId(this.id).children("[class$=findinlineselected][isnew$=true]").length},SuperOffice.Find.CriteriaControl.moveRestrictionUpOrDown=function(row,moveUp){if(this.isIEmptyRowSelected())return!1;var sibling,deltaPos=1==moveUp?-1:1,uniqueHash=row.attr("uniquehash"),index=this.getRowIndex(parseInt(uniqueHash)),that=(moveUp?(sibling=row.prev(),row.remove().insertBefore(sibling)):(sibling=row.next(),row.remove().insertAfter(sibling)),this);this.doChange(this.getArchiveRestrictionInfo(uniqueHash),function(){var x=that.criteriaState.Restrictions[index+deltaPos];that.criteriaState.Restrictions[index+deltaPos]=that.criteriaState.Restrictions[index],that.criteriaState.Restrictions[index]=x})},SuperOffice.Find.CriteriaControl.onMoveUpClick=function(){var firstUniqueHash,firstVisibleCriteriaIndex,that,selectedRows=$.fromSoId(this.id).children(".findinlineselected");0!=selectedRows.length&&(firstUniqueHash=selectedRows.first().attr("uniquehash"),firstUniqueHash=this.getRowIndex(parseInt(firstUniqueHash)),firstVisibleCriteriaIndex=this.getFirstVisibleCriteriaIndex(),that=this,-1<firstVisibleCriteriaIndex)&&firstVisibleCriteriaIndex<firstUniqueHash&&selectedRows.each(function(){that.moveRestrictionUpOrDown($(this),!0)})},SuperOffice.Find.CriteriaControl.onMoveDownClick=function(){var selectedRows=$.fromSoId(this.id).children(".findinlineselected");if(0!=selectedRows.length){var lastUniqueHash=selectedRows.last().attr("uniquehash"),lastUniqueHash=this.getRowIndex(parseInt(lastUniqueHash));if(lastUniqueHash<this.criteriaState.Restrictions.length-1)for(var t=selectedRows.length-1;0<=t;--t)this.moveRestrictionUpOrDown($(selectedRows[t]),!1)}},SuperOffice.Find.CriteriaControl.getFirstVisibleCriteriaIndex=function(){for(var t=0;t<this.criteriaState.Restrictions.length;++t)if(this.criteriaState.Restrictions[t].IsVisible)return t;return-1},SuperOffice.Find.CriteriaControl.setSelectedRestrictionNames=function(e,mdoControl){for(var existingRestrictionNames="",t=0;t<this.criteriaState.Restrictions.length;++t)""!=existingRestrictionNames&&(existingRestrictionNames+=";"),existingRestrictionNames+=this.criteriaState.Restrictions[t].Name;mdoControl.setExtraInfo(mdoControl.g_extraInfo+(existingRestrictionNames=""!=existingRestrictionNames?"~"+existingRestrictionNames:existingRestrictionNames))},SuperOffice.Find.CriteriaControl.changeStaticContactCriteria=function(name,value){var restrictionValue=value+"",ari=("boolean"==typeof value&&(restrictionValue=value?"[I:1]":"[I:0]",value=value?"1":"0"),this.getArchiveRestrictionInfoByName(name));null!=ari&&this.doChange(ari,function(){ari.Values[0]=restrictionValue,ari.DisplayValues[0]=value})},extendNs("SuperOffice.Controls.FreeTrial",function(ns){var $=jQuery,urlDispatcher=getNs("SuperOffice.Util.UrlDispatcher");ns.checkFreeTrialUrlFromService=function(soid){var freeTrialServiceUrl=urlDispatcher.GetUrlWithSchemeTranslation("FreeTrialBuyNowUrl");$.ajax({url:freeTrialServiceUrl,success:function(data){void 0!==data&&0<data.Url.length?($.fromSoId(soid).css({visibility:"",display:""}),$.fromSoId(soid).parent().css({visibility:"",display:""}),$.fromSoId(soid).on("click",function(){AjaxMethodDispatcher.CallASync("","","","","SuperOffice.DCF.Web.AjaxMethods.SuperState.LogCustomSoProtocol","FreeTrial.BuyNow"),window.open(data.Url)})):$.fromSoId(soid).css({visibility:"hidden",display:"none"})},timeout:2e3})}}),extendNs("SuperOffice.Controls",function(ns){var $=jQuery;ns.IconSelector=function(icons,container,valueCtrl){function getNumPages(numIcons){var rounded=Math.round(numIcons/pageSize);return rounded*pageSize<numIcons?rounded+1:rounded}function getIsDisabled(control){return"true"===$(this).attr("disabled")}function renderPage(pageNum){for(var firstPage=1===pageNum,lastPage=pageNum===totalPages,container=$(".container",self.control),pageIcons=($(".previous",container).attr({disabled:firstPage}),$(".next",container).attr({disabled:lastPage}),container.empty(),getPageIcons(pageNum)),i=0;i<pageIcons.length;i++)(i=>{var icon=pageIcons[i];(i=$("<img src='"+icon.iconSrc+"' class='icon' />")).on("click",function(e){return onClick(icon),e.preventDefault(),!1}),container.append(i)})(i)}var self=this,pageSize=(self.controlContainer=container,self.valueCtrl=valueCtrl,self.icons=icons,36),currentPage=1,getPageIcons=function(pageNum){var pageNum=(pageNum-1)*pageSize,end=pageNum+pageSize;return $(self.icons).slice(pageNum,end)},onClick=function(icon){$(self.valueCtrl).val(JsonHelper.toJSON(icon)),self.control.remove(),setSelectedIcon(icon)},setSelectedIcon=function(icon){$(".previewImage",self.controlContainer).attr("src",icon.iconSrc)},container=(self.nextPage=function(){getIsDisabled()||(currentPage<totalPages&¤tPage++,renderPage(currentPage))},self.prevPage=function(){getIsDisabled()||(1<currentPage&¤tPage--,renderPage(currentPage))},self.renderPage=renderPage,self.getNumPages=getNumPages,self.getPageIcons=getPageIcons,$(self.controlContainer).offset()),valueCtrl=(self.control=$('<div class="iconselector"><div class="navigator"><div type="button" class="SCILButton action round left svgNav_arrow"></div><div type="button" class="SCILButton action round right svgNav_arrow"></div></div><div class="container"></div></div>'),{position:"absolute",zIndex:"1000",top:container.top+20,left:container.left+20}),totalPages=(self.control.css(valueCtrl),$(document.body).append(self.control),$(document).on("mousedown.iconselector",function(e){$(self.control).is(":hover")||$(self.control).remove()}),$(".left",self.control).on("click",self.prevPage),$(".right",self.control).on("click",self.nextPage),getNumPages(icons.length));renderPage(currentPage)},ns.IconSelector.init=function(icons,container,valueCtrl){return new ns.IconSelector(icons,container,valueCtrl)},ns.IconSelector.popup=function(container,valueCtrl){var icons=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.UI.Controls.IconSelector.GetApplicationIcons");return ns.IconSelector.init(icons,container,valueCtrl)}});var g_isMainpage=null,g_standaloneDialog=null,g_yellowUpdate=!1,g_splitter=null,g_hSplitter=null,EditMode={READ:0,EDIT:1},g_mdcount=0,g_calendarDay=null,g_calendarMonth=null,g_calendarWeek=null,g_calendarWiew=null,g_miniMonth="",g_currentCalendar=null,g_containerElementId="container",g_viewContainerMarginRight=34,g_viewContainerMarginTop=20,g_pageRefreshed=!0,g_superStateCopy="",g_formIsValid=!0,g_isReport=!1,g_scrollBarWidth=0,g_checkInterval=2,g_currentPageId=null;function loggedOnMailServerCallback(res){res&&UIHelper.EnableSpeedBarButton($.fromSoId("ToolBarEmail_6"))}function loggedOnMailServerError(res){UIHelper.DisableSpeedBarButton($.fromSoId("ToolBarEmail_6"))}function setReport(isReport){g_isReport=isReport}function isReport(){return g_isReport}var g_clientRect=null,classKeyPressOverride=($(window).on("load",function(){var container=$("#container");container&&0!==container.length&&isReport()&&(container.css({width:"99%",height:"100%"}),container.css({visibility:"visible"}))}),function(){}),classKP=(classKeyPressOverride.prototype.toString=function(){return" Class Key Press Override "},classKeyPressOverride.prototype.attachListener=function(type,functionCode){var obj=window.document;obj.eventParent=this,"addEventListener"in obj?obj.addEventListener(type,functionCode,!0):"attachEvent"in obj&&obj.attachEvent("on"+type,functionCode)},classKeyPressOverride.prototype.stopPropagation=function(ev){"stopPropagation"in ev?(ev.stopPropagation(),ev.preventDefault()):(ev.keyCode=0,ev.cancelBubble=!0,ev.returnValue=!1)},new classKeyPressOverride),onReady=(classKP.attachListener("help",classKP.stopPropagation),classKP.attachListener("keydown",function(event,parentClass){var ev=event||window.event,ev=ev.keyCode||ev.which,fKeyPressed=!1;112==ev?(fKeyPressed=!0,Dialog.ShowHelp(g_isMainpage)):113!=ev&&114!=ev&&115!=ev||(fKeyPressed=!0),1==fKeyPressed&&this.eventParent&&this.eventParent.stopPropagation(event)}),$(document).ready(function(){$(document).on("mousedown",function(evt){if("INPUT"!==evt.target.nodeName&&"TEXTAREA"!==evt.target.nodeName&&evt.target.attributes.contenteditable||$(evt.target).first().hasClass("forceSelectable"))return(evt=$(evt.target).first()).hasClass("cdlgbodytext")||evt.hasClass("forceSelectable")?(evt.removeClass("TextUnselectable").addClass("TextSelectable"),!0):!!evt.closest(".TextSelectable").length||void evt.addClass("TextUnselectable")})}),function(){var inner=document.createElement("p"),outer=(inner.style.width="100%",inner.style.height="200px",document.createElement("div")),w1=(outer.style.position="absolute",outer.style.top="0px",outer.style.left="0px",outer.style.visibility="hidden",outer.style.width="200px",outer.style.height="150px",outer.style.overflow="hidden",outer.appendChild(inner),document.body.appendChild(outer),inner.offsetWidth),inner=(outer.style.overflow="scroll",inner.offsetWidth);w1==inner&&(inner=outer.clientWidth),document.body.removeChild(outer),console.log||(console.log=function(){}),window.g_scrollBarWidth=w1-inner}),g_dialogCounter=($(document).ready(onReady),window.getFromSoId=function(soid){return SuperOffice.SoHelper.getElementBySoId(soid)},window.getPlaceholders=function(){return $("[id*='DialogCardPlaceHolder']")},window.unBindLoad=function(){$(document).off("load")},0),g_dialogLastZIndex=98;function InlineDialog(){this._containerId="",this._dialogId="",this._dialogLayer=null,this._isDragging=!1,this._dialogStartPos=new Object,this._mouseStartPos=new Object,this._checkBoxes=new Array,this._radioButtons=new Array,this._radioButtonGroups=[],this._radioButtonGroupValues=new Array,this._context,this._closeCallback="","admin"==g_clientOptions.SubClient?(this._closeImage="../Images/System/Web/Close.png",this._closeImageHover="../Images/System/Web/Close.png"):(this._closeImage="Images/System/Web/Close.png",this._closeImageHover="Images/System/Web/Close.png"),this._textArea=null,this._originalText="",this._postItMinWidth=154,this._postItMinHeight=154,this._paperclipCallback="",this._isDeleted=!1,this._dragLayer=null,this._onDragInitCallback="",this._onDragCancelCallback="",this._onDragMoveCallback="",this._onDragDropCallback="",this._initialMousePosX=0,this._initialMousePosY=0,this._initialDialogWidth=0,this._initialDialogHeight=0,this._clientRectX=0,this._clientRectY=0}InlineDialog.prototype.CreateContainer=function(){var dlgLayer=document.createElement("DIV");dlgLayer.id="dialogContainer"+ ++g_dialogCounter,this._containerId=dlgLayer.id,this._dialogLayer=$(dlgLayer)},InlineDialog.prototype.AddDialogToDocument=function(src){this._dialogLayer.html(src),$(document.forms[0]).append(this._dialogLayer)},InlineDialog.prototype.GetHeight=function(){return this._dialogLayer.children().first().getHeight()},InlineDialog.prototype.GetWidth=function(){return this._dialogLayer.children().first().getWidth()},InlineDialog.prototype.Display=function(src,closeCallback){if(""==src)return!1;this._closeCallback=closeCallback;var midButtonLeft,x,closeCallback=document.createElement("DIV"),src=($(closeCallback).attr("id","dialogContainer"+ ++g_dialogCounter),$(closeCallback).setStyle({position:"absolute",top:"0px",left:"0px",right:"0px",zIndex:++g_dialogLastZIndex}),this._containerId=closeCallback.id,$(closeCallback).append(src),document.forms[0].appendChild(closeCallback),$(closeCallback).children().first()),closeCallback=(this._dialogId=src.attr("soid"),$(getFromSoId(this._dialogId)).find(".cdlgbody")),minHeight=50,imgs=closeCallback.children().first().find("IMG").each(function(){"none"!==$(this).css("float")&&(minHeight=Math.max(minHeight,$(this).position().top+$(this).getHeight()))}),firstBlock=closeCallback.children().first(),that=(0<imgs.length&&0<firstBlock.length&&firstBlock.getHeight()<minHeight&&firstBlock.setStyle({height:minHeight+"px"}),this),buttons=new Array,t=0,inputs=closeCallback.find("INPUT"),left=(inputs.each(function(){switch(this.type.toLowerCase()){case"button":if(so_defined($(this).attr("onclick"))){var inputFnAttrib=$(this).attr("onclick");if(void 0!==inputFnAttrib){let mouseupHandler=function(){return debug.trace("mouseup->onClose","InlineDialog"),that.onClose(Event,inputFnAttrib)};$(this).on("mouseup",function(){mouseupHandler()});var p=$(this).parent();p.hasClass("SoInputButton")&&p.on("mouseup",function(e){mouseupHandler()})}$(this).attr("onclick","")}buttons.push($(this));break;case"checkbox":that._checkBoxes.push(inputs[t]);break;case"radio":var groupId=inputs[t].id.substring(0,inputs[t].id.indexOf("_"));-1===$.inArray(groupId,that._radioButtonGroups)&&that._radioButtonGroups.push(groupId),inputs[t].checked&&(that._radioButtonGroupValues[$.inArray(groupId,that._radioButtonGroups)]=inputs[t].value),$(inputs[t]).on("click",function(e){that.onRadioButtonDown(e,groupId)}),that._radioButtons.push($(inputs[t]))}t+=1}),0<buttons.length&&(imgs=$(buttons[0].parent().parent()),firstBlock=Math.floor(src.getWidth()/2),left=imgs.position().left,midButtonLeft=0,1==buttons.length?midButtonLeft=buttons[0].position().left+$(buttons[0].getWidth()/2):2==buttons.length?midButtonLeft=buttons[buttons.length-1].position().left:3==buttons.length?midButtonLeft=buttons[buttons.length-2].position().left:4==buttons.length&&(midButtonLeft=buttons[buttons.length-3].position().left),firstBlock=Math.max(0,firstBlock-(midButtonLeft+left)),imgs.css({left:left+firstBlock+"px"}),0<(midButtonLeft=imgs.getWidth()-firstBlock+"px"))&&imgs.css({width:midButtonLeft+"px"}),src.setStyle({height:closeCallback.getHeight()+closeCallback.position().top+"px"}),self.innerHeight?(x=self.innerWidth,0):document.documentElement&&document.documentElement.clientHeight?(x=document.documentElement.clientWidth,document.documentElement.clientHeight):document.body&&(x=document.body.clientWidth,document.body.clientHeight),src.getWidth()),firstBlock=$(src).height();return src.setStyle({left:Math.max(0,(x-left)/2)+"px",top:Math.max(0,($(document).height()-firstBlock)/2)+"px"}),this.onOpen(),!0},InlineDialog.prototype.onOpen=function(){var gripLayer=$("#"+this._dialogId+"Grip"),that=this,gripLayer=(gripLayer.on("mousedown",function(e){debug.trace(that._containerId,"InlineDialog"),that._isDragging&&that.onDrop(e),$(that._containerId).setStyle({zIndex:++g_dialogLastZIndex});var dialogLayer=$("#"+that._dialogId);return that._dialogStartPos.x=dialogLayer.position().left,that._dialogStartPos.y=dialogLayer.position().top,that._mouseStartPos.x=Event.pointerX(e),that._mouseStartPos.y=Event.pointerY(e),$(document).on("mousemove.inlinedialog",function(event){var deltaX=Event.pointerX(event)-that._mouseStartPos.x,event=Event.pointerY(event)-that._mouseStartPos.y,dialog=$("#"+that._dialogId),rect=UIHelper.getClientRectangle(),width=dialog.getWidth(),height=dialog.getHeight(),deltaX=Math.max(0,that._dialogStartPos.x+deltaX),event=Math.max(0,that._dialogStartPos.y+event);return deltaX+width>rect[0]&&(deltaX=rect[0]-width),event+height>rect[1]&&(event=rect[1]-height),dialog.setStyle({left:deltaX+"px",top:event+"px"}),!1}),$(document).on("mouseup.inlinedialog",function(e){return debug.trace("onDrop","InlineDialog"),that._isDragging=!1,$(document).off("mousemove.inlinedialog"),$(document).off("mouseup.inlinedialog"),!1}),!(that._isDragging=!0)}),$("#"+this._dialogId+"Close"));0<gripLayer.length&&(SuperOffice.Dialog.currentInlineModalDialog=this,gripLayer.on("click",function(){SuperOffice.Dialog.currentInlineModalDialog.onClose(null,"")}),UIHelper.setHoverImageOnElement(gripLayer,this._closeImage,this._closeImageHover,this._closeImage))},InlineDialog.prototype.onClose=function(e,fn){debug.trace("onClose","InlineDialog");for(var gripLayer=$("#"+this._dialogId+"Grip"),checkBoxValues=(debug.trace("Removing "+this._dialogId,"InlineDialog"),$("#"+this._containerId).remove(),[]),t=0;t<this._checkBoxes.length;++t)checkBoxValues.push($(this._checkBoxes).is(":checked"));for(var radioValues=new Array,t=0;t<this._radioButtonGroupValues.length;++t)radioValues.push(this._radioButtonGroupValues[t]);return""!=this._closeCallback&&eval(this._closeCallback+"(this);"),eval(fn),!1},InlineDialog.prototype.onRadioButtonDown=function(e,groupId){e=Event.element(e);debug.trace(e.id+"-"+e.value+"-"+groupId),$(e).prop("checked")&&(this._radioButtonGroupValues[$.inArray(groupId,this._radioButtonGroups)]=$(e).val())},InlineDialog.prototype.DisplayPostit=function(src,targetElement,noteContext,width,height,closeCallback,paperclipCallback){debug.trace("DisplayPostit: "+width+","+height,"InlineDialog"),this._closeCallback=closeCallback,this._originalText=noteContext.PostitText,this._paperclipCallback=paperclipCallback;var closeCallback=(this._noteContext=noteContext).PostitText,paperclipCallback=(this.CreateContainer(),this._dialogLayer.css({visibility:"hidden"}),this._containerId=$(this._dialogLayer).attr("id"),this.AddDialogToDocument(src),0<width&&0<height&&this.resizePostitElements(width,height),this._dialogLayer.children().first().attr("id")),textArea=$(paperclipCallback+"textarea")[0],noteContext=(textArea.value=closeCallback,this._textArea=textArea,$(targetElement).position().left),src=(noteContext=(noteContext+=$(targetElement).getWidth()/2)-this._dialogLayer.children().first().getWidth()/2,$(targetElement).offset().top),width=(this._dialogLayer.setStyle({position:"absolute",top:src+"px",left:noteContext+"px",zIndex:++g_dialogLastZIndex}),this._dialogLayer.children().first()),height=$(width).offset(),closeCallback=UIHelper.getClientRectangle();height.left+width.getWidth()>closeCallback[0]-5&&width.setWidth(closeCallback[0]-height.left-5),height.top+width.getHeight()>closeCallback[1]-5&&width.setHeight(closeCallback[1]-height.top-5);$("#"+paperclipCallback+"paperclip").on("mousedown",this.onPaperclipMouseDown);var targetElement=$(document.createElement("DIV")),that=(targetElement.attr("id",this._containerId+"resize"),this._dialogLayer.children().first().append(targetElement),targetElement.setClass("dialogresize"),targetElement.setStyle({position:"absolute",bottom:"0px",right:"0px",width:"13px",height:"13px",zIndex:199}),this),src=(this.registerDragDrop(targetElement,that.onPostitResizeInit,that.onPostitResizeMove,that.onPostitResizeDrop,that.onPostitResizeCancel),this._dialogLayer.css({visibility:"visible"}),null),src=textArea.setSelectionRange?function(){textArea.selectionStart=0,textArea.selectionEnd=textArea.value.indexOf("\n"),textArea.focus()}:function(){var rng=textArea.createTextRange(),str=textArea.value.substring(0,textArea.value.indexOf("\n"));""!=str&&(rng.findText(str),rng.select()),textArea.focus()};setTimeout(src,200),$(document).on("keydown.notebook",function(e){27==JsHelper.GetKeyCode(e)&&that.Close()}),$(document).on("mousedown.notebook",function(e){try{for(var node=$(Event.element(e));null!=node&&0<node.length&&"FORM"!=node[0].tagName&&"BODY"!=node[0].tagName;){if(node[0].id==that._containerId)return!0;node=node.parent()}}catch(ex){}return that.Close(),!1})},InlineDialog.prototype.Close=function(){""!=this._closeCallback&&eval(this._closeCallback+"(this);"),$(document).off("keydown.notebook"),$(document).off("mousedown.notebook"),$(this._containerId).remove()},InlineDialog.prototype.HasTextChanged=function(){var taString=this._textArea.value.replace(/(\r\n|\n|\r)/gm,"\n"),originalString=this._originalText.replace(/(\r\n|\n|\r)/gm,"\n");return 0!==$.trim(taString).localeCompare($.trim(originalString))?(debug.trace("Changed!: "+taString.length+","+originalString.length,"InlineDialog"),!0):(debug.trace("NOT Changed!","InlineDialog"),!1)},InlineDialog.prototype.GetPostitText=function(){return this._textArea.value},InlineDialog.prototype.resizePostitElements=function(w,h){var dialogId=$(this._dialogLayer.children().first()).attr("id");this._dialogLayer.children().first().setWidth(w),this._dialogLayer.children().first().setHeight(h),$("#"+dialogId+"editorcontainer").setWidth(w),$("#"+dialogId+"editorcontainer").setHeight(h-48),$("#"+dialogId+"textarea").setWidth(w-5),$("#"+dialogId+"textarea").setHeight(h-48)},InlineDialog.prototype.onPostitResizeInit=function(e){debug.trace("onDragInit","InlineDialog"),this._initialDialogWidth=this.GetWidth(),this._initialDialogHeight=this.GetHeight()},InlineDialog.prototype.onPostitResizeMove=function(e,deltaX,deltaY){var dialogId=$(this._dialogLayer.children().first()).attr("id"),dialogId=$("#"+dialogId),deltaX=Math.max(this._postItMinWidth,this._initialDialogWidth+deltaX),deltaY=Math.max(this._postItMinHeight,this._initialDialogHeight+deltaY),dialogId=dialogId.offset();dialogId.left+deltaX>this._clientRectX-5&&(deltaX=this._clientRectX-dialogId.left-5),dialogId.top+deltaY>this._clientRectY-5&&(deltaY=this._clientRectY-dialogId.top-5),this.resizePostitElements(deltaX,deltaY)},InlineDialog.prototype.onPostitResizeDrop=function(e,deltaX,deltaY){this._dialogLayer.children().first().getWidth(),this._dialogLayer.children().first().getHeight()},InlineDialog.prototype.onPaperclipMouseDown=function(e){void 0!==this._paperclipCallback&&""!=this._paperclipCallback&&eval(this._paperclipCallback+"(e, this);")},InlineDialog.prototype.onDocumentMouseDown=function(e){try{for(var node=Event.element(e);null!=node&&"FORM"!=node.tagName&&"BODY"!=node.tagName;){if(node.id==this._containerId)return!1;node=node.parentNode}}catch(ex){console.log("onDocumentMouseDown exception: "+ex.message)}return this.Close(),!1},InlineDialog.prototype.registerDragDrop=function(dragLayer,dragInitCallback,dragMoveCallback,dragDropCallback,dragCancelCallback){this._dragLayer=dragLayer,this._onDragInitCallback=dragInitCallback,this._onDragCancelCallback=dragCancelCallback,this._onDragMoveCallback=dragMoveCallback,this._onDragDropCallback=dragDropCallback;var that=this;$(this._dragLayer).on("mousedown",function(e){that._initialMousePosX=Event.pointerX(e),that._initialMousePosY=Event.pointerY(e);var rect=UIHelper.getClientRectangle();that._clientRectX=rect[0],that._clientRectY=rect[1],that._onDragInitCallback(e),$(document).on("mousemove.inlinedragdrop",function(e){var deltaX=Event.pointerX(e)-that._initialMousePosX,deltaY=Event.pointerY(e)-that._initialMousePosY;that._onDragMoveCallback(e,deltaX,deltaY)}),$(document).on("mouseup.inlinedragdrop",function(e){var deltaX,deltaY;$(document).off("mousemove.inlinedragdrop"),$(document).on("mouseup.inlinedragdrop"),deltaX=Event.pointerX(e)-that._initialMousePosX,deltaY=Event.pointerY(e)-that._initialMousePosY,that._onDragDropCallback(e,deltaX,deltaY),that._initialMousePosX=0,that._initialMousePosY=0,that._initialDialogWidth=0,that._initialDialogHeight=0})})};var ModifyKey={NONE:0,CTRL:1,SHIFT:2,ALT:3},g_shiftDown=!1,g_ctrlDown=!1,g_altDown=!1,KeyPressHandler=new _KeyPressHandler;function _KeyPressHandler(){this._keyPressCollection=new SoCollection}function _LinksArchive(){this._dataFieldSoId="LinksArchiveData",this._dataField=null}function _LinksArchiveData(){this._inputFieldSoId="LinksArchiveData",this._inputField=null,this._saleIds=new Array,this._appIds=new Array,this._docIds=new Array,this._projIds=new Array,this._urlIds=new Array,this._personIds=new Array,this._contactIds=new Array,this._selectionIds=new Array}function TableRowState(){this._selectedItems=new SoCollection}function TableRowParser(id,tableId){this._id=id,this._tableId=tableId,this._table=null,this._selectedClassName="",this._passiveClassName="",this._borderClassName="",this._isMultiSelect=!1,this._tableRowState=new TableRowState,this._lastSelectedRow="",this._prevSelectedRows=null,this._lastSelectedIndex=0,this._funcMD=new Function("e","try{"+id+".onMouseDown(e);}catch(ex){}"),this._funcMU=new Function("e","try{"+id+".onMouseUp(e);}catch(ex){}"),this._active=!1,debug.trace("Id: "+id,"TableRowParser"),this.initialize()}function ListRowState(){this._selectedItems=new SoCollection}function ListRowParser(id,tableId){this._id=id,this._divId=tableId,this._div=null,this._selectedClassName="",this._passiveClassName="",this._borderClassName="",this._isMultiSelect=!1,this._listRowState=new ListRowState,this._lastSelectedRow="",this._prevSelectedRows=null,this._lastSelectedIndex=0,this._funcMD=new Function("e","try{"+id+".onMouseDown(e);}catch(ex){}"),this._funcMU=new Function("e","try{"+id+".onMouseUp(e);}catch(ex){}"),this._active=!1,debug.trace("Id: "+id,"ListRowParser"),this.initialize()}_this=_KeyPressHandler.prototype,$(window).on("load",function(){PageEventHandler.addEvent(EventType.ONKEYDOWN,"KeyPressHandler","KeyPressHandler.OnKeyDown(e)"),PageEventHandler.addEvent(EventType.ONKEYUP,"KeyPressHandler","KeyPressHandler.OnKeyUp(e)")}),_this.AddKeyPressListenerByKeyCode=function(keycode,modifyKey,func){this.AddKeyPressListener(String.fromCharCode(keycode),modifyKey,func)},_this.RemoveKeyPressListenerByKeyCode=function(keycode,modifyKey,func){this.RemoveKeyPressListener(String.fromCharCode(keycode),modifyKey,func)},_this.AddKeyPressListener=function(key,modifyKey,func){var col,modifyKey=this.getModifyKeyString(modifyKey);this._keyPressCollection.exist(modifyKey+key)?(col=this._keyPressCollection.get(modifyKey+key)).exist(func)||col.add(func,func):((col=new SoCollection).add(func,func),this._keyPressCollection.add(modifyKey+key,col))},_this.RemoveKeyPressListener=function(key,modifyKey,func){var col;this._keyPressCollection.exist(modifyKey+key)&&((col=this._keyPressCollection.get(modifyKey+key)).exist(func)||col.remove(func),0==col.getLength)&&this._keyPressCollection.remove(modifyKey+key)},_this.getModifyKeyString=function(modifyKey){switch(modifyKey){case ModifyKey.NONE:return"";case ModifyKey.SHIFT:return"SHIFT";case ModifyKey.CTRL:return"CTRL";case ModifyKey.ALT:return"ALT"}},_this.FireEvent=function(key){if("undefined{"==key&&(key="{"),this._keyPressCollection.exist(key))for(var collection=this._keyPressCollection.get(key),t=0;t<collection.getLength();t++)try{eval(collection.getByIdx(t))}catch(e){debug.error(e.message,"KeyPressHandler")}},_this.OnKeyDown=function(obj,e){e=JsHelper.GetKeyCode(e);this.modifierKeyDown(e),18<e&&this.FireEvent(this._modifyKey+String.fromCharCode(e))},_this.OnKeyUp=function(obj,e){g_ctrlDown=g_shiftDown=!1,this._modifyKey=this.getModifyKeyString(ModifyKey.NONE)},_this.modifierKeyDown=function(keyCode){16==keyCode&&(g_shiftDown=!0,this._modifyKey=this.getModifyKeyString(ModifyKey.SHIFT)),17==keyCode&&(g_ctrlDown=!0,this._modifyKey=this.getModifyKeyString(ModifyKey.CTRL)),18==keyCode&&(g_altDown=!0,this._modifyKey=this.getModifyKeyString(ModifyKey.ALT)),27==keyCode&&(g_altDown=g_ctrlDown=g_shiftDown=!1,this._modifyKey=this.getModifyKeyString(ModifyKey.NONE))},SuperOffice.Admin.LicenseInfo=function(){var pub={showLicenseInfoDialog:function(ownerName,licenseName){var s=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminLicenseDataHandler.GetLicenseInfoDialog","",ownerName,licenseName);eval(s)}};return pub}(),SuperOffice.Admin.LicenseEditor=(()=>{var pub={EnDisBoth:function(id){pub.EnDisRadio(id),pub.EnDis(id)},EnDis:function(id){var chosenRadio=$("[soid=SoLicenseEditorRadioButtonCurrentSelected]")[0],noSelectionRadio=$("[soid=SoLicenseEditorNoSelectionHiddenField]")[0],validRadioSelect=!0;null!=noSelectionRadio&&""!=noSelectionRadio.value&&(validRadioSelect=null!=chosenRadio&&0<=chosenRadio.value&&""!=chosenRadio.value&&chosenRadio.value!=noSelectionRadio.value);($("[soid='"+id+"']").prop("checked")&&validRadioSelect?($("span[sohierarchyid] input:checkbox").attr("disabled",!1).length,$("span[sohierarchyid] input:checkbox:not(:checked)").each(function(i,e){$(this).closest("table").find("[sohierarchyid^='"+$(e).parent().attr("sohierarchyid")+"/']").find(":checkbox").removeAttr("checked").length}).length,$("span[sohierarchyid] input:checkbox:not(:checked)").each(function(i,e){$(this).closest("table").find("[sohierarchyid^='"+$(e).parent().attr("sohierarchyid")+"/']").find(":checkbox").attr("disabled",!0).length})):($("span[sohierarchyid] input:checkbox").removeAttr("checked").length,$("span[sohierarchyid] input:checkbox").attr("disabled",!0))).length;for(var uncheckedboxes=$("span[sohierarchyid] input:checkbox:not(:checked)"),i=0;i<uncheckedboxes.length;i++){var freeElem=$(uncheckedboxes[i]).closest("tr").children("td")[2];"0"==$(freeElem).text()&&$(uncheckedboxes[i]).attr("disabled",!0)}},valChange:function(activeuser,chkbox){if(null!=chkbox&&"radio"==chkbox.type)pub.radioValChange(activeuser,chkbox);else{$("[soid='"+activeuser+"']").prop("checked");var subchecks=$("span[sohierarchyid^='"+$(chkbox).parent().attr("sohierarchyid")+"/'] input:checkbox:checked"),elem=(null==chkbox&&(subchecks=$("span[sohierarchyid] input:checkbox:checked")),chkbox),newValueChecked=$(elem).prop("checked"),i=0;do{if(null==elem){if(subchecks.length<=0)break;elem=subchecks[i]}else{var cells=$(elem).closest("tr").children("td"),inUseElem=cells[1],cells=cells[2];null!=chkbox&&$(elem).prop("checked")&&newValueChecked?($(inUseElem).text(parseInt($(inUseElem).text())+1),0<$(cells).text().length&&$(cells).text(parseInt($(cells).text())-1)):($(inUseElem).text(parseInt($(inUseElem).text())-1),0<$(cells).text().length&&$(cells).text(parseInt($(cells).text())+1)),elem=subchecks[i],parsingChilden=!0}}while(null!=elem&&i++<=subchecks.length);null!=chkbox&&pub.EnDis(activeuser)}},radioValChange:function(activeuser,radioClicked){for(var inUseRadio,radios=$("input[name=SoLicenseEditor]"),hidden=$("[soid=SoLicenseEditorRadioButtonCurrentSelected]"),isUserActive=$("[soid='"+activeuser+"']").prop("checked"),hidden=hidden[0].value,j=(0<=hidden&&null!=(hidden=radios[hidden])&&(inUseRadio=(hidden=$(hidden).closest("tr").children("td"))[1],hidden=hidden[2],null==radioClicked&&isUserActive||($(inUseRadio).text(parseInt($(inUseRadio).text())-1),0<$(hidden).text().length&&$(hidden).text(parseInt($(hidden).text())+1))),0),found=!1;j<radios.length&&!found;)radios[j].checked&&($("[soid=SoLicenseEditorRadioButtonCurrentSelected]")[0].value=j,found=!0),j++;null!=radioClicked?(isUserActive=radioClicked,hidden=(inUseRadio=$(isUserActive).closest("tr").children("td"))[1],inUseRadio=inUseRadio[2],null!=radioClicked&&$(isUserActive).prop("checked")?($(hidden).text(parseInt($(hidden).text())+1),0<$(inUseRadio).text().length&&$(inUseRadio).text(parseInt($(inUseRadio).text())-1)):($(hidden).text(parseInt($(hidden).text())-1),0<$(inUseRadio).text().length&&$(inUseRadio).text(parseInt($(inUseRadio).text())+1)),pub.EnDisBoth(activeuser)):$("[soid=SoLicenseEditorRadioButtonCurrentSelected]")[0].value=-1,SuperOffice.SoHelper.enableElementsBySoId("tempSave","tempCancel")},EnDisRadio:function(id){var freeElem,tabs=0,radioContainer=$("[soid=licenseeditor_licenseownertabs_page_0]");if($("[soid='"+id+"']").prop("checked"))for(;0<radioContainer.length&&tabs<10;){radios=radioContainer.find("input:radio");for(var i=0;i<radios.length;i++)freeElem=$(radios[i]).closest("tr").children("td")[2],"0"!=$(freeElem).text()||$(radios[i]).prop("checked")?$(radios[i]).prop("disabled",!1):$(radios[i]).prop("disabled",!0);tabs++,radioContainer=$("[soid=licenseeditor_licenseownertabs_page_"+tabs+"]")}else for(;0<radioContainer.length&&tabs<10;){for(var radios=radioContainer.find("input:radio"),j=0;j<radios.length;j++)$(radios[j]).attr("disabled",!0),$(radios[j]).removeAttr("checked");tabs++,radioContainer=$("[soid=licenseeditor_licenseownertabs_page_"+tabs+"]")}}};return pub})(),_this=_LinksArchive.prototype,_this.Initialize=function(){this._dataField=SuperOffice.SoHelper.getInputElementBySoId(this._dataFieldSoId)},_this.RefreshArchive=function(){this.RefreshArchive(!1)},_this.RefreshArchive=function(force){LinksArchiveData.PopulateToField(),(force||LinksArchiveData.HasLinks())&&"undefined"!=typeof LinksArchiveCtrlArchiveControl&&LinksArchiveCtrlArchiveControl.RefreshList(this._dataField.value)},_this.SetTabImage=function(){Debug.trace("Setting tab image","Links"),LinksArchiveData.HasLinks()&&SetTabItemImage("LinksArchive_TabItem_Icon","")},_this.DeleteLinks=function(selectedRows){if(0<selectedRows.length){for(var i=0;i<selectedRows.length;i++){var entity=selectedRows[i].attributes.rowEntityName.value,primaryKey=GetPrimaryKeyFromRow(selectedRows[i]);"sale"==entity?LinksArchiveData.DeleteSaleId(primaryKey):"appointment"==entity?LinksArchiveData.DeleteAppointmentId(primaryKey):"document"==entity?LinksArchiveData.DeleteDocumentId(primaryKey):"project"==entity?LinksArchiveData.DeleteProjectId(primaryKey):"url"==entity?LinksArchiveData.DeleteUrlId(primaryKey):"person"==entity?LinksArchiveData.DeletePersonId(primaryKey):"contact"==entity?LinksArchiveData.DeleteContactId(primaryKey):"selection"==entity&&LinksArchiveData.DeleteSelectionId(primaryKey)}this.RefreshArchive(!0)}},_this.OpenLink=function(selectedRows){if(0<selectedRows.length){var entity=selectedRows[0].attributes.rowEntityName.value,primaryKey=GetPrimaryKeyFromRow(selectedRows[0]);if("sale"===entity||"person"===entity||"selection"===entity||"project"===entity)UIHelper.SafeGetOpener().PageUpdate("soprotocol:"+entity+"?"+entity+"_id="+primaryKey,"");else if("url"===entity)for(var keyValPair,elements=selectedRows[0].attributes.rowType.value.split("&"),i=0;i<elements.length;i++)0===elements[i].indexOf("url=")&&2===(keyValPair=elements[i].split("=")).length&&window.open(keyValPair[1],"_blank","noopener");else Dialog.open(entity,entity+"[dialog=stop]?"+entity+"_id="+primaryKey)}},_this.OpenFindDialog=function(entity){SuperOffice.Find.OpenFindInlineDialog({FindType:SuperOffice.Find.FindTypeEnum.Single,CriterionEntity:entity,Callback:"LinksArchive.AddLinks('"+entity+"');"})},_this.AddLinks=function(entity){if(Debug.trace("Add links callback","Links archive"),1==Dialog.getReturnStatus()){for(var tmp=Dialog.getReturnValue().split("|,|"),selectedId="",i=0;i<tmp.length;i++)""!=selectedId&&(selectedId+=","),selectedId+=tmp[i].substring(0,tmp[i].indexOf("|"));null!=selectedId&&("sale"==entity?LinksArchiveData.SetSaleIds(selectedId):"appointment"==entity?LinksArchiveData.SetAppointmentIds(selectedId):"document"==entity?LinksArchiveData.SetDocumentIds(selectedId):"project"==entity?LinksArchiveData.SetProjectIds(selectedId):"url"==entity&&LinksArchiveData.SetUrlIds(selectedId),this.RefreshArchive())}},_this.AddLinksFromLinksDialog=function(){var tmp,selectedId;Debug.trace("Add links callback","Links archive"),1===Dialog.getReturnStatus()&&(tmp=Dialog.getReturnValue().split("|§|"),selectedId="",null!==(selectedId="Url"===(entity=tmp[0])?tmp[2]:tmp[1]))&&("Sale"===entity?LinksArchiveData.SetSaleIds(selectedId):"Appointment"===entity?LinksArchiveData.SetAppointmentIds(selectedId):"Document"===entity?LinksArchiveData.SetDocumentIds(selectedId):"Project"===entity?LinksArchiveData.SetProjectIds(selectedId):"Url"===entity&&(selectedId=tmp[1].replace(/,/g,"§colon§").replace(/;/g,"§scolon§"),LinksArchiveData.SetUrlIds(selectedId)),this.RefreshArchive())},_this=_LinksArchiveData.prototype,_this.Initialize=function(){this._inputField=SuperOffice.SoHelper.getInputElementBySoId(this._inputFieldSoId),this.PopulateFromField()},_this.PopulateFromField=function(){if(""!=this._inputField.value)for(var linkIds=this._inputField.value.split(";"),i=0;i<linkIds.length;i++)-1!=linkIds[i].indexOf("saleIds")?this.SetSaleIds(linkIds[i].substring(linkIds[i].indexOf("=")+1)):-1!=linkIds[i].indexOf("appIds")?this.SetAppointmentIds(linkIds[i].substring(linkIds[i].indexOf("=")+1)):-1!=linkIds[i].indexOf("docIds")?this.SetDocumentIds(linkIds[i].substring(linkIds[i].indexOf("=")+1)):-1!=linkIds[i].indexOf("projIds")?this.SetProjectIds(linkIds[i].substring(linkIds[i].indexOf("=")+1)):-1!=linkIds[i].indexOf("urlIds")?this.SetUrlIds(linkIds[i].substring(linkIds[i].indexOf("=")+1)):-1!=linkIds[i].indexOf("personIds")?this.SetPersonIds(linkIds[i].substring(linkIds[i].indexOf("=")+1)):-1!=linkIds[i].indexOf("contactIds")?this.SetContactIds(linkIds[i].substring(linkIds[i].indexOf("=")+1)):-1!=linkIds[i].indexOf("selectionIds")&&this.SetSelectionIds(linkIds[i].substring(linkIds[i].indexOf("=")+1));""==g_initialLinkIds&&(g_initialLinkIds=this._appIds.join(",")+"|"+this._saleIds.join(",")+"|"+this._docIds.join(",")+"|"+this._projIds.join(",")+"|"+this._urlIds.join(",")+"|"+this._personIds.join(",")+"|"+this._contactIds.join(",")+"|"+this._selectionIds.join(","))},_this.PopulateToField=function(){this._inputField.value="saleIds="+this.GetSaleIdsAsString()+";",this._inputField.value+="appIds="+this.GetAppointmentIdsAsString()+";",this._inputField.value+="docIds="+this.GetDocumentIdsAsString()+";",this._inputField.value+="projIds="+this.GetProjectIdsAsString()+";",this._inputField.value+="urlIds="+this.GetUrlIdsAsString()+";",this._inputField.value+="personIds="+this.GetPersonIdsAsString()+";",this._inputField.value+="contactIds="+this.GetContactIdsAsString()+";",this._inputField.value+="selectionIds="+this.GetSelectionIdsAsString()+";"},_this.HasLinks=function(){return 0<this._saleIds.length+this._appIds.length+this._docIds.length+this._projIds.length+this._urlIds.length+this._personIds.length+this._contactIds.length+this._selectionIds.length},_this.SetSaleIds=function(ids){this._saleIds=this.setIds(ids,this._saleIds)},_this.DeleteSaleId=function(id){this._saleIds=this.removeId(id,this._saleIds)},_this.GetSaleIdsAsString=function(){return this._saleIds.join(",")},_this.SetAppointmentIds=function(ids){this._appIds=this.setIds(ids,this._appIds)},_this.DeleteAppointmentId=function(id){this._appIds=this.removeId(id,this._appIds)},_this.GetAppointmentIdsAsString=function(){return this._appIds.join(",")},_this.SetDocumentIds=function(ids){this._docIds=this.setIds(ids,this._docIds)},_this.DeleteDocumentId=function(id){this._docIds=this.removeId(id,this._docIds)},_this.GetDocumentIdsAsString=function(){return this._docIds.join(",")},_this.SetProjectIds=function(ids){this._projIds=this.setIds(ids,this._projIds)},_this.DeleteProjectId=function(id){this._projIds=this.removeId(id,this._projIds)},_this.GetProjectIdsAsString=function(){return this._projIds.join(",")},_this.SetUrlIds=function(ids){this._urlIds=this.setIds(ids,this._urlIds)},_this.DeleteUrlId=function(id){this._urlIds=this.removeId(id,this._urlIds)},_this.GetUrlIdsAsString=function(){return this._urlIds.join(",")},_this.SetPersonIds=function(ids){this._personIds=this.setIds(ids,this._personIds)},_this.DeletePersonId=function(id){this._personIds=this.removeId(id,this._personIds)},_this.GetPersonIdsAsString=function(){return this._personIds.join(",")},_this.SetContactIds=function(ids){this._contactIds=this.setIds(ids,this._contactIds)},_this.DeleteContactId=function(id){this._contactIds=this.removeId(id,this._contactIds)},_this.GetContactIdsAsString=function(){return this._contactIds.join(",")},_this.SetSelectionIds=function(ids){this._selectionIds=this.setIds(ids,this._selectionIds)},_this.DeleteSelectionId=function(id){this._selectionIds=this.removeId(id,this._selectionIds)},_this.GetSelectionIdsAsString=function(){return this._selectionIds.join(",")},_this.setIds=function(ids,idList){for(var idArr=ids.split(","),i=0;i<idArr.length;i++)""!=idArr[i]&&-1==idList.indexOf(idArr[i])&&idList.push(idArr[i]);return idList},_this.removeId=function(id,idList){id=idList.indexOf(id);return-1!=id&&idList.splice(id,1),idList},_this=TableRowState.prototype,_this.getSelectedItems=function(){return this._selectedItems},_this.setSelectedItems=function(selectedItems){this._selectedItems=selectedItems},_this.getSelectedItemsCopy=function(){for(var items=new SoCollection,length=this._selectedItems.getLength(),i=0;i<length;i++)items.add(this._selectedItems.getByIdx(i),this._selectedItems.getByIdx(i));return items},_this.getSelectedItemsAsString=function(){for(var items="",length=this._selectedItems.getLength(),i=0;i<length;i++)items+=this._selectedItems.getByIdx(i)+";";return items},_this.setSelectedItemsAsString=function(selectedIdsString){if(""!=selectedIdsString){this._selectedItems=new SoCollection;for(var selectedIds=(selectedIdsString=";"==selectedIdsString.substr(selectedIdsString.length-1,1)?selectedIdsString.substr(0,selectedIdsString.length-1):selectedIdsString).split(";"),i=0;i<selectedIds.length;i++)this._selectedItems.add(selectedIds[i],selectedIds[i])}},_this=TableRowParser.prototype,_this.setTable=function(table){this._table=table},_this.getTable=function(){return this._table},_this.getTableRowState=function(){return this._tableRowState},_this.setSelectedClassName=function(selectedClassName){this._selectedClassName=selectedClassName},_this.getSelectedClassName=function(){return this._selectedClassName},_this.setPassiveClassName=function(passiveClassName){this._passiveClassName=passiveClassName},_this.getPassiveClassName=function(){return this._passiveClassName},_this.setBorderClassName=function(borderClassName){this._borderClassName=borderClassName},_this.getBorderClassName=function(){return this._borderClassName},_this.setIsMultiSelect=function(isMultiSelect){this._isMultiSelect=isMultiSelect},_this.getIsMultiSelect=function(){return this._isMultiSelect},_this.isActive=function(){return this._active},_this.initialize=function(){this._isInitialized||(this._table=document.getElementById(this._tableId),this.parseTable())},_this.count=function(){return void 0===this._table||null==this._table?0:this._table.rows.length},_this.parseTable=function(){if(debug.trace("Parsing table...","list.js"),null!=this._table)for(var i=0;i<this._table.rows.length;i++){var tableRow=this._table.rows[i],originalClassName=tableRow.getAttribute("defaultclass");null!=originalClassName&&""!=originalClassName||tableRow.setAttribute("defaultclass",tableRow.className)}debug.trace("Table parsed...","list.js")},_this.getItemsAsString=function(){var items="";if(null!=this._table)for(var i=0;i<this._table.rows.length;i++)items+=this._table.rows[i].id+";";return items},_this.getSelectedItemsAsString=function(){return this._tableRowState.getSelectedItemsAsString()},_this.setSelectedItemsAsString=function(selectedItems){this._tableRowState.setSelectedItemsAsString(selectedItems),this.setSelectedRows()},_this.setLastSelectedRow=function(){0<this._tableRowState._selectedItems.getLength()&&(this._lastSelectedRow=this._tableRowState._selectedItems.getByIdx(0))},_this.scrollToSelected=function(){var rows=this._tableRowState.getSelectedItems();null!=rows&&"undefined"!=rows&&0<rows.getLength()&&(rows=rows.getByIdx(0),location.href="#"+rows)},_this.getAllRows=function(){return null!=this._table?this._table.rows:new Array},_this.getSelectedRows=function(){for(var rowId,selectedRows=this._tableRowState.getSelectedItems(),tmpArray=new Array,i=0;i<selectedRows.getLength();i++)rowId=selectedRows.getByIdx(i),null!=(rowId=this._table.rows.namedItem(rowId))&&(1<rowId.length?tmpArray.push(rowId[0]):tmpArray.push(rowId));return tmpArray},_this.getSelectedIds=function(){for(var rowId,selectedIds="",selectedRows=this._tableRowState.getSelectedItems(),i=0;i<selectedRows.getLength();i++)rowId=selectedRows.getByIdx(i),null!=(rowId=this._table.rows.namedItem(rowId))&&(selectedIds+=rowId.attributes.primaryKey.value+",");return selectedIds=","==selectedIds.substr(selectedIds.length-1,1)?selectedIds.substr(0,selectedIds.length-1):selectedIds},_this.regMouseDown=function(){},_this.setSelectedOnElementId=function(id,event){setTimeout(this.regMouseDown.bind(this),0);var indexOfPrevSelected=0,selItems=(this._prevSelectedRows=this._tableRowState.getSelectedItemsCopy(),""!=this._lastSelectedRow&&(this._prevSelectedRow=this._table.rows.namedItem(this._lastSelectedRow),null!=this._prevSelectedRow)&&(indexOfPrevSelected=this._prevSelectedRow.rowIndex),this._lastSelectedRow=id,""!=this._lastSelectedRow&&null!=this._table.rows.namedItem(this._lastSelectedRow)&&(this._lastSelectedIndex=this._table.rows.namedItem(this._lastSelectedRow).rowIndex),null),ctrlDown=!1,shiftDown=!1,shiftDown=event?(console.log("Using event"),ctrlDown=event.ctrlKey,event.shiftKey):(ctrlDown=g_ctrlDown,g_shiftDown);if(this._isMultiSelect&&(ctrlDown||shiftDown)){if(ctrlDown)(selItems=this._tableRowState.getSelectedItems()).exist(id)?selItems.remove(id):selItems.add(id,id);else if(shiftDown){var event=0,endIdx=0,endIdx=this._lastSelectedIndex>=indexOfPrevSelected?(event=indexOfPrevSelected,this._lastSelectedIndex):(event=this._lastSelectedIndex,indexOfPrevSelected);this._tableRowState.setSelectedItems(new SoCollection);for(var i=event;i<=endIdx;i++){var row=this._table.rows[i];this._tableRowState.getSelectedItems().add(row.id,row.id)}}}else(selItems=new SoCollection).add(id,id),this._tableRowState.setSelectedItems(selItems);this.setSelectedRows()},_this.setSelectedOnIndex=function(idx,event){idx=this._table.rows[idx];this.setSelectedOnElementId(idx.id,event)},_this.selectAll=function(){this._prevSelectedRows=this._tableRowState.getSelectedItems();for(var selItems=new SoCollection,i=0;i<this._table.rows.length;i++)row=this._table.rows[i],selItems.add(row.id,row.id);this._tableRowState.setSelectedItems(selItems),this.setSelectedRows()},_this.deSelectAll=function(){this._prevSelectedRows=this._tableRowState.getSelectedItems(),this._tableRowState.setSelectedItems(new SoCollection),this.setSelectedRows()},_this.setSelectedRows=function(){debug.trace("SetSelectedRows","list.js"),MenuManager.hideMenu(),this._active=!0;var row=null;if(null!=this._prevSelectedRows&&null!=this._table)for(var selLength=this._prevSelectedRows.getLength(),i=0;i<selLength;i++){var rowTmp=this._table.rows.namedItem(this._prevSelectedRows.getByIdx(i));null!=(rowTmp=null!=rowTmp&&void 0!==rowTmp.length?rowTmp[0]:rowTmp)&&"TR"==rowTmp.tagName&&(rowTmp.className=rowTmp.getAttribute("defaultclass"),this.setRowBorders(rowTmp,""))}if(null!=this._table)for(var selItems=this._tableRowState.getSelectedItems(),i=0;i<selItems.getLength();i++){var rowId=selItems.getByIdx(i);null!=(row=null!=(row=this._table.rows.namedItem(rowId))&&void 0!==row.length?row[0]:row)&&this.toggleRowStyle()&&(row.className=this._selectedClassName+" "+row.styleHint,this.setRowBorders(row,this._borderClassName))}},_this.toggleRowStyle=function(){return""!=this._selectedClassName},_this.onMouseUp=function(e){$(document).off("mouseup.list"),$(document).off("mousedown.list")},_this.onMouseDown=function(e){try{if(debug.trace("OnMouseDown","List.OnMouseDown"),null!=this._tableRowState){var obj=Event.element(e),tagName="";for(void 0!==obj.tagName&&(tagName=obj.tagName),$(document).on("mouseup.list",this._funcMU);"BODY"!=tagName;){if("FORM"==tagName||"HTML"==tagName){for(var selItems=this._tableRowState.getSelectedItems(),i=0;i<selItems.getLength();i++){var rowId=selItems.getByIdx(i);null!=(row=this._table.rows.namedItem(rowId))&&(""!=this._passiveClassName?row.className=this._passiveClassName:row.className=row.getAttribute("defaulclass"),this.toggleRowStyle())&&this.setRowBorders(row,this._borderClassName)}$(document).off("mousedown.list"),this._active=!1;break}if(obj==this._table){this._active=!0;break}tagName=void 0===obj.parentNode?"FORM":void 0!==(obj=obj.parentNode).tagName?obj.tagName:""}}}catch(ex){debug.error(ex.message,"list.js")}},_this.setRowBorders=function(row,styleClass){for(var j=0;j<row.childNodes.length;j++)0==j?row.childNodes[j].className=styleClass+"Left":j==row.childNodes.length-1?row.childNodes[j].className=styleClass+"Right":row.childNodes[j].className=styleClass},_this.moveRowUp=function(){this.switchRows(this._lastSelectedIndex,"up")},_this.moveRowDown=function(){this.switchRows(this._lastSelectedIndex,"down")},_this.switchRows=function(index,direction){index=this._table.getElementsByTagName("tr")[index];"up"==direction&&index.previousSibling?index.parentNode.insertBefore(index,index.previousSibling):"down"==direction&&index.nextSibling&&index.parentNode.insertBefore(index.nextSibling,index),this.parseTable(),this.setSelectedOnElementId(index.id)},_this.appendRow=function(row){this._table.appendChild(row),this.parseTable()},_this.appendRows=function(rows){for(var i=0;i<rows.length;i++)this._table.appendChild(rows[i]);this.parseTable()},_this.removeSelectedRows=function(){for(var selItems=this._tableRowState.getSelectedItems(),i=0;i<selItems.getLength();i++){var rowId=selItems.getByIdx(i),rowId=this._table.rows.namedItem(rowId);null!=rowId&&this._table.deleteRow(rowId.rowIndex)}this._tableRowState.setSelectedItems(new SoCollection),this.setSelectedRows()},_this.copySelectedRows=function(tableParser){for(var selItems=tableParser.getTableRowState().getSelectedItems(),rows=new Array(selItems.getLength()),i=0;i<selItems.getLength();i++){var rowId=selItems.getByIdx(i);null==this._table.rows.namedItem(rowId)&&(rowId=this._table.rows.namedItem(rowId),rows[i]=rowId.cloneNode(!0))}this.appendRows(rows)},_this.cloneRow=function(row){row=row.cloneNode(!0);this._table.appendChild(row),this.parseTable()},_this.Dispose=function(){$(document).off("mousedown.list")},_this=ListRowState.prototype,_this.getSelectedItems=function(){return this._selectedItems},_this.setSelectedItems=function(selectedItems){this._selectedItems=selectedItems},_this.getSelectedItemsCopy=function(){for(var items=new SoCollection,length=this._selectedItems.getLength(),i=0;i<length;i++)items.add(this._selectedItems.getByIdx(i),this._selectedItems.getByIdx(i));return items},_this.getSelectedItemsAsString=function(){for(var items="",length=this._selectedItems.getLength(),i=0;i<length;i++)items+=this._selectedItems.getByIdx(i)+";";return items},_this.setSelectedItemsAsString=function(selectedIdsString){if(""!=selectedIdsString){this._selectedItems=new SoCollection;for(var selectedIds=(selectedIdsString=";"==selectedIdsString.substr(selectedIdsString.length-1,1)?selectedIdsString.substr(0,selectedIdsString.length-1):selectedIdsString).split(";"),i=0;i<selectedIds.length;i++)this._selectedItems.add(selectedIds[i],selectedIds[i])}},_this=ListRowParser.prototype,_this.setTable=function(table){this._div=table},_this.getTable=function(){return this._div},_this.getListRowState=function(){return this._listRowState},_this.setSelectedClassName=function(selectedClassName){this._selectedClassName=selectedClassName},_this.getSelectedClassName=function(){return this._selectedClassName},_this.setPassiveClassName=function(passiveClassName){this._passiveClassName=passiveClassName},_this.getPassiveClassName=function(){return this._passiveClassName},_this.setBorderClassName=function(borderClassName){this._borderClassName=borderClassName},_this.getBorderClassName=function(){return this._borderClassName},_this.setIsMultiSelect=function(isMultiSelect){this._isMultiSelect=isMultiSelect},_this.getIsMultiSelect=function(){return this._isMultiSelect},_this.isActive=function(){return this._active},_this.initialize=function(){this._isInitialized||(this._div=document.getElementById(this._divId),this._parseDiv())},_this.count=function(){return void 0===this._div||null==this._div?0:this._div.getElementsByTagName("DIV").length},_this._parseDiv=function(){if(debug.trace("Parsing table...","list.js"),null!=this._div){isFirstParse=!0;for(var rows=this._div.getElementsByTagName("DIV"),i=0;i<rows.length;i++){var originalClassName,divRow=rows[i];divRow.localIndex=i,!isFirstParse||null!=(originalClassName=divRow.getAttribute("defaultclass"))&&""!=originalClassName||divRow.setAttribute("defaultclass",divRow.className)}}debug.trace("Table parsed...","list.js")},_this.getItemsAsString=function(){var items="";if(null!=this._div)for(var rows=this._div.getElementsByTagName("DIV"),i=0;i<rows.length;i++)items+=rows[i].id+";";return items},_this.getSelectedItemsAsString=function(){return this._listRowState.getSelectedItemsAsString()},_this.setSelectedItemsAsString=function(selectedItems){this._listRowState.setSelectedItemsAsString(selectedItems),this.setSelectedRows()},_this.scrollToSelected=function(){var rows=this._listRowState.getSelectedItems();null!=rows&&"undefined"!=rows&&0<rows.getLength()&&(rows=rows.getByIdx(0),location.href="#"+rows)},_this.getSelectedRows=function(){for(var rowId,selectedRows=this._listRowState.getSelectedItems(),tmpArray=new Array,i=0;i<selectedRows.getLength();i++)rowId=selectedRows.getByIdx(i),null!=(rowId=document.getElementById(rowId))&&(1<rowId.length?tmpArray.push(rowId[0]):tmpArray.push(rowId));return tmpArray},_this.getSelectedIds=function(){for(var rowId,selectedIds="",selectedRows=this._listRowState.getSelectedItems(),i=0;i<selectedRows.getLength();i++)rowId=selectedRows.getByIdx(i),so_defined(rowId=document.getElementById(rowId))&&so_defined(rowId.attributes.primaryKey)&&(selectedIds+=rowId.attributes.primaryKey.value+",");return selectedIds=","==selectedIds.substr(selectedIds.length-1,1)?selectedIds.substr(0,selectedIds.length-1):selectedIds},_this.regMouseDown=function(){},_this.setSelectedOnElementId=function(id){var that=this,indexOfPrevSelected=(setTimeout(function(){that.regMouseDown()},0),0),selRow=(this._prevSelectedRows=this._listRowState.getSelectedItemsCopy(),""!=this._lastSelectedRow&&(this._prevSelectedRow=document.getElementById(this._lastSelectedRow),null!=this._prevSelectedRow)&&(indexOfPrevSelected=this._prevSelectedRow.localIndex),this._lastSelectedRow=id,""!=this._lastSelectedRow&&null!=document.getElementById(this._lastSelectedRow)&&(selRow=document.getElementById(this._lastSelectedRow),this._lastSelectedIndex=selRow.localIndex),null);if(this._isMultiSelect&&(g_ctrlDown||g_shiftDown)){if(g_ctrlDown)(selRow=this._listRowState.getSelectedItems()).exist(id)?selRow.remove(id):selRow.add(id,id);else if(g_shiftDown){var startIdx=0,endIdx=0,endIdx=this._lastSelectedIndex>=indexOfPrevSelected?(startIdx=indexOfPrevSelected,this._lastSelectedIndex):(startIdx=this._lastSelectedIndex,indexOfPrevSelected);this._listRowState.setSelectedItems(new SoCollection);for(var i=startIdx;i<=endIdx;i++){var rows=this._div.getElementsByTagName("DIV");row=rows[i],this._listRowState.getSelectedItems().add(row.id,row.id)}}}else(selRow=new SoCollection).add(id,id),this._listRowState.setSelectedItems(selRow);this.setSelectedRows()},_this.setSelectedOnIndex=function(idx){idx=this._div.getElementsByTagName("DIV")[idx];this.setSelectedOnElementId(idx.id)},_this.selectAll=function(){this._prevSelectedRows=this._listRowState.getSelectedItems();for(var selItems=new SoCollection,rows=this._div.getElementsByTagName("DIV"),i=0;i<rows.length;i++)"progress"!=(row=rows[i]).id.match(/progress$/)&&selItems.add(row.id,row.id);this._listRowState.setSelectedItems(selItems),this.setSelectedRows()},_this.deSelectAll=function(){this._prevSelectedRows=this._listRowState.getSelectedItems(),this._listRowState.setSelectedItems(new SoCollection),this.setSelectedRows()},_this.setSelectedRows=function(){debug.trace("SetSelectedRows","list.js"),MenuManager.hideMenu(),this._active=!0;var row=null;if(null!=this._prevSelectedRows)for(var elems=$(".SelectedListBoxItem"),selLength=elems.length,i=0;i<selLength;i++){var rowTmp=elems[i];null!=(rowTmp=null!=rowTmp&&void 0!==rowTmp.length?rowTmp[0]:rowTmp)&&"DIV"==rowTmp.tagName&&(rowTmp.className=rowTmp.getAttribute("defaultclass"),this.setRowBorders(rowTmp,""))}if(null!=this._div){var selItems=this._listRowState.getSelectedItems();debug.trace("selItems:"+selItems.getLength(),"list.js");for(i=0;i<selItems.getLength();i++){var sh,rowId=selItems.getByIdx(i);null!=(row=null!=(row=document.getElementById(rowId))&&void 0!==row.length?row[0]:row)&&this.toggleRowStyle()&&(rowId="",sh=row.getAttribute("stylehint"),row.className=this._selectedClassName+(rowId=sh?" "+sh:rowId),this.setRowBorders(row,this._borderClassName))}}},_this.toggleRowStyle=function(){return""!=this._selectedClassName},_this.onMouseUp=function(e){$(document).off("mouseup.listparser"),$(document).off("mousedown.listparser")},_this.onMouseDown=function(e){try{if(debug.trace("ListParser OnMouseDown","List.OnMouseDown"),null!=this._listRowState){var obj=Event.element(e),tagName="",that=(void 0!==obj.tagName&&(tagName=obj.tagName),this);for($(document).on("mouseup.listparser",function(event){that._funcMU(event)});"BODY"!=tagName;){if("FORM"==tagName||"HTML"==tagName){for(var selItems=this._listRowState.getSelectedItems(),i=0;i<selItems.getLength();i++){var rowId=selItems.getByIdx(i);null!=(row=document.getElementById(rowId))&&(""!=this._passiveClassName?row.className=this._passiveClassName:row.className=row.getAttribute("defaulclass"),this.toggleRowStyle())&&this.setRowBorders(row,this._borderClassName)}$(document).off("mousedown.listparser"),this._active=!1;break}if(obj==this._div){this._active=!0;break}tagName=void 0===obj.parentNode?"FORM":void 0!==(obj=obj.parentNode).tagName?obj.tagName:""}}}catch(ex){debug.error(ex.message,"list.js")}},_this.setRowBorders=function(row,styleClass){},_this.moveRowUp=function(){this.switchRows(this._lastSelectedIndex,"up")},_this.moveRowDown=function(){this.switchRows(this._lastSelectedIndex,"down")},_this.switchRows=function(index,direction){index=this._div.getElementsByTagName("DIV")[index];"up"==direction&&index.previousSibling?index.parentNode.insertBefore(index,index.previousSibling):"down"==direction&&index.nextSibling&&index.parentNode.insertBefore(index.nextSibling,index),this._parseDiv(),this.setSelectedOnElementId(index.id)},_this.appendRow=function(row){this._div.appendChild(row),this._parseDiv()},_this.appendRows=function(rows){for(var i=0;i<rows.length;i++)this._div.appendChild(rows[i]);this._parseDiv()},_this.removeSelectedRows=function(){for(var selItems=this._listRowState.getSelectedItems(),i=0;i<selItems.getLength();i++){var rowId=selItems.getByIdx(i);null!=(row=document.getElementById(rowId))&&row.parentNode.removeChild(row)}this._listRowState.setSelectedItems(new SoCollection),this.setSelectedRows()},_this.copySelectedRows=function(tableParser){for(var selItems=tableParser.getListRowState().getSelectedItems(),rows=new Array(selItems.getLength()),i=0;i<selItems.getLength();i++){var rowId=selItems.getByIdx(i);null==(row=document.getElementById(rowId))&&(rowId=document.getElementById(rowId),rows[i]=rowId.cloneNode(!0))}this.appendRows(rows)},_this.cloneRow=function(row){row=row.cloneNode(!0);this._div.appendChild(row),this._parseDiv()},_this.Dispose=function(){$(document).off("mousedown.listparser")};var g_mainMenuVisible=!1,g_currentContextMenu="",g_contextMenuCache=new Array,g_currentHighLight="",g_lastItemElem=null,g_lastParent=null,g_currentMenuElement=null,g_currentIndex=-1,g_currentSubMenuId=-1,g_keyNavigate=!1,MenuManager=new _MenuManager;function _MenuManager(){this.MenuCallBackFunction=new Function("val","elementId","MenuManager.menuCallBack(val, elementId);"),this.lastMenuButtonId="",this.menuPosition=new Array,this.cursorCoordinates=new Array,this.menuLayerTop=0,this.menuLayerBottom=0,this.touchEventId=0,this.touchEvent=null,this.subMenuIndicator="_",this.onKeyDownCallback=null}function NumberFormat(num,inputDecimal){this.VERSION="Number Format v1.5.4",this.COMMA=",",this.PERIOD=".",this.DASH="-",this.LEFT_PAREN="(",this.RIGHT_PAREN=")",this.LEFT_OUTSIDE=0,this.LEFT_INSIDE=1,this.RIGHT_INSIDE=2,this.RIGHT_OUTSIDE=3,this.LEFT_DASH=0,this.RIGHT_DASH=1,this.PARENTHESIS=2,this.NO_ROUNDING=-1,this.num,this.numOriginal,this.hasSeparators=!1,this.separatorValue,this.inputDecimalValue,this.decimalValue,this.negativeFormat,this.negativeRed,this.hasCurrency,this.currencyPosition,this.currencyValue,this.places,this.roundToPlaces,this.truncate,this.setNumber=setNumberNF,this.toUnformatted=toUnformattedNF,this.setInputDecimal=setInputDecimalNF,this.setSeparators=setSeparatorsNF,this.setCommas=setCommasNF,this.setNegativeFormat=setNegativeFormatNF,this.setNegativeRed=setNegativeRedNF,this.setCurrency=setCurrencyNF,this.setCurrencyPrefix=setCurrencyPrefixNF,this.setCurrencyValue=setCurrencyValueNF,this.setCurrencyPosition=setCurrencyPositionNF,this.setPlaces=setPlacesNF,this.toFormatted=toFormattedNF,this.toPercentage=toPercentageNF,this.toUnformatted=toUnformattedNF,this.getOriginal=getOriginalNF,this.moveDecimalRight=moveDecimalRightNF,this.moveDecimalLeft=moveDecimalLeftNF,this.getRounded=getRoundedNF,this.preserveZeros=preserveZerosNF,this.justNumber=justNumberNF,this.expandExponential=expandExponentialNF,this.getZeros=getZerosNF,this.moveDecimalAsString=moveDecimalAsStringNF,this.moveDecimal=moveDecimalNF,this.addSeparators=addSeparatorsNF,null==inputDecimal?this.setNumber(num,this.PERIOD):this.setNumber(num,inputDecimal),this.setCommas(!0),this.setNegativeFormat(this.LEFT_DASH),this.setNegativeRed(!1),this.setCurrency(!1),this.setCurrencyPrefix("$"),this.setPlaces(2)}function setInputDecimalNF(val){this.inputDecimalValue=val}function setNumberNF(num,inputDecimal){null!=inputDecimal&&this.setInputDecimal(inputDecimal),this.numOriginal=num,this.num=this.justNumber(num)}function toUnformattedNF(){return this.num}function getOriginalNF(){return this.numOriginal}function setNegativeFormatNF(format){this.negativeFormat=format}function setNegativeRedNF(isRed){this.negativeRed=isRed}function setSeparatorsNF(isC,separator,decimal){this.hasSeparators=isC,null==separator&&(separator=this.COMMA),null==decimal&&(decimal=this.PERIOD),this.decimalValue=separator==decimal?decimal==this.PERIOD?this.COMMA:this.PERIOD:decimal,this.separatorValue=separator}function setCommasNF(isC){this.setSeparators(isC,this.COMMA,this.PERIOD)}function setCurrencyNF(isC){this.hasCurrency=isC}function setCurrencyValueNF(val){this.currencyValue=val}function setCurrencyPrefixNF(cp){this.setCurrencyValue(cp),this.setCurrencyPosition(this.LEFT_OUTSIDE)}function setCurrencyPositionNF(cp){this.currencyPosition=cp}function setPlacesNF(p,tr){this.roundToPlaces=!(p==this.NO_ROUNDING),this.truncate=null!=tr&&tr,this.places=p<0?0:p}function addSeparatorsNF(nStr,inD,outD,sep){for(var inD=(nStr+="").indexOf(inD),nStrEnd="",rgx=(-1!=inD&&(nStrEnd=outD+nStr.substring(inD+1,nStr.length),nStr=nStr.substring(0,inD)),/(\d+)(\d{3})/);rgx.test(nStr);)nStr=nStr.replace(rgx,"$1"+sep+"$2");return nStr+nStrEnd}function toFormattedNF(){var nNum=this.num,nStr=(new Array(2),this.roundToPlaces?(nNum=this.getRounded(nNum),this.preserveZeros(Math.abs(nNum))):this.expandExponential(Math.abs(nNum))),c0=(nStr=this.hasSeparators?this.addSeparators(nStr,this.PERIOD,this.decimalValue,this.separatorValue):nStr.replace(new RegExp("\\"+this.PERIOD),this.decimalValue),""),n0="",c1="",n1="",n2="",c2="",n3="",c3="",negSignL=this.negativeFormat==this.PARENTHESIS?this.LEFT_PAREN:this.DASH,negSignR=this.negativeFormat==this.PARENTHESIS?this.RIGHT_PAREN:this.DASH;return this.currencyPosition==this.LEFT_OUTSIDE?(nNum<0&&(this.negativeFormat!=this.LEFT_DASH&&this.negativeFormat!=this.PARENTHESIS||(n1=negSignL),this.negativeFormat!=this.RIGHT_DASH&&this.negativeFormat!=this.PARENTHESIS||(n2=negSignR)),this.hasCurrency&&(c0=this.currencyValue)):this.currencyPosition==this.LEFT_INSIDE?(nNum<0&&(this.negativeFormat!=this.LEFT_DASH&&this.negativeFormat!=this.PARENTHESIS||(n0=negSignL),this.negativeFormat!=this.RIGHT_DASH&&this.negativeFormat!=this.PARENTHESIS||(n3=negSignR)),this.hasCurrency&&(c1=this.currencyValue)):this.currencyPosition==this.RIGHT_INSIDE?(nNum<0&&(this.negativeFormat!=this.LEFT_DASH&&this.negativeFormat!=this.PARENTHESIS||(n0=negSignL),this.negativeFormat!=this.RIGHT_DASH&&this.negativeFormat!=this.PARENTHESIS||(n3=negSignR)),this.hasCurrency&&(c2=this.currencyValue)):this.currencyPosition==this.RIGHT_OUTSIDE&&(nNum<0&&(this.negativeFormat!=this.LEFT_DASH&&this.negativeFormat!=this.PARENTHESIS||(n1=negSignL),this.negativeFormat!=this.RIGHT_DASH&&this.negativeFormat!=this.PARENTHESIS||(n2=negSignR)),this.hasCurrency)&&(c3=this.currencyValue),nStr=c0+n0+c1+n1+nStr+n2+c2+n3+c3,nStr=this.negativeRed&&nNum<0?'<font color="red">'+nStr+"</font>":nStr}function toPercentageNF(){return nNum=100*this.num,(nNum=this.getRounded(nNum))+"%"}function getZerosNF(places){for(var extraZ="",i=0;i<places;i++)extraZ+="0";return extraZ}function expandExponentialNF(origVal){var eLoc,plusLoc,negLoc,justNumber,places;return isNaN(origVal)||-1!=(eLoc=(origVal=parseFloat(origVal)+"").toLowerCase().indexOf("e"))&&(plusLoc=origVal.toLowerCase().indexOf("+"),negLoc=origVal.toLowerCase().indexOf("-",eLoc),justNumber=origVal.substring(0,eLoc),origVal=justNumber=-1!=negLoc?(places=origVal.substring(negLoc+1,origVal.length),this.moveDecimalAsString(justNumber,!0,parseInt(places))):(places=origVal.substring((plusLoc=-1==plusLoc?eLoc:plusLoc)+1,origVal.length),this.moveDecimalAsString(justNumber,!1,parseInt(places)))),origVal}function moveDecimalRightNF(val,places){return null==places?this.moveDecimal(val,!1):this.moveDecimal(val,!1,places)}function moveDecimalLeftNF(val,places){return null==places?this.moveDecimal(val,!0):this.moveDecimal(val,!0,places)}function moveDecimalAsStringNF(val,left,places){var extraZ,re1,re2,places=arguments.length<3?this.places:places;return places<=0?val:(val=val+"",extraZ=this.getZeros(places),re1=new RegExp("([0-9.]+)"),(val=left?(val=val.replace(re1,extraZ+"$1"),re2=new RegExp("(-?)([0-9]*)([0-9]{"+places+"})(\\.?)"),val.replace(re2,"$1$2.$3")):(null!=(left=re1.exec(val))&&(val=val.substring(0,left.index)+left[1]+extraZ+val.substring(left.index+left[0].length)),re2=new RegExp("(-?)([0-9]*)(\\.?)([0-9]{"+places+"})"),val.replace(re2,"$1$2$4."))).replace(/\.$/,""))}function moveDecimalNF(val,left,places){var newVal="",newVal=null==places?this.moveDecimalAsString(val,left):this.moveDecimalAsString(val,left,places);return parseFloat(newVal)}function getRoundedNF(val){return val=this.moveDecimalRight(val),val=this.truncate?0<=val?Math.floor(val):Math.ceil(val):Math.round(val),val=this.moveDecimalLeft(val)}function preserveZerosNF(val){if(val=this.expandExponential(val),!(this.places<=0)){var decimalPos=val.indexOf(".");if(-1==decimalPos){val+=".";for(var i=0;i<this.places;i++)val+="0"}else for(var decimalPos=val.length-1-decimalPos,difference=this.places-decimalPos,i=0;i<difference;i++)val+="0"}return val}function justNumberNF(val){var tempRight,isPercentage=!1,val=(-1!=(newVal=val+"").indexOf("%")&&(newVal=newVal.replace(/\%/g,""),isPercentage=!0),new RegExp("[^\\"+this.inputDecimalValue+"\\d\\-\\+\\(\\)eE]","g")),val=(newVal=newVal.replace(val,""),new RegExp("["+this.inputDecimalValue+"]","g")),treArray=val.exec(newVal);return null!=treArray&&(tempRight=newVal.substring(treArray.index+treArray[0].length),newVal=newVal.substring(0,treArray.index)+this.PERIOD+tempRight.replace(val,"")),newVal.charAt(newVal.length-1)==this.DASH?newVal="-"+(newVal=newVal.substring(0,newVal.length-1)):newVal.charAt(0)==this.LEFT_PAREN&&newVal.charAt(newVal.length-1)==this.RIGHT_PAREN&&(newVal="-"+(newVal=newVal.substring(1,newVal.length-1))),newVal=parseFloat(newVal),isFinite(newVal)||(newVal=0),newVal=isPercentage?this.moveDecimalLeft(newVal,2):newVal}function _NumberFormatter(){this._decimalDelimiter=".",this._commaDelimiter="."}_MenuManager.prototype.disableIEContextMenu=function(){try{document.body.attachEvent("oncontextmenu",MenuManager.hideIEContextMenu)}catch(ex){}},_MenuManager.prototype.hideIEContextMenu=function(){return g_debug.trace("hideIEContextMenu"),event.stopPropagation&&event.stopPropagation(),!(event.cancelBubble=!0)},_MenuManager.prototype.displayContextMenuOnTouch=function(funcString){funcString=funcString.replace("belowcursor","abovecursor");var e=MenuManager.touchEvent;Function("e",funcString)(e)},_MenuManager.prototype.registerRightClickContextMenu=function(elementId,context,subcontext,id,position,callBack){var elem,elem="object"==typeof elementId&&"string"==typeof elementId.jquery?elementId.get():SuperOffice.SoHelper.getElementById(elementId),currentOnMouseDownEvent=(MenuManager.disableIEContextMenu(),null),funcStr=(null!=elem.onmousedown&&(currentOnMouseDownEvent=elem.onmousedown),""),func,funcStr=void 0!==callBack&&null!=callBack&&""!=callBack?callBack+"(e, '"+elementId+"', '"+context+"', '"+subcontext+"', "+id+",'"+position+"' );":"MenuManager.displayMenu(e, '"+elementId+"', '"+context+"', '"+subcontext+"', "+id+",'"+position+"' );";JsHelper.IsTouchEnabled()?(elem.ontouchstart=function(e){0<MenuManager.touchEventId&&clearTimeout(MenuManager.touchEventId),MenuManager.touchEvent=e,MenuManager.touchEventId=setTimeout('MenuManager.displayContextMenuOnTouch("'+funcStr+'")',500)},elem.ontouchend=function(e){clearTimeout(MenuManager.touchEventId),MenuManager.touchEventId=0}):(func=Function("e",funcStr),elem.oncontextmenu=function(){return!1},$(elem).on("mouseup",function(e){return(null!=currentOnMouseDownEvent&&eval(currentOnMouseDownEvent)(),null==e)?!1:(document.oncontextmenu=function(){return!1},elem.oncontextmenu=function(){return!1},debug.trace("e:"+e,"menu"),2!=e.button||(eval(funcStr),e.cancelBubble=!0,!1))}))},_MenuManager.prototype.registerLeftClickContextMenu=function(elementId,context,subcontext,id,position,callBack){var elem=null,elem="object"==typeof elementId&&"string"==typeof elementId.jquery?elementId.get():SuperOffice.SoHelper.getElementById(elementId),funcStr="",funcStr=void 0!==callBack&&null!=callBack&&""!=callBack?callBack+"(event, '"+elementId+"', '"+context+"', '"+subcontext+"', "+id+",'"+position+"' );":"MenuManager.displayMenu(event, '"+elementId+"', '"+context+"', '"+subcontext+"', "+id+",'"+position+"' );",callBack=$(elem).attr("onclick");callBack?-1===callBack.indexOf(funcStr)&&$(elem).attr("onclick",callBack+funcStr):$(elem).attr("onclick",funcStr)},_MenuManager.prototype.registerMenu=function(strElementId,strContext,strSubcontext,strId,strPosition,strMouseClick,strCallBack){void 0!==strCallBack&&null!=strCallBack||(strCallBack=""),null==("object"==typeof strElementId&&"string"==typeof strElementId.jquery?strElementId.get():SuperOffice.SoHelper.getElementById(strElementId))?debug.trace("Not found:"+strElementId,"menu"):"right"==strMouseClick?MenuManager.registerRightClickContextMenu(strElementId,strContext,strSubcontext,strId,strPosition,strCallBack):MenuManager.registerLeftClickContextMenu(strElementId,strContext,strSubcontext,strId,strPosition,strCallBack)},_MenuManager.prototype.displayMenu=function(e,elementId,context,subcontext,id,position){var mouseCoords;null==position&&(position="below"),ToolTipManager.Hide(),g_currentContextMenu=context.toString()+subcontext.toString()+id.toString(),debug.trace("display:"+g_currentContextMenu,"menu"),"abovecursor"!=(MenuManager.menuPosition[elementId]=position)&&"belowcursor"!=position||(mouseCoords=null,(mouseCoords=void 0===e?JsHelper.GetMouseCoordinates(event):JsHelper.GetMouseCoordinates(e)).getX()<=0&&mouseCoords.getY()<=0&&null!=(e=document.getElementById(elementId))&&"undefined"!=e&&(mouseCoords=new Dimension(findPosX(e),findPosY(e)),"belowcursor"==position)&&mouseCoords.setY(mouseCoords.getY()+e.offsetHeight),MenuManager.cursorCoordinates[elementId]=mouseCoords);null==g_contextMenuCache[g_currentContextMenu]?AjaxMethodDispatcher.CallASync("MenuManager.menuCallBack","","",elementId,AjaxMethod.GetContextMenu,context,subcontext,id):g_contextMenuCache[g_currentContextMenu],MenuManager.flushCache()},_MenuManager.prototype.menuCallBack=function(val,socontext){var position;debug.trace("menuCallBack","menu"),""!=val&&(debug.trace("menuPosition:"+MenuManager.menuPosition[socontext],"menu"),null==(position=MenuManager.menuPosition[socontext])&&(position="below"),debug.trace("position:"+position,"menu"),MenuManager.RenderMenu(socontext,val,position))},_MenuManager.prototype.RenderMenu=function(elementId,menuHtml,position){var x,elementLayer=$("#"+elementId),cmenuContainerLayer=(0==elementLayer.length&&(elementLayer=$.fromSoId(elementId)),$("#cmenuplaceholder")),rect=(cmenuContainerLayer.setStyle({zIndex:1e3}),getWindowRectangle()),y=0,cmenuLayer=("below"==position||"above"==position?(x=findPosX(elementLayer),y=findPosY(elementLayer),"below"==position&&(y+=elementLayer.getHeight())):y="ontop"==position?(x=findPosX(elementLayer),(mouseCoords=MenuManager.cursorCoordinates[elementId]).getY()):(mouseCoords=MenuManager.cursorCoordinates[elementId],debug.trace("mouse coords:"+mouseCoords,"menu"),x=mouseCoords.getX(),mouseCoords.getY()-10),console.log("x",x),"string"==typeof menuHtml?cmenuContainerLayer.html(menuHtml):(cmenuContainerLayer.empty(),cmenuContainerLayer.append(menuHtml)),$("#cmenu")),elementId=(cmenuLayer.setStyle({zIndex:99}),cmenuLayer.getHeight()),mouseCoords=cmenuLayer.getWidth(),cmenuContainerLayer=("below"==position||"belowcursor"==position?(x+mouseCoords+32>rect.getX()&&(x=rect.getX()-mouseCoords-32),y+elementId>rect.getY()&&(y=Math.max(0,y-(elementId-(rect.getY()-y))-10)),cmenuLayer.moveTo(x,y)):"ontop"==position?((y-=elementId/2)<5&&(y=5),x+=(elementLayer.getWidth()-cmenuLayer.getWidth())/2,cmenuLayer.moveTo(x,y)):cmenuLayer.moveTo(x,Math.max(0,y-elementId)),$("#shadow")),menuHtml=cmenuLayer.getLeft()+2,mouseCoords=cmenuLayer.getTop()+6,rect=(cmenuContainerLayer.setLeft(menuHtml),cmenuContainerLayer.setTop(mouseCoords),cmenuContainerLayer.setHeight(cmenuLayer.getHeight()),cmenuContainerLayer.setWidth(cmenuLayer.getWidth()),cmenuContainerLayer.css("visibility","visible"),cmenuLayer.height());return cmenuLayer.height(0),cmenuLayer.css({visibility:"visible",overflow:"hidden"}),cmenuLayer.animate({height:rect},100,function(){cmenuLayer.css({height:"",overflow:""})}),$(document).on("keydown.menumanager",MenuManager.onKeyDown),$(document).on("mouseup.menumanager",function(evt){debug.trace("onMouseDownForContextMenu","menu");var src=Event.element(evt),src=$(src);if(src.exists()){try{for(var node=src;null!=node&&"FORM"!=node.tagName&&"BODY"!=node.tagName;){if("cmenu"==node.id)return!1;node=node.parentNode}}catch(ex){debug.error("mousedown.menumanager: "+ex.message,"MenuManager")}debug.trace("closed on mousedown","menu"),MenuManager.hideMenu()}return!(evt.cancelBubble=!0)}),MenuManager.flushCache(),$("body").css("overflow","hidden"),!1},_MenuManager.prototype.SetMenuItems=function(strHtml){document.getElementById("cmenu").innerHTML=strHtml},_MenuManager.prototype.hideMenu=function(){debug.trace("hideMenu","menu"),$(document).off("mouseup.menumanager"),$(document).off("keydown.menumanager"),$(document).off("mousemove.menumanager"),MenuManager.onKeyDownCallback=null,MenuManager.hideSubMenu();var shadow=$("#shadow"),shadow=(null!=shadow&&shadow.css("visibility","hidden"),$("#cmenu"));null!=shadow&&shadow.css("visibility","hidden"),$("body").css("overflow","")},_MenuManager.prototype.displaySubMenu=function(parentItem,menuElementId){null!=g_lastParent&&MenuManager.hideSubMenu();var subMenuLayer=$("#"+menuElementId),parentLayer=$("#"+parentItem.id),overflow=Math.min(0,UIHelper.getClientRectangle()[0]-(parentLayer.offset().left+3+parentLayer.outerWidth()+subMenuLayer.outerWidth()+10));subMenuLayer.setLeft(parentLayer.outerWidth()+3+overflow),subMenuLayer.setTop(parentItem.offsetTop),document.getElementById(menuElementId).getBoundingClientRect().bottom>document.documentElement.clientHeight&&subMenuLayer.setTop(parentItem.offsetTop+parentLayer.outerHeight()-subMenuLayer.outerHeight()),subMenuLayer.css("visibility","visible"),g_lastParent=parentItem,g_currentSubMenuId=menuElementId},_MenuManager.prototype.hideSubMenu=function(){null!=g_lastParent&&(debug.trace("hidesubmenu:"+g_currentSubMenuId,"menu"),$("#"+g_currentSubMenuId).css("visibility","hidden"),g_lastParent=null,g_currentSubMenuId="")},_MenuManager.prototype.onMenuItemHover=function(elem,index,force){(!0===force||null!=elem&&elem!=g_lastItemElem)&&($(g_lastItemElem).removeClass("hover"),g_currentMenuElement=elem.parentNode,$(elem).addClass("hover"),force=!1,-1<elem.id.indexOf("-")&&(force=!0),null!=document.getElementById(elem.parentNode.id+"-"+index)?MenuManager.displaySubMenu(elem,elem.parentNode.id+"-"+index):force||null==g_lastParent||MenuManager.hideSubMenu(),g_lastItemElem=elem,g_currentIndex=index)},_MenuManager.prototype.onMenuItemHoverOut=function(elem){null!=elem&&$(elem).removeClass("hover")},_MenuManager.prototype.onKeyDown=function(event){debug.trace("onKeyDown","MenuManager");var keyCode=JsHelper.GetKeyCode(event),delta=0,leftright="",menuIndex;27==keyCode?MenuManager.hideMenu():(null==g_currentMenuElement&&(g_currentMenuElement=document.getElementById("cmenu")),13==keyCode?(event.cancelBubble=!0,event.stopPropagation(),event.preventDefault(),"function"==typeof g_lastItemElem.onmousedown?g_lastItemElem.onmousedown(event):"string"==typeof g_lastItemElem.onmousedown?eval(g_lastItemElem.onmousedown):"function"==typeof g_lastItemElem.onclick?g_lastItemElem.onclick(event):"string"==typeof g_lastItemElem.onclick&&eval(g_lastItemElem.onclick)):(38==keyCode&&(delta=-1),40==keyCode&&(delta=1),39==keyCode&&(leftright="R"),37==keyCode&&(leftright="L"),"R"==leftright&&(-1<g_currentMenuElement.id.indexOf("-")||null==g_lastParent)&&(leftright=""),"L"==leftright&&-1==g_currentMenuElement.id.indexOf("-")&&(leftright=""),0==delta&&""==leftright||(-1<g_currentIndex&&MenuManager.onMenuItemHoverOut(g_lastItemElem),g_currentIndex+=delta,"R"==leftright?(g_currentIndex=0,g_currentMenuElement=document.getElementById(g_lastItemElem.id.replace("_","-"))):"L"==leftright&&(g_currentIndex=Number(g_currentMenuElement.id.substr(g_currentMenuElement.id.length-1)),g_currentMenuElement=document.getElementById("cmenu")),menuIndex=0,-1<g_currentMenuElement.id.indexOf("-")&&(menuIndex=Number(g_currentMenuElement.id.substr(g_currentMenuElement.id.length-1))+1),debug.trace("menuindex: "+menuIndex,"menu"),MenuManager.onMenuItemHover(document.getElementById(g_currentMenuElement.id+"_"+g_currentIndex),g_currentIndex),MenuManager.onKeyDownCallback&&MenuManager.onKeyDownCallback(g_currentIndex,delta,leftright))))},_MenuManager.prototype.displayMenuOnHover=function(elementId,context,subcontext,id){g_mainMenuVisible&&(g_debug.trace("g_currentContextMenu: "+g_currentContextMenu),g_currentContextMenu!=context+subcontext+id)&&(MenuManager.hideContextMenu(),MenuManager.displayMenu(elementId,context,subcontext,id))},_MenuManager.prototype.flushCache=function(){g_debug.trace("flushContextMenuCache"),g_contextMenuCache=new Array,g_debug.trace("flushContextMenuCache - ok")},extendNs("SuperOffice.Util.MultiLanguageStringParser",function(ns){ns.parseInlineMultiLanguageString=function(str,cultureName,startIndex,returnAlternativeTranslation){if(0<=(startIndex=str.indexOf(":",startIndex=startIndex||0)-2)){if(str.length>startIndex+3&&!this.isQuote(str[startIndex+3]))return this.parseInlineMultiLanguageString(str,cultureName,startIndex+3,returnAlternativeTranslation);for(var quotes=0,i=startIndex;i<str.length;i++)if(this.isQuote(str.charAt(i))&"es++,2===quotes){if(str.length<=i+4||str.length>i+4&&":"!==str.charAt(i+4)){var c=1,c=(str.length>i+1&&";"===str.charAt(i+1)&&(c=2),str.substring(startIndex,i+c-startIndex)),newString=0<c.length?this.parseMultiLanguageString(c,cultureName,returnAlternativeTranslation):"",c=(c!==newString&&(str=str.replace(c,newString)),i+1-c.length+newString.length);0<=c&&startIndex!==c&&(str=this.parseInlineMultiLanguageString(str,cultureName,c,returnAlternativeTranslation));break}quotes=0}}return str},ns.isQuote=function(character){return'"'===character||"«"===character||"»"===character||"“"===character||"”"===character||"„"===character||"“"===character},ns.ParserState={InLangspecOrOtherText:0,ColonSeen:1,InFragment:2,TrailingQuoteSeen:3},ns.LanguageFragment=function(){this.LanguageName="",this.Fragment=""},ns.LanguageFragment.prototype.Clear=function(){this.LanguageName="",this.Fragment=""},ns.parseMultiLanguageString=function(multilangString,cultureName,returnAlternativeTranslation){if(multilangString){for(var langName=cultureName,fragments=[],state=this.ParserState.InLangspecOrOtherText,currentFragment=new this.LanguageFragment,output="",tmp={},i=0;i<multilangString.length;i++){var character=multilangString.charAt(i);switch(state){case this.ParserState.InLangspecOrOtherText:if(!this.isWhitespace(character))if(currentFragment.LanguageName.length<2)currentFragment.LanguageName+=character;else{if(":"!==character)return multilangString;state=this.ParserState.ColonSeen}break;case this.ParserState.ColonSeen:this.isQuote(character)?state=this.ParserState.InFragment:(output=(tmp=this.Reset(langName,fragments,state,currentFragment,output,"\0")).output,fragments=tmp.fragments,state=tmp.state,output+=":",(currentFragment=tmp.currentFragment).LanguageName+=character);break;case this.ParserState.InFragment:this.isQuote(character)?(fragments.push(currentFragment),currentFragment=new this.LanguageFragment,state=this.ParserState.TrailingQuoteSeen):currentFragment.Fragment+=character;break;case this.ParserState.TrailingQuoteSeen:state=";"===character?this.ParserState.InLangspecOrOtherText:(output=(tmp=this.Reset(langName,fragments,state,currentFragment,output,character,returnAlternativeTranslation)).output,currentFragment=tmp.currentFragment,fragments=tmp.fragments,tmp.state)}}switch(state){case this.ParserState.InLangspecOrOtherText:output=(tmp=this.Reset(langName,fragments,state,currentFragment,output,"\0",returnAlternativeTranslation)).output,currentFragment=tmp.currentFragment,fragments=tmp.fragments,state=tmp.state;break;case this.ParserState.ColonSeen:output=(tmp=this.Reset(langName,fragments,state,currentFragment,output,"\0",returnAlternativeTranslation)).output,currentFragment=tmp.currentFragment,fragments=tmp.fragments,state=tmp.state,output+=":";break;case this.ParserState.InFragment:output=(tmp=this.Reset(langName,fragments,state,currentFragment,output,"\0",returnAlternativeTranslation)).output,fragments=tmp.fragments,state=tmp.state,output=output+':"'+(currentFragment=tmp.currentFragment).Fragment;break;case this.ParserState.TrailingQuoteSeen:output=(tmp=this.Reset(langName,fragments,state,currentFragment,output,"\0",returnAlternativeTranslation)).output,currentFragment=tmp.currentFragment,fragments=tmp.fragments,state=tmp.state}return output}},ns.isWhitespace=function(char){return" "===char||"\t"===char||"\n"===char},ns.Reset=function(langName,fragments,state,currentFragment,output,character,returnAlternativeTranslation){var chosenFragment;return 0<fragments.length&&(0<(chosenFragment=$.grep(fragments,function(e){return e.LanguageName===langName})).length?output+=chosenFragment[0].Fragment:returnAlternativeTranslation&&(0<(chosenFragment=$.grep(fragments,function(e){return"US"===e.LanguageName})).length?output+=chosenFragment[0].Fragment:output+=fragments[0].Fragment),fragments=[]),0<currentFragment.LanguageName.length&&(output+=currentFragment.LanguageName.charAt(0),currentFragment.LanguageName=currentFragment.LanguageName.substring(1)),"\0"===character?(output+=currentFragment.LanguageName,currentFragment.LanguageName=""):currentFragment.LanguageName+=character,{output:output,fragments:[],currentFragment:currentFragment,state:this.ParserState.InLangspecOrOtherText}}});var NumberFormatter=new _NumberFormatter,_this=_NumberFormatter.prototype,g_record=(_this.GetDecimalDelimiter=function(){return this._decimalDelimiter},_this.GetCommaDelimiter=function(){return this._commaDelimiter},_this.SetDecimalDelimiter=function(delimiter){this._decimalDelimiter=delimiter},_this.SetCommaDelimiter=function(delimiter){this._commaDelimiter=delimiter},_this.FormatClean=function(num){var sVal="",sChar="";try{for(var nVal=num.length,i=0;i<nVal;i++)sChar=num.charAt(i),48<=(nChar=sChar.charCodeAt(0))&&nChar<=57&&(sVal+=num.charAt(i))}catch(exception){}return sVal},_this.ParseNumericValue=function(numAsString){return new NumberFormat(numAsString,this.GetDecimalDelimiter()).toUnformatted()},_this.ParsePercentage=function(pctAsString,roundToHundred){var pctAsString=pctAsString.replace(/\%/g,""),numberFormat=new NumberFormat(pctAsString,"."),pctAsString=new NumberFormat(pctAsString,","),numberFormat=numberFormat.toUnformatted(),pctAsString=pctAsString.toUnformatted();return 0<numberFormat&&0<pctAsString?pctAsString<numberFormat&&(numberFormat=pctAsString):numberFormat<0&&pctAsString<0&&numberFormat<pctAsString&&(numberFormat=pctAsString),numberFormat},_this.PrintPercentage=function(pct){return pct=pct.toFixed(2),this.FormatCurrency(new String(pct))+"%"},_this.PrintNumericValue=function(num,decimalNumbers,removeEmptyDecimals){return num=num.toFixed(decimalNumbers=removeEmptyDecimals&&100*num%100==0?0:decimalNumbers),this.FormatCurrency(new String(num),removeEmptyDecimals)},_this.FormatCurrency=function(num,removeEmptyDecimals){var sVal="",minus="",addedDecimals=!1,decimals=(0==num.lastIndexOf("-")&&(minus="-"),num.lastIndexOf(".")<0&&(num+="00",addedDecimals=!0),num=this.FormatClean(num),this.FormatCents(num));return"00"==decimals?(sVal=minus+this.FormatDollar(num,this.GetCommaDelimiter(),addedDecimals),removeEmptyDecimals&&(sVal=sVal.split(this.GetDecimalDelimiter())[0])):sVal=minus+this.FormatDollar(num,this.GetCommaDelimiter(),addedDecimals)+this.GetDecimalDelimiter()+decimals,sVal},_this.FormatNumber=function(num){var CommaDelimiter,minus="";try{CommaDelimiter=this.GetCommaDelimiter(),0==num.lastIndexOf("-")&&(minus="-"),num=this.FormatClean(num),num=parseInt(num);for(var samount=new String(num),i=0;i<Math.floor((samount.length-(1+i))/3);i++)samount=samount.substring(0,samount.length-(4*i+3))+CommaDelimiter+samount.substring(samount.length-(4*i+3))}catch(exception){}return minus+samount},_this.FormatCents=function(amount){var cents="";try{for(var i=0;"0"==amount.charAt(i);)i++;if(amount.length==i)return"00";var tmpAmount=parseInt(amount.slice(i)),samount=new String(tmpAmount);if(-1<samount.indexOf("e+",0))return"00";if(0==samount.length)return"00";if(1==samount.length)return"0"+samount;if(2==samount.length)return samount;cents=samount.substring(samount.length-2,samount.length)}catch(exception){}return cents},_this.FormatDollar=function(amount,CommaDelimiter,decimalsAdded){try{if(amount=parseInt(amount),(samount=-1<(samount=new String(amount)).indexOf("e+",0)&&(samount=new String(amount.toFixed()),decimalsAdded)?samount.substring(0,samount.length-3):samount).length<3)return 0;for(var samount=samount.substring(0,samount.length-2),i=0;i<Math.floor((samount.length-(1+i))/3);i++)samount=samount.substring(0,samount.length-(4*i+3))+CommaDelimiter+samount.substring(samount.length-(4*i+3))}catch(exception){}return samount},!1),g_pageUpdates=new Array,ready=!1,totalscripts=0,scripts=new Array,g_ControlFocusId="",g_busyIndicator=new BusyIndicator,g_singlepanel;function ReceiveServerError(){alert("Error")}function ASyncServersideEvent(soprotocol,id,param,context){so_defined(context)||(context=""),document.getElementById("__EVENTTARGET").value=id,document.getElementById("__EVENTARGUMENT").value=param,PageUpdate(soprotocol,context)}var countRequests=0;function MoveElement(sourceId,targetId){sourceId=document.getElementById(sourceId),targetId=document.getElementById(targetId);null!=sourceId&&null!=targetId&&(targetId.innerHTML=sourceId.innerHTML,sourceId.innerHTML="")}function SetControlFocus(id){null!=document.getElementById(id)&&(g_ControlFocusId=id)}function SetControlFocusBySoId(soid){soid=SuperOffice.SoHelper.getElementBySoId(soid);null!=soid&&(debug.trace("SetControlFocusBySoId: "+soid.id,"PageBuilder"),g_ControlFocusId=soid.id)}var g_additionalParams="",g_waitForConfirm=!1;function AlwaysFireBeforeFormSubmit(eventTarget,eventArgument){var soProtocol=FindSoProtocol(eventTarget),eventTarget=(theForm.__EVENTTARGET.value=eventTarget,theForm.__EVENTARGUMENT.value=eventArgument,g_additionalParams);""==g_additionalParams&&(eventTarget="[Request=Callback]"),g_additionalParams="",g_waitForConfirm||PageUpdate("soprotocol:"+soProtocol+eventTarget,"")}function FindSoProtocol(controlID){for(;-1!=controlID.indexOf("$");)controlID=controlID.replace("$","_");var control=document.getElementById(controlID);return null!=control&&(control=FindParentView(control))?control.attributes.soprotocol.value:null}function FindSoProtocolBySoId(soid){var controlID="",soid=SuperOffice.SoHelper.getElementBySoId(soid);return""!=(controlID=null!=soid?soid.id:controlID)?FindSoProtocol(controlID):""}function FindParentView(control){if(null==control)return 0;if(control.parentNode)for(;control.parentNode;){if("DIV"==control.tagName&&void 0!==control.attributes.soprotocol)return control;control=control.parentNode}return null}function AddWhiteCurtain(){$("#container").append("<div soid='pleasewaitdimmer' class='pleasewaitdimmer' />")}function RemoveWhiteCurtain(){$("[soid='pleasewaitdimmer']").remove()}function NewProject(){PageUpdate("soprotocol:project.main[mode=edit&new=true]?project_id=0","")}function NewPerson(){PageUpdate("soprotocol:person.main[mode=edit&new=true]?person_id=0","")}function EditPerson(id){PageUpdate("soprotocol:person.main[mode=edit]?person_id="+id,"")}var g_personIdToDelete=0;function DeletePerson(personId){0!=personId&&(personId="{nav=person&person_id="+(g_personIdToDelete=personId)+"}",Dialog.ConfirmDelete(personId,!1,"DeletePersonCallback"))}function DeleteCurrentPerson(){var personCurrent=AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.GetCurrent","","person");void 0!==personCurrent&&0<personCurrent.Id&&DeletePerson(personCurrent.Id)}function RetirePerson(personId,refreshFunction){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Person.TogglePersonRetired","",parseInt(personId)),eval(refreshFunction)}function DeletePersonCallback(res){0!=g_personIdToDelete&&(1!=res.getStatus()&&2!=res.getStatus()||(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Person.DeletePerson","",parseInt(g_personIdToDelete)),PageUpdate("soprotocol:refresh","")),g_personIdToDelete=0)}function ExternalPersonRowClick(archiveControl,selectedRows){archiveControl=archiveControl.getSelectedRows()[0].attributes.rowtype.value;debug.trace("linkhint: "+archiveControl,"ExtUsers")}function ExternalPersonRowDoubleClick(archiveControl,personId,selectedRows){archiveControl.getSelectedRows()[0].attributes.rowtype.value;archiveControl="editexternalperson[dialog=stop]?person_id={0}".replace("{0}",personId);debug.trace("dlgStr: "+archiveControl,"ExtUsers"),Dialog.open("editexternalperson",archiveControl,"ExternalPersonsArchiveArchiveControl.RefreshList(g_lastUserFilterId)")}var g_lastUserFilterId="";function ExternalPersonFilter(id,archiveControl){debug.trace("ExternalPersonFilter, id="+id,"External users"),debug.trace("ExternalPersonFilter, a="+archiveControl,"External users"),g_lastUserFilterId=id,archiveControl.RefreshList(id)}function ExternalPersonEdit(archiveControl){var linkHint,rows=archiveControl.getSelectedRows();0<rows.length&&(linkHint=rows[0].attributes.rowtype.value,ExternalPersonRowDoubleClick(archiveControl,SuperOffice.SoHelper.getValueFromLinkHint(linkHint,"person"),rows))}function ExternalPersonRemoveLogin(archiveControl){for(var rows=archiveControl.getSelectedRows(),assocIds=new Array,t=0;t<rows.length;++t){var linkHint=rows[t].attributes.rowtype.value,aid=SuperOffice.SoHelper.getValueFromLinkHint(linkHint,"associate"),linkHint="0"==SuperOffice.SoHelper.getAnyValueFromLinkHint(linkHint,"deleted");-1<aid&&linkHint&&assocIds.push(aid)}0<assocIds.length&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Person.RemoveExternalUserLogin","",assocIds.join(",")),archiveControl.RefreshList(g_lastUserFilterId))}function ExternalPersonRemoveAsExternalUser(archiveControl){for(var rows=archiveControl.getSelectedRows(),assocIds=new Array,t=0;t<rows.length;++t){var linkHint=rows[t].attributes.rowtype.value,linkHint=SuperOffice.SoHelper.getValueFromLinkHint(linkHint,"associate");-1<linkHint&&assocIds.push(linkHint)}0<assocIds.length&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Person.RemoveExternalUsers","",assocIds.join(",")),archiveControl.RefreshList(g_lastUserFilterId))}function ExtPersonDisableButtons(id,archiveControl){debug.trace("ExtPersonDisableButtons; "+id,"External users");var archiveControl=archiveControl.getSelectedRows(),rowLen=archiveControl.length;0==rowLen?SuperOffice.SoHelper.disableElementBySoId(id):id.endsWith("_0")?_hasActiveUsers(archiveControl)?SuperOffice.SoHelper.enableElementBySoId(id):SuperOffice.SoHelper.disableElementBySoId(id):id.endsWith("_1")?_hasInactiveUsers(archiveControl)||_hasActiveUsers(archiveControl)?SuperOffice.SoHelper.enableElementBySoId(id):SuperOffice.SoHelper.disableElementBySoId(id):1<rowLen?SuperOffice.SoHelper.disableElementBySoId(id):SuperOffice.SoHelper.enableElementBySoId(id)}function _hasActiveUsers(rows){for(var t=0;t<rows.length;++t)if(-1<rows[t].attributes.rowentityname.value.indexOf("all"))return!0}function _hasInactiveUsers(rows){for(var t=0;t<rows.length;++t)if(-1<rows[t].attributes.rowentityname.value.indexOf("expired"))return!0}function RemoveMiddleName(){$("[soid=MiddleName_textfield]").is(":hidden")&&$("[soid=MiddleName_textfield]").parent().parent().parent().css("width","0")}function OpenCardAfterClose(personId){Dialog.closeWithCallback(),void 0!==personId&&UIHelper.SafeGetOpener().PageUpdate("soprotocol:person.main?person_id="+personId)}function addDocument(){UIHelper.GetOpener().Dialog.close(),AjaxMethodDispatcher.GetData({ajaxMethod:"SuperOffice.CRM.Web.AjaxMethods.SuperStateCRM.IsRunningTestDrive",methodArguments:[],cacheoptions:{useCache:!0,duration:6e4,refresh:!1},fnCallback:function(data){data?UIHelper.GetOpener().Dialog.Information("SuperOffice","[SR_COMMON_TESTDRIVE_NODOCS]"):UIHelper.GetOpener().Dialog.open("document","document[dialog=stop]?document_id=0","RefreshDocumentCurrent();")},readonlysession:!0})}function addAppointment(){UIHelper.GetOpener().Dialog.close();var date=new Date,minutes=date.getMinutes(),date=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.SuperState.GetCurrent","","day").Name+" "+date.getHours()+":"+(minutes-minutes%15);UIHelper.GetOpener().Dialog.open("appointment","appointment[dialog=stop]?appointment_id=0&appointment_type=1&doby="+date,"")}function toggleShipmentTypes(x,soid){var tmpX;1==x||"true"==x||"True"==x?tmpX=!0:0!=x&&"false"!=x&&"False"!=x||(tmpX=!1),$("[soid="+soid+"]").css("visibility",0==tmpX?"hidden":"visible")}function SendEMailToPersonEmailAddress(email,description,type){var method;""!==email&&(UIHelper.GetOpener().Dialog.close(),method=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetSendEMailToPersonEmailAdddressScript","",email,description,type),(0<=method.indexOf("Dialog.open('")||0<=method.indexOf("Dialog.Information("))&&(method="UIHelper.GetOpener()."+method),eval(method))}function SendEMailToPerson(personId){var method;0!=personId&&(method=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetSendEMailToPersonsScript","",personId.toString()),eval(method))}SuperOffice.Project=function(){var pub={saveProject:function(saveMethod,typeField){var value,displayConfirmationDialog,context;typeField?(value=typeField.getSelectedValue(),displayConfirmationDialog=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Project.DisplayConfirmationDialog","",value),displayConfirmationDialog?(context=new Object,context.saveMethod=saveMethod,Dialog.YesNo("","[SR_PROJECTTYPE_CHANGED_WARNING]","question","","SuperOffice.Project.confirmCalllback",context)):eval(saveMethod)):eval(saveMethod)},confirmCalllback:function(res){1==res.getStatus()&&eval(res.getContext().saveMethod)}};return pub}();var g_projectIdToDelete=0,blobId="ProjectImageId",blobName="ProjectImageName";function DeleteProject(projectId){debug.trace("Delete project: "+projectId,"project"),0!=projectId&&(g_projectIdToDelete=projectId,Dialog.ConfirmDelete("{nav=project&project_id="+projectId+"}",!1,"DeleteProjectCallBack"))}function DeleteProjectCallBack(res){0!=g_projectIdToDelete&&(1!=res.getStatus()&&2!=res.getStatus()||(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Project.DeleteProject","",g_projectIdToDelete),PageUpdate("soprotocol:?project_id="+g_clientOptions.LastValidHistoryItem,"")),g_projectIdToDelete=0)}function UpdateProjectImage(imageIdElementSoId){g_SoImage_ProjectImageCtrl.changeImageId(SuperOffice.SoHelper.getElementBySoId(imageIdElementSoId).value)}function SetProjectImageFromDialog(){Dialog.setParentReturnObject(1,SuperOffice.SoHelper.getElementBySoId("ProjectImageDlgBlobIdKey").value,SuperOffice.SoHelper.getElementBySoId("ProjectImageDlgBlobNameKey").value)}function ClearProjectImage(){SuperOffice.SoHelper.getElementBySoId(blobId).value="0",SuperOffice.SoHelper.getElementBySoId(blobName).value="",SuperOffice.SoHelper.getElementBySoId("ProjectImageNameLabel").value="",UpdateProjectImage(blobId)}function GetEndDateFromExtraInfo(extraInfo){var unit,duration,values=extraInfo.split("&");for(i=0;i<values.length;i++){var keyAndValue=values[i].split("=");2==keyAndValue.length&&("duration"==keyAndValue[0]?duration=keyAndValue[1]:"unit"==keyAndValue[0]&&(unit=keyAndValue[1]))}return AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Project.GetEndDate","",Number(duration),Number(unit))}function AddMembersToNewProject(ids){ids=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Project.NewProjectWithMembers","",ids);PageUpdate("soprotocol:project?project_id="+ids,""),QueuedPageUpdate("soprotocol:project.main[mode=edit&refresh=true]")}function CorrectButtonPlacement(labelWithButtonId){var label,controlGroup,labelWithButton=$("[soid="+labelWithButtonId+"]");0!=labelWithButton.length&&0!=(controlGroup=labelWithButton.parent().parent().parent()).length&&(label=$("[soid="+labelWithButtonId+"_label]"),labelWithButtonId=$("[soid="+labelWithButtonId+"_button]"),controlGroup=controlGroup.width()+controlGroup.offset().left-labelWithButton.offset().left,label.outerWidth()+labelWithButtonId.outerWidth()>controlGroup&&(labelWithButtonId.css("position","absolute"),label.css("position","absolute")),labelWithButton.css("width",labelWithButton=controlGroup-10),label.css("width",labelWithButton-(labelWithButtonId.outerWidth()+20)))}function SetLabelWidth(labelWithButtonId){var controlGroup,labelWithButton=$(SuperOffice.SoHelper.getElementBySoId(labelWithButtonId));null!=labelWithButton&&0!=(controlGroup=labelWithButton.parent().parent().parent()).length&&(labelWithButtonId=$("[soid="+labelWithButtonId+"_label]"),controlGroup=controlGroup.width()+controlGroup.offset().left-labelWithButton.offset().left-10,labelWithButton.css("width",controlGroup),labelWithButtonId.css("width",controlGroup))}function DeleteProjectImage(imageId,current){imageId=$("[soid="+imageId+"]").attr("value");AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Project.DeleteProjectImage","",parseInt(imageId)),SuperOffice.PageBuilder.refresh(null,current+"_id=0&"+current+"_type=0")}function openEditProjectMembersDialog(){for(var rows=ProjectMemberArchiveArchiveControl.getSelectedRows(),ids="",i=0;i<rows.length;i++)ids?ids+=","+GetSelectedLinkHintValue(rows[i],"projectmember_id"):ids=GetSelectedLinkHintValue(rows[i],"projectmember_id");0<(ids=String(ids)).length&&Dialog.open("ProjectMember","projectmembers[dialog=stop].main?projectmembers_id=&projectmembers_name="+ids,"ProjectMemberArchiveArchiveControl.RefreshList();",!1)}function FindSelectionFromMdoExtension(mdoObj,callback,selectionType,selectionMemberType){var overrideObject=[];so_defined(selectionType)&&("combined"==selectionType&&overrideObject.push({Name:"kind",OperatorName:"set",Value:2,DisplayValue:"[SR_SELECTION_COMBINED]",Active:!0,ReadOnly:!0}),"!combined"==selectionType?overrideObject.push({Name:"kind",OperatorName:"notOneOf",Value:"[I:2]",DisplayValue:"[SR_SELECTION_COMBINED]",Active:!0,ReadOnly:!0}):"static"==selectionType?overrideObject.push({Name:"kind",OperatorName:"set",Value:0,DisplayValue:"[SR_SELECTION_STATIC]",Active:!0,ReadOnly:!0}):"dynamic"==selectionType&&overrideObject.push({Name:"kind",OperatorName:"set",Value:1,DisplayValue:"[SR_SELECTION_DYNAMIC]",Active:!0,ReadOnly:!0})),so_defined(selectionMemberType)&&""!=selectionMemberType&&overrideObject.push({Name:"targetTableNumber",OperatorName:"set",Value:selectionMemberType,DisplayValue:selectionMemberType,Active:!0,ReadOnly:!0}),mdoObj.openExternalFind("selection",selectionMemberType,overrideObject,!1,!1)}function removeStaticMembers(selectedRows){for(var args=new Array,i=0;i<selectedRows.length;i++){var linkHint=selectedRows[i].attributes.id.value,linkHint=SuperOffice.SoHelper.getAnyValueFromLinkHint(linkHint,"selectionmember_id");args.push(linkHint)}return 0<args.length?AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.RemoveStaticMembersOnCurrentSelection","",args.join(",")):""}function silentRemoveStaticMembers(archiveControl){for(var selectedRows=archiveControl.getSelectedRows(),args=new Array,i=0;i<selectedRows.length;i++){var linkHint=selectedRows[i].attributes.id.value,linkHint=SuperOffice.SoHelper.getAnyValueFromLinkHint(linkHint,"selectionmember_id");args.push(linkHint)}0<args.length&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.RemoveStaticMembersOnCurrentSelection","",args.join(",")),archiveControl.removeSelectedRows())}function disableGroupFields(checkboxId1,textboxId1,checkboxId2,textboxId2){for(var chkBox1=SuperOffice.SoHelper.getElementBySoId(checkboxId1),chkBox2=SuperOffice.SoHelper.getElementBySoId(checkboxId2),t=4;t<arguments.length;t++)chkBox1.checked||chkBox2.checked?SuperOffice.SoHelper.disableElementBySoId(arguments[t]):SuperOffice.SoHelper.enableElementBySoId(arguments[t])}function SyncCheckboxes(checkboxId1,checkboxId2){checkboxId1=SuperOffice.SoHelper.getElementBySoId(checkboxId1);null!=checkboxId1&&checkboxId1.click(function(){setCheckboxesRev('" + checkboxId1 + "','" + checkboxId2 + "')})}function setCheckboxes(checkboxId1,checkboxId2){checkboxId1=SuperOffice.SoHelper.getElementBySoId(checkboxId1);SuperOffice.SoHelper.getElementBySoId(checkboxId2).checked=checkboxId1.checked}function setCheckboxesRev(checkboxId1,checkboxId2){checkboxId1=SuperOffice.SoHelper.getElementBySoId(checkboxId1);SuperOffice.SoHelper.getElementBySoId(checkboxId2).checked=checkboxId1.checked}extendNs("SuperOffice.Controls.SearchTextBox",function(ns){var $=jQuery;ns.watch=function(soid){var controlElem=$.fromSoId(soid),input=$("input",controlElem);$("#freetextsearch .clear-icon").on("click",function(){$("input",controlElem).val(""),$(".clear-icon",controlElem).fadeOut(),$("input",controlElem).trigger("focus")}),FreeTextSearchWatch(soid,!0,!0),input.on("keyup",function(e){0<e.target.value.length?$(".clear-icon",controlElem).fadeIn():$(".clear-icon",controlElem).fadeOut()}),input.focusParentWithSelf("focused")}}),SuperOffice.Selection=(()=>{var pub={Archive:{}};return pub.Archive.Current={},pub.MiniCardArchive={},pub.MiniCardArchive.Current={},pub.SelectionId=0,pub.SelectionMemberType=null,pub.SelectionType=null,pub.miniSelectionRefresh=!1,pub.Current=null,pub.SwitchTaskView=function(o){o=$(so(o)).attr("soprotocol");"selection"==SuperOffice.Environment.CurrentMainPageId&&QueuedPageUpdate(o+"[refresh=false]?selection_id="+g_clientOptions.LastValidHistoryItem)},pub.openFindFromSelectionMenu=function(){var context=new Object;context.CriterionEntity="findselection",context.FindType=SuperOffice.Find.FindTypeEnum.Normal,SuperOffice.Find.OpenFindInlineDialog(context)},pub.OpenAddDialog=function(){"contact"!=this.SelectionMemberType&&SuperOffice.Find.OpenFindInlineDialog({FindType:SuperOffice.Find.FindTypeEnum.Single,CriterionEntity:this.SelectionMemberType,Callback:"SuperOffice.Selection.OpenAddDialogCallback",IsSelectionAdd:!0,MultiSelect:!0})},pub.OpenAddDialogCallback=function(res){res=res.getValue();if(null!=res&&""!=res){var items=res.split("|,|");if(0!=items.length){for(var idArray=new Array,t=0;t<items.length;++t){var tmp=items[t].split("|");0<tmp.length&&""!=(tmp=tmp[0])&&idArray.push(parseInt(tmp,10))}0<idArray.length&&AjaxMethodDispatcher.CallASync("SuperOffice.Selection.AddSelectionMembersCallBack","SuperOffice.Selection.AddSelectionMembersErrorCallBack","SuperOffice.Selection.AddSelectionMembersErrorCallBack","","SuperOffice.CRM.Web.AjaxMethods.Selection.AddSelectionMembers",this.SelectionId,idArray)}}},pub.AddSelectionMembersCallBack=function(res){this.RefreshArchives()},pub.AddSelectionMembersErrorCallBack=function(res){},pub.OpenAddMembersDialog=function(membertype){var membertypeToFind="",membertypeToFind=so_defined(membertype)?membertype:this.SelectionMemberType;Dialog.open("findinlinetoselection","findinlinetoselection[dialog=stop].find"+membertypeToFind+"?membermode_id=0&findtype_id=1&findtype_type=single","SuperOffice.Selection.RefreshArchives();",!0)},pub.RemoveMembersDialog=function(){Dialog.open("findinlinetoselection","findinlinetoselection[dialog=stop].find"+this.SelectionMemberType+"?membermode_id=1&findtype_id=1&findtype_type=single","SuperOffice.Selection.RefreshArchives();",!0)},pub.SetCompleted=function(isCompleted){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.SetCompleted","",isCompleted)},pub.OnArchiveListReceived=function(tableRowParser,selType){debug.trace("OnArchiveListReceived","selection")},pub.GetSelectionArchive=function(){return this.Current.MemberArchiveVisible?SelectionMemberArchiveArchiveControl:this.Current.ShadowArchiveVisible?ShadowSelectionMemberArchiveArchiveControl:void 0},pub.RefreshArchives=function(){null!=this.Current&&(0!=SuperOffice.Selection.SelectionType?(SelectionMemberArchiveArchiveControl.ClearList(),SelectionMemberArchiveArchiveControl.ShowEmptyListLink(),"undefined"!=typeof ShadowSelectionMemberArchiveArchiveControl&&(ShadowSelectionMemberArchiveArchiveControl.ClearList(),ShadowSelectionMemberArchiveArchiveControl.ShowEmptyListLink()),this.miniSelectionRefresh&&"undefined"!=typeof SelectionMemberMiniCardArchiveArchiveControl&&(SelectionMemberMiniCardArchiveArchiveControl.ClearList(),SelectionMemberMiniCardArchiveArchiveControl.ShowEmptyListLink())):(this.Current.MemberArchiveVisible&&SelectionMemberArchiveArchiveControl.RefreshList(),this.Current.ShadowArchiveVisible&&ShadowSelectionMemberArchiveArchiveControl.RefreshList()))},pub.EnableEmptyListLink=function(){this.Current.MemberArchiveVisible&&SelectionMemberArchiveArchiveControl.EnableEmptyListLink()},pub.DisableEmptyListLink=function(){this.Current.MemberArchiveVisible&&SelectionMemberArchiveArchiveControl.DisableEmptyListLink()},pub.HideEmptyListLink=function(){this.Current.MemberArchiveVisible&&SelectionMemberArchiveArchiveControl.HideEmptyListLink()},pub.ShowEmptyListLink=function(){this.Current.MemberArchiveVisible&&SelectionMemberArchiveArchiveControl.ShowEmptyListLink()},pub.OnMiniCardSelectionTabClick=function(archiveControl){archiveControl.RefreshList()},pub.SetIconState=function(enabledIcon,disabledIcon){UIHelper.DisableSoImageBySoId(disabledIcon),UIHelper.EnableSoImageBySoId(enabledIcon)},pub.EnableDisableMailingTasks=function(selectedIsChecked){selectedIsChecked?SuperOffice.SoHelper.disableElementsBySoId("SelectionTaskMailingHtml","SelectionTaskMailingSms","SelectionTaskMailingDocument"):SuperOffice.SoHelper.enableElementsBySoId("SelectionTaskMailingHtml","SelectionTaskMailingSms","SelectionTaskMailingDocument")},pub.getPersonIdFromRowTypeValue=function(str){return pub.getIdFromString("person_id=",str)},pub.getContactIdFromRowTypeValue=function(str){return pub.getIdFromString("contact_id=",str)},pub.getIdFromString=function(strId,str){var endPos,strIdLen=strId.length,personId=0,strId=str.indexOf(strId);return personId=-1<strId?(endPos=-1<(endPos=str.indexOf("&",strId+strIdLen))?str.substring(strId+strIdLen,endPos):str.substr(strId+strIdLen),parseInt(endPos)):personId},pub})(),g_selectionIsCreated=!1;var g_uniqueChkBoxElem="";function SetUnique(chkBoxId){g_selectionIsCreated||2!=SuperOffice.Selection.SelectionType&&(chkBoxId=SuperOffice.SoHelper.getElementBySoId(chkBoxId),(g_uniqueChkBoxElem=chkBoxId).checked)&&Dialog.YesNo("SuperOffice","[SR_SE_WARN_ONLY_ONE_PERSON]","warning","","SetUniqueCallBack")}function SetUniqueCallBack(res){1==res.getStatus()?g_uniqueChkBoxElem.checked=!0:g_uniqueChkBoxElem.checked=!1}function SetIncludePerson(chkBoxId){var include=0;SuperOffice.SoHelper.getElementBySoId(chkBoxId).checked&&(include=1),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.SetIncludePerson","",include)}function CopySelectionCallBack(val,socontext){PageUpdate("soprotocol:Selection?selection_id="+val,"")}var g_selectionIdToDelete=0;function DeleteSelection(selectionId){0!=selectionId&&(g_selectionIdToDelete=selectionId,AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.GetParentCombinedSelections","",selectionId)?Dialog.YesNo("SuperOffice","[SR_SE_WARN_PARENT_SELECTION_CONTAINS_THIS_SELECTION]","warning","","DeleteSelectionConfirm"):DeleteSelectionConfirm(null))}function DeleteSelectionConfirm(res){0==g_selectionIdToDelete||res&&1!=res.getStatus()||Dialog.ConfirmDelete("{nav=selection&selection_id="+g_selectionIdToDelete+"}",!1,"DeleteSelectionCallBack")}function DeleteSelectionCallBack(res){0!=g_selectionIdToDelete&&(1!=res.getStatus()&&2!=res.getStatus()||(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.DeleteSelection","",g_selectionIdToDelete),PageUpdate("soprotocol:?selection_id="+g_clientOptions.LastValidHistoryItem,"")),g_selectionIdToDelete=0)}function ExportToFile(p1,p2){}function OpenEmailDialog(){var script=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Mail.GetSendEMailScriptWithDefaults","");eval(script)}function CheckPerformOnSelected(){try{SuperOffice.Selection.Current.MemberArchiveVisible&&"undefined"!=typeof SelectionMemberArchiveArchiveControl?TogglePerformOnSelected(SelectionMemberArchiveArchiveControl):SuperOffice.Selection.Current.ShadowArchiveVisible&&"undefined"!=typeof ShadowSelectionMemberArchiveArchiveControl&&TogglePerformOnSelected(ShadowSelectionMemberArchiveArchiveControl)}catch(ex){}}function TogglePerformOnSelected(ArchiveControl){var elem;so_defined(ArchiveControl)&&null!=(elem=SuperOffice.SoHelper.getElementBySoId("SelectionPerformOnSelected"))&&(debug.trace("TogglePerformOnSelected: "+ArchiveControl._id+", "+ArchiveControl.getSelectedRows().length,"selection"),1<ArchiveControl.getSelectedRows().length?elem.checked=!0:elem.checked=!1,SuperOffice.Selection.EnableDisableMailingTasks(elem.checked))}function DeleteContactsFromSelection(selectionId){var tempSelId=SuperOffice.Selection.Tasks.CheckCreateTempSelection(!0);Dialog.YesNo("[SR_WARN_CAPTION]","[SR_SEL_DELETE_MEMBERS_YES_NO]","question","","DeleteContactsFromSelectionCallback",0<tempSelId?tempSelId:selectionId)}function DeleteContactsFromSelectionCallback(res){1==res.getStatus()&&Dialog.YesNo("[SR_WARN_CAPTION]","[SR_SEL_DELETE_MEMBERS_OK_CANCEL]","warning","","DeleteContactsFromSelectionCallback2",res.getContext())}function DeleteContactsFromSelectionCallback2(res){1==res.getStatus()&&(Dialog.disableWindow(window),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.DeleteCompaniesFromSelection","",parseInt(res.getContext(),10)),Dialog.enableWindow(window),"undefined"!=typeof SelectionMemberArchiveArchiveControl)&&null!=SelectionMemberArchiveArchiveControl&&SuperOffice.Selection.RefreshArchives()}function DeletePersonsFromSelection(selectionId){var tempSelId=SuperOffice.Selection.Tasks.CheckCreateTempSelection(!0);Dialog.YesNo("[SR_WARN_CAPTION]","[SR_SELECTION_DELETE_PERSONS_YES_NO]","question","","DeletePersonsFromSelectionCallback",0<tempSelId?tempSelId:selectionId)}function DeletePersonsFromSelectionCallback(res){1==res.getStatus()&&Dialog.YesNo("[SR_WARN_CAPTION]","[SR_SELECTION_DELETE_PERSONS_OK_CANCEL]","warning","","DeletePersonsFromSelectionCallback2",res.getContext())}function DeletePersonsFromSelectionCallback2(res){1==res.getStatus()&&(Dialog.disableWindow(window),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.DeletePersonsFromSelection","",parseInt(res.getContext(),10)),Dialog.enableWindow(window),"undefined"!=typeof SelectionMemberArchiveArchiveControl)&&null!=SelectionMemberArchiveArchiveControl&&SuperOffice.Selection.RefreshArchives()}function OpenDynamicSelectionCriterionDialog(){debug.trace("g_selCriterion: "+SuperOffice.Selection.Archive.Current.criterion,"selection"),debug.trace("g_currentCriterionFieldName: "+g_currentCriterionFieldName,"selection"),OpenCriterionDialogForSelection(SuperOffice.Selection.Archive.Current.criterion,g_currentCriterionFieldName,"criteria",g_currentCriterionPrimaryKey)}function RemoveEmptySelectionArchive(tableRowParser,soid){void 0!==tableRowParser&&(0==(tableRowParser=$("[soid="+soid+"]")).children(".ArchiveListContainer").children().length?tableRowParser.css("display","none"):tableRowParser.css("display",""))}function taskloggedOnMailServerCallback(res){res?(UIHelper.EnableToolButtonBySoId("SelectionTaskMailMerge"),UIHelper.EnableToolButtonBySoId("SelectionTaskSendEmail")):(UIHelper.DisableToolButtonBySoId("SelectionTaskMailMerge"),UIHelper.DisableToolButtonBySoId("SelectionTaskSendEmail"))}function taskloggedOnMailServerError(res){UIHelper.DisableToolButtonBySoId("SelectionTaskMailMerge"),UIHelper.DisableToolButtonBySoId("SelectionTaskSendEmail")}function ArchiveControl(){}function ArchiveResultParser(result){if(null!=result)for(var endIndex=result.indexOf("}|§|"),args=(this._dataGrid=result.substring(endIndex+4),this._result=result.substring(1,endIndex),this._result.split(";")),i=0;i<args.length;i++){var tmp=args[i].split(":");switch(tmp[0]){case"inputRowIds":this._inputRowIds=tmp[1].split(",");break;case"currentPage":this._currentPage=tmp[1];break;case"hasMorePages":this._hasMorePages=tmp[1];break;case"extraReturn":this._extraReturn=tmp[1];break;case"count":this._count=tmp[1];break;case"currentvalues":this._currentValues=tmp[1];break;case"instanceId":this._responseInstanceId=tmp[1]}}}function GetPrimaryKeyFromRow(row){return row.attributes.primaryKey.value}function GetEntityKeyValue(linkhint,entityName){for(var step1=linkhint.split("&"),i=0;i<step1.length;i++){var step2=step1[i].split("=");if(step2[0].toLowerCase()==entityName.toLowerCase()+"_id")return step2[1]}return""}function disabletext(e){return!1}function reEnable(){return!0}SuperOffice.Selection.Tasks=(()=>{var pub={IsPerformOnSelected:function(){try{if(!SuperOffice.SoHelper.getSoCheckBoxState("SelectionPerformOnSelected"))return 0}catch(ex){return 0}return 1},CheckCreateTempSelection:function(overrideCheckbox){var selectionArchiveControl=null;if(!so_defined(selectionArchiveControl=!SuperOffice.Selection.Current.HasShadowArchive||SuperOffice.Selection.Current.MemberArchiveVisible?SelectionMemberArchiveArchiveControl:ShadowSelectionMemberArchiveArchiveControl))return 0;if(!(overrideCheckbox=so_defined(overrideCheckbox)?overrideCheckbox:!1)&&!this.IsPerformOnSelected())return 0;var overrideCheckbox=0,idArray=selectionArchiveControl.getSelectedKeys(),idString="",isContact=!1;if(0<idArray.length){var nav=SuperOffice.SoHelper.getNavFromLinkHint(idArray[0]);"contact"!=nav&&"person"!=nav||(isContact=!0);for(var t=0;t<idArray.length;++t)isContact?(""!=idString&&(idString+="|"),idString+=SuperOffice.Selection.getContactIdFromRowTypeValue(idArray[t])+","+SuperOffice.Selection.getPersonIdFromRowTypeValue(idArray[t])):(""!=idString&&(idString+=","),idString+=SuperOffice.Selection.getIdFromString(nav+"_id=",idArray[t]));overrideCheckbox=isContact?AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.CreateTemporarySelection","",idString):AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.CreateTemporaryGenericSelection","",SuperOffice.Selection.Current.TargetTableNumber,idString)}return overrideCheckbox},CloneSelection:function(toolbuttonSoId){SuperOffice.SoHelper.disableElementBySoId(toolbuttonSoId);var selectionId=0;if(null!=(selectionArchiveControl=!SuperOffice.Selection.Current.HasShadowArchive||SuperOffice.Selection.Current.MemberArchiveVisible?SelectionMemberArchiveArchiveControl:ShadowSelectionMemberArchiveArchiveControl))try{0<selectionArchiveControl.getSelectedRows().length&&(selectionId=this.CheckCreateTempSelection(!1))}catch(ex){}var useShadow=!1;0==selectionId&&SuperOffice.Selection.Current.ShadowArchiveVisible&&(useShadow=!0),AjaxMethodDispatcher.CallASync("SuperOffice.Selection.Tasks.CloneSelectionCallBack","SuperOffice.Selection.Tasks.CloneSelectionErrorCallBack","SuperOffice.Selection.Tasks.CloneSelectionErrorCallBack",toolbuttonSoId,"SuperOffice.CRM.Web.AjaxMethods.Selection.CopySelection",selectionId,useShadow)},CloneSelectionCallBack:function(val,socontext){PageUpdate("soprotocol:Selection?selection_id="+val,""),SuperOffice.SoHelper.enableElementsBySoId(socontext)},CloneSelectionErrorCallBack:function(val,socontext){SuperOffice.SoHelper.enableElementsBySoId(socontext)},ExportToFile:function(){selectionArchiveControl=!SuperOffice.Selection.Current.HasShadowArchive||SuperOffice.Selection.Current.MemberArchiveVisible?SelectionMemberArchiveArchiveControl:ShadowSelectionMemberArchiveArchiveControl;var tempSelId=SuperOffice.Selection.Tasks.CheckCreateTempSelection(!1),orderby=selectionArchiveControl.getOrderBy(),orderbystr="";if(orderby&&0<orderby.length){for(var i=0;i<orderby.length;i++){var order=orderby[i];orderbystr+=order.Name+","+order.Direction+";"}0<orderbystr.length&&(orderbystr=orderbystr.substring(0,orderbystr.length-1))}Dialog.open("taskexporttofile","taskexporttofile[dialog=stop]&tempselectionid="+tempSelId+"&useContacts="+SuperOffice.Selection.Current.ShadowArchiveVisible+"&orderby="+orderbystr,"",!1,!1,!1,!0)},ExportToExcel:function(useSelectedRows){void 0===useSelectedRows&&(useSelectedRows=1==this.IsPerformOnSelected());var isShadow=!1,tempRest=(!SuperOffice.Selection.Current.HasShadowArchive||SuperOffice.Selection.Current.MemberArchiveVisible?selectionArchiveControl=SelectionMemberArchiveArchiveControl:(selectionArchiveControl=ShadowSelectionMemberArchiveArchiveControl,isShadow=!0),"");if(useSelectedRows)if(isShadow){for(var rows=selectionArchiveControl.getSelectedRows(),i=0;i<rows.length;i++)tempRest=(tempRest+="contactpersonids="+GetSelectedLinkHintValue(rows[i],"contact_id")+",")+"contactpersonids="+GetSelectedLinkHintValue(rows[i],"person_id")+",";tempRest+="selectionId="+SuperOffice.Selection.SelectionId}else{useSelectedRows=SuperOffice.Selection.Tasks.CheckCreateTempSelection(!1);0<useSelectedRows&&(tempRest="selectionId="+useSelectedRows)}else tempRest="selectionId="+SuperOffice.Selection.SelectionId;selectionArchiveControl.ExportToFile(tempRest)},DeleteEntitiesFromDatabase:function(selectionId,titleResource1,titleResource2){var tempSelId=SuperOffice.Selection.Tasks.CheckCreateTempSelection(!0);Dialog.YesNo("",titleResource1,"question","","SuperOffice.Selection.Tasks.DeleteEntitiesFromDatabaseCallback",{SelectionId:0<tempSelId?tempSelId:selectionId,ConfirmCaption:titleResource2})},DeleteEntitiesFromDatabaseCallback:function(res){1==res.getStatus()&&Dialog.YesNo("",res.getContext().ConfirmCaption,"warning","","SuperOffice.Selection.Tasks.DeleteEntitiesFromDatabaseCallback2",res.getContext())},DeleteEntitiesFromDatabaseCallback2:function(res){1==res.getStatus()&&(Dialog.disableWindow(window),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Selection.DeleteEntitiesFromSelection","",parseInt(res.getContext().SelectionId,10)),Dialog.enableWindow(window),"undefined"!=typeof SelectionMemberArchiveArchiveControl)&&null!=SelectionMemberArchiveArchiveControl&&SuperOffice.Selection.RefreshArchives()},PerformMailMerge:function(){var tempSelId=SuperOffice.Selection.Tasks.CheckCreateTempSelection(!1);Dialog.open("mailmergewizard","mailmergewizard[dialog=stop]&selid="+tempSelId,"PageUpdate('soprotocol:', '');")},findIdsForBulkUpdate:function(onlyOnSelectedMemebers,rows,entity){var ids="";return ids=onlyOnSelectedMembers?GetSelectedLinkHintValues(rows,SuperOffice.Selection.Current.SelectionMemberType+"_id"):ids},OpenBulkUpdateDialog:function(){var isShadow=!1,onlyOnSelectedMembers=(!SuperOffice.Selection.Current.HasShadowArchive||SuperOffice.Selection.Current.MemberArchiveVisible?selectionArchiveControl=SelectionMemberArchiveArchiveControl:(selectionArchiveControl=ShadowSelectionMemberArchiveArchiveControl,isShadow=!0),this.IsPerformOnSelected()),archiveControl=SuperOffice.Selection.GetSelectionArchive(),entities=[],entityName=isShadow?"contact":SuperOffice.Selection.Current.SelectionMemberType;if(onlyOnSelectedMembers){var rows=archiveControl.getSelectedRows(),ids=GetSelectedLinkHintValues(rows,entityName+"_id");if(void 0===ids)return;entities.push({entityName:entityName,value:{ids:ids,count:ids.split(",").length}}),"contact"===entityName&&void 0!==(ids=GetSelectedLinkHintValues(rows,"person_id"))&&""!==ids&&entities.push({entityName:"person",value:{ids:ids,count:ids.split(",").length}})}else if(entities.push({entityName:entityName,value:{count:"SR_BULKUPDATE_ALLROWS"}}),"contact"===entityName){var havePerson=!1;if(1===SuperOffice.Selection.SelectionType){ids=SuperOffice.SoHelper.getElementBySoId("SelectionUnique2");(isShadow||void 0!==ids&&(ids.checked||ids.disabled))&&(havePerson=!0)}else if(isShadow)havePerson=0<(all=archiveControl.getRowsByLinkHint("person")).length;else for(var all=archiveControl.getAllRows(),i=0;i<all.length&&!havePerson;i++)"person"===SuperOffice.SoHelper.getNavFromLinkHint(all[i].LinkHint)&&(havePerson=!0);havePerson&&entities.push({entityName:"person",value:{count:"SR_BULKUPDATE_ALLROWS"}})}$sodlgm.open(null,{id:"BulkUpdate",recipeName:"BulkUpdateDialog",caption:"[SR_BULKUPDATE_BULKUPDATE]"},function(ctx){onlyOnSelectedMembers?ctx.set("rowCount",rows.length):(ctx.set("selectionId",SuperOffice.Selection.Current.SelectionId),ctx.set("rowCount",archiveControl.getCount()),ctx.set("isShadow",isShadow)),ctx.set("entityIds",entities),console.log(ctx),ctx.set("archiveControl",archiveControl)},function(ctx){ctx.get("archiveControl").RefreshList()},"bulkupdate")}};return pub})(),void 0===SuperOffice.Controls&&(SuperOffice.Controls={}),void 0===SuperOffice.Controls.SoArchiveControl&&(SuperOffice.Controls.SoArchiveControl={}),SuperOffice.Controls.SoArchiveControl.DefaultRenderer=function(archiveControl){var pub={},_archiveControl=archiveControl,DataSourceName="SuperOffice.CRM.Web.UI.Controls.SoArchiveControl.GetArchiveList";return pub.initialize=function(){""!=_archiveControl._archiveControlContext.CurrentName&&PageEventHandler.addCustomEvent(_archiveControl._archiveControlContext.CurrentName,_archiveControl._id,_archiveControl.GetClientControlId()+".SetCurrentSelected();")},pub.ReceiveList=function(res){debug.trace("ReceiveList Start","ArchiveControl");var elem=_archiveControl.getDataContainer();null!=elem&&(res=new ArchiveResultParser(res)).getResponseInstanceId()==_archiveControl._archiveControlContext.ClientInstanceID&&(_archiveControl._currentPage=res.getPageNumber(),_archiveControl._hasMorePages=res.getHasMorePages(),_archiveControl.setCount(res.getCount()),_archiveControl._archiveControlContext.CurrentValue=res.getCurrentValues(),console.log("New Current Values: "+res.getCurrentValues(),"ArchiveControl"),res=_archiveControl.createAlignTable(res.getDataGrid()),$(elem).find("table").remove(),null!=res?(elem.appendChild(res),null==_archiveControl.tableRowParser?(_archiveControl.createTableRowParser(),_archiveControl.SetCurrentSelected(),_archiveControl._archiveControlContext.KeepSelected&&(console.log("ReceiveList KeepSelected","ArchiveControl"),_archiveControl.setSelectedRowsByString(SuperOffice.Archives.StateManager.get(_archiveControl._id)))):(_archiveControl.updateTableRowParser(),_archiveControl.SetCurrentSelected())):_archiveControl.updateTableRowParser(),null!=_archiveControl.tableRowParser&&0<_archiveControl._selectedIds.length?(console.log("ReceiveList setSelectedItemsAsString: "+_archiveControl._selectedIds.join(";"),"ArchiveControl"),_archiveControl.tableRowParser.setSelectedItemsAsString(_archiveControl._selectedIds.join(";")),setTimeout(_archiveControl.GetClientControlId()+".scrollToSelected()",1e3),_archiveControl.FireOnRowSelect()):null!=_archiveControl.tableRowParser&&0<_archiveControl.getSelectedRows().length&&_archiveControl.FireOnRowSelect(),_archiveControl.ShowEmptyListLink(),setTimeout(_archiveControl.GetClientControlId()+".onScroll()",10),setTimeout(_archiveControl.GetClientControlId()+".FireOnListReceived()",20),debug.trace("ReceiveList End","ArchiveControl"))},pub.getSelectedRows=function(){var selectedRows=new Array;if(null!=_archiveControl.tableRowParser){var items=_archiveControl.tableRowParser.getTableRowState().getSelectedItems(),dataTable=_archiveControl.getDataTable();if(void 0!==dataTable&&null!=dataTable)for(var i=0;i<items.getLength();i++){var rowId=items.getByIdx(i);null!=(rowId=dataTable.rows.namedItem(rowId))&&(1<rowId.length?selectedRows.push(rowId[0]):selectedRows.push(rowId))}}return selectedRows},pub.SetCurrentSelected=function(){debug.trace("SetCurrentSelected","ArchiveControl");var selId=0,curNames=_archiveControl._archiveControlContext.CurrentName.split(","),curValues=_archiveControl._archiveControlContext.CurrentValue.split(",");if(1!=_archiveControl._archiveControlContext.IndexType&&""!=_archiveControl._archiveControlContext.CurrentName)for(var i=0;i<curNames.length&&(selId=eval("typeof(g_"+curNames[i]+"_current)!='undefined'?g_"+curNames[i]+"_current:0"),0==selId);i++);if(0==selId)for(var i=0;i<curValues.length;i++)if("0"!=curValues[i]){selId=curValues[i];break}if(1==_archiveControl._archiveControlContext.IndexType&&null!=_archiveControl.tableRowParser)for(var foundRow=!1,items=_archiveControl.tableRowParser.getAllRows(),i=0;i<items.length;i++){for(var ii=0;ii<curNames.length;ii++){var item=$(items[i]);if(""!=curNames[ii]){var val=SuperOffice.SoHelper.getValueFromLinkHint(item.attr("id"),curNames[ii]);if(""!=val&&Number(val)===Number(curValues[ii])){selId=item.attr("id"),foundRow=!0;break}}}if(foundRow)break}""==selId||_archiveControl.isSelected(selId)?PageEventHandler.removeCustomEvent(_archiveControl._archiveControlContext.CurrentName,_archiveControl._id):(_archiveControl.SetSelectedById(selId),_archiveControl._localSort||setTimeout(_archiveControl.GetClientControlId()+".scrollToSelected()",50))},pub},SuperOffice=SuperOffice||{__namespace:!0},SuperOffice.Archives||(SuperOffice.Archives={__namespace:!0}),SuperOffice.Archives.StateManager=Object.create(Object.prototype),SuperOffice.Archives.StateManager.__class=!0,SuperOffice.Archives.StateManager.State={},SuperOffice.Archives.StateManager.add=function(id,state){this.State[id]=state},SuperOffice.Archives.StateManager.get=function(id){return so_defined(this.State[id])?this.State[id]:""},_this=ArchiveControl.prototype,_this.preInit=function(id,archiveControlContext){try{this._id=id,this._archiveControlContext=archiveControlContext,this._currentPos=0,this._currentObj=null,this._newDiff=0,this._leftCellNewWidth=0,this._rightCellNewWidth=0,this._dragDiv=null,this._ignoreLoad=!1,this._currentPage=0,this._hasMorePages="true",this._entityCollection=new SoCollection,this._archiveConfiguration=this._archiveControlContext.ArchiveConfiguration,this._restrictions=this._archiveControlContext.ArchiveRestrictionInfo,this._currentOrderByElem=null,this._selectedIds=new Array,this._disableEmptyListLink=!1,this._clientOnRowSelect=new Array,this._waitCount=0,this._fetchListReturnFunction=null,this._fetchListTimeoutFunction=null,this._fetchInProgress=!1,this._timeoutInProgress=!1,this._orgOrderByInfo=this.copyOrderByInfo(this._archiveConfiguration.ArchiveOrderByInfo),null!=this._orgOrderByInfo&&0<this._orgOrderByInfo.length&&this.setOrderByStyle(this._orgOrderByInfo[0].Name),this._instance="g_archive"+id,this._archiveControlContext.ClientInstanceID="uniqueInstanceId_"+(65536*(1+Math.random())|0).toString(16).substring(1),eval(this._instance+"=this;");var dc=this.getDataContainer(),that=(null!=dc&&JsHelper.DisableSelectTextOnTarget(this.getDataContainer()),""!=this._archiveControlContext.CurrentName&&PageEventHandler.addCustomEvent(this._archiveControlContext.CurrentName,id,this.GetClientControlId()+".SetCurrentSelected();"),this);PageEventHandler.addEvent(EventType.ONPAGELOAD,this._instance+"ResizeArchiveColumnsLoad",function(){that.alignColumns(null),that.sizeChanged=!0}),PageEventHandler.addEvent(EventType.ONPAGERESIZE,this._instance+"ResizeArchiveColumnsPage",function(){SuperOffice.Throttle.run(that._instance+"ONPAGERESIZETHROTTLE",200,function(){that.alignColumns(null),that.sizeChanged=!0})}),PageEventHandler.addEvent(EventType.ONVIEWCHANGE,this._instance+"ResizeArchiveColumnsPage2",function(){that.alignColumns(null,!0)}),PageEventHandler.addEvent(EventType.ONAFTERSPLITTERRESIZE,this._instance+"ResizeArchiveColumnsSplitter",function(){SuperOffice.Throttle.run(that._instance+"ONAFTERSPLITTERRESIZETHROTTLE",50,function(){that.alignColumns(null),that.sizeChanged=!0})}),PageEventHandler.addEvent(EventType.ONTABCLICKED,this._instance+"tabchange2",function(){that.scrollToSelected()}),PageEventHandler.addEvent(EventType.ONCACHELOAD,this._instance+"cacheload",function(){that._archiveControlContext.LocalRenderer&&(that.customRenderer=new SuperOffice.Controls.SoArchiveControl.LocalRenderer(that)),that.SetCurrentSelected(),that.scrollToSelected()}),KeyPressHandler.AddKeyPressListenerByKeyCode(35,ModifyKey.CTRL,this._instance+".OnPageEnd();"),this.initalize(),(new InstanceManager).RegisterDisposable(this.getDataContainer(),this)}catch(e){Dialog.Information("[SR_ERROR_CAPTION]",e.message)}},_this.initalize=function(){var tmpDataContainer;0==this._archiveControlContext.Static&&this._archiveControlContext.AutoFetch?(this._archiveControlContext.ShowHeader&&this._archiveControlContext.HasDynamicFilter&&this.ToggleFilter(),debug.trace("Adding AutoFetch events ("+this._id+")","ArchiveControl"),PageEventHandler.addEvent(EventType.ONVIEWCHANGE,this._id+"AutoFetchArchive",this.GetClientControlId()+".delayFetchList();"),PageEventHandler.addEvent(EventType.ONPAGELOAD,this._id+"AutoFetchArchivePageLoad",this.GetClientControlId()+".FetchList();")):(debug.trace("Static list("+this._id+")","ArchiveControl"),this.createTableRowParser(),this._archiveControlContext.KeepSelected&&this.setSelectedRowsByString(SuperOffice.Archives.StateManager.get(this._id)),this.initData(),this.alignColumns(),null==this._archiveControlContext.ProviderName||""==this._archiveControlContext.ProviderName||this.tableRowParser.count()<this._archiveControlContext.PageSize?(this._hasMorePages="false",this.ShowEmptyListLink()):setTimeout(this.GetClientControlId()+".onScroll()",20),null!=(tmpDataContainer=this.getDataContainer())&&(tmpDataContainer.scrollTop=0,setTimeout(this.GetClientControlId()+".FireOnListReceived()",20)))},_this.GetArchiveControlContextCopy=function(){return JSON.parse(JSON.stringify(this._archiveControlContext))},_this.GetClientControlId=function(){return this._archiveControlContext.ClientControlID},_this.GetHeaderTableId=function(){return this._archiveControlContext.ClientHeaderTableID},_this.GetDataContainerId=function(){return this._archiveControlContext.ClientDataContainerID},_this.ContextMenu=function(e,elementId,context,subcontext,id,position){var linkHint="",entity="",rows=this.getSelectedRows(),mixedEntities=(0<rows.length&&(linkHint=rows[0].attributes.rowtype.value+"&ArchiveControlId="+this._instance,entity=rows[0].attributes.rowEntityName.value),!1),lastEntity=entity;if(1<rows.length)for(var t=1;t<rows.length;++t){var ent=rows[t].attributes.rowEntityName.value;if(ent!=lastEntity){debug.trace("We got a mix!","ArchiveControl"),mixedEntities=!0;break}lastEntity=ent}MenuManager.menuPosition[elementId]=position;position=null,position=void 0===e?JsHelper.GetMouseCoordinates(event):JsHelper.GetMouseCoordinates(e);MenuManager.cursorCoordinates[elementId]=position,AjaxMethodDispatcher.CallASync("MenuManager.menuCallBack","","",elementId,AjaxMethod.GetOverriddenArchiveContextMenu,linkHint,entity,2<=rows.length,mixedEntities,this._archiveControlContext.RowMenuContext,SuperOffice.Environment.SoProtocol)},_this.FireOnRowActionComplete=function(retVal){this.OnRowActionComplete&&null!==this.OnRowActionComplete&&(this.OnRowActionComplete(retVal),this.OnRowActionComplete=null)},_this.FireOnListReceived=function(){null!=this.OnListReceived&&this.OnListReceived(this.tableRowParser),0==this.getSelectedRows().length&&this.FireOnNoRowSelect()},_this.Dispose=function(){null!=this.tableRowParser&&(this.tableRowParser.Dispose(),this.tableRowParser=null),""!=this._archiveControlContext.CurrentName&&PageEventHandler.removeCustomEvent(this._archiveControlContext.CurrentName,this._id),PageEventHandler.removeEvent(EventType.ONPAGELOAD,this._instance+"ResizeArchiveColumnsLoad"),PageEventHandler.removeEvent(EventType.ONPAGERESIZE,this._instance+"ResizeArchiveColumnsPage"),PageEventHandler.removeEvent(EventType.ONAFTERSPLITTERRESIZE,this._instance+"ResizeArchiveColumnsSplitter"),KeyPressHandler.RemoveKeyPressListenerByKeyCode(35,ModifyKey.CTRL,this._instance+".OnPageEnd();"),null!=this._archiveControlContext.ToggleFunction&&KeyPressHandler.RemoveKeyPressListener("T",ModifyKey.CTRL,this._instance+".OnToggle();")},_this.addUsageStats=function(type){try{var that=this;"click"===type?SuperOffice.StickyThrottle.run("archiveusagestatscript",400,function(){"undefined"!=typeof UsageStats&&UsageStats.AddArchiveClick(that._archiveControlContext.ClientControlID)}):SuperOffice.StickyThrottle.run("archiveusagestatscript",10,function(){"undefined"!=typeof UsageStats&&UsageStats.AddArchiveDoubleClick(that._archiveControlContext.ClientControlID)})}catch(ex){}},_this.IsVisible=function(){var elem=document.getElementById(this.GetDataContainerId());return UIHelper.IsElementVisible(elem)},_this.RowAction=function(archiveAction,id){1!=this.RowActionInProgress&&this.SetSelectedById(id),this.RowsAction(archiveAction)},_this.RowActionNoSelect=function(archiveAction,id){id=this.getDataTable().rows.namedItem(id);this.RowsAction(archiveAction,id)},_this.RowsAction=function(archiveAction,actionRows){if(1!=this.RowActionInProgress){this.RowActionInProgress=!0,this.ShowProgressImage(),"undefined"==typeof pageNumber&&(pageNumber=0);for(var rows=null,argumentRowIds=(null==actionRows?rows=this.getSelectedRows():null!=actionRows.length?rows=actionRows:(rows=new Array).push(actionRows),new Array),argumentIds=new Array,argumentLinkHints=new Array,i=0;i<rows.length;i++)null!=rows[i]&&(argumentRowIds.push(rows[i].id),argumentIds.push(rows[i].attributes.rowEntityName.value+"_id="+GetPrimaryKeyFromRow(rows[i])),argumentLinkHints.push(rows[i].attributes.rowtype.value));var that=this;UIHelper.GetMainPageWindow().$clientapi.post("SoArchiveControl/RowActionLinkHint",{id:this._id,orderBy:this._orderBy,page:pageNumber,ArchiveControlContext:this.GetArchiveControlContextCopy(),actionName:archiveAction,entityIds:argumentIds.join(","),rowLinkHints:argumentLinkHints.join(","),rowIds:argumentRowIds.join(",")},null,!0).then(function(res){that.updateRows(res)}).catch(function(err){that.onRowActionError(err)})}},_this.onRowsActionError=function(res){this.RowActionInProgress=!1,this.HideProgressImage(),void 0!==res&&console.error("RowAction Error",res)},_this.updateRows=function(res){document.getElementById(this.GetDataContainerId());var res=new ArchiveResultParser(res),returnedRows=new Array,dataTable=this.getDataTable(),tmpLayer=document.createElement("div");tmpLayer.innerHTML=res.getDataGrid();var newPageTable=tmpLayer.getElementsByTagName("TABLE")[0];if(null!=newPageTable)for(var i=0;i<newPageTable.rows.length;i++){returnedRows.push(newPageTable.rows[i].attributes.id.value);var rowEntityName,entityId,oldrow=dataTable.rows.namedItem(newPageTable.rows[i].attributes.id.value);if(null!==(oldrow=null==oldrow&&(rowEntityName=newPageTable.rows[i].attributes.rowEntityName.value,entityId=SuperOffice.SoHelper.getValueFromLinkHint(newPageTable.rows[i].attributes.rowtype.value,rowEntityName),0<(rows=this.getRowsByLinkHint(rowEntityName+"_id="+entityId)).length)?rows[0]:oldrow)){oldrow.attributes.rowtype.value=newPageTable.rows[i].attributes.rowtype.value,oldrow.attributes.id.value=newPageTable.rows[i].attributes.id.value;for(var t=0;t<oldrow.cells.length;t++)oldrow.cells[t].innerHTML=newPageTable.rows[i].cells[t].innerHTML}}var selectedRows=null,inputRowIds=res.getInputRowIds();if(null!=inputRowIds)for(var rows=this.getDataTable().rows,selectedRows=new Array,idx=0;idx<inputRowIds.length;idx++){var row=rows.namedItem(inputRowIds[idx]);null!=row&&selectedRows.push(row)}else selectedRows=this.getSelectedRows();for(var tt=0;tt<selectedRows.length;tt++){for(var remove=!0,selectedValue=selectedRows[tt].attributes.id.value,ttt=0;ttt<returnedRows.length;ttt++)if(returnedRows[ttt]==selectedValue){remove=!1;break}remove&&dataTable.deleteRow(selectedRows[tt].rowIndex)}this.alignColumns(),this.HideProgressImage(),this.FireOnRowActionComplete(res._extraReturn),this.RowActionInProgress=!1,this._fetchInProgress=!1},_this.copyOrderByInfo=function(orderByInfo){if(null==orderByInfo)return null;for(var tmpOrderByInfos=new Array,i=0;i<orderByInfo.length;i++){var tmp=SuperOffice.JsonUtil.ClassInstance.new("SuperOffice.CRM.ArchiveLists.ArchiveOrderByInfo, SOCore");tmp.Name=orderByInfo[i].Name,tmp.Direction=orderByInfo[i].Direction,tmpOrderByInfos.push(tmp)}return tmpOrderByInfos},_this.getHeaderColumnByColumnName=function(columnName){var headerTable=this.getHeaderTable();if(null!=headerTable)for(var tds=headerTable.getElementsByTagName("TD"),i=0;i<tds.length;i++)if(null!=tds[i].attributes.columnname&&tds[i].attributes.columnname.value==columnName)return tds[i];return null},_this.addOnScroll=function(){var scrollLayer=this.getDataContainer(),that=this;$(scrollLayer).on("scroll.soarchive",function(e){that.onScroll(e)})},_this.removeOnScroll=function(){var scrollLayer=this.getDataContainer();$(scrollLayer).off("scroll.soarchive")},_this.getHeaderTable=function(){return document.getElementById(this.GetHeaderTableId())},_this.getDataTable=function(){var elem=this.getDataContainer();return null!=elem?(0<(elem=elem.getElementsByTagName("table")).length?elem:$("#dataTable"))[0]:null},_this.getDataContainer=function(){return document.getElementById(this.GetDataContainerId())},_this.getArchiveElement=function(){var elem=this.getDataContainer();return null!=elem?elem.parentNode:null},_this.getTableCells=function(table,row){if(null!=table)return 0==(table=table.getElementsByTagName("TR")).length?null:table[row].getElementsByTagName("TD")},_this.getTableHeaderCells=function(table,row){var a;if(null!=table)return 0==(table=table.getElementsByTagName("TR")).length?null:(table=$(table[row]).find("td.ArchiveHeaderColumn"),a=new Array,table.each(function(i,e){a.push(e)}),a)},_this.ShowProgressImage=function(){var elem=$(this.getDataContainer()),elem=(null!=elem&&elem.setStyle({cursor:"progress"}),document.getElementById(this._archiveControlContext.ProgressImageID));null!=elem&&(elem.style.display="")},_this.HideProgressImage=function(){var elem=$(this.getDataContainer()),elem=(null!=elem&&elem.setStyle({cursor:""}),document.getElementById(this._archiveControlContext.ProgressImageID));null!=elem&&(elem.style.display="none")},_this.disposeElement=function(obj){null!=obj.parentNode&&obj.parentNode.removeChild(obj)},_this.createTableRowParser=function(){var dataTable=this.getDataTable();null!=dataTable?(this.tableRowParser=new TableRowParser(this.GetClientControlId()+".tableRowParser",dataTable.id),this.tableRowParser.setSelectedClassName("ArchiveSelectedRow"),this.tableRowParser.setPassiveClassName("ArchivePassiveRow"),this.tableRowParser.setIsMultiSelect(this._archiveControlContext.IsMultiSelect)):this.tableRowParser=new TableRowParser(this.GetClientControlId()+".tableRowParser",""),this._archiveControlContext.NoRowSelectedStyle&&this.tableRowParser.setSelectedClassName("")},_this.updateTableRowParser=function(){var keys;void 0!==this.tableRowParser&&(keys=this.getSelectedKeys(),this.tableRowParser.deSelectAll(),this.createTableRowParser(),debug.trace("updateTableRowParser with keys: "+keys.join(";"),"ArchiveControl"),this.tableRowParser.setSelectedItemsAsString(keys.join(";")),this.tableRowParser.setLastSelectedRow(),setTimeout(this.GetClientControlId()+".scrollToSelected()",50))},_this.alignColumns=function(tempElem){if(!this.IsVisible())return!1;this.lastWindowSize=$(this.getDataContainer()).width(),this.initData();try{var dataTable=null!=tempElem?tempElem:this.getDataTable();if(null==dataTable)return!1;var header=this.getHeaderTable();if(null==header||"false"==this._archiveControlContext.ShowHeader||0==this._archiveControlContext.ShowHeader)return!1;$(header).css({width:this.lastWindowSize+"px"}),$(dataTable).css({width:this.lastWindowSize+"px"});var originalOverflow=$(".DialogSimpleView").css("overflow"),headercells=(null!=originalOverflow&&($(".DialogSimpleView").css({overflow:"hidden"}),setTimeout(function(){$(".DialogSimpleView").css({overflow:originalOverflow})},250)),this.getTableCells(header,0)),datacells=this.getTableCells(dataTable,0);if(null==headercells||null==datacells)return!1;this.setHeaderWidth();for(var i=0;i<headercells.length;i++)$(datacells[i]).css({width:$(headercells[i]).width()+"px"});return dataTable}catch(e){console.error("alignColumns: "+e.message)}},_this.setHeaderWidth=function(headerTable,maxWidth){var tableCells;null!=headerTable&&headerTable.offsetWidth>maxWidth&&(tableCells=this.getTableCells(headerTable,0),headerTable=headerTable.offsetWidth-maxWidth,tableCells[tableCells.length-1].style.width=tableCells[tableCells.length-1].offsetWidth-headerTable+"px")},_this.dragColumn=function(e,obj){this.initHeader(),this.initData(),JsHelper.DisableSelectTextOnTarget(this.getHeaderTable()),JsHelper.DisableSelectTextOnTarget(this.getDataContainer());var that=this;$(document).on("mousemove.archive",function(e){JsHelper.DisableSelectTextOnTarget(that.getHeaderTable()),JsHelper.DisableSelectTextOnTarget(that.getDataContainer());var leftCellPosX=findPosX(that._currentObj.previousSibling),leftCellWidth=that._currentObj.previousSibling.offsetWidth,e=JsHelper.GetMouseCoordinates(e).getX(),leftCellPosX=(that._newDiff=leftCellPosX+leftCellWidth-e,that._currentObj.nextSibling.offsetWidth);that._leftCellNewWidth=leftCellWidth-that._newDiff,that._rightCellNewWidth=leftCellPosX+that._newDiff,that._dragDiv.style.left=e+"px"}),$(document).on("mouseup.archive",function(){JsHelper.EnableSelectTextOnTarget(that.getHeaderTable()),JsHelper.EnableSelectTextOnTarget(that.getDataContainer()),document.body.removeChild(that._dragDiv);var headerTable=that.getHeaderTable();that.setPixelWidth(headerTable);0<that._leftCellNewWidth&&0<that._rightCellNewWidth&&(that._currentObj.previousSibling.style.width=that._leftCellNewWidth+"px",that._currentObj.nextSibling.style.width=that._rightCellNewWidth+"px",that._currentObj.previousSibling.width=that._leftCellNewWidth+"px",that._currentObj.nextSibling.width=that._rightCellNewWidth+"px",that.resizeColumn(that._currentObj.previousSibling,that._leftCellNewWidth,that._currentObj.nextSibling,that._rightCellNewWidth),so_defined(that.onColumnReSize)&&that.onColumnReSize(),that.alignColumns()),$(document).off("mousemove.archive"),$(document).off("mouseup.archive"),that.SetColumnSizes()}),this._currentPos=JsHelper.GetMouseCoordinates(e).getX(),this._currentObj=obj,this._dragDiv=document.createElement("div"),this._dragDiv.style.height=this.getDataContainer().offsetHeight+this.getHeaderTable().offsetHeight+"px",this._dragDiv.style.width="1px",this._dragDiv.style.backgroundColor="black",this._dragDiv.style.position="absolute",this._dragDiv.style.left=this._currentPos+"px",this._dragDiv.style.top=findPosY(obj)+"px",this._dragDiv.style.zIndex="100",document.body.appendChild(this._dragDiv)},_this.resizeColumn=function(leftCell,leftWidth,rightCell,rightWidth){var dataTable=this.getDataTable();null!=dataTable&&((dataTable=this.getTableCells(dataTable,0))[leftCell.cellIndex].style.width=leftWidth+"px",dataTable[rightCell.cellIndex].style.width=rightWidth+"px")},_this.initHeader=function(){var widthFactor,headercells,seperatorwidth,header=this.getHeaderTable(),listelem=document.getElementById(this._archiveControlContext.ClientDataContainerID);null!=header&&(widthFactor=1,debug.trace("head:"+$(header).width()+"data:"+$(this.getDataContainer()).width()+"list?: "+listelem.offsetWidth,"initHeader"),seperatorwidth=10*((headercells=this.getTableCells(header,0)).length/2-1),$(header).width()>listelem.offsetWidth&&(widthFactor=(listelem.offsetWidth-seperatorwidth)/($(header).width()-seperatorwidth)),debug.trace("width factor:"+widthFactor,"initHeader"),this.initCellsWithComp(headercells,widthFactor),debug.trace("head:"+$(header).width()+"data:"+$(this.getDataContainer()).width(),"initHeader"))},_this.initCellsWithComp=function(cells,widthFactor){},_this.initData=function(){var widthFactor,datacells,seperatorwidth,dataTable=this.getDataTable(),listelem=document.getElementById(this._archiveControlContext.ClientDataContainerID);null!=dataTable&&(widthFactor=1,null!=(datacells=this.getTableCells(dataTable,seperatorwidth=0))&&(seperatorwidth=10*(datacells.length/2-1)),$(dataTable).width()>listelem.offsetWidth&&(widthFactor=(listelem.offsetWidth-seperatorwidth)/($(dataTable).width()-seperatorwidth)),this.initCellsWithComp(datacells,widthFactor))},_this.initCells=function(cells){if(null!=cells)for(var i=0;i<cells.length;i++)$(cells[i]).width(cells[i].offsetWidth)},_this.setPixelWidth=function(table){if(null==table)return null;for(var tds=this.getTableCells(table,0),orgPixels=new Array,i=0;i<tds.length;i++)orgPixels[i]=parseInt(tds[i].offsetWidth);for(var ii=0;ii<tds.length;ii++)tds[ii].style.width=orgPixels[ii]+"px";return orgPixels},_this.SetColumnSizes=function(){for(var tbl=this.getHeaderTable(),cells=this.getTableCells(tbl,0),output="",t=1;t<cells.length;t+=2)output+=cells[t].attributes.columnname.value+","+cells[t].offsetWidth,"percent"==cells[t].attributes.resizetype.value&&(output+="%"),output+=";";tbl=""==this._archiveControlContext.GuiName?this._id:this._archiveControlContext.GuiName;debug.trace(output,"SetColumnSizes"),UIHelper.GetMainPageWindow().$clientapi.post("SoArchiveControl/SetColumnWidths",{id:tbl,columnWidthInfos:output},null,!0)},_this.getGuiName=function(){return this._archiveControlContext.GuiName},_this.reCalcWidthPercentage=function(reftable,table){for(var tds=this.getTableCells(reftable,0),tds2=this.getTableCells(table,0),totalPercentPixels=0,orgPixels=new Array,i=tds.length-1;0<=i;i-=2)"percent"==tds[i].attributes.resizetype.value&&(totalPercentPixels+=parseInt(tds2[i].offsetWidth),orgPixels[i]=parseInt(tds2[i].offsetWidth),tds2[i].style.width="0%");for(var percent,i=tds.length-1;0<=i;i-=2)"percent"==tds[i].attributes.resizetype.value&&(percent=100*parseInt(orgPixels[i])/totalPercentPixels,debug.trace("Before! Pixels:"+tds2[i].offsetWidth+"Precent: "+parseInt(percent)+"%","reCalcWidthPercentage"),tds2[i].style.width=parseInt(percent)+"%",debug.trace("After! Pixels:"+tds2[i].offsetWidth+"Precent: "+parseInt(percent)+"%","reCalcWidthPercentage"));debug.trace(totalPercentPixels,"reCalcWidthPercentage")},_this.ExportToFile=function(customRestriction){var that,msg;this.getTotalRowCount()>this._archiveControlContext.ExportPageSize?(msg=(msg=ResourceUtils.GetResourceText("[SR_ARCHIVE_EXPORT_CONFIRMATION]")).replace("{0}",(that=this)._archiveControlContext.ExportPageSize),$sodlgm.confirm(SCIL.Router.createUIContext(),{caption:"Export to Excel",message:msg,height:256,ok:function(){that._exportToFile(customRestriction)}})):this._exportToFile(customRestriction)},_this._exportToFile=function(customRestriction){100<this.getTotalRowCount()&&(SuperOffice.Toast.show(ResourceUtils.GetResourceText("[SR_ARCHIVE_EXPORT_WAIT]"),SuperOffice.Toast.Wait),Dialog.disableWindow(window));var argumentIds=new Array;if(so_defined(customRestriction))argumentIds.push(customRestriction);else{var rows=this.getSelectedRows();if(1<rows.length)for(var i=0;i<rows.length;i++)null!=rows[i]&&argumentIds.push(rows[i].attributes.rowEntityName.value+"_id="+GetPrimaryKeyFromRow(rows[i]))}var customRestriction=g_ctrlDown,that=this;UIHelper.GetMainPageWindow().$clientapi.post("SoArchiveControl/ExportToFileROSS",{id:this._id,orderBy:this._orderBy,page:0,ArchiveControlContext:this.GetArchiveControlContextCopy(),additionalRestricitons:argumentIds.join(","),noHeading:customRestriction},null,!0).then(function(res){that.ExportToFileReturnFunction(res)}).catch(function(err){that.CallbackError(err)})},_this.ExportToFileReturnFunction=function(res){SuperOffice.Toast.close(),Dialog.enableWindow(window),location.href="filedownload?filetype=excelfile&id=0&filename="+res},_this.delayFetchList=function(){0<this._archiveControlContext.FetchTimeout?UIHelper.setTimeout(this.GetClientControlId(),this.GetClientControlId()+".FetchList()",this._archiveControlContext.FetchTimeout):this.FetchList()},_this.GetFullList=function(buttonSoId){this._archiveControlContext.LocalRenderer&&this.customRenderer.GetFullList(buttonSoId)},_this.FetchList=function(returnFunction,pageNumber,timeoutFunction){if(this._fetchInProgress=!0,this.customRenderer=null,void 0===pageNumber&&(pageNumber=0),void 0===returnFunction&&(returnFunction=this._instance+".ReceiveList"),this._fetchListReturnFunction=returnFunction,this._fetchListTimeoutFunction=void 0===timeoutFunction?null:timeoutFunction,!SuperOffice.FeatureToggle.SCILHostedArchives){if(!UIHelper.IsElementVisible(document.getElementById(this.GetDataContainerId())))return debug.trace("Not visible, waiting("+this._id+")","ArchiveControl"),this._waitCount++,void(this._waitCount<=50&&(this.delayHandler=setTimeout(this.GetClientControlId()+".FetchList('"+returnFunction+"',"+pageNumber+")",this._waitCount+100)));clearTimeout(this.delayHandler)}if(this._archiveControlContext.LocalRenderer)delete this.customRenderer,this.customRenderer=new SuperOffice.Controls.SoArchiveControl.LocalRenderer(this),this.customRenderer.GetFirstPage(),PageEventHandler.removeEvent(EventType.ONVIEWCHANGE,this._id+"AutoFetchArchive"),PageEventHandler.removeEvent(EventType.ONPAGELOAD,this._id+"AutoFetchArchivePageLoad");else{if(this._archiveControlContext.ShowHeader){var timeoutFunction=this.getHeaderTable(),cells=this.getTableHeaderCells(timeoutFunction,0);if(cells)for(var i=0,t=0;t<cells.length;t++)this._archiveControlContext.ArchiveConfiguration.ArchiveColumnInfo[i].Width=cells[t].offsetWidth+"px",i++}this._waitCount=0,this.ShowProgressImage(),debug.trace("Removing AutoFetch events ("+this._id+")","ArchiveControl"),PageEventHandler.removeEvent(EventType.ONVIEWCHANGE,this._id+"AutoFetchArchive"),PageEventHandler.removeEvent(EventType.ONPAGELOAD,this._id+"AutoFetchArchivePageLoad");var that=this;UIHelper.GetMainPageWindow().$clientapi.post(this.getArchiveListEndPointName(),{id:this._id,orderBy:this._orderBy,page:pageNumber,ArchiveControlContext:this._archiveControlContext},null,!0).then(function(res){that.FetchListReturnFunction(res),that.addOnScroll()}).catch(function(err){that.CallbackError(err)})}},_this.getArchiveListEndPointName=function(){return this._archiveControlContext.RequireSessionWrite?"SoArchiveControl/GetArchiveList":"SoArchiveControl/GetArchiveListROSS"},_this.FetchListReturnFunction=function(res){var script;this.HideProgressImage(),this._archiveControlContext.HasChangedEntities=!1,this._fetchInProgress=!1,null!=this._fetchListReturnFunction&&(script=this._fetchListReturnFunction+"(res);",eval(script))},_this.CallbackError=function(err){SuperOffice.Toast.close(),Dialog.enableWindow(window),this.HideProgressImage();var message="An error occurred";err&&(err.responseJSON&&""!==err.responseJSON.ExceptionMessage?message=(err.responseJSON.InnerException||err.responseJSON).ExceptionMessage:""!==err.message&&(message=err.message),Dialog.Information("[SR_ERROR_CAPTION]",message,"error"))},_this.TimeoutError=function(){SuperOffice.Toast.close(),Dialog.enableWindow(window);return 0==this._timeoutInProgress&&1==this._fetchInProgress&&(this._timeoutInProgress=!0,alert(ResourceUtils.GetResourceText("[SR_PROCESSING_REQUEST]")),this._timeoutInProgress=!1),!1},_this.DisableEmptyListLink=function(){this._disableEmptyListLink=!0},_this.EnableEmptyListLink=function(){this._disableEmptyListLink=!1},_this.HideEmptyListLink=function(){var elem=document.getElementById(this._archiveControlContext.ClientEmptyListLinkID);null!=elem&&(elem.style.display="none")},_this.ShowEmptyListLink=function(settings){var fullContainer,config={},settings=(settings&&$.extend(config,settings),document.getElementById(this._archiveControlContext.ClientEmptyListLinkID));return null!=this.tableRowParser&&0<this.tableRowParser.count()?null!=settings&&(settings.style.display="none"):this._disableEmptyListLink||this._archiveControlContext.ReadOnly||(fullContainer=document.getElementById(this._archiveControlContext.ClientDataContainerID),null!=settings&&(settings.style.display="",settings.style.width="100%",fullContainer=fullContainer.offsetWidth/2-settings.offsetWidth/2,settings.style.position="absolute",settings.style.top="50%",settings.style.left=fullContainer+"px",settings.style.textalign="center",fullContainer=$(".ArchiveControlEmptyListLink").text(),config.headingText&&$(".ArchiveControlEmptyListHeader").text(config.headingText),config.linkText!=fullContainer&&$(".ArchiveControlEmptyListLink").text(config.linkText),config.link&&($(".ArchiveControlEmptyListLink")[0].onclick="",$(".ArchiveControlEmptyListLink").off("click").on("click",config.link)),$(".ArchiveControlEmptyListLink").show())),!0},_this.createAlignTable=function(newPageTable){var tmp1=document.createElement("div"),newPageTable=(tmp1.innerHTML=newPageTable,tmp1.getElementsByTagName("table")[0]);return this._archiveControlContext.ShowHeader&&this.alignColumns(newPageTable),newPageTable},_this.ClearList=function(){var elem=this.getDataContainer();null!=elem&&(this.removeOnScroll(),$(elem).find("table").remove(),this.updateTableRowParser(),this.ShowEmptyListLink())},_this.setCount=function(count){debug.trace("count:"+count,"SoArchiveControl");var that,countLabel=$.fromSoId(this._id+"_Counter_PL"),countHyperLink=$.fromSoId(this._id+"_Counter_Hyperlink");-1<count?(countLabel.addClass("countlabel"),countLabel.html(this._archiveControlContext.RowCountCaption+count),countHyperLink.hide(),this.rowCount=count):(that=this,UIHelper.EnableToolButton(countHyperLink.get(0)),countHyperLink.on("click",function(){that._archiveControlContext.RowOptions="rowcount=true",that.RefreshList()}))},_this.getCount=function(){return this.rowCount},_this.ReceiveList=function(res){debug.trace("ReceiveList Start","ArchiveControl");var elem=this.getDataContainer();null!=elem&&(res=new ArchiveResultParser(res)).getResponseInstanceId()==this._archiveControlContext.ClientInstanceID&&(this._currentPage=res.getPageNumber(),this._hasMorePages=res.getHasMorePages(),this.setCount(res.getCount()),this._archiveControlContext.CurrentValue=res.getCurrentValues(),debug.trace("New Current Values: "+res.getCurrentValues(),"ArchiveControl"),res=this.createAlignTable(res.getDataGrid()),$(elem).find("table").remove(),null!=res?(elem.appendChild(res),null==this.tableRowParser?(this.createTableRowParser(),this.SetCurrentSelected(),this._archiveControlContext.KeepSelected&&(debug.trace("ReceiveList KeepSelected","ArchiveControl"),this.setSelectedRowsByString(SuperOffice.Archives.StateManager.get(this._id)))):(this.updateTableRowParser(),this.SetCurrentSelected())):this.updateTableRowParser(),null!=this.tableRowParser&&0<this._selectedIds.length?(debug.trace("ReceiveList setSelectedItemsAsString: "+this._selectedIds.join(";"),"ArchiveControl"),this.tableRowParser.setSelectedItemsAsString(this._selectedIds.join(";")),setTimeout(this.GetClientControlId()+".scrollToSelected()",1e3),this.FireOnRowSelect()):null!=this.tableRowParser&&0<this.getSelectedRows().length&&this.FireOnRowSelect(),this.ShowEmptyListLink(),setTimeout(this.GetClientControlId()+".onScroll()",10),setTimeout(this.GetClientControlId()+".FireOnListReceived()",20))},_this.Refresh=function(mode){var soprotocol=FindSoProtocol(this.GetDataContainerId());QueuedPageUpdate("soprotocol:"+soprotocol+"["+(null!=mode?"mode="+mode+"&":"")+"refresh=true]","")},_this.RefreshList=function(extraInfo){this._currentPage=0,this._archiveControlContext.ExtraInfo=extraInfo,this.FetchList(this._instance+".ReceiveRefreshedList")},_this.ReceiveRefreshedList=function(res){this.ReceiveList(res);res=new ArchiveResultParser(res);if(res.getResponseInstanceId()==this._archiveControlContext.ClientInstanceID)return this.setCount(res.getCount()),this._archiveControlContext.CurrentValue=res.getCurrentValues(),setTimeout(this.GetClientControlId()+".FireOnListReceived()",20),res.getExtraReturn()},_this.FetchFullList=function(){this._archiveControlContext.PageSize=1e5,this.FetchList()},_this.RowExists=function(rowId){var dataTable=this.getDataTable();return null!=dataTable&&null!=dataTable.rows.namedItem(rowId)},_this.scrollToSelected=function(){debug.trace("scrollToSelected","ArchiveControl");var dataContainer,rowOffsetTop,row=this.getSelectedRow();null!=row&&(dataContainer=this.getDataContainer(),(rowOffsetTop=row.offsetTop)>dataContainer.offsetHeight+dataContainer.scrollTop?dataContainer.scrollTop=rowOffsetTop-(dataContainer.offsetHeight-row.offsetHeight):row.offsetTop<dataContainer.scrollTop&&(dataContainer.scrollTop=rowOffsetTop))},_this.onScroll=function(e){0!=this.count()&&this.CheckForLoad(this.getDataContainer())},_this.OnKeyDown=function(){var tmpStr,tmpStr;this.tableRowParser.isActive()&&(tmpStr=this._archiveControlContext.ToggleFunction,tmpStr=tmpStr.format(this._instance+".getSelectedKeys()"),eval(tmpStr))},_this.OnPageEnd=function(){"true"==this._hasMorePages&&this.FetchFullList()},_this.FireOnDblClick=function(e){"IE"!=g_clientOptions.BrowserIdent&&(event=e);var row=this.getSelectedRow(),att;null!=row&&"undefined"!=row&&(att=row.attributes.ondblclick,null!=att)&&"undefined"!=att&&eval(att.value)},_this.OnDblClick=function(){this._rowSelected||eval(this._archiveControlContext.DblClick),this._rowSelected=!1},_this.OnToggle=function(){eval(this._archiveControlContext.ToggleFunction)},_this.CheckForLoad=function(obj){debug.trace("Check for load start","ArchiveControl"),this._checkForLoadObj=obj,setTimeout(this.GetClientControlId()+"._checkForLoad()",100)},_this._checkForLoad=function(){var jObj;null!=this._checkForLoadObj&&(jObj=$(this._checkForLoadObj),this.IsVisible())&&"true"==this._hasMorePages&&jObj[0].scrollTop+3>=jObj[0].scrollHeight-jObj[0].offsetHeight&&!this._ignoreLoad&&(this._curScrollTop=jObj[0].scrollTop,this._ignoreLoad=!0,this.FetchList(this._instance+".AddPage",parseInt(this._currentPage)+1),null!=this.OnListReceived)&&this.OnListReceived(this.tableRowParser)},_this.pagingDelay=function(){this._ignoreLoad=!1,null!=this.getDataContainer()&&(this.getDataContainer().scrollTop=this._curScrollTop)},_this.AddPage=function(html){var tmpLayer;null!=html&&(tmpLayer=document.createElement("div"),html=new ArchiveResultParser(html),this._currentPage=html.getPageNumber(),this._hasMorePages=html.getHasMorePages(),this._archiveControlContext.CurrentValue=html.getCurrentValues(),tmpLayer.innerHTML=html.getDataGrid(),null!=(html=tmpLayer.getElementsByTagName("TABLE")[0])&&(this.addNewPage(html),this.disposeElement(html),this.updateTableRowParser(),setTimeout(this.GetClientControlId()+".pagingDelay()",50)),setTimeout(this.GetClientControlId()+".onScroll()",10)),this.HideProgressImage()},_this.addNewPage=function(newPageTable){var dataTable=this.getDataTable();if(null!=dataTable)for(var tBody=dataTable.getElementsByTagName("TBODY");0<newPageTable.rows.length;)tBody[0].appendChild(newPageTable.rows[0])},_this.SetExtraInfo=function(extrainfo){this._archiveControlContext.ExtraInfo=extraInfo},_this.SetSelectedByLinkHint=function(linkhint){if(debug.trace("SetSelectedByLinkHint: "+linkhint,"ArchiveControl"),1!=this.RowActionInProgress)try{this.tableRowParser.setSelectedOnElementId(rowId),this.FireOnRowSelect()}catch(e){}},_this.SetSelectedById=function(rowId){if(debug.trace("SetSelectedById: "+rowId,"ArchiveControl"),1!=this.RowActionInProgress)try{this.tableRowParser.setSelectedOnElementId(rowId),setTimeout(this.GetClientControlId()+".scrollToSelected()",50),this.FireOnRowSelect()}catch(e){}},_this.setFirstRowSelected=function(){var items;debug.trace("Setting first row selected","ArchiveControl"),void 0!==this.tableRowParser&&0<(items=this.tableRowParser.getAllRows()).length&&($(items[0]).trigger("onmousedown"),$(items[0]).trigger("onclick"))},_this.SetSelected=function(e,rowObj){if(debug.trace("SetSelected: "+rowObj,"ArchiveControl"),1!=this.RowActionInProgress){if(this._rowSelected=!0,null!=e&&!Event.isLeftClick(e))for(var rows=this.getSelectedRows(),i=0;i<rows.length;i++)if(rows[i]==rowObj)return!1;return this.tableRowParser||this.createTableRowParser(),this.tableRowParser.setSelectedOnIndex(rowObj.rowIndex,e),this.FireOnRowSelect(),null==e||Event.isLeftClick(e)||$(rowObj).trigger("onclick"),this._archiveControlContext.KeepSelected&&SuperOffice.Archives.StateManager.add(this._id,this.getSelectedKeysByString()),setTimeout(this.GetClientControlId()+"._rowSelected=false;",500),!0}},_this.FireOnNoRowSelect=function(){if(void 0!==this.tableRowParser&&this.tableRowParser.deSelectAll(),null!=this._archiveControlContext.OnNoRowSelected)for(var key in this._archiveControlContext.OnNoRowSelected){var script;this._archiveControlContext.OnNoRowSelected.hasOwnProperty(key)&&!key.startsWith("$")&&(script=this._archiveControlContext.OnNoRowSelected[key],script+="('"+key+"',"+this._instance+")",eval(script))}},_this.AddOnRowSelect=function(id,script){this._clientOnRowSelect.push(script)},_this.FireOnRowSelect=function(){if(null!=this._archiveControlContext.OnRowSelected)for(var key in this._archiveControlContext.OnRowSelected){var script;this._archiveControlContext.OnRowSelected.hasOwnProperty(key)&&!key.startsWith("$")&&(script=this._archiveControlContext.OnRowSelected[key],script+="('"+key+"',"+this._instance+")",eval(script))}for(var i=0,dataright;i<this._clientOnRowSelect.length;i++){var script=this._clientOnRowSelect[i];script+="("+this._instance+")",eval(script)}if(null!=this._archiveControlContext.OnDataRight){for(var key in this._archiveControlContext.OnDataRight){this._archiveControlContext.OnDataRight.hasOwnProperty(key)&&!key.startsWith("$")&&(dataright=this._archiveControlContext.OnDataRight[key],"delete"===dataright)&&eval("canDelete('"+key+"',"+this._instance+")")}return!0}},_this.ShowSelected=function(){null!=this.tableRowParser&&alert(this.tableRowParser.getTableRowState().getSelectedItems().getLength())},_this.getSelectedKeysByString=function(){return null!=this.tableRowParser?this.tableRowParser.getSelectedItemsAsString():""},_this.getSelectedIdsByString=function(){return null!=this.tableRowParser?this.tableRowParser.getSelectedIds():""},_this.setSelectedRowsByString=function(items){debug.trace("setSelectedRowsByString: "+items,"ArchiveControl"),null!=this.tableRowParser&&this.tableRowParser.setSelectedItemsAsString(items)},_this.getSelectedKeys=function(){var keys=new Array;if(void 0!==this.tableRowParser)for(var selectedItems=this.tableRowParser.getTableRowState().getSelectedItems(),length=selectedItems.getLength(),i=0;i<length;i++)keys.push(selectedItems.getByIdx(i));return keys},_this.getSelectedKey=function(){new Array;var selectedItems=this.tableRowParser.getTableRowState().getSelectedItems();return 0<selectedItems.getLength()?selectedItems.getByIdx(0):null},_this.getRowsByLinkHint=function(regex){var rows=new Array,re=new RegExp(regex,"i");if(null!=this.tableRowParser)for(var items=this.tableRowParser.getAllRows(),t=0;t<items.length;++t)re.test(items[t].attributes.rowtype.value)&&rows.push(items[t]);return rows},_this.getRowsByPrimaryKey=function(key){var rows=new Array;if(null!=this.tableRowParser)for(var items=this.tableRowParser.getAllRows(),t=0;t<items.length;++t)items[t].attributes.primarykey.value==key&&rows.push(items[t]);return rows},_this.getSelectedRow=function(){if(null!=this.tableRowParser){var items=this.tableRowParser.getTableRowState().getSelectedItems(),dataTable=this.getDataTable();if(null==dataTable)return null;if(0<items.getLength())return items=items.getByIdx(0),dataTable.rows.namedItem(items)}return null},_this.getSelectedRows=function(){var selectedRows=new Array;if(null!=this.tableRowParser){var items=this.tableRowParser.getTableRowState().getSelectedItems(),dataTable=this.getDataTable();if(void 0!==dataTable&&null!=dataTable)for(var i=0;i<items.getLength();i++){var rowId=items.getByIdx(i);null!=(rowId=dataTable.rows.namedItem(rowId))&&(1<rowId.length?selectedRows.push(rowId[0]):selectedRows.push(rowId))}}return selectedRows},_this.removeRowByIndex=function(index){this.getDataTable().deleteRow(index),this.onScroll()},_this.removeSelectedRows=function(){if(null!=this.tableRowParser){for(var items=this.tableRowParser.getTableRowState().getSelectedItems(),dataTable=this.getDataTable(),i=items.getLength()-1;0<=i;i--){var rowId=items.getByIdx(i),rowId=dataTable.rows.namedItem(rowId);dataTable.deleteRow(rowId.rowIndex)}this.tableRowParser.deSelectAll(),this.FireOnRowSelect(),this.onScroll()}},_this.selectAll=function(){var items;null!=this.tableRowParser&&(items=this.tableRowParser.getItemsAsString(),this.tableRowParser.setSelectedItemsAsString(items),this.FireOnRowSelect())},_this.getTotalRowCount=function(){return-1},_this.count=function(){return null==this.tableRowParser?0:this.tableRowParser.count()},_this.deSelectAll=function(){this.tableRowParser.deSelectAll(),this.FireOnRowSelect()},_this.SetCurrentSelected=function(){debug.trace("SetCurrentSelected","ArchiveControl");var selId=0,curNames=this._archiveControlContext.CurrentName.split(","),curValues=this._archiveControlContext.CurrentValue.split(",");if(1!=this._archiveControlContext.IndexType&&""!=this._archiveControlContext.CurrentName)for(var i=0;i<curNames.length&&(selId=eval("typeof(g_"+curNames[i]+"_current)!='undefined'?g_"+curNames[i]+"_current:0"),0==selId);i++);if(0==selId)for(var i=0;i<curValues.length;i++)if("0"!=curValues[i]){selId=curValues[i];break}if(1==this._archiveControlContext.IndexType&&null!=this.tableRowParser)for(var foundRow=!1,items=this.tableRowParser.getAllRows(),i=0;i<items.length;i++){for(var ii=0;ii<curNames.length;ii++){var item=$(items[i]);if(""!=curNames[ii]){var val=SuperOffice.SoHelper.getValueFromLinkHint(item.attr("id"),curNames[ii]);if(""!=val&&Number(val)===Number(curValues[ii])){selId=item.attr("id"),foundRow=!0;break}}}if(foundRow)break}""==selId||this.isSelected(selId)?PageEventHandler.removeCustomEvent(this._archiveControlContext.CurrentName,this._id):(this.SetSelectedById(selId),setTimeout(this.GetClientControlId()+".scrollToSelected()",50))},_this.isSelected=function(id){for(var keys=this.getSelectedKeys(),i=0;i<keys.length;i++)if(keys[i]==id)return!0;return!1},_this.OrgOrderBy=function(){this._archiveConfiguration.ArchiveOrderByInfo=this.copyOrderByInfo(this._orgOrderByInfo),this._currentPage=0,this._hasMorePages="true",this.FetchList(),null!=this._orgOrderByInfo&&0<this._orgOrderByInfo.length&&this.setOrderByStyle(this._orgOrderByInfo[0].Name)},_this.getOrderBy=function(){return this._archiveConfiguration.ArchiveOrderByInfo},_this.setOrderByStyle=function(orderBy){null!=this._currentOrderByElem&&(this._currentOrderByElem.style.fontWeight="",this._currentOrderByElem.style.color="");orderBy=this.getHeaderColumnByColumnName(orderBy);null!=orderBy&&(orderBy.style.fontWeight="bold",orderBy.style.color="black"),this._currentOrderByElem=orderBy},_this.SortList=function(orderBy){this._sortList(orderBy)},_this._setOrderByInfo=function(orderBy){1<this._archiveConfiguration.ArchiveOrderByInfo.length&&this._archiveConfiguration.ArchiveOrderByInfo.splice(1,this._archiveConfiguration.ArchiveOrderByInfo.length-1);var currentOrderBy=this._archiveConfiguration.ArchiveOrderByInfo[0];null==currentOrderBy&&(currentOrderBy=SuperOffice.JsonUtil.ClassInstance.new("SuperOffice.CRM.ArchiveLists.ArchiveOrderByInfo, SOCore"),this._archiveConfiguration.ArchiveOrderByInfo.push(currentOrderBy)),orderBy==currentOrderBy.Name?0==currentOrderBy.Direction?currentOrderBy.Direction=1:currentOrderBy.Direction=0:(currentOrderBy.Name=orderBy,currentOrderBy.Direction=0)},_this._sortList=function(orderBy){!this._sortInProgress&&null!=this._archiveConfiguration.ArchiveOrderByInfo&&this.getArchiveColumnInfoByName(orderBy).CanOrderBy&&(this._sortInProgress=!0,this.setOrderByStyle(orderBy),this._setOrderByInfo(orderBy),this._currentPage=0,this._hasMorePages="true",setTimeout(this.GetClientControlId()+"._sortInProgress = false;",500),this.FetchList())},_this.getArchiveColumnInfoByName=function(name){for(var i=0;i<this._archiveControlContext.ArchiveConfiguration.ArchiveColumnInfo.length;i++)if(this._archiveControlContext.ArchiveConfiguration.ArchiveColumnInfo[i].Name==name)return this._archiveControlContext.ArchiveConfiguration.ArchiveColumnInfo[i];return null},_this.ToggleFilter=function(){var headerTable=this.getHeaderTable(),scrollLayer=this.getDataContainer();if(null==headerTable)return null;var trs=headerTable.getElementsByTagName("TR");if(1<trs.length)if("none"==trs[1].style.display)trs[1].style.display="",headerTable.parentNode.style.height="33px",scrollLayer.style.top="54px",this.setLockImg(),document.getElementById("ToggleLockFilter").style.display="",this._archiveControlContext.HasDynamicFilter=!0;else{for(var inputs=trs[1].getElementsByTagName("INPUT"),t=0;t<inputs.length;t++)UIHelper.IsElementVisible(inputs[t])&&(inputs[t].value="");trs[1].style.display="none",headerTable.parentNode.style.height="17px",scrollLayer.style.top="27px",document.getElementById("ToggleLockFilter").style.display="none";for(var i=0;i<this._archiveControlContext.DynamicFilterRestrictionInfo.length;i++)this._archiveControlContext.DynamicFilterRestrictionInfo[i].IsActive=!1;var that=this;UIHelper.GetMainPageWindow().$clientapi.post("SoArchiveControl/ClearDynamicFilter",{archiveControlContext:this.GetArchiveControlContextCopy()},null,!0).then(function(){that._archiveControlContext.HasDynamicFilter=!1,that.RefreshList()})}},_this.ToggleLockFilter=function(){var that=this;UIHelper.GetMainPageWindow().$clientapi.post("SoArchiveControl/ToggleDynamicFilterLock",{archiveControlContext:this.GetArchiveControlContextCopy()},null,!0).then(function(res){that._archiveControlContext.HasDynamicFilter=res,that.setLockImg()})},_this.setLockImg=function(){var span=document.getElementById("ToggleLockFilter").getElementsByTagName("span");0<span.length&&$(span).removeClass("Images-SmallIcon-LockFilter"),$(span).removeClass("Images-SmallIcon-LockedFilter"),this._archiveControlContext.HasDynamicFilter?$(span).addClass("Images-SmallIcon-LockedFilter"):$(span).addClass("Images-SmallIcon-LockFilter")},_this.ChangeSingleEntitySetting=function(elem){elem=elem.getSelectedType();this.SetSingleEntity(elem)},_this.ChangeEntitySetting=function(elem,entityName){if(this._archiveControlContext.HasChangedEntities)elem.checked=!elem.checked;else{for(var i=0;i<this._archiveConfiguration.ArchiveEntityInfo.length;i++)this._archiveConfiguration.ArchiveEntityInfo[i].Type==entityName&&(this._archiveConfiguration.ArchiveEntityInfo[i].Selected=elem.checked);this._archiveControlContext.HasChangedEntities=!0,this._currentPage=0,this.FetchList()}},_this.SetSingleEntity=function(entityName){for(var i=0;i<this._archiveConfiguration.ArchiveEntityInfo.length;i++)this._archiveConfiguration.ArchiveEntityInfo[i].Type==entityName?this._archiveConfiguration.ArchiveEntityInfo[i].Selected=!0:this._archiveConfiguration.ArchiveEntityInfo[i].Selected=!1;this._archiveControlContext.HasChangedEntities=!0,this._currentPage=0,this.FetchList()},_this.SetSingleFirstEntity=function(callback){UIHelper.GetMainPageWindow().$clientapi.post("SoArchiveControl/SetSingleFirstEntity",{id:this._id,archiveControlContext:this.GetArchiveControlContextCopy()},null,!0).then(function(){callback()})},_this.SetAllEntities=function(){for(var i=0;i<this._archiveConfiguration.ArchiveEntityInfo.length;i++)this._archiveConfiguration.ArchiveEntityInfo[i].Selected=!0;this._archiveControlContext.HasChangedEntities=!0,this._currentPage=0,this.FetchList()},_this.SetEntities=function(entities){for(var i=0;i<this._archiveConfiguration.ArchiveEntityInfo.length;i++){this._archiveConfiguration.ArchiveEntityInfo[i].Selected=!1;for(var ii=0;ii<entities.length;ii++)if(this._archiveConfiguration.ArchiveEntityInfo[i].Type==entities[ii]){this._archiveConfiguration.ArchiveEntityInfo[i].Selected=!0;break}}this._archiveControlContext.HasChangedEntities=!0,this._currentPage=0,this.FetchList()},_this.GetEntities=function(){return this._archiveConfiguration.ArchiveEntityInfo},_this.setArchiveColumnFilter=function(e,restrictionValue,restrictionName,restrictionType,defaultOperator,restrictionDisplayValue){var keypress=0,doRefresh=!1;if(13!=(keypress=e?e.keyCode||e.which:keypress)&&null!=e)return!0;var ari=null;"listAny"==restrictionType&&"0"==restrictionValue&&(restrictionValue="");for(var that,i=0;i<this._archiveControlContext.DynamicFilterRestrictionInfo.length;i++)this._archiveControlContext.DynamicFilterRestrictionInfo[i].Name==restrictionName&&(ari=this._archiveControlContext.DynamicFilterRestrictionInfo[i]);null==ari&&""!=restrictionValue&&((ari=SuperOffice.JsonUtil.ClassInstance.new("SuperOffice.CRM.ArchiveLists.ArchiveRestrictionInfo, SOCore")).Name=restrictionName,this._archiveControlContext.DynamicFilterRestrictionInfo[this._archiveControlContext.DynamicFilterRestrictionInfo.length]=ari),null!=ari&&(""==restrictionValue?(ari.IsActive&&(doRefresh=!0),ari.IsActive=!1,ari.DisplayValues=new Array,ari.Values=new Array):null!=ari.Values&&ari.Values[0]==restrictionValue&&0!=ari.IsActive||(ari.IsActive=!0,"int"==restrictionType?">"==restrictionValue[0]?(ari.Operator="greater",restrictionValue=restrictionValue.substring(1)):"<"==restrictionValue[0]?(ari.Operator="less",restrictionValue=restrictionValue.substring(1)):-1!=restrictionValue.indexOf(",")?(ari.Operator="in",restrictionValue=restrictionValue.split(",")):-1!=restrictionValue.indexOf("-")?(ari.Operator="between",restrictionValue=restrictionValue.split("-")):ari.Operator=defaultOperator:ari.Operator=defaultOperator,"string"==typeof restrictionValue?(ari.Values=[restrictionValue],ari.DisplayValues=[restrictionDisplayValue]):(ari.Values=restrictionValue,ari.DisplayValues=restrictionDisplayValue),doRefresh=!0)),doRefresh&&(this._archiveControlContext.HasDynamicFilter?(that=this,UIHelper.GetMainPageWindow().$clientapi.post("SoArchiveControl/SaveDynamicFilter",{archiveControlContext:this.GetArchiveControlContextCopy()},null,!0).then(function(){that.RefreshList()})):this.RefreshList())},_this=ArchiveResultParser.prototype,_this.getResponseInstanceId=function(){return this._responseInstanceId},_this.getCurrentValues=function(){return this._currentValues},_this.getCount=function(){return this._count},_this.getPageNumber=function(){return this._currentPage},_this.getHasMorePages=function(){return this._hasMorePages},_this.getExtraReturn=function(){return this._extraReturn},_this.getDataGrid=function(){return this._dataGrid},_this.getInputRowIds=function(){return this._inputRowIds};var g_ListContainerID="";function RefreshArchive(ListContainerID){g_ListContainerID=ListContainerID,setTimeout("FetchList()",200)}function ToggleAppointments(tmp){alert(tmp.length)}function KillMe(instance){}function DisableOnEmpty(id,archiveControl){0==archiveControl.getSelectedRows().length?SuperOffice.SoHelper.disableElementBySoId(id):SuperOffice.SoHelper.enableElementBySoId(id)}function JustDisableOnEmpty(id,archiveControl){0==archiveControl.getSelectedRows().length&&SuperOffice.SoHelper.disableElementBySoId(id)}function DisableOnNoRows(id,archiveControl){0==archiveControl.count()?SuperOffice.SoHelper.disableElementBySoId(id):SuperOffice.SoHelper.enableElementBySoId(id)}function canDelete(id,archiveControl){try{for(var rows=archiveControl.getSelectedRows(),can=!1,obj=SuperOffice.SoHelper.getElementBySoId(id),i=0;i<rows.length;i++){for(var row,rights=(row=rows[i]).attributes.rowrights.value.split(","),ii=0;ii<rights.length;ii++)if("D"==rights[ii]){can=!0,obj.title=row.attributes.rowrightsreason.value;break}if(!can)break}can?(UIHelper.EnableToolButton(obj),obj.title=""):UIHelper.DisableToolButton(obj)}catch(e){debug.error(e.message)}}function canRank(id,archiveControl){var archiveControl=archiveControl.getSelectedRows(),id=SuperOffice.SoHelper.getElementBySoId(id),can=!1;if(1==archiveControl.length){var archiveControl=archiveControl[0],rights=archiveControl.attributes.rowrights.value.split(",");id.title=archiveControl.attributes.rowrightsreason.value;for(var ii=0;ii<rights.length;ii++)if("D"==rights[ii]||"U"==rights[ii]){can=!0;break}}can?(UIHelper.EnableToolButton(id),id.title=""):UIHelper.DisableToolButton(id)}function DownloadDocument(docId){var res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.DownloadDocument","",docId);eval(res)}function DownloadDocumentFile(docId){var res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.DownloadDocumentFile","",docId);eval(res)}function OpenDocument(docId,archiveControlId,useSuperStateCopy){var useCopy=1==useSuperStateCopy,res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Document.OpenDocument","",docId,archiveControlId,useCopy);setTimeout(function(){eval(res)},50)}function OpenActivityDialog(value){var res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.ActivityArchive.OpenNewActivityDialog","",value?.useProjectCurrent??!1,value?.useSaleCurrent??!1);eval(res)}function RefreshFromDialog(ArchiveControl){ArchiveControl.RefreshList(),"contact"!==g_currentPageId&&"person"!==g_currentPageId||PageUpdate("soprotocol:?"+g_currentPageId+"_id="+g_clientOptions.LastValidHistoryItem,"")}function RefreshCurrentFromDialog(ArchiveControl,currentname){ArchiveControl.RefreshList(),RefreshCurrent(currentname)}function RefreshSelectedRows(ArchiveControl){ArchiveControl.RowsAction("UpdateRows")}function RefreshCurrentFromDocumentDialog(ArchiveControl){SCIL.Context.getContext("SuperStateWorker").sendCommand(ArchiveControl)}SuperOffice.Data.CultureDataFormatter=function(){var pub={parse:function(val){var start=val.indexOf("[I:"),end=val.indexOf("]");return-1!=start&&-1!=end?val.substring(start+3,end):val}};return pub},SuperOffice.Controls.Base=function(soid){var pub,elem=$.fromSoId(soid);return null==(pub=null!=elem?elem.data("instance"):pub)&&((pub=Object.create(Object.prototype)).soid=soid,elem.data("instance",pub)),pub},SuperOffice.Controls.SoArchiveGridView=function(_soid,_context,_archiveGridViewContext){var pub=new SuperOffice.Controls.Base(_soid),soid=_soid,context=_context,archiveGridViewContext=_archiveGridViewContext,elem=$.fromSoId(_soid),pageSize=50,fetchPageSize=200,altStyle="ArchiveRowStyle",headerHeight="34px",rowHeight="24px";return void 0!==_context?elem.data("context",_context):context=null!==elem.data("context")?elem.data("context"):null,void 0!==_archiveGridViewContext?elem.data("archiveGridViewContext",_archiveGridViewContext):archiveGridViewContext=null!==elem.data("archiveGridViewContext")?elem.data("archiveGridViewContext"):null,pub.init=function(){UIHelper.IsElementVisible(elem[0])&&this.initArchiveGridView(),this.setPageNo(0)},pub.initArchiveGridView=function(){var stickyContainer,that=this,stickyHeaderContainer=(0<archiveGridViewContext.StickyColumns&&(stickyHeaderContainer=this.getStickyHeaderContainer(),stickyHeaderTable=this.getStickyHeaderTable(),stickyHeaderContainer.append(stickyHeaderTable),stickythead=$("<thead/>"),stickyHeaderTable.append(stickythead),elem.append(stickyHeaderContainer),stickyContainer=this.getStickyContainer(),stickyHeaderTable=this.getStickyTable(),stickyContainer.append(stickyHeaderTable),stickytbody=$("<tbody/>"),stickyHeaderTable.append(stickytbody),elem.append(stickyContainer)),this.getHeaderContainer()),mainContainer=(elem.append(stickyHeaderContainer),this.getMainContainer()),stickyHeaderTable=(elem.append(mainContainer),this.getHeaderTable()),stickyHeaderContainer=(stickyHeaderContainer.append(stickyHeaderTable),thead=$("<thead/>"),stickyHeaderTable.append(thead),this.getMainTable());mainContainer.append(stickyHeaderContainer),tbody=$("<tbody/>"),stickyHeaderContainer.append(tbody),mainContainer.scroll(function(){that.scrollFunc(that,stickyContainer,mainContainer)}),_context.ShowHeader&&this.addHeaderRow(context.ArchiveConfiguration.ArchiveColumnInfo),this.getPage()},pub.scrollFunc=function(that,stickyContainer,mainContainer){0<archiveGridViewContext.StickyColumns&&$(stickyContainer).scrollTop(mainContainer.scrollTop()),that.getHeaderContainer().scrollLeft(mainContainer.scrollLeft()),that.getMorePages()&&mainContainer.scrollTop()>=mainContainer[0].scrollHeight-mainContainer[0].offsetHeight&&that.getPage()},pub.getContainer=function(id,className){var id=soid+"_"+id,container=$("#"+id);return 0==container.length&&(container=$("<div id='"+id+"'/>")).addClass(className),container},pub.getMainContainer=function(){var mainContainer=this.getContainer("mainContainer","ArchiveGridViewDataContainer");return mainContainer.addClass(archiveGridViewContext.CssClassBody),mainContainer},pub.getStickyContainer=function(){return this.getContainer("stickyContainer","ArchiveGridViewStickyDataContainer")},pub.getHeaderContainer=function(){var headerContainer=this.getContainer("headerContainer","ArchiveGridViewHeaderContainer");return headerContainer.addClass(archiveGridViewContext.CssClassHeader),headerContainer},pub.getStickyHeaderContainer=function(){return this.getContainer("stickyHeaderContainer","ArchiveGridViewStickyHeaderContainer")},pub.getTable=function(id,cssClass){var id=soid+"_"+id,table=$("#"+id);return 0==table.length&&(table=$("<table id='"+id+"' cellspacing='0' cellpadding='0' style='table-layout:auto'/>")).addClass(cssClass),table},pub.getHeaderTable=function(){return this.getTable("headerTable","SoArchiveGridView")},pub.getStickyHeaderTable=function(){return this.getTable("stickyHeaderTable")},pub.getMainTable=function(){return this.getTable("mainTable","SoArchiveGridView")},pub.getStickyTable=function(){return this.getTable("stickyTable")},pub.onClick=function(element,text){$(element).html(""),$(element).append(this.createDropDown(text)),this.recalcWidth(this.getMainTable(),this.getHeaderTable()),this.scrollFunc(this,this.getStickyContainer(),this.getMainContainer())},pub.recalcWidth=function(from,to){var fromRow=from[0].rows[0],toRow=to[0].rows[0];if(fromRow)for(var i=0;i<fromRow.cells.length;i++)toRow.cells[i].offsetWidth<fromRow.cells[i].offsetWidth?this.copyWidth(toRow.cells[i],fromRow.cells[i]):this.copyWidth(fromRow.cells[i],toRow.cells[i]);to.find("tr>th:last").css({width:"+="+g_scrollBarWidth}),0<archiveGridViewContext.StickyColumns&&(from=this.getStickyContainer(),this.getHeaderContainer().css({left:from.outerWidth()}),this.getMainContainer().css({left:from.outerWidth()}),this.getStickyHeaderTable().css({width:from.outerWidth()}))},pub.copyWidth=function(to,from){$(to).children().first().css({width:from.offsetWidth-12}),$(to).css({width:from.offsetWidth-12})},pub.setPageNo=function(i){elem.data("pageNo",i)},pub.getPageNo=function(){var retVal=elem.data("pageNo");return null==retVal?0:retVal},pub.clearResultSet=function(){elem.data("resultSet",null)},pub.setMorePages=function(hasmore){elem.data("hasmorepages",hasmore)},pub.getMorePages=function(){var retVal=elem.data("hasmorepages");return null==retVal||retVal},pub.setResultSet=function(realPage,result){var resultSet=elem.data("resultSet");(resultSet=null!=resultSet&&void 0!==resultSet?resultSet:[])[realPage]=result,elem.data("resultSet",resultSet)},pub.getResultSet=function(realPage){var resultSet=elem.data("resultSet");return null==resultSet||resultSet.length<=realPage?null:resultSet[realPage]},pub.getCursor=function(){return this.getPageNo()*pageSize%fetchPageSize},pub.getRealPage=function(){return Math.floor(this.getPageNo()*pageSize/fetchPageSize)},pub.refresh=function(){this.setPageNo(0),this.clearResultSet(),this.setMorePages(!0),this.getStickyTable().find(">tbody").children().remove(),this.getMainTable().find(">tbody").children().remove(),this.getMainContainer().scrollTop(0),this.getPage()},pub.getPage=function(){var realPage,that,resultSet;pub.addingPage||(pub.addingPage=!0,realPage=this.getRealPage(),pub.loadingElem=$("<div class='Spinner'></div>"),elem.append(pub.loadingElem),null===(resultSet=(that=this).getResultSet(realPage))?UIHelper.GetMainPageWindow().$clientapi.post("SoArchiveGridView/GetArchiveData",{context:context,page:realPage,pageSize:fetchPageSize},null,!0).then(function(res){that.getPageCallBack(res)}).catch(function(){}):(pub.loadingElem.remove(),this.addPage(resultSet)))},pub.getPageCallBack=function(res){pub.loadingElem.remove();var result=eval(res);this.setResultSet(this.getRealPage(),result),this.addPage(result)},pub.addPage=function(result){for(var mainContainer,stickyContainer,cursor=this.getCursor(),ii=cursor;ii<cursor+pageSize&&ii<result.length;ii++)ii%3==0&&(altStyle="ArchiveRowStyle"==altStyle?"ArchiveAlternatingRowStyle":"ArchiveRowStyle"),this.addRow(result[ii],altStyle);null!=result&&result.length<fetchPageSize&&result.length==ii?this.setMorePages(!1):this.setPageNo(this.getPageNo()+1),pub.addingPage=!1,this.recalcWidth(this.getMainTable(),this.getHeaderTable()),0<archiveGridViewContext.StickyColumns&&(mainContainer=this.getMainContainer(),stickyContainer=this.getStickyContainer(),mainContainer[0].scrollWidth>mainContainer.width()?stickyContainer.css({bottom:g_scrollBarWidth+"px"}):stickyContainer.css({bottom:"0px"}))},pub.createDropDown=function(displayText){var tmp=$("<div/>"),icon=(tmp.attr("title",displayText),$("<span class='SelectableDropDown'/>")),icon=(tmp.append(icon),$("<span>"+(""!=displayText?displayText:" ")+"</span>"));return tmp.append(icon),tmp},pub.addHeaderRow=function(rowObj){var row=$("<tr/>"),stickyrow;row.css({height:headerHeight}),row.data("row",rowObj),0<archiveGridViewContext.StickyColumns&&(stickyrow=$("<tr/>"),stickyrow.css({height:headerHeight}),$(stickythead).append(stickyrow));for(var i=0;i<rowObj.length;i++){var headerElem=$("<th/>"),dropDownContext,tmp;"dropdown"===rowObj[i].DisplayType?(headerElem.append(this.createDropDown(rowObj[i].DisplayName)),""!=context.HeaderContext&&(dropDownContext=eval("("+context.HeaderContext+")"),dropDownContext.soid=soid+row.children().length,headerElem.dropDown("init",dropDownContext))):(tmp=$("<div>"+(null!=rowObj[i]?rowObj[i].DisplayName:" ")+"</div>"),tmp.attr("title",rowObj[i].DisplayName),headerElem.append(tmp)),(i<archiveGridViewContext.StickyColumns?stickyrow:row).append(headerElem)}return row.append("<th/>"),$(thead).append(row),row},pub.onLinkHintClick=function(row){var onclickScr=archiveGridViewContext.LinkHints[$(this).data("item").LinkHint];new Function("row",onclickScr).call(this,$(row).data("row"))},pub.addRow=function(rowObj,rowClass){var stickyrow,that=this,row=$("<tr/>");row.css({height:rowHeight}),row.addClass(rowClass),$(tbody).append(row),0<archiveGridViewContext.StickyColumns&&((stickyrow=$("<tr/>")).css({height:rowHeight}),stickyrow.addClass(rowClass),$(stickytbody).append(stickyrow)),row.data("row",rowObj);for(var i=0;i<rowObj.ColumnData.length;i++){var retVal=$("<td></td>"),tdContainer=(retVal.data("item",rowObj.ColumnData[i]),$("<div/>"));switch(retVal.append(tdContainer),context.ArchiveConfiguration.ArchiveColumnInfo[i].DisplayType){case"bool":var chkElem=$("<input type='checkbox' "+("true"==rowObj.ColumnData[i].DisplayValue.toLowerCase()?"checked=checked":"")+"/>");chkElem.attr("name",context.ArchiveConfiguration.ArchiveColumnInfo[i].Name),chkElem.data("item",rowObj.ColumnData[i]),chkElem.on("click",function(){that.onLinkHintClick.call(this,row)}),tdContainer.append(chkElem);break;case"icon":for(var icons=rowObj.ColumnData[i].DisplayValue.split(","),tooltip=rowObj.ColumnData[i].TooltipHint.split(","),ii=0;ii<icons.length;ii++){var tmp,iconElem=$("<img/>");iconElem.css({width:"16px"}),iconElem.attr("src",rowObj.ColumnData[i].LinkHint+"/"+icons[ii].trim()+".png"),iconElem.data("item",rowObj.ColumnData[i]),tooltip.length>ii&&""!=(tmp=tooltip[ii].trim())&&(iconElem.bind("mouseover",{param:tmp},function(e){ToolTipManager.Show(e,"qwerty"+i,e.data.param,!0)}),iconElem.bind("mouseout",function(){ToolTipManager.Hide()})),tdContainer.css({width:16*icons.length+"px"}),tdContainer.append(iconElem)}break;default:tdContainer.text(null!=rowObj.ColumnData[i]?rowObj.ColumnData[i].DisplayValue:"")}(i<archiveGridViewContext.StickyColumns?stickyrow:row).append(retVal)}return row},pub},SuperOffice=SuperOffice||{__namespace:!0},SuperOffice.ArchiveMethods||(SuperOffice.ArchiveMethods={__namespace:!0}),SuperOffice.ArchiveMethods.Contact||(SuperOffice.ArchiveMethods.Contact={__namespace:!0}),SuperOffice.ArchiveMethods.Person||(SuperOffice.ArchiveMethods.Person={__namespace:!0});var initializeContact=function(ns){ns.saleArchiveClick=function(isStakeholderSale,saleId){if(isStakeholderSale){for(var protocolItems=SuperOffice.Environment.SoProtocolPageAndViewAndMiniCard.split("."),miniCardName="",i=0;i<protocolItems.length;i++)-1<protocolItems[i].indexOf("mini")&&(miniCardName=protocolItems[i]);isStakeholderSale="soprotocol:salearchive[refresh=false]."+miniCardName+"[refresh=true]";AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.SetSpecifiedCurrentOnly","","sale",saleId,"","");PageUpdate(isStakeholderSale,"")}else PageUpdate("soprotocol:salearchive[refresh=false]?sale_id="+saleId,"")}},initializePerson=(initializeContact(SuperOffice.ArchiveMethods.Contact),function(ns){ns.participantAppointmentArchiveClick=function(appointmentId){for(var protocolItems=SuperOffice.Environment.SoProtocolPageAndViewAndMiniCard.split("."),miniCardName="",i=0;i<protocolItems.length;i++)-1<protocolItems[i].indexOf("mini")&&(miniCardName=protocolItems[i]);var updateString="soprotocol:activityarchive[refresh=false]."+miniCardName+"[refresh=true]";AjaxMethodDispatcher.CallSync("SuperOffice.DCF.Web.AjaxMethods.SuperState.SetSpecifiedCurrentOnly","","appointment",appointmentId,"","");PageUpdate(updateString,"")}});function PersonToggleActivity(e,ArchiveControl,id){var nav,viewSoProtocol,numericId;(e=e||window.event).cancelBubble=!0,e.stopPropagation&&e.stopPropagation(),""!=id&&(nav=SuperOffice.SoHelper.getNavFromLinkHint(id),viewSoProtocol=FindSoProtocol(SuperOffice.SoHelper.getElementBySoId(ArchiveControl._id).id),viewSoProtocol+="[refresh=false]",""!=nav&&(numericId=Number(SuperOffice.SoHelper.getValueFromLinkHint(id,"appointment")),ArchiveControl.OnRowActionComplete=function(retVal){PersonToggleActivityComplete(numericId.toString(),viewSoProtocol,nav,retVal)}),ArchiveControl.RowAction("ToggleActivities",id))}function PersonToggleActivityComplete(id,soprotocol,nav,retVal){"participantAppointment"==nav?SuperOffice.ArchiveMethods.Person.participantAppointmentArchiveClick(Number(id)):QueuedPageUpdate("soprotocol:"+soprotocol+"?"+nav+"_id="+id)}function PersonToggleActivitiesByRowAction(ArchiveControl,rows){FindSoProtocol(SuperOffice.SoHelper.getElementBySoId(ArchiveControl._id).id);ArchiveControl.RowsAction("ToggleActivities")}function ToggleActivity(e,ArchiveControl,id){var nav,viewSoProtocol,numericId;(e=e||window.event).cancelBubble=!0,e.stopPropagation&&e.stopPropagation(),""!=id&&(nav=SuperOffice.SoHelper.getNavFromLinkHint(id),viewSoProtocol=FindSoProtocol(SuperOffice.SoHelper.getElementBySoId(ArchiveControl._id).id),viewSoProtocol+="[refresh=false]",""!=nav&&(numericId=Number(SuperOffice.SoHelper.getValueFromLinkHint(id,"appointment")),ArchiveControl.OnRowActionComplete=function(retVal){ToggleActivityComplete(numericId.toString(),viewSoProtocol,nav,retVal),OpenNextSuggestedAppointmentDialog(numericId.toString())}),ArchiveControl.RowAction("ToggleActivities",id))}function ToggleActivityComplete(id,soprotocol,nav,retVal){null!=retVal&&void 0!==retVal&&(2<(retVal=retVal.split("#")).length?Dialog.Information(ResourceUtils.GetResourceText(retVal[1]),ResourceUtils.GetResourceText(retVal[2])):2==retVal.length&&(OpenNextSuggestedAppointmentDialogWithoutCallback(Number(retVal[1])),SuperOffice.Guide.Project.SuggestMoveToNextStatus(Number(retVal[1]),"SuperOffice.Guide.Project.Refresh(true,false)"))),QueuedPageUpdate("soprotocol:"+soprotocol+"?"+nav+"_id="+id)}function ToggleActivitiesByRowAction(ArchiveControl,rows){FindSoProtocol(SuperOffice.SoHelper.getElementBySoId(ArchiveControl._id).id);1==rows.length&&(rows[0].attributes.primaryKey.value,rows=rows[0].attributes.rowEntityName.value),ArchiveControl.RowsAction("ToggleActivities")}function ToggleActivities(rows){for(var args=new Array,i=0;i<rows.length;i++)args.push(rows[i].attributes.rowEntityName.value+"_id="+rows[i].attributes.primaryKey.value);AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.ActivityArchive.ToggleActivities","",args.join(","))}function ToggleGuide(id,archiveControl,linkHint,entityname,callFunc){AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.ActivityArchive.ToggleActivity","",entityname+"_id="+id),archiveControl.RefreshList(),callFunc()}function ToggleProjectGuideActivity(archiveControl,linkHint,entityname){var id=SuperOffice.SoHelper.getValueFromLinkHint(linkHint,entityname);ToggleGuide(id,archiveControl,linkHint,entityname,function(){var numericId;"appointment"!=entityname&&"todo"!=entityname||(numericId=Number(id),SuperOffice.Guide.Project.SuggestMoveToNextStatus(numericId,"SuperOffice.Guide.Project.Refresh()"))})}function ToggleGuidedActivity(archiveControl,linkHint,entityname){var id=SuperOffice.SoHelper.getValueFromLinkHint(linkHint,entityname);ToggleGuide(id,archiveControl,linkHint,entityname,function(){var numericId;"appointment"!=entityname&&"todo"!=entityname||(numericId=Number(id),OpenNextSuggestedAppointmentDialog(numericId,""))})}function MovePerson(ArchiveControl,moveUp){var id=ArchiveControl.getSelectedKey(),swapId=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.ActivityArchive.ChangePersonRank","",Number(id),moveUp),orderBy=(ArchiveControl.setSelectedRowsByString(id+";"+swapId),ArchiveControl.getOrderBy());0==orderBy.length||1<orderBy.length||"rank"!=orderBy[0].Name?ArchiveControl.OnRowActionComplete=function(){ArchiveControl.SortList("rank"),ArchiveControl.RefreshList()}:ArchiveControl.OnRowActionComplete=function(){SwapRows(ArchiveControl,id,swapId,moveUp)},ArchiveControl.RowAction("UpdateRows","person_id="+id+",person_id="+swapId)}function SwapRows(ArchiveControl,id,swapId,moveUp){ArchiveControl.setSelectedRowsByString(id+";"+swapId);var swapId=ArchiveControl.getSelectedRows(),first=0,second=1,orderBy=ArchiveControl.getOrderBy();1<orderBy.length||"rank"!=orderBy[0].Name||swapId.length<2||null==swapId[1]||((moveUp=1==orderBy[0].Direction?!moveUp:moveUp)||(first=1,second=0),swapId[first].parentNode.insertBefore(swapId[first],swapId[second]),orderBy=swapId[0].attributes.defaultclass.value,swapId[0].attributes.defaultclass.value=swapId[1].attributes.defaultclass.value,swapId[1].attributes.defaultclass.value=orderBy,ArchiveControl.setSelectedRowsByString(id.toString()),ArchiveControl.alignColumns())}function SplitLinkHint(inStr){var equalIndex=inStr.indexOf("=");return inStr.substring(equalIndex+1)}function DeletePerson(ArchiveControl,rows){0<rows.length&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.ActivityArchive.DeletePerson","",rows.join(",")),ArchiveControl.Refresh())}function DeleteProjectMembers(ArchiveControl,rows){0<rows.length&&(AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.AjaxMethods.Project.RemoveProjectMembers","",rows.join(",")),ArchiveControl.Refresh())}function OnArchiveAppointmentMouseDown(e,contextObject,type){2!=e.button&&(debug.trace("rowmousedown, id="+contextObject.AppointmentId+", type="+type,"DDManager"),DDManager._mode=DragDropMode.MOVE,DDManager.InitDragDrop(e,contextObject))}function GetSelectedLinkHintValue(selectedRow,key){var id=0;return null!=selectedRow&&"undefined"!=selectedRow&&(selectedRow=selectedRow.attributes.rowtype.value,id=SuperOffice.Selection.getIdFromString(key+"=",selectedRow)),id}function GetSelectedLinkHintValues(selectedRows,key){if(0!=selectedRows.length){for(var linkHint,idArray=new Array,t=0;t<selectedRows.length;++t)linkHint=selectedRows[t].attributes.rowtype.value,0<(linkHint=SuperOffice.Selection.getIdFromString(key+"=",linkHint))&&idArray.push(linkHint);return idArray.join(",")}}function OpenMergeDialog(archiveControl,sourcePersonId,sourceContactId){var rows,targetPersonId=0;sourcePersonId=SuperOffice.SoHelper.getValueFromLinkHint(g_currentMainPageSoProtocol,"person"),sourceContactId=SuperOffice.SoHelper.getValueFromLinkHint(g_currentMainPageSoProtocol,"contact"),archiveControl&&(0<(rows=archiveControl.getSelectedRows()).length&&(sourcePersonId=GetSelectedLinkHintValue(rows[0],"person_id")),1<rows.length)&&(targetPersonId=GetSelectedLinkHintValue(rows[1],"person_id")),"string"==typeof sourceContactId&&(sourceContactId=parseInt(sourceContactId,10)),$sodlgm.open(null,{id:"MergeDialog",recipeName:"MergeDialog",caption:"[SR_MM_MENU_LIST_MERGE_CONTACTS]",windowSetting:{width:"600px",height:"570px"}},function(ctx){0<=sourceContactId&&!(0<sourcePersonId)&&ctx.set("sourceContactId",sourceContactId),0<=sourcePersonId&&(ctx.set("sourcePersonId",sourcePersonId),ctx.set("sourceContactId",0)),0<=targetPersonId&&(ctx.set("targetPersonId",targetPersonId),ctx.set("targetContactId",0))},function(ctx,dialogState){var sourceAction,targetPersonId;1===dialogState&&(dialogState=ctx.get("showContactPanelWhenDone"),sourceAction=ctx.get("actionOnSourceContact"),targetPersonId=ctx.get("targetPersonId"),dialogState&&targetPersonId?PageUpdate("soprotocol:person[refresh=true]?person_id="+targetPersonId,""):(dialogState=SuperOffice.Environment.SoProtocolPageAndView,targetPersonId=ctx.get("targetPersonId"),-1<dialogState.indexOf("contact")?SuperOffice.PageBuilder.setCurrent("person",0):-1<dialogState.indexOf("person")&&("deleteSourcePerson"===sourceAction?PageUpdate("soprotocol:person[refresh=true]?person_id="+targetPersonId,""):SuperOffice.PageBuilder.refreshCurrent("person")),archiveControl&&archiveControl.RefreshList()))},"mergepersons")}function OpenMoveDialog(archiveControl,personId,forceReload){var rows;if(!(0<(personId=!personId&&archiveControl&&0<(rows=archiveControl.getSelectedRows()).length?GetSelectedLinkHintValues(rows,"person_id"):personId)))throw new Error("TODO");$sodlgm.open(null,{id:"MoveDialog",recipeName:"MoveDialog",caption:"[SR_MM_MENU_LIST_MOVE_CONTACT]",windowSetting:{width:"500px",height:"570px"}},function(ctx){0<personId&&ctx.set("personId",personId)},function(ctx,dialogState){1===dialogState&&(ctx.get("showContactPanelWhenDone")?PageUpdate("soprotocol:person[refresh=true]?person_id="+personId,""):(-1<(dialogState=SuperOffice.Environment.SoProtocolPageAndView).indexOf("contact")?SuperOffice.PageBuilder.setCurrent("person",0):-1<dialogState.indexOf("person")&&PageUpdate("soprotocol:person[refresh=true]?person_id="+personId,""),archiveControl&&archiveControl.RefreshList()))},"moveperson")}function OpenMoveMergeDialog(dialogName,soprotocol,rows,callBack,entityname){var sourceId;0!=rows.length&&(sourceId=GetSelectedLinkHintValue(rows[0],entityname+"_id"),entityname=GetSelectedLinkHintValue(rows[1],entityname+"_id"),0<rows.length&&(soprotocol+=name+"[dialog=stop]?source_id="+sourceId),1<rows.length&&(soprotocol+="&destination_id="+entityname),entityname===sourceId&&0==sourceId?$sodlgm.info(SCIL.Router.createUIContext(),{caption:"[SR_INFO_CAPTION]",message:"[SR_SELECT_COMPANIES]",height:256}):Dialog.open(dialogName,soprotocol,callBack))}function OpenBulkUpdateDialogFromArchive(entity,selectedIds){$sodlgm.open(null,{id:"BulkUpdate",recipeName:"BulkUpdateDialog",caption:"[SR_BULKUPDATE_BULKUPDATE]"},function(ctx){ctx.set("currentEntity",entity),ctx.set("selectedIds",selectedIds),ctx.set("entityIds",{entity:selectedIds}),console.log(ctx)},function(){console.log("hello")},"bulkupdate")}function OpenBulkUpdateDialogFromArchiveControl(entity,archiveControl){$sodlgm.open(null,{id:"BulkUpdate",recipeName:"BulkUpdateDialog",caption:"[SR_BULKUPDATE_BULKUPDATE]"},function(ctx){var rows=archiveControl.getSelectedRows(),ids=GetSelectedLinkHintValues(rows,entity+"_id"),entities=[];entities.push({entityName:entity,value:{ids:ids,count:ids.split(",").length}}),"person"===entity&&0<rows.length&&(rows[0].attributes.rowentityname.value,void 0!==(ids=GetSelectedLinkHintValues(rows,"contact_id")))&&""!==ids&&entities.push({entityName:"contact",value:{ids:ids,count:ids.split(",").length}}),"contact"===entity&&0<rows.length&&(rows[0].attributes.rowentityname.value,void 0!==(ids=GetSelectedLinkHintValues(rows,"person_id")))&&""!==ids&&entities.push({entityName:"person",value:{ids:ids,count:ids.split(",").length}}),ctx.set("entityIds",entities),ctx.set("archiveControl",archiveControl),console.log(ctx)},function(ctx){ctx.get("archiveControl").RefreshList()},"bulkupdate")}function SoButtonSelect(button){button.value="true",PageBuilderHelper.CreateCallbackWithServerSideEvent(this)}initializePerson(SuperOffice.ArchiveMethods.Person),SuperOffice.SimpleMdoList=function(list){var pub={},simpleMdoList=list;return pub.getList=function(){return simpleMdoList},pub.getFromId=function(id){for(var i=0;i<simpleMdoList.length;i++)if(simpleMdoList[i].Id==id)return simpleMdoList[i];return null},pub.getFromIds=function(ids){for(var itemArray=[],i=0;i<ids.length;i++){var item=this.getFromId(ids[i]);null!=item&&itemArray.push(item)}return itemArray},pub.remove=function(id){simpleMdoList.splice(this.getIndexFromId(id),1)},pub.getIndexFromId=function(id){for(var i=0;i<simpleMdoList.length;i++)if(simpleMdoList[i].Id==id)return i;return-1},pub.toggleSelectedValue=function(id,selected){for(var i=0;i<simpleMdoList.length;i++)simpleMdoList[i].Id==id&&(simpleMdoList[i].Selected=selected)},pub.setSelectedValueForItems=function(selected){for(var i=0;i<simpleMdoList.length;i++)simpleMdoList[i].Selected=selected},pub.swap=function(id1,id2,swapRank){var id1=this.getIndexFromId(id1),id2=this.getIndexFromId(id2),temp=simpleMdoList[id1];simpleMdoList[id1]=simpleMdoList[id2],simpleMdoList[id2]=temp,void 0!==swapRank&&swapRank&&(temp=simpleMdoList[id2].Rank,simpleMdoList[id2].Rank=simpleMdoList[id1].Rank,simpleMdoList[id1].Rank=temp)},pub.getCheckedItems=function(){for(var itemArray=[],i=0;i<simpleMdoList.length;i++)simpleMdoList[i].Selected&&itemArray.push(simpleMdoList[i]);return itemArray},pub.getAllTypes=function(){for(var typeArray=[],i=0;i<simpleMdoList.length;i++)typeArray.push(simpleMdoList[i].Type);return typeArray},pub},void 0===SuperOffice.Controls&&(SuperOffice.Controls={}),SuperOffice.Controls.ListBoxBase=function(soid){var pub=Object.create(Object.prototype),stateElement=(pub.soid=soid,$.fromSoId(soid).parent().find("[type=hidden]").first());return pub.getStateElement=function(){return stateElement},pub.hasCache=function(prop){return void 0!==this.getStateElement()[0][prop]&&null!==this.getStateElement()[0][prop]},pub.setCache=function(prop,value){this.getStateElement()[0][prop]=value},pub.clearCache=function(prop){return this.getStateElement()[0][prop]=null},pub.getCache=function(prop){return this.getStateElement()[0][prop]},pub.init=function(){},pub},SuperOffice.SoCheckedListBox=function(soid,refSimpleMdoList){var pub=new SuperOffice.Controls.ListBoxBase(soid),simpleMdoList=SuperOffice.SimpleMdoList(null),listBox=$.fromSoId(soid),toolBar=listBox.parent().find(".ArchiveToolbar"),multiSelect=!1,useCache=!0,stateElement=pub.getStateElement();function setState(){useCache&&(pub.getStateElement().jsonStringify(simpleMdoList.getList()),pub.setCache("sostate_"+this.soid,simpleMdoList))}function swapGuiRankCellContents(row1,row2){var tempText,row1=row1.find("[rank]"),row2=row2.find("[rank]");0<row1.length&&(tempText=row1.text(),row1.text(row2.text()),row2.text(tempText))}function setToolbarButtonStates(){var disable,hasSelectedRows=!(0<listBox.find(".ArchiveSelectedRow").length);toolBar.find("[disableonempty=true]").each(function(){hasSelectedRows?SuperOffice.SoHelper.disableElementBySoId($(this).attr("soid")):SuperOffice.SoHelper.enableElementBySoId($(this).attr("soid"))}),hasSelectedRows||0<toolBar.find("[dataright=Delete]").length&&(disable=!1,listBox.find(".ArchiveSelectedRow").each(function(){-1==$(this).attr("rowrights").indexOf("D")&&(disable=!0)}),toolBar.find("[dataright=Delete]").each(function(){disable?SuperOffice.SoHelper.disableElementBySoId($(this).attr("soid")):SuperOffice.SoHelper.enableElementBySoId($(this).attr("soid"))}))}return 0<stateElement.length&&(void 0!==refSimpleMdoList?(simpleMdoList=refSimpleMdoList,useCache=!1):pub.hasCache("sostate_"+soid)?(simpleMdoList=pub.getCache("sostate_"+soid),multiSelect=pub.getCache("multiselect")):(null!=(refSimpleMdoList=JSON.parse(stateElement.val()))&&(multiSelect=refSimpleMdoList.MultiSelect,pub.setCache("multiselect",multiSelect),simpleMdoList=SuperOffice.SimpleMdoList(refSimpleMdoList.SimpleMdoItems),pub.setCache("sostate_"+soid,simpleMdoList)),setState()),pub.hasCache("lastClickIndex")||pub.setCache("lastClickIndex",-1)),pub.init=function(){var id=this.soid;$.fromSoId(this.soid).find(".sclbbody TABLE").on("resize",function(){SuperOffice.SoCheckedListBox(id).alignTables()}),setToolbarButtonStates()},pub.onclick=function(id){var selectedClass="ArchiveSelectedRow",indexClicked=this.getRowIndexFromId(id);if(multiSelect)if(g_ctrlDown)this.getRowFromId(id).toggleClass(selectedClass),this.setCache("lastClickIndex",indexClicked);else if(g_shiftDown){this.getRows().removeClass(selectedClass);for(var lastClickIndex=this.getCache("lastClickIndex"),rows=(-1===lastClickIndex&&this.setCache("lastClickIndex",lastClickIndex=indexClicked),this.getRows()),i=0;i<rows.length;i++)i>=Math.min(indexClicked,lastClickIndex)&&i<=Math.max(indexClicked,lastClickIndex)&&$(rows[i]).addClass(selectedClass)}else this.getRows().removeClass(selectedClass),this.getRowFromId(id).toggleClass(selectedClass),this.setCache("lastClickIndex",indexClicked);else this.getRows().removeClass(selectedClass),this.getRowFromId(id).addClass(selectedClass),this.setCache("lastClickIndex",indexClicked);setToolbarButtonStates()},pub.getRows=function(){return $.fromSoId(this.soid).find("[rowid]")},pub.getListBox=function(){return listBox},pub.getToolBar=function(){return toolBar},pub.getRowIndexFromId=function(id){return this.getRowFromId(id).prevAll().length},pub.getSimpleMdoItems=function(){return simpleMdoList.getList()},pub.getIdsFromHighlightedRows=function(){var ids=[],that=this;return listBox.find(".ArchiveSelectedRow").each(function(){ids.push(that.getIdFromRow($(this)))}),ids},pub.getTypesFromHighlightedRows=function(){var types=[];return listBox.find(".ArchiveSelectedRow").each(function(){types.push($(this).attr("rowtype"))}),types},pub.getRowIdFromRowType=function(rowType){return listBox.find("[rowtype='"+rowType+"']").first().attr("rowid")},pub.getRowFromId=function(id){return listBox.find("[rowid="+id+"]").first()},pub.getIdFromRow=function(row){return parseInt(row.attr("rowid"),10)},pub.getSimpleMdoItemsFromHighlightedRows=function(){return simpleMdoList.getFromIds(this.getIdsFromHighlightedRows())},pub.getSimpleMdoItem=function(id){return simpleMdoList.getFromId(id)},pub.getCheckedRows=function(){return simpleMdoList.getCheckedItems()},pub.getAllTypes=function(){return simpleMdoList.getAllTypes()},pub.toggleSelectedValue=function(elem){var isChecked=elem.is(":checked"),elem=elem.parent().attr("listid");simpleMdoList.toggleSelectedValue(elem,isChecked),setState()},pub.setAllSelectedValue=function(val){$("[soid="+this.soid+"] input:checkbox").prop("checked",val),simpleMdoList.setSelectedValueForItems(val),setState()},pub.highlightAll=function(){listBox.find("[rowid]").each(function(){$(this).addClass("ArchiveSelectedRow")}),setState(),setToolbarButtonStates()},pub.highlightNone=function(){listBox.find("[rowid]").each(function(){$(this).removeClass("ArchiveSelectedRow")})},pub.deleteHighlightedRows=function(){for(var ids=this.getIdsFromHighlightedRows(),i=0;i<ids.length;i++)simpleMdoList.remove(ids[i]);return listBox.find(".ArchiveSelectedRow").remove(),setState(),setToolbarButtonStates(),ids.length},pub.changeRank=function(moveUp,callback){var id,row;0<listBox.find(".ArchiveSelectedRow").length&&(row=listBox.find(".ArchiveSelectedRow").first(),id=this.getIdFromRow(row),moveUp?!(moveUp=row.prev()).hasClass("header")&&0<moveUp.length&&(swapGuiRankCellContents(row,moveUp),row.prev().before(row),moveUp=this.getIdFromRow(moveUp),simpleMdoList.swap(id,moveUp,!0)):0<(moveUp=row.next()).length&&(swapGuiRankCellContents(row,moveUp),moveUp.after(row),row=this.getIdFromRow(moveUp),simpleMdoList.swap(id,row,!0)),setState(),SuperOffice.Throttle.run(this.soid,1e3,callback))},pub.alignTables=function(){var headerTable=$.fromSoId(this.soid).find(".sclbheader TABLE"),bodyTable=$.fromSoId(this.soid).find(".sclbbody TABLE");headerTable.width()!==bodyTable.width()&&headerTable.width(bodyTable.width())},pub},SuperOffice.SoSelectableList=function(soid){var sostate,pub=new SuperOffice.Controls.ListBoxBase(soid),simpleMdoList=(pub.soid=soid,SuperOffice.SimpleMdoList(null)),stateElement=pub.getStateElement();function getTableTbodyElement(socheckedListBoxSoId){var tbody=$.fromSoId(socheckedListBoxSoId).find(".sclbbody TABLE TBODY");return 0==tbody.length&&($.fromSoId(socheckedListBoxSoId).find(".sclbbody TABLE").append("<tbody></tbody>"),tbody=$.fromSoId(socheckedListBoxSoId).find(".sclbbody TABLE TBODY")),tbody}return pub.hasCache("sostate_"+soid)?simpleMdoList=pub.getCache("sostate_"+soid):(sostate=JSON.parse(pub.getStateElement().val()),simpleMdoList=SuperOffice.SimpleMdoList(sostate.SimpleMdoItems),stateElement.jsonStringify(simpleMdoList.getList()),pub.setCache("sostate_"+soid,simpleMdoList),pub.setCache("instantsave",sostate.InstantSave)),pub.init=function(){},pub.getSimpleMdoList=function(){return simpleMdoList.getList()},pub.highlightAll=function(which){SuperOffice.SoCheckedListBox(this.soid+"_"+which).highlightAll()},pub.toggleSelected=function(id,fnCallback){simpleMdoList.getFromId(id).Selected?(rowRight=SuperOffice.SoCheckedListBox(soid+"_right").getRowFromId(id),tbodyLeft=getTableTbodyElement(soid+"_left"),rowRight.removeClass("ArchiveSelectedRow"),tbodyLeft.append(rowRight),rowRight.attr("onclick",rowRight.attr("onclick").replace(/_right/g,"_left")),simpleMdoList.toggleSelectedValue(id,!1)):(tbodyLeft=SuperOffice.SoCheckedListBox(soid+"_left").getRowFromId(id),rowRight=getTableTbodyElement(soid+"_right"),tbodyLeft.removeClass("ArchiveSelectedRow"),rowRight.append(tbodyLeft),tbodyLeft.attr("onclick",tbodyLeft.attr("onclick").replace(/_left/g,"_right")),simpleMdoList.toggleSelectedValue(id,!0)),stateElement.jsonStringify(simpleMdoList.getList()),pub.setCache("sostate_"+soid,simpleMdoList);var tbodyLeft,rowRight,that=this;void 0!==fnCallback&&SuperOffice.Throttle.run(that.soid,1e3,fnCallback),pub.getCache("instantsave")&&SuperOffice.Throttle.run(that.soid,1e3,function(){SuperOffice.PageBuilder.save(that.soid)})},pub.moveFromLeftToRight=function(fnCallback){for(var ids=SuperOffice.SoCheckedListBox(this.soid+"_left").getIdsFromHighlightedRows(),i=0;i<ids.length;i++)this.toggleSelected(ids[i],fnCallback)},pub.moveFromRightToLeft=function(fnCallback){for(var ids=SuperOffice.SoCheckedListBox(this.soid+"_right").getIdsFromHighlightedRows(),i=0;i<ids.length;i++)this.toggleSelected(ids[i],fnCallback)},pub},extendNs("SuperOffice.Controls",function(ns){var F=getNs("SuperOffice.Util").Functional,$=jQuery;ns.ClientState=function(clientStateSoId){function updateState(){var stateValue=_stateObject.Value;null!==stateValue&&(stateValue=JsonHelper.toJSON(stateValue),$.fromSoId(_clientStateSoId).val(stateValue))}var _clientStateSoId=clientStateSoId,_stateObject={Value:null};$(document).on("load",function(){var stateString=$.fromSoId(_clientStateSoId).val(),stateString=JSON.parse(stateString);_stateObject.Value=stateString});$("form",document).on("submit",updateState),PageUpdate=F.compose(1,[updateState,PageUpdate]),this.getClientStateObject=function(){return _stateObject}},ns.ClientState.__class=!0,ns.ClientState.setupClientStateFor=function(clientStateSoid){return new ns.ClientState(clientStateSoid).getClientStateObject()}});class PropertyReader{constructor(propertyClass){this._props=propertyClass}read(property,defaultValue){void 0===defaultValue&&(defaultValue=null);try{var obj=eval("this._props."+property);return void 0===obj?defaultValue:obj}catch(ex){return defaultValue}}readDateFromYYYYmmdd(property,defaultValue){var obj=eval("this._props."+property),date,month;return void 0!==obj&&8==obj.length?(date=new Date,month=parseInt(obj.substr(4,2)),--month,date.setFullYear(obj.substr(0,4),month,obj.substr(6,2)),date.clearTime(),date):defaultValue}}var PositionType={None:0,Left:1,Right:2,Top:3,Bottom:4},RangeFlags={None:0,Year:1,Month:2,Day:4};class SoDateRange{constructor(id,properties){this._inited=!1,this._id=id,this._elem=$("#"+id),this._properties=new PropertyReader(properties),this.setDates(),this._width=this._properties.read("Layout.PopUpWidth","200"),this._snap=this._properties.read("Snap",RangeFlags.None),this._valueLabel=$("#"+this._id+"_value"),this._autoExpand=this._properties.read("AutoExpand",!1),this._showExpandBeforeAfterButtons=!!this._autoExpand||this._properties.read("ShowExpandBeforeAfterButtons",!1),this._expandInterval=this._properties.read("ExpandInterval",2),this._showExpandContractButtons=this._properties.read("ShowExpandContractButtons",!1),this._showOkButton=this._properties.read("ShowOkButton",!1),this._showCancelButton=this._properties.read("ShowCancelButton",!1),this._canMoveRange=this._properties.read("CanMoveRange",!1),this._isRangeMove=!1,this._canMoveOtherSlider=this._properties.read("CanMoveOtherSlider",!1),this._heightNoOkButton=64,this._heightWithOkButton=90,this.createPopupContainer(),this.writeDate(this._fromPopupDateLabel,this._fromDate),this.writeDate(this._toPopupDateLabel,this._toDate),this._knobPos=new Object,this.setPosition(this._leftKnob,this.getPosition(this._fromDate,PositionType.Left)),this.setPosition(this._rightKnob,this.getPosition(this._toDate)),this.setActiveSliderPos(),eval("g_"+this._id+" = this;"),this._closeAnimFunctionName="g_"+this._id+".closeAnim()",this._addBeforeFunctionName="g_"+this._id+".addBefore()",this._addAfterFunctionName="g_"+this._id+".addAfter()",this.SelectedFromDate=this._fromDate,this.SelectedToDate=this._toDate}show(){this._initialFromDate=this._fromDate.clone(),this._initialToDate=this._toDate.clone(),this._elem=$("#"+this._id),this._popup.setHeight(this._height),this._popup.setWidth(this._width),PopUpManager.DisplayPopUp({PopUpElement:this._popup,PopUpClientId:"",TargetElement:this._elem,Alignment:"bottomleft",BorderColor:"#001E62",DropShadow:!0,Overflow:"hidden",Padding:null,BackgroundColor:"",CancelCallback:"g_"+this._id+".onCancel()"}),this.setActiveSliderPos(),this.initSlideKnobs()}setDates(){this._minDate=this._properties.readDateFromYYYYmmdd("MinDate",Date()).clearTime(),this._maxDate=this._properties.readDateFromYYYYmmdd("MaxDate",Date()).clearTime(),this._initialFromDate=this._properties.readDateFromYYYYmmdd("FromDate",Date()),this._initialToDate=this._properties.readDateFromYYYYmmdd("ToDate",Date()),this._fromDate=this._properties.readDateFromYYYYmmdd("FromDate",Date()),this._toDate=this._properties.readDateFromYYYYmmdd("ToDate",Date())}initSlideKnobs(){var that;this._inited||(that=this,$(this._leftKnob).mousedown(function(e){that.onLeftMouseDown(e)}),$(this._rightKnob).mousedown(function(e){that.onRightMouseDown(e)}),this._canMoveRange&&$(this._activeSlider).mousedown(function(e){that.onRangeMouseDown(e)}),this._inited=!0)}analyzeConstraints(){this._sliderWidth=this._slider.getWidth()-this._rightKnob.getWidth()-this._leftKnob.getWidth(),this._sliderStartPos=this._slider.getLeft()+this._leftKnob.getWidth(),this._milliSecondsRange=this._maxDate.getTime()-this._minDate.getTime(),this._msPerPixel=this._milliSecondsRange/this._sliderWidth,this._dayRange=this._milliSecondsRange/864e5,this._daysPerPixel=this._sliderWidth/this._dayRange}getPosition(date,position){void 0===position&&(position=PositionType.None);date=date.clone().clearTime().getTime()-this._minDate.getTime(),date=this._sliderStartPos+date/this._msPerPixel;return position===PositionType.Left&&(date-=this._leftKnob.getWidth()),date}setPosition(elem,pos){this._knobPos[elem.id]=pos,elem.setLeft(pos)}getDateFromKnob(elem,position){var pos=this._knobPos[elem.id],newDate=(pos-=this._sliderStartPos,this._minDate.clone());switch(position){case PositionType.Left:pos+=elem.getWidth();break;case PositionType.Right:}return newDate.addMilliseconds(pos*this._msPerPixel),newDate.addHours(1),newDate.clearTime()}writeDate(elem,date){date.getMonth();elem.html(date.toString(Date.CultureInfo.formatPatterns.shortDate))}setActiveSliderPos(){this._activeSlider.setLeft(this._leftKnob.getLeft()+this._leftKnob.getWidth()),this._activeSlider.setWidth(Math.max(0,this._rightKnob.getLeft()-this._leftKnob.getLeft()-this._rightKnob.getWidth()))}close(doCallback){doCallback&&this.doCallback(),PopUpManager.Hide()}closeAnim(){this._popup.setHeight(this._popup.getHeight()-4),this._popup.setWidth(this._popup.getWidth()-8),this._popup.getHeight()<5?this._popup.hide():setTimeout(this._closeAnimFunctionName,10)}onDocumentClicked(e){for(var node=Event.element(e);null!=node&&"FORM"!=node.tagName&&"BODY"!=node.tagName;){if(node.id==this._id+"_popupcontainer")return!1;node=node.parentNode}e.cancelBubble=!0,this.close(!0)}doCallback(){var attrib=this._elem[0].attributes.onrangeselected;void 0!==attrib&&null!=attrib&&eval(attrib.value)}onLeftMouseDown(e){new DragDrop(this,{DragDropStartMethod:this.onLeftDragStart,DragDropEndMethod:this.onLeftDragEnd,DragDropMoveMethod:this.onLeftDragMove,DragDropCancelMethod:this.onLeftCancelDrag,UseDragCursor:!1,DragElement:this._leftKnob},null).StartDrag(e)}onRightMouseDown(e){new DragDrop(this,{DragDropStartMethod:this.onRightDragStart,DragDropEndMethod:this.onRightDragEnd,DragDropMoveMethod:this.onRightDragMove,DragDropCancelMethod:this.onRightCancelDrag,UseDragCursor:!1,DragElement:this._rightKnob},null).StartDrag(e)}onLeftDragStart(data){this._fromDragDate=this._fromDate.clone(),this._leftKnobStartPos=this._leftKnob.getLeft(),this._leftKnobLastPos=this._leftKnobStartPos}onLeftDragEnd(data){this._fromDate=this._fromDragDate.clone(),this.onFromDateSelected()}onLeftDragMove(data){var newPos=this._leftKnobStartPos+data.getMouseDeltaX(),newPos=Math.max(newPos,this._slider.getLeft()),width=this._leftKnob.getWidth();if((newPos=1!=this._isRangeMove&&this._canMoveOtherSlider?Math.min(newPos,this._slider.getLeft()+this._slider.getWidth()-this._rightKnob.getWidth()-this._leftKnob.getWidth()):Math.min(newPos,this._rightKnob.getLeft()-width))!=this._leftKnobLastPos){if(this._snap&&RangeFlags.Year)for(var t=0;t<this._yearMarks.length;++t)Math.abs(this._yearMarks[t].Pos-newPos-width)<this._snapDelta&&(newPos=this.getPosition(this._yearMarks[t].Date,PositionType.Left));this.setPosition(this._leftKnob,newPos),this._leftKnobLastPos=newPos,this.onLeftKnobPosChanged(),newPos>this._knobPos[this._rightKnob[0].id]-width&&(this.setPosition(this._rightKnob,newPos+width),this.onRightKnobPosChanged()),this.setActiveSliderPos()}}onLeftCancelDrag(data){this.setPosition(this._leftKnob,this._leftKnobStartPos),this.setActiveSliderPos(),this.writeDate(this._fromPopupDateLabel,this._fromDate)}onRightDragStart(data){this._toDragDate=this._toDate.clone(),this._rightKnobStartPos=this._rightKnob.getLeft(),this._rightKnobLastPos=this._rightKnobStartPos}onRightDragEnd(data){this._toDate=this._toDragDate.clone(),this.onToDateSelected()}onRightDragMove(data){var newPos=this._rightKnobStartPos+data.getMouseDeltaX(),newPos=1!=this._isRangeMove&&this._canMoveOtherSlider?Math.max(newPos,this._slider.getLeft()+this._leftKnob.getWidth()):Math.max(newPos,this._leftKnob.getLeft()+this._leftKnob.getWidth());if((newPos=Math.min(newPos,this._slider.getLeft()+this._slider.getWidth()-this._rightKnob.getWidth()))!=this._rightKnobLastPos){if(this._snap&&RangeFlags.Year)for(var t=0;t<this._yearMarks.length;++t)Math.abs(this._yearMarks[t].Pos-newPos)<this._snapDelta&&(newPos=this.getPosition(this._yearMarks[t].Date));this.setPosition(this._rightKnob,newPos),this._rightKnobLastPos=newPos,this.onRightKnobPosChanged(),newPos<this._knobPos[this._leftKnob[0].id]+this._leftKnob.getWidth()&&(this.setPosition(this._leftKnob,newPos-this._leftKnob.getWidth()),this.onLeftKnobPosChanged()),this.setActiveSliderPos()}}onRightCancelDrag(data){this.setPosition(this._rightKnob,this._rightKnobStartPos),this.setActiveSliderPos(),this.writeDate(this._toPopupDateLabel,this._toDate)}onRangeMouseDown(e){new DragDrop(this,{DragDropStartMethod:this.onRangeDragStart,DragDropEndMethod:this.onRangeDragEnd,DragDropMoveMethod:this.onRangeDragMove,DragDropCancelMethod:this.onRangeCancelDrag,UseDragCursor:!1,DragElement:this._activeSlider},null).StartDrag(e)}onRangeDragStart(data){this._isRangeMove=!0,this._lastMouseDeltaX=0,this._knobDiff=this._knobPos[this._rightKnob[0].id]-this._knobPos[this._leftKnob[0].id],this._rangeStartPos=this._activeSlider.getLeft(),this._rangeLastPos=this._rangeStartPos,this.onRightDragStart(),this.onLeftDragStart()}onRangeDragEnd(data){this._isRangeMove=!1,this.onLeftDragEnd(),this.onRightDragEnd(),this.onRangeSelected()}onRangeDragMove(data){var dx=data.getMouseDeltaX();dx>this._lastMouseDeltaX?(this.onRightDragMove(data),this.setPosition(this._leftKnob,this._knobPos[this._rightKnob[0].id]-this._knobDiff)):(this.onLeftDragMove(data),this.setPosition(this._rightKnob,this._knobPos[this._leftKnob[0].id]+this._knobDiff)),this._lastMouseDeltaX=dx}onRangeCancelDrag(data){this._isRangeMove=!1,this.setPosition(this._activeSlider,this._rangeStartPos),this.onLeftCancelDrag(data),this.onRightCancelDrag(data),this.setActiveSliderPos()}onLeftKnobPosChanged(){this._fromDragDate=this.getDateFromKnob(this._leftKnob,PositionType.Left),this.writeDate(this._fromPopupDateLabel,this._fromDragDate)}onRightKnobPosChanged(){this._toDragDate=this.getDateFromKnob(this._rightKnob),this.writeDate(this._toPopupDateLabel,this._toDragDate)}onFromDateSelected(){this.SelectedFromDate=this._fromDate.clone(),this.onRangeSelected()}onToDateSelected(){this.SelectedToDate=this._toDate.clone(),this.onRangeSelected()}onRangeSelected(){this._properties.read("UpdateCallerElement",!1)&&this.writeDate(this._valueLabel,this._fromDate),this._showOkButton||(this.doCallback(),this._properties.read("CloseAfterRangeSelected",!1)&&this.close(!0))}addAfter(){this.expandRange(this._expandInterval)}addBefore(){this.expandRange(-this._expandInterval)}onExpand(){this.expandRange(this._expandInterval),this.expandRange(-this._expandInterval)}onContract(){this.contractRange(this._expandInterval)}onOk(){this.close(!0)}onCancel(){debug.trace("onCancel","SoDateRange"),this._fromDate=this._initialFromDate.clone(),this._toDate=this._initialToDate.clone(),this.setPosition(this._leftKnob,this.getPosition(this._fromDate,PositionType.Left)),this.setPosition(this._rightKnob,this.getPosition(this._toDate)),this.writeDate(this._fromPopupDateLabel,this._fromDate),this.writeDate(this._toPopupDateLabel,this._toDate),this.close(!1)}expandRange(years){(0<years?this._maxDate:this._minDate).addYears(years),this.analyzeConstraints(),this.createMarkers(),this.setPosition(this._leftKnob,this.getPosition(this._fromDate,PositionType.Left)),this.setPosition(this._rightKnob,this.getPosition(this._toDate)),this.setActiveSliderPos()}contractRange(years){this._maxDate.addYears(-years),this._minDate.addYears(years),this._minDate>this._fromDate&&(this._minDate=this._fromDate.clone(),this._minDate.setMonth(0),this._minDate.setDate(1)),this._maxDate<this._toDate&&(this._maxDate=this._toDate.clone(),1<this._toDate.getDate())&&0<this._toDate.getMonth()&&(this._maxDate.addYears(1),this._maxDate.setMonth(0),this._maxDate.setDate(1)),this.analyzeConstraints(),this.createMarkers(),this.setPosition(this._leftKnob,this.getPosition(this._fromDate,PositionType.Left)),this.setPosition(this._rightKnob,this.getPosition(this._toDate)),this.setActiveSliderPos()}resetRange(){this._fromDate=this.__initialFromDate.clone(),this._toDate=this.__initialToDate.clone(),this.expandRange(0)}createPopupContainer(){var sliderLeft=10,popUp=$(document.createElement("div")),html=(popUp.attr("id",this._id+"_popupcontainer"),popUp.attr("class","daterangepopup"),""),that=(html=(html=(html=(html+="<span id='daterange_popupcontainer_dateFrom' class='drfrom'>?</span>")+"<span class='drdivider'> - </span>"+"<span id='daterange_popupcontainer_dateTo' class='drto'>?</span>")+"<div id='daterange_popupcontainer_slider' class='drslider'></div>"+"<div id='daterange_popupcontainer_slideractive' class='dractiveslider'></div>")+"<div id='daterange_popupcontainer_slideknob1' class='drknobleft'></div>"+"<div id='daterange_popupcontainer_slideknob2' class='drknobright'></div>",this._showExpandBeforeAfterButtons&&(html+="<div id='daterange_popupcontainer_addbefore' class='addbefore'></div><div id='daterange_popupcontainer_addafter' class='addafter'></div>",sliderLeft=20),this._showExpandContractButtons&&(html+="<div id='daterange_popupcontainer_contract' class='contract'></div><div id='daterange_popupcontainer_expand' class='expand'></div>"),(this._showOkButton||this._showCancelButton)&&(html+="<div class='daterangebuttoncontainer'>"),this._showOkButton&&(html+="<a href='#' id='daterange_popupcontainer_ok' class='okbutton'>"+g_clientOptions.OkTranslated+"</a>"),this._showCancelButton&&(html+="<a href='#' id='daterange_popupcontainer_cancel' class='cancelbutton'>"+g_clientOptions.CancelTranslated+"</a>"),(this._showOkButton||this._showCancelButton)&&(html+="</div>"),html=html.replace(/daterange_/g,this._id+"_"),popUp.html(html),$(document.forms[0]).append(popUp),this._popup=$("#"+this._id+"_popupcontainer"),this._slider=$("#"+this._id+"_popupcontainer_slider"),this._activeSlider=$("#"+this._id+"_popupcontainer_slideractive"),this._leftKnob=$("#"+this._id+"_popupcontainer_slideknob1"),this._rightKnob=$("#"+this._id+"_popupcontainer_slideknob2"),this._fromPopupDateLabel=$("#"+this._id+"_popupcontainer_dateFrom"),this._toPopupDateLabel=$("#"+this._id+"_popupcontainer_dateTo"),this);this._showExpandContractButtons&&(this._expand=$("#"+this._id+"_popupcontainer_expand"),this._contract=$("#"+this._id+"_popupcontainer_contract"),$(this._expand).mousedown(function(){that.onExpand()}),$(this._contract).mousedown(function(){that.onContract()})),this._showCancelButton&&(this._cancelButton=$("#"+this._id+"_popupcontainer_cancel"),$(this._cancelButton).mousedown(function(){that.onCancel()})),this._showOkButton&&(this._okButton=$("#"+this._id+"_popupcontainer_ok"),$(this._okButton).mousedown(function(){that.onOk()}),html=10,this._showCancelButton)&&(html+=this._cancelButton.getWidth()+8,this._okButton.setStyle({right:html})),this._popup.setWidth(this._width),this._height=this._showOkButton||this._showCancelButton?this._heightWithOkButton:this._heightNoOkButton,this._slider.setLeft(sliderLeft),this._slider.setWidth(this._width-2*this._slider.getLeft()),this.analyzeConstraints(),this._showExpandBeforeAfterButtons&&(this._addBefore=$("#"+this._id+"_popupcontainer_addbefore"),this._addAfter=$("#"+this._id+"_popupcontainer_addafter"),$(this._addBefore).mousedown(function(){that.addBefore()}),$(this._addAfter).mousedown(function(){that.addAfter()}),this._addBefore.setLeft(this._slider.getLeft()-12),this._addBefore.setTop(this._slider.getTop()-3),this._addAfter.setLeft(this._slider.getLeft()+this._slider.getWidth()+2),this._addAfter.setTop(this._slider.getTop()-3)),this.createMarkers(),JsHelper.DisableSelectTextOnTarget(popUp)}setPopupPosition(){var rect=UIHelper.getClientRectangle(),elemPos=Position.cumulativeOffset(this._elem),left=elemPos[0],elemPos=(left+this._width>rect[0]&&(left-=left+this._width-rect[0]+5),elemPos[1]);elemPos+this._height>rect[1]&&(elemPos-=elemPos+this._height-rect[1]),this._popup.setLeft(left),this._popup.setTop(elemPos)}createMarkers(){this._properties.read("Layout.Markers",RangeFlags.None)&&RangeFlags.Year&&this.createYearMarkers()}createYearMarkers(){void 0!==this._yearMarks&&this.removeYearMarkers();var pos,mark,d=this._minDate.clone(),top=(d.setDate(1),d.setMonth(0),this._slider.getTop()-4);for(this._yearMarks=new Array;d.getFullYear()<=this._maxDate.getFullYear();)d>=this._minDate&&((mark=$(document.createElement("div"))).addClass("yearmark"),mark.setTop(top),mark.setHeight(9),pos=this.getPosition(d),mark.setLeft(pos),$(this._popup).append(mark),this._yearMarks.push({Year:d.getFullYear(),Date:d.clone(),Pos:pos,Elem:mark,Label:null})),d.addYears(1);1<this._yearMarks.length&&(this._distanceYearMarks=Math.floor(this._yearMarks[1].Pos-this._yearMarks[0].Pos)),this._snapDelta=Math.min(5,Math.max(1,Math.floor(this._distanceYearMarks/2))),debug.trace("this._snapDelta: "+this._snapDelta,"daterange");for(var t=0;t<this._yearMarks.length;++t){var label=$(document.createElement("div")),labelWidth=(label.addClass("yearlabel"),label.setTop(top-13),label.setLeft(this._yearMarks[t].Pos-12),$(this._popup).append(label),label.getWidth());this._distanceYearMarks<12&&0<t&&(t+1)%2==0?label.html(""):labelWidth>this._distanceYearMarks?(labelWidth=this._yearMarks[t].Year+"",label.html(labelWidth.substr(2,2))):label.html(this._yearMarks[t].Year),this._yearMarks[t].Label=label}}removeYearMarkers(){for(var t=0;t<this._yearMarks.length;++t)this._yearMarks[t].Elem[0].remove(),this._yearMarks[t].Elem=null,this._yearMarks[t].Label[0].remove(!0),this._yearMarks[t].Label=null}}function SoListBox(listid,tableRowParser,id,selectedValueId,isClickedId,hasServerClick,isReadOnly,scrollPos,state,clickScripts,showIcons){this._tableRowParser=tableRowParser,this._listid=listid,this._id=id,this._selectedValue=document.getElementById(selectedValueId),this._isClicked=document.getElementById(isClickedId),this._hasServerClick=hasServerClick,this._isReadOnly=isReadOnly,this._clickScripts=clickScripts,this._scrollPos=scrollPos,this._state=state,this._showIcons=showIcons}function so_defined(obj){return void 0!==obj}function so(soid){return SuperOffice.SoHelper.getElementBySoId(soid)}function so_setEventTarget(target){""!=target&&(document.getElementById("__EVENTTARGET").value=target)}function so_setEventArgument(argument){var docArg;""!=argument&&(docArg=""==(docArg=document.getElementById("__EVENTARGUMENT").value)?argument:";"+argument,document.getElementById("__EVENTARGUMENT").value=docArg)}function _ToolTipContext(uId,id,txt,x,y,serverRequest,escapeHtml){this.Text=txt,this.Id=id,this.uId=uId,this.x=x,this.y=y,this.serverRequest=serverRequest,this.escapeHtml=escapeHtml}SuperOffice.Controls.Base=function(soid){var pub=Object.create(Object.prototype);return pub.soid=soid,pub},SuperOffice.Controls.SoDropDownControl=function(_soid,_context){var popup,pub=new SuperOffice.Controls.Base(_soid),soid=_soid,context={extraInfo:""},elem=($.extend(context,_context),$.fromSoId(_soid));return void 0!==_context?elem.data("context",_context):context=null!==elem.data("context")?elem.data("context"):null,pub.init=function(item){null!=item&&elem.data("selecteditem",item),elem.css({cursor:"pointer"}),elem.on("click",function(){SuperOffice.Controls.SoDropDownControl(soid).getList()}),$("#"+soid+"Icon").on("click",function(){elem.trigger("click")})},pub.getList=function(){var that=this,res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.UI.Controls.SoDropDownControl.GetList","",context.listName,context.fetcher,context.extraInfo);popup=this.createPopupBox();for(var i=0;i<res.length;i++)this.addRow(res[i],0);popup.find(".SoDropDownItem").on("click",function(){that.setSelected($(this).data("item")),context.onClick.call(this,elem),that.unloadPopupBox()}),popup.find(".SoDropDownItem").mouseenter(function(){$(this).addClass("hover")}).mouseleave(function(){$(this).removeClass("hover")}),this.loadPopupBox(popup)},pub.setSelected=function(item){elem.data("selecteditem",item),elem.val(item.Name)},pub.addRow=function(rowObj,level){if(!rowObj.Deleted){var row=$("<div>"+rowObj.Name+"</div>");row.css({paddingLeft:6*level}),0<rowObj.ChildItems.length?(row.addClass("SoDropDownHeaderItem"),level++):row.addClass("SoDropDownItem"),rowObj.ToolTip&&row.attr("title",rowObj.ToolTip),rowObj.Type?row.attr("sotype",rowObj.Type):row.attr("soid",rowObj.Id),row.data("item",rowObj),$(popup).append(row);for(var i=0;i<rowObj.ChildItems.length;i++)this.addRow(rowObj.ChildItems[i],level)}},pub.createPopupBox=function(){var name="SoDropDownPopup"+soid,p=$("#"+name);return 0==p.length&&((p=$("<div id='"+name+"'/>")).addClass("SoDropDownPopup"),$("#container").append(p)),p},pub.unloadPopupBox=function(){$(popup).fadeOut("",function(){$(this).remove()})},pub.loadPopupBox=function(){var that=this,mainOffset=$.fromSoId(soid).offset(),height=$(document).height()-mainOffset.top-30,left=(popup.css({width:"+=17"}),mainOffset.left);mainOffset.left+popup.width()>$(window).width()&&(left=$(window).width()-(popup.width()+17)),popup.offset({top:mainOffset.top+16,left:left}),console.log("popup.height(): "+popup.height()),console.log("popup.top: "+popup.offset().top),popup.height()+popup.offset().top>height&&popup.height(height),popup.on("mousedown",function(e){return JsHelper.CancelBubble(e)}),$(popup).fadeIn(),$(document).on("mousedown.dropdownpopup",function(){that.unloadPopupBox(),$(document).off("mousedown.dropdownpopup")})},pub},($=>{var methods={init:function(options){this.attr("soid",options.soid),this.css({cursor:"pointer"}),this.on("click",function(){SuperOffice.Controls.SoDropDownControl(options.soid,options).getList()})}};$.fn.dropDown=function(method){return methods[method]?methods[method].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof method&&method?void $.error("Method "+method+" does not exist on jQuery.udefEditor"):methods.init.apply(this,arguments)}})(jQuery),SuperOffice.ErpSyncDefaults=(()=>{var pub={SetRadio:function(toLeft){$("[id*='SoErpSyncDefaults_"+(toLeft?"Left":"Right")+"']").each(function(key,value){value.checked=!0})}};return pub})(),SuperOffice.Controls.SoErpSyncMapping=function(_soid,_data,_headingCaptions,_actorId){var pub=new SuperOffice.Controls.Base(_soid),soid=_soid,elem=$.fromSoId(_soid),data,actorId=_actorId,headingCaptions=_headingCaptions;return void 0!==_data?(data=_data,elem.data("data",_data)):data=null!==elem.data("data")?elem.data("data"):null,pub.init=function(){var container=elem.parent(),container=$("<table class='ErpSyncMapping' cellpadding='0' cellspacing='0'/>").appendTo(container);this.renderHeaderRow(container),this.renderDataRows(container),this.actorId=actorId},pub.renderHeaderRow=function(table){for(var row=$("<tr/>").appendTo(table),i=0;i<headingCaptions.length;i++)this.addHeaderCaption($("<th/>").appendTo(row),headingCaptions[i])},pub.renderDataRows=function(table){for(var i=0;i<data.length;i++){var row=$("<tr/>").appendTo(table);this.addSearchCheckbox(i,$("<td/>").appendTo(row),data[i].ShowInSearch),this.addLabel(i,$("<td/>").appendTo(row),data[i].ErpDisplayName),this.addDirectionButton(i,$("<td/>").appendTo(row),data[i].SyncToErp,data[i].SyncToCrm),this.addDropDown(i,$("<td/>").appendTo(row),data[i].CrmDisplayName,data[i].ErpFieldId),this.addGuiCheckbox(i,$("<td/>").appendTo(row),data[i].ShowInGui)}for(var showInSearchCount=0,selectedIndex=0,ii=0;ii<data.length;ii++)data[ii].ShowInSearch&&(selectedIndex=ii,showInSearchCount++);1==showInSearchCount&&$("#showInSearch"+selectedIndex).attr("disabled","disabled")},pub.addHeaderCaption=function(container,text){container.append(text)},pub.addLabel=function(index,container,text){container.append("<span>"+text+"</span>")},pub.addDirectionButton=function(index,container,toLeft,toRight){var that,leftBtn=$("<button id='left_"+index+"' class='ErpSyncBtn'><</button>"),rightBtn=$("<button id='right_"+index+"' class='ErpSyncBtn'>></button>");toLeft&&this.enableBtn(leftBtn),toRight&&this.enableBtn(rightBtn),container.append(leftBtn),container.append(rightBtn),""==data[index].CrmDisplayName||""==data[index].CrmFieldKey?(this.disableBtn(leftBtn,ResourceUtils.GetResourceText("[SR_EIS_MAPPING_CRMFIELD_REQUIRED]")),this.disableBtn(rightBtn,ResourceUtils.GetResourceText("[SR_EIS_MAPPING_CRMFIELD_REQUIRED]"))):(5===data[index].FieldType?""===data[index].ListReference&&this.disableBtn(leftBtn,ResourceUtils.GetResourceText("[SR_EIS_MAPPING_LIST_TYPE]")):2==data[index].Access&&this.disableBtn(leftBtn,ResourceUtils.GetResourceText("[SR_EIS_READONLY_MAPPING]")),that=this,leftBtn.on("click",function(){that.toERPBtn(index)}),rightBtn.on("click",function(){that.toCRMBtn(index)}))},pub.enableBtn=function(btn){btn.addClass("activeBtn"),btn.attr("title","")},pub.unEnableBtn=function(btn){btn.removeClass("activeBtn"),btn.attr("title","")},pub.disableBtn=function(btn,reason){btn.addClass("disableBtn"),btn.attr("title",reason)},pub.addSearchCheckbox=function(index,container,checked,onclick){var that=this,checked=$("<input id='showInSearch"+index+"' type='checkbox'/>").attr("checked",checked);checked.on("click",function(){that.setShowInSearch(index,this.checked)}),container.append(checked)},pub.addGuiCheckbox=function(index,container,checked,onclick){var that=this,checked=$("<input type='checkbox'/>").attr("checked",checked);checked.on("click",function(){that.setShowInERPTab(index,this.checked)}),container.append(checked)},pub.addDropDown=function(index,container,selVal,extraInfo){var that=this,tmp=$("<div/>"),icon=(tmp.attr("title",selVal),$("<div class='SelectableDropDown'/>")),text=(tmp.append(icon),$("<span>"+(""!=selVal?selVal:" ")+"</span>")),dropDownContext=(tmp.append(text),eval("({ listName: 'CrmFieldsWithNoSelection',extraInfo:'erpfield_id="+extraInfo+"', onClick: function (elem) {that.setCrmFieldId(elem,"+index+",$(this).data('item') );}})"));dropDownContext.soid=soid+index,tmp.dropDown("init",dropDownContext),container.append(tmp)},pub.toERPBtn=function(index){data[index].SyncToErp=!data[index].SyncToErp,data[index].SyncToErp?this.enableBtn($("#left_"+index)):this.unEnableBtn($("#left_"+index)),this.SaveData()},pub.toCRMBtn=function(index){data[index].SyncToCrm=!data[index].SyncToCrm,data[index].SyncToCrm?this.enableBtn($("#right_"+index)):this.unEnableBtn($("#right_"+index)),this.SaveData()},pub.checkSync=function(index){data[index].SyncToErp||data[index].SyncToCrm||(data[index].CrmDisplayName="",data[index].CrmFieldKey="")},pub.setShowInERPTab=function(index,checked){data[index].ShowInGui=checked,this.SaveData()},pub.setShowInSearch=function(index,checked){data[index].ShowInSearch=checked,this.SaveData()},pub.setCrmFieldId=function(element,index,item){var msg,caption,that;""!==data[index].ListReference?(msg=ResourceUtils.GetResourceText("[SR_ERP_WARNING_CHANGELIST]"),caption=ResourceUtils.GetResourceText("[SR_WARN_CAPTION]"),that=this,UIHelper.GetMainPageWindow().$sodlgm.confirm(UIHelper.GetMainPageWindow().SCIL.Router.createUIContext(),{caption:caption,message:msg,height:256,ok:function(){that.setCrmFieldIdCallback(index,item)}})):this.setCrmFieldIdCallback(index,item)},pub.setCrmFieldIdCallback=function(index,item){data[index].CrmDisplayName=item.Name,0!==item.Id?(data[index].CrmFieldKey=item.ExtraInfo+"",""!==data[index].ListReference&&""===item.Type&&(data[index].SyncToErp=!1)):(data[index].CrmFieldKey="",data[index].SyncToCrm=!1,data[index].SyncToErp=!1),data[index].ListReference=item.Type,this.SaveData(!0)},pub.SetActive=function(active,eisaActorType){var w=UIHelper.GetMainPageWindow(),lockLayer=(w.SendWorkerCommand("NotificationWorker","ShowAlert",{title:w.$rm.getResource("[SR_CHAT_STATUSVAL_4]"),tag:"savingErpSync"}),document.createElement("div"));lockLayer.style.position="absolute",lockLayer.style.inset="0",lockLayer.style.zIndex="9999",lockLayer.style.backgroundColor="#000",lockLayer.style.opacity="0.2",document.body.appendChild(lockLayer),AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.Data.AdminErpSyncMappingDataHandler.SetActive","",active,eisaActorType),lockLayer.remove(),w.SendWorkerCommand("NotificationWorker","HideAlert",{tag:"savingErpSync"})},pub.SaveData=function(instantSave){var originalScrollTop,that;$(elem).val(JsonHelper.toJSON(data)),instantSave?(originalScrollTop=$(so("AdminErpSyncMappingFieldsControlGroup_"+actorId)).scrollTop(),SuperOffice.PageBuilder.save(function(){$(so("AdminErpSyncMappingFieldsControlGroup_"+actorId)).scrollTop(originalScrollTop)})):(that=this,SuperOffice.Throttle.run("saveEISMapping",500,function(){AjaxMethodDispatcher.CallASync("","","","","SuperOffice.CRM.Web.Data.AdminErpSyncMappingDataHandler.AsyncSave",data,that.actorId)}))},pub},_this=SoListBox.prototype,_this.Scroll=function(){var selectedValue,layer=$("#"+this._id);0<layer.length&&(0<=this._scrollPos?layer.scrollTop=this._scrollPos:0<(selectedValue=this._selectedValue.value.split(";")[0]).length&&0<(selectedValue=$("#"+selectedValue)).length&&layer.scrollTop(selectedValue.position().top))},_this.SelectAll=function(){this._isReadOnly||(this._tableRowParser.selectAll(),this._selectedValue.value=this._tableRowParser.getSelectedItemsAsString())},_this.DeSelectAll=function(){this._isReadOnly||(this._tableRowParser.deSelectAll(),this._selectedValue.value=this._tableRowParser.getSelectedItemsAsString())},_this.ListItemClicked=function(id){this._isReadOnly||(this.setScrollPos(),this._tableRowParser.setSelectedOnElementId(id),this._selectedValue.value=this._tableRowParser.getSelectedItemsAsString(),this._hasServerClick&&(this._isClicked.value="true"),eval(this._clickScripts.OnClientClick))},_this.setScrollPos=function(){var layer=$("#"+this._id);this._scrollPos=layer.scrollTop},_this.ClearScrollPos=function(){this._scrollPos=-1},_this.ListItemDblClicked=function(id){this._isReadOnly||(this.setScrollPos(),this._tableRowParser.setSelectedOnElementId(id),this._selectedValue.value=this._tableRowParser.getSelectedItemsAsString(),this._hasServerClick&&(this._isClicked.value="true"),eval(this._clickScripts.OnDblClick))},_this.GetList=function(extraInfo,showHistory){var res=AjaxMethodDispatcher.CallSync("SuperOffice.CRM.Web.UI.Controls.SoListBox.GetList","",this._listid,this._showIcons,extraInfo,this._state,showHistory,this._clickScripts);"undefined"!=res&&null!=res&&(document.getElementById(this._id).innerHTML=res.Html,eval(res.CodeToEval))},SuperOffice.Gui.SoListBox=(()=>{var pub={getPrimaryKeyFromRowId:function(listboxId,rowId){rowId=rowId.split(";");return document.getElementById(rowId[0]).attributes.primaryKey.value},getMdoTypeFromListBoxRow:function(listboxId,rowId){rowId=rowId.split(";");return document.getElementById(rowId[0]).attributes.mdoItemType.value}};return pub})(),SuperOffice=SuperOffice||{},SuperOffice.Controls=SuperOffice.Controls||{},SuperOffice.Controls.SoMultiLanguageTextBox=SuperOffice.Controls.SoMultiLanguageTextBox||function(context){var parser=getNs("SuperOffice.Util.MultiLanguageStringParser"),that=(this.context=context,this.dataArray={},this.popup,this.animationSpeed=160,this.popUpStack=new Stack,this);$.fromSoId(this.context.Id+"_textbox").on("keyup",function(){that.updateDatasource(that.context.CurrentLanguage,$(this).val())}),this.onKeyDown=function(){},this.onClick=function(){this.showPopup()},this.getPosAndSize=function(elem){var top=$.fromSoId(this.context.Id+"_textbox").offset().top+22,left=$.fromSoId(this.context.Id+"_textbox").offset().left,maxHeight=$("#container").height();return top+elem.height()>maxHeight&&(top=Math.max(maxHeight-elem.height()+10,0)),console.log(top,left,maxHeight),{top:top,left:left,maxHeight:maxHeight-top-20,height:""}},this.showPopup=function(){function keyUp(){$.fromSoId(that.context.Id+"_textbox").val($(this).val())}var otherLanCode,that=this,data=$.fromSoId(this.context.Id+"_datacontainer").val(),data=(this.parseMultiLanguageStringToArray(data),$("#container")),items=(0<$(".MLpopup").length&&this.unloadPopup("popup"),this.popup=$("<div id='"+this.context.Id+"_popup' class='MLpopup'/>"),data.append(this.popup),this.languageContainer=$("<div id='"+this.context.Id+"_languageContainer'/>"),this.popup.append(this.languageContainer),this.popup.css({width:$.fromSoId(this.context.Id+"_textbox").width()}),this.context.CurrentLanguage!=this.context.DefaultLanguage&&this.addInputLine(this.languageContainer,this.context.CurrentLanguage,!1,!1,keyUp),this.addInputLine(this.languageContainer,this.context.DefaultLanguage,!1,!1,this.context.CurrentLanguage==this.context.DefaultLanguage?keyUp:null),this.getSortedArray());for(otherLanCode in items)items.hasOwnProperty(otherLanCode)&&items[otherLanCode].lanCode!=this.context.CurrentLanguage&&items[otherLanCode].lanCode!=this.context.DefaultLanguage&&this.addInputLine(this.languageContainer,items[otherLanCode].lanCode,!0,!1);data=$("<div class='MLadd'><a href='javascript:;'>"+this.context.AddLanguageCaption+"</a></div>"),data.on("click",function(e){that.showAvailableLanguage(e)}),this.popup.append(data),this.popup.css(this.getPosAndSize(this.popup)),data=$(this.popup).height();$(this.popup).css({visibility:"visible",height:"1px"}).animate({height:data},this.animationSpeed),this.popUpStack.push("MLpopup"),$(document).on("mousedown.MLpopup",function(e){"MLpopup"==that.popUpStack.top()&&(1<$(".MLpopup").length&&that.unloadPopup("MLpopup",!0),$(".MLpopup").is(":hover")||that.unloadPopup("MLpopup",!0))}),$(window).on("unload",function(){that.unloadPopup("MLpopup",!0)}),$(this.languageContainer).find("input").first().trigger("focus")},this.getSortedArray=function(){var data,items=new Array;for(data in this.dataArray)items.push(this.dataArray[data]);var that=this;return items.sort(function(a,b){a=that.context.AvailableLanguages[a.lanCode],b=that.context.AvailableLanguages[b.lanCode];return a&&b?a.DisplayName>b.DisplayName?1:a.DisplayName<b.DisplayName?-1:0:0}),items},this.showAvailableLanguage=function(e){var data,lanElem,that=this,lanPopContainer=$("<div class='MLpopup2'/>");for(data in this.context.AvailableLanguages)data==this.context.CurrentLanguage||data==this.context.DefaultLanguage||this.usedLangauges(data)||data.startsWith("$")||((lanElem=$("<div>"+this.makeNiceDisplayName(this.context.AvailableLanguages[data].DisplayName)+"</div>")).addClass("MLpopuplistitem"),lanElem.data("lanCode",data),lanElem.on("click",null,data+"",function(e){that.addInputLine(that.languageContainer,$(this).data("lanCode"),!0,!0),that.unloadPopup("MLpopup2")}),lanPopContainer.append(lanElem),isMoreLanguages=!0);$("#container").append(lanPopContainer),$(".MLadd").on("keydown",function(e){console.log("keydown");var selectedItem=$(lanPopContainer).find(".selectedMLpopuplistitem");40==e.which&&(0==selectedItem.length?$(lanPopContainer).children().first().addClass("selectedMLpopuplistitem"):(selectedItem.next().addClass("selectedMLpopuplistitem"),selectedItem.removeClass("selectedMLpopuplistitem"))),38==e.which&&(0==selectedItem.length?$(lanPopContainer).children().last().addClass("selectedMLpopuplistitem"):(selectedItem.prev().addClass("selectedMLpopuplistitem"),selectedItem.removeClass("selectedMLpopuplistitem"))),13==e.which&&$(lanPopContainer).find(".selectedMLpopuplistitem").trigger("click")});var top=$(".MLadd").offset().top,left=$(".MLadd").offset().left,top=(top+lanPopContainer.height()>$("#container").height()&&(top=$("#container").height()-lanPopContainer.height()-20),lanPopContainer.css({top:top,left:left}),lanPopContainer.height());$(lanPopContainer).css({visibility:"visible",height:"1px"}).animate({height:top},this.animationSpeed),this.popUpStack.push("MLpopup2"),$(document).on("mousedown.MLpopup2",function(e){$(".MLpopup2").is(":hover")||that.unloadPopup("MLpopup2",!0)})},this.usedLangauges=function(lanCode){return null!=this.dataArray[lanCode]},this.unloadPopup=function(classToRemove,useAnimation){useAnimation?$("."+classToRemove).slideUp(this.animationSpeed,function(){$(this).remove()}):$("."+classToRemove).remove(),$(document).off("mousedown."+classToRemove),this.popUpStack.pop()},this.addInputLine=function(parentElement,lanCode,addDelete,resize,onKeyUp){null==this.dataArray[lanCode]&&(this.dataArray[lanCode]={lanCode:lanCode,value:""});var that=this,elemContainer=$("<div/>"),elemCaption=$("<div class='MLcap'>"+this.makeNiceDisplayName(this.context.AvailableLanguages[lanCode].DisplayName)+"</div>"),elemInput=this.context.MultiLine?$("<textarea rows='3'>"+(null!=this.dataArray[lanCode]?this.dataArray[lanCode].value:"")+"</textarea>"):$("<input type='text' value='"+(null!=this.dataArray[lanCode]?SuperOffice.Util.HtmlEncode(this.dataArray[lanCode].value):"")+"'/>");elemInput.data("lanCode",lanCode),elemContainer.append(elemCaption),elemContainer.append(elemInput),addDelete&&((lanCode=$("<span class='delete svgDeleteGrey smallIconBox'></span>")).on("click",function(){that.deleteLine(elemInput)}),elemContainer.append(lanCode)),onKeyUp&&elemInput.on("keyup",onKeyUp),elemInput.on("change",function(){console.log($(this).data("lanCode"),$(this).val()),that.updateDatasource($(this).data("lanCode"),$(this).val())}),parentElement.append(elemContainer),elemInput.trigger("focus"),resize&&that.popup.css(that.getPosAndSize(that.popup)),this.toggleAddLanguageLink()},this.toggleAddLanguageLink=function(){var data,isMoreLanguages=!1;for(data in this.context.AvailableLanguages)data==this.context.CurrentLanguage||data==this.context.DefaultLanguage||this.usedLangauges(data)||data.startsWith("$")||(isMoreLanguages=!0);isMoreLanguages?$(".MLadd").show():$(".MLadd").hide()},this.deleteLine=function(elemInput){var lanCode=$(elemInput).data("lanCode");delete this.dataArray[lanCode],this.encodeMultiLanguageString(),$(elemInput).parent().remove(),this.toggleAddLanguageLink(),this.popup.css(this.getPosAndSize(this.popup))},this.updateDatasource=function(lanCode,value){null==this.dataArray[lanCode]&&this.parseMultiLanguageStringToArray($.fromSoId(this.context.Id+"_datacontainer").val()),null==this.dataArray[lanCode]?this.dataArray[lanCode]={lanCode:lanCode,value:value}:this.dataArray[lanCode].value=value,this.encodeMultiLanguageString()},this.parseMultiLanguageStringToArray=function(str){this.dataArray={};for(var curCode,curLang,curStr,langs=Object.keys(this.context.AvailableLanguages),i=0;i<langs.length;i++)"$type"!==langs[i]&&(curCode=langs[i],curLang=this.context.AvailableLanguages[curCode],0<(curStr=parser.parseInlineMultiLanguageString(str,curCode,!1)).length)&&curStr!==str&&(this.dataArray[langs[i]]={lanCode:curCode,value:curStr,displayName:curLang.DisplayName});var lanCode=this.context.CurrentLanguage===this.context.DefaultLanguage?this.context.DefaultLanguage:this.context.CurrentLanguage;null==this.dataArray[lanCode]&&(this.dataArray[lanCode]={lanCode:lanCode,value:parser.parseInlineMultiLanguageString(str,curCode,!1),displayName:this.context.AvailableLanguages[lanCode].DisplayName})},this.encodeMultiLanguageString=function(){var data,mStr="",count=0;for(data in this.dataArray)count++,null!=this.dataArray[data].value&&0<this.dataArray[data].value.length&&(mStr+=data+':"'+this.dataArray[data].value+'";');1==count&&void 0!==this.dataArray[this.context.DefaultLanguage]?$.fromSoId(this.context.Id+"_datacontainer").val(this.dataArray[this.context.DefaultLanguage].value):$.fromSoId(this.context.Id+"_datacontainer").val(mStr)},this.makeNiceDisplayName=function(entireDisplayName){var entireDisplayName=entireDisplayName.split("("),displayName=entireDisplayName[0];return 2<entireDisplayName.length&&(displayName+=" ("+entireDisplayName[1]),displayName}},SuperOffice.Controls.SoNavigatorSearchControl=function(){var soid,soDropDownItemClassName="NavigatorSearchItem",soDropDownHeaderClassName="SoDropDownHeaderItem",pub={},onclick="",context,listBox;return pub.getList=function(context){onclick=context.onclick,soid=context.soId,this.context={onlyHistory:!0},$.extend(this.context,context);context=this.search("");popup=this.createPopupBox(),searchContainer=this.createSearchBox(),listBox=this.createListBox(),this.populateList(context,""),this.loadPopupBox(popup)},pub.search=function(searchValue){return AjaxMethodDispatcher.CallSyncReadOnly("SuperOffice.CRM.Web.UI.Controls.SoNavigatorSearchControl.GetList","",this.context.listName,this.context.fetcher,searchValue,this.context.historyName,this.context.onlyHistory)},pub.aSyncSearch=function(searchValue){var that=this;return AjaxMethodDispatcher.CallASyncReadOnly(function(res){that.populateList(res,searchValue)},"","","","SuperOffice.CRM.Web.UI.Controls.SoNavigatorSearchControl.GetList",this.context.listName,this.context.fetcher,searchValue,this.context.historyName,this.context.onlyHistory)},pub.populateList=function(res,searchedValue){if(searchedValue===popup.find("#searchBox").val()&&void 0!==res){popup.find("#list").empty();for(var i=0;i<res.length;i++)this.addRow(listBox,res[i],0);var that=this;popup.find("."+soDropDownItemClassName).on("click",function(){onclick=onclick.replace(/{id}/g,$(this).data("item").Id),onclick=onclick.replace(/{name}/g,encodeURIComponent($(this).data("item").Name)),onclick=onclick.replace(/{type}/g,encodeURIComponent($(this).data("item").Type)),onclick=onclick.replace(/{extrainfo}/g,encodeURIComponent($(this).data("item").ExtraInfo)),eval(onclick),that.unloadPopupBox()})}},pub.setSelected=function(item){elem.data("selecteditem",item),elem.val(item.Name)},pub.addRow=function(listBox,rowObj,level){if(!rowObj.Deleted){var row=$("<div>"+$("<div/>").text(rowObj.Name).html()+"</div>");0<rowObj.ChildItems.length?(row.addClass(soDropDownHeaderClassName),level++):row.addClass(soDropDownItemClassName),row.soToolTip(rowObj.ToolTip),row.data("item",rowObj),$(listBox).append(row);for(var i=0;i<rowObj.ChildItems.length;i++)this.addRow(listBox,rowObj.ChildItems[i],level)}},pub.createPopupBox=function(){var name="SoDropDownPopup",p=$("#"+name);return 0==p.length&&((p=$("<div id='"+name+"'/>")).addClass("SoNavigatorSearchPopup"),$("#container").append(p)),p},pub.createSearchBox=function(){var that=this,l=$("<div class='searchcontainer'><div class='search-icon'/><input id='searchBox' type='text'/></div>"),searchBox=(popup.append(l),popup.find("#searchBox"));return searchBox.delayedChange.oldVal="",searchBox.delayedChange(function(e){var searchVal=searchBox.val();(0==searchVal.length||1<searchVal.length)&&that.aSyncSearch(searchBox.val())}),searchBox.on("keydown",function(e){var selectedItem=$(listBox).find(".NavigatorSearchSelectedItem");40==e.which&&(0==selectedItem.length?$(listBox).children().first().addClass("NavigatorSearchSelectedItem"):(selectedItem.next().addClass("NavigatorSearchSelectedItem"),selectedItem.removeClass("NavigatorSearchSelectedItem"))),38==e.which&&(0==selectedItem.length?$(listBox).children().last().addClass("NavigatorSearchSelectedItem"):(selectedItem.prev().addClass("NavigatorSearchSelectedItem"),selectedItem.removeClass("NavigatorSearchSelectedItem"))),13==e.which&&$(listBox).find(".NavigatorSearchSelectedItem").trigger("click")}),l},pub.createListBox=function(){var l=$("<div id='list'/>");return l.on("mousedown",function(e){return JsHelper.CancelBubble(e)}),popup.append(l),l},pub.unloadPopupBox=function(){$(popup).fadeOut(100,function(){$(this).remove()}),$(document).off("mousedown.dropdownpopup")},pub.loadPopupBox=function(){var that=this,mainOffset=$.fromSoId(soid).offset(),left=mainOffset.left;mainOffset.left+popup.width()>$(window).width()&&(left=$(window).width()-(popup.width()+17)),popup.offset({top:mainOffset.top+30,left:left+28}),$(popup).fadeIn(100),$(document).on("mousedown.dropdownpopup",function(e){$("#SoDropDownPopup").is(":hover")||that.unloadPopupBox()}),popup.find("#searchBox").trigger("focus")},pub},($=>{$.fn.delayedChange=function(options){var timer,o=jQuery.isFunction(options)?{onChange:options}:options;return o=$.extend({},$.fn.delayedChange.defaultOptions,o),this.each(function(){var element=$(this);element.keyup(function(){clearTimeout(timer),timer=setTimeout(function(){var newVal=element.val(),newVal=$.trim(newVal);element.delayedChange.oldVal!=newVal&&(element.delayedChange.oldVal=newVal,o.onChange.call(this))},o.delay)})})},$.fn.delayedChange.defaultOptions={delay:350,onChange:function(){}},$.fn.delayedChange.oldVal=""})(jQuery),SuperOffice.SplitterGroup=Object.create(Object.prototype),SuperOffice.SplitterGroup.__class=!0,SuperOffice.SplitterGroup.currentTop=0,SuperOffice.SplitterGroup.newTop=0,SuperOffice.SplitterGroup.dragElement=null,SuperOffice.SplitterGroup.prevElements=[],SuperOffice.SplitterGroup.nextElements=[],SuperOffice.SplitterGroup.settings={minPreviousHeight:100,minNextHeight:100},SuperOffice.SplitterGroup.init=function(options){$.extend(this.settings,options);var that=this;this.dragElement=$.fromSoId(options.id),this.defaultOffset=this.dragElement.position().top;for(var i=0;i<this.settings.dockElements.length;i++){var elem=$.fromSoId(this.settings.dockElements[i].id);elem.index()<this.dragElement.index()?this.prevElements[this.prevElements.length]={Element:elem,Dock:this.settings.dockElements[i].dock}:this.nextElements[this.nextElements.length]={Element:elem,Dock:this.settings.dockElements[i].dock}}this.dragElement.kendoDraggable({hint:function(element){return element.clone()},axis:"y",drag:function(e){var prevElement=that.dragElement.prev(),parentElement=that.dragElement.parent(),prevElement=[0,prevElement.offset().top+that.settings.minPreviousHeight,0,parentElement.height()-that.settings.minNextHeight],parentElement=(e.y.location<prevElement[1]?e.y.location=prevElement[1]:e.y.location>prevElement[3]&&(e.y.location=prevElement[3]),e.y.location-that.startOffset),prevElement=parseInt(that.dragElement.css("top"),10);that.dragElement.css("top",prevElement+parentElement+"px"),that.dragMove(e,parentElement)},dragstart:function(e){that.startOffset=e.y.startLocation},dragend:function(e){var delta=e.y.location-that.startOffset,top=parseInt(that.dragElement.css("top"),10);that.dragElement.css("top",top+delta+"px"),that.setSplitterPosition(e,{position:{top:that.dragElement.position().top}})}}),PageEventHandler.addEvent(EventType.ONPAGERESIZE,"dragResize",function(){SuperOffice.SplitterGroup.setContainment(that.dragElement)}),0!=this.settings.offset&&(debug.trace("this.settings.offset : "+this.settings.offset,"SoSplitter"),this.isOutsideContainment(that.dragElement,that.settings.offset))&&that.moveSplitter(that.dragElement,Number(that.settings.offset))},SuperOffice.SplitterGroup.isOutsideContainment=function(dragElement,offset){return 0<dragElement.prev().height()-dragElement.prev().offset().top+this.settings.minPreviousHeight+Number(offset)&&dragElement.next().height()-this.settings.minNextHeight+Number(offset)<0},SuperOffice.SplitterGroup.dragMove=function(event,delta){this.startOffset=this.startOffset+delta,this.setOffset(delta)},SuperOffice.SplitterGroup.setOffset=function(delta){for(var i=0;i<this.prevElements.length;i++)(elem=this.prevElements[i].Element).height(elem.height()+delta);for(var elem,i=0;i<this.nextElements.length;i++)(elem=this.nextElements[i].Element).offset({top:elem.offset().top+delta}),""!=elem.css("height")&&-1!=this.nextElements[i].Dock.indexOf("bottom")&&elem.height("")},SuperOffice.SplitterGroup.moveSplitter=function(dragElement,offset){dragElement.offset({top:dragElement.offset().top+offset}),this.setOffset(offset)},SuperOffice.SplitterGroup.setSplitterPosition=function(event,ui){var delta=this.startOffset-this.defaultOffset;AjaxMethodDispatcher.CallASync("","","",null,"SuperOffice.CRM.Web.UI.Controls.SoSplitterControlGroup.SetSplitterPosition",this.settings.id,Math.round(delta))},"function"!=typeof String.prototype.parseFunction&&(String.prototype.parseFunction=function(){var match=/function *\(([^()]*)\)[ \n\t]*{(.*)}/gim.exec(this.replace(/\n/g," "));return match?new Function(match[1].split(","),match[2]):null}),SuperOffice.Toast=(()=>{var pub={Long:6e3,Short:3e3,Wait:-1,Confirm:-2,show:function(text,duration){$(".toast").remove();var toast=$("<div class='toast'/>");duration==pub.Wait&&toast.append("<div class='SpinnerLeft'/>"),toast.append("<span>"+text+"</span>"),duration==pub.Confirm&&toast.append("<button onclick='SuperOffice.Toast.close();'>Ok</button>"),$("#container").append(toast),0<duration&&setTimeout(function(){SuperOffice.Toast.close()},duration),$(window).on("unload",function(){SuperOffice.Toast.close()})},close:function(){console.log("closing toast"),$(".toast").fadeOut()}};return pub})(),_this=_ToolTipContext.prototype;var ToolTipManager=new _ToolTipManager;function _ToolTipManager(id){this._toolTipContext=null,this._toolTipLayer=null}function SoTreeView_ToggleExpandCollapse(nodeId){var sub=document.getElementById(nodeId+"_sub"),nodeId=document.getElementById(nodeId+"_img");null!=sub&&null!=nodeId&&(""==sub.style.display?(nodeId.src="Images/System/web/expand.gif",sub.style.display="none"):(sub.style.display="",nodeId.src="Images/System/web/collapse.gif"))}function SoTreeView_GetSelectedValue(controlId){var selectedNodeValue="",controlId=document.getElementById(controlId+"_selectedNodeValue");return selectedNodeValue=null!=controlId?controlId.value:selectedNodeValue}function SoTreeView_GetSelectedId(controlId){var retval="",selectedNodeValue=SoTreeView_GetSelectedValue(controlId+"_TreeView");if(""!=selectedNodeValue)for(var idx=1;idx<999999;++idx){var node=document.getElementById(controlId+"_"+idx.toString());if(null==node)break;if(node.attributes.name.value==selectedNodeValue){retval=controlId+"_"+idx.toString();break}}return retval}function SoTreeView_SetSelectedByName(controlId,name){var control=document.getElementById(controlId+"_TreeView");if(null!=control)for(var idx=1;idx<999999;++idx){var node=document.getElementById(controlId+"_"+idx.toString());if(null==node||null==node.attributes||null==node.attributes)break;if(node.attributes.name.value.toLowerCase()==name.toLowerCase()){SoTreeView_SetSelected(controlId,node.id);break}}}function SoTreeView_SetSelected(controlId,nodeId){var selectedNodeValue="",control=document.getElementById(controlId+"_TreeView");if(null!=control)for(var idx=1;idx<999999;++idx){var node=document.getElementById(controlId+"_"+idx.toString()+"_Text");if(null==node)break;node.id!=nodeId+"_Text"?node.attributes.class.value="TreeViewNode":(node.attributes.class.value="TreeViewNodeSelected",null!=(node=document.getElementById(controlId+"_"+idx.toString()))&&(selectedNodeValue=node.attributes.name.value))}control=document.getElementById(controlId+"_selectedNodeValue");null!=control&&(control.value=selectedNodeValue)}function SoTreeView_GetNodeValue(rowId){rowId=JsHelper.GetElementsByTagAndName("div",rowId);return null!=rowId&&null!=rowId[0]&&null!=rowId[0]?rowId[0].attributes.displayValue.value:""}function SoTreeView_GetNodeDisplayText(rowId){rowId=JsHelper.GetElementsByTagAndName("div",rowId);return null!=rowId&&null!=rowId[0]&&null!=rowId[0]?rowId[0].innerHTML:""}function SoTreeView_SetNodeDisplayText(rowId,value){rowId=JsHelper.GetElementsByTagAndName("div",rowId);null!=rowId&&null!=rowId[0]&&null!=rowId[0]&&(rowId[0].innerHTML=value)}_this=_ToolTipManager.prototype,_this.Show=function(evt,id,txt,serverRequest,escapeHtml){var uId;null!=evt&&(serverRequest&&g_shiftDown&&(txt=txt.replace(/\}$/,"&debuginfo=true}")),uId=1e3*Math.random(),this._toolTipContext=new _ToolTipContext(uId,id,txt,Event.pointerX(evt),Event.pointerY(evt),serverRequest,escapeHtml),setTimeout("ToolTipManager.DisplayToolTip("+uId+",'"+id+"');",1500))},_this.ShowStatic=function(elem,id,txt,serverRequest){serverRequest&&g_shiftDown&&(txt=txt.replace(/\}$/,"&debuginfo=true}"));var x=0,y=0,elem=(so_defined(elem)&&(x=(elem=$(elem)).offset().left,y=elem.offset().top),1e3*Math.random());this._toolTipContext=new _ToolTipContext(elem,id,txt,x,y,serverRequest),this.CreateToolTip(),$(document).on("click",function(){ToolTipManager.Hide()})},_this.Hide=function(){try{(this._toolTipContext=null)!=this._toolTipLayer&&(debug.trace("Hide","Tooltipmanager"),document.body.contains(this._toolTipLayer)&&document.body.removeChild(this._toolTipLayer),this._toolTipLayer=null)}catch(e){debug.error("Hide: "+e.message,"Tooltipmanager")}},_this.AutoHide=function(uId,id){debug.trace("AutoHide:"+id,"Tooltipmanager"),null!=this._toolTipContext&&this._toolTipContext.Id==id&&this._toolTipContext.uId==uId&&this.Hide()},_this.DisplayToolTip=function(uId,id){null!=this._toolTipContext&&this._toolTipContext.Id==id&&this._toolTipContext.uId==uId&&(this.CreateToolTip(),$(document).on("click",function(){ToolTipManager.Hide()}),setTimeout("ToolTipManager.AutoHide("+uId+",'"+id+"');",this.getReadTime()))},_this.getReadTime=function(){var time=6e3,time=(time+=this.linebreakTime())+this.wordTime();return debug.trace("Tooltip time:"+time,"Tooltipmanager"),time},_this.wordTime=function(){for(var content=this._toolTipLayer.innerHTML,i=0,numberofwords=1;i<=content.length;)" "==content.substring(i,i+1)&&(numberofwords++,i++),"\n"==content.substring(i,i+1)&&(numberofwords++,i++),i++;return 50*numberofwords},_this.linebreakTime=function(){return 100*this._toolTipLayer.getElementsByTagName("BR").length},_this.CreateToolTip=function(){try{if(null!=this._toolTipLayer){try{document.body.removeChild(this._toolTipLayer)}catch(e){debug.error("CreateToolTip top: "+e.message,"Tooltipmanager")}this._toolTipLayer=null}this._toolTipLayer=document.createElement("DIV"),this._toolTipLayer.id="ToolTipLayer",this._toolTipLayer.style.overflow="hidden",this._toolTipLayer.style.position="absolute",this._toolTipLayer.style.top="0px",this._toolTipLayer.style.left="0px",this._toolTipLayer.style.zIndex=2e3;var tooltipText="",tooltipText=this._toolTipContext.serverRequest?this.UnEscapeToolTip(this.GetToolTipText()):this.UnEscapeToolTip(this._toolTipContext.Text);!0===this._toolTipContext.escapeHtml?(tooltipText=(tooltipText=tooltipText.replace(/<br\/>/g,"\n")).replace(/\"/g,'"'),$(this._toolTipLayer).text(tooltipText),this._toolTipLayer.style.whiteSpace="pre-wrap"):$(this._toolTipLayer).html(_DOMPurify.sanitize(tooltipText)),this._toolTipLayer.style.visibility="hidden",document.body.appendChild(this._toolTipLayer),this._toolTipLayer.className="ToolTipLayer",this.checkBoundary(this._toolTipContext.y+14,this._toolTipContext.x+14),""!=this._toolTipLayer.innerHTML&&(this._toolTipLayer.style.visibility="visible")}catch(e){debug.error("CreateToolTip: "+e.message,"Tooltipmanager")}},_this.UnEscapeToolTip=function(tooltip){return unescape(tooltip).replace(/&singlequote;/gi,"'").replace(/\+/g," ")},_this.checkBoundary=function(top,left){var rect=getWindowRectangle(),rightVal=left+this._toolTipLayer.offsetWidth,bottomVal=top+this._toolTipLayer.offsetHeight;rightVal>rect.getX()&&bottomVal>rect.getY()&&(this._toolTipLayer.style.width=Math.min(rect.getX()-20,this._toolTipLayer.offsetWidth)+"px",this._toolTipLayer.style.height=Math.min(rect.getY()-top-10,this._toolTipLayer.offsetHeight)+"px",rightVal=left+this._toolTipLayer.offsetWidth,bottomVal=top+this._toolTipLayer.offsetHeight),this._toolTipLayer.style.maxHeight=rect.getX(),this._toolTipLayer.style.maxWidth=rect.getY(),rightVal>rect.getX()?left-this._toolTipLayer.offsetWidth-10<0&&0<left-this._toolTipLayer.offsetWidth/2&&left+this._toolTipLayer.offsetWidth/2<rect.getX()?this._toolTipLayer.style.left=left-this._toolTipLayer.offsetWidth/2+"px":this._toolTipLayer.style.left=Math.max(0,left-this._toolTipLayer.offsetWidth-10)+"px":this._toolTipLayer.style.left=Math.max(0,left)+"px",bottomVal>rect.getY()?this._toolTipLayer.style.top=Math.max(0,top-this._toolTipLayer.offsetHeight-10)+"px":this._toolTipLayer.style.top=Math.max(0,top)+"px"},_this.GetToolTipText=function(){return AjaxMethodDispatcher.CallSyncReadOnly("SuperOffice.CRM.Web.AjaxMethods.ToolTipText.GetToolTip","",unescape(this._toolTipContext.Text))},_this.RegisterToolTip=function(element,text){text="javascript:ToolTipManager.Show(event, '"+"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=16*Math.random()|0;return("x"===c?r:3&r|8).toString(16)})+"', '"+text+"', false);",text=new Function(text);$(element).off("mousemove"),$(element).on("mousemove",text)},SuperOffice.Controls.Udef=function(soid,onMoveCallback,udefFieldsUpdate){var pub={},udefEditorElement=null,udefFieldsUpdateArray=udefFieldsUpdate,onMoveCallbackFunctionName=onMoveCallback||"",self=this,editorScroll={left:0,top:0},snapPixels={x:21,y:21};return pub.soid=soid,(udefEditorElement=$.fromSoId(soid)).data("inited")||udefEditorElement.udefEditor("init",{snapPixels:snapPixels,editorScroll:editorScroll,onMoved:function(udefElements,setAlign){console.log("# moved:"+udefElements.length);for(var fieldArray=jQuery.extend([],udefFieldsUpdateArray),t=0;t<udefElements.length;++t){var field=jQuery.extend({},udefFieldsUpdateArray[0]),udefElement=(field.Position=jQuery.extend({},udefFieldsUpdateArray[0].Position),$(udefElements.get(t)));field.ProgId=udefElement.attr("progid"),field.Type=udefElement.attr("type"),field.X=Math.floor(udefElement.position().left),field.Y=Math.floor(udefElement.position().top),(1===setAlign||2===setAlign&&udefElement.children().first().hasClass("SoLabel"))&&(field.Align=setAlign),fieldArray[t]=field}""===onMoveCallbackFunctionName?$.error("No SaveMethod defined on AdminUdefControlGroup with ID="+soid):SuperOffice.Throttle.run(this.soid,2e3,function(){console.log("AJAX SAVE"),editorScroll[soid]=udefEditorElement.udefEditor("getScrollPos"),new Function("fieldArray",onMoveCallbackFunctionName+"(fieldArray)")(fieldArray)})},onSelectionChanged:function(udefelements){console.log("onSelectionChanged: "+udefelements.length),SuperOffice.Throttle.executeNow(self.soid)},onDoubleClick:function(udefelement){console.log("double click:"+udefelement.attr("progid"));var soid=SuperOffice.Admin.Fields.listBoxSoId,soid=SuperOffice.SoCheckedListBox(soid).getRowIdFromRowType(udefelement.attr("progid"));console.log("rowId:"+soid),SuperOffice.Admin.Fields.openEditFieldDialog(soid)}}),pub.select=function(id){udefEditorElement.udefEditor("select",id)},pub.alignLeft=function(){udefEditorElement.udefEditor("alignSelected",{align:1})},pub.alignRight=function(){udefEditorElement.udefEditor("alignSelected",{align:2})},pub.moveLeft=function(){udefEditorElement.udefEditor("moveSelected",{x:-snapPixels.x,y:0})},pub.moveRight=function(){udefEditorElement.udefEditor("moveSelected",{x:snapPixels.x,y:0})},pub.moveUp=function(){udefEditorElement.udefEditor("moveSelected",{x:0,y:-snapPixels.y})},pub.moveDown=function(){udefEditorElement.udefEditor("moveSelected",{x:0,y:snapPixels.y})},pub},($=>{var host=null,initOptions=null,children=null,helper_getAll=function(){return host?host.children("[progid]"):$("justadummyselector")},helper_getSelected=function(){return host?host.children(".udefselected"):$("justadummyselector")},helper_getUnselected=function(){return host?host.children(":not(.udefselected)"):$("justadummyselector")},helper_unSelectAll=function(){null!=host&&host.children().removeClass("udefselected")},helper_storeCurrentPosition=function(udefElements){udefElements.each(function(){var elem=$(this);elem.data("pos",{left:elem.position().left,top:elem.position().top})})},helper_getMaxTopPosition=function(udefElements){return Math.max.apply(udefElements,udefElements.map(function(){return $(this).position().top+$(this).height()}).get())},helper_getMaxRightPosition=function(udefElements){return Math.max.apply(udefElements,udefElements.map(function(){return $(this).position().left+$(this).width()}).get())},helper_getMinTopPosition=function(udefElements){return Math.min.apply(udefElements,udefElements.map(function(){return $(this).position().top}).get())},helper_getMinLeftPosition=function(udefElements){return Math.min.apply(udefElements,udefElements.map(function(){return $(this).position().left}).get())},eventDispatcher_fireOnMoved=function(udefElements,setAlign){initOptions.onMoved&&initOptions.onMoved(udefElements,setAlign);setAlign=helper_getMaxTopPosition(udefElements),host.height()<setAlign&&(host.height(setAlign+50),host.parent().scrollTop(9999)),setAlign=helper_getMaxRightPosition(udefElements);host.width()<setAlign&&(host.width(setAlign+20),host.parent().scrollLeft(9999))},eventDispatcher_fireOnSelectionChanged=function(){helper_getUnselected().find(".udefgrip").remove(),helper_getSelected().append("<div class='udefgrip'></div>"),initOptions.onSelectionChanged&&initOptions.onSelectionChanged(helper_getSelected())},eventDispatcher_fireOnDoubleClick=function(){initOptions.onDoubleClick&&initOptions.onDoubleClick(helper_getSelected().first())},methods={init:function(options){var elemId,allUdefElements,maxTop;host.data("inited")||((initOptions=options||{}).snapPixels=initOptions.snapPixels||{x:21,y:21},children=host.children(),host.mousedown(function(event){$(event.target).parent().attr("id")==host.parent().attr("id")&&(event=helper_getSelected().length,helper_unSelectAll(),0<event)&&eventDispatcher_fireOnSelectionChanged()}),children.toggleClass("udefunselected"),children.mousedown(function(event){var minTop,hasSelectionChanged=!1,udefElement=$(this);return 1==event.which&&(g_ctrlDown?hasSelectionChanged=!0:udefElement.hasClass("udefselected")||(hasSelectionChanged=!0,helper_unSelectAll()),g_ctrlDown?udefElement.toggleClass("udefselected"):udefElement.hasClass("udefselected")||(udefElement.toggleClass("udefselected"),hasSelectionChanged=!0),host.data("hasdragged",!1),host.data("currentlyselected",helper_getSelected()),event=helper_getSelected(),host.offset().top,host.offset().left,1<event.length&&(minTop=helper_getMinTopPosition(event),event=helper_getMinLeftPosition(event),udefElement.position().left>event&&udefElement.position().left,udefElement.position().top>minTop)&&udefElement.position().top,hasSelectionChanged&&eventDispatcher_fireOnSelectionChanged(),$(":focus").trigger("blur")),!1}),children.mouseup(function(event){var udefElement=$(this);if(1!=event.which)return!1;g_ctrlDown||(event=helper_getSelected().length,helper_unSelectAll(),host.data("hasdragged")?host.data("currentlyselected").toggleClass("udefselected"):(udefElement.toggleClass("udefselected"),1<event&&eventDispatcher_fireOnSelectionChanged()))}),children.dblclick(function(){eventDispatcher_fireOnDoubleClick()}),elemId=host.parent().attr("id"),$(document).on("keyup."+elemId,function(event){if(host.isVisible(host)){var x=0,y=0;switch(event.which){case 39:x=1;break;case 37:x=-1;break;case 38:y=-1;break;case 40:y=1;break;case 65:event.ctrlKey&&(host.children().addClass("udefselected"),eventDispatcher_fireOnSelectionChanged())}var elems=helper_getSelected(),minTop=(helper_storeCurrentPosition(elems),helper_getMinTopPosition(elems)),elems=helper_getMinLeftPosition(elems);minTop+y<0&&(y=0),((x=elems+x<0?0:x)||y)&&(helper_getSelected().each(function(){$(this).setLeft($(this).position().left+x),$(this).setTop($(this).position().top+y)}),eventDispatcher_fireOnMoved(helper_getSelected()))}else $(document).off("keyup."+elemId)}),host.parent().append("<div id='udefcontainerhost'></div>"),$("#udefcontainerhost").css({overflow:"auto",position:"absolute",top:"0px",left:"0px",bottom:"40px",right:"0px"}),$("#udefcontainerhost").append($("[udefcontainer]")),host.css({width:"100%",height:"100%"}),host.toggleClass("udefgrid21"),allUdefElements=helper_getAll(),maxTop=helper_getMaxTopPosition(allUdefElements),host.height()<maxTop&&host.height(maxTop+50),maxTop=helper_getMaxRightPosition(allUdefElements),host.width()<maxTop&&host.width(maxTop+20),helper_getAll().has("[readonly='readonly']").addClass("udefreadonlyborder"),helper_getAll().find("input").addClass("nofocus"),(0<options.editorScroll.left||0<options.editorScroll.top)&&(host.parent().scrollLeft(options.editorScroll.left),host.parent().scrollTop(options.editorScroll.top)),host.data("inited",!0))},getScrollPos:function(){return{left:host.parent().scrollLeft(),top:host.parent().scrollTop()}},select:function(id){helper_unSelectAll(),host.find("[progid='"+id+"']").toggleClass("udefselected"),initOptions.onSelectionChanged&&eventDispatcher_fireOnSelectionChanged()},moveSelected:function(options){var moveX,moveY,minLeft,elems=helper_getSelected();helper_storeCurrentPosition(elems),0<elems.length&&(moveX=options.x,moveY=options.y,options=helper_getMinTopPosition(elems),(minLeft=helper_getMinLeftPosition(elems))+moveX<0&&(moveX=-minLeft),options+moveY<0&&(moveY=-options),elems.each(function(){var modX;0!=moveX&&(modX=$(this).position().left%initOptions.snapPixels.x,moveX=0<moveX?initOptions.snapPixels.x-modX:0==modX?-initOptions.snapPixels.x:-modX),0!=moveY&&(modX=$(this).position().top%initOptions.snapPixels.y,moveY=0<moveY?initOptions.snapPixels.y-modX:0==modX?-initOptions.snapPixels.y:-modX),$(this).setLeft($(this).position().left+moveX),$(this).setTop($(this).position().top+moveY)}),eventDispatcher_fireOnMoved(helper_getSelected()))},alignSelected:function(options){var leftmostposition,rightmostposition,elems=helper_getSelected();helper_storeCurrentPosition(elems),0<elems.length&&(leftmostposition=helper_getMinLeftPosition(elems.filter(function(elem){return $(this).children().first().hasClass("SoLabel")})),rightmostposition=helper_getMaxRightPosition(elems.filter(function(elem){return $(this).children().first().hasClass("SoLabel")})),elems.each(function(){$(this).children().first().hasClass("SoLabel")&&(1==options.align?($(this).setLeft(leftmostposition),$(this).children().first().css("text-align","left")):2==options.align&&($(this).setLeft(rightmostposition-$(this).width()),$(this).children().first().css("text-align","right")))})),eventDispatcher_fireOnMoved(helper_getSelected(),options.align)},getSelected:function(){return helper_getSelected()},getUnselected:function(){return helper_getUnselected()}};$.fn.udefEditor=function(method){return(host=$(this)).attr("udefcontainer")||(host=host.find("[udefcontainer]")),methods[method]?methods[method].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof method&&method?void $.error("Method "+method+" does not exist on jQuery.udefEditor"):methods.init.apply(this,arguments)}})(jQuery);
|
|
//# sourceMappingURL=pagebuilder.min.js.map |