$(function () {
    var productSearch = new ProductSearch.FindProducts();
    productSearch.initialize();
});
var ProductSearch;
(function (ProductSearch) {
    var FindProducts = /** @class */ (function () {
        //#endregion
        //#region Constructor
        function FindProducts() {
            var _this = this;
            //#region Private Members
            this.currentLanguage = $(".findproducts").data("currentLanguage");
            this.currentMarket = $(".findproducts").data("currentMarket");
            this.currentVehicleType = $(".findproducts").data("currentVehicletype");
            this.regCountries = new Array("gb", "ie", "pt");
            this.sivCountries = new Array("fr");
            this.kbaCountries = new Array("de");
            this.vinCountries = new Array("es", "it", "pl", "ru", "tr", "cn");
            $(".findproducts").on("submit", "form", function (event) {
                event.preventDefault();
                var form = $(event.currentTarget);
                if (form.valid()) {
                    var action = form.attr("action");
                    var method = form.attr("method");
                    //Set method and parameters into localStorage
                    var actionData = { 'action': action, 'method': method, 'formData': form.serialize() };
                    localStorage.setItem("actionData", JSON.stringify(actionData));
                    //Remove parameters from localStorage if vehicletypeselector is choosen before
                    localStorage.removeItem("queryParams");
                    var containerToBlock = $("html");
                    containerToBlock.block({
                        message: Utilities.ajaxLoaderWhiteHtml(50)
                    });
                    $.ajax(action, {
                        data: form.serialize(),
                        type: method
                    }).done(function (data, status, jqXHR) {
                        if (jqXHR.status === 204) {
                            var redirectUrl = jqXHR.getResponseHeader("X-Product-Search-Results-Url");
                            //Check that we are not already on the results page
                            if (window.location.href.indexOf(redirectUrl) > -1) {
                                containerToBlock.unblock();
                            }
                            else {
                                window.location.href = redirectUrl;
                            }
                        }
                        else {
                            var container = $(".find-products-wrapper");
                            container.html(data);
                            $.validator.unobtrusive.parse(container);
                            _this.initialize();
                            _this.marketSelected();
                            containerToBlock.unblock();
                            var productSearch = new ProductSearch.FindProducts();
                            productSearch.initialize();
                        }
                    });
                }
            });
            this.marketSelected();
        }
        //#endregion
        //#region Public Methods
        FindProducts.prototype.ChangeVehicleType = function (vehicleselector, newVehicleType) {
            if (newVehicleType === void 0) { newVehicleType = null; }
            $.post(vehicleselector.data("persistSelectionUrl"), { vehicleType: newVehicleType }, function (data) {
            }).done(function (data) {
                $('.vehicletypetab').removeClass('selected');
                if (newVehicleType == "P") {
                    $('#tabcar').addClass('selected');
                }
                else if (newVehicleType == "O") {
                    $('#tabhgv').addClass('selected');
                }
                else if (newVehicleType == "M") {
                    $('#tabbike').addClass('selected');
                }
                $('#vehiclesearchtext').val(data);
            });
            this.marketSelected(null, newVehicleType);
            var changeLocation = $(".cataloguesearchresultspage").length > 0;
            if (changeLocation) {
                localStorage.removeItem("queryParams");
                localStorage.removeItem("actionData");
                var catalogueSearchResultsPageUrl = $(".catalogue-page").data("catalogueResultPage");
                if (Utilities.isUndefinedNullOrEmpty(catalogueSearchResultsPageUrl)) {
                    catalogueSearchResultsPageUrl = $("#catalogue-product").data("catalogueresultpage") + "?vehicleType=" + newVehicleType;
                }
                if (!Utilities.isUndefinedNullOrEmpty(catalogueSearchResultsPageUrl)) {
                    window.location.href = catalogueSearchResultsPageUrl + "?vehicleType=" + newVehicleType;
                }
            }
        };
        FindProducts.prototype.ChangeMarket = function (marketselector, newMarketCountryCode) {
            if (newMarketCountryCode === void 0) { newMarketCountryCode = null; }
            console.log('selection changed to:' + newMarketCountryCode);
            this.marketSelected(newMarketCountryCode);
            //Save the new market selection to the server - saved in session state
            $.post(marketselector.data("persistSelectionUrl"), { market: newMarketCountryCode }, function (data) {
            }).done(function (data) {
                var _this = this;
                $('.market-currentcountry').html(data);
                var changingSearchMethod = false;
                //US market changed to non-US or Non-US market changed to US market, reload page
                if ((this.currentMarket == 'us' && newMarketCountryCode != 'us')
                    || (this.currentMarket != 'us' && newMarketCountryCode == 'us')) {
                    changingSearchMethod = true;
                    //$(".partsearch").hide();
                }
                var changeWhereToBuy = $(".wheretobuypage, .wheretobuyinstallerpage, wheretobuyenduserpage, .catalogueproductpage").length > 0;
                //ES or PT market changed to non-ES or PT market
                if ((this.currentMarket == 'es' && newMarketCountryCode != 'es')
                    || (this.currentMarket != 'es' && newMarketCountryCode == 'es')) {
                    changeWhereToBuy = true;
                }
                //ES or PT market changed to non-ES or PT market
                if ((this.currentMarket == 'pt' && newMarketCountryCode != 'pt')
                    || (this.currentMarket != 'pt' && newMarketCountryCode == 'pt')) {
                    changeWhereToBuy = true;
                }
                //CN market changed to non-CN or vice-versa
                if ((this.currentMarket == 'cn' && newMarketCountryCode != 'cn')
                    || (this.currentMarket != 'cn' && newMarketCountryCode == 'cn')) {
                    changeWhereToBuy = true;
                }
                //RU market changed to non-RU or vice-versa
                if ((this.currentMarket == 'ru' && newMarketCountryCode != 'ru')
                    || (this.currentMarket != 'ru' && newMarketCountryCode == 'ru')) {
                    changeWhereToBuy = true;
                }
                if (changeWhereToBuy) {
                    localStorage.removeItem("queryParams");
                    localStorage.removeItem("actionData");
                    window.location.href = window.location.href;
                }
                if (changingSearchMethod) { // Just redirect to page after clearing stored data - market has already been set
                    localStorage.removeItem("queryParams");
                    localStorage.removeItem("actionData");
                    var catalogueSearchResultsPageUrl = $(".catalogue-page").data("catalogueResultPage");
                    if (Utilities.isUndefinedNullOrEmpty(catalogueSearchResultsPageUrl)) {
                        catalogueSearchResultsPageUrl = $("#catalogue-product").data("catalogueresultpage");
                    }
                    if (!Utilities.isUndefinedNullOrEmpty(catalogueSearchResultsPageUrl)) {
                        window.location.href = catalogueSearchResultsPageUrl;
                    }
                }
                else {
                    //Get the last search method and parameters
                    var actionData = localStorage.getItem('actionData');
                    var actionDataObject = JSON.parse(actionData);
                    var shouldSearch = false;
                    //Get the last search method and parameters if vehicletypeselector is choosen before 
                    var paramsDataObject = JSON.parse(localStorage.getItem('queryParams'));
                    if (paramsDataObject != null) {
                        localStorage.removeItem("actionData");
                        $(".catalogue-page").data("marketFallback", newMarketCountryCode);
                        paramsDataObject.market = newMarketCountryCode;
                        location.hash = $.param(paramsDataObject);
                    }
                    if (actionDataObject != null) {
                        localStorage.removeItem("queryParams");
                        //Check what type is last search method and if it is available for the new selected market
                        if (actionDataObject.action.indexOf("KBASearch") != -1 && $.inArray(newMarketCountryCode, this.kbaCountries) > -1) {
                            shouldSearch = true;
                        }
                        else if (actionDataObject.action.indexOf("RegistrationSearch") != -1 && $.inArray(newMarketCountryCode, this.regCountries) > -1) {
                            shouldSearch = true;
                        }
                        else if (actionDataObject.action.indexOf("SIVSearch") != -1 && $.inArray(newMarketCountryCode, this.sivCountries) > -1) {
                            shouldSearch = true;
                        }
                        else if (actionDataObject.action.indexOf("VINSearch") != -1 && $.inArray(newMarketCountryCode, this.vinCountries) > -1
                            || (newMarketCountryCode == "cn" && $.inArray(newMarketCountryCode, this.vinCountries) > -1 && this.currentLanguage != "")) {
                            shouldSearch = true;
                        }
                        // Part search method is avaliable for all markets and it is applied for the new selected merket
                        else if (actionDataObject.action.indexOf("PartSearch") != -1) {
                            shouldSearch = true;
                        }
                        if (shouldSearch) {
                            $.ajax(actionDataObject.action, {
                                method: actionDataObject.method,
                                data: actionDataObject.formData
                            }).then(function (data, textStatus, jqXHR) {
                                if (jqXHR.status === 204) {
                                    window.location.href = jqXHR.getResponseHeader("X-Product-Search-Results-Url");
                                }
                                else {
                                    var container = $(".find-products-wrapper");
                                    container.html(data);
                                    $.validator.unobtrusive.parse(container);
                                    _this.initialize();
                                    _this.marketSelected();
                                }
                            }, function (jqXHR, textStatus, errorThrown) {
                            });
                        }
                        else {
                            //Reset search fields if last search method is not available for the new selected market
                            localStorage.removeItem("queryParams");
                            localStorage.removeItem("actionData");
                            var catalogueSearchResultsPageUrl = $(".catalogue-page").data("catalogueResultPage");
                            window.location.href = catalogueSearchResultsPageUrl + "#market=" + newMarketCountryCode + "&vehicleType=P";
                        }
                    }
                }
            });
        };
        FindProducts.prototype.initialize = function () {
            var _this = this;
            $(".marketselector > a").click(function (event) {
                event.preventDefault();
                _this.toggleMenu(event.currentTarget);
            });
            $(".marketselector").click(function (event) { return event.stopPropagation(); });
            $(".marketselector > .expanded-content > ul > li").click(function (event) {
                var target = $(event.currentTarget);
                var targetText = target.children("span").text();
                var targetTextCountryCode = target.children("input[type=hidden]").val();
                var marketselector = target.parents(".marketselector");
                marketselector.removeClass("open").children(".expanded-content").slideUp("fast");
                marketselector.find("a > span").text(targetText);
                marketselector.find("a > input[type=hidden]").val(targetTextCountryCode);
                _this.ChangeMarket(marketselector, targetTextCountryCode);
            });
            $('#vehicletypetabs > .vehicletypetab').click(function (event) {
                event.preventDefault();
                var target = $(event.currentTarget);
                var targetVehicleType = target.children("input[type=hidden]").val();
                var vehicleselector = target.parents("#vehicletypetabs");
                _this.ChangeVehicleType(vehicleselector, targetVehicleType);
            });
            $(".vehiclesearch > .search-button").click(function (event) {
                event.preventDefault();
                var action = "/FindProducts/VehicleSearch";
                var clientIP = $('#hdnClientIP').val();
                var params = {
                    clientIP: clientIP
                };
                $.ajax(action, {
                    data: params,
                    type: "GET"
                }).done(function (data, status, jqXHR) {
                    if (jqXHR.status === 204) {
                        window.location.href = jqXHR.getResponseHeader("X-Product-Search-Results-Url");
                    }
                    else {
                        //TODO?
                    }
                });
            });
            $('input[type=text][name="SIVSearch.SIVNumber"], input[type = text][name = "VINSearch.VINNumber"],  input[type = text][name = "PartSearch.PartNumber"]').tooltip({
                placement: "bottom",
                trigger: "hover focus",
                html: true
            });
            var clientIP = $('#hdnClientIP').val();
            $('input[name="KBASearch.ClientIP"], input[name="RegistrationSearch.ClientIP"], input[name="SIVSearch.ClientIP"], input[name="VINSearch.ClientIP"], input[name="PartSearch.ClientIP"]').val(clientIP);
            $('[data-toggle="popover"]').popover({
                html: true,
                placement: "bottom",
                trigger: 'hover focus',
                content: function () {
                    return '<img src="' + $(this).data('img') + '" alt="TRW Aftermarket" />';
                }
            });
            $("form").not('[data-toggle="popover"]').tooltip({
                placement: "bottom",
                trigger: "hover focus"
            });
            //Extra check on IP address to cater for proxy servers
            // ServerIP is what the server 'thinks' the client IP is
            var serverIP = $("#hdnServerIP").val();
            // ClientIP is what ipify returns from the client
            var clientIP = $("#hdnClientIP").val();
            //alert('Server IP:' + serverIP + '  Client IP:' + clientIP);
            // Need to invoke ajax call to get new value for current market if IP addresses differ
            if ($("#hdnClientIP").val() != '' && clientIP != serverIP) {
                $.post('/FindProducts/SetClientIP', { 'clientIP': clientIP }, function (data) {
                }).done(function (data) {
                    // Current market has been set on the server, so reload the page
                    window.location.href = window.location.href;
                });
            }
        };
        FindProducts.prototype.toggleMenu = function (target, forceHide) {
            if (target === void 0) { target = null; }
            if (forceHide === void 0) { forceHide = false; }
            var selector = (target !== null) ?
                ($(target).parents(".marketselector").length > 0) ?
                    $(target).parents(".marketselector") :
                    ($(target).parents(".vehicletypeselector").length > 0) ?
                        $(target).parents(".vehicletypeselector") :
                        null : null;
            if (selector !== null) {
                var expandedContent = selector.children(".expanded-content");
                if (selector.hasClass("open") || forceHide) {
                    expandedContent.slideUp("fast", function () { return selector.removeClass("open"); });
                }
                else {
                    expandedContent.slideDown("fast");
                    selector.addClass("open");
                }
            }
        };
        //#endregion
        //#region Private Methods
        FindProducts.prototype.getInitialValue = function () {
            //return $(".marketselector").find(":selected").val();
            return $(".marketselector").find("a > input[type=hidden]").val();
        };
        FindProducts.prototype.marketSelected = function (marketCountry, vehicleType) {
            if (marketCountry === void 0) { marketCountry = null; }
            if (vehicleType === void 0) { vehicleType = null; }
            if (marketCountry === null) {
                marketCountry = this.getInitialValue();
            }
            if (vehicleType === null) {
                vehicleType = this.currentVehicleType;
            }
            $(".search-padding").hide();
            $(".kbasearch").hide();
            $(".vinsearch").hide();
            $(".registrationsearch").hide();
            $(".sivsearch").hide();
            var noOfSelectors = 0;
            if (vehicleType == "M") {
                $(".marketselector").hide();
            }
            else {
                $(".marketselector").show();
                if ($.inArray(marketCountry, this.kbaCountries) > -1) {
                    $(".kbasearch").show();
                    noOfSelectors++;
                }
                else if ($.inArray(marketCountry, this.regCountries) > -1) {
                    $(".registrationsearch").show();
                    $(".registrationsearch > form > input").addClass(marketCountry);
                    noOfSelectors++;
                }
                else if ($.inArray(marketCountry, this.sivCountries) > -1) {
                    $(".sivsearch").show();
                    $(".sivsearch").removeClass("fr").addClass(marketCountry);
                    noOfSelectors++;
                }
                else if ($.inArray(marketCountry, this.vinCountries) > -1 //&& $.inArray(this.currentLanguage, this.vinCountries) > -1
                    || (marketCountry == "cn" && $.inArray(marketCountry, this.vinCountries) > -1 && this.currentLanguage != "")) { //TEMP FIX FOR CHiNESE SEARCH
                    $(".vinsearch").show();
                    noOfSelectors++;
                }
            }
            $(".partsearch").show();
            $(".vehicletypeselector").show();
            if (noOfSelectors === 0) {
                $(".search-padding").show();
            }
        };
        return FindProducts;
    }());
    ProductSearch.FindProducts = FindProducts;
})(ProductSearch || (ProductSearch = {}));
//# sourceMappingURL=find-products.js.map
var PaginationItem = /** @class */ (function () {
    function PaginationItem(pageNo, isCurrentPage) {
        this.pageNo = pageNo;
        this.isCurrentPage = isCurrentPage;
    }
    return PaginationItem;
}());
var PaginationModel = /** @class */ (function () {
    function PaginationModel(totalCount, pageNo, pageSize, maxPagesToShow) {
        if (pageSize === void 0) { pageSize = 10; }
        if (maxPagesToShow === void 0) { maxPagesToShow = 5; }
        this.previousPageNo = null;
        this.nextPageNo = null;
        this.totalCount = null;
        this.resultStart = null;
        this.resultEnd = null;
        this.pageNumbers = new Array();
        this.totalCount = totalCount;
        if (totalCount > 0) {
            if (Utilities.isUndefinedNullOrEmpty(pageNo) || isNaN(pageNo))
                pageNo = 1;
            var totalPages = Math.ceil(totalCount / pageSize);
            if (totalPages > 1 && pageNo > 1)
                this.previousPageNo = pageNo - 1;
            if (totalPages > 1 && pageNo < totalPages)
                this.nextPageNo = pageNo + 1;
            var startPageNo = 1;
            var maxPages = maxPagesToShow;
            if (totalPages <= maxPagesToShow) {
                maxPages = totalPages;
            }
            else {
                var halfway = Math.floor(maxPages / 2);
                startPageNo = pageNo - halfway;
                if (startPageNo < halfway)
                    startPageNo = 1;
                else if (totalPages - halfway < pageNo)
                    startPageNo = totalPages - maxPages + 1;
            }
            for (var i = 0; i < maxPages; i++) {
                var pageNumber = startPageNo++;
                this.pageNumbers.push(new PaginationItem(pageNumber, pageNumber == pageNo));
            }
            //Calculate result set start and end values
            this.resultStart = pageSize * (pageNo - 1) + 1;
            this.resultEnd = pageSize * pageNo;
            if (this.resultEnd > totalCount)
                this.resultEnd = totalCount;
        }
    }
    return PaginationModel;
}());
//# sourceMappingURL=utilities.js.map
