
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, maximum-scale=1.0" />
    <meta name="format-detection" content="telephone=no" />
    <meta property="og:locale" content="en_US" />
    <meta property="og:type" content="website" />
        <meta property="og:title" content="Heartland Market - Riceville, IA" />
            <meta property="og:url" content="https://heartlandmarket.us/" />
                <meta property="og:image" content="https://du9m0k402rjmo.cloudfront.net/images/P_38699/db58983c-adbe-4666-95b3-3cb9d0d0e65f.jpg" />
            <meta property="og:description" content="Heartland Market, situated in Riceville, IA, serves as a premier discount grocery destination for residents of Mitchell and Howard counties. Dedicated to making grocery shopping more affordable, we offer a broad selection of products that include meats, cheeses, ice cream, and more. Additionally, we feature a variety of cosmetics, toys, and other overstock items from popular brands. Our innovative Heartland Market Mobile Unit allows us to conveniently extend our services across northeastern Iowa. Visit us today to explore our outstanding selection in Riceville or check our schedule to find out when we&#39;ll be in your neighborhood!" />
        <meta name="description" content="Heartland Market, situated in Riceville, IA, serves as a premier discount grocery destination for residents of Mitchell and Howard counties. Dedicated to making grocery shopping more affordable, we offer a broad selection of products that include meats, cheeses, ice cream, and more. Additionally, we feature a variety of cosmetics, toys, and other overstock items from popular brands. Our innovative Heartland Market Mobile Unit allows us to conveniently extend our services across northeastern Iowa. Visit us today to explore our outstanding selection in Riceville or check our schedule to find out when we&#39;ll be in your neighborhood!" />
            <meta name="title" content="Heartland Market - Riceville IA" />
            <meta name="keywords" content="Groceries,Ice Cream,Meat,Cheese,Discount,Gifts,Toys,Games" />
    <title>Heartland Market - Riceville, IA</title>
    <script src="/Scripts/Profile/googleAnalytics.js" type="text/javascript"></script>
    <script type="text/javascript" src="https://www.google.com/recaptcha/api.js" async defer></script>

    <script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
    
    <script>window.jQuery || document.write('<script src="/scripts/templates/jquery-3.5.0.min.js"><\/script>')</script>

    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    
    <script>if (typeof (Popper) === 'undefined') { document.write('<script src="/scripts/templates/popper.min.js"><\/script>') }</script>

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.min.js" integrity="sha384-mrcBkRTg0HmTfecoh1I+48Ptm7cAe18uN+3GsS5SXXGSwzpjIhJZkxEJ5jYaZmE" crossorigin="anonymous"></script>
    
    <script>if (typeof ($.fn.modal) === 'undefined') { document.write('<script src="/scripts/templates/bootstrap.min.js"><\/script>') }</script>

    <script src="/Scripts/Templates/googleMaps.js" type="text/javascript"></script>
    <link href="/Content/Templates/custom-bootstrap.css" type="text/css" rel="stylesheet" />
    <script src="/Scripts/bootbox.min.js" type="text/javascript"></script>
    <script src="/Scripts/Profile/jquery.barrating.1.1.4.js" type="text/javascript"></script>
    <script src="/Scripts/Templates/cleave.min.js" type="text/javascript"></script>
    <script src="/Scripts/Templates/cleave-phone.us.js" type="text/javascript"></script>
    <script src="/Scripts/Templates/slick.min.js" type="text/javascript"></script>
    <link href="/Content/Templates/slick.css" type="text/css" rel="stylesheet" />
    <link href="/Content/Templates/slick-theme.css" type="text/css" rel="stylesheet" />
    <script src="/Scripts/Templates/googleMapsMultiLocation.js" type="text/javascript"></script>
    <script src="https://www.google.com/recaptcha/api.js?render=6LcokacUAAAAAH_snk3O5bpdYwjpC5XAuXNLrJLH" type="text/javascript"></script>
    <script src="https://player.vimeo.com/api/player.js" type="text/javascript"></script>

    <link href="/Content/Templates/chatbot.css" type="text/css" rel="stylesheet" />

    <meta name="viewport" content="width=device-width, user-scalable=yes,initial-scale=1, maximum-scale=2" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    
    
    <link href="/Content/Templates/template_1.css" type="text/css" rel="stylesheet" />

        <link rel="canonical" href="https://heartlandmarket.us/">


<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "LocalBusiness",
      "@id": "https://heartlandmarket.us/#localbusiness",
      "name": "Heartland Market",
      "url": "https://heartlandmarket.us/",
      "description": "Heartland Market, situated in Riceville, IA, serves as a premier discount grocery destination for residents of Mitchell and Howard counties. Dedicated to making grocery shopping more affordable, we offer a broad selection of products that include meats, cheeses, ice cream, and more. Additionally, we feature a variety of cosmetics, toys, and other overstock items from popular brands. Our innovative Heartland Market Mobile Unit allows us to conveniently extend our services across northeastern Iowa. Visit us today to explore our outstanding selection in Riceville or check our schedule to find out when we'll be in your neighborhood!",
      "image": "https://du9m0k402rjmo.cloudfront.net/images/P_38699/db58983c-adbe-4666-95b3-3cb9d0d0e65f.jpg",
      "logo": "https://du9m0k402rjmo.cloudfront.net/images/P_38699/db58983c-adbe-4666-95b3-3cb9d0d0e65f.jpg",
      "address": {
        "@type": "PostalAddress",
        "streetAddress": "102 W Main St",
        "addressLocality": "Riceville",
        "addressRegion": "IA",
        "postalCode": "50466",
        "addressCountry": "US"
      },
      "telephone": "(641) 985-2834",
      "email": "heartlandmarketllc@gmail.com",
      "geo": {
        "@type": "GeoCoordinates",
        "latitude": 43.3640255,
        "longitude": -92.5544273
      },
      "openingHoursSpecification": [
        {
          "@type": "OpeningHoursSpecification",
          "dayOfWeek": "Monday",
          "opens": "09:00",
          "closes": "18:00"
        },
        {
          "@type": "OpeningHoursSpecification",
          "dayOfWeek": "Tuesday",
          "opens": "09:00",
          "closes": "18:00"
        },
        {
          "@type": "OpeningHoursSpecification",
          "dayOfWeek": "Wednesday",
          "opens": "09:00",
          "closes": "18:00"
        },
        {
          "@type": "OpeningHoursSpecification",
          "dayOfWeek": "Thursday",
          "opens": "09:00",
          "closes": "18:00"
        },
        {
          "@type": "OpeningHoursSpecification",
          "dayOfWeek": "Friday",
          "opens": "09:00",
          "closes": "18:00"
        },
        {
          "@type": "OpeningHoursSpecification",
          "dayOfWeek": "Saturday",
          "opens": "09:00",
          "closes": "17:00"
        }
      ],
      "paymentAccepted": "Visa, Discover, American Express, Food Stamps, EBT Food Only, Personal Checks, MasterCard",
      "sameAs": [
        "https://www.facebook.com/p/Heartland-Market-100086256219106/"
      ]
    },
    {
      "@type": "WebSite",
      "@id": "https://heartlandmarket.us/#website",
      "url": "https://heartlandmarket.us/",
      "name": "Heartland Market",
      "description": "Heartland Market, situated in Riceville, IA, serves as a premier discount grocery destination for residents of Mitchell and Howard counties. Dedicated to making grocery shopping more affordable, we offer a broad selection of products that include meats, cheeses, ice cream, and more. Additionally, we feature a variety of cosmetics, toys, and other overstock items from popular brands. Our innovative Heartland Market Mobile Unit allows us to conveniently extend our services across northeastern Iowa. Visit us today to explore our outstanding selection in Riceville or check our schedule to find out when we'll be in your neighborhood!",
      "potentialAction": {
        "@type": "SearchAction",
        "target": "https://heartlandmarket.us/?s={search_term_string}",
        "query-input": "required name=search_term_string"
      }
    },
    {
      "@type": "WebPage",
      "@id": "https://heartlandmarket.us/#webpage",
      "url": "https://heartlandmarket.us/",
      "name": "Heartland Market - Riceville, IA",
      "description": "Heartland Market, situated in Riceville, IA, serves as a premier discount grocery destination for residents of Mitchell and Howard counties. Dedicated to making grocery shopping more affordable, we offer a broad selection of products that include meats, cheeses, ice cream, and more. Additionally, we feature a variety of cosmetics, toys, and other overstock items from popular brands. Our innovative Heartland Market Mobile Unit allows us to conveniently extend our services across northeastern Iowa. Visit us today to explore our outstanding selection in Riceville or check our schedule to find out when we'll be in your neighborhood!",
      "isPartOf": {
        "@id": "https://heartlandmarket.us/#website"
      },
      "about": {
        "@id": "https://heartlandmarket.us/#localbusiness"
      },
      "primaryImageOfPage": {
        "@type": "ImageObject",
        "url": "https://du9m0k402rjmo.cloudfront.net/images/P_38699/db58983c-adbe-4666-95b3-3cb9d0d0e65f.jpg"
      },
      "breadcrumb": {
        "@type": "BreadcrumbList",
        "itemListElement": [
          {
            "@type": "ListItem",
            "position": 1,
            "name": "Home",
            "item": "https://heartlandmarket.us/"
          }
        ]
      }
    },
    {
      "@type": "Service",
      "@id": "https://heartlandmarket.us/#service",
      "name": "Our Services",
      "provider": {
        "@id": "https://heartlandmarket.us/#localbusiness"
      },
      "serviceType": [
        "At Heartland Market, we’re more than just a grocery store—we’re your neighbors, your friends, and your go-to destination for everyday essentials. We proudly offer a wide selection of fresh produce, quality meats, pantry staples, and locally sourced goods, all with the personalized service you’d expect from a hometown store. Whether you're picking up a quick dinner, stocking up for the week, or just stopping in for a friendly chat, our team is here to make your shopping experience easy, welcoming, and convenient. We’re committed to serving Riceville and the surrounding communities with heart, integrity, and a smile—because that’s what neighbors do.",
        "Our innovative Heartland Market Mobile Unit allows us to extend our reach across northeastern Iowa, bringing fresh food and essential items directly to surrounding communities. Whether you're shopping in-store or visiting our mobile unit, you’ll find the same friendly service, locally sourced products, and commitment to excellence that define who we are. We’re here to make your life easier—wherever you are."
      ],
      "description": "Professional services offered by Heartland Market"
    },
    {
      "@type": "FAQPage",
      "@id": "https://heartlandmarket.us/#faqpage",
      "url": "https://heartlandmarket.us/#faq",
      "name": "Frequently Asked Questions",
      "description": "Frequently asked questions about Heartland Market",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "Can I purchase groceries at your store?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Yes, we have a selection of groceries available for your everyday needs."
          }
        },
        {
          "@type": "Question",
          "name": "Do you offer over-the-counter medications?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "We provide a selection of OTC medications for general health needs."
          }
        },
        {
          "@type": "Question",
          "name": "Are games available for purchase?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Yes, we have a collection of games for entertainment and fun."
          }
        },
        {
          "@type": "Question",
          "name": "Where is your store located?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Our store, Heartland Market, is located at 102 W Main St, Riceville, IA 50466. We invite you to visit us for all your grocery and daily needs!"
          }
        },
        {
          "@type": "Question",
          "name": "What are your regular business hours?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Our store is open Monday through Friday from 9:00 AM to 6:00 PM and Saturday from 9:00 AM to 5:00 PM. Please call for holiday hours as they may vary."
          }
        }
      ]
    }
  ]
}
</script></head>
<body>
    <div id="bootstrapCssTest" class="d-none"></div>
    <script>
        $(function () {
            
            if ($('#bootstrapCssTest').is(':visible')) {
                $("head").prepend('<link rel="stylesheet" href="/content/templates/bootstrap.min.css">');
            }
        });
    </script>

    
<div class="container-fullwidth">
    


<nav class="bg-default-color navbar fixed-top navbar-light bg-light navbar-expand-md pt-1 pb-1">
    <div class="d-xs-block d-md-none">
        <div class="d-flex flex-wrap w-100">
                <div class="flex-column">
                    <a href="#home-section" class="navbar-brand ml-3" id="HomeNav">
                        <img src="https://du9m0k402rjmo.cloudfront.net/images/P_38699/db58983c-adbe-4666-95b3-3cb9d0d0e65f.jpg" alt="navbar logo" class="d-line-block align-top nav-logo" />
                    </a>
                </div>
                            <div class="flex-column align-self-center p-1">
                    <a id="PhoneNav" href="tel:6419852834" class="phone-nav-mobile">
                        <i class="fas fa-phone fa-inverse fa-xs fa-rotate-90"></i>
                        (641) 985-2834
                    </a>
                </div>
        </div>
    </div>

    <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarToggler" aria-controls="navbarToggler" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
        <span class="my-1 mx-2 close">X</span>
    </button>

    <div class="collapse navbar-collapse flex-column mx-auto" id="navbarToggler">
        
        <div class="d-none d-md-block nav-section">
            <ul class="navbar-nav mx-auto mt-2 mt-lg-0 flex-row align-items-center">
                    <li class="pl-lg-4 pr-lg-4">
                        <a href="#home-section" class="navbar-brand ml-2 mr-2" id="HomeNav">
                            <img src="https://du9m0k402rjmo.cloudfront.net/images/P_38699/db58983c-adbe-4666-95b3-3cb9d0d0e65f.jpg" alt="navbar logo" class="d-line-block align-top nav-logo" />
                        </a>
                    </li>
                                            <li class="nav-item text-center header-item mx-auto pl-lg-4 pr-lg-4">
                                <a id="HomeNav" class="nav-link" href="#home-section">Home</a>
                            </li>
                            <li class="nav-item text-center header-item mx-auto pl-lg-4 pr-lg-4">
                                <a id="AboutNav" class="nav-link" href="#about-section">About</a>
                            </li>
                            <li class="nav-item text-center header-item mx-auto pl-lg-4 pr-lg-4">
                                <a id="ServicesNav" class="nav-link" href="#services-section">Services</a>
                            </li>
                            <li class="nav-item text-center header-item mx-auto pl-lg-4 pr-lg-4">
                                <a id="PhotosNav" class="nav-link" href="#photos-section">Photos</a>
                            </li>
                            <li class="nav-item text-center header-item mx-auto pl-lg-4 pr-lg-4">
                                <a id="360TourNav" class="nav-link" href="#gsv-section">360 Tour</a>
                            </li>
                                <li class="nav-item text-center header-item mx-auto pl-lg-4 pr-lg-4">
                                    <a id="FAQNav" class="nav-link" href="#faq-section">FAQ</a>
                                </li>
                            <li class="nav-item text-center header-item mx-auto pl-lg-4 pr-lg-4">
                                <a id="ContactNav" class="nav-link" href="#contact-section">Contact &amp; Hours</a>
                            </li>
                                    <li class="nav-item text-center header-item mx-auto pl-lg-4 pr-lg-4">
                        <a id="PhoneNav" href="tel:6419852834" class="nav-link ml-2">
                            <i class="fas fa-phone fa-inverse fa-xs fa-rotate-90"></i>
                            (641) 985-2834
                        </a>
                    </li>
            </ul>
            <div class="d-flex flex-wrap justify-content-center pt-1">
                <ul class="navbar-nav mx-auto mr-auto mt-2 mt-lg-0 mb-2 business-info-nav d-flex flex-wrap justify-content-center">
                        <li class="nav-item text-center nav-business-name mr-1 ml-1 pl-1 pr-1">
                            Heartland Market
                        </li>
                                                <li class="nav-item text-center header-item mr-1 ml-1 pl-1 pr-1">

                                102 W Main St
                            </li>
                                            <li class="nav-item text-center header-item mr-1 ml-1 pl-1 pr-1">
                            Riceville, IA 50466
                        </li>
                </ul>
            </div>
        </div>
        
        <div class="d-xs-block d-md-none d-lg-none d-xl-none">
            <ul class="navbar-nav mx-auto mr-auto mt-2 mt-lg-0 mb-2">
                    <li class="nav-item text-center header-item mr-1 ml-1">
                        Heartland Market
                    </li>

                            <li class="nav-item text-center header-item mr-1 ml-1">
                                <a id="HomeNav" class="nav-link" href="#home-section">Home</a>
                            </li>
                            <li class="nav-item text-center header-item mr-1 ml-1">
                                <a id="AboutNav" class="nav-link" href="#about-section">About</a>
                            </li>
                            <li class="nav-item text-center header-item mr-1 ml-1">
                                <a id="ServicesNav" class="nav-link" href="#services-section">Services</a>
                            </li>
                            <li class="nav-item text-center header-item mr-1 ml-1">
                                <a id="PhotosNav" class="nav-link" href="#photos-section">Photos</a>
                            </li>
                            <li class="nav-item text-center header-item mr-1 ml-1">
                                <a id="360TourNav" class="nav-link" href="#gsv-section">360 Tour</a>
                            </li>
                                <li class="nav-item text-center header-item mr-1 ml-1">
                                    <a id="FAQNav" class="nav-link" href="#faq-section">FAQ</a>
                                </li>
                            <li class="nav-item text-center header-item mr-1 ml-1">
                                <a id="ContactNav" class="nav-link" href="#contact-section">Contact &amp; Hours</a>
                            </li>
            </ul>
        </div>
    </div>
</nav>


    
    <div id="home-section" class="page-section">
        


<div class="d-flex jumbotron parallax justify-content-center">
        <div class="parallax-image " style="background-image: url(https://du9m0k402rjmo.cloudfront.net/images/P_38699/ac7ed952-03a0-4dfd-8727-9d0f4b67b79a.jpg)"></div>
    <div class="row no-gutters">
            <div style="display:none !important">Heartland Market</div>
                    <div class="col-md-12 mt-3 mb-3 text-center heading mx-auto" style="color: #F19FA3;">
                Fresh Finds. Friendly Faces
            </div>
    </div>
</div>

    </div>

    
    <div id="about-section" class="page-section row no-gutters">

<div class="d-xs-block mx-auto">
    <div class="w-100 w-lg-90 mx-auto">
        <div class="d-flex flex-row flex-wrap justify-content-center mt-3 mb-3">
            <div class="w-100 w-lg-50 mx-auto m-3 p-4">
                <div class="section-header m-2 text-left fadein">
                    About Us
                </div>
                <div class="d-flex flex-wrap">
                        <div class="col-md-12 m-2 section-information text-left p-0">
                            Heartland Market, situated in Riceville, IA, serves as a premier discount grocery destination for residents of Mitchell and Howard counties. Dedicated to making grocery shopping more affordable, we offer a broad selection of products that include meats, cheeses, ice cream, and more. Additionally, we feature a variety of cosmetics, toys, and other overstock items from popular brands. Our innovative Heartland Market Mobile Unit allows us to conveniently extend our services across northeastern Iowa. Visit us today to explore our outstanding selection in Riceville or check our schedule to find out when we'll be in your neighborhood!
                        </div>
                                            <div class="m-2 mt-4 mr-auto">
                            <a id="contactPhone" href="tel:6419852834" class="contact-phone d-flex align-items-start justify-content-center btn btn-secondary pt-1 pb-1 pl-2 pr-2">
                                (641) 985-2834
                            </a>
                        </div>
                </div>
            </div>
            <div class="w-100 w-lg-50 mx-auto">
                <div class="d-flex flex-wrap">
                    <div class="col-lg mx-auto mt-3 p-0">
                            <div class="text-center mx-auto mt-2 mb-2 p-0 p-lg-4">
                                <img src="https://du9m0k402rjmo.cloudfront.net/images/P_38699/b19e18ff-4370-46a8-9a04-66b86be76cd3.jpg" class="rounded about-image mx-auto d-block img-fluid" alt="About" />
                            </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

    </div>

    
    <div id="services-section" class="page-section row no-gutters"></div>

    
    <div id="testimonials-section" class="page-section row no-gutters"></div>

    
    <div id="faq-section" class="page-section row no-gutters"></div>

    
    <div id="contact-section" class="page-section"></div>

    
    <div id="footer-section" class="row no-gutters mt-5 bg-alt-color p-4">

<div class="d-none d-md-block col-md-12 mx-auto text-center flex-column flex-wrap">

        <div class="flex-row mx-auto">
            Heartland Market
        </div>
            <div class="flex-row mx-auto">
            102 W Main St Riceville, IA 50466
        </div>
            <div class="flex-row mx-auto">
            <a id="phoneLink" class="phoneLinkInput" href="tel:6419852834">(641) 985-2834</a>
        </div>
</div>

<div class="d-sm-block d-md-none d-lg-none d-xl-none mx-auto text-center flex-column flex-wrap">
        <div class="flex-row mx-auto">
            Heartland Market
        </div>
            <div class="flex-row mx-auto">
            102 W Main St
        </div>
            <div class="flex-row mx-auto">
            Riceville, IA 50466
        </div>
            <div class="flex-row mx-auto">
            <a id="phoneLink" class="phoneLinkInput" href="tel:6419852834">(641) 985-2834</a>
        </div>
</div>
<div class="col-md-12 mx-auto mt-2 text-center">
    <a href="/Home/TermsOfUse" id="tosLink" target="_blank">Terms of Use</a>
    |
    <a href="/Home/PrivacyPolicy" id="ppLink" target="_blank">Privacy Policy</a>
</div>
<div class="col-md-12 mx-auto mt-2 text-center" style="font-size: 0.75rem; color: #999;">
    &copy; 2026 American Marketing & Publishing, L.L.C. All rights reserved. Names, logos, and other marks displayed are the property of their respective owners.
</div>

    </div>
</div>

    <div class="accessibility-img py-2 px-2">
        <div class="d-flex flex-wrap justify-content-center align-items-center text-center">
            <a href="/Accessibility?domain=heartlandmarket" target="_blank" class="dark">
                <img src="/Content/Templates/images/accessibility_icon.png" height="60" width="42" />
            </a>
        </div>
    </div>




<div class="chatbot-toggle-container">
  <button id="chatbot-toggle">
    <img src="/Content/Templates/images/chat_icon.png" height="60" width="60" />
  </button>
</div>

<!-- Chat Window -->
<div id="chat-window">
  <!-- Chat Header -->
  <div class="chat-header">
    <div class="chat-header-content">
      <h3 class="chat-header-title">Heartland Market Assistant</h3>
    </div>
    <button id="close-chat" class="chat-close-btn" aria-label="Close chat">
      <i class="fas fa-times"></i>
    </button>
  </div>

  <!-- Chat Messages -->
  <div id="chat-messages">
    <div class="chat-message-container">
      <div class="chat-message">
        Hi there! How can we help you today?
      </div>
    </div>
  </div>

  <div id="disclaimer-info">
    <div class="disclaimer-content">
      <div class="disclaimer-text">
        AI Responses not guaranteed; verify before reliance
      </div>
    </div>
  </div>

  <!-- Cost Display -->
  <div id="cost-info">
    <div class="cost-info-row">
      <div class="cost-info-left">
        <i class="fas fa-dollar-sign fa-xs cost-icon"></i>
        <span id="cost-display">Cost: $0.00000</span>
      </div>
      <span id="percentage-display">0.0% of $0.02</span>
    </div>
    <div class="cost-progress-bar">
      <div id="cost-progress"></div>
    </div>
  </div>

  <!-- Chat Input -->
  <div class="chat-input-container">
    <form id="chat-form">
      <input type="text" id="chat-input" placeholder="Type your message..." />
      <button type="submit" id="send-message">
        <i class="fas fa-paper-plane"></i>
      </button>
    </form>
    <div id="character-count">0/250</div>
    <div id="character-limit-message" style="display: none; color: #dc2626; font-size: 12px; margin-top: 4px;">
      Your message is too long. Please limit your question to 250 characters or less.
    </div>
  </div>
</div>

<!-- Contact Form Window -->
<div id="contact-form-window">
  <div class="contact-form-header">
    <h3 class="contact-form-title">Contact Form</h3>
    <button id="close-contact-form" class="contact-form-close-btn" aria-label="Close contact form">
      <i class="fas fa-times"></i>
    </button>
  </div>

  <div class="contact-form-content">
    <form id="chatbot-contact-form">
      <input type="hidden" id="chat_captcha_alt" name="chat_captcha_alt" value="DoCEkihWSTa8Enm+2S441dVOh0zYd/cvM+2ypb6YRJAXOmckMVdzAaVkNny+E6HU" />
      <input type="hidden" id="chat_g-Recaptcha-Response-Contact" name="chat_g-Recaptcha-Response-Contact" value="" />
      <input type="hidden" name="chat_aid" value="11c31fdb-512e-47d8-a0fa-5716393b584a" />
      <input type="hidden" name="chat_contactSubject" value="FrontDesk&#8482; Contact Form" />
      <input type="hidden" name="chat_contactAddress" value="" />
      <input type="hidden" name="chat_contactZip" value="" />
      <input type="hidden" name="chat_contactCity" value="" />
      <input type="hidden" name="chat_contactState" value="" />

      <div class="ai-liability mt-1 mb-1">(Messages sent through this site are subject to third party moderation and are not encrypted or secure. We always try to respond as soon as possible, but off-hours inquiries may take us a little longer to reply.)</div>

      <div class="form-group">
        <label for="chat_contactName" class="form-label">Name *</label>
        <input type="text" id="chat_contactName" name="chat_contactName" class="form-input" required />
      </div>

      <div class="form-group">
        <label for="chat_contactEmail" class="form-label">Email *</label>
        <input type="email" id="chat_contactEmail" name="chat_contactEmail" class="form-input" required />
      </div>

      <div class="form-group">
        <label for="chat_contactPhone" class="form-label">Phone</label>
        <input type="tel" id="chat_contactPhone" name="chat_contactPhone" class="form-input" />
      </div>

      <div class="form-group">
        <label for="chat_contactMessage" class="form-label">Message *</label>
        <textarea id="chat_contactMessage" name="chat_contactMessage" rows="4" class="form-textarea" required></textarea>
      </div>

      <div id="classicCaptcha" class="d-flex flex-column">
        <div class="g-recaptcha ml-auto mb-3 captcha-responsive" data-sitekey="6LeprWcUAAAAAF533Xd5p6kCrnRs0z4ceJieYgeO"></div>
      </div>

      <!-- Sticky footer section with reCAPTCHA disclaimer and submit button -->
      <div class="form-sticky-footer">
        <div class="grecaptcha-info">
          This site is protected by reCAPTCHA and the Google
          <a href="https://policies.google.com/privacy">Privacy Policy</a> and
          <a href="https://policies.google.com/terms">Terms of Service</a> apply.
        </div>
        <button type="submit" id="contact-submit-btn" class="form-submit-btn">Submit</button>
      </div>
    </form>
  </div>
</div>

<script>
    // Wrap entire chatbot functionality in a namespace to prevent conflicts
    window.ChatbotModule = (function() {
        'use strict';

        // Private variables
        let isOpen = false;
        let contactFormOpen = false;
        let messages = [
            { role: 'assistant', content: 'Hi there! How can we help you today?' }
        ];
        let isLoading = false;
        let showContactForm = false;
        let limitReached = false;
        let apiCost = 0;
        const maxCost = 0.5;
        const maxQuestionLength = 250;

        // Private element references
        let $chatbotToggle;
        let $chatWindow;
        let $contactFormWindow;
        let $closeChat;
        let $closeContactForm;
        let $chatMessages;
        let $chatForm;
        let $chatInput;
        let $sendMessage;
        let $characterCount;
        let $costDisplay;
        let $percentageDisplay;
        let $costProgress;
        let $contactForm;

        // Initialize element references
        function initializeElements() {
            $chatbotToggle = $('#chatbot-toggle');
            $chatWindow = $('#chat-window');
            $contactFormWindow = $('#contact-form-window');
            $closeChat = $('#close-chat');
            $closeContactForm = $('#close-contact-form');
            $chatMessages = $('#chat-messages');
            $chatForm = $('#chat-form');
            $chatInput = $('#chat-input');
            $sendMessage = $('#send-message');
            $characterCount = $('#character-count');
            $costDisplay = $('#cost-display');
            $percentageDisplay = $('#percentage-display');
            $costProgress = $('#cost-progress');
            $contactForm = $('#chatbot-contact-form');
        }

        // Initialize
        function init() {
            // Initialize element references
            initializeElements();

            // Load cost from localStorage
            const savedCost = localStorage.getItem('api_cost');
            if (savedCost) {
                apiCost = parseFloat(savedCost);

                // Check if cost limit is reached
                if (apiCost >= maxCost) {
                    limitReached = true;
                    updateChatInputState();
                }
            }

            // Initialize character count display
            updateCharacterCount();

            document.documentElement.style.setProperty('--adaptive-text-color', '#374151');
            document.documentElement.style.setProperty('--image-invert', 'none');

            setTimeout(updateTextColors, 100);

            // Ensure chatbot stays on top even when modals are opened
            $(document).on('shown.bs.modal', function (e) {
              // Temporarily boost chatbot z-index when modals are shown
              $('.chatbot-toggle-container').css('z-index', '2147483647');
              $('#chat-window').css('z-index', '2147483646');
              $('#contact-form-window').css('z-index', '2147483645');
            });

            // Set up event listeners
            setupEventListeners();
        }

        // Event Listeners with namespacing
        function setupEventListeners() {
            // Remove any existing chatbot event listeners to prevent duplicates
            $chatbotToggle.off('.chatbot');
            $closeChat.off('.chatbot');
            $closeContactForm.off('.chatbot');
            $chatForm.off('.chatbot');
            $chatInput.off('.chatbot');
            $contactForm.off('.chatbot');

            // Toggle chat window
            $chatbotToggle.on('click.chatbot', function(e) {
                e.preventDefault();
                e.stopPropagation();
                toggleChat();
            });

            $closeChat.on('click.chatbot', function(e) {
                e.preventDefault();
                e.stopPropagation();
                closeChat();
            });

            $closeContactForm.on('click.chatbot', function(e) {
                e.preventDefault();
                e.stopPropagation();
                hideContactForm();
            });

            // Send message
            $chatForm.on('submit.chatbot', function (e) {
                e.preventDefault();
                e.stopPropagation();

                // Check if submit button is disabled
                if ($sendMessage.prop('disabled') || $sendMessage.hasClass('disabled')) {
                    return false;
                }

                sendMessage();
            });

            // Character count - update on every keystroke
            $chatInput.on('input.chatbot', function(e) {
                // Only handle if this is specifically the chatbot input
                if ($(this).attr('id') === 'chat-input') {
                    updateCharacterCount();
                }
            });

            // Also check on keyup to catch paste events
            $chatInput.on('keyup.chatbot paste.chatbot', function(e) {
                // Only handle if this is specifically the chatbot input
                if ($(this).attr('id') === 'chat-input') {
                    setTimeout(updateCharacterCount, 10);
                }
            });

            // Handle "Enter" key for sending messages
            $chatInput.on('keydown.chatbot', function (e) {
                // Only handle if this is specifically the chatbot input
                if ($(this).attr('id') !== 'chat-input') {
                    return;
                }

                if (e.key === 'Enter' && !e.shiftKey && !limitReached) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    // Check if submit button is disabled
                    if ($sendMessage.prop('disabled') || $sendMessage.hasClass('disabled')) {
                        return false;
                    }

                    sendMessage();
                    return;
                }
            });

            // Contact form submission
            $contactForm.on('submit.chatbot', function (e) {
                e.preventDefault();
                e.stopPropagation();
                submitContactForm();
            });
        }

        // Toggle chat window
      function toggleChat() {
        if (!isOpen) {
          // Opening the chat
          isOpen = true;

          // Hide toggle button on both mobile and desktop
          $('.chatbot-toggle-container').addClass('hide-toggle');

          // First show the window (still off-screen)
          $chatWindow.show();

          // Force a reflow to ensure the transition will work
          $chatWindow[0].offsetHeight;

          // Then add the class that triggers the slide-in animation
          setTimeout(function () {
            $chatWindow.addClass('show');
            scrollToBottom();
          }, 10);
        } else {
          // Closing the chat
          isOpen = false;

          // Show toggle button again
          $('.chatbot-toggle-container').removeClass('hide-toggle');

          // Remove the show class to trigger slide-out animation
          $chatWindow.removeClass('show');

          // Hide the window after the animation completes
          setTimeout(function () {
            $chatWindow.hide();
          }, 300); // Match the CSS transition duration

          // Also hide contact form if open
          if (contactFormOpen) {
            hideContactForm();
          }
        }
      }

        // Close chat window
      function closeChat() {
        if (isOpen) {
          isOpen = false;

          // Show toggle button again
          $('.chatbot-toggle-container').removeClass('hide-toggle');

          // Trigger slide-out animation
          $chatWindow.removeClass('show');

          // Hide after animation
          setTimeout(function () {
            $chatWindow.hide();
          }, 300);

          if (contactFormOpen) {
            hideContactForm();
          }
        }
      }

        // Update character count and submit button state
        function updateCharacterCount() {
            const count = $chatInput.val().length;
            const remaining = maxQuestionLength - count;
            const $limitMessage = $('#character-limit-message');

            if (count > maxQuestionLength) {
                // Over limit - disable submit button and show message
                $characterCount.text(`${count}/${maxQuestionLength} (${Math.abs(remaining)} over limit)`).css('color', '#dc2626');
                $limitMessage.text(`Your message is too long. Please limit your question to ${maxQuestionLength} characters or less. Your message is currently ${count} characters.`).show();
                $chatInput.addClass('over-limit');

                // Disable submit button with proper styling
                $sendMessage.prop('disabled', true).addClass('disabled');
                $sendMessage.css({
                    'background-color': '#9ca3af',
                    'color': '#6b7280',
                    'cursor': 'not-allowed',
                    'opacity': '0.5',
                    'pointer-events': 'none'
                });

            } else if (remaining <= 20) {
                // Close to limit - show warning but allow submit
                $characterCount.text(`${count}/${maxQuestionLength}`).css('color', '#f59e0b');
                $limitMessage.hide();
                $chatInput.removeClass('over-limit');

                // Enable submit button and reset styling
                $sendMessage.prop('disabled', false).removeClass('disabled');
                $sendMessage.css({
                    'background-color': '',
                    'color': '',
                    'cursor': '',
                    'opacity': '',
                    'pointer-events': ''
                });

            } else {
                // Within limit - normal state
                $characterCount.text(`${count}/${maxQuestionLength}`).css('color', '#6b7280');
                $limitMessage.hide();
                $chatInput.removeClass('over-limit');

                // Enable submit button and reset styling
                $sendMessage.prop('disabled', false).removeClass('disabled');
                $sendMessage.css({
                    'background-color': '',
                    'color': '',
                    'cursor': '',
                    'opacity': '',
                    'pointer-events': ''
                });
            }
        }

        // Send message
        function sendMessage() {
            const message = $chatInput.val().trim();
            if (!message || isLoading || limitReached) return;

            // Double check character limit including whitespace
            if (message.length > maxQuestionLength) {
                appendMessage('assistant', `Your message is too long. Please limit your question to ${maxQuestionLength} characters or less. Your message is currently ${message.length} characters.`);
                return;
            }

            // Add user message to chat
            messages.push({ role: 'user', content: message });
            appendMessage('user', message);

            // Clear input
            $chatInput.val('');
            updateCharacterCount();

            // Send to API
            fetchChatResponse(messages);
        }

        // Fetch chat response from API
        function fetchChatResponse(messages) {
            isLoading = true;
            showLoadingIndicator();

            $.ajax({
                url: '/Home/Chat',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    Messages: messages,
                    ProfileId: '38699'
                }),
                headers: {
                    'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                },
                success: function (response) {
                    hideLoadingIndicator();

                    if (response.error) {
                        appendMessage('assistant', `Error: ${response.error}`);
                        console.error('API Error:', response.error);
                        isLoading = false;
                        return;
                    }

                    // Update cost
                    apiCost = response.Cost;
                    localStorage.setItem('api_cost', apiCost.toString());

                    // Check if limit reached
                    if (response.LimitReached) {
                        limitReached = true;
                        showContactFormWindow();
                        appendMessage('assistant', 'Our AI chat has reached its capacity. Please use the contact form to get in touch directly with us.');
                    } else {
                        // Check if response contains contact form trigger
                        if (response.Message.includes('<start_contact_form>')) {
                            const cleanResponse = response.Message.replace('<start_contact_form>', '');
                            appendMessage('assistant', cleanResponse);
                            showContactFormWindow();
                        } else {
                            appendMessage('assistant', response.Message);
                        }

                        // Add response to messages array
                        messages.push({ role: 'assistant', content: response.Message });
                    }

                    isLoading = false;
                    updateChatInputState();
                },
                error: function (xhr, status, error) {
                    hideLoadingIndicator();
                    appendMessage('assistant', 'Sorry, I encountered an error. Please try again later.');
                    console.error('AJAX Error:', error);
                    isLoading = false;
                }
            });
        }

        // Append message to chat
        function appendMessage(role, content) {
            content = convertMarkdownLinksToHTML(content);
            const rootStyles = getComputedStyle(document.documentElement);
            const customerColor = rootStyles.getPropertyValue('--customer_color').trim();
            const adaptivefontColor = rootStyles.getPropertyValue('--adaptive-text-color').trim();

            const messageClass = role === 'user' ? 'flex-end' : 'flex-start';
            const bgColor = role === 'user' ? customerColor : 'white';
            const textColor = role === 'user' ? adaptivefontColor : '#374151';
            const borderRadius = role === 'user' ? 'border-bottom-right-radius: 0;' : 'border-bottom-left-radius: 0;';
            const border = role === 'user' ? '' : 'border: 1px solid #e5e7eb;';

            const messageHtml = `
                <div style="display: flex; justify-content: ${messageClass}; margin-bottom: 16px;">
                    <div style="max-width: 75%; padding: 12px; border-radius: 8px; background-color: ${bgColor}; ${border} ${borderRadius} color: ${textColor}; word-wrap: break-word; overflow-wrap: break-word;">
                        ${content}
                    </div>
                </div>
            `;

            $chatMessages.append(messageHtml);
            scrollToBottom();
        }

        // Show loading indicator
        function showLoadingIndicator() {
            const loadingHtml = `
                <div id="loading-indicator" style="display: flex; justify-content: flex-start; margin-bottom: 16px;">
                    <div style="max-width: 75%; padding: 12px; border-radius: 8px; background-color: white; border: 1px solid #e5e7eb; color: #374151; display: flex; gap: 4px;">
                        <div class="loading-dot" style="width: 8px; height: 8px; background-color: #9ca3af; border-radius: 50%;"></div>
                        <div class="loading-dot" style="width: 8px; height: 8px; background-color: #9ca3af; border-radius: 50%;"></div>
                        <div class="loading-dot" style="width: 8px; height: 8px; background-color: #9ca3af; border-radius: 50%;"></div>
                    </div>
                </div>
            `;

            $chatMessages.append(loadingHtml);
            animateLoadingDots();
            scrollToBottom();

            // Disable input while loading
            $chatInput.prop('disabled', true);
            $sendMessage.prop('disabled', true);
        }

        // Animate loading dots
        function animateLoadingDots() {
            if (!$("#loading-indicator").length) return;

            $(".loading-dot").each(function (index) {
                var $dot = $(this);
                setTimeout(function () {
                    $dot.animate({ opacity: 0.3 }, 300)
                        .animate({ opacity: 1 }, 300);
                }, index * 200);
            });

            setTimeout(function () {
                animateLoadingDots();
            }, 900);
        }

        // Hide loading indicator
        function hideLoadingIndicator() {
            $('#loading-indicator').remove();

            // Enable input after loading (unless limit reached)
            if (!limitReached) {
                $chatInput.prop('disabled', false);
                updateCharacterCount(); // This will set the correct submit button state
            }
        }

        // Scroll to bottom of chat
        function scrollToBottom() {
            $chatMessages.scrollTop($chatMessages[0].scrollHeight);
        }

        // Update cost display
        function updateCostDisplay() {
            $("#cost-info").show();
            $costDisplay.text(`Cost: $${apiCost.toFixed(5)}`);

            const percentage = (apiCost / maxCost) * 100;
            $percentageDisplay.text(`${percentage.toFixed(1)}% of $${maxCost.toFixed(2)}`);

            $costProgress.css('width', `${percentage}%`);

            // Change progress bar color if near limit
            if (percentage > 80) {
                $costProgress.css("background-color", "#dc2626");
            } else {
                $costProgress.css("background-color", "#4f46e5");
            }

            // Update chat input state
            updateChatInputState();
        }

        // Update chat input state based on limit
        function updateChatInputState() {
            if (limitReached) {
                $chatInput.prop('disabled', true);
                $sendMessage.prop('disabled', true);
                $chatInput.attr('placeholder', 'Chat Unavailable.');
            } else {
                $chatInput.prop('disabled', false);
                updateCharacterCount(); // This will set the correct submit button state
                $chatInput.attr('placeholder', 'Type your message...');
            }
        }

        // Show contact form
      function showContactFormWindow() {
        if (!contactFormOpen) {
          contactFormOpen = true;

          // Hide toggle button when contact form opens
          $('.chatbot-toggle-container').addClass('hide-toggle');

          if (isMobile()) {
            // On mobile, slide out chat and slide in contact form
            $chatWindow.removeClass('show');
            setTimeout(function () {
              $chatWindow.hide();
              $contactFormWindow.show();
              // Force reflow
              $contactFormWindow[0].offsetHeight;
              // Add show class for slide animation
              setTimeout(function () {
                $contactFormWindow.addClass('show');
                $('.contact-form-content').scrollTop(0);
              }, 10);
            }, 300);
          } else {
            // Desktop - slide chat to left and slide in contact form
            $chatWindow.animate({ right: '390px' }, 300);
            $contactFormWindow.show();
            setTimeout(function () {
              $contactFormWindow.animate({ right: '20px' }, 300);
            }, 50);
          }
        }
      }

      // Hide contact form - slides out and chat returns to original position
      function hideContactForm() {
        if (contactFormOpen) {
          contactFormOpen = false;

          if (isMobile()) {
            // Slide out contact form
            $contactFormWindow.removeClass('show');

            setTimeout(function () {
              $contactFormWindow.hide();
              // Show chat window again if it was open
              if (isOpen) {
                $chatWindow.show();
                // Force reflow
                $chatWindow[0].offsetHeight;
                setTimeout(function () {
                  $chatWindow.addClass('show');
                }, 10);
              } else {
                // If chat is not open, show toggle button
                $('.chatbot-toggle-container').removeClass('hide-toggle');
              }
            }, 300);
          } else {
            // Desktop - animate back
            $contactFormWindow.animate({ right: '-370px' }, 300, function () {
              $contactFormWindow.hide();
            });
            $chatWindow.animate({ right: '20px' }, 300);

            // Only show toggle if both windows are closed
            if (!isOpen) {
              $('.chatbot-toggle-container').removeClass('hide-toggle');
            }
          }
        }
      }

      // Submit contact form
        function submitContactForm() {
            const name = $('#chat_contactName').val();
            const email = $('#chat_contactEmail').val();
            const phone = $('#chat_contactPhone').val();
            const message = $('#chat_contactMessage').val();

            // Basic validation
            if (!name || !email || !message) {
                alert('Please fill out all required fields.');
                return;
            }

            // Email validation
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                alert('Please enter a valid email address.');
                return;
            }

            // Message length validation
            if (message.length < 10) {
                alert('Your message must be at least 10 characters long.');
                return;
            }

            // Disable form during submission
            $('#contact-submit-btn').prop('disabled', true).text('Sending...');

            var form = $("#chatbot-contact-form");

            // Execute reCAPTCHA before submitting
            grecaptcha.ready(function() {
                grecaptcha.execute('6LcokacUAAAAAH_snk3O5bpdYwjpC5XAuXNLrJLH', {action: 'contact_us'}).then(function(token) {
                    // Set the reCAPTCHA token
                    $("#chat_g-Recaptcha-Response-Contact").val(token);

                    // Submit the form with reCAPTCHA token
                    $.ajax({
                        url: "/Home/ChatContactPost",
                        type: 'POST',
                        data: form.serialize(),
                        success: function (response) {
                            if (typeof response === 'string' && response.indexOf('{"message":') != -1) {
                                var jsonData = JSON.parse(response);
                                if (jsonData.success) {
                                    appendMessage('assistant', 'Thanks for providing your information! We will get back to you soon.');
                                    hideContactForm();

                                    // Reset the form
                                    $('#chat_contactName').val('');
                                    $('#chat_contactEmail').val('');
                                    $('#chat_contactPhone').val('');
                                    $('#chat_contactMessage').val('');
                                } else {
                                    alert(jsonData.message || 'There was an error processing your request.');
                                }
                            } else if (response.success) {
                                appendMessage('assistant', 'Thanks for providing your information! We will get back to you soon.');
                                hideContactForm();

                                // Reset the form
                                $('#chat_contactName').val('');
                                $('#chat_contactEmail').val('');
                                $('#chat_contactPhone').val('');
                                $('#chat_contactMessage').val('');

                            } else {
                                alert(response.message || 'There was an error processing your request.');
                            }

                            $('#contact-submit-btn').prop('disabled', false).text('Submit');
                        },
                        error: function (xhr, status, error) {
                            alert('Failed to submit your information. Please try again.');
                            console.error('AJAX Error:', error);
                            $('#contact-submit-btn').prop('disabled', false).text('Submit');
                        }
                    });
                });
            });
        }

        function convertMarkdownLinksToHTML(text) {
            return text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, linkText, url) => {
                // Add target="_blank" for http/https links
                if (url.startsWith('http://') || url.startsWith('https://')) {
                    return `<a href="${url}" target="_blank" rel="noopener noreferrer">${linkText}</a>`;
                }
                // Keep tel: and mailto: links as-is
                return `<a href="${url}">${linkText}</a>`;
            });
        }

        function getLuminance(hex) {
            // Remove # if present
            hex = hex.replace('#', '');

            // Convert hex to RGB
            const r = parseInt(hex.substr(0, 2), 16) / 255;
            const g = parseInt(hex.substr(2, 2), 16) / 255;
            const b = parseInt(hex.substr(4, 2), 16) / 255;

            // Calculate relative luminance
            const rLum = r <= 0.03928 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4);
            const gLum = g <= 0.03928 ? g / 12.92 : Math.pow((g + 0.055) / 1.055, 2.4);
            const bLum = b <= 0.03928 ? b / 12.92 : Math.pow((b + 0.055) / 1.055, 2.4);

            return 0.2126 * rLum + 0.7152 * gLum + 0.0722 * bLum;
        }

        function isLightColor(hex) {
            const luminance = getLuminance(hex);
            return luminance > 0.5; // Threshold for light vs dark
        }

        function updateTextColors() {
            const rootStyles = getComputedStyle(document.documentElement);
            let customerColor = rootStyles.getPropertyValue('--customer_color').trim();

            // Check if customer color is not set or is empty
            if (!customerColor || customerColor === '') {
                const defaultColor = '#f3f3f3';

                // Set the default customer color
                document.documentElement.style.setProperty('--customer_color', defaultColor);
                customerColor = defaultColor;
            }

            const isLight = isLightColor(customerColor);
            const textColor = isLight ? '#000000b3' : '#ffffff';

            const $chatbotToggle = $('#chatbot-toggle');
            if (isLight) {
                $chatbotToggle.removeClass('dark-background').addClass('light-background');
            } else {
                $chatbotToggle.removeClass('light-background').addClass('dark-background');
            }

            // Update the CSS custom property
            document.documentElement.style.setProperty('--adaptive-text-color', textColor);
        }

        function isMobile() {
            return window.innerWidth <= 768;
        }

        // Public interface
        return {
            init: init
        };
    })();

    // Initialize the chatbot module when document is ready
    $(document).ready(function () {
        if (window.ChatbotModule) {
            window.ChatbotModule.init();
        }
    });
</script>
<!-- Review Modal -->
<div class="modal" id="carouselReviewFullModal">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button></div>
            <div class="modal-body review-full-modal-body"></div>
        </div>
    </div>
</div>

<script type="text/javascript">
    var isMobile = false;
    var notReputation = true;
    var isHidden = false;
    var allContentLoaded = false;
    var contentLoadedCount = 0;
    var expectedContentCount = 3; // Services, FAQ, Contact (+ optionally Testimonials)

    $(document).ready(function ()
    {
        if($("#contact_us_phone").length > 0){
            var cleave = new Cleave('#contact_us_phone', {
                phone: true,
                phoneRegionCode: 'US'
            });
        }

        checkMobile();

        // Adjust expected content count if testimonials should be loaded
        if (!isHidden && !notReputation) {
            expectedContentCount = 4;
        }

        var analyticsCategory = "Desktop";
        if (isMobile == true) {
            analyticsCategory = "Mobile";
        }

        FadeIn();
        $(window).scroll(function () {
            FadeIn();
            var scroll = $(window).scrollTop();
            if(scroll > 100){
                $(".nav-section").addClass("is-sticky");
                $(".nav-logo").addClass("nav-logo-adjust");

                $("#home-section").addClass("page-section-adjust");
            }
            else if(scroll <= 100){
                $(".nav-section").removeClass("is-sticky");
                $(".nav-logo").removeClass("nav-logo-adjust");

                $("#home-section").removeClass("page-section-adjust");
            }
        });

        $('.navbar-collapse a').click(function () {
            //$(".navbar-collapse").collapse('hide'); 
            $(".navbar-collapse").removeClass('show');
            $(".navbar-toggler").addClass('collapsed');
        });

        var navMain = $("#navbarToggler");
        navMain.on("click", "a", null, function () {
            navMain.collapse('hide');
        });

        //handle links with href started with '#' only
        $(document).on('click', 'a[href^="#"]', function (e) {
            // target element id
            var id = $(this).attr('href');

            // target element
            var $id = $(id);
            if ($id.length === 0) {
                return;
            }

            // prevent standard hash navigation (avoid blinking in IE)
            e.preventDefault();

            // top position relative to the document
            var pos = $id.offset().top - $('.navbar').height();

            // animated top scrolling
            $('body, html').animate({ scrollTop: pos });
        });

        $(document).on("click", "#btnContactPost", function (e) {
            $("#btnContactPost").prop('disabled', true);
            $("#btnContactPost").css('font-weight', 'normal');
            contactUsPost(e);
        });


        //Google Analytics Events
        $('a').on('click', function () {
            if (this.id !== "undefined" && this.id !== "") {
                gtag('event', 'Link Click', {
                    'event_category': analyticsCategory,
                    'event_label': this.id
                });
            }
        });
        $('#HomeNav').on('click', function () {
            gtag('event', 'Link Click', {
                'event_category': analyticsCategory,
                'event_label': 'CustomerHomeNavigationLinkTemplate1'
            });
        });
        $('#AboutNav').on('click', function () {
            gtag('event', 'Link Click', {
                'event_category': analyticsCategory,
                'event_label': 'CustomerAboutNavigationLinkTemplate1'
            });
        });
        $('#ServicesNav').on('click', function () {
            gtag('event', 'Link Click', {
                'event_category': analyticsCategory,
                'event_label': 'CustomerServicesNavigationLinkTemplate1'
            });
        });
        $('#ContactNav').on('click', function () {
            gtag('event', 'Link Click', {
                'event_category': analyticsCategory,
                'event_label': 'CustomerContactNavigationLinkTemplate1'
            });
        });
        $('#facebook-social').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerFacebookLinkTemplate1' 
            }); 
        }); 
        $('#google-social').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerGoogleLinkTemplate1' 
            }); 
        }); 
        $('#yelp-social').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerYelpLinkTemplate1' 
            }); 
        }); 
        $('#twitter-social').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerTwitterLinkTemplate1' 
            }); 
        }); 
        $('#instagram-social').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerInstagramLinkTemplate1' 
            }); 
        }); 
        $('#linkedin-social').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerLinkedInLinkTemplate1' 
            }); 
        }); 
        $('#contactPhone').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-1' 
            }); 
        }); 
        $('#contactPhoneSecondary').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-3' 
            }); 
        }); 
        $('#contactPhoneMobile').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-4' 
            }); 
        }); 
        $('#contactPhoneFax').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-5' 
            }); 
        }); 
        $('#contactPhoneTollfree').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-6' 
            }); 
        }); 
        $('#contactPhoneC1').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-8' 
            }); 
        }); 
        $('#contactPhoneC2').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-9' 
            }); 
        }); 
        $('#contactPhoneC3').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-10' 
            }); 
        }); 
        $('#contactPhoneC4').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-11' 
            }); 
        }); 
        $('#contactPhoneC5').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-12' 
            }); 
        }); 
        $('#PhoneNav').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactPhoneLinkTemplate1-2' 
            }); 
        });
        $('#btnContactPost').on('click', function () {
            gtag('event', 'Link Click', {
                'event_category': analyticsCategory,
                'event_label': 'CustomerContactLeadPostTemplate1'
            });
        });
        $('#googleMapEmbed').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerGoogleMapEmbedTemplate1' 
            }); 
        }); 
        $('#phoneLink').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerPhoneLinkFooterTemplate1' 
            }); 
        }); 
        $('#contactEmail').on('click', function () { 
            gtag('event', 'Link Click', { 
                'event_category': analyticsCategory, 
                'event_label': 'CustomerContactEmailLinkTemplate1' 
            }); 
        });
        //unable to directly track cross domain iFrame clicks. Track only first click on the iFrame itself
        var monitor = setInterval(function () {
            var elem = document.activeElement;
            if (elem && elem.tagName == "IFRAME" && elem.id == "googleMapEmbed") {
                gtag('event', 'iFrame Click', {
                    'event_category': analyticsCategory,
                    'event_label': 'GoogleDirectionsTemplate1'
                });
                clearInterval(monitor);
            }
        }, 1000);

        loadServices();
        loadFAQ();
        loadContact();
        if (!isHidden && !notReputation) {
            loadTestimonials();
        } else {
            // If not loading testimonials, adjust the expected count
            expectedContentCount = 3;
        }
    });

    var testimonialsRendered = false;

    function checkAllContentLoaded() {
        contentLoadedCount++;

        if (contentLoadedCount >= expectedContentCount) {
            allContentLoaded = true;
        }
    }

    function loadServices() {
        $.get('/Home/GetServicesContent', {id: 38699, template: "Template_1"}, function (data) {
            if (data != "")
            {
                $("#services-section").append(data);
            }
        }).always(function () {
            initializeCarousel();
            checkAllContentLoaded();
        });
    }

    function loadFAQ() {
        $.get('/Home/GetFAQContent', { id: 38699, template: "Template_1" }, function (data) {
            if (data != "") {
                $("#faq-section").append(data);
            }
        }).always(function() {
            checkAllContentLoaded();
        });
    }

    function loadContact() {
        $.get('/Home/GetContactContent', {id: 38699, template: "Template_1"}, function (data) {
            if (data != "")
            {
                $("#contact-section").append(data);
            }
        }).always(function() {
            checkAllContentLoaded();
        });
    }

    /*ABC-2932 Start*/
    function loadTestimonials() {
        $.get('/Home/GetTestimonialsContent', {id: 38699, template: "Template_1"}, function (data) {
            if (data != "")
            {
                $("#testimonials-section").append(data);
            }
        }).always(function () {
            testimonialsRendered = true;
            intializeReviewCarousel();
            checkAllContentLoaded();
        });

        $("html, body").animate({ scrollTop: 0 }, "fast");

        var reviewSlider = $(".slider-single-blurb");
        if (reviewSlider != null) {
            reviewSlider.slick('refresh');
        }
    }

    function nextReview() {
        ScrollForReviews();
        GetReviewData(1);
    }

    function prevReview() {
        ScrollForReviews();
        GetReviewData(-1);
    }

    function ScrollForReviews() {
        // target element
        var $id = $(".review-partial-content");
        if ($id.length === 0) {
            return;
        }

        // prevent standard hash navigation (avoid blinking in IE)
        //e.preventDefault();

        // top position relative to the document
        var pos = $id.offset().top - $('.navbar').height();

        // animated top scrolling
        // .stop() keeps from scrolling to top then to element
        $('body, html').stop().animate({ scrollTop: pos }, 500);
    }

    function GetMoreButtonValue()
    {
        var d = new Date();
        var r = Math.random();
        $.get('/Home/GetValueOfMoreButton' + '?r=' + r + d.getMilliseconds(), {pageIndex: pageIndex, pageSize: pageSize, numOfReviews: numOfReviews}, function(data){
            if(data.showButton == 0)
            {
                $("#showMoreButton").hide();
            }
        });
    }

    function SetPaginationButtons() {
        //look ahead by one
        if (((pageIndex + 1) * pageSize) >= numOfReviews) {
            $("#nextReview").hide();
        }
        else {
            $("#nextReview").show();
            $("#nextReview").prop('disabled', false);
        }

        if (pageIndex <= 0) {
            pageIndex = 0;
            $("#prevReview").hide();
        }
        else if (pageIndex > 0) {
            $("#prevReview").show();
            $("#prevReview").prop('disabled', false);
        }
    }

    function DisplayFullReview(element) {
        var text = $(element).html().replace("col-xl", "col-12");    //format so information is stacked
        $(".review-full-modal-body").html(text);
        $("#carouselReviewFullModal").modal('show');
    }

    function HideModal(e) {
        $("#carouselReviewFullModal").modal('hide');
        ScrollForReviews(e);
    }
    /*ABC-2932 End*/

    function checkMobile() {
        var windowsize = $(window).width();
        switch (true) {
            case /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent):
                isMobile = true;
                break;
            case windowsize < 768:
                isMobile = true;
                break;
            default:
                isMobile = false;
        }
    }

  function contactUsPost(event) {
    var _contactForm = $("#ContactPostForm");

    // Clear previous validation states
    $('.validation-error-message').remove();
    _contactForm.find('.validation-error').removeClass('validation-error');
    $("#contactResponseMessage").empty();

    if (_contactForm[0].checkValidity()) {
      contactUsSubmit(event);
    } else {
      var firstInvalidField = null;

      _contactForm.find('input[required], textarea[required], select[required]').each(function () {
        var $field = $(this);

        if (!this.checkValidity()) {
          var fieldId = $field.attr('id') || $field.attr('name');
          var fieldLabel = getFieldLabel(fieldId);

          $field.addClass('validation-error');

          var errorMessage = getCustomErrorMessage($field, fieldLabel);
          $field.after(`<div class="validation-error-message">${errorMessage}</div>`);

          if (!firstInvalidField) {
            firstInvalidField = $field;
          }
        }
      });

      // Focus first invalid field
      if (firstInvalidField) {
        firstInvalidField.focus();
      }

      // Re-enable submit button
      $("#btnContactPost").prop('disabled', false);
      $("#btnContactPost").css('font-weight', 'bold');
    }
  }

  function getFieldLabel(fieldId) {
    var labels = {
      'contact_us_phone': 'Phone Number',
      'contact_us_address': 'Address',
      'contact_us_city': 'City',
      'contact_us_state': 'State',
      'contact_us_zip': 'ZIP Code',
      'contact_us_subject': 'Subject',
      'contact_us_name': 'Name',
      'contact_us_email': 'Email',
      'contact_us_message': 'Message'
    };
    return labels[fieldId] || 'This field';
  }

  function getCustomErrorMessage($field, fieldLabel) {
    if ($field.prop('required') && !$field.val().trim()) {
      return `${fieldLabel} required`;
    }

    if ($field.attr('type') === 'email' && $field.val()) {
      return `Please enter a valid email address.`;
    }

    return `Please enter a valid ${fieldLabel.toLowerCase()}.`;
  }

    function contactUsSubmit(event) {
        event.preventDefault();

        var form = $("#ContactPostForm");
        grecaptcha.ready(function() {
            grecaptcha.execute('6LcokacUAAAAAH_snk3O5bpdYwjpC5XAuXNLrJLH', {action: 'contact_us'}).then(function(token) {
                $("#g-Recaptcha-Response-Contact").attr("value", token); //add token for server side validation
                $.ajax({
                    type: "POST",
                    url: "/Home/ContactPost",
                    data: form.serialize(),
                    success: function(data){
                        if (data.indexOf('{"message":') != -1) {
                            var jsonData = JSON.parse(data);
                            if (!jsonData.success) {
                                $("#contactResponseMessage").html('<div class="alert alert-warning alert-dissmisable" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + jsonData.message + '</div>');
                                recaptchaContactUsInComplete();
                                showClassicCaptcha();
                            }
                            else{
                                $("#contactResponseMessage").html('<div class="alert alert-success alert-dissmisable" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + jsonData.message + '</div>');
                                recaptchaContactUsComplete();
                            }
                        }
                    }
                });
            });
        });
    }

    function FadeIn() {
        /* Check the location of each desired element */
        $('.fadein').each(function (i) {
            var elementTop = $(this).offset().top;
            var elementBottom = elementTop + $(this).outerHeight();

            var viewportTop = $(window).scrollTop();
            var viewportBottom = viewportTop + $(window).height();

            var inViewPort = elementBottom > viewportTop && elementTop < viewportBottom;

            /* If the object is completely visible in the window, fade it in */
            if ((viewportBottom > elementBottom) || inViewPort) {
                $(this).addClass('animate');
            }
        });
    }

    function recaptchaContactUsInComplete(){
        $("#btnContactPost").prop('disabled', false);
        $("#btnContactPost").css('font-weight', 'bold');
  }

  function recaptchaContactUsComplete() {
    $("#btnContactPost").prop('disabled', false);
    $("#btnContactPost").css('font-weight', 'normal');
    $("#ContactPostForm").trigger("reset");
  }

    function showClassicCaptcha() {
        $("#classicCaptcha").show();
    }

    function initializeCarousel() {
        //https://codepen.io/dolce/pen/QarQde
        $('.slider-single').slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            arrows: true,
            fade: false,
            adaptiveHeight: false,
            infinite: true,
            useTransform: true,
            speed: 400,
            cssEase: 'cubic-bezier(0.77, 0, 0.18, 1)',
            autoplay: true,
        });

        $('.slider-nav')
            .on('init', function (event, slick) {
                $('.slider-nav .slick-slide.slick-current').addClass('is-active');
            })
            .slick({
                slidesToShow: 5,
                slidesToScroll: 5,
                dots: false,
                focusOnSelect: false,
                infinite: true,
            });

        $('.slider-single').on('afterChange', function (event, slick, currentSlide) {
            $('.slider-nav').slick('slickGoTo', currentSlide);
            var currrentNavSlideElem = '.slider-nav .slick-slide[data-slick-index="' + currentSlide + '"]';
            $('.slider-nav .slick-slide.is-active').removeClass('is-active');
            $(currrentNavSlideElem).addClass('is-active');
        });

        $('.slider-nav').on('click', '.slick-slide', function (event) {
            event.preventDefault();
            var goToSingleSlide = $(this).data('slick-index');
            $('.slider-single').slick('slickGoTo', goToSingleSlide);
        });
    }

    function intializeReviewCarousel() {
        //initialize the testimonial carousel ABC-2932
        $('.slider-single-blurb').slick({
            autoplay: true,
            centerMode: true,
            centerPadding: '25%',
            slidesToShow: 1,
            infinite: true,
            adaptiveHeight: true,
            autoplaySpeed: 5000,
            dots: true,
            dotsClass: 'slick-dots',
            customPaging: function (slider, i) {
                return '<button type="button" aria-label="Go to slide ' + (i + 1) + '"></button>';
            },
            responsive: [
                {
                    breakpoint: 992,
                    settings: {
                        arrows: false,
                        centerMode: true,
                        centerPadding: '10px',
                        slidesToShow: 1
                    }
                },
                {
                    breakpoint: 768,
                    settings: {
                        arrows: true,
                        centerMode: false,
                        centerPadding: '10px',
                        slidesToShow: 1,
                        adaptiveHeight: true
                    }
                },
                {
                    breakpoint: 480,
                    settings: {
                        arrows: true,
                        centerMode: false,
                        centerPadding: '10px',
                        slidesToShow: 1,
                        adaptiveHeight: true
                    }
                }
            ]
        });
    }
</script>
</body>
</html>