<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2, user-scalable=1">
    
	<!-- Preconnect -->
    <link rel="preconnect" href="https://www.optimizecdn.com" crossorigin>
    <link rel="preconnect" href="https://fonts.googleapis.com">
	<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
	<link rel="apple-touch-icon" href="https://how.to.seo.diy/favicon.ico?v=20261020-greencheck">
    <link rel="icon" type="image/x-icon" href="https://how.to.seo.diy/favicon.ico?v=20261020-greencheck">
      <link rel="preconnect" href="https://how.to.seo.diy">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link rel="stylesheet" href="/assets/seo-pages.css?v=20261023-mobile1">
  <link rel="stylesheet" href="/assets/seo-assets-home.css?v=20261024-figma1"><meta name="apple-mobile-web-app-title" content="SEO.diy">

    <!-- Site Meta Data -->
    <title>How to SEO (DIY) Guide &amp; Software Tools</title>
    <meta name="description" content="Discover software reviews, curated SEO tools, exclusive website tools, and expert podcast videos. Practical ideas to build, grow, and improve your website.">
    <meta name="keywords" content="">
    <meta name="robots" content="index, follow">

    <!-- Canonical URL -->
	<link rel="canonical" href="https://seo.diy/">
	<link rel="alternate" type="application/rss+xml" title="SEO.diy RSS Feed" href="https://seo.diy/rss" />
	
    	<!-- Social Media Meta Data -->
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://seo.diy/">
    <meta property="og:site_name" content="SEO.diy">
    <meta property="og:title" content="SEO.diy &mdash; Smarter tools, better SEO decisions">
    <meta property="og:description" content="Software reviews, SEO tools, and practical podcast videos in one place.">
    <meta property="og:image" content="https://seo.diy/images/SEO-DIY/SEO.diy.png">
	<script>
	var siteInfoSpan=document.createElement('span');
	siteInfoSpan.style.cssText='position:absolute;color:transparent;width:100%;z-index:-1;height:50px;top:0;';
	siteInfoSpan.textContent='www.seo.diy - SEO.diy';
	document.documentElement.appendChild(siteInfoSpan);
	</script>

	<!-- Preload -->
	<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=Inter:300,400,600,700,800,900|Open+Sans:300,400,600,700,800,900|Ubuntu:300,400,600,700,800,900|Noto+Sans:300,400,600,700,800,900&display=swap" fetchpriority="high">
	    
    <!-- Google Fonts Stylesheet -->
    <link rel="stylesheet" media="print" onload="this.onload=null;this.removeAttribute('media');" href="https://fonts.googleapis.com/css?family=Inter:300,400,600,700,800,900|Open+Sans:300,400,600,700,800,900|Ubuntu:300,400,600,700,800,900|Noto+Sans:300,400,600,700,800,900&display=swap">
    <noscript>
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inter:300,400,600,700,800,900|Open+Sans:300,400,600,700,800,900|Ubuntu:300,400,600,700,800,900|Noto+Sans:300,400,600,700,800,900&display=swap">
    </noscript>

    <!-- FontAwesome Stylesheet -->
    <link rel="stylesheet" media="print" onload="this.onload=null;this.removeAttribute('media');" href="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/font-awesome/css/font-awesome.min.css" crossorigin>
    <noscript>
        <link rel="stylesheet" href="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/font-awesome/css/font-awesome.min.css" crossorigin>
    </noscript>

    <!-- Bootstrap Icons Stylesheet -->
    <link rel="stylesheet" media="print" onload="this.onload=null;this.removeAttribute('media');" href="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/fonts/bootstrap-icons.min.css?v=1.13.1" crossorigin>
    <noscript>
        <link rel="stylesheet" href="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/fonts/bootstrap-icons.min.css?v=1.13.1" crossorigin>
    </noscript>

    <!-- Critical JavaScript -->
    <script src="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/libraries/latest/jquery.min.js"></script>
	<script src="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/libraries/latest/bootstrap.min.js"></script>
	<script>
		/* jQuery.event.special.touchstart = {
			setup: function( _, ns, handle ) {
				this.addEventListener("touchstart", handle, { passive: !ns.includes("noPreventDefault") });
			}
		}; */
		jQuery.event.special.touchmove = {
			setup: function( _, ns, handle ) {
				this.addEventListener("touchmove", handle, { passive: !ns.includes("noPreventDefault") });
			}
		};
		jQuery.event.special.wheel = {
			setup: function( _, ns, handle ){
				this.addEventListener("wheel", handle, { passive: true });
			}
		};
		jQuery.event.special.mousewheel = {
			setup: function( _, ns, handle ){
				this.addEventListener("mousewheel", handle, { passive: true });
			}
		};
	</script>

	<!-- Breadcrumb Position -->
	<style>html.bc-relocate .container:has(> .breadcrumb):has(~ .hero_section_container) .breadcrumb{display:none!important;}html.bc-relocate .hero_section_container + .clearfix + .container::before{content:"";display:block;min-height:24px;}.hero_section_container + .clearfix + .container > .breadcrumb:first-child{position:relative;top:-24px;}</style>
	<script>document.documentElement.classList.add('bc-relocate');document.addEventListener('DOMContentLoaded',function(){var bc=document.querySelector('ol.breadcrumb'),hero=document.querySelector('.hero_section_container');if(bc&&hero){var t=hero.nextElementSibling;while(t&&!t.classList.contains('container'))t=t.nextElementSibling;if(t)t.insertBefore(bc,t.firstChild);}document.documentElement.classList.remove('bc-relocate');});</script>
	

    <!-- Prefetch -->
    <link rel="prefetch" href="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/jquery.lazy/1.7.9/jquery.lazy.min.js" as="script">
    <link rel="prefetch" href="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/js/websiteScripts.min.js?v=8.0.0" as="script">

    <!-- Custom Site-wide HEAD Content --><script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-NFPC4QMX');</script>    </head>

<body class="general-session"><!--GOOGLE TAG MANAGER CODE--><div class="clearfix"></div>
<!-- Begin  Content -->
<main role="main" id="main-content">
<div id="first_container" class="content-container fr-view">
        <div class="container">
                        <div class="clearfix body-content"></div>
        
        <div class="row">

        <div class="col-md-12">
                <div class="seo-home">  <link rel="stylesheet" href="/assets/seo-pages.css?v=20261023-mobile1"><script src="/assets/seo-pages.js?v=20261020-greencheck" defer></script><nav class="seo-network-bar seo-network-bar--content" aria-label="SEO network sites">  <div class="seo-network-bar__inner">    <a class="seo-network-bar__label" href="https://seo.directory">SEO DIRECTORY:</a>    <div class="seo-network-bar__links" id="seo-network-home-sites">                        <span class="seo-network-bar__link is-current" aria-current="location"><span class="seo-network-bar__brand"><strong>SEO</strong><span>.diy</span></span></span>                                <a class="seo-network-bar__link" href="https://seo.blog/" aria-describedby="seo-network-description-home-blog">            <span class="seo-network-bar__brand"><strong>SEO</strong><span>.blog</span></span>            <span class="seo-network-bar__description" id="seo-network-description-home-blog" role="tooltip">Educational articles and expert insights for improving organic traffic.</span>          </a>                                <a class="seo-network-bar__link" href="https://seo.audio/" aria-describedby="seo-network-description-home-audio">            <span class="seo-network-bar__brand"><strong>SEO</strong><span>.audio</span></span>            <span class="seo-network-bar__description" id="seo-network-description-home-audio" role="tooltip">Podcasts covering tools, keywords, content, and technical optimization.</span>          </a>                                <a class="seo-network-bar__link" href="https://seo.business/" aria-describedby="seo-network-description-home-business">            <span class="seo-network-bar__brand"><strong>SEO</strong><span>.business</span></span>            <span class="seo-network-bar__description" id="seo-network-description-home-business" role="tooltip">List of trusted agencies, and consultants offering website optimization.</span>          </a>                                <a class="seo-network-bar__link" href="https://seo.school/" aria-describedby="seo-network-description-home-school">            <span class="seo-network-bar__brand"><strong>SEO</strong><span>.school</span></span>            <span class="seo-network-bar__description" id="seo-network-description-home-school" role="tooltip">Master your skills, expect-led courses from beginner to advanced lessons.</span>          </a>                                <a class="seo-network-bar__link" href="https://seo.forum/" aria-describedby="seo-network-description-home-forum">            <span class="seo-network-bar__brand"><strong>SEO</strong><span>.forum</span></span>            <span class="seo-network-bar__description" id="seo-network-description-home-forum" role="tooltip">Ask questions and learn from a community focused on search growth.</span>          </a>                  </div>  </div></nav><link data-seo-head-link rel="icon" type="image/x-icon" href="https://how.to.seo.diy/favicon.ico?v=20261020-greencheck"><link data-seo-head-link rel="apple-touch-icon" type="image/png" href="https://how.to.seo.diy/favicon.ico?v=20261020-greencheck">  <a class="seo-home-skip" href="#seo-home-content">Skip to content</a>  <div class="seo-home-frame content">    <header class="seo-home-header">  <a class="seo-home-brand" href="/" aria-label="SEO.diy homepage"><img src="/images/SEO-DIY/seo-diy.png" width="119" height="33" alt="SEO.diy"></a>  <nav class="seo-home-nav" aria-label="Main navigation">    <a href="/devtools">Software Reviews</a>    <a href="/devtools/seo">SEO Tools</a>    <a href="#exclusive-tools">Exclusive Tools</a>    <a href="/videos">Podcast Videos</a>  </nav></header>    <div id="seo-home-content" tabindex="-1">      <section class="seo-home-hero" aria-labelledby="seo-home-title">  <h1 id="seo-home-title">Smarter tools,<br><span>better <em>SEO decisions.</em></span></h1>  <p>Discover honest software reviews, curated SEO tools, exclusive tools and expert podcast videos all in one place.</p>  <span class="seo-home-art seo-home-art--hero" role="img" aria-label="SEO dashboard with software ratings, website analytics, and podcast tools"></span>  <ul class="seo-home-trust" aria-label="What you can discover">    <li><span class="seo-home-art seo-home-art--honest" aria-hidden="true"></span>Honest &amp; unbiased reviews</li>    <li><span class="seo-home-art seo-home-art--curation" aria-hidden="true"></span>Curated tools for real results</li>    <li><span class="seo-home-art seo-home-art--experts" aria-hidden="true"></span>Expert insights &amp; interviews</li>  </ul></section>      <section class="seo-home-section" aria-labelledby="seo-home-categories">  <h2 id="seo-home-categories">Software Categories</h2>  <p>Explore software categories to find the right tools for your needs.</p>  <div class="seo-home-category-grid">        <a class="seo-home-category" href="/devtools/backend-tools">      <span class="seo-home-art seo-home-art--backend" aria-hidden="true"></span>      <h3>Backend Tools</h3>      <p>Tools for servers, databases, APIs, and backend development.</p>      <span class="seo-home-card-action">Explore tools</span>    </a>        <a class="seo-home-category" href="/devtools/business-tools">      <span class="seo-home-art seo-home-art--business" aria-hidden="true"></span>      <h3>Business Tools</h3>      <p>Software to help manage, organize, and grow your business.</p>      <span class="seo-home-card-action">Explore tools</span>    </a>        <a class="seo-home-category" href="/devtools/frontend-tools">      <span class="seo-home-art seo-home-art--frontend" aria-hidden="true"></span>      <h3>Frontend Tools</h3>      <p>Tools for building and improving website interfaces and user experiences.</p>      <span class="seo-home-card-action">Explore tools</span>    </a>        <a class="seo-home-category" href="/devtools/marketing-tools">      <span class="seo-home-art seo-home-art--marketing" aria-hidden="true"></span>      <h3>Marketing Tools</h3>      <p>Software for campaigns, analytics, content, and digital marketing.</p>      <span class="seo-home-card-action">Explore tools</span>    </a>        <a class="seo-home-category" href="/devtools/seo">      <span class="seo-home-art seo-home-art--seo" aria-hidden="true"></span>      <h3>SEO Tools</h3>      <p>Tools for keyword research, rankings, audits, and search optimization.</p>      <span class="seo-home-card-action">Explore tools</span>    </a>      </div>  </section>      <section class="seo-home-section seo-home-exclusive" id="exclusive-tools" aria-labelledby="seo-home-exclusive-title">  <h2 id="seo-home-exclusive-title">Exclusive Tools</h2>  <p>Practical tools built to support specific SEO and website tasks.</p>  <div class="seo-home-tool-grid">        <a class="seo-home-category" href="https://backlink.software/">      <span class="seo-home-art seo-home-art--backlink" aria-hidden="true"></span>      <h3>Backlink.software</h3>      <p>Tools for working with backlinks and link-related SEO tasks.</p>      <span class="seo-home-card-action">Visit website</span>    </a>        <a class="seo-home-category" href="https://nofollow.link/">      <span class="seo-home-art seo-home-art--nofollow" aria-hidden="true"></span>      <h3>Nofollow.link</h3>      <p>Tools for managing and checking nofollow links.</p>      <span class="seo-home-card-action seo-home-card-action--pending">Not yet available</span>    </a>        <a class="seo-home-category" href="https://keyword.tools/">      <span class="seo-home-art seo-home-art--keyword" aria-hidden="true"></span>      <h3>Keyword.tools</h3>      <p>Tools for keyword research and search optimization.</p>      <span class="seo-home-card-action seo-home-card-action--pending">Not yet available</span>    </a>        <a class="seo-home-category" href="https://startup.services/">      <span class="seo-home-art seo-home-art--startup" aria-hidden="true"></span>      <h3>Startup.services</h3>      <p>Useful tools and resources for startups and growing businesses.</p>      <span class="seo-home-card-action seo-home-card-action--pending">Not yet available</span>    </a>      </div></section>      <section class="seo-home-mission" aria-labelledby="seo-home-mission-title">  <div class="seo-home-mission-copy"><span>OUR MISSION</span><h2 id="seo-home-mission-title">Better tools. Better decisions.<br>Better <em>websites.</em></h2><p>We provide practical software reviews, curated SEO tools, and expert podcast content to help you build, grow and succeed online.</p></div>  <ul class="seo-home-mission-values">    <li><span class="seo-home-art seo-home-art--research" aria-hidden="true"></span><span>Discover<br>Trusted Tools</span></li>    <li><span class="seo-home-art seo-home-art--decisions" aria-hidden="true"></span><span>Make Smarter<br>Decisions</span></li>    <li><span class="seo-home-art seo-home-art--growth" aria-hidden="true"></span><span>Grow Your<br>Website</span></li>    <li><span class="seo-home-art seo-home-art--resource" aria-hidden="true"></span><span>All in One<br>Resource Hub</span></li>  </ul></section>      <section class="seo-home-section seo-home-featured" aria-labelledby="seo-home-popular-title">  <div class="seo-home-section-heading"><h2 id="seo-home-popular-title">Featured Software</h2><a href="/devtools">All software</a></div>  <p>Explore tools for SEO, marketing, and website growth.</p>  <div class="seo-home-software-grid">        <a class="seo-home-software" href="/beyond-compare">      <img src="/logos/profile/limage-27-340-photo.webp" width="60" height="60" alt="" loading="lazy">      <h3>Beyond Compare</h3>      <span class="seo-sp-stars" role="img" aria-label="4.5 out of 5 stars"><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--half" aria-hidden="true"></span></span><span class="seo-home-rating">4.4 / 5 editorial score</span>    </a>        <a class="seo-home-software" href="/editplus">      <img src="/logos/profile/limage-19-tly7e2798ff356.webp" width="60" height="60" alt="" loading="lazy">      <h3>EditPlus</h3>      <span class="seo-sp-stars" role="img" aria-label="4.5 out of 5 stars"><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--half" aria-hidden="true"></span></span><span class="seo-home-rating">4.4 / 5 editorial score</span>    </a>        <a class="seo-home-software" href="/semrush-magic-keyword-tool">      <img src="/logos/profile/limage-31-495-photo.webp" width="60" height="60" alt="" loading="lazy">      <h3>Adobe</h3>      <span class="seo-sp-stars" role="img" aria-label="3.5 out of 5 stars"><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--full" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--half" aria-hidden="true"></span><span class="seo-sp-star seo-sp-star--empty" aria-hidden="true"></span></span><span class="seo-home-rating">3.6 / 5 editorial score</span>    </a>      </div>  </section>      <section class="seo-home-section seo-home-podcasts" aria-labelledby="seo-home-podcast-title">  <div class="seo-home-section-heading"><h2 id="seo-home-podcast-title">Podcast Videos</h2><a href="/videos">All podcast videos</a></div>  <p>Watch expert conversations, insights, and practical SEO discussions.</p>  <div class="seo-home-video-grid">        <article class="seo-home-video">      <a href="/seo-demo-06">        <span class="seo-home-video-art"><img src="https://seo.diy/pictures/profile/pimage-37-tm5pi868fa80fa.webp" alt="" loading="lazy" width="360" height="203"><span class="seo-home-video-play" aria-hidden="true">▶</span></span>        <h3>SEO Demo 06</h3>      </a>      <div class="seo-home-video-meta"><span>2 views</span><span class="seo-video-platforms"><a href="/forum" aria-label="Open Discord discussion"><i class="seo-video-platform--discord" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Open Discord discussion</span></a><a href="https://www.youtube.com/watch?v=5MIAugQ17ks" aria-label="Watch on YouTube (demo link)" target="_blank" rel="noopener"><i class="seo-video-platform--youtube" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Watch on YouTube (demo link)</span></a><a href="https://www.reddit.com/r/SEO/" aria-label="Open Reddit discussion (demo link)" target="_blank" rel="noopener"><i class="seo-video-platform--reddit" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Open Reddit discussion (demo link)</span></a><a href="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" aria-label="Listen to MP3 (demo link)" target="_blank" rel="noopener"><i class="seo-video-platform--mp3" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Listen to MP3 (demo link)</span></a></span></div>    </article>        <article class="seo-home-video">      <a href="/growthhacks-demo-06">        <span class="seo-home-video-art"><img src="https://seo.diy/pictures/profile/pimage-31-tm5pgvf0d51bd2.webp" alt="" loading="lazy" width="360" height="203"><span class="seo-home-video-play" aria-hidden="true">▶</span></span>        <h3>GrowthHacks Demo 06</h3>      </a>      <div class="seo-home-video-meta"><span>3 views</span><span class="seo-video-platforms"><a href="/forum" aria-label="Open Discord discussion"><i class="seo-video-platform--discord" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Open Discord discussion</span></a><a href="https://www.youtube.com/watch?v=5MIAugQ17ks" aria-label="Watch on YouTube (demo link)" target="_blank" rel="noopener"><i class="seo-video-platform--youtube" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Watch on YouTube (demo link)</span></a><a href="https://www.reddit.com/r/SEO/" aria-label="Open Reddit discussion (demo link)" target="_blank" rel="noopener"><i class="seo-video-platform--reddit" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Open Reddit discussion (demo link)</span></a><a href="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" aria-label="Listen to MP3 (demo link)" target="_blank" rel="noopener"><i class="seo-video-platform--mp3" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Listen to MP3 (demo link)</span></a></span></div>    </article>        <article class="seo-home-video">      <a href="/seo-demo-05">        <span class="seo-home-video-art"><img src="https://seo.diy/pictures/profile/pimage-36-tm5pi18e2a015c.webp" alt="" loading="lazy" width="360" height="203"><span class="seo-home-video-play" aria-hidden="true">▶</span></span>        <h3>SEO Demo 05</h3>      </a>      <div class="seo-home-video-meta"><span>4 views</span><span class="seo-video-platforms"><a href="/forum" aria-label="Open Discord discussion"><i class="seo-video-platform--discord" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Open Discord discussion</span></a><a href="https://www.youtube.com/watch?v=5MIAugQ17ks" aria-label="Watch on YouTube (demo link)" target="_blank" rel="noopener"><i class="seo-video-platform--youtube" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Watch on YouTube (demo link)</span></a><a href="https://www.reddit.com/r/SEO/" aria-label="Open Reddit discussion (demo link)" target="_blank" rel="noopener"><i class="seo-video-platform--reddit" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Open Reddit discussion (demo link)</span></a><a href="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" aria-label="Listen to MP3 (demo link)" target="_blank" rel="noopener"><i class="seo-video-platform--mp3" aria-hidden="true"></i><span class="seo-video-platform-tooltip" role="tooltip">Listen to MP3 (demo link)</span></a></span></div>    </article>      </div>  </section>    </div>    <footer class="seo-home-footer">  <div class="seo-home-footer-about">    <a class="seo-home-brand" href="/"><img src="/images/SEO-DIY/seo-diy.png" width="152" height="42" alt="SEO.diy"></a>    <h2>How to SEO (DIY) Guide &amp; Software Tools</h2>    <p>Learn what actually works. Perfect for SEOs, marketers, web developers, and business owners who want legitimate, long-term results without the hype.</p>    <div class="seo-home-socials">      <a href="https://www.x.com/SleepEatOften" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/x.svg" alt="Twitter / X SEO" width="20" height="20" loading="lazy"></a><a href="https://www.facebook.com/SleepEatOften" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/facebook.svg" alt="Facebook SEO" width="20" height="20" loading="lazy"></a><a href="https://www.youtube.com/@SleepEatOften" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/youtube.svg" alt="YouTube SEO" width="20" height="20" loading="lazy"></a><a href="https://www.pinterest.com/SleepEatOften/" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/pinterest.svg" alt="Pinterest SEO" width="20" height="20" loading="lazy"></a><a href="https://bsky.app/profile/sleepeatoften.bsky.social" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/bluesky.svg" alt="BlueSky SEO" width="20" height="20" loading="lazy"></a><a href="https://www.instagram.com/SleepEatOften" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/instagram.svg" alt="Instagram SEO" width="20" height="20" loading="lazy"></a><a href="https://www.snapchat.com/@sleepeatoften" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/snapchat.svg" alt="SnapChat SEO" width="20" height="20" loading="lazy"></a><a href="https://www.linkedin.com/company/SleepEatOften" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/linkedin.svg" alt="LinkedIn SEO" width="20" height="20" loading="lazy"></a><a href="https://www.tiktok.com/@SleepEatOften" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/tiktok.svg" alt="TikTok SEO" width="20" height="20" loading="lazy"></a><a href="https://www.reddit.com/r/SleepEatOften/" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/reddit.svg" alt="Reddit SEO" width="20" height="20" loading="lazy"></a><a href="https://www.tumblr.com/sleepeatoften" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/tumblr.svg" alt="Tumblr SEO" width="20" height="20" loading="lazy"></a><a href="https://www.threads.com/@sleepeatoften" target="_blank" rel="noopener"><img src="https://how.to.seo.diy/threads.svg" alt="Threads SEO" width="20" height="20" loading="lazy"></a>    </div>    <a class="seo-home-community" href="https://www.discord.com/invite/seo" target="_blank" rel="noopener">Join our Discord community</a>  </div>  <nav aria-label="Software categories"><h2>Software Categories</h2><a href="/devtools/backend-tools">Backend Tools</a><a href="/devtools/business-tools">Business Tools</a><a href="/devtools/frontend-tools">Frontend Tools</a><a href="/devtools/marketing-tools">Marketing Tools</a><a href="/devtools/seo">SEO Tools</a></nav>  <nav aria-label="Exclusive tools"><h2>Exclusive Tools</h2><a href="https://backlink.software/">Backlink.software</a><a href="https://nofollow.link/">Nofollow.link</a><a href="https://keyword.tools/">Keyword.tools</a><a href="https://startup.services/">Startup.services</a></nav>  <nav aria-label="Podcast"><h2>Podcast</h2><a href="/videos">Podcast Videos</a><a href="/forum">Community discussion</a></nav></footer><footer class="site-footer">SEO Public Benefit Corporation</footer>  </div>  </div>        </div>

        
        </div>  <!-- Closes Row -->

    
    <script type="application/ld+json">
{
    "@context": "https://schema.org/",
    "@type": "WebPage",
    "@id": "https://seo.diy/home",
    "url": "https://seo.diy/home",
    "name": "How to SEO (DIY) Guide &amp; Software Tools",
    "headline": "Discover software reviews, curated SEO tools, exclusive website tools, and expert podcast videos. Practical ideas to build, grow, and improve your website.",
    "about": "SEO.diy > Home",
    "inLanguage": "en-US",
    "mainEntityOfPage": "https://seo.diy/home",
    "author": {
        "@id": "https://seo.diy/#organization"
    },
    "publisher": {
        "@id": "https://seo.diy/#organization"
    },
    "isPartOf": {
        "@id": "https://seo.diy/#website"
    },
    "primaryImageOfPage": {
        "@type": "ImageObject",
        "url": "https://seo.diy/images/SEO-DIY/SEO.diy.png"
    },
    "keywords": [
        "How to SEO (DIY) Guide &amp; Software Tools",
        "SEO.diy"
    ],
    "dateModified": "2026-09-04T14:39:59+07:00"
}</script>
        <div class="clearfix"></div>
    </div>
</div>
</main>
<!-- End Content -->
<style type='text/css'> .scrollup {
  border-radius: 3px;
  width: 40px;
  height: 40px;
  opacity: 0.4;
  position: fixed;
  bottom: 30px;
  right: 30px;
  display: none;
  background: rgba(119, 119, 119, 0.8);
  z-index: 1000000;
}
.scrollup i {
  font-size: 36px;
  color: white;
  position: relative;
  top: 0px;
  left: 10px;
} </style>


    <link rel="stylesheet" type="text/css" href="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/limonte-sweetalert2/6.11.2/sweetalert2.min.css">
<script src="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/limonte-sweetalert2/6.11.2/sweetalert2.min.js"></script>

<script>
    function clearContent(thisObj){
        var size;
        if(thisObj.hasClass('input-sm') || thisObj.parents('.input-group').hasClass('input-group-sm')){
            size = "small";
        } else if (thisObj.hasClass('input-lg') || thisObj.parents('.input-group').hasClass('large-autosuggest')){
            size = "large";
        } else {
            size = "medium";
        }
        if(!thisObj.parent().hasClass('input_wrapper')){
            if(thisObj.parent().hasClass('input-group-sm')){
                thisObj.wrap('<span class="input-group-sm input_wrapper"></span>');
            } else if (thisObj.parent().hasClass('input-group-lg')){
                thisObj.wrap('<span class="input-group-lg input_wrapper"></span>');
            } else {
                thisObj.wrap('<span class="input_wrapper"></span>');
            }
        }
        if(thisObj.val() != ""){
            if(thisObj.hasClass('googleSuggest')){
                thisObj.parent().find('.fill_location').remove();
            }
            if (!thisObj.parent().find('.clear_content').length){
                thisObj.parent().append(`<span class="clear_content ${size}"><i class="fa fa-times-circle" aria-hidden="true"></i></span>`);
                if (thisObj.hasClass("tt-input")) {
            		thisObj.focus();
        		}

            }
        }
            }

    $(document).on('click', '.drp-buttons .applyBtn', function(){
        clearContent($(".dateRange input"));
    });

    $('.sm-autosuggest input, .googleSuggest, .large-autosuggest input, .md-autosuggest input, .normal-autosuggest input, .google-writen-location, .dateRange input').keyup(function(){
        clearContent($(this));
    });

    $(document).ready(function(){
        $('.sm-autosuggest input, input.googleSuggest, .large-autosuggest input, .md-autosuggest input, .normal-autosuggest input, .google-writen-location, .dateRange input').each(function(){
            clearContent($(this));
        })
    })

    $(document).on('click', '.clear_content', function(){
        /* Google Location Suggest locks the value after a suggestion is picked; release it or val('') is ignored. */
        if (window.protectedInputId && $(this).parent().find('input').filter(function(){ return this.id === window.protectedInputId; }).length) {
            window.inputValueProtected = false;
            window.expectedInputValue = null;
            window.protectedInputId = null;
        }
        $(this).parent().find('input').val('');
        //tt-input its a class for typeahead auto-suggest
        if ($(this).parent().find('input').hasClass("tt-input")) {
            $(this).parent().find('input').typeahead('val','');
        }
        clearContent($(this).parent().find('input'));
        $(this).remove();
    });

	$(window).on('load', function () {
		setTimeout(function() {
			// add missing href attribute to multi-category options in search modules
			$('.bootstrap-select.show-tick .dropdown-menu a').attr('href', '#');
		}, 2000);
        	});
</script>



<a href="#" class="scrollup" title="scrollup">
    <i class="fa fa-caret-up" aria-hidden="true"></i>
</a>
<script>
        $(document).ready(function(){
        // .progressbar() comes from bootstrap-progressbar.min.js, loaded only by widgets 1236/1318.
        // Elsewhere it used to fall through to jQuery UI's; jQuery UI is no longer global, so an
        // unguarded call throws and kills the rest of this ready() handler (scrollup, crop button).
        if ($.fn.progressbar) {
            $('.progress .progress-bar').progressbar({
                display_text: 'fill'
            });
        }
        $(window).scroll(function(){

            if ($(this).scrollTop() > 600) {
                $('.scrollup').fadeIn();

            } else {
                $('.scrollup').fadeOut();
            }
        });
        $('.scrollup').click(function(){
            $("html, body").animate({
                scrollTop: 0
            }, 600);
            return false;
        });
        $('#cropButton').click(function(){
            var iframe = $("#cropiFrame");
            iframe.attr("src", iframe.data("src"));
        });
    });
</script>

<style>
/* YouTube Lazy Load Styles */
.youtube-lazy-container {
	position: relative;
	display: block;
	cursor: pointer;
	overflow: hidden;
	background: #000;
	margin: 0;
}
.youtube-lazy-thumbnail {
	display: block !important;
	width: 100% !important;
	height: 100% !important;
	object-fit: cover !important;
	position: absolute !important;
	top: 0 !important;
	left: 0 !important;
	transition: opacity 0.3s;
}
.youtube-lazy-container iframe {
	display: block !important;
	width: 100% !important;
	height: 100% !important;
	position: absolute !important;
	top: 0 !important;
	left: 0 !important;
	border: 0 !important;
}
.youtube-lazy-play {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: clamp(40px, 12vw, 68px);
	height: clamp(28px, 8.5vw, 48px);
	background: rgba(255, 0, 0, 0.8);
	border-radius: clamp(8px, 2vw, 12px);
	display: flex;
	align-items: center;
	justify-content: center;
	transition: background 0.2s;
	z-index: 1;
}
.youtube-lazy-container:hover .youtube-lazy-play {
	background: rgba(255, 0, 0, 1);
}
.youtube-lazy-play::before {
	content: '\F4F4';
	font-family: 'bootstrap-icons';
	color: white;
	font-size: clamp(14px, 4vw, 24px);
	display: flex;
	align-items: center;
	justify-content: center;
}
.fr-view .fr-video {
	visibility: hidden;
}
.fr-box[role="application"] .fr-video {
	visibility: visible !important;
}
.fr-view .fr-video.fr-dvi.fr-fvc:has(.youtube-lazy-container) {
	display: inline-block;
	position: relative;
	left: 50%;
	transform: translateX(-50%);
}
@media only screen and (max-width: 768px) {
	.youtube-lazy-container {
		aspect-ratio: 16 / 9 !important;
		max-width: calc(100vw - 30px) !important;
		padding-bottom: 56.25% !important;
	}
	.fr-video, div:not(.fr-element) p .fr-video.fr-dvi.fr-fvr {
		float: none !important;
		margin: 0 auto !important;
		width: 100% !important;
		text-align: center !important;
		display: block !important;
		max-width: 100% !important;
	}
}
</style>
<script>
/* YouTube Lazy Load Script */
(function() {
	/* CRITICAL: Remove src IMMEDIATELY to prevent YouTube from loading */
	var iframes = document.querySelectorAll('iframe[src*="youtube.com/embed"], iframe[src*="youtube-nocookie.com/embed"]');
	if (!iframes.length) return;
	var firstIframe = iframes[0];
	/* ULTRA-PRIORITY: Preload first thumbnail BEFORE anything else for maximum LCP speed */
	try {
		var rect = firstIframe.getBoundingClientRect();
		if (rect && rect.top < (window.innerHeight + 50)) {
			var src = firstIframe.src || firstIframe.getAttribute('data-src');
			if (src) {
				var videoId = null;
				var playlistMatch = src.match(/[?&]playlist=([a-zA-Z0-9_-]+)/);
				if (playlistMatch && playlistMatch[1]) {
					videoId = playlistMatch[1];
				} else {
					var embedMatch = src.match(/youtube(?:-nocookie)?\.com\/embed\/([a-zA-Z0-9_-]+)/);
					if (embedMatch && embedMatch[1]) {
						videoId = embedMatch[1];
					}
				}
				if (videoId && document.head) {
					var thumbnailUrl = 'https://img.youtube.com/vi/' + videoId + '/sddefault.jpg';
					var preloadLink = document.createElement('link');
					preloadLink.rel = 'preload';
					preloadLink.as = 'image';
					preloadLink.href = thumbnailUrl;
					preloadLink.fetchpriority = 'high';
					document.head.appendChild(preloadLink);
					var img = new Image();
					img.fetchpriority = 'high';
					img.src = thumbnailUrl;
				}
			}
		}
	} catch(e) {};
	Array.prototype.forEach.call(iframes, function(iframe) {
		if (!iframe.getAttribute('data-youtube-lazy')) {
			iframe.setAttribute('data-youtube-src', iframe.src);
			iframe.removeAttribute('src');
			iframe.setAttribute('data-youtube-lazy', 'src-removed');
		}
	});
	var playerPreconnected = false;
	var debounceTimer;
	/* Check if we should wait for mobile preloader */
	var isMobile = window.innerWidth <= 768;
	var hasPreloader = document.getElementById('mobile-loading-message');
	var shouldWaitForPreloader = isMobile && hasPreloader;
	/* Parse pixel values from styles */
	function parsePxValue(value) {
		if (!value) return null;
		var str = String(value);
		if (str.indexOf('%') > -1) return null;
		var num = parseInt(str, 10);
		return (num > 0) ? num : null;
	}
	/* Extract video ID from URL */
	function extractYouTubeVideoId(src) {
		if (!src) return null;
		/* Check for playlist param first (priority) */
		var playlistMatch = src.match(/[?&]playlist=([a-zA-Z0-9_-]+)/);
		if (playlistMatch && playlistMatch[1]) {
			return playlistMatch[1];
		}
		/* Fallback to embed ID */
		var embedMatch = src.match(/youtube(?:-nocookie)?\.com\/embed\/([a-zA-Z0-9_-]+)/);
		if (embedMatch && embedMatch[1]) {
			return embedMatch[1];
		}
		return null;
	}
	/* Preconnect to www.youtube.com on demand (for player) */
	function preconnectYouTube() {
		if (playerPreconnected) return;
		if (!document.head) return;
		playerPreconnected = true;
		var link = document.createElement('link');
		link.rel = 'preconnect';
		link.href = 'https://www.youtube.com';
		document.head.appendChild(link);
	}
	/* Handle thumbnail loading with fallback */
	function setThumbnailErrorHandler(thumbnail) {
		thumbnail.onerror = function() {
			thumbnail.style.background = '#333';
			thumbnail.onerror = null;
		};
	}
	/* Load thumbnail with play button */
	function loadThumbnail(container, videoId, iframe, width, height, parentElement) {
		var thumbnail = new Image();
		thumbnail.className = 'youtube-lazy-thumbnail img-rounded';
		var finalWidth = width || 640;
		var finalHeight = height || 360;
		thumbnail.width = finalWidth;
		thumbnail.height = finalHeight;
		thumbnail.style.aspectRatio = finalWidth + ' / ' + finalHeight;
		var iframeTitle = iframe.getAttribute('title') || iframe.getAttribute('alt');
		if (iframeTitle) {
			thumbnail.alt = iframeTitle;
		}
		var isInViewport = false;
		try {
			var rect = container.getBoundingClientRect();
			isInViewport = rect.top < (window.innerHeight + 50);
		} catch(e) {
			isInViewport = true;
		}
		thumbnail.loading = isInViewport ? 'eager' : 'lazy';
		if (isInViewport) {
			thumbnail.fetchPriority = 'high';
			thumbnail.decoding = 'sync';
		}
		if (parentElement) {
			var revealed = false;
			var revealParent = function() {
				if (!revealed && parentElement.style.visibility === 'hidden') {
					revealed = true;
					parentElement.style.visibility = 'visible';
				}
			};
			thumbnail.onload = thumbnail.onerror = revealParent;
			setTimeout(revealParent, 3000);
		}
		if (isInViewport) {
			thumbnail.src = 'https://img.youtube.com/vi/' + videoId + '/sddefault.jpg';
			setThumbnailErrorHandler(thumbnail);
			container.appendChild(thumbnail);
		} else {
			if (typeof IntersectionObserver !== 'undefined') {
				thumbnail.style.opacity = '0';
				container.appendChild(thumbnail);
				var observer = new IntersectionObserver(function(entries) {
					entries.forEach(function(entry) {
						if (entry.isIntersecting) {
							thumbnail.src = 'https://img.youtube.com/vi/' + videoId + '/sddefault.jpg';
							setThumbnailErrorHandler(thumbnail);
							thumbnail.style.transition = 'opacity 0.3s';
							thumbnail.style.opacity = '1';
							observer.unobserve(container);
						}
					});
				}, { rootMargin: '100px' });
				observer.observe(container);
			} else {
				thumbnail.src = 'https://img.youtube.com/vi/' + videoId + '/sddefault.jpg';
				setThumbnailErrorHandler(thumbnail);
				container.appendChild(thumbnail);
			}
		}
		/* Add play button and click handler */
		var playButton = document.createElement('div');
		playButton.className = 'youtube-lazy-play';
		container.appendChild(playButton);
		var isLoading = false;
		container.addEventListener('mouseenter', preconnectYouTube, { once: true });
		container.addEventListener('click', function() {
			if (isLoading) return;
			isLoading = true;
			preconnectYouTube();
			playButton.style.display = 'none';
			thumbnail.style.pointerEvents = 'none';
			var iframeSrc = iframe.getAttribute('data-youtube-src');
			if (!iframeSrc) return;
			/* Mobile: the tap gesture is delegated to the iframe via allow="autoplay" so playback can start unmuted */
			var isMobile = window.innerWidth <= 768;
			if (isMobile) {
				var allowAttr = iframe.getAttribute('allow') || '';
				if (allowAttr.indexOf('autoplay') === -1) {
					iframe.setAttribute('allow', (allowAttr ? allowAttr + '; ' : '') + 'autoplay');
				}
				iframeSrc += (iframeSrc.indexOf('?') > -1 ? '&' : '?') + 'autoplay=1&playsinline=1';
			} else {
				iframeSrc += (iframeSrc.indexOf('?') > -1 ? '&' : '?') + 'autoplay=1';
			}
			iframe.setAttribute('loading', 'lazy');
			iframe.src = iframeSrc;
			iframe.className = (iframe.className + ' img-rounded').trim();
			iframe.style.opacity = '0';
			container.appendChild(iframe);
			setTimeout(function() {
				thumbnail.style.transition = 'opacity 0.3s';
				thumbnail.style.opacity = '0';
				iframe.style.transition = 'opacity 0.3s';
				iframe.style.opacity = '1';
			}, 250);
		});
	}
	/* Process all YouTube iframes on page */
	function processYouTubeIframes() {
		var iframes = document.querySelectorAll('iframe[src*="youtube.com/embed"], iframe[src*="youtube-nocookie.com/embed"], iframe[data-youtube-src*="youtube.com/embed"], iframe[data-youtube-src*="youtube-nocookie.com/embed"]');
		Array.prototype.forEach.call(iframes, function(iframe) {
			var lazyState = iframe.getAttribute('data-youtube-lazy');
			if (lazyState === 'processed' || lazyState === 'pending') return;
			/* Get src - prioritize data-youtube-src over src */
			var originalSrc = iframe.getAttribute('data-youtube-src') || iframe.src;
			if (!originalSrc) return;
			/* Skip nolazy/forceplay iframes - check for params in URL */
			var hasNoLazy = originalSrc.indexOf('nolazy=1') > -1;
			var hasForcePlay = originalSrc.indexOf('forceplay=1') > -1;
			if (hasNoLazy || hasForcePlay) {
				var cleanSrc = originalSrc.replace(/[?&](nolazy|forceplay)=1/g, '').replace(/\?&/, '?').replace(/[&?]$/, '');
				if (hasForcePlay) {
					var separator = cleanSrc.indexOf('?') > -1 ? '&' : '?';
					iframe.src = cleanSrc + separator + 'autoplay=1&mute=1&playsinline=1';
				} else {
					iframe.src = cleanSrc;
				}
				iframe.className = (iframe.className + ' img-rounded').trim();
				/* Reveal parent fr-video span if hidden */
				var parentElement = iframe.parentNode;
				if (parentElement && parentElement.classList && parentElement.classList.contains('fr-video')) {
					parentElement.style.visibility = 'visible';
				}
				iframe.setAttribute('data-youtube-lazy', 'processed');
				return;
			}
			/* Check if iframe is in or near viewport */
			var rect = iframe.getBoundingClientRect();
			var isNearViewport = rect.top < (window.innerHeight + 200);
			if (!isNearViewport) {
				/* Below fold - mark as pending */
				iframe.setAttribute('data-youtube-lazy', 'pending');
				/* Set up IntersectionObserver to process later */
				var observer = new IntersectionObserver(function(entries) {
					entries.forEach(function(entry) {
						if (entry.isIntersecting) {
							processSingleIframe(entry.target);
							observer.unobserve(entry.target);
						}
					});
				}, { rootMargin: '200px' });
				observer.observe(iframe);
				return;
			}
			/* In/near viewport - process immediately */
			processSingleIframe(iframe);
		});
	}
	/* Process a single iframe */
	function processSingleIframe(iframe) {
		if (iframe.getAttribute('data-youtube-lazy') === 'processed') return;
		iframe.setAttribute('data-youtube-lazy', 'processed');
		var src = iframe.getAttribute('data-youtube-src');
		if (!src) return;
		var videoId = extractYouTubeVideoId(src);
		if (!videoId) return;
		/* Set title for accessibility if missing */
		if (!iframe.getAttribute('title')) {
			iframe.setAttribute('title', 'YouTube video player - ' + videoId);
		}
		/* Create container with proper dimensions */
		var container = document.createElement('div');
		container.className = 'youtube-lazy-container img-rounded';
		var inlineWidth = parsePxValue(iframe.style.width);
		var inlineHeight = parsePxValue(iframe.style.height);
		var attrWidth = parsePxValue(iframe.getAttribute('width'));
		var attrHeight = parsePxValue(iframe.getAttribute('height'));
		var width = inlineWidth || attrWidth || iframe.offsetWidth || null;
		var height = inlineHeight || attrHeight || iframe.offsetHeight || null;
		if (!width && !height) {
			width = 560;
			height = 315;
		} else if (width && !height) {
			height = Math.round(width * 9 / 16);
		} else if (!width && height) {
			width = Math.round(height * 16 / 9);
		}
		if (width <= 0 || height <= 0) {
			width = 560;
			height = 315;
		}
		/* Find constraining parent width (skip wrapper containers like fr-video and embed-responsive) */
		var parentElement = iframe.parentNode;
		var constrainingWidth = null;
		var isFrVideo = parentElement && parentElement.classList && parentElement.classList.contains('fr-video');
		var isEmbedResponsive = parentElement && parentElement.classList && parentElement.classList.contains('embed-responsive');
		if (parentElement) {
			if (isFrVideo) {
				/* For fr-video, check grandparent width, use smaller of 2 */
				var grandparent = parentElement.parentNode;
				if (grandparent) {
					constrainingWidth = grandparent.offsetWidth;
				}
			} else if (isEmbedResponsive) {
				/* For embed-responsive, check grandparent width and use it (ignore iframe dimensions) */
				var grandparent = parentElement.parentNode;
				if (grandparent) {
					constrainingWidth = grandparent.offsetWidth;
				}
			} else {
				constrainingWidth = parentElement.offsetWidth;
			}
		}
		/* Set responsive dimensions with padding-bottom trick */
		var maxWidth;
		if (isEmbedResponsive && constrainingWidth && constrainingWidth > 0) {
			/* For embed-responsive, always use grandparent width (fluid container) */
			maxWidth = constrainingWidth;
		} else {
			/* For fr-video and others, use smaller of: grandparent or iframe width */
			maxWidth = (constrainingWidth && constrainingWidth > 0 && constrainingWidth < width) ? constrainingWidth : width;
		}
		var paddingBottom = ((height / width) * 100).toFixed(2) + '%';
		container.style.width = '100%';
		container.style.paddingBottom = paddingBottom;
		container.style.height = '0';
		/* Set parent fr-video span dimensions to prevent CLS */
		if (isFrVideo) {
			parentElement.style.visibility = 'hidden';
			parentElement.className = (parentElement.className + ' img-rounded').trim();
			parentElement.style.width = '100%';
			parentElement.style.maxWidth = maxWidth + 'px';
			parentElement.style.aspectRatio = width + ' / ' + height;
			parentElement.setAttribute('width', maxWidth);
			parentElement.setAttribute('height', Math.round(maxWidth * (height / width)));
		}
		if (iframe.style.cssText) {
			var inlineStyles = iframe.style.cssText.split(';');
			for (var i = 0; i < inlineStyles.length; i++) {
				var style = inlineStyles[i].trim();
				if (style && style.indexOf('width') === -1 && style.indexOf('height') === -1) {
					container.style.cssText += style + ';';
				}
			}
		}
		var clonedIframe = iframe.cloneNode(true);
		var outerWrapper = document.createElement('div');
		outerWrapper.className = 'youtube-lazy-outer bmargin img-rounded';
		outerWrapper.style.maxWidth = maxWidth + 'px';
		outerWrapper.style.aspectRatio = width + ' / ' + height;
		outerWrapper.setAttribute('width', maxWidth);
		outerWrapper.setAttribute('height', Math.round(maxWidth * (height / width)));
		outerWrapper.appendChild(container);
		iframe.parentNode.replaceChild(outerWrapper, iframe);
		loadThumbnail(container, videoId, clonedIframe, width, height, isFrVideo ? parentElement : null);
	}
	/* Remove src from dynamically added iframes (used by MutationObserver) */
	function removeSrcFromAllIframes() {
		var iframes = document.querySelectorAll('iframe[src*="youtube.com/embed"], iframe[src*="youtube-nocookie.com/embed"]');
		Array.prototype.forEach.call(iframes, function(iframe) {
			if (!iframe.getAttribute('data-youtube-lazy')) {
				iframe.setAttribute('data-youtube-src', iframe.src);
				iframe.removeAttribute('src');
				iframe.setAttribute('data-youtube-lazy', 'src-removed');
			}
		});
	}
	/* Wait for preloader on mobile, then init */
	document.addEventListener('DOMContentLoaded', function() {
		if (shouldWaitForPreloader) {
			setTimeout(initYouTubeLazyLoad, 8000);
		} else {
			initYouTubeLazyLoad();
		}
	});
	/* Initialize lazy load and watch for new videos */
	function initYouTubeLazyLoad() {
		try {
			processYouTubeIframes();
			if (typeof MutationObserver !== 'undefined') {
				var observer = new MutationObserver(function(mutations) {
					clearTimeout(debounceTimer);
					debounceTimer = setTimeout(function() {
						var hasNewIframes = false;
						mutations.forEach(function(mutation) {
							if (mutation.addedNodes.length > 0) {
								mutation.addedNodes.forEach(function(node) {
									if (node.nodeType === 1) {
										if (node.tagName === 'IFRAME' || (node.querySelectorAll && node.querySelectorAll('iframe').length > 0)) {
											hasNewIframes = true;
										}
									}
								});
							}
						});
						if (hasNewIframes) {
							removeSrcFromAllIframes();
							processYouTubeIframes();
						}
					}, 100);
				});
				if (document.body) {
					observer.observe(document.body, {
						childList: true,
						subtree: true
					});
				}
			}
		} catch(e) {
			// Silently fail - prevent page breaking
		}
	}
})();
</script>
<script>
/* === NON-YOUTUBE VIDEO PROVIDERS LAZY LOAD === */
/* Added for Vimeo, Wistia, Spotify, etc. - Independent of YouTube system */
(function() {
	try {
	var videoProviders = ["brightcove","dailymotion","embedly","facebook.com","giphy","imgur","instagram.com","jwplatform","khanacademy","linkedin.com","loom","pinterest.com","podcasts.apple","reddit","rumble","soundcloud","spotify.com","streamable","ted.com","tiktok","twitch","twitter.com","udemy","vimeo","vidyard","wistia","x.com","player.viloud.tv","viloud.tv","iubenda.com","cdn.iubenda.com"];
	if (!videoProviders || videoProviders.length === 0) return;
	/* Check if iframe domain matches provider list */
	function isVideoProvider(src) {
		if (!src) return false;
		var domainMatch = src.match(/^https?:\/\/([^\/\?#]+)/);
		if (!domainMatch) return false;
		var domain = domainMatch[1].toLowerCase();
		for (var i = 0; i < videoProviders.length; i++) {
			if (domain.indexOf(videoProviders[i]) > -1) return true;
		}
		return false;
	}
	/* Parse pixel values from styles */
	function parsePx(value) {
		if (!value) return null;
		var str = String(value);
		if (str.indexOf('%') > -1) return null;
		var num = parseInt(str, 10);
		return (num > 0) ? num : null;
	}
	/* Check if we should wait for mobile preloader */
	var isMobile = window.innerWidth <= 768;
	var hasPreloader = document.getElementById('mobile-loading-message');
	var shouldWaitForPreloader = isMobile && hasPreloader;
	/* Strip src from video provider iframes immediately */
	var iframes = document.querySelectorAll('iframe[src]');
	Array.prototype.forEach.call(iframes, function(iframe) {
		if (!iframe.getAttribute('data-video-lazy') && isVideoProvider(iframe.src)) {
			iframe.setAttribute('data-video-src', iframe.src);
			iframe.removeAttribute('src');
			iframe.setAttribute('data-video-lazy', 'removed');
		}
	});
	/* Process video iframes */
	function processVideoIframes() {
		var iframes = document.querySelectorAll('iframe[data-video-src], iframe[src]');
		Array.prototype.forEach.call(iframes, function(iframe) {
			var state = iframe.getAttribute('data-video-lazy');
			if (state === 'processed') return;
			var src = iframe.getAttribute('data-video-src') || iframe.src;
			if (!src || !isVideoProvider(src)) return;
			/* Set title for accessibility if missing (do this early for PageSpeed) */
			if (!iframe.getAttribute('title')) {
				var providerName = 'Video';
				for (var i = 0; i < videoProviders.length; i++) {
					if (src.indexOf(videoProviders[i]) > -1) {
						providerName = videoProviders[i].charAt(0).toUpperCase() + videoProviders[i].slice(1);
						break;
					}
				}
				iframe.setAttribute('title', providerName + ' embed player');
			}
			/* Check for nolazy/forceplay params */
			if (src.indexOf('nolazy=1') > -1 || src.indexOf('forceplay=1') > -1) {
				var cleanSrc = src.replace(/[?&](nolazy|forceplay)=1/g, '').replace(/\?&/, '?').replace(/[&?]$/, '');
				iframe.src = cleanSrc;
				iframe.setAttribute('data-video-lazy', 'processed');
				return;
			}
			/* Check viewport position */
			var rect = iframe.getBoundingClientRect();
			var isNearViewport = rect.top < (window.innerHeight + 200);
			if (!isNearViewport) {
				iframe.setAttribute('data-video-lazy', 'pending');
				if (typeof IntersectionObserver !== 'undefined') {
					var observer = new IntersectionObserver(function(entries) {
						entries.forEach(function(entry) {
							if (entry.isIntersecting) {
								loadVideoIframe(entry.target);
								observer.unobserve(entry.target);
							}
						});
					}, { rootMargin: '200px' });
					observer.observe(iframe);
				}
				return;
			}
			/* In viewport - load immediately */
			loadVideoIframe(iframe);
		});
	}
	/* Load iframe by restoring src */
	function loadVideoIframe(iframe) {
		if (iframe.getAttribute('data-video-lazy') === 'processed') return;
		iframe.setAttribute('data-video-lazy', 'processed');
		var src = iframe.getAttribute('data-video-src');
		if (!src) return;
		/* Check if wrapped in Froala .fr-video span */
		var parentElement = iframe.parentNode;
		var isFrVideo = parentElement && parentElement.classList && parentElement.classList.contains('fr-video');
		/* Check if wrapped in Bootstrap .embed-responsive container - its CSS already sizes the iframe to 100% of the container, so inline px dimensions would clobber the responsive sizing */
		var isEmbedResponsive = parentElement && parentElement.classList && parentElement.classList.contains('embed-responsive');
		/* Calculate and set dimensions to prevent CLS */
		var inlineWidth = parsePx(iframe.style.width);
		var inlineHeight = parsePx(iframe.style.height);
		var attrWidth = parsePx(iframe.getAttribute('width'));
		var attrHeight = parsePx(iframe.getAttribute('height'));
		var width = inlineWidth || attrWidth || iframe.offsetWidth || 640;
		var height = inlineHeight || attrHeight || iframe.offsetHeight || 360;
		if (width <= 0 || height <= 0) {
			width = 640;
			height = 360;
		}
		if (!isEmbedResponsive) {
			iframe.style.width = width + 'px';
			iframe.style.height = height + 'px';
			iframe.style.aspectRatio = width + ' / ' + height;
		}
		/* Reveal parent .fr-video after load or timeout */
		if (isFrVideo) {
			var revealed = false;
			var revealParent = function() {
				if (!revealed) {
					revealed = true;
					parentElement.style.visibility = 'visible';
				}
			};
			iframe.onload = revealParent;
			setTimeout(revealParent, 3000);
		}
		iframe.src = src;
	}
	/* Watch for dynamically added iframes */
	function removeNewIframeSrc() {
		var iframes = document.querySelectorAll('iframe[src]');
		Array.prototype.forEach.call(iframes, function(iframe) {
			if (!iframe.getAttribute('data-video-lazy') && isVideoProvider(iframe.src)) {
				iframe.setAttribute('data-video-src', iframe.src);
				iframe.removeAttribute('src');
				iframe.setAttribute('data-video-lazy', 'removed');
			}
		});
	}
	/* Initialize video iframe lazy load */
	function initVideoIframeLazyLoad() {
		processVideoIframes();
		if (typeof MutationObserver !== 'undefined') {
			var debounce;
			var observer = new MutationObserver(function(mutations) {
				clearTimeout(debounce);
				debounce = setTimeout(function() {
					var hasIframes = false;
					mutations.forEach(function(mutation) {
						if (mutation.addedNodes.length > 0) {
							mutation.addedNodes.forEach(function(node) {
								if (node.nodeType === 1 && (node.tagName === 'IFRAME' || (node.querySelectorAll && node.querySelectorAll('iframe').length > 0))) {
									hasIframes = true;
								}
							});
						}
					});
					if (hasIframes) {
						removeNewIframeSrc();
						processVideoIframes();
					}
				}, 100);
			});
			if (document.body) {
				observer.observe(document.body, { childList: true, subtree: true });
			}
		}
	}
	/* Wait for preloader on mobile, then init */
	document.addEventListener('DOMContentLoaded', function() {
		if (shouldWaitForPreloader) {
			setTimeout(initVideoIframeLazyLoad, 8000);
		} else {
			initVideoIframeLazyLoad();
		}
	});
	} catch(e) {
		// Silently fail - prevent page breaking
	}
})();
</script>
        <script type="text/javascript">
    /* CT dissolved its county governments in 1960, so Google returns its 8 counties as
       colloquial_area instead of administrative_area_level_2 — they must never reach a
       city field. Google translates the component name to the site language, so the
       language-stable place_id is checked first and the word list only backs it up. */
    if (typeof window.bdIsColloquialCounty !== 'function') {
        window.bdIsColloquialCounty = function (componentName, resultPlaceId) {
            var countyPlaceIds = [
                'ChIJWRM2Nakw5okRoTCxHvz_5xw', /* Middlesex County, CT */
                'ChIJmeTbuDYH6IkR3xgeNvszpgg', /* Fairfield County, CT */
                'ChIJiT24cvvP54kR2fSPHkp0Akc', /* New Haven County, CT */
                'ChIJvYe7N7eQ54kRL6nZaXRwPkI', /* Litchfield County, CT */
                'ChIJtxC3p6qs54kRIvK-2bctar0', /* Hartford County, CT */
                'ChIJj-lvZQli5okRGCuGRd6xKt0', /* Tolland County, CT */
                'ChIJRWKqeLdi5okRLXWDlSEGeTY', /* Windham County, CT */
                'ChIJwTIQbvVv5okRU5_gSJczUTQ'  /* New London County, CT */
            ];

            if (typeof resultPlaceId === 'string' && resultPlaceId !== ''
                && countyPlaceIds.indexOf(resultPlaceId) !== -1) {
                return true;
            }

            if (typeof componentName !== 'string' || componentName === '') {
                return false;
            }

            var name = componentName.toLowerCase();

            /* Only unambiguous county words — generic ones (region, district) would strip
               legitimate colloquial areas, and their languages already match on place_id.
               Word-boundary matched so names like "Countyline, OK" are left alone. */
            var wordTokens = ['county', 'condado', 'comté', 'contea',
                              'comitatul', 'hrabstwo', 'megye', 'konderria'];
            var isAlnum = function (ch) {
                return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9');
            };

            for (var t = 0; t < wordTokens.length; t++) {
                var token = wordTokens[t];
                var from = 0;
                while (true) {
                    var at = name.indexOf(token, from);
                    if (at === -1) {
                        break;
                    }
                    var before = (at > 0) ? name.charAt(at - 1) : ' ';
                    var after = ((at + token.length) < name.length) ? name.charAt(at + token.length) : ' ';
                    if (!isAlnum(before) && !isAlnum(after)) {
                        return true;
                    }
                    from = at + 1;
                }
            }

            /* Non-latin scripts have no alphanumeric word boundary. */
            var scriptTokens = ['каунти', 'کاؤنٹی', 'काउंटी', '카운티'];
            for (var s = 0; s < scriptTokens.length; s++) {
                if (name.indexOf(scriptTokens[s]) !== -1) {
                    return true;
                }
            }

            return false;
        };
    }

            // Debug mode variable
            var isDevMode = ``;
            
            var cityTypes       = [
                'colloquial_area',
                'locality',
                'sublocality',
                'sublocality_level_1',
                'sublocality_level_2',
                'sublocality_level_3',
                'sublocality_level_4',
                'sublocality_level_5',
                'neighborhood',
                'ward',
                'postal_town'
            ];

            var postalTypes = [
                'postal_code',
                'postal_code_prefix',
                'postal_code_suffix',
                'street_number',
                'premise',
                'subpremise',
                'route',
                'intersection',
                'street_address',
                'floor',
                'room',
                'post_box',
                'delivery_address'
            ];

            var localizedMainCountry = '';
            // Add debugging for Google Maps loading
            window.gm_authFailure = function() {
                const errorMessage = document.createElement('div');
                errorMessage.className = 'alert alert-danger';
                errorMessage.innerHTML = `Google Maps authentication failed. Please check the console for more details.`;
                document.body.insertBefore(errorMessage, document.body.firstChild);
            };

            // Try to load coordinates from sessionStorage on page load
            var vlat = 0;
            var vlon = 0;
            try {
                var savedLat = sessionStorage.getItem('bd_geolocation_lat');
                var savedLon = sessionStorage.getItem('bd_geolocation_lon');
                if (savedLat && savedLon) {
                    vlat = parseFloat(savedLat);
                    vlon = parseFloat(savedLon);
                }
            } catch(e) {}
            var isSubmit = false;
            var mapsLoaded = false;
            var mapsLoading = false;
            var placesInitialized = false;
            let newestRequestId = 0;
            var cachedSelectedOption = null;
            var warningMessageWasTriggered = false; // Track if warning message was shown
            var isGettingLocation = false; // Flag to prevent multiple simultaneous geolocation requests
            
            // Function to save coordinates to sessionStorage
            function saveCoordinatesToSession(lat, lon) {
                try {
                    sessionStorage.setItem('bd_geolocation_lat', lat.toString());
                    sessionStorage.setItem('bd_geolocation_lon', lon.toString());
                } catch(e) {}
            }
            
            // Function to get coordinates from sessionStorage if current ones are 0
            function getCoordinatesFromSession() {
                if (vlat === 0 && vlon === 0) {
                    try {
                        var savedLat = sessionStorage.getItem('bd_geolocation_lat');
                        var savedLon = sessionStorage.getItem('bd_geolocation_lon');
                        if (savedLat && savedLon) {
                            vlat = parseFloat(savedLat);
                            vlon = parseFloat(savedLon);
                            return true;
                        }
                    } catch(e) {}
                }
                return false;
            }

            var gmapScriptLoading = false;
            var gmapScriptPromise = null;

            function googleMapOnFormClick() {
                if (typeof google !== "undefined" && google.hasOwnProperty('maps')) {
                    return Promise.resolve();
                }
                if (gmapScriptLoading && gmapScriptPromise) {
                    return gmapScriptPromise;
                }
                gmapScriptLoading = true;
                gmapScriptPromise = new Promise((resolve, reject) => {
                    window.isSubmittingMainSearch = false;
                    let mapUri = "https://maps.googleapis.com/maps/api/js?v=quarterly&libraries=places&region=US&callback=initializeGoogleMaps&language=en";

                    let script = document.createElement('script');
                    script.type = 'text/javascript';
                    script.src = mapUri;
                    script.async = true;
                    script.onload = function () {
                        resolve("ok");
                    };
                    script.onerror = function () {
                        gmapScriptLoading = false;
                        reject("Failed to load Google Maps script.");
                    };
                    document.head.appendChild(script);
                });
                return gmapScriptPromise;
            }

            function loadGoogleMaps() {
                return new Promise((resolve, reject) => {
                    if (mapsLoaded) {
                        resolve();
                        return;
                    }

                    if (mapsLoading) {
                        const checkLoaded = setInterval(() => {
                            if (mapsLoaded) {
                                clearInterval(checkLoaded);
                                resolve();
                            }
                        }, 100);
                        return;
                    }

                    mapsLoading = true;

                    // Remove any existing Google Maps scripts
                    const existingScripts = document.querySelectorAll('script[src*="maps.googleapis.com"]');
                    existingScripts.forEach(script => script.remove());

                    window.initMap = async function() {
                        try {
                            let mapExists = document.querySelectorAll('[id^="map"]').length > 0;
                            const functionsToInvoke = {
                                setJsMap: true,
                                setJsMapOverview: mapExists,
                                setJsMapSR: mapExists,
                                setJsMapSidebar: mapExists
                            };
                            if (window['maps_loaded'] !== true) {
                                for (let func in functionsToInvoke) {
                                    if (typeof window[func] === 'function' && functionsToInvoke[func]) {
                                        window['maps_loaded'] = true;
                                        window[func]();
                                    }
                                }
                            }
                            mapsLoaded = true;
                            mapsLoading = false;
                            resolve();
                        } catch (error) {
                            reject(error);
                        }
                    };

                   /* const script = document.createElement('script');
                    script.type = 'text/javascript';
                    script.src = `https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initMap&language=en`;
                    script.async = true;
                    script.defer = true;
                    script.onerror = function(error) {
                        console.error('Failed to load Google Maps:', error);
                        mapsLoading = false;
                        reject(error);
                    };
                    */
                    //document.head.appendChild(script);
                    if((typeof google == "undefined" || !google.hasOwnProperty('maps')) && typeof googleMapOnFormClick !== 'undefined' && typeof googleMapOnFormClick === 'function'){
                        googleMapOnFormClick().then(() => {
                            initMap();
                        });
                    }else{
                        initMap();
                    }
                });
            }

            function normalizePlaceToGeocoder(place) {
                if (!place) return null;

                return {
                    formatted_address: place.formattedAddress || null,
                    place_id: place.id || null,
                    types: place.types || [],
                    address_components: place.addressComponents?.map(comp => ({
                        long_name: comp.longText || "",
                        short_name: comp.shortText || "",
                        types: comp.types || []
                    })) || [],
                    geometry: {
                        bounds: place.viewport || null,
                        location: place.location || null,
                        viewport: place.viewport || null
                    }
                };
            }

            async function initializeAutocomplete() {
                if (placesInitialized) {
                    return;
                }

                try {
                    if (!window.google || !window.google.maps) {
                        throw new Error('Maps API not available');
                    }

                    const inputs = document.querySelectorAll('.googleSuggest, #location_google_maps_header, .google-writen-location, input[name="lead_location"], .fill_location');
                    
                            inputs.forEach(input => {
                                if (input.getAttribute('data-autocomplete-initialized')) {
                                    return;
                                }
                                
                                // Add value setter interceptor to block unauthorized value changes
                                const originalValueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
                                if (originalValueSetter) {
                                    let valueSetterInterceptor = function(newValue) {
                                        const stack = new Error().stack;
                                        const caller = stack.split('\n')[2]?.trim() || 'unknown';
                                        
                                        // Protect the input value if it was set by a valid suggestion selection
                                        if (window.inputValueProtected && 
                                            window.protectedInputId === this.id &&
                                            window.expectedInputValue &&
                                            newValue !== window.expectedInputValue) {
                                            if (isDevMode) {
                                                console.warn('🚫 BLOCKED: Attempt to change protected input value');
                                            }
                                            return;
                                        }
                                        
                                        // Allow value changes if a suggestion is being clicked (legitimate selection)
                                        if (window.suggestionBeingClicked) {
                                            const expectedValue = window.expectedInputValue || 
                                                                 (window.cachedSelectedOption && 
                                                                  window.cachedSelectedOption[0] &&
                                                                  (window.cachedSelectedOption[0].displayName || 
                                                                   window.cachedSelectedOption[0].formatted_address || 
                                                                   window.cachedSelectedOption[0].name));
                                            
                                            const isFromOurCode = caller.includes('javascript.php') || 
                                                                  caller.includes('connect?devmode') ||
                                                                  caller.includes('sample-member');
                                            
                                            if (expectedValue && newValue === expectedValue) {
                                                window.inputClearedByUser = false;
                                                window.clearedInputId = null;
                                            } else if (expectedValue && newValue !== expectedValue) {
                                                if (isDevMode) {
                                                    console.warn('🚫 BLOCKED: Value doesnt match selected suggestion');
                                                }
                                                return;
                                            } else if (!isFromOurCode) {
                                                // Block external scripts from setting values when suggestion is being clicked
                                                if (isDevMode) {
                                                    console.warn('🚫 BLOCKED: External script trying to set value while suggestion is being clicked');
                                                }
                                                return;
                                            }
                                        }
                                        // Block value changes if input was recently cleared by user
                                        else if (window.inputClearedByUser && 
                                            window.clearedInputId === this.id &&
                                            Date.now() - window.inputClearedTimestamp < 2000 &&
                                            newValue && newValue.trim() !== '') {
                                            if (isDevMode) {
                                                console.warn('🚫 BLOCKED: Attempt to set value after user cleared input');
                                            }
                                            return;
                                        }
                                        
                                        return originalValueSetter.call(this, newValue);
                                    };
                                    
                                    try {
                                        Object.defineProperty(input, 'value', {
                                            get: Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.get,
                                            set: valueSetterInterceptor,
                                            configurable: true
                                        });
                                    } catch (e) {
                                        // Ignore if we can't intercept
                                    }
                                }
                        
                        try {
                            // Create the request object with initial configuration
                            const websiteLanguage = 'en';
                            const countryRegion = '';
                            
                            const request = {
                                input: '',
                                language: 'en',
                                includedRegionCodes: localizedMainCountry ? [ localizedMainCountry ] : [],
                                sessionToken: null
                            };

                            // Create and style the suggestions container
                            const suggestionsContainer = document.createElement('div');
                            suggestionsContainer.className = 'pac-container pac-logo';
                            suggestionsContainer.setAttribute('data-input-id', input.id || 'input-' + Math.random().toString(36).substr(2, 9));
                            suggestionsContainer.style.cssText = `
                                position: absolute;
                                z-index: 1000;
                                background-color: #fff;
                                border: 1px solid rgba(0,0,0,0.2);
                                box-shadow: 0 2px 6px rgba(0,0,0,0.3);
                                -moz-box-sizing: border-box;
                                -webkit-box-sizing: border-box;
                                box-sizing: border-box;
                                overflow: hidden;
                                font-family: Arial, sans-serif;
                                margin-top: 1px;
                                display: none;
                            `;
                                                        
                            // Add PAC banner header
                            const header = document.createElement('div');
                            header.className = 'pac-header';
                            header.setAttribute('role', 'note');
                            header.setAttribute('aria-hidden', 'true');
                            header.innerHTML = "<span>REQUIRED: Select Location</span>";
                            
                            suggestionsContainer.appendChild(header);
                                                        document.body.appendChild(suggestionsContainer);
                            
                            // Add styles for suggestion items
                            const style = document.createElement('style');
                            style.textContent = `
                                .pac-container {
                                    background-color: #fff;
                                    position: absolute;
                                    z-index: 1000;
                                    border-radius: 2px;
                                    border-top: 1px solid #d9d9d9;
                                    font-family: Arial, sans-serif;
                                    box-shadow: 0 2px 6px rgba(0,0,0,0.3);
                                    -moz-box-sizing: border-box;
                                    -webkit-box-sizing: border-box;
                                    box-sizing: border-box;
                                    overflow: hidden;
                                    visibility: hidden;
                                    opacity: 0;
                                }
                                .pac-container.visible {
                                    visibility: visible;
                                    opacity: 1;
                                }
                                .pac-item {
                                    cursor: default;
                                    padding: 0 4px;
                                    text-overflow: ellipsis;
                                    overflow: hidden;
                                    white-space: nowrap;
                                    line-height: 30px;
                                    text-align: left;
                                    border-top: 1px solid #e6e6e6;
                                    font-size: 11px;
                                    color: #999;
                                    height: 40px;
                                    display: flex;
                                    align-items: center;
                                }
                                .pac-item:first-child {
                                    border-top: none;
                                }
                                .pac-item:hover {
                                    background-color: #fafafa;
                                }
                                .pac-item-query {
                                    font-size: 13px;
                                    padding-right: 3px;
                                    color: #000;
                                }
                                .pac-matched {
                                    font-weight: 700;
                                }
                                .pac-icon-marker {
                                    width: 15px !important;
                                    height: 20px;
                                    margin-right: 7px;
                                    margin-top: 6px;
                                    display: inline-block;
                                    vertical-align: top;
                                    background-image: url(https://maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons.png);
                                    background-position: -1px -161px;
                                    -webkit-background-size: 34px;
                                    background-size: 34px;
                                    min-width: 15px;
                                    box-sizing: content-box;
                                }
                            `;
                            document.head.appendChild(style);

                            // Function to update container position
                            function updateContainerPosition() {
                                const inputRect = input.getBoundingClientRect();
                                const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
                                const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
                                
                                suggestionsContainer.style.top = `${inputRect.bottom + scrollTop}px`;
                                suggestionsContainer.style.left = `${inputRect.left + scrollLeft}px`;
                                suggestionsContainer.style.width = `${inputRect.width}px`;
                                suggestionsContainer.style.zIndex = '9999';
                            }

                            // Update position on scroll and resize
                            window.addEventListener('scroll', updateContainerPosition);
                            window.addEventListener('resize', updateContainerPosition);

                            // Helper function to refresh the session token
                            function refreshToken() {
                                request.sessionToken = new google.maps.places.AutocompleteSessionToken();
                            }

                            // Handle input changes
                            let debounceTimer;
                            input.addEventListener('input', async () => {
                                clearTimeout(debounceTimer);
                                const query = input.value.trim();

                                // Clear cached selection when user types new text
                                if (window.cachedSelectedOption && window.cachedSelectedOption[0]) {
                                    const currentValue = window.cachedSelectedOption[0].displayName || window.cachedSelectedOption[0].formatted_address || window.cachedSelectedOption[0].name || '';
                                    
                                    if (query !== currentValue) {
                                        // User is typing new text - remove input value protection
                                        window.inputValueProtected = false;
                                        window.expectedInputValue = null;
                                        window.protectedInputId = null;
                                        window.cachedSelectedOption = null;
                                        sessionStorage.removeItem("google_result");
                                        
                                        // Show warning when user modifies the text
                                        if (query.length > 0) {
                                            // Add a small delay to allow for suggestion selection
                                            setTimeout(() => {
                                                // Only show warning if no new suggestion was selected during the delay
                                                if (!window.cachedSelectedOption || !window.cachedSelectedOption[0]) {
                                                    window.replaceClearIconWithWarning(input);
                                                }
                                            }, 500);
                                        }
                                    }
                                }

                                // Update the request with the latest input
                                request.input = query;

                                // Store the request ID to avoid race conditions
                                const requestId = ++newestRequestId;
                                
                                // Handle case when user deletes all text
                                if (query.length === 0) {
                                    suggestionsContainer.style.display = 'none';
                                    suggestionsContainer.classList.remove('visible');
                                    window.cachedSelectedOption = null;
                                    sessionStorage.removeItem("google_result");
                                    
                                    // Clear any existing warning
                                    const clearIcon = input.parentElement.querySelector('.clear_content.large, .clear_content.medium, .clear_content');
                                    if (clearIcon) {
                                        // Clear any pending warning timeout
                                        if (clearIcon.dataset.warningTimeoutId) {
                                            clearTimeout(parseInt(clearIcon.dataset.warningTimeoutId));
                                            delete clearIcon.dataset.warningTimeoutId;
                                        }
                                        
                                        $(clearIcon).popover('hide');
                                        $(clearIcon).popover('destroy');
                                        clearIcon.classList.remove('clicked');
                                        
                                        // Restore original icon if it was changed
                                        const iconElement = clearIcon.querySelector('i');
                                        if (iconElement && iconElement.className.includes('fa-exclamation-circle')) {
                                            iconElement.className = 'fa fa-times-circle';
                                        }
                                        
                                        warningMessageWasTriggered = false;
                                    }
                                    return;
                                }

                                debounceTimer = setTimeout(async () => {
                                    try {
                                        if (query.length < 2) {
                                            suggestionsContainer.style.display = 'none';
                                            suggestionsContainer.classList.remove('visible');
                                            return;
                                        }

                                        // Fetch autocomplete suggestions
                                        const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);

                                        // If the request has been superseded by a newer request, do not render
                                        if (requestId !== newestRequestId) {
                                            return;
                                        }

                                        // Filter out unwanted suggestions and limit to 5 items
                                        const filteredSuggestions = suggestions;

                                        if (isDevMode) {
                                            console.log(filteredSuggestions);
                                        }

                                        // Only show container and update if we have suggestions
                                        if (filteredSuggestions.length > 0) {
                                            // Preserve the header when clearing the container
                                            const existingHeader = suggestionsContainer.querySelector('.pac-header');
                                            suggestionsContainer.innerHTML = '';
                                            
                                            // Re-add the header if it existed
                                            if (existingHeader) {
                                                suggestionsContainer.appendChild(existingHeader);
                                            }
                                            
                                            suggestionsContainer.style.display = 'block';
                                            suggestionsContainer.classList.add('visible');
                                            updateContainerPosition();

                                            for (const suggestion of filteredSuggestions) {
                                                const placePrediction   = suggestion.placePrediction;
                                                // Don't fetch full details here - save API credits
                                                // Only get basic place object for logging
                                                const placeObject       = await placePrediction.toPlace();
                                                if (isDevMode) {
                                                    console.log('place object (basic)',placeObject);
                                                    console.log('placePrediction object',placePrediction);
                                                    console.log('suggestion',suggestion);
                                                }
                                                const suggestionElement = document.createElement('div');
                                                suggestionElement.className = 'pac-item';
                                                
                                                // Debug the available properties
                                                let mainText = '';
                                                let secondaryText = '';

                                                if(isDevMode){
                                                    console.log('formatted text',placePrediction.formattedSuggestion);
                                                    console.log('structured_formatting',placePrediction.structured_formatting);
                                                    console.log('description',placePrediction.description);
                                                }
                                                
                                                // Try different ways to get the text
                                                if (placePrediction.formattedSuggestion && placePrediction.formattedSuggestion.mainText) {
                                                    mainText = placePrediction.formattedSuggestion.mainText;
                                                    secondaryText = placePrediction.formattedSuggestion.secondaryText || '';
                                                    
                                                    // Clean up the secondary text to remove country
                                                    if (secondaryText) {
                                                        secondaryText = secondaryText.split(',')
                                                            .map(part => part.trim())
                                                            .filter(part => part !== 'USA')
                                                            .join(', ');
                                                    }
                                                } else if (placePrediction.structured_formatting) {
                                                    mainText = placePrediction.structured_formatting.main_text;
                                                    secondaryText = placePrediction.structured_formatting.secondary_text || '';
                                                    
                                                    // Clean up the secondary text to remove country
                                                    if (secondaryText) {
                                                        secondaryText = secondaryText.split(',')
                                                            .map(part => part.trim())
                                                            .filter(part => part !== 'USA')
                                                            .join(', ');
                                                    }
                                                } else if (placePrediction.description) {
                                                    const parts = placePrediction.description.split(',').map(part => part.trim());
                                                    mainText = parts[0];
                                                    // Filter out USA and join remaining parts
                                                    secondaryText = parts.slice(1)
                                                        .filter(part => part !== 'USA')
                                                        .join(', ');
                                                } else if (placePrediction.text) {
                                                    mainText  = secondaryText = placePrediction.text.toString();
                                                } else {
                                                    const parts = (placePrediction.displayName || placePrediction.name || 'Unknown location').split(',').map(part => part.trim());
                                                    mainText = parts[0];
                                                    // Filter out USA and join remaining parts
                                                    secondaryText = parts.slice(1)
                                                        .filter(part => part !== 'USA')
                                                        .join(', ');
                                                }
                                                
                                                
                                                // Create the suggestion element with the map marker icon
                                                suggestionElement.innerHTML = `
                                                    <span class="pac-icon-marker" style="width: 15px !important; min-width: 15px;"></span>
                                                    <span class="pac-item-query">${mainText}</span>
                                                    <span>${secondaryText}</span>
                                                `;
                                                
                                                // Handle suggestion selection with proper mouse event handling
                                                const handleSuggestionSelection = async () => {
                                                    try {
                                                        // Set flag to prevent warning when suggestion is clicked
                                                        window.suggestionBeingClicked = true;
                                                        
                                                        // Clear the input clearing protection since user is selecting a suggestion
                                                        window.inputClearedByUser = false;
                                                        window.clearedInputId = null;
                                                        
                                                        // Set a temporary expected value based on the prediction text to block external scripts
                                                        const predictionText = placePrediction.text ? placePrediction.text.toString() : '';
                                                        if (predictionText) {
                                                            const parts = predictionText.split(',').map(part => part.trim());
                                                            const tempDisplayName = parts.filter(part => part !== 'USA').join(', ');
                                                            window.expectedInputValue = tempDisplayName;
                                                            window.inputValueProtected = true;
                                                            window.protectedInputId = input.id;
                                                        }
                                                        
                                                        // Clear any existing warnings immediately when suggestion is clicked
                                                        const clearIcon = input.parentElement.querySelector('.clear_content.large, .clear_content.medium, .clear_content');
                                                        if (clearIcon) {
                                                            // Clear any pending warning timeout
                                                            if (clearIcon.dataset.warningTimeoutId) {
                                                                clearTimeout(parseInt(clearIcon.dataset.warningTimeoutId));
                                                                delete clearIcon.dataset.warningTimeoutId;
                                                            }
                                                            
                                                            $(clearIcon).popover('hide');
                                                            $(clearIcon).popover('destroy');
                                                            clearIcon.classList.remove('clicked');
                                                            
                                                            // Restore original icon
                                                            const iconElement = clearIcon.querySelector('i');
                                                            if (iconElement && iconElement.className.includes('fa-exclamation-circle')) {
                                                                iconElement.className = 'fa fa-times-circle';
                                                            }
                                                        }
                                                        
                                                        // Store the original input value before setting the suggestion
                                                        const originalInputValue = input.value;
                                                        
                                                        // Fetch full place details only when user clicks (saves API credits)
                                                        const place = await placePrediction.toPlace();
                                                        if (isDevMode) {
                                                            console.log('Place session token:', place.sessionToken);
                                                            console.log('Prediction session token:', placePrediction.sessionToken);
                                                        }
                                                        await place.fetchFields({
                                                            fields: [
                                                                'addressComponents',
                                                                'adrFormatAddress',
                                                                'formattedAddress',
                                                                'location',
                                                                'plusCode',
                                                                'postalAddress',
                                                                'types',
                                                                'viewport'
                                                            ]
                                                        });

                                                        if (!place.location) {
                                                            if (isDevMode) console.warn('No location found for selected place');
                                                            return;
                                                        }

                                                        const cachedOption = normalizePlaceToGeocoder(place);
                                                        cachedOption.suggestion_address = placePrediction.text.toString() ;

                                                        if (placePrediction.text) {
                                                            const parts = placePrediction.text.toString().split(',').map(part => part.trim());
                                                            displayName = parts.filter(part => part !== 'USA').join(', ');
                                                        } else {
                                                            const parts = displayName.split(',').map(part => part.trim());
                                                            displayName = parts.filter(part => part !== 'USA').join(', ');
                                                        }
                                                        
                                                        // Store both the full formatted address and the display name
                                                        cachedOption.displayName = displayName;
                                                        window.cachedSelectedOption = [cachedOption];
                                                        
                                                        // Store the expected value to protect it from being changed
                                                        window.expectedInputValue = displayName;
                                                        window.inputValueProtected = true;
                                                        window.protectedInputId = input.id;

                                                        input.value = displayName;
                                                        suggestionsContainer.style.display = 'none';
                                                        suggestionsContainer.classList.remove('visible');
                                                        
                                                        // Check if the text actually changed after setting the suggestion
                                                        const textChanged = originalInputValue !== displayName;
                                                        
                                                        // If text didn't change, mark this as a valid selection to prevent warning
                                                        if (!textChanged && !window.cachedSelectedOption) {
                                                            window.cachedSelectedOption = [{
                                                                formatted_address: displayName,
                                                                name: displayName,
                                                                displayName: displayName
                                                            }];
                                                        }
                                                        
                                                        if (typeof makeSearch === 'function') {
                                                            makeSearch(cachedOption);
                                                        }
                                                        
                                                        // Refresh the session token after a selection
                                                        refreshToken();
                                                        warningMessageWasTriggered = false; // Reset flag when suggestion is selected
                                                    } catch (error) {
                                                        if (isDevMode) {
                                                            console.error('Error fetching place details:', error);
                                                            console.error('Error stack:', error.stack);
                                                        }
                                                    } finally {
                                                        // Reset the flag after a delay to ensure blur event doesn't interfere
                                                        setTimeout(() => {
                                                            window.suggestionBeingClicked = false;
                                                        }, 500);
                                                    }
                                                };
                                                
                                                // Track if mouse was pressed down on this element
                                                let mouseDownOnElement = false;
                                                
                                                // Handle mousedown to track where the press started
                                                suggestionElement.addEventListener('mousedown', (e) => {
                                                    mouseDownOnElement = true;
                                                    if (isDevMode) console.log('🖱️ Mouse down on suggestion');
                                                    e.preventDefault(); // Prevent text selection during drag
                                                });
                                                
                                                // Handle mouseup to trigger selection if press started on this element
                                                suggestionElement.addEventListener('mouseup', async (e) => {
                                                    if (mouseDownOnElement) {
                                                        if (isDevMode) console.log('🖱️ Mouse up on same suggestion - triggering selection');
                                                        e.preventDefault();
                                                        e.stopPropagation();
                                                        await handleSuggestionSelection();
                                                    }
                                                    mouseDownOnElement = false;
                                                });
                                                
                                                // Handle mouseleave to reset flag if user drags away
                                                suggestionElement.addEventListener('mouseleave', () => {
                                                    if (mouseDownOnElement && isDevMode) {
                                                        console.log('🖱️ Mouse left suggestion during press');
                                                    }
                                                    mouseDownOnElement = false;
                                                });
                                                
                                                // Keep click handler as fallback for accessibility (keyboard, etc.)
                                                suggestionElement.addEventListener('click', async (e) => {
                                                    // Only handle click if mouseup didn't already handle it
                                                    if (!window.suggestionBeingClicked) {
                                                        if (isDevMode) console.log('🖱️ Click event fallback triggered');
                                                        await handleSuggestionSelection();
                                                    }
                                                });

                                                suggestionsContainer.appendChild(suggestionElement);
                                            }
                                        }
                                    } catch (error) {
                                        console.error('Error fetching suggestions:', error);
                                    }
                                }, 300);
                            });

                            // Function to replace clear icon with warning icon (moved to global scope)
                            if (typeof window.replaceClearIconWithWarning === 'undefined') {
                                window.replaceClearIconWithWarning = function(inputElement) {
                                    // Check if this input has a valid suggestion selected
                                    const hasValidSuggestion = window.cachedSelectedOption && 
                                                             Array.isArray(window.cachedSelectedOption) && 
                                                             window.cachedSelectedOption.length > 0 &&
                                                             window.cachedSelectedOption[0] && 
                                                             window.cachedSelectedOption[0].formatted_address &&
                                                             window.cachedSelectedOption[0].formatted_address !== '';
                                    
                                    // Don't show warning if a valid suggestion is selected AND the input value matches
                                    if (hasValidSuggestion) {
                                        const cachedValue = window.cachedSelectedOption[0].displayName || window.cachedSelectedOption[0].formatted_address || window.cachedSelectedOption[0].name || '';
                                        const currentValue = inputElement.value.trim();
                                        
                                        if (currentValue === cachedValue) {
                                            return;
                                        }
                                    }
                                    
                                    const clearIcon = inputElement.parentElement.querySelector('.clear_content.large, .clear_content.medium, .clear_content');
                                    if (clearIcon) {
                                        // Store original icon class and container class
                                        const originalIconClass = clearIcon.querySelector('i').className;
                                        const originalContainerClass = clearIcon.className;
                                        
                                        // Replace icon class but preserve the container class (large/medium)
                                        clearIcon.querySelector('i').className = 'fa fa-exclamation-circle';
                                        
                                        // Add clicked class for tooltip
                                        clearIcon.classList.add('clicked');
                                        
                                        // Show tooltip with error message
                                        $(clearIcon).popover({
                                            content: `Please select a location from the suggestions dropdown to continue.`,
                                            container: 'body',
                                            placement: 'top',
                                            trigger: 'manual'
                                        });
                                        $(clearIcon).popover('show');
                                        warningMessageWasTriggered = true;
                                        
                                        // Restore original icon after 3 seconds
                                        const warningTimeoutId = setTimeout(() => {
                                            if (clearIcon.querySelector('i').className.includes('fa-exclamation-circle')) {
                                                clearIcon.querySelector('i').className = originalIconClass;
                                                clearIcon.className = originalContainerClass;
                                                
                                                $(clearIcon).popover('hide');
                                                $(clearIcon).popover('destroy');
                                                clearIcon.classList.remove('clicked');
                                                warningMessageWasTriggered = false;
                                            }
                                        }, 3000);
                                        
                                        // Store the timeout ID on the icon element for potential cancellation
                                        clearIcon.dataset.warningTimeoutId = warningTimeoutId;
                                    }
                                };
                            }
                            
                            // Handle focus/blur
                            input.addEventListener('focus', () => {
                                // Clear any existing tooltips when user focuses into the field
                                const clearIcon = input.parentElement.querySelector('.clear_content.large, .clear_content.medium, .clear_content');
                                if (clearIcon) {
                                    // Clear any pending warning timeout
                                    if (clearIcon.dataset.warningTimeoutId) {
                                        clearTimeout(parseInt(clearIcon.dataset.warningTimeoutId));
                                        delete clearIcon.dataset.warningTimeoutId;
                                    }
                                    
                                    $(clearIcon).popover('hide');
                                    $(clearIcon).popover('destroy');
                                    clearIcon.classList.remove('clicked');
                                    
                                    // Restore original icon if it was changed
                                    const iconElement = clearIcon.querySelector('i');
                                    if (iconElement && iconElement.className.includes('fa-exclamation-circle')) {
                                        iconElement.className = 'fa fa-times-circle';
                                    }
                                }
                                
                                if (input.value.trim().length >= 2) {
                                    updateContainerPosition();
                                    suggestionsContainer.style.display = 'block';
                                }
                            });
                            
                            // Handle blur event - when user leaves the field
                            input.addEventListener('blur', () => {
                                // Don't show warning if user is clicking a suggestion
                                if (window.suggestionBeingClicked) {
                                    return;
                                }
                                
                                // Store the value at blur start to detect if Google's autocomplete changes it
                                const valueAtBlurStart = input.value;
                                
                                // Check if there's a valid suggestion selected
                                const hasValidSuggestion = window.cachedSelectedOption && 
                                                         Array.isArray(window.cachedSelectedOption) && 
                                                         window.cachedSelectedOption.length > 0 &&
                                                         window.cachedSelectedOption[0] && 
                                                         window.cachedSelectedOption[0].formatted_address &&
                                                         window.cachedSelectedOption[0].formatted_address !== '';
                                
                                // Wait a bit to see if Google's autocomplete widget changes the value
                                setTimeout(() => {
                                    // Don't clear if a suggestion is being clicked
                                    if (window.suggestionBeingClicked) {
                                        return;
                                    }
                                    
                                    // Re-check if a suggestion was selected during the delay
                                    const currentHasValidSuggestion = window.cachedSelectedOption && 
                                                                     Array.isArray(window.cachedSelectedOption) && 
                                                                     window.cachedSelectedOption.length > 0 &&
                                                                     window.cachedSelectedOption[0] && 
                                                                     window.cachedSelectedOption[0].formatted_address &&
                                                                     window.cachedSelectedOption[0].formatted_address !== '';
                                    
                                    const valueAfterBlur = input.value;
                                    
                                    // If no valid suggestion was selected, prevent any auto-filled values
                                    if (!currentHasValidSuggestion) {
                                        // Check if the value changed (Google's autocomplete might have auto-filled)
                                        if (valueAfterBlur !== valueAtBlurStart) {
                                            // Restore the original value the user typed
                                            input.value = valueAtBlurStart;
                                        }
                                        
                                        // If the original value was just partial text (like "Lo"), clear it completely
                                        const preloaded_location_value = ``;
                                        const hasPreloadedValue = preloaded_location_value && 
                                                                 preloaded_location_value !== '' && 
                                                                 preloaded_location_value !== 'undefined';
                                        
                                        if ((!hasPreloadedValue || valueAtBlurStart !== preloaded_location_value) &&
                                            (valueAtBlurStart.length < 3 || (!valueAtBlurStart.includes(',') && !valueAtBlurStart.match(/\d/)))) {
                                            // Set a flag to prevent other scripts from setting values
                                            window.inputClearedByUser = true;
                                            window.inputClearedTimestamp = Date.now();
                                            window.clearedInputId = input.id;
                                            
                                            // Clear the input
                                            input.value = '';
                                            
                                            // Monitor and block any attempts to set a value for the next 2 seconds
                                            const blockValueChanges = () => {
                                                if (input.value && input.value.trim() !== '' && input.value !== valueAtBlurStart) {
                                                    input.value = '';
                                                }
                                            };
                                            
                                            // Check immediately and repeatedly
                                            blockValueChanges();
                                            setTimeout(blockValueChanges, 10);
                                            setTimeout(blockValueChanges, 50);
                                            setTimeout(blockValueChanges, 100);
                                            setTimeout(blockValueChanges, 200);
                                            setTimeout(blockValueChanges, 500);
                                            setTimeout(blockValueChanges, 1000);
                                            
                                            // Remove the flag after 2 seconds
                                            setTimeout(() => {
                                                window.inputClearedByUser = false;
                                                window.clearedInputId = null;
                                            }, 2000);
                                        }
                                    }
                                }, 200);
                                
                                // Check if we should show warning
                                const hasValue = input.value && input.value.trim().length > 0;
                                
                                // Check if there's preloaded data from URL parameters
                                const preloaded_place_id = ``;
                                const preloaded_location_value = ``;
                                const hasPreloadedData = (preloaded_place_id && preloaded_place_id !== '' && preloaded_place_id !== 'undefined') || 
                                                       (preloaded_location_value && preloaded_location_value !== '' && preloaded_location_value !== 'undefined');
                                
                                // Check if current input value matches preloaded data
                                const currentValue = input.value.trim();
                                const preloadedValueMatches = preloaded_location_value && 
                                                             preloaded_location_value !== '' && 
                                                             preloaded_location_value !== 'undefined' && 
                                                             currentValue === preloaded_location_value;
                                
                                // Hide suggestions container after a short delay to allow for clicks
                                setTimeout(() => {
                                    suggestionsContainer.style.display = 'none';
                                    suggestionsContainer.classList.remove('visible');
                                }, 150);
                                
                                // Show warning if:
                                // 1. Input has value AND
                                // 2. No valid suggestion AND (no preloaded data OR preloaded value doesn't match) AND
                                // 3. Values don't match (if there is a valid suggestion)
                                if (hasValue) {
                                    // If we have preloaded data AND the current value matches the preloaded value, don't show warning
                                    if (hasPreloadedData && preloadedValueMatches) {
                                        return;
                                    }
                                    
                                    if (!hasValidSuggestion) {
                                        // Add a small delay to allow for suggestion selection
                                        setTimeout(() => {
                                            const currentHasValidSuggestion = window.cachedSelectedOption && 
                                                                             Array.isArray(window.cachedSelectedOption) && 
                                                                             window.cachedSelectedOption.length > 0 &&
                                                                             window.cachedSelectedOption[0] && 
                                                                             window.cachedSelectedOption[0].formatted_address &&
                                                                             window.cachedSelectedOption[0].formatted_address !== '';
                                            
                                            if (!currentHasValidSuggestion && !window.suggestionBeingClicked) {
                                                window.replaceClearIconWithWarning(input);
                                            }
                                        }, 100);
                                    } else {
                                        // Check if values match
                                        const cachedValue = window.cachedSelectedOption[0].displayName || window.cachedSelectedOption[0].formatted_address || window.cachedSelectedOption[0].name || '';
                                        const currentValue = input.value.trim();
                                        
                                        if (currentValue !== cachedValue) {
                                            window.replaceClearIconWithWarning(input);
                                        }
                                    }
                                }
                            });

                            // Close suggestions when clicking outside
                            document.addEventListener('click', (e) => {
                                if (!input.contains(e.target) && !suggestionsContainer.contains(e.target)) {
                                    suggestionsContainer.style.display = 'none';
                                }
                            });

                            // Handle keyboard navigation
                            input.addEventListener('keydown', (e) => {
                                const pacItems = suggestionsContainer.querySelectorAll('.pac-item');
                                const selectedItem = suggestionsContainer.querySelector('.pac-item.selected');
                                let currentIndex = selectedItem ? Array.from(pacItems).indexOf(selectedItem) : -1;

                                // Prevent form submission when suggestions are visible
                                if (e.key === 'Enter' || e.keyCode === 13) {
                                    const visibleContainers = document.querySelectorAll('.pac-container');
                                    let visibleCount = 0;
                                    visibleContainers.forEach(container => {
                                        if (container.style.display !== 'none') {
                                            visibleCount++;
                                        }
                                    });
                                    if (visibleCount > 0) {
                                        e.preventDefault();
                                        if (selectedItem) {
                                            // Create and dispatch a click event on the selected item
                                            const clickEvent = new MouseEvent('click', {
                                                bubbles: true,
                                                cancelable: true,
                                                view: window
                                            });
                                            selectedItem.dispatchEvent(clickEvent);
                                            suggestionsContainer.style.display = 'none';
                                        }
                                        return;
                                    }
                                }

                                if (e.key === 'ArrowDown') {
                                    e.preventDefault();
                                    if (suggestionsContainer.style.display !== 'none' && pacItems.length > 0) {
                                        // Remove selection from current item
                                        if (selectedItem) {
                                            selectedItem.classList.remove('selected');
                                        }
                                        // Select next item or first item if at end
                                        currentIndex = (currentIndex + 1) % pacItems.length;
                                        pacItems[currentIndex].classList.add('selected');
                                    }
                                } else if (e.key === 'ArrowUp') {
                                    e.preventDefault();
                                    if (suggestionsContainer.style.display !== 'none' && pacItems.length > 0) {
                                        // Remove selection from current item
                                        if (selectedItem) {
                                            selectedItem.classList.remove('selected');
                                        }
                                        // Select previous item or last item if at start
                                        currentIndex = currentIndex <= 0 ? pacItems.length - 1 : currentIndex - 1;
                                        pacItems[currentIndex].classList.add('selected');
                                    }
                                } else if (e.key === 'Escape') {
                                    suggestionsContainer.style.display = 'none';
                                }
                            });

                            // Add styles for selected item
                            const selectedStyle = document.createElement('style');
                            selectedStyle.textContent = `
                                .pac-item.selected {
                                    background-color: #f5f5f5;
                                }
                                .pac-item {
                                    cursor: pointer;
                                }
                            `;
                            document.head.appendChild(selectedStyle);

                            // Initialize with a session token
                            refreshToken();

                            // Set initialization flags
                            input.setAttribute('data-autocomplete-initialized', 'true');
                            input.setAttribute('data-google-autocomplete-initialized', 'true');
                            input.setAttribute('data-pac-initialized', 'true');
                        } catch (error) {
                            console.error('Error initializing autocomplete:', error);
                            input.setAttribute('data-autocomplete-error', 'true');
                        }
                    });

                    placesInitialized = true;
                    

                    
                    // Trigger PAC banners after places are initialized
                   // console.log('Checking if triggerPacBanners function exists...');
                    if (typeof window.triggerPacBanners === 'function') {
                        window.triggerPacBanners();
                    } else {
                      //  console.log('triggerPacBanners function not found');
                    }

                } catch (error) {
                    console.error('Failed to initialize Places API:', error);
                    throw error;
                }
            }

            // Initialize Google Maps when needed
            async function initializeGoogleMaps() {
                try {
                    await loadGoogleMaps();
                    await initializeAutocomplete();
                } catch (error) {
                    console.error('Error in Google Maps initialization:', error);
                }
            }

            // Initialize event listeners once DOM is loaded
            document.addEventListener('DOMContentLoaded', () => {
                // Restore cached data from sessionStorage if it exists
                const cachedData = sessionStorage.getItem("google_result");
				
                if (cachedData) {
                    try {
                        const parsedData = JSON.parse(cachedData);
                        
                        // Reconstruct the geometry object with proper methods
                        if (parsedData[0] && parsedData[0].geometry) {
                            const lat = parsedData[0].geometry.location.lat;
                            const lng = parsedData[0].geometry.location.lng;
                            const sw = parsedData[0].geometry.viewport.sw;
                            const ne = parsedData[0].geometry.viewport.ne;
                            
                            parsedData[0].geometry = {
                                location: {
                                    lat: () => lat,
                                    lng: () => lng
                                },
                                viewport: {
                                    getSouthWest: () => ({
                                        lat: () => sw.lat,
                                        lng: () => sw.lng
                                    }),
                                    getNorthEast: () => ({
                                        lat: () => ne.lat,
                                        lng: () => ne.lng
                                    })
                                },
                                bounds: {
                                    getSouthWest: () => ({
                                        lat: () => sw.lat,
                                        lng: () => sw.lng
                                    }),
                                    getNorthEast: () => ({
                                        lat: () => ne.lat,
                                        lng: () => ne.lng
                                    })
                                }
                            };
                        }
                        
                        window.cachedSelectedOption = parsedData;
                        
                        // Update the input field with the cached location
                        const inputs = document.querySelectorAll('.googleSuggest, #location_google_maps_header, .google-writen-location, input[name="lead_location"], .fill_location');
                        inputs.forEach(input => {
                            if (parsedData[0] && parsedData[0].name) {
                                input.value = parsedData[0].name;
                            }
                        });
                    } catch (error) {
                        console.error('Error restoring cached data:', error);
                    }
                }

                const inputs = document.querySelectorAll('.googleSuggest, #location_google_maps_header, .google-writen-location, input[name="lead_location"], .fill_location');
                
                inputs.forEach(input => {
                    if (input.getAttribute('data-listeners-initialized')) {
                        return;
                    }
                    /** 
                     * 
                     * <div class="views pull-right ">
                    <i class="fa fa-th-list activeView listView"></i>
                            <i class="fa fa-th js-click gridView hidden-xs"></i>
                            <i class="fa fa-map-marker mapView" style="display: inline-block;"></i>
            </div>
                    */
					
                    // Initialize immediately for the header location input
					input.addEventListener('focus', initializeGoogleMaps, { once: true });
                    // Add input change handler to clear cache when input is manually changed
                    let lastValue = input.value;
                    input.addEventListener('input', () => {
                        if (input.value !== lastValue) {
                            lastValue = input.value;
                            
                            // Clear cached selection when user types new text
                            if (window.cachedSelectedOption && window.cachedSelectedOption[0]) {
                                const currentValue = window.cachedSelectedOption[0].formatted_address || window.cachedSelectedOption[0].name || '';
                                
                                if (input.value !== currentValue) {
                                    window.cachedSelectedOption = null;
                                    sessionStorage.removeItem("google_result");
                                }
                            }
                            
                            if (!input.value.trim()) {
                                window.cachedSelectedOption = null;
                                sessionStorage.removeItem("google_result");
                            }
                        }
                    });

                    input.setAttribute('data-listeners-initialized', 'true');
                });
                // Add form submission handler
                $('.website-search').submit(function (e) {
                    if (window.isSubmittingMainSearch) {
                        e.preventDefault();
                        return false;
                    }

                    var currentForm = $(this);
                    var locationInput = $(this).find(".googleLocation");
                    cachedSelectedOption = window.cachedSelectedOption;

                    var $submitButton = currentForm.find('input[type=submit], button[type=submit]');
                    

                    if (locationInput.val() != "" && typeof locationInput.val() != 'undefined') {
                        // Check if a valid suggestion was selected
                        const hasValidSuggestion = window.cachedSelectedOption && 
                                                 Array.isArray(window.cachedSelectedOption) && 
                                                 window.cachedSelectedOption.length > 0 &&
                                                 window.cachedSelectedOption[0] && 
                                                 window.cachedSelectedOption[0].formatted_address &&
                                                 window.cachedSelectedOption[0].formatted_address !== '';
                        
                        // Check if there's preloaded data from URL parameters
                        const preloaded_place_id = ``;
                        const preloaded_location_value = ``;
                        const hasPreloadedData = (preloaded_place_id && preloaded_place_id !== '' && preloaded_place_id !== 'undefined') || 
                                               (preloaded_location_value && preloaded_location_value !== '' && preloaded_location_value !== 'undefined');
                        
                        // Check if current input value matches preloaded data
                        const currentInputValue = locationInput.val().trim();
                        const preloadedValueMatches = preloaded_location_value && 
                                                     preloaded_location_value !== '' && 
                                                     preloaded_location_value !== 'undefined' && 
                                                     currentInputValue === preloaded_location_value;
                        
                        if (isDevMode) {
                            console.log('Location input value:', currentInputValue);
                            console.log('Preloaded location value:', preloaded_location_value);
                            console.log('Preloaded value matches current input:', preloadedValueMatches);
                        }
                        
                        if (!hasValidSuggestion && !(hasPreloadedData && preloadedValueMatches)) {
                            if (isDevMode) {
                                console.log('❌ No valid suggestion selected and preloaded data does not match current input - preventing form submission');
                                console.log('cachedSelectedOption:', window.cachedSelectedOption);
                                console.log('hasPreloadedData:', hasPreloadedData);
                                console.log('preloadedValueMatches:', preloadedValueMatches);
                            }
                            
                            // Show warning icon and prevent submission
                            const inputElement = locationInput[0];
                            if (inputElement && typeof window.replaceClearIconWithWarning === 'function') {
                                window.replaceClearIconWithWarning(inputElement);
                            }
                            
                            e.preventDefault();
                            return false;
                        }
                        
                        if (hasPreloadedData && preloadedValueMatches) {
                            if (isDevMode) console.log('✅ Preloaded data matches current input - allowing form submission');
                        }
                        
                        // Check if warning message was triggered
                        if (warningMessageWasTriggered) {
                            if (isDevMode) console.log('❌ Warning message was triggered - preventing form submission');
                            e.preventDefault();
                            return false;
                        }
                        
                        if (isDevMode) console.log('✅ Valid suggestion selected - allowing form submission');
                        
                        // Disable submit button immediately
                        window.isSubmittingMainSearch = true;
                        $submitButton.prop('disabled', true);
                        
                        e.preventDefault();
                        var form = currentForm;
                        var urlGET = form.serialize();
                        var formActionUrl = form.attr("action");
                        var locationValue = locationInput.val();
                        var place_id_in_url = ``;
                        var location_value_in_url = ``;
                        const mainCountry = '';
                        var inputOptions  = {};
                        var placeIdFound = false;
                        
                        // Prioritize selected suggestion over preloaded data
                        if(cachedSelectedOption && cachedSelectedOption[0] && cachedSelectedOption[0].formatted_address && cachedSelectedOption[0].formatted_address != ''){
                            if (isDevMode) console.log('???? Using selected suggestion for geocoding:', cachedSelectedOption[0].formatted_address);
                            inputOptions = {
                                address:cachedSelectedOption[0].formatted_address
                            }
                        }else if (place_id_in_url != '' && place_id_in_url != 'undefined' && place_id_in_url != null){
                            if (isDevMode) console.log('???? Using preloaded place_id for geocoding:', place_id_in_url);
                            inputOptions = {
                                placeId:place_id_in_url
                            }
                            placeIdFound = true;
                        }else{
                            if (isDevMode) console.log('???? Using current input value for geocoding:', locationValue);
                            inputOptions = {
                                address:locationValue
                            }
                        }

                        const language = "en";

                        if (language) {
                            inputOptions.language = language;
                        }
                        if (mainCountry && placeIdFound == false) {
                            inputOptions.componentRestrictions = {country: mainCountry};
                            inputOptions.region = mainCountry;
                        }

                        if (typeof cachedSelectedOption == 'undefined' || !cachedSelectedOption || typeof cachedSelectedOption[0] == 'undefined') {
                            cachedSelectedOption = [{
                                'formatted_address': ''
                            }];
                        }

                        if (isDevMode) {
                            console.log(inputOptions);
                            console.log('cachedSelectedOption',cachedSelectedOption);
                        }

                        if (isDevMode) {
                            console.log('locationValue',locationValue);
                            if (cachedSelectedOption && cachedSelectedOption[0]) {
                                console.log('cachedSelectedOption[0][formatted_address]',cachedSelectedOption[0]['formatted_address']);
                            } else {
                                console.log('cachedSelectedOption[0][formatted_address]', 'null or undefined');
                            }
                        }
                        geocoder = new google.maps.Geocoder();
                        geocoder.geocode(inputOptions, function (results, status) {
                            if (status == google.maps.GeocoderStatus.OK) {
                                if(isDevMode){
                                    console.log('geocode result with formatted_address:',results[0].formatted_address);
                                    console.log('original geocode result',results[0]);
                                }

                                // Prioritize selected suggestion over preloaded data for formatted_address
                                if(cachedSelectedOption && cachedSelectedOption[0] && cachedSelectedOption[0]['suggestion_address'] != '' && cachedSelectedOption[0]['suggestion_address'] != 'undefined' && cachedSelectedOption[0]['suggestion_address'] != null){
                                    if (isDevMode) console.log('???? Using selected suggestion address:', cachedSelectedOption[0]['suggestion_address']);
                                    results[0].formatted_address = cachedSelectedOption[0]['suggestion_address'];
                                }else if(location_value_in_url != '' && location_value_in_url != 'undefined' && location_value_in_url != null){
                                    if (isDevMode) console.log('???? Using preloaded location value:', location_value_in_url);
                                    results[0].formatted_address = location_value_in_url;
                                }

                                if(cachedSelectedOption && cachedSelectedOption[0] && cachedSelectedOption[0]['geometry']){
                                    results[0].geometry = cachedSelectedOption[0]['geometry'];
                                }

                                if(cachedSelectedOption && cachedSelectedOption[0] && cachedSelectedOption[0]['types']){
                                    results[0].types = cachedSelectedOption[0]['types'];
                                }

                                parseInfoToSearch(results, urlGET, formActionUrl);
                            } else {
                                var urlPath = formActionUrl;
                                var redirect = urlPath + "?" + urlGET;
                                window.location.href = redirect;
                            }
                        });
                        
                    }
                });

                // Add click handlers for submit buttons
                $('.website-search [type=submit]').click(async function (e) {
                    e.preventDefault();
                    var nativeForm = $(this).closest('form')[0];
                    if (nativeForm && typeof nativeForm.reportValidity === 'function' && !nativeForm.reportValidity()) {
                        return false;
                    }
                    await initializeGoogleMaps();
                    $(this).closest('form').submit();
                });

                // Auto-detect location on page load if settings are enabled
                var geocodeVisitorsSetting = '0';
                var geocodingMethod = 'HTML5';
                if (geocodeVisitorsSetting == 1 && (geocodingMethod === "HTML5" || geocodingMethod === "IP") && $('.googleSuggest').length > 0 && $('.googleSuggest').val() == '') {
                    initializeGoogleMaps().then(function() {
                        populateSearchFields();
                    });
                }
            });

            function parseInfoToSearch(results, urlGET, formActionUrl) {
                var parameters = {};
                
                if (!results || !results.length) {
                    return;
                }

                const result = results[0];
               // console.log('geocode result',result);

                let remainingComponents = [...(result.address_components || [])];
                
                // Find components in hierarchical order and remove them from the search pool
                const countryComponent = remainingComponents.find(comp => comp.types.includes('country'));
                if (countryComponent) {
                    remainingComponents = remainingComponents.filter(comp => comp !== countryComponent);
                }

                const stateComponent = remainingComponents.find(comp => comp.types.includes('administrative_area_level_1'));
                if (stateComponent) {
                    remainingComponents = remainingComponents.filter(comp => comp !== stateComponent);
                }

                const countyComponent = remainingComponents.find(comp => comp.types.includes('administrative_area_level_2'));
                if (countyComponent) {
                    remainingComponents = remainingComponents.filter(comp => comp !== countyComponent);
                }

                const cityComponent = remainingComponents.find(comp => {
                    if (!comp.types.some(type => cityTypes.includes(type))) {
                        return false;
                    }
                    /* CT counties come back as colloquial_area — never match them as the city. */
                    if (comp.types.includes('colloquial_area')
                        && window.bdIsColloquialCounty(comp.long_name, result.place_id)) {
                        return false;
                    }
                    return true;
                });
                if (cityComponent) {
                    remainingComponents = remainingComponents.filter(comp => comp !== cityComponent);
                }

                // Match ONLY true postal-code types. postalTypes also contains
                // street_number/route/premise (used for city detection), which on
                // a premise result captured the street number as the ZIP.
                const postalComponent = remainingComponents.find(comp => comp.types.some(type => ['postal_code', 'postal_code_prefix'].includes(type)));
                if (postalComponent) {
                    remainingComponents = remainingComponents.filter(comp => comp !== postalComponent);
                }

                // Set location value using the formatted address but remove USA
                if (result.formatted_address) {
                    const addressParts = result.formatted_address.split(',').map(part => part.trim());
                    // Remove USA from the end if present
                    if (addressParts[addressParts.length - 1].trim() === 'USA') {
                        addressParts.pop();
                    }
                    parameters.location_value = addressParts.join(', ');
                } else if (result.name) {
                    parameters.location_value = result.name;
                }

                // Set address components.
                // Preserve the (cityComponent || postalComponent) guard so postal-only
                // geocodes still trigger downstream city handling, but only assign
                // long_name when cityComponent is actually defined — filtering out
                // CT colloquial counties (above) makes cityComponent undefined more
                // often, and the previous unconditional .long_name access would throw.
                if (cityComponent || postalComponent) {
                    if (cityComponent) {
                        parameters.city = cityComponent.long_name;
                    }
                }
                if (countyComponent) {
                    // Remove the extra "County" word
                    parameters.county_sn = countyComponent.long_name;
                    if (parameters.county_sn.endsWith('County County')) {
                        parameters.county_sn = parameters.county_sn.replace('County County', 'County');
                    }
                }
                if (stateComponent) {
                    parameters.adm_lvl_1_sn = stateComponent.short_name;
                    parameters.stateSearchLN = stateComponent.long_name;
                    parameters.stateSearch = stateComponent.short_name;
                }
                if (countryComponent) {
                    parameters.country_sn = countryComponent.short_name;
                }
                if (postalComponent) {
                    parameters.postal_code = postalComponent.long_name;
                }

                // Improved location type handling
                const types = result.types || [];

                // Map Google Places types to our location types
                const typeMapping = {
                    'route': 'route',
                    'street_address': 'street_address',
                    'premise': 'premise',
                    'locality': 'locality',
                    'postal_code': 'postal_code',
                    'administrative_area_level_2': 'administrative_area_level_2',
                    'administrative_area_level_1': 'administrative_area_level_1',
                    'country': 'country',
                    'colloquial_area': 'locality',
                    'sublocality': 'locality',
                    'sublocality_level_1': 'locality',
                    'sublocality_level_2': 'locality',
                    'sublocality_level_3': 'locality',
                    'sublocality_level_4': 'locality',
                    'sublocality_level_5': 'locality',
                    'neighborhood': 'locality',
                    'political': 'locality',
                    'postal_town': 'locality',
                    'natural_feature': 'natural_feature',
                    'point_of_interest': 'point_of_interest',
                    'establishment': 'establishment',
                    'intersection': 'intersection',
                    'park': 'park',
                    'ward': 'locality'
                };

                // Find the first matching type
                parameters.location_type = null;
                for (const type of types) {
                    if (typeMapping[type]) {
                        parameters.location_type = typeMapping[type];
                        break;
                    }
                }

                // If no matching type found, use a default
                if (!parameters.location_type) {
                    parameters.location_type = 'locality';
                }

                // When searching by city/locality, omit postal_code — Google returns
                // a partial zip prefix that doesn't match all members in the city
                if (parameters.location_type == 'locality' && parameters.postal_code) {
                    delete parameters.postal_code;
                }

                // Set formatted address without USA
                if (result.formatted_address) {
                    parameters.faddress = result.formatted_address.split(',').map(part => part.trim()).filter(part => part !== 'USA').join(', ');
                } else {
                    parameters.faddress = parameters.location_value;
                }

                // Handle geometry and bounds
                if (result.geometry) {
                    const location = result.geometry.location;
                    const viewport = result.geometry.viewport;

                    if (location) {
                        parameters.lat = typeof location.lat === 'function' ? location.lat() : location.lat;
                        parameters.lng = typeof location.lng === 'function' ? location.lng() : location.lng;
                    }

                    if (viewport) {
                        const sw = typeof viewport.getSouthWest === 'function' ? viewport.getSouthWest() : viewport.sw;
                        const ne = typeof viewport.getNorthEast === 'function' ? viewport.getNorthEast() : viewport.ne;

                        parameters.swlat = typeof sw.lat === 'function' ? sw.lat() : sw.lat;
                        parameters.nelat = typeof ne.lat === 'function' ? ne.lat() : ne.lat;
                        parameters.swlng = typeof sw.lng === 'function' ? sw.lng() : sw.lng;
                        parameters.nelng = typeof ne.lng === 'function' ? ne.lng() : ne.lng;
                    }
                }

                parameters.place_id = result.place_id;

                // Parse urlGET into a URLSearchParams object
                const mergedParams = new URLSearchParams(urlGET);

                // Add/override with new parameters
                Object.entries(parameters).forEach(([key, value]) => {
                    if (value !== undefined && value !== null && value !== '') {
                        mergedParams.set(key, value); // set() will override if already present
                    }
                });

                // Get the final URL
                const finalUrl = formActionUrl + "?" + mergedParams.toString();
                window.location.href = finalUrl;
            }

            async function populateSearchFields(){
                var prePopulateLocationSetting = '0';
                var geolocationMethod = 'HTML5';

                // If coordinates are 0, try to get from sessionStorage
                if (vlat === 0 || vlon === 0) {
                    getCoordinatesFromSession();
                }

                if (typeof google != 'undefined' && prePopulateLocationSetting == 1 && (geolocationMethod === "HTML5" || geolocationMethod === "IP") && (vlat !== '' && vlon !== '' && vlat != undefined && vlon != undefined && vlat != 0 && vlon != 0)) {
                    const visitorLatLng = new google.maps.LatLng(parseFloat(vlat), parseFloat(vlon));
                    const geocoder = new google.maps.Geocoder();
                    
                    try {
                        const results = await geocoder.geocode({ location: visitorLatLng });
                        
                        if (results.results && results.results[0]) {
                            const formattedAddress = [];
                            window.cachedSelectedOption = results.results;
                            const preFormattedStructure = {
                                "locality": "long_name",
                                "administrative_area_level_2": "long_name",
                                "administrative_area_level_1": "long_name",
                                "country": "long_name"
                            };

                            Object.entries(preFormattedStructure).forEach(([type, nameType]) => {
                                const component = results.results[0].address_components.find(comp => comp.types[0] === type);
                                if (component) {
                                    formattedAddress.push(component[nameType]);
                                }
                            });

                            $('.googleSuggest').each(function () {
                                if ($(this).val() == '') {
                                    if (formattedAddress.length > 0) {
                                        $(this).val(formattedAddress.join(', '));
                                        clearContent($(this));
                                    }
                                }
                            });
                        }
                    } catch (error) {
                        $('.googleSuggest').each(function () {
                            $(this).val('');
                        });
                    }
                }
            }

            function showError(error) {
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        $('.fill_location.clicked').popover({
                            content: `Your local browser settings have prevented location targeting. Please enable location permissions in your browser settings.`,
                            container: 'body'
                        });
                        $('.fill_location.clicked').popover('toggle');
                        setTimeout(function () {
                            $('.fill_location.clicked').popover('hide');
                            $('.fill_location.clicked').removeClass('clicked');
                        }, 2000);
                        break;
                    case error.POSITION_UNAVAILABLE:
                        console.log("Location information is unavailable.");
                        break;
                    case error.TIMEOUT:
                        console.log("The request to get user location timed out.");
                        break;
                    case error.UNKNOWN_ERROR:
                        console.log("An unknown error occurred.");
                        break;
                }
            }

            if (navigator.geolocation) {
                if ($(".googleSuggest")[0]) {
                    $(document).on('click', '.fill_location', function getCXPosition() {
                        // Prevent multiple simultaneous geolocation requests
                        if (isGettingLocation) {
                            return;
                        }
                        
                        var $button = $(this);
                        $button.addClass('clicked');
                        var startPos;
                        
                        // Set flag to prevent concurrent requests
                        isGettingLocation = true;
                        
                        // Function to actually get the position
                        var attemptGetPosition = function() {
                            // Try with shorter timeout first for faster response
                            var geoOptions = {
                                enableHighAccuracy: false, // Use false for faster response
                                timeout: 8000, // 8 second timeout (reduced for faster failure)
                                maximumAge: 300000 // Accept cached position up to 5 minutes old
                            };
                            
                            navigator.geolocation.getCurrentPosition(function (position) {
                            startPos = position;
                            vlat = startPos.coords.latitude;
                            vlon = startPos.coords.longitude;
                            
                            // Validate coordinates before proceeding
                            if (!vlat || !vlon || vlat === 0 || vlon === 0) {
                                isGettingLocation = false;
                                $button.removeClass('clicked');
                                return;
                            }
                            
                            // Save coordinates to sessionStorage
                            saveCoordinatesToSession(vlat, vlon);
                            
                            $.get("/api/data/html/get/data_widgets/widget_name", {
                                "vlat": vlat,
                                "vlon": vlon,
                                "name": "Website - Save Coordinates Session"
                            });
                            (async function () {
                                await initializeGoogleMaps();
                                populateSearchFields();
                                isGettingLocation = false;
                                $button.removeClass('clicked');
                            })();
                        }, function(error) {
                            // Clear flag on error
                            isGettingLocation = false;
                            $button.removeClass('clicked');
                            
                            // For timeout errors, try sessionStorage as fallback
                            if (error.code === 3) {
                                if (getCoordinatesFromSession()) {
                                    // Use cached coordinates
                                    $.get("/api/data/html/get/data_widgets/widget_name", {
                                        "vlat": vlat,
                                        "vlon": vlon,
                                        "name": "Website - Save Coordinates Session"
                                    });
                                    (async function () {
                                        await initializeGoogleMaps();
                                        populateSearchFields();
                                        isGettingLocation = false;
                                        $button.removeClass('clicked');
                                    })();
                                } else {
                                    $button.popover({
                                        content: `Location request timed out. Please ensure location services are enabled and grant permission when prompted.`,
                                        container: 'body'
                                    });
                                    $button.popover('show');
                                    setTimeout(function() {
                                        $button.popover('hide');
                                    }, 5000);
                                }
                            } else {
                                showError(error);
                            }
                        }, geoOptions);
                        };
                        
                        // Check if geolocation permission is already denied (but don't block if it's prompt)
                        if (navigator.permissions && navigator.permissions.query) {
                            navigator.permissions.query({name: 'geolocation'}).then(function(result) {
                                if (result.state === 'denied') {
                                    isGettingLocation = false;
                                    $button.removeClass('clicked');
                                    showError({code: 1, message: 'Permission denied'});
                                    return;
                                } else {
                                    // Permission is granted or prompt - proceed with geolocation
                                    attemptGetPosition();
                                }
                            }).catch(function(err) {
                                // If permission API not supported, proceed anyway
                                attemptGetPosition();
                            });
                        } else {
                            // Permission API not available, proceed with geolocation
                            attemptGetPosition();
                        }
                    })
                }
            } else {
                console.log('Geolocation is not supported for this Browser/OS version yet.');
            }

            function getUrlParameter(sParam) {
                var sPageURL = window.location.search.substring(1);
                var sURLVariables = sPageURL.split('&');

                for (var i = 0; i < sURLVariables.length; i++) {
                    var sParameterName = sURLVariables[i].split('=');

                    if (sParameterName[0] == sParam) {
                        return decodeURIComponent(sParameterName[1]);
                    }
                }
            }
        </script>
            <script>
        window.addEventListener('load', (event) => {
            setTimeout(() => {
                    }, 501);
        });
    </script>
<script>
	function decision(message, url) {
		if (confirm(message)) {
			setTimeout(function () {
				window.location = url;
			}, 0);
		}
	}
</script>
<script>
	// Function to add alt, width, and height attributes to <img> elements without them
	function addAttributesToImages() {
		var images = document.querySelectorAll('img:not([alt]), img:not([width]), img:not([height])');
		Array.prototype.forEach.call(images, function(img) {
			// Skip if we've already processed this image
			if (img.dataset.processed === 'true') {
				return;
			}
			
			// Mark this image as being processed
			img.dataset.processed = 'true';
			
			// Add alt attribute if missing
			if (!img.hasAttribute('alt')) {
				var src = img.getAttribute('src') || 'image';  // Default src to 'image' if missing
				var altText = src.split('/').pop().split('?')[0].replace(/\.\w+$/, '');

				try {
					altText = decodeURIComponent(altText)
					.replace(/[_\-+,.:;]+/g, ' ')
					.replace(/\s+/g, ' ')
					.trim();
				} catch (e) {
					altText = 'image';  // Fallback to 'image' if decoding fails
				}

				// Ensure altText is not empty, otherwise use 'image'
				altText = altText || 'image';

				img.setAttribute('alt', altText);
			}

			// Add width and height attributes if missing
			if (!img.hasAttribute('width') || !img.hasAttribute('height')) {
				// Handle SVG differently
				if (img.src && img.src.endsWith('.svg')) {
					// For SVG, use the viewBox to set width and height, if available
					fetch(img.src)
					.then(response => {
						if (!response.ok) {
							throw new Error('Failed to fetch SVG: ' + response.status);
						}
						return response.text();
					})
					.then(svgText => {
						var parser = new DOMParser();
						var svgDoc = parser.parseFromString(svgText, "image/svg+xml");
						var svgElement = svgDoc.querySelector('svg');
						
						if (svgElement) {
							var viewBox = svgElement.getAttribute('viewBox');
							if (viewBox) {
								var viewBoxValues = viewBox.split(' ');
								var width = viewBoxValues[2];
								var height = viewBoxValues[3];

								if (!img.hasAttribute('width')) {
									img.setAttribute('width', width);
								}
								if (!img.hasAttribute('height')) {
									img.setAttribute('height', height);
								}
							}
						}
					})
					.catch(error => {
						// Fallback to default dimensions for SVG
						if (!img.hasAttribute('width')) {
							img.setAttribute('width', '100');
						}
						if (!img.hasAttribute('height')) {
							img.setAttribute('height', '100');
						}
					});
				} else {
					// For non-SVG images, use natural dimensions
					var tempImg = new Image();
					tempImg.src = img.src;
					
					tempImg.onload = function() {
						if (!img.hasAttribute('width')) {
							img.setAttribute('width', tempImg.naturalWidth);
						}
						if (!img.hasAttribute('height')) {
							img.setAttribute('height', tempImg.naturalHeight);
						}
					};
					
					tempImg.onerror = function() {
						// Fallback to default dimensions
						if (!img.hasAttribute('width')) {
							img.setAttribute('width', '100');
						}
						if (!img.hasAttribute('height')) {
							img.setAttribute('height', '100');
						}
					};
				}
			}
		});
	}

	document.addEventListener('DOMContentLoaded', function() {
		// Run the function initially to catch images already in the DOM
		addAttributesToImages();

		// Create a MutationObserver to monitor the DOM for added/changed images
		var observer = new MutationObserver(function(mutations) {
			mutations.forEach(function(mutation) {
				if (mutation.addedNodes.length > 0 || mutation.type === 'attributes') {
					// Only process if we have new images or src attribute changes
					var hasNewImages = false;
					
					if (mutation.addedNodes.length > 0) {
						mutation.addedNodes.forEach(function(node) {
							if (node.nodeType === 1) { // Element node
								if (node.tagName === 'IMG' || node.querySelectorAll) {
									hasNewImages = true;
								}
							}
						});
					}
					
					if (mutation.type === 'attributes' && mutation.attributeName === 'src') {
						hasNewImages = true;
					}
					
					if (hasNewImages) {
						addAttributesToImages();
					}
				}
			});
		});

		// Start observing the document body for changes
		observer.observe(document.body, {
			childList: true, // Watch for added or removed nodes
			subtree: true, // Watch the entire subtree
			attributes: true, // Watch for attribute changes
			attributeFilter: ['src'] // Specifically watch for changes in the 'src' attribute
		});
	});
</script><style type='text/css'> select#sid[disabled], select#tid[disabled], select.combobox[disabled], select#bd-chained[disabled], select#category-chained[disabled], select.infinite-chained[disabled], select.subcategory-chained[disabled], select.search-chained[disabled], select#country-chained[disabled], select#state-chained[disabled], select#country-chained-2[disabled], select#state-chained-2[disabled], select#profession_id[disabled] {
    cursor: wait
}
select.select2-preload {
    line-height: initial;
}

select#sid, select#tid, select#ttid, select.combobox, select#bd-chained, select#category-chained, select.infinite-chained, select.subcategory-chained, select.search-chained, select#country-chained, select#state-chained, select#country-chained-2, select#state-chained-2, select#profession_id, [name^="bd_phone_country_code"] {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    background-image: url(/images/select2ArrowDown.png) !important;
    background-repeat: no-repeat !important;
    background-size: 10px 9px !important;
    background-position: 99% 16px;
    border-radius: 6px;
    overflow: hidden;
}
.module select#sid, .module select#tid, .module select.combobox, .module select#bd-chained, .module select#category-chained, .module select.infinite-chained, .module select.subcategory-chained, .module select.search-chained, .module select#country-chained, .module select#state-chained, .module select#country-chained-2, .module select#state-chained-2, .module select#profession_id, [name^="bd_phone_country_code"] {
    background-position: 98.2% 12px;
} </style><script>
    // Function to add aria-label to <select> elements without it, for better pagespeed accessibility score
    $(document).ready(function() {
        var ariaLabelCounter = {}; // Object to keep track of aria-label counts for uniqueness

        // Iterate over each select element that does not have an aria-label
        $('select:not([aria-label])').each(function() {
            // Use the ID or placeholder as the base for the aria-label, stripping HTML tags
            var baseLabel = this.id || $(this).attr('placeholder') || 'select';
            baseLabel = baseLabel.replace(/<[^>]*>/g, '').trim(); // Remove HTML tags and trim

            // Ensure uniqueness of each aria-label
            ariaLabelCounter[baseLabel] = (ariaLabelCounter[baseLabel] || 0) + 1;
            var ariaLabel = baseLabel + '-' + ariaLabelCounter[baseLabel];

            // Truncate aria-label to 100 characters
            ariaLabel = ariaLabel.length > 100 ? ariaLabel.substring(0, 100) : ariaLabel;

            // Set the aria-label attribute to the unique label
            $(this).attr('aria-label', ariaLabel);
        });
    });
</script>
<script type="application/ld+json">
{
    "@context": "https://schema.org",
    "@graph": [
        {
            "@type": "WebSite",
            "@id": "https://seo.diy/#website",
            "name": "SEO.diy",
            "url": "https://seo.diy/",
            "inLanguage": "en-US",
            "potentialAction": {
                "@type": "SearchAction",
                "target": "https://seo.diy/sitesearch?q={search_term_string}",
                "query-input": "required name=search_term_string",
                "name": "Search Directory: SEO.diy"
            },
            "publisher": {
                "@id": "https://seo.diy/#organization"
            }
        },
        {
            "@type": "Organization",
            "@id": "https://seo.diy/#organization",
            "name": "SEO.diy",
            "description": "SEO.diy – SEO – SEO",
            "url": "https://seo.diy/",
            "mainEntityOfPage": {
                "@type": "WebPage",
                "@id": "https://seo.diy/#webpage"
            },
            "contactPoint": [
                {
                    "@type": "ContactPoint",
                    "email": "team@f12.org",
                    "contactType": "customer support",
                    "availableLanguage": [
                        "en"
                    ],
                    "areaServed": "US"
                }
            ],
            "areaServed": {
                "@type": "Country",
                "name": "US"
            },
            "sameAs": [
                "https://www.facebook.com/SEO.diy",
                "https://x.com/_SEOdiy",
                "https://www.pinterest.com/seo",
                "https://www.linkedin.com/SEO-diy",
                "https://www.youtube.com/@SEO.diy",
                "https://www.instagram.com/SEO.diy",
                "https://www.tiktok.com/@seo",
                "https://wa.me/SEOdiy",
                "https://www.snapchat.com/add/SEOdiy"
            ],
            "logo": {
                "@type": "ImageObject",
                "@id": "https://seo.diy/#logo",
                "url": "https://seo.diy/images/SEO-DIY/SEO.diy.png"
            },
            "image": {
                "@type": "ImageObject",
                "@id": "https://seo.diy/#image",
                "url": "https://seo.diy/images/SEO-DIY/SEO.diy.png"
            },
            "keywords": [
                "SEO.diy",
                "SEO"
            ]
        }
    ]
}</script>

<script>
// Bootstrap Icons fallback loader - ensures Bootstrap Icons work even if HEAD widget is customized, do not delete
(function() {
    if (!document.querySelector('link[href*="bootstrap-icons"]')) {
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://www.optimizecdn.com/directory/cdn/assets/bootstrap/fonts/bootstrap-icons.min.css?v=1.13.1';
        document.head.appendChild(link);
    }
})();
</script>
<style type='text/css'> .input-group.normal-autosuggest input,.input-group.sm-autosuggest input, .input-group.md-autosuggest input {
	}
.normal-autosuggest .twitter-typeahead, .sm-autosuggest .twitter-typeahead, .md-autosuggest .twitter-typeahead, .large-autosuggest .twitter-typeahead {
	display: inline-block;
	height: 25px;
	position: relative;
	width: 100%;
}
.input-group.normal-autosuggest .twitter-typeahead, .input-group.sm-autosuggest .twitter-typeahead, .input-group.large-autosuggest .twitter-typeahead:not(.search_box .twitter-typeahead) {
	width: inherit;
}
.normal-autosuggest .twitter-typeahead .clear_content.medium{
	bottom: 0px;
}
.sm-autosuggest .twitter-typeahead .clear_content.small{
	bottom: -4px;
}
.md-autosuggest.input-group .twitter-typeahead .clear_content.medium  {
    bottom: -2px;
}
.md-autosuggest .twitter-typeahead {
	height: 32px;
}
.md-autosuggest .input-group-addon + .input_wrapper .twitter-typeahead {
	height: 38px;
	vertical-align: top;
}
.md-autosuggest-input + .clear_content.medium {
    bottom: 0px;
}
.large-autosuggest .twitter-typeahead {
	height: 40px;
}
.normal-autosuggest .twitter-typeahead{
	height: 38px;
}
.normal-autosuggest .twitter-typeahead .tt-hint, .sm-autosuggest .twitter-typeahead .tt-hint {
	background: #fff !important;
	border: 1px solid #ccc!important;
	border-radius: 0 8px 8px 0;
	box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset!important;
	color: transparent;
	left: 0;
	padding: 4px 11px;
	position: absolute;
	top: 0;
	width: 100%;
	font-size:12px;
}
.normal-autosuggest.input-group-addon .fa, .sm-autosuggest .input-group-addon .fa, .input-group-sm .input-group-addon .fa {font-size:12px}
.md-autosuggest .twitter-typeahead .tt-hint {
	height: 100%;
	background: #ffffff none repeat scroll 0 0 !important;
	border: 1px solid #cccccc !important;
	border-radius: 0 8px 8px 0;
	box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset !important;
	color: rgba(0, 0, 0, 0);
	left: 0;
	padding: 6px 11px;
	position: absolute;
	top: 0;
	width: 100%;
}
.large-autosuggest {background: #fff !important;border-radius:10px;}
.large-autosuggest input {width: 100%!important;box-shadow:none; border-radius: 10px;}
.large-autosuggest .twitter-typeahead .tt-hint {
	background: #fff !important;
	border: 1px solid #ccc!important;
	border-radius: 10px;
	box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset!important;
	color: transparent;
	left: 0;
	position: absolute;
	top: 0;
	width: 100%;
	font-size: 18px;
	height: 46px;
	line-height: 1.33333;
	padding: 10px 15px;
}	
.tt-dataset .empty-message {
	display: none !important;
}
.twitter-typeahead .tt-query {background-color:#fff!important}
.input-group.large-autosuggest span:first-child .tt-hint {border-radius: 0 !important;}
span.tt-dropdown-menu {
	border: 1px solid #FCFCFC;
	border-radius: 5px;
	box-shadow: 0 5px 10px rgba(0,0,0,.2);
	width: 100% !important;
}
.tt-is-under-cursor a.suggest-link {
	background: #55ACEE;
}

.tt-is-under-cursor .media-heading,
.tt-is-under-cursor .suggest-origin,
.tt-is-under-cursor .location{
	color:#fff!important;
}
.tt-suggestion .media .media-body .suggest-origin {
		color: rgba(45, 91, 137,0.9);
	padding: 1px 0;
	border-radius: 6px;
	font-weight: bold;
	line-height: 12px;
}
.tt-suggestion {
	background: #fff;
	border-bottom: 1px solid #eee;
	-webkit-transition: all 0.3s ease-in-out;
	-moz-transition: all 0.3s ease-in-out;
	-o-transition: all 0.3s ease-in-out;
	transition: all 0.3s ease-in-out;
}
body .tt-suggestions .media.br-bottom img {
	max-width: 45px;
	height: auto;
}
body .tt-suggestions .media-body span {
	font-size: 10px;
}
body .tt-suggestions .media-body h4 {
	font-size: 12px;
	margin: 2px 0px;
	text-transform: capitalize;
}
a.suggest-link {
	padding: 5px;
	display: block;
}
a.suggest-link img {
	border-radius: 100px;
	display: block;
	margin: 0 auto;
	height: 100%!important;
	width: 100%;
	object-fit: cover;
}
.left-suggest-col {
	display: inline-block;
	vertical-align: middle;
	width: 44px;
	height: 44px;
}
.right-suggest-col {
	display: inline-block;
	padding-left: 1%;
	text-align: left;
	vertical-align: middle;
	width: calc(100% - 1% - 50px);
}
p.media-heading {
	color: #333;
	font-size: 12px;
	font-weight: 600;
	margin-bottom: 0;
}
p.suggest-origin {
	font-size: 10px;
	color: #333;
	margin:0;
}
p.location {
	color: #333;
	font-size: 10px;
	margin: 2px 0;
}
body .tt-is-under-cursor a.suggest-link {
	background: #F7F7F7;
}
body .tt-is-under-cursor .media-heading, body .tt-is-under-cursor .suggest-origin, body .tt-is-under-cursor .location {
	color: #333!important;
}
a.suggest-link[data-heading="heading"] {
	 pointer-events: none;
  	cursor: default;
  	text-decoration: none;
}
body .tt-is-under-cursor a.suggest-link[data-heading="heading"] {
	background: rgb(255, 255, 255);
}
/* --- all the novalue css --- */
a.suggest-link .suggest-origin[data-state="novalue"] {
	display: none;
}
a.suggest-link .location[data-state="novalue"] {
	display: none;
}
a.suggest-link img[data-state="novalue"] {
	display: none;
}
a.suggest-link .suggest-origin[data-state="heading"] {
	display: none;
}
a.suggest-link .media-heading[data-heading="heading"] {
	color:rgb(0, 0, 0)!important;
	font-weight: bold;
	padding: 4px;
	font-size: 13px;
}
.left-suggest-col[data-photo="novalue"], .left-suggest-col[data-photo="undefined"] {
	display: none;
}
.right-suggest-col[data-photo="novalue"], .right-suggest-col[data-photo="undefined"] {
	width: 100%;
}
a.suggest-link[href="novalue"] {
	cursor: default !important;
	pointer-events: none;
}
a.suggest-link[data-heading="heading"] {
	background-color: rgb(255, 255, 255);
}
div.content-shell {
	overflow: inherit;
}
span.tt-dropdown-menu div {
	float: none;
}
.tt-menu {
	border-radius: 0 0 6px 6px;
	box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
	overflow: hidden;
	width: 100%;
	z-index: 150 !important;
}
.tt-menu .tt-dataset {
    overflow-y: auto;
    max-height: 200px;
} </style><script>
    window.addEventListener('load', () => {
        let embedlyClass = document.querySelector('.fr-embedly');
        if (typeof embedlyClass != "undefined" && embedlyClass != null) {
            let embedlyURI = "https://www.optimizecdn.com/directory/cdn/assets/bootstrap/js/embedly_widget.min.js";
            let head = document.getElementsByTagName("head")[0];
            let script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = embedlyURI;
            script.async = true;
            script.onload = function() {
                setTimeout(function() {
                    if (typeof embedly !== 'undefined' && embedly.card) {
                        document.querySelectorAll('.embedly-card').forEach(function(card) {
                            embedly.card(card);
                        });
                    }
                }, 500);
            };
            head.appendChild(script);
        }
    });
</script><script type="text/javascript" src="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/jquery.lazy/1.7.9/jquery.lazy.min.js"></script><script>
                            $(function () {
                                $(".lazyloader").Lazy({
                                    afterLoad: function(element) {
                                        $(".gridView.activeView").click();
                                    }
                                });
                                
                            });
                            $("button[class*='slick'],button[id*='slick']").click(function () {
                              $(this).parents(".row").find(".lazyloader").lazy({
                                    bind: "event",
                                    delay: 0
                                });
                            });
                            $("[class*='slick'],[id*='slick']").on("swipe",function(){
                              $(this).parents(".row").find(".lazyloader").lazy({
                                    bind: "event",
                                    delay: 0
                                });
                            });
                        </script><script defer src="https://www.optimizecdn.com/directory/cdn/assets/bootstrap/js/websiteScripts.min.js?v=8.0.0"></script>
            </body>
        </html>