﻿//bundle
var BUNDLE_ADDTOCART_LINK = "/bundle1/addtocart/";
var BUNDLE_GET_PURCHASE_CE_PRICE_POPUP = '/bundle1/getbundlepurchasecepricepopup';
var BUNDLE_ADD_CECREDITTOCART_URL = "/bundle1/addbundlececredit";

// Account
var ACCOUNT_REGISTER_COMPANY_AUTOCOMPLETE = "/account/autocomplete/";
var ACCOUNT_REGISTER_COMPANY_DROPDOWN_AUTOCOMPLETE = "/account/AutocompleteCompany/";
var EMAIL_IN_USED_ACCOUNT_REGISTER = "/account/emailcheck";
var EMAIL_IS_MATCH_WITH_COMPANY_DOMAIN = "/account/emailmatchwithcompanydomain"
var GENERATE_NEW_GIFTCARD_URL = "/account/generatenewgiftcard";
var DELETE_SAVED_ITEM_URL = "/account/deletesaveditem";
var CHECK_REGISTRANT_EMAIL_URL = "/account/checkregistrantemail";
var UPLOAD_AVATAR_URL = "/account/uploadavatar";
var GET_STATE_URL = '/account/getstate/';
var GET_CONTACT_INFO_URL = '/account/getcontactinfo';
var GET_SHIPPING_INFO_URL = '/account/getshippinginfo/';
var CANCELLED_GIFT_CARD_URL = '/account/cancelledgiftcard';
var PENDING_SEMINAR = '/account/pendingseminar';
var COMPLETED_SEMINAR = '/account/completedseminar';
var SAVED_ITEMS = '/account/customersaveditem';
var GET_COMPARE_PRODUCT_URL = '/account/compareitemsview';
var GET_County_URL = '/account/getcounty/';
var CHECK_CUSTOMER_SICCODE = "/account/checkcustomersiccodes";
var GET_ORDERITEM_EVENTDATE = "/account/getorderitemeventdate";
var GET_CUSTOMER_LINKEDTENANTS = "/base/getlinkedtenants";
var CUSTOMER_CANCELMEMBERSHIP = "/account/cancelcustomermembership";
var CHECK_MARKETINGCONSENT_CUSTOMER = "/account/checkmarketingconsentcustomer";
var GET_CUSTOMER_ACCOUNT_MESSAGE_URL = "/account/getcustomeraccountmessage";
var GET_PREREQUSITE_PRODUCTS = "/account/getprerequsiteproducts";

var GET_CUSTOMER_GET_CUSTOMER_ADDRESS_LIST = "/account/getcustomeraddresslist";
var GET_CUSTOMER_CUSTOMER_GET_EXISTING_ADDRESSES = "/account/getcustomerexistingaddresses";

// QuestionAnswer
var DELETE_MESSAGE_URL = "/questionanswer/deletemessage/";
var MARK_AS_UNREAD_URL = "/questionanswer/markasunread/";
var COMPOSE_MESSAGE_URL = '/questionanswer/composemessage';
var QUESTION_ANSWER_LIST_URL = "/questionanswer/questionanswerlist";

// ShoppingCart
var SHOPPING_CART_HOME = "/shoppingcart/index";
var UPDATE_PRODUCT_QUANTITY_URL = "/shoppingcart/updateproductquantity";
var REMOVE_PROGRAM_REGISTRANT_URL = "/shoppingcart/removeprogramregistrant";
var REMOVE_REGISTRANT_URL = "/registrant/removeregistrants";
var UPDATE_PRODUCT_ITEM_AND_REGISTRANT_QTY = "/registrant/updateproductitemandregistrantqty";
var GET_REGISTRANT_DETAIL = "/registrant/getregistrantdetail";
var GET_REGISTRANT_PRODUCT_DETAIL = "/registrant/getregistrantproductdetail";

var REMOVE_ASSIGNLATER_REGISTRANTS = "/account/deleteprogramregforassignlater";
var UPDATE_BUNDLE_QAUNTITY_URL = "/shoppingcart/updatebundleqauntity";
var UPDATE_ORDER_EVENTDATE_URL = "/shoppingcart/updateordereventdate";
var MY_CART_URL = "/shoppingcart/mycart";
var REMOVE_ITEM_URL = "/shoppingcart/removeitem";
var UPDATE_OR_REMOVE_PRODUCT_BY_PARENTORDERITEM = "/shoppingcart/updateorremoveproductbyparentorderitem"; //#12528
var GET_ADDON_PRODUCT_IN_CART = "/shoppingcart/getaddonproductincart"; //#12528
var REMOVE_ITEM_FROM_BUNDLE_URL = "/shoppingcart/removeitemfrombundle";
var CHECK_GIFT_CARD_CODE_URL = "/shoppingcart/checkgiftcardcode";
var CHECK_GIFT_CARD_CODE_ALERDAY_APPLIED_URL = "/shoppingcart/checkgiftcardcodealerdayapplied";
var CHECK_COUPON_CODE_URL = "/shoppingcart/checkcouponcode";
var GET_CURRENT_DISCOUNT_DETAIL = "/shoppingcart/getcurrentdiscountdetail";
var REMOVE_COUPN_CODE_URL = "/shoppingcart/removecoupncode";
var SET_SHIPPING_METHOD_URL = "/shoppingcart/setshippingmethod";
var GET_SHIPPING_METHOD_URL = "/account/getshippingmethod";
var SAVE_SHIPPING_INFO_URL = "/account/shippinginfo";
var GET_SHIPPING_METHOD_BY_ADDRESS = "/account/getshippingmethodbyaddress";
var REMOVE_GIFT_CARD_CODE_URL = "/shoppingcart/removegiftcardcode";
var GET_CART_URL = '/shoppingcart/getcart';
var GET_RECEIPT = '/shoppingcart/receiptpart';
var GET_COMPAREPRODUCTCART_URL = '/shoppingcart/getcompareproductcart';
var APPLY_GLOBAL_AUTO_DISCOUNT_URL = '/shoppingcart/applyglobalautodiscount';
var SET_BILLING_ZIPCODE_URL = "/shoppingcart/setbillingzipcode";
var GET_MULTIPAYMENTS_ITEMS = '/items/multipayment';
var POST_MULTIPAYMENTS_ITEMS = "/items/savemultipayment";
var GET_PAYMENTINFO_ADDRESS_DETAIL = "/account/paymentinfoaddressdetail";
var UPDATE_CHANGED_PRICE_CART_ITEMS = "/shoppingcart/updatechangedpricecartitems"; //#17693
var REWARD_POINTS_NOTIFICATION_URL = '/shoppingcart/rewardpointsnotification';

// Items
var SAVE_PARTICIPATION_CODE_URL = "/items/saveparticipationcode";
var AUTO_SAVE_PARTICIPATION_CODE_URL = "/items/autosaveparticipationcode";
var SAVE_EVALUATION_URL = "/items/saveevaluation";
var SAVE_AFFIDAVIT_URL = "/items/saveaffidavit";
var ADD_TO_CART_URL = "/items/addtocart";
var SAVE_TO_CALENDAR_URL = "/items/savetocalendar";
var GET_EVALUATION_URL = '/items/getevaluation';
var GET_PARTICIPATION_CODE_URL = '/items/getparticipationcode';
var GET_AFFIDAVIT_URL = '/items/getaffidavit';
var GET_QUIZES_URL = '/items/getquizehistory';
var COMPLETED_CERT_REQUIREMENT = '/items/completedcertrequirement';
var COMPLETED_MOVE_REQUIREMENT = '/items/movetocompleted';
var ADD_COMPAREPRODUCT_URL = "/items/addcompareproduct";
var ADD_PURCHASEEXTENSION_URL = "/items/addtocartextension";
var ADD_CECREDITTOCART_URL = "/items/addcecredit";
var ADD_SAVE_SINGLE_PRODUCT_URL = "/items/savesingleproduct";
var GET_PRODUCT_AGENDATAB = "/items/getproductagenda";
var AGENDA_PRODUCT_POPUP = "/items/productagenda";
var AGENDA_CUSTOMER_ATTEDANCE = "/items/getcustomerattedanceconfirmation";
var CHECK_DISCOUNTPRODUCT_ELIGIBLITY = "/items/checkdiscountproducteligiblity";
var GET_ATTENDANCE_HISTORY = "/items/getattendancehistory";
var UPDATE_EXPIRED_DISCOUNTINCART = "/items/updateexpireddiscountincart";
var GET_LOGGEDINCUSTOMERID = '/items/getloggedincustomerid';
var GET_PURCHASECECREDIT_STATUS = '/items/getpurchasececreditstatus';
var GET_PRODUCTS_INFO = '/items/getproductsinfo';
var GET_PURCHASECE_PRICE_POPUP = '/items/getpurchasecepricepopup';
var CHECK_ADDON_OR_RELATEDPRODUCT_EXIST = '/items/checkaddonorrelatedproductexist';
var GET_ACKNOWLEDGE_PREREQUISITE_PRODUCTS = "/items/getacknowledgeprerequisiteproducts";

// Support
var ARTICLE_LIKED_URL = "/support/articleliked";
var ARTICLE_DISLIKED_URL = "/support/articledisliked";

// Additioal participant
var ADDITIONAL_PARTICIPANT_URL = "/search/additionalparticipantce";
var ADDITIONAL_PARTICIPANT_ADDTOCARTURL = "/search/addtocartadditionalpriceitem";

var Subscription_List_URL = "/search/subscriptionlist";
var Docreadyeventid = 1;
var DdlChangeid = 2;

//Bundle
var GET_BUNDLEDETAIL_URL = "/bundle2/bundledetail";
var GET_BUNDLETYPEFIVE_DATEPOPUP = "/items/bundletypefivemultidates";

// Company Catalog(Learning Management System) URL
var GET_CATALOG_USER_TAB_URL = "/companycatalog/getcatalogusertab";
var GET_CATALOG_COURSE_TAB_URL = "/companycatalog/catalogcoursestab";
var GET_CATALOG_COURSE_LIST_URL = "/companycatalog/getcatalogcourses";
var GET_CATALOG_SETTING_TAB_URL = "/companycatalog/getcatalogsetting";
var SAVE_CATALOG_SETTING_TAB_URL = "/companycatalog/updatecompanycatalogsetting";
var POST_HIDE_SHOW_COURSE_URL = "/companycatalog/showhidecourse";
var CATALOG_MESSAGE_URL = "/companycatalog/messageuser";
var CATALOG_DELETE_NOTES = "/companycatalog/deletenote";
var CATALOG_LOAD_NOTES = "/companycatalog/getallnotesbyentityidntype";
var CATALOG_SEND_CUSTOMER_ACCOUNTLINK = "/companycatalog/sendcustomeraccountlink";
var CATALOG_LOAD_CUSTOMER_USERDETAIL = "/companycatalog/cataloguserdetail";
var CATALOG_COURSE_LISTINGS_SEND_REQUEST_URL = "/companycatalog/sendcourserequest";
var CATALOG_COURSE_REQUEST_TAB_URL = "/companycatalog/catalogcourserequesttab";
var CATALOG_COURSE_ALLOW_DENY_URL = "/companycatalog/allowdenyaccess";
var CATALOG_LMS_USERTAB_USERLIST = "/companycatalog/getusers";
var CATALOG_LMS_ENROLUSER_URL = "/companycatalog/enrollusers/";
var CATALOG_LMS_ENROL_COURSE_URL = "/companycatalog/enrollcourses/"
var CATALOG_LMS_REMOVEUSERFROMENROL = "/companycatalog/removeusers";
var CATALOG_LMS_REMOVE_USER_FROM_COURSE = "/companycatalog/removecourse";
var CATALOG_ADD_COURSE_MY_ACCOUNT_URL = "/companycatalog/addcoursetomyaccount";
var CATALOG_USER_MESSAGE_TAB_URL = "/companycatalog/getmessagetab";
var CATALOG_USER_HISTORY_TAB_URL = "/companycatalog/getlmshistory";

//Speaker Portal
var SPEAKER_PORTAL_DELETEDOCUMENT_URL = "/documents/deletedocument";
var SPEAKER_PORTAL_DOCUMENT_TAB_URL = "/documents/getalldocumentsbyentityidntype";
var SPEAKER_PORTAL_PROFILEINFO_TAB_URL = "/speakerprofileinformation/getprofileinformation";
var SPEAKER_PORTAL_PRODUCT_TAB_URL = "/speakerproducts/getspeakerproducts";

//BUNDLE TYPE 4 ADD TO CART
var ADD_BUNDLE_TYPE_4_ADD_TO_CART_URL = "/bundletype4product/getproductlist";
var REMOVE_REWARDPOINT = "/shoppingcart/removerewardpoints";

//BUNDLE TYPE 5 Add Product by customer
var BUNDLE_TYPE_5_List_CUSTOMER_PRODUCT = "/bundletype5product/getcustomerbundleproductlist";
var BUNDLE_TYPE_5_ADD_CUSTOMER_PRODUCT = "/bundletype5product/addcustomerbundleproduct";
var BUNDLE_TYPE_5_ADD_CECREDITTOCART_URL = "/bundletype5product/addbundlefivececredit";

var GET_PURCHASEALERTMESSSAGE = "/items/getpurchasealertmesssage";
var GET_MULTIPLE_PURCHASEALERTMESSSAGE = "/items/getmultiplepurchasealertmesssageforbundle";

var LAUNCH_FREE_VIEWER_URL = "/LaunchFreeViewer";
var COMPLETE_FREE_ORDER_URL = "/CompleteFreeOrder";
var CLASSROOM_LOGIN_URL = '/sq/lg/LoginView';

//Banner Click Count
var BANNER_CLICK_COUNT = "/home/updateclickcountforbanneradvert";
var BANNER_SHOWN_COUNT = "/home/updatebannershowncount";
var CENCEL_PURCHASECE = "/items/cancelpurchaseforpurchasece";

//Group
var ADD_OUT_STANDING_INVOICE_IN_CART = "/group/addoutstandinginvoiceincart";
var RETRY_PENDING_INVOICE_PAYMENTS = "/group/retrypendinginvoicepayments"; //#19014
var DEACTIVATE_MEMBERSHIP_PAYMENT_PROFILE = "/group/deactivatemembershippaymentprofile";//#19014

//GuestBook
var CHECK_GBOOKCUSTOMER = "/guestbook/checkforguestbookcustomer";
var GET_GUESTBOOK_ORDER_SUMMARY = "/guestbook/getordersummary";


//Classified Ads
var ADD_TO_CART_CLASSIFIED_URL = "/ClassifiedAds/AddToCart";

var MediaTypes = {
    nonLiveTypes: [4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15],
    liveTypes: [1, 2, 3, 8],
    isLiveType: function (val) {
        return MediaTypes.liveTypes.indexOf(val) > -1
    }
}

var ISRELOADPAGE = false;

var newProductId = 0; //#24468

// Disable caching of AJAX responses
if (typeof ($.ajaxSetup) == "function") {
    $.ajaxSetup({ cache: false });
}

var width;
$(document).ready(function () {
    width = $(window).width();
    toggleSidebarToHamburger();
    loadAlertToolTip();
    updateCartCount();
    getComparelist();
    getCartItems();
    NoOfImg();
    updateProductNameWithoutDiscount($("#hdnProductNameWithNoDiscount").val());

    // #22137 - Remove Placeholder from SignUp Page
    $("#SignUp-form .socialmedia").attr("placeholder", "");


    // Hide blank message of validation summery
    if ($(".validation-summary-errors").length > 0 && $(".validation-summary-errors ul li:visible").length == 0) {
        $(".validation-summary-errors").hide();
    }

    $('[data-toggle="popover"]').popover({
        trigger: "hover",
        placement: 'auto top',
        html: true
    });

    $('.scheduleAtGlance').popover({ trigger: 'hover', placement: 'top' })
        .on("show.bs.popover", function () {
            return $(this).data("bs.popover").tip().css({ "width": "fit-content", "max-width": "500px" });
        });


    $(".clsCalenderTooltip").tooltip();

    if ($(".PendingPaymentPopOver").length > 0) {
        showPendingPaymentPopup();
    }

    if (document.getElementById("myCarousel") != null) {
        $("#myCarousel").carousel({
            interval: 10000
        });
    }
    //for ADA Requirement 
    if ($("#DivADARequirement").length > 0) {
        if ($("#ADARequirementNote").val() != "" && $("#ADARequirementNote") != undefined) {
            $("#ADARequirement").prop("checked", true);
        }
        if ($("#ADARequirement").prop("checked") == true) {
            $("#ADARequirementNote").attr("required", "required");
            $("#ADARequirementNote").closest("div").find("span.field-validation-error").show().html('');
        }
    }

    $('.recentcarousel').each(function () {
        var next = $(this).next();
        if (!next.length) {
            next = $(this).siblings(':first');
        }
        next.children(':first-child').clone().appendTo($(this));

        if (next.next().length > 0) {
            next.next().children(':first-child').clone().appendTo($(this));
        }
        else {
            $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
        }
    });
    if (document.getElementById("myCarousel1") != null) {
        $("#myCarousel1").carousel({
            interval: 10000
        });
    }

    //Sticky navbar
    function affixChange() {
        $('#cartbar').affix({
            offset: {
                top: ($(".headersection").outerHeight(true) + 25),
                bottom: null
            }
        });
    }
    affixChange();

    var offset = 250;
    var duration = 300;
    $(window).scroll(function () {
        affixChange();
        if (jQuery(this).scrollTop() > offset) {
            jQuery('.back-to-top').fadeIn(duration);
        } else {
            jQuery('.back-to-top').fadeOut(duration);
        }
    });

    $('.back-to-top').click(function (event) {
        event.preventDefault();
        jQuery('html, body').animate({ scrollTop: 0 }, duration);
        return false;
    });

    //$("#txtProductSearch").val(getParameterByName('search'));

    $(document).on('change', '.checkroundradiolbl input', function () {
        $('.divRadioAddress').removeClass('selected-address');
        if ($(this).is(':checked')) {
            $(this).closest('.divRadioAddress').addClass('selected-address');
        }
    });

    $("body").on('click', '.popAddtoCart', function () {

        if ($(this).hasClass("linkChangePrice")) {
            var arr = [];
            var productId = $(this).attr("data-productId");
            var swapProducts = localStorage.getItem('SwapProducts');

            if (swapProducts) {
                arr = JSON.parse(swapProducts);
            }

            if (arr.indexOf(productId) == -1) {
                arr.push(productId);
            }
            localStorage.setItem('SwapProducts', JSON.stringify(arr));
        }

        var url = $(this).attr("href");
        openAddToCartPopupModal(url);
        return false;
    });

    $("body").on('click', '.popAddtoCartFeePlan', function () {

        if ($(this).hasClass("linkChangePrice")) { 
            var arr = [];
            var productId = $(this).attr("data-productId");
            var swapProducts = localStorage.getItem('SwapProducts');

            if (swapProducts) {
                arr = JSON.parse(swapProducts);
            }

            if (arr.indexOf(productId) == -1) {
                arr.push(productId);
            }
            localStorage.setItem('SwapProducts', JSON.stringify(arr));
        }

        var url = $(this).attr("href");
        openAddToCartFeePlanPopupModal(url);
        return false;
    });

    $(".container").on('click', '.calendar_nav', function () {
        var calContainer = $(this).attr("data-rel");
        $.get($(this).attr("href"), function (data, status) {
            $("#" + calContainer).html(data);
            $(".clsCalenderTooltip").tooltip();
        });
        return false;
    });

    $("body").on('click', '.popUploadImage', function () {
        $.magnificPopup.open({
            items: {
                src: $(this).attr("href")
            },
            type: 'iframe',
            closeOnBgClick: false,
            enableEscapeKey: false,
            mainClass: 'popUploadImageMainClass'
        });
        $('.mfp-iframe-scaler iframe').each(function () {
            this.style.setProperty('background-image', 'none', 'important');
        });
        return false;
    });

    $("body").on('click', '.popCourseDescription', function () {
        $.magnificPopup.open({
            items: {
                src: $(this).attr("href")
            },
            type: 'iframe',
            closeOnBgClick: false,
            mainClass: 'popCourseDescriptionMainClass'
        });
        return false;
    });

    $("body").on('click', '.pop400', function () {
        $.magnificPopup.open({
            items: {
                src: $(this).attr("href")
            },
            type: 'iframe',
            closeOnBgClick: true,
            mainClass: 'pop400'
        });
        return false;
    });

    $("#tabDocuments").on('click', '.popDocumentUpload', function () {
        $.magnificPopup.open({
            items: {
                src: $(this).attr("href")
            },
            type: 'iframe',
            closeOnBgClick: false,
            mainClass: 'pop700MainClass'
        });
        return false;
    });

    $("body").on('click', '.popRequiredInfo', function () {
        $.magnificPopup.open({
            items: {
                src: $(this).attr("href")
            },
            type: 'iframe',
            closeOnBgClick: false,
            mainClass: 'popRequiredInfoMainClass'
        });
        return false;
    });
    $("body").on('click', '.pop850', function () {
        $.magnificPopup.open({
            items: {
                src: $(this).attr("href")
            },
            type: 'iframe',
            closeOnBgClick: false,
            mainClass: 'pop850mainClass'
        });
        return false;
    });

    $("body").on('click', '.popReactivate', function () {
        openPopup($(this).attr("href"));
        return false;
    });

    $("body").on('click', '.clsChangeGroupPopup', function () {
        var customerMembershipId = $(this).attr("data-customerMembershipId");
        var membershipTypeId = $(this).attr("data-membershipTypeId");
        var upgradeGroupPopupURL = "/Group/UpgradeGroupPopupMessage";
        var upgradeGroupURL = "/Group/UpgradeGroup?customerMembershipId=" + customerMembershipId + "&membershipTypeId=" + membershipTypeId;
        $.ajax({
            type: "GET",
            url: upgradeGroupPopupURL,
            dataType: "json",
            data: {
                'customerMembershipId': customerMembershipId,
                'membershipTypeId': membershipTypeId
            },
            success: function (data) {
                if (data && data.message) {
                    $.confirm({
                        title: "Membership Upgraded",
                        boxWidth: '550px',
                        useBootstrap: false,
                        type: 'green',
                        content: data.message,
                        buttons: {
                            ok: {
                                text: 'Ok',
                                btnClass: 'btn-success',
                                action: function () {
                                }
                            }
                        }
                    });
                } else {
                    $.magnificPopup.open({
                        items: {
                            src: upgradeGroupURL
                        },
                        type: 'iframe',
                        closeOnBgClick: false,
                        mainClass: 'pop1200MainClass'
                    });
                    return false;
                }
            },
            error: function (data) {
                alert('Error! Please try again later.');
            }
        });
    });

    /*
    //START: Two searchbox in _Header, both below #0008719
    $("#btnProductSearch").on("click", function () {
        //var prvSearch = getParameterByName('search');
        var search = $("#txtProductSearch").val();
        if (search.trim().length > 0) {
            search = encodeURIComponent(search);
            //if (prvSearch != null && prvSearch != '') {
            //    search = prvSearch + "~" + search;
            //}

            window.location.href = '/search?search=' + search;
        }
    });

    $("#btnProductSearchOutside").on("click", function () {
        //var prvSearch = getParameterByName('search');
        var search = $("#txtProductSearchOutside").val();
        if (search.trim().length > 0) {
            search = encodeURIComponent(search);
            //if (prvSearch != null && prvSearch != '') {
            //    search = prvSearch + "~" + search;
            //}

            window.location.href = '/search?search=' + search;
        }
    });
    //END: Two searchbox in _Header, both above
    */

    //START: #18359
    $(".toggle-password").on("click", function () {
        $(this).toggleClass("fa-eye fa-eye-slash");
        var passwordinput = $($(this).attr("data-toggleid"));
        if (!passwordinput) return false;
        if ((passwordinput.attr("type") || '') === "password") {
            passwordinput.attr("type", "text");
        } else {
            passwordinput.attr("type", "password");
        }
    });
    //END: #18359

    if ($(".topWishlistMessage").length > 0) {
        setTimeout(function () {
            $(".topWishlistMessage").remove();
        }, 5000);
    }

    if ($(".topSubscriptionsMessage").length > 0) {
        setTimeout(function () {
            $(".topSubscriptionsMessage").remove();
        }, 5000);
    }

    $("#content").on('click', '.pop700', function () {
        $.magnificPopup.open({
            items: {
                src: $(this).attr("href")
            },
            type: 'iframe',
            closeOnBgClick: true,
            mainClass: 'pop700'
        });
        return false;
    });

    $(document).ajaxStart(function () {
        $("#divProgress").show();
    });
    $(document).ajaxComplete(function () {
        $("#divProgress").hide();
        setTimeout(function () { updateCartCount(); }, 200);

        preventViewerLaunchInNewTab();
    });
    $(document).ready(function () {
        $("#divProgress").hide();
    });
    //form related jquery
    try {
        var IsContryExists = $("#IsContryExists").val();
        if (IsContryExists == "true") {
            //var formCountryId = $("#formCountryId").val();
            var formCountryId = $(".clsformCountryId").val();
            // if (formCountryId > 0) {
            frmGetAllState(formCountryId, Docreadyeventid);
            // }
        }
    } catch (e) {
    }
    //$('#formCountryId').change(function () {
    //    $('#divProgress').show();
    //    var formCountryId = $("#formCountryId").val();
    //    frmGetAllState(formCountryId);
    //});
    $('body').on('change', '.clsformCountryId', function () {
        $('#divProgress').show();
        var formCountryId = $(this).val();
        frmGetAllState(formCountryId, DdlChangeid);
    });

    setTimeout(function () { LoadCustomerBundleProductList(); }, 100);

    //DateTime Formate validation Start
    if (typeof (dateFormate) == "string" && dateFormate == 'ddMMyyyy' && $.validator) {
        $.validator.addMethod('date', function (value, element) {
            if (this.optional(element)) {
                return true;
            } var valid = true;
            try {
                $.datepicker.parseDate('dd/mm/yy', value);
            } catch (err) {
                valid = false;
            } return valid;
        });
    }
    // DateTime Formate validation End

    changePlaceHolderGlobalSearh();
    removeTableResponsiveCss();

    // Start -  #10435 Collapse (+)(-)
    $('.collapse').on('shown.bs.collapse', function (event) {
        if (event.target.id == 'filtersSidebarmenuInToggle')
            $(this).parent().find(".fa-chevron-down").removeClass("fa-chevron-down").addClass("fa-chevron-up");
        else
            $('#' + event.target.id).parent().find(".glyphicon-plus").removeClass("glyphicon-plus").addClass("glyphicon-minus");
    }).on('hidden.bs.collapse', function (event) {
        if (event.target.id == 'filtersSidebarmenuInToggle')
            $(this).parent().find(".fa-chevron-up").removeClass("fa-chevron-up").addClass("fa-chevron-down");
        else
            $('#' + event.target.id).parent().find(".glyphicon-minus").removeClass("glyphicon-minus").addClass("glyphicon-plus");
    });
    // End -  #10435 Collapse (+)(-)

    if (typeof SearchFiltersCollapse == "function") {
        SearchFiltersCollapse();
    }
    if ($('.datepicker').length > 0) {
        $('.datepicker').datepicker();
    }

    if ($('.DOBdatepicker').length > 0) {

        $('.DOBdatepicker').datepicker({
            defaultDate: new Date(new Date().setYear(2019 - 30)), //set the default date 
            changeMonth: true,
            changeYear: true,
            yearRange: "1900:" + (new Date().getFullYear() - 10) //set the range of years
        });

        $(".DOBdatepicker").on('blur', function () {
            try {
                var date = $.datepicker.parseDate(dateFormate == "ddMMyyyy" ? "dd/mm/yy" : "mm/dd/yy", $(this).val());
                if (date > new Date()) {
                    alert('Please select another date');
                    $(this).val('');
                }
            }
            catch (ex) {
                return false;
            }
        });

    }


    preventViewerLaunchInNewTab();
    //#21323
    $(".custom-mobileview #cartbar .navbar-toggle").click(function () {
        $(".overlay-Mobileview").toggleClass("overlay-div");
        $(".custom-mobileview .nav__sub").removeClass("is-active");
        if ($(".overlay-Mobileview").hasClass("overlay-div")) {
            $("body").css("overflow", "hidden");
        }
        else {
            $("body").css("overflow", "");
        }
    });

    if (window.location !== window.parent.location) {
        console.log("I'm stuck in an iFrame!");

        var pParse = document.createElement("a");
        pParse.href = document.referrer;
        var p = pParse.hostname;

        var cParse = document.createElement("a");
        cParse.href = document.URL;
        var c = cParse.hostname;

        if (p !== c) {
            $.ajax({
                type: "POST",
                url: "https://" + window.location.host + "/iframe",
                data: { "url": encodeURIComponent(document.referrer) + "|" + encodeURIComponent(document.URL) }
            });
        }
    }
    //#5633846136
    $('#createFreeAds').on('click', function (event) {
        event.preventDefault();
        var classifiedFeePlanId = $(this).data('searchproduct');
        if (!userIsAuthenticated()) {
            redirectToLogin();
        } else {
            createFreeClassifiedAd(classifiedFeePlanId);
        }
    });

    $('.carousel4item').each(function () {
        var totalItem = $(this).attr('data-totalItem') || 1;
        $(this).find('.carousel .item').each(function () {
            var i = $(this).next();
            i.length || (i = $(this).siblings(":first")),
                i.children(":first-child").clone().appendTo($(this));
            if (totalItem != 2 && totalItem != 3) {
                for (var n = 0; n < 2; n++)(i = i.next()).length ||
                    (i = $(this).siblings(":first")),
                    i.children(":first-child").clone().addClass('hidden-sm hidden-xs').appendTo($(this))
            }
            else if (totalItem == 3) {
                var j = i.next();
                j.length || (j = $(this).siblings(":first")),
                    j.children(":first-child").clone().addClass('hidden-sm hidden-xs').appendTo($(this));
            }
        })
    })

    if ($('.dropCompanyName').length > 0) {
        var companyLabel = "Company";
        if ($("#hdnCompanyCustomLaberl").val() != undefined && $("#hdnCompanyCustomLaberl").val() != '') {
            companyLabel = $("#hdnCompanyCustomLaberl").val();
        }
        bindCompanyNameDropdown(companyLabel,'.dropCompanyName'); //7780486500: bind company name dropdown 
    }

});
$("body").on("click", ".btnAddtowishlist", function () {
    var element = $(this);
    var labelId = $(this).attr('data-value');
    var Value = labelId.split(',');
    var eventTimeId = 0;
    var ProductId = Value[0];
    var Type = Value[1];
    var MultipleEventTimeId = $('.EventDate').val();
    var pagetype = '';
    var pageno = 1;
    var sortby = 11;
    var eventDateId = $(this).attr('data-eventTimeId');

    if (parent.$("#pageType").val() != undefined) {
        pagetype = parent.$("#pageType").val();
    }

    if (parent.$("#pageno").val() != undefined) {
        pageno = parent.$("#pageno").val();
    }
    if (parent.$("#sortby").val() != undefined) {
        sortby = parent.$("#sortby").val();
    }

    if (Type == "ShoppingCart") {
        eventTimeId = eventDateId;
    }
    else if (MultipleEventTimeId > 0) {
        eventTimeId = MultipleEventTimeId;
    }

    $.ajax({
        type: "POST",
        url: "/Items/SaveToCalendar",
        dataType: "json",
        data: {
            'ProductId': ProductId, 'eventDateId': eventTimeId, 'Type': Type
        },
        success: function (data) {
            if (data.WishlistCount > 0) {
                parent.$("#Wishlistcount").html("(" + data.WishlistCount + ")");
            }
            //compare Product item
            if (data.isCompareProduct != undefined && data.isCompareProduct == true) {
                parent.$("#compareProductcartspancount").html(data.compareProductCount);
                parent.$("#compareProductcartItemList").load(GET_COMPAREPRODUCTCART_URL);
            }
            //compare Product item
            if (pagetype == "CompareItem") {
                parent.$("#grid-compareProduct").load(GET_COMPARE_PRODUCT_URL + '?page=' + pageno + '&sortby=' + sortby);
            }
            if (data.Message != null && data.Message != "") {
                displayCartMessages(element, data, Type); //#16325

                //ShoppingCart
                if (data.Type != null && data.Type == 'ShoppingCart') {
                    //$("#grid-WishList").load('/Account/CustomerSavedItem');
                    //updateWishList();

                    var removeItem = $(element).prev().prev();
                    if (removeItem != null && $(removeItem).hasClass('RemoveItemFromCart') && data.isAlreadyPurchase == false) {
                        isRefreshWishList = true;
                        $(removeItem).trigger('click');

                    }
                    $("#spnMessage").html(data.Message);
                    $(".wishlistCart").show();
                }
            }

        },
        complete: function (data) {
        },
        error: function (data) {
            alert('Error! Please try again later.');
        }
    });
});

function ChangeAlterMessageClass(className, data) {
    if (className && data.Message) {
        if (data.IsPurchaseLimitExceeded) {
            $(className).find(".alert").removeClass('alert-success').addClass('alert-warning');
            $(className).find("i").removeClass('fa-check').addClass('fa-exclamation-circle');
        }
        else {
            $(className).find(".alert").removeClass('alert-warning').addClass('alert-success');
            $(className).find("i").removeClass('fa-exclamation-circle').addClass('fa-check');
        }
    }
}




function beginPagingSingleCol(args) {
    // Animate
    //$('#grid-list').fadeOut('normal');
}

function onRegisterSubmit() {
    $("#Widget-form").submit();
}

function successPagingSingleCol() {
    $("#dt_basic_wrapper_singlecol").attr("action", $("#pagingFormAction").attr("href"));
}

function failurePagingSingleCol() {
    alert("Could not retrieve list.");
}

function beginPagingTwoCol(args) {
    // Animate
    //$('#grid-list').fadeOut('normal');
}

function successPagingTwoCol() {
    $("#dt_basic_wrapper_twocol").attr("action", $("#pagingFormActiontwocol").attr("href"));
}

function failurePagingTwoCol() {
    alert("Could not retrieve list.");
}

function beginPagingThreeCol(args) {
    // Animate
    //$('#grid-list').fadeOut('normal');
}

function successPagingThreeCol() {
    $("#dt_basic_wrapper_threecol").attr("action", $("#pagingFormActionthreecol").attr("href"));
}

function failurePagingThreeCol() {
    alert("Could not retrieve list.");
}

function beginPagingSimpleProd(args) {
    // Animate
    //$('#grid-list').fadeOut('normal');
}

function successPagingSimpleProd() {
    $("#dt_basic_wrapper_simplepro").attr("action", $("#pagingFormActionsimplepro").attr("href"));
}

function failurePagingSimpleProd() {
    alert("Could not retrieve list.");
}

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, " "));
}

function getParameterByNameForHref(hrefUrl, name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(hrefUrl);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function closePopup() {
    $.magnificPopup.close();
}

function frmGetAllState(formCountryId, eventId) {
    var frmStateId = $(".clsfrmStateId").val();
    var OtherState = $("#OtherState").val();
    var isOther = true;
    $.getJSON('/Account/GetState/', { Id: formCountryId }, function (data) {
        var items = '';
        if (data.length > 0) {
            items += "<option value=''></option>";
            $.each(data, function (i, data) {
                if (frmStateId == data.Text) {
                    isOther = false;
                    items += "<option selected='selected' value='" + data.Text + "'>" + data.Text + "</option>";
                } else {
                    isOther = false;
                    items += "<option value='" + data.Text + "'>" + data.Text + "</option>";
                }
            });

            $('.clsfrmstateDrp').attr('style', 'display');
            $('.clsOtherState').attr('style', 'display:none');
            $('.clsfrmState').html(items);
            if (isOther && eventId == 1) {
                $(".clsfrmStateId").val('');
                if (OtherState == "") {
                    $(".clsOtherState").val(frmStateId);
                }
                else {
                    $(".clsOtherState").val(OtherState);
                }



            } else {
                $(".clsOtherState").val('');
            }
        }
        else {
            $('.clsfrmstateDrp').attr('style', 'display:none');
            $('.clsOtherState').attr('style', 'display');
            $('.clsfrmState').html('');
            if (isOther && eventId == 1) {
                if (OtherState == "") {
                    $(".clsOtherState").val(frmStateId);
                }
                else {
                    $(".clsOtherState").val(OtherState);
                }
            } else {
                $(".clsOtherState").val('');
            }
        }
        $('#divProgress').hide();
    });

}
function frmGetAllStateLoad() {
    var formCountryId = $(".clsformCountryId").val();

    var Id = $("#Customerid").val();
    if (Id < 0) {
        formCountryId = "United States";
        $(".clsformCountryId").val('United States');
    }
    jQuery.noConflict();
    if (formCountryId != undefined) {
        frmGetAllState(formCountryId, 1);
    }
    //$('textarea.ce21ckeditor').ckeditor();
    //window.location.reload();
}

function CloseMagnificPop() {
    //close any magnific popup in catalog
    $.magnificPopup.close();
}

$("body").on("click", ".btnAddCompareProduct", function () {
    var element = $(this);
    var ProductId = element.attr('data-value');
    var Type = element.attr('data-widgetType');
    var isViewerProduct = false;
    if (Type != undefined && Type == 'ViewerCompareProduct') {
        isViewerProduct = true;
    }
    $.ajax({
        type: "POST",
        url: ADD_COMPAREPRODUCT_URL,
        dataType: "json",
        data: {
            'ProductId': ProductId,
            'IsFromViewerProduct': isViewerProduct
        },
        success: function (data) {
            if (data.CartCount != null && data.CartCount != "" && data.CartCount != "0") {
                parent.$("#compareProductcartspancount").html(data.CartCount);
                parent.$("#compareProductcartItemList").load(GET_COMPAREPRODUCTCART_URL);
            }
            //set wishlist count
            if (data.isChangeWishlist == true) {
                parent.$("#Wishlistcount").html("(" + data.wishlistCount + ")");
            }
            if (data.Message != null && data.Message != "") {
                displayCartMessages(element, data, Type); //#16325
            }
        },
        complete: function (data) {
        },
        error: function (data) {
            alert('Error! Please try again later.');
        }
    });
});

// #region subscription
function subscriptionFailure() {
    alert('There is a problem to submit code. Please, try after some time');
}

function subscriptionSuccess(data) {
    if (data !== undefined && data != null && data.Message !== undefined && data.Message != null) {
        if (data.Message != "success" && data.Message.length > 0) {
            alert(data.Message);
        }
    }
    if (data != null && data != undefined && data.Url != null && data.Url != undefined) {
        window.location.href = data.Url;
    }
    $('.subscriptionCode').val('');
    if ($.validator != undefined && $.validator.unobtrusive != undefined) {
        $.validator.unobtrusive.parse("form");
    }
}
// #end region subscription

//#region Order summary

function UpdateOrderSummary(callback) {
    $("#divProgress").show();
    var purchaserCustomerId = '';
    if ($('#currentCartStage').val() == 'RegistrantConfirmation') {
        purchaserCustomerId = GetPurchaserCustomerId();
    }
    if ($('#div-order-summary').length > 0 || $('#div-bundle-information')) {
        var orderId = null;
        if ($('#OrderId').length > 0) {
            orderId = Number($('#OrderId').val());
        }

        $.ajax({
            url: MY_CART_URL,
            type: "POST",
            data: {
                'DisplayScreen': '_OrderSummary',
                'orderId': orderId,
                'currentStage': $("#CurrentStage").val(),
                'purchaserCustomerId': purchaserCustomerId
            },
            cache: false,
            success: function (result) {
                $("#divProgress").show();
                $('#div-order-summary').html(result);
                if ($("#hdnMessage").val() != null && $("#hdnMessage").val() != "") {
                    alert($("#hdnMessage").val());
                }
                if (typeof setDataAttributeToSubmitButton == "function") {
                    setDataAttributeToSubmitButton();
                }
            },
            complete: function () {
                $("#divProgress").hide();
                if (callback && typeof (callback) == "function") { callback(); }
            },
            error: function () {
                $("#divProgress").hide();
            }
        });
    }
    else {
        $("#divProgress").hide();
    }
}


function updateWishList() {
    //if ($("#grid-WishList") !== undefined && $("#grid-WishList").length > 0 && $("#grid-WishList").html().trim().length == 0) {
    $("#grid-WishList").load('/Account/CustomerSavedItem', function () {
        loadAlertToolTip();
    }).prepend("<p class='loaderTxt' >Please wait ...</p>");
    //}
}

// #22292
function CheckCode(appliedCode) {
    if (!appliedCode || !appliedCode.trim()) {
        alert("Please enter a valid code.");
        return false;
    }
    $.post("/shoppingcart/CheckGiftCardCodeAndCoupenCode", { 'discountCode': appliedCode }, function (data) {
        if (data.message == "DiscountCode")
            ApplyDiscountCode(appliedCode);
        else if (data.message == "GiftCard") {
            CheckGiftCardCodeAlerdayApplied(appliedCode);
        }
        else
            alert("Applied code is invalid");
    });
}

//#region Discount
$("body").on("click", ".btnCouponShoppingCart", function () {
    CheckCode($(".txtCouponCodeShoppingCart").val());
});

// #22292
function ApplyDiscountCode(couponCode) {
    var registrantEmails = GetRegistrantEmails();
    var purchaserCustomerId = '';
    if ($('#currentCartStage').val() == 'RegistrantConfirmation') {
        purchaserCustomerId = GetPurchaserCustomerId();
    }
    if (couponCode && couponCode.trim() != '') {
        $.ajax({
            type: "POST",
            url: CHECK_COUPON_CODE_URL,
            dataType: "json",
            data: {
                'DiscountCode': couponCode,
                'registrantEmails': registrantEmails,
                'purchaserCustomerId': purchaserCustomerId,
                'isRegistrantConfirmation': ($('#currentCartStage').val().toLowerCase() == "registrantconfirmation")
            },
            success: function (data) {
                if (data != "") {
                    if (data.type == 1) {

                        if (data.isApplyOnlyToRegistrant && (data.inValidRegistrants || data.registrantsDiscountMessageType != 'Default') && data.message) {//#21994
                            ConfirmRegistrantDiscount(couponCode, null, data.inValidRegistrants, data.message, data.registrantsDiscountMessageType);
                        }
                        else if (data.message != "") {
                            if (data.ishareProduct) {
                                updateProductNameWithoutDiscount(data.message)
                            }
                            else {
                                alert(data.message);
                            }

                        }
                        if (ISRELOADPAGE) {//#21994
                            ISRELOADPAGE = false;
                            $('#divProgress').show();
                            location.reload();
                        }

                        UpdateOrderSummary();
                        if (typeof UpdateItemCart == 'function') {
                            UpdateItemCart(0);
                        }
                    } else {
                        if (confirm(data.message)) {
                            UpdateOrderSummary();
                            if (typeof UpdateItemCart == 'function') {
                                UpdateItemCart(0);
                            }
                        } else {
                            RemoveDisount();
                        }
                    }

                    if (location.href && location.href.toLowerCase().indexOf('/account/shippinginfo') > -1) {
                        ApplyFreeShipping(data.freeshipping, data);
                    }
                }
            },
            error: function (data) {
                alert('Error! Please try again later.');
            }
        });
    } else {
        RemoveDisount();
    }
}

//#end region Discount

function ApplyGiftCard(GiftCardCode) {
    $.ajax({
        type: "POST",
        url: CHECK_GIFT_CARD_CODE_URL,
        dataType: "json",
        data: {
            'DiscountCode': GiftCardCode,
        },
        success: function (data) {
            if (data != "") {
                alert(data);
            }
        },
        complete: function (data) {
            UpdateItemCart(0);
        },
        error: function (data) {
            alert('Error! Please try again later.');
        }
    });
}

// #region discouunts
function UpdateItemCart(discountId) {
    var purchaserCustomerId = '';
    if ($('#currentCartStage').val() == 'RegistrantConfirmation') {
        purchaserCustomerId = GetPurchaserCustomerId();
    }
    $("#divProgress").show();
    var orderId = null;
    var usedrewardAmount = $('#hdnRewardPoint').val();
    var exchangeRate = $('#hdnExchangeRate').val();
    if ($('#OrderId').length > 0) {
        orderId = Number($('#OrderId').val());
    }

    $.ajax({
        url: MY_CART_URL,
        type: "POST",
        data: {
            'GroupDiscountId': discountId,
            'DisplayScreen': '_ConfirmPurchase',
            'orderId': orderId,
            'purchaserCustomerId': purchaserCustomerId
        },
        cache: false,
        success: function (result) {
            UpdateOrderSummary(function () {
                var productWithNoDisocuntHtml = $('.clsAddProductCartMessage_discount').html()
                $('#grid-list').html(result);
                if (productWithNoDisocuntHtml != undefined && productWithNoDisocuntHtml.length > 0) {
                    $('.clsAddProductCartMessage_discount').html(productWithNoDisocuntHtml)
                }
                //if ($("#hdnMessage").val() != null && $("#hdnMessage").val() != "") {
                //    alert($("#hdnMessage").val());
                //}
                var grandTotal = Number($("#hdnGrandTotal").val());
                var subTotal = Number($("#hdnSubTotal").val());
                var rewardTotal = Number($("#hdnRewardTotal").val());
                if (grandTotal == 0 || (subTotal == rewardTotal)) {
                    $("#rdbUseAll").attr('disabled', true);
                    $("#rdbChooseAmount").attr('disabled', true);
                    $("#txtRewardPoint").attr('disabled', true);
                }

                var productNameWithNoDiscount = $("#hdnProductNameWithNoDiscount") != undefined ? $("#hdnProductNameWithNoDiscount").val() : "";
                updateProductNameWithoutDiscount(productNameWithNoDiscount);
                validateCreditCard();
                validateACH();

                var RBvalue = $("#rdbChooseAmount").prop('checked');
                if (RBvalue == true) {
                    $(".divCustomRewardPoint").show();
                    if (usedrewardAmount != undefined && usedrewardAmount != null) {
                        $("#txtRewardPoint").val(usedrewardAmount);
                    }
                }

                var rpCheck = $("#rdbChooseRewardsPoint").prop('checked');
                if (rpCheck == true) {
                    $(".divAddRewardPoint").show();
                    if (usedrewardAmount != undefined && usedrewardAmount != null) {
                        $("#txtAddRewardPoint").val(usedrewardAmount / exchangeRate);
                    }
                }
                LoadOrderAttributeLists();

                loadAlertToolTip();

                if (typeof (hideShowPyamentAssignToCompanyPurchase) == "function") {
                    hideShowPyamentAssignToCompanyPurchase();
                }
            });
        },
        error: function () {
            UpdateOrderSummary();
            if (typeof (hideShowPyamentAssignToCompanyPurchase) == "function") {
                hideShowPyamentAssignToCompanyPurchase();
            }
        }
    });

}

function validateCreditCard() {
    if ($("#hdnGrandTotal") != undefined && Number($("#hdnGrandTotal").val()) <= 0) {

        if ($("#CCInfornation_CardHolderName").length > 0) {
            if ($("#CCInfornation_CardHolderName") != undefined && $("#CCInfornation_CardHolderName").length > 0) {
                $("#CCInfornation_CardHolderName").rules("remove", "required");
            }
            if ($("#drpCardType") != undefined && $("#drpCardType").length > 0) {
                $("#drpCardType").rules("remove", "required");
                $("#drpCardType").removeAttr("required");
            }
            if ($("#CCInfornation_CardNumber") != undefined && $("#CCInfornation_CardNumber").length > 0) {
                $("#CCInfornation_CardNumber").rules("remove", "required");
            }
            if ($("#CCInfornation_CVV") != undefined && $("#CCInfornation_CVV").length > 0) {
                $("#CCInfornation_CVV").rules("remove", "required");
            }
            if ($("#CCInfornation_CardMonth") != undefined && $("#CCInfornation_CardMonth").length > 0) {
                $("#CCInfornation_CardMonth").rules("remove", "required");
            }
            if ($("#CCInfornation_CardYear") != undefined && $("#CCInfornation_CardYear").length > 0) {
                $("#CCInfornation_CardYear").rules("remove", "required");
            }
            if ($("select[name='CCInfornation.CardType']") != undefined && $("select[name='CCInfornation.CardType']").length > 0) {
                $("select[name='CCInfornation.CardType']").rules("remove", "required");
            }
        }


        //hide credit card section and billing info section
        if ($(".clsCreditCardInformation") != undefined && $(".clsCreditCardInformation").length > 0) {
            $(".clsCreditCardInformation").hide();
        }
        //remove rules for billing info section
        if ($("#CountryId") != undefined && $("#CountryId").length > 0) {
            $("#CountryId").rules("remove", "required");
            $("#CountryId").removeAttr("required");
        }
        if ($("select[name='BillCountry']") != undefined && $("select[name='BillCountry']").length > 0) {
            $("select[name='BillCountry']").rules("remove", "required");
        }
        if ($("#BillAddress") != undefined && $("#BillAddress").length > 0) {
            $("#BillAddress").rules("remove", "required");
        }
        if ($("#BillCity") != undefined && $("#BillCity").length > 0) {
            $("#BillCity").rules("remove", "required");
        }
        if ($("#State") != undefined && $("#State").length > 0) {
            $("#State").rules("remove", "required");
            $("#State").removeAttr("required");
        }
        if ($("select[name='State']") != undefined && $("select[name='State']").length > 0) {
            $("select[name='State']").rules("remove", "required");
        }
        if ($("#BillOtherState") != undefined && $("#BillOtherState").length > 0) {
            $("#BillOtherState").rules("remove", "required");
        }
        if ($("#BillZipcode") != undefined && $("#BillZipcode").length > 0) {
            $("#BillZipcode").rules("remove", "required");
        }

    }
    else {

        if ($("#CCInfornation_CardHolderName").length > 0) {
            if ($("#CCInfornation_CardHolderName") != undefined && $("#CCInfornation_CardHolderName").length > 0) {
                $("#CCInfornation_CardHolderName").rules("add", "required");
            }
            if ($("#drpCardType") != undefined && $("#drpCardType").length > 0) {
                $("#drpCardType").rules("add", "required");
                $("#drpCardType").attr("required", "required");
            }
            if ($("#CCInfornation_CardNumber") != undefined && $("#CCInfornation_CardNumber").length > 0) {
                $("#CCInfornation_CardNumber").rules("add", "required");
            }
            if ($("#CCInfornation_CVV") != undefined && $("#CCInfornation_CVV").length > 0) {
                $("#CCInfornation_CVV").rules("add", "required");
            }
            if ($("#CCInfornation_CardMonth") != undefined && $("#CCInfornation_CardMonth").length > 0) {
                $("#CCInfornation_CardMonth").rules("add", "required");
            }
            if ($("#CCInfornation_CardYear") != undefined && $("#CCInfornation_CardYear").length > 0) {
                $("#CCInfornation_CardYear").rules("add", "required");
            }
            if ($("select[name='CCInfornation.CardType']") != undefined && $("select[name='CCInfornation.CardType']").length > 0) {
                $("select[name='CCInfornation.CardType']").rules("add", "required");
            }
            if ($(".CCInfornation") != undefined && $(".CCInfornation").length > 0) {
                $(".CCInfornation").parent('.has-error').removeClass("has-error");
            }
        }

        //show credit card section and billing info section
        if ($(".clsCreditCardInformation") != undefined && $(".clsCreditCardInformation").length > 0) {
            $(".clsCreditCardInformation").show();
        }
        //add rules for billing info section
        if ($("#CountryId") != undefined && $("#CountryId").length > 0) {
            $("#CountryId").rules("add", "required");
            $("#CountryId").attr("required", "required");
        }
        if ($("select[name='BillCountry']") != undefined && $("select[name='BillCountry']").length > 0) {
            $("select[name='BillCountry']").rules("add", "required");
        }
        if ($("#BillAddress") != undefined && $("#BillAddress").length > 0) {
            $("#BillAddress").rules("add", "required");
        }
        if ($("#BillCity") != undefined && $("#BillCity").length > 0) {
            $("#BillCity").rules("add", "required");
        }
        if ($("#State") != undefined && $("#State").length > 0) {
            $("#State").rules("add", "required");
            $("#State").attr("required", "required");
        }
        if ($("select[name='State']") != undefined && $("select[name='State']").length > 0) {
            $("select[name='State']").rules("add", "required");
        }
        if ($("#BillOtherState") != undefined && $("#BillOtherState").length > 0) {
            $("#BillOtherState").rules("add", "required");
        }
        if ($("#BillZipcode") != undefined && $("#BillZipcode").length > 0) {
            $("#BillZipcode").rules("add", "required");
        }
    }
}

// load the order attribute list
function LoadOrderAttributeLists() {
    if ($("#divOrderAttributes").length > 0) {
        var url = '/Account/GetCartOrderAttribute';
        if ($("#SessionId").length > 0) {
            url = url + '?SessionId=' + $("#SessionId").val();
        }
        $("#divOrderAttributes").load(url, function () {
            $(".datepicker").datepicker();
        });
    }
}
// #endregion discouunts

function validateACH() {
    if (Number($("#hdnGrandTotal").val()) <= 0) {
        if ($("#ACHInfornation_Name").length > 0) {
            $("#ACHInfornation_AccountHolderType").rules("remove", "required");
            $("#ACHInfornation_Name").rules("remove", "required");
            $("#ACHInfornation_FirstName").rules("remove", "required");
            $("#ACHInfornation_LastName").rules("remove", "required");
            $("#ACHInfornation_BankAccountNumber").rules("remove", "required");
            $("#ACHInfornation_RoutingNumber").rules("remove", "required");
            $("#ACHInfornation_AccountType").rules("remove", "required");
        }
    }
    else {
        if ($("#ACHInfornation_Name").length > 0) {
            $("#ACHInfornation_AccountHolderType").rules("add", "required");
            $("#ACHInfornation_Name").rules("add", "required");
            $("#ACHInfornation_FirstName").rules("add", "required");
            $("#ACHInfornation_LastName").rules("add", "required");
            $("#ACHInfornation_BankAccountNumber").rules("add", "required");
            $("#ACHInfornation_RoutingNumber").rules("add", "required");
            $("#ACHInfornation_AccountType").rules("add", "required");
        }
    }
}

$("body").on('click', ".clsGlobalDiscount", function () {
    var discountId = Number($(this).attr("data-priceId"));
    var isAdded = $(this).attr("data-isAdded");
    var discountOffPrice = $("#discountOffPrice").val();
    if ($('[name="discountOffPrice"]').length > 1)
        discountOffPrice = $('[name="discountOffPrice"]')[1].value;
    discountOffPrice = typeof (discountOffPrice) == "string" && discountOffPrice != undefined && discountOffPrice != "" ? discountOffPrice : "";
    if (isAdded == 1) {
        if (typeof (RemoveDisount) == "function") {
            RemoveDisount();
        }
    }
    else if (discountId > 0) {
        //customer have already discount and apply another discount then display confirmation
        $.ajax({
            type: "POST",
            url: GET_CURRENT_DISCOUNT_DETAIL,
            dataType: "json",
            data: { 'newDiscountId': discountId, 'currentStage': $("#CurrentStage").val() },
            success: function (data) {
                if (data != undefined && data != null && data.discountId != undefined && data.discountId != null && Number(data.discountId) > 0) {
                    var newDiscountOffPrice = typeof (data.newDiscount) == "string" && data.newDiscount != undefined && data.newDiscount != "" ? data.newDiscount : "";
                    $.confirm({
                        title: '',
                        boxWidth: '600px',
                        useBootstrap: false,
                        type: '',
                        content: 'You currently have a discount in your cart that is saving you ' + discountOffPrice + '.<br/>If you apply this discount you will receive ' + newDiscountOffPrice + ' off of your purchase instead.<br/>Please choose one discount to apply.<br/><br/> Do you wish to continue? ',
                        buttons: {
                            cancel: {
                                text: 'No, Keep the other discount',
                                btnClass: 'btn-warning',
                                action: function () {
                                }
                            },
                            ok: {
                                text: 'Yes, Apply new discount',
                                btnClass: 'btn-success',
                                action: function () {
                                    applyGlobalDiscount(discountId);
                                }
                            }

                        }
                    });

                }
                else {
                    applyGlobalDiscount(discountId);
                }

            },
            complete: function (data) {

            },
            error: function (data) {
                alert('Error! Please try again later.');
            }
        });
    }
});

//#region Discount
$("body").on('click', ".lnkRemoveDiscountShoppingCart", function () {
    RemoveDisount();
});
//#end region Discount

function RemoveDisount() {
    $.ajax({
        type: "POST",
        url: REMOVE_COUPN_CODE_URL,
        dataType: "json",
        success: function (data) {
            $("#divShippingMethods").show();
            if (data) {
                //if (window.location.pathname.indexOf("/registrantconfirmation") > -1 && data.IsApplyOnlyToRegistrant) {
                //    $('#divProgress').show();
                //    location.reload();
                //}                
                if (data.IsFreeShippingType) {
                    updateShippingOptionsByDiscount();
                }
            }
            $(".clsAddProductCartMessage_discount").html("")
            UpdateOrderSummary();
            if (typeof UpdateItemCart == 'function') {
                UpdateItemCart(0);
            }
        }
    });
}

function applyGlobalDiscount(discountId) {
    var registrantEmails = GetRegistrantEmails();
    var purchaserCustomerId = '';
    if ($('#currentCartStage').val() == 'RegistrantConfirmation') {
        purchaserCustomerId = GetPurchaserCustomerId();
    }
    $.ajax({
        type: "POST",
        url: CHECK_COUPON_CODE_URL,
        dataType: "json",
        data: {
            'discountId': discountId,
            'registrantEmails': registrantEmails,
            'purchaserCustomerId': purchaserCustomerId,
            'isRegistrantConfirmation': ($('#currentCartStage').val().toLowerCase() == "registrantconfirmation")
        },
        success: function (data) {
            if (data != "") {
                ApplyFreeShipping(data.freeshipping, data);
                if (data.type == 1) {

                    if (data.isApplyOnlyToRegistrant && (data.inValidRegistrants || data.registrantsDiscountMessageType != 'Default') && data.message) {//#21994
                        ConfirmRegistrantDiscount(null, discountId, data.inValidRegistrants, data.message, data.registrantsDiscountMessageType);
                    }
                    else if (data.message != "") {
                        if (data.ishareProduct) {
                            updateProductNameWithoutDiscount(data.message)
                        }
                        else {
                            alert(data.message);
                        }
                    }

                    if (ISRELOADPAGE) {//#21994
                        ISRELOADPAGE = false;
                        $('#divProgress').show();
                        location.reload();
                    }
                    if (typeof UpdateItemCart == 'function') {
                        UpdateItemCart(0);
                    }
                    if (typeof UpdateOrderSummary == 'function') {
                        UpdateOrderSummary(0);
                    }

                } else {
                    if (confirm(data.message)) {
                        if (typeof UpdateItemCart == 'function') {
                            UpdateItemCart(0);
                        }
                        if (typeof UpdateOrderSummary == 'function') {
                            UpdateOrderSummary(0);
                        }
                    } else {
                        if (typeof (RemoveDisount) == "function") {
                            RemoveDisount();
                        }
                    }
                }
            }
        },
        complete: function (data) {

        },
        error: function (data) {
            alert('Error! Please try again later.');
        }
    });
}
function updateProductNameWithoutDiscount(data) {
    if (data != undefined && data != "") {
        $(".clsAddProductCartMessage_discount").html("")
        var ProductWithNoDiscount = data.split("^|^");
        var appendDivHTML = '<div class="alert alert-danger fade in font-15 mt-10 CartMessage_discount" style="display: none; margin-top:10px;"><strong><button data-dismiss="alert" class="close">×</button><span id="CartMessage_discount">This discount is not eligible for one or more products in your cart.</span></strong></div >';
        //$(".clsAddProductCartMessage_discount").append('<button data-dismiss="alert" class="close">×</button>');
        $(".clsAddProductCartMessage_discount").append(appendDivHTML);
        $(".CartMessage_discount").show();
        $("#CartMessage_discount").append('<ul class="ml-20"></ul>');
        ProductWithNoDiscount.forEach(function (product) {
            $("#CartMessage_discount").find('ul').append('<li>' + product + '</li>');
        });
    }
}
//ScrollToFixed Order Summary
$(function () {

    //if ($(".shoppingCartLayout .btnForHideShowSideBarShoppingCart").is(":visible")) {
    //    $('.shoppingCartLayout .fixedSideBar').removeClass('fixedSideBar');
    //} else {
    //    $('.shoppingCartLayout .sidebar').removeClass('fixedSideBar');
    //}&& !$(".btnForHideShowSideBarShoppingCart").is(":visible")

    if ($('.shoppingCartLayout .fixedSideBar').length > 0) {
        $('.shoppingCartLayout .fixedSideBar').scrollToFixed({
            marginTop: $(".custom-navbar.navbar").length > 0 ? 65 : 25,
            limit: function () {
                var limit = $('footer.footer').offset().top - $('.shoppingCartLayout .fixedSideBar').outerHeight(true) - 55;
                return limit;
                //var cartSideBarHeight = $('.fixedSideBar .panel.panel-default').outerHeight(true);
                //var limit = $('.ce21_shoppingcart_orrdersummary').closest('.row').outerHeight(true) + $('.ce21_shoppingcart_orrdersummary').closest('.row').offset().top;
                //console.log(limit - cartSideBarHeight);
                //return limit - cartSideBarHeight;

            }
        });
    }
});

//#end region
//$("body").on('submit', 'form[action*="Form"]', function () {
//    var count = 0;
//    var form = $(this);
//    form.find('textarea[data-value="required"]').each(function () {
//        if ($.trim($(this).val()) == '') {
//            count += 1;
//            var spanMsg = form.find('span[data-valmsg-for=' + $(this).attr('id') + ']');
//            spanMsg.html('This field is required.');
//            spanMsg.removeClass("field-validation-valid").addClass("field-validation-error");
//            $(this).closest(".form-group").addClass("has-error");
//        } else {
//            var spanMsg = form.find('span[data-valmsg-for=' + $(this).attr('id') + ']');
//            spanMsg.html('');
//            spanMsg.removeClass("field-validation-error").addClass("field-validation-valid");
//            $(this).closest(".form-group").removeClass("has-error");
//        }
//    });
//    if (count > 0) {
//        return false;
//    } else {
//        return true;
//    }
//});

// Commented Due to resolve http://mantis.ce21.com/view.php?id=8177 issue
//$("body").on('click', ".clsGlobalDiscount", function () {
//    var discountId = Number($(this).attr("data-priceId"));
//    var isAdded = $(this).attr("data-isAdded");

//    if (discountId > 0) {
//        $.ajax({
//            type: "POST",
//            url: APPLY_GLOBAL_AUTO_DISCOUNT_URL,
//            dataType: "json",
//            data: {
//                'discountId': discountId, 'IsRemove': isAdded
//            },
//            success: function (data) {
//                if (data !== undefined && data != null) {
//                    if (data.Message !== undefined && data.Message !== null && data.Message != "") {
//                        alert(data.Message);
//                    }
//                }
//            },
//            complete: function (data) {
//                //if (isAdded == "1") {
//                //    UpdateItemCart(0);
//                //}
//                //check function exist then call
//                if (typeof UpdateItemCart == 'function') {
//                    UpdateItemCart(0);
//                }
//                UpdateOrderSummary();
//            },
//            error: function (data) {
//                alert('Error! Please try again later.');
//            }
//        });
//    }
//});

// name your elements here
//var stickyElement = '.fixedSideBar',   // the element you want to make sticky
//bottomElement = $('.clsbottomElement').val()//'footer'; // the bottom element where you want the sticky element to stop (usually the footer) 

//Function from Bluthemes, lets you add li elemants to affix object without having to alter and data attributes set out by bootstrap
//$(function () {
//    if ($(window).width() < 767) {
//        $('.fixedSideBar').addClass('disableAffix');
//        return;
//    }

//    bottomElement = bottomElement != undefined && bottomElement != null ? bottomElement : 'footer';
//    var orderSummaryWidth = $('.fixedSideBar').width();
//    $('.fixedSideBar').css({ width: orderSummaryWidth + 'px' });

//    // make sure the element exists on the page before trying to initalize
//    if ($(stickyElement).length) {
//        $(stickyElement).each(function () {

//            // let's save some messy code in clean variables
//            // when should we start affixing? (the amount of pixels to the top from the element)
//            var fromTop = $(this).offset().top,
//                // where is the bottom of the element?
//                fromBottom = $(document).height() - ($(this).offset().top + $(this).outerHeight()),
//                // where should we stop? (the amount of pixels from the top where the bottom element is)
//                // also add the outer height mismatch to the height of the element to account for padding and borders
//                stopOn = $(document).height() - ($(bottomElement).offset().top) + ($(this).outerHeight() - $(this).height());

//            // if the element doesn't need to get sticky, then skip it so it won't mess up your layout
//            if ((fromBottom - stopOn) > 200) {
//                // let's put a sticky width on the element and assign it to the top
//                $(this).css('width', $(this).width()).css('top', 0).css('position', '');
//                // assign the affix to the element
//                $(this).affix({
//                    offset: {
//                        // make it stick where the top pixel of the element is
//                        top: fromTop + 65,
//                        // make it stop where the top pixel of the bottom element is
//                        bottom: stopOn
//                    }
//                    // when the affix get's called then make sure the position is the default (fixed) and it's at the top
//                }).on('affix.bs.affix', function () { $(this).css('top', '70px').css('position', ''); });
//            }
//            // trigger the scroll event so it always activates 
//            $(window).trigger('scroll');
//        });
//    }

//});

$("body").on('click', '.pop500', function () {
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        callbacks: {
            close: function () {
                //do stuff
            }
        },
        mainClass: 'pop500rMainClass'
    });
    return false;
});

$("body").on("click", ".removeSavedItems", function () {
    var Id = $(this).attr('id');
    var pId = Id.split('~')[0];
    var dateId = Id.split('~')[1];
    if (confirm('Are you sure you want to remove this item?')) {
        $.ajax({
            type: "POST",
            url: DELETE_SAVED_ITEM_URL,
            dataType: "json",
            data: {
                'productID': pId,
                'dateID': dateId
            },
            success: function (data) {
                //$("#tabWishList").load('/Account/CustomerSavedItem');
                if (data.WishlistCount >= 0) {
                    parent.$("#Wishlistcount").html("(" + data.WishlistCount + ")");
                    $("#Wishcount").html(data.WishlistCount);
                }
                $("#divProgress").hide();
                updateWishList();
            },
            error: function (data) {
                alert('Error Occured');
                $("#divProgress").hide();
            }
        });
        $("#divProgress").show();
    }
});

var cls_saveSingleProduct = '';

//Close Add to cart popup
function closeAddToCartPopup(productid, data, otype, baseProductId) {
    //cls_saveSingleProduct
    $.magnificPopup.close();

    if (data.Message) {

        displayCartMessages(cls_saveSingleProduct, data, otype); //#16325

        //Shoppingcart
        if (otype != null && otype == 'shoppingcart') {
            if (typeof UpdateItemCart == 'function') {
                UpdateItemCart(0);
                $("#spnMessage").html("The item was successfully added to your shopping cart");
                $(".wishlistCart").show();
            }
        }

    }
    if (window.location.pathname == '/registrant/registrantconfirmation')
    {
        window.location.reload(); //reload the page to update the registrant details 
    }
}

//#16325
function displayCartMessages($this_element, data, pageType) {

    if (!$this_element || $this_element == 0) { return };

    $this_element.closest(".divItemProductSection").find(".cartAlertMessage, .maxRegistrantAlertMessage, .compareProductAlertMessage").hide();

    var clsAlertMessage = ".cartAlertMessage";
    var clsAlertMessageDiv = ".divAlertMessageSection";

    if (data.IsPurchaseLimitExceeded) {
        clsAlertMessage = ".maxRegistrantAlertMessage";
        clsAlertMessageDiv = ".divMaxRegistrantLimitAlert";
    }

    if (data.isAddInComparedProduct) {
        clsAlertMessage = ".compareProductAlertMessage";
        clsAlertMessageDiv = ".divCompareProductAlert";
    }

    var $existsAlertDiv = $this_element.closest(".divItemProductSection").find(clsAlertMessage);

    //check div already exists
    if ($existsAlertDiv.length > 0) {
        $existsAlertDiv.show();
        if (pageType && pageType.toLowerCase() === "bundlepage") {
            $existsAlertDiv.find('span').html(data.ErrorMessage);
            if (data.Message) {
                $existsAlertDiv.find('span').html(data.Message);
            }
        }
        else {
            $existsAlertDiv.find('span').html(data.Message);
        }
    }
    else {
        //append alert message
        var alertMessageDiv = $(clsAlertMessageDiv);

        if (pageType && pageType.toLowerCase() === "bundlepage") {
            alertMessageDiv.find('span').html(data.ErrorMessage);
            if (data.Message) {
                alertMessageDiv.find('span').html(data.Message);
            }
        }
        else {
            alertMessageDiv.find('span').html(data.Message);
        }

        if (pageType && pageType.toLowerCase() === "featuredscroll") {
            $this_element.closest(".divItemProductSection").prepend(alertMessageDiv.html()).css("margin-top", "8px");
        }
        else if (pageType && (pageType.toLowerCase() === "threecolumn" || pageType.toLowerCase() === "threecolumnsimple" || pageType.toLowerCase() === "relatedproduct" || pageType.toLowerCase() === "productdetail" || pageType.toLowerCase() === "addtocart")) {
            //display message at top
            $this_element.closest(".divItemProductSection").prepend(alertMessageDiv.html());
        }
        else {
            $this_element.closest(".divItemProductSection").append(alertMessageDiv.html());
        }
    }
}

$("body").on("click", ".btnPopAddToCart", function () {
    cls_saveSingleProduct = $(this);
});

//#16325
$("body").on("click", ".closeCartAlertMessage, .closeMaxRegistrantMessage, .closeCompareProductMessage", function () {
    $(this).closest(".cartAlertMessage").hide();
    $(this).closest(".maxRegistrantAlertMessage").hide();
    $(this).closest(".compareProductAlertMessage").hide();
});

$(".btnClose").click(function () {
    $(this).closest("div.alert").hide();
});

$(".btnCloseFromSearchList").click(function () {
    $(this).closest("div.alertMessage").hide();
});

function backtoParentSingleCartItem($this_element, data, pageType) {
    $.magnificPopup.close();
    displayCartMessages($this_element, data, pageType)
}

$("body").on("click", ".clsSaveSingleProduct", function (e, displayPurchaseAlert, registrantTypeOrderItemId, displayDownPaymentAlert) {
    var element = $(this);
    cls_saveSingleProduct = element;
    var btnType = $(this).attr("data-btnType");
    var purchaseAlertId = $(this).attr("data-purchasealertid");
    var productAvailibityRuleId = $(this).attr("data-productAvailibityRuleId");
    var productTypeId = $(this).attr("data-typeid");
    var productId = $(this).attr("data-val");
    var urlPopupAddToCart = $(this).attr("data-urlpopupaddtocart");

    var singleAddToCart = function () {

        if (displayPurchaseAlert != "1") //((purchaseAlertId != undefined && purchaseAlertId != null && purchaseAlertId > 0) || (productAvailibityRuleId && productAvailibityRuleId > 0)) && 
        {
            $.get(GET_PURCHASEALERTMESSSAGE + '?purchaseAlertId=' + purchaseAlertId + '&btyType=' + btnType + '&productAvailibityRuleId=' + productAvailibityRuleId + "&productTypeId=" + productTypeId + "&productId=" + productId, function (data) {
                if (data && data.indexOf("divGeneralPurchaseAlert") > -1) {
                    $(data).modal();
                    return false;
                } else {
                    saveSingleProduct(displayPurchaseAlert, element, registrantTypeOrderItemId, true);
                }
            });
        } else {
            saveSingleProduct(displayPurchaseAlert, element, registrantTypeOrderItemId, displayDownPaymentAlert);
        }
    }

    //check any add on or related product is available
    checkAddOnOrRelatedProductExist(productId, urlPopupAddToCart, singleAddToCart, element);

});

function checkAddOnOrRelatedProductExist(productId, urlPopupAddToCart, callback, element) {
    $(element).attr('disabled', true);

    //no popup url found then add product to cart
    if (!urlPopupAddToCart) {
        callback();
        $(element).removeAttr('disabled');
        return false;
    }


    $.get(CHECK_ADDON_OR_RELATEDPRODUCT_EXIST, { 'productId': productId }, function (data) {
        $(element).removeAttr('disabled');
        if (data) {
            openAddToCartPopupModal(urlPopupAddToCart);
            return false;
        } else if (callback) {
            callback();
        }
    });
}

function saveSingleProduct(displayPurchaseAlert, element, registrantTypeOrderItemId, displayDownPaymentAlert = false, _callback = '') {

    if (displayPurchaseAlert == "1") {
        $(".btndismissAlert").trigger('click');
    }

    var productpriceId = $(element).attr("data-productpriceid");
    if (displayDownPaymentAlert == true && productpriceId && Number(productpriceId) > 0) {
        $.ajax({
            type: "GET",
            url: "/Items/GetDiscountDetails",
            data: { "discountId": productpriceId },
            dataType: "json",
            async: false,
            success: function (data) {
                data.DownPaymentAlertMessage = data.DownPaymentAlertMessage.replace(/{DownPaymentAmount}/g, currencySymbol + parseFloat(data.DownPaymentAmount).toFixed(2));
                if (data != undefined && data.DownPaymentAmount != undefined && data.DownPaymentAmount != '' && data.DownPaymentAlertMessage != '') {
                    $.confirm({
                        title: 'Alert',
                        content: data.DownPaymentAlertMessage,
                        boxWidth: '600px',
                        type: 'green',
                        buttons: {
                            ok: {
                                text: addToCartLabel,
                                btnClass: 'btn-success',
                                action: function () {
                                    if (_callback && typeof _callback == 'function') {
                                        _callback();
                                    }
                                    else {
                                        saveSingleProductAfterAlert(element, registrantTypeOrderItemId);
                                    }
                                }
                            },
                            cancel: {
                                text: 'Cancel',
                                btnClass: 'btn-danger'
                            }
                        }
                    });
                }
                else {
                    if (_callback && typeof _callback == 'function') {
                        _callback();
                    }
                    else {
                        saveSingleProductAfterAlert(element, registrantTypeOrderItemId);
                    }
                }
            },
            error: function () {
                if (_callback && typeof _callback == 'function') {
                    _callback();
                }
                else {
                    saveSingleProductAfterAlert(element, registrantTypeOrderItemId);
                }
            }
        });
    }
    else {
        if (_callback && typeof _callback == 'function') {
            _callback();
        }
        else {
            saveSingleProductAfterAlert(element, registrantTypeOrderItemId);
        }
    }
}
function saveSingleProductAfterAlert(element, registrantTypeOrderItemId) {

    var productId = $(element).attr("data-val");
    var btnType = $(element).attr("data-btnType");
    var isAgendaAnwer = $(element).attr("data-isAgendaAnswer");
    var isAgendacart = $(element).attr("data-isAgendacart");
    var productpriceId = $(element).attr("data-productpriceid");
    var discountEntityType = $(element).attr("data-productpricetype");
    var event_TimeId = $(element).attr("data-eventid");
    var product_typeId = $(element).attr("data-typeid");
    var productregistranttypeId = $(element).attr("data-productregistranttypeid");


    //12842: Registration Types - Registration Question Sets.
    if (productpriceId && Number(productpriceId) > 0 && !registrantTypeOrderItemId && productregistranttypeId > 0) {
        var isQuestionExist = IsRegistrantTypeQuestionSetAvailable(productpriceId, event_TimeId, productId, product_typeId);
        if (isQuestionExist) { OpenRegistrantTypeQuestionSetPopup(productId, productpriceId); return false; }
    }

    if (isAgendaAnwer != undefined && isAgendaAnwer == '0' && isAgendacart != undefined && isAgendacart == "1") {
        $.ajax({
            type: "POST",
            url: "/Items/IsOpenAgendaPopup",
            dataType: "json",
            data: {
                'productId': productId,
                'productPriceId': productpriceId,
                'entityType': discountEntityType
            },
            success: function (data) {
                if (data != undefined && data == true) {
                    openAgendaFormFromDiscount(productId, btnType, $(this).attr("data-price"), productpriceId, discountEntityType, registrantTypeOrderItemId, false);
                    return false;
                }
                else {
                    AddSingleProductToCart(element, registrantTypeOrderItemId);
                }
            },
            error: function (data) {
                $("#divProgress").hide();
                alert('Error! Please try again later.');
            }
        });
    }
    else {
        AddSingleProductToCart(element, registrantTypeOrderItemId)
    }
}

function AddSingleProductToCart(element, registrantTypeOrderItemId) {
    var productId = $(element).attr("data-val") || $(element).attr("data-ProductId");
    var pagetype = '';
    var pageno = 1;
    var sortby = 11;
    var Type = $(element).attr("data-token");
    var isViewerProduct = false;
    var marketingEntityId = $(element).attr("data-marketingEntityId");
    var marketingEntityType = $(element).attr("data-marketingEntityType");
    var relatedProductId = $(element).attr("data-relatedproductid");
    var chkPurchaser = $(element).attr("data-chkPurchaser") || false;
    var isAgendaRequestInfo = $(element).attr("data-isAgendaRequestInfo") || false;

    if (Type != undefined && Type == 'ViewerCartProduct') {
        isViewerProduct = true;
    }

    if (parent.$("#pageType").val() != undefined) {
        pagetype = parent.$("#pageType").val();
    }
    if (parent.$("#pageno").val() != undefined) {
        pageno = parent.$("#pageno").val();
    }
    if (parent.$("#sortby").val() != undefined) {
        sortby = parent.$("#sortby").val();
    }

    $.ajax({
        type: "POST",
        url: ADD_SAVE_SINGLE_PRODUCT_URL,
        dataType: "json",
        data: {
            "productId": productId,
            "quantity": 1,
            "EventTimeId": $(element).attr("data-eventid") || $(element).attr("data-eventtimeid"),
            "productTypeId": $(element).attr("data-typeid") || $(element).attr("data-producttypeid"),
            "productPrice": $(element).attr("data-price") || 0,
            "priceType": $(element).attr("data-pricetype"),
            "IsAddOnProduct": isViewerProduct,
            "productPriceId": $(element).attr("data-productpriceid"),
            "marketingEntityType": marketingEntityType,
            "marketingEntityId": marketingEntityId,
            "RelatedProductId": relatedProductId,
            "RegistrantTypeOrderItemId": (registrantTypeOrderItemId && !isNaN(registrantTypeOrderItemId) ? registrantTypeOrderItemId : 0),
            "chkPurchaser": chkPurchaser,
            "isAgendaRequestInfo": isAgendaRequestInfo
        },
        success: function (data) {
            // 17507: Google Analytics -E-commerce Tracking
            if (data && data.productAddedInCartDetails) {
                googleAnalytics.addToCartEvent(data.productAddedInCartDetails);
                faceBookAnalytics.addToCartEvent(data.productAddedInCartDetails);
            }

            if (isViewerProduct == true) {
                var alertMessage = "The item is now in your shopping cart at the discounted price. You can go to your shopping cart now and check out or after the seminar is finished.";
                if (confirm(alertMessage)) {
                    parent.$.magnificPopup.close();
                } else {
                    parent.$.magnificPopup.close();
                }
                return false;
            }
            else {
                if (data.isSendCustomerToCart != undefined && data.isSendCustomerToCart == true && !data.IsCECreditPrice && !data.IsPurchaseLimitExceeded) {
                    setTimeout(function () {
                        window.parent.location.href = '/ShoppingCart';
                    }, 555);
                    return false;
                }

            }

            if (typeof (parent.clearSessionStorageKeyForGroup) == 'function') {
                parent.clearSessionStorageKeyForGroup();//--0011726
            }

            if (data.CartCount != null && data.CartCount != "" && data.CartCount != "0") {
                parent.$("#cartspancount").html(data.CartCount);
                parent.$("#cartItemList").load(GET_CART_URL);
                parent.$("#grid-WishList").load(SAVED_ITEMS);
            }
            //compare Product item
            if (data.isCompareProduct != undefined && data.isCompareProduct == true) {
                parent.$("#compareProductcartspancount").html(data.compareProductCount);
                parent.$("#compareProductcartItemList").load(GET_COMPAREPRODUCTCART_URL);
            }
            //compare Product item
            if (pagetype == "CompareItem") {
                parent.$("#grid-compareProduct").load(GET_COMPARE_PRODUCT_URL + '?page=' + pageno + '&sortby=' + sortby);
            }

            if (data.Message != null && data.Message != "") {
                displayCartMessages(element, data, Type); //#16325
            }

            if (data.IsCECreditPrice) {
                $("#bundleType4AlertPopup").modal('hide');
                cartMessage = "";
                cartMessage = data.Message;
                //$("#cecreditpurchase" + productId).modal();
                displayPurchaseCEMessage(productId, data.CECreditPrice);

            }
            else {
                backtoParentSingleCartItem(element, data, Type);
            }
        },
        complete: function (data) {
        },
        error: function (data) {
            alert('Error! Please try again later.');
        }
    });
}

//display purchase CE popup modal
var displayPurchaseCEMessage = function (productId, cECreditPrice, displayPageType = 0, customerBundleId = 0, isAcknowledge = false) {
    $.get(GET_PURCHASECE_PRICE_POPUP + '?productId=' + productId + "&ceCreditPrice=" + cECreditPrice + "&displayPageType=" + displayPageType + "&customerBundleId=" + customerBundleId + "&isAcknowledge=" + isAcknowledge, function (dataPurchaseCEHtml) {
        if ($('#divPurchaseCECreditmodal').length > 0) {
            $('#div-list-purchaseCE').html(dataPurchaseCEHtml);
            $("#divPurchaseCECreditmodal").modal();
        }
        else {
            $('body').append(dataPurchaseCEHtml);
            $("#divPurchaseCECreditmodal").modal();
        }
        return false;
    });
}

//Start Add To cart discount
$("body").on("click", ".btnAddtocartDiscountProductFromSearch", function (e, displayPurchaseAlert, registrantTypeOrderItemId, displayDownPaymentAlert) {
    var element = $(this);
    cls_saveSingleProduct = element;
    var custoemrId = element.attr("data-customerid");
    var excludeDiscount = element.attr("data-exclude-discount");
    var productId = element.attr("data-productid");
    var btnType = element.attr("data-btnType");
    var purchaseAlertId = element.attr("data-purchasealertid");
    var productAvailibityRuleId = element.attr("data-productAvailibityRuleId");
    var productTypeId = element.attr("data-typeid");
    var urlPopupAddToCart = element.attr("data-urlpopupaddtocart");
    var productPriceEntityType = element.attr("data-productPriceEntityType");
    var event_TimeId = $(element).attr("data-eventid");
    var isAgendaAnwer = $(element).attr("data-isAgendaAnswer");
    var isAgendacart = $(element).attr("data-isAgendacart");
    var discountEntityType = $(element).attr("data-productpricetype");
    var productpriceid = element.attr("data-productpriceid");
    var productregistranttypeId = element.attr("data-productregistranttypeid");

    if (displayPurchaseAlert == "1" && $("#divGeneralPurchaseAlert.modal.fade.in:visible").length > 0) {
        $("#divGeneralPurchaseAlert.modal.fade.in:visible").modal('hide');
    }

    //check customer is log in or not 
    if (parseInt(custoemrId) <= 0 && excludeDiscount == 1) {
        alert("You just need to Log In for purchase this product.");
        return false;
    }

    if (displayPurchaseAlert != "1") {
        var singleAddToCart = function () {
            $.get(GET_PURCHASEALERTMESSSAGE + '?purchaseAlertId=' + purchaseAlertId + '&btyType=' + btnType + '&productAvailibityRuleId=' + productAvailibityRuleId + "&productTypeId=" + productTypeId + "&productId=" + productId, function (data) {
                if (data && data.indexOf("divGeneralPurchaseAlert") > -1) {
                    $(data).modal();
                    return false;
                } else {
                    saveSingleProduct(displayPurchaseAlert, element, registrantTypeOrderItemId, true, function () {
                        addToCartFromDiscountAfterAlert(element, registrantTypeOrderItemId);
                    });

                    //addToCartFromDiscount(element, registrantTypeOrderItemId);
                    //if (isAgendaAnwer != undefined && isAgendaAnwer == '0' && isAgendacart != undefined && isAgendacart == "1" && productPriceEntityType) {
                    //    $.ajax({
                    //        type: "POST",
                    //        url: "/Items/IsOpenAgendaPopup",
                    //        dataType: "json",
                    //        data: {
                    //            'productId': productId,
                    //            'productPriceId': productpriceid,
                    //            'entityType': discountEntityType
                    //        },
                    //        success: function (data) {
                    //            if (data != undefined && data == true) {
                    //                openAgendaFormFromDiscount(productId, btnType, element.attr("data-price"), productpriceid, discountEntityType, registrantTypeOrderItemId);
                    //                return false;
                    //            }
                    //            else {
                    //                addToCartFromDiscount(element, registrantTypeOrderItemId);
                    //            }
                    //        },
                    //        error: function (data) {
                    //            $("#divProgress").hide();
                    //            alert('Error! Please try again later.');
                    //        }
                    //    });
                    //}
                    //else {
                    //    addToCartFromDiscount(element, registrantTypeOrderItemId);
                    //}
                }
            });
        }
    } else {
        //addToCartFromDiscount(element, registrantTypeOrderItemId);
        saveSingleProduct(displayPurchaseAlert, element, registrantTypeOrderItemId, displayDownPaymentAlert, function () {
            addToCartFromDiscountAfterAlert(element, registrantTypeOrderItemId);
        });

        //if (productpriceid && Number(productpriceid) > 0 && !registrantTypeOrderItemId && productregistranttypeId > 0) {
        //    var isQuestionExist = IsRegistrantTypeQuestionSetAvailable(productpriceid, event_TimeId, productId, productTypeId);
        //    if (isQuestionExist) { OpenRegistrantTypeQuestionSetPopup(productId, productpriceid); return false; }
        //}

        //if (isAgendaAnwer != undefined && isAgendaAnwer == '0' && isAgendacart != undefined && isAgendacart == "1" && productPriceEntityType) {
        //    $.ajax({
        //        type: "POST",
        //        url: "/Items/IsOpenAgendaPopup",
        //        dataType: "json",
        //        data: {
        //            'productId': productId,
        //            'productPriceId': productpriceid,
        //            'entityType': productPriceEntityType
        //        },
        //        success: function (data) {
        //            if (data != undefined && data == true) {
        //                openAgendaFormFromDiscount(productId, btnType, element.attr("data-price"), productpriceid, discountEntityType, registrantTypeOrderItemId);
        //                return false;
        //            }
        //            else {
        //                addToCartFromDiscount(element, registrantTypeOrderItemId);
        //            }
        //        },
        //        error: function (data) {
        //            $("#divProgress").hide();
        //            alert('Error! Please try again later.');
        //        }
        //    });
        //} else {
        //    addToCartFromDiscount(element, registrantTypeOrderItemId);
        //}
    }

    checkAddOnOrRelatedProductExist(productId, urlPopupAddToCart, singleAddToCart, element);

});
//End Add To cart discount

function addToCartFromDiscountAfterAlert(element, registrantTypeOrderItemId) {
    var productId = element.attr("data-productid");
    var btnType = element.attr("data-btnType");
    var productTypeId = element.attr("data-typeid");
    var productPriceEntityType = element.attr("data-productPriceEntityType");
    var event_TimeId = $(element).attr("data-eventid");
    var isAgendaAnwer = $(element).attr("data-isAgendaAnswer");
    var isAgendacart = $(element).attr("data-isAgendacart");
    var productpriceid = element.attr("data-productpriceid");
    var productregistranttypeId = element.attr("data-productregistranttypeid");

    if (productpriceid && Number(productpriceid) > 0 && !registrantTypeOrderItemId && productregistranttypeId > 0) {
        var isQuestionExist = IsRegistrantTypeQuestionSetAvailable(productpriceid, event_TimeId, productId, productTypeId);
        if (isQuestionExist) { OpenRegistrantTypeQuestionSetPopup(productId, productpriceid); return false; }
    }

    if (isAgendaAnwer != undefined && isAgendaAnwer == '0' && isAgendacart != undefined && isAgendacart == "1" && productPriceEntityType) {
        $.ajax({
            type: "POST",
            url: "/Items/IsOpenAgendaPopup",
            dataType: "json",
            data: {
                'productId': productId,
                'productPriceId': productpriceid,
                'entityType': productPriceEntityType
            },
            success: function (data) {
                if (data != undefined && data == true) {
                    openAgendaFormFromDiscount(productId, btnType, element.attr("data-price"), productpriceid, productPriceEntityType, registrantTypeOrderItemId);
                    return false;
                }
                else {
                    addToCartFromDiscount(element, registrantTypeOrderItemId);
                }
            },
            error: function (data) {
                $("#divProgress").hide();
                alert('Error! Please try again later.');
            }
        });
    } else {
        addToCartFromDiscount(element, registrantTypeOrderItemId);
    }
}

function addToCartFromDiscount(element, registrantTypeOrderItemId) {
    //$(this) = element;
    var custoemrId = element.attr("data-customerid");
    var excludeDiscount = element.attr("data-exclude-discount");
    var productpriceid = element.attr("data-productpriceid");
    var productregistranttypeId = element.attr("data-productregistranttypeid");
    var productId = element.attr("data-productid");
    var productTypeId = element.attr("data-typeid");
    var event_TimeId = $(element).attr("data-eventid");
    //check customer is log in or not 
    if (parseInt(custoemrId) <= 0 && excludeDiscount == 1) {
        alert("You just need to Log In for purchase this product.");
        return false;
    }

    if (productpriceid && Number(productpriceid) > 0 && !registrantTypeOrderItemId && productregistranttypeId > 0) {
        var isQuestionExist = IsRegistrantTypeQuestionSetAvailable(productpriceid, event_TimeId, productId, productTypeId);
        if (isQuestionExist) { OpenRegistrantTypeQuestionSetPopup(productId, productpriceid); return false; }
    }

    var listCart = [];
    listCart.push({
        "productId": element.attr("data-productid"),
        "EventTimeId": element.attr("data-eventtimeid"),
        "priceType": "DiscountPrice",
        "productPrice": element.attr("data-ProductPrice"),
        "quantity": 1,
        "productPriceId": element.attr("data-productpriceid"),
        "IsDiscountProduct": true,
        "ProductDiscountId": element.attr("data-product-discountid"),
        "RegistrantTypeOrderItemId": (registrantTypeOrderItemId && !isNaN(registrantTypeOrderItemId) ? registrantTypeOrderItemId : 0)
    });
    $.ajax({
        type: "POST",
        url: ADD_TO_CART_URL,
        dataType: "json",
        data: { "listCart": JSON.stringify(listCart) },
        success: function (data) {

            if (data.CartCount != null && data.CartCount != "" && data.CartCount != "0") {
                parent.$("#cartspancount").html(data.CartCount);
                parent.$("#cartItemList").load(GET_CART_URL);
            }
            if (data.Message != null && data.Message != "") {
                displayCartMessages(element, data, "SearchProduct");
            }

            if (data.isSendCustomerToCart != undefined && data.isSendCustomerToCart == true && !data.IsCECreditPrice && !data.IsPurchaseLimitExceeded) {
                setTimeout(function () {
                    window.parent.location.href = '/ShoppingCart';
                }, 555);
                return false;
            }
            backtoParentSingleCartItem(element, data, 'SearchProduct');

            if (productpriceid != undefined && productpriceid != null && Number(productpriceid) > 0) {
                $.ajax({
                    type: "POST",
                    url: CHECK_COUPON_CODE_URL,
                    dataType: "json",
                    data: {
                        'discountId': productpriceid,
                    },
                    success: function (data) {
                    },
                    complete: function (data) {

                    },
                    error: function (data) {
                        alert('Error! Please try again later.');
                    }
                });
            }
        },
        complete: function (data) {

        },
        error: function (data) {
            alert('Error! Please try again later.');
        }
    });
}

function loadCharacterCount() {
    // load char count
    $('.charcount').after(function () {
        if ($('#char' + $(this).attr('id')).length == 0) {
            return '<div class="note" style="font-weight:normal;" id="char' + this.id + '">' + $(this).val().length + ' of ' + $(this).attr("data-val-maxlength-max") + ' characters maximum.</div>';
        }
    }).keyup(function () {
        if ($(this).val().length > $(this).attr("data-val-maxlength-max")) {
            $(this).val($(this).val().substring(0, $(this).attr("data-val-maxlength-max")));
        }
        $('#char' + $(this).attr('id')).html($(this).val().length + ' of ' + $(this).attr("data-val-maxlength-max") + ' characters maximum.');
    });

}

$("body").on("click", ".btnItemProductStock", function () {
    var saveLaterUrl = $(this).attr('data-saveLaterUrl');
    var message = "We're sorry, but this product is out of stock.";
    var Type = $(this).attr('data-ItemType');
    if (saveLaterUrl != undefined && saveLaterUrl != '' && saveLaterUrl != "") {
        message += " Click " + saveLaterUrl + " to save this for later"
    }
    var data = {
        Message: message
    };
    displayCartMessages($(this), data, Type); //#16325
});

function CloseAgendamodal(isReloadWindow = false) {
    $.magnificPopup.close();
    if (isReloadWindow)
        window.location.reload();
}

var isRegistrationComplete = false;
$('body').on('click', '.clsEditSelection', function () {
    var element = $(this);
    editSelection(element)
});

function editSelection(element, chkPurchaserForRegistrant = false, isRegistrantRequestInfo = false) {
    var productPriceId = element.attr("data-productPriceId");
    var eventTimeId = element.attr("data-eventTimeId");
    var productId = element.attr("data-productId");
    var productTypeId = element.attr("data-productTypeId");
    var productPrice = element.attr("data-productPrice");
    var customerId = element.attr("data-customerId");
    var orderItemId = element.attr("data-orderItemId");
    var entityType = element.attr("data-entityType");
    var isQuestionExist = IsRegistrantTypeQuestionSetAvailable(productPriceId, eventTimeId, productId, productTypeId, true);
    var isAgendaExists = (productTypeId != undefined && Number(productTypeId) == 1) ? IsAgendaForProductAvailable(productPriceId, productId, entityType) : false;

    if (isQuestionExist && !isRegistrationComplete) {
        $.magnificPopup.open({
            items: {
                src: '/search/registranttypequestionset?productId=' + productId + '&discountId=' + productPriceId + '&priceType=' + productPrice + '&orderItemId=' + orderItemId + "&isRegistrantConfirmationPage=" + true + "&customerId=" + customerId + "&isFetchAnswer=" + true + "&isForEditRegistrant=" + true + "&isAgendaExists=" + isAgendaExists + "&isFromShoppinCart=" + true
            },
            type: 'iframe',
            closeOnBgClick: false,
            showCloseBtn: true,
            mainClass: 'CustomPop',
            callbacks: {
                close: function () {
                }
            }
        });
        return false;
    }
    else if (isAgendaExists && isAgendaExists.toString().toLocaleLowerCase() == 'true' && typeof OpenProductAgendaPopup == "function") {
        isRegistrationComplete = false;
        OpenProductAgendaPopup(productId, orderItemId, productPrice, entityType, productPriceId, false, false, 0, false, chkPurchaserForRegistrant, isRegistrantRequestInfo);
        return false;
        $('#divProgress').hide();
    }
}

$('body').on('click', '.cartAgenda', function () {
    var height = $(this).attr("data-height");
    var width = $(this).attr("data-width");
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        callbacks: {
            close: function () {
            }
        },
        mainClass: 'CustomPop',
    });
    $('.mfp-content').css('height', height);
    $('.mfp-content').css('width', width);
    $('.mfp-iframe-holder .mfp-content').css('max-height', height + 'px');
    $('.mfp-iframe-holder .mfp-content').css('max-width', width + 'px');
    return false;
});

//New Support Ticket Pop up
$('body').on('click', '.supportTicketPopUp', function () {
    $.magnificPopup.open({
        items: {
            src: '/CreateSupportTicket'
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'popCreateSupportTicket'
    });

    return false;
});

$("body").on('click', '.popEmailToFriend', function () {
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'popCreateSupportTicket'
    });
    return false;
});
function closeEmailPopUp() {
    $.magnificPopup.close();
}

$('body').on('click', '.launchiosapp,.launchandroid', function () {

    if ($(this).hasClass('launchandroid')) {
        setTimeout(function () { window.location = AndroidMarketLink; }, 500);

    } else {
        setTimeout(function () { window.location = iOSStoreLink; }, 500);
    }
    window.location = DeepLinkingUrl;

    return false;
});

$('body').on('click', '.launchvieweriosapp,.launchviewerandroid', function () {
    var registrantEncryptkey = $(this).attr("data-registrantencryptkey");

    if ($(this).hasClass('launchviewerandroid')) {
        setTimeout(function () { window.location = AndroidMarketLink; }, 500);
        registrantEncryptkey = encodeURIComponent(registrantEncryptkey);
    } else {
        setTimeout(function () { window.location = iOSStoreLink; }, 500);
        registrantEncryptkey = encodeURIComponent(registrantEncryptkey);
    }
    window.location = DeepLinkingUrl + registrantEncryptkey;

    return false;
});

$('body').on('click', '.popNotificationOption', function () {
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        callbacks: {
            close: function () {
                //do stuff
            }
        },
        mainClass: 'popNotificationOptionMainClass'
    });
    return false;
});

// Open or Focus to particular tab of broswer
var popup;
var openedTab;
function OpenOrFocus(oLink, sTarget) {
    if (window.event.ctrlKey) {
        return true;
    }
    var nAgt = navigator.userAgent;
    oLink.href = oLink.href == "" || oLink.href == "javascript:void(0);" ? $(oLink).attr("data-href") : oLink.href;
    if (nAgt.indexOf("Firefox") > -1) {
        if (oLink.href.includes("launchfreeviewer")) {
            popup = window.open(oLink.href, sTarget)
        }
        else if (oLink.href == "" && oLink.classList.contains("CE21_Classroom_LaunchBtn") && !oLink.classList.contains("btnScheduletabsLaunchViewer")) {
            popup = window.open(oLink.getAttribute('data-href'), sTarget)
        }
        else {
            return true;
        }
    }
    else if (nAgt.indexOf("Chrome") > -1 || nAgt.indexOf("Safari") > -1) {
        if (!oLink.href.includes("launchfreeviewer") && (!oLink.href.includes("ClassroomTab") || !oLink.classList.contains("btnScheduletabsLaunchViewer"))) {
            if ((nAgt.indexOf("iPhone") > - 1 || nAgt.indexOf("iPad") > - 1) && openedTab && !openedTab.closed) {
                openedTab.close();
            }
            openedTab = window.open(oLink.href, sTarget)
        }
        return true;
    }
    else if (detectIE()) {
        if (popup == null && !oLink.href.includes("launchfreeviewer")) {
            popup = window.open(oLink.href, sTarget)
        } else {
            popup.close();
            if (!oLink.href.includes("launchfreeviewer")) {
                popup = window.open(oLink.href, sTarget);
            }
        }
    }
    else {
        if (!oLink.href.includes("launchfreeviewer")) {
            popup = window.open(oLink.href, sTarget)
        }
        popup.close()
        if (!oLink.href.includes("launchfreeviewer")) {
            popup = window.open(oLink.href, sTarget);
        }
        return false;
    }
}

function PIPFeatureAlert(url, sTarget) {
    $.confirm({
        title: 'Program Certification Alert',
        boxWidth: '700px',
        boxHeight: '700px',
        useBootstrap: true,
        icon: 'fa fa-bell',
        closeIcon: true,
        async: false,
        animateFromElement: false,
        closeIconClass: 'fa fa-close',
        animation: 'scale',
        content: "<hr><lable>Your Internet browser might support popping the video out of the program viewer as a picture-in-picture feature.<br>By proceeding, you agree not to utilize this feature, as it may affect your certification outcome.</label><hr>",
        buttons: {
            CONTINUE: {
                text: 'CONTINUE',
                btnClass: 'btn btn-success',
                action: function () {
                    popup = window.open(url, sTarget)
                    return false;
                },
            },
            Close: {
                text: 'Close',
                btnClass: 'btn btn-default',
                action: function () {
                },
            }
        }
    });
}

function detectIE() {
    var ua = window.navigator.userAgent;

    // Test values; Uncomment to check result …

    // IE 10
    // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';

    // IE 11
    // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';

    // IE 12 / Spartan
    // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';

    // Edge (IE 12+)
    // ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';

    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older => return version number
        return true;
        //return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }

    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return true;
        //return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }

    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
        // Edge (IE 12+) => return version number
        return true;
        //return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }

    // other browser
    return false;
}


//bundle type 5 product add by customer start
//Sort random function
function random(owlSelector) {
    owlSelector.children().sort(function () {
        return Math.round(Math.random()) - 0.5;
    }).each(function () {
        $(this).appendTo(owlSelector);
    });
}
function initBundleSlider() {
    if (parent.$("#divBundleCarousel").length > 0) {
        parent.$("#divBundleCarousel").owlCarousel({
            items: 4,
            itemsDesktop: [1600, 3],
            itemsDesktopSmall: [979, 2],
            navigation: true,
            navigationText: [
                "<i class='fa fa-angle-left'></i>",
                "<i class='fa fa-angle-right'></i>"
            ],
            beforeInit: function (elem) {
                //Parameter elem pointing to $("#owl-demo")
                random(elem);
            }
        });
    }
    else if (parent.parent.$("#divBundleCarousel").length > 0) {
        parent.parent.$("#divBundleCarousel").owlCarousel({
            items: 4,
            itemsDesktop: [1600, 3],
            itemsDesktopSmall: [979, 2],
            navigation: true,
            navigationText: [
                "<i class='fa fa-angle-left'></i>",
                "<i class='fa fa-angle-right'></i>"
            ],
            beforeInit: function (elem) {
                random(elem);
            }
        });

    }
}
//for widget/serach pages start
function DefaultAddToBundleCheckBoxButtonSettings() {
    //simple checkbox
    $('.chkAddCustomerBundle').prop('checked', false);


    //checkbox button
    $('.btnAddCustomerBundle').attr('data-status', '0');
    $('.btnAddCustomerBundle').removeClass("btn-warning").addClass("btn-info");
    $('.clsBundleFiveglyphicon').removeClass("glyphicon-check").addClass("glyphicon-unchecked");
    $('.btnAddCustomerBundle').prop('title', 'Use the Add To Bundle button to create your own bundle of products and receive increasing discounts based on the products you add.');
}
function SelectedAddToBundleProducts(productId) {
    $('.chkCustomerBundle' + productId).prop('checked', true);
    var btnClass = '.btnCustomerBundle' + productId;
    if ($(btnClass).length > 0) {
        $(btnClass).attr('data-status', '1');
        $(btnClass).removeClass("btn-info").addClass("btn-warning");
        $(btnClass).find('i').removeClass("glyphicon-unchecked").addClass("glyphicon-check");
        $(btnClass).prop('title', 'Remove product from Bundle');
    }

}
//for widget/serach pages end

//for Add To Cart popup page start
function DefaultAddToBundleCheckBoxButtonSettingsAddToCart() {
    //simple check box
    $('.chkAddCustomerBundleAddToCart').prop('checked', false);

    //check box button
    $('.btnAddCustomerBundleAddToCart').attr('data-status', '0');
    $('.divItemProductSection .btnAddCustomerBundleAddToCart, .divAddToCartProductDetail .btnAddCustomerBundleAddToCart').removeClass("btn-warning").addClass("btn-info");
    $('.clsBundleFiveglyphiconAddToCart').removeClass("glyphicon-check").addClass("glyphicon-unchecked");
    $('.btnAddCustomerBundleAddToCart ').prop('title', 'Use the Add To Bundle button to create your own bundle of products and receive increasing discounts based on the products you add.');
}
function SelectedAddToBundleProductsAddToCart(productId) {
    //simple check box
    $('.chkAddCustomerBundleAddToCart' + productId).prop('checked', true);

    //check box button
    var btnClass = '.btnCustomerBundleAddToCart' + productId;
    if ($(btnClass).length > 0) {
        $(btnClass).attr('data-status', '1');
        $(btnClass).removeClass("btn-info").addClass("btn-warning");
        $(btnClass).find('i').removeClass("glyphicon-unchecked").addClass("glyphicon-check");
        $(btnClass).prop('title', 'Remove product from Bundle');
    }

}
//for Add To Cart popup page end


function ChkBundleTypeFiveCustomerSelectedProducts() {
    //set default all unchecked for widget/serach pages
    DefaultAddToBundleCheckBoxButtonSettings();

    //Add to cart popup page
    DefaultAddToBundleCheckBoxButtonSettingsAddToCart();

    var arrBundle = parent.$(".clsCustomerBundleType5Products").map(function () { return Number($(this).attr("data-productid")) }).get();
    var parentarraybundle = parent.parent.$(".clsCustomerBundleType5Products").map(function () { return Number($(this).attr("data-productid")) }).get();
    var combinedArray = arrBundle.concat(parentarraybundle);
    if (combinedArray != undefined && combinedArray != null && combinedArray.length > 0) {
        jQuery.each(combinedArray, function (i, productId) {
            if (productId != undefined && productId != null && productId > 0) {
                //widget/search pages start
                SelectedAddToBundleProducts(productId);

                //add to cart page start
                SelectedAddToBundleProductsAddToCart(productId);

            }
        });
    }
}

function BtnBundleTypeFiveCustomerSelectedProducts() {
    //for unchecked checkbox
    $(this).removeClass("btn-warning").addClass("btn-info");
    $(this).find('i').removeClass("glyphicon-check").addClass("glyphicon-unchecked");

    if ($(this).attr('data-status') == "0") {
        $(this).attr('data-status', '1')
    }
    else if ($(this).attr('data-status') == "0") {
        $(this).attr('data-status', '0')
    }
}

function LoadCustomerBundleProductList(isClosePopup) {

    if (isClosePopup != undefined && isClosePopup != null && isClosePopup == true) {
        $.magnificPopup.close();
    }

    if (typeof (isBundle5Active) != "undefined" && isBundle5Active != undefined && isBundle5Active.toLowerCase() == "true" && $("#CustomreProductsList").length == 0) {

        if (parent.$("#divCustomerBundleProduct").length == 0) {
            parent.$('body').append('<div id="divCustomerBundleProduct"></div>')
        }

        $.ajax({
            type: "GET",
            url: BUNDLE_TYPE_5_List_CUSTOMER_PRODUCT,
            global: false,
            success: function (response) {
                if ($('#divCustomerBundleProduct').length > 1 && parent.$('#divCustomerBundleProduct').length > 1) {
                    parent.$("#divCustomerBundleProduct").html(response);
                }
                else {
                    parent.parent.$("#divCustomerBundleProduct").html(response);
                }
                //selected customer products start
                ChkBundleTypeFiveCustomerSelectedProducts();
                //selected customer products end


                initBundleSlider();
                if ($('#stickyCompareFooter').length > 0) {
                    //footer margin from top    margin-bottom: 236px;
                    var height = $("#stickyCompareFooter").height();
                    $('footer').attr("style", " margin-bottom:" + height + "px;");
                }
                else {
                    $('footer').attr("style", " margin-bottom: 0px;");
                }
                if (isClosePopup != true) {
                    var arrow = localStorage.getItem("BundleArrow");
                    if (arrow == "fa-chevron-up") {
                        parent.$("#isc-compare-control").hide();
                        $(".stickyCompareFooter").removeClass("active");
                        parent.$("#StickeyBundleIcon").removeClass("fa-chevron-down").addClass("fa-chevron-up");
                        parent.$("#StickeyBundleIcon").attr("data-arrow", "fa-chevron-up");
                        $('footer').attr("style", " margin-bottom: 0px;");
                    }
                }
                else {
                    // open the bottom panel when new product added
                    localStorage.setItem("BundleArrow", "fa-chevron-down");
                }
            }
        });


        //parent.$("#divCustomerBundleProduct").load(BUNDLE_TYPE_5_List_CUSTOMER_PRODUCT, function () {

        //    //selected customer products start
        //    ChkBundleTypeFiveCustomerSelectedProducts();
        //    //selected customer products end


        //    initBundleSlider();
        //    if ($('#stickyCompareFooter').length > 0) {
        //        //footer margin from top    margin-bottom: 236px;
        //        var height = $("#stickyCompareFooter").height();
        //        $('footer').attr("style", " margin-bottom:" + height + "px;");
        //    }
        //    else
        //    {
        //        $('footer').attr("style", " margin-bottom: 0px;");
        //    }
        //});

    }

}
//var lastClickedButtonId = null;
//$('a[data-toggle="modal"], button[data-toggle="modal"]').on('click', function () {
//    lastClickedButtonId = $(this).attr('id'); // Store the ID of the clicked button
//});


//$('.purchaseAlert').on('shown.bs.modal', function () {
//    if (lastClickedButtonId != undefined) {
//        var $modal = $(this);

//        // Hide both buttons initially inside the current modal
//        $modal.find('.modal-footer a.btn-ok').hide();

//        if (lastClickedButtonId === 'btnAddCustomerBundleAddToCart') {
//            // Add the class to the relevant button in the modal
//            var $btnAddCustomerBundle = $modal.find('.btnAddCustomerBundle');
//            if ($btnAddCustomerBundle.length > 0) {
//                $btnAddCustomerBundle.removeClass('btnAddCustomerBundle').addClass('btnAddCustomerBundleAddToCart');
//            }
//        }
//        // Check if the button with the lastClickedButtonId class exists inside the current modal
//        var $lastClickedBtn = $modal.find('.' + lastClickedButtonId);
//        if ($lastClickedBtn.length > 0) {
//            // Show only the relevant button inside the current modal
//            $lastClickedBtn.show();
//        } else {
//            // If the relevant button does not exist, show a default button if needed
//            $modal.find('.modal-footer a.btn-ok').first().show(); // Show the first button as a fallback
//        }
//        lastClickedButtonId = null; // Reset the lastClickedButtonId
//    }
//});

$('body').on('click', '.btnAddCustomerBundle', function () {
    var productId = $(this).attr("data-ProductId");
    var bundleproductId = $(this).attr("data-bundleproductid");
    var eventTimeId = $(this).attr("data-eventid");
    var priceId = $(this).attr("data-priceid");
    var MultipleEventTimeId = $('.EventDate').val();
    $('.purchaseAlert').modal('hide');
    //if date choose from drop down start
    if ($("#EventDate").length > 0) {
        var selectedEventTimeId = $("#EventDate").val();
        if (selectedEventTimeId != undefined && selectedEventTimeId != null && selectedEventTimeId > 0) {
            eventTimeId = selectedEventTimeId
        }
    }

    if (MultipleEventTimeId != undefined && MultipleEventTimeId > 0) {
        eventTimeId = MultipleEventTimeId
    }

    //if date choose from drop down start
    var btnstatus = $(this).attr('data-status');
    var status = true;
    if (btnstatus != undefined && btnstatus != "" && btnstatus == "0") {
        status = true;
    }
    else if (btnstatus != undefined && btnstatus != "" && btnstatus == "1") {
        status = false;
    }

    //check if video replay & multi dates available start
    //comment start #7768
    var bundleUrl = $(this).attr("data-href");
    var isDisplayDatePopup = $(this).attr("data-displaypopup");
    if (status != undefined && status == true && isDisplayDatePopup != undefined && isDisplayDatePopup == "True" && bundleUrl != undefined && bundleUrl != "") {
        WidgetBundleDateSelectorPopup(bundleUrl);
        return false;
    }
    //comment end #7768
    //check if video replay & multi dates available end
    var otherProductIds = [];
    $('.clsRelatedProduct:checked').each(function (i) {
        otherProductIds.push($(this).attr("data-productid"));
    });
    var otherProductId = otherProductIds.length > 0 ? otherProductIds.join(',') : null;
    SaveCustomerBundleTypeFive(productId, bundleproductId, eventTimeId, status, priceId, otherProductId)
});
function RemoveItemFromCart(orderItemId) {
    $("#divProgress").show();
    $.ajax({
        type: "POST",
        url: "/ShoppingCart/RemoveItem",
        dataType: "json",
        data: {
            'OrderItemId': orderItemId,
        },
        success: function (data) {
            // alert(data);
        },
        complete: function (data) {
            UpdateItemCart();
        },
        error: function (data) {
            alert('Error! Please try again later.');
        }
    });
}

$("body").on("click", ".bundleEligible", function () {
    $('#divProgress').show();

    var elem = $(this); 
    elem.addClass("disabled");
    setTimeout(function () {
        elem.removeClass("disabled"); 
    }, 2000);

    var productId = $(this).attr("data-ProductId");
    var bundleproductId = $(this).attr("data-bundleproductid");
    var eventTimeId = $(this).attr("data-eventtimeid");
    var priceId = $(this).attr("data-priceid");
    var btnstatus = $(this).attr('data-status');
    var orderItemId = $(this).attr('value');
    var status = true;
    if (btnstatus != undefined && btnstatus != "" && btnstatus == "0") {
        status = true;
    }
    else if (btnstatus != undefined && btnstatus != "" && btnstatus == "1") {
        status = false;
    }
    $.ajax({
        type: "POST",
        url: BUNDLE_TYPE_5_ADD_CUSTOMER_PRODUCT,
        dataType: "json",
        data: {
            'productId': productId,
            'bundleProductId': bundleproductId,
            'eventTimeId': eventTimeId,
            'status': status,
            'priceId': priceId,
            'bundleEligible': true
        },
        success: function (data) {
            if (data.Message != null && data.Message != "") {
                alert(data.Message);
            }
            else {
                var ceCreditOrderItem = data.ceCreditOrderItem;
                $.ajax({
                    type: "GET",
                    url: "bundle/addToCartBundleFiveProducts",
                    dataType: "json",
                    data: {
                        'bundleEligible': true
                    },
                    success: function (data) {
                        $('#divProgress').show();
                        RemoveItemFromCart(orderItemId);
                        if (ceCreditOrderItem != undefined && ceCreditOrderItem != null && ceCreditOrderItem > 0) {
                            RemoveItemFromCart(ceCreditOrderItem);
                        }
                        //UpdateOrderSummary();
                    },
                    error: function () {
                        alert('Error! Please try again later.');
                    }
                });
            }
        },
        error: function (data) {
            $('#divProgress').hide();
            alert('Error! Please try again later.');
        }
    });
});

$("body").on("click", ".removeFromBundleAddtoCart", function () {
    var orderItemId = $(this).attr("data-orderitemid");
    $('#divProgress').show();
    $.ajax({
        type: "GET",
        url: "bundle/removeFromBundleAddtoCart",
        dataType: "json",
        data: { 'orderItemId': orderItemId },
        success: function (data) {
            if (data == true) {
                updateChangedPriceCartItems();
            }
        },
        error: function (data) {
            $('#divProgress').hide();
            alert('Error! Please try again later.');
        }
    });
});
$("body").on("click", "#StickeyBundleIcon", function () {
    var Arrow = $(this).attr("data-arrow");
    if (Arrow == "fa-chevron-down") {
        $(this).removeClass("fa-chevron-down").addClass("fa-chevron-up");
        $(this).attr("data-arrow", "fa-chevron-up");
        $("#isc-compare-control").hide('500');
        $(".stickyCompareFooter").removeClass("active");
        $('footer').attr("style", " margin-bottom: 0px;");
        localStorage.setItem("BundleArrow", "fa-chevron-up");
    }
    else {
        $(this).removeClass("fa-chevron-up").addClass("fa-chevron-down");
        $(this).attr("data-arrow", "fa-chevron-down");
        $("#isc-compare-control").show('500');
        $(".stickyCompareFooter").addClass("active");
        var height = $("#stickyCompareFooter").height();
        $('footer').attr("style", " margin-bottom:" + height + "px;");
        localStorage.setItem("BundleArrow", "fa-chevron-down");
    }
});

function SaveCustomerBundleTypeFive(productId, bundleproductId, eventTimeId, status, priceId, otherProductId) {
    //selected price from product detail page or add to cart popup modal start
    if (priceId == undefined || priceId == "" || priceId == null) {
        var chkRadioPrice = $('.rdbprice input[type=radio]:checked,.rdbprice input[type=checkbox]:checked');
        if (chkRadioPrice != undefined && chkRadioPrice != null && chkRadioPrice != "" && chkRadioPrice.length > 0) {
            var Price = $(chkRadioPrice).attr('value');
            if (Price != undefined && Price != null && Price.length > 0) {
                if (chkRadioPrice.attr("data-pricetype") == "AdditionalPrice") {
                    alert("The selected price is not eligible to be included in this bundle.");
                    return false;
                }
                var PriceData = Price.split(',');
                priceId = PriceData[0];
            }
        }
        else {
            alert("Please select one of the pricing options to add this item to bundle.");
            return false;
        }
    }
    //selected price from product detail page or add to cart popup modal start

    $.ajax({
        type: "POST",
        url: BUNDLE_TYPE_5_ADD_CUSTOMER_PRODUCT,
        dataType: "json",
        data: {
            'productId': productId,
            'bundleProductId': bundleproductId,
            'eventTimeId': eventTimeId,
            'status': status,
            'priceId': priceId,
            'otherProductId': otherProductId
        },
        success: function (data) {
            if (data.Message != null && data.Message != "") {
                var myContent = data.Message;
                if (isHTML(myContent)) {
                    alert($(myContent).text());
                }
                else {
                    alert(myContent);
                }
            }
            else if (data.IsCECreditPrice) {
                displayPurchaseCEMessage(productId, data.CECreditPrice, 3, data.CustomerBundleId);
            }
            LoadCustomerBundleProductList();
        },
        error: function (data) {
            $('#divProgress').hide();
            alert('Error! Please try again later.');
        }
    });
}

$('body').on('change', '.chkAddCustomerBundle', function () {
    var productId = $(this).attr("data-ProductId");
    var bundleproductId = $(this).attr("data-bundleproductid");
    var eventTimeId = $(this).attr("data-eventid");
    var priceId = $(this).attr("data-priceid");
    var MultipleEventTimeId = $('.EventDate').val();
    if ($("#EventDate").length > 0) {
        var selectedEventTimeId = $("#EventDate").val();
        if (selectedEventTimeId != undefined && selectedEventTimeId != null && selectedEventTimeId > 0) {
            eventTimeId = selectedEventTimeId
        }
    }
    if (MultipleEventTimeId != undefined && MultipleEventTimeId > 0) {
        eventTimeId = MultipleEventTimeId;
    }
    var status = $(this).prop('checked');

    //check if video replay & multi dates available start
    //comment start #7768
    var isDisplayDatePopup = $(this).attr("data-displaypopup");
    var bundleUrl = $(this).attr("data-href");
    if (status != undefined && status == true && isDisplayDatePopup != undefined && isDisplayDatePopup == "True" && bundleUrl != undefined && bundleUrl != "") {
        WidgetBundleDateSelectorPopup(bundleUrl);
        return false;
    }
    //comment end #7768
    //check if video replay & multi dates available end

    SaveCustomerBundleTypeFive(productId, bundleproductId, eventTimeId, status, priceId);
});

$("body").on("click", ".clsDeleteCustomerBundleProduct", function () {
    var productId = $(this).attr('data-productid');
    var chkClass = ".chkCustomerBundle" + productId;
    if (confirm("Are you sure you want to remove this product?")) {
        $('#divProgress').show();
        $.ajax({
            type: "POST",
            url: "/Bundle/DeleteCustomerBundleProduct",
            dataType: "json",
            data: {
                'customerBundleId': $(this).attr('data-customerbundleid'),
            },
            success: function (data) {
                LoadCustomerBundleProductList();
                //$(chkClass).attr('checked', false);
            },
            complete: function (data) {
                $('#divProgress').hide();
            },
            error: function (data) {
                $('#divProgress').hide();
                alert('Error! Please try again later.');
            }
        });
    }
});

var isValidateRegistrantQuestionsForBundle = false;
var listBundleProducts;

$("body").on("click", ".clsPurchaseall", function () {
    var url = $(this).attr('data-href');
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        data: {
            'isFromBundlePurchaseAll': true
        },
        success: function (data) {
            if (data != null) {
                listBundleProducts = data;
                DisplayRegistrantPopUpForBundle();
            }
        }
    });
});

function DisplayRegistrantPopUpForBundle() {
    if (listBundleProducts.length > 0) {
        while (listBundleProducts.length > 0) {
            var promoCouponCode = listBundleProducts[0].PromoCouponCode;
            if (promoCouponCode.toString() == "CECreditPrice") {
                listBundleProducts.splice(0, 1);
            }
            if (listBundleProducts.length > 0) {
                var productId = listBundleProducts[0].ProductId;
                var discountId = listBundleProducts[0].ProductPriceId;
                var eventTimeId = listBundleProducts[0].EventTimeId;
                var productTypeId = listBundleProducts[0].ProductTypeId;
                var orderItemId = listBundleProducts[0].OrderItemId;
                var customerId = listBundleProducts[0].CustomerId;
                var priceType = listBundleProducts[0].PriceType;
                var isAgendaExists = listBundleProducts[0].IsAgendaExists != null ? listBundleProducts[0].IsAgendaExists : false;
                var isRegQuestionExist = listBundleProducts[0].IsRegQuestionExist != null ? listBundleProducts[0].IsRegQuestionExist : false;

                listBundleProducts.splice(0, 1);
                if (listBundleProducts.length == 0) {
                    isValidateRegistrantQuestionsForBundle = true;
                }

                if (isRegQuestionExist) {
                    if (typeof OpenRegistrantTypeQuestionSetPopup == 'function') {
                        OpenRegistrantTypeQuestionSetPopup(productId, discountId, priceType, 0, 0, orderItemId, false, customerId, true, null, null, 0, false, false, isAgendaExists, true, false, "", false)
                        return false;
                    }
                }
                else if (isAgendaExists) {
                    if (isAgendaExists.toString().toLocaleLowerCase() == 'true' && typeof OpenProductAgendaPopup == "function") {
                        OpenProductAgendaPopup(productId, orderItemId, null, null, discountId, false, true);
                        return false;
                    }
                    $('#divProgress').hide();
                }
                else if (isValidateRegistrantQuestionsForBundle) {
                    window.location.href = '/shoppingcart';
                }
            }
            else {
                window.location.href = '/shoppingcart';
            }
        }
    }
    else {
        return false;
    }
}

$("body").on("click", ".clsClearAllCustomerBundleProduct", function () {
    if (confirm("Are you sure you want to Clear this Bundle?")) {
        $('#divProgress').show();
        $.ajax({
            type: "POST",
            url: "/Bundle/ClearCustomerBundle",
            dataType: "json",
            data: {
            },
            success: function (data) {
                LoadCustomerBundleProductList();
                if ($('.chkAddCustomerBundle') != undefined) {
                    $('.chkAddCustomerBundle').attr('checked', false);
                }
            },
            complete: function (data) {
                $('#divProgress').hide();
            },
            error: function (data) {
                $('#divProgress').hide();
            }
        });
    }
});
//bundle type 5 product add by customer end

//get the mobile ce21 app

$('body').on('click', '.btnGetMobileApp,.linkPagerDutySubmit', function () {
    $.magnificPopup.open({
        items: {
            src: $(this).attr("data-href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        callbacks: {
            close: function () {
                //do stuff
            }
        },
        mainClass: $(this).hasClass('linkPagerDutySubmit') ? 'popPagerDuty' : 'popNotificationOptionMainClass'
    });
    return false;
});

// #region CE Credit Purchase
$("body").on("click", ".btnAddCECredittoCart", function () {
    var isClickByAckButton = $('#isAcknowledge').val();
    var productId = $(this).attr('data-productId');
    addCECredittoCart(productId, isClickByAckButton);
});

$("body").on("click", ".btnCloseAddCECredittoCart", function () {
    var isSendTocart = $(this).attr('data-isSendCustomerCart');
    var isPreRequestProduct = $('#isPreRequestProduct').val() || "false";
    //if (isPreRequestProduct == "true") {
    //    $('#dvPrerequisiteModalBody').css('margin-top', '266px');
    //}
    if (typeof (parent.IsProceedToMemberShipGroup) == 'function' && parent.IsProceedToMemberShipGroup() && typeof (parent.proceedToMembershipGroup) == 'function') {
        parent.proceedToMembershipGroup();//--0011726
    }
    else if (isSendTocart != undefined && isSendTocart == "True" || isPreRequestProduct != "true") {
        parent.window.location.href = '/ShoppingCart';
    }
});

function addCECredittoCart(productId, isClickByAckButton) {
    //var datatarget = "cecreditpurchase" + productId;
    //$('#' + datatarget).modal('hide');
    if ($("#divPurchaseCECreditmodal").length > 0) {
        $("#divPurchaseCECreditmodal").modal("hide");
    }
    $.ajax({
        type: "POST",
        url: ADD_CECREDITTOCART_URL,
        dataType: "json",
        data: {
            'productId': productId
        },
        success: function (data) {

            // 17507: Google Analytics -E-commerce Tracking
            if (data && data.productAddedInCartDetails) {
                googleAnalytics.addToCartEvent(data.productAddedInCartDetails);
                faceBookAnalytics.addToCartEvent(data.productAddedInCartDetails);
            }

            if (data.isSendCustomerToCart != undefined && data.isSendCustomerToCart == true && (isClickByAckButton != "true")) {
                setTimeout(function () {
                    parent.window.location.href = '/ShoppingCart';
                }, 555);
                return false;
            }

            if (data.CartCount != null && data.CartCount != "" && data.CartCount != "0") {
                parent.$("#cartspancount").html(data.CartCount);
                parent.$("#cartItemList").load(GET_CART_URL);
            }
        },
        complete: function (data) {
        },
        error: function (data) {
            alert('Error! Please try again later.');
        }
    });
}
// #endregion CE Credit Purchase

//Close Add to cart popup
function ClosePurchaseCECreditModel(isSendCustomerToCart) {
    $.magnificPopup.close();
    window.location.href = '/ShoppingCart';
}

function LoadCustomerBundleWidget() {
    $.magnificPopup.close();
    LoadCustomerBundleProductList();
}

$(function () {
    var queryParams = [];
    queryParams.push('IsUpdateCartId'); //ReceiptPart,CheckRegistrationView,PaymentInfo
    queryParams.push('Message'); //ShippingInfoView,PaymentInfo,RegistrantConfirmationView,IsShippingAddressExist,PlaceNewOrder
    queryParams.push('subscriptionsMessage');//Account-Register,Account-Login
    queryParams.push('wishListMessage');//Account-Register,Account-Login
    queryParams.push('classroomMessage');//Classroom-AddToCart,ShoppingCart-Mycart
    queryParams.push('InActiveProductCount');//ShoppingCart-Mycart
    queryParams.push('InActiveDiscountProductCount');//ShoppingCart-Mycart
    queryParams.push('alertMsg');
    queryParams.push('sucMsg');
    queryParams.push('warnMsg');
    removeUrlMessage(queryParams);
});

function removeUrlMessage(params) {
    var queryParams = [];
    var urlparts = window.location.href.split('?');
    if (urlparts.length >= 2) {
        for (var i = 0; i < params.length; i++) {
            if (urlparts[1].indexOf(params[i]) > -1) {
                queryParams.push(params[i]);
            }
        }
        if (queryParams && queryParams.length > 0) {

            window.history.pushState("object or string", "Title", removeURLParameter(window.location.href.indexOf("#") > -1 ? window.location.href.substring(0, window.location.href.indexOf("#")) : window.location.href, queryParams));
        }
    }
}

function removeURLParameter(url, parameterArray) {
    //prefer to use l.search if you have a location/link object

    var urlparts = url.split('?');
    if (urlparts.length >= 2) {
        var pars = urlparts[1].split(/[&;]/g);
        for (var j = 0; j < parameterArray.length; j++) {

            var prefix = encodeURIComponent(parameterArray[j]) + '=';


            //reverse iteration as may be destructive
            for (var i = pars.length; i-- > 0;) {
                //idiom for string.startsWith
                if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                    pars.splice(i, 1);
                }
            }

            url = urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
        }

        return url;
    }
    else {
        return url;
    }
}

$('.topMyAccountBar').mouseover(function () {
    getLinkedTenants();
})

function getLinkedTenants() {
    if ($("#divCustomerLinkedTenants").length > 0 && $("#divCustomerLinkedTenants").html().trim().length == 0) {
        $("#divCustomerLinkedTenants").prepend("<p class='loaderTxt' >Please wait ...</p>");

        $.ajax({
            type: "GET",
            url: GET_CUSTOMER_LINKEDTENANTS,
            global: false,
            success: function (response) {
                $("#divCustomerLinkedTenants").html(response);
            }
        });
    }
}

function WidgetBundleDateSelectorPopup(url) {
    $.magnificPopup.close();
    $.magnificPopup.open({
        items: {
            src: url
        },
        type: 'iframe',
        closeOnBgClick: false,
        callbacks: {
            close: function () {
                $(".divProgress").hide();
                ChkBundleTypeFiveCustomerSelectedProducts();
            }
        },
        mainClass: 'popAddtoCartMainClass'
    });

    return false;
}

function closeMultiPaymentSalesPageModal() {
    $.magnificPopup.close();
    window.location.href = '/ShoppingCart';
}

$("body").on("click", ".clsGoToLinkedAccount", function () {
    var linkedCatalogName = $(this).attr("data-linkedCatalogName");
    if (linkedCatalogName != undefined) {
        $("#divProgressLinkedAccount").show();
        $(".clsLinkedAccountLoaderTxt").text("Switching to " + linkedCatalogName);
    }
});

//START: sidebar button in mobile view #0008719
$('.sideBarCloseButton').click(function () {
    $('body').removeClass('sidemenu-active');
});

//if ($('#sidebar').length > 0 && $('#sidebar').html().trim().length > 0) {
//    $('.divBtnFilterShowHide').show();
//}
//else {
//    $('.divBtnFilterShowHide').hide();
//};


//if ($('.btnForHideShowSideBarShoppingCart').length > 0 && $('#sidebar').length > 0) {
//    $('.btnForHideShowSideBarShoppingCart').click(function () {
//        $('body').addClass('sidemenu-active');
//    });
//};

if ($('.btnForHideShowSideBar').length > 0 && $('#sidebar').length > 0) {
    $('.btnForHideShowSideBar').click(function () {
        $('body').addClass('sidemenu-active');
    });
};
function updateCartCount() {
    $('#mobile-cartspancount').html($("#cartspancount").html());
}
//END: sidebar button in mobile view

var changePlaceHolderGlobalSearh = function () {
    if ($(window).width() <= 415) {
        $('#txtProductSearch').attr('placeholder', 'Global Search');
        $('#txtProductSearchOutside').attr('placeholder', 'Global Search');
    }
    else {
        var customFacultyLabel = $("#lblCustomLabelFaculty").val();
        if (customFacultyLabel == null || customFacultyLabel == undefined || customFacultyLabel == "") {
            customFacultyLabel = '';
        }
        $('#txtProductSearch').attr('placeholder', 'Global Search on Seminars, ' + customFacultyLabel);
        $('#txtProductSearchOutside').attr('placeholder', 'Global Search on Seminars, ' + customFacultyLabel);
    };
};
$(window).resize(function () {
    if (width != $(window).width()) {
        toggleSidebarToHamburger();
        changePlaceHolderGlobalSearh();

        if ($('.fixedSideBar').length) {
            if ($(window).width() < 767) {
                $('.fixedSideBar').addClass('disableAffix');
            } else {
                $('.fixedSideBar').removeClass('disableAffix');
            }
        }
    }
});


function onMarketingCodeBegin() {
    $("#btnMarketingCodeSave").attr('disabled', true);
    //$("#btnMarketingCodeSave").html('Processing please wait ...');
}
function onMarketingCodeSuccess(data) {
    if (data != null) {
        loadMarketingDiv(false);
        //$("#marketingCodeSuccessMassage").html(data).closest('.alert').show();       
    }
}

function onMarketingCodefailure() {
    $("#btnMarketingCodeSave").prop('disabled', false);
}

$("body").on('click', ".btnRemoveMarketingCode", function () {
    loadMarketingDiv(true)
});

function loadMarketingDiv(removeCode) {
    $('#divMarketingCode').load("/ShoppingCart/MarketingCodeViewSummary?removeCode=" + removeCode, function () { });
}

$(window).resize(function () {
    if ($('.remove-table-responsive').length > 0) {
        removeTableResponsiveCss();
    }
});

function removeTableResponsiveCss() {
    if ($(window).width() < 974) {
        if ($('.remove-table-responsive').length > 0) {
            $('.remove-table-responsive').removeClass('table-responsive');
        }
    }
    else {
        if (!$('.remove-table-responsive').hasClass('table-responsive')) {
            $('.remove-table-responsive').addClass('table-responsive');
        }
    }
}

$("body").on('click', '.popUpFreeCourseRegister', function () {
    var element = $(this);
    var actionUrl = element.attr("data-href");
    var alternateUrl = element.attr("data-returnUrl");
    var productId = element.attr("data-ProductId"),
        pageType = element.closest(".ProductDetailPortion").length > 0 ? "productdetail" : "SearchProduct";

    if (productId) {

        $.get("/Items/CheckMaxRegistrantForFreeProducts?productId=" + productId, function (data) {
            if (data && data.Message) {
                displayCartMessages(element, data, pageType);
            }
            else {
                $.ajax({
                    type: "GET",
                    url: GET_LOGGEDINCUSTOMERID,
                    dataType: "json",
                    success: function (data) {
                        var isOpenInFullPage = false;
                        if (data != undefined && data != null) {
                            actionUrl = data.customerId > 0 ? alternateUrl : actionUrl;
                            isOpenInFullPage = data.customerId <= 0 && data.isLoginRedirectUrlActive;
                        }
                        if (isOpenInFullPage) {
                            window.location.href = actionUrl;
                        }
                        else {
                            $.magnificPopup.open({
                                items: {
                                    src: actionUrl
                                },
                                type: 'iframe',
                                closeOnBgClick: true,
                                mainClass: 'CustomPop'
                            });
                        }
                        return false;

                    },
                    complete: function (data) {
                    },
                    error: function (data) {

                    }
                });
            }
        });
    }
});

$("body").on("click", ".btnGuestBookRegistration", function () {

    var eventTimeId = $(this).attr('data-eventtimeid');
    var guestbookUrl = $(this).attr('data-href')
    var timeId = 0;
    var multipleEventTimeId = $('.EventDate').val()
    element = $(this),
        productId = element.attr("data-ProductId"),
        pageType = element.closest(".ProductDetailPortion").length > 0 ? "productdetail" : "SearchProduct";;

    if (productId) {
        $.get("/Items/CheckMaxRegistrantForFreeProducts?productId=" + productId + "&eventTimeId=" + eventTimeId, function (data) {
            if (data && data.Message) {
                displayCartMessages(element, data, pageType);
            }
            else {
                if (multipleEventTimeId > 0) {
                    timeId = multipleEventTimeId;
                }
                else {
                    timeId = eventTimeId;
                }

                if (timeId != undefined && timeId > 0 && guestbookUrl != undefined && guestbookUrl != null && guestbookUrl != "") {
                    parent.location.href = guestbookUrl + '/' + timeId;
                }
            }
        });
    }
});

//display purchase alert in widget
$("body").on("click", "#purchaseProductWithAlert", function () {
    var className = $(this).attr('data-purchasebuttontype');
    if (className != undefined && className != null && className != "") {
        $("." + className).trigger('click', [1, undefined, true]);
    }
});

function SearchFiltersCollapse() {
    if ($('.clsSearchFilterWidget').length > 0) {
        $('.clsSearchFilterWidget').each(function () {

            if (this.parentElement.classList.contains('filtersSidebarmenuInToggle') && $(this).find('input[type=checkbox]:checked').length>0) {
                $(this).closest("div").find(".collapse").parent().find('.panel-heading [data-toggle="collapse"]').attr('aria-expanded', 'true');
                $(this).parent().find(".fa-chevron-down").removeClass("fa-chevron-down").addClass("fa-chevron-up");
                $(this).closest("div").find("#filtersSidebarmenuInToggle").addClass("in");
            }
            else {
                //Get Checked Box length
                var CheckedValues = $(this).find('input[type=checkbox]:checked').length;
                var collapseSection = false;

                // Open div for checked Item while user seleted filters
                if (CheckedValues && CheckedValues > 0) {
                    collapseSection = true;
                }
                if ($(this).find('[data-value="Search Near Me"]').length > 0 || $(this).find('[data-value="Directory Search"]').length > 0 || $(this).find('#DirectorySearchByMemberNumber').length > 0) {
                    collapseSection = true;
                }
                if ($(this).find('[data-value="Event Date Filter"]').length > 0 && ($("#txtStartingOnOrAfter").val() || $("#txtStartingOnOrBefore").val())) {
                    collapseSection = true;
                }
                if ($(this).find('[data-value="Geo Search By City"]').length > 0) {
                    collapseSection = true;
                }
                if (collapseSection) {
                    $(this).find(".collapse").parent().find('.panel-heading [data-toggle="collapse"]').attr('aria-expanded', 'true');
                    $(this).find(".collapse").parent().find(".glyphicon-plus").removeClass("glyphicon-plus").addClass("glyphicon-minus");
                    $(this).find(".panel-collapse").addClass("in");
                }
            }
        });
    }

}

$("#txtStartingOnOrAfter").on('change', function () {
    $("#txtStartingOnOrBefore").datepicker("option", "minDate", $("#txtStartingOnOrAfter").val());
});
$("#txtStartingOnOrBefore").on('change', function () {
    $("#txtStartingOnOrAfter").datepicker("option", "maxDate", $("#txtStartingOnOrBefore").val());
});


$(function () {
    if ($('.clsNotices').length > 0 && document.cookie.indexOf('CookieNoticeAccepted=') === -1 && document.cookie.indexOf('CookieNoticeDeclined=') === -1) {
        $('.clsNotices').show();
    }
});

//Start: 0011084: EUGDPR Step 4: Cookie Notice
$('body').on('click', '.clsCookieNoticeAccept', function () {
    var expDate = new Date();
    expDate.setFullYear(expDate.getFullYear() + 1);
    var domain = window.location.hostname;
    if (domain.indexOf("ce21") === -1) {
        var d = domain.split('.');
        d.shift();
        domain = d.join('.');
    }
    var setDate = new Date();
    document.cookie = "CookieNoticeAccepted=" + setDate.toISOString() + "; domain=" + domain + "; path=/; expires=" + expDate.toUTCString();
    setTimeout(function () { $('.clsNotices').hide(); }, 500);
})
$('body').on('click', '.clsCookieNoticeDecline', function () {
    var expDate = new Date();
    expDate.setFullYear(expDate.getFullYear() + 1);
    var domain = window.location.hostname;
    if (domain.indexOf("ce21") === -1) {
        var d = domain.split('.');
        d.shift();
        domain = d.join('.');
    }
    var setDate = new Date();
    document.cookie = "CookieNoticeDeclined=" + setDate.toISOString() + "; domain=" + domain + "; path=/; expires=" + expDate.toUTCString();
    setTimeout(function () { $('.clsNotices').hide(); }, 500);
})
$('body').on('click', '.clsCookieNoticeRevoke', function () {
    var domain = window.location.hostname;
    if (domain.indexOf("ce21") === -1) {
        var d = domain.split('.');
        d.shift();
        domain = d.join('.');
    }
    document.cookie = "CookieNoticeAccepted=; domain=" + domain + "; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
    document.cookie = "CookieNoticeDeclined=; domain=" + domain + "; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
    setTimeout(function () { $('.clsNotices').show(); }, 500);
})
//End: 0011084: EUGDPR Step 4: Cookie Notice

// #11007:EUGDPR Step 2: Marketing Consent-EU Start
function checkMarketingConsentCustomer(email, countryName) {
    countryName = countryName == undefined ? "" : countryName;
    if ($("#divMarketingConsentCustomerEUAware").length > 0 || $("#divLegitimateInterestEUaware").length > 0) //#11618: Use for displaying Legitimate Interest statement
    {
        $.ajax({
            type: "GET",
            url: CHECK_MARKETINGCONSENT_CUSTOMER,
            dataType: "json",
            data: {
                'email': email,
                'countryName': countryName
            },
            success: function (data) {
                if (data) {
                    if ($("#divMarketingConsentCustomerEUAware").length > 0) {
                        $("#divMarketingConsentCustomerEUAware").show();
                        enableDisablemarketingConsent(false);
                    }
                    if ($("#divLegitimateInterestEUaware").length > 0) {
                        $("#divLegitimateInterestEUaware").show();
                        setOrRemoveConsentInCookie("LegitimateInterestEUaware", false, $("#divLegitimateInterestEUaware").attr("data-page"));
                    }
                }
                else {
                    if ($("#divMarketingConsentCustomerEUAware").length > 0) {
                        $("#divMarketingConsentCustomerEUAware").hide();
                        enableDisablemarketingConsent(true);
                        setOrRemoveConsentInCookie("MarketingConsentEUAware", true, $("#divMarketingConsentCustomerEUAware").attr("data-page"))
                    }
                    if ($("#divLegitimateInterestEUaware").length > 0) {
                        $("#divLegitimateInterestEUaware").hide();
                        setOrRemoveConsentInCookie("LegitimateInterestEUaware", true, $("#divLegitimateInterestEUaware").attr("data-page"));
                    }
                }
            },
            error: function (data) {
                alert('Error! Please try again later.');
            }
        });
    }

}

// set the consent in cookie
function setOrRemoveConsentInCookie(type, isRemove, page) {
    if (!page) { return; }
    if (isRemove) {
        document.cookie = type + "=; path=/ "
    } else {
        document.cookie = type + "=true; path=/ "
    }
}

//As per mantis : #11211
function enableDisablemarketingConsent(enable) {
    if ($('#MarketingConsentEUAware').length > 0) {
        $('#MarketingConsentEUAware').prop("disabled", enable);
        if ($('#hdnMarketingConsentEUAware').length == 0) {
            $('input[name="MarketingConsentEUAware"]').prop("disabled", enable);
        }

    }
}
// #11007:EUGDPR Step 2: Marketing Consent-EU End

// display alert for show the authorization payment of membership when memberhip having recurring payment
function membbershipAuthorizationAlert(membershipRequestData, callback) {

    var childIds = "";
    var alertFrom = membershipRequestData.alertFrom || '';
    if (alertFrom == "addonpage") {
        var childIds = $(".chkAddonMemberships:checked").map(function () { return $(this).attr("data-id") }).get().join();
    }

    $.post("/Search/GroupBillingcycle", {
        memberShipTypeId: membershipRequestData.mebershipTypeId,
        childIds: childIds,
        checkAddons: alertFrom != "addonpage",
        noOfUser: membershipRequestData.noOfUsers || 0
    }, function (data) {
        if (data && data.ParentId && data.ParentId > 0) {

            if (alertFrom == "questionset") {
                $("#parentMembershipId").val(data.ParentId);
                callback();
            }
            else {
                chooseAddonGroups(data.ParentId);
            }
        }
        else if (data && data.trim()) {
            $.confirm({
                title: membershipRequestData.memberhipLable || 'Membership',
                boxWidth: '550px',
                useBootstrap: false,
                type: 'green',
                content: data,
                buttons: {
                    ok: {
                        text: 'Accept and Add to Cart',
                        btnClass: 'btn-success',
                        action: callback
                    },
                    cancel: {
                        text: 'Cancel Order',
                        btnClass: 'btn-warning',
                        action: function () {
                            if (typeof (parent.clearSessionStorageKeyForGroup) == 'function') {
                                parent.clearSessionStorageKeyForGroup();//--0011726
                            }
                            $("#groupPaymentCycleId").val('');
                            $("#autoRecurringType").val(0);
                        }
                    }
                }
            });
            setTimeout(function () {
                $("#groupPaymentCycleId").val($(".billingCycleType:checked").attr("data-GroupCycleId"))
                $("#autoRecurringType").val($(".customerRecurringType:checked").val());
            }, 200);
        } else {
            callback();
        }
    });
}

// used for send to particular inner tab when url having the has parameter
function DisplayInnerTabs() {
    var hasTabUrl = window.location.hash;
    if (hasTabUrl && $('.aInnerTab[href=' + hasTabUrl + ']').length > 0) {
        $('.aInnerTab[href=' + hasTabUrl + ']').trigger('click');
    }
}

function chooseAddonGroups(parentId) {
    if (parentId > 0) {
        $('#divProgress').show();
        location.href = "/Group/Addons?parentMembershipId=" + parentId;
    }
}

// used for attached hash tag to url
$(".aInnerTab[data-toggle='tab']").click(function () {
    var hasTag = $(this).attr('href');
    if (hasTag) {
        window.history.replaceState(null, null, hasTag);
    }
});

//ads image upload in form
var adsImageFiles = [];
var i;
var img = '<img style="max-height:100%;object-fit:contain;">';
var updateImageName = "";

function dragAdsImg(event, i) {
    var allowedFileExtension = ["jpg", "jpeg", "png", "gif", "ico", "bmp"];
    var selectedFile = event.target.files[0];
    var selectedFileName = selectedFile.name;

    if ($.inArray(selectedFileName.split('.').pop().toLowerCase(), allowedFileExtension) == -1) {
        alert("Only the following formats are allowed: .jpg, .jpeg, .png, .gif, .ico or bmp");
        $("#AdsImgUpload" + i).val("");
        $("#EditAdImg" + i).val("");
        return;
    }

    var fileSize = selectedFile.size;
    if (fileSize > (1048576 * 5)) {
        alert("Maximum file size is 5 MB");
        $("#AdsImgUpload" + i).val("");
        $("#EditAdImg" + i).val("");
        return;
    }

    if (updateImageName != undefined && updateImageName != null && updateImageName != "") {
        var deletedFiles = $('#DeletedFiles').text();
        var latestDeletedFiles = updateImageName;
        var allDeleteFiles = deletedFiles.concat(latestDeletedFiles, ",");
        $('#DeletedFiles').text(allDeleteFiles);
        $('#DeletedFiles').attr('value', allDeleteFiles);
        updateImageName = "";
    }

    adsImageFiles[i] = event.target.files[0];
    imgSrc = URL.createObjectURL(event.target.files[0]);
    $('#FileUploadDiv' + i + ' span').remove();
    $('#FileUploadDiv' + i + ' #btnDivAdsUpload' + i).remove();
    $('#FileUploadDiv' + i + ' h4').remove();
    $('#FileUploadDiv' + i + ' img').remove();
    $("#inputDiv" + i).css({ 'display': 'none' });
    $('#FileUploadDiv' + i).css({ 'background': 'white', 'padding': '0' });
    $('#FileUploadDiv' + i).append('<img style="max-height:100%;object-fit:contain;" src="' + imgSrc + '">');
    $('#FileUploadDiv' + i).append('<input type="file" name="files" accept=".jpg,.jpeg,.png,.gif,.ico,.bmp" id="EditAdImg' + i + '" class="EditAdImg" onChange="dragAdsImg(event,' + i + ')" style="display:none;" /><div id="btnDivAdsUpload' + i + '" class="btnDivAdsUpload"><a style ="border-right:1px solid #ddd;padding-left:5px" title = "click here for edit this image" ><h4><span aria-hidden="true" style="margin-right: 5px;" class="glyphicon glyphicon-edit" onclick="EditAdsImg(' + i + ')"></span></h4></a ><a style="padding-left:5px;" title="click here for remove this image" ><h4><span aria-hidden="true" style="margin-right: 5px;" onclick="removeAdsImg(' + i + ')" class="glyphicon glyphicon-remove"></span></h4></a></div > ');
    $('#AdsImgUpload' + i).css('display', 'none');
}

$('body').on('click', '#uploadImageButton', function () {
    var isRequired = $(this).attr('data-val');
    var imageCount = $("#imageAddedCount").val();
    $('#imageInputGroup').append('<div id="0" class="FileUploadThumbnail col-lg-2" style="width:151px;"><div id="FileUploadDiv' + imageCount + '" class="FileUploadDiv"><div class="inputDiv" id="inputDiv' + imageCount + '"><h4 class="fa fa-cloud-upload" style="margin-top: 0; text-align: end; font-size:25px"></h4><span style="padding-bottom:35px; text-align:center;">Drag &amp; Drop Image<br>Or<br> Click Here to Upload</span><input class="' + (isRequired == "1" ? 'adsAnswerImages' : '') + '" type="file" name="files" accept=".jpg,.jpeg,.png,.gif,.ico,.bmp" onchange="dragAdsImg(event,' + imageCount + ')" id="AdsImgUpload' + imageCount + '" style="height: 100%; width: 100%; opacity: 0; margin-top: -110px;"></div></div></div>');
    $("#imageAddedCount").val(parseInt(imageCount) + 1);
})

$('#ClassifiedAdsPostingForm').submit(function (e) {
    //chek date is valid or not start
    var isValid = true;
    $('.clsDatePicker').each(function () {
        var dateValue = $(this).val();
        var questionId = $(this).attr('data-questionid');
        var clsName = ".clsValDate" + questionId;

        if (dateValue != undefined && dateValue != null && dateValue != "") {
            if (ValidateDate(dateValue)) {
                $(clsName).hide();
            }
            else {
                isValid = false;
                $(clsName).show();
                var divText = "#txtDate" + questionId;
                $(divText).focus();
                return false;
            }
        }
        validateDatePicker(dateValue, clsName);

    });

    //check document required validation
    $('.clsMembershipAnswerDocuments').each(function () {
        var $this = $(this);
        var id = $this.attr("data-questionId");
        if ($this.find("table").hasClass("noResults")) {
            $("#spnError_" + id).text('Please upload document.')
            $("#spnError_" + id).addClass("field-validation-error");
            isValid = false;
        }
    });


    // Trim whitespace from input fields and textareas in the #ClassifiedAdsPostingForm
    $('#ClassifiedAdsPostingForm input[type="text"]').each(function () {
        var element = $(this);
        var elementValue = element.val().trim();
        element.val(elementValue); // Trim the value and set it back to the input field
    });

    $('#ClassifiedAdsPostingForm textarea').each(function () {
        var element = $(this);
        var elementValue = element.val().trim();
        if (elementValue == '') {
            element.val(elementValue);
        }
        // Trim the value and set it back to the input textarea
    });

    //check Ads Images required validation
    $('.adsAnswerImages').each(function () {
        var isRequired = $('#IsImageUploadRequired').val();
        var imageCount = $("#imageAddedCount").val();
        var count = 0;

        if (isRequired == '1') {
            for (var i = 0; i < parseInt(imageCount); i++) {
                if ($('#FileUploadDiv' + i).find('img').length != 0) {
                    count++;
                }
            }

            if (count == 0) {
                $("#spnError_AdsImage").text('Please upload Image.')
                $("#spnError_AdsImage").addClass("field-validation-error");
                $("#spnError_AdsImage").addClass("help-block");
                isValid = false;
            } else {
                $("#spnError_AdsImage").text('')
                $("#spnError_AdsImage").addClass("");
            }
        }
        else {
            $("#spnError_AdsImage").text('')
            $("#spnError_AdsImage").addClass("");
        }
    });

    isValid = checkMultiChoiceValidation(isValid);

    var isCKEditorRequired = $("#IsCKEditorRequired").val();
    if (isCKEditorRequired == "1") {
        var ckEditorValue = $(".ckEditorValue").val();
        if (ckEditorValue == "") {
            $("#CKEditorValidationMessage").html("This field is required.").css("color", "#b94a48").addClass("field-validation-error").show();
            return false;
        }
    }

    if (isValid == false) {
        return false;
    }

    var formdetails = document.getElementById("ClassifiedAdsPostingForm"); // Find the form by its ID
    if (formdetails.checkValidity()) {
        $('#btnClassifiedQuestionSet').html('<i class="fa fa-refresh fa-spin"></i>&nbsp;&nbsp;Processing...').attr('disabled', 'disabled');
    }
});

//Ordering Ads Images start
$(function () {
    $("#imageInputGroup").sortable({
        update: function (event, ui) {
            getIdsOfImages();
        }
    });
});


function getIdsOfImages() {
    var values = [];
    $('.FileUploadThumbnail').each(function (index) {
        values.push($(this).attr("id"));
    });

    $('#ImageDisplayOrder').text(values);
    $('#ImageDisplayOrder').attr('value', values);
}

//Ordering Ads Images end

function AdDetailsTxtLmt(id) {
    var TextLimit = $("#TextLimit").val();
    if (TextLimit != "") {
        $(id).attr('maxlength', TextLimit);
    }
    var adsDetailsMsg = $(".AdsDetailsMsg").val();
    var CharLeft = adsDetailsMsg.length;
    $("#charLeftforMsg").text(" " + CharLeft + " of ")
}

function EditAdsImg(i, imageName) {
    if (imageName != undefined) {
        updateImageName = imageName;
    }

    $("#EditAdImg" + i).trigger("click");
    $("#inputDiv" + i).remove();
}

function removeAdsImg(i, fileName) {
    var deletedFiles = $('#DeletedFiles').text();
    var latestDeletedFiles = fileName ? fileName : ""; // If fileName is undefined, set it to an empty string
    var allDeleteFiles = deletedFiles.concat(latestDeletedFiles, ",");
    $('#DeletedFiles').text(allDeleteFiles);
    $('#DeletedFiles').attr('value', allDeleteFiles);

    var isRequired = $('#IsImageUploadRequired').val();
    document.getElementById('FileUploadDiv' + i).innerHTML = "";
    $('#FileUploadDiv' + i).append('<h4 class="fa fa-cloud-upload" style="margin-top: 0; text-align: end; font-size:25px"></h4><span style = "padding-bottom:35px; text-align:center;">Drag & Drop Image<br />Or <br /> Click Here to Upload</span ><input type="file" name="files" class="' + (isRequired == "1" ? 'adsAnswerImages' : '') + '" accept=".jpg,.jpeg,.png,.gif,.ico,.bmp" onChange="dragAdsImg(event,' + i + ')" id="AdsImgUpload' + i + '"  />');
    SetDefault(i);
    $('#FileUploadDiv' + i).css({
        'background': 'lightgrey',
        'padding': '5px'
    });
}

//css changes for ads img div
function NoOfImg() {
    var NoOfImg = (document.getElementById("NoOfImg") != null && document.getElementById("NoOfImg").value != null && document.getElementById("NoOfImg").value != undefined) ? document.getElementById("NoOfImg").Value : 0;
    if (NoOfImg > 0) {
        for (i = 0; i < NoOfImg; i++) {
            $('#AdsImgUpload' + i).css({
                'height': '100%',
                'width': '100%',
                'opacity': '0',
                'margin-top': '-110px'
            })
        }
    }
}

function SetDefault(i) {
    $('#AdsImgUpload' + i).css({
        'height': '100%',
        'width': '100%',
        'opacity': '0',
        'margin-top': '-110px'

    })
}

//mantis item : #11106: Manager/Catalog > Do not allow letters to be entered into any phone files / fax fields in Customer / Speaker Accounts
//$("body").on("keydown", ".numValidation", function (e) {
//        var key = e.charCode || e.keyCode || 0;
//        var validateNumber = /^([0-9]|[(]|[)]|[-]|[+]|[ ])+$/;
//        // Allow: backspace, delete, tab, escape, enter and .
//        if ($.inArray(key, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
//            // Allow: Ctrl+A, Command+A,Ctrl+V, Command+V
//            ((key === 65 || key === 86) && (e.ctrlKey === true || e.metaKey === true)) ||
//            // Allow: home, end, left, right, down, up
//            (key >= 35 && key <= 40)) {
//            // let it happen, don't do anything
//            //return;
//        }
//        else if (validateMobileNumber(e.key) || e.ctrlKey === true) {
//            return;
//        }
//        else {
//            e.preventDefault();
//        }

//});

//$('body').on('paste', '.numValidation', function (e) {
//    var pastedData = e.originalEvent.clipboardData.getData('text');
//    if (pastedData && pastedData != "")
//    {
//        var isValid = validateMobileNumber(pastedData);
//        if (!isValid)
//        {
//            e.preventDefault();
//        }

//    }
//});

var validateMobileNumber = function (number) {
    var validateNumber = /^([0-9]|[(]|[)]|[-]|[+]|[ ])+$/;
    if (validateNumber.test(number)) {
        return true;
    }
    else {
        return false;
    }
}


$("body").on("click", ".clsExistsMembership", function () {
    var membershipTypeId = $(this).attr("data-val");
    var url = $(this).attr("data-href");
    $("#divProgress").show();
    $.get("/Search/MembershipExistsForCustomer?membershipTypeId=" + membershipTypeId, function (data) {
        $("#divProgress").hide();
        if (data !== undefined && data !== "") {
            alert(data);
        }
        else {
            window.location.href = url;
        }
    });
});

function addtoCartMembership(mebershipTyprId, isPurchaseGroupWithProduct, priceId, childMembershipIds, itemId) {
    var groupPaymentCycleId = $("#groupPaymentCycleId").val();
    var autoRecurringType = Number($("#autoRecurringType").val() || 0);
    if (mebershipTyprId) {
        $("#divProgress").show();
        $.ajax({
            type: "POST",
            url: "/Search/AddToCartMemberType",
            dataType: "json",
            data: {
                "membershipTypeId": mebershipTyprId,
                "groupPaymentCycleId": groupPaymentCycleId,
                "autoRecurringType": autoRecurringType,
                "childMemberships": childMembershipIds,
                "itemId": itemId
            },
            success: function (data) {
                $("#divProgress").hide();
                var message = data.message;
                if (data.isSuccess != undefined && data.isSuccess == false && data.message) {
                    alert(data.message);
                }
                if (isPurchaseGroupWithProduct && isPurchaseGroupWithProduct == true) {
                    memberShipSuccessMessage(data);
                    if (typeof (addToCartProductAfterMembership) == "function") {
                        addToCartProductAfterMembership(priceId);
                    }
                }
                else {
                    if (data.isSendCustomerToCart != undefined && data.isSendCustomerToCart == true && !data.message) {
                        window.location.href = '/ShoppingCart';
                        return false;
                    }
                    // retrieve message
                    memberShipSuccessMessage(data);
                }


            },
            error: function (data) {
                $("#divProgress").hide();
                alert("Error! please try later.");
            }
        });
    }
}

function memberShipSuccessMessage(data) {
    if (data && data.message != "") {
        $("#spnMemberTypeConfirmationMessage").html(data.message);
        $("#divMemberTypeConfirmationMessage").show();
        setTimeout(function () {
            $("#divMemberTypeConfirmationMessage").hide();
        }, 10000);
    }
    parent.$("#cartspancount").html(data.CartCount);
    parent.$("#cartItemList").load('/ShoppingCart/GetCart');
}

//#10402 - Save BrowserInfo - Start
function SaveBrowserInfo() {
    if ($("#hfBrowserInfo").length > 0) {
        browserReport(function (err, report) {
            if (err) {
                throw err;
            }
            $("#hfBrowserInfo").val(JSON.stringify(report));
        });
    }
}

$("body").on("click", ".webinar-launch-button, .clsFreeViewerLaunch, .CE21_MyAccount_tabPendingSeminars_LaunchScrombtn", function () {
    SubmitBrowerInfoForWebinar($(this).attr("data-ProgramRegistrantId"));
})

function SubmitBrowerInfoForWebinar(programRegistrantId) {
    if ($("#hfBrowserInfo").length > 0) {
        if (!$("#hfBrowserInfo").val()) {
            browserReport(function (err, report) {
                if (err) {
                    throw err;
                }
                $("#hfBrowserInfo").val(JSON.stringify(report));
            });
        }

        if (isImpersonateSession()) return;

        $.get("/ShowtimeWidget/GetCurrurntDateTimeWithTimeZone", function (data) {
            if (data !== undefined && $("#hfBrowserInfo").val()) {
                report = JSON.parse($("#hfBrowserInfo").val());
                report.submittedVia = "Webinar Launch Button";
                report.SubmmitedDate = data;

                $.ajax({
                    type: 'POST',
                    url: '/ShowtimeWidget/SubmitBrowser',
                    dataType: 'json',
                    data: {
                        'programRegistrantId': programRegistrantId, 'settings': JSON.stringify(report)
                    },
                    success: function () {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                    }
                });
            }
        });
    }
}
//#10402 - Save BrowserInfo - End

function getProductsInfo() {
    var pIds = $(".hdnGlobalPid").map(function () {
        return $(this).val();
    }).get().join(",");

    $.ajax({
        type: "POST",
        url: GET_PRODUCTS_INFO,
        dataType: "json",
        data: {
            'pIds': pIds,
        },
        success: function (data) {
            if (data) {
                $.each(data, function (i, data) {
                    if (Number(data.ProductId) > 0) {
                        if (data.WidgetMessage) { //set widget messages for shippable item
                            $(".clsWidgetMessage[data-Pid=" + data.ProductId + "]").html(data.WidgetMessage);
                        }
                        if (data.CatalogMessage) { //set catalog messages for shippable item
                            $(".clsCatalogMessage[data-Pid=" + data.ProductId + "]").html(data.CatalogMessage);
                        }
                    }
                });
            }
        },
        error: function (data) {
        }
    });
}

function CheckADARequirement() {
    if ($("#DivADARequirement").length > 0) {
        if ($("#ADARequirementNote").val() != "" && $("#ADARequirementNote").val() != undefined) {
            $("#ADARequirement").prop("checked", true);
            $("#ADARequirementNote").attr("data-Note", $("#ADARequirementNote").val());
        }
        else {
            $("#ADARequirement").prop("checked", false);
            removeADARequirementValidation();
        }
    }
}
function AddADARequirementValidation() {
    if ($("#DivADARequirement").length > 0) {
        if ($("#ADARequirement").prop("checked") == true) {
            $("#ADARequirementNote").attr("required", "required");
            $("#ADARequirementNote").closest("div").find("span.field-validation-error").show().html('');
            $("#ADARequirementNote").val($("#ADARequirementNote").attr("data-Note"));
        }
        else {
            $("#ADARequirementNote").attr("data-Note", $("#ADARequirementNote").val());
            $("#ADARequirementNote").val("");
            removeADARequirementValidation();
        }
    }
}
function removeADARequirementValidation() {
    $("#ADARequirementNote").removeAttr("required").removeClass("input-validation-error");;
    $("#ADARequirementNote").closest("div").find("span.field-validation-error").hide();
    $("#ADARequirementNote").closest("div").parents('div').removeClass("has-error");
}

//Start::> 0012639: iPhone Only > Browser > Attendance Question/Participation Code Cert Requirement - not compatible warning w/ Quick Launch
//method using for all pages on catalog: classroom-schedule, product-detail, all widgets, membership-group
$('body').on('click', 'a:not(.clsIphoneMsgBtn)[href*="/launchfreeviewer?"], .clsFreeViewerLaunch, .btnScheduletabsLaunchViewer', function () {
    if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
        var $this = $(this);
        var viewerURL = $this.attr('href');
        var slashIndex = 0;
        var programRegistrantId = 0;
        var encryptedString = getParameterByNameForHref(viewerURL, 'x');

        var isShowTimeUrl = viewerURL.indexOf('showtime/') > 0;

        if (!viewerURL || viewerURL.indexOf('javascript') > 0)
            return false;

        if (isShowTimeUrl) {
            var classroomViewerRegId = $this.attr('data-programregistrantid');
            slashIndex = viewerURL.lastIndexOf('/');
            programRegistrantId = viewerURL.indexOf('?') > 0 ? classroomViewerRegId : viewerURL.substring(slashIndex + 1); //handle viewer open through classroom schedule tab
        }


        if ((encryptedString && encryptedString.trim() != "") || (isShowTimeUrl && Number(programRegistrantId) > 0)) {
            $.ajax({
                type: "POST",
                url: "/Items/IphoneNonCompatibleMessage",
                dataType: "json",
                data: {
                    'encryptedStr': encryptedString.trim(), 'viewerUrl': viewerURL, 'programRegistrantId': programRegistrantId
                },
                success: function (data) {
                    $('#divProgress').hide();


                    if (data && data.ShowMessage == true) {
                        var showMessage = function () {
                            var ExistAttendanceRequirment = data.ExistAttendanceRequirment;
                            parent.$('#divIphoneMessageGeneral').modal('show');
                            parent.$("#divIphoneMessageGeneral .modal-footer").find('a').attr('href', viewerURL);
                            parent.$("#divIphoneMessageGeneral .modal-footer").find('a').addClass('csViewerOk');

                            if (ExistAttendanceRequirment == true) {
                                parent.$('.iphone-questionrequirement-message').show();
                                parent.$('.iphone-participationcode-message').hide();
                            } else {
                                parent.$('.iphone-questionrequirement-message').hide();
                                parent.$('.iphone-participationcode-message').show();
                            }
                            parent.$.magnificPopup.close();

                        };

                        if (parent.$('#divIphoneMessageGeneral').length > 0) {
                            showMessage();
                        }
                        else {
                            //Firs time call get html
                            $.get('/Items/IphoneInCompatiblePopup', function (iPohneHtml) {
                                parent.$('body').append(iPohneHtml);
                                showMessage();
                            });
                        }
                        return false;
                    } else {
                        if (!isIOsSafari() && $this.attr('target') && ($this.attr('target') == '_blank' || $this.attr('target').indexOf('ce21') >= 0)) {
                            window.open(viewerURL, '_blank');
                        } else if (isIOsSafari()) {
                            window.open(viewerURL, '_self'); //#0017560
                        }
                    }
                },
                error: function (data) {
                    alert('Error! Please try again later.');
                    $('#divProgress').hide();
                }
            });
        }
        return false;
    }
    else {
        //#22343
        var btnUrl = $(this).attr('href') == undefined ? $(this).attr('data-href') : $(this).attr('href');

        if (!$(this).hasClass('csIphone')) {
            if (btnUrl.indexOf('?ClassroomTab=') != -1) {
                var classroomTabVal = getURLParameter(btnUrl, "ClassroomTab");
                if (classroomTabVal != null && classroomTabVal != undefined && classroomTabVal != '') {
                    var newUrl = new URL(btnUrl);
                    newUrl.searchParams.set("ClassroomTab", classroomTabVal + "_" + document.documentElement.scrollTop); // setting your param
                    window.open(newUrl, 'ce21');
                    return false;
                }
            }
        }
    }
});

$("body").on('click', '.csViewerOk', function () {
    window.open($(this).attr("href"), isIOsSafari() ? '_self' : '_blank');
});
//End::> 0012639

//Logic for Checking checkboxes and all Checkbox.
//Use the pattern for class for single checkbox => "chkSelect-'AnySignificantName'" and for all checkbox => "chkSelect-'AnySignificantName'-all" to make use of this logic.
$("body").on("click", "input[type='checkbox'][class*='chkSelect-']", function () {
    var classes = $(this).attr('class').split(' ');
    var selfClassname = '', type = 'single', singleClassName = '', allClassName = '';
    if (classes.length > 0) {
        classes.forEach(function (a) {
            if (a.indexOf('chkSelect-') > -1) {
                selfClassname = a;
                return;
            }
        });
    }
    if (selfClassname !== '') {
        if ((selfClassname.match(/-/g) || []).length === 2) {
            type = 'all';
            allClassName = selfClassname;
            singleClassName = allClassName.replace("-All", "");
        }
        else {
            singleClassName = selfClassname;
            allClassName = singleClassName + "-All";
        }
        if (singleClassName !== '' && allClassName !== '') {
            if (type === "all") {
                $("." + singleClassName).prop("checked", $(this).is(":checked"));
            }
            else {
                if ($(this).is(":checked") && $("." + singleClassName).length === $("." + singleClassName + ":checked").length) {
                    $("." + allClassName).prop("checked", true);
                }
                else {
                    $("." + allClassName).prop("checked", false);
                }
            }
        }
    }
});

function deleteOldRegistrantTypeQuestionSetAnswers(orderItemId, isDeleteRegistrantSetAnswers) {
    $.getJSON("/Search/DeleteRegistrantTypeQuestionSetAnswers/", {
        orderItemId: orderItemId,
        isDeleteRegistrantSetAnswers: isDeleteRegistrantSetAnswers
    })
        .fail(() => {
            console.error("Failed to delete registrant type question set answers.");
        });
}

var getComparelist = function () {
    $("#compareProductcartItemList").load(GET_COMPAREPRODUCTCART_URL, function () {
        var count = $('#compareProductcartItemList input[name="CompareCount"]').val();
        $('#compareProductcartspancount').text(count);
    });
};

//12850: Catalog - change placement of mail code functionality to make more visible / likely a customer will enter one
$("body").on("click", "#btnMarketingCodeSave", function () {
    var marketingCode = $("#MarketingCode").val();
    if (!marketingCode) {
        $(".clsRequired").show();
        return false;
    }
    $('#divProgress').show();
    $.ajax({
        type: "POST",
        url: "/ShoppingCart/SaveMarketingCode",
        dataType: "json",
        data: {
            'marketingCode': marketingCode
        },
        beforeSend: function () {
            onMarketingCodeBegin();
        },
        success: function (data) {
            onMarketingCodeSuccess(data);
            $('#divProgress').hide();
        },
        error: function (data) {
            onMarketingCodefailure();
            $('#divProgress').hide();
        }
    });
    $('#divProgress').hide();
});



//12842: Registration Types - Registration Question Sets start.
//chek any registrant type question set available with price adjustment
var IsRegistrantTypeQuestionSetAvailable = function (discountId, eventTimeId, productId, productTypeId, isCheckForRegistrants = false, isFromEditRegistrant = false) {
    var isEnable = false;
    $.ajax({
        type: "GET",
        url: "/Items/IsRegistrantTypeQuestionSetAvailable/",
        data: { "discountId": discountId, "eventTimeId": eventTimeId, "productId": productId, "productTypeId": productTypeId, "isCheckForRegistrants": isCheckForRegistrants, "isFromEditRegistrant": isFromEditRegistrant },
        dataType: "json",
        async: false,
        success: function (Data) {
            isEnable = Data;
        },
        error: function () {
            isEnable = false;
        }
    });
    return isEnable;
}


//open registrant type question set popup  
var OpenRegistrantTypeQuestionSetPopup = function (productId, discountId, priceType, questionSetId = 0, programRegistrantId = 0, orderItemId = 0, isFetchAnswers = false, customerId = 0, isRegistrantConfirmationPage = false, customerEmail = '', _callback = '', orderId = 0, isShowCloseButton = true, IsRealtedProduct = false, isAgendaExists = false, isForBundle = false, isCompleteRegistration = false, btnType = "", isDisplayRequestInfo = false) {
    var width = 800;
    var height = 700;
    parent.$('.mfp-iframe-holder .mfp-iframe-scaler').css('padding-top', '80%');
    parent.$('.mfp-iframe-holder .mfp-content').css('max-width', '900px');
    parent.parent.$('.mfp-iframe-holder .mfp-iframe-scaler').css('padding-top', '80%');
    parent.parent.$('.mfp-iframe-holder .mfp-content').css('max-width', '920px');
    $.magnificPopup.open({
        items: {
            src: "/Search/RegistrantTypeQuestionSet" + '?productId=' + productId + '&discountId=' + discountId + '&priceType=' + priceType
                + '&questionSetId=' + questionSetId + '&programRegistrantId=' + programRegistrantId + '&orderItemId=' + orderItemId
                + '&isFetchAnswer=' + isFetchAnswers + '&customerId=' + customerId + '&isRegistrantConfirmationPage=' + isRegistrantConfirmationPage + '&customerEmail=' + customerEmail
                + '&orderId=' + orderId + '&IsRealtedProduct=' + IsRealtedProduct + '&isAgendaExists=' + isAgendaExists + '&isForBundle=' + isForBundle + '&isCompleteRegistration=' + isCompleteRegistration + '&btnType=' + btnType + '&isDisplayRequestInfo=' + isDisplayRequestInfo
        },
        type: 'iframe',
        showCloseBtn: isShowCloseButton,
        closeOnBgClick: false,
        mainClass: 'CustomPop',
        callbacks: {
            close: function () {
                if (_callback && typeof _callback == 'function') {
                    _callback();
                }
                //if (typeof(clearSessionStorageKeyForGroup) == 'function') {
                //    clearSessionStorageKeyForGroup();
                //}
            }
        }
    });
    $('.mfp-content').css('height', height);
    $('.mfp-content').css('width', width);
    $('.mfp-iframe-holder .mfp-content').css('max-height', height + 'px');
    $('.mfp-iframe-holder .mfp-content').css('max-width', width + 'px');
    return false;
}

//close registrant type question set pop up
var addToCartProductAfterRegistrantTypeQuestionSet = function (isRealtedProduct, ProductId, orderItemId, groupProductPricecId, isUserInfoRequest = false, isClosePopUp = 'false', registrantQuestionSubmissionType = 0, customerEmail = '', isAgendaExists = 'false', isAgendaRequestInfo = false, isForBundle = false, chkPurchaserForRegistrant = 'false') {
    var isRegistrantRequestInfo = registrantQuestionSubmissionType == 2 ? true : false;
    if (isClosePopUp.toLowerCase() == 'true' && isForBundle) {
        if (isAgendaExists.toLocaleLowerCase() == 'true' && typeof OpenProductAgendaPopup == "function") {
            OpenProductAgendaPopup(ProductId, orderItemId, null, null, groupProductPricecId, false, true, 0, false, chkPurchaserForRegistrant, isRegistrantRequestInfo);
            return false;
        }
        else if (registrantQuestionSubmissionType >= 0) {
            if (isValidateRegistrantQuestionsForBundle) {
                window.location.href = '/shoppingcart';
            }
            if (typeof DisplayRegistrantPopUpForBundle == "function") {
                DisplayRegistrantPopUpForBundle();
            }
            return false;
        }
    }
    else {
        if (isClosePopUp.toLowerCase() == 'true' && customerEmail) {
            if (registrantQuestionSubmissionType == 2 || isAgendaRequestInfo) {
                SaveRequestInfoByCustomerOrderItemId(orderItemId, customerEmail, isAgendaRequestInfo);
            }

            if (isAgendaExists.toLocaleLowerCase() == 'true' && typeof OpenProductAgendaPopup == "function") {
                OpenProductAgendaPopup(ProductId, orderItemId, null, null, groupProductPricecId, true, customerEmail, 0, false, chkPurchaserForRegistrant, isRegistrantRequestInfo)
                return false;
            }
            else if (registrantQuestionSubmissionType >= 0) {
                if (isValidateRegistrantQuestions) {
                    $('#btnContinue').trigger("click");
                }
                else if (typeof DisplayRegistrantPopUp == "function") {
                    DisplayRegistrantPopUp();
                }
                return false;
            }
        }
        if (isClosePopUp && isClosePopUp.toLowerCase() == 'true') { return false; }

        //#21279
        if (isUserInfoRequest.toLowerCase() === 'true') {
            location.reload();
            return false;
        }

        //search,widget pages
        if (cls_saveSingleProduct && cls_saveSingleProduct.length > 0) {
            if ($(cls_saveSingleProduct).hasClass("btnAddtocartDiscountProductFromSearch")) {
                $(cls_saveSingleProduct).trigger("click", [1, orderItemId]);
                //addToCartFromDiscount(cls_saveSingleProduct, orderItemId);
            } else {
                saveSingleProduct(false, cls_saveSingleProduct, orderItemId);
            }

        }
        else if (isRealtedProduct == "true") {
            saveAddToCartProductsForAcknowledge(orderItemId, groupProductPricecId, ProductId, chkPurchaserForRegistrant, isRegistrantRequestInfo);

        }
        else if (chkPurchaserForRegistrant.toLocaleLowerCase() === 'true' || registrantQuestionSubmissionType == 2) {
            let params = {
                registrantTypeOrderItemId: orderItemId,
                groupProductPricecId: groupProductPricecId,
                chkPurchaserForRegistrant: chkPurchaserForRegistrant,
                isRegistrantRequestInfo: isRegistrantRequestInfo
            };
            //product detail page
            saveAddToCartProducts(params);

        } else {
            let params = {
                registrantTypeOrderItemId: orderItemId,
                groupProductPricecId: groupProductPricecId,
                chkPurchaserForRegistrant: chkPurchaserForRegistrant,
                isRegistrantRequestInfo: isRegistrantRequestInfo
            };
            saveAddToCartProducts(params);
        }
    }
}

//12842: Registration Types - Registration Question Sets end.

//#12874: Sales - Discounts - Free shipping limitation - only within <selectedRegion>
function ApplyFreeShipping(freeshipping, data) {
    if (freeshipping) {
        $("#divShippingMethods").hide();
        $('.clsshippingOption').prop('checked', false);
    }
    else if (data && data.partialShipping) {
        $("#divShippingMethods").show();
        updateShippingOptionsByDiscount();
    }
    else {
        $("#divShippingMethods").show();
    }
}

function updateShippingOptionsByDiscount() {
    $("#divShippingMethods").load(GET_SHIPPING_METHOD_URL).prepend("<p class='loaderTxt'>Please wait ...</p>");
}

//#13296: Catalog > Products > Edit Product - 'No Certificate' option for programs
function LoadCertificateButton() {
    if ($(".btnCert[data-certid=-1]").length > 0) {
        var productIds = $(".btnCert[data-certid=-1]").map(function () { return $(this).attr('data-pid'); }).get().join(',');
        if (productIds) {
            $.ajax({
                type: "GET",
                url: "/Certificate/GetProductWithoutCertRequirement",
                data: { "productIds": productIds },
                dataType: "json",
                async: false,
                success: function (data) {
                    if (data.length > 0) {
                        $.each(data, function (i, data) {
                            parent.$(".btnCert_" + data).hide();
                            parent.$(".tdCert_" + data).html('<span>N/A</span>');
                        });
                    }
                },
            });
        }
    }
    initAfterMyAccountProduct();
}

function initAfterMyAccountProduct() {
    var launchChatProducts = "";
    if ($(".btnLaunchChat").length > 0) {
        launchChatProducts = $(".btnLaunchChat").map(function () { return $(this).attr('data-pid'); }).get().join(',');
    }
    if (launchChatProducts) {
        $.ajax({
            type: "GET",
            url: "/Account/InitMyAccountProducts",
            data: { "launchChatProductIds": launchChatProducts },
            dataType: "json",
            async: false,
            success: function (data) {
                if (data && data.directChatId) {
                    $.each(data.directChatId.split(","), function (i, data) {
                        $(".btnLaunchChat[data-pid=" + data + "]").removeClass("hidden");
                    });
                }
            },
        });
    }
}
//END

function openAddToCartPopupModal(url) {
    $.magnificPopup.open({
        items: {
            src: url
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'popAddtoCartMainClass',
        callbacks: {
            close: function () {
                $(".divProgress").hide();
                isValidateRegistrantQuestions = false;
                listProductsForBundle = [];
                arrRandomOrderItemId = [];
                relatedProductPopup = false;
            }
        }
    });
    return false;
}

function openAddToCartFeePlanPopupModal(url) {
    $.magnificPopup.open({
        items: {
            src: url
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'popAddToCartFeePlan'
    });
    return false;
}


//13398: Quick Launch is selecting the wrong date again : Start
//launch free catalog courses
$("body").on("change", ".videoReplyEventDate", function () {
    setFreeViewerUrl($(this).attr('data-productid'), $(this).val());
});

function setFreeViewerUrl(productId, eventTimeId) {

    var $this = $(".LaunchFreeViewerRoute[data-productid='" + productId + "']");
    var url = $this.attr("href")
    var btnTitle = $this.attr("data-btnTitle");
    var discountId = $this.attr("data-productpriceid");
    var marketingEntityId = $this.attr("data-marketingEntityId");
    var marketingEntityType = $this.attr("data-marketingEntityType"); 
    var x = $.trim(productId) + "|" + $.trim(eventTimeId);
    var launchPurchased = $(".clsLaunchPurchasedSeminar")

    //var memberShipDiscountId = 0;
    //var marketingEntityType = 'General';
    //if ($("#hdnMemberShipDiscountId").length > 0) {
    //    memberShipDiscountId = $("#hdnMemberShipDiscountId").val();
    //    marketingEntityType = 'MemberShipGroup';
    //}

    $this.attr("data-eventtimeid", eventTimeId);

    $.ajax({
        url: "/Viewer/GetEncryptedValue?x=" + $.trim(x),
        type: "GET",
        async: false,  // Makes the request synchronous
        success: function (data) {
            //    }
            //});
            //$.get("/Viewer/GetEncryptedValue?x=" + $.trim(x), function (data) {

            if (btnTitle && btnTitle.toLowerCase() == "launch") {
                var paramLaunchFreeViewer = {
                    x: data,
                    discountId: discountId,
                    marketingEntityId: marketingEntityId,
                    marketingEntityType: marketingEntityType
                };

                var launchFreeViewerUrl = LAUNCH_FREE_VIEWER_URL + "?" + $.param(paramLaunchFreeViewer);
                $this.attr("href", launchFreeViewerUrl);

                if (launchPurchased) {
                    $(launchPurchased).attr("href", launchFreeViewerUrl + "&isLaunchPurchased=true");
                }
                url = launchFreeViewerUrl;

            }
            else {
                var paramCompleteFreeOrder = {
                    x: data,
                    discountId: discountId
                };

                var returnUrl = COMPLETE_FREE_ORDER_URL + "?" + $.param(paramCompleteFreeOrder);
                var classRoomLogInUrl = CLASSROOM_LOGIN_URL + "?isFromFreeProduct=" + true + "&returnUrl=" + encodeURIComponent(returnUrl);
                $this.attr("data-returnUrl", returnUrl);
                $this.attr("data-href", classRoomLogInUrl);
                if (launchPurchased) {
                    $(launchPurchased).attr("href", classRoomLogInUrl + "&isLaunchPurchased=true");
                }
                url = returnUrl;
            }
        }
    });
    return url;
}
//13398: Quick Launch is selecting the wrong date again : End


//#13383: Catalog - Quick Launch - Update to Quick Launch Feature
$("body").on("click", ".ce21FreeCourse", function () {
    var $this = $(this);
    var URL = $(this).attr("href");
    var productId = $this.attr("data-ProductId"),
        eventTimeId = $this.attr("data-eventtimeid"),
        productTypeId = $this.attr("data-productTypeId"),
        discountId = $this.attr("data-productpriceid"),
        priceType = $this.attr("data-pricetype"),
        entityType = $this.attr("data-entityType"),
        programRegistrantId = $this.attr("data-ProgramRegistrantId"),
        pageType = $this.closest(".ProductDetailPortion").length > 0 ? "productdetail" : "SearchProduct";

    $(this).attr("disabled", "disabled");
    setTimeout(function () {
        $(".ce21FreeCourse").removeAttr("disabled");
    }, 3000);

    if (!URL) return;
    if (URL.toLowerCase() == "javascript:void(0);" || URL.toLowerCase() == "javascript:void(0)") { return; }

    //#24468
    if (productId == newProductId || Number(programRegistrantId) > 0) {
        URL += "&isProductPurchased=" + true;
    }
    if (Number(programRegistrantId) > 0) {
        launchPurchasedProduct($this, URL);
    }
    else if (productId) {
        $.get("/Items/CheckMaxRegistrantForFreeProducts?productId=" + productId + "&eventTimeId=" + eventTimeId, function (data) {
            if (data && data.Message) {
                displayCartMessages($this, data, pageType);
            }
            else {
                newProductId = productId;                
                if (discountId && Number(discountId) > 0) { //#6648104808
                    var isQuestionExist = IsRegistrantTypeQuestionSetAvailable(discountId, eventTimeId, productId, productTypeId);
                    if (isQuestionExist) {
                        OpenRegistrantTypeQuestionSetPopup(productId, discountId, priceType, 0, 0, 0, false, 0, false, null, null, 0, true, false, false, false, false, "ce21FreeCourse"); return false;
                    }
                }

                var isAgendaExists = (productTypeId != undefined && Number(productTypeId) == 1) ? IsAgendaForProductAvailable(discountId, productId, entityType) : false;
                if (isAgendaExists) {
                    openAgendaFormFromDiscount(productId, "ce21FreeCourse", 0, discountId, entityType, 0, false);
                    return false;
                }
                
                launchPurchasedProduct($this, URL);
            }
        });
    }

    return false;
});

function launchFreeProductAfterRegistrantTypeQuestionSet(registrantTypeOrderItemId, productId) {
    var $this = $(".ce21FreeCourse[data-ProductId='" + productId + "']");
    var productTypeId = $this.attr("data-productTypeId"),
        discountId = $this.attr("data-productpriceid"),
        entityType = $this.attr("data-entityType"),
        eventTimeid = $this.attr("data-eventtimeid");

    $this.attr("disabled", "disabled").attr("data-btnTitle", "launch");

    var url = setFreeViewerUrl(productId, eventTimeid);
    setTimeout(function () {
        $this.removeAttr("disabled");
    }, 5000);

    if ($this && url) {
        url += '&registrantTypeOrderItemId=' + registrantTypeOrderItemId;
        $this.attr('href', url);

        var isAgendaExists = (productTypeId != undefined && Number(productTypeId) == 1) ? IsAgendaForProductAvailable(discountId, productId, entityType) : false;
        if (isAgendaExists) {
            openAgendaFormFromDiscount(productId, "ce21FreeCourse", 0, discountId, entityType, registrantTypeOrderItemId, false);
            return false;
        }

        launchPurchasedProduct($this, url);
    }
}
function launchFreeProductAfterAgenda(productId, agendaPrice, registrantTypeOrderItemId) {
    var $this = $(".ce21FreeCourse[data-ProductId='" + productId + "']");
    var eventTimeid = $this.attr("data-eventtimeid");

    $this.attr("disabled", "disabled").attr("data-btnTitle", "launch");

    var url = setFreeViewerUrl(productId, eventTimeid);

    setTimeout(function () {
        $this.removeAttr("disabled");
    }, 5000);
    if ($this && url && Number(agendaPrice) <= 0) {
        url += '&registrantTypeOrderItemId=' + registrantTypeOrderItemId;
        launchPurchasedProduct($this, url);
    }
    else {
        AddSingleProductToCart($this, registrantTypeOrderItemId);        
    }
}

function hideShowAddToCartButton() {

    //5167: Pricing checkbox - If customer unselect the main price, gray out the add on product checkboxes.
    if ($('.productBody input[name="price"][data-pricetype!="AdditionalPrice"]:checked').length > 0) {
        $(".clsRelatedAddOnProducts").removeClass('addongrayout').find('input[type="checkbox"]').prop('disabled', false);
    }
    else {
        $(".clsRelatedAddOnProducts").addClass('addongrayout').find('input[type="checkbox"]').prop('disabled', true).prop('checked', false);
    }

    var elem = $(".productBody input[name='price']:checked");
    var checkedPrice = elem.val();
    var price = checkedPrice ? parseFloat(checkedPrice.split(',')[1]) : 0;

    var productpriceid = elem.attr('data-productpriceid');
    var pricetype = elem.attr('data-pricetype');
    var entitytype = elem.attr('data-entitytype');

    var launchBtn = $('.productBody .LaunchFreeViewerRoute');

    if (launchBtn.length > 0) {
        if (price > 0) { 
            launchBtn.hide();
            if ($(".clsAdditionalprice").is(":checked")) {
                $(".clsAdditionalPriceCart").show();
                $(".clsStandardPriceCart").hide();
            }
            else {
                $(".clsAdditionalPriceCart").hide(); 
                $(".clsStandardPriceCart").show();
            }
        }
        else {
            if ($(".clsAdditionalprice").is(":checked")) { 
                launchBtn.hide();
                if ($(".ShowAcknowledgePopup").length > 0) { 
                    $(".ShowAcknowledgePopup").attr("data-val", $(".ShowAcknowledgePopup").attr("data-additionalpricediv"));
                    $(".ShowAcknowledgePopup").show();
                }
                else {
                    $(".clsAdditionalPriceCart").show();
                    $(".clsStandardPriceCart").hide();
                }
            }
            else {
                launchBtn.attr('data-productpriceid', productpriceid).attr('data-pricetype', pricetype).attr('data-entitytype', entitytype);
                setFreeViewerUrl(launchBtn.attr('data-productid'), launchBtn.attr('data-eventTimeId'));
                launchBtn.show();
                $('.clsStandardPriceCart, .clsAdditionalPriceCart').hide();
            }
        }
    }
    else if ($(".ShowAcknowledgePopup").length > 0) {
        if ($(".clsAdditionalprice").is(":checked")) { 
            $(".ShowAcknowledgePopup").attr("data-val", $(".ShowAcknowledgePopup").attr("data-additionalpricediv"));
            if ($(".ShowPrerequisiteProducts").length > 0) { 
                $(".ShowAcknowledgePopup").show(); 
                $(".ShowPrerequisiteProducts").hide();
            }            
        }
        else if (price > 0) {
            $(".ShowAcknowledgePopup").attr("data-val", $(".ShowAcknowledgePopup").attr("data-nexttargetdiv"));
            if ($(".ShowPrerequisiteProducts").length > 0) { 
                $(".ShowAcknowledgePopup").show();
                $(".ShowPrerequisiteProducts").hide();
            }
        }
        else {
            $(".ShowAcknowledgePopup").attr("data-val", $(".ShowAcknowledgePopup").attr("data-nexttargetdiv"));
            if ($(".ShowPrerequisiteProducts").length > 0) { 
                $(".ShowPrerequisiteProducts").show();
                $(".ShowAcknowledgePopup").hide();
            }
        }
    }
    else {
        if ($(".clsAdditionalprice").is(":checked")) {
            $(".clsAdditionalPriceCart").show();
            $(".clsStandardPriceCart").hide();
        }
        else {
            $(".clsAdditionalPriceCart").hide();
            $(".clsStandardPriceCart").show();
        }
    }
}
$("body").on("click", ".btnLunchModelYmLogin", function () {
    top.window.location = $(this).attr("data-href");
    return;
});

$("body").on("change", ".billingCycleType", function () {
    $("#groupPaymentCycleId").val($(this).attr("data-GroupCycleId"));
    $("#renewAmount").html($(this).attr("data-price"));
    $("#renewDays").html($(this).attr("data-days"));
    $("#renewalDate").html($(this).attr("data-renewalDate"));
});

$("body").on("change", ".customerRecurringType", function () {
    $("#autoRecurringType").val($(this).val());
});

$("body").on("click", ".freeMembershipRegistration", function () {
    var membershipTypeId = $(this).attr("data-val");
    processQuickPurchaseMembership(membershipTypeId)
    return false;
});

function processQuickPurchaseMembership(membershipTypeId, orderItemId) {
    quickPurchaseMembership(membershipTypeId, orderItemId, function () {
        $("#divProgress").show();
        window.location.href = "/account/myaccount#tabMemberShip";
    });
}

function quickPurchaseMembership(membershipTypeId, orderItemId, callback) {

    if (membershipTypeId > 0) {
        $("#divProgress").show();
        $.ajax({
            type: "POST",
            url: "/Search/FreeMembershipRegistration",
            dataType: "json",
            data: {
                "membershipTypeId": membershipTypeId,
                "orderItemId": orderItemId
            },
            success: function (data) {

                $("#divProgress").hide();
                if (!data.Message && !data.PopUp) {
                    $("#divProgress").show();
                    if (window.location.pathname.toLowerCase() == '/account/myaccount' && data.RedirectURL.toLowerCase().includes('/account/myaccount')) {
                        LoadMemberhipTab(); //if redirect URL is my account page and already in my account page load only membership tab 
                    }
                    else {
                        window.location = data.RedirectURL;
                    }
                }
                else if (!data.Message && data.PopUp) {

                    $.magnificPopup.open({
                        items: {
                            src: data.RedirectURL
                        },
                        type: 'iframe',
                        callbacks: {
                            afterClose: callback
                        },
                        closeOnBgClick: false,
                    });

                }
                else {
                    alert(data.Message);
                }

            },
            error: function (data) {
                $("#divProgress").hide();
                alert("Error! please try later.");
            }
        });
    }
}

//Show Progressing
$('#memberShipQuestionAnswerForm').submit(function () {
    //chek date is valid or not start
    var isValid = true;
    $('.clsDatePicker').each(function () {
        var dateValue = $(this).val();
        var questionId = $(this).attr('data-questionid');
        var clsName = ".clsValDate" + questionId;

        if (dateValue != undefined && dateValue != null && dateValue != "") {
            if (ValidateDate(dateValue)) {
                $(clsName).hide();
            }
            else {
                isValid = false;
                $(clsName).show();
                var divText = "#txtDate" + questionId;
                $(divText).focus();
                return false;
            }
        }
        validateDatePicker(dateValue, clsName);

    });

    //check document required validation
    $('.clsMembershipAnswerDocuments').each(function () {
        var $this = $(this);
        var id = $this.attr("data-questionId");
        if ($this.find("table").hasClass("noResults")) {
            $("#spnError_" + id).text('Please upload document.')
            $("#spnError_" + id).addClass("field-validation-error");
            isValid = false;
        }
    });

    isValid = checkMultiChoiceValidation(isValid);

    if (isValid == false) {
        return false;
    }
    //chek date is valid or not end
    $(':disabled').prop('disabled', false);
    if ($("#memberShipQuestionAnswerForm").valid()) {

        if (isValid) {
            $('button[type="submit"],input[type="submit"]').html('<i class="fa fa-refresh fa-spin"></i>&nbsp;&nbsp;Processing...').prop('disabled', true);

            if ($(this).attr('pagetype') === "Default") {
                $('#divProgress').show();
                saveMembershipQuestion();
                return false;
            }
        }
    }
});

$('#frmEditCustomer').submit(function () {

    var isValid = true;
    //check document required validation
    $('.clsMembershipAnswerDocuments').each(function () {
        var $this = $(this);
        var id = $this.attr("data-questionId");
        if ($this.find("table").hasClass("noResults")) {
            $("#spnError_" + id).text('Please upload document.')
            $("#spnError_" + id).addClass("field-validation-error");
            isValid = false;
        }
    });

    //Monday: 6480813440
    var ActiveCBM = false;
    var CBMOwner = false;
    if ($("#hasActiveCBM").val() == "True") {
        ActiveCBM = true;
    }
    if ($('#IsCBMOwner').val() == "True") {
        CBMOwner = true;
    }
    var IsCompanyChanged = $("#hdnIsCompanyChanged").val();
    if (ActiveCBM && $('#CompanyName').length > 0 && IsCompanyChanged == 'False') {
        var OldCompanyName = $("#hdnCompanyName").val();
        var CompanyName = $("#CompanyName").val();

        const details = {
            hasActiveCBM: ActiveCBM,
            IsCBMOwner: CBMOwner,
            EncryptedCompanyId: $("#EncryptedCompanyId").val(),
            CustomerId: $("#CustomerId").val(),
            CustomerMembershipId: parseInt($("#CustomerMembershipId").val()),
            OldCompanyName: OldCompanyName,
            CompanyName: CompanyName,
            pageName: 'EditCustomer',
            formid: '',
            buttonid: ''
        };

        if (OldCompanyName != undefined && OldCompanyName != '' && OldCompanyName != CompanyName) {
            isValid = false;
            $("#hdnIsCompanyChanged").val('True');
            ChangeCompanyConfirmation(details);
        }
    }

    return isValid;
});

$('#SignUp-form').submit(function () {

    var isValid = true;
    //check document required validation
    $('.clsMembershipAnswerDocuments').each(function () {
        var $this = $(this);
        var id = $this.attr("data-questionId");
        if ($this.find("table").hasClass("noResults")) {
            $("#spnError_" + id).text('Please upload document.')
            $("#spnError_" + id).addClass("field-validation-error");
            isValid = false;
        }
    });

    return isValid;
});

function saveMembershipQuestion() {
    var formData = $('#memberShipQuestionAnswerForm').serialize();
    $.post('/Search/SaveMemberTypeQuestions', formData, function (data) {
        if (data.membershipTypeId && data.orderItemId) {
            processQuickPurchaseMembership(data.membershipTypeId, data.orderItemId);
        } else {
            if (data && data.PriceId) {
                parent.addToCartProductAfterMembership(data.PriceId);
            }
            window.location.href = data.RedirectUrl || '/ShoppingCart';
        }
    });
}

function openMembershipCertificate(customerMembershipId, displayMembershipCertButtonLabel) {
    $.get("/Group/CustomerMembershipCertificate?customerMembershipId=" + customerMembershipId + "&displayMembershipCertButtonLabel=" + displayMembershipCertButtonLabel, function (data) {
        if (data && data.trim()) {
            $.confirm({
                title: displayMembershipCertButtonLabel,
                boxWidth: '550px',
                useBootstrap: false,
                content: data,
                buttons: {
                    cancel: {
                        text: 'Close',
                        btnClass: 'btnCloseMemberCertificate',
                        action: function () {
                        }
                    }
                }
            });
        }
    });
}

$('body').on('click', '.btnEmailGroupCert', function () {
    $(".btnCloseMemberCertificate").trigger('click');
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'popPagerDuty'
    });
    return false;
});

$('body').on('click', '.popEditAddress', function () {
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'popEditAddressMainClass'
    });
    return false;
});

$('.autoCompleteCompanyName').autocomplete({
    source: function (data, callback) {
        $.ajax({
            global: false,  // <-- this is the key!
            url: '/Search/Autocomplete',
            dataType: 'json',
            data: data,
            success: callback
        });
    }
});

//#14552
function addressMethod(editAddressPopupType, isHideDirectory) {
    $.magnificPopup.close();
    if ($(".grid-list-address").length > 0) {

        isHideDirectory = (isHideDirectory && isHideDirectory.toLowerCase() === "false") ? false : true;
        var customerCustomFieldIds = $("#CustomerCustomFieldIds").val() || "";

        $(".grid-list-address").each(function () {

            var isQuestionset = ($(this).attr("data-isquestionset") || "").toLowerCase() == "true";
            var isRequired = ($(this).attr("data-isrequired") || "").toLowerCase() == "true";
            var questionId = $(this).attr("data-questionid") || "";

            $(this).load(GET_CUSTOMER_GET_CUSTOMER_ADDRESS_LIST + '?editAddressPopupType=' + editAddressPopupType + '&isHideDirectory=' + isHideDirectory + '&IsQuestionset=' + isQuestionset + '&IsRequired=' + isRequired + '&QuestionId=' + questionId + "&customerCustomFieldIds=" + customerCustomFieldIds, function () {
                $('.verifiedLabel[data-toggle="tooltip"]').tooltip();

                var selectedValue = $('#IsAddressBlockQuestion' + questionId).attr("data-selectedvalue");
                $("input[name=addressRadio" + questionId + "][value='" + selectedValue + "']").prop("checked", true);

                $(".divAddressListLayout:visible").each(function () {
                    $(this).height($(this).outerHeight());
                    $(".addresslist-card", this).height($(".addresslist-card", this).outerHeight());
                });
                loadAlertToolTip();
            }).prepend("<p class='loaderTxt'>Please wait ...</p>");
        });


    }
    if ($("#divExistingAddress").length > 0) {
        $("#divExistingAddress").load(GET_CUSTOMER_CUSTOMER_GET_EXISTING_ADDRESSES + '?editAddressPopupType=' + editAddressPopupType).prepend("<p class='loaderTxt'>Please wait ...</p>");
        if (editAddressPopupType === "EditShippingInfo") {
            getShippingMethodByAddress();
        }
        else {
            UpdateOrderSummary();

            if (typeof (calculatePriceAndTax) === "function") {
                calculatePriceAndTax()
            }
        }


    }
}

// Set as Default address
$("body").on("click", ".setDefaultAddress", function () {
    var addressId = $(this).attr('data-value');
    var editAddressPopupType = $(this).attr('data-editAddressPopupType');
    var referralClientId = $(this).attr('data-referralClientId');

    if (confirm('Are you sure you want to set this address as default?')) {
        $.post(referralClientId > 0 ? "/ReferralService/MakePrimaryAddress" : "/Account/MakePrimaryAddress", { addressId: addressId }, function (data) {
            if (referralClientId > 0) {
                referralAddressMethod(editAddressPopupType, referralClientId)
            } else {
                addressMethod(editAddressPopupType);
            }
        }).fail(function (data) {
            alert('Error! Please try again later.');
        });
    }
});

// Set as Directory address
$("body").on("click", ".setDirectoryAddress", function () {
    var addressId = $(this).attr('data-value');
    var editAddressPopupType = $(this).attr('data-editAddressPopupType');
    var isDirectoryAddress = ($(this).attr('data-isDirectoryAddress') == "True") ? true : false;
    var addressUsageType = isDirectoryAddress ? 0 : 1;
    var alertMessage = isDirectoryAddress ? "Are you sure you want to remove this address from the directory address?" : "Are you sure you want to set this address as directory address?";
    //#21752
    //if (confirm(alertMessage)) {
    $.post("/Account/MakeDirectoryAddress", { addressId: addressId, addressUsageType: addressUsageType }, function (data) {
        addressMethod(editAddressPopupType);
    }).fail(function (data) {
        alert('Error! Please try again later.');
    });
    //} else {
    //    return false;
    //}
});

//js for check element is visible or not on screen
function isElementVisibleOnScreen(elem) {
    var $elem = $(elem);
    var $window = $(window);

    var docViewTop = $window.scrollTop();
    var docViewBottom = docViewTop + $window.height();
    if ($elem.length > 0) {
        var elemTop = $elem.offset().top;
        var elemBottom = elemTop + $elem.height();
        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }

    return false;
}

// #14921: Delete Address
$("body").on("click", ".deleteAddress", function () {
    var id = $(this).attr('data-encrypted');
    var editAddressPopupType = $(this).attr('data-editAddressPopupType');
    var isHideDirectory = $(this).attr('data-isHideDirectory');
    var questionId = $(this).attr('data-questionId') || 0;
    var referralClientId = $(this).attr('data-referralClientId');
    var tempCustomerId = $(this).attr('data-tempCustomerId');
    var isFromUserRegistration = $(this).attr('data-isFromUserRegistration');
    if (confirm('Are you sure you want to delete this address?')) {
        $.post(referralClientId > 0 ? "/ReferralService/DeleteAddress" : "/Account/DeleteAddress", { a: id }, function (data) {
            if (questionId > 0) {
                if (isFromUserRegistration == 'True') {
                    loadCustomerCustomAddressBlock(tempCustomerId, false);
                }
                else {
                    loadCustomerAddressListForQuestionSet();
                }
            } else if (referralClientId > 0) {
                referralAddressMethod(editAddressPopupType, referralClientId)
            } else {
                addressMethod(editAddressPopupType, isHideDirectory);
            }
        }).fail(function (data) {
            alert('Error! Please try again later.');
        });
    }
});


function toggleGroupType(groupType) {

    var eleAccordian = $(".groupAccordian[data-gId=" + groupType + "]");
    if ($(eleAccordian).find(".panel-collapse").is(':visible')) {
        $(eleAccordian).find(".groupExpander").addClass("fa-plus").removeClass("fa-minus");
        $(eleAccordian).find(".pastMembershipGroupAccordian[data-gId=" + groupType + "]").find(".pastMembershipGroupExpander").addClass("fa-plus").removeClass("fa-minus");
    }
    else {
        $(eleAccordian).find(".groupExpander").addClass("fa-minus").removeClass("fa-plus");
    }
}

function pastToggleGroup(groupType) {
    var eleAccordian = $(".pastMembershipGroupAccordian[data-gId=" + groupType + "]");
    if ($(eleAccordian).find(".pastMembershipPanel-collapse").is(':visible')) {
        $(eleAccordian).find(".pastMembershipGroupExpander").addClass("fa-plus").removeClass("fa-minus");
    }
    else {
        $(eleAccordian).find(".pastMembershipGroupExpander").addClass("fa-minus").removeClass("fa-plus");
    }

}

//#15273
$('body').on('click', '#printProductDecription', function () {
    var printContents = $('.printDescription').html();
    var originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
});

//# 15037 - Custom Fields Multi-Select DropDown - START
$("body").on('change', '.chkSelecAllCustomFields', function () {
    checkUncheckAllCustomCheckBox(this);
});

$("body").on('click', '.btnClearCustomFields', function () {
    var txtSearch = $(this).closest('th').find('input[type="text"]');
    $(txtSearch).val('');
    searchCustomFieldCheckBox(txtSearch);
});

function checkUncheckAllCustomCheckBox(ele) {

    if ($(ele).prop('checked') === true) {
        $(ele).closest("table").find('input[type="checkbox"]:visible').prop('checked', true);
    }
    else {
        $(ele).closest("table").find('input[type="checkbox"]').prop('checked', false);
    }

    var findTrigger = $(ele).closest("table").find('input[data-triggerType="1"],[data-tirggerquestiontype="1"]').first();
    if (findTrigger) {
        callTriggerQuestion(findTrigger);
    }

}

function searchCustomFieldCheckBox(txtSearch) {
    if (txtSearch) {
        $(txtSearch).closest("table").find("tbody>tr").filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf($(txtSearch).val().toLowerCase()) > -1)
        });
    }
}

function checkMultiChoiceValidation(isValid) {

    //Required validation if all rows rows are hidden
    $(".tblCustomFieldMultiSelect:visible").each(function () {
        var table = $(this);
        if ($(table).find("tbody>tr:visible").length == 0) {
            if ($(table).find("tbody>tr:hidden").find('input[type="checkbox"]:required').length > 0 && $(table).find("tbody>tr:hidden").find('input[type="checkbox"]:checked').length == 0) {
                $(table).find("tbody>tr").show();
                isValid = false;
            }
        }
    });

    return isValid;
}
//# 15037 - Custom Fields Multi-Select DropDown - END

$("body").on("click", ".btnCancelPurchaseCE", function () {
    var productId = $(this).attr('data-productId');
    var displaypagetype = $(this).attr('data-displaypagetype');
    if (displaypagetype && displaypagetype === '3') {
        $.ajax({
            type: "POST",
            url: "/Bundle/DeleteCustomerBundleProduct",
            dataType: "json",
            data: {
                'customerBundleId': $(this).attr('data-customerbundleid'),
            },
            success: function (data) {
                LoadCustomerBundleProductList();
            },
            complete: function (data) {
                $('#divProgress').hide();
            },
            error: function (data) {
                $('#divProgress').hide();
                alert('Error! Please try again later.');
            }
        });
    }
    else {
        if (productId) {
            $.get(CENCEL_PURCHASECE, { productId: productId }, function (data) {
                if (data != undefined) {
                    parent.$("#cartspancount").html(data);
                    parent.$("#cartItemList").load(GET_CART_URL);
                }
            });
        }
    }
});

function dataCustomFilter() {
    var elCustomFilter = $('.dataCustomFilter'),
        elFilterInput = $('input#customFilterinput'),
        divEntities = $('.dataEntities'),
        entities = $('.dataEntity');

    if (!elCustomFilter || elCustomFilter.length == 0
        || !elFilterInput || elFilterInput.length == 0
        || !divEntities || divEntities.length == 0
        || !entities || entities.length == 0) return;

    elFilterInput.on("change", function () {
        var input = ($(this).val() || '').trim();
        if (input) {

            divEntities.attr('data-filter', 'true');
            divEntities.find('.active').removeClass('active');

            entities.filter(function () {
                return $(this).attr('data-title').toLowerCase().indexOf((input || "").toLowerCase()) > -1 || $(this).is(':contains(' + (input || "") + ')');
            }).addClass('active');

        } else {
            divEntities.attr('data-filter', 'false');
        }
        return false;
    })
        .on("keyup", function () {
            // fire the above change event after every letter
            $(this).change();
        });
}

// custom css expression for a case-insensitive contains()
jQuery.expr[":"].contains = function (a, i, m) {
    return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};

function loadAlertToolTip() {
    if ($('.moreinfo') != undefined) {
        $('.moreinfo').popover({ trigger: 'hover' })
            .on("show.bs.popover", function () {
                return $(this).data("bs.popover").tip().css({
                    maxWidth: "500px"
                })
            });
    }
}

function redirectToShoppingCart() {
    window.location.href = '/ShoppingCart';
}
$('.chkSelect-FuturePayment, .chkSelect-FuturePayment-All').on('change', function () {
    if ($('.chkSelect-FuturePayment:checked').length > 0) {
        $('.btnPayMultiple').removeClass('disabled');
    } else {
        $('.btnPayMultiple').addClass('disabled');
    }
});
$("body").on('click', '.processMembershipPaymentWithSaveCard', function () {

    if (!confirm("Are you sure you want to Process Payment?")) { return; }

    var customerMembershipId = $(this).attr("data-customerMembershipId");
    var membershipsPaymentIds = $(this).attr("data-paymentId");

    $('#divProgress').show();
    $.ajax({
        type: "GET",
        url: "/Group/ProcessMembershipPayment",
        data: {
            "customerMembershipId": customerMembershipId,
            "membershipsPaymentIds": membershipsPaymentIds
        },
        success: function (data) {            
            if (data && data.Success) {
                window.location.reload();
            }
            else {
                if (data && data.Message) {
                    alert(data.Message);
                    window.location.reload();
                }
                else {
                    alert('Error! Please try again later.');
                }
            }
            $('#divProgress').hide();
        },
        error: function () {
            alert('Error! Please try again later.');
        }
    });
});
isValidPayNowForSeleted = function () {
    if ($("input[type='checkbox'][class='chkSelect-FuturePayment']:checked").length === 0) {
        alert('Please select a record for payment.');
        return false;
    }

    var firstSelectedIndex = parseInt($("input[type='checkbox'][class='chkSelect-FuturePayment']:checked:first").attr("data-index"));
    var lastSeletectedIndex = parseInt($("input[type='checkbox'][class='chkSelect-FuturePayment']:checked:last").attr("data-index"));
    var firstNotSeletedIndex = parseInt($("input[type='checkbox'][class='chkSelect-FuturePayment']:not(:checked):first").attr("data-index"));
    if (firstSelectedIndex && lastSeletectedIndex && firstNotSeletedIndex && (firstSelectedIndex > firstNotSeletedIndex || firstNotSeletedIndex < lastSeletectedIndex)) {
        alert('You cannot skip a middle payment.');
        return false;
    }

    return true;
}

$("body").on('click', '.btnPayNow,.btnPayMultiple', function () {
    var customerMembershipId = $(this).attr("data-customerMembershipId");
    var paymentIds = $(this).attr("data-paymentId");
    var pageName = $(this).attr("data-pageName");

    //Pay selected invoices
    if ($(this).hasClass("btnPayMultiple")) {
        //if the pay now for selected items is valid
        if (!isValidPayNowForSeleted()) {
            return false;
        }
        paymentIds = $("input[type='checkbox'][class='chkSelect-FuturePayment']:checked").map(function () { return $(this).val() }).get().join(',');
    }

    if ($("#hdnAutoPayerEnable").length > 0 && $("#hdnAutoPayerEnable").val() === "false") {
        var content = "You have not yet authorized a payment method to be used for recurring payments. Would you like to set up an automatic payment method for future dues invoices?";
        content += "<br/><br/> If you select Yes, the payment method will be stored and can be updated in the Invoices & Payments section of your membership tab. If you select No, only this current transaction will be processed."
        $.confirm({
            title: "Enable Automatic Recurring Payments?",
            boxWidth: '750px',
            useBootstrap: false,
            type: 'green',
            content: content,
            buttons: {
                ok: {
                    text: 'Yes',
                    btnClass: 'btn-success',
                    action: function () {
                        var rdata = { IsAuthorize: true };
                        AddToCartPayments(customerMembershipId, paymentIds, pageName, rdata);
                    }
                },
                cancel: {
                    text: 'No',
                    btnClass: 'btn-warning',
                    action: function () {
                        AddToCartPayments(customerMembershipId, paymentIds, pageName);
                    }
                }
            }
        });
    }
    else {
        AddToCartPayments(customerMembershipId, paymentIds, pageName);
    }
});


function AddToCartPayments(customerMembershipId, paymentIds, pageName, rdata) {
    var IsAuthorize = rdata && rdata.IsAuthorize || 0;

    $('#divProgress').show();
    $.post("/Group/AddMembershipPaymentsInCart", { customerMembershipId: customerMembershipId, membershipPaymentsIds: paymentIds, IsAuthorize: IsAuthorize }, function (data) {
        if (data && data.Success) {
            if (pageName && pageName.toLowerCase() == "companybasedmembershipdetail") {
                parent.goToShoppingCart();
            }
            window.location.href = '/ShoppingCart';
        } else {
            $('#divProgress').hide();
            if (data && data.Message) {
                alert(data.Message);
            }
            else {
                alert('Currently, invoice(s) is not added into cart. Please try again.');
            }
        }
    });
}

function showPendingPaymentPopup() {
    $(".PendingPaymentPopOver").popover({
        trigger: "manual",
        content: function () {
            var element = $(this);
            var content = element.attr('data-originalcontent');
            var customerMembershipId = element.attr('data-customermembershipId');
            return content + $("#dvPendingPayments" + customerMembershipId).html()
        },
        placement: 'top',
        container: 'body',
        html: true,
        animation: false
    }).on("mouseenter", function () {
        var _this = this;
        $(_this).popover("show");

        $(".popover").on("mouseleave", function () {
            $(_this).popover('hide');
        });

    }).on("mouseleave", function () {
        var _this = this;
        setTimeout(function () {
            if (!$(".popover:hover").length) {
                $(_this).popover("hide");
            }
        }, 100);
    }).on("show.bs.popover", function () {
        return $(this).data("bs.popover").tip().css({
            minWidth: "925px"
        })
    });
}




function reloadParentWindow(url) {
    parent.location.href = url;
}


function clearGroupSessionAfterPurchaseProduct() {
    if (typeof (clearSessionStorageKeyForGroup) === "function") {
        clearSessionStorageKeyForGroup();
    }
}


//mantis item : 16481: Mobile check out - remove popup and put discount code into main page.
$("body").on("click", ".clsContinueCartForMobile, #btnCheckoutContinue", function () {
    //shopping cart stages
    var listForms = ["#frmEditCustomer", "#frmShippingInfo", "#frmRegistrant", "#frmMarketingCode", "#frmPaymentInfo"];

    var $this_From = $($.grep(listForms, function (itemForm) {
        return $(itemForm).length > 0;
    })[0]);
    var isPaymentForm = $this_From.attr('id') === 'frmPaymentInfo';
    var message = isPaymentForm
        ? '<span><i class="fa fa-refresh fa-spin"></i>&nbsp;&nbsp;Processing Payment...</span>'
        : '<span><i class="fa fa-refresh fa-spin"></i>&nbsp;&nbsp;Please wait...</span>';
    var buttonText = isPaymentForm ? 'Place Order' : '<span class="m-5"> Continue&nbsp;</span><i class="fa fa-solid fa-caret-right "></i>';
    
    if (!$this_From) { return false; }

    //disabled button for invalid form
    if ($this_From.valid()) {
        $(".clsContinueCartForMobile, #btnCheckoutContinue").html(message);
        $(".clsContinueCartForMobile, #btnCheckoutContinue").attr('disabled', 'disabled');
    }

    //submit form
    $this_From.submit();

    //remove disabled attributes
    setTimeout(function () {
        if (!window.Stripe) { // do not enable if stripe payment gateway
            $(".clsContinueCartForMobile, #btnCheckoutContinue").html(buttonText);
            $(".clsContinueCartForMobile, #btnCheckoutContinue").removeAttr('disabled');
        }
    }, 4000);

});

function toggleSidebarToHamburger() {
    var divSidebar = $('div#sidebar.sidebar-offcanvas[role="navigation"]');

    if (window && window.innerWidth > 768) {
        $('body').removeClass('custom-mobileview');
        $(".custom-navbar.navbar").addClass("hidden-xs");
        var divContent = $("body").find('#groupTopCartBar').length > 0 ? $('div.container div.container-fluid .ce21_tab_cotent #mainSection') : $('div.container2 > div.body-content > div.row.row-offcanvas.row-offcanvas-right > div.col-xs-12.col-sm-9');

        if (!divContent || !divSidebar || divContent.length == 0 || divSidebar.length == 0) return;

        switch (divSidebar.attr('data-layouttype')) {
            case "LeftSidebar":
                divSidebar.insertBefore(divContent);
                break;
            case "RightSidebar":
                divSidebar.insertAfter(divContent);
                break;
            default:
                break;
        }
    } else {
        $('body').addClass('custom-mobileview');

        var navbarToggle = $("body").find('#groupTopCartBar').length > 0 ? $('#groupTopCartBar a.dropdown-toggle') : $('#cartbar button.navbar-toggle');

        if (navbarToggle.length == 0) {
            $(".custom-navbar.navbar").removeClass("hidden-xs");
        }
        if (!navbarToggle || !divSidebar || navbarToggle.length == 0 || divSidebar.length == 0) return;

        var sidebarFiltersMenu = $("body").find('.filtersSidebarmenuInToggle').length > 0 ? $("#filtersSidebarmenuInToggle div.TopmenuInToggle") : $('#navbar div.TopmenuInToggle');
        divSidebar.insertAfter(sidebarFiltersMenu);
    }

    if (divSidebar && divSidebar.hasClass("hidden-xs")) divSidebar.removeClass("hidden-xs");
}

//mantis item : 15859#c14803
$("body").on('click', '.PayOutStandingInvoices', function () {

    var customerMembershipId = $(this).attr("data-customerMembershipId");
    var productPriceId = $(this).attr("data-productpriceid"); //As per mantis item 15859#c14280

    if (!productPriceId || !customerMembershipId || Number(productPriceId) <= 0 || Number(customerMembershipId) <= 0) { return false; }

    $('#divProgress').show();
    $.post(ADD_OUT_STANDING_INVOICE_IN_CART, { customerMembershipId: customerMembershipId }, function (data) {
        if (data && data.Success) {
            let params = {
                registrantTypeOrderItemId: undefined,
                groupProductPricecId: productPriceId
            };
            saveAddToCartProducts(params);
        }
        else {
            $('#divProgress').hide();
            var errorMessage = data && data.Message ? data.Message : 'Currently, invoice(s) is not added into cart. Please try again.';
            alert(errorMessage);
        }
    });

});

function getCartItems() {
    $("#cartItemList").load(GET_CART_URL);
}

//#14452 - Viewer Launch Button Click Event - Start
$("body").on("click", ".ShowPrerequisiteProducts", function () {
    var productId = parseInt($(this).attr("data-productid")) || 0;
    var productName = $(this).attr("data-productname");
    if (productId > 0) {
        showPrerequisiteProducts(productId, productName);
    }
});

function showPrerequisiteProducts(productId, productName) {
    $.ajax({
        type: 'get',
        url: GET_PREREQUSITE_PRODUCTS + '?productId=' + productId + '&productName=' + productName,
        success: function (html) {
            if ($("#divPrerequisiteProducts").length === 0) {
                $("body").append("<div class='modal fade' id='divPrerequisiteProducts' tabindex='- 1' role='dialog' aria-hidden='true' style='display: none;'></div>");
            }

            $("#divPrerequisiteProducts").html(html);
            $("#divPrerequisiteProducts").modal();
        },
        error: function () {
            alert('Error! Please try again later.');
        }
    });
}
//#14452 - Viewer Launch Button Click Event - End

$("body").on("click", ".ShowAcknowledgePopup", function () {
    var IsChangePopupLoaction = ($(this).attr("data-IscenterPopUp") != undefined && $(this).attr("data-IscenterPopUp") != null) ? $(this).attr("data-IscenterPopUp") : 'false';
    var productId = parseInt($(this).attr("data-productid")) || 0;
    var params = {
        "productId": productId,
        "nextTargetDiv": $(this).attr("data-val") || "",
        "agendaHeight": parseInt($(this).attr("data-height")) || 0,
        "agendaWidth": parseInt($(this).attr("data-width")) || 0
    };
    if (productId > 0) {
        $.ajax({
            type: 'get',
            url: GET_ACKNOWLEDGE_PREREQUISITE_PRODUCTS + "?" + $.param(params),
            success: function (html) {
                if ($("#dvAcknowledgePopup").length === 0) {
                    $("body").append("<div class='modal fade' id='dvAcknowledgePopup' data-bs-backdrop='static' data-bs-keyboard='false' tabindex='-1' role='dialog' aria-hidden='true' style='display: none;'></div>");

                }

                $("#dvAcknowledgePopup").html(html);
                $('#dvAcknowledgePopup').modal({
                    backdrop: 'static',
                    keyboard: false
                });
                if (IsChangePopupLoaction == 'true') {
                    $('#AcknowledgeForm').css('margin-left', '25%');
                }
            },
            error: function () {
                alert('Error! Please try again later.');
            }
        });
        return false;
    }
});

$("body").on("click", "#dvAcknowledgePopup a", function () {
    var val = $(this).attr("data-val") || "";;
    $("#dvAcknowledgePopup").modal('hide');
    if (val) {
        $(val).modal();
    }
});


$('body').on('click', '.btnSocilMediaShare', function () {
    var provider = $(this).attr('displayText');
    var productUrl = $(this).attr('st_url') || location.href;
    var providerUrl = '';
    var productTitle = $(this).attr('st_title') || $('title').text();
    switch (provider) {
        case 'Facebook':
            providerUrl = 'https://www.facebook.com/sharer/sharer.php?u={productUrl}'; //'https://www.facebook.com/dialog/share?href={productUrl}';
            break;
        case 'LinkedIn':
            providerUrl = 'https://www.linkedin.com/shareArticle?mini=true&url={productUrl}&title={productTitle}';
            break;
        case 'Tweet':
            providerUrl = 'http://twitter.com/share?url={productUrl}&text={productTitle}';
            break;
        case 'Email':
            openSharToEmailModel(productTitle, productUrl);
            return;
            break;

        default:
    }

    if (providerUrl) {
        providerUrl = providerUrl.replace('{productUrl}', encodeURIComponent(productUrl)).replace('{productTitle}', encodeURIComponent(productTitle));
        window.open(providerUrl, 'NewSharingWindow', 'height=700,width=800');
    }
});


$('body').on('click', '.btnShareOnMail', function () {
    var provider = $(this).attr('displayText');
    var productUrl = $('#externalEmailShareScreen #shareUrl').val() || location.href; //$(this).attr('st_url');
    var providerUrl = '';
    var productTitle = $('#externalEmailShareScreen #shareTitle').val() || $('title').text(); // $(this).attr('st_title') || '';
    var subject = productTitle;
    var body = '{productUrl}';
    switch (provider) {
        case 'Gmail':
            providerUrl = 'https://mail.google.com/mail/?view=cm&fs=1&su={subject}&body={body}';
            break;
        case 'Yahoo':
            providerUrl = 'http://compose.mail.yahoo.com/?subject={subject}&body={body}';
            break;
        case 'Email':
            providerUrl = 'mailto:test@example.com?subject={productUrl}&body={body}';
            break;
        default:
    }

    if (providerUrl) {
        body = body.replace('{productUrl}', productUrl);
        providerUrl = providerUrl.replace('{subject}', encodeURIComponent(subject)).replace('{body}', encodeURIComponent(body));
        window.open(providerUrl);
    }
});

function openSharToEmailModel(productTitle, productUrl) {
    $('#externalEmailShareScreen #shareUrl').val(productUrl);
    $('#externalEmailShareScreen #shareTitle').val(productTitle);
    var content = $('#externalEmailShareScreen').html();
    $.confirm({
        title: '',
        boxWidth: '450px',
        useBootstrap: false,
        type: '',
        content: content,
        buttons: {
            close: {
                text: 'Close',
                btnClass: 'btn-danger',
                action: function () {
                }
            }
        }
    });
}

$('body').on('click', '.impersonateInfo', function () {
    $.alert({
        title: 'Impersonate Session',
        content: $(".clsImpersonateTextModel").html(),
        useBootstrap: false,
        boxWidth: '600px',
        backgroundDismiss: true,
        buttons: {
            cancel: {
                text: 'Close',
                btnClass: 'btn-default'
            }
        },
        onContentReady: function () {
            $(".impersonateUL").css("padding-left", "18px")
        }
    });
});

var isImpersonateSession = function () {
    return document.cookie.indexOf('ImpersonateId=') != -1;
}

function getParameterFromUrl(param) {
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] && param && sParameterName[0].toLowerCase() == param.toLowerCase()) {
            return sParameterName[1];
        }
    }
}

$("body").on("click", ".supoortSolutionPopup", function () {
    $.magnificPopup.open({
        items: {
            src: '/Tickets/TicketEmailPopup?isViewer=false'
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'pop700'
    });
    $(".pop700").find('iframe').attr("id", "ifrSupportSolution");
    $(".pop700").attr("data-html2canvas-ignore", "true");
    return false;
});



function isIOsSafari() {
    var userAgent = navigator.userAgent;

    return /iP(ad|od|hone)/i.test(userAgent) && /WebKit/i.test(userAgent) && !(/(CriOS|FxiOS|OPiOS|mercury)/i.test(userAgent));
}

//#region #0017560: Viewer > Safari > Mobile Device >Open viewer in same tab vs target _blank
function preventViewerLaunchInNewTab() {
    if (!isIOsSafari()) return false;

    var buttons = [];

    var targetButtons = [$('a[href*="/ShowTime"]'), $('a[href*="/viewer/classroom"]'), $('a[href*="/Viewer"]'), $('a[href*="/UnAutheticatedLinkDemo"]'), $('a[href*="/LaunchFreeViewer"]')];

    if (!targetButtons || targetButtons.length == 0) return false;

    targetButtons.map(function (element) {
        if (element && element.length > 0) {
            buttons.push(element);
        }
    });

    if (!buttons || buttons.length == 0) return false;

    buttons.map(function (element) {
        var $this = $(element);

        if (!$this || $this.length == 0) return false;

        var targetAttr = $this.attr('target');

        if (!targetAttr || targetAttr != '_self') {
            $this.attr('target', '_self');
        }
    });
}
//#endregion

$("body").on("click", ".copyToClipboard", function () {
    var element = $(this);
    var text = $(this).attr("data-text");
    Helper.Common.copyToClipBoard(text, element);
});

function showWebinarPassword() {
    if ($(".webinar-launch-button").length > 0) {
        $(".webinar-launch-button").each(function () {
            var programRegistrantId = $(this).attr("data-programregistrantid");
            $(".webinar-password[data-programRegistrantId=" + programRegistrantId + "]").show();
        });
    }
}
//#endregion

$("body").on('click', '.popCancellationOptions', function () {
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'popCancellationOptionsMainClass'
    });
    return false;
});


// check card type and card number validation
function checkCreditCardTypeValidation(VARCARDTYPE, ccNumber) {
    var ERROR_MSG = 'You have selected ' + VARCARDTYPE + ' as card type. Please make sure your card is ' + VARCARDTYPE + '.';
    if (VARCARDTYPE == "American Express") {
        VARCARDTYPE = "amex";
    }
    if (VARCARDTYPE && VARCARDTYPE != 'MasterPass' && ccNumber) {
        var VAR_ORIGINAL_CARDTYPE = getCreditCardName(ccNumber)
        if (VAR_ORIGINAL_CARDTYPE != VARCARDTYPE.toLowerCase()) {
            alert(ERROR_MSG);
        }
    }
}

// get card name from  payment method selection
function getCreditCardName(cur_val) {
    var sel_brand;

    // the regular expressions check for possible matches as you type, hence the OR operators based on the number of chars
    // Visa
    visa_regex = new RegExp('^4[0-9]{0,15}$');
    // MasterCard
    mastercard_regex = new RegExp('^5[1-5][0-9]{0,17}$|^2[2-7][0-9]{0,17}$');
    // Maestro
    maestro_regex = new RegExp('^6[7-9][0-9]{0,17}$');
    // American Express
    amex_regex = new RegExp('^3$|^3[47][0-9]{0,13}$');
    // Diners Club
    diners_regex = new RegExp('^3$|^3[068]$|^3(?:0[0-5]|[68][0-9])[0-9]{0,11}$');
    //Discover
    discover_regex = new RegExp('^6$|^6[05]$|^601[1]?$|^65[0-9][0-9]?$|^6(?:011|5[0-9]{2})[0-9]{0,12}$');
    //JCB
    jcb_regex = new RegExp('^2[1]?$|^21[3]?$|^1[8]?$|^18[0]?$|^(?:2131|1800)[0-9]{0,11}$|^3[5]?$|^35[0-9]{0,14}$');

    // get rid of spaces and dashes before using the regular expression
    cur_val = cur_val.replace(/ /g, '').replace(/-/g, '');

    // checks per each, as their could be multiple hits
    if (cur_val.match(visa_regex)) {
        sel_brand = "visa";
    } else if (cur_val.match(mastercard_regex)) {
        sel_brand = "mastercard";
    } else if (cur_val.match(maestro_regex)) {
        sel_brand = "maestro";
    } else if (cur_val.match(amex_regex)) {
        sel_brand = "amex";
    } else if (cur_val.match(diners_regex)) {
        sel_brand = "diners_club";
    } else if (cur_val.match(discover_regex)) {
        sel_brand = "discover";
    } else if (cur_val.match(jcb_regex)) {
        sel_brand = "jcb";
    } else {
        sel_brand = "unknown";
    }

    return sel_brand;
}

function fixedSideBarScrollTop() {
    //setTimeout(function () {
    //    $(".fixedSideBar").css("top", $(".fixedSideBar").offset().top - $(".divPurhaceItems:first").height() - 20);
    //}, 500);
    //Mantis: #22280
    window.scrollBy(0, -500);
}

$("body").on("keypress", "#frmMembershipSearch", function (e) {
    kCode = e.keyCode || e.charCode
    if (kCode == 13) {
        membershipList();
        return false;
    }
});

function membershipList() {
    var search = $("#txtMembershipSearch").val();
    var groupTypeName = $("#txtMembershipSearch").attr("data-groupTypeName");
    search = encodeURIComponent(search);
    if (groupTypeName != "") {
        window.location.href = '/grouptype/' + groupTypeName + '?q=' + search;
    }
    else {
        window.location.href = '/search/membershiptypeslist?q=' + search;
    }
}
$("body").on("click", "#btnClearTxtbox", function () {
    $("#txtMembershipSearch").val("");
    membershipList();
});
$("body").on("click", "#btnSearchGroupType", function () {
    membershipList();
});

$("body").on('click', '.popManualRenewal', function () {
    var isAutoPayer = $(this).attr("data-isautopayer");
    var isACHPayment = $(this).attr("data-isACHPayment");
    if (isAutoPayer && isAutoPayer.toLocaleLowerCase() == "true") {
        DisplayCardOnFile($(this).attr("data-href"), isACHPayment);
    }
    else {
        ManualRenewalPopup($(this).attr("data-href"));
        return false;
    }
});

function ManualRenewalPopup(url, useCardOnFile) {
    url = url + "&IsUseCardOnFile=" + (useCardOnFile || false);
    openPopup(url);
    return false;
}

function DisplayCardOnFile(url, isACHPayment) {
    var contentMessage = "A credit card has been authorized to be used for recurring payments. Would you like to use this payment method to process any outstanding invoices? "
    if (isACHPayment && isACHPayment.toLocaleLowerCase() == "true") {
        contentMessage = "ACH/eCheck has been authorized to be used for recurring payments. Would you like to use this payment method to process any outstanding invoices? "
    }
    $.confirm({
        title: 'Use Payment Method on File?',
        boxWidth: '500px',
        useBootstrap: false,
        type: 'green',
        content: '<span style="font-size: 14px;margin-top:20px;">' + contentMessage + '</span>',
        buttons: {
            ok: {
                text: "Yes",
                btnClass: 'btn-success',
                action: function () {
                    ManualRenewalPopup(url, true);
                }
            },
            cancel: {
                text: 'No',
                btnClass: 'btn-danger',
                action: function () {
                    ManualRenewalPopup(url, false);
                }
            }
        }
    });
}

function openPopup(url) {
    $.magnificPopup.open({
        items: {
            src: url
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'poprenewManually'
    });
    return false;
}


//#region mantis item #19014
$("body").on('click', '.btnPendingInvoiceRetryPayment', function () {
    var customerMembershipId = $(this).attr("data-customerMembershipId");
    $.confirm({
        title: 'Retry Payment',
        content: '<p>The Retry Payment will just check, whether the pending payment has received or not.</p>',
        type: 'green',
        useBootstrap: true,
        buttons: {
            YES: {
                btnClass: 'btn-success',
                action: function () { retryPendingInvoicePayments(customerMembershipId); }
            },
            NO: {
                btnClass: 'btn-warning'
            }
        }
    });
});

function retryPendingInvoicePayments(customerMembershipId, isManulaPayment) {

    if (!customerMembershipId) { return false; }

    $('#divProgress').show();
    //check the payment is received or not
    $.post(RETRY_PENDING_INVOICE_PAYMENTS, { "customerMembershipId": customerMembershipId, "isManulaPayment": isManulaPayment }, function (data) {
        $('#divProgress').hide();

        if (!data || !data.success) {
            if (data.errorMessage) alert(data.errorMessage);

            return false;
        }

        //manually pay the invoice
        function manuallyPayPendingInvoice(customerMembershipId) {
            //Pay selected invoices
            if (!isValidPayNowForSeleted()) { return false; }

            //first deactivate the payment profile and then  proceed
            $.post(DEACTIVATE_MEMBERSHIP_PAYMENT_PROFILE, { "customerMembershipId": customerMembershipId }, function (data) {
                $('#divProgress').hide();
                //profile not deactivated successfully.
                if (!data) { alert("Your payment profile has not been deactivated successfully. Please try again or contact support."); return false; }

                //add invoice to the cart and proceed further
                var pageName = $(this).attr("data-pageName");
                var paymentIds = $("input[type='checkbox'][class='chkSelect-FuturePayment']:checked").map(function () { return $(this).val() }).get().join(',');
                AddToCartPayments(customerMembershipId, paymentIds, pageName);

            });

        }

        if (isManulaPayment && data.isPendingPayment === true) {
            manuallyPayPendingInvoice(customerMembershipId);
        }
        else {
            window.location.reload();
        }

    });
}

$("body").on('click', '.btnPendingInvoiceManualPayment', function () {
    var customerMembershipId = $(this).attr("data-customerMembershipId");

    //Pay selected invoices
    if (!isValidPayNowForSeleted()) { return false; }

    $.confirm({
        title: 'Pay Manually',
        content: '<p>It will deactivate your current payment profile. It allows paying manually all the pending selected invoices.</p>',
        type: 'red',
        useBootstrap: true,
        buttons: {
            YES: {
                btnClass: 'btn-red',
                action: function () { retryPendingInvoicePayments(customerMembershipId, true); }
            },
            NO: {
                btnClass: 'btn-warning'
            }
        }
    });
});

//#endregion mantis item #19014

$("body").on("click", ".showMoreFaculty", function () {
    var $this = $(this);
    $this.closest(".facultyList").find(".moreFacultyList").toggleClass("hidden");

    if (!$this.closest(".facultyList").find(".moreFacultyList").hasClass("hidden")) {
        $this.text('- Less');
    }
    else {
        $this.text('+ More');
    }
});

$('body').on('click', '.previewInfo', function () {
    $.alert({
        title: 'Preview Viewer',
        content: $(".clsPreviewTextModel").html(),
        useBootstrap: false,
        boxWidth: '800px',
        backgroundDismiss: true,
        buttons: {
            cancel: {
                text: 'Close',
                btnClass: 'btn-default'
            }
        }
    });
});

function edgeBrowserLaunch() {
    window.location = 'microsoft-edge:' + window.location;
    setTimeout(function () {
        window.location = 'https://www.microsoft.com/en-us/edge?browser=Chrome&FORM=MG0AU2';
    }, 100);
}

$("body").on("click", ".clsLaunchPurchasedSeminar", function () {
    var $this = $(this);
    var URL = $(this).attr("href");

    if (!URL) return;
    if (URL.toLowerCase() == "javascript:void(0);" || URL.toLowerCase() == "javascript:void(0)") { return; }

    if ($this.attr("data-ProductId")) {
        launchPurchasedProduct($this, URL);
    }

    return false;
});


function launchPurchasedProduct($this, URL) {

    $.ajax({
        url: URL,
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            if (data.Success === false && data.ErrorMessage) {
                alert(data.ErrorMessage);
                return;
            }

            if (data.Success === true) {
                if (data.IsOpenPopup !== undefined && data.IsOpenPopup === true) {

                    if ($this.hasClass("clsLaunchModel")) {
                        if (data.PopupClass) {
                            parent.parent.$(".mfp-bg.mfp-ready").addClass(data.PopupClass).removeClass("CustomPop");
                            parent.parent.$(".mfp-wrap.mfp-ready").addClass(data.PopupClass).removeClass("CustomPop");
                            parent.parent.$(".mfp-content").removeAttr("style");
                        }
                        window.location = data.RedirectURL;
                        return;
                    }

                    $.magnificPopup.open({
                        items: {
                            src: data.RedirectURL
                        },
                        type: 'iframe',
                        closeOnBgClick: false,
                        mainClass: data.PopupClass || 'popQuickLaunchMainClass'
                    });
                    return false;
                }
                else if (data.OpenInNewTab !== undefined && data.OpenInNewTab === true && !isIOsSafari()) {
                    var pop = window.open(data.RedirectURL, '_blank');
                    if (!pop) {
                        window.top.location = data.RedirectURL; //if popup is blocked by the browser open in same tab
                    }
                    if ($this.hasClass("clsLaunchModel")) {
                        parent.$.magnificPopup.close();
                    }
                } else {
                    if ($this.hasClass("clsLaunchModel") || $this.text() == 'View in Account' || data.RedirectURL.toLowerCase() == '/account/myaccount') {
                        window.top.location = data.RedirectURL;
                        parent.$.magnificPopup.close();
                    }
                    else {
                        window.location = data.RedirectURL;
                    }
                }
            }
        }
    });
}

$("body").on('click', '.popUpdateQuestionset', function () {
    parent.$('.mfp-bg,.mfp-ready').removeClass("pop700").addClass('CustomPop');
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        callbacks: {
            close: function () {
                parent.$('.mfp-bg,.mfp-ready').removeClass("CustomPop").addClass('pop700');
            }
        },
        mainClass: 'poprenewManually',
    })

    return false;
});

$("body").on('change', 'input[type=radio].addressQuestionRadio', function () {
    var questionId = $(this).attr("data-questionid") || "";
    $('#IsAddressBlockQuestion' + questionId).attr('data-selectedvalue', $(this).val())
});

$("body").on("keypress", ".searchByEnter", function (e) {

    kCode = e.keyCode || e.charCode //for cross browser
    if (kCode == 13) {
        var defaultbtn = $(this).attr("data-DefaultButton");
        $("#" + defaultbtn).click();
        return false;
    }
});
function validateUploadingFile(param, disableButtons) {
    var fileExtension = ['gif', 'jpeg', 'jpg', 'png', '.ico', 'bmp', 'webp', 'avif'];
    var fUpload = $('#' + param);
    if (fUpload[0].files.length > 0) {
        if ($.inArray(fUpload.val().split('.').pop().toLowerCase(), fileExtension) == -1) {
            $("#rfvFile").html("File upload is limited to the following formats (e.g - gif, jpeg, jpg, png, ico, bmp, webp or avif )").css("color", "red").addClass("field-validation-error");
            $(disableButtons).attr("disabled", "disabled");
        }
        else {
            $("#rfvFile").html("").removeClass("field-validation-error");
            $(disableButtons).removeAttr("disabled");
        }
    }
    else {
        $("#rfvFile").html("").removeClass("field-validation-error");
        $(disableButtons).removeAttr("disabled");
    }
}

$("body").on("change", ".socialmedia", function () {

    var count = 0;
    var urlRegex = /^http(s)?:\/\/(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/;
    var url = $(this).val();

    var $element = $('#divProdNotActiveMessageOnFirstRegistration');
    var isUnPublishAlert = $element.length > 0 ? $element.is(':hidden') : true;

    if (url) {
        if (!urlRegex.test(url)) {
            $(':submit').attr("disabled", "disabled");
            alert("Invalid Url. Please Enter Url in proper Format");
            $(this).focus();
        }
        else if (isUnPublishAlert) {
            $(':submit').removeAttr("disabled");
        }
    }
    $(".socialmedia").each(function () {
        if ($(this).val() && !urlRegex.test($(this).val())) {
            count += 1; // here is the validation condition
        }
        else if ($(this).val()) {
            var spanId = $(this).prop('id');
            $("#" + spanId + "errorMsg").text("");
            $(this).css("border-color", "#ccc");
        }
    });
    if (count > 0 || !isUnPublishAlert) {
        $(':submit').attr("disabled", "disabled");
    }
    else {
        $(':submit').removeAttr("disabled");
    }
});

function checkSocialMediaAndBackGroundRequired() {
    var isValid = true;
    $(".socialmedia").each(function () {
        if ($(this).prop('required') && !$(this).val()) {
            var spanId = $(this).prop('id');
            var errorText = $(this).prop('placeholder');
            $("#" + spanId + "errorMsg").text(errorText);
            $(this).css("border-color", "#a94442");
            isValid = false;
        }
    });

    if ($("#Background").length > 0 && $("#Background").hasClass("backgroundBioRequired") && !$("#Background").val() && $("#Background").val().trim() == '') {
        var bioLabel = $(".backgroundBioLabel").text();
        $("#bioErrorMsg").text("Please enter " + bioLabel);
        isValid = false;
    }
    else if ($("#Companies_Description").length > 0 && $("#Companies_Description").hasClass("backgroundBioRequired") && !$("#Companies_Description").val() && $("#Companies_Description").val().trim() == '') {
        var bioLabel = $(".backgroundBioLabel").text();
        $("#bioErrorMsg").text("Please enter " + bioLabel);
        isValid = false;
    }
    return isValid;
}
jQuery.fn.extend({
    serializeJSONObj: function () {
        var fields = this.serializeArray(),
            keys = {};

        fields.map(function (x, i) {
            if (keys[x.name]) {
                keys[x.name] = keys[x.name] + ',' + x.value
            }
            else {
                keys[x.name] = x.value
            }
        });

        return keys;
    }
});

//mantis #21829 -  Sales > Bundles > Display Purchase CE within Bundles - START
// #region CE Credit Purchase
$("body").on("click", ".btnBundle05AddCECredittoCart", function () {
    var productId = $(this).attr('data-productId');
    if ($("#divPurchaseCECreditmodal").length > 0) {
        $("#divPurchaseCECreditmodal").modal("hide");
    }
    $.ajax({
        type: "POST",
        url: BUNDLE_TYPE_5_ADD_CECREDITTOCART_URL,
        dataType: "json",
        data: {
            'productId': productId
        },
        success: function (data) {
            LoadCustomerBundleProductList();
        },
        complete: function (data) {
        },
        error: function (data) {
            alert('Error! Please try again later.');
        }
    });
});

$("body").on("click", ".btnBundle05CloseAddCECredittoCart", function () {
    LoadCustomerBundleProductList();
});

//display purchase CE popup modal
var displayBundlePurchaseCEMessage = function (bundleId) {
    $.get(BUNDLE_GET_PURCHASE_CE_PRICE_POPUP + '?bundleId=' + bundleId, function (dataPurchaseCEHtml) {
        if ($('#divBundlePurchaseCECreditmodal').length > 0) {
            $('#divBundlePurchaseCECreditmodal').remove();
        }
        $('body').append(dataPurchaseCEHtml);
        $("#divBundlePurchaseCECreditmodal").modal();
        return false;
    });
}

$("body").on("click", ".chkAllBundleCECreditPurchase", function () {
    var chkAll = this;
    $('#divBundlePurchaseCECreditmodal').find("input[type='checkbox'][class='chkBundleCECreditPurchase']:not(:disabled)").each(function () {
        $(this).prop('checked', chkAll.checked);
    });
});

$("body").on("click", ".chkBundleCECreditPurchase", function () {
    $(".chkAllBundleCECreditPurchase").prop("checked", $(".chkBundleCECreditPurchase:checkbox").length === $(".chkBundleCECreditPurchase:checkbox:checked").length);
});

// #region CE Credit Purchase
$("body").on("click", ".btnBundleAddCECredittoCart", function () {
    var bundleId = $(this).attr("data-bundleId")
    var productids = [];
    if ($('#divBundlePurchaseCECreditmodal').find(".chkBundleCECreditPurchase:checkbox:checked").length > 0) {
        $('#divBundlePurchaseCECreditmodal').find(".chkBundleCECreditPurchase:checkbox:checked").each(function () {
            productids.push($(this).attr("data-productid"));
            var ele = $(".clsBundleDiv").closest("[data-bundleid='" + bundleId + "']");
            var hdnTotal = $(ele).find(".hdnTotal").val();
            var newPrice = $(this).attr("data-price");
            var newval = parseFloat(hdnTotal) + parseFloat(newPrice)
            $(ele).find(".hdnTotal").val(newval.toFixed(2));
            $(ele).find(".spnTotal").html(parseFloat($(ele).find(".hdnTotal").val())).addClass("dollarsign");
        });
    }
    else {
        alert("Please select atleast one " + $("#CustomPurchaseCECreditTitle").val() + "");
        return false;
    }

    if ($("#divBundlePurchaseCECreditmodal").length > 0) {
        $("#divBundlePurchaseCECreditmodal").modal("hide");
    }

    $.ajax({
        type: "POST",
        url: BUNDLE_ADD_CECREDITTOCART_URL,
        dataType: "json",
        data: {
            'productIds': productids, 'bundleId': bundleId
        },
        success: function (data) {
            if (data.isSendCustomerToCart != undefined && data.isSendCustomerToCart == true) {
                window.parent.location.href = '/shoppingcart';
                return false;
            }

            if (data.CartCount != null && data.CartCount != "" && data.CartCount != "0") {
                parent.$("#cartspancount").html(data.CartCount);
                parent.$("#cartItemList").load('/shoppingcart/getcart');
            }

            if (typeof backtoParent === "function" && productids.length > 0) {
                backtoParent(productids[0], data.Message);
            }

        },
        complete: function (data) {
        },
        error: function (data) {
            alert('Error! Please try again later.');
        }
    });
});

$("body").on("click", ".btnBundleCloseAddCECredittoCart", function () {
    var isSendTocart = $(this).attr('data-isSendCustomerCart');

    if (isSendTocart != undefined && isSendTocart == "True") {
        parent.window.location.href = '/ShoppingCart';
    }
});

//mantis #21829 -  Sales > Bundles > Display Purchase CE within Bundles - END

//#21763
$("body").on('change', 'input[type=radio].addressQuestionSetRadio', function () {
    var questionId = $(this).attr("data-questionid") || "";
    $(this).parents('#QuestionSetExistingAddress' + questionId).attr('data-selectedvalue', $(this).val());
});

$("body").on("click", ".questionSetAddressType", function (e) {
    var $this = $(this);
    $.magnificPopup.open({
        items: {
            src: $this.attr("data-href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'popEditAddressMainClass',
        callbacks: {
            beforeClose: function () {
                $this.prop("checked", false);
            }
        }
    });
    return false;
});

function loadCustomerAddressListForQuestionSet(questionId, addressId) {

    if ($(".divQuestionSetAddress").length <= 0) return false;

    $(".divQuestionSetAddress").each(function () {
        var $this = $(this);
        var divQuestionId = $this.attr("data-questionid") || 0;
        var isRequired = $this.attr("data-isRequired") || false;
        var isCurrentQuestion = divQuestionId > 0 && (questionId || 0) > 0 && divQuestionId == questionId;
        var selectedAddressId = isCurrentQuestion ? (addressId || 0) : $this.find(".divExistingAddress").attr("data-selectedvalue");
        var isExistingAddressSelected = $this.find(".questionSetAddressType[value='ExistingAddress']").is(':checked');

        $this.load('/Account/GetQuestionSetAddressDetails?questionId=' + divQuestionId + '&addressId=' + selectedAddressId + '&isRequired=' + isRequired, function () {
            if (isCurrentQuestion) {
                $this.find(".questionSetAddressType[value='ExistingAddress']").trigger("change");
            }

            if (isExistingAddressSelected) {
                $this.find(".divExistingAddress").show();
            }
        }).prepend("<p class='loaderTxt'>Please wait ...</p>");
    });
}

//#21771
$("body").on("click", "#unlinkCustomAddress", function () {
    if (confirm("Are you sure want to unlink this address?")) {
        var id = $(this).attr("data-id");
        var editAddressPopupType = $(this).attr('data-editAddressPopupType');
        if (id) {
            $('#divProgress').show();
            $.post('/Account/UnlinkCustomerCustomAddress', { id: id }, function (data) {
                addressMethod(editAddressPopupType);
                $('#divProgress').hide();
            });
        }
    }
});

//pagging for New Single Column Upcoming Live Programs Widget in Catalog - #21544
$("body").on("click", ".datatables_paginate_single_upcoming_live_widget >.pagination a", function () {
    var url = $(this).attr('href');
    var upcomingPageWidgetId = 0;
    if ($(this).closest('.grid-list-singlecol').find("#UpcomingPageWidgetId").length > 0) {
        upcomingPageWidgetId = $(this).closest('.grid-list-singlecol').find("#UpcomingPageWidgetId").val();
    }
    $(".divSingleUpcomingLiveWidget-" + upcomingPageWidgetId + "").load(url, function () {
        $('.scheduleAtGlance').popover({ trigger: 'hover', placement: 'top' })
            .on("show.bs.popover", function () {
                return $(this).data("bs.popover").tip().css({ "width": "fit-content", "max-width": "500px" });
            });
    });
    return false;
});


//#21994 Start
function ConfirmRegistrantDiscount(couponCode, couponId, inValidRegistrants, message, registrantsDiscountMessageType) {

    //#22585
    if (registrantsDiscountMessageType != 'Default') {

        switch (registrantsDiscountMessageType) {
            case "AssignLater":
                message = message + " We cannot allow you to assign these later as we need to validate who those registrants are at this time.";
                break;
            case "NoRegistrantsInTheCart":
                message = message + " You must register the registrants, then you will be able to apply the discount on next step.";
                break;
            case "AllRegistrantsAreInValid":
                message = " This discount is limited to specific registrants. The additional registrants not included in the discount will need to be registered in a separate transaction and will be removed from this order.";
        }

        $.confirm({
            title: '',
            boxWidth: '500px',
            useBootstrap: false,
            type: 'green',
            content: message,
            buttons: {
                ok: {
                    text: 'Ok',
                    btnClass: 'btn-success'
                }
            }
        });
    }
    else {
        $.confirm({
            title: '',
            boxWidth: '500px',
            useBootstrap: false,
            type: 'green',
            content: message,
            buttons: {
                ok: {
                    text: 'Continue',
                    btnClass: 'btn-success',
                    action: function () {
                        RemoveInvalidRegistrants(couponCode, couponId, inValidRegistrants);
                        if ($('#currentCartStage').val() == 'RegistrantConfirmation') {
                            if (couponId) {
                                applyGlobalDiscount(couponId);
                            }
                            else {
                                ApplyDiscountCode(couponCode);
                            }
                        }
                    }
                },
                cancel: {
                    text: 'Cancel Discount',
                    btnClass: 'btn-warning',
                    action: function () {
                    }
                }
            }
        });
    }
}

function RemoveInvalidRegistrants(couponCode, discountId, inValidRegistrants) {
    if ($('#currentCartStage').val() == 'RegistrantConfirmation') {
        let lstRegistrantEmail = inValidRegistrants.split(',');
        $.each(lstRegistrantEmail, function (e, i) {
            $.each($('.clsEmailAddress'), function () {
                if ($(this).val() == i) {
                    var isPurchaserEmail = $(this).closest(".row").parent('.divPurchaseSection.clsInputPortion').find('#chkPurchaser')
                    $(this).closest(".row").find('input:text').val('').trigger('change');
                    if (isPurchaserEmail) {
                        $(isPurchaserEmail).prop('checked', 'checked').trigger('change');
                    }

                }
            });
        });
    }
    else {
        $.post('/ShoppingCart/RemoveInvalidRegistrants', { inValidRegistrants: inValidRegistrants }, function (data) {
            if (couponCode) {
                $("#txtCouponCode").val(couponCode);
                $(".btnCouponShoppingCart").trigger('click');
            }
            else if (discountId) {
                applyGlobalDiscount(discountId);
            }
            ISRELOADPAGE = true;
        });
    }
}
//#21994 End

//#Start Region 21323: Enhancement: Catalog Mobile Updates

// Prepend back button to sub menu(s)
$('.nav__item .nav__sub').prepend('<li class="nav__item"><a class="nav__link sub__close" href="#"><i class="fa fa-chevron-left"></i> Back</a></li>');

// Close out sub menu
$('.sub__close').click(function (e) {
    e.preventDefault();

    $(this).parent().parent().removeClass('is-active');
});

// Trigger sub menu
$('.drop-link .nav__item_i, .nav__item .nav__link').click(function (e) {
    e.preventDefault();

    $(this).siblings().addClass('is-active');
});

//#end Region

// 22459 Set and Collect Cookie
function setCookie(cname, cvalue, exdays) {
    const d = new Date();
    if (exdays > 0) {
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        let expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    } else {
        document.cookie = cname + "=" + cvalue + ";path=/";
    }
}

function getCookie(cname) {
    let name = cname + "=";
    let ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function getURLParameter(url, name) {
    return (RegExp(name + '=' + '(.+?)(&|$)').exec(url) || [, null])[1];
}

$("body").on('click', '.pop700', function () {
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: true,
        mainClass: 'pop700'
    });
    return false;
});

function isHTML(str) {
    var a = document.createElement('div');
    a.innerHTML = str;

    for (var c = a.childNodes, i = c.length; i--;) {
        if (c[i].nodeType == 1) return true;
    }

    return false;
}

//0022254
function validateAddressField(frmId) {
    if ($("#" + frmId + " #OtherState:visible").length > 0 && $("#" + frmId + " #OtherState:visible").attr("required") != undefined) {
        var fieldVal = $("#" + frmId + " #OtherState:visible").val();
        if (fieldVal != undefined && (fieldVal.length <= 0 || $.trim(fieldVal).length <= 0)) {
            validateAddressFieldWithErrorMsg($("#" + frmId + " #OtherState:visible"));
            return false;
        }
    }
    if ($("#" + frmId + " #PostalCode:visible").length > 0 && $("#" + frmId + " #PostalCode:visible").attr("required") != undefined && $("#" + frmId + " #PostalCode:visible").parent().find(".help-block").length <= 0) {
        var fieldVal = $("#" + frmId + " #PostalCode:visible").val();
        if (fieldVal.length <= 0 || $.trim(fieldVal).length <= 0) {
            validateAddressFieldWithErrorMsg($("#" + frmId + " #PostalCode:visible"));
            return false;
        }
    }
    if ($("#" + frmId + " #Address2:visible").length > 0 && $("#" + frmId + " #Address2:visible").attr("required") != undefined) {
        var fieldVal = $("#" + frmId + " #Address2:visible").val();
        if (fieldVal.length <= 0 || $.trim(fieldVal).length <= 0) {
            validateAddressFieldWithErrorMsg($("#" + frmId + " #Address2:visible"));
            return false;
        }
    }
    if ($("#" + frmId + " #City:visible").length > 0 && $("#" + frmId + " #City:visible").attr("required") != undefined) {
        var fieldVal = $("#" + frmId + " #City:visible").val();
        if (fieldVal.length <= 0 || $.trim(fieldVal).length <= 0) {
            validateAddressFieldWithErrorMsg($("#" + frmId + " #City:visible"));
            return false;
        }
    }
    if ($("#" + frmId + " #Address:visible").length > 0 && $("#" + frmId + " #Address:visible").attr("required") != undefined) {
        var fieldVal = $("#" + frmId + " #Address:visible").val();
        if (fieldVal.length <= 0 || $.trim(fieldVal).length <= 0) {
            validateAddressFieldWithErrorMsg($("#" + frmId + " #Address:visible"));
            return false;
        }
    }
    if ($("#" + frmId + " #Address1:visible").length > 0 && $("#" + frmId + " #Address1:visible").attr("required") != undefined) {
        var fieldVal = $("#" + frmId + " #Address1:visible").val();
        if (fieldVal.length <= 0 || $.trim(fieldVal).length <= 0) {
            validateAddressFieldWithErrorMsg($("#" + frmId + " #Address1:visible"));
            return false;
        }
    }
    if ($("#" + frmId + " #AddressLabel:visible").length > 0 && $("#" + frmId + " #AddressLabel").attr("required") != undefined) {
        var fieldVal = $("#" + frmId + " #AddressLabel").val();
        if (fieldVal.length <= 0 || $.trim(fieldVal).length <= 0) {
            validateAddressFieldWithErrorMsg($("#" + frmId + " #AddressLabel"));
            return false;
        }
    }
    if ($("#" + frmId + " #County:visible").length > 0 && $("#" + frmId + " #County:visible").attr("required") != undefined && $("#" + frmId + " #County:visible").parent().find(".help-block").length <= 0) {
        var fieldVal = $("#" + frmId + " #County:visible").val();
        if (fieldVal != undefined && (fieldVal.length <= 0 || $.trim(fieldVal).length <= 0)) {
            validateAddressFieldWithErrorMsg($("#" + frmId + " #County:visible"));
            return false;
        }
    }
    return true;
}

function validateAddressFieldWithErrorMsg(element) {
    var elementId = element.attr("id");
    element.closest(".form-group").addClass("has-error");
    element.next("#fieldErrorMsg").html("");
    if ($("#" + elementId + "-error").length <= 0) {
        element.after('<span id="fieldErrorMsg" style="color:#a94442;font-weight: bold;"> This field is required </span>');
    }
}

function CheckGiftCardCodeAlerdayApplied(GiftCardCode) {
    $.ajax({
        type: "GET",
        url: CHECK_GIFT_CARD_CODE_ALERDAY_APPLIED_URL,
        dataType: "json",
        data: {
            'giftCardCode': GiftCardCode,
        },
        success: function (data) {
            if (data != null && data.IsExist) {
                alert(data.Message);
                $('#txtCouponCode').val('');
            }
            else {
                ApplyGiftCard(GiftCardCode);
            }
        },
        error: function (data) {
            return false;
        }
    });
}

//23621 - 
function QuestionSetCompanyConformation(frmid) {
    var ActiveCBM = false;
    var CBMOwner = false;
    if ($("#ActiveCBM").val() == "True") {
        ActiveCBM = true;
    }
    if ($('#IsCBMOwner').val() == "True") {
        CBMOwner = true;
    }
    if ($("#" + frmid).valid() && ($(".autoCompleteCompanyName").length == 1 || $("select.dropQsetCompanyName").length == 1) && ActiveCBM) {
        var OldCompanyName = ($(".autoCompleteCompanyName").length == 1 ? $(".autoCompleteCompanyName").attr('data-answer') : $("select.dropQsetCompanyName").attr('data-answer'));
        var IsEnableCompanyDrop = ($(".autoCompleteCompanyName").length == 1 ? false : ($("select.dropQsetCompanyName").length == 1 ? true : false));
        var CompanyName = "";
        var othercompanyid = "";
        if (IsEnableCompanyDrop) {
            if ($("select.dropQsetCompanyName").val() == "-1") {
                othercompanyid = "OtherCompany_" + $("select.dropQsetCompanyName").attr("id");
                CompanyName = $("#" + othercompanyid).val();
            } else {
                CompanyName = $("select.dropQsetCompanyName").val();
            }
        } else {
            CompanyName = $(".autoCompleteCompanyName").val();
        }

        const details = {
            hasActiveCBM: ActiveCBM,
            IsCBMOwner: CBMOwner,
            EncryptedCompanyId: $("#EncryptedCompanyId").val(),
            CustomerId: $("#hdnCustomerId").val(),
            CustomerMembershipId: parseInt($("#CBMCustomerMembershipId").val()),
            OldCompanyName: OldCompanyName,
            CompanyName: CompanyName,
            pageName: 'ParentQuestionSet',
            formid: frmid,
            buttonid: ''
        };

        if (OldCompanyName != '' && OldCompanyName != CompanyName) {
            ChangeCompanyConfirmation(details);
        } else {
            $("#" + frmid).submit();
        }
    } else {
        $("#" + frmid).submit();
    }
};

//#23067
function GetRegistrantEmails() {
    var emailAddress = '';
    if ($('#currentCartStage').val() == 'PersonalInfo') {
        emailAddress = email
    } else if ($('#currentCartStage').val() == 'RegistrantConfirmation') {
        emailAddress = $.map($('.clsEmailAddress'), function (e) {
            if ($(e).val()) {
                return $(e).val();
            }
        }).join(",");
    }
    return emailAddress;
}
function GetPurchaserCustomerId() {
    return (($('#chkPurchaser').is(':checked')) ? ($(".purchaserEmail").closest(".clsInputPortion").find("input[name='Email']").attr('data-purchasercustomerid')) : '');
}


//#23969
var SaveRequestInfoByCustomerOrderItemId = function (orderItemId, customerEmail, isAgendaRequestInfo) {
    var divOrderItemId = $('#OrderItemId[value="' + orderItemId + '"]').closest('.divFullRegConfirmation');

    if (divOrderItemId.hasClass("consolidateRegistrant")) {
        $(divOrderItemId).find('.purchaserEmail').attr('data-RequestQuestionSet', true);
        $(divOrderItemId).find('.purchaserEmail').attr('data-IsAddRegTypeId', true);
    }
    else {
        $(divOrderItemId).find('.registrantInfo').each(function (e, d) {
            if ($(this).find('.registrantEmail').val() == customerEmail) {
                if (!isAgendaRequestInfo) {
                    $(this).find('.registrantEmail').attr('data-RequestQuestionSet', true);
                    $(this).find('.registrantEmail').attr('data-IsAddRegTypeId', true);
                }
                else {
                    $(this).find('.registrantEmail').attr('data-RequestAgenda', true);
                }
            }
        });
    }
};

//Monday: 6480813440
function QuestionSetForChildQuestionSet(frmid, buttonid) {
    var formdetails = buttonid.closest("#" + frmid);
    var ActiveCBM = false;
    var CBMOwner = false;
    if (formdetails[0]["ActiveCBM"].value == "True") {
        ActiveCBM = true;
    }
    if (formdetails[0]["IsCBMOwner"].value == "True") {
        CBMOwner = true;
    }

    if (formdetails.valid()) {
        var OldCompanyName = formdetails.find(".autoCompleteCompanyName").attr('data-answer');
        var CompanyName = formdetails.find(".autoCompleteCompanyName").val();

        const details = {
            hasActiveCBM: ActiveCBM,
            IsCBMOwner: CBMOwner,
            EncryptedCompanyId: formdetails[0]["EncryptedCompanyId"].value,
            CustomerId: formdetails[0]["hdnCustomerId"].value,
            CustomerMembershipId: parseInt(formdetails[0]["CBMCustomerMembershipId"].value),
            OldCompanyName: OldCompanyName,
            CompanyName: CompanyName,
            pageName: 'ChildQueastionSet',
            formid: frmid,
            buttonid: buttonid
        };

        if (OldCompanyName != '' && OldCompanyName != CompanyName && ActiveCBM) {
            ChangeCompanyConfirmation(details)
        } else {
            SubmitForm(buttonid, frmid);
        }
    }
};
function SubmitForm(thisbutton, formid) {
    $(':disabled').prop('disabled', false);
    var ChildQuestionSetForm = thisbutton.closest("#" + formid).serialize();
    var MembershipTypeId = thisbutton.closest("#" + formid)[0]["MembershipTypeId"].value;
    $.ajax({
        url: '/group/SaveGroupQuestionsets',
        type: "post",
        dataType: "JSON",
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        data: ChildQuestionSetForm,
        success: function (data) {
            if (data != null) {
                if (data.membershipTypeId > 0 && data.orderItemId < 0) {
                    $("#IsQuestionSetField").val(true);
                    $(".panel-default .chkAddonMemberships:checked").each(function () {
                        if ($(this).attr('data-id') == MembershipTypeId) {
                            $(this).attr('data-QSetFiled', true);
                            $("#childalert_" + data.membershipTypeId).removeClass("hidden");
                            thisbutton.closest("#" + formid).focus();
                        } else {
                            $(this).click();
                            $(this).click();
                        }
                    });
                    var parentCustomerMembershipId = $(".btnAddChildMembership").attr("data-parentcustomermembershipsid");
                    if (parentCustomerMembershipId != undefined)
                        AddChildMembership(MembershipTypeId, parentCustomerMembershipId, data.orderItemId);

                    var pendingQuestionSet = $(".chkAddonMemberships:checked").map(function () { if ($(this).attr("data-questionsetexist") == "True" && $(this).attr("data-qsetfiled") == "False") { return $(this).attr("data-id"); } }).get().join();
                    if (pendingQuestionSet == '')
                        $(".btnAddGroupAddOns").removeClass("disabled");
                }
            }
        },
        error: function (errmsg) {
            console.log(errmsg);
        }
    });
};
// mantish(#22985)
$("body").on("click", ".btnAddtocartForpreProduct,.btnCartAgendaProductForPrepare", function (e, registrantTypeOrderItemId, ProductId, groupProductPricecId, chkPurchaserForRegistrant = false, isRegistrantRequestInfo = false) {
    var ProductsId = ($(this).attr("data-ProductId") != undefined && $(this).attr("data-ProductId") != null) ? $(this).attr("data-ProductId") : ProductId;
    if (!$(".list-group-item" + ProductsId + " input[name='PreRequestProductprice']:checked").val()) {
        alert("Please select one of the pricing options to add this item to your cart.");
        return false;
    }
    else {
        $('.SpinnerForAddToCart' + ProductsId).remove();
        $('.btnAddtocart' + ProductsId).html('<span class"ProcessingItem"><i class="fa fa-refresh fa-spin"></i>&nbsp;&nbsp;Processing...</span>').prop('disabled', true);
        saveAddToCartProductsForAcknowledge(registrantTypeOrderItemId, groupProductPricecId, ProductsId, chkPurchaserForRegistrant, isRegistrantRequestInfo);
    }
})

function openAgendaFormFromDiscount(productId, btnType, productPrice, productpriceid, discountEntityType, registrantTypeOrderItemId, isFromDiscountPage = true) {
    var height = $(this).attr("data-height");
    var width = $(this).attr("data-width");
    $.magnificPopup.close();
    $.magnificPopup.open({
        items: {
            src: AGENDA_PRODUCT_POPUP + '?productId=' + productId + '&orderItemId=' + 0 + '&btnType=' + btnType + "&productPrice=" + productPrice + "&discountId=" + productpriceid + "&entityType=" + discountEntityType + "&registrantTypeOrderItemId=" + registrantTypeOrderItemId + "&isFromDiscountPage=" + isFromDiscountPage
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'CustomPop'
    });
    $('.mfp-content').css('height', height);
    $('.mfp-content').css('width', width);
    $('.mfp-iframe-holder .mfp-content').css('max-height', height + 'px');
    $('.mfp-iframe-holder .mfp-content').css('max-width', width + 'px');
    return false;

}

$("body").on("change", "#divOptInSetting .chkUnsubscribeAll", function () {
    if (this.checked) {
        var entityType = $(this).attr("data-optintype");
        $("input[name='" + entityType + "']").prop("checked", false);
    }
});

$("body").on("change", "#divOptInSetting .chkOptInItem", function () {
    var name = $(this).attr("name");

    if ($('input[name=' + name + ' ]:checked').length > 0) {
        $("input[data-optintype='" + name + "'].chkUnsubscribeAll").prop("checked", false);
    }
});

$("body").on("click", "#divOptInSetting #btnSaveOptInSetting", function () {
    $('#divProgress, #divProgressReciept').show();
    //get selected email freq setting
    var emailFrequency = $("#divOptInSetting #EmailFrequency").val();
    var mobile = $("#divOptInSetting #Mobile").val();

    //get selected category
    var chkCategories = $('input[name=chkCategories]:checked');
    var categoryIds = "";
    chkCategories.each(function () {
        categoryIds += $(this).attr("value") + ","
    });
    categoryIds = categoryIds.substring(0, categoryIds.length - 1);

    //get selected tag
    var chkTags = $('input[name=chkTags]:checked');
    var tagIds = "";
    chkTags.each(function () {
        tagIds += $(this).attr("value") + ","
    });
    tagIds = tagIds.substring(0, tagIds.length - 1);

    //get selected topic area
    var topicAreaIds = $('input[name=chkTopicArea]:checked').map(function () {
        return $(this).attr("value");
    }).get().join(",");

    //get selected emailCampaignCategorie
    var emailCampaignCategorieIds = '';
    $.each($('input.chkEmailCampaignCategories:checked'), function (i, data) {
        emailCampaignCategorieIds += $(this).val() + ',';
    });
    emailCampaignCategorieIds = emailCampaignCategorieIds.substring(0, emailCampaignCategorieIds.length - 1);
    if ($(".chkUnsubscribeAll").is(":checked")) {

        var unsubScribeAllCategoriesName = [];

        $.each($(".chkUnsubscribeAll:checked"), function (i, data) {
            unsubScribeAllCategoriesName.push($(this).attr("name"));
        });

        if (unsubScribeAllCategoriesName.length > 0) {
            for (var i = 0; i < unsubScribeAllCategoriesName.length; i++) {
                if (unsubScribeAllCategoriesName[i] != undefined && unsubScribeAllCategoriesName[i].toLowerCase() == "chkcategoriesunsubscribeall") {
                    categoryIds = "";
                    $.each($('input[name=chkCategories]'), function (i, data) {
                        categoryIds += $(this).attr("value") + ',';
                    });

                    categoryIds = categoryIds.substring(0, categoryIds.length - 1);
                    categoryIds += ",-1"
                }
                if (unsubScribeAllCategoriesName[i] != undefined && unsubScribeAllCategoriesName[i].toLowerCase() == "chktagsunsubscribeall") {
                    tagIds = "";
                    $.each($('input[name=chkTags]'), function (i, data) {
                        tagIds += $(this).attr("value") + ',';
                    });

                    tagIds = tagIds.substring(0, tagIds.length - 1);
                    tagIds += ",-1"
                }
                if (unsubScribeAllCategoriesName[i] != undefined && unsubScribeAllCategoriesName[i].toLowerCase() == "chktopicareaunsubscribeall") {
                    topicAreaIds = "";
                    $.each($('input[name=chkTopicArea]'), function (i, data) {
                        topicAreaIds += $(this).attr("value") + ',';
                    });

                    topicAreaIds = topicAreaIds.substring(0, topicAreaIds.length - 1);
                    topicAreaIds += ",-1"
                }
            }
        }
    }

    var jsonSMSNotifications = $(".smsNotification").map(function () {
        if ($(this).find(".chkOptInItem").is(":checked")) {
            return {
                EntityId: $(this).attr("data-entityid"),
                EntityType: $(this).attr("data-entitytype"),
                Period: $(this).find(".notificationPeriod").val(),
                PeriodType: $(this).find(".notificationPeriodType").val()
            };
        }
    });

    $.ajax({
        type: "POST",
        url: "/CustomerNotification/SaveOptIn/",
        dataType: "json",
        data: {
            'categoryIds': categoryIds,
            'tagIds': tagIds,
            'topicAreaIds': topicAreaIds,
            'emailFrequency': emailFrequency,
            'mobile': mobile,
            'jsonSMSNotifications': JSON.stringify(jsonSMSNotifications.get()),
            'emailCampaignCategorieIds': emailCampaignCategorieIds
        },
        success: function (data) {
            $('#divProgress, #divProgressReciept').hide();
            if (typeof (OptInEmails) == 'function') {
                OptInEmails();
            }
        },
        error: function (data) {
            $('#divProgress, #divProgressReciept').hide();
            alert('Error! Please try again later.');
        }
    });
});

$("body").on('click', '.clsCompanyPurchase', function () {
    $("#divProgress").show();
    var value = $(this).is(":checked") ? "false" : "true";
    var pageName = $(this).attr("data-pageName");
    var isFromAfterOrder = false;
    var orderid = $(this).attr("data-orderId");
    if (pageName && pageName == 'AllTransactionsTab')
        isFromAfterOrder = true;
    //12952: Company - Employees - allows for company purchase if active employee even if no valid tax status
    $.post("/ShoppingCart/SaveCompanyTaxExemptPurchase?isCompanyPurchase=" + value + "&isFromAfterOrder=" + isFromAfterOrder + "&orderId=" + orderid, function (data) {
        if (data && pageName && pageName == "shoppingCart") {
            UpdateItemCart(0, true);
        } else if (pageName && pageName == "shoppingCart") {
            hideShowPyamentAssignToCompanyPurchase();
        }
        $("#divProgress").hide();
    });
});

function hideShowPyamentAssignToCompanyPurchase() {
    $("#divProgress").show();
    if ($(".clsCompanyPurchase").length > 0) {
        if ($(".clsCompanyPurchase").is(":checked")) {
            $(".clsPyamentAssignToCompanyPurchase").hide();
            if ($("#rbtnCompanyPurchase").is(":checked")) {
                $("#rbtnCompanyPurchase").prop("checked", false);
                $("#rbtnCreditCard").prop("checked", true);
                $("#creditCard").show('slow');
            }
            if ($('input[name=paymentMethod]:visible').length == 1) {
                $("#creditCardPanel").hide();
                $("#rbtnCreditCard").prop("checked", true).trigger("click");
            }
        } else {
            $(".clsPyamentAssignToCompanyPurchase").show();
            if ($("#rbtnCompanyPurchase").length > 0 && $("#rbtnCompanyPurchase").is(":checked")) {
                $("#CompanyPurchase").show();
            } else {
                $("#CompanyPurchase").hide();
            }
            $("#creditCardPanel").show();
        }
    } else {
        $(".clsPyamentAssignToCompanyPurchase").hide();
        if ($('input[name=paymentMethod]:visible').length == 1) {
            $("#creditCardPanel").hide();
            $("#rbtnCreditCard").prop("checked", true).trigger("click");
        }
    }

    $("#divProgress").hide();
}

//mantish(#22985)
var saveAddToCartProductsForAcknowledge = function (registrantTypeOrderItemId, groupProductPricecId, ProductId, chkPurchaserForRegistrant = false, isRegistrantRequestInfo = false) {
    var productTypeId = $('#ProductId' + ProductId).val();
    var addOnPriceType = "AddOnPrice";
    if (productTypeId != undefined && productTypeId == 12) {
        addOnPriceType = "ClassroomAddOn";
    }
    //need to check this
    var hdnBundleType4Product = "";
    if ($("#hdnBundleType4Product") != undefined) {
        hdnBundleType4Product = $("#hdnBundleType4Product").val();
    }
    var datatarget;
    if (hdnBundleType4Product == "1" && !$(".clsAdditionalprice").is(":checked")) {
        datatarget = "bundleType4AlertPopup";
        $('#' + datatarget).modal('hide');
    } else {
        if ($(".clsAdditionalprice").is(":checked")) {
            datatarget = "alertmodelAdditionalPrice" + ProductId;
            $('#' + datatarget).modal('hide');
        }
        else {
            datatarget = "alertmodel" + ProductId;
            $('#' + datatarget).modal('hide');
        }
    }
    var TimeId = 0;
    var $current_radio = $('.rdbprice input[type="radio"][name="PreRequestProductprice"]:checked, .rdbprice input[type="checkbox"][name="PreRequestProductprice"]:checked');

    //mantis item : 15859 > note > c14280
    var isGroupPendingPaymentWithProduct = groupProductPricecId && Number(groupProductPricecId) > 0;
    if (isGroupPendingPaymentWithProduct) {
        $("#divProgress").show();
        $current_radio = $('.rdbprice input[type=radio][data-productpriceid=' + groupProductPricecId + '],.rdbprice input[type=checkbox][data-productpriceid=' + groupProductPricecId + ']');
    }

    var chkRadioPrice = $('.rdbprice input[type=radio]:checked, .rdbprice input[type=checkbox]:checked');
    var Price = $current_radio.attr('value');
    var PriceData = Price != undefined && Price != null ? Price.split(',') : 0;
    var productPriceId = PriceData[0];
    var productPrice = PriceData[1];
    var Quantity = 1;
    var EventTimeId = $('.btnAddtocart' + ProductId).attr("data-eventtimeid");
    var MultipleEventTimeId = $('.EventDate' + ProductId).val();
    if (EventTimeId == undefined) {
        EventTimeId = $("#ProductEventTimeId").val();
    }
    var priceType = $current_radio.attr("data-priceType");
    var pagetype = '';
    var pageno = 1;
    var sortby = 11;
    var entitytype = $current_radio.attr("data-entitytype");
    var marketingEntityId = $("#hdnMarketingEntityId").val();
    var marketingEntityType = $("#hdnMarketingEntityType").val();
    var SwapOrderItemId = $("#hdnSwapOrderItemId").val();
    var relatedProductId = $("#hdnRelatedProductId").val();
    var productregistranttypeId = $current_radio.attr("data-productregistranttypeid");
    var productDiscountId = $("#hdnProductDiscountId").val();
    var isDiscountProduct = false;
    if (productDiscountId && productDiscountId > 0) {
        isDiscountProduct = true;
        priceType = "DiscountPrice";
    }

    if (parent.$("#pageType").val() != undefined) {
        pagetype = parent.$("#pageType").val();
    }

    if (parent.$("#pageno").val() != undefined) {
        pageno = parent.$("#pageno").val();
    }
    if (parent.$("#sortby").val() != undefined) {
        sortby = parent.$("#sortby").val();
    }


    if (MultipleEventTimeId > 0) {
        TimeId = MultipleEventTimeId;
    }
    else {
        TimeId = EventTimeId;
    }

    var isAdditionalItemChecked = false;
    var additionalItemChecked = $('input[class=clsAdditionalprice]:checked').prop('checked');
    var additionalprice = 0;
    var marketingEntityId = 0;
    var marketingEntityType = 0;

    if (isGroupPendingPaymentWithProduct) {
        priceType = '@(CE21.Data.Common.PromoCouponCodeType.MembershipPrice.ToString())';
        marketingEntityId = $current_radio.closest('.clsProductPriceItem').find('.PayOutStandingInvoices').attr('data-groupmembershiptypeid');
        marketingEntityType = 1;
    }
    //#21208
    else if ($('#hdnMarketingEntityType').val() != '' && $('#hdnMarketingEntityType').val() == 2) {
        marketingEntityId = $("#hdnMarketingEntityId").val();
        marketingEntityType = $("#hdnMarketingEntityType").val();
    }

    if (isGroupPendingPaymentWithProduct) {
        priceType = 'MembershipPrice';
    }


    var listCart = [];
    if (priceType != "AdditionalPrice") {
        listCart.push({
            "productId": ProductId, "productPriceId": productPriceId, "EventTimeId": TimeId, "productPrice": productPrice,
            "quantity": Quantity, "priceType": priceType, "MarketingEntityType": marketingEntityType, "MarketingEntityId": marketingEntityId, "SwapOrderItemId": SwapOrderItemId, "RelatedProductId": relatedProductId,
            "RegistrantTypeOrderItemId": (registrantTypeOrderItemId && !isNaN(registrantTypeOrderItemId) ? registrantTypeOrderItemId : 0),
            "IsAdditionalItemChecked": isAdditionalItemChecked, "additionalprice": additionalprice,
            "MarketingEntityId": marketingEntityId,
            "MarketingEntityType": marketingEntityType,
            "productDiscountId": productDiscountId, "IsDiscountProduct": isDiscountProduct,
        });
    }

    if (additionalItemChecked && !isGroupPendingPaymentWithProduct) {
        isAdditionalItemChecked = true;
        additionalprice = $('input[class=clsAdditionalprice]:checked').attr('data-value');
        var additionalPriceTimeId = $('input[class=clsAdditionalprice]:checked').attr('data-eventid');
        listCart.push({
            "productId": ProductId, "productPriceId": productPriceId, "EventTimeId": additionalPriceTimeId, "productPrice": productPrice,
            "quantity": Quantity, "priceType": priceType, "IsAdditionalItemChecked": isAdditionalItemChecked, "additionalprice": additionalprice,
            "IsAddOnProduct": false
        });
    }

    //Add Related Add On Products
    if (!isGroupPendingPaymentWithProduct) {
        $('.clsRelatedProduct:checked').each(function (i) {
            listCart.push({
                "productId": $(this).attr("data-productId"), "EventTimeId": $(this).attr("data-eventTimeId"),
                "priceType": addOnPriceType, "productPrice": $(this).attr("data-ProductPrice"), "quantity": 1,
                "IsAddOnProduct": true, "RelatedProductId": $(this).attr("data-relatedproductid")
            });
        });
    }

    //12842: Registration Types - Registration Question Sets.
    if (productPriceId && Number(productPriceId) > 0 && !registrantTypeOrderItemId && productregistranttypeId > 0) {
        var isQuestionExist = IsRegistrantTypeQuestionSetAvailable(productPriceId, TimeId, ProductId, productTypeId);
        if (isQuestionExist) {
            $("#dvAcknowledgePopup").css("z-index", "0");
            OpenRegistrantTypeQuestionSetPopup(ProductId, productPriceId, priceType, 0, 0, 0, false, 0, false, '', '', 0, false, true);
            return false;
        }
    }
    else {
        $("#dvAcknowledgePopup").css("z-index", "");
    }


    var agendaAnswer = $("#hdnAgendaAnswer").val();
    var isAgenda = $('#hdnisExistAgendaonCart' + ProductId).val();
    if ((isAgenda != undefined) && (isAgenda == 1) && (agendaAnswer == undefined || agendaAnswer == '' || agendaAnswer == "")) {
        $.ajax({
            type: "POST",
            url: "/Items/IsOpenAgendaPopup",
            dataType: "json",
            data: {
                'productId': ProductId,
                'productPriceId': productPriceId,
                'entityType': entitytype
            },
            success: function (data) {
                if (data != undefined && data == true) {
                    $("#dvAcknowledgePopup").css("z-index", "0");
                    OpenAgendaPopup(ProductId, productPrice, entitytype, productPriceId, registrantTypeOrderItemId, priceType, false, true, chkPurchaserForRegistrant, isRegistrantRequestInfo);
                    return false;
                }
                else {
                    AddProductToCart(listCart, ProductId, true);
                }
            },
            error: function (data) {
                $("#divProgress").hide();
                alert('Error! Please try again later.');
            }
        });
    }
    else {
        $("#dvAcknowledgePopup").css("z-index", "");
        AddProductToCart(listCart, ProductId, true);
    }
}

//Commented because of firing double click event on delete documents in classified ad form.
//$("body").on("click", ".delDocuments", function () {
//    if (confirm("Are you sure, you want to remove documents?")) {

//        var documentId = $(this).attr('data-migrationid');
//        var entityType = "ClassifiedAdsPosting";

//        $.post("/Search/DeleteDocuments", { documentId: documentId, entityType: entityType }, function (response) {
//            if (response != null) {

//            }
//        });
//    }
//});


//For Customer Custom Field 
$("body").on("click", ".delCustomFieldDocuments", function () {
    if (confirm("Are you sure, you want to remove documents?")) {
        var documentId = $(this).attr('data-migrationid');
        var questionId = $(this).attr('data-questionid');
        var answerId = $(this).attr('data-answerid');
        var tempCustomerId = $(this).attr('data-temp-customerid');
        var entityType = 'CustomerCustomFieldUpload';
        $.post("/Account/DeleteDocuments", { documentId: documentId, entityType: entityType }, function (response) {
            if (response != null) {
                loadDocuments(answerId, questionId, entityType, null, tempCustomerId);
            }
        });
    }
});

function loadDocuments(answerId, questionId, entityType, question, customerId) {
    var Question = encodeURIComponent(question);
    var CustomerID = encodeURIComponent(customerId);
    var url = "/Account/GetCustomerDocumentList?answerId=" + answerId + "&questionId=" + questionId + "&customerId=" + CustomerID + "&entityType=" + entityType + "&question=" + Question;
    $("#grid-list-MembershipAnswerDocuments_" + questionId).load(url, function () {
    }).prepend("<p class='loaderTxt'>Please wait ...</p>");
}

//  Search Terms
var elt = $('#txtSearchTerm');

var hdSearchTerms = $("#hdSearchTerms").val() ? JSON.parse($("#hdSearchTerms").val()) : null;
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;");

var isSearchTextTermRemoved = false; // Flag to track if search text term removed

$('#txtSearchTerm').on('itemRemoved', function (event) {
    if (event.item.sst == 'cat') {
        var category = $("#AdCategoryIds").val();
        categoryList = category.split(',');

        var deletedCategoryIndex = categoryList.indexOf(event.item.id);
        categoryList.splice(deletedCategoryIndex, 1);
        $("#AdCategoryIds").val(categoryList.join(','));

        var selectedAdsCategory = $('#AdCategoryIds').val() || [];
        if (selectedAdsCategory.length > 0) {
            var selectedList = selectedAdsCategory.split(',');
            $('#AdCategoryFilter').val(selectedList).multiselect('refresh');
        }
        else {
            $('#AdCategoryFilter').val([]).multiselect('refresh');
        }

        getSearchResult();
    }
    else if (event.item.sst == 'searchText') {
        isSearchTextTermRemoved = true;
        $("#keyword").val("");
        getSearchResult();
        isSearchTextTermRemoved = false;
    }
    else 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').prop('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();
        var chk = $('.chkCreditTypes[value="' + removeItem + '"]');
        chk.trigger('click');
    } else if (event.item.sst == 'certJurisdictionIdsSearch') {
        var removeItem = event.item.id.toString();
        var chk = $('.chkCertJurisdictions[value="' + removeItem + '"]');
        chk.trigger('click');
    } else if (event.item.sst == 'searchClearAll') {
        $("#hdSearchTerms, #keyword, #txtSearch, #txtProductSearch,#txtZipCode, #txtStartingOnOrAfter, #txtStartingOnOrBefore, #txtGeoSearchByCity, #hdnLongitude, #hdnLatitude, #txtZipCode").val(""); $('.chkTopicAreas, .chkProductType, .chkCategory, .chkMonthDates, .chkClosedCaptioning, .clsChkbState, .clsChkbCity, .chkRegistrantTypes, .chkCreditTypes, .chkCertJurisdictions').prop('checked', false);
        getSearchResult();
    }
});

function getSearchResult(latestSelecetedFacet = "", currentIndex = 1, scrollPage = false) {

    if (scrollPage)
        $("#divProgress").hide();
    else
        $("#divProgress").show();

    var Url = '';

    if ($('body').find('#AdCategoryIds').length > 0) {
        var Url = '?keyword=' + $("#keyword").val();
        Url = Url + '&pagevalue=' + $("#pagevalue").val();
        Url = Url + "&page=" + $("#page").val();
        Url = Url + "&SortDir=" + $("#SortDir").val();
        Url = Url + "&SortCol=" + $("#SortCol").val();
        var adsCategory = $('#AdCategoryFilter').val() || [];
        if (adsCategory.length > 0) {
            $('#AdCategoryIds').val(adsCategory);
            $("#divProgress").show();
            Url += '&adCategoryIds=' + adsCategory;
        }
        window.location = "/classifiedads/searchadsposting" + Url;
    }
    else {
        if ($("#CustomerMembershipTypeId").val() > 0 || $("#MembershipTypeId").val() > 0 || $("#CurrentTabId").val()) {
            Url = Url + '?customerMembershipId=' + $("#CustomerMembershipTypeId").val();
            Url = Url + '&membershipTypeId=' + $("#MembershipTypeId").val();
            Url = Url + '&tabId=' + $("#CurrentTabId").val();
        }
        Url = Url + ($("#CustomerMembershipTypeId").val() > 0 ? '&pagesize=' + $("#drpPageSize").val() : '?pagesize=25');
        Url = Url + "&sortby=" + $("#drpSortBy").val();
        Url = Url + "&myProductFilter=" + $("#drpMyProductFilter").val();
        
        //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;
        }
        else if ($("#topicArea").val()) {
            Url = Url + "&topicArea=" + $("#topicArea").val();
        }

        //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 = $("#hdSearchTerms").val() ? 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
        //get category
        var selectedCreditTypes = $('input[name=SelectedCreditTypes]:checked');
        var creditTypes = "";
        selectedCreditTypes.each(function () {
            creditTypes += $(this).attr("value") + ","
        });
        creditTypes = creditTypes.substring(0, creditTypes.length - 1);
        if (creditTypes != "") {
            Url = Url + "&CertCreditTypeIds=" + creditTypes;
        }

        //#22351
        var certJurisdicationsTypes = $('input[name=SelectedCertJurisdictions]:checked');
        var certJurisdications = "";
        certJurisdicationsTypes.each(function () {
            certJurisdications += $(this).attr("value") + ","
        });
        certJurisdications = certJurisdications.substring(0, certJurisdications.length - 1);
        if (certJurisdications != "") {
            Url += '&CertJurisdictionIds=' + certJurisdications;
        }

        if ($("#tag").val()) {
            Url += '&tag=' + $("#tag").val();
        }

        if ($("#drpProductDisplayType").val() == "3")
            window.location = "/calendar" + Url;
        else {
            if ($("#CustomerMembershipTypeId").val() || $("#MembershipTypeId").val() || $("#CurrentTabId").val()) { // group search page
                window.location.href = '/group/searchproducts/' + Url;
            }
            else {// catalog search page
                if (latestSelecetedFacet != "") {
                    Url = Url + "&latestSelection=" + latestSelecetedFacet;
                }
                var isChange = currentIndex != Number($("#hdnPageNo").val());

                if (isChange && scrollPage) { //for lazy loading in search page
                    Url = Url + '&page=' + currentIndex;
                    var bundleIds = $('#bundleIds').val();
                    if (bundleIds.endsWith(',')) { // remove last unnecessary comma
                        bundleIds = bundleIds.slice(0, -1);
                    }
                    Url = Url + '&bundleIds= ' + bundleIds;
                    $('#bundleIds').remove();
                    const querystring_url = new URL('http://search' + Url);
                    const params = new URLSearchParams(querystring_url.search);
                    $('#hdnIsWaitingForResponse').val('true');

                    var keys = [
                        'search', 'category', 'topicArea', 'productType', 'sst', 'eventdate', 'tag', 'dateStartingOnOrAfter',
                        'dateStartingOnOrBefore', 'displaytype', 'page', 'pagesize', 'pagewidgetid', 'sortby', 'isClosedCaptioning', 'fromDuration', 'toDuration', 'certCreditType', 'zipCode', 'distanceMiles', 'subscriptionId', 'cityVenueIds', 'stateVenueIds', 'othermediatype', 'discountId', 'productGroupCampaignId', 'geoSearchByCity', 'registrantProductTypeIds', 'gioLat', 'gioLong', 'CertCreditTypeIds', 'CertJurisdictionIds', 'latestSelection', 'sortbtnId', 'pagewidgetid', 'isShowMyProductFilter', 'myProductFilter', 'bundleIds'
                    ];
                    $('#hdnPageNo').val(currentIndex);
                    const requestData = Object.fromEntries(keys.map(key => [key, params.get(key)]));

                    $.ajax({
                        url: '/search/ProductList',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(requestData),
                        beforeSend: function () {
                            // Show loader here
                            $(".searchProductList").append('<div id="productSearchLoader" style="display:flex; justify-content:center;"><p class= "loaderTxt" > loading ...</p></div>');
                        },
                        success: function (data) {

                            //$('.divsearchterms').addClass('hidden');
                            if (data != undefined && data != null && data.trim() != '') {
                                $(".searchProductList").append(data);
                                $("#hdnHasNextPage").val('true');
                            } else {
                                $("#hdnHasNextPage").val('false');
                            }
                            $('#hdnIsWaitingForResponse').val('false');
                            //addSearchTags(urlQuerstring);
                            $("#productSearchLoader").remove(); // Hide the loader after the request is complete
                        },
                        error: function (xhr, status, error) {
                            console.error('Error:', error);
                        }
                    });
                }
                else
                    window.location = "/search" + Url;
            }
        }
    }
}

$("body").on('click', '.popEditAdDetails', function () {
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'popEditPosting'
    });
    return false;
});

function closeClassifiedAdPostingPopup() {
    $.magnificPopup.close();
    window.location.reload(true)

}

//#5633846136
function createFreeClassifiedAd(classifiedFeePlanId) {

    $.ajax({
        url: '/classifiedads/CreateFreeAd',
        type: 'POST',
        data: { classifiedFeePlanId: classifiedFeePlanId },
        success: function (data) {
            // Handle the JSON response
            var classifiedFeePlanId = data.ClassifiedFeePlanId;
            var orderItemId = data.OrderItemId;
            var orderId = data.OrderId;

            // Redirect to the specified URL
            window.location.href = "/classifiedads/classifiedadscategories?classifiedFeePlanId=" + classifiedFeePlanId + "&orderItemId=" + orderItemId + "&orderId=" + orderId;
        },
        error: function (error) {
        }
    });
}

function userIsAuthenticated() {
    var isAuthenticated = false;
    // Make an AJAX request to check the session status
    $.ajax({
        url: '/classifiedads/CheckSessionStatus',
        type: 'GET',
        async: false,
        success: function (data) {
            isAuthenticated = data.isAuthenticated;
        },
        error: function (error) {
        }
    });

    return isAuthenticated;
}

function redirectToLogin() {
    var returnUrl = window.location.href;
    window.location.href = "/account/login?returnUrl=" + encodeURIComponent(returnUrl);
}

function addProductToBundleTypeFive(productId, bundleproductId, eventTimeId, status, priceId, otherProductId) {
    $.ajax({
        type: "POST",
        url: BUNDLE_TYPE_5_ADD_CUSTOMER_PRODUCT,
        dataType: "json",
        data: {
            'productId': productId,
            'bundleProductId': bundleproductId,
            'eventTimeId': eventTimeId,
            'status': status,
            'priceId': priceId,
            'otherProductId': otherProductId
        },
        success: function (data) {
            if (data.Message != null && data.Message != "") {
                var myContent = data.Message;
                if (isHTML(myContent)) {
                    alert($(myContent).text());
                }
                else {
                    alert(myContent);
                }
            }
            else if (data.IsCECreditPrice) {//mantis #21829
                parent.displayPurchaseCEMessage(productId, data.CECreditPrice, 3, data.CustomerBundleId);
            }
            parent.LoadCustomerBundleProductList(data.Message == "");
        },
        error: function (data) {
            $('#divProgress').hide();
            alert('Error! Please try again later.');
        }
    });
}
$("body").on("change", ".dropCompanyName", function () {
    var value = $(this).val();
    if ($(this).parents(".additionalStandardFields").length == 0) //bugfix:81460 
    {
        if (value != undefined && value == "-1") {
            $(".clsNewCompany").show();
        } else {
            $(".clsNewCompany").hide();
            $("#OtherCompanyName").val('');

        }
    }
});

var saveAddToCartProducts = function (params) {

    let registrantTypeOrderItemId = params.registrantTypeOrderItemId;
    let groupProductPricecId = params.groupProductPricecId;

    var ProductId = '0';
    var ClassifiedFeePlanId = '@Model.ClassifiedFeePlanId';
    var $current_radio = $('.rdbprice input[type=radio]:checked, .rdbprice input[type=checkbox]:checked');
    var chkRadioPrice = $('.rdbprice input[type=radio]:checked, .rdbprice input[type=checkbox]:checked');
    var Price = $current_radio.attr('value');
    var PriceData = Price != undefined && Price != null ? Price.split(',') : 0;
    var productPriceId = PriceData[0];
    var productPrice = PriceData[1];
    var Quantity = 1;
    var priceType = $current_radio.attr("data-priceType");
    var pagetype = '';
    var pageno = 1;
    var sortby = 11;
    var productDiscountId = $("#hdnProductDiscountId").val();
    var SwapOrderItemId = $("#hdnSwapOrderItemId").val();

    var isDiscountProduct = false;
    if (productDiscountId && productDiscountId > 0) {
        isDiscountProduct = true;
        priceType = "DiscountPrice";
    }

    if (parent.$("#pageType").val() != undefined) {
        pagetype = parent.$("#pageType").val();
    }

    if (parent.$("#pageno").val() != undefined) {
        pageno = parent.$("#pageno").val();
    }
    if (parent.$("#sortby").val() != undefined) {
        sortby = parent.$("#sortby").val();
    }

    var listCart = [];

    listCart.push({
        "productId": parseInt(ProductId),
        "ClassifiedFeePlanId": parseInt(ClassifiedFeePlanId),
        "productPriceId": productPriceId,
        "productPrice": parseInt(productPrice),
        "quantity": Quantity,
        "priceType": priceType,
        "SwapOrderItemId": SwapOrderItemId,
        "RegistrantTypeOrderItemId": (registrantTypeOrderItemId && !isNaN(registrantTypeOrderItemId) ? registrantTypeOrderItemId : 0)
    });
}

$("body").on('click', '.clsbetterPriceForBundle', function () {

    var bundleId = $(this).attr("data-bundleId");
    var bundlePermalink = $(this).attr("data-bundlePermalink");
    var bundleLabel = $(this).attr("data-bundleLabel");
    var registrantCustomerId = $(this).attr("data-registrantCustomerId");

    $.confirm({
        title: 'Better price available',
        boxWidth: '600px',
        boxHeight: '700px',
        useBootstrap: true,
        icon: 'fa fa-warning',
        async: false,
        animateFromElement: false,
        animation: 'scale',
        content: '<hr><label>There may be a better price available for you on this <b>' + bundleLabel + '</b>. To change your prices, you will be taken to the bundle to review and reselect.<br> If you would like to keep the <b>' + bundleLabel + '</b> as it is, choose to make no change instead.</label><hr>',
        buttons: {
            CONTINUE: {
                text: 'Change Price',
                btnClass: 'btn btn-success',
                action: function () {
                    window.location.href = bundlePermalink + '?isForBundlePrice=true' + (registrantCustomerId > 0 ? '&registrantCustomerId=' + registrantCustomerId : '');
                },
            },
            Close: {
                text: 'Make No Change',
                btnClass: 'btn btn-default',
                action: function () {
                   // $(".betterPriceAlert").remove();
                },
            }
        }
    });
});

$("body").on('click', '.pop600', function () {
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'pop600MainClass'
    });
    return false;
});

function OpenProductAgendaPopup(productId, orderItemId, productPrice, entitytype, productPriceId, isDisplayRequestInfo, isFromBundle, bundleTypeId = 0, isFromRegistrantConfirmation = true, chkPurchaserForRegistrant = false, isRegistrantRequestInfo = false) {
    $.magnificPopup.open({
        items: {
            src: AGENDA_PRODUCT_POPUP + '?productId=' + productId + '&orderItemId=' + orderItemId + "&productPrice=" + productPrice + "&entityType=" + entitytype + "&discountId=" + productPriceId + "&isDisplayRequestInfo=" + isDisplayRequestInfo + '&isFromRegistrantConfirmation=' + isFromRegistrantConfirmation + "&isFromBundle=" + isFromBundle + "&bundleTypeId=" + bundleTypeId + "&chkPurchaserForRegistrant=" + chkPurchaserForRegistrant + "&isRegistrantRequestInfo=" + isRegistrantRequestInfo
        },
        type: 'iframe',
        closeOnBgClick: false,
        showCloseBtn: ((bundleTypeId != undefined && Number(bundleTypeId) > 0) || !isFromRegistrantConfirmation) ? true : false,
        mainClass: 'CustomPop',
        callbacks: {
            close: function () {
                if (bundleTypeId != undefined && Number(bundleTypeId) > 0) {
                    isValidateRegistrantQuestions = false;
                    listProductsForBundle = [];
                    arrRandomOrderItemId = [];
                }
            }
        }
    });
    return false;
}

var IsAgendaForProductAvailable = function (discountId, productId, entityType) {
    var isEnable = false;
    $.ajax({
        type: "GET",
        url: "/Items/IsOpenAgendaPopup",
        dataType: "json",
        async: false,
        data: {
            'productId': productId,
            'productPriceId': discountId,
            "entityType": entityType
        },
        success: function (data) {
            if (data != undefined && data == true) {
                isEnable = true;
            }
            else {
                isEnable = false;
            }
        },
        error: function (data) {
            isEnable = false;
        }
    });
    return isEnable;
}

function referralAddressMethod(editAddressPopupType, clientId) {
    $.magnificPopup.close();
    $(".grid-list-address").each(function () {

        var isRequired = ($(this).attr("data-isrequired") || "").toLowerCase() == "true";
        var questionId = $(this).attr("data-questionid") || "";
        var referralClientId = clientId > 0 ? clientId : $(this).attr("data-referralClientId")
        $(this).load("/referralservice/getcustomeraddresslist" + '?editAddressPopupType=' + editAddressPopupType + '&referralClientId=' + referralClientId, function () {
            $('.verifiedLabel[data-toggle="tooltip"]').tooltip();

            var selectedValue = $('#IsAddressBlockQuestion' + questionId).attr("data-selectedvalue");
            $("input[name=addressRadio" + questionId + "][value='" + selectedValue + "']").prop("checked", true);

            $(".divAddressListLayout:visible").each(function () {
                $(this).height($(this).outerHeight());
                $(".addresslist-card", this).height($(".addresslist-card", this).outerHeight());
            });
            loadAlertToolTip();
        }).prepend("<p class='loaderTxt'>Please wait ...</p>");
    });
    if ($("#divExistingAddress").length > 0) {
        $("#divExistingAddress").load("/referralservice/getreferralclientexistingaddresses" + '?editAddressPopupType=' + editAddressPopupType + '&clientId=' + clientId).prepend("<p class='loaderTxt'>Please wait ...</p>");
    }
}

$("body").on('click', '.csIphone', function () {
    var viewerUrl = $(this).attr('data-href') == undefined ? $(this).attr('href') : $(this).attr('data-href');
    var programRegistrantId = $(this).attr('data-ProgramRegistrantId');
    var btntarget = $(this).attr('target');
    var ExistAttendanceRequirment = $(this).attr('data-ExistAttendanceRequirment');
    if (ExistAttendanceRequirment != undefined && ExistAttendanceRequirment == "true") {
        $('.iphone-questionrequirement-message').show();
        $('.iphone-participationcode-message').hide();
    } else {
        $('.iphone-questionrequirement-message').hide();
        $('.iphone-participationcode-message').show();
    }


    $('#divIphoneMessage').appendTo("body").modal('show');
    $("#divIphoneMessage .modal-footer").find('a').attr('data-href', viewerUrl).attr('target', btntarget);
    $("#divIphoneMessage .modal-footer").find('a').addClass('csViewer').attr('data-ProgramRegistrantId', programRegistrantId);
});

// Monday #6063805421
$("body").on('click', '.firefoxlaunch', function () {
    var viewerUrl = $(this).attr('data-href') == undefined ? $(this).attr('href') : $(this).attr('data-href');
    var sTarget = $(this).attr('target');

    if (popup == null) {
        popup = window.open(viewerUrl, sTarget);
    } else {
        popup.close();
        popup = window.open(viewerUrl, sTarget);
    }
})

var openAgendaPopUpAfterRegistration = function (orderItemId, isAgendaExists, chkPurchaserForRegistrant, registrantQuestionSubmissionType) {
    if (isAgendaExists && isAgendaExists.toString().toLocaleLowerCase() == 'true' && typeof OpenProductAgendaPopup == "function") {
        isRegistrationComplete = true;
        var element = $("#clsEditSelection" + orderItemId);
        var isRegistrantRequestInfo = registrantQuestionSubmissionType == 2 ? true : false;
        editSelection(element, chkPurchaserForRegistrant, isRegistrantRequestInfo);
    }
    else {
        $.magnificPopup.close();
    }
}

function loadCustomerCustomAddressBlock(tempCustomerId = 0, isFromParent = false) {
    const context = isFromParent ? parent.$ : $;
    const matchingBlocks = context("[id^='grid-list-CustomerCustomAddressBlock_']");

    if (matchingBlocks.length > 0) {
        matchingBlocks.each(function () {
            const questionId = $(this).data("questionid");
            const url = `/Account/GetCustomerCustomAddressBlock?questionId=${questionId}&tempCustomerId=${tempCustomerId}`;
            const $target = context(`#grid-list-CustomerCustomAddressBlock_${questionId}`);

            $target.prepend("<p class='loaderTxt'>Please wait ...</p>");
            $target.load(url, function (response, status, xhr) {
            });
        });
    }

    if (isFromParent) {
        parent.$.magnificPopup.close();
    } else {
        $.magnificPopup.close();
    }
}

$("body").on("click", "#btnSearch, #btnProductSearch", function () { //#7016454545
    var search = "";
    search = $("#txtSearch").val() || $("#txtProductSearch").val();
    var searchPages = ['search', 'discount', 'productgroupcampaigns', 'group'];
    if (search.trim().length > 0) {
        if (searchPages.includes(window.location.pathname.split('/')[1].toLowerCase())) {
            getSearchResult("SearchText");
        }
        else {
            window.location.href = '/search?search=' + encodeURIComponent(search);
        }
    }
});
$("body").on("click", ".loadMoreProduct", function () {
    var parentDiv = $(this).closest('.divWidget');
    var url = $(this).attr("data-href")
    $(this).remove();

    $("<div>").load(url, function () {
        var $seminars = $(this);
        parentDiv.append($seminars.html());
    })
});
$(window).scroll(function () {
    $(".loadMoreProduct").each(function () {
        if (isElementVisibleOnScreen($(this))) {
            $(this).trigger('click');
        }
    });
});

$("body").on('click', '.cancelMembership', function () {
    $.magnificPopup.open({
        items: {
            src: $(this).attr("href")
        },
        type: 'iframe',
        closeOnBgClick: false,
        mainClass: 'popCancelGroup'
    });
    return false;
});

function TransferOwnershipCallBack(IsCanceled, pagename, formid, buttonid, OldCompanyName) {
    if (pagename == 'EditCustomer') {
        $("#hdnIsCompanyChanged").val(true);
        if (IsCanceled) {
            $('#CompanyName').val(OldCompanyName);
            $('#frmEditCustomer').submit();
        } else {
            $('#frmEditCustomer').submit();
        }
    } else if (pagename == 'ParentQuestionSet') {
        if (IsCanceled) {
            $("select.dropQsetCompanyName").val(OldCompanyName).trigger('change');
            $(".autoCompleteCompanyName").val(OldCompanyName);
            $("#" + formid).submit();
        } else {
            $("#companyChange").val('1');
            $("#" + formid).submit();
        }
    } else if (pagename == 'ChildQueastionSet') {
        if (IsCanceled) {
            $(".autoCompleteCompanyName").val(OldCompanyName);
            SubmitForm(buttonid, formid);
        } else {
            SubmitForm(buttonid, formid);
        }
    }
}

$(document).keydown(function (event) {
    if (event.target.id === 'Address' && event.key === 'Enter') {
        event.preventDefault();
        return false;
    }
});

$("#btnDateFilterSearch").on("click", function () {
    getSearchResult("DateFilter");
});

$("body").on("click", ".chkCreditTypes, .chkCertJurisdictions", function () {
    getSearchResult();
});

$("body").on("change", ".topFilters #drpPageSize", function () {
    getSearchResult();
});

$("#btnGeoSearchByCity").on("click", function () {
    getSearchResult();
});

$("body").on("click", ".chkClosedCaptioning", function () {
    if ($("#txtsst").val() == "")
        $("#txtsst").val("cc");
    getSearchResult("TranscriptCount");
});

$("#btnDurationSearch").on("click", function () {
    getSearchResult();
});

$("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");
    }

    if (getParameterByName('sortby') == "" && (pdtype == 1 || pdtype == 2 || pdtype == 3)) {
        $("#drpSortBy").val("51");
    }
    
    getSearchResult("ProductTypeId");
});

$("body").on("click", ".chkCategory", function () {
    if ($("#txtsst").val() == "")
        $("#txtsst").val("c");
    getSearchResult("Categories"); //21954
});

$("body").on("click", ".chkMonthDates", function () {
    if ($("#txtsst").val() == "")
        $("#txtsst").val("d");
    getSearchResult("MonthStartDates");
});

$("body").on("click", ".chkTopicAreas", function () {
    if ($("#txtsst").val() == "")
        $("#txtsst").val("t");
    getSearchResult("TopicAreas");
});

$("body").on("click", ".clsChkbState", function () {
    if ($("#txtsst").val() == "")
        $("#txtsst").val("liveEventState");
    getSearchResult("VenueIdToState");
});
$("body").on("click", ".clsChkbCity", function () {
    if ($("#txtsst").val() == "")
        $("#txtsst").val("liveEventCity");
    getSearchResult("IdtoCityWithAbbreviationtoState");
});

$("body").on("click", ".rblSubscription", function () {
    if ($("#txtsst").val() == "")
        $("#txtsst").val("ss");
    getSearchResult();
});

$("body").on('keyup', '.txtSearch', function () {
    searchSidebarMenu($(this));
});

function searchSidebarMenu(elSearchTextbox) {
    var keyword = elSearchTextbox.val();
    $(elSearchTextbox).closest("ul").find("li").show();
    if (keyword) {
        $(elSearchTextbox).closest("ul").find("li").filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(keyword.toLowerCase().trim()) > -1);
        });
    }
}

$("body").on('click', '.clearSearch', function () {
    var elSearchTextbox = $(this).closest('ul').find('.txtSearch');
    $(elSearchTextbox).val('');
    searchSidebarMenu(elSearchTextbox);
});