jQuery(document).ready(function($) {
    "use strict";
    var numbersType = $.fn.dataTable.absoluteOrderNumber([{
            value: "0",
            position: "bottom"
        }]),
        currencyType = $.fn.dataTable.absoluteOrderNumber([{
            value: "0.000000",
            position: "bottom"
        }]);
        
    columnDefs: [{
        targets: 3,
        type: numbersType
    }, {
        targets: 4,
        type: numbersType
    }, {
        targets: 6,
        type: currencyType
    }], $.fn.celpDatatable = function() {     
        var $celp_table = $(this),
            exchangetype=$celp_table.data("coin-exchangetype"),

            coin_symbol = $celp_table.data("coin-symbol"),
            coin_price = $celp_table.data("coin-price"),
            prevLbl = $celp_table.data("prev"),
            nextLbl = $celp_table.data("next"),
            showEntriesLbl = $celp_table.data("show-entries"),
            searchLbl = $celp_table.data("search"),
            zeroRecords = $celp_table.data("zero-records"),
            ShowingEntries = $celp_table.data("showing_entries"),
            FilterEntries = $celp_table.data("filter_entries"),
            loadingText = $celp_table.data("loading_records"),
            perPage = $celp_table.data("per-page"),
            defaultLogo = $celp_table.parents(".celp_container").data("default-logo"),
            columns = [];        
          var dropdownList = [10, 25, 50, 100];
            if (!dropdownList.includes(perPage)) {
                dropdownList.push(perPage); 
                dropdownList.sort(function(a, b){return a - b})
            }
            $celp_table.find("thead th").each(function(index) {
            var index = $(this).data("index"),
                thisTH = $(this),
                classes = $(this).data("classes"),
                fiatSymbol = "$";
              
            var type = '';
            if (index == "coin_supports" || index == "trading_pairs") {
                type = numbersType
            } else if (index == "name" || index == "official_website" || index == "trust_score") {
                type = "html"
            } else if (index == "btc_price") {
                type = currencyType
            } else if (index == "id" || index == "volume_24h" || index == "alexa_rank" ) {
                type = 'num-fmt'
            } else {
                type = "string"
            }
            columns.push({
                data: index,
                name: index,
                type: type,
                render: function(data, type, row, meta) {
                    if (void 0 === meta.settings.json) return data;
                    if ("display" === type) switch (index) {
                        case "id":
                            return row.id;
                        case "country":
                            return parseInt(data) <= 0 ? '<div class="' + classes + '">N/A</div>' : '<div class="' + classes + '">' + data + "</div>";
                        case "established":
                            return parseInt(data) <= 0 ? '<div class="' + classes + '">N/A</div>' : '<div class="' + classes + '">' + data + '</div>';
                        case "name":
                            var singleUrl, url = thisTH.data("single-page-url") + "/" + row.ex_id + '/',
                                html;

                                if(exchangetype=="decentralized"){
                                    return html = '<div class="' + classes + '"><a title ="' + data + '" href = "' + url + '"> <img id="' + data + '"  src="' + row.logo + '"  onerror="this.src=\'' + defaultLogo + '\'">' + data + " </a><span>Decentralized</span></div>";
                                }else if(exchangetype=="centralized"){
                                    return html = '<div class="' + classes + '"><a title ="' + data + '" href = "' + url + '"> <img id="' + data + '"  src="' + row.logo + '"  onerror="this.src=\'' + defaultLogo + '\'">' + data + " </a><span>Centralized</span></div>";

                                }else{
                                    return html = '<div class="' + classes + '"><a title ="' + data + '" href = "' + url + '"> <img id="' + data + '"  src="' + row.logo + '"  onerror="this.src=\'' + defaultLogo + '\'">' + data + " </a></div>";

                                }
                        case "trust_score":                           
                            return parseInt(data) <= 0 ? '<div class="' + classes + '">N/A</div>' : '<div class="' + classes + '"><span class="celp-progress"><span class="celp-progress-color celp-progress-' + numeral(data).format("0,0") + '" style="width:' + (numeral(data).format("0,0") * 10) +'%"></span ></span ><span class="celp-progress-score">' + numeral(data).format("0,0")+ '</span></div>';
                        case "description":
                            return html = '<div class="' + classes + '">' + data + '</div>';
                        case "volume_24h":
                            var formatedVal = coin_price * data,
                                btcVol = row.btc_volume,
                                formatedbtcVol = numeral(btcVol).format("0,0.00");
                            return formatedVal = numeral(formatedVal).format("0,0.00"), html = void 0 !== data && null != data ? '<div data-val="' + row.volume_24h + '" class="' + classes + '">' + coin_symbol + formatedVal.toUpperCase() + " <br/><span>" + formatedbtcVol + " BTC</span></div>" : '<div class="' + classes + '">?</span></div>';
                        case "official_website":
                            var html;
                            return html = '<div class="' + classes + '"> <a target="_blank"  rel="nofollow"  title ="' + row.ex_id + '" href="' + data + '"><i class="cmc_icon-website"></i></a> </div>'
                    }
                    return data
                }
            })
        }), $celp_table.DataTable({          
            serverSide: true,       
            "deferRender": true,
            ajax: {
                url: ajax_object.ajax_url,
                type: "POST",
                dataType: "JSON",
                async: true,
                data: function(d) {
                    d.action = "celp_get_ex_list";
                    d._wpnonce = ajax_object.nonce;
                    d.exchangetype=exchangetype;
                    d.search = d['search']['value'];
                    
                },
                error: function(xhr, error, thrown) {}
            },
            columns: columns,
            ordering: false,
            searching: true,
            pageLength: perPage,
            pagingType: "simple",
            processing: true,
           lengthMenu: dropdownList,
            language: {
                info: ShowingEntries,
                infoFiltered: "(" + FilterEntries + ")",
                loadingRecords: loadingText + "...",
                processing: "",
                loading: loadingText + "...",
                paginate: {
                    next: nextLbl,
                    previous: prevLbl
                },
                lengthMenu: showEntriesLbl,
                search: searchLbl,
                zeroRecords: zeroRecords
            },
            drawCallback: function(settings) {

                $celp_table.tableHeadFixer({

                    head: !1,
                    left: 2,
                    "z-index": 1
                })
                
                var pageInfo = this.api().page.info();

                if (pageInfo.pages <= 1) {
                    $('.dataTables_paginate .next').addClass('disabled');
                } else {
                    $('.dataTables_paginate .next').removeClass('disabled');
                }
            },

            "initComplete": function (settings, json) {
                if (json?.error == "nonce_failed") {
                
                    $(this).find('.dataTables_empty').html("<span style=\"color:red\">Attention: Please exclude this page from your cache plugin, as it is currently causing a nonce failure.<br> For detailed instructions on how to implement the exclusion, kindly follow this link: <a href=\"https://cryptocurrencyplugins.com/docs/coins-marketcap/nonce-validation-failed\" target=\"_balnk\">Exclusion Guide..</a></span>")
                       

                }
            }
        })
    }
    
    $(".celp_container .celp-datatable").each(function () {
         $.fn.dataTable.ext.errMode = 'none';
        $(this).celpDatatable();
        new Tablesort(this, {
            descending: true
        });
    });

    
})