﻿function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, '');
    }
}

var isSearchTextTermRemoved = false; // Flag to track if search text term removed


//function used for search page,category page and tag page
function getSearchResult(isSort = true, latestSelecetedFacet="") {
    $("#divProgress").show();
    //get display type,sort by and page size
    var Url = '?displaytype=' + $("#drpProductDisplayType").val();
    Url = Url + '&pagesize=' + $("#drpPageSize").val();
    if (isSort) {
        Url = Url + "&sortby=" + $("#drpSortBy").val();
    }

    if (latestSelecetedFacet != "") {
        Url = Url + "&latestSelection=" + latestSelecetedFacet;
    }


    //get product type
    var selectedProductType = $('input[name=SelectedProductType]:checked');
    var producttype = "";
    selectedProductType.each(function () {
        producttype += $(this).attr("value") + ","
    });
    producttype = producttype.substring(0, producttype.length - 1);
    if (producttype != "") {
        Url = Url + "&productType=" + producttype;
    }

    //get other media type
    var selectedOtherMediaType = $('input[name=SelectedOtherMediaType]:checked');
    var othermediatype = "";
    selectedOtherMediaType.each(function () {
        othermediatype += $(this).attr("value") + ","
    });
    othermediatype = othermediatype.substring(0, othermediatype.length - 1);
    if (othermediatype != "") {
        Url = Url + "&othermediatype=" + othermediatype;
    }



    //get category
    var selectedCategory = $('input[name=SelectedCategory]:checked');
    var category = "";
    selectedCategory.each(function () {
        category += $(this).attr("value") + ","
    });   
    category = category.substring(0, category.length - 1);
    if (category != "") {
        Url = Url + "&category=" + category;
    }

    //get topicarea
    var SelectedTopicArea = $('input[name=SelectedTopicArea]:checked');
    var topicarea = "";
    SelectedTopicArea.each(function () {
        topicarea += $(this).attr("value") + ","
    });
    topicarea = topicarea.substring(0, topicarea.length - 1);
    if (topicarea != "") {
        Url = Url + "&topicArea=" + topicarea;
    }


    //get monthName
    var monthName = $('input[name=MonthName]:checked');
    var getmonth = "";
    monthName.each(function () {
        getmonth += $(this).attr("value") + ","
    });
    getmonth = getmonth.substring(0, getmonth.length - 1);
    if (getmonth != "") {
        Url = Url + "&eventdate=" + getmonth;
    }


    //get registrant types : #12836
    var selectedRegistrantTypes = $('input[name=SelectedchkRegistrantTypes]:checked').map(function () { return this.value; }).get().join(',');
    if (selectedRegistrantTypes) {
        Url = Url + "&registrantProductTypeIds=" + selectedRegistrantTypes;
    }


    if (producttype == "" && category == "" && getmonth == "" && topicarea == "" && othermediatype == "" && selectedRegistrantTypes == "") {
        $("#txtsst").val("");
    }
    Url = Url + "&sst=" + $("#txtsst").val();


    //search text value
    var search = $("#txtSearch").val() || $("#txtProductSearch").val() || "";

    if (search.trim() != "") {
        Url = Url + "&search=" + encodeURIComponent(search);
    } else {
        var searchTermsarray = JSON.parse($("#hdSearchTerms").val());
        for (var i = 0; i < searchTermsarray.length; i++) {
            if (searchTermsarray[i].sst == 's' && !isSearchTextTermRemoved) {
                Url = Url + "&search=" + encodeURIComponent(searchTermsarray[i].Name);
            }
        }
    }

    //search closed captioning
    var isClosedCaptioning = $(".chkClosedCaptioning").prop('checked');
    if (isClosedCaptioning != undefined) {
        Url = Url + "&isClosedCaptioning=" + isClosedCaptioning;
    }

    //search duration, legacy search

    var duration = $("#duration-slider").val();
    if (duration != undefined) {
        var fromDuration = duration.split(';')[0];
        var toDuration = duration.split(';')[1];
        Url = Url + "&fromDuration=" + fromDuration + "&toDuration=" + toDuration;
    }

    //search by duration filter
    var fromDuration = $("#txtFromDuration").val();
    var toDuration = $("#txtToDuration").val();
    if (fromDuration || toDuration) {
        Url = Url + "&fromDuration=" + fromDuration + "&toDuration=" + toDuration;
    }

    //search by Zip Code start
    var zipCode = $("#txtZipCode").val();
    var distanceMiles = $("#drpMiles").val();
    if (zipCode != undefined && zipCode != '' && zipCode != "") {
        Url = Url + "&zipCode=" + zipCode + "&distanceMiles=" + distanceMiles;

    }
    //search by Zip Code end

    //search by subscription 
    var subscriptionId = $('input[name=SubscriptionRadio]:checked').val();
    if (subscriptionId != undefined && subscriptionId > 0) {
        Url = Url + "&subscriptionId=" + subscriptionId;
    }

    //live event venue location #10438
    var cityVenueIds = "";
    $('input[name=ChkProductCity]:checked').each(function () {
        cityVenueIds += $(this).attr("value") + ","
    });
    cityVenueIds = cityVenueIds.substring(0, cityVenueIds.length - 1);

    var stateVenueIds = "";
    $('input[name=ChkProductState]:checked').each(function () {
        stateVenueIds += $(this).attr("value") + ","
    });
    stateVenueIds = stateVenueIds.substring(0, stateVenueIds.length - 1);

    if (stateVenueIds != "" || cityVenueIds != "") {
        Url = Url + "&cityVenueIds=" + cityVenueIds + "&stateVenueIds=" + stateVenueIds;
    }
    //live event venue location #10438

    var discountId = $('#hdDiscountId').val();
    if (discountId != undefined && discountId != null && discountId > 0) {
        Url = Url + "&discountId=" + discountId;
    }

    var productGroupCampaignId = $('#hdProductGroupCampaignId').val();
    if (productGroupCampaignId != undefined && productGroupCampaignId != null && productGroupCampaignId > 0) {
        Url = Url + "&productGroupCampaignId=" + productGroupCampaignId;
    }

    var latitude = $('#hdnLatitude').val();
    if (latitude != undefined && latitude != null) {
        Url = Url + "&gioLat=" + latitude;
    }

    var longitude = $('#hdnLongitude').val();
    if (longitude != undefined && longitude != null) {
        Url = Url + "&gioLong=" + longitude;
    }

    var geoSearchByCity = $('#txtGeoSearchByCity').val();
    if (geoSearchByCity) {
        Url = Url + "&geoSearchByCity=" + geoSearchByCity;
    }

    //search by event date filter
    var eventFromDate = $("#txtStartingOnOrAfter").val();
    var eventToDate = $("#txtStartingOnOrBefore").val();
    if (eventFromDate || eventToDate) {
        Url = Url + "&dateStartingOnOrAfter=" + eventFromDate + "&dateStartingOnOrBefore=" + eventToDate;
    }

    //#22352
    var certCreditTypeIds = $('.drpSelect2').val() || [];
    if (certCreditTypeIds.length > 0) {
        Url += '&CertCreditTypeIds=' + certCreditTypeIds;
    }

    //#22351
    var certJurisdications = $('#certJurisdicationFilter').val() || [];
    if (certJurisdications.length > 0) {
        Url += '&CertJurisdictionIds=' + certJurisdications;
    }
    var myProductFilter = $('#drpMyProductFilter').val();
    if (myProductFilter) {
        Url += '&myProductFilter=' + myProductFilter;
    }

    if ($("#drpProductDisplayType").val() == "3")
        window.location = "/calendar" + Url;
    else
        window.location.href = '/search' + Url;
}

function toggleShowMore(facetType) {
    var showMoreElement = $(`#${facetType}`).find(".show-more-link");
    var doShow = showMoreElement.text() === "Show More";

    var listItems = $(`#${facetType} .list-group-item`);
    listItems.each(function () {
        var listItem = $(this);
        var checkbox = listItem.find('input[type="checkbox"]');
        var isChecked = checkbox.prop('checked')
        if (listItem.find('.badge').text() === '0' && !isChecked) {
            listItem.css("display", doShow ? 'block' : 'none');
        }
    });
    showMoreElement.text(doShow ? "Show Less" : "Show More");
}

function getParam(params, name) {
    const keys = Array.from(params.keys());
    const key = keys.find(key => key.toLowerCase() === name.toLowerCase());
    return key ? params.get(key) : null;
}

function ClearAndRecheckCheckBoxes(params) {
    // uncheck and recheck all filters, in case the user used the back button on their browser
    $(".chkProductType").prop("checked", false);
    $(".chkCategory").prop("checked", false);
    $(".chkMonthDates").prop("checked", false);
    $(".clsChkbCity").prop("checked", false);
    $(".clsChkbState").prop("checked", false);
    $(".chkTopicAreas").prop("checked", false);
    $(".chkClosedCaptioning").prop("checked", false);
    $(".chkRegistrantTypes").prop("checked", false);

    var registrantParams = params.get('registrantProductTypeIds');
    if (registrantParams) {
        var reigstrantIds = registrantParams.split(',');
        reigstrantIds.forEach(function (id) {
            $(".chkRegistrantTypes[value='" + id + "']").prop("checked", true);
        });
    }

    var productTypeValue = getParam(params, 'productType');
    if (productTypeValue) {
        var productTypes = productTypeValue.split(',');
        productTypes.forEach(function (productType) {
            $(".chkProductType[value='" + productType + "']").prop("checked", true);
        });
    }

    var otherProductTypeValue = getParam(params, 'othermediatype');
    if (otherProductTypeValue) {
        var otherProductType = otherProductTypeValue.split(',');
        otherProductType.forEach(function (productType) {
            $(".chkProductType[value='" + productType + "']").prop("checked", true);
        });
    }

    var categoryTypeValues = params.get('category');
    if (categoryTypeValues) {
        var categories = categoryTypeValues.split(',');
        categories.forEach(function (category) {
            $(".chkCategory[value='" + category + "']").prop("checked", true);
        });
    }

    var topicAreaParams = params.get('topicArea');
    if (topicAreaParams) {
        var topicAreas = topicAreaParams.split(',');
        topicAreas.forEach(function (topicArea) {
            $(".chkTopicAreas[value='" + topicArea + "']").prop("checked", true);
        });
    }

    var monthParams = params.get('eventdate');
    if (monthParams) {
        var months = monthParams.split(',');
        months.forEach(function (month) {
            $(".chkMonthDates[value='" + month + "']").prop("checked", true);
        });
    }

    var cityParams = params.get('cityVenueIds');
    if (cityParams) {
        var cities = cityParams.split(',');
        cities.forEach(function (city) {
            $(".clsChkbCity[value='" + city + "']").prop("checked", true);
        });
    }

    var stateParams = params.get('stateVenueIds');
    if (stateParams) {
        var states = stateParams.split(',');
        states.forEach(function (state) {
            $(".clsChkbState[value='" + state + "']").prop("checked", true);
        });
    }

    var topicAreaParams = params.get('topicArea');
    if (topicAreaParams) {
        var topicAreas = topicAreaParams.split(',');
        topicAreas.forEach(function (topicArea) {
            $(".chkTopicAreas[value='" + topicArea + "']").prop("checked", true);
        });
    }

    var monthParams = params.get('eventdate');
    if (monthParams) {
        var months = monthParams.split(',');
        months.forEach(function (month) {
            $(".chkMonthDates[value='" + month + "']").prop("checked", true);
        });
    }


    var cityParams = params.get('cityVenueIds');
    if (cityParams) {
        var cities = cityParams.split(',');
        cities.forEach(function (city) {
            $(".clsChkbCity[value='" + city + "']").prop("checked", true);
        });
    }

    var stateParams = params.get('stateVenueIds');
    if (stateParams) {
        var states = stateParams.split(',');
        states.forEach(function (state) {
            $(".clsChkbState[value='" + state + "']").prop("checked", true);
        });
    }

    var isClosedCaptioningParam = params.get('isClosedCaptioning')
    if (isClosedCaptioningParam === 'true') {
        $(".chkClosedCaptioning").prop("checked", true);
    }
}

$(document).ready(function () {

    var queryString = window.location.search;
    // Create an object to store the parameters
    var params = new URLSearchParams(queryString);
    var latestSelectedFacetFromUrl = params.get("latestSelection");

    ClearAndRecheckCheckBoxes(params);

    if (!latestSelectedFacetFromUrl) {
        latestSelectedFacetFromUrl = "";
    }

    var lblText = $("#lblSearchPagging").text();
    if (lblText != undefined && lblText != null && lblText != "") {
        $("#lblSideBarPagging").text(lblText);
    }

    //#22352
    $('.drpSelect2').multiselect({
        includeSelectAllOption: true,
        selectAllValue: 'multiselect-all',
        buttonWidth: '100%',
        nonSelectedText: 'Select Credit Type',
        maxHeight: 400,
        enableFiltering: true,
        enableCaseInsensitiveFiltering: true
    });

    $('#certJurisdicationFilter').multiselect({
        includeSelectAllOption: true,
        selectAllValue: 'multiselect-all',
        buttonWidth: '100%',
        nonSelectedText: getCertJurisdictionName(),
        maxHeight: 400,
        enableFiltering: true,
        enableCaseInsensitiveFiltering: true
    });

    var productGroupCampaignId = $('#hdProductGroupCampaignId').val();
    if (productGroupCampaignId != undefined && productGroupCampaignId != '' && productGroupCampaignId != null) {
        $('.select2-container').css("min-width", "215px").css("max-width", "250px");
        $('.select2-drop').css("min-width", "215px").css("max-width", "250px");
        $('.select2-search').css("min-width", "215px").css("max-width", "250px");

        $('.select2-search > input').css("min-width", "205px");
    }

    var searchTermsarray = JSON.parse($("#hdSearchTerms").val());

    if (searchTermsarray.length > 0) {
        var jurisdictionIdsSearchArray = [];
        var certCreditIdsSearchArray = [];

        for (var i = 0; i < searchTermsarray.length; i++) {
            var searchTerm = searchTermsarray[i];
            if (searchTerm.sst == 'certJurisdictionIdsSearch') {
                jurisdictionIdsSearchArray.push(searchTermsarray[i].Id);
            }
            else if (searchTerm.sst == 'certCreditIdsSearch') {
                certCreditIdsSearchArray.push(searchTermsarray[i].Id);
            }
        }

        if (jurisdictionIdsSearchArray.length > 0) {
            $('#certJurisdicationFilter').val(jurisdictionIdsSearchArray).multiselect('refresh');
        }

        if (certCreditIdsSearchArray.length > 0) {
            $('#certCreditType').val(certCreditIdsSearchArray).multiselect('refresh');
        }
    }

    $(".divsearchterms").find("input[type=text]").hide();


    //set value from query string
    $("body").on("click", ".chkProductType", function () {
        var pdtype = $(this).attr('data-type');
        if ($("#txtsst").val() == "" && (pdtype == 11 || pdtype == 14)) {
            $("#txtsst").val("o");
        } else if ($("#txtsst").val() == "") {
            $("#txtsst").val("p");
        }

        //22264
        //var sortby = [51, 52];//51= Sort by Date (Ascending), 52= Sort by Date (Descending) 
        //var nonLiveSeminarCount = 0;
        //var selectedProductTypes = $(".chkProductType:checked:not([data-type =" + pdtype + "])").map(function () {
        //    return $(this).attr('data-type');
        //}).get();

        //if (nonLiveSeminarCount == 0 && sortby.indexOf($("#drpSortBy").val()) > -1 && !MediaTypes.isLiveType(pdtype)) {
        //    $("#drpSortBy").val('11');
        //}

        //if (getParameterByName('sortby') == "" && (pdtype == 1 || pdtype == 2 || pdtype == 3) && nonLiveSeminarCount == 0) {
        //    $("#drpSortBy").val("51");
        //}

        getSearchResult(true, "ProductTypeId");
    });
    $("body").on("click", ".chkCategory", function () {
        if ($("#txtsst").val() == "")
            $("#txtsst").val("c");
        getSearchResult(true, "Categories"); //21954
    });
    $("body").on("click", ".chkMonthDates", function () {
        if ($("#txtsst").val() == "")
            $("#txtsst").val("d");
        getSearchResult(true, "MonthStartDates");
    });
    $("body").on("click", ".chkTopicAreas", function () {
        if ($("#txtsst").val() == "")
            $("#txtsst").val("t");
        getSearchResult(true, "TopicAreas");
    });

    //subscription search #7154
    $("body").on("click", ".rblSubscription", function () {
        if ($("#txtsst").val() == "")
            $("#txtsst").val("ss");
        getSearchResult();
    });

    $("body").on("keypress", "#frmSideBarSearch", function (e) {
        kCode = e.keyCode || e.charCode //for cross browser
        if (kCode == 13) {
            var defaultbtn = $(this).attr("DefaultButton");
            $("#" + defaultbtn).click();
            return false;
        }
    });

    $("#drpProductDisplayType").on("change", function () {
        getSearchResult();
    });
    $("body").on("change", "#drpPageSize", function () {
        getSearchResult(true, latestSelectedFacetFromUrl);
    });
    $("#drpSortBy").on("change", function () {
        getSearchResult(true, latestSelectedFacetFromUrl);
    });

    $("#btnZipSearch").on("click", function () {
        var zipCode = $("#txtZipCode").val().trim('');
        var distanceMiles = $("#drpMiles").val();
        var discountId = $('#hdDiscountId').val(); // BUG ID #24995
        var productGroupCampaignId = $('#hdProductGroupCampaignId').val();
        if (zipCode != undefined && zipCode != '' && zipCode != "") {
            $("#divProgress").show();
            var zipSearhURL = "?zipCode=" + zipCode + "&distanceMiles=" + distanceMiles + "&productGroupCampaignId=" + productGroupCampaignId + "&discountId=" + discountId;
            window.location.href = '/search' + zipSearhURL;
        }
    });

    $("#btnGeoSearchByCity").on("click", function () {
        getSearchResult();
    });


    $("#btnDateFilterSearch").on("click", function () {
        getSearchResult(true, "DateFilter");
    });

    $("#btnDurationSearch").on("click", function () {
        getSearchResult();
    });


    //  Search Terms
    var elt = $('#txtSearchTerm');

    var hdSearchTerms = JSON.parse($("#hdSearchTerms").val());
    elt.tagsinput({
        tagClass: function (item) {
            return 'label label-default';
        },
        itemValue: 'value',
        itemText: 'text'
    });

    //Set serach filters
    $.each(hdSearchTerms, function (index, data) {
        elt.tagsinput('add', { "value": data.Id + '-' + data.sst, "text": data.Name, "sst": data.sst, "id": data.Id });
    });
    $("#txtSearchTerm").parent().find('input[type="text"]').attr("style", "display:none;");
    //$("#txtSearchTerm").parent().append("<label class='hidden' for='btTag'>Keyword</label>");
    //Before Remove search tag
    $('#txtSearchTerm').on('itemRemoved', function (event) {
        if (event.item.sst == 't') {
            var removeItem = event.item.id.toString();
            var chk = $('.chkTopicAreas[value="' + removeItem + '"]');
            chk.trigger('click');
        }
        else if (event.item.sst == 'p') {
            var removeItem = event.item.id.toString();
            var chk = $('.chkProductType[name="SelectedProductType"][value="' + removeItem + '"]');
            chk.trigger('click');
        }
        else if (event.item.sst == 'o') {
            var removeItem = event.item.id.toString();
            var chk = $('.chkProductType[name="SelectedOtherMediaType"][value="' + removeItem + '"]');
            chk.trigger('click');
        }
        else if (event.item.sst == 'c') {
            var removeItem = event.item.id.toString();
            var chk = $('.chkCategory[value="' + removeItem + '"]');
            chk.trigger('click');
        }
        else if (event.item.sst == 's') {
            isSearchTextTermRemoved = true;
            $("#txtSearch, #txtProductSearch").val("");
            getSearchResult();
            isSearchTextTermRemoved = false;
        }
        else if (event.item.sst == 'd') {
            var removeItem = event.item.id.toString();
            var chk = $('.chkMonthDates[value="' + removeItem + '"]');
            chk.trigger('click');
        }
        else if (event.item.sst == 'tag') {
            var removeItem = event.item.id.toString();
            getSearchResult();
        }
        else if (event.item.sst == 'cc') {
            $('.chkClosedCaptioning').attr('checked', false);
            getSearchResult();
        }
        //cert credit type
        else if (event.item.sst == 'cct') {
            $("#certCreditType").val(0);
            getSearchResult();
        }

        else if (event.item.sst == 'zcs') {
            $("#txtZipCode").val('');
            $("#drpMiles").val(25);
            getSearchResult();
        }

        else if (event.item.sst == 'geoSearchByCity') {
            $("#hdnLatitude").val('');
            $("#hdnLongitude").val('');
            $("#txtGeoSearchByCity").val('');
            getSearchResult();
        }

        else if (event.item.sst == 'ss') {
            $('input[name="SubscriptionRadio"]').prop('checked', false);
            getSearchResult();
        }
        else if (event.item.sst == 'liveEventState') {  //10438
            var removeItem = event.item.id.toString();
            var chk = $('.clsChkbState[value="' + removeItem + '"]');
            chk.trigger('click');
        }
        else if (event.item.sst == 'liveEventCity') {
            var removeItem = event.item.id.toString();
            var chk = $('.clsChkbCity[value="' + removeItem + '"]');
            chk.trigger('click');
        }
        else if (event.item.sst == 'dateStartingOnOrAfter') {  //10436
            $("#txtStartingOnOrAfter").val('');
            getSearchResult();
        }
        else if (event.item.sst == 'dateStartingOnOrBefore') {  //10436
            $("#txtStartingOnOrBefore").val('');
            getSearchResult();
        }
        else if (event.item.sst == 'rpt') { //#12836
            var removeItem = event.item.id.toString();
            var chk = $('.chkRegistrantTypes[value="' + removeItem + '"]');
            chk.trigger('click');
        }
        else if (event.item.sst == 'certCreditIdsSearch') {
            var removeItem = event.item.id.toString();
            $("#certCreditTypes option[value=\"" + removeItem + "\"]").remove().multiselect('refresh');
            getSearchResult();
        }
        else if (event.item.sst == 'certJurisdictionIdsSearch') {  
            var removeItem = event.item.id.toString();
            $("#certJurisdicationFilter option[value=\"" + removeItem + "\"]").remove().multiselect('refresh');
            getSearchResult();
        }
    });

    //$("#txtSearch").val(getParameterByName('search'));

    if ($("#hdnSortBtnId").val() != null && $("#hdnSortBtnId").val() != "") {
        if ($("#hdnSortBtnId").val() == "btnUp") {
            $("#btnUp").addClass("disabled");
            $("#btnDown").removeClass("disabled");
        }
        else {
            $("#btnDown").addClass("disabled");
            $("#btnUp").removeClass("disabled");
        }
    }

    $("body").on("click", ".chkClosedCaptioning", function () {
        getSearchResult(true, "TranscriptCount");
    });

    $(".btnUpDown li[class!='active'] > a").click(function () {
        $("#divProgress").show();
    });

    // getting product realted information and update the div that data
    getProductsInfo();


});

//start Duration slider
String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10); // don't forget the second param
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours < 10) { hours = "0" + hours; }
    if (minutes < 10) { minutes = "0" + minutes; }
    if (seconds < 10) { seconds = "0" + seconds; }
    var time = '';
    if (hours > 0) {
        time = hours + ':' + minutes; //+ ':' + seconds;
    } else {
        time = minutes;//+ ':' + seconds;
    }
    return time;
}

var fromDuration = $("#fromDuration").val();
var toDuration = $("#toDuration").val();
var maxDuration = $("#maxDuration").val();


//$("#duration-slider").ionRangeSlider({
//    type: 'double',
//    min: 0,
//    max: Number(maxDuration),
//    from: Number(fromDuration),
//    to: Number(toDuration),
//    grid: true,
//    keyboard: true,
//    //   force_edges: true,
//    //prettify: function (num) {
//    //    //console.log(num)
//    //    return (num * 60).toString().toHHMMSS();
//    //},
//    grid: true,
//    onFinish: function (data) {
//        var duration = $("#duration-slider").val();
//        if (duration != undefined) {
//            getSearchResult();
//        }
//    },
//});



//});
if (maxDuration > 85) {
    $("#duration-slider").ionRangeSlider({
        type: "double",
        min: 0,
        max: Number(maxDuration),
        from: Number(fromDuration),
        to: Number(toDuration),
        grid: true,
        keyboard: true,
        onFinish: function (data) {
            var duration = $("#duration-slider").val();
            if (duration != undefined) {
                getSearchResult(latestSelecetedFacet = "Duration");
            }
        },
    });
}
else {
    $("#duration-slider").ionRangeSlider({
        type: "double",
        min: 0,
        max: Number(maxDuration),
        from: Number(fromDuration),
        to: Number(toDuration),
        step: 1,
        grid: true,
        grid_snap: true,
        keyboard: true,
        onFinish: function (data) {
            var duration = $("#duration-slider").val();
            if (duration != undefined) {
                getSearchResult(latestSelecetedFacet="Duration");
            }
        },
    });
}

//search by live event venue #10438
$("body").on("click", ".clsChkbState", function () {
    if ($("#txtsst").val() == "")
        $("#txtsst").val("liveEventState");
    getSearchResult(true, "VenueIdToState");
});
$("body").on("click", ".clsChkbCity", function () {
    if ($("#txtsst").val() == "")
        $("#txtsst").val("liveEventCity");
    getSearchResult(true, "IdtoCityWithAbbreviationtoState");
});



// #10436 
$("body").on("change", ".clsDatePicker", function () {
    var dateValue = $(this).val();

    if (validateDatePicker(dateValue) == false) { $(this).val(''); }
});

function ValidateDate(dtValue) {
    var dtRegex = new RegExp(/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](18|19|20|21)\d\d+$/);
    if (dateFormate == "ddMMyyyy")
        dtRegex = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/);
    return dtRegex.test(dtValue);
}
function validateDatePicker(dateValue) {
    if (dateValue != undefined && dateValue != null && dateValue != "") {
        if (ValidateDate(dateValue)) {
        }
        else {
            return false;
        }
    }
}
// #10436


//#12836
$("body").on("click", ".chkRegistrantTypes", function () {
    if ($("#txtsst").val() == "")
        $("#txtsst").val("rtp");
    getSearchResult(true, "ProductRegistrantTypes");
});

$("#txtGeoSearchByCity").autocomplete({
    minLength: 3,   //Don't ask for suggestions until atleast 3 characters have been typed. This will reduce costs by not making requests that will likely not have much relevance.
    source: function (request, response) {
        $.ajax({
            url: "/Search/AddressAutoComplete",
            global: false,
            data: {
                query: request.term
            },
            success: function (data) {
                response(data);
            }
        });
    },
    change: function (event, ui) {
        if (ui.item != null && ui.item != undefined) {
            var selection = ui.item;
            $("#hdnLatitude").val(ui.item.latitude);
            $("#hdnLongitude").val(ui.item.longitude);
        }
        else {
            //When a search has been started.
            $("#hdnLatitude").val('');
            $("#hdnLongitude").val('');
        }
    },
});

//#22352 //#22351 //#5232843921
$("body").on("click", "#btnSearchCredits, #btnSearchCertJurisdictions, #btnMyProductFilter", function () {
    getSearchResult();
});

function getCertJurisdictionName() {
    var certJurisdictionName = $("#customCertJurisdictionName").text();
    if (!certJurisdictionName) {
        certJurisdictionName = "Select Cert Jurisdications";
    }
    return "Select " + certJurisdictionName;
}