﻿(function ($) {
    $.webSvc = function (options) {
        var settings = $.extend({
            'svcPath': '',
            'methodName': '',
            'async': true,
            'cache': false,
            timeout: 5000,
            debug: false,
            'parameters': {},
            success: function (response) { },
            error: function (response) { }
        }, options); var parameterjson = "{}";
        var result = null;
        if (settings.parameters != null) { parameterjson = JSON.stringify(settings.parameters); }
        $.ajax({
            type: "POST",
            url: settings.svcPath + "/" + settings.methodName,
            data: parameterjson,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: settings.async,
            cache: settings.cache,
            timeout: settings.timeout,
            success: function (value) {
                result = value.d;
                settings.success(result);
            },
            error: function (response) {
                settings.error(response);
                if (settings.debug) { alert("Error Calling Method \"" + settings.methodName + "\"\n\n+" + response.responseText); }
            }
        });
        return result;
    };
    $.getCookie = function (cookieName) {
        var re = new RegExp(cookieName + "=([^;]+)");
        var value = re.exec(document.cookie);
        return (value != null) ? unescape(value[1]) : null;
    };
    $.cartId = function () {
        var cartId = $.getCookie('JacksCart');
        if (!cartId)
            cartId = 0;

        return cartId;
    };
})(jQuery);

var searchTimeout;
var searchValue = '';
$(document).ready(function () {

    try {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_pageLoaded(EndRequestHandler);
    } catch (e) {
    }

    $('.dropdown-menu .left-tabs a.nav-link').on('click', function (e) {

        $('.dropdown-menu .left-tabs a.nav-link').removeClass('active');
        $(this).addClass('active');
        $('.dropdown-menu .tab-content .tab-pane').removeClass('active');
        $(this.hash).addClass('active');
        return false;
    });
    $('.dropdown-menu a.dropdown-toggle').on('click', function (e) {
        if (!$(this).next().hasClass('show')) {
            $(this).parents('.dropdown-menu').first().find('.show').removeClass("show");
        }
        var $subMenu = $(this).next(".dropdown-menu");
        $subMenu.toggleClass('show');


        $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function (e) {
            $('.dropdown-submenu .show').removeClass("show");
        });

        return false;
    });

    $("#txtSearch").keydown(function (e) {
        if (e.keyCode === 13) {
            doPartSearch();
            return false;
        } else {
            return e;
        }
    });
    $("#txtSearch").keyup(function (e) {
        if (searchTimeout)
            clearTimeout(searchTimeout);

        searchValue = $("#txtSearch").val();

        if (searchValue.length > 0)
            $('#btnResetMainSearch').show();
        else
            $('#btnResetMainSearch').hide();

        searchTimeout = window.setTimeout(function () {
            if (searchValue.length >= 3) {
                if (e.keyCode !== 32)
                    OnSearch(searchValue);
            }
            else
                resetSerachBox();
        }, 325);
    });
    var nav1Width = $('#topNav1').width();
    $('#txtSearch').focus(function () {
        var options = { direction: "up" };
        $('#topNav1').animate({ width: "0px" });
        $('#divSearchBox').show("slide", options, 250, null);
        if (searchValue.length > 0)
            $('#btnResetMainSearch').show();
    });
    $('#txtSearch').blur(function () {
        window.setTimeout(function () {
            var options = { direction: "up" };
            $('#divSearchBox').hide("slide", options, 250, null);
            $('#topNav1').animate({ width: nav1Width });
            if (searchValue.length === 0)
                $('#btnResetMainSearch').hide();
        }, 100);
    });
    $('#btnMainSearch').click(function () {
        if ($('#txtSearch').val().length >= 3)
            doPartSearch();
        else {
            var options = { direction: "up" };
            $('#divSearchBox').show("slide", options, 500, null);
            $("#divSearchBox").empty();
            $("<div class='row'><div class='col-12 searchPrompt'>Type 3 or more characters</div></div>").appendTo("#divSearchBox");
        }

        return false;
    });
    $('#btnResetMainSearch').click(function () {
        $('#txtSearch').val('');
        resetSerachBox();
        return false;
    });

    searchValue = $("#txtSearch").val();
    $('#btnResetMainSearch').hide();

    $('.seo-ads img').addClass('img-fluid');
    $('table.order img').addClass('img-fluid img-thumbnail');
    $('.parts-display img').addClass('img-fluid img-thumbnail');
    $('#model-locator img').addClass('img-fluid img-thumbnail');

    $(window).scroll(function () {
        var scTop = $(this).scrollTop();
        if (setScroll)
            setScroll(scTop);

        if (scTop > 50) {
            $('#back-to-top').fadeIn();
        } else {
            $('#back-to-top').fadeOut();
        }
    });
    $('#back-to-top').click(function () {
        $('body,html').animate({ scrollTop: 0 }, 'slow');
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
        return false;
    });

    //-- from base.js
    var touch = $('#menu');
    var menu = $('.nav .contentcontainer ul');
    $(touch).click(function (e) {
        e.preventDefault(); menu.slideToggle();
    });
    $(window).resize(function () {
        var w = $(window).width();
        // breakpoint
        if (w > 767 && menu.is(':hidden')) { menu.removeAttr('style'); }
    });
    $("a.login").click(function () {
        $(".sign-in").show();
        $(".sign-in a.close").click(function () {
            $(".sign-in").hide();
            return false;
        });
        return false;
    });
    $("a.hours").click(function () {
        $(".phone-hours p").show();
        $(".phone-hours a.close").click(function () {
            $(".phone-hours p").hide();
            return false;
        });
        return false;
    });
    if ($(".r-section").length) {
        for (var i = 0; i < 3; i++) {
            var height = $(".review:eq(" + i + ")").height();
            var pHeight = $(".review:eq(" + i + ") .r-part").height();
            var tHeight = $(".review:eq(" + i + ") .r-text").height();
            if (height < (pHeight + tHeight)) {
                $(".review:eq(" + i + ")").append("<span class='see-more'><a data-rev='" + i + "' href='#'>. . . see more . . .</a></span>");
            }
        }
        $("span.see-more a").click(function () {
            var rev = $(this).attr("data-rev");
            if ($(this).html() == ". . . see more . . .") {
                $(".review:eq(" + rev + ")").css({ "height": "auto" });
                $(this).html(". . . view less . . .");
            } else {
                $(".review:eq(" + rev + ")").css({ "height": height + "px" });
                $(this).html(". . . view more . . .");
            }
            return false;
        });
    }

    $('.cartButton').prop('disabled', false);
    $('.cartButton').prop('title', '');
    $('.amButton').prop('disabled', false);
    //$('.amButton').prop('disabled', false);

    getCartCount();
});

function getCartCount() {
    var cartEl = $('#spanCartCount');
    if (cartEl) {
        var cartId = $.cartId();
        if (cartId > 0) {
            $.webSvc({
                'svcPath': '/jacks-parts-lookup/uc/ToolTipWebService.asmx', 'methodName': 'getCartCount', 'async': true, 'parameters': { 'cartId': cartId },
                success: function (value) {
                    try {
                        $(cartEl).text(value);
                    } catch (e) {
                        alert(e.message);
                        $(cartEl).text('?');
                    }
                },
                error: function (response) {
                    alert(response.responseText);
                    $(cartEl).text('?');
                }
            });
        } else {
            $(cartEl).text('0');
        }
    }
}
function EndRequestHandler(sender, args) {
    if (getScroll) {
        var scTop = getScroll();
        document.body.scrollTop = scTop;
        document.documentElement.scrollTop = scTop;
    }
}  
function setCartCount(numItems) {
    $('#spanCartCount').text(numItems);
}

function doPartSearch() {
    var searchValue = $("#txtSearch").val();
    if (searchValue.length >= 3) {
        var redirectUrl = "//" + document.siteBaseUrl + "/jacks-parts-lookup/part/" + encodeURIComponent(searchValue.trim()).replace('%2F', '/');
        //showRedirectLoadingPanel();
        $('#divSearchBox').fadeOut();
        window.location = redirectUrl;
    }
    else {
        var options = { direction: "up" };
        $('#divSearchBox').show("slide", options, 500, null);
        resetSerachBox();
    }
    return false;
}
function OnSearch(searchTerm) {
    $('#btnResetMainSearch').hide();
    $("#txtSearch").addClass('searchingGif');
    $.ajax({
        url: document.searchApiEndpoint + encodeURIComponent(searchTerm.trim()),
        type: "Get",
        success: function (sections) {
            $("#txtSearch").removeClass('searchingGif');
            $('#btnResetMainSearch').show();
            $("#divSearchBox").empty();
            var headHtml = "<div class='row'><div class='col-sm-12 searchHead'>";
            if (sections.length > 0)
                headHtml += "Search Results for <b><i>" + searchTerm.trim() + "</i></b>";
            else
                headHtml += "<h6>We can't seem to locate anything that matches <b><i>" + searchTerm.trim() + "</b></i></h6>";
            headHtml += "</div></div>";
            $(headHtml).appendTo("#divSearchBox");

            for (var s = 0; s < sections.length; s++) {
                var rowHtml = "<div class='row'>";

                //section name
                rowHtml += "<div class='col-sm-3 searchSection searchSectionName'><h6>" + sections[s].label + "</h6></div>";
                var imageClass = 'searchItemImage';
                if (sections[s].label === "Part Categories")
                    imageClass = 'searchItemImageCategory';

                var data = sections[s].items;
                rowHtml += "<div class='col-sm-9 searchSection searchSectionDetail'><div class='pt-1'>";
                for (var i = 0; i < data.length && i < 4; i++) {
                    rowHtml += "<div class='row pb-3'>";
                    rowHtml += "<div class='col-3 searchItem " + imageClass + "'><a href='" + data[i].itemUrl + "'><img class='img-fluid' src='" + data[i].imageUrl + "' /></a></div>";
                    rowHtml += "<div class='col-9 searchItem searchItemDesc'><a href='" + data[i].itemUrl + "'>" + data[i].itemResult + "</a></div>";
                    rowHtml += "</div>";
                }
                rowHtml += "</div></div></div>";

                $(rowHtml).appendTo("#divSearchBox");
            }

        }
        , error: function (msg) { $("#txtSearch").removeClass('searchingGif'); }
    });
}
function resetSerachBox() {
    $("#divSearchBox").empty();
    $("<div class='row'><div class='col-sm-12 searchPrompt'>Type a Part#, Model# or Keyword</div></div>").appendTo("#divSearchBox");
}
var curRedirectLoadingPanel = null;
var curRedirectControl = null;
function hideRedirectLoadingPanel() {
    setTimeout(function () {
        if (currentLoadingPanel !== null)
            currentLoadingPanel.hide(currentUpdatedControl);
        currentUpdatedControl = null;
        currentLoadingPanel = null;
    }, 250);
}

window.HFCHAT_CONFIG = {
    EMBED_TOKEN: 'e9065fc0-5fe5-11ea-b41e-230bece049e3',
    ASSETS_URL: 'https://widget.happyfoxchat.com/v2/visitor'
};
(function () {
    var scriptTag = document.createElement('script')
    scriptTag.type = 'text/javascript'
    scriptTag.async = true
    scriptTag.src = window.HFCHAT_CONFIG.ASSETS_URL + '/js/widget-loader.js'

    var s = document.getElementsByTagName('script')[0]
    s.parentNode.insertBefore(scriptTag, s)
})()

var HappyFoxChat;
window.HFCHAT_CONFIG.onload = function () {
    HappyFoxChat = this;
}

function OpenChat() {
    try {
        HappyFoxChat.getAgentsAvailability(function (err, agentsAvailability) {
            if (err) {
                console.error('Failed to get agent availability');
            } else {
                if (agentsAvailability) {
                    console.info('Online');
                    HappyFoxChat.expandChatbox(function (err) {
                        if (err) {
                            console.error('Failed to expand chatbox. Error:', err);
                        } else {
                            console.log('chat expanded');
                        }
                    });
                }
                else {
                    console.info('Offline')
                    $('#chatOfflineModal').modal('show');
                }
            }
        });
    } catch (e) {
        console.error(e);
        $('#chatOfflineModal').modal('show');
    }
}