(function($) {


    $.fn.gernateChart = function() {
        //  $(this).parents().find(".ccpw-preloader").show();
        var coinId = $(this).data("coin-id");
        var mainThis = $(this);
        var coinperiod = $(this).data("coin-period");
        var label_1D = $(this).data("1d");
        var label_7D = $(this).data("7d");
        var label_1M = $(this).data("1m");
        var label_3M = $(this).data("3m");
        var label_6M = $(this).data("6m");
        var label_1Y = $(this).data("1y");
        var coinid = $(this).data("coinid");
        var uniqueId = $(this).data("unique-id");
        var fromLbl = $(this).data("from-lbl");
        var toLbl = $(this).data("to-lbl");
        var zoomLbl = $(this).data("zoom-lbl");
        var priceLbl = $(this).data("price-lbl");
        priceLbl= $.trim(priceLbl);
        var currentPrice = $(this).parents('.ccpw-container.chart').find('.CCP-' + coinId).text();
        var rest_url = $(this).parents('.ccpw-container.chart').find('.coin_details').attr('data-rest-url');
        var currentVol = $(this).parents('.ccpw-container.chart').children('.CCMC').text();
        var volumeLbl = $(this).data("volume-lbl");
        volumeLbl=$.trim(volumeLbl);
        var color = $(this).data("chart-color");
        var noFormatting = $(this).data("no-formatting");
        var price_section = $(this).find(".CCP-" + coinId);
        var priceData = [];
        var milliseconds = (new Date).getTime();
        if (currentPrice < 0.50) {
            var formatedPrice = numeral(currentPrice).format('00.000000')
        } else {
            var formatedPrice = numeral(currentPrice).format('00.00')
        }       
        var currentPriceIndex = {
            date: milliseconds,
            value: formatedPrice.replace('$', ''),
            volume: numeral(currentVol).format('00.00')
        };
        $(this).find('.CCMC,.CCV').number(true);
        var cacheIndex = coinId + '-historical-data';
        var coinCacheData = lscache.get(cacheIndex);
        if (coinCacheData) {
            $(".chart-wrp img.ccpw-preloader").hide();
            priceData = coinCacheData;
           // amchart5(coinId, color, priceData, fromLbl, toLbl, zoomLbl, priceLbl, volumeLbl, label_1D, label_7D, label_1M, label_3M, label_6M, label_1Y, noFormatting, coinid);
          generateChart(coinId, color, priceData, fromLbl, toLbl, zoomLbl, priceLbl, volumeLbl, label_1D, label_7D, label_1M, label_3M, label_6M, label_1Y, noFormatting, coinid,uniqueId)
        } else {
            var request_data = {
                'action': 'ccpw_charts',
                'coin_id': coinId,
                //'type': 'chart',
                // 'day': 31,
                'nonce': ccpw_data_object.nonce
            };
            jQuery.ajax({
                type: "post",
                dataType: "json",
                url: ccpw_data_object.ajax_url,
                data: request_data,
                async: !0,
                success: function(response) {                   
                    if (response.status == "success") {

                        if (response.data && response.data.length !== 0 && response.data != null) {
                            var priceData = response.data;                        
                        //    var lastIndex = priceData[priceData.length - 1];
                          //  currentPriceIndex.volume = lastIndex.volume;
                          //  priceData.push(currentPriceIndex);
                            $(".chart-wrp img.ccpw-preloader").hide();
                            mainThis.find(".ccpw-preloader").hide();
                            //cached for 1 hour
                            lscache.set(coinId + '-historical-data', priceData, 120);
                          //  amchart5(coinId, color, priceData, fromLbl, toLbl, zoomLbl, priceLbl, volumeLbl, label_1D, label_7D, label_1M, label_3M, label_6M, label_1Y, noFormatting, coinid);
                            generateChart(coinId, color, priceData, fromLbl, toLbl, zoomLbl, priceLbl, volumeLbl, label_1D, label_7D, label_1M, label_3M, label_6M, label_1Y, noFormatting, coinid,uniqueId)
                        
                        }                      
                        else {
                            $(".chart-wrp img.ccpw-preloader").hide();
                            $(".chart-wrp span.ccpw-no-data").html("<center>No chart data found</center>");
                            mainThis.css('height', 'auto')
                            console.log('No data available!');
                        }
                    }
                      else if (response?.error == "nonce_failed") {       
                          
                        $(".chart-wrp span.ccpw-no-data").html("<span style=\"color:red\">Attention: Please exclude this page from your cache plugin, as it is currently causing a nonce failure.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>")
                    
                        }
                }
            });
        }
    }
     $('.ccpw-chart').each(function(index) {
        $(this).gernateChart();
    }); 







})(jQuery);




function generateChart(coinId, color, price, fromLbl, toLbl, zoomLbl, priceLbl, volumeLbl, label_1D, label_7D, label_1M, label_3M, label_6M, label_1Y, noFormatting, coinid,uniqueId, ) {
    

    am5.ready(function () {


        

        // Create root element
        // https://www.amcharts.com/docs/v5/getting-started/#Root_element
        am5.array.each(am5.registry.rootElements, function(root) {
            if (root.dom.id === 'CCPW-CHART-' + coinId + '-' +uniqueId) {
                root.dispose();
            }
        });

     
        var root = am5.Root.new('CCPW-CHART-' + coinId + '-' + uniqueId);

        // console.log("3",coinId)
        // console.log("4",coinid)


        // Set themes
        // https://www.amcharts.com/docs/v5/concepts/themes/
        root.setThemes([
            am5themes_Animated.new(root)
        ]);

        // Create a stock chart
        // -------------------------------------------------------------------------------
        // https://www.amcharts.com/docs/v5/charts/stock-chart/#Instantiating_the_chart
        var stockChart = root.container.children.push(am5stock.StockChart.new(root, {

        }));

       
        // Set global number format
        // -------------------------------------------------------------------------------
        // https://www.amcharts.com/docs/v5/concepts/formatters/formatting-numbers/
      //  root.numberFormatter.set("numberFormat", "#,###.00");
        root.numberFormatter.setAll({
            numberFormat: noFormatting,

            // Group only into M (millions), and B (billions)
            bigNumberPrefixes: [
                { "number": 1e+3, "suffix": "K" },
                { "number": 1e+6, "suffix": "M" },
                { "number": 1e+9, "suffix": "B" },
                
            ],

            // Do not use small number prefixes at all
           // smallNumberPrefixes: []
        });

        // Create a main stock panel (chart)
        // -------------------------------------------------------------------------------
        // https://www.amcharts.com/docs/v5/charts/stock-chart/#Adding_panels
        var mainPanel = stockChart.panels.push(am5stock.StockPanel.new(root, {
            panX: false,
            panY: false,
            wheelX: "panX",          
            wheelY: "zoomX"
          
        }));

        mainPanel.get("colors").set("colors", [
            am5.color(color)
            
        ]);
        // Add cursor
        // https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
        var cursor = mainPanel.set("cursor", am5xy.XYCursor.new(root, {
            behavior: "zoomX",
        }));
        cursor.lineY.set("visible", true);  

        // Create axes
        // https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
        var xAxis = mainPanel.xAxes.push(am5xy.GaplessDateAxis.new(root, {
            maxDeviation: 0,
            baseInterval: {
                timeUnit: "day",
                count: 1
            },
            renderer: am5xy.AxisRendererX.new(root, {
               
            }),
            tooltip: am5.Tooltip.new(root, {})
        }));

        var yAxis = mainPanel.yAxes.push(am5xy.ValueAxis.new(root, {
            extraMin: 0,        
            renderer: am5xy.AxisRendererY.new(root, {
                inside: false,
                opposite:false,
              
               
            }),
           
            tooltip: am5.Tooltip.new(root, {})
        }));


        // Add series
        // https://www.amcharts.com/docs/v5/charts/xy-chart/series/
        var series = mainPanel.series.push(am5xy.LineSeries.new(root, {
            name: priceLbl,
            xAxis: xAxis,
            yAxis: yAxis,
            valueYField: "value",
            valueXField: "date",
            minBulletDistance: 10,
            calculateAggregates: true,
            tooltip: am5.Tooltip.new(root, {
                pointerOrientation: "horizontal",
                labelText: "{valueY}"
            }),
           
            legendLabelText: "[bold {stroke}]{name}:[/]",
            legendRangeLabelText: "[{stroke}]{name}:[/]",
            legendValueText: "[bold {stroke}]{valueY}[/]",
            legendRangeValueText: "[{stroke}]{valueYClose}[/]"
           
        }));
        series.fills.template.setAll({
            fillOpacity: 0.2,
            visible: true
        });

        series.strokes.template.setAll({
            strokeWidth: 2
        });
     //   series.set("fill", am5.color(color)); 

        // y axis for volume
        var volumeAxisRenderer = am5xy.AxisRendererY.new(root, {});
        volumeAxisRenderer.grid.template.set("forceHidden", true);
        volumeAxisRenderer.labels.template.set("forceHidden", true);

        var volumeAxis = mainPanel.yAxes.push(am5xy.ValueAxis.new(root, {
            height: am5.percent(25),
            y: am5.percent(100),
            centerY: am5.percent(100),
            panY: false,
            renderer: volumeAxisRenderer
        }));

        // Add series
        // https://www.amcharts.com/docs/v5/charts/xy-chart/series/
        var volumeSeries = mainPanel.series.push(am5xy.ColumnSeries.new(root, {
            name: volumeLbl,
            xAxis: xAxis,
            yAxis: volumeAxis,
            valueYField: "volume",
            valueXField: "date",
            calculateAggregates: true,
            tooltip: am5.Tooltip.new(root, {
                labelText: "{valueY.formatNumber('$#,###.00a')}"
            }),
            legendLabelText: "[bold {stroke}]{name}:[/]",
            legendRangeLabelText: "[{stroke}]{name}:[/]",
            legendValueText: "[bold {stroke}]{valueY.formatNumber('$#,###.00a')}[/]",
            legendRangeValueText: "[{stroke}]{valueYClose.formatNumber('$#,###.00a')}[/]",
           
            
        }));

        volumeSeries.columns.template.setAll({ fillOpacity: 0.8, strokeOpacity: 0, width: am5.percent(40) })


        // Add scrollbar
        // https://www.amcharts.com/docs/v5/charts/xy-chart/scrollbars/

    

        var scrollbar = mainPanel.set(
            "scrollbarX",
            am5xy.XYChartScrollbar.new(root, {
                orientation: "horizontal",
                height: 60
            })
        );

        scrollbar.get("background").setAll({
            fill: am5.color(color),
            fillOpacity: 0.2,
            cornerRadiusTR: 0,
            cornerRadiusBR: 0,
            cornerRadiusTL: 0,
            cornerRadiusBL: 0
        });
        mainPanel.bottomAxesContainer.children.push(scrollbar);
        var sbDateAxis = scrollbar.chart.xAxes.push(
            am5xy.DateAxis.new(root, {
                baseInterval: {
                    timeUnit: "day",
                    count: 1
                },
                renderer: am5xy.AxisRendererX.new(root, {})
            })
        );

        var sbValueAxis = scrollbar.chart.yAxes.push(
            am5xy.ValueAxis.new(root, {
                renderer: am5xy.AxisRendererY.new(root, {})
            })
        );

        var sbSeries = scrollbar.chart.series.push(
            am5xy.LineSeries.new(root, {
                valueYField: "value",
                valueXField: "date",
                xAxis: sbDateAxis,
                yAxis: sbValueAxis
            })
        );



        // Stock toolbar
        // -------------------------------------------------------------------------------
        // https://www.amcharts.com/docs/v5/charts/stock/toolbar/
        var toolbar = am5stock.StockToolbar.new(root, {
            container: document.getElementById('ccpw-default-chart-' + coinId + '-' + uniqueId),
            stockChart: stockChart,
            controls: [
                /* am5stock.IndicatorControl.new(root, {
                    stockChart: stockChart,
                    legend: valueLegend
                }), */
                am5stock.DateRangeSelector.new(root, {
                    stockChart: stockChart
                }),
                
                am5stock.PeriodSelector.new(root, {
                    stockChart: stockChart,
                    
                    periods: [
                        { timeUnit: "day", count: 1, name: label_1D },
                        { timeUnit: "day", count: 7, name: label_7D },
                        { timeUnit: "month", count: 1, name: label_1M },
                        { timeUnit: "month", count: 3, name: label_3M },
                        { timeUnit: "month", count: 6, name: label_6M },
                        { timeUnit: "year", count: 1, name: label_1Y },

                    ],
                  
                }),
                // seriesSwitcher,
                /* am5stock.DrawingControl.new(root, {
                    stockChart: stockChart
                }),
                am5stock.ResetControl.new(root, {
                    stockChart: stockChart
                }),
                am5stock.SettingsControl.new(root, {
                    stockChart: stockChart
                }) */
            ]
        })
       
        //stockChart.set("stockSeries", series);
        //  stockChart.set("volumeSeries", volumeSeries);
        // Set data
        var data = price; 
        series.data.setAll(data);
        volumeSeries.data.setAll(data);
        sbSeries.data.setAll(data);

        let valueLegend = mainPanel.plotContainer.children.push(am5stock.StockLegend.new(root, {
            stockChart: stockChart
        }));
        valueLegend.settingsButtons.template.set("visible", false);
        //valueLegend.closeButtons.template.set("visible", false);
        valueLegend.data.setAll([series, volumeSeries]);

        series.bullets.push(function () {
            var circle = am5.Circle.new(root, {
                radius: 4,
                fill: root.interfaceColors.get("background"),
                stroke: series.get("fill"),
                strokeWidth: 2
            })

            return am5.Bullet.new(root, {
                sprite: circle
            })
        });

       
            jQuery('#ccpw-default-chart-' + coinId + '-' + uniqueId).ready(function ($) {
                var def_chart = ('#ccpw-default-chart-' + coinId + '-' + uniqueId);
                var selected = $(def_chart).find('.am5stock-control-label .am5stock-link');
                $(selected[5]).addClass('am5stock-active');              
                $(selected).click(function () {
                    $(selected).removeClass('am5stock-active');
                    $(this).addClass("am5stock-active");


                })
            })   
          
    
       // console.log(jQuery('#ccpw-default-chart-' + coinId).find('.am5stock-control-label .am5stock-link'))
       

    }); // end am5.ready()
}