$(document).ready(function () {

    window.scholarshipContainer = $('#scholarship');

    if (scholarshipContainer.length != 1) return;
    var baseApiUrl = "https://careercenter-api.azurewebsites.net/api/novi/";
    scholarshipContainer.empty();
    $('head').append("<link href='https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css' rel='stylesheet' />");

    $('head').append("<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css' integrity='sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==' crossorigin='anonymous' referrerpolicy='no-referrer' />");

    $('head').append("<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/paginationjs/2.1.5/pagination.css'    integrity='sha512-QmxybGIvkSI8+CGxkt5JAcGOKIzHDqBMs/hdemwisj4EeGLMXxCm9h8YgoCwIvndnuN1NdZxT4pdsesLXSaKaA=='    crossorigin='anonymous' referrerpolicy='no-referrer' />");

    let syncfusioncdn = '<link href="https://cdn.syncfusion.com/ej2/21.1.35/ej2-base/styles/material.css" rel="stylesheet" type="text/css"/>' +
        '<link href="https://cdn.syncfusion.com/ej2/21.1.35/ej2-popups/styles/material.css" rel="stylesheet" type="text/css"/>' +
        '<!-- Essential JS 2 Grid\'s material theme -->' +
        '<link href="https://cdn.syncfusion.com/ej2/21.1.35/ej2-grids/styles/material.css" rel="stylesheet" type="text/css"/>' +
        '<!-- Essential JS 2 Grid\'s dependent script -->' +
        '<!-- Essential JS 2 Grid\'s global script -->' +
        '<link href="https://cdn.syncfusion.com/js/web/16.4.52/ej.web.all.min.css" rel="stylesheet" />';

    $('head').append(syncfusioncdn);

   

    jQuery.cachedScript = function (url, options) {
        // from: https://api.jquery.com/jQuery.getScript/
        options = $.extend(options || {}, {
            dataType: "script",
            cache: true,
            url: url
        });
        return jQuery.ajax(options);
    };


    //only the list page has prerequsites.  for listpage use:
    //LoadSelect2() > LoadPagination() > LoadListPage()
    // we could run LoadSelect and LoadPagination in parallel, but that is more difficult to keep track of.
    //for the details page, just 
    //LoadDetailsPage() directly

    var loc = document.location.href;
    if (loc.toString().includes("www.wai.org")) {
        baseApiUrl = "https://wai-api.azurewebsites.net/api/novi/";
    }
    if (loc.indexOf('id') > -1) {
        LoadDetailsPage();
    } else {
        LoadSelect2();
    }

    async function LoadSelect2() {
        const baseScriptPromise = await $.cachedScript("https://cdn.syncfusion.com/ej2/21.1.35/ej2-base/dist/global/ej2-base.min.js").done(function (script, textStatus) {
        });

        const dataScriptPromise = await $.cachedScript("https://cdn.syncfusion.com/ej2/21.1.35/ej2-data/dist/global/ej2-data.min.js").done(function (script, textStatus) {
        });

        const popupsScriptPromise = await $.cachedScript("https://cdn.syncfusion.com/ej2/21.1.35/ej2-popups/dist/global/ej2-popups.min.js").done(function (script, textStatus) {
        });

        const gridsScriptPromise = await $.cachedScript("https://cdn.syncfusion.com/ej2/21.1.35/ej2-grids/dist/global/ej2-grids.min.js").done(function (script, textStatus) {
        });

        const webScriptPromise = await $.cachedScript("https://cdn.syncfusion.com/js/web/16.4.52/ej.grid.min.js").done(function (script, textStatus) {
        });

        const webLoadPromise = await $.cachedScript("https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js")
            .done(function (script, textStatus) {
            })
        await LoadPagination();

    }
    async function LoadPagination() {
        $.cachedScript("https://cdnjs.cloudflare.com/ajax/libs/paginationjs/2.1.5/pagination.min.js").done(function (script, textStatus) {
            console.log('LoadPagination ' + textStatus);
            LoadListPage();
        });
    }

    function LoadDetailsPage() {
        scholarshipContainer.append('<style> #scholarship {text-align:left;} #scholarship h3 {margin-top:0px;} #scholarship a.view-scholarship {margin-bottom:0!important; display: inline-block;} .label-style{margin-bottom:0px; font-family:"Lato" !important;}   .loader { border: 16px solid #f3f3f3; border-radius: 50%; border-top: 16px solid #3498db; width: 120px; height: 120px; -webkit-animation: spin 1s linear infinite; animation: spin 1s linear infinite; } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .label-inline { font-weight: 700; display: inline-block; margin-right: 2px; float: none; } .btn.btn-blue { background: #1086C7; border: 1px solid #1086C7; } .btn.btn-blue a { color: white; text-decoration: none; } .btn { border-radius: 50px; padding: 9px 40px; color: #FFFFFF; text-align: center; } .position-title { display: inline-block; vertical-align: middle; margin: 0 2em 0 0; } .inner-content{margin-bottom:0px !important;} .font { font-size: 15px; font-weight: 700; margin-bottom: 1em; color: white; } .font2 { font-size: 15px; font-weight: 700; margin-bottom: 1em; color: white; } .head{ margin: 0 auto; max-width: 1170px; padding: 0 15px; font-size: 36px; font-weight: 900; padding-left: 60px; } .subtitle-bottom { width: 100px; height: 4px; background: white; margin-top:40px; display: block; } h2{ margin-bottom: -35px !important; font-size: 35px; margin-top: 15px; color:white;}</style> ');

        var listUrl = location.href.replace(location.search, "").replace("##", "");
        var baseUrl = (window.location).href;
        var id = baseUrl.substring(baseUrl.lastIndexOf('=') + 1).replace("##", "");
        var memberUrl = window.location.protocol + '//' + window.location.hostname + '/scholarships-member-benefits';
        var offset = new Date().toLocaleDateString('en-GB');

        $.ajax({
            type: 'GET',
            url: baseApiUrl + 'GetScholarshipById?scholarshipId=' + id + "&epoch=" + offset,
            success: function (post) {
                if (post.jobId != 0) {
                    var returnURL = memberUrl;
                    if (window.isLogin == 'true')
                        returnURL = window.applicationURL + baseApiUrl + "AccessScholarshipApp?scholarshipId=" + post.id;



                    scholarshipContainer.append('<div style="display:flex;justify-content:space-between;text-align: center; border-bottom: 1px solid #FF7373; margin-top:20px;">' +
                        '    <a href="' + listUrl + '" ><div class="btn btn-blue  " style="background:transparent; border:none; color: #ff7373; font-size:16px; padding-left:0px;"><i class="fa fa-arrow-circle-left "  style="margin-right:6px"></i>RETURN TO LISTINGS</div></a>' +
                        '    <a href="' + returnURL + '"  target="_blank"><div id="apply" class="btn btn-blue " style="background:transparent; border:none; color: #ff7373; font-size:16px; padding-right:0px;">APPLY<i class="fa fa-arrow-circle-right" style=" margin-left:6px"></i></div></a>' +
                        '    </div>' +
                        '<div style="margin: 0 auto;padding: 0 0px;padding-top: 25px">' +
                        '<div> <h3 class="title"> <span id="titleInfo">'
                        + post.title + '</span> </h3></div>'
                        + '<div style="font-size: 15px;">' +
                        ' <div class="position-title">' +
                        //'<i class="fa-solid fa-money-bill-1-wave"></i>' +
                        '            <div class="label-inline">Category:&nbsp;</div>' +
                        '            <span id="estimateValue"> ' + post.category + ' </span>' +
                        '        </div>' +
                        ' </div>' +

                        '    <div style="font-size: 15px;">' +
                        '        <div class="position-title">' +
                        '            <div class="label-inline">Estimated Value:&nbsp;</div>' +
                        '            <span id="estimateValue"> ' + post.estimatedValue + ' </span>' +
                        '        </div>' +
                        '    </div>' +
                        '    <div style="font-size: 15px;">' +
                        '        <div class="company">' +
                        '            <div class="label-inline">Available Scholarship:&nbsp;</div>' +
                        '            <span id="avlScholarship"> ' + post.numberAvailable + '</span>' +
                        '        </div>' +
                        '    </div>' +
                        '    <div style="font-size: 15px;">' +
                        '        <div class="company">' +
                        '            <div class="label-inline">Scholarship Year:&nbsp;</div>' +
                        '            <span id="comInfo"> ' + post.year + '</span>' +
                        '        </div>' +
                        '    </div>' +
                        '       <br/>' +
                        '    <div style="color: #636975; font-size: 16px; font-family: Lato,Helvetica,Arial,sans-serif; font-weight: 300; line-height: 24px; word-break:break-word;">' +
                        '        ' + post.fullDescription + '' +
                        '    </div>' +
                        '    <div style="margin-top: 35px; display:flex;justify-content:space-between;text-align: center; border-bottom: 1px solid #FF7373; border-top: 1px solid #FF7373;">' +
                        '    <a href="' + listUrl + '" ><div class="btn btn-blue " style="background:transparent; border:none; color: #ff7373; font-size:16px; padding-left:0px;"><i class="fa fa-arrow-circle-left "  style="margin-right:6px"></i>RETURN TO LISTINGS</div></a>' +
                        '    <a href="' + returnURL + '"  target="_blank"><div id="apply" class="btn btn-blue" style="background:transparent; border:none; color: #ff7373; font-size:16px; padding-right:0px;">APPLY<i class="fa fa-arrow-circle-right "  style="margin-left:6px"></i></div></a>' +
                        '    </div>' +
                        '</div>');
                }
            }
        });

    }

    function LoadListPage() {

        var scholarshipContainer = window.scholarshipContainer;
        scholarshipContainer.append('<style>body{font-family:"Lato" !important;} .e-grid{font-family:"Lato" !important;} .e-headertext{font-weight:900;color:black} .search-bar{height:30px; width:100%; }.loader { border: 16px solid #f3f3f3; border-radius: 50%; border-top: 16px solid #3498db; width: 120px; height: 120px; -webkit-animation: spin 1s linear infinite; animation: spin 1s linear infinite; } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .ml-1 { margin-left: 36px; margin-top: 15px; } .select2-selection__rendered { line-height: 31px !important; } .select2-container .select2-selection--single { height: 30px !important;  border-radius: 0px } .select2-selection__arrow { margin-right: 0px !important; height: 34px !important; } .select2-container--default .select2-selection--single .select2-selection__arrow{ width:40px; !important; } .font { font-size: 15px; font-weight: 700; margin-bottom: 1em; color: white; } .ddl { width: 200px !important; height: 35px !important; border-radius: 25px !important;} .mt-30 { margin-top: 30px } .mt-10 { margin-top: 10px } body { font-family: Roboto, sans-serif; font-size: 14px; line-height: 18px; background: #f4f4f4; } .list-wrapper { padding: 15px; overflow: hidden; } .list-item { border: 1px solid #EEE; background: #FFF; margin-bottom: 10px; padding: 10px; box-shadow: 0px 0px 10px 0px #EEE; } .list-item h4 { color: #FF7182; font-size: 18px; margin: 0 0 5px; } .list-item p { margin: 0; } .simple-pagination ul { margin: 0 0 20px; padding: 0; list-style: none; text-align: center; } .simple-pagination li { display: inline-block; margin-right: 5px; } .simple-pagination li a, .simple-pagination li span { color: #666; padding: 5px 10px; text-decoration: none; border: 1px solid #EEE; background-color: #FFF; box-shadow: 0px 0px 10px 0px #EEE; } .simple-pagination .current { color: #FFF; background-color: #FF7182; border-color: #FF7182; } .simple-pagination .prev.current, .simple-pagination .next.current { background: #e04e60; } .paginationjs{ display: flex; justify-content: flex-start; margin-top:10px; width:50%;} .title h2, .title h3 { font-size: 20px; color: #505662; margin: 0; padding: 0; } .title a, .title a { color: #505662; text-decoration: none; } .position-title { display: inline-block; vertical-align: middle; margin: 0 2em 0 0; } .label-inline { font-weight: 700; display: inline-block; margin-right: 2px; float: none; } .position-title, .company { display: inline-block; vertical-align: middle; margin: 0 2em 0 0; } .subtitle-bottom { width: 100px; height: 4px; background: #E08147; margin: 1.2em 0 2.5em; display: block; } .btn.btn-blue { background: #1086C7; border: 1px solid #1086C7; } .btn.btn-blue a { color: white; text-decoration: none; } .btn { -webkit-border-radius: 50px; -moz-border-radius: 50px; font-family:"Lato" !important; border-radius: 50px; padding: 0.8em 3em; color: #FFFFFF; text-align: center; -webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -o-transition: all 0.5s ease; transition: all 0.5s ease; white-space: normal; } p { margin-top: 0; margin-bottom: 1rem; color: #636975; font-size: 16px; font-family: Lato,Helvetica,Arial,sans-serif; font-weight: 300; line-height: 24px; } .ml{ margin-left: 40px; margin-top: 20px; } .result{ display: inline-block; padding:5px 0; margin: 0 0 1em; border: 2px solid #DFE4ED; font-size: 18px;  color: #ff7373; -webkit-border-radius: 50px; -moz-border-radius: 50px; border-radius: 50px; } .hrVal{ background: #DFE4ED; bottom: 60px;  display: block; height: 1px; left: 0; position: absolute; } html, body{ height: 100%; min-height: 100%; } #objList { height : 100%; width : 100%; overflow : hidden; } .view-scholarship{ background-color:#ff7373;color:white; border:none; padding:13px 37px 13px 37px; border-radius:97px; margin-bottom: 26px; font-weight:500;font-size:16px;} .view-scholarship a{ background-color:#ff7373;color:white; border:none;  font-weight:500;font-size:16px;} @media (max-width: 992px) {.buttons {margin-top: 0px !important;padding-left: 14px !important;}}</style>');
        scholarshipContainer.append('<a style="text-decoration:none; color:white; font-weight:500" href=' + window.applicationURL + baseApiUrl + 'AccessScholarshipApp class="view-scholarship" target=_blank>View My Scholarship Portal</a><div class="row" style="background-color: none; height: fit-content;" id="elementtoScrollToID">' +
            '    <div class="col-sm-5 col-md-4 col-lg-3 mt-30" style="margin-bottom:3%;"> <span class="font2"><b> Category</b> </span>' +
            '        <div class="mt-10"> <select id="category" class="ddl">' +
            '                <option value="all">All</option>' +
            '            </select> </div>' +


            '    </div>' +
            '<div class="col-sm-5 col-md-3 col-lg-6 mt-30" style="margin-bottom:3%;><span class="font2"><b>Search Term(s)</b></span>'
            + ' <div class="mt-10" style="margin-left:1px;"><div class="searchbar"><input class="search-bar" type="text" id="searchInput"></div></div>' +
            '</div> <div class="col-sm-12 col-md-5 col-lg-3 buttons"style="display:flex;margin-bottom:3%;margin-top:45px;padding-left: 0px;"> <button id="find" class="ddl mt-10"' +
            '            style="max-width: 121px !important; font-weight: 500;background: #ff7373; border: 0px; color: white; padding: 0px;margin-left:3px;margin-right:3px;">' +
            '            <span style="margin-left: 5px;"> SEARCH</span></button> ' +
            '<button id = "reset" class= "ddl mt-10"' +
            '            style="max-width: 82px !important; font-weight:500;background: #ff7373; border: 0px; color: white; padding: 0px;margin-left: 5px;">' +
            '            <span style="margin-left: 5px;"> RESET</span></button>' +
            '</div ></div> ' +
            '</div>' +

            '' +
            '</div>' +
            '    <div id="wrapper" class="">' +
            '        <section>' +
            '            <div class="data-container"></div>' +
            '            <div id="demo"></div>' +
            '        </section>' +
            '    </div>' + '<div style="display: -webkit-inline-flex;  width: 100%; margin-top=-31px;">' +
            '<hr/ style="width: auto;"> <div class="result" id="pg_no" style="width: fit-content; margin-top:-35px; border:none"></div> ' +
            '' +
            '</div>' +
            '' +
            '</div>');

        $('#category').select2();

        $.ajax({
            type: 'GET',
            url: baseApiUrl + 'GetScholarshipCategories',
            success: function (res) {
                var result = res.map(d => ({ id: d, text: d }));
                $('#category').select2({ data: result });
            }
        });

        // get references to search input and search button
        var searchButton = document.getElementById('searchButton');
        var scholarshipContainer = $('#demo'); // Do not remove this
        var total = 20;
        var rec = [];
        var current = new Date();
        $('#find').click(function () {
            var searchInput = document.getElementById('searchInput');
            var searchquery = searchInput.value;
            var cat = $('#category').val()
            scholarshipContainer.prev().html('<div style="display: flex;justify-content: center;margin-top:50px;"> <div class="loader"></div></div>');
            scholarshipContainer.pagination(
                {

                    dataSource: function (done) {
                        $.ajax({
                            type: 'GET',
                            url: baseApiUrl + 'GetActiveScholarships/?search=' + searchquery + '&category=' + cat + '&epoch=' + current.toLocaleDateString('en-GB'),
                            success: function (res) {
                                total = res.length;
                                rec = res;
                                done(res);
                                if (total == 0) {
                                    scholarshipContainer.prev().html('<p>No results found.</p>');
                                    $('#demo').hide();
                                    $('#pg_no').hide();
                                }
                                else {
                                    $('#pg_no').show();
                                    $('#demo').show();
                                }

                            }
                        });
                    },
                    locator: 'items', totalNumber: total, pageSize: 10,
                    ajax: { beforeSend: function () { scholarshipContainer.prev().html('<div style="display: flex;justify-content: center;margin-top:50px;"> <div class="loader"></div></div>'); } },
                    callback: function (response, pagination) {
                        var dataHtml = '';
                        var data = [];
                        var pageStart = (pagination.pageNumber - 1) * pagination.pageSize;

                        var start = pageStart + 1;
                        var pageEnd = pageStart + pagination.pageSize;
                        $('#pg_no').html('<div>  ' + start + ' - ' + pageEnd + ' of ' + total + '</div>');
                        if (pageEnd > total)
                            $('#pg_no').html('<div>' + start + ' - ' + total + ' of ' + total + '</div>');
                        $('#pg_res').show();
                        var pageItems = rec.slice(pageStart, pageEnd);



                        var url = document.location.href;
                        $.each(pageItems, function (index, item) {
                            //dataHtml += '<div class="val" style="margin:10px;">  <div> <p id="category" style=" margin-bottom: 1px; font-size: small;"> ' + item.scholarshipCategory + '</p> <h3 class="title" style=" margin-top: 0;"> <a href="' + url + '?id=' + item.id + '" style="font-weight: 900;"> <span  id="titleInfo">' + item.title + '</span> </a> </h3> </div> <div> <div class="position-title"> <i class="fa-solid fa-money-bill-1-wave"></i> <div class="label-inline">Estimated Value:&nbsp;</div> <span id="estimateValue"> ' + item.estimatedValue + '</span> </div> </div> <div> <div class="avlScholarship"> <i class="fa-solid fa-graduation-cap"></i> <div class="label-inline">Available Scholarship: &nbsp;</div> <span id="comInfo">' + item.numberAvailable + '</span> </div> </div> <div> <div class="company"> <i class="fa-solid fa-calendar"></i> <div class="label-inline">Scholarship Year: &nbsp;</div> <span id="comInfo">' + item.year + '</span> </div> </div>  <div class="subtitle-bottom"></div> <div style=" word-break:break-word;"> <p id="shortDesc"> ' + item.shortDescription + '... </p> <a href="' + url + '?id=' + item.id + '" ><div class="btn btn-blue ">Read More</div> </a></div> <hr style="border: 1px solid #D2D6E0;background-color: #D2D6E0;" /> </div>'


                            dataHtml += '<div id="grid"></div>'
                            // sample data
                            var sampledata;


                            // dataHtml+='<div class="val" style="margin:10px;">  <div> <p id="category" style=" margin-bottom: 1px; font-size: small;"> ' + item.scholarshipCategory + '</p> <h3 class="title" style=" margin-top: 0;"> <a href="' + url + '?id=' + item.id + '" style="font-weight: 900; " > <span  id="titleInfo">' + item.title + '</span> </a> </h3> </div> <div> <div class="position-title"> <i class="fa-solid fa-money-bill-1-wave"></i> <div class="label-inline">Estimated Value:&nbsp;</div> <span id="estimateValue"> ' + item.estimatedValue + '</span> </div> </div> <div> <div class="avlScholarship"> <i class="fa-solid fa-graduation-cap"></i> <div class="label-inline">Available Scholarship: &nbsp;</div> <span id="comInfo">' + item.numberAvailable + '</span> </div> </div> <div> <div class="company"> <i class="fa-solid fa-calendar"></i> <div class="label-inline">Scholarship Year: &nbsp;</div> <span id="comInfo">' + item.year + '</span> </div> </div> <div class="subtitle-bottom"></div> <div style=" word-break:break-word;"> <p id="shortDesc"> ' + item.shortDescription + '... </p> <a href="' + url + '?id=' + item.id + '" ><div class="btn btn-blue">Read More</div></a> </div> <hr style="border: 1px solid #D2D6E0;background-color: #D2D6E0;" /> </div>'

                            sampledata = item;
                            var newData = {
                                id: item.id, scholarshipname: String(item.title), category: String(item.scholarshipCategory), value: String(item.estimatedValue), available: String(item.numberAvailable), year: String(item.year), description: String(item.shortDescription), apply: '<a href="' + url + '?id=' + item.id + '" ><div class="btn btn-blue ">Read More</div></a> </div> '
                            };
                            data.push(newData);
                        });
                        ej.base.registerLicense('Mgo+DSMBaFt+QHFqVkNrXVNbdV5dVGpAd0N3RGlcdlR1fUUmHVdTRHRcQllhT39Td0ZhUX5deHM=;Mgo+DSMBPh8sVXJ1S0d+X1RPd11dXmJWd1p/THNYflR1fV9DaUwxOX1dQl9gSXpRcERjWHxceHVQQ2c=;ORg4AjUWIQA/Gnt2VFhhQlJBfV5AQmBIYVp/TGpJfl96cVxMZVVBJAtUQF1hSn5XdENiWX5dcnxUQWJb;NRAiBiAaIQQuGjN/V0d+XU9Hc1RDX3xKf0x/TGpQb19xflBPallYVBYiSV9jS31TckdlWH9fc3ZdR2hUVg==;Mgo+DSMBMAY9C3t2VFhhQlJBfV5AQmBIYVp/TGpJfl96cVxMZVVBJAtUQF1hSn5XdENiWX5dcnxXRmZb;MTg0ODkyMUAzMjMxMmUzMTJlMzMzNWt0SnNMc01xSWEvajBnY0l5ZWQ1T0ttSW1iVnE3VnVvdGlsaTBZdllTRDA9;MTg0ODkyMkAzMjMxMmUzMTJlMzMzNUtJb2ZTVE1kaVBSUndZQTFNOXZFQW5jaHBrdUZrQmprb2FCeitIQlIzSDg9');
                        // create the Syncfusion Grid
                        createGrid(data, dataHtml, scholarshipContainer, url, baseApiUrl);
                        document.getElementById('elementtoScrollToID').scrollIntoView();
                    }
                })
        });
        const resetButton = document.getElementById("reset");
        resetButton.addEventListener("click", resetclick);
        function resetclick() {


            $('#category').val('all').trigger('change');
            $('#searchInput').val('');

            scholarshipContainer.prev().html('<div style="display: flex;justify-content: center;margin-top:50px;"> <div class="loader"></div></div>');
            scholarshipContainer.pagination(
                {
                    dataSource: function (done) {
                        $.ajax({
                            type: 'GET',
                            url: baseApiUrl + 'GetActiveScholarships' + '?epoch=' + current.toLocaleDateString('en-GB'),
                            success: function (res) {
                                total = res.length;
                                rec = res;
                                done(res);
                                if (total == 0) {
                                    scholarshipContainer.prev().html('<p>No results found.</p>');
                                    $('#demo').hide();
                                    $('#pg_no').hide();
                                }
                                else {
                                    $('#pg_no').show();
                                    $('#demo').show();
                                }
                            }
                        });
                    },



                    locator: 'items', totalNumber: total, pageSize: 10,
                    ajax: { beforeSend: function () { scholarshipContainer.prev().html('<div style="display: flex;justify-content: center;margin-top:50px;"> <div class="loader"></div></div>'); } },
                    callback: function (response, pagination) {
                        var dataHtml = '';
                        var data = [];
                        var pageStart = (pagination.pageNumber - 1) * pagination.pageSize;
                        var start = pageStart + 1;
                        var pageEnd = pageStart + pagination.pageSize;
                        var pageItems = rec.slice(pageStart, pageEnd);
                        $('#pg_no').html('<div>  ' + start + ' - ' + pageEnd + ' of ' + total + '</div>');
                        if (pageEnd > total)
                            $('#pg_no').html('<div>  ' + start + ' - ' + total + ' of ' + total + '</div>');
                        $('#pg_res').show();


                        var url = document.location.href;
                        var id = 0;


                        dataHtml += '<div id="grid"></div>'
                        // sample data
                        var sampledata;

                        
                        $.each(pageItems, function (index, item) {
                            var ur = url + '#' + item.Id
                            // dataHtml+='<div class="val" style="margin:10px;">  <div> <p id="category" style=" margin-bottom: 1px; font-size: small;"> ' + item.scholarshipCategory + '</p> <h3 class="title" style=" margin-top: 0;"> <a href="' + url + '?id=' + item.id + '" style="font-weight: 900; " > <span  id="titleInfo">' + item.title + '</span> </a> </h3> </div> <div> <div class="position-title"> <i class="fa-solid fa-money-bill-1-wave"></i> <div class="label-inline">Estimated Value:&nbsp;</div> <span id="estimateValue"> ' + item.estimatedValue + '</span> </div> </div> <div> <div class="avlScholarship"> <i class="fa-solid fa-graduation-cap"></i> <div class="label-inline">Available Scholarship: &nbsp;</div> <span id="comInfo">' + item.numberAvailable + '</span> </div> </div> <div> <div class="company"> <i class="fa-solid fa-calendar"></i> <div class="label-inline">Scholarship Year: &nbsp;</div> <span id="comInfo">' + item.year + '</span> </div> </div> <div class="subtitle-bottom"></div> <div style=" word-break:break-word;"> <p id="shortDesc"> ' + item.shortDescription + '... </p> <a href="' + url + '?id=' + item.id + '" ><div class="btn btn-blue">Read More</div></a> </div> <hr style="border: 1px solid #D2D6E0;background-color: #D2D6E0;" /> </div>'

                            sampledata = item;
                            var newData = {
                                id: item.id, scholarshipname: String(item.title), category: String(item.scholarshipCategory), value: String(item.estimatedValue), available: String(item.numberAvailable), year: String(item.year), description: String(item.shortDescription), apply: '<a href="' + url + '?id=' + item.id + '" ><div class="btn btn-blue ">Read More</div></a> </div> '
                            };
                            data.push(newData);
                        });
                        // create the Syncfusion Grid
                        createGrid(data, dataHtml, scholarshipContainer, url, baseApiUrl);
                        document.getElementById('elementtoScrollToID').scrollIntoView();
                    }
                }
            );
        }






        scholarshipContainer.prev().html('<div style="display: flex;justify-content: center;margin-top:50px;"> <div class="loader"></div></div>');
        scholarshipContainer.pagination(
            {
                dataSource: function (done) {
                    $.ajax({
                        type: 'GET',
                        url: baseApiUrl + 'GetActiveScholarships' + '?epoch=' + current.toLocaleDateString('en-GB'),
                        success: function (res) {
                            total = res.length;
                            rec = res;
                            done(res);
                        }
                    });
                },

                locator: 'items', totalNumber: total, pageSize: 10,

                ajax: {
                    beforeSend: function () {
                        scholarshipContainer.prev().html('<div style="display: flex;justify-content: center;margin-top:50px;"> <div class="loader"></div></div>');
                    }
                },
                timeout: 1000, callback: function (response, pagination) {
                    var dataHtml = '';
                    var data = [];
                    var pageStart = (pagination.pageNumber - 1) * pagination.pageSize;
                    var start = pageStart + 1;
                    var pageEnd = pageStart + pagination.pageSize;
                    var pageItems = rec.slice(pageStart, pageEnd);
                    $('#pg_no').html('<div>  ' + start + ' - ' + pageEnd + ' of ' + total + '</div>');
                    if (pageEnd > total)
                        $('#pg_no').html('<div>  ' + start + ' - ' + total + ' of ' + total + '</div>');
                    $('#pg_res').show();


                    var url = document.location.href;
                    var id = 0;


                    dataHtml += '<div id="grid"></div>'
                    // sample data
                    var sampledata;


                    $.each(pageItems, function (index, item) {
                        var ur = url + '#' + item.Id
                        // dataHtml+='<div class="val" style="margin:10px;">  <div> <p id="category" style=" margin-bottom: 1px; font-size: small;"> ' + item.scholarshipCategory + '</p> <h3 class="title" style=" margin-top: 0;"> <a href="' + url + '?id=' + item.id + '" style="font-weight: 900; " > <span  id="titleInfo">' + item.title + '</span> </a> </h3> </div> <div> <div class="position-title"> <i class="fa-solid fa-money-bill-1-wave"></i> <div class="label-inline">Estimated Value:&nbsp;</div> <span id="estimateValue"> ' + item.estimatedValue + '</span> </div> </div> <div> <div class="avlScholarship"> <i class="fa-solid fa-graduation-cap"></i> <div class="label-inline">Available Scholarship: &nbsp;</div> <span id="comInfo">' + item.numberAvailable + '</span> </div> </div> <div> <div class="company"> <i class="fa-solid fa-calendar"></i> <div class="label-inline">Scholarship Year: &nbsp;</div> <span id="comInfo">' + item.year + '</span> </div> </div> <div class="subtitle-bottom"></div> <div style=" word-break:break-word;"> <p id="shortDesc"> ' + item.shortDescription + '... </p> <a href="' + url + '?id=' + item.id + '" ><div class="btn btn-blue">Read More</div></a> </div> <hr style="border: 1px solid #D2D6E0;background-color: #D2D6E0;" /> </div>'

                        sampledata = item;
                        var newData = {
                            id: item.id, scholarshipname: String(item.title), category: String(item.scholarshipCategory), value: String(item.estimatedValue), available: String(item.numberAvailable), year: String(item.year), description: String(item.shortDescription), apply: '<a href="' + url + '?id=' + item.id + '" ><div class="btn btn-blue ">Read More</div></a> </div> '
                        };
                        data.push(newData);
                    });
                    // create the Syncfusion Grid
                    createGrid(data, dataHtml, scholarshipContainer, url, baseApiUrl);
                    document.getElementById('elementtoScrollToID').scrollIntoView();
                }
            }
        );

    }

});


function createGrid(data, dataHtml, scholarshipContainer, url, baseApiUrl) {
    registerLicenseAsyncCall();
    var grid = new ej.grids.Grid({
        dataSource: data,
        allowPaging: false,
        columnWidth: 0, // Set columnWidth to 0 to disable auto column sizing
        columns: [
            // add a column for the expandable button
            { headerText: '', width: 80, template: '<button class="expand-btn fa fa-angle-right btn-sm" style="color:#ff7373; font-size:17px; padding:5px; padding-right:2px;padding-left:2px; border:none; background:none;"></button>' },
            { headerText: 'Scholarship Name', field: 'scholarshipname', width: 400, clipMode: "EllipsisWithTooltip", tooltip: true },
            { headerText: 'Category', field: 'category', width: 200,clipMode: "EllipsisWithTooltip", tooltip: true },
            { headerText: 'Value', field: 'value', width: 100, clipMode: "EllipsisWithTooltip", tooltip: true }
        ]
    });
    //  grid.appendTo('#grid');
    // Add a resize event listener to handle responsiveness
    //window.addEventListener('resize', handleGridResponsive);

    //// Function to handle grid responsiveness
    //function handleGridResponsive() {
    //    var gridContainer = document.getElementById('gridContainer');
    //    var gridElement = document.getElementById('grid');

    //    if (gridContainer && gridElement) {
    //        if (gridContainer.offsetWidth < gridElement.offsetWidth) {
    //            gridContainer.style.overflowX = 'auto';
    //            gridContainer.style.overflowY = 'auto';
    //        } else {
    //            gridContainer.style.overflowX = 'hidden';
    //            gridContainer.style.overflowY = 'auto';
    //        }
    //    }
    //}
    //// Call the function initially to set the initial state based on the screen size
    //handleGridResponsive();
    scholarshipContainer.prev().html(dataHtml);
    grid.appendTo('#grid');
    // add the Grid to the page
    // add an event listener to the Grid element
    if (grid && grid.element) {
        grid.element.addEventListener('click', function (event) {
            // check if the clicked element is the expand button
            if (event.target.classList.contains('expand-btn')) {
                // find the corresponding row
                var row = event.target.closest('tr');
                // get the data item for the current row
                var dataItem = grid.getRowObjectFromUID(row.getAttribute('data-uid')).data;
                id = dataItem.id;
                // check if the description is already visible
                if (row.nextSibling && row.nextSibling.classList.contains('description-row')) {
                    // hide the description and remove the row
                    row.nextSibling.remove();
                    event.target.classList.remove('fa-angle-down');
                    event.target.classList.add('fa-angle-right');
                    //    event.target.innerHTML = '<a class="fa fa-angle-right btn-sm" style="color:#ff7373; font-size:17px;"></a>';
                }
                else {
                    // insert a new row after the current row
                    var newRow = document.createElement('tr');
                    newRow.classList.add('description-row');
                    newRow.innerHTML = '<td colspan="4" style="word-break: break-word;'
                        + 'padding: 20px; line - height: 1!important; font - size: 16px!important; color: black!important; ">'
                        + '<div class=description-outer style="display:flex;justify-content:space-between">'
                        + '<div class=content-container>'
                        + " <div> <label style='margin-bottom:0px; font-family:Lato !important;'>Category:&nbsp</label>"
                        + dataItem.category + "&nbsp</div ><div><label style='margin-bottom:0px; font-family:Lato !important;'>Estimated Value:&nbsp</label>"
                        + dataItem.value + "&nbsp</div><div><label  style='margin-bottom:0px; font-family:Lato !important;'>Available Scholarship:&nbsp</label>"
                        + dataItem.available + "&nbsp</div><div><label  style='margin-bottom:12px; font-family:Lato !important;'>Scholarship Year:&nbsp</label>"
                        + dataItem.year
                        + '</div>'
                        + '</div > '
                        + '<div class=button-container>'
                        + '<a class="alert-btn border-0 bg-white text-danger p-1 1rem" style="font-size:15px !important; font-weight:700; margin-top:5px; color:#ff7373;" href = "' + url + '?id=' + dataItem.id + '"><div  style="background: transparent; border:none; color:#ff7373; font-size:15px; padding:0px; padding-bottom:10px; padding-top:10px" >READ MORE<i class="fa fa-arrow-circle-right " style="padding:5px;"></i></div></a>'
                        + '<a class="alert-btn border-0 bg-white text-danger p-1 1rem" style="font-size:15px !important; font-weight:700; margin-top:5px; color:#ff7373;">APPLY<i class="fa fa-arrow-circle-right alert-btn" style="padding-left:5px;"></i></a>'
                        + '</div > '
                        + '</div > '
                        + dataItem.description
                        + '</td > ';


                    row.parentNode.insertBefore(newRow, row.nextSibling);
                    // toggle the button text
                    event.target.classList.remove('fa-angle-right');
                    event.target.classList.add('fa-angle-down');
                }
            }
            if (event.target.classList.contains('alert-btn')) {
                // find the corresponding row
                var row = event.target.closest('tr');
                testurl = window.applicationURL + baseApiUrl + "AccessScholarshipApp?scholarshipId=" + id;
                window.open(testurl, '_blank');

            }
        });
    }
}
//Syncfusion License Keys Added
async function registerLicenseAsync() {
    return await new Promise(resolve => {
        ej.base.registerLicense('Mgo+DSMBaFt+QHFqVkNrXVNbdV5dVGpAd0N3RGlcdlR1fUUmHVdTRHRcQllhT39Td0ZhUX5deHM=;Mgo+DSMBPh8sVXJ1S0d+X1RPd11dXmJWd1p/THNYflR1fV9DaUwxOX1dQl9gSXpRcERjWHxceHVQQ2c=;ORg4AjUWIQA/Gnt2VFhhQlJBfV5AQmBIYVp/TGpJfl96cVxMZVVBJAtUQF1hSn5XdENiWX5dcnxUQWJb;NRAiBiAaIQQuGjN/V0d+XU9Hc1RDX3xKf0x/TGpQb19xflBPallYVBYiSV9jS31TckdlWH9fc3ZdR2hUVg==;Mgo+DSMBMAY9C3t2VFhhQlJBfV5AQmBIYVp/TGpJfl96cVxMZVVBJAtUQF1hSn5XdENiWX5dcnxXRmZb;MTg0ODkyMUAzMjMxMmUzMTJlMzMzNWt0SnNMc01xSWEvajBnY0l5ZWQ1T0ttSW1iVnE3VnVvdGlsaTBZdllTRDA9;MTg0ODkyMkAzMjMxMmUzMTJlMzMzNUtJb2ZTVE1kaVBSUndZQTFNOXZFQW5jaHBrdUZrQmprb2FCeitIQlIzSDg9', () => {
            resolve();
        });
    });
}
async function registerLicenseAsyncCall() {
    await registerLicenseAsync();
};

