/* Minification failed. Returning unminified contents.
(962,56-57): run-time error JS1014: Invalid character: `
(962,58-59): run-time error JS1193: Expected ',' or ')': {
(962,64-65): run-time error JS1014: Invalid character: `
(962,65-66): run-time error JS1004: Expected ';': )
(1273,64-65): run-time error JS1014: Invalid character: `
(1273,66-67): run-time error JS1193: Expected ',' or ')': {
(1273,72-73): run-time error JS1014: Invalid character: `
(1273,73-74): run-time error JS1004: Expected ';': )
(1274,10-11): run-time error JS1195: Expected expression: )
(1277,29-30): run-time error JS1004: Expected ';': {
(1886,20-21): run-time error JS1003: Expected ':': ,
(1886,26-27): run-time error JS1003: Expected ':': }
(3845,1-2): run-time error JS1002: Syntax error: }
 */
$(document).ready(function () {
    setTimeout(function () {
        setBgColors();
    }, 200);

    setTimeout(function () {
        setBgColors();
    }, 1000);

    setTimeout(function () {
        setBgColors();
    }, 2000);

    setTimeout(function () {
        setBgColors();
    }, 5000);
});

$(window).resize(function () {
    setBgColors();
});

var setBgColors = function () {
    $(".backgroundObj").each(function (i, val) {
        var valObj = $(val);
        var parent = $(val.parentElement);
        var theHeight = parent.height();
        valObj.css("height", theHeight + "px");
        parent.css("opacity", 1);
        valObj.css("opacity", 1);     
    });
};
;
let navbar = document.getElementById("stickyNav");

if (navbar !== undefined && navbar !== null) {
    window.onscroll = function () {
        fixedNav();
    };

    $(window).resize(function () {
        refreshWidth();
    });


    var navHeight = navbar.clientHeight;
    var bottom = document.getElementById("jsPageContent");
    var viewportOffset = bottom.getBoundingClientRect();
    var stop = (viewportOffset.height - 90) - navHeight;
    var productSection = $(".recommended-products-section");
    var navWidth = $(".article-nav").width();
    // navbar.style.width = navWidth + "px";

    if (productSection.length > 0) {
        stop = stop - productSection.height();
    }

    var sticky = navbar.parentElement.offsetTop - 90;

    function fixedNav() {
        var pageYOffset = window.pageYOffset;

        if (pageYOffset >= stop) {
            navbar.classList.add("bottom");

        }
        else {
            navbar.classList.remove("bottom");
        }

        if (pageYOffset >= sticky) {
            navbar.classList.add("sticky");
        } else {
            navbar.classList.remove("sticky");
        }
    }

    function refreshWidth() {
        navWidth = $(".article-nav").width();
        navbar.style.width = navWidth + "px";
    }

    // To make sure all content is fully loaded and every variable gets right values
    function refreshVariables() {
        navbar = document.getElementById("stickyNav");
        navHeight = navbar.clientHeight;
        bottom = document.getElementById("jsPageContent");
        viewportOffset = bottom.getBoundingClientRect();
        stop = (viewportOffset.height - 90) - navHeight;
        productSection = $(".recommended-products-section");

        navWidth = $(".article-nav").width();
        // navbar.style.width = navWidth + "px";

        if (productSection.length > 0) {
            stop = stop - productSection.height();
        }

        sticky = navbar.parentElement.offsetTop - 90;
    }

    $(document).ready(function () {
        refreshVariables();

        setTimeout(function () {
            refreshVariables();
        }, 200);

        setTimeout(function () {
            refreshVariables();
        }, 500);

        setTimeout(function () {
            refreshVariables();
        }, 1000);

        setTimeout(function () {
            refreshVariables();
        }, 1500);

        setTimeout(function () {
            refreshVariables();
        }, 2000);

        setTimeout(function () {
            refreshVariables();
        }, 5000);
    });

}

;

let isIe = isIE();

$(document).ready(function () {
    if (isIe) {
        objectFitImageIE();

        $('body').on("mousewheel", function () {
            // remove default behavior
            event.preventDefault();

            //scroll without smoothing
            var wheelDelta = event.wheelDelta;
            var currentScrollPosition = window.pageYOffset;
            window.scrollTo(0, currentScrollPosition - wheelDelta);
        });
    }

    setTimeout(function () {
        fadeOutByClass("jsFadeOut");
    }, 5000);

    calculate_time_zone();
});

var minutes;
function calculate_time_zone() {
    var rightNow = new Date();
    var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
    var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
    var temp = jan1.toGMTString();
    var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
    temp = june1.toGMTString();
    var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
    var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
    var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
    var dst;
    if (std_time_offset == daylight_time_offset) {
        dst = "0"; // daylight savings time is NOT observed
    } else {
        // positive is southern, negative is northern hemisphere
        //var hemisphere = std_time_offset - daylight_time_offset;
        //if (hemisphere >= 0)
            std_time_offset = daylight_time_offset;

        dst = "1"; // daylight savings time is observed
    }

    setCookie("ClientTimeZone", std_time_offset, 60);
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

// SendConfirmEmail from login modal
function sendConfirmEmail(e,nodeId) {
    e.preventDefault();
    let it;
    let email;
    if (nodeId != undefined && nodeId !== "") {
        it = $("#" + nodeId);
        email = it.attr("data-email");
    } else {
        it = $("#sendConfirmEmailId");
        const id = it.attr("data-id");
        email = $("#" + id).val();
    }
  
    const url = it.attr("data-url");

 
    const postUrl = url + "?email=" + email;

    it.addClass("disabled");

    $.ajax({
        method: "POST",
        url: postUrl,
        complete: function () {
            it.removeClass("disabled");
        }
    });
}


// Style all quotes same (Force-change parent to p)
$('q').each(function () {
    var quoteBlock = $(this),
        parent = quoteBlock.parent();
    parent.replaceWith(function () {
        return "<p>" + $(this).html() + "</p>";
    });
});

//Transform images to div with background image for IE
function objectFitImageIE() {
    $('.jsObject-fit-img').each(function () {
        var theImage = $(this),
            src = 'url(' + theImage.attr('src') + ')',
            parent = theImage.parent();
        // theImage.hide();
        parent.css({
            'background-size': 'cover',
            'background-repeat': 'no-repeat',
            'background-position': 'center',
            'background-image': src
        });
    });
}

function fadeOutByClass(className) {
    var fadeObjects = document.getElementsByClassName(className);

    var i;
    for (i = 0; i < fadeObjects.length; i++) {
        fadeObject(fadeObjects[i]);
    }
}
function fadeObject(obj) {
    var fadeTarget = obj;
    var fadeEffect = setInterval(function () {
        if (!fadeTarget.style.opacity) {
            fadeTarget.style.opacity = 1;
        }
        if (fadeTarget.style.opacity > 0) {
            fadeTarget.style.opacity -= 0.1;
        } else {
            clearInterval(fadeEffect);
        }
    }, 50);
}
;
$().ready(function () {
    $(".FormSubmitButton").on("click", function (e) {
        var inputField = $(".EpiForms-body > section .Form__Element.FormTextbox.ValidationRequired");
        var selectField = $(".EpiForms-body > section .Form__Element.FormSelection.ValidationRequired");

        // For input fields
        inputField.find(".FormTextbox__Input").each(function () {
            var fldId = $(this).attr('id');
            var fldName = $(this).attr('name');
            var inputCheck = $("#"+fldId).val().trim().length !== 0;
            var refId = 'epiFormInputErr'+fldName;
            var refErrContainerId = 'epiWrapErr'+fldName;

            if (!inputCheck) {
                $("#"+fldId).addClass('error');
                // adding exclamation (!) icon
                // use this if you are using id to check if exist
                // $("#"+refId).attr("style", "display: block");
                if( $("#"+refErrContainerId).length == 0 )         
                {
                    $("<i class='fas fa-exclamation icon' id='" + refErrContainerId + "' style='display: block' ></i>").insertAfter(this);
                }
            }
        });

        // For input validation error
        inputField.find(".Form__Element__ValidationError").each(function () {
            var fldId = $(this).attr('data-f-linked-name');
                fldId = "labelError" + fldId;
            $(this).attr('id', fldId);
        });

        // For select options
        selectField.find(".form-control").each(function () {
            var fldId = $(this).attr('id');
            var isMultiple = $(this).attr('multiple');
            var inputCheck = false;
            var val = $("#"+fldId).val();

            try {
                if (val.length > 0) {
                    inputCheck = true;
                }
            } catch(e) {}

            if (!inputCheck) {
                $("#"+fldId).addClass('error');
            }
        });

        // For select validation error
        selectField.find(".Form__Element__ValidationError").each(function () {
            var fldId = $(this).attr('data-f-linked-name');
                fldId = "labelError" + fldId;
            $(this).attr('id', fldId);
        });
    });

    EpiForms.init();
});

var EpiForms = {
    init: function () {
        $(".EPiServerForms").parent().addClass("row-flex center");
        $(".EPiServerForms").addClass("EpiForms-wrapper col-lg-10 col-md-12 col-sm-12 col-xs-12");
        $(".container .Form__Title").addClass("EpiForms-header col-xs-12"); 
        $(".container .Form__Description").addClass("EpiForms-description col-xs-12"); 
        $("div.Form__MainBody").addClass("EpiForms-body col-xs-12");
        $(".EpiForms-body > section .Form__Element").addClass("EpiForms-row col-xs-12 col-md-6");      
        $(".EpiForms-body > section .Form__Element .FormTextbox__Input").addClass("form-control");
        $(".EpiForms-body > section .Form__Element .Form__CustomInput").addClass("form-control");
        $(".EpiForms-body > section .Form__Element select").addClass("form-control");
        $(".EpiForms-body > section .FormChoice").removeClass("col-md-6");
        
        $(".EpiForms-body > section .FormResetButton").removeClass("col-md-6");
        $(".EpiForms-body > section .FormResetButton").removeClass("col-xs-12");
        $(".EpiForms-body > section .FormResetButton").wrap("<div class='EpiForms-submit col-xs-12'></div>");
        $(".EpiForms-body > section .Form__Element.FormResetButton").addClass("btn btnprimary");
        $(".EpiForms-body > section .Form__Element.FormResetButton").removeClass("disabled submitted");

        $(".EpiForms-body > section .FormSubmitButton").removeClass("col-md-6");
        $(".EpiForms-body > section .FormSubmitButton").removeClass("col-xs-12");
        $(".EpiForms-body > section .FormChoice").addClass("col-md-12");
        $(".EpiForms-body > section .FormSubmitButton").wrap("<div class='EpiForms-submit col-xs-12'></div>");
        $(".EpiForms-body > section .Form__Element.FormSubmitButton").addClass("btn btnprimary");
        $(".EpiForms-body > section .Form__Element.FormSubmitButton").removeClass("disabled submitted");
        $(".EpiForms-body > section .Form__Element.FormParagraphText").removeClass("col-md-6");
        $(".EpiForms-body > section .Form__Element.FormTextbox--Textarea").removeClass("col-md-6");
        $(".EpiForms-body > section .FormChoice").closest("a").css({ "text-align": "right" });
        $(".EpiForms-body > section .FormCaptcha").addClass(" col-md-push-3");
        $(".EpiForms-body > section .FormRecaptcha").removeClass("col-md-6");
        $(".EpiForms-body > section .FormRecaptcha").addClass("col-md-12");
        $(".contactUsPage").css({"display" : "block"});
        $(".EpiForms-body > section .Form__Element.FormChoice label").addClass("ChoiceBottomLine");
        $(".EpiForms-body > section .Form__Element.FormChoice legend").css({ "border-bottom": "none" });
        EpiForms.generateSubmitSpinnerButton();
        EpiForms.checkRequiredRadioButton();
        EpiForms.checkTextAndSelectField();
    },
    generateSubmitSpinnerButton: function () {
        var btn = $(".EpiForms-body > section .FormSubmitButton");
        var btnText = btn.html();
        btn.html("");
        btn.append('<span class="text">' + btnText + '</span><span class="spinner-conatiner"><span class="spinner"></span></span>');
        btn.addClass("spinner-btn");
    },
    checkRequiredRadioButton: function () {
        var form = $(".EpiForms-body > section .Form__Element.FormChoice.ValidationRequired");

        form.find(".Form__Element__Caption").each(function () {
            form.addClass('NoAfter');
            form.addClass('LegendValidationRequired');
        });
    },
    checkTextAndSelectField: function () {
        var inputF = $(".EpiForms-body > section .Form__Element.FormTextbox");
        var selectField = $(".EpiForms-body > section .Form__Element.FormSelection");
        var dateTimeField = $(".EpiForms-body > section .Form__Element.Form__CustomElement.FormDateTime");
        var inputFieldCustomAddress = $(".EpiForms-body > section .Form__Element.Form__CustomElement.FormAddressElement");

        inputF.find(".FormTextbox__Input").each(function () {
            inputF.addClass('inputText');
            var fldId = $(this).attr('id');
            var fldName = $(this).attr('name');

            $("#"+fldId).on("input", function (e) {
                e.stopPropagation();
                e.preventDefault();

                var inputEl = $(this);
                var inputCheck = inputEl.val().trim().length !== 0;
                var attrType = inputEl.attr("type");
                
                var refId = 'epiFormInput'+fldName;
                var refErrId = 'epiFormInputErr'+fldName;
                var refErrContainerId = 'epiWrapErr'+fldName;
                var refClearContainerId = 'epiWrapClear'+fldName;
                var labelErrorId = "labelError" + fldName;

                // use this if you are using id to check if exist
                if( $("#"+refId).length == 0 && attrType != "number")         
                {
                    $("<i class='fal fa-times icon' id='" + refId + "' style='display: none'></i>").insertAfter(this);
                    
                    $("#"+refId).on("click", function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        inputEl.val("");
                        $("#"+refId).attr("style", "display: none");
                    });
                }

                if (!inputCheck) {
                    if( $("#"+refId).length > 0 )         
                    {
                        $("#"+refId).attr("style", "display: none");
                    }
                } else {
                    $("#"+refErrContainerId).attr("style", "display: none");
                    $("#"+fldId).removeClass("error");
                    $("#"+labelErrorId).text("");

                    if( $("#"+refId).length > 0 )         
                    {
                        $("#"+refId).attr("style", "display: block");
                    }
                }
            });
        });

        // Custom Address Field
        inputFieldCustomAddress.find(".Form__CustomInput").each(function () {
            inputFieldCustomAddress.addClass('inputText');
            var fldId = $(this).attr('id');
            var fldName = $(this).attr('name');

            $("#"+fldId).on("input", function (e) {
                e.stopPropagation();
                e.preventDefault();

                var inputEl = $(this);
                var inputCheck = inputEl.val().trim().length !== 0;
                var attrType = inputEl.attr("type");
                
                var refId = 'epiFormInput'+fldId;
                var refErrId = 'epiFormInputErr'+fldName;
                var refErrContainerId = 'epiWrapErr'+fldName;
                var refClearContainerId = 'epiWrapClear'+fldName;
                var labelErrorId = "labelError" + fldName;

                // use this if you are using id to check if exist
                if( $("#"+refId).length == 0 && attrType != "number")         
                {
                    $("<i class='fal fa-times icon' id='" + refId + "' style='display: none'></i>").insertAfter(this);
                    
                    $("#"+refId).on("click", function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        inputEl.val("");
                        $("#"+refId).attr("style", "display: none");
                    });
                }

                if (!inputCheck) {
                    if( $("#"+refId).length > 0 )         
                    {
                        $("#"+refId).attr("style", "display: none");
                    }
                } else {
                    $("#"+refErrContainerId).attr("style", "display: none");
                    $("#"+fldId).removeClass("error");
                    $("#"+labelErrorId).text("");

                    if( $("#"+refId).length > 0 )         
                    {
                        $("#"+refId).attr("style", "display: block");
                    }
                }
            });
        });

        // For  selection
        selectField.find(".form-control").each(function (index) {
            var fldId = $(this).attr('id');
            var fldName = $(this).attr('name');
            var isMultiple = $(this).attr('multiple') ? true : false;
            var labelErrorId = "labelError" + fldName;
            var inputCheck = false;

            if (!isMultiple) {
                selectField.addClass('customSelect');
            } else {
                $(this).addClass('multiSelect');
            }

            $("#"+fldId).on("change", function (e) {
                var val = $("#"+fldId).val();

                try {
                    if (val.length > 0) {
                        inputCheck = true;
                    }
                } catch(e) {}
    
                if (inputCheck) {
                    $("#"+fldId).removeClass('error');
                    $("#"+labelErrorId).text("");
                }
            });
        });

        // For date time
        dateTimeField.find(".FormDateTime__Input").each(function () {
            var fldId = $(this).attr('id');
            var fldName = $(this).attr('name');

            var refId = 'epiDateTimeField' + fldName;
            var refCalendarContainerId = "epiCalendarWrap" + fldName;

            if( $("#"+refId).length == 0 )         
            {
                $("<i class='fad fa-calendar-day icon' id='" + refId + "'></i>").insertAfter(this);
            }
        });
    },
    wrapErrorField: function () {
        var inputF = $(".EpiForms-body > section .Form__Element.FormTextbox.ValidationRequired");

        inputF.find(".FormTextbox__Input").each(function () {
            var fldId = $(this).attr('id');

            $("#"+fldId).on("input", function (e) {
                e.stopPropagation();
                e.preventDefault();
                if (!inputCheck) {
                } else {
                    $("#"+fldId).addClass('error');
                }
            });
        });
    },
    formSubmit: function () {
        var submitBtn = $(".EpiForms-body > section .FormSubmitButton");

        var form = $(".EPiServerForms .Form__Element");
        let valid = true;

        form.find(".ValidationFail").each(function () {
            submitBtn.removeClass('disabled submitted');
            valid = false;
        });

        // Pass Submit status to Hotjar
        if (valid) {
            if (window.hj) { window.hj('formSubmitSuccessful'); }
        } else {
            if (window.hj) { window.hj('formSubmitFailed'); }
        }
    },
    formSubmitClick: function () {
        var submitBtn = $(".EpiForms-body > section .FormSubmitButton");

        var form = $(".EPiServerForms .Form__Element");
        let valid = true;

        form.find(".ValidationFail").each(function () {
            submitBtn.removeClass('disabled submitted');
            valid = false;
        });

        // Pass Submit status to Hotjar
        if (valid) {
            if (window.hj) { window.hj('formSubmitSuccessful'); }
        } else {
            if (window.hj) { window.hj('formSubmitFailed'); }
        }
    }
}    ;
$(document).ready(function() {
    var toggleSpeed = 200;

    $(".faq-wrap").hover(
        function(e) {
            $(this)
                .find(".faq-question")
                .addClass("isHover");
        },
        function(e) {
            $(this)
                .find(".faq-question")
                .removeClass("isHover");
        }
    );

    $(".faq-question").on("click", function() {
        var questionNode = $(this);
        var anwserNode = questionNode.parent().find(".faq-answer");
        var status = questionNode.data("status");
        var btn = questionNode.find(".glyphicon");

        if (status === "open") {
            questionNode.data("status", "closed");
            btn.removeClass("glyphicon-menu-up");
            btn.addClass("glyphicon-menu-down");
            anwserNode.slideUp(toggleSpeed);
        } else {
            questionNode.data("status", "open");
            btn.removeClass("glyphicon-menu-down");
            btn.addClass("glyphicon-menu-up");
            anwserNode.slideDown(toggleSpeed);
            clearSelection();
        }
    });
});

function clearSelection() {
    if (window.getSelection) {
        window.getSelection().removeAllRanges();
    } else if (document.selection) {
        document.selection.empty();
    }
}
;
var xDown = null;
var yDown = null;

var Carousel = {
    init: function () {
        var className = document.getElementsByClassName("carousel");
        for (var i = 0; i < className.length; i++) {
            className[i].addEventListener('touchstart', Carousel.handleTouchStart, false);
            className[i].addEventListener('touchmove', Carousel.handleTouchMove, false);
        }
    },
    handleTouchStart: function (evt) {
        xDown = evt.touches[0].clientX;
        yDown = evt.touches[0].clientY;
    },
    handleTouchMove: function (evt) {
        if (!xDown || !yDown) {
            return;
        }

        var xUp = evt.touches[0].clientX;
        var yUp = evt.touches[0].clientY;

        var xDiff = xDown - xUp;
        var yDiff = yDown - yUp;

        if (Math.abs(xDiff) > Math.abs(yDiff)) {/*most significant*/
            if (xDiff > 0) {
                $(".carousel").carousel("next");
                /* left swipe */
            } else {
                $(".carousel").carousel("prev");
                /* right swipe */
            }
        } else {
            if (yDiff > 0) {
                /* up swipe */
            } else {
                /* down swipe */
            }
        }
        /* reset values */
        xDown = null;
        yDown = null;
    }
}
Carousel.init();

$(document).ready(function () {
    updateCarouselImageUsage();
});

$(window).resize(function () {
    updateCarouselImageUsage();
});

var updateCarouselImageUsage = function()
{
    var isMobile = $(window).width() <= 511;
    $('.slide-wrap').children('.slide-full-mobile-img').each(function()
    {
        if (isMobile)
        {
            $(this).show();
            $(this).siblings('.slide-media').hide();
        }
        else
        {
            $(this).hide();
            $(this).siblings('.slide-media').show();
        }
    });
};
$(document).ready(function () {
    const logInModal = $(".logInModal");
    const mainMenu = $(".mainMenu");
    const logInModalWrapper = $(".logInModalWrapper");
    const body = document.querySelector('body');
    let logInModalIsActive = false;

    $(".signInButton").on("click", function (event) {
        logInModal.removeClass("hidden");
        logInModalIsActive = !logInModalIsActive;
        logInModal.addClass("visible");
        if (isMobile()) {
            mainMenu.addClass("hidden");
        }
        logInModalWrapper.addClass("visible");

        event.stopPropagation();

        const source = this.getAttribute("data-source");
        if (source == null || source != 'drawer') {
            if (logInModalIsActive) {
                $(document).click(function () {
                    logInModalIsActive = !logInModalIsActive;
                    logInModal.removeClass("visible");
                    logInModalWrapper.removeClass("visible");
                });

                $(".logInModal").click(function (event) {
                    event.stopPropagation();
                });
            }
        }

    });

    $(".closeModalButton").on("click", function () {
        logInModalIsActive = !logInModalIsActive;
        logInModal.removeClass("visible");
        logInModalWrapper.removeClass("visible");
        logInModal.removeClass("visible");
        if (isMobile()) {
            mainMenu.removeClass("hidden");
        }

        setTimeout(function () {
            logInModal.addClass("hidden");
            if (isMobile()) {
                mainMenu.addClass("visible");
            }
        }, 
            500);
    });

    $("body").click(function(){
        if (isMobile()) {
            mainMenu.removeClass("hidden");
        }
        
        setTimeout(function () {
            if (isMobile()) {
                mainMenu.addClass("visible");
            }
        }, 
            500);
    });

});

function isMobile() {
    var check = false;
    (function(a){
      if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) 
        check = true;
    })(navigator.userAgent||navigator.vendor||window.opera);
    
    return check;
};
;

$(".jsLinkContainer").on("click", function () {
    var me = $(this);

    me.toggleClass("open");
});;
$("#sendEmailLink").click(function (e) {
    e.preventDefault();
    $.ajax({
        url: $(this).attr("href"), // comma here instead of semicolon   
        async:true,
        success: function() {
           
        }
    });
});
;
$(document).ready(function () {
    var skipCount = 10;
    var takeCount = 10;
    var hasMoreRecords = true;
    var isFetching = false;
    var urlParams = new URLSearchParams(location.search);

    var sortBy = urlParams.get('sortBy');

    if (sortBy) {
        SelectElement("newsSortBy", sortBy);
    }

    function FetchDataFromServer() {
        if (!hasMoreRecords) {
            return;
        }
        var newsSortBySelect = document.getElementById("newsSortBy");
        var sortBy = newsSortBySelect.options[newsSortBySelect.selectedIndex].value;
        let eventSort = newsSortBySelect.getAttribute("data-eventSort");
        const isNews = newsSortBySelect.getAttribute("data-isNews");

        var urlParams = new URLSearchParams(location.search);

        var queryString = urlParams.get('q');
        $.ajax({
            url: UrlSettings.CurrentUrl + '/LoadMoreNews',
            data: {
                skip: skipCount,
                take: takeCount,
                sortBy: sortBy,
                eventSortBy: eventSort,
                q: queryString,
                isNews: isNews == "True"
            },
            method: 'POST',
            datatype: 'application/json',
            success: function (data) {
                if ($(data).filter('li.newsTeaser').length < takeCount) {
                    hasMoreRecords = false;
                    if ($('#fetchMore').length > 0) {

                        $("#fetchMore").hide();
                        var elem = document.getElementById('fetchMore');
                        elem.parentNode.removeChild(elem);
                    }
                }
                // If using group by month, these code snippet shall be used

                //var list = document.getElementsByClassName("groupMonth");
                //for (var i = 0, len = list.length; i < len; i++) {

                //    var test = $(data).find("[data-test='" + list[i].id + "'], data-test");
                //    var htmlObject = $(data);
                //    console.log(htmlObject);
                //    console.log($("li#" + list[i].id, htmlObject).id, 'selected element');
                //    var elementToRemove = $("#" + list[i].id, htmlObject);
                //    if (elementToRemove.length > 0) {
                //        console.log('removing child');
                //        data.removeChild(elementToRemove);
                //    }
                //}
                $("#newsList").append(data);
                isFetching = false;
                skipCount += takeCount; // update for next iteration
            },
            error: function () {
                alert("error");
            }
        });
    }
    $(window).on("scroll", function () {
        if ($('#fetchMore').length > 0) {

            var winHeight = $(window).height(); // viewport 
            if (($(window).scrollTop() + winHeight >= $("#fetchMore").position().top + 150) && !isFetching) {
                isFetching = true;
                FetchDataFromServer();
            }
        }
    });



    function SelectElement(id, valueToSelect) {
        var element = document.getElementById(id);
        element.value = valueToSelect;
    }

    $('#newsSearchInput').keypress(function (e) {
        var key = e.which;
        if (key == 13)  // the enter key code
        {
            $('#btnSearchNews').click();
        }
    });

    $("#newsSortBy").on('change', function () {
        triggerNewsSearch();
    });

    $('#btnSearchNews').on('click', function () {
        triggerNewsSearch(undefined, "FutureToPast");
    });

    $('#btnGetNews').on('click', function (e) {
        e.preventDefault();
        triggerNewsSearch();
    });

    $('#btnGetEvents').on('click', function (e) {
        e.preventDefault();
        triggerNewsSearch(true, "Basic");
    });

    function triggerNewsSearch(isEvent, eventOrder) {
        const querySearchNews = $('#newsSearchInput').val();
        const newsSortBySelect = document.getElementById("newsSortBy");
        const sortBy = newsSortBySelect.options[newsSortBySelect.selectedIndex].value;
        let isNews = newsSortBySelect.getAttribute("data-isNews");


        if (isEvent != undefined && isEvent) {
            isNews = false;
        }

        let evOrder = "Basic";
        if (eventOrder === "FutureToPast") {
            evOrder = eventOrder;
        }

        var searchPage = window.location.href.split('?')[0];
        searchPage += "?q=" + querySearchNews + "&sortBy=" + sortBy + "&eventSortBy=" + evOrder + "&isNews=" + isNews;

        window.location = searchPage;

    }
});;
$(document).ready(function() {
    var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
        acc[i].addEventListener("click", function () {
            this.classList.toggle("active");
            var panel = this.nextElementSibling;
            if (panel.style.maxHeight) {
                panel.style.maxHeight = null;
            } else {
                panel.style.maxHeight = panel.scrollHeight + "px";
            }
        });
    }
});;
$(document).ready(function () {
    function hasClass(ele, cls) {
        return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
    }

    // First we get the viewport height and we multiple it by 1% to get a value for a vh unit
    let vh = window.innerHeight * 0.01;
    // Then we set the value in the --vh custom property to the root of the document
    document.documentElement.style.setProperty('--vh', `${vh}px`);

    const retailersMaxCount = 25;
    const dealerLocatorContainer = $("#dealer-locator-container");

    const cultureData = dealerLocatorContainer.data("site-culture");

    const siteCulture = cultureData && cultureData.toLowerCase();
    const locationData = dealerLocatorContainer.data("default-location");
    const defaultLocation = locationData && locationData.toLowerCase();

    // Layout
    const SMALL = "small";
    const MEDIUM = "medium";

    var storeResultList = [];
    var selectedItemId = "";
    var isDefaultMobileView = true;
    var isFromSelectList = false;
    var isSemiViewMobile = false;
    var isFocus = false;
    var dealerLocatorMap;
    var isFromMarker = false;
    var isHrBarClicked = false;
    var isCompleteClick = false;
    var isSeeMore = false;
    var selectedStore = null;

    // MARKER
    let markerCluster;
    const markers = [];
    let markerStoreMap = [];

    var stores = [];
    var iconCircleLarge = '/Styles/Images/Icons/Sigvaris_Circle_lrg.svg';
    var iconCircle = '/Styles/Images/Icons/Sigvaris_Circle.svg';
    var selectedIconPin = '/Styles/Images/Icons/Sigvaris_Selected_Pin.svg';

    if (hasClass(document.getElementsByTagName("BODY")[0], "SigvarisGroup")) {
        iconCircleLarge = '/Styles/Images/Icons/SIG_GROUP_Circle_lrg.svg';
        iconCircle = '/Styles/Images/Icons/SIG_GROUP_Circle.svg';
        selectedIconPin = '/Styles/Images/Icons/SIG_GROUP_Selected_pin.svg';
    }

    //----------------------------------------------------------
    // Function that creates or generate unique id
    //----------------------------------------------------------
    function create_UUID(){
        var dt = new Date().getTime();
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = (dt + Math.random()*16)%16 | 0;
            dt = Math.floor(dt/16);
            return (c=='x' ? r :(r&0x3|0x8)).toString(16);
        });
        return uuid;
    }

    //-------------------------------------------------------------
    // Call this function to set to default mobile view layout
    //-------------------------------------------------------------
    function defaultMobileView() {
        setSearchContainerDefaultTop();

        seachLocatorContainerClassList(false);

        retailersFoundDisplay("none");
        showMobileResultList(false);
        resultListContainerDisplay("none");
        resetDefaultLabel();

        isDefaultMobileView = true;
        isSemiViewMobile = false;

        var searchContainer = document.getElementById("dealer-locator-search__container");
        searchContainer.classList.remove("dealer-locator-search__container__semiview");
        searchContainer.removeAttribute("style");
        
        // adjust the dealerLocatorMap height, to center the marker's position
        var dealerLocatorMapWrap = document.getElementById("dealerLocatorMap");
        dealerLocatorMapWrap.classList.remove("dealerLocatorMap__semiview");
        dealerLocatorMapWrap.classList.remove("dealerLocatorMap__fTop");

        var listContainer = document.getElementById("result-list-container");
        listContainer.classList.remove("scrollbar__compact_semiview");

        try {
            // filter seach container
            var filterSearch = document.getElementById("filter_search_container");
            filterSearch.style.display = "block";
        } catch(e) {

        }
    }

    // Mobile input result
    function showMobileResultList(isShow) {
        var searchWrap = document.getElementById("dealer-locator-search__container");

        if (isShow) {
            searchWrap.classList.add("dealer-locator-search__container__input_result");
        } else {
            searchWrap.classList.remove("dealer-locator-search__container__input_result");
        }
    }

    function setSearchContainerDefaultTop() {
        var searchContainer = document.getElementById("dealer-locator-search__container");
        var resultListContainer = document.getElementById("result-list-container");
        var top = 0;
        var adjust = 180;

        switch (window.innerHeight) {
            case 568:
              top = 385 + adjust;
              if (breakpoint() != SMALL) {
                resultListContainer.style.maxHeight = "55vh"; 
              }
              break;
            case 622:
              top = 440 + adjust;
              break;
            case 635:
              top = 639;
              if (breakpoint() != SMALL) {
                resultListContainer.style.maxHeight = "59vh"; 
              }
              break;
            case 667:
              top = 485 + adjust;
              if (breakpoint() != SMALL) {
                resultListContainer.style.maxHeight = "60vh"; 
              }
              break;
            case 719:
              top = 535 + adjust;
              if (breakpoint() != SMALL) {
                resultListContainer.style.maxHeight = "63vh"; 
              }
              break;
            case 736:
              top = 555 + adjust;
              if (breakpoint() != SMALL) {
                resultListContainer.style.maxHeight = "65vh"; 
              }
              break;
            case 812:
              top = 620 + adjust - 1; 
              if (breakpoint() != SMALL) {
                resultListContainer.style.maxHeight = "68vh"; 
              }
            default:
                if (breakpoint() != SMALL) {
                    resultListContainer.style.maxHeight = "50vh"; 
                }
        }
        
        if (top == 0) {
            // searchContainer.style.top = "calc((var(--vh, 1vh) * 100) - 2.3rem)";
        } else {
            searchContainer.style.top = top + "px";
        }
    }

    function noScroll() {
        window.scrollTo(0, 0);
    }

    function initSearchButtonsAndListeners() {
        setSearchContainerDefaultTop();

        // add listener to disable scroll in mobile
        if (breakpoint() == SMALL) {
            window.addEventListener('scroll', noScroll);
            var appContainer = document.getElementById("app-container");
                appContainer.style.overflow = "hidden";
        }
        
        // Remove listener to re-enable scroll
        // window.removeEventListener('scroll', noScroll);

        // Go Map Link on mobile view
        var goMapLink = document.getElementById('goMapLink');
        goMapLink.addEventListener("mousedown", function(e) {
            $('#addressInput').blur();
        });

        goMapLink.addEventListener("mouseover", function(e) {
            $('#addressInput').blur();
        });

        goMapLink.addEventListener("click", function (e) {
            e.stopPropagation();    
            e.preventDefault();
            isDefaultMobileView  = true;
            
            var searchContainer = document.getElementById("dealer-locator-search__container");
            searchContainer.removeAttribute("style");
            searchContainer.classList.remove("dealer-locator-search__container__onInput");

            var dealerLocatorMap = document.getElementById("dealerLocatorMap");
            dealerLocatorMap.classList.remove("dealerLocatorMap__fTop");

            defaultMobileView();
            setSearchContainerDefaultTop();

            if (isSemiViewMobile) {
                isSemiViewMobile = false;
            }

            try {
                var customZoom = document.getElementById("customZoom");
                customZoom.style.display = "block";
            } catch(e) {

            }

            return;
        });

        // Clear text input event 
        document.getElementById('dealerlocatorTimesIcon').addEventListener("click", function (e) {
            e.stopPropagation();    
            e.preventDefault();
            resetDealerLocator();
            return;
        });

        // Event for search icon
        document.getElementById('dealerlocatorSearchIcon').addEventListener("click", function (e) {
            e.stopPropagation();
            e.preventDefault();
            handleClickSearch();
            return;
        });

        // Go to current location
        document.getElementById('currentLocationBtn').addEventListener("click", function () {
            const infoWindow = new google.maps.InfoWindow;
            tryCreateYourPositionMarker(infoWindow);
        });

        // show on tab and mobile view
        var btnPanel = document.getElementById('btnDealerlocatorPanelIcon');
        btnPanel.addEventListener("click", function () {
            panelDisplay();
        });

        // mobile view adjust to semi view
        var mobilHrBar = document.getElementById("mobileHorizontalBar")
        mobilHrBar.addEventListener("mousedown", function(e) {
            $('#addressInput').blur();
        });

        mobilHrBar.addEventListener("mouseover", function(e) {
            $('#addressInput').blur();
        });

        mobilHrBar.addEventListener("click", function(e) {
            e.stopPropagation();
            e.preventDefault();

            if (!isCompleteClick) {
                $('#addressInput').blur();
            }

            var searchContainer = document.getElementById("dealer-locator-search__container");

            var dealerLocatorMap = document.getElementById("dealerLocatorMap");
            dealerLocatorMap.classList.remove("dealerLocatorMap__fTop");

            if ($("#dealer-locator-search__container").hasClass("dealer-locator-search__container__onInput")) {
                if (storeResultList.length < retailersMaxCount && storeResultList.length > 0) {
                    isHrBarClicked = true;

                    // from top most to semi view
                    searchContainer.classList.remove("dealer-locator-search__container__onInput");
                    searchContainer.classList.remove("dealer-locator-search__container__defaultFullTop");

                    resultListContainerDisplay("flex");
                    adjustSemiViewMobile();

                    isSemiViewMobile = true;
                    searchContainer.removeAttribute("style");
                }
                else {
                    // if no stores found then set to default view
                    defaultMobileView();
                }
            } else {
                searchContainer.removeAttribute("style");
                
                resultListContainerDisplay("block")
                setDefaultFullViewMobile();

                if ($("#dealer-locator-search__container").hasClass("dealer-locator-search__container__semiviewContentClicked")) {
                    searchContainer.classList.remove("dealer-locator-search__container__semiviewContentClicked");
                }

                isSemiViewMobile = false;
                isDefaultMobileView = false
            }
            return;
        });

        // Attaching the event listener function to window's resize event
        window.addEventListener("resize", function () {
            handleResize();

            // We listen to the resize event
            // We execute the same script as before
            let vh = window.innerHeight * 0.01;
            document.documentElement.style.setProperty('--vh', `${vh}px`);
        });
    }

    function handleResize() {
        var hrBar = document.getElementById('mobileHorizontalBar');
        var goMapLink = document.getElementById('goMapLink');
        var listContainer = document.getElementById('result-list-container');
        var searchContainer = document.getElementById("dealer-locator-search__container");
        
        if (breakpoint() === SMALL) {
            // if there's a result then fullviewmobile
            if (storeResultList.length > 0) {
                searchContainer.classList.add("dealer-locator-search__container__onInput");

                if (isHrBarClicked) {
                    setDefaultFullViewMobile();
                    isSemiViewMobile = false;
                    isDefaultMobileView = false
                }
                
                hrBar.style.display = "block";
                hrBar.classList.add("mobile_horizontal_bar__mt");
                hrBar.classList.add("mobile_horizontal_bar");
            }
        } else {
            hrBar.style.display = "none";
            hrBar.classList.remove("mobile_horizontal_bar__mt");
            hrBar.classList.remove("mobile_horizontal_bar");

            goMapLink.style.display = "none";
            goMapLink.classList.remove("go_map_link__onInput");

            resultListContainerDisplay("block");
            listContainer.classList.remove("scrollbar__compact_semiview");
            listContainer.classList.remove("active");
            searchContainer.classList.remove("dealer-locator-search__container__semiviewContentClicked");

            searchContainer.classList.remove("dealer-locator-search__container__onInput");
            searchContainer.removeAttribute("style");

            try {
                if (storeResultList.length > 0) {
                    for (var i = 0; i < storeResultList.length; i++) {
                        const divId = storeResultList[i].MarkerIndex + "-" + storeResultList[i].Guid;
                        
                        var seeMoreLink = document.getElementById("seeMoreLink"+divId);
                        var itemArea = document.getElementById("itemArea"+divId);
                        var itemWrapper = document.getElementById("wrapper"+divId);
    
                        seeMoreLink.display.style = "none";
                        itemArea.classList.remove("dealerLocatorResult__area_semiview");
                        itemWrapper.classList.remove("dealerLocatorResult__wrapper_semiview");
                    }
                }
            }
            catch(e) {

            }
        }
    }

    function panelDisplay() {
        var searchInputWrap = document.getElementById('div-search-input__wrap');
        var iconPanel = document.getElementById('icon-panel');
        var btnPanel = document.getElementById('btnDealerlocatorPanelIcon');

        if ($("#btnDealerlocatorPanelIcon").hasClass("active")) {
            iconPanel.classList.remove("fa-chevron-left");
            iconPanel.classList.add("fa-chevron-right");
            searchInputWrap.classList.add("search-input__wrap__collapse");
            searchInputWrap.classList.remove("search-input__wrap__expand");
            btnPanel.classList.remove("active");
        } else {
            iconPanel.classList.remove("fa-chevron-right");
            iconPanel.classList.add("fa-chevron-left");

            searchInputWrap.classList.remove("search-input__wrap__collapse");
            btnPanel.classList.add("active");
            searchInputWrap.classList.add("search-input__wrap__expand");
        }
    }

    //////////////////////////////////////
    // SEMI VIEW
    //////////////////////////////////////
    function adjustSemiViewMobile() {
        try {
            // filter seach container
            var filterSearch = document.getElementById("filter_search_container");
            filterSearch.style.display = "none";
        } catch(e) {

        }

        var mapLink = document.getElementById("goMapLink");
        mapLink.style.display = "none";

        var retailerFound = document.getElementById("div-retailersFound");
        retailerFound.style.display = "none";

        var searchTextLabel = document.getElementById("div-search-textLabel");
        searchTextLabel.style.display = "none";
        searchTextLabel.classList.remove("search-textLabel__mount");

        var searchContainer = document.getElementById("dealer-locator-search__container");
        searchContainer.classList.add("dealer-locator-search__container__semiview");

        var resultListContainer = document.getElementById("result-list-container");
        resultListContainer.classList.add("scrollbar__compact_semiview");

        var listContainerWrapper = document.getElementById("listContainerWrapper");
        listContainerWrapper.style.marginTop = "1rem";
        listContainerWrapper.classList.add("list-container-wrapper__semiview");

        semiViewWidthAreaClasslist(false);

        // adjust the dealerLocatorMap height, to center the marker's position
        var dealerLocatorMapWrap = document.getElementById("dealerLocatorMap");
        dealerLocatorMapWrap.classList.add("dealerLocatorMap__semiview");
        dealerLocatorMapWrap.classList.add("dealerLocatorMap__fTop");

        if (selectedItemId !== "") {
            var itemArea = document.getElementById("itemArea"+selectedItemId);
            
            try {
                itemArea.scrollIntoView({
                    behavior: "auto", 
                    inline: "center"
                });
            } catch(e) {

            }
        } 

        var customZoom = document.getElementById("customZoom");
        customZoom.style.display = "none";
    }

    function semiViewWidthAreaClasslist(isRemove) {
        for (var i = 0; i < storeResultList.length; i++) {
            const divId = storeResultList[i].MarkerIndex + "-" + storeResultList[i].Guid;
            semiViewItem(isRemove, divId, false);
        }
    }

    function semiViewItem(isRemove, divId, hideSeeMore) {
        var seeMoreLink = document.getElementById("seeMoreLink" + divId);
        var itemArea = document.getElementById("itemArea" + divId);
        var itemWrapper = document.getElementById("wrapper" + divId);

        var collapseDown = document.getElementById("collapsableDown"+divId);
        var collapseUp = document.getElementById("collapsableUp"+divId);

        var addressSytle1 = document.getElementById("addressStyle1"+divId);
        var addressSytle2 = document.getElementById("addressStyle2"+divId);
        var detailArea = document.getElementById("detailArea"+divId);

        try {
            if (!hideSeeMore) {
                if (selectedItemId !== "" && selectedItemId === divId) {
                    if (isRemove) {
                        seeMoreLink.style.display = "none";
                        detailArea.style.display = "block";
                    } else {
                        seeMoreLink.style.display = "block";
                        detailArea.style.display = "none";
                    }
                } else {
                    // fullview
                    if (isRemove) {
                        seeMoreLink.style.display = "none";
                    } else {
                    // semi view
                        seeMoreLink.style.display = "block";
                        detailArea.style.display = "none";
                    }
                }
            } else {
                seeMoreLink.style.display = "none";
            }
            
            if (isRemove) {
                // Full view
                collapseDown.style.cursor="pointer";
                itemArea.classList.remove("dealerLocatorResult__area_semiview");
                itemWrapper.classList.remove("dealerLocatorResult__wrapper_semiview");
                seeMoreLink.style.display = "none";

                if (selectedItemId !== "" && selectedItemId === divId) {
                    collapseDown.style.display="none";
                    collapseUp.style.display="block";
                    
                } else {
                    addressSytle1.style.display = "block";
                    addressSytle2.style.display = "none";

                    collapseDown.style.display="block";
                    collapseUp.style.display="none";    
                }
            } else {
                itemArea.classList.add("dealerLocatorResult__area_semiview");
                itemWrapper.classList.add("dealerLocatorResult__wrapper_semiview");

                addressSytle1.style.display = "none";
                addressSytle2.style.display = "flex";

                collapseDown.style.display="none";
                collapseUp.style.display="none";
            }
        } catch(e) {

        }
    }

    //-----------------------------------------------------------------
    // Function that handles the semi view item style display
    //-----------------------------------------------------------------
    function semiViewItemStyleDisplay(divId, isReset) {
        var detailArea = document.getElementById("detailArea"+divId);
        var seeMoreLink = document.getElementById("seeMoreLink"+divId);

        try {
            if (isSemiViewMobile) {
                detailArea.style.display = "none";
                seeMoreLink.style.display = "block";
                // if (!isReset) {
                //     if (detailArea.style.display === "none") {
                //         detailArea.style.display = "flex";
                //         seeMoreLink.style.display = "none";
                //     } else {
                //         detailArea.style.display = "none";
                //         seeMoreLink.style.display = "block";
                //     }
                // } else {
                //     detailArea.style.display = "none";
                //     seeMoreLink.style.display = "block";
                // }
            } else {
                seeMoreLink.style.display = "none";
            }
        } catch(e) {

        }
    }
    //////////////////////////////////////
    // END OF SEMI VIEW
    //////////////////////////////////////

    //////////////////////////////////////
    // MOBILE FULL VIEW
    //////////////////////////////////////
    function setDefaultFullViewMobile() {
        fullViewMobile();
        seachLocatorContainerClassList(true);
    }

    function fullViewMobile() {
        // filter seach container
        try {
            var filterSearch = document.getElementById("filter_search_container");
            filterSearch.style.display = "block";
        } catch(e) {

        }

        var mapLink = document.getElementById("goMapLink");
        mapLink.style.display = "block";

        var searchContainer = document.getElementById("dealer-locator-search__container");
        searchContainer.classList.remove("dealer-locator-search__container__semiview");

        var resultListContainer = document.getElementById("result-list-container");
        resultListContainer.classList.remove("scrollbar__compact_semiview");

        var retailerFound = document.getElementById("div-retailersFound");
        var searchTextLabel = document.getElementById("div-search-textLabel");

        // adjust the dealerLocatorMap height, to center the marker's position
        var dealerLocatorMapWrap = document.getElementById("dealerLocatorMap");
        dealerLocatorMapWrap.classList.remove("dealerLocatorMap__semiview");

        var storesFoundLen = 0;

        if (storeResultList.length < retailersMaxCount && storeResultList.length > 0) {
            // show only if less than the dealer cap
            storesFoundLen = storeResultList.length;
        } 
        
        if (storesFoundLen > 0) {
            retailerFound.style.display = "block";
            searchTextLabel.style.display = "none";
        } else {
            retailerFound.style.display = "none";
            searchTextLabel.style.display = "block";
        }

        var listContainerWrapper = document.getElementById("listContainerWrapper");
        listContainerWrapper.style.marginTop = "0";
        listContainerWrapper.classList.remove("list-container-wrapper__semiview");

        // from semi view to full view
        semiViewWidthAreaClasslist(true);

        if (isHrBarClicked) {
            if (isSemiViewMobile) {
                if (isFromSelectList || isFromMarker) {
                    searchContainer.style.marginRight = "-16px";
                } 
            }
            resultListContainerDisplay("block");
        } 
    
        dealerLocatorMapWrap.classList.add("dealerLocatorMap__fTop");

        if (isFromMarker) {
            searchContainer.removeAttribute("style");
            if (selectedItemId != "") {
                scrollParentToChild(selectedItemId);
            }
        }

        // remove the define top if on full view 
        searchContainer.removeAttribute("style");
    }

    ////////////////////////////
    // CLASSLIST
    ////////////////////////////

    // Mobile
    function seachLocatorContainerClassList(isAdd) {
        if (breakpoint() == SMALL) {
            var searchLocatorContainer = document.getElementById("dealer-locator-search__container");
            var goMapLink = document.getElementById("goMapLink");
            var mobileHr = document.getElementById("mobileHorizontalBar");

            if (isAdd) {
                searchLocatorContainer.classList.add("dealer-locator-search__container__onInput");

                goMapLink.style.display = "block";
                goMapLink.classList.add("go_map_link__onInput");
                mobileHr.classList.add("mobile_horizontal_bar__mt");
                searchTextLabelClassList(true);
            } else {
                searchLocatorContainer.classList.remove("dealer-locator-search__container__onInput");

                goMapLink.classList.remove("go_map_link__onInput");
                goMapLink.style.display = "none";
                mobileHr.classList.remove("mobile_horizontal_bar__mt");
                searchTextLabelClassList(false);
            }
        }
    }

    /////////////////////////////////////
    // CLASS LIST FOR Search Text Label
    /////////////////////////////////////
    function searchTextLabelClassList(isAdd) {
        var searchTextLabel = document.getElementById("div-search-textLabel");
        if (isAdd) {
            searchTextLabel.classList.remove("search-textLabel__unmount");
            searchTextLabel.classList.add("search-textLabel__mount");

            if (storeResultList.length > 0) {
                searchTextLabel.classList.remove("search-textLabel__mount");    
            } else {
                searchTextLabel.classList.add("search-textLabel__mount");
            }
        } else {
            searchTextLabel.classList.add("search-textLabel__unmount");
            searchTextLabel.classList.remove("search-textLabel__mount");
        }
    }

    ////////////////////////////
    // SCROLLBAR
    ////////////////////////////
    function resultListContainerClassList(isAdd) {
        var resultListContainer = document.getElementById("result-list-container");
        
        if (isAdd) {
            if (!resultListContainer.classList.contains("scrollbar__compact")) {
                resultListContainer.classList.add("scrollbar__compact");
            }
            // this is for mobile view
            resultListContainer.classList.remove("scrollbar__none");
        } else {
            resultListContainer.classList.remove("scrollbar__compact");
            
            if (!resultListContainer.classList.contains("scrollbar__none")) {
                // this is for mobile view
                resultListContainer.classList.add("scrollbar__none");
            }
        }
    }

    ////////////////////////////
    // BREAKPOINT
    ////////////////////////////
    function breakpoint () {
        const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
        const XL_MEDIUM = 1024;
        const L_MEDIUM = 992;
        const SMALL = 767;
        const X_SMALL = 511;
        const MEDIUM = 768;
        var dealerLocScreenSize="large";

        if (viewportWidth > XL_MEDIUM) {
            dealerLocScreenSize="xlmedium";
        } else if (viewportWidth > L_MEDIUM && viewportWidth <= XL_MEDIUM) {
            dealerLocScreenSize="lmedium";
        }
        else if (viewportWidth > SMALL && viewportWidth < L_MEDIUM) {
            dealerLocScreenSize="medium";
        } else if (viewportWidth < X_SMALL) {
            dealerLocScreenSize="small";
        } 

        return dealerLocScreenSize;
    }

    ////////////////////////////
    // Google Map Zoom Control
    ////////////////////////////
    function zoomControlPosition(controlDiv, map) {
        // Creating divs & styles for custom zoom control
        controlDiv.style.padding = '5px';

        // Set CSS for the control wrapper
        var controlWrapper = document.createElement('div');
        controlDiv.appendChild(controlWrapper);
        
        // Set CSS for the zoomIn
        var zoomInButton = document.createElement('div');
        zoomInButton.setAttribute("class", "custom-zoom__plus");

        controlWrapper.setAttribute("class", "custom-zoom__wrapper");
        controlWrapper.setAttribute("id", "customZoom");
        controlWrapper.appendChild(zoomInButton);

         // Set CSS for the divider 
         var zoomDivider = document.createElement('div');
         zoomDivider.setAttribute("class", "custom-zoom__divider");

         controlWrapper.appendChild(zoomDivider);
            
        // Set CSS for the zoomOut
        var zoomOutButton = document.createElement('div');
        zoomOutButton.setAttribute("class", "custom-zoom__minus ");

        controlWrapper.appendChild(zoomOutButton);

        // Setup the click event listener - zoomIn
        google.maps.event.addDomListener(zoomInButton, "click", function() {
            handleClickZoomControl(map, true);
        });
            
        // Setup the click event listener - zoomOut
        google.maps.event.addDomListener(zoomOutButton, "click", function() {
            handleClickZoomControl(map, false);
        });
    }

    ////////////////////////////////////
    // Handle Google Map Zoom Control
    ////////////////////////////////////
    function handleClickZoomControl(map, isPlus) {
        isHrBarClicked = false;
        isSemiViewMobile = false;
        isCompleteClick = false;
        isSeeMore = false;
        selectedItemId = "";
        selectedStore = null;
        resetCheckboxFilters();
        getSelectedFilters();

        if (isPlus) {
            map.setZoom(map.getZoom() + 1);
        } else {
            map.setZoom(map.getZoom() - 1);
        }

        showVisibleMarkersRetailersFound(dealerLocatorMap, markerStoreMap);

        if (breakpoint() === SMALL) {
            defaultMobileView();
        }
        
        isFromSelectList = false;
    }

    ///////////////////////////////////////////
    // ---                               --- //
    ///////////////////////////////////////////
    $('.carousel[data-type="multi"] .item').each(function () {
        var next = $(this).next();
        if (!next.length) {
            next = $(this).siblings(':first');
        }
        next.children(':first-child').clone().appendTo($(this));

        for (var i = 0; i < 4; i++) {
            next = next.next();
            if (!next.length) {
                next = $(this).siblings(':first');
            }

            next.children(':first-child').clone().appendTo($(this));
        }
    });

    //-------------------------------------------------------
    // Handle reset dealer locator
    //-------------------------------------------------------
    function resetDealerLocator() {
        document.getElementById("addressInput").value = "";
        appendDealerUrl(null, "");
        resetVar();
        
        var location = getDefaultPositionAndZoom();
        var zoom = location.zoom;
        var pos = location.pos;

        dealerLocatorMap.setZoom(zoom);
        dealerLocatorMap.setCenter(pos);

        if (breakpoint() == SMALL) {
            var searchContainer = document.getElementById("dealer-locator-search__container");
            var dealerLocatorMapContainer = document.getElementById("dealerLocatorMap");

            searchContainer.removeAttribute("style");
            defaultMobileView();
            var dealerLocatorContainer = document.getElementById("dealer-locator-container");

            dealerLocatorContainer.classList.remove("dealer-locator-container__semiview");
            searchContainer.removeAttribute("style");

            dealerLocatorMapContainer.classList.remove("dealerLocatorMap__fTop");
        }

        handleResize();
        handleSearchIcons(true, false);
        setSearchContainerDefaultTop();

    }
    
    function getDefaultPositionAndZoom() {
        var pos = { lat: 37.887638, lng: -92.853439 }
        var zoom = 5;

        // https://developers.google.com/public-data/docs/canonical/countries_csv
        if (defaultLocation === "en-ca" || defaultLocation === "fr-ca" || defaultLocation === "ca") {
            pos = { lat: 55.1858411, lng: -116.417535 };
            zoom = 4;
        }
        else if (defaultLocation === "es-mx" && siteCulture === "es") {
            // South american view
            pos = { lat: -15.3380065, lng: -59.241489 };
            zoom = 4;
        }
        else if (defaultLocation === "es-mx" || defaultLocation === "mx") {
            pos = { lat: 23.3144669, lng: -111.636982 };
        }
        else if (defaultLocation === "fr-fr" || defaultLocation === "fr") {
            pos = { lat: 47.203554, lng: 2.325589 };
            zoom = 6;
        }
        else if (defaultLocation === "pt-br" || defaultLocation === "br") {
            pos = { lat: -14.399227, lng: -47.050548 };
        }
        else if (defaultLocation === "ru-ru" || defaultLocation === "ru") {
            pos = { lat: 60.343327, lng: 63.490280 };
        }
        else if (defaultLocation === "de-ch" || defaultLocation === "fr-ch") {
            pos = { lat: 46.818188, lng: 8.227512 };
            zoom = 7;
        }
        else if (defaultLocation === "de-de") {
            pos = { lat: 51.165691, lng: 10.451526 };
            zoom = 6;
        }
        else if (defaultLocation === "de-at") {
            pos = { lat: 47.516231, lng: 14.550072 };
            zoom = 7;
        }
        else if (defaultLocation === "pl-pl") {
            pos = { lat: 51.919438, lng: 19.145136 };
            zoom = 6;
        }
        else if (defaultLocation === "zh-cn" || defaultLocation === "zh") {
            pos = { lat: 35.86166, lng: 104.195397 };
            zoom = 4;
        }
        else if (defaultLocation === "en-au") {
            pos = { lat: -25.274398, lng: 133.775136 };
            zoom = 4;
        }
        else if (defaultLocation === "it-it") {
            pos = { lat: 41.87194, lng: 12.56738 };
            zoom = 6;
        }
        else if (defaultLocation === "en-gb") {
            pos = { lat: 55.378051, lng: -3.435973 };
            zoom = 6;
        }
        else if (defaultLocation === "en-ch") {
            // World view
            pos = { lat: 46.818188, lng: 8.227512 };
            zoom = 2;
        }

        return {pos, zoom};
    }

    function init() {
        initSearchButtonsAndListeners();
        handleResize();
        setSearchContainerDefaultTop();

        var location = getDefaultPositionAndZoom();
        var zoom = location.zoom;
        var pos = location.pos;
        
        var mapOptions = {
            zoom: zoom,
            center: pos,
            zoomControl: false,
            zoomControlOptions: {
                position: google.maps.ControlPosition.RIGHT_TOP,
            },
            mapTypeControl: false,
            scaleControl: false,
            streetViewControl: false,
            rotateControl: false,
            fullscreenControl: false,
            styles: [
                {
                    "featureType": "water",
                    "elementType": "geometry",
                    "stylers": [{ "color": "#e9e9e9" }, { "lightness": 17 }]
                },
                {
                    "featureType": "landscape",
                    "elementType": "geometry",
                    "stylers": [{ "color": "#f5f5f5" }, { "lightness": 20 }]
                }, {
                    "featureType": "road.highway",
                    "elementType": "geometry.fill",
                    "stylers": [
                        { "color": "#ffffff" }, { "lightness": 17 }
                    ]
                }, {
                    "featureType": "road.highway",
                    "elementType": "geometry.stroke",
                    "stylers": [{ "color": "#ffffff" }, { "lightness": 29 }, { "weight": 0.2 }]
                },
                {
                    "featureType": "road.arterial",
                    "elementType": "geometry",
                    "stylers": [{ "color": "#ffffff" }, { "lightness": 18 }]
                }, {
                    "featureType": "road.local",
                    "elementType": "geometry",
                    "stylers": [
                        {
                            "color": "#ffffff"
                        }, { "lightness": 16 }
                    ]
                },
                {
                    "featureType": "poi",
                    "elementType": "geometry",
                    "stylers": [{ "color": "#f5f5f5" }, { "lightness": 21 }]
                }, {
                    "featureType": "poi.park",
                    "elementType": "geometry",
                    "stylers": [
                        { "color": "#dedede" }, { "lightness": 21 }
                    ]
                },
                {
                    "elementType": "labels.text.stroke",
                    "stylers": [{ "visibility": "on" }, { "color": "#ffffff" }, { "lightness": 16 }]
                }, {
                    "elementType": "labels.text.fill",
                    "stylers": [
                        { "saturation": 36 }, { "color": "#333333" }, { "lightness": 40 }
                    ]
                }, { "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, {
                    "featureType": "transit",
                    "elementType": "geometry",
                    "stylers": [
                        {
                            "color": "#f2f2f2"
                        }, { "lightness": 19 }
                    ]
                },
                {
                    "featureType": "administrative",
                    "elementType": "geometry.fill",
                    "stylers": [{ "color": "#fefefe" }, { "lightness": 20 }]
                }, {
                    "featureType": "administrative",
                    "elementType": "geometry.stroke",
                    "stylers": [{ "color": "#fefefe" }, { "lightness": 17 }, { "weight": 1.2 }]
                }
            ]
        };
        
        const mapDiv = document.getElementById('dealerLocatorMap');
        dealerLocatorMap = new google.maps.Map(mapDiv, mapOptions);

        initMap(dealerLocatorMap);
        initSearch();
        loadAllDealerLocators(siteCulture, 0, function() {
            // Do a search if addressInput has value
            handleClickSearch();
        },
        function(error) {
            console.log(error);
        });
    }

    /*
     * ##########################################
     * ##########################################
     * 
     * Store
     * 
     * ##########################################
     * ##########################################
     */

    let visibleStores = [];

    function getVisibleStores() {
        return visibleStores;
    }

    function updateVisibleStores(filters) {
        if (filters == null) {
            filters = getSelectedFilters();
        }

        visibleStores = getFilteredStores(stores, filters);
    }

    function addStores(newStores) {
        for (var i = 0; i < newStores.length; i++) {
            const city = newStores[i].City;
            const locationName = newStores[i].LocationName;

            var searchValue = locationName.trim() + ", " + city.trim();
            var store = newStores[i];
            store.normalizedValue = normalizeString(searchValue.toLowerCase());

            var storeFilters = [];

            if (store.Filters)
            {
                storeFilters.push.apply(storeFilters, store.Filters.split(','));
            }

            store.storeFilters = storeFilters.map(function(f) { return f.trim(); });

            store.MarkerIndex = i;
            store.Guid = create_UUID();
            stores.push({
                value: newStores[i].LocationName,
                data: store,
            });
        }

        updateVisibleStores();
    }

    function loadAllDealerLocators(siteCulture, next, successCb, errorCb) {
        const batchSize = 1000;

        var intSuccessCb = function(stores) {
            try {
                if (stores == null || stores.length == 0) {
                    successCb();
                }
                
                addStores(stores);
                addMarkersFromStores(stores);
    
                // Continue fetching
                if (stores.length >= batchSize) {
                    loadAllDealerLocators(siteCulture, next + batchSize, successCb, errorCb);
                }
                else
                {
                    successCb();
                }
            }
            catch (error) {
                errorCb(error);
            };
        }

        setTimeout(function() { fetchDealerLocators(siteCulture, batchSize, next, intSuccessCb, errorCb) }, 0);
    }

    function fetchDealerLocators(siteCulture, batchSize, start, successCb, errorCb) {
        const url = '/DealerLocatorPage/GetStores?siteCulture=' + siteCulture + '&start=' + start + '&take=' + batchSize;
        $.ajax({
            type: "GET",
            url: url,
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                successCb((result && result.slice()) || []);
            },
            error: function (xhr, status, error) {
                errorCb(error);
            }
        });
    }

    /*
     * ##########################################
     * ##########################################
     * 
     * Search filters
     * 
     * ##########################################
     * ##########################################
     */

    function getFilteredStores(stores, filters) {
        if (filters != null && filters.length > 0) {
            return stores.filter(function (dealerLocator) {
                return isStoreInFilter(dealerLocator.data, filters);
            });
        }

        return stores;
    }

    function isStoreInFilter(store, filters) {
        if (filters == null || filters.length == 0) {
            return true;
        }

        if (store == null) {
            return false;
        }

        var storeFilters = store.storeFilters;

        if (storeFilters.length > 0) {
            return storeFilters.some(function (storeFilter) {
                return filters.some(function (filter) {
                    return filter === storeFilter;
                });
            });
        }
    }

    function getSelectedFilters() {
        var selectedFilters = [];
        var checkboxFilters = getCheckboxFilters();
        var queryFilters = getQueryFilters();
        selectedFilters.push.apply(selectedFilters, checkboxFilters);
        selectedFilters.push.apply(selectedFilters, queryFilters);

        // console.log("getSelectedFilters", checkboxFilters,selectedFilters );
        return selectedFilters;
    }

    function getCheckboxFilters() {
        var selectedFilters = [];
        $("input.dealerLocatorFilterInput").each(function () {
            var filter = $(this);
            if (filter[0].checked) {
                selectedFilters.push(filter.attr("data-filter"));
            }
        });

        return selectedFilters;
    }

    function resetCheckboxFilters() {
        $("input.dealerLocatorFilterInput").each(function () {
            var filter = $(this);
            if (filter[0].checked) {
                $(this).click();
            }
        });
    }

    var queryFilters = null;
    function getQueryFilters() {
        if (queryFilters == null)
        {
            queryFilters = [];
            var url = new URLSearchParams(location.search);
            queryFilters = url.getAll("f");

            queryFilters = queryFilters.map(function(f)
            {
                return f.toLowerCase();
            });
        }
        
        return queryFilters;
    }

    $(".dealerLocatorFilterInput").on("change", function () {
        setTimeout(function () {
            const filters = getSelectedFilters();
            // console.log("dealerLocatorFilterInput", filters);
            updateVisibleStores(filters);
            updateVisibleMarkersFromFilter(filters);
            showVisibleMarkersRetailersFound(dealerLocatorMap, markerStoreMap)
        }, 0);
    });

    /*
     * ##########################################
     * ##########################################
     * 
     * Markers
     * 
     * ##########################################
     * ##########################################
     */

    function initMarkerCluster() {
        var mcOptions = {
            styles: [
                {
                    height: 58,
                    url: iconCircleLarge,
                    width: 58,
                    textSize: 20,
                    textColor: "#FFFFFF"
                }],
            maxZoom: 14,
            ignoreHidden: true,
        };

        markerCluster = new MarkerClusterer(dealerLocatorMap, [], mcOptions);
    }

    function addMarkersFromStores(stores) {
        var filters = getSelectedFilters();
        var newMarkerStoreMap = [];
        var newMarkers = stores.map(function (store) {
            var marker = new google.maps.Marker({
                position: { lng: Number(store.Longitude), lat: Number(store.Latitude) },
                icon: iconCircle,
                title: store.LocationName + "(" + store.LocationId + ")",
                locationName: store.LocationName,
                city: store.City,
                address1: store.Address1,
                country: store.Country,
                visible: isStoreInFilter(store, filters),
            });

            marker.addListener("click", function (e) {
                appendDealerUrl(null, store.LocationName + ", " + store.City + " " + store.Country);

                // Will only allow to display information list if less than or equal to retailer max
                if (storeResultList.length <= retailersMaxCount && storeResultList.length > 0) {
                    resetMarkerIcons();

                    isFromMarker = true;

                    // override marker index to allow duplicate lang and lat - hack fixed
                    if (isFromSelectList && store != selectedStore) {
                        store = selectedStore;
                    }

                    const divId = store.MarkerIndex + "-" + store.Guid;
                    displayCardInfoOnClickMarker(store, divId, marker);
                    
                    if (!isSemiViewMobile) {
                        scrollParentToChild(divId);
                    } else {
                        if (breakpoint() == SMALL) {
                            try {
                                var itemArea = document.getElementById("itemArea"+divId);
                                itemArea.scrollIntoView({
                                    behavior: "auto", 
                                    inline: "center"
                                });
                            } catch(e) {

                            }
                        }
                    }
                } else {
                    // Display card info from marker click with more than dealers
                    resetMarkerIcons();
                    $('.dealerLocatorResult__wrapper').remove();
                    const divId = store.MarkerIndex + "-" + store.Guid;
                    handleCreateDealerListResult(store, divId);
                    displayCardInfoOnClickMarker(store, divId, marker);
                }
            });

            newMarkerStoreMap.push({ marker: marker, store: store });
            return marker;
        });

        addMarkersToCluster(newMarkers, newMarkerStoreMap);
    }

    function displayCardInfoOnClickMarker(store, divId, marker) {
        if (selectedItemId == divId) {
            if (isSeeMore) {
                showClickedMarkerOnRetailersFound(store);
                if (store.MarkerIndex) {
                    marker.setIcon(selectedIconPin);   
                }
                dealerItemStyleDisplay(divId, false);
            } else {
                if (store.MarkerIndex) {
                    marker.setIcon(iconCircle);   
                }

                dealerItemStyleDisplay(divId, true);

                if (breakpoint() == SMALL) {
                    semiViewItemStyleDisplay(divId, true);
                }
            }

            selectedItemId = ""; 
        } else {
            showClickedMarkerOnRetailersFound(store);

            if (isSeeMore && selectedItemId !== "") {
                // set default layout previous selected item id
                dealerItemStyleDisplay(selectedItemId, true);
                if (breakpoint() == SMALL) {
                    semiViewItemStyleDisplay(selectedItemId, true);    
                }
            }
        
            if (store.MarkerIndex >= 0) {
                marker.setIcon(selectedIconPin);   
            }

            dealerItemStyleDisplay(divId, false);
            if (breakpoint() == SMALL) {
                semiViewItemStyleDisplay(divId, true);    
            }

            selectedItemId = divId; 
        }
    }

    function addMarkersToCluster(newMarkers, newMarkerStoreMap) {
        markers.push.apply(markers, newMarkers);
        markerStoreMap.push.apply(markerStoreMap, newMarkerStoreMap);
        markerCluster.addMarkers(getMarkersToAdd(newMarkerStoreMap, getSelectedFilters()));
    }

    function getVisibleMarkers() {
        return markerCluster.getMarkers();
    }

    function getMarkersToAdd(markerStoreMap, storeFilters) {
        return markerStoreMap.reduce(function (markersToAdd, x) {
            if (isStoreInFilter(x.store, storeFilters)) {
                x.marker.setVisible(true);
                markersToAdd.push(x.marker);
            }
            else {
                x.marker.setVisible(false);
            }
            return markersToAdd;
        }, []);
    }

    function updateVisibleMarkersFromFilter(storeFilters) {
        const markersToAdd = getMarkersToAdd(markerStoreMap, storeFilters);
        markerCluster.clearMarkers();
        markerCluster.addMarkers(markersToAdd);
    }

    /*
     * ##########################################
     * ##########################################
     * 
     * Map
     * 
     * ##########################################
     * ##########################################
     */

    function initMap(dealerLocatorMap) {
        // Loads custom zoom controls
        const zoomControlDiv = document.createElement('div');
        var renderZoomControls = new zoomControlPosition(zoomControlDiv, dealerLocatorMap);
        zoomControlDiv.index = 1;

        dealerLocatorMap.controls[google.maps.ControlPosition.RIGHT_TOP].push(zoomControlDiv);

        initMarkerCluster();
        initMarkerInfoWindow();
        initCenterChanged();
        initDragMap();
    }

    function initCenterChanged() {
        var timeout = null;
        google.maps.event.addListener(dealerLocatorMap, 'center_changed', function () {
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                if (!isFromSelectList) {
                    if (!isSemiViewMobile) {
                        isFromMarker = false;
                        showVisibleMarkersRetailersFound(dealerLocatorMap, markerStoreMap)
                    }
                }
            }, 300);
        });
    }

    function initDragMap() {
        var timeout = null;
        google.maps.event.addListener(dealerLocatorMap, 'dragend', function() { 
            clearTimeout(timeout);

            timeout = setTimeout(function () {
                isFromSelectList = false;
                isFromMarker = false;

                if (!isSemiViewMobile && breakpoint() != SMALL) {
                    showVisibleMarkersRetailersFound(dealerLocatorMap, markerStoreMap)
                }
            }, 300);
        });
    }

    function tryCreateYourPositionMarker(infoWindow) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var pos = {
                    lat: position.coords.latitude, //For testing: 27.967611
                    lng: position.coords.longitude //For testing: -81.958537
                };

                infoWindow.setPosition(pos);
                infoWindow.setContent("Your location");
                infoWindow.open(dealerLocatorMap);
                dealerLocatorMap.setCenter(pos);

                document.querySelector(".gm-style-iw-d").style.display="block";
                document.querySelector(".gm-style-iw-c").style.display="block";
                document.querySelector(".gm-style-iw-t").style.display="block";
            });
        }
    }

    /*
     * ##########################################
     * ##########################################
     * 
     * Search
     * 
     * ##########################################
     * ##########################################
     */

    function initSearch() {
        initSearchAutocomplete();
        handleSearchIcons(true, false);

        $('#addressInput').bind("enterKey", function (e) {
            var showCheck = $(this).val().trim().length !== 0;
            // trigger search if not empty
            if (showCheck) {
                searchLocations(); 
                resetMarkerIcons();
                handleSearchIcons(false, true);
            }
           
        });
        $('#addressInput').keyup(function (e) {
            if (e.keyCode == 13) {
                $(this).trigger("enterKey");
            }
        });

        $('#addressInput').on("input", function (e) {
            e.stopPropagation();
            e.preventDefault();
            var showCheck = $(this).val().trim().length !== 0;
            isFocus = true;

            if (!showCheck) {
                // if empty set search icon only
                handleSearchIcons(true, false);
            } else {
                handleSearchIcons(false, false);
            }
        });

        $('#addressInput').on("click", function (e) {
            e.stopPropagation();
            e.preventDefault();
            if (breakpoint() == SMALL) {
                if (!isFocus && isDefaultMobileView || !isFocus && isSemiViewMobile) {
                    document.getElementById("mobileHorizontalBar").click();
                    $('#addressInput').focus();
                }
            }
            isFocus = true;
        });

        $('#addressInput').on("blur", function (e) {
            e.stopPropagation();
            e.preventDefault();
            isCompleteClick = false;
            isFocus = false;
        });
    }

    function initSearchAutocomplete() {
        var normalizedQueryCache = {};
        $('#addressInput').autocomplete({
            lookup: lookup,
            dealerLocPos: true,
            width: 'auto',
            formatResult: formatResult,
            minChars: 4,
            onSelect: function (suggestion) {
                searchLocations();
                resetMarkerIcons();
                autoCompleteIconInteraction();
            }
        });

        function lookup(query, done) {
            var queryLowerCase = query.toLowerCase();
            done({
                suggestions: getVisibleStores().filter(function (store) {
                    return lookupFilter(store, query, queryLowerCase);
                }),
            });
        }

        function getCachedNormalizedQueryValue(query, queryLowerCase) {
            // To avoid running toLowerCase too many times
            queryLowerCase = queryLowerCase || query.toLowerCase();
            var cachedQuery = normalizedQueryCache[queryLowerCase];
            if (!cachedQuery) {
                cachedQuery = normalizeString(queryLowerCase);
                normalizedQueryCache[queryLowerCase] = cachedQuery;
            }

            return cachedQuery;
        }

        function lookupFilter(suggestion, query, queryLowerCase) {
            return suggestion.data.normalizedValue.indexOf(getCachedNormalizedQueryValue(query, queryLowerCase)) !== -1
        }

        // From jquery.autocomplete.js with some modifications
        function formatResult(suggestion, currentValue) {
            // Do not replace anything if the current value is empty
            if (!currentValue) {
                return suggestion.value + ', ' + suggestion.data.City + ', ' + suggestion.data.Country;
            }
            handleSearchIcons(false, false);
           
            var value = getCachedNormalizedQueryValue(currentValue);
            value = value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");

            var pattern = '(' + value + ')';
            var suggestionValue = suggestion.value
                .replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/&lt;(\/?strong)&gt;/g, '<$1>').trim() + ', ' + suggestion.data.City.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/&lt;(\/?strong)&gt;/g, '<$1>').trim() + ', ' + suggestion.data.Country.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/&lt;(\/?strong)&gt;/g, '<$1>');
            suggestionValue = '<div class="suggestion__wrapper"><i class="fal fa-map-marker-alt"></i><div>' + suggestionValue.trim() + '</div></div>';
            return suggestionValue;    
        };
    }

    //------------------------------------------------------
    // SVG ICON
    //------------------------------------------------------
    // Facebook SVG Icon
    function facebookSvgIcon(href, title) {
        const target="_blank";
        const svgStroke="#685bc7";
        var content = "";
        content = "<a target='" + target + "' href='" + href +"' title='" + title + "'>";
        content += "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='60.734px' viewBox='0 0 60.734 60.733' fill='" + svgStroke + "' xml:space='preserve'>";
        content += "<path stroke='" + svgStroke + "' d='M57.378,0.001H3.352C1.502,0.001,0,1.5,0,3.353v54.026c0,1.853,1.502,3.354,3.352,3.354h29.086V37.214h-7.914v-9.167h7.914 v-6.76c0-7.843,4.789-12.116,11.787-12.116c3.355,0,6.232,0.251,7.071,0.36v8.198l-4.854,0.002c-3.805,0-4.539,1.809-4.539,4.462 v5.851h9.078l-1.187,9.166h-7.892v23.52h15.475c1.852,0,3.355-1.503,3.355-3.351V3.351C60.731,1.5,59.23,0.001,57.378,0.001z'/>";
        content += "</svg>";
        content += '</a>';

        return content;
    }

    // LinkedIn SVG Icon
    function linkedInSvgIcon(href, title) {
        const target="_blank";
        const svgStroke="#685bc7";
        var content = "";
        content = "<a target='" + target + "' href='" + href +"' title='" + title + "'>";
        content += "<svg version='1.1' id='Capa_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 455.731 455.731' height='25px' fill='#685bc7' xml:space='preserve'>";
        content += "<path stroke='#685bc7' d='M0,0v455.731h455.731V0H0z M139.94,375.963c0,5.804-4.705,10.509-10.509,10.509H84.71c-5.804,0-10.509-4.705-10.509-10.509 V185.18c0-5.804,4.705-10.509,10.509-10.509h44.721c5.804,0,10.509,4.705,10.509,10.509V375.963z M106.998,145.491 c-20.308,0.411-38.155-16.551-38.151-38.188c0-20.985,17.282-38.105,38.408-38.088c20.873,0.017,38.088,17.257,38.043,38.234 C145.248,129.413,127.02,145.969,106.998,145.491z M386.884,382.153c0,2.41-1.954,4.363-4.364,4.362l-57.152-0.014 c-2.409-0.001-4.362-1.954-4.362-4.363V264.331c0-10.183-4.126-19.407-10.802-26.079c-6.764-6.768-16.149-10.916-26.501-10.799 c-20.279,0.229-36.454,17.068-36.454,37.348v117.323c0,2.41-1.954,4.363-4.364,4.362l-57.011-0.014 c-2.409-0.001-4.361-1.954-4.361-4.362V179.034c0-2.409,1.953-4.363,4.363-4.363h55.795c2.409,0,4.363,1.953,4.363,4.363v23.418 c0.005-0.01,0.225,0.018,0.599,0.075c1.078-1.95,2.252-3.839,3.52-5.658c11.628-16.688,30.96-27.606,52.842-27.606h11.47 c39.996,0,72.42,32.423,72.42,72.42V382.153z'/>";
        content += "</a>";

        return content;
    }

    // Instagram SVG Icon
    function instagramSvgIcon(href, title) {
        const target="_blank";
        const svgStroke="#685bc7";
        var content = "";
        content = "<a target='" + target + "' href='" + href +"' title='" + title + "'>";
        content += "<?xml version='1.0' ?><svg data-name='Layer 1' id='Layer_1' x='0px' y='0px' viewBox='0 0 508.33 508.36' xmlns='http://www.w3.org/2000/svg'><defs><style>.cls-1{fill:#685bc7;fill-rule:evenodd;}.cls-2{fill:#fff;}</style></defs><title/><path class='cls-1' d='M485,29.72c11.45,15.13,16.61,40.21,19.15,70.7,3.36,45.5,4.71,100.1,6,156.52-1.67,57.47-2.35,115.43-6,156.52-2.88,31.54-9,52.66-19.22,65.47-13,12.79-37.94,23.59-73.5,26.15-43.25,3.69-96.61,3.65-155.48,5.1-65.44-1.12-109.82-.64-156.38-5.08-36.32-2.52-60.08-13.19-74.7-26.07-10.83-14.54-14-30-17-66.24-3.75-41.85-4.58-98.56-6-155.54C4,200.57,4.13,143.44,7.9,100.74,10.43,67.05,14.42,44.4,24.65,30,39,17.77,63.48,11.69,100,8.69c50-5.85,102.06-7,155.88-6.87,55.39.09,108.56,1.67,156,6.34,32,2.56,58.48,8.07,73.07,21.56Z' transform='translate(-1.83 -1.82)'/><path class='cls-2' d='M250.43,126.1c40.17,0,44.92.15,60.8.88,14.65.68,22.61,3.14,27.91,5.18a49.81,49.81,0,0,1,28.55,28.55c2.06,5.3,4.51,13.27,5.18,27.93.72,15.86.88,20.62.88,60.8s-.15,44.92-.88,60.8c-.67,14.67-3.12,22.63-5.18,27.93a49.82,49.82,0,0,1-28.55,28.55c-5.3,2.06-13.27,4.51-27.93,5.18-15.86.72-20.62.88-60.8.88s-44.93-.15-60.8-.88c-14.67-.67-22.63-3.12-27.93-5.18a50,50,0,0,1-28.51-28.58c-2.06-5.3-4.51-13.27-5.18-27.93-.72-15.86-.88-20.62-.88-60.8s.15-44.92.88-60.8c.67-14.67,3.12-22.63,5.18-27.93a49.86,49.86,0,0,1,28.54-28.51c5.3-2.06,13.27-4.51,27.93-5.18,15.86-.72,20.62-.88,60.8-.88m0-27.1c-40.86,0-46,.17-62,.9s-26.94,3.27-36.51,7a77,77,0,0,0-44,44c-3.72,9.57-6.26,20.5-7,36.51s-.9,21.16-.9,62,.17,46,.9,62,3.27,26.94,7,36.51a76.92,76.92,0,0,0,44,44c9.57,3.72,20.5,6.26,36.51,7s21.16.9,62,.9,46-.17,62-.9,26.94-3.27,36.51-7a76.92,76.92,0,0,0,44-44c3.72-9.57,6.26-20.5,7-36.51s.9-21.16.9-62-.17-46-.9-62-3.27-26.94-7-36.51a76.92,76.92,0,0,0-44-44c-9.59-3.72-20.52-6.26-36.53-7s-21.16-.9-62-.9h0Z' transform='translate(-1.83 -1.82)'/><path class='cls-2' d='M250.43,172.18a77.25,77.25,0,1,0,77.25,77.25,77.25,77.25,0,0,0-77.25-77.25Zm0,127.39a50.14,50.14,0,1,1,50.14-50.14,50.14,50.14,0,0,1-50.14,50.14Z' transform='translate(-1.83 -1.82)'/><circle class='cls-2' cx='328.89' cy='167.31' r='18.05'/></svg>";
        content += "</a>";

        return content;
    }

    // Twitter SVG Icon
    function twitterSvgIcon(href, title) {
        const target="_blank";
        const svgStroke="#685bc7";

        var content = "";
        content = "<a target='" + target + "' href='" + href +"' title='" + title + "'>";
        content += "<svg version='1.1' id='Capa_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 455.731 455.731' xml:space='preserve'>";
        content += "<g>";
        content += "<rect x='0' y='0' style='fill:" + svgStroke + "' width='455.731' height='455.731'/>";
        content += "<path style='fill:#FFFFFF;' stroke='" + svgStroke + "' d='M60.377,337.822c30.33,19.236,66.308,30.368,104.875,30.368c108.349,0,196.18-87.841,196.18-196.18 c0-2.705-0.057-5.39-0.161-8.067c3.919-3.084,28.157-22.511,34.098-35c0,0-19.683,8.18-38.947,10.107 c-0.038,0-0.085,0.009-0.123,0.009c0,0,0.038-0.019,0.104-0.066c1.775-1.186,26.591-18.079,29.951-38.207 c0,0-13.922,7.431-33.415,13.932c-3.227,1.072-6.605,2.126-10.088,3.103c-12.565-13.41-30.425-21.78-50.25-21.78 c-38.027,0-68.841,30.805-68.841,68.803c0,5.362,0.617,10.581,1.784,15.592c-5.314-0.218-86.237-4.755-141.289-71.423 c0,0-32.902,44.917,19.607,91.105c0,0-15.962-0.636-29.733-8.864c0,0-5.058,54.416,54.407,68.329c0,0-11.701,4.432-30.368,1.272 c0,0,10.439,43.968,63.271,48.077c0,0-41.777,37.74-101.081,28.885L60.377,337.822z'/>";
        content += "</g>";
        content += '</a>';

        return content;
    }

    function normalizeString(str) {
        return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
    }

    function formatSearchString(str) {
        return normalizeString(str.toLowerCase().trim().replace(/\s/g, ''));
    }

    function searchLocations() {
        isFromMarker = false;
        var address = "";
        address = document.getElementById("addressInput").value;
        isFromSelectList = false;
        isSeeMore = false;
        isCompleteClick = true;

        var geocoder = new google.maps.Geocoder();

        let bestHit = undefined;
        var localHits = [];
        const query = formatSearchString(address);

        getVisibleMarkers().find(function (marker, i) {
            // due to common locationName, city and country
            // when selecting item from list do search by address1 for unique search
            // else it will be weird behaviour like, jumping to the first item of the duplicate or redundant records
            const locationName = formatSearchString(isFromSelectList ? marker.address1 : marker.locationName);
            const country = formatSearchString(marker.country);
            const city = formatSearchString(marker.city);

            const queryString1 = locationName + "," + city + country;
            const queryString2 = locationName + "," + city;
            const queryString3 = locationName;

            if (query.includes(locationName)) {
                if (query == queryString1) {
                    localHits.push({
                        prior: 1,
                        index: i,
                        data: marker
                    });
                } else if (query == queryString2) {
                    localHits.push({
                        prior: 2,
                        index: i,
                        data: marker
                    });
                } else if (query == queryString3) {
                    localHits.push({
                        prior: 3,
                        index: i,
                        data: marker
                    });
                }
                else if (query.includes(locationName) && query.includes(city) && query.includes(country)) {
                    localHits.push({
                        prior: 4,
                        index: i,
                        data: marker
                    });
                }
                else if (query.includes(locationName) && query.includes(city)) {
                    localHits.push({
                        prior: 5,
                        index: i,
                        data: marker
                    });
                }
                else {
                    localHits.push({
                        prior: 6,
                        index: i,
                        data: marker
                    });
                }
            }
        });

        if (localHits.length > 0) {
            localHits.find(function (hit) {

                if (bestHit === undefined) {
                    bestHit = hit;
                } else {
                    if (bestHit.prior > hit.prior) {
                        bestHit = hit;
                    }
                }
            });

            if (bestHit.prior <= 3) {
                setMarkerHit(bestHit.data);

                return;
            }
        }

        if (address) {
            geocoder.geocode({ address: address },
                function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {

                        var r = results[0];
                        if (r != null) {

                            if (!r.partial_match && (r.types.includes("establishment")
                                || r.types.includes("health")
                                || r.types.includes("pharmacy")
                                || r.types.includes("point_of_interest")
                                || r.types.includes("store"))) {
                                // Is dealer
                                // Have hit from google geo
                                setLatLngHit(r.geometry.location.lat(), r.geometry.location.lng(), true, r.geometry);
                            } else if (bestHit !== undefined) {
                                // Don't have a direct hit from google geo but have a "partial_hit" local
                                setMarkerHit(bestHit.data);
                                return;
                            } else if (r.types.includes("establishment")
                                || r.types.includes("health")
                                || r.types.includes("pharmacy")
                                || r.types.includes("point_of_interest")
                                || r.types.includes("store")) {
                                // Have a "partial_hit" from google geo
                                setLatLngHit(r.geometry.location.lat(), r.geometry.location.lng(), true, r.geometry);
                            }
                            else {
                                // Same as above but keep in separate block for future use.
                                setLatLngHit(r.geometry.location.lat(), r.geometry.location.lng(), true, r.geometry);
                            }
                        }
                    }
                });
        }
    }

    function setMarkerHit(marker) {
        var markerLat = marker.position.lat();
        var markerLng = marker.position.lng();
        

        dealerLocatorMap.setZoom(16);

        google.maps.event.trigger(marker, "click", {
            latLng: new google.maps.LatLng(markerLat, markerLng)
        });

        dealerLocatorMap.setCenter({ lat: markerLat, lng: markerLng });
    }

    function setLatLngHit(lat, lng, triggerMarkerClick, geometry) {
        var googleHitBound = new google.maps.LatLng(lat, lng);

        var visibleMarkers = getVisibleMarkers();
        var closestMarker = getClosestMarker(visibleMarkers, lat, lng);
        var closestMarkerBounds = null;
        if (closestMarker != null) {
            var markerLat = closestMarker.position.lat();
            var markerLng = closestMarker.position.lng();

            // If the same location, we use the marker to set correct center.
            if (roundLocation(lat) === roundLocation(markerLat) && roundLocation(lng) === roundLocation(markerLng)) {
                setMarkerHit(closestMarker);
                return;
            }

            closestMarkerBounds = new google.maps.LatLng(markerLat, markerLng);

            if (triggerMarkerClick) {
                google.maps.event.trigger(closestMarker, "click", { latLng: closestMarkerBounds });
            }
        }

        // Fit map to show both google hit and closest marker locations
        var bounds = new google.maps.LatLngBounds();
        bounds.extend(googleHitBound);
        if (closestMarkerBounds != null) {
            bounds.extend(closestMarkerBounds);
        }
        dealerLocatorMap.setOptions({ maxZoom: 16 });

        if (geometry != null) {
            dealerLocatorMap.fitBounds(geometry.viewport);
        }

        var loc = { lat: markerLat, lng: markerLng }

        // Option 1: Center on google search result location + closest dealer on map.
        google.maps.event.addListenerOnce(dealerLocatorMap, "bounds_changed", function () {
            google.maps.event.addListenerOnce(dealerLocatorMap, "center_changed", function () {
                if (!dealerLocatorMap.getBounds().contains(closestMarkerBounds)) {
                    dealerLocatorMap.setZoom(dealerLocatorMap.getZoom() - 1);
                }
            });
            dealerLocatorMap.setCenter(loc);
        });

        // Option 2: Both google search result location + closest dealer on map but not centered.
        //dealerLocatorMap.panToBounds(bounds);
    }

    function rad(x) { return x * Math.PI / 180; }
    function getClosestMarker(markers, lat, lng) {
        var R = 6371; // radius of earth in km
        var closestIndex = -1;
        var closestDistance = -1;
        for (i = 0; i < markers.length; i++) {
            var mlat = markers[i].position.lat();
            var mlng = markers[i].position.lng();
            var dLat = rad(mlat - lat);
            var dLong = rad(mlng - lng);
            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            var d = R * c;

            if (closestIndex == -1 || closestDistance == -1 || d < closestDistance) {
                closestIndex = i;
                closestDistance = d;
            }
        }

        if (markers.length > 0) {
            return markers[closestIndex];
        }
        return null;
    }

    function roundLocation(loc) {
        return Math.floor(loc * 10000 + 0.5 / 10000);
    };

    /*
     * ##########################################
     * ##########################################
     * 
     * Marker info window
     * 
     * ##########################################
     * ##########################################
     */

    function initMarkerInfoWindow() {
        google.maps.event.addListener(dealerLocatorMap, "click", function (event) {
            isFromSelectList = false;
            isFromMarker = false;
        });
    }

    /*
     * ##########################################
     * ##########################################
     * 
     * Retailers Found
     * 
     * ##########################################
     * ##########################################
     */

    function showClickedMarkerOnRetailersFound(store) {
        if (!isFromSelectList) {
            if (breakpoint() === SMALL) {
                if (!isHrBarClicked) {
                    isHrBarClicked = true;
                } 

                if (!isSemiViewMobile) {
                    setDefaultFullViewMobile();    
                    isSemiViewMobile = false;
                    isDefaultMobileView = false
                }
            }
        } else {
            if (isSeeMore) {
                if (breakpoint() === SMALL) {
                    if (!isHrBarClicked) {
                        isHrBarClicked = true;
                    } 

                    setDefaultFullViewMobile();
                    isSemiViewMobile = false;
                    isDefaultMobileView = false
                }   
            }
        }

        $('#retailersFound').text("");
        $("#collapse"+store.LocationId).click();
    }

    function showVisibleMarkersRetailersFound(dealerLocatorMap, markerStoreMap) {
        var currentZoom = dealerLocatorMap.getZoom();

        if (currentZoom >= 4) {
            resetMarkerIcons();
            $('.dealerLocatorResult__wrapper').remove();

            const bounds = dealerLocatorMap.getBounds();
            storeResultList = [];
            let storesFound = 0;

            resetDefaultLabel();

            for (let i = 0; i < markerStoreMap.length; i++) {
                if (bounds.contains(markerStoreMap[i].marker.getPosition()) && markerStoreMap[i].marker.getVisible()) {
                    const storeInfo = markerStoreMap[i].store;
                    const divId = storeInfo.MarkerIndex + "-" + storeInfo.Guid;
            
                    storesFound++;
                    storeResultList.push(markerStoreMap[i].store);
                    handleCreateDealerListResult(storeInfo, divId);
                }
                // List: Cap amount of dealers listed at 25 
                // (so only show map view, without list of dealers, if more than 25 close dealers are found)
                if (storesFound > retailersMaxCount) {
                    $('.dealerLocatorResult__wrapper').remove();
                    break;
                }
            } // End of for loop
            
            // console.log("storesFound", storesFound, storeResultList);
            if (storesFound.length === 0) {
                $('.dealerLocatorResult__wrapper').remove();
            }

            if (breakpoint() === SMALL && isHrBarClicked) {
                isDefaultMobileView  = false;
            }

            retailersContainer(storeResultList);
            
        } else {
            storeResultList = [];
            retailersFoundDisplay("none");
            $('.dealerLocatorResult__wrapper').remove();
        }
    }

    //---------------------------------------------------------
    // Handle Create Dealer List Result
    //---------------------------------------------------------
    function handleCreateDealerListResult(storeInfo, divId) {
        // Create dealer locator result item list in html
        createResultListHtml(storeInfo);
                
        // for mobile view
        if (breakpoint() === SMALL) {
            $("#seeMoreLink" + divId).on("click", function(e) {
                e.stopPropagation();    
                e.preventDefault();

                selectItemInList(storeInfo, true);
            });
        } 

        $("#" + divId).on("click", function(e) {
            e.stopPropagation();    
            e.preventDefault();

            selectItemInList(storeInfo, false);
        });
    }

    //---------------------------------------------------------
    // Format Address Style 1
    //---------------------------------------------------------
    function formatAddressStyle1(store) {
        const divId = store.MarkerIndex + "-" + store.Guid;
        const address1 = store.Address1 != null ?  store.Address1.trim() : "";
        const country = store.Country != null ?  store.Country.trim() : "";
        const city = store.City != null ?  store.City.trim() : "";
        const stateProvince = store.State_Province != null ? store.State_Province.trim() : "";
        const zipCode = store.Zip_PostalCode != null ? store.Zip_PostalCode.trim() : "";
        const translatedCountry = store.TranslatedCountry ? store.TranslatedCountry : country;
        var truncate = '';
        if (breakpoint() === MEDIUM || breakpoint() === SMALL) {
            truncate = 'truncate';
        }

        var addressStyle1 = "<div class='dealerLocatorResult__addressStyle1 " + truncate + "' id='addressStyle1" + divId + "'>";
        addressStyle1 += address1 + ", ";

        switch (country.toLowerCase()) {
            case "us":
            case "united states":
                city && (addressStyle1 += city + ", ");
                stateProvince && (addressStyle1 += stateProvince + " ");
                zipCode && (addressStyle1 += zipCode);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "ca":
            case "canada":
                city && (addressStyle1 += city + ", ");
                stateProvince && (addressStyle1 += stateProvince + " ");
                zipCode && (addressStyle1 += zipCode);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "mx":
            case "méxico":
            case "mexico":
                zipCode && (addressStyle1 += zipCode + ", ");
                stateProvince && (addressStyle1 += stateProvince + ", ");
                city && (addressStyle1 += city);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "br":
            case "brasil":
            case "brazil":
                city && (addressStyle1 += city + " - ");
                stateProvince && (addressStyle1 += stateProvince);
                zipCode && (addressStyle1 += zipCode);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "fr":
            case "france":
                zipCode && (addressStyle1 += zipCode + " ");
                city && (addressStyle1 += city);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "ch":
            case "switzerland":
                zipCode && (addressStyle1 += zipCode + " ");
                city && (addressStyle1 += city);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "de":
            case "germany":
                zipCode && (addressStyle1 += zipCode + " ");
                city && (addressStyle1 += city);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "at":
            case "austria":
                zipCode && (addressStyle1 += zipCode + " ");
                city && (addressStyle1 += city);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "it":
            case "italy":
                zipCode && (addressStyle1 += zipCode + " ");
                city && (addressStyle1 += city + " ");
                stateProvince && (addressStyle1 += stateProvince);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "au":
            case "australia":
                city && (addressStyle1 += city + " ");
                stateProvince && (addressStyle1 += stateProvince + " ");
                zipCode && (addressStyle1 += zipCode);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "uk":
            case "united kingdom":
                city && (addressStyle1 += city + " ");
                zipCode && (addressStyle1 += zipCode);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "ru":
            case "russia":
                city && (addressStyle1 += city + " ");
                stateProvince && (addressStyle1 += stateProvince + " ");
                zipCode && (addressStyle1 += zipCode);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "pl":
            case "poland":
                zipCode && (addressStyle1 += zipCode + " ");
                city && (addressStyle1 += city);
                country && (addressStyle1 += ", " + translatedCountry);
                break;

            case "cn":
            case "china":
                country && (addressStyle1 += translatedCountry + " ");
                zipCode && (addressStyle1 += zipCode + " ");
                stateProvince && (addressStyle1 += stateProvince + " ");
                city && (addressStyle1 += city + " ");
                break;

            default:
                zipCode && (addressStyle1 += zipCode + " ");
                city && (addressStyle1 += city);
                country && (addressStyle1 += ", " + translatedCountry);
        }

        addressStyle1 += "</div>";    
        return addressStyle1;
    }

    //---------------------------------------------------------
    // Format Address Style 2
    //---------------------------------------------------------
    function formatAddressStyle2(store) {
        const divId = store.MarkerIndex + "-" + store.Guid;
        const address1 = store.Address1 != null ?  store.Address1.trim() : "";
        const country = store.Country != null ?  store.Country.trim() : "";
        const city = store.City != null ?  store.City.trim() : "";
        const stateProvince = store.State_Province != null ? store.State_Province.trim() : "";
        const zipCode = store.Zip_PostalCode != null ? store.Zip_PostalCode.trim() : "";
        const translatedCountry = store.TranslatedCountry ? store.TranslatedCountry : country;
        var addressStyle2 = "<div class='dealerLocatorResult__addressStyle2' id='addressStyle2" + divId + "' style='display: none'>";
        addressStyle2 += address1 + ", ";

        switch (country.toLowerCase()) {
            case "us":
            case "united states":
                city && (addressStyle2 += "<span>" + city + ", </span>");
                addressStyle2 += "<span>";
                stateProvince && (addressStyle2 += stateProvince + " ");
                zipCode && (addressStyle2 += zipCode);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "ca":
            case "canada":
                city && (addressStyle2 += "<span>" + city + ", </span>");
                addressStyle2 += "<span>";
                stateProvince && (addressStyle2 += stateProvince + " ");
                zipCode && (addressStyle2 += zipCode);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "mx":
            case "méxico":
            case "mexico":
                zipCode && (addressStyle2 += "<span>" + zipCode + ", </span>");
                addressStyle2 += "<span>";
                stateProvince && (addressStyle2 += stateProvince + ", ");
                city && (addressStyle2 += city);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "br":
            case "brasil":
            case "brazil":
                city && (addressStyle2 += "<span>" + city + " - </span>");
                addressStyle2 += "<span>";
                stateProvince && (addressStyle2 += stateProvince);
                zipCode && (addressStyle2 += zipCode);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "fr":
            case "france":
                zipCode && (addressStyle2 += "<span>" + zipCode + " </span>");
                addressStyle2 += "<span>";
                city && (addressStyle2 += city);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "ch":
            case "switzerland":
                zipCode && (addressStyle2 += "<span>" + zipCode + "  </span>");
                addressStyle2 += "<span>";
                city && (addressStyle2 += city);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "de":
            case "germany":
                zipCode && (addressStyle2 += "<span>" + zipCode + "  </span>");
                addressStyle2 += "<span>";
                city && (addressStyle2 += city);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "at":
            case "austria":
                zipCode && (addressStyle2 += "<span>" + zipCode + "  </span>");
                addressStyle2 += "<span>";
                city && (addressStyle2 += city);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "it":
            case "italy":
                zipCode && (addressStyle2 += "<span>" + zipCode + "  </span>");
                addressStyle2 += "<span>";
                city && (addressStyle2 += city + " ");
                stateProvince && (addressStyle2 += stateProvince);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "au":
            case "australia":
                city && (addressStyle2 += "<span>" + city + "  </span>");
                addressStyle2 += "<span>";
                stateProvince && (addressStyle2 += stateProvince + " ");
                zipCode && (addressStyle2 += zipCode);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "uk":
            case "united kingdom":
                city && (addressStyle2 += "<span>" + city + "  </span>");
                addressStyle2 += "<span>";
                zipCode && (addressStyle2 += zipCode);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "ru":
            case "russia":
                city && (addressStyle2 += "<span>" + city + "  </span>");
                addressStyle2 += "<span>";
                stateProvince && (addressStyle2 += stateProvince + " ");
                zipCode && (addressStyle2 += zipCode);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "pl":
            case "poland":
                zipCode && (addressStyle2 += "<span>" + zipCode + "  </span>");
                addressStyle2 += "<span>";
                city && (addressStyle2 += city);
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
                break;

            case "cn":
            case "china":
                country && (addressStyle2 += "<span>" + translatedCountry + "  </span>");
                addressStyle2 += "<span>";
                zipCode && (addressStyle2 += zipCode + " ");
                stateProvince && (addressStyle2 += stateProvince + " ");
                city && (addressStyle2 += city);
                addressStyle2 += "</span>";
                break;

            default:
                zipCode && (addressStyle2 += "<span>" + zipCode + "  </span>");
                addressStyle2 += "<span>";
                city && (addressStyle2 += city + " ");
                country && (addressStyle2 += ", " + translatedCountry);
                addressStyle2 += "</span>";
        }
        addressStyle2 += "</div>";
        return addressStyle2;
    }

    //---------------------------------------------------------
    // Function that will create dealer locator item list in HTML 
    // and append the html in result-list-container
    //---------------------------------------------------------
    function createResultListHtml(data) { 
        var content = "";
        var storeListContainer = $('#result-list-container');
        const address1 = data.Address1 != null ? data.Address1.trim() : "";
        const locationName = data.LocationName != null ? data.LocationName.trim() : "";
        const postalCode = data.Zip_PostalCode != null ?  data.Zip_PostalCode.trim() : "";
        const country = data.Country != null ?  data.Country.trim() : "";
        const city = data.City != null ?  data.City.trim() : "";
        
        // for debugging purposes;
        // data.Email = "info@sanitaetshauswinkler.de"; 
        // data.Facebook = "http://facebook.com"; 
        // data.Twitter = "http://twitter.com"; 
        // data.Instagram = "http://instagram.com"; 
        // data.LinkedIn = "http://linkedin.com"; 

        // Contact
        const emailAdd = data.Email != null ?  data.Email.trim() : "";
        const phoneNum = data.Phone != null ?  data.Phone.trim() : "";

        // Social Media
        const facebook  = data.Facebook != null ? data.Facebook.trim() : "";
        const twitter   = data.Twitter != null ? data.Twitter.trim() : "";
        const instagram = data.Instagram != null ? data.Instagram.trim() : "";
        const linkedIn  = data.LinkedIn != null ? data.LinkedIn.trim() : "";
        const divId = data.MarkerIndex + "-" + data.Guid;

        if (locationName && address1) {
            var mapmarker = "<div class='dealerLocatorResult__mapmarker' id='mapmarker" + divId + "'>";
                mapmarker += "<i class='fal fa-map-marker-alt'></i></div>";

            var mapmarkerFill = "<div class='dealerLocatorResult__mapmarkerfill' style='display: none;' id='mapmarkerfill" + divId +"'>";
                mapmarkerFill += "<i class='fas fa-map-marker-alt'></i></div>";

            var collapeDown = "<div class='dealerLocatorResult__collapse__down' id='collapsableDown" + divId + "'>";
                collapeDown += "<i class='fal fa-chevron-down'></i>";
                collapeDown += "</div>";

            var collapeUp = "<div class='dealerLocatorResult__collapse__up' style='display: none;' id='collapsableUp" + divId + "'>";
                collapeUp += "<i class='fal fa-chevron-up'></i>";
                collapeUp += "</div>";

            const locationNameWrap = "<div class='dealerLocatorResult__name'>" + locationName.toUpperCase() + "</div>";
            var truncate = '';

            if (breakpoint() === MEDIUM || breakpoint() === SMALL) {
                truncate = 'truncate';
            }

            // in CH/DE/AT postal code should be displayed before city name
            var addressStyle1 = formatAddressStyle1(data);
            var addressStyle2 = formatAddressStyle2(data);

            var openingHours = "<div class='dealerLocatorResult__detailArea__opening'>";
                openingHours += "<div class='dealerLocatorResult__detailArea__hoursLabel'>";
                openingHours += "<span>Opening Hours</span>";
                openingHours += "</div>";
                openingHours += "<div class='dealerLocatorResult__detailArea__hours'>";
                openingHours += "<span>Monday-Satuday 9.00am-7:30pm</span>";
                openingHours += "</div>";
                openingHours += "</div>";

            var openingHoursCompact = "<div class='dealerLocatorResult__detailArea__opening'>";
                openingHoursCompact += "<div class='dealerLocatorResult__detailArea__hoursLabel'>";
                openingHoursCompact += "<span>Opening Hours</span>";
                openingHoursCompact += "</div>";
                openingHoursCompact += "<div class='dealerLocatorResult__detailArea__hours'>";
                openingHoursCompact += "<span>Monday-Satuday</span>";
                openingHoursCompact += "<span>9.00am-7:30pm</span>";
                openingHoursCompact += "</div>";
                openingHoursCompact += "</div>";
            
            var emailWrap = "";
            if (emailAdd) {
                emailWrap = "<div class='dealerLocatorResult__detailArea__label'><a href='mailto:" + emailAdd + "'>" + emailAdd + "</a></div>";
            }
            
            var phoneWrap = "";
            if (phoneNum) {
                phoneWrap = "<div class='dealerLocatorResult__detailArea__label'><a href='tel:" + phoneNum + "'>" + phoneNum + "</a></div>";
            }

            var facebookWrap = "";
            if (facebook) {
                facebookWrap = facebookSvgIcon(facebook, 'Facebook');
            }

            var linkedInWrap = "";
            if (linkedIn) {
                linkedInWrap = linkedInSvgIcon(linkedIn, 'LinkedIn');
            }

            var twitterWrap = "";
            if (linkedIn) {
                twitterWrap = twitterSvgIcon(twitter, 'Twitter');
            }

            var instagramWrap = "";
            if (instagram) {
                instagramWrap = instagramSvgIcon(instagram, 'Instagram');
            }

            var socialContact = "";
            if (emailWrap || phoneWrap) {
                socialContact = "<div class='dealerLocatorResult__detailArea__contactLabel'><span>Contact</span></div>";
            }
            if (emailWrap) {
                socialContact += emailWrap;
            }
            if (phoneWrap) {
                socialContact += phoneWrap;
            }

            var filterWrap = ""; 

            if (data.storeFilters && data.storeFilters.length > 0) {
                filterWrap += "<div class='store_filter__wrapper'>";
                for (var i = 0; i < data.storeFilters.length; i++) {
                    filterWrap += "<div class='store_filter'><i class='fal fa-check'></i><span>" + data.storeFilters[i] + "</span></div>";
                }
                filterWrap += "</div>";
            }
            
            var contactWrap = "<div class='dealerLocatorResult__detailArea__contact'>";
                contactWrap += socialContact;
                contactWrap += "<div class='dealerLocatorResult__detailArea__social_media'>";
                contactWrap += facebookWrap + linkedInWrap + twitterWrap + instagramWrap;
                contactWrap += "</div>";
                contactWrap += filterWrap;
                contactWrap += "<input type='hidden' id='txtAdd-"+ divId +"' value='"+ address1 + " " + postalCode + " " + data.City + "' />";
                contactWrap += "<form action='https://maps.google.com/maps' method='get' target='_blank'>";
                contactWrap += "<input type='text' class='hidden' name='daddr' value='"+ address1 + " " + postalCode + " " + data.City + "'/>";
                contactWrap += "<span class='distance'>";
                contactWrap += "<button class='btn btnprimary' type='submit' name='Submit' value='  "+ data.GetDestinationString + "'>" + data.GetDestinationString + "</button>";
                contactWrap += "</span>";
                contactWrap += "</form>";
                contactWrap += "</div>";

            var detailContent =  "<div class='dealerLocatorResult__detailArea' style='display: none;' id='detailArea" + divId + "'>";
                detailContent += contactWrap;
                detailContent += "</div>";

            var headerContent = "<div class='dealerLocatorResult__headerArea' id='" + divId + "'>";
                headerContent += mapmarker + mapmarkerFill;
                headerContent += "<div class='dealerLocatorResult__headerArea__content'>" + locationNameWrap + addressStyle1 + addressStyle2 + "</div>";
                headerContent += collapeDown + collapeUp;
                headerContent += "</div>";

            var seeAllTextLabel = $('#seeAllLabel');
            const seeAllTextLabelDefault = seeAllTextLabel.attr("data-label");
            
            var seeMoreLinkWrap = "<div class='dealerLocatorResult__seeMoreArea' style='display: none;' id='seeMoreLink"+divId + "'>";
                seeMoreLinkWrap += "<div class='dealerLocatorResult__seeMoreArea__seeMore'>";
                seeMoreLinkWrap += "<div class='dealerLocatorResult__seeMoreArea__seeMoreLabel'>";
                seeMoreLinkWrap += "<span>" + seeAllTextLabelDefault + "</span>";
                seeMoreLinkWrap += "</div>";
                seeMoreLinkWrap += "</div>";
                seeMoreLinkWrap += "</div>";

            content = "<div class='dealerLocatorResult__wrapper' id='wrapper"+ divId + "'>";
            content += "<div class='dealerLocatorResult__area' id='itemArea"+ divId + "'>";
            content += headerContent + detailContent + seeMoreLinkWrap;
            content += "</div>";
            content += "</div>";
            storeListContainer.append(content);
        }
    }

    /*
     * ##########################################
     * ##########################################
     * 
     * Init
     * 
     * ##########################################
     * ##########################################
     */

    if ($('#dealerLocatorMap').length > 0) {
        init();
    }

    /*
     * ##########################################
     * ##########################################
     * 
     * New Layout
     * 
     * ##########################################
     * ##########################################
     */
    function resetDefaultLabel() {
        var retailersFound = document.getElementById("div-retailersFound");
        var textLabel = document.getElementById("div-search-textLabel");
        
        retailersFound.style.display = "none";
        
        if (breakpoint() === SMALL) {
            // default on mobile view
            textLabel.style.display = "none";
            textLabel.classList.remove("search-textLabel__mount");
        } else {
            textLabel.style.display = "block";
        }
    }

    function resetMarkerIcons() {
        //  reset all the icons back to normal except the one you clicked
        for (var i = 0; i < markers.length; i++) {
            markers[i].setIcon(iconCircle);
        }

        for (var i = 0; i < storeResultList.length; i++) {
            const divId = storeResultList[i].MarkerIndex + "-" + storeResultList[i].Guid;

            dealerItemStyleDisplay(divId, true);
            if (breakpoint() == SMALL) {
                semiViewItemStyleDisplay(divId, true);
            }
        }
    }

    /* 
     * function handle to draw the dealer item card display
     * isReset true, it will draw the dealer item card to its default(non collapse or not selected item) layout 
     * 
     * string @div 
     * boolean isReset
     *  
     */
    function dealerItemStyleDisplay(divId, isReset) {
        var itemArea = document.getElementById("itemArea"+divId);
        var detailArea = document.getElementById("detailArea"+divId);
        var mapmarker = document.getElementById("mapmarker"+divId);
        var mapmarkerfill = document.getElementById("mapmarkerfill"+divId);
        var collapseDown = document.getElementById("collapsableDown"+divId);
        var collapseUp = document.getElementById("collapsableUp"+divId);

        var addressStyle1 = document.getElementById("addressStyle1"+divId);
        var addressStyle2 = document.getElementById("addressStyle2"+divId);
        var listContainer = document.getElementById("result-list-container");
        var searchContainer = document.getElementById("dealer-locator-search__container");
        
        try {
            if (!isReset) {
                if (detailArea.style.display === "none" || isSeeMore) {
                    
                    mapmarker.style.display = "none";
                    mapmarkerfill.style.display = "block";

                    addressStyle1.style.display = "block";
                    addressStyle2.style.display = "none";

                    if (breakpoint() == SMALL || breakpoint == MEDIUM) {
                        addressStyle1.style.display = "none";
                        addressStyle2.style.display = "flex";
                    } 

                    if (!isSemiViewMobile) {
                        collapseDown.style.display = "none";
                        collapseUp.style.display = "block";
                        detailArea.style.display = "flex";
                    }
                    
                    if (isSemiViewMobile) {
                        if (detailArea.style.display !== "block") {
                            detailArea.style.display = "none";
                        }
                        
                        listContainer.classList.add("active");
                        searchContainer.classList.add("dealer-locator-search__container__semiviewContentClicked");

                        if (breakpoint() == SMALL) {
                            itemArea.scrollIntoView({
                                behavior: "auto", 
                                inline: "center"
                            });
                        }
                    } 

                } else {
                    detailArea.style.display = "none";
                    mapmarker.style.display = "block";
                    mapmarkerfill.style.display = "none";

                    if (!isSemiViewMobile) {
                        collapseDown.style.display = "block";
                        collapseUp.style.display = "none";

                        addressStyle1.style.display = "block";
                        addressStyle2.style.display = "none";

                        if (breakpoint() == SMALL || breakpoint == MEDIUM) {
                            addressStyle1.style.display = "none";
                            addressStyle2.style.display = "flex";
                        } 

                    } else {
                        listContainer.classList.remove("active");

                        collapseDown.style.display = "none";
                        collapseUp.style.display = "none";

                        addressStyle1.style.display = "none";
                        addressStyle2.style.display = "flex";
                    }
                }    
            } else {
                mapmarker.style.display = "block";
                mapmarkerfill.style.display = "none";

                if (!isSemiViewMobile) {
                    detailArea.style.display = "none";
                    collapseDown.style.display = "block";
                    collapseUp.style.display = "none";

                    addressStyle1.style.display = "block";
                    addressStyle2.style.display = "none";
                } else {
                    listContainer.classList.remove("active");
                    searchContainer.classList.remove("dealer-locator-search__container__semiviewContentClicked");

                    collapseDown.style.display = "none";
                    collapseUp.style.display = "none";

                    addressStyle1.style.display = "none";
                    addressStyle2.style.display = "flex";

                    if (detailArea.style.display !== "block") {
                        detailArea.style.display = "none";
                    }
                }
            }

        }
        catch(e) {
        }
    }
    
    function scrollParentToChild(divId) {
        try {
            var child = document.getElementById("itemArea"+divId);
            var parent = document.getElementById('result-list-container');
            parent.scrollTop = child.offsetTop;
        } catch (e) {

        }
    }
  
    function autoCompleteIconInteraction() {
        var resultListContainer = document.getElementById("result-list-container");
        var searchTextLabel = document.getElementById("div-search-textLabel");
        
        resultListContainerDisplay("none");
        // Show X icon only
        handleSearchIcons(false, true);

        if (resultListContainer.style.display === "none") {
            if (breakpoint() == SMALL && isHrBarClicked || (breakpoint() == SMALL && isCompleteClick)) {
                if (isSemiViewMobile) {
                    resultListContainerDisplay("flex");
                } else {
                    resultListContainerDisplay("block");
                }
            } 
            if (breakpoint() != SMALL) {
                resultListContainerDisplay("block");
            }
            searchTextLabel.style.marginTop = "0";
        }
    }

    function resultListContainerDisplay(display) {
        var resultListContainer = document.getElementById("result-list-container");
        resultListContainer.style.display = display;
    }

    function retailersFoundDisplay(display) {
        if (storeResultList.length == 0) {
            document.getElementById("retailersFoundCount").innerHTML = 0;
        }

        var retailersFound = document.getElementById("div-retailersFound");
        var searchTextLabel = document.getElementById("div-search-textLabel");
        retailersFound.style.display = display;

        if (breakpoint() === SMALL) {
            if (isDefaultMobileView && display == "none") {
                searchTextLabel.style.display = "none";
                retailersFound.style.display = "none";
                searchTextLabelClassList(false);
            } else {
                if (display === "block") {
                    searchTextLabel.style.display = "none";
                    searchTextLabelClassList(false);
                } else {
                    searchTextLabel.style.display = "block";
                    searchTextLabelClassList(true);
                }    
            }
        } else {
            if (display === "block") {
                searchTextLabel.style.display = "none";
                searchTextLabelClassList(false);
            } else {
                searchTextLabel.style.display = "block";
                searchTextLabelClassList(true);
            }
        }
    }

    function retailersContainer(stores) {
        if (stores.length <= retailersMaxCount) {
            retailersFoundDisplay("block");

            if (stores.length === 0) {
                resultListContainerClassList(false);

                // for mobile
                // if (breakpoint() == SMALL) {
                //     seachLocatorContainerClassList(false);    
                // }
                // retailersFoundDisplay("none"); 
            } else {
                resultListContainerClassList(true);
                retailersFoundDisplay("block"); 

                // for mobile
                if (breakpoint() == SMALL && isHrBarClicked) {
                    if (!isFromMarker) {
                        // do nothing
                    } else {
                        seachLocatorContainerClassList(true);
                    }
                }

                // If select from autocomplete then set to open or select mode
                if (stores.length == 1 && isCompleteClick) {
                    const divId = stores[0].MarkerIndex + "-" + stores[0].Guid;
                    markers[stores[0].MarkerIndex].setIcon(selectedIconPin);
                    dealerItemStyleDisplay(divId, false);
                    selectedItemId = divId;
                }
            }
        } else {
            isHrBarClicked = false;
            resultListContainerClassList(false);
            // for mobile
            if (breakpoint() == SMALL) {
                defaultMobileView();
                // seachLocatorContainerClassList(false);
            } else {
                retailersFoundDisplay("none");
            }
        }

        try {
            document.getElementById("retailersFoundCount").innerHTML = stores.length;
        } catch(e) {

        }

        /////////
        if (isSemiViewMobile) {
            // from top most to semi view
            var searchLocatorContainer = document.getElementById("dealer-locator-search__container");
            searchLocatorContainer.classList.remove("dealer-locator-search__container__onInput");
            searchLocatorContainer.removeAttribute("style");
            if (isHrBarClicked) {
                resultListContainerDisplay("flex")
                adjustSemiViewMobile();
            }
        }
    }

    //--------------------------------------------------------
    // function used to handle the select item in list
    //--------------------------------------------------------
    function selectItemInList(storeFound, isClickSeeMore) {
        isFromSelectList = true;
        isFromMarker = false;
        isSeeMore = isClickSeeMore;
        selectedStore = storeFound;

        appendDealerUrl(null, storeFound.LocationName + ", " + storeFound.City + " " + storeFound.Country);
        setLatLngHit(storeFound.Latitude, storeFound.Longitude, false, null);
    }

    function resetVar() {
        selectedItemId = "";
        isDefaultMobileView = false;
        isFromSelectList = false;
        isSemiViewMobile = false;
        isFromMarker = false;
        isHrBarClicked = false;
        isCompleteClick = false;
        isSeeMore = false;
        selectedStore = null;

        resetMarkerIcons();
        $('.dealerLocatorResult__wrapper').remove();
        resetDefaultLabel();
        storeResultList = [];
        resetCheckboxFilters();
        getSelectedFilters();
    }

    function handleSearchIcons(isDefault, isClearOnly) {
        var iconsearch = document.getElementById('dealerlocatorSearchIcon');
        var icontimes = document.getElementById('dealerlocatorTimesIcon');
        var iconDivider = document.getElementById('dealerlocatorDividerIcon');
        var addressInputText = document.getElementById("addressInput");

        if (isDefault) {
            addressInputText.classList.remove("input-group__text__onInput");
            iconsearch.classList.remove("dealerlocatorSearchIcon__onSearch");
            icontimes.classList.remove("dealerlocatorTimesIcon__onSearch");

            icontimes.style.display = "none";
            iconDivider.style.display = "none";
            iconsearch.style.display = "block";
        } else {
            if (isClearOnly) {
                icontimes.style.display = "block";
                iconDivider.style.display = "none";
                iconsearch.style.display = "none";
            } else {
                addressInputText.classList.add("input-group__text__onInput");
                iconsearch.classList.add("dealerlocatorSearchIcon__onSearch");
                icontimes.classList.add("dealerlocatorTimesIcon__onSearch");

                icontimes.style.display = "block";
                iconDivider.style.display = "block";
                iconsearch.style.display = "block";
            }
        }
    }

    function handleClickSearch() {
        var addressInputText = document.getElementById("addressInput");
        var addressInputVal = addressInputText.value.length != 0;

        if (addressInputVal) {
            handleSearchIcons(false, false);
            searchLocations();
            resetMarkerIcons();
        }
    }
});

var appendDealerUrl = function (e, injectedValue) {

    let pendingUrl = "";
    let useHash = true;

    if (injectedValue !== undefined) {
        pendingUrl = injectedValue;
        useHash = false;
    } else {
        const it = $(e);
        pendingUrl = it.attr("data-appendUrl");
    }

    pendingUrl = pendingUrl.replace("#", "*|HASH|*");
    pendingUrl = pendingUrl.replace("&", "*|AND|*");
    pendingUrl = pendingUrl.replace("?", "*|QUEST|*");
    pendingUrl = pendingUrl.replace("/", "*|RIGHT|*");
    pendingUrl = pendingUrl.replace("\\", "*|LEFT|*");

    const urlValues = window.location.href.split('?');
    const baseUrl = urlValues[0];

    var urlParams = new URLSearchParams(urlValues[1]);
    urlParams.set('q', pendingUrl);
    const endUrl = "?" + urlParams.toString();

    let anchorUrl = ""
    if (useHash) {
        if (urlValues[1] != undefined) {
            const endUrlValues = urlValues[1].split('#');

            if (endUrlValues[1] != undefined) {
                anchorUrl = "#" + endUrlValues[1];
            }
        }
    }

    const newUrl = baseUrl + endUrl + anchorUrl;

    window.history.pushState("", "", newUrl);
};;

$(".openMediaHighlightModal").on("click",
    function() {
        var id = $(this).attr("data-id");
        $("." + id).css("display", "block");
    });

$(".closeMediaHighlightModal").on("click",
    function () {
        var id = $(this).attr("data-id");
        $("." + id).css("display", "none");
    });
;

$(document).ready(function () {
    $(".jsChangeProductDisplay").on("click",
        function() {
            var key = $(this).attr("data-key");

            $(".jsProductDisplay").css("display", "none");
            $("."+key).css("display", "block");
        });
});

;

$(document).ready(function () {
    setArticleMediaPosition();
});

$(window).resize(function () {
    setArticleMediaPosition();
});

var setArticleMediaPosition = function () {
    const articlePage = $("#jsArticlePage");
    const articlePageWidth = articlePage.width();

    if ($(window).width() > 1280) {
        const articleMediaWrap = $("#jsArticleMediaWrap");

        const articleMediaWrapWidth = articleMediaWrap.width();
        let marginLeft = (articleMediaWrapWidth - articlePageWidth) / 2;
        marginLeft = marginLeft * -1;

        articleMediaWrap.css({ marginLeft: marginLeft + "px" });
    }
};
$(document).ready(function () {
    var skipCount = 12;
    var takeCount = 12;
    var hasMoreRecords = true;
    var isFetching = false;

    function FetchDataFromServer() {
        if (!hasMoreRecords) {
            return;
        }
       
        $.ajax({
            url: UrlSettings.CurrentUrl + '/LoadArticles',
            data: {
                skip: skipCount,
                take: takeCount,
            },
            method: 'GET',
            datatype: 'application/json',
            success: function (data) {
                if ($(data).filter('div.article-card-container').length < takeCount) {
                    hasMoreRecords = false;
                    if ($('#fetchMoreArticles').length > 0) {

                        $("#fetchMoreArticles").hide();
                        var elem = document.getElementById('fetchMoreArticles');
                        elem.parentNode.removeChild(elem);
                    }
                }

                $("#articleList").append(data);
                isFetching = false;
                skipCount += takeCount; // update for next iteration
            },
            error: function () {
                alert("error");
            }
        });
    }
    $(window).on("scroll", function () {
        if ($('#fetchMoreArticles').length > 0) {

            var winHeight = $(window).height(); // viewport 
            if (($(window).scrollTop() + winHeight >= $("#fetchMoreArticles").position().top + 150) && !isFetching) {
                isFetching = true;
                FetchDataFromServer();
            }
        }
    });
});;
