PageSourceSearch

https://thecleanstart.com/wp-content/litespeed/js/3a69344929f1d59f405eb44899dd0a11.js?ver=d0a11

js thecleanstart.com collected 2026-10-04 14:56:05 UTC 34,895 bytes, 116 lines download raw bytes

1(function(){var chatOpen=!1;var history=[];var rawResponses=[];var sending=!1;var hasInteracted=!1;var suggestions=['What services do you offer?','How do I get a free quote?','Cleaning Tips & How-To\'s','Do you serve my area?','Customer Support','Are you hiring?'];var STORAGE_KEY='csp-chat-history';var STORAGE_RAW='csp-chat-raw';var STORAGE_TS='csp-chat-ts';var STORAGE_SESSION='csp-chat-session';var STORAGE_SESSION_STARTED='csp-chat-session-started';var STORAGE_SUMMARY_SENT='csp-chat-summary-sent';var CHAT_TTL=30*60*1000;var CHAT_IDLE_TIMEOUT=10*60*1000;var STATUS_IDLE='Typically replies instantly';var STATUS_THINKING='Thinking up a reply...';var pendingCloseReason='';var idleSummaryTimer=null;function isMobile(){return window.innerWidth<=480}
2function getSessionId(){try{var existing=localStorage.getItem(STORAGE_SESSION);if(existing)return existing;var created='chat-'+Date.now().toString(36)+'-'+Math.random().toString(36).slice(2,8);localStorage.setItem(STORAGE_SESSION,created);localStorage.removeItem(STORAGE_SUMMARY_SENT);return created}catch(e){return'chat-'+Date.now().toString(36)+'-'+Math.random().toString(36).slice(2,8)}}
3function getSessionStartedAt(){try{var existing=localStorage.getItem(STORAGE_SESSION_STARTED);if(existing)return existing;var created=new Date().toISOString();localStorage.setItem(STORAGE_SESSION_STARTED,created);localStorage.removeItem(STORAGE_SUMMARY_SENT);return created}catch(e){return new Date().toISOString()}}
4window.cspGetSessionId=getSessionId;window.cspGetSessionStartedAt=getSessionStartedAt;function hasUserMessages(){for(var i=0;i<history.length;i++){if(history[i].role==='user'&&String(history[i].content||'').trim())return!0}
5return!1}
6function hasSummarySent(){try{return localStorage.getItem(STORAGE_SUMMARY_SENT)==='1'}catch(e){return!1}}
7function markSummarySent(){try{localStorage.setItem(STORAGE_SUMMARY_SENT,'1')}catch(e){}}
8function clearIdleSummaryTimer(){if(idleSummaryTimer){clearTimeout(idleSummaryTimer);idleSummaryTimer=null}}
9function resetChatSession(){clearIdleSummaryTimer();try{localStorage.removeItem(STORAGE_KEY);localStorage.removeItem(STORAGE_RAW);localStorage.removeItem(STORAGE_TS);localStorage.removeItem(STORAGE_SESSION);localStorage.removeItem(STORAGE_SESSION_STARTED);localStorage.removeItem(STORAGE_SUMMARY_SENT)}catch(e){}
10history=[];rawResponses=[];pendingCloseReason=''}
11function getLastActivityTs(){try{var ts=localStorage.getItem(STORAGE_TS);return ts?Number(ts):0}catch(e){return 0}}
12function sendChatSummary(reason,opts){opts=opts||{};if(!hasUserMessages()||hasSummarySent())return;clearIdleSummaryTimer();markSummarySent();var payload=JSON.stringify({action:'end_session',messages:history,sessionId:getSessionId(),sessionStartedAt:getSessionStartedAt(),sessionEndedAt:new Date().toISOString(),endReason:reason,pageUrl:window.location.href,pageTitle:document.title});try{if(opts.useBeacon&&navigator.sendBeacon){var sent=navigator.sendBeacon('https://cleanstart-proxy-coral.vercel.app/api/chat',new Blob([payload],{type:'application/json'}));if(!sent){fetch('https://cleanstart-proxy-coral.vercel.app/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:payload,keepalive:!0}).catch(function(){})}}else{fetch('https://cleanstart-proxy-coral.vercel.app/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:payload,keepalive:!!opts.keepalive}).catch(function(){})}}catch(e){}
13if(opts.resetAfter)resetChatSession();}
14function finalizeIdleSession(){if(!hasUserMessages()||hasSummarySent())return;if(sending){pendingCloseReason='inactivity_timeout';return}
15sendChatSummary('inactivity_timeout',{keepalive:!0,resetAfter:!0});if(chatOpen){chatOpen=!1;document.body.classList.remove('csp-chat-open');document.getElementById('csp-chat-panel').classList.remove('open');document.getElementById('csp-chat-btn').classList.remove('mobile-hidden');setAssistantState('idle')}
16resetChatUi()}
17function scheduleIdleSummary(){clearIdleSummaryTimer();if(!hasUserMessages()||hasSummarySent())return;var lastActivityTs=getLastActivityTs();if(!lastActivityTs)return;var remaining=CHAT_IDLE_TIMEOUT-(Date.now()-lastActivityTs);if(remaining<=0){finalizeIdleSession();return}
18idleSummaryTimer=setTimeout(finalizeIdleSession,remaining)}
19function resetChatUi(){var msgs=document.getElementById('csp-chat-messages');if(msgs)msgs.textContent=''}
20function saveChat(){try{localStorage.setItem(STORAGE_KEY,JSON.stringify(history)
20);localStorage.setItem(STORAGE_RAW,JSON.stringify(rawResponses));localStorage.setItem(STORAGE_TS,String(Date.now()))}catch(e){}
21scheduleIdleSummary()}
22function clearChat(){resetChatSession()}
23function isChatExpired(){try{var ts=localStorage.getItem(STORAGE_TS);if(!ts)return!1;return(Date.now()-Number(ts))>CHAT_TTL}catch(e){return!1}}
24function showBadge(){var b=document.getElementById('csp-chat-badge');if(b)b.classList.add('show');}
25function hideBadge(){var b=document.getElementById('csp-chat-badge');if(b)b.classList.remove('show');}
26function setAssistantState(state){var panel=document.getElementById('csp-chat-panel');if(panel)panel.setAttribute('data-assistant-state',state);var btn=document.getElementById('csp-chat-btn');if(btn)btn.classList.toggle('thinking',state==='thinking');var status=document.getElementById('csp-chat-status');if(status)status.textContent=state==='thinking'?STATUS_THINKING:STATUS_IDLE}
27function initNudge(){setTimeout(function(){if(chatOpen)return;var nudge=document.getElementById('csp-chat-nudge');if(nudge){nudge.classList.add('show');nudge.onclick=function(){window.cspDismissNudge&&window.cspDismissNudge();window.cspToggleChat&&window.cspToggleChat()}}},4300)}
28window.cspDismissNudge=function(){var nudge=document.getElementById('csp-chat-nudge');if(nudge)nudge.classList.remove('show');try{sessionStorage.setItem('csp-nudge-dismissed','1')}catch(e){}};function addFeedbackButtons(div){var row=document.createElement('div');row.className='csp-msg-feedback';var thumbUp=document.createElement('button');thumbUp.textContent='\uD83D\uDC4D';thumbUp.title='Helpful';var thumbDown=document.createElement('button');thumbDown.textContent='\uD83D\uDC4E';thumbDown.title='Not helpful';thumbUp.onclick=function(){thumbUp.classList.add('selected');thumbDown.classList.remove('selected')};thumbDown.onclick=function(){thumbDown.classList.add('selected');thumbUp.classList.remove('selected')};var copyBtn=document.createElement('button');copyBtn.textContent='\uD83D\uDCCB';copyBtn.title='Copy message';copyBtn.onclick=function(){var msgText='';var children=div.childNodes;for(var i=0;i<children.length;i++){if(children[i]!==row)msgText+=children[i].textContent}
29navigator.clipboard.writeText(msgText.trim()).then(function(){copyBtn.textContent='\u2713';setTimeout(function(){copyBtn.textContent='\uD83D\uDCCB'},1500)})};row.appendChild(thumbUp);row.appendChild(thumbDown);row.appendChild(copyBtn);div.appendChild(row);div.addEventListener('touchstart',function(){row.classList.toggle('show')},{passive:!0})}
30function escapeHtml(text){return String(text||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')}
31function normalizeRawEntry(entry){if(typeof entry==='string')return{text:entry,rag:null};if(entry&&typeof entry==='object')return{text:String(entry.text||''),rag:entry.rag||null};return{text:'',rag:null}}
32function getRagMetaFromResponse(resp){var used=resp.headers.get('X-Cleanstart-Rag-Used')==='1';var matches=Number(resp.headers.get('X-Cleanstart-Rag-Matches')||'0');var titles=String(resp.headers.get('X-Cleanstart-Rag-Titles')||'').split(' | ').filter(
32Boolean);var links=String(resp.headers.get('X-Cleanstart-Rag-Links')||'').split('||').filter(Boolean).map(function(entry){var parts=entry.split('::');if(parts.length<2)return null;try{return{title:decodeURIComponent(parts[0]),path:decodeURIComponent(parts[1]),sourceType:parts[2]?decodeURIComponent(parts[2]):'',sourceKind:parts[3]?decodeURIComponent(parts[3]):'',sourceSection:parts[4]?decodeURIComponent(parts[4]):'',sourcePath:parts[5]?decodeURIComponent(parts[5]):''}}catch(e){return null}}).filter(Boolean);var linkMap=String(resp.headers.get('X-Cleanstart-Link-Map')||'').split('||').filter(Boolean).map(function(entry){var parts=entry.split('::');if(parts.length<2)return null;try{return{name:decodeURIComponent(parts[0]),url:decodeURIComponent(parts[1])}}catch(e){return null}}).filter(Boolean);if(!used&&!matches&&!titles.length&&!links.length)return null;return{used:used,matches:matches,titles:titles,links:links,linkMap:linkMap}}
33function renderRagItems(items){var html='<div class="csp-msg-rag-pills">';for(var i=0;i<items.length;i++){var kindLabel=items[i].sourceKind==='website'?(items[i].sourceSection||'Website'):(items[i].sourceKind==='document'?'Document':'Source');var badge='<span class="csp-msg-rag-pill-kind">'+kindLabel+'</span>';var pathLine=items[i].sourceKind==='website'&&items[i].sourcePath?'<span class="csp-msg-rag-pill-path">'+escapeHtml(items[i].sourcePath)+'</span>':'';var body='<span class="csp-msg-rag-pill-title">'+badge+'<span>'+escapeHtml(items[i].title)+'</span></span>'+pathLine;var isDocument=items[i].sourceKind==='document'||(items[i].sourceType&&items[i].sourceType!=='html');if(items[i].path&&!isDocument){html+='<a href="'+items[i].path+'" class="csp-msg-rag-pill" target="_blank">'+body+'</a>'}else{html+='<span class="csp-msg-rag-pill">'+body+'</span>'}}
34html+='</div>';return html}
35function renderRagMeta(rag,citedPaths){if(!rag||!rag.used||(!rag.titles||!rag.titles.length)&&(!rag.links||!rag.links.length))return'';var ragItems=rag.links&&rag.links.length?rag.links:((rag.titles||[]).map(function(title){return{title:title,path:'',sourceType:'',sourceKind:''}}));if(!citedPaths||!citedPaths.length)return'';ragItems=ragItems.filter(function(item){for(var ci=0;ci<citedPaths.length;ci++){if(item.path&&citedPaths[ci]&&(item.path===citedPaths[ci]||item.sourcePath===citedPaths[ci]||item.title===citedPaths[ci]))return!0}
36return!1});if(!ragItems.length)return'';var seenTitles={};ragItems=ragItems.filter(function(item){var key=item.title||item.path||'';if(!key||seenTitles[key])return!1;seenTitles[key]=!0;return!0});if(!ragItems.length)return'';var websiteItems=ragItems.filter(function(item){return item.sourceKind==='website'||item.sourceType==='html'});var documentItems=ragItems.filter(function(item){return item.sourceKind==='document'||(item.sourceType&&item.sourceType!=='html')});var otherItems=ragItems.filter(function(item){return websiteItems.indexOf(item)===-1&&documentItems.indexOf(item)===-1});var html='<div class="csp-msg-rag"><span class="csp-msg-rag-label">Sources used</span>';if(websiteItems.length){html+='<div class="csp-msg-rag-group"><span class="csp-msg-rag-group-label">Website pages</span>'+renderRagItems(websiteItems)+'</div>'}
37if(documentItems.length){html+='<div class="csp-msg-rag-group"><span class="csp-msg-rag-group-label">Documents</span>'+renderRagItems(documentItems)+'</div>'}
38if(otherItems.length){html+='<div class="csp-msg-rag-group"><span class="csp-msg-rag-group-label">Other sources</span>'+renderRagItems(otherItems)+'</div>'}
39html+='</div>';return html}
40function renderInlineCitation(citation){var isDoc=citation.path&&citation.path.indexOf('/sources/')===0;if(isDoc){return'<span class="csp-msg-inline-cite" title="Source: '+escapeHtml(citation.title)+'">'+escapeHtml(citation.title)+'</span>'}
41return'<a href="'+citation.path+'" class="csp-msg-inline-cite" target="_blank" title="Open source: '+escapeHtml(citation.title)+'">'+escapeHtml(citation.title)+'</a>'}
42function isQuotedLine(line){return/^&quot;.*&quot;(?:\s*<a\b[^>]*class="csp-msg-inline-cite"[^>]*>.*?<\/a>)*$/.test(line)}
43function renderMarkdown(text,rag){var citations=[];var seenCitations={};var citationTokens=[];var clean=text.replace(/\[Source:\s*([^|]+)\|([^\]]+)\]/g,function(_,title,path){var citation={title:title.trim(),path:path.trim()};var citationKey=citation.title+'|'+citation.path;if(!seenCitations[citationKey]){citations.push(citation);seenCitations[citationKey]=!0}
44var token='@@CSPCITE'+citationTokens.length+'@@';citationTokens.push({token:token,citation:citation});return token}).trim();var escaped=escapeHtml(clean);escaped=escaped.replace(/!\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)/g,function(_,alt,imgUrl){var trusted=imgUrl.indexOf('.supabase.co/storage/v1/object/public/product-images/')!==-1;if(!trusted)return'';return'<img src="'+imgUrl+'" alt="'+alt+'" class="csp-msg-img" loading="lazy">'});escaped=escaped.replace(/\[([^\]]+)\]\(((?:\/|https?:\/\/)[^)]+)\)/g,function(_,linkText,linkUrl){var isTrustedDomain=linkUrl.indexOf('thecleanstart.com')!==-1||linkUrl.indexOf('thecleanstart.myshopify.com')!==-1||linkUrl.charAt(0)==='/';if(isTrustedDomain)return'<a href="'+linkUrl+'" class="csp-msg-link" target="_blank">'+linkText+'</a>';if(!rag||!rag.linkMap||!rag.linkMap.length)return linkText;var verified=!1;for(var vi=0;vi<rag.linkMap.length;vi++){if(rag.linkMap[vi].url===linkUrl)verified=!0}
45return verified?'<a href="'+linkUrl+'" class="csp-msg-link" target="_blank">'+linkText+'</a>':linkText});escaped=escaped.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>');for(var tokenIndex=0;tokenIndex<citationTokens.length;tokenIndex++){escaped=escaped.replace(citationTokens[tokenIndex].token,renderInlineCitation(citationTokens[tokenIndex].citation))}
46var lines=escaped.split('\n');var html='';var inList=!1;for(var i=0;i<lines.length;i++){var line=lines[i].trim();
46var headingMatch=line.match(/^(#{1,6})\s+(.+)$/);if(headingMatch){if(inList){html+='</ul>';inList=!1}
47var hLevel=Math.min(headingMatch[1].length+1,6);html+='<h'+hLevel+' class="csp-msg-h">'+headingMatch[2]+'</h'+hLevel+'>';continue}
48if(line.match(/^-{3,}$/)){if(inList){html+='</ul>';inList=!1}
49html+='<hr class="csp-msg-hr">';continue}
50if(line.match(/^[-\u2022]\s+/)){var listContent=line.replace(/^[-\u2022]\s+/,'');if(isQuotedLine(listContent)){if(inList){html+='</ul>';inList=!1}
51html+='<div class="csp-msg-quote">'+listContent+'</div>';continue}
52if(!inList){html+='<ul>';inList=!0}
53html+='<li>'+listContent+'</li>'}else{if(inList){html+='</ul>';inList=!1}
54if(line){if(isQuotedLine(line)){html+='<div class="csp-msg-quote">'+line+'</div>'}else{html+=line+'<br>'}}}}
55if(inList)html+='</ul>';html=html.replace(/<br>$/,'');var STATIC_LINK_PHRASES=[{pattern:'Cleanstart Distributing portal',url:'/distributing/'},{pattern:'Cleanstart Distributing catalog',url:'/distributing/'},{pattern:'Cleanstart Distributing',url:'/distributing/'},{pattern:'Distributing portal',url:'/distributing/'},{pattern:'Distributing catalog',url:'/distributing/'},{pattern:'Cleanstart University',url:'/cleanstart-university/'},{pattern:'Tools of the Trade starter kit',url:'/tools-of-the-trade-starter-kit/'},{pattern:'Tools of the Trade',url:'/tools-of-the-trade-starter-kit/'}];for(var sl=0;sl<STATIC_LINK_PHRASES.length;sl++){var sEntry=STATIC_LINK_PHRASES[sl];var sPatLower=sEntry.pattern.toLowerCase();var searchFrom=0;for(;;){var sPos=html.toLowerCase().indexOf(sPatLower,searchFrom);if(sPos===-1)break;var preChunk=html.substring(0,sPos);var lastOpenA=preChunk.lastIndexOf('<a ');var lastCloseA=preChunk.lastIndexOf('</a>');if(lastOpenA>lastCloseA){searchFrom=sPos+sPatLower.length;continue}
56if(preChunk.lastIndexOf('<')>preChunk.lastIndexOf('>')){searchFrom=sPos+sPatLower.length;continue}
57var origText=html.substring(sPos,sPos+sEntry.pattern.length);var sReplace='<a href="'+sEntry.url+'" class="csp-msg-link" target="_blank">'+origText+'</a>';html=html.substring(0,sPos)+sReplace+html.substring(sPos+sEntry.pattern.length);searchFrom=sPos+sReplace.length}}
58if(rag&&rag.linkMap&&rag.linkMap.length){var htmlLower=html.toLowerCase();for(var lm=0;lm<rag.linkMap.length;lm++){var entry=rag.linkMap[lm];if(!entry.name||!entry.url||entry.name.length<4)continue;var searchName=entry.name.toLowerCase();var pos=htmlLower.indexOf(searchName);if(pos===-1){var altName=searchName.replace(/-/g,' ');if(altName!==searchName){pos=htmlLower.indexOf(altName);if(pos!==-1)searchName=altName}}
59if(pos===-1){var altName2=searchName.replace(/\s+/g,'-');if(altName2!==searchName){pos=htmlLower.indexOf(altName2);if(pos!==-1)searchName=altName2}}
60if(pos===-1)continue;var chunk=html.substring(Math.max(0,pos-300),pos);if(chunk.lastIndexOf('<a')>chunk.lastIndexOf('</a>'))continue;if(chunk.lastIndexOf('<span class="csp-msg-inline-cite"')>chunk.lastIndexOf('</span>'))continue;if(chunk.lastIndexOf('<')>chunk.lastIndexOf('>'))continue;var after=html.substring(pos,Math.min(html.length,pos+searchName.length+10));if(after.indexOf('</a>')!==-1&&after.indexOf('<a')===-1)continue;var originalText=html.substring(pos,pos+searchName.length);html=html.substring(0,pos)+'<a href="'+escapeHtml(entry.url)+'" class="csp-msg-link" target="_blank">'+originalText+'</a>'+html.substring(pos+searchName.length);htmlLower=html.toLowerCase()}}
61var citedPaths=citations.map(function(c){return c.path}).concat(citations.map(function(c){return c.title}));var dedupedCitations=[];var seenCiteTitles={};for(var dc=0;dc<citations.length;dc++){var citeKey=citations[dc].title;if(!seenCiteTitles[citeKey]){seenCiteTitles[citeKey]=!0;dedupedCitations.push(citations[dc])}}
62return html}
63function restoreChat(){try{if(isChatExpired()){clearChat();return!1}
64var saved=localStorage.getItem(STORAGE_KEY);var savedRaw=localStorage.getItem(STORAGE_RAW);if(!saved)return!1;var msgs=JSON.parse(saved);var raws=savedRaw?JSON.parse(savedRaw):[];if(!msgs.length)return!1;history=msgs;rawResponses=raws;if(hasUserMessages()&&(Date.now()-getLastActivityTs())>=CHAT_IDLE_TIMEOUT){sendChatSummary('inactivity_timeout',{keepalive:!0,resetAfter:!0});return!1}
65hasInteracted=!0;var container=document.getElementById('csp-chat-messages');var rawIdx=0;for(var i=0;i<msgs.length;i++){var div=document.createElement('div');if(msgs[i].role==='user'){div.className='csp-msg csp-msg-user';div.textContent=msgs[i].content}else{div.className='csp-msg csp-msg-bot';var rawEntry=normalizeRawEntry(raws[rawIdx]);var rawText=rawEntry.text||msgs[i].content;rawIdx++;if(rawEntry.rag||rawText.indexOf('[')>-1||rawText.indexOf('**')>-1){var safeHtml=renderMarkdown(rawText,rawEntry.rag);var template=document.createElement('template');template.innerHTML=safeHtml;div.appendChild(template.content)}else{div.textContent=rawText}
66addFeedbackButtons(div)}
67container.appendChild(div)}
68container.scrollTop=container.scrollHeight;scheduleIdleSummary();return!0}catch(e){return!1}}
69window.cspClearChat=function(){sendChatSummary('chat_cleared',{keepalive:!0});clearChat();resetChatUi();cspAddBotHtml("Hi! I'm Dusty, Cleanstart's virtual assistant. How can I help you today?");showSuggestions()};window.cspToggleChat=function(){if(chatOpen){window.cspCloseChat();return}
70chatOpen=!0;hasInteracted=!0;
70try{sessionStorage.setItem('csp-chat-was-open','1')}catch(e){}
71document.body.classList.toggle('csp-chat-open',chatOpen);document.getElementById('csp-chat-panel').classList.toggle('open',chatOpen);if(chatOpen){hideBadge();window.cspDismissNudge&&window.cspDismissNudge();if(isMobile())document.getElementById('csp-chat-btn').classList.add('mobile-hidden');}else{document.getElementById('csp-chat-btn').classList.remove('mobile-hidden')}
72if(chatOpen&&history.length===0){var restored=restoreChat();if(!restored){cspAddBotHtml("Hi! I'm Dusty, Cleanstart's virtual assistant. How can I help you today?");showSuggestions()}}
73setAssistantState(sending?'thinking':'idle');if(chatOpen)document.getElementById('csp-chat-input').focus();};window.cspCloseChat=function(){if(!chatOpen)return;chatOpen=!1;try{sessionStorage.removeItem('csp-chat-was-open')}catch(e){}
74document.body.classList.remove('csp-chat-open');document.getElementById('csp-chat-panel').classList.remove('open');document.getElementById('csp-chat-btn').classList.remove('mobile-hidden');setAssistantState(sending?'thinking':'idle');if(sending){pendingCloseReason='chat_closed';return}
75if(!hasUserMessages()){resetChatSession()}
76sendChatSummary('chat_closed',{keepalive:!0,resetAfter:!0});resetChatUi()};(function(){var chatMsgs=document.getElementById('csp-chat-messages');if(chatMsgs){chatMsgs.addEventListener('click',function(e){var a=e.target;while(a&&a!==chatMsgs&&a.tagName!=='A')a=a.parentElement;if(!a||a.tagName!=='A')return;var href=(a.getAttribute('href')||'').toLowerCase();var text=(a.textContent||'').toLowerCase();if(href.indexOf('quote')!==-1||text.indexOf('free quote')!==-1||text.indexOf('get a quote')!==-1||text.indexOf('request a quote')!==-1){e.preventDefault();if(window.cspOpenQuote)window.cspOpenQuote();}})}})();function showSuggestions(){var msgs=document.getElementById('csp-chat-messages');var wrap=document.createElement('div');wrap.className='csp-suggestions';wrap.id='csp-suggestions';for(var i=0;i<suggestions.length;i++){var btn=document.createElement('button');btn.textContent=suggestions[i];if(window.cspMakeMagnetic)window.cspMakeMagnetic(btn);btn.onclick=(function(q){return function(){var el=document.getElementById('csp-suggestions');if(el)el.remove();if(q==='Customer Support'){if(window.cspOpenSupport){window.cspCloseChat();window.cspOpenSupport()}return}
77document.getElementById('csp-chat-input').value=q;window.cspSendMsg&&window.cspSendMsg()}})(suggestions[i]);wrap.appendChild(btn)}
78msgs.appendChild(wrap);msgs.scrollTop=msgs.scrollHeight}
79function initResize(){var panel=document.getElementById('csp-chat-panel');var handle=document.getElementById('csp-chat-resize');var topHandle=document.getElementById('csp-chat-resize-top');var cornerHandle=document.getElementById('csp-chat-resize-corner');if(!panel||!handle)return;var MIN_W=360,MAX_W=Math.min(720,window.innerWidth),DEFAULT_W=440,KEY_W='csp-chat-panel-width';var MIN_H=400,DEFAULT_H=window.innerHeight,KEY_H='csp-chat-panel-height';var maxH=function(){return window.innerHeight};var storedW=parseInt(localStorage.getItem(KEY_W)||'',10);var initialW=(isFinite(storedW)&&storedW>=MIN_W&&storedW<=MAX_W)?storedW:DEFAULT_W;var storedH=parseInt(localStorage.getItem(KEY_H)||'',10);var initialH=(isFinite(storedH)&&storedH>=MIN_H&&storedH<=maxH())?storedH:DEFAULT_H;panel.style.setProperty('--csp-panel-width',initialW+'px');panel.style.setProperty('--csp-panel-height',initialH+'px');function setupHandle(el,mode){if(!el)return;var dragging=!1;el.addEventListener('pointerdown',function(e){if(window.innerWidth<=480)return;dragging=!0;el.classList.add('dragging');el.setPointerCapture(e.pointerId);document.body.style.userSelect='none';e.preventDefault()});el.addEventListener('pointermove',function(e){if(!dragging)return;if(mode==='width'||mode==='corner'){var w=window.innerWidth-e.clientX;if(w<MIN_W)w=MIN_W;if(w>MAX_W)w=MAX_W;panel.style.setProperty('--csp-panel-width',w+'px')}
80if(mode==='height'||mode==='corner'){var h=window.innerHeight-e.clientY;if(h<MIN_H)h=MIN_H;if(h>maxH())h=maxH();panel.style.setProperty('--csp-panel-height',h+'px')}});function endDrag(e){if(!dragging)return;dragging=!1;el.classList.remove('dragging');try{el.releasePointerCapture(e.pointerId)}catch(err){}
81document.body.style.userSelect='';var w=parseInt(panel.style.getPropertyValue('--csp-panel-width'),10);var h=parseInt(panel.style.getPropertyValue('--csp-panel-height'),10);if(isFinite(w))localStorage.setItem(KEY_W,String(w));if(isFinite(h))localStorage.setItem(KEY_H,String(h));}
82el.addEventListener('pointerup',endDrag);el.addEventListener('pointercancel',endDrag)}
83setupHandle(handle,'width');setupHandle(topHandle,'height');setupHandle(cornerHandle,'corner');var kbTimer=null;handle.addEventListener('keydown',function(e){if(window.innerWidth<=480)return;var curr=parseInt(panel.style.getPropertyValue('--csp-panel-width'),10);if(!isFinite(curr))curr=DEFAULT_W;var next=curr;if(e.key==='ArrowLeft')next=Math.min(MAX_W,curr+20);else if(e.key==='ArrowRight')next=Math.max(MIN_W,curr-20);else return;e.preventDefault();panel.style.setProperty('--csp-panel-width',next+'px');if(kbTimer)clearTimeout(kbTimer);kbTimer=setTimeout(function(){localStorage.setItem(KEY_W,String(next))},500)});if(topHandle){var kbTimer2=null;topHandle.addEventListener('keydown',function(e){if(window.innerWidth<=480)return;var curr=parseInt(panel.style.getPropertyValue('--csp-panel-height'),10);if(!isFinite(curr))curr=DEFAULT_H;var next=curr;if(e.key==='ArrowUp')next=Math.min(maxH(),curr+20);else if(e.key==='ArrowDown')next=Math.max(MIN_H,curr-20);else return;e.preventDefault();panel.style.setProperty('--csp-panel-height',next+'px');if(kbTimer2)clearTimeout(kbTimer2);kbTimer2=setTimeout(function(){localStorage.setItem(KEY_H,String(next))},500)})}}
84function transformProductMarkdown(root){if(!root)return;function norm(s){return(s||'').trim().toLowerCase().replace(/\s+/g,' ')}
85function alike(a,b){function alpha(s){return(s||'').toLowerCase().replace(/[^a-z0-9]+/g,' ').replace(/\s+/g,' ').trim()}
86var sa=alpha(a),sb=alpha(b);if(!sa||!sb)return!1;if(sa===sb)return!0;
86if(sa.length>=8&&sb.indexOf(sa)>=0)return!0;if(sb.length>=8&&sa.indexOf(sb)>=0)return!0;var wa=sa.split(' ').filter(function(w){return w.length>=3});var wb=sb.split(' ').filter(function(w){return w.length>=3});if(!wa.length||!wb.length)return!1;var setB={};for(var i=0;i<wb.length;i++)setB[wb[i]]=!0;var overlap=0;for(var j=0;j<wa.length;j++)if(setB[wa[j]])overlap++;var shorter=Math.min(wa.length,wb.length);return shorter>0&&(overlap/shorter)>=0.6}
87function buildBrand(linkText){if(/^one cleaning\b/i.test(linkText))return'ONE CLEANING';if(/^cleanstart\b/i.test(linkText))return'CLEANSTART';var first=linkText.split(/[\s\-:]/)[0];return(first&&first.length>2)?first.toUpperCase():''}
88function buildCard(imgSrc,linkText,href,description,price){var card=document.createElement('div');card.className='csp-product-card';var imgEl=document.createElement('img');imgEl.className='csp-product-image';imgEl.src=imgSrc;imgEl.alt=linkText;imgEl.loading='lazy';var body=document.createElement('div');body.className='csp-product-body';var brand=buildBrand(linkText);if(brand){var b=document.createElement('div');b.className='csp-product-brand';b.textContent=brand;body.appendChild(b)}
89var n=document.createElement('div');n.className='csp-product-name';n.textContent=linkText;body.appendChild(n);if(price){var pr=document.createElement('div');pr.className='csp-product-price';pr.textContent=price;body.appendChild(pr)}
90if(description){var d=document.createElement('div');d.className='csp-product-desc';d.textContent=description;body.appendChild(d)}
91var cta=document.createElement('a');cta.className='csp-product-cta';cta.href=href;cta.target='_blank';cta.rel='noopener';cta.textContent='Shop \u2192';body.appendChild(cta);card.appendChild(imgEl);card.appendChild(body);return card}
92function extractPriceAfter(imgNode){var cur=imgNode.nextSibling;var collected=[];var accum='';var hops=0;while(cur&&hops<8){var isEl=cur.nodeType===1;if(isEl&&(cur.tagName==='IMG'||cur.tagName==='A'||cur.tagName==='UL'||cur.tagName==='OL'||cur.tagName==='DIV'||cur.tagName==='H2'||cur.tagName==='H3'||cur.tagName==='HR'))break;collected.push(cur);accum+=' '+(cur.textContent||'');hops++;if(/price/i.test(accum)){var m=accum.match(/\$(\d+(?:[.,]\d{2})?)/);if(m)return{price:'$'+m[1].replace(',',''),nodes:collected}}
93cur=cur.nextSibling}
94return null}
95var images=Array.prototype.slice.call(root.querySelectorAll('img'));for(var i=0;i<images.length;i++){var img=images[i];var imgAlt=norm(img.getAttribute('alt'));var imgSrc=img.getAttribute('src')||'';if(!imgAlt||!imgSrc)continue;if(img.classList&&img.classList.contains('csp-product-image'))continue;var anchors=root.querySelectorAll('a');var match=null;for(var j=0;j<anchors.length;j++){var a=anchors[j];if(a.classList&&a.classList.contains('csp-product-cta'))continue;if(alike(a.textContent,imgAlt)){match=a;break}}
96if(!match)continue;var linkText=(match.textContent||'').trim();var href=match.getAttribute('href')||'';var description='';var li=match.closest?match.closest('li'):null;if(li){var liText=(li.textContent||'').trim();var afterAnchor=liText.substring(liText.indexOf(linkText)+linkText.length);description=afterAnchor.replace(/^[\s\u2014\-:|—]+/,'').trim();if(description.length>140)description=description.substring(0,137)+'\u2026'}
97var priceInfo=extractPriceAfter(img);var priceText=priceInfo?priceInfo.price:'';var card=buildCard(imgSrc,linkText,href,description,priceText);if(li&&li.parentNode){li.parentNode.insertBefore(card,li);li.parentNode.removeChild(li)}else if(match.parentNode){match.parentNode.insertBefore(card,match);match.parentNode.removeChild(match)}
98if(priceInfo){for(var pi=0;pi<priceInfo.nodes.length;pi++){var pn=priceInfo.nodes[pi];if(pn&&pn.parentNode)pn.parentNode.removeChild(pn);}}
99var imgNext=img.nextSibling;if(img.parentNode)img.parentNode.removeChild(img);if(imgNext&&imgNext.nodeType===1&&imgNext.tagName==='BR'&&imgNext.parentNode){imgNext.parentNode.removeChild(imgNext)}}
100var lists=root.querySelectorAll('ul');for(var k=0;k<lists.length;k++){if(!lists[k].children.length&&lists[k].parentNode){lists[k].parentNode.removeChild(lists[k])}}}
101function initA11y(){var panel=document.getElementById('csp-chat-panel');if(!panel)return;document.addEventListener('keydown',function(e){if(e.key!=='Escape')return;if(!document.body.classList.contains('csp-chat-open'))return;if(!panel.contains(document.activeElement)&&document.activeElement!==document.body)return;window.cspCloseChat&&window.cspCloseChat()});panel.addEventListener('keydown',function(e){if(e.key!=='Tab')return;var focusables=panel.querySelectorAll('button, [href], input, textarea, [tabindex]:not
101([tabindex="-1"])');if(!focusables.length)return;var first=focusables[0];var last=focusables[focusables.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus()}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus()}})}
102function cspAddBotHtml(text){var msgs=document.getElementById('csp-chat-messages');var div=document.createElement('div');div.className='csp-msg csp-msg-bot';div.textContent=text;msgs.appendChild(div);msgs.scrollTop=msgs.scrollHeight;history.push({role:'assistant',content:text});rawResponses.push(text);saveChat()}
103function cspAddBotResponse(text){var msgs=document.getElementById('csp-chat-messages');var el=document.getElementById('csp-suggestions');if(el)el.remove();var div=document.createElement('div');div.className='csp-msg csp-msg-bot';var safeHtml=renderMarkdown(text,null);var template=document.createElement('template');template.innerHTML=safeHtml;div.appendChild(template.content);addFeedbackButtons(div);msgs.appendChild(div);msgs.scrollTop=msgs.scrollHeight;var rawText=text.replace(/\[Source:[^\]]+\]/g,'').trim();history.push({role:'assistant',content:rawText});rawResponses.push(text);saveChat();if(!chatOpen)showBadge();}
104function addUserMsg(text){getSessionId();getSessionStartedAt();var msgs=document.getElementById('csp-chat-messages');var div=document.createElement('div');div.className='csp-msg csp-msg-user';div.textContent=text;msgs.appendChild(div);msgs.scrollTop=msgs.scrollHeight;history.push({role:'user',content:text});saveChat()}
105function showTyping(){var msgs=document.getElementById('csp-chat-messages');var div=document.createElement('div');div.className='csp-msg csp-msg-typing';div.id='csp-typing';var orb=document.createElement('img');orb.src='https://cleanstart-proxy-coral.vercel.app/chat-mascot.png';orb.className='csp-typing-avatar';orb.style.cssText='width:22px;height:22px;border-radius:50%;object-fit:cover;object-position:65% 20%';var dots=document.createElement('div');dots.className='csp-typing-dots';for(var i=0;i<3;i++){dots.appendChild(document.createElement('span'))}
106div.appendChild(orb);div.appendChild(dots);msgs.appendChild(div);msgs.scrollTop=msgs.scrollHeight}
107function hideTyping(){var el=document.getElementById('csp-typing');if(el)el.remove();}
108window.cspSendMsg=async function(){if(sending)return;var input=document.getElementById('csp-chat-input');var text=input.value.trim();if(!text)return;input.value='';input.style.height='auto';input.style.height='40px';addUserMsg(text);sending=!0;document.getElementById('csp-chat-send').disabled=!0;setAssistantState('thinking');showTyping();try{var resp=await fetch('https://cleanstart-proxy-coral.vercel.app/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({messages:history,sessionId:getSessionId(),pageUrl:window.location.href,pageTitle:document.title})});var ragMeta=getRagMetaFromResponse(resp);if(!resp.ok||!resp.body){hideTyping();cspAddBotResponse('Sorry, something went wrong. Please try again or call us at (253) 921-2593.');return}
109var msgsEl=document.getElementById('csp-chat-messages');var sugEl=document.getElementById('csp-suggestions');if(sugEl)sugEl.remove();var div=null;var full='';var reader=resp.body.getReader();var decoder=new TextDecoder();var buf='';for(;;){var result=await reader.read();if(result.done)break;buf+=decoder.decode(result.value,{stream:!0});var parts=buf.split('\n\n');buf=parts.pop()||'';for(var p=0;p<parts.length;p++){var line=parts[p].trim();if(!line.startsWith('data: '))continue;var payload=line.slice(6);if(payload==='[DONE]')break;try{full+=JSON.parse(payload)}catch(e){}}
110if(full&&!div){hideTyping();div=document.createElement('div');div.className='csp-msg csp-msg-bot';msgsEl.appendChild(div)}
111if(div){div.textContent=full;msgsEl.scrollTop=msgsEl.scrollHeight}}
112if(!div){hideTyping()}
113if(full){var rendered=renderMarkdown(full,ragMeta);div.textContent='';var tpl=document.createElement('template');tpl.innerHTML=rendered;div.appendChild(tpl.content);transformProductMarkdown(div);addFeedbackButtons(div);var rawText=full.replace(/\[Source:[^\]]+\]/g,'').trim();history.push({role:'assistant',content:rawText});rawResponses.push({text:full,rag:ragMeta});saveChat();if(!chatOpen)showBadge();}else{div.textContent='Sorry, something went wrong.';history.push({role:'assistant',content:'Sorry, something went wrong.'});saveChat()}}catch(e){hideTyping();cspAddBotResponse('Sorry, I had trouble connecting. Please try again or call us at (253) 921-2593.')}finally{sending=!1;setAssistantState('idle');document.getElementById('csp-chat-send').disabled=!1;document.getElementById('csp-chat-input').focus();if(pendingCloseReason){var reason=pendingCloseReason;pendingCloseReason='';sendChatSummary(reason,{keepalive:!0,resetAfter:!0});resetChatUi()}}};window.addEventListener('pagehide',function(){sendChatSummary('page_exit',{useBeacon:!0,resetAfter:!0})});initResize();initA11y();function tryAutoOpenSavedChat(){try{if(sessionStorage.getItem('csp-chat-was-open')!=='1')return!1;var saved=localStorage.getItem(STORAGE_KEY);if(!saved)return!1;if(isChatExpired())return!1;var msgs=JSON.parse(saved);if(!msgs.length)return!1;var hasUser=!1;for(var i=0;i<msgs.length;i++){if(msgs[i].role==='user'&&String(msgs[i].content||'').trim()){hasUser=!0;break}}
114if(!hasUser)return!1;window.cspToggleChat&&window.cspToggleChat();return!0}catch(e){return!1}}
115if(!tryAutoOpenSavedChat())initNudge();setAssistantState('idle')})()
116;

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.