const StepDisplay =['Zipcode','customerStep-9','customerStep-10','Address','Details','Username','Verify','End']; const cssLoad= `.appActive {display: flex;justify-content: center;align-items: center;position: fixed; top:0px; left:0px; width: 100%;height: 100%;background: #fff;z-index: 9999;}.loadingRoofCal{position:relative;margin: auto;top:0;left:0;right:0;bottom:0;background-color:transparent;display:none;justify-content:center;align-items:center;z-index:9999;transition:1s all;}.loadingRoofCal.show{display:flex}.loadingRoofCal .spin{border:3px solid hsla(185,100%,62%,.2);border-top-color:#019720;background-color:transparent!important;border-radius:50%;width:3em;height:3em;animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.btnNone{display: none;}.navRoofCal{display: none;}#btnOpenRoofCal {box-sizing: border-box;padding: 5px 8px;color: #555;background-color: #fff;border: 1px solid #ccc;border-radius: 4px;font-size: 16px;font-family: Nunito, sans-serif;}.headRoofCal {position: relative;width: 100%;min-height: 50px;}.sectBtnClose {position: absolute;right: 20px;top: 10px;}button.btnCloseIcon {background-color: transparent;color: #D81E1E;font-size: 32px;font-weight: bold;box-sizing: border-box;border: 1px solid #D81E1E;border-radius: 4px;padding: 0px 12px;cursor: pointer;font-family: Nunito, sans-serif;}#errorReload{display:none;}`; const textBtnMain= `RoofCal Estimate`; const urlLogo= `https://marketeaaccounts.com/media/100582/420/roofcal/`; const imgLogo= ``; const desc_company= ``; const user_id = "100582"; const org_id = "420"; const site = "amazingmetalroofing.com"; const ip = "3.145.45.205"; const ip_info = JSON.parse('{"status":"success","country":"United States","countryCode":"US","region":"OH","regionName":"Ohio","city":"Dublin","zip":"43017","lat":40.09920000000000328554961015470325946807861328125,"lon":-83.1140999999999934289007796905934810638427734375,"timezone":"America\/New_York","isp":"Amazon.com, Inc.","org":"AWS EC2 (us-east-2)","as":"AS16509 Amazon.com, Inc.","query":"3.145.45.205"}'); const consultaApiIp = "1"; const idsesion = "790888"; const urlSession = "https://marketeaaccounts.com/api/roofcal/sendids/1743917214306"; const urlStep = "https://marketeaaccounts.com/api/roofcal/step"; const allZip = "0"; const cssMain="https://marketeaaccounts.com/api/roofcal/maincss/1743917214306"; const btnIframeCSS="https://marketeaaccounts.com/api/roofcal/btnIframeCSS/1743917214306"; const redirect = "0"; const urlSendcode = "https://marketeaaccounts.com/api/roofcal/sendvalidcode"; const opt = "1"; const uri = ""; const time = "25000"; const zip = ['01757'];// creando html var divBase =document.querySelector("#"+appRoofCal); divBase.classList.add('appRoofCal'); divBase.style.display='none'; // btn princial var btnOpenRoofCal = document.createElement('button'); btnOpenRoofCal.type="button"; btnOpenRoofCal.id=`btnOpenRoofCal`; btnOpenRoofCal.classList.add('btnOpenRoofCal'); var htmlBtn =``; htmlBtn+=``+textBtnMain+``; htmlBtn+=``; btnOpenRoofCal.innerHTML=htmlBtn; divBase.appendChild(btnOpenRoofCal); // iframe con wiget var iframeRoof = document.createElement('iframe'); iframeRoof.classList.add('iframeRoof', 'roofHide'); // divBase.appendChild(iframeRoof); // Accede al documento del iframe var iframeLoad = iframeRoof.contentDocument || iframeRoof.contentWindow.document; var Q = function(e){ return iframeLoad.querySelector(e); }; var qAll = function(e){ return iframeLoad.querySelectorAll(e); }; var getSO=function(){var b=window.navigator.appVersion.toLowerCase(),a="Sistema Operativo";return -1!=b.indexOf("win")?a="Windows":-1!=b.indexOf("android")?a="Android":-1!=b.indexOf("mac")?a="Mac Os":-1!=b.indexOf("linux")&&(a="Linux"),a}; var getBrowser=function(){var b,c=navigator.userAgent,a=c.match(/(opera|chrome|safari|firefox|msie|edge|trident(?=\/))\/?\s*(\d+)/i)||[];return/trident/i.test(a[1])?"IE "+((b=/\brv[ :]+(\d+)/g.exec(c)||[])[1]||""):"Chrome"===a[1]&&null!=(b=c.match(/\b(OPR|Edge)\/(\d+)/))?b.slice(1).join(" ").replace("OPR","Opera"):(a=a[2]?[a[1],a[2]]:[navigator.appName,navigator.appVersion,"-?"],null!=(b=c.match(/version\/(\d+)/i))&&a.splice(1,1,b[1]),a.join(" "))}; var detectDevice=function(){return navigator.userAgent,navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/webOS/i)||navigator.userAgent.match(/iPhone/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/Windows Phone/i)?"Mobile":navigator.userAgent.match(/iPad/i)?"iPad":window.innerWidth>=768&&window.innerWidth<=992?"Tablet":window.innerWidth>=1190?"Desktop":"Other device"}; var ids = window.localStorage.getItem('idsRoofcal'); if(ids==null || consultaApiIp==1){ ids = idsesion; window.localStorage.setItem('idsRoofcal', ids) } var iniEst ={}; iniEst.idEst = 0; iniEst.user_id = user_id; iniEst.org_id = org_id; iniEst.site = site; iniEst.title = d.title; iniEst.pathname = d.location.pathname; iniEst.pageVisits = d.location.href; iniEst.referer = (d.referrer!='') ? d.referrer : 'Direct'; iniEst.ip = ip; iniEst.consultaApiIp = consultaApiIp; iniEst.os = getSO(); iniEst.browser = getBrowser(); iniEst.device = detectDevice(); iniEst.ids = window.localStorage.getItem('idsRoofcal'); iniEst.ip_info = ip_info; iniEst.quest = new Array(); var estimate = iniEst; var divIdStep = "step"; var stepCount = 0; var calculator = {}; calculator.step = stepCount; window.localStorage.setItem('calculator', JSON.stringify(calculator)); window.localStorage.removeItem('reload'); var selectedShape; var registerLog = function(){ fetch(urlSession, { method: "POST", mode: 'cors', cache: 'no-cache', credentials: 'same-origin', headers: { "Content-Type": "application/json", "Authentication": "Bearer "+user_id+"-"+org_id+"" }, redirect: 'follow', referrerPolicy: 'no-referrer', body: JSON.stringify(iniEst), }) .then(res => res.json()) .catch(error => {console.error('Error:', error)}) .then(response => { console.log('Success:', response) }); }; setTimeout(function(){registerLog();}, 1000); var setLS = function (obj, val) { window.localStorage.setItem(obj, JSON.stringify(val)); getLS(obj); } var getLS = function (obj) { var json = window.localStorage.getItem(""+obj+""); obj = JSON.parse(json); } var btnDis = function (btn, disabled) { if(Q(".navRoofCal #"+btn)){ if(disabled == "true"){ Q(".navRoofCal #"+btn).setAttribute('disabled', disabled); }else{ Q(".navRoofCal #"+btn).removeAttribute('disabled'); } } }; var requestFiles = function(url, typeFile, idDiv){ btnDis('next' ,'true'); return new Promise((resolve) => { fetch(url, { method: 'GET', mode: 'cors', cache: 'no-cache', credentials: 'same-origin', headers: { "Content-Type": "text/xml", "Authentication": "Bearer "+user_id+"-"+org_id+"" }, redirect: 'follow', referrerPolicy: 'no-referrer', }) .then(response => { response.text().then(function(text) { //console.log('response text', text); if(text.includes('syntax error') || text.includes('Exception')) { window.localStorage.setItem('reload', stepCount); console.log('response text error php'); showLoading(); pantallaStepNone(); showReload(); } else { if(typeFile =='js'){ } else if(typeFile == 'css'){ createCssIframe(text, idDiv); } else if(typeFile == 'cssDOM'){ createCssDOM(text, idDiv); } else if(typeFile == 'html'){ if(window.localStorage.getItem('reload')){ window.localStorage.removeItem('reload'); Q('#errorReload').classList.remove('showFlex'); } createAppHtml(text, idDiv); btnDis('next' ,'false'); } } resolve(true) }) }) .catch(error => { console.log('Error:', error); btnDis('next' ,'false'); resolve(false); }); }); }; var createCssDOM = function(cssText, cssID){ var s=d.createElement("style"); s.type="text/css"; s.rel="stylesheet"; s.id=cssID; s.innerHTML=cssText; var wgRoofCalS =document.querySelector("#"+idS); wgRoofCalS.after(s); }; var createCssIframe = function(cssText, cssID){ var s=d.createElement("style"); s.type="text/css"; s.rel="stylesheet"; s.id=cssID; s.innerHTML=cssText; iframeLoad.body.append(s); }; var createAppsj = function(urlRoofCal){ var s=d.createElement('script'); s.type="text/javascript"; s.id=idS; s.defer=!0; s.src=urlRoofCal+'/'+f.getTime(); t.after(s) }; var createAppHtml = function(html, idDiv){ var divCode=d.createElement("div"); idDiv = idDiv=='Address' ? 'Address-step' : idDiv; divCode.id=idDiv; divCode.classList.add('pantallaStep'); divCode.innerHTML=html; var divMainCR =Q(".bodyRoofCalContent"); divMainCR.append(divCode); console.log('createAppHtml', idDiv); showLoading(); //validaciones validations(); setTimeout(function(){ validNext(); }, 400); }; var showLoading = function(){ if(window.localStorage.getItem('reload')==stepCount){ //console.log('cerrando showReload') showReload(); } if(Q('#loadingRoofCal').classList.length>1){ //console.log('desactivando loanding', 'step', stepCount); Q('#loadingRoofCal').classList.remove('show'); stepActive(); if(Q('.headRoofCal').style.display=="none"){ Q('.headRoofCal').style.display="block"; } } else{ //console.log('activando loanding', 'step', stepCount); Q('#loadingRoofCal').classList.add('show'); pantallaStepNone(); } }; var pantallaStepNone = function(){ console.log('ocultando pantallaStep', 'step', stepCount); var steps = iframeLoad.querySelectorAll('.pantallaStep'); steps.forEach( function(e, i) { e.style.display="none"; }); }; var stepActive = function(){ console.log('stepActive', 'step', stepCount); if(Q("#"+StepDisplay[stepCount])){Q("#"+StepDisplay[stepCount]).style.display="block";} if(stepCount > 0){ if(Q('.navRoofCal #back').classList.length>0){ Q('.navRoofCal #back').classList.remove('opa0'); } if(Q(".navRoofCal").style.display=="none"){ Q(".navRoofCal").style.display="flex"; } }else{ Q(".navRoofCal").style.display="none"; if(Q('.navRoofCal #back').classList.length==0){ Q('.navRoofCal #back').classList.add('opa0'); } } }; var requestFilesPOST = function(url, typeFile, idDiv, varPost){ var data = JSON.stringify({data:varPost}) btnDis('next' ,'true'); fetch(url, { method: "POST", mode: 'cors', cache: 'no-cache', credentials: 'same-origin', headers: { "Content-Type": "application/json", "Authentication": "Bearer "+user_id+"-"+org_id+"" }, redirect: 'follow', referrerPolicy: 'no-referrer', body: data, }) .then(response => { response.text().then(function(text) { //console.log('response text', text); if(text.includes('syntax error') || text.includes('Exception')) { window.localStorage.setItem('reload', stepCount); console.log('response text error php'); showLoading(); pantallaStepNone(); showReload(); } else { if(typeFile =='js'){ }else if(typeFile == 'css'){ createCssIframe(text, idDiv); }else if(typeFile == 'html'){ if(window.localStorage.getItem('reload')){ window.localStorage.removeItem('reload'); Q('#errorReload').classList.remove('showFlex'); } createAppHtml(text, idDiv); btnDis('next' ,'false'); } } }) }) .catch(error => { console.log('Error:', error); btnDis('next' ,'false'); }); }; var fetchStepHTML = function(estimate){ console.log('step', StepDisplay[stepCount]); var sentget = JSON.stringify(estimate); var p = urlStep+'/'+StepDisplay[stepCount]+'/'+f.getTime(); requestFilesPOST(p, 'html', StepDisplay[stepCount], sentget); }; var llamarHTML = function(estimate){ fetchStepHTML(estimate); Q(".navRoofCal").style.display="flex"; }; var back =function(){ if(stepCount > 0){ stepCount--; } showLoading(); window.localStorage.removeItem('reload'); Q('#errorReload').classList.remove('showFlex'); btnDis('next' ,'false'); calculator.step = stepCount; setLS('calculator', calculator); if(Q("#"+StepDisplay[stepCount]) == undefined){ fetchStepHTML(estimate); }else{ showLoading(); stepActive() } }; var next =function(){ showLoading(); if(StepDisplay[stepCount] == 'Address'){ var tildes = ['á','é','í','ó','ú','ä','ë','ï','ö','ü','Á','É','Í','Ó','Ú','Ä','Ë','Ï','Ö','Ü']; var sintildes=['a','e','i','o','u','a','e','i','o','u','A','E','I','O','U','A','E','I','O','U',]; var addressVal= Q("#address").value.split(''); var addressNew = ''; for (var i in addressVal) { if(addressVal[i]){ for (var e in tildes) { if(addressVal[i].indexOf(tildes[e]) > -1){ addressVal[i]=addressVal[i].replace(tildes[e], sintildes[e]); } } addressNew+=addressVal[i]; } } estimate.address = addressNew; } stepCount++; if(window.localStorage.getItem('reload') == stepCount){ showReload(); } if(StepDisplay[stepCount] == 'Username'){ estimate.otherdetails = Q("#other-details").value; } if(StepDisplay[stepCount] == 'Verify'){ estimate.firsname = Q("#firsname").value; estimate.lastname = Q("#lastname").value; estimate.phone = Q("#phone").value; estimate.email = Q("#email").value; } if(StepDisplay[stepCount] == 'End'){ estimate.code = Q("#code").value; estimate.idEst = Q("#idEst").value; } setLS('estimate', estimate); calculator.step = stepCount; setLS('calculator', calculator); if(Q("#"+StepDisplay[stepCount]) == undefined && StepDisplay[stepCount] != 'End'){ llamarHTML(estimate); } else if(StepDisplay[stepCount] == 'Address' && !Q("#address")){ // si fallo antes volver a llamar Q("#"+StepDisplay[stepCount]).remove(); llamarHTML(estimate); } else if(StepDisplay[stepCount] == 'Verify'){ var validFinal = validFormUser(); if(validFinal=='false'){ // siempre volver actualizar esta vista Q("#"+StepDisplay[stepCount]).remove(); llamarHTML(estimate); }else{ showLoading(); back(); } } else if(StepDisplay[stepCount] == 'End' ){ // si fallo antes volver a llamar if(Q("#codeSMS")){ Q("#codeSMS").style.display="none"; } var data= { user_id: estimate.user_id, org_id: estimate.org_id, code: estimate.code, idEst: estimate.idEst, }; fetch(urlSendcode+"/"+f.getTime(), { method: 'POST', body: JSON.stringify(data), headers:{'Content-Type': 'application/json'} }).then(res => res.json()) .catch(error => {console.error('Error:', error);}) .then(response => { console.log('response', response) //debugger; if(response.respSMS.status){ if(Q("#"+StepDisplay[stepCount])){Q("#"+StepDisplay[stepCount]).remove();} llamarHTML(estimate); if(redirect==1){ redirection(opt, uri, time); } } else{ showLoading(); back(); if(Q("#codeSMS")){ Q("#codeSMS").style.display="block"; } } }); } else{ showLoading(); validations(); validNext(); } }; var formZip = function(e) { e.preventDefault(); var zipVal = Q(".zipcode-input").value; if(allZip==1 && zipVal.length==5){ Q(".form-field-error").style.display="none"; // Q("#Zipcode").style.display="none"; estimate.zipcode = zipVal; estimate.idEst = Q("#idEst").value; setLS('estimate', estimate); next(); } else if(zip.includes(zipVal) && zipVal.length==5){ Q(".form-field-error").style.display="none"; // Q("#Zipcode").style.display="none"; estimate.zipcode = zipVal; estimate.idEst = Q("#idEst").value; setLS('estimate', estimate); next(); } else{ Q(".form-field-error").style.display="block"; } } var closeRoofCal = function() { Q("#contentRoofCal").style.display="none"; Q('.headRoofCal').style.display="none"; document.querySelector('#btnOpenRoofCal').classList.remove('btnNone'); document.querySelector("#"+appRoofCal).classList.remove('appActive'); if(StepDisplay[stepCount]=='End'){resetPantallas();} }; var newEst = function() { if(StepDisplay[stepCount]=='End'){resetPantallas();} openRoofCal(); }; var resetPantallas = function(){ var steps = iframeLoad.querySelectorAll('.pantallaStep'); steps.forEach( function(e, i) { e.remove(); }); window.localStorage.clear(); stepCount=0; calculator.step = stepCount; setLS('calculator', calculator); var newEst = iniEst; setLS('estimate', newEst); estimate =newEst; }; function copyGoogleMapsStylesToIframe(iframe) { const iframeHead = iframe.head; var checkStyleMapLoaded = setInterval(function () { if(!Q("#GoogleMapsStylesPlace")){ // console.log('buscando estilos de map place') const parentStyles = window.parent.document.head.querySelectorAll("style"); parentStyles.forEach(style => { if (style.innerHTML.includes(".pac-container")) { // Solo copiar estilos de Google Maps const clonedStyle = document.createElement('style'); clonedStyle.innerHTML = style.innerHTML; clonedStyle.id = 'GoogleMapsStylesPlace'; iframeHead.appendChild(clonedStyle); // console.log('estilos de map place COPIADOS') clearInterval(checkStyleMapLoaded); } }); } }, 200); // Verifica cada 200ms } function repositionPacContainer(iframe) { setTimeout(() => { const pacContainer = iframe.querySelector(".pac-container"); const input = iframe.querySelector("#address"); if (pacContainer && input) { const rect = input.getBoundingClientRect(); pacContainer.style.position = "absolute"; pacContainer.style.top = `${rect.bottom}px`; pacContainer.style.left = `${rect.left}px`; pacContainer.style.width = `${rect.width}px`; pacContainer.style.zIndex = "10000"; // console.log('repositionPacContainer', pacContainer) } }, 300); } function initMapPaceRoofCal() { var searchInput = '#address'; const myLatLng = { lat: 42.1630697, lng: -71.5090529 }; if(Object.keys(ip_info).length>0){ myLatLng.lat = ip_info?.lat; myLatLng.lng = ip_info?.lon; } console.log('lat', myLatLng.lat, 'lng', myLatLng.lng); const mapElement = Q("#map"); if (!mapElement) { console.log("No se encontró el elemento #map dentro del iframe"); return; } const map = new google.maps.Map(mapElement, { center: myLatLng, zoom: 18, mapTypeId: "satellite" //"roadmap | satellite", }); // Create the search box and link it to the UI element. const input = Q(searchInput); const searchBox = new google.maps.places.SearchBox(input); //map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); // Bias the SearchBox results towards current map's viewport. map.addListener("bounds_changed", () => { searchBox.setBounds(map.getBounds()); }); let markers = []; // Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener("places_changed", () => { const places = searchBox.getPlaces(); if (places.length == 0) { return; } // Clear out the old markers. markers.forEach((marker) => { marker.setMap(null); }); markers = []; // For each place, get the icon, name and location. //const bounds = new google.maps.LatLngBounds(); // Llama a la función para geocodificar la dirección y dibujar el polígono let e = searchBox.getPlaces(); if(0!=e.length){ // console.log('getPlaces', e) // geocodeAddress(e[0].formatted_address); } places.forEach((place) => { if (!place.geometry || !place.geometry.location) { console.log("Returned place contains no geometry"); return; } map.panTo(place.geometry.location); map.setZoom(19); const icon = { url: place.icon, size: new google.maps.Size(71, 71), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(17, 34), scaledSize: new google.maps.Size(25, 25), }; // Create a marker for each place. markers.push( new google.maps.Marker({ map, //icon, title: place.name, position: place.geometry.location, }) ); // if (place.geometry.viewport) { // // Only geocodes have viewport. // bounds.union(place.geometry.viewport); // } else { // bounds.extend(place.geometry.location); // } estimate.location = {lat: place.geometry.location.lat(), lng: place.geometry.location.lng()}; setLS('estimate', estimate); }); //map.fitBounds(bounds); }); /*function geocodeAddress(address) { const geocoder = new google.maps.Geocoder(); geocoder.geocode({'address': address}, function(results, status) { if (status === 'OK') { const location = results[0].geometry.location; map.setCenter(location); // Dibuja un polígono alrededor de la ubicación obtenida drawPolygon(location); } else { alert('Geocode was not successful for the following reason: ' + status); } }); }*/ function drawPolygon(location) { const bounds = [ {lat: location.lat() + 0.0001, lng: location.lng() - 0.0001}, {lat: location.lat() + 0.0001, lng: location.lng() + 0.0001}, {lat: location.lat() - 0.0001, lng: location.lng() + 0.0001}, {lat: location.lat() - 0.0001, lng: location.lng() - 0.0001} ]; const polygon = new google.maps.Polygon({ paths: bounds, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35, editable: true, draggable: true }); polygon.setMap(map); if (selectedShape) { selectedShape.setMap(null); } selectedShape = polygon; google.maps.event.addListener(polygon.getPath(), 'set_at', calculateArea); google.maps.event.addListener(polygon.getPath(), 'insert_at', calculateArea); calculateArea(); } function calculateArea() { const area = google.maps.geometry.spherical.computeArea(selectedShape.getPath()); alert('Área del techo: ' + area.toFixed(2) + ' metros cuadrados'); } }; var validations = function(){ if(StepDisplay[stepCount] == 'Zipcode'){ //setTimeout(function(){Q("#zipcode").value ='01757';}, 1000); setTimeout(function(){ console.log('Zipcode focus'); Q("#zipcode").focus(); }, 500); console.log('Zipcode', estimate) } if(stepCount>0 && StepDisplay[stepCount-1].indexOf('customerStep-')>-1){ let idQuest = StepDisplay[stepCount-1].split('-'); let inputName = "input[name='item"+idQuest[1]+"']"; let items = '.item'+idQuest[1]; let multiple = "#multiple"+idQuest[1]; let questElem = "questID"+idQuest[1]; let questName = Q("#questName"+idQuest[1]).value; let countQuest =stepCount-2; estimate.quest[countQuest]={ questName: questName, answers: [] }; if(Q(inputName)){ estimate.quest[countQuest].answers = [Q(inputName).value]; } else if(Q(multiple).value==1 && iframeLoad.querySelectorAll(items).length>0){ valItems = []; let contItem = 0; iframeLoad.querySelectorAll(items).forEach( function(e, i) { //console.log('check ', e.checked) if(e.checked){ valItems[contItem]=e.value; contItem++; } }); estimate.quest[countQuest].answers = valItems; } else{ estimate.quest[countQuest].answers = []; } if(estimate.quest[countQuest].answers.length==0){ alert("You must select one of the options."); back(); }else{ setLS('estimate', estimate); } } if(StepDisplay[stepCount] == 'Address'){ console.log('cargando MapPlace') if(Q("#address").value.length <= 4){ initMapPaceRoofCal(); //cpiando estilo de google fuera del iframe copyGoogleMapsStylesToIframe(iframeLoad); } } if(StepDisplay[stepCount] == 'End'){ Q(".navRoofCal").style.display="none"; } }; var reloadHTML = function(){ Q('#errorReload').classList.remove('showFlex'); showLoading(); if(Q("#"+StepDisplay[window.localStorage.getItem('reload')])){ Q("#"+StepDisplay[window.localStorage.getItem('reload')]).remove(); } llamarHTML(estimate); }; var showReload = function(){ if(Q('#errorReload').classList.length == 0 || window.localStorage.getItem('reload') == stepCount){ Q('#errorReload').classList.add('showFlex'); } else{ window.localStorage.removeItem('reload'); Q('#errorReload').classList.remove('showFlex'); Q('#loadingRoofCal').classList.remove('show'); } }; var showErrorForm = function(elem, msj, show){ if(elem){ if(show==0){ elem.style.display="none"; } else{ elem.innerHTML=msj; elem.style.display="block"; } } }; var validNext = function(){ var stop = 'false'; if(StepDisplay[stepCount] == 'Address'){ if( Q("#address").value.trim().length <= 1 ){ stop = 'true'; }else{ repositionPacContainer(iframeLoad); } } if(StepDisplay[stepCount] == 'Username'){ if( Q("#firsname").value.trim().length == 0 || Q("#lastname").value.trim().length == 0 || Q("#phone").value.trim().length == 0 || Q("#email").value.trim().length == 0 ){ stop = 'true'; } } if(StepDisplay[stepCount] == 'Verify'){ if( Q("#code").value.trim().length < 4){ stop = 'true'; } } btnDis('next' , stop); }; var validFormUser = function(){ var stop = 'false'; var logfirstname = Q(".error-firstname"); var loglastname = Q(".error-lastname"); var logphone = Q(".error-phone"); var logemail = Q(".error-email"); var msj = ""; showErrorForm(logfirstname, msj, 0); showErrorForm(loglastname, msj, 0); showErrorForm(logphone, msj, 0); showErrorForm(logemail, msj, 0); var emailRegex = /^[-\w.%+]{1,64}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/i; if(Q("#firsname").value.trim().length == 0){ msj='First name is required'; showErrorForm(logfirstname, msj, 1); stop = 'true'; } if(Q("#firsname").value.trim().length < 2){ msj='First name is invalid'; showErrorForm(logfirstname, msj, 1); stop = 'true'; } if(Q("#lastname").value.trim().length == 0){ msj='Last name is required'; showErrorForm(loglastname, msj, 1); stop = 'true'; } if(Q("#lastname").value.trim().length < 2){ msj='Last name is invalid'; showErrorForm(loglastname, msj, 1); stop = 'true'; } if(Q("#phone").value.trim().length == 0){ msj='Phone is required'; showErrorForm(logphone, msj, 1); stop = 'true'; }else{ var valNroUSA = formatPhone(Q("#phone").value, "USA"); var valNroCOL = formatPhone(Q("#phone").value, "COL"); var valNroPEP = formatPhone(Q("#phone").value, "PEP"); var valNroBRA = formatPhone(Q("#phone").value, "BRA"); if( !valNroUSA && !valNroCOL && !valNroPEP && !valNroBRA ){ msj='Phone is invalid'; showErrorForm(logphone, msj, 1); stop = 'true'; } } if(Q("#email").value.trim().length == 0){ msj='Email is invalid'; showErrorForm(logemail, msj, 1); stop = 'true'; } if(!emailRegex.test(Q("#email").value)){ msj='Email is required'; showErrorForm(logemail, msj, 1); stop = 'true'; } if(msj.length>0){stop = 'true';} btnDis('next' , stop); return stop; }; var formatPhone= function(phoneNumber, country) { // var phoneRe = /^[2-9]\d{2}[2-9]\d{2}\d{4}$/; // var digits = value.replace(/\D/g, ""); // return phoneRe.test(digits); const mobilePatterns = { USA: /^(?:\+1)?[2-9]\d{2}[2-9]\d{6}$/, // Solo móviles de EE.UU. COL: /^(?:\+57)?3\d{9}$/, // Solo celulares en Colombia (3XX-XXXXXXX) PEP: /^(?:\+57)?3(2|14|24|10)\d{7}$/, // Celulares en rangos PEP BRA: /^(?:\+55)?(?:[14689][1-9])9\d{8}$/ // Celulares en Brasil (+55 DDD 9XXXX-XXXX) }; const pattern = mobilePatterns[country.toUpperCase()]; if (!pattern) { throw new Error("País no soportado"); } return pattern.test(phoneNumber); }; var validFormatPhone = function (){ var nroVal=['0','1','2','3','4','5','6','7','8','9','+']; var str = Q("#phone").value.trim(); var nro = str.split(''); var nroFormat = ''; var contNro=0; var valid = false; for (var i in nro) { if(nro[i]){ valid = false; for (var e in nroVal) { if(nro[i] == nroVal[e]){ valid = true; } } if(valid){ contNro++; nroFormat+=''+nro[i]; } } } if(contNro!=10){ return false; }else{ Q("#phone").value = nroFormat; return true; } } var redirection = function(opt, uri, time){ setTimeout(function(){ if(opt==1){ window.location.href=window.location.origin } else{ window.location.href=uri; } }, time); }; // cargar estilos if(!document.querySelector('#btnIframeCSS')){ requestFiles(btnIframeCSS, 'cssDOM', 'btnIframeCSS').then(result =>{ if(document.querySelector('#btnIframeCSS')){ console.log('load btnIframeCSS') divBase.removeAttribute('style'); } }); } if(!Q('#cssMain')){ requestFiles(cssMain, 'css', 'cssMain'); } // agregando html al iframe var htmlDivMain = `
`; htmlDivMain+= `