const leadingZero=(num,places)=>String(num).padStart(places,'0');Number.prototype.countDecimals=function(){if(Math.floor(this.valueOf())===this.valueOf())
return 0;var str=this.toString();if(str.indexOf(".")!==-1&&str.indexOf("-")!==-1){return str.split("-")[1]||0}else if(str.indexOf(".")!==-1){return str.split(".")[1].length||0}
return str.split("-")[1]||0};function round2Dec(num){num=Number(num);var m=Number((Math.abs(num)*100).toPrecision(15));return Math.round(m)/100*Math.sign(num)}
function getHostName(){var host=window.location.hostname;if((host=="www.gme.ao")||(host=="gme.ao")){host+="/sfront"}
return host}
function renewLicenseHost(){var host=getHostName();if(getDesktopStatus()){host="silicaweb.ao"}
return host}
function dateExtension(d,separator=" de "){var dt=new Date(d);return dt.getDate()+separator+monthName(dt.getMonth())+separator+dt.getFullYear()}
function dateDiffDays(date1,date2){var date1d=new Date(date1);var date2d=new Date(date2);var time=date1d.getTime()-date2d.getTime();return(time/(1000*60*60*24))}
function dateDiffMinutes(dateNew,dateOld){var date1d=new Date(dateNew);var date2d=new Date(dateOld);var time=date1d.getTime()-date2d.getTime();return(time/(1000*60))}
function daysInMonth(month,year){return new Date(year,month,0).getDate()}
function dateAddDays(date,days){days=Number(days);var result=new Date(date);result.setDate(result.getDate()+(days));return result}
function validateUserControl(control){if(control===null){return!1}else{return!0}}
function validateDate(d){return d instanceof Date&&!isNaN(d)}
function createTableCell(row,inner,clas="",dataLabel=""){let cell=row.insertCell(-1);let div=createElement("div","","");cell.appendChild(div);if((inner!=null)&&(inner!="")){div.innerHTML=inner}else{if(dataLabel!="..."){clas+=" pseudo-content"}}
var tbody=$(row).parent()[0];var colIdx=cell.cellIndex;var att=tbody.getAttribute("hide_this_col_"+colIdx);var tIdx=tbody.getAttribute("table_index");if(att==1){clas+=" display-none"}
if(clas!=""){cell.setAttribute("class",clas)}
clas+=" div-on-cell-to-print-"+tIdx+"-"+colIdx;div.setAttribute("class",clas.replace("pseudo-content",""));if(dataLabel!=""){cell.setAttribute("data-label",dataLabel)}
if(dataLabel!=""){cell.setAttribute("title",dataLabel)}
return cell}
function createElement(tag,type="",clas="",style=""){let elem=document.createElement(tag);if(type!=""){elem.type=type}
if(clas!=""){elem.setAttribute("class",clas)}
if(style!=""){elem.style=style}
return elem}
function removeElement(elementId){var element=document.getElementById(elementId);if(validateUserControl(element)){element.remove()}}
function setElementValue(elementId,elementValue=""){var element=document.getElementById(elementId);if(validateUserControl(element)){element.value=elementValue}}
function getElementValue(elementId){var element=document.getElementById(elementId);if(validateUserControl(element)){return element.value}}
function getElementChecked(elementId){var element=document.getElementById(elementId);if(validateUserControl(element)){if(element.checked==!0){return 1}}
return 0}
function getSelectText(elementId){var element=document.getElementById(elementId);if(validateUserControl(element)){return element.options[element.selectedIndex].text}}
function setElementInnerHtml(elementId,elementValue=""){var element=document.getElementById(elementId);if(validateUserControl(element)){element.innerHTML=elementValue}}
function getElementInnerHTML(elementId){var element=document.getElementById(elementId);if(validateUserControl(element)){return element.innerHTML}}
function setElementFocus(elementId){var element=document.getElementById(elementId);if(validateUserControl(element)){element.focus()}}
function setElementAttribute(elementId,attr,valueAttr){var element=document.getElementById(elementId);if(validateUserControl(element)){element.setAttribute(attr,valueAttr)}}
function disabledElement(elementId){var element=document.getElementById(elementId);if(validateUserControl(element)){element.disabled=!0}}
function enabledElement(elementId){var element=document.getElementById(elementId);if(validateUserControl(element)){element.disabled=""}}
function showParts(id,inline=!1){var part=document.getElementById(id);if(validateUserControl(part)){if(inline){part.style.display='inline'}else{part.style.display='block'}
if(part.getAttribute(ST_ONLOAD_ATTRIBUTE)==1){part.dispatchEvent(new Event("load"))}}}
function showDivPayment(divId,whoCall){var div=document.getElementById(divId);if(validateUserControl(div)){div.style.display='block'}
document.getElementById("selRecPagPaymentMecanism").dispatchEvent(new Event("change"))}
function hideParts(id){var part=document.getElementById(id);if(validateUserControl(part)){part.style.display='none'}}
function cleanElement(id){var part=document.getElementById(id);if(validateUserControl(part)){part.innerHTML=""}}
function showNotification(msg="Processando...",sucess=-1){const div=document.getElementById('divNotification');const lb=document.getElementById('lbNotification');const divProg=document.getElementById('divNotificationProgress');if((sucess==0)||(sucess==1)){let divBox=document.getElementById("divNotificationBox");let divIcon=document.getElementById("divNotificationBoxIcon");setElementInnerHtml("pNotificationBoxText",msg);if(sucess==1){divIcon.classList.add("notification-bcg-check");divIcon.classList.remove("notification-bcg-not-ckeck")}else{divIcon.classList.add("notification-bcg-not-ckeck");divIcon.classList.remove("notification-bcg-check")}
showParts(divBox.id);var duration=msg.length*80;if(duration<3000){duration=3000}else if(duration>8000){duration=8000}
setTimeout(function(){hideParts(divBox.id)},duration);hideNotification();return!0}else{showParts("divLongTimeNotificationBox");setElementInnerHtml("pLongTimeNotificationBoxText",msg);return!1}
divProg.style.width="0%";if(!validateUserControl(div)){return!1}
div.classList.remove('labelValidate');div.classList.remove('labelError');if(sucess==1){div.style.backgroundColor="rgba(0,176,80)";div.classList.add('labelValidate')}
if(sucess==0){div.style.backgroundColor="rgba(196,0,0)";div.classList.add('labelError')}
div.style.height="70px";lb.innerHTML=msg;if(sucess==-1){div.style.backgroundColor="#2c69cc";var pStatus=0;function progress(){pStatus+=5;divProg.style.width=pStatus+"%";if(pStatus<85){setTimeout(function(){progress()},500)}else if(pStatus==85){setTimeout(function(){pStatus=20;progress()},500)}}
progress()}else{setTimeout(function(){div.style.height="0px"},3000)}}
function hideNotification(){setTimeout(function(){hideParts("divLongTimeNotificationBox")},1000)}
function hideDivFilter(){const divFilter=document.getElementById('divFilter');if(validateUserControl(divFilter)){var span=divFilter.querySelector(".div-fieldset-legend");var status=span.getAttribute("status");if((status!=0)){span.dispatchEvent(new Event('click'))}}}
function setSpanHideFieldSet(buttonId,fieldsetId){const bt=document.getElementById(buttonId);const flds=document.getElementById(fieldsetId);if(!validateUserControl(bt)){return!1}
if(!validateUserControl(flds)){return!1}
flds.style.display="none";bt.onclick=function(){if(window.getComputedStyle(flds).display=="none"){flds.style.display="flex";bt.innerHTML="-"}else{flds.style.display="none";bt.innerHTML="+"}}}
function showConfirm(question,callBack){const div=document.getElementById('divConfirmOverlay');const lbQuest=document.getElementById('lbConfirmQuestion');const btConfirm=document.getElementById('btConfirmYes');lbQuest.innerHTML=question;div.style.display="block";btConfirm.onclick=function(){div.style.display="none";callBack()}}
function showPrintOptions(printReceipt,printA5,printA4,sendByEmail,sendByWhatsApp,customerEmail="",customerWhatsApp="",onlyPrint=!1){const div=document.getElementById('divPreviewAndPrintAndSend');const btReceipt=document.getElementById('btPriPrevPrintReceipt');const btA5=document.getElementById('btPriPrevPrintA5');const btA4=document.getElementById('btPriPrevPrintA4');const btEmail=document.getElementById('btPriPrevSendMail');const btWhatsApp=document.getElementById('btPriPrevSendWhatsApp');const txtEmail=document.getElementById('txtPriPrevCustomerEmail');const txtWhatsApp=document.getElementById('txtPriPrevCustomerPhone');div.style.display="block";if(onlyPrint){hideParts('divPriPrevPrintA5');hideParts('divPriPrevSendMail');hideParts('divPriPrevSendWhatsApp')}else{showParts('divPriPrevPrintA5');showParts('divPriPrevSendMail');showParts('divPriPrevSendWhatsApp')}
txtEmail.value=customerEmail;if(customerWhatsApp.length==9){customerWhatsApp="244"+customerWhatsApp}
txtWhatsApp.value=customerWhatsApp;btReceipt.onclick=function(){div.style.display="none";printReceipt()};btA5.onclick=function(){div.style.display="none";printA5()};btA4.onclick=function(){div.style.display="none";printA4()};btEmail.onclick=function(){customerEmail=txtEmail.value.toLowerCase();customerEmail=customerEmail.trim().replace(/[^a-z0-9\_\.\@\;]/g,'').replace(/\s/g,'');txtEmail.value=customerEmail;if(customerEmail.length<=0){showNotification("E-mail fora do formato.",0);return!1}
var mails=customerEmail.split(";");if(mails.length<=1){if(!validateEmail(customerEmail)){showNotification("E-mail fora do formato.",0);return!1}}
var isOk=!0;mails.forEach(element=>{var email=element.toString();if(!validateEmail(email)){showNotification("E-mail fora do formato.",0);isOk=!1;return!1}});if(!isOk){showNotification("E-mail fora do formato.",0);return!1}
div.style.display="none";sendByEmail()};btWhatsApp.onclick=function(){customerWhatsApp=txtWhatsApp.value;customerWhatsApp=customerWhatsApp.trim().replace(/[^0-9]/g,"");if(customerWhatsApp.slice(0,2)=="00"){customerWhatsApp=customerWhatsApp.slice(2)}
txtWhatsApp.value=customerWhatsApp;if(customerWhatsApp.length<12){showNotification("Número do WhatsApp fora do formato.",0);return!1}
div.style.display="none";sendByWhatsApp()}}
function showHideDivUserInfo(a){var x=document.getElementById("divUserInfo");if(window.getComputedStyle(x).display==="none"){x.style.display="block"}else{x.style.display="none"}}
function dateToProductCode(dateX){var date1=new Date("2000-01-01");var Difference_In_Time=dateX.getTime()-date1.getTime();return Number(Difference_In_Time/(1000*3600*24)).toFixed()}
function subMenuShow(itemId,aId,subItemId){var menuItem=document.getElementById(itemId);var aItem=document.getElementById(aId);var subMenuItem=document.getElementById(subItemId);var status=menuItem.value;if(status==1){subMenuItem.style.display="none";menuItem.classList.remove('menuItemSelect');menuItem.value=0;aItem.style.color="white"}else{$(function(){$(".menuItemSelect").each(function(){if(this.id!=itemId){$(this).removeClass("menuItemSelect");this.value=0;$(this).children("ul").css("display","none");$(this).children().css("color","white")}})});subMenuItem.style.display="block";menuItem.classList.add('menuItemSelect');menuItem.value=1;aItem.style.color="#4b007d"}}
function reviewString(control){if(!validateUserControl(control)){return""}
var strValue="";if(typeof control==='string'||control instanceof String){strValue=control}else{strValue=control.value}
strValue=strValue.trim().replace(/[^A-zÀ-ú0-9\"\-\.\s\,\!\%\@\(\)\ª\º\;\#]/g,"").replace(/\s{2,}/g,' ');if(typeof control!=='string'){var size=Number(control.maxlength);if(!isNaN(size)){if(size>0){strValue=strValue.slice(0,size)}}}
return strValue}
function reviewEmail(strValue){strValue=strValue.toString().toLowerCase();strValue=strValue.trim().replace(/[^a-z0-9\_\-\.\@]/g,'').replace(/\s/g,'');return strValue}
function validateEmail(email){const re=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;return re.test(String(email).toLowerCase())}
function isEmail(email){var regex=/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;return regex.test(email)}
function getFirtLastName(fullName){if(fullName){fullName=reviewString(fullName);var names=fullName.toString().split(" ");if(names.length<=1){return fullName}
return names[0]+" "+names[names.length-1]}else{return""}}
function validateTaxId(taxId){if(taxId.length<10){return!1}
var numericPart=taxId.substring(0,9);if(isNaN(numericPart)){return!1}
return!0}
function formatNumber(num){num=Number(num);return(num.toFixed(2).replace('.',',').replace(/(\d)(?=(\d{3})+(?!\d))/g,'$1 '))}
function selectYesNoChangeColor(sel){if(validateUserControl(sel)){sel.title=sel.value}}
function selectCountryChange(country,province,municipality,city){const selCountry=document.getElementById(country);const selProvince=document.getElementById(province);const selMunicipality=document.getElementById(municipality);const lbCity=document.getElementById(city);if(validateUserControl(selCountry)){selCountry.onchange=function(){if(selCountry.value==1){selProvince.disabled=!1;selMunicipality.disabled=!1;if(validateUserControl(lbCity)){lbCity.innerHTML="Cidade"}}else{selProvince.disabled=!0;selProvince.value=-1;selMunicipality.disabled=!0;selMunicipality.value=-1;if(validateUserControl(lbCity)){lbCity.innerHTML="Cidade / Estado"}}}}}
function setCookie(cname,cvalue,exmin){var d=new Date();d.setTime(d.getTime()+(exmin*60*1000));var expires="expires="+d.toUTCString();document.cookie=cname+"="+cvalue+";"+expires+";path=/"}
function getCookie(cname){var name=cname+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' '){c=c.substring(1)}
if(c.indexOf(name)==0){return c.substring(name.length,c.length)}}
return""}
function printPageA4(title="",subtitle="",printForm=!1){showParts('divPrintOptions');if(!printForm){$(".print-as-subtitle").each(function(){var div=this;var strValue="-#";$(div).find("input").each(function(){strValue=$(div).find("input")[0].value});if(strValue=="-#"){$(div).find("select").each(function(){strValue=this.value;if(strValue!=""){if(strValue!="-1"){strValue=getSelectText(this.id)}}})}
if(strValue!="-#"){if(strValue!=""){if(strValue!="-1"){$(div).find("span").each(function(){var lb=$(this)[0].innerHTML;if(lb!=""){if(subtitle!=""){subtitle+=" | "}
subtitle+=lb+" <b>"+strValue+"</b>"}})}}}})}
document.getElementById('txtPrintOptionTitle').value=title;document.getElementById('txtPrintOptionSubtitle').value=subtitle;var companyId=SYSTEM_USER_STATUS.companyId;var dependencyId=SYSTEM_USER_STATUS.workplaceId;var cookiename=companyId+dependencyId+"printOptionSignature";fillSelectPrintOptionSignature("selPrintOptionVisaBy",-1);fillSelectPrintOptionSignature("selPrintOptionSignature1",-1);fillSelectPrintOptionSignature("selPrintOptionSignature2",-1);fillSelectPrintOptionSignature("selPrintOptionSignature3",-1);var visa=getCookie(cookiename+0);if((visa!=null)&&(visa!="")){var signature=JSON.parse(visa);document.getElementById('txtPrintOptionVisaQuality').value=signature.quality;document.getElementById('txtPrintOptionVisaPerson').value=signature.person}
var sign1=getCookie(cookiename+1);if((sign1!=null)&&(sign1!="")){var signature=JSON.parse(sign1);document.getElementById('txtPrintOptionSignatureQuality1').value=signature.quality;document.getElementById('txtPrintOptionSignaturePerson1').value=signature.person}
var sign2=getCookie(cookiename+2);if((sign2!=null)&&(sign2!="")){var signature=JSON.parse(sign2);document.getElementById('txtPrintOptionSignatureQuality2').value=signature.quality;document.getElementById('txtPrintOptionSignaturePerson2').value=signature.person}
var sign3=getCookie(cookiename+3);if((sign3!=null)&&(sign3!="")){var signature=JSON.parse(sign3);document.getElementById('txtPrintOptionSignatureQuality3').value=signature.quality;document.getElementById('txtPrintOptionSignaturePerson3').value=signature.person}
var divs=document.getElementsByClassName("no-print-on-form");Array.from(divs).forEach(div=>{if(printForm){div.classList.add("noPrint")}else{div.classList.remove("noPrint")}});var comb="-"+ST_SRH_MAIN_WHO_CALL+"-"+SYSTEM_USER_STATUS.userId;var ftSizeTitle=getCookie("selPrintOptionFtSzTitle"+comb);var ftSizeSubTitle=getCookie("selPrintOptionFtSzSubtitle"+comb);var ftSizeLabel=getCookie("selPrintOptionFtSzLabel"+comb);var ftSizeInPut=getCookie("selPrintOptionFtSzForm"+comb);var ftSizeP=getCookie("selPrintOptionFtSzParagraph"+comb);var ftSizeTH=getCookie("selPrintOptionFtSzTableHeader"+comb);var ftSizeTD=getCookie("selPrintOptionFtSzTableCell"+comb);if(ftSizeTitle==""){ftSizeTitle="14pt"}
if(ftSizeSubTitle==""){ftSizeSubTitle="12pt"}
if(ftSizeLabel==""){ftSizeLabel="10pt"}
if(ftSizeInPut==""){ftSizeInPut="10pt"}
if(ftSizeP==""){ftSizeP="10pt"}
if(ftSizeTH==""){ftSizeTH="8pt"}
if(ftSizeTD==""){ftSizeTD="8pt"}
fillSelectFontSize("selPrintOptionFtSzTitle",1,ftSizeTitle);fillSelectFontSize("selPrintOptionFtSzSubtitle",1,ftSizeSubTitle);fillSelectFontSize("selPrintOptionFtSzLabel",1,ftSizeLabel);fillSelectFontSize("selPrintOptionFtSzForm",1,ftSizeInPut);fillSelectFontSize("selPrintOptionFtSzParagraph",1,ftSizeP);fillSelectFontSize("selPrintOptionFtSzTableHeader",1,ftSizeTH);fillSelectFontSize("selPrintOptionFtSzTableCell",1,ftSizeTD)}
function printOptionPrint(){hideParts('divPrintOptions');const lbTitle=document.getElementById('lbPrintHeaderDocumentTitle');const lbSubTitle=document.getElementById('lbPrintHeaderDocumentSubTitle');const divVisa=document.getElementById('divPrintHeaderVisaBox');const divSignature1=document.getElementById('divPrintFooterSignatureBox1');const divSignature2=document.getElementById('divPrintFooterSignatureBox2');const divSignature3=document.getElementById('divPrintFooterSignatureBox3');var title=document.getElementById('txtPrintOptionTitle').value.trim();var subTitle=document.getElementById('txtPrintOptionSubtitle').value.trim();var visaQuality=document.getElementById('txtPrintOptionVisaQuality').value.trim();var visaPerson=document.getElementById('txtPrintOptionVisaPerson').value.trim();var signatureQuality1=document.getElementById('txtPrintOptionSignatureQuality1').value.trim();var signaturePerson1=document.getElementById('txtPrintOptionSignaturePerson1').value.trim();var signatureQuality2=document.getElementById('txtPrintOptionSignatureQuality2').value.trim();var signaturePerson2=document.getElementById('txtPrintOptionSignaturePerson2').value.trim();var signatureQuality3=document.getElementById('txtPrintOptionSignatureQuality3').value.trim();var signaturePerson3=document.getElementById('txtPrintOptionSignaturePerson3').value.trim();setPrintOptionFontSize();if(title==""){hideParts(lbTitle.id)}else{showParts(lbTitle.id);lbTitle.innerHTML=title}
if(subTitle==""){hideParts(lbSubTitle.id)}else{showParts(lbSubTitle.id);lbSubTitle.innerHTML=subTitle}
if((visaQuality!="")&&(visaPerson!="")){showParts(divVisa.id);document.getElementById('lbPrintHeaderVisaQuality').innerHTML=visaQuality;document.getElementById('lbPrintHeaderVisaPerson').innerHTML=visaPerson}else{hideParts(divVisa.id)}
if((signatureQuality1!="")&&(signaturePerson1!="")){showParts(divSignature1.id);document.getElementById('lbPrintFooterSignatureQuality1').innerHTML=signatureQuality1;document.getElementById('lbPrintFooterSignaturePerson1').innerHTML=signaturePerson1}else{hideParts(divSignature1.id)}
if((signatureQuality2!="")&&(signaturePerson2!="")){showParts(divSignature2.id);document.getElementById('lbPrintFooterSignatureQuality2').innerHTML=signatureQuality2;document.getElementById('lbPrintFooterSignaturePerson2').innerHTML=signaturePerson2}else{hideParts(divSignature2.id)}
if((signatureQuality3!="")&&(signaturePerson3!="")){showParts(divSignature3.id);document.getElementById('lbPrintFooterSignatureQuality3').innerHTML=signatureQuality3;document.getElementById('lbPrintFooterSignaturePerson3').innerHTML=signaturePerson3}else{hideParts(divSignature3.id)}
printOptionSaveSignature();var pageTitle=document.title;document.title="Processado pelo GME Sílica RH.";window.print();document.title=pageTitle}
function setPrintOptionFontSize(){var comb="-"+ST_SRH_MAIN_WHO_CALL+"-"+SYSTEM_USER_STATUS.userId;var r=document.querySelector(':root');$(".print-font-size").each(function(){var cssRoot=this.getAttribute("css-root");var elmId=this.getAttribute("id");var cname=elmId+comb;var cvalue=$(this).val();setCookie(cname,cvalue,3000000);r.style.setProperty(cssRoot,cvalue)})}
function invoiceDucumentSerie(docType,request=10){var year=new Date().getFullYear();var companyId=SYSTEM_USER_STATUS.companyId;var dependencyId=SYSTEM_USER_STATUS.workplaceId;if((isNaN(dependencyId))||Number(dependencyId)<=0){dependencyId=""}
return wordToNumberPitagoras(docType)+request+companyId+dependencyId+year.toString()}
function getLoginStatus(){if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();FILTER.frc=0;const urlParams=new URLSearchParams(window.location.search);if(urlParams.has('frc')){FILTER.frc=urlParams.get('frc')}
var http=new XMLHttpRequest();var params="action=getLoginStatus"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_LOGIN_STATUS_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){setSystemUserStatus()}};http.send(params);setCookie(ST_SRH_MAIN_LAST_PAGE_CNAME,window.location.pathname.toString().split("app/")[1])}
var SYSTEM_USER_STATUS={systemtype:1,companyId:-1,officialpartnerid:-1,registerpartnerid:-1,taxGroup:1,userId:-1,email:"",userFullName:"",billingprofile:1,coordinatorUser:-1,managerUser:-1,directorGeneralUser:-1,administratorUser:-1,partnershipUser:1,udaoxuser:0,permissionlevel:-1,workplaceId:-1,billingStockId:-1,dependecyName:"",municipalityId:-1,municipalityName:"",provinceId:-1,provinceName:"",employeeId:-1};var SYSTEM_USER_PERMISSION={};var LICENSE_STATUS={status:0,type:"",duration:0,startdate:"",enddate:"",selfdomain:0,maxusers:0,maxproducts:0,maxinvoices:0,saleamount:0,salepercentage:0,licenselevel:1,currentUsers:0,currentInvoices:0,currentAmount:0};function setSystemUserStatus(){if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();FILTER.pagepermission=ST_SRH_MAIN_PAGE_PERMISSION;var phttp=new XMLHttpRequest();var params="action=getPermissionInfo"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_LOGIN_STATUS_X;phttp.open('POST',url,!0);phttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');phttp.onreadystatechange=function(){if(phttp.readyState==4&&phttp.status==200){var PAGE_PERMISSION=phttp.responseText;if(PAGE_PERMISSION==1){var uhttp=new XMLHttpRequest();var params="action=getSystemUserInfo"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_LOGIN_STATUS_X;uhttp.open('POST',url,!0);uhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');uhttp.onreadystatechange=function(){if(uhttp.readyState==4&&uhttp.status==200){try{var infoData=JSON.parse(uhttp.responseText)}catch(e){showHttpResponseText(uhttp)}
SYSTEM_USER_STATUS.companyId=infoData.companyid;SYSTEM_USER_STATUS.officialpartnerid=infoData.officialpartnerid;SYSTEM_USER_STATUS.userId=infoData.userid;SYSTEM_USER_STATUS.email=infoData.email;SYSTEM_USER_STATUS.userFullName=infoData.userfullname;SYSTEM_USER_STATUS.billingprofile=Number(infoData.billingprofile);SYSTEM_USER_STATUS.coordinatorUser=(infoData.coordinatoruser!=-1)?infoData.coordinatoruser:SYSTEM_USER_STATUS.userId;SYSTEM_USER_STATUS.managerUser=(infoData.manageruser!=-1)?infoData.manageruser:SYSTEM_USER_STATUS.userId;SYSTEM_USER_STATUS.directorGeneralUser=(infoData.directorgeneraluser!=-1)?infoData.directorgeneraluser:SYSTEM_USER_STATUS.userId;SYSTEM_USER_STATUS.administratorUser=(infoData.administratoruser!=-1)?infoData.administratoruser:SYSTEM_USER_STATUS.userId;SYSTEM_USER_STATUS.partnershipUser=infoData.partnershipuser;SYSTEM_USER_STATUS.udaoxuser=infoData.udaoxuser;SYSTEM_USER_STATUS.permissionlevel=infoData.permissionlevel;SYSTEM_USER_STATUS.workplaceId=infoData.workplaceid;SYSTEM_USER_STATUS.billingStockId=infoData.billingStockId;SYSTEM_USER_STATUS.dependecyName=infoData.dependency;SYSTEM_USER_STATUS.municipalityId=infoData.municipalityid;SYSTEM_USER_STATUS.municipalityName=infoData.municipalityname;SYSTEM_USER_STATUS.provinceId=infoData.provinceid;SYSTEM_USER_STATUS.provinceName=infoData.provinceName;SYSTEM_USER_STATUS.employeeId=infoData.employeeid;SYSTEM_USER_PERMISSION=infoData.userPermissions;LOCK_WINDOWS_TIME=Number(infoData.lockwindowstime);if(infoData.accountstatus!=1){alert("Conta de utilizador desactivada. <br>"+"Por favor contactar o administrador do sistema.");setTimeout(function(){window.location.href="../../"},3000)}
setElementInnerHtml('lbHeaderUserFullname',SYSTEM_USER_STATUS.userFullName);setElementInnerHtml('lbHeaderUserFullname2',SYSTEM_USER_STATUS.userFullName);document.getElementById('imgHeaderUserLogedPhoto').src=urlRepositoryReplace(infoData.photo);if(infoData.needconfirmemail==1){showParts('btHeaderConfirmEmail')}
if(SYSTEM_USER_STATUS.companyId==5000){showParts('btHeaderPromotionSilica')}
licenseValidation();silivaUniverseMenuConstructor();menuConstructor();menuConstructor(ST_SRH_MAIN_PAGE_PERMISSION.slice(0,2));var http=new XMLHttpRequest();var params="action=getCompanyInfo"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_LOGIN_STATUS_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){try{var infoData=JSON.parse(http.responseText)}catch(e){showHttpResponseText(http)}
SYSTEM_USER_STATUS.taxGroup=infoData.ivagroup;SYSTEM_USER_STATUS.systemtype=infoData.systemtype;SYSTEM_USER_STATUS.registerpartnerid=infoData.registerpartnerid;document.getElementById('imgMainFooterCompanyLogo').src=urlRepositoryReplace(infoData.photo);setElementInnerHtml('lbHearderCompanyName',infoData.companyname);setElementInnerHtml('lbHeaderCompanyTaxId',"NIF: "+infoData.companytaxid.bold());setElementInnerHtml('lbHeaderCompanyNus',"N.U.S: "+SYSTEM_USER_STATUS.companyId.bold());setElementInnerHtml('lbHeaderCompanyIVA',"IVA: "+regimeIva(SYSTEM_USER_STATUS.taxGroup).bold());setElementInnerHtml('lbHeaderDependency',"Filial: "+SYSTEM_USER_STATUS.dependecyName);setPartnerInfo(infoData.partnerInfo)}};http.send(params)}};uhttp.send(params)}else if((PAGE_PERMISSION==-1)||(PAGE_PERMISSION==-2)){setTimeout(function(){window.location.href="../../"},2000);showNotification("Precisar fazer login.",0)}else if(PAGE_PERMISSION==0){setTimeout(function(){window.location.href="../home/home"},1000);showNotification("Não tem permissão para acessar esta página.",0)}}};phttp.send(params)}
function licenseValidation(){if(!desktopSecurityCheck()){return!1}
console.log("Validating license...");var http=new XMLHttpRequest();var params="action=getCompanyLicenseStatus"+"&filterInfo="+JSON.stringify(setFilterStatus());var url=URL_SRH_LOGIN_STATUS_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){var lic=JSON.parse(http.responseText);if(lic.status==1){console.log("Licença válida!");LICENSE_STATUS.status=lic.status;LICENSE_STATUS.type=lic.designation;LICENSE_STATUS.duration=lic.duration;LICENSE_STATUS.startdate=lic.startdate;LICENSE_STATUS.enddate=lic.enddate;LICENSE_STATUS.selfdomain=lic.selfdomain;LICENSE_STATUS.maxusers=lic.maxusers;LICENSE_STATUS.maxproducts=lic.maxproducts;LICENSE_STATUS.maxinvoices=lic.maxinvoices;LICENSE_STATUS.saleamount=lic.saleamount;LICENSE_STATUS.salepercentage=lic.salepercentage;LICENSE_STATUS.licenselevel=lic.licenselevel;LICENSE_STATUS.currentUsers=lic.currentUsers;LICENSE_STATUS.currentInvoices=lic.currentInvoices;LICENSE_STATUS.currentAmount=lic.currentAmount;if(getDesktopStatus()){LICENSE_STATUS.serverposition=lic.serverposition}else{LICENSE_STATUS.serverposition=-1}}}
setElementInnerHtml('lbHeaderLicenseStatus',"Licença: "+LICENSE_STATUS.type.bold()+". <br>"+"Data de activação: "+LICENSE_STATUS.startdate.bold()+" <br>"+"Data de validade: "+LICENSE_STATUS.enddate.bold());if(SYSTEM_USER_STATUS.billingprofile<BILLING_PROFILE_PARTNER_INDEX){hideParts("lbHeaderLicenseStatus")}};http.send(params)}
var PAGE_VALIDATION_START=0;var PAGE_VALIDATION_ERROR=0;var PAGE_VALIDATION_END=0;function checkUserStatusAfterExecute(funcao,isPOS=!1){var TIME_TO_REPEAT=250;callValidation();function callValidation(){TIME_TO_REPEAT+=250;if((PAGE_VALIDATION_START==0)||(PAGE_VALIDATION_ERROR==1)){startValidation()}else if(PAGE_VALIDATION_END==1){callback()}else{setTimeout(function(){callValidation()},TIME_TO_REPEAT)}}
function startValidation(){showNotification("Verificando estado do utilizador...");if(!desktopSecurityCheck()){return!1}
PAGE_VALIDATION_START=1;var FILTER=setFilterStatus();FILTER.pagepermission=ST_SRH_MAIN_PAGE_PERMISSION;FILTER.frc=0;const urlParams=new URLSearchParams(window.location.search);if(urlParams.has('frc')){FILTER.frc=urlParams.get('frc')}
var http=new XMLHttpRequest();var params="action=getLoginStatus"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_LOGIN_STATUS_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){try{var response=validateSession(http);let pagePermission=response.pagePermission;if(pagePermission.status==1){console.log("Validando utilizador...");let infoData=response.systemUser;SYSTEM_USER_STATUS.companyId=infoData.companyid;SYSTEM_USER_STATUS.officialpartnerid=infoData.officialpartnerid;SYSTEM_USER_STATUS.userId=infoData.userid;SYSTEM_USER_STATUS.email=infoData.email;SYSTEM_USER_STATUS.userFullName=infoData.userfullname;SYSTEM_USER_STATUS.billingprofile=Number(infoData.billingprofile);SYSTEM_USER_STATUS.coordinatorUser=(infoData.coordinatoruser!=-1)?infoData.coordinatoruser:SYSTEM_USER_STATUS.userId;SYSTEM_USER_STATUS.managerUser=(infoData.manageruser!=-1)?infoData.manageruser:SYSTEM_USER_STATUS.userId;SYSTEM_USER_STATUS.directorGeneralUser=(infoData.directorgeneraluser!=-1)?infoData.directorgeneraluser:SYSTEM_USER_STATUS.userId;SYSTEM_USER_STATUS.administratorUser=(infoData.administratoruser!=-1)?infoData.administratoruser:SYSTEM_USER_STATUS.userId;SYSTEM_USER_STATUS.partnershipUser=infoData.partnershipuser;SYSTEM_USER_STATUS.udaoxuser=infoData.udaoxuser;SYSTEM_USER_STATUS.permissionlevel=infoData.permissionlevel;SYSTEM_USER_STATUS.workplaceId=infoData.workplaceid;SYSTEM_USER_STATUS.billingStockId=infoData.billingStockId;SYSTEM_USER_STATUS.dependecyName=infoData.dependency;SYSTEM_USER_STATUS.municipalityId=infoData.municipalityid;SYSTEM_USER_STATUS.municipalityName=infoData.municipalityname;SYSTEM_USER_STATUS.provinceId=infoData.provinceid;SYSTEM_USER_STATUS.provinceName=infoData.provinceName;SYSTEM_USER_STATUS.employeeId=infoData.employeeid;SYSTEM_USER_STATUS.sessionposition=infoData.sessionposition;SYSTEM_USER_PERMISSION=infoData.userPermissions;LOCK_WINDOWS_TIME=Number(infoData.lockwindowstime);if(infoData.accountstatus!=1){alert("Conta de utilizador desactivada. <br>"+"Por favor contactar o administrador do sistema.");setTimeout(function(){window.location.href="../../"},3000)}
setElementInnerHtml('lbHeaderUserFullname',SYSTEM_USER_STATUS.userFullName);setElementInnerHtml('lbHeaderUserFullname2',SYSTEM_USER_STATUS.userFullName);document.getElementById('imgHeaderUserLogedPhoto').src=urlRepositoryReplace(infoData.photo);if(infoData.needconfirmemail==1){showParts('btHeaderConfirmEmail')}
if(SYSTEM_USER_STATUS.companyId==5000){showParts('btHeaderPromotionSilica')}
var url=new URL(window.location.href);url.searchParams.set('companyId',SYSTEM_USER_STATUS.companyId);updateCurrentUrlWithouRelaod(url);showNotification("Validando a licença...");console.log("Validando a licença...");var lic=response.licenseInfo;if(lic.status==1){console.log("Licença válida");LICENSE_STATUS.status=lic.status;LICENSE_STATUS.type=lic.designation;LICENSE_STATUS.duration=lic.duration;LICENSE_STATUS.startdate=lic.startdate;LICENSE_STATUS.enddate=lic.enddate;LICENSE_STATUS.selfdomain=lic.selfdomain;LICENSE_STATUS.maxusers=lic.maxusers;LICENSE_STATUS.maxproducts=lic.maxproducts;LICENSE_STATUS.maxinvoices=lic.maxinvoices;LICENSE_STATUS.saleamount=lic.saleamount;LICENSE_STATUS.salepercentage=lic.salepercentage;LICENSE_STATUS.licenselevel=lic.licenselevel;LICENSE_STATUS.currentUsers=lic.currentUsers;LICENSE_STATUS.currentInvoices=lic.currentInvoices;LICENSE_STATUS.currentAmount=lic.currentAmount;if(getDesktopStatus()){LICENSE_STATUS.serverposition=lic.serverposition}else{LICENSE_STATUS.serverposition=-1}}else{console.log("Não foi encontrada uma licença válida.");showParts('divAlertNoLicense');hideNotification()}
setElementInnerHtml('lbHeaderLicenseStatus',"Licença: "+LICENSE_STATUS.type.bold()+". <br>"+"Data de activação: "+LICENSE_STATUS.startdate.bold()+" <br>"+"Data de validade: "+LICENSE_STATUS.enddate.bold());if(SYSTEM_USER_STATUS.billingprofile<BILLING_PROFILE_MANAGER_INDEX){hideParts("lbHeaderLicenseStatus")}
showNotification();silivaUniverseMenuConstructor();menuConstructor();menuConstructor(ST_SRH_MAIN_PAGE_PERMISSION.slice(0,2));showNotification("Validando a instituição...");console.log("Validando a instituição...");infoData=response.companyInfo;QUICK_SETTING_DATA.companyInfo=infoData;SYSTEM_USER_STATUS.taxGroup=infoData.ivagroup;SYSTEM_USER_STATUS.systemtype=infoData.systemtype;SYSTEM_USER_STATUS.companyName=infoData.companyname;SYSTEM_USER_STATUS.registerpartnerid=infoData.registerpartnerid;document.getElementById('imgMainFooterCompanyLogo').src=urlRepositoryReplace(infoData.photo);setElementInnerHtml('lbHearderCompanyName',infoData.companyname);setElementInnerHtml('lbHeaderCompanyTaxId',"NIF: "+infoData.companytaxid.bold());setElementInnerHtml('lbHeaderCompanyNus',"N.U.S: "+SYSTEM_USER_STATUS.companyId.bold());setElementInnerHtml('lbHeaderCompanyIVA',"IVA: "+regimeIva(SYSTEM_USER_STATUS.taxGroup).bold());setElementInnerHtml('lbHeaderDependency',"Filial: "+SYSTEM_USER_STATUS.dependecyName);setPartnerInfo(infoData.partnerInfo);PAGE_VALIDATION_END=1;console.log("Validações iniciais com sucesso");callback()}else{showNotification(pagePermission.msg,0);if(pagePermission.status==0){setTimeout(function(){window.location.href="../home/home"},2000)}else{setTimeout(function(){window.location.href="../../"},2000)}}}catch(e){PAGE_VALIDATION_ERROR=1;console.log(e);showNotification("Carregamento da página com erro.",0)}}};http.send(params)}
function callback(){showNotification("Falta pouco...");mainHeaderConstructorPrintHeader();qsettLoadPopup();sessionPageVisited();getAllSelects();changeIframePort();funcao();sessionStorage.setItem("last-maibody-move",new Date());setSessionTimeOut();mainBodyOnMouseMove();setDivFieldsetLegend();setPrintTableOption();setHorizintalScrollButton();ST_SRH_WAITING_SERVER=0;showNotification("Página carregada com sucesso",1);console.log("Full page load")}}
function checkPermission(permission){if(SYSTEM_USER_PERMISSION.length<=0){return!1}else{permission="p"+permission;if(permission in SYSTEM_USER_PERMISSION){return!!+SYSTEM_USER_PERMISSION[permission]}else{return!1}}}
function mainBodyOnMouseMove(){var body=document.getElementById("divFullBodyId");body.addEventListener('mousemove',()=>{sessionStorage.setItem("last-maibody-move",new Date());hideParts("lbHeaderSessionTime")});body.addEventListener('keypress',()=>{body.dispatchEvent(new Event('mousemove'))});body.addEventListener('click',()=>{body.dispatchEvent(new Event('mousemove'))})}
var LOCK_WINDOWS_TIME=5;function setSessionTimeOut(){var maxSecond=(LOCK_WINDOWS_TIME*60)+1;var lbSessionTime=document.getElementById('lbHeaderSessionTime');lbSessionTime.style.animation="";lbSessionTime.style.fontSize="small";lbSessionTime.style.fontWeight="normal";const sessionTimeOutInterval=setInterval(function(){displayTime()},1000);function displayTime(){if(sessionStorage.getItem("sms_lockwindows")==1){clearInterval(sessionTimeOutInterval);lockWindowShow();return!1}else{var now=new Date();var last=new Date(sessionStorage.getItem("last-maibody-move"));var dif=now.getTime()-last.getTime();dif=dif/1000;if(validateUserControl(lbSessionTime)){var timeToClose=maxSecond-dif;lbSessionTime.innerHTML=sec2time(timeToClose);if(Math.floor(timeToClose)==60){lbSessionTime.style.fontSize="large";lbSessionTime.style.fontWeight="bold";showParts(lbSessionTime.id)}else if(Math.floor(timeToClose)==30){lbSessionTime.style.animation="blink-text 1.0s step-end infinite";showParts(lbSessionTime.id)}else if(Math.floor(timeToClose)<=0){clearInterval(sessionTimeOutInterval);lockWindowShow();return!1}}}}}
function setSystemType(a){SYSTEM_TYPES=[];SYSTEM_TYPES[1]="Genérico";SYSTEM_TYPES[2]="Uso doméstico";SYSTEM_TYPES[3]="Gestor de mercado informal";SYSTEM_TYPES[4]="Gestor de condomínio"}
function setDocumentType(a){DOCUMENT_TYPE=[];DOCUMENT_TYPE.FT="FACTURA";DOCUMENT_TYPE.FR="FACTURA RECIBO";DOCUMENT_TYPE.VD="VENDA A DINHEIRO";DOCUMENT_TYPE.RC="RECIBO";DOCUMENT_TYPE.RE="RECIBO";DOCUMENT_TYPE.RG="RECIBO";DOCUMENT_TYPE.PP="PROFORMA";DOCUMENT_TYPE.ND="NOTA DE DÉBITO";DOCUMENT_TYPE.NC="NOTA DE CRÉDITO";DOCUMENT_TYPE.DC="DOC. CONFERÊNCIA";DOCUMENT_TYPE.GR="GUIA DE REMESSA";DOCUMENT_TYPE.GA="MOVIMENTAÇÃO";DOCUMENT_TYPE.NA="ADIANTAMENTO";DOCUMENT_TYPE.GE="GUIA DE ENTRADA";DOCUMENT_TYPE.GF="FACTURA GENÉRICA";DOCUMENT_TYPE.FG="FACTURA GLOBAL";DOCUMENT_TYPE.AC="AVISO DE COBRANÇA";DOCUMENT_TYPE.AR="AVISO DE COBRANÇA/RECIBO";DOCUMENT_TYPE.AF="FACTURA / RECIBO (autofacturação)";DOCUMENT_TYPE.TV="TALÃO DE VENDA";DOCUMENT_TYPE.TS="TALÃO DE SERVIÇO PRESTADO";DOCUMENT_TYPE.TD="TALÃO DE DEVOLUÇÃO";DOCUMENT_TYPE.AA="ALIENAÇÃO DE ACTIVOS";DOCUMENT_TYPE.DA="DEVOLUÇÃO DE ACTIVOS";DOCUMENT_TYPE.GT="GUIA DE TRANSPORTE";DOCUMENT_TYPE.GC="GUIA DE CONCIGNAÇÃO";DOCUMENT_TYPE.GD="GUIA DE DEVOLUÇÃO";DOCUMENT_TYPE.CM="CONSULTA DE MESA";DOCUMENT_TYPE.CC="CRÉDITO DE CONSIGNAÇÃO";DOCUMENT_TYPE.NR="NOTA DE REMESSA";DOCUMENT_TYPE.FO="FOLHA DE OBRA";DOCUMENT_TYPE.NE="NOTA DE ENCOMENDA";DOCUMENT_TYPE.OR="ORÇAMENTO";DOCUMENT_TYPE.CI="CONSUMO INTERNO";DOCUMENT_TYPE.AE="ABATE DE ESTOQUE"}
function setMovimentTargetType(a){MOVIMENT_TARGET_TYPE=[];MOVIMENT_TARGET_TYPE[1]=GLOBAL_DICTIONARY.customer+" com factura";MOVIMENT_TARGET_TYPE[2]=GLOBAL_DICTIONARY.customer+" sem factura";MOVIMENT_TARGET_TYPE[3]="Movimento entre depedências (posto)";MOVIMENT_TARGET_TYPE[4]="Movimento Interno";MOVIMENT_TARGET_TYPE[5]="Consumo Interno";MOVIMENT_TARGET_TYPE[6]="Abate de estoque";MOVIMENT_TARGET_TYPE[7]="Devolução ao fornecedor"}
class _paymentMechanism{constructor(id,mechanism="",short="",shortplus="",initials=""){this.id=id;this.mechanism=mechanism;this.short=short;this.shortplus=shortplus;this.initials=initials}};function setPaymentMechanism(a){PAYMENT_MECHANISM=[];PAYMENT_MECHANISM[1]=new _paymentMechanism(1,'Numerário','Numerário','','NU');PAYMENT_MECHANISM[2]=new _paymentMechanism(2,'Terminal de Pagamento Automático','TPA','Per:Tr:M:','CD');PAYMENT_MECHANISM[3]=new _paymentMechanism(3,'Depósito Bancário','Depósito','Bordx','TB');PAYMENT_MECHANISM[4]=new _paymentMechanism(4,'Transferência Bancária','Transferência','','TB');PAYMENT_MECHANISM[5]=new _paymentMechanism(5,'Compensação de Saldo em Conta Corrente','Conta Corrente','','CS');PAYMENT_MECHANISM[6]=new _paymentMechanism(6,'Referencia de Pagamento para Multicaixa','Ref.Multicaixa','Ref','MB');PAYMENT_MECHANISM[7]=new _paymentMechanism(7,'Cartão de Crédito','C. Crédito','Ref','CC');PAYMENT_MECHANISM[8]=new _paymentMechanism(8,'Cheque Bancário','Cheque','Nº','CH');PAYMENT_MECHANISM[9]=new _paymentMechanism(9,'Dinheiro Electrónico','DE','','DE');PAYMENT_MECHANISM[10]=new _paymentMechanism(10,'Outro','Outro','','OU');PAYMENT_MECHANISM[11]=new _paymentMechanism(11,'Código QR','QR','','TB');PAYMENT_MECHANISM[12]=new _paymentMechanism(12,'PIX','PIX','','TB');PAYMENT_MECHANISM[100]=new _paymentMechanism(100,'Troco','Troco','','TR')}
function setInstallmentStatus(a){INSTALLMENT_STATUS=[];INSTALLMENT_STATUS.AP='Aguarda pagamento';INSTALLMENT_STATUS.PP='Pagamento parcial';INSTALLMENT_STATUS.PT='Pagamento total'}
function setDocumentRequestSource(a){DOCUMENT_REQUEST_SOURCE=[];DOCUMENT_REQUEST_SOURCE[10]="Presencial";DOCUMENT_REQUEST_SOURCE[15]="Cartão digital";DOCUMENT_REQUEST_SOURCE[20]="Online"}
function setCustomerType(a){CUSTOMER_TYPE=[];CUSTOMER_TYPE[0]="Por indicar.";CUSTOMER_TYPE[1]="Pessoa Singular";CUSTOMER_TYPE[2]="Profissional Autónomo";CUSTOMER_TYPE[3]="Sociedade Unipessoal (SU)";CUSTOMER_TYPE[4]="Empresa em nome individual";CUSTOMER_TYPE[5]="Sociedade por quota (Lda)";CUSTOMER_TYPE[6]="Sociedade Anónima (S.A.)";CUSTOMER_TYPE[7]="Empresa Pública (EP)";CUSTOMER_TYPE[8]="Instituto Público";CUSTOMER_TYPE[9]="Instituto Pmpresarial";CUSTOMER_TYPE[10]="Cooperativa";CUSTOMER_TYPE[11]="Organização Sindical";CUSTOMER_TYPE[12]="Organização Não Governamental (ONG)";CUSTOMER_TYPE[13]="Organização Religiosa";CUSTOMER_TYPE[14]="Organização da Sociedade Civil";CUSTOMER_TYPE[15]="Associação";CUSTOMER_TYPE[16]="Fundação"}
var BILLING_PROFILE_SELLER_INDEX=1;var BILLING_PROFILE_MANAGER_INDEX=10;var BILLING_PROFILE_DEPARTMENT_BOSS_INDEX=15;var BILLING_PROFILE_PARTNER_INDEX=20;var LICENSE_TYPE_STATUS=[];function setLicenseStatus(a){LICENSE_TYPE_STATUS=[];LICENSE_TYPE_STATUS[-1]="Suspensa";LICENSE_TYPE_STATUS[0]="Expirada";LICENSE_TYPE_STATUS[1]="Activa";LICENSE_TYPE_STATUS[2]="Em espera"}
function setSystemUserBillingProfile(){SYSTEM_USER_BILLING_PROFILE=[];SYSTEM_USER_BILLING_PROFILE[0]="Agente";SYSTEM_USER_BILLING_PROFILE[BILLING_PROFILE_SELLER_INDEX]="Operador (Vendedor)";SYSTEM_USER_BILLING_PROFILE[BILLING_PROFILE_MANAGER_INDEX]="Gerente / Superisor (Filial)";SYSTEM_USER_BILLING_PROFILE[BILLING_PROFILE_DEPARTMENT_BOSS_INDEX]="Gerente / Superisor (Todas Filiais)";SYSTEM_USER_BILLING_PROFILE[BILLING_PROFILE_PARTNER_INDEX]="Administrador (Sócio)";SYSTEM_USER_TITLE=[];SYSTEM_USER_TITLE['1']='Sr.';SYSTEM_USER_TITLE['2']='Sra.';SYSTEM_USER_TITLE['3']='Lic.';SYSTEM_USER_TITLE['4']='Dr.';SYSTEM_USER_TITLE['5']='Dra.';SYSTEM_USER_TITLE['6']='Msc.';SYSTEM_USER_TITLE['7']='PhD.'}
function setProductChargeType(a){PRODUCT_CHARGE_TYPES=[];PRODUCT_CHARGE_TYPES[1]="Padrão";PRODUCT_CHARGE_TYPES[2]="Diária";PRODUCT_CHARGE_TYPES[3]="Mensal";PRODUCT_CHARGE_TYPES[4]="Anual";PRODUCT_CHARGE_SEQUENCES=[];PRODUCT_CHARGE_SEQUENCES[1]="Padrão";PRODUCT_CHARGE_SEQUENCES[2]="Sem sequência";PRODUCT_CHARGE_SEQUENCES[3]="Sequência obrigatória";PRODUCT_INSTALLMENT_INDICATORS=[];PRODUCT_INSTALLMENT_INDICATORS[1]="Padrão";PRODUCT_INSTALLMENT_INDICATORS[2]="Automático";PRODUCT_INSTALLMENT_INDICATORS[3]="Manual"}
function identificationDocumentList(){var docList=[];docList[0]="BILHETE DE IDENTIDADE";docList[1]="PASSAPORTE";docList[2]="CARTÃO DE RESIDENTE";docList[3]="OUTRO";return docList}
function pointControlWorkDayStatus(status=-1){status=Number(status);var statusList=[];statusList[1]="";statusList[2]="Feriado";statusList[3]="Dispensa";statusList[4]="Férias";statusList[5]="Deslocação em serviço";if(status==-1){return statusList}else{return statusList[status]}}
function pointControlFaultStatus(status=-1){status=Number(status);var statusList=[];statusList[0]="";statusList[1]="Falta";statusList[2]="Falta Justificada";statusList[3]="Falta Anulada";if(status==-1){return statusList}else{return statusList[status]}}
function pointControlDelayStatus(status=-1){status=Number(status);var statusList=[];statusList[0]="";statusList[1]="Atraso";statusList[2]="Atraso Justificado";statusList[3]="Atraso Anulado";if(status==-1){return statusList}else{return statusList[status]}}
function academicDegreeList(){var docList=[];docList[0]={level:1,description:"Ensino Primário"};docList[1]={level:2,description:"Ensino Secundário"};docList[2]={level:3,description:"Ensino Técnico-Profissional"};docList[3]={level:4,description:"Licenciatura"};docList[4]={level:5,description:"Pós-graduação"};docList[5]={level:6,description:"Mestrado"};docList[6]={level:7,description:"Doutoramento"};return docList}
function monthName(month){var mName=[];mName[0]="Janeiro";mName[1]="Fevereiro";mName[2]="Março";mName[3]="Abril";mName[4]="Maio";mName[5]="Junho";mName[6]="Julho";mName[7]="Agosto";mName[8]="Setembro";mName[9]="Outubro";mName[10]="Novembro";mName[11]="Dezembro";return mName[month]}
function weekDay(day,short=0){var wday=new Array(7);wday[0]=["Domingo","Dom"];wday[1]=["Segunda-feira","Seg"];wday[2]=["Terça-feira","Ter"];wday[3]=["Quarta-feira","Qua"];wday[4]=["Quinta-feira","Qui"];wday[5]=["Sexta-feira","Sex"];wday[6]=["Sábado","Sáb"];return wday[day][short]}
var SYSTEM_TYPES=[];var DOCUMENT_TYPE=[];var MOVIMENT_TARGET_TYPE=[];var PAYMENT_MECHANISM=[];var INSTALLMENT_STATUS=[];var DOCUMENT_REQUEST_SOURCE=[];var CUSTOMER_TYPE=[];var SYSTEM_USER_BILLING_PROFILE=[];var PRODUCT_CHARGE_TYPES=[];var PRODUCT_CHARGE_SEQUENCES=[];var PRODUCT_INSTALLMENT_INDICATORS=[];var PERIODIC_SERVICE_LIST=[];var CUSTOMER_PERIODIC_SERVICE_LIST=[];var LABEL_EDIT=reviewString(getComputedStyle(document.documentElement).getPropertyValue('--edit'));var LABEL_DETAIL=reviewString(getComputedStyle(document.documentElement).getPropertyValue('--detail'));var LABEL_PRINT=reviewString(getComputedStyle(document.documentElement).getPropertyValue('--print'));var LABEL_DELETE=reviewString(getComputedStyle(document.documentElement).getPropertyValue('--delete'));var LABEL_REMOVE=reviewString(getComputedStyle(document.documentElement).getPropertyValue('--remove'));function setSelectedRowBackground(CookeiName,name){var fromCook=getCookie(CookeiName);if(fromCook==name){return" selected-row"}
return""}
function setSelectedRowOnClick(newRow,cookieName){newRow.classList.add("selected-row");setCookie(cookieName,newRow.id,1400)}
function systemUserAutocomplete(txtAutocomplete){const txtUsers=document.getElementById(txtAutocomplete);if(!validateUserControl(txtUsers)){return!1}
if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();var http=new XMLHttpRequest();var params="action=getSystemUserAutocompleteList"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_SYSTEM_USER_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){var users=this.responseText.split("-/-");autocomplete(txtUsers,users)}};http.send(params)}
function saleReportCreateGraphic(arraySourceData,chartId,chartTitle,chartType){try{google.charts.load('current',{'packages':['corechart']});google.charts.setOnLoadCallback(drawChart);function drawChart(){var data=google.visualization.arrayToDataTable(arraySourceData);var options={title:chartTitle,pieHole:0.4,legend:{position:'left'}};var chart=new google.visualization.PieChart(document.getElementById(chartId));chart.draw(data,options)}}catch(ex){showNotification("Gráfico indispunível, provavelmente por falta de internet,",0)}}
function setAutoCompleteToFiel(txtName,tblFld,needCompanyId=0){const txtDocument=document.getElementById(txtName);if(!validateUserControl(txtDocument)){return!1}
var SS_KEY="@AUTOCOMPLETE_"+SYSTEM_USER_STATUS.companyId+"_"+btoa(tblFld);var OLD_LIST=[];var content=sessionStorage.getItem(SS_KEY);if(content!=null){if(content!=undefined){try{OLD_LIST=JSON.parse(atob(content));if(OLD_LIST.length>0){autocomplete(txtDocument,OLD_LIST)}}catch(e){}}}
txtDocument.addEventListener("input",function(e){var mark=reviewString(this);if(mark!=""){realtAutoComplete(mark)}});function realtAutoComplete(mark){var needRecheck=!0;var content=sessionStorage.getItem(SS_KEY);if(content!=null){if(content!=undefined){try{OLD_LIST=JSON.parse(atob(content));OLD_LIST.forEach(sentense=>{if(sentense.toUpperCase().toString().includes(mark.toUpperCase())){needRecheck=!1}})}catch(e){}}}
if(!needRecheck){autocomplete(txtDocument,OLD_LIST)}else{if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();FILTER.companyId=-1;FILTER.mark=mark;if(needCompanyId!=0){FILTER.companyId=SYSTEM_USER_STATUS.companyId}
FILTER.tblFld=tblFld;var http=new XMLHttpRequest();var params="action=getAutocompleteField"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_CRUD_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){try{var response=validateSession(http);Array.from(response).forEach(sentense=>{OLD_LIST.push(sentense)});sessionStorage.setItem(SS_KEY,btoa(JSON.stringify(OLD_LIST)))
autocomplete(txtDocument,OLD_LIST)}catch(e){}}};http.send(params)}}}
function printOptionSaveSignature(){if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();var visaQuality=document.getElementById('txtPrintOptionVisaQuality').value.trim();var visaPerson=document.getElementById('txtPrintOptionVisaPerson').value.trim();var signatureQuality1=document.getElementById('txtPrintOptionSignatureQuality1').value.trim();var signaturePerson1=document.getElementById('txtPrintOptionSignaturePerson1').value.trim();var signatureQuality2=document.getElementById('txtPrintOptionSignatureQuality2').value.trim();var signaturePerson2=document.getElementById('txtPrintOptionSignaturePerson2').value.trim();var signatureQuality3=document.getElementById('txtPrintOptionSignatureQuality3').value.trim();var signaturePerson3=document.getElementById('txtPrintOptionSignaturePerson3').value.trim();var signatures=[];signatures[0]=({person:visaPerson,quality:visaQuality});signatures[1]=({person:signaturePerson1,quality:signatureQuality1});signatures[2]=({person:signaturePerson2,quality:signatureQuality2});signatures[3]=({person:signaturePerson3,quality:signatureQuality3});var cookiename="printOptionSignature";setCookie(FILTER.companyId+FILTER.dependencyId+cookiename+0,JSON.stringify(signatures[0]),10080);setCookie(FILTER.companyId+FILTER.dependencyId+cookiename+1,JSON.stringify(signatures[1]),10080);setCookie(FILTER.companyId+FILTER.dependencyId+cookiename+2,JSON.stringify(signatures[2]),10080);setCookie(FILTER.companyId+FILTER.dependencyId+cookiename+3,JSON.stringify(signatures[3]),10080);FILTER.signatureInfo=signatures;var http=new XMLHttpRequest();var params="action=savePrintOptionSignature"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_CRUD_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.send(params)}
function printOptionSelectSignatureOnChange(selSign,qualityId,personId){const txtQuality=document.getElementById(qualityId);const txtPerson=document.getElementById(personId);var signature=selSign.value.toString().split("-/-");if(signature.length>=2){txtQuality.value=signature[1];txtPerson.value=signature[0]}else{txtQuality.value="";txtPerson.value=""}}
function wordToNumberPitagoras(word){word=reviewString(word);if(word==""){return""}
var i=0;var result="";for(i=0;i<word.toString().length;i++){result+=letterToNumber(word.substring(i,i+1)).toString()}
return result}
function letterToNumber(letter){letter=letter.toString().toUpperCase();if((letter=="A")||(letter=="J")||(letter=="S")){return 1}
if((letter=="B")||(letter=="K")||(letter=="T")){return 2}
if((letter=="C")||(letter=="L")||(letter=="U")){return 3}
if((letter=="D")||(letter=="M")||(letter=="V")){return 4}
if((letter=="E")||(letter=="N")||(letter=="W")){return 5}
if((letter=="F")||(letter=="O")||(letter=="X")){return 6}
if((letter=="G")||(letter=="P")||(letter=="Y")){return 7}
if((letter=="H")||(letter=="Q")||(letter=="Z")){return 8}
return 9}
var ALERT_TITLE="SÍLICA RH";var ALERT_BUTTON_TEXT="Ok";if(document.getElementById){window.alert=function(txt){createCustomAlert(txt)}}
function createCustomAlert(txt){d=document;if(d.getElementById("modalContainer"))
return;mObj=d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));mObj.id="modalContainer";mObj.style.height=d.documentElement.scrollHeight+"px";alertObj=mObj.appendChild(d.createElement("div"));alertObj.id="alertBox";if(d.all&&!window.opera)
alertObj.style.top=document.documentElement.scrollTop+"px";alertObj.style.left=(d.documentElement.scrollWidth-alertObj.offsetWidth)/2+"px";alertObj.style.visiblity="visible";h1=alertObj.appendChild(d.createElement("h1"));h1.appendChild(d.createTextNode(ALERT_TITLE));msg=alertObj.appendChild(d.createElement("p"));msg.innerHTML=txt;btn=alertObj.appendChild(d.createElement("a"));btn.id="closeBtn";btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));btn.href="#";btn.focus();btn.onclick=function(){removeCustomAlert();return!1};alertObj.style.display="block"}
function removeCustomAlert(){document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"))}
function animateValue(obj,start,end,duration,format=!1,extraLabel=""){if(!validateUserControl(obj)){return!1}
let startTimestamp=null;const step=(timestamp)=>{if(!startTimestamp)
startTimestamp=timestamp;const progress=Math.min((timestamp-startTimestamp)/duration,1);var value=Math.floor(progress*(end-start)+start);if(format){value=formatNumber(value)}
obj.innerHTML=value+extraLabel;if(progress<1){window.requestAnimationFrame(step)}};window.requestAnimationFrame(step)}
function sec2time(timeInSeconds,useHour=!1,useSecond=!0){var pad=function(num,size){return('000'+num).slice(size*-1)},time=parseFloat(timeInSeconds).toFixed(3),hours=Math.floor(time/60/60),minutes=Math.floor(time/60)%60,seconds=Math.floor(time-minutes*60),milliseconds=time.slice(-3);hours=(useHour==!0)?pad(hours,2)+":":"";seconds=(useSecond==!0)?':'+pad(seconds,2):"";return hours+pad(minutes,2)+seconds}
function maskInputByPlaceHold(inputId){const obj=document.getElementById(inputId);if(!validateUserControl(obj)){return!1}
obj.addEventListener('input',()=>{for(const el of document.querySelectorAll("[placeholder][data-slots]")){const pattern=el.getAttribute("placeholder"),slots=new Set(el.dataset.slots||"_"),prev=(j=>Array.from(pattern,(c,i)=>slots.has(c)?j=i+1:j))(0),first=[...pattern].findIndex(c=>slots.has(c)),accept=new RegExp(el.dataset.accept||"\\d","g"),clean=input=>{input=input.match(accept)||[];return Array.from(pattern,c=>input[0]===c||slots.has(c)?input.shift()||c:c)},format=()=>{const[i,j]=[el.selectionStart,el.selectionEnd].map(i=>{i=clean(el.value.slice(0,i)).findIndex(c=>slots.has(c));return i<0?prev[prev.length-1]:back?prev[i-1]||first:i});el.value=clean(el.value).join``;el.setSelectionRange(i,j);back=!1};let back=!1;el.addEventListener("keydown",(e)=>back=e.key==="Backspace");el.addEventListener("input",format);el.addEventListener("focus",format);el.addEventListener("blur",()=>el.value===pattern&&(el.value=""))}})}
function noRequiredShowHide(bt){const demoClasses=document.getElementsByClassName('noRequiredHide');var divsTeste=Array.prototype.filter.call(demoClasses,function(elementoTeste){if(window.getComputedStyle(elementoTeste).display=="none"){elementoTeste.style.display="inline";bt.innerHTML="Ocultar campos não obrigatórios"}else{elementoTeste.style.display="none";bt.innerHTML="Ver campos não obrigatórios"}})}
function getDocumentStatus(status){status=status.toUpperCase();if(status=="A"){return"Anulado"}else if(status=="N"){return"Normal"}else if(status=="AF"){return"Aguarda Facturação"}else if(status=="F"){return"Facturado"}else{return status}}
function hideShortcuts(){if(!checkPermission('0201')){document.getElementById('btShortcutSaleInvoice').style.display="none"}
if(!checkPermission('0204')){document.getElementById('btShortcutSaleWorkdocument').style.display="none"}
if(!checkPermission('0205')){document.getElementById('btShortcutSalePayment').style.display="none"}
if(!checkPermission('0207')){document.getElementById('btShortcutOrder').style.display="none"}
if(!checkPermission('0306')){document.getElementById('btShortcutMoviment').style.display="none"}
if(!checkPermission('0304')){document.getElementById('btShortcutEntrance').style.display="none"}}
function regimeIva(iva){if(Number(iva)<=1){return"Regime de exclusão"}else if(iva==2){return"Regime simplificado."}else{return"Regime geral."}}
function setTriggerButtonByText(txtId,btId){var input=document.getElementById(txtId);var btn=document.getElementById(btId);if(!validateUserControl(input)){return!1}
if(!validateUserControl(btn)){return!1}
input.addEventListener("keyup",function(event){if(event.keyCode===13){event.preventDefault();btn.click()}})}
function setTriggerButtonByRowDobleClick(rowId,btId,coockieName=""){var row=document.getElementById(rowId);var btn=document.getElementById(btId);if(!validateUserControl(row)){return!1}
if(!validateUserControl(btn)){return!1}
row.style.cursor="pointer";row.addEventListener("click",function(event){if(coockieName!=""){setCookie(coockieName,row.id,1400)}
event.preventDefault();btn.click()})}
function setSessionResultSearch(numResultId){const numResult=document.getElementById(numResultId);if(!validateUserControl(numResult)){return!1}
var cookName=SYSTEM_USER_STATUS.userId+numResultId;var initVal=getCookie(cookName);if(initVal!=null){if(initVal!=""){numResult.value=initVal}}
numResult.addEventListener("change",function(){setCookie(cookName,numResult.value,10300)})}
function setLocalDate(inDate,formated=!1){if((inDate==null)||(inDate=="")){return inDate}
var date=new Date(inDate);if(!validateDate(date)){return inDate}
date.setMinutes(date.getMinutes()-date.getTimezoneOffset());if(!formated){return date}else{return date.toISOString().slice(0,formated).replace("T"," ")}}
function addAmountResume(listOf,item,value){if(item!=null){if(item!=""){if(!(item in listOf)){listOf[item]={desigination:item,amount:value}}else{listOf[item].amount=Number(listOf[item].amount)+Number(value)}}}}
function resume(tblResume,nRows,sType,listOf,element,strValue="Valor (AOA)"){if(nRows==1){let rwHd=tblResume.insertRow(-1);rwHd.setAttribute("class","borderGray");let cellType=rwHd.insertCell(-1);cellType.setAttribute("colspan","2");cellType.innerHTML=sType.bold();let cellValue=rwHd.insertCell(-1);cellValue.innerHTML=strValue.bold();cellValue.style.textAlign="right"}
let newRow=tblResume.insertRow(-1);newRow.setAttribute("class","borderGray");let cellRow=newRow.insertCell(-1);cellRow.setAttribute("class","colRowNumber");cellRow.innerHTML=nRows;let cellDesign=newRow.insertCell(-1);cellDesign.innerHTML=listOf[element].desigination;let cellAmount=newRow.insertCell(-1);cellAmount.style.textAlign="right";cellAmount.style.paddingRight="5px";cellAmount.style.whiteSpace="nowrap";cellAmount.innerHTML=formatNumber(listOf[element].amount)}
function invoicePrintA5(printNumber,via=1){window.open("_pdf/SaleDocumentLayoutA5.php?pn="+printNumber+"&v="+via+"&a=0")}
function invoicePrintA4(printNumber,via=1){window.open("_pdf/SaleDocumentLayoutA4.php?pn="+printNumber+"&v="+via+"&a=0")}
function invoicePrintReceipt(printNumber,via=1){window.open("_pdf/SaleDocumentReceipt.php?pn="+printNumber+"&v="+via+"&a=0")}
function invoiceSendByEmail(printNumber,companyName="",documentNumber="Documento",customerName="",emails=""){var remetente="<b>"+companyName+"</b";var invoiceUrl=encodeURIComponent("https://"+getHostName()+"/sw/_pdf/SaleDocumentLayout.php?pn="+printNumber);var content="<p>Caro "+customerName+",</p>"+"<p>Segue a baixo o link de acesso ao documento solicitado.</p>"+"<p><b>"+documentNumber+"</b></p>"+'<a href="'+invoiceUrl+'">Acessar '+documentNumber+'</a>';mailingSend(emails,documentNumber,content,remetente)}
function invoiceSendByWhatsApp(printNumber,documentNumber="Documento",customerName="",phoneNumber=""){var companyName=document.getElementById('lbHearderCompanyName').innerHTML;var invoiceUrl=encodeURIComponent("https://"+getHostName()+"/sw/_pdf/SaleDocumentLayout.php?pn="+printNumber);invoiceUrl=invoiceUrl.replace(" ","%20");var content="*"+companyName+"*%0a%0a"+"*"+documentNumber+"*%0a%0a"+"Caro "+customerName+",%0a"+"Segue a baixo o link de acesso ao documento solicitado. %0a%0a"+"*"+invoiceUrl+"*%0a%0a"+"Grato pela sua visita %0a%0a"+"--------------%0a"+"*Sílica RH* - _Software de Gestão de Recursos Humanos_%0a"+"_www.silicaweb.ao_";window.open("https://wa.me/"+phoneNumber+"/?text="+content)}
function paymentPrintA5(printNumber,via=1){window.open("_pdf/PaymentDocumentLayoutA5.php?pn="+printNumber+"&v="+via+"&a=0")}
function paymentPrintA4(printNumber,via=1){window.open("_pdf/PaymentDocumentLayoutA4.php?pn="+printNumber+"&v="+via+"&a=0")}
function paymentPrintReceipt(printNumber,via=1){window.open("_pdf/PaymentDocumentReceipt.php?pn="+printNumber+"&v="+via+"&a=0")}
function paymentSendByEmail(printNumber,companyName="",documentNumber="Documento",customerName="",emails=""){var remetente="<b>"+companyName+"</b";var invoiceUrl=encodeURIComponent("https://"+getHostName()+"/sw/_pdf/PaymentDocumentLayout.php?pn="+printNumber);var content="<p>Caro"+customerName+",</p>"+"<p>Segue a baixo o link de acesso ao documento solicitado.</p>"+"<p><b>"+documentNumber+"</b></p>"+'<a href="'+invoiceUrl+'">Acessar '+documentNumber+'</a>';mailingSend(emails,documentNumber,content,remetente)}
function paymentSendByWhatsApp(printNumber,documentNumber="Documento",customerName="",phoneNumber=""){var companyName=document.getElementById('lbHearderCompanyName').innerHTML;var invoiceUrl=encodeURIComponent("https://"+getHostName()+"/sw/_pdf/PaymentDocumentLayout.php?pn="+printNumber);invoiceUrl=invoiceUrl.replace(" ","%20");var content="*"+companyName+"*%0a%0a"+"*"+documentNumber+"*%0a%0a"+"Caro "+customerName+",%0a"+"Segue a baixo o link de acesso ao documento solicitado. %0a%0a"+"*"+invoiceUrl+"*%0a%0a"+"Grato pela sua visita %0a%0a"+"--------------%0a"+"*Sílica RH* - _Software de Gestão de Recursos Humanos_%0a"+"_www.silicaweb.ao_";window.open("https://wa.me/"+phoneNumber+"/?text="+content)}
function entrancePrintA5(printNumber,via=1){window.open("_pdf/EntranceDocumentLayoutA5.php?pn="+printNumber+"&v="+via+"&a=0")}
function entrancePrintA4(printNumber,via=1){window.open("_pdf/EntranceDocumentLayoutA4.php?pn="+printNumber+"&v="+via+"&a=0")}
function entrancePrintReceipt(printNumber,via=1){window.open("_pdf/EntranceDocumentReceipt.php?pn="+printNumber+"&v="+via+"&a=0")}
function entranceSendByEmail(printNumber,companyName="",documentNumber="Documento",customerName="",emails=""){var remetente="<b>"+companyName+"</b";var invoiceUrl=encodeURIComponent("https://"+getHostName()+"/sw/_pdf/EntranceDocumentLayout.php?pn="+printNumber);var content="<p>Caro "+customerName+",</p>"+"<p>Segue a baixo o link de acesso ao documento solicitado.</p>"+"<p><b>"+documentNumber+"</b></p>"+'<a href="'+invoiceUrl+'">Acessar '+documentNumber+'</a>';mailingSend(emails,documentNumber,content,remetente)}
function entranceSendByWhatsApp(printNumber,documentNumber="Documento",customerName="",phoneNumber=""){var companyName=document.getElementById('lbHearderCompanyName').innerHTML;var invoiceUrl=encodeURIComponent("https://"+getHostName()+"/sw/_pdf/EntranceDocumentLayout.php?pn="+printNumber);invoiceUrl=invoiceUrl.replace(" ","%20");var content="*"+companyName+"*%0a%0a"+"*"+documentNumber+"*%0a%0a"+"Caro "+customerName+",%0a"+"Segue a baixo o link de acesso ao documento solicitado. %0a%0a"+"*"+invoiceUrl+"*%0a%0a"+"Grato pela sua visita %0a%0a"+"--------------%0a"+"*Sílica RH* - _Software de Gestão de Recursos Humanos_%0a"+"_www.silicaweb.ao_";window.open("https://wa.me/"+phoneNumber+"/?text="+content)}
function movimentPrintA5(printNumber,via=1){window.open("_pdf/MovimentDocumentLayoutA5.php?pn="+printNumber+"&v="+via+"&a=0")}
function movimentPrintA4(printNumber,via=1){window.open("_pdf/MovimentDocumentLayoutA4.php?pn="+printNumber+"&v="+via+"&a=0")}
function movimentPrintReceipt(printNumber,via=1){window.open("_pdf/MovimentDocumentReceipt.php?pn="+printNumber+"&v="+via+"&a=0")}
function movimentSendByEmail(printNumber,companyName="",documentNumber="Documento",customerName="",emails=""){var remetente="<b>"+companyName+"</b";var invoiceUrl=encodeURIComponent("https://"+getHostName()+"/sw/_pdf/MovimentDocumentLayout.php?pn="+printNumber);var content="<p>Caro "+customerName+",</p>"+"<p>Segue a baixo o link de acesso ao documento solicitadi.</p>"+"<p><b>"+documentNumber+"</b></p>"+'<a href="'+invoiceUrl+'">Acessar '+documentNumber+'</a>';mailingSend(emails,documentNumber,content,remetente)}
function movimentSendByWhatsApp(printNumber,documentNumber="Documento",customerName="",phoneNumber=""){var companyName=document.getElementById('lbHearderCompanyName').innerHTML;var invoiceUrl=encodeURIComponent("https://"+getHostName()+"/sw/_pdf/MovimentDocumentLayout.php?pn="+printNumber);invoiceUrl=invoiceUrl.replace(" ","%20");var content="*"+companyName+"*%0a%0a"+"*"+documentNumber+"*%0a%0a"+"Caro "+customerName+",%0a"+"Segue a baixo o link de acesso ao documento solicitado. %0a%0a"+"*"+invoiceUrl+"*%0a%0a"+"Grato pela sua visita %0a%0a"+"--------------%0a"+"*Sílica RH* - _Software de Gestão de Recursos Humanos_%0a"+"_www.silicaweb.ao_";window.open("https://wa.me/"+phoneNumber+"/?text="+content)}
function lockWindowShow(){showParts('divLockWindow');setElementInnerHtml('lbLockWindowUserFullName',SYSTEM_USER_STATUS.userFullName);setElementValue('txtIndPassword',"");document.getElementById('txtIndPassword').focus();setTriggerButtonByText('txtIndPassword','btIndLogin');sessionStorage.setItem("sms_lockwindows",1);var url=new URL(window.location.href);url.searchParams.set('frc','0');const nextTitle=document.title;const nextState={additionalInformation:'Updated the URL with JS'};window.history.pushState(nextState,nextTitle,url);if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();var http=new XMLHttpRequest();var params="action=sessionStatusLock"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_LOGOUT_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(this.readyState==4&&this.status==200){}};http.send(params)}
function lockWindowLogin(){var lbMsg=document.getElementById('lbIndMsgError');lbMsg.innerHTML="";if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();FILTER.st="SRH";FILTER.wc="LOCKWINDOWS";FILTER.username=SYSTEM_USER_STATUS.email;FILTER.pass=getElementValue('txtIndPassword').toString().trim();if(ST_SRH_WAITING_SERVER==1){showNotification("Aguardando resposta do servidor",0);return!1}
showNotification();ST_SRH_WAITING_SERVER=1;var http=new XMLHttpRequest();var params="action=getSystemLogin"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_LOGOUT_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(this.readyState==4&&this.status==200){try{hideNotification();ST_SRH_WAITING_SERVER=0;var response=JSON.parse(http.responseText)}catch(e){showNotification(http)}
if(response.status==1){sessionStorage.setItem(ST_SRH_MAIN_SESSION_CNAME,response.sessionid);sessionStorage.setItem("sms_lockwindows",0);hideParts('divLockWindow');setSessionTimeOut()}else{lbMsg.innerHTML="Email ou palavra passe errada."}}};http.send(params)}
function systemUserLogOut(goToIndex=!0){if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();var http=new XMLHttpRequest();var params="action=logoutUser"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_LOGOUT_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(this.readyState==4&&this.status==200){if(goToIndex){showNotification("Saindo do Sílica RH...",2);setTimeout(function(){window.location.href="../../"},2000)}
sessionStorage.setItem(ST_SRH_MAIN_SESSION_CNAME,"")}};http.send(params)}
function mailingSend(destinatary,subject,contentHtmlStyle,entityRemetent=""){if(!desktopSecurityCheck()){return!1}
var mailInfo={destinatary:destinatary,subject:subject,contentHtmlStyle:contentHtmlStyle,entityRemetent:entityRemetent};var http=new XMLHttpRequest();var params="action=sendMailStandard"+"&mailInfo="+JSON.stringify(mailInfo)+"&filterInfo="+JSON.stringify(setFilterStatus());var url=URL_SRH_CRUD_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){var response=this.responseText;if(response==!0){showNotification("E-mail enviado",1)}else{showNotification("Não foi possível enviar o e-mail.",0)}}};http.send(params)}
function getAllSelects(){var selectors=document.querySelectorAll("select");for(var i=0;i<selectors.length;i++){let sel=selectors[i];sel.addEventListener('input',()=>{sel.title=sel.value});sel.dispatchEvent(new Event('input'))}}
function setSelectValue(selectId,valueToSet=""){var select=document.getElementById(selectId);if(validateUserControl(select)){select.value=valueToSet;select.dispatchEvent(new Event('input'))}}
function dispatchOnInputChange(){var selectors=document.querySelectorAll("select");for(var i=0;i<selectors.length;i++){let sel=selectors[i];sel.dispatchEvent(new Event('input'))}}
function temporaryBackgroundGray(elementId){var element=document.getElementById(elementId);if(validateUserControl(element)){element.style.animation="blink-background-gray 0.7s step-end infinite";setTimeout(function(){element.style.animation=""},3000)}}
function temporaryBorderOrange(elementId){var element=document.getElementById(elementId);if(validateUserControl(element)){element.style.animation="blink-caret 0.7s step-end infinite";element.classList.add('border-primary');setTimeout(function(){element.style.animation="";element.classList.remove('border-primary')},3000)}}
function setResultTotalPages(numPagesId,numItemsId,totalItems,callBack=null){var CLONED_DIV_ID="divClonedResultElementContentX";var CLONED_NUM_PAGES_ID="numClonedResultPageNumber";var CLONED_SPAN_TOTAL_PAGES="spanClonedResultTotalPages";var CLONED_NUM_ITEM_ID="numClonedResultItems";var CLONED_SPAN_TOTAL_ITEM="spanClonedResultTotalItems";var numPages=document.getElementById(numPagesId);var numItems=document.getElementById(numItemsId);var pages=Number(totalItems/Number(numItems.value));if(isNaN(pages)){pages=1}
var decPart=Number(pages-Math.floor(pages));if(decPart>0){pages=Math.floor(pages)+1}
if(pages<0){pages=1}
numPages.max=pages;setElementInnerHtml("lbTesultTotalPages",pages);if(Number(numPages.value)>pages){numPages.value=pages}
if(Number(numPages.value)<=0){numPages.value=1}
if(callBack!=null){numPages.onchange=function(){callBack();setElementValue(CLONED_NUM_PAGES_ID,this.value)};numItems.onchange=function(){setResultTotalPages(numPages.id,numItems.id,totalItems,callBack);callBack();setElementValue(CLONED_NUM_ITEM_ID,this.value)}}
if(!validateUserControl(document.getElementById(CLONED_DIV_ID))){var divContent=createElement("div","","div-list-result");divContent.setAttribute("id",CLONED_DIV_ID);var divPN=createElement("div");divContent.appendChild(divPN);var spanPN=createElement("span");spanPN.innerHTML="Página ";divPN.appendChild(spanPN);var numPN=createElement("input","number");numPN.id=CLONED_NUM_PAGES_ID;numPN.min=1;numPN.value=numPages.value;numPN.onchange=function(){numPages.value=this.value;numPages.dispatchEvent(new Event("change"))};spanPN.appendChild(numPN);var spanTP=createElement("span");spanTP.id=CLONED_SPAN_TOTAL_PAGES;spanTP.innerHTML=" / "+pages;spanPN.appendChild(spanTP);var divITEM=createElement("div");divContent.appendChild(divITEM);var spanITEM=createElement("span");spanITEM.innerHTML="Item: ";divITEM.appendChild(spanITEM);var numITEM=createElement("input","number");numITEM.id=CLONED_NUM_ITEM_ID;numITEM.min=1;numITEM.value=numItems.value;numITEM.onchange=function(){numItems.value=this.value;numItems.dispatchEvent(new Event("change"))};spanITEM.appendChild(numITEM);var spanTI=createElement("span","","colResultOnList");spanTI.id=CLONED_SPAN_TOTAL_ITEM;spanITEM.appendChild(spanTI);var bigs=document.getElementsByClassName("divContentBigTable");Array.from(bigs).forEach(divBig=>{divBig.appendChild(divContent)})}
setElementAttribute(CLONED_NUM_PAGES_ID,"max",pages);setElementInnerHtml(CLONED_SPAN_TOTAL_PAGES," / "+pages)}
function showHttpResponseText(http,wc=""){const url=window.location.href;if((url.includes("localhost"))||(url.includes("gme.ao"))||(getDesktopStatus())){console.log(http.responseText);hideNotification()}else{if(wc!=""){showNotification("Não foi possível executar esta operação.",0);console.log("Erro no servidor")}}
console.log(wc)}
function randomString(length){var result='';var characters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';var charactersLength=characters.length;for(var i=0;i<length;i++){result+=characters.charAt(Math.floor(Math.random()*charactersLength))}
return result}
function scrollElementToTop(elementId,direction){var element=document.getElementById(elementId);if(!validateUserControl(element)){return!1}
element.scrollTop=element.scrollTop+(direction)}
function scrollElementToLeft(elementId,direction){var element=document.getElementById(elementId);if(!validateUserControl(element)){return!1}
element.scrollLeft=element.scrollLeft+(direction)}
function scrollToElement(elementId){var el=document.getElementById(elementId);if(!validateUserControl(el)){return!1}
el.scrollIntoView(!0)}
function includeHtmlInHtml(){$("div").each(function(){var file=this.getAttribute("include-data");var elmId=this.getAttribute("id");this.removeAttribute("include-data");if(file){var CHECK_ON_SERVER=!0;var cKey="@SRH_html_"+btoa(file);var cHtml=sessionStorage.getItem(cKey);if(cHtml!=null){if(cHtml!=""){cHtml=atob(cHtml);$("#"+elmId).append(cHtml);CHECK_ON_SERVER=!1}}
var assynch=!1;if(this.getAttribute("include-assynch")==1){assynch=!0}
if(CHECK_ON_SERVER){var http=new XMLHttpRequest();http.open('GET',file,assynch);http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){var response=http.responseText;$("#"+elmId).append(response);sessionStorage.setItem(cKey,btoa(response))}};http.send()}}})}
function setPageTitleWhoCall(pPermission,wc,pTitle){includeHtmlInHtml();ST_SRH_MAIN_PAGE_PERMISSION=pPermission;ST_SRH_MAIN_WHO_CALL=wc.toString().toUpperCase();var pageTitle=pTitle;document.title=pageTitle;setElementInnerHtml("h2MainHeaderPageTitle",pageTitle);var currentPage=window.location.pathname.toString().split("app/")[1].toString();if(currentPage.includes("SalePOS")){currentPage=""}
setCookie(ST_SRH_MAIN_LAST_PAGE_CNAME,currentPage)}
function menuConstructor(menuBlock=!1){var mainMenu=sessionStorage.getItem("SRH_MAIN_MENU");if(mainMenu!=null){if(mainMenu!=""){var frc=0;const urlParams=new URLSearchParams(window.location.search);if(urlParams.has('frc')){frc=urlParams.get('frc')}
if(frc!=1){if(menuBlock===!1){mainMenu=atob(mainMenu);setMenuHtml(mainMenu);return!0}}}}
if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();FILTER.menuBlock=menuBlock;FILTER.pagePermission=ST_SRH_MAIN_PAGE_PERMISSION;var http=new XMLHttpRequest();var params="action=getMenuConstructor"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_MENU_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){var response=http.responseText;if(menuBlock===!1){sessionStorage.setItem("SRH_MAIN_MENU",btoa(response))}else{sessionStorage.setItem("SRH_MENU_BLOCK",btoa(response))}
setMenuHtml(response)}};http.send(params);function setMenuHtml(mHtml){if(menuBlock===!1){setElementInnerHtml("ulMainMenuMenu",mHtml);$(".subMenuItem").each(function(){var lastPage=getCookie(ST_SRH_MAIN_LAST_PAGE_CNAME);var elmHref=this.getAttribute("href");if(elmHref.toString().includes(lastPage)){$(this).parent().parent().parent().trigger("click");$(this).parent().addClass("active")}else{$(this).parent().removeClass("active")}})}else{setElementInnerHtml("navHeaderMenu",mHtml)}}}
var HEADER_PRINT_CHECK=!1;function mainHeaderConstructorPrintHeader(){var printHeader=sessionStorage.getItem("SRH_PRINT_HEADER");if(printHeader!=null){if(printHeader!=""){var frc=0;const urlParams=new URLSearchParams(window.location.search);if(urlParams.has('frc')){frc=urlParams.get('frc')}
if((frc!=1)||(HEADER_PRINT_CHECK)){var divPrintHeader=document.getElementById("divMainHeaderRealPrintHeader");divPrintHeader.innerHTML=atob(printHeader);setElementInnerHtml("divAppIndFooterPrint",atob(sessionStorage.getItem("SSETT_PRINT_FOOTER")));return!0}}}
if(!desktopSecurityCheck()){return!1}
HEADER_PRINT_CHECK=!0;var http=new XMLHttpRequest();var params="action=getPrintHeader"+"&filterInfo="+JSON.stringify(setFilterStatus());var url=URL_SRH_LOGIN_STATUS_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){try{var dependencyInfo=JSON.parse(http.responseText);QUICK_SETTING_DATA.dependencyInfo=dependencyInfo}catch(e){showHttpResponseText(http)}
var divPrintHeader=document.getElementById("divMainHeaderRealPrintHeader");divPrintHeader.innerHTML="";var divPrintFooter=document.getElementById("divAppIndFooterPrint");divPrintFooter.innerHTML="";var printLayout=dependencyInfo.headerprintlayout;var src=urlRepositoryReplace(dependencyInfo.photo);var existLogo=!0;if(src.toString().endsWith("/")){existLogo=!1}
if(printLayout==3){if(existLogo){printLayout=1}}
if(printLayout==3){var divPrintLay3=createElement("div","","div-print-layout-3");divPrintHeader.appendChild(divPrintLay3);var imgPL3=createElement("img");imgPL3.setAttribute("src",src);divPrintLay3.appendChild(imgPL3)}else{var companyName=dependencyInfo.companyname;var taxId=dependencyInfo.companytaxid;var address=dependencyInfo.address;var contacts=dependencyInfo.phone1;if(dependencyInfo.phone2!=""){contacts+="<br> "+dependencyInfo.phone2}
if(dependencyInfo.phone3!=""){contacts+=" <br> "+dependencyInfo.phone3}
var email=dependencyInfo.email;var website=dependencyInfo.website;var facebook=dependencyInfo.facebook;var whatsapp=dependencyInfo.whatsapp;var companyFontSize=(existLogo)?"font-size: 12pt;":"font-size: 14pt;";var divCompanyNameTax=createElement("div","","div-print-layout-companyname-companaytax");var divCompanyName=createElement("div","","div-print-layout-companyname",companyFontSize);divCompanyName.innerHTML=companyName;var divCompanyTax=createElement("div","","div-taxid text-align-right");divCompanyTax.innerHTML=" NIF: "+taxId;divCompanyNameTax.appendChild(divCompanyName);divCompanyNameTax.appendChild(divCompanyTax);var divAddress=createElement("div");if(address!=""){divAddress=createElement("div","","print-layout-div-info-style flex-item");var imgAddress=createElement("img","","print-layout-img-info-style");imgAddress.setAttribute("src","../../_svg/home_gray_png.png");divAddress.appendChild(imgAddress);var lbAddres=createElement("legend","","print-layout-label-info-style");lbAddres.innerHTML=address;divAddress.appendChild(lbAddres)}
if(printLayout!=1){contacts=contacts.toString().replace("<br>",",")}
var divContacts=createElement("div");if(contacts!=""){divContacts=createElement("div","","print-layout-div-info-style flex-item");var imgContacts=createElement("img","","print-layout-img-info-style");imgContacts.setAttribute("src","../../_svg/phone_square_gray_png.png");divContacts.appendChild(imgContacts);var lbContacts=createElement("legend","","print-layout-label-info-style");lbContacts.innerHTML=contacts;divContacts.appendChild(lbContacts)}
var divEmail=createElement("div");if(email!=""){divEmail=createElement("div","","print-layout-div-info-style flex-item");var imgEmail=createElement("img","","print-layout-img-info-style");imgEmail.setAttribute("src","../../_svg/mail_gray_png.png");divEmail.appendChild(imgEmail);var lbEmail=createElement("legend","","print-layout-label-info-style");lbEmail.innerHTML=email;divEmail.appendChild(lbEmail)}
var divWebsite=createElement("div");if(website!=""){divWebsite=createElement("div","","print-layout-div-info-style flex-item");var imgWebsite=createElement("img","","print-layout-img-info-style");imgWebsite.setAttribute("src","../../_svg/globe_gray_png.png");divWebsite.appendChild(imgWebsite);var lbWebsite=createElement("legend","","print-layout-label-info-style");lbWebsite.innerHTML=website;divWebsite.appendChild(lbWebsite)}
var divFacebook=createElement("div");if(facebook!=""){divFacebook=createElement("div","","print-layout-div-info-style flex-item");var imgFacebook=createElement("img","","print-layout-img-info-style");imgFacebook.setAttribute("src","../../_svg/fb_gray_png.png");divFacebook.appendChild(imgFacebook);var lbFacebook=createElement("legend","","print-layout-label-info-style");lbFacebook.innerHTML=facebook;divFacebook.appendChild(lbFacebook)}
var divWhatsapp=createElement("div");if(whatsapp!=""){divWhatsapp=createElement("div","","print-layout-div-info-style flex-item");var imgWhatsapp=createElement("img","","print-layout-img-info-style");imgWhatsapp.setAttribute("src","../../_svg/whatsapp_gray_png.png");divWhatsapp.appendChild(imgWhatsapp);var lbWhatsapp=createElement("legend","","print-layout-label-info-style");lbWhatsapp.innerHTML=whatsapp;divWhatsapp.appendChild(lbWhatsapp)}
if(printLayout==2){var divPrintLay2=createElement("div","","div-print-layout-2");divPrintHeader.appendChild(divPrintLay2);if(existLogo){var divLogo=createElement("div","","div-print-layout-2-logo");divPrintLay2.appendChild(divLogo);var imgLogo=createElement("img");imgLogo.setAttribute("src",src);divLogo.appendChild(imgLogo)}
var divNameContacts=createElement("div","","div-print-layout-2-name-contacts");divNameContacts.appendChild(divCompanyNameTax);if(dependencyInfo.headeraddress==1){divNameContacts.appendChild(divAddress)}
if(dependencyInfo.headerphone==1){divNameContacts.appendChild(divContacts)}
if(dependencyInfo.headeremail==1){divNameContacts.appendChild(divEmail)}
if(dependencyInfo.headerwebsite==1){divNameContacts.appendChild(divWebsite)}
if(dependencyInfo.headerfacebook==1){divNameContacts.appendChild(divFacebook)}
if(dependencyInfo.headerwhatsapp==1){divNameContacts.appendChild(divWhatsapp)}}else if(printLayout==4){var divPrintLay4=createElement("div","","div-print-layout-4");divPrintHeader.appendChild(divPrintLay4);var divLogoCompany=createElement("div","","div-print-layout-4-logo-company");divPrintLay4.appendChild(divLogoCompany);if(existLogo){var divLogo=createElement("div","","div-print-layout-4-logo");divLogoCompany.appendChild(divLogo);var imgLogo=createElement("img");imgLogo.setAttribute("src",src);divLogo.appendChild(imgLogo)}
var divComp=createElement("div","","div-print-layout-4-company");divLogoCompany.appendChild(divComp);divComp.appendChild(divCompanyNameTax);var divLayout4Contacts=createElement("div","","div-print-layout-4-contacts");divPrintLay4.appendChild(divLayout4Contacts);if(dependencyInfo.headeraddress==1){divLayout4Contacts.appendChild(divAddress)}
if(dependencyInfo.headerphone==1){divLayout4Contacts.appendChild(divContacts)}
if(dependencyInfo.headeremail==1){divLayout4Contacts.appendChild(divEmail)}
if(dependencyInfo.headerwebsite==1){divLayout4Contacts.appendChild(divWebsite)}
if(dependencyInfo.headerfacebook==1){divLayout4Contacts.appendChild(divFacebook)}
if(dependencyInfo.headerwhatsapp){divLayout4Contacts.appendChild(divWhatsapp)}}else{var divPrintLay1=createElement("div","","div-print-layout-1");divPrintHeader.appendChild(divPrintLay1);if(existLogo){var divLogo=createElement("div","","div-print-layout-1-logo");divPrintLay1.appendChild(divLogo);var imgLogo=createElement("img");imgLogo.setAttribute("src",src);divLogo.appendChild(imgLogo)}else{divPrintLay1.appendChild(divCompanyNameTax)}
if(dependencyInfo.headeraddress==1){var divP1=createElement("div","","","padding-left: 3mm; width: 60mm;");divPrintLay1.appendChild(divP1);divP1.appendChild(divAddress)}
if(dependencyInfo.headerphone==1){var divP2=createElement("div","","","padding-left: 3mm; width: 25mm;");divPrintLay1.appendChild(divP2);divP2.appendChild(divContacts)}
var divP3=createElement("div","","","padding-left: 3mm; width: 55mm;");divPrintLay1.appendChild(divP3);if(dependencyInfo.headeremail==1){divP3.appendChild(divEmail)}
if(dependencyInfo.headerwebsite==1){divP3.appendChild(divWebsite)}
if(dependencyInfo.headerfacebook==1){divP3.appendChild(divFacebook)}
if(dependencyInfo.headerwhatsapp==1){divP3.appendChild(divWhatsapp)}
if(existLogo){divPrintLay1.appendChild(divCompanyNameTax)}}
var footerPrintLayout=Number(dependencyInfo.footerprintlayout);var r=document.querySelector(':root');if(footerPrintLayout>0){r.style.setProperty('--footerPrintHeight','1.2cm');var divLayout4Footer=createElement("div","","div-print-layout-4-contacts");divPrintFooter.appendChild(divLayout4Footer);if(dependencyInfo.footeraddress==1){divLayout4Footer.innerHTML+=(divAddress.outerHTML)}
if(dependencyInfo.footerphone){divLayout4Footer.innerHTML+=(divContacts.outerHTML.toString().replace("<br>",","))}
if(dependencyInfo.footeremail){divLayout4Footer.innerHTML+=(divEmail.outerHTML)}
if(dependencyInfo.footerwebsite){divLayout4Footer.innerHTML+=(divWebsite.outerHTML)}
if(dependencyInfo.footerfacebook){divLayout4Footer.innerHTML+=(divFacebook.outerHTML)}
if(dependencyInfo.footerwhatsapp){divLayout4Footer.innerHTML+=(divWhatsapp.outerHTML)}}else{r.style.setProperty('--footerPrintHeight','0cm')}}
sessionStorage.setItem("SRH_PRINT_HEADER",btoa(divPrintHeader.innerHTML));sessionStorage.setItem("SSETT_PRINT_FOOTER",btoa(divPrintFooter.innerHTML))}};http.send(params)}
function silivaUniverseMenuConstructor(){var mainMenu=sessionStorage.getItem("SRH_SILICA_UNIVERSE_MENU");if(mainMenu!=null){if(mainMenu!=""){var frc=0;const urlParams=new URLSearchParams(window.location.search);if(urlParams.has('frc')){frc=urlParams.get('frc')}
if(frc!=1){mainMenu=atob(mainMenu);setMenuHtml(mainMenu);return!0}}}
if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();FILTER.pagePermission=ST_SRH_MAIN_PAGE_PERMISSION;FILTER.officialpartnerid=SYSTEM_USER_STATUS.officialpartnerid;var http=new XMLHttpRequest();var params="action=getUniverseSilicaMenu"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_MENU_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){var response=http.responseText;sessionStorage.setItem("SRH_SILICA_UNIVERSE_MENU",btoa(response));setMenuHtml(response)}};http.send(params);function setMenuHtml(mHtml){setElementInnerHtml("divMenuSilicaUniverse",mHtml)}}
function validateSession(http){try{const err=new Error();const pilhaDeChamada=err.stack.split("\n");let wcall=pilhaDeChamada[pilhaDeChamada.length-1].trim().split(" ")[1];try{var resp=JSON.parse(http.responseText);if(resp.sessionSatus==0){alert("Sessão inválida ou expirada. Porfavor, faça novo login.");return!1}else{return resp}}catch(e){showHttpResponseText(http,wcall)}}catch(e){console.log("Erro na pilha de chamadas")}}
function stickMainButtonsOfPages(){return!1;window.onscroll=function(){stickyButtonsBar();scrollFunction()};var buttonsBar=document.getElementById("divButtonsBar");var sticky=buttonsBar.offsetTop;function stickyButtonsBar(){if(window.pageYOffset>=sticky){buttonsBar.classList.add("stickyButtonsBar")}else{buttonsBar.classList.remove("stickyButtonsBar")}}}
function getOperatorName(operatorName,operatorId){return getFirtLastName(operatorName)+" ["+operatorId+"]"}
function addEventInput2Select(sel){sel.addEventListener('input',()=>{sel.title=sel.value})}
function dynamicSort(property){var sortOrder=1;if(property[0]==="-"){sortOrder=-1;property=property.substr(1)}
return function(a,b){var result=(a[property]<b[property])?-1:(a[property]>b[property])?1:0;return result*sortOrder}}
function lightColorByIndex(idx){var n=Math.abs(Number(idx));if(n>16){var d=Number(n/16);d=Math.trunc(d);var x=n-(d*16);n=x}
if(n==1){return"#D0CECE"}else if(n==2){return"#D6DCE5"}else if(n==3){return"#DEEBF7"}else if(n==4){return"#FBE4D6"}else if(n==5){return"#EDEDED"}else if(n==6){return"#FFF2CC"}else if(n==7){return"#DAE3F3"}else if(n==8){return"#E2F0D9"}else if(n==9){return"#AFABAB"}else if(n==10){return"#ADB9CA"}else if(n==11){return"#BDD7EE"}else if(n==12){return"#F8CBAD"}else if(n==13){return"#DBDBDB"}else if(n==14){return"#FFE699"}else if(n==15){return"#B4C7E7"}else if(n==16){return"#C5E0B4"}}
function setPrintTableOption(){var n=0;$(".table-header-print").each(function(){const tableHeader=this;if(!validateUserControl(tableHeader)){return!1}
if(tableHeader.getAttribute("option-print")==1){return}else{tableHeader.setAttribute("option-print",1)}
const bigTable=$(this).parent().parent();var needButton=!0;var tblOption=document.getElementById("tbodyTableOptionSelector_"+n);$(".btn-call-table-option_"+n).each(function(){needButton=!1;tblOption.innerHTML=""});if(needButton){const tfoot=createElement("tfoot","");bigTable[0].appendChild(tfoot);const trFoot=tfoot.insertRow(0);const tdFoot=trFoot.insertCell(0);tdFoot.innerHTML='<div class="onlyOnPrint footer-print-space"></div>';const btCallOption=createElement("button","button","noPrint btn-call-table-option_"+n);btCallOption.innerHTML="Opções da tabela";const bigDiv=bigTable.parent()[0];bigDiv.insertBefore(btCallOption,bigTable[0]);const divOverlay=createElement("div","","overlay");bigDiv.appendChild(divOverlay);btCallOption.onclick=function(){divOverlay.style.display="block"};const divPopup=createElement("div","","popup");divOverlay.appendChild(divPopup);const divHeader=createElement("div","","popup-header");divHeader.innerHTML="<h2>Opções da tabela</h2>";divPopup.appendChild(divHeader);const btClose=createElement("button","button","popup-close-button labelClose");divHeader.appendChild(btClose);btClose.onclick=function(){divOverlay.style.display="none"};const divContent=createElement("div","","popup-content");divPopup.appendChild(divContent);const tbl=createElement("table","","tbl1");divContent.appendChild(tbl);const thead=createElement("thead","","");tbl.appendChild(thead);const trHe=createElement("tr","","tblHead1");thead.appendChild(trHe);var heads=["Coluna","Visibilidade","Largura","Moldar texto","Tamanho","Fundo","Cor do texto"];for(var i=0;i<heads.length;i++){let h=createElement("th","","");h.innerHTML=heads[i];trHe.appendChild(h)}
tblOption=createElement("tbody","","");tblOption.setAttribute("id","tbodyTableOptionSelector_"+n);tbl.appendChild(tblOption)}
const tablePrint=bigTable.children('tbody')[0];tablePrint.setAttribute("table_index",n);const columns=tableHeader.children;Array.from(columns).forEach(col=>{if(col.tagName.toString().toUpperCase()=="TH"){if(!col.classList.contains("colAction")){if(!col.classList.contains("noPrint")){const colIdx=col.cellIndex;const row=createElement("tr","","borderGray");tblOption.appendChild(row);let cellCol=createTableCell(row,col.innerHTML,"");let cellVis=createTableCell(row,"","text-align-center");const chbPrint=createElement("input","checkbox","noPrint");chbPrint.setAttribute("checked",!0);chbPrint.setAttribute("id","chbHideShowTableOption_"+n+"_"+colIdx);chbPrint.setAttribute("title","Visivel na empressão.");cellVis.appendChild(chbPrint);chbPrint.onchange=function(){var status=getElementChecked(this.id);if(status==1){this.setAttribute("title","Visível na impressão");col.classList.remove("display-none");tablePrint.setAttribute("hide_this_col_"+colIdx,"0")}else{this.setAttribute("title","Oculto na impressão");col.classList.add("display-none");tablePrint.setAttribute("hide_this_col_"+colIdx,"1")}
const rows=tablePrint.children;Array.from(rows).forEach(row=>{if(row.tagName.toString().toUpperCase()=="TR"){const cells=row.children
Array.from(cells).forEach(cell=>{if(cell.cellIndex==colIdx){if(status==1){cell.classList.remove("display-none")}else{cell.classList.add("display-none")}}})}})};const cellWidth=createTableCell(row,"","");const divWidth=createElement("div","");divWidth.style.display="flex";cellWidth.appendChild(divWidth);const selWidth=createElement("select","","font-size-small");selWidth.innerHTML='<option value="0">Automátivo</option><option value="1">Manual</option>';divWidth.appendChild(selWidth);const numWidth=createElement("input","number","font-size-small display-none");numWidth.value=0;numWidth.min=0;numWidth.step="any";numWidth.title="Largura da coluna em centimetros";divWidth.appendChild(numWidth);let t=n;selWidth.onchange=function(){if(this.value=="0"){numWidth.classList.add("display-none");changeWidth("auto",t,colIdx)}else{numWidth.classList.remove("display-none")}};numWidth.onchange=function(){var width=this.value+"cm";changeWidth(width,t,colIdx)};const cellWarp=createTableCell(row,"","");const selWarp=createElement("select","","font-size-small");selWarp.innerHTML='<option value="0">Moldar texto</option><option value="1">Não modar</option><option value="2">Não modar e ocultar</option>';cellWarp.appendChild(selWarp);selWarp.onchange=function(){changeWrap(this.value,t,colIdx)};const cellFSize=createTableCell(row,"","");const selFSize=createElement("select","","font-size-small");cellFSize.appendChild(selFSize);fillSelFSize(selFSize);selFSize.onchange=function(){changeFSize(this.value,t,colIdx)};const cellBGC=createTableCell(row,"","");const selBGC=createElement("select","","font-size-small");cellBGC.appendChild(selBGC);fillSelColor(selBGC);selBGC.onchange=function(){changeColor(this.value,t,colIdx);this.style.backgroundColor=this.value};const cellColor=createTableCell(row,"","");const selColor=createElement("select","","font-size-small");cellColor.appendChild(selColor);fillSelColor(selColor);selColor.onchange=function(){changeColor(this.value,t,colIdx,!1);this.style.backgroundColor=this.value}}}}});n++});function changeWidth(width,tidx,cidx){$(".div-on-cell-to-print-"+tidx+"-"+cidx).each(function(){const div=this;div.style.width=width})}
function changeFSize(fsize,tidx,cidx){$(".div-on-cell-to-print-"+tidx+"-"+cidx).each(function(){const div=this;div.style.fontSize=fsize})}
function changeColor(color,tidx,cidx,bgc=!0){$(".div-on-cell-to-print-"+tidx+"-"+cidx).each(function(){const div=this;if(bgc){const cell=$(this).parent();cell[0].style.backgroundColor=color;div.style.backgroundColor=color}else{div.style.color=color}})}
function changeWrap(wrap,tidx,cidx){$(".div-on-cell-to-print-"+tidx+"-"+cidx).each(function(){const div=this;if(wrap==0){div.style.whiteSpace="normal";div.style.overflow="visible"}else if(wrap==1){div.style.whiteSpace="nowrap";div.style.overflow="visible"}else{div.style.whiteSpace="nowrap";div.style.overflow="hidden"}})}
function fillSelFSize(sel){sel.innerHTML='';let optAuto=createElement("option","","");optAuto.value="";optAuto.innerHTML="Automático";sel.appendChild(optAuto);for(var s=6;s<37;s++){let optSize=createElement("option","","");optSize.value=s+"pt";optSize.innerHTML=s+"pt";sel.appendChild(optSize)}}
function fillSelColor(sel){const COLOR_SET=['rgba(0,0,0)','rgba(255,255,255)','rgba(192,0,0)','rgba(255,0,0)','rgba(255,192,0)','rgba(255,255,0)','rgba(146,208,80)','rgba(0,176,80)','rgba(0,176,240)','rgba(0,112,192)','rgba(0,32,96)','rgba(112,48,160)'];sel.innerHTML='';let optAuto=createElement("option","","");optAuto.value="";optAuto.innerHTML="Automático";sel.appendChild(optAuto);for(var c=0;c<COLOR_SET.length;c++){var color=COLOR_SET[c];let optColor=createElement("option","","");optColor.value=color;optColor.style.backgroundColor=color;sel.appendChild(optColor)}}}
function setHorizintalScrollButton(){var arDivBigs=document.getElementsByClassName("divContentBigTable");if(arDivBigs.length>0){for(var i=0;i<arDivBigs.length;i++){let divBig=arDivBigs[i];divBig.setAttribute("id","divContentBigTable_"+i);let divButtons=createElement("div","","div-horintal-scroll noPrint","display: none;");divBig.insertBefore(divButtons,divBig.firstChild);let divLeft=createElement("div","","arrow-button");divLeft.onclick=function(){divBig.scrollLeft=divBig.scrollLeft-130};divButtons.appendChild(divLeft);let spanLeft=createElement("span","","triangle arrow-left");divLeft.appendChild(spanLeft);let divRight=createElement("div","","arrow-button");divRight.onclick=function(){divBig.scrollLeft=divBig.scrollLeft+130};divButtons.appendChild(divRight);let spanRight=createElement("span","","triangle arrow-right");divRight.appendChild(spanRight);divBig.addEventListener('mousemove',()=>{if(divBig.scrollWidth>divBig.clientWidth){divButtons.style.display="flex"}else{divButtons.style.display="none"}})}}}
function setBgcByDates(startDate,endDate){var bgc="";var now=new Date();startDate=new Date(startDate);endDate=new Date(endDate);if(endDate.getTime()<now.getTime()){bgc="background-color-brown"}else if(startDate.getTime()<=now.getTime()){if(endDate.getTime()>=now.getTime()){bgc="background-color-green-light"}}else if(dateDiffDays(startDate,now)<7){bgc="border-color-green-light"}
return bgc}
function pageMenuCreate(){var divBts=document.querySelector(".div-mainbutton-content");var divMain=divBts.parentNode;if(divMain.getAttribute("PAGE_MENU_CREATE")==1){return!1}
var btCallMenu=document.createElement("button");btCallMenu.type="button";btCallMenu.setAttribute("class","button-call-menu labelMenuBarsDark");divMain.appendChild(btCallMenu);var divMenu=document.createElement("div");divMenu.setAttribute("class","div-page-menu");divMenu.setAttribute("display-mode",0);divMain.appendChild(divMenu);Array.from(divBts.children).forEach(bt=>{let cloneBt=bt.cloneNode();cloneBt.innerHTML=bt.innerHTML;cloneBt.classList.remove("mainButton");cloneBt.classList.add("button-on-menu");cloneBt.onclick=function(){bt.click()};divMenu.appendChild(cloneBt)});btCallMenu.onclick=function(){var dis=divMenu.getAttribute("display-mode");if(dis==0){divMenu.style.display="block";divMenu.setAttribute("display-mode",1)}else{divMenu.style.display="none";divMenu.setAttribute("display-mode",0)}};document.addEventListener('mouseup',function(e){if(!divMenu.contains(e.target)){if(divMenu.getAttribute("display-mode")==1){divMenu.setAttribute("display-mode",0);divMenu.style.display='none'}}});divMain.setAttribute("PAGE_MENU_CREATE",1)}
function setDivFieldsetLegend(){$(".div-fieldset-legend").each(function(){if(this.getAttribute("set-div-fieldset")!=1){const subArrow=document.createElement("span");subArrow.setAttribute("class","sub-arrow rotate-270-deg");this.prepend(subArrow);this.onclick=function(){if(this.getAttribute("status")!=0){$(this).parent().removeClass("div-fieldset-expand");$(this).parent().addClass("div-fieldset-collapse");this.setAttribute("status","0");subArrow.classList.remove("rotate-270-deg");subArrow.classList.add("rotate-90-deg")}else{$(this).parent().removeClass("div-fieldset-collapse");$(this).parent().addClass("div-fieldset-expand");this.setAttribute("status","1");subArrow.classList.remove("rotate-90-deg");subArrow.classList.add("rotate-270-deg")}};this.setAttribute("set-div-fieldset",1)}})}
function getSessionId(){var sessionId=sessionStorage.getItem(ST_SRH_MAIN_SESSION_CNAME);if(sessionId==null){return""}
return sessionId}
function showHideColumnOptional(elemId){var status=getElementChecked(elemId);var r=document.querySelector(':root');if(status){r.style.setProperty('--forceOptionalColumn','none')}else{r.style.setProperty('--forceOptionalColumn','table-cell')}}
function getDesktopStatus(){var deskStatus=sessionStorage.getItem('SU_DESKTOP_STATUS');const url=new URL(window.location.href);if(url.port!=undefined){const port=url.port;if(port==25320){deskStatus=1}}
if(deskStatus==null){return!1}
if(deskStatus==1){return!0}else{return!1}}
function strDiv(content,clas=""){if(content==null){return""}
if(clas!=""){clas='class="'+clas+'"'}
return'<div '+clas+'>'+content+'</div>'}
function exportTableToExcel(tableId,tblName=""){var tbl=document.getElementById(tableId);$(tbl).table2excel({exclude:".noPrint__XXXX",name:tblName,filename:tblName+".xls",preserveColors:!0})}
function desktopSecurityCheck(level=2){var deskStatus=sessionStorage.getItem('SU_DESKTOP_STATUS');if(deskStatus!=1){console.log("Not Desktop");return!0}
var devStatus=sessionStorage.getItem('DEVELOPMENT_STATUS');if(devStatus==1){console.log("Test Mode, don't need check");return!0}
var FILTER=setFilterStatus();var result=!1;var wherePass="";var http=new XMLHttpRequest();var params="action=getBankAccountList"+"&filterInfo="+JSON.stringify(FILTER);var url=(level==2)?URL_SRH_DESKTOP_SECURITY_CHECK_X:URL_SRH_INDEX_DESKTOP_SECURITY_CHECK_X;http.open('POST',url,!1);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(this.readyState==4&&this.status==200){var response=validateSession(http);var localTreatment1=sessionStorage.getItem('SU_DESKTOP_TREATMENT_CONTENT_1');var localTreatment2=sessionStorage.getItem('SU_DESKTOP_TREATMENT_CONTENT_2');var serverTreatment1=response.contentT1;var serverTreatment2=response.contentT2;if(localTreatment1==serverTreatment1){wherePass+="Level 1 - Check";if(localTreatment2==serverTreatment2){wherePass+="Level 2 - Check";result=!0}}}};http.send(params);if(!result){console.log("Potential security violation");console.log(wherePass);showNotification("Potencial violação de segurança",0)}
return result}
function setPartnerInfo(info){setElementInnerHtml("lbFooterRegisterPartner","Distribuído por "+info.companyname);var divCont=document.getElementById("divAlertNoLicPartnerInfo");divCont.innerHTML="";var spName=createElement("div","","font-weight-bold");spName.innerHTML=info.companyname;divCont.appendChild(spName);var spAddress=createElement("div","");spAddress.innerHTML=info.address;divCont.appendChild(spAddress);var spPhone=createElement("div","");spPhone.innerHTML="Contactos: ";divCont.appendChild(spPhone);var phone1=info.phone1;if(phone1!=""){var aPhone1=createElement("a","");aPhone1.href="tel:"+phone1;aPhone1.innerHTML=phone1+" / ";spPhone.appendChild(aPhone1)}
var phone2=info.phone2;if(phone2!=""){var aPhone2=createElement("a","");aPhone2.href="tel:"+phone2;aPhone2.innerHTML=phone2+" / ";spPhone.appendChild(aPhone2)}
var phone3=info.phone3;if(phone3!=""){var aPhone3=createElement("a","");aPhone3.href="tel:"+phone3;aPhone3.innerHTML=phone3;spPhone.appendChild(aPhone3)}
var email=info.email;if(email!=""){var spMail=createElement("div","");spMail.innerHTML="E-mail: ";divCont.appendChild(spMail);var aEmail=createElement("a","");aEmail.href="mailto:"+email;aEmail.innerHTML=email;spMail.appendChild(aEmail)}
var website=info.website;if(website!=""){var spWS=createElement("div","");spWS.innerHTML="Website: ";divCont.appendChild(spWS);var aWebSite=createElement("a","");aWebSite.href=website;aWebSite.innerHTML=website;aWebSite.target="_blank";spWS.appendChild(aWebSite)}
var whatsapp=info.whatsapp;if(whatsapp!=""){var spWA=createElement("div","");spWA.innerHTML="WhatsApp: ";divCont.appendChild(spWA);var aWA=createElement("a","");aWA.href="https://wa.me/244"+whatsapp;aWA.innerHTML=whatsapp;aWA.target="_blank";spWA.appendChild(aWA)}}
function rootSilicaUniverMenuConstroctor(){var FILTER={};FILTER.userId=SYSTEM_USER_STATUS.userId;FILTER.companyId=SYSTEM_USER_STATUS.companyId;FILTER.officialpartnerid=SYSTEM_USER_STATUS.officialpartnerid;var http=new XMLHttpRequest();var params="action=getRootMenu"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SU_COMMON_ROOT_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){var response=http.responseText;setMenuHtml(response)}};http.send(params);function setMenuHtml(mHtml){setElementInnerHtml("divIndSilContMenu",mHtml)}}
function regularSynchLocalEntityList(silicaGroup,forceSynch=0){var action=[];action[0]="getSynchLocalToOnlineFull";action[1]="checkSynchTempFiles";var current_index=0;callback();function callback(){if(current_index!=1){if(!getDesktopStatus()){console.log("Synch - Only for desktop version");return!1}}
if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();FILTER.silicaGroup=silicaGroup;FILTER.forceSynch=forceSynch;if(forceSynch!=0){showNotification("Esta operação pode demorar alguns miniutos.")}
console.log("Synch - Trying start synch");var http=new XMLHttpRequest();var params="action="+action[current_index]+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SSETT_SYNC_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){console.log(http.responseText);if(forceSynch==1){try{var response=JSON.parse(http.responseText);if(response.status==1){showNotification(response.msg,1)}else{showNotification(response.msg,0)}}catch(e){hideNotification()}}
if(current_index==0){current_index=1;callback()}}};http.send(params)}}
function strFilterResult(obj=null){var msg="Procurando...";if(obj!=null){try{var n=Array.from(obj).length;if(n<=0){msg="Sem resultados.";hideNotification()}else{msg=""}}catch(e){msg="Sem resultados.";hideNotification()}}
if(msg==""){return""}else{return'<tr class=""noPrint><td>'+msg+'</td></tr>'}}
function sessionPageVisited(){if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();FILTER.page=document.title;FILTER.st="SRH";var http=new XMLHttpRequest();var params="action=saveSessionPage"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SSETT_SYSTEM_USER_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.send(params)}
function pointControlAttendeceFromDeviceAuto(){if(!getDesktopStatus()){console.log("Attendence from device, only for desktop");return!1}
if(!desktopSecurityCheck()){return!1}
var FILTER=setFilterStatus();FILTER.automatic=1;console.log("Trying start get attendence from device automatic");var http=new XMLHttpRequest();var params="action=getPointControlAttendenceFromDeviceAuto"+"&filterInfo="+JSON.stringify(FILTER);var url=URL_SRH_POINT_CONTROL_X;http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){console.log(http.responseText)}};http.send(params)}
function changeIframePort(){if(getDesktopStatus()){var iFrames=document.querySelectorAll("iframe");Array.from(iFrames).forEach(iframe=>{var src=iframe.src;src=src.replace(/:\d+/,':25319');iframe.src=src})}}
function updateCurrentUrlWithouRelaod(nextUrl){const nextTitle=document.title;const nextState={additionalInformation:'Updated the URL with JS'};window.history.pushState(nextState,nextTitle,nextUrl)}
function setOnloadStatus(divId,callback){let divOverlay=document.getElementById(divId);if(!validateUserControl(divOverlay)){return!1}
var onLoadStatus=divOverlay.getAttribute(ST_ONLOAD_ATTRIBUTE);if(onLoadStatus==2){return!1}
if(onLoadStatus!=1){divOverlay.onload=function(){callback()};setElementAttribute(divOverlay.id,ST_ONLOAD_ATTRIBUTE,1);return!1}
setElementAttribute(divOverlay.id,ST_ONLOAD_ATTRIBUTE,2);return!0}
function serverHttpRequest(FILTER,action,url,callback=null){const erro=new Error();const pilhaDeChamadas=erro.stack.split("\n");const whoCallMe=pilhaDeChamadas[2].trim().split(" ")[1];FILTER.action=action;url+='&companyId='+SYSTEM_USER_STATUS.companyId+'&&depId='+SYSTEM_USER_STATUS.workplaceId;let http=new XMLHttpRequest();let params="action="+action+"&filterInfo="+JSON.stringify(FILTER);http.open('POST',url,!0);http.setRequestHeader('Content-type','application/x-www-form-urlencoded');http.onreadystatechange=function(){if(http.readyState==4&&http.status==200){try{var response=JSON.parse(http.responseText);if(response.sessionSatus==0){alert("Sessão inválida ou expirada. Porfavor, faça novo login.");return!1}else if(callback!=null){callback(response)}}catch(e){ST_SRH_WAITING_SERVER=0;hideNotification();const url=window.location.href;if((url.includes("localhost"))||(url.includes("gme.ao"))||(getDesktopStatus())){console.log(http.responseText);console.log(e)}else{showNotification("Não foi possível executar esta operação.",0);console.log("Erro no servidor")}
console.log(whoCallMe);console.log(action+" ------------------")}}else if(http.readyState==4&&http.status!=200){ST_SRH_WAITING_SERVER=0;hideNotification();console.log("Erro no servidor");console.log(whoCallMe);console.log(action+" ------------------")}};http.onerror=function(){console.log('Request encountered an error');hideNotification();ST_SRH_WAITING_SERVER=0};http.ontimeout=function(){console.log('Request connection timeout');hideNotification();ST_SRH_WAITING_SERVER=0};http.send(params)}
function formValidateInput(container){mustCheck=(elem)=>{var check=!0;var req_dep=elem.getAttribute("req-dep");if(elem.getAttribute("req-opt")==0){if(elem.value==""){check=!1}}else if(req_dep!=null){var depValue=getElementValue(req_dep);var req_dep_v=elem.getAttribute("req-dep-value");if(req_dep_v=="!="){if(depValue==""){check=!1}}else{if(depValue!=req_dep_v){check=!1}}}
return check};var status=!0;var toFocus="";$(container).find("input").each(function(){var req=this.getAttribute("required");if(req!=null){$(this).removeClass("is-invalid");if(mustCheck(this)){this.value=reviewString(this);var currVal=this.value;var tp=this.getAttribute("type");if((tp=="text")||(tp=="password")){if(currVal==""){status=!1;$(this).addClass("is-invalid");if(toFocus==""){toFocus=this.id}}else{var det=this.getAttribute("data-extra-type");if(det){if(det=="tax-id"){if(!validateTaxId(currVal,!1)){status=!1;$(this).addClass("is-invalid");if(toFocus==""){toFocus=this.id}}}}}}else if(tp=="tel"){this.value=currVal.replace(/\D/g,'');if(this.value==""){status=!1;$(this).addClass("is-invalid");if(toFocus==""){toFocus=this.id}}}else if(tp=="email"){if(!isEmail(currVal)){status=!1;$(this).addClass("is-invalid");if(toFocus==""){toFocus=this.id}}}else if(tp=="date"){if(!validateDate(new Date(currVal))){status=!1;$(this).addClass("is-invalid");if(toFocus==""){toFocus=this.id}}}
this.dispatchEvent(new Event('change'))}}});$(container).find("select").each(function(){var req=this.getAttribute("required");if(req!=null){$(this).removeClass("is-invalid");if(mustCheck(this)){var currVal=this.value;if((currVal=="")||(currVal=="-1")){status=!1;$(this).addClass("is-invalid");if(toFocus==""){toFocus=this.id}}}}});if(!status){setElementFocus(toFocus)}
return status}
function strElement(tag,clas="",inner=""){if(clas!=""){clas=' class="'+clas+'"'}
return'<'+tag+clas+'>'+inner+'</'+tag+'>'}