jQuery.noConflict();
(function ($) {
    $(document).ready(function () {
        
        populateDefaultValues();
        showdatepicker();
        
        $("#update_stats1").click(function () {
            populate_stats();
        });
        
        $(".xtabmenus a:nth-child(8)").click(function(){
            populate_stats();
        });
        
    });

    function populate_stats() {
        var from = "";
        var to  = "";

        if($('#wpbb_datepicker_from').val() == "" || $('#wpbb_datepicker_from').val() == null){
            var today = new Date();
            var datefrom = today.getDate();
            var yearfrom = today.getFullYear();
            var monthfrom = today.getMonth();
            from = monthfrom + '/' + datefrom + '/' + yearfrom;
        } else {
            from = $('#wpbb_datepicker_from').val();
        }
        
        if($('#wpbb_datepicker_to').val() == "" || $('#wpbb_datepicker_to').val() == null ){
            var today = new Date();
            var dateto = today.getDate();
            var yearto = today.getFullYear();
            var monthto = today.getMonth()+1;
            to =  monthto + '/' + dateto + '/' + yearto;
        }else{
            to = $('#wpbb_datepicker_to').val();
        }

        var data1 = {
            action: 'wpbb_get_block_stats',
            nonce: wpbb_vars.wpbb_nonce,
            from: from,
            to: to
        };

        var req = $.post(ajaxurl, data1, function (response) {
            response = jQuery.parseJSON(response);

            populate_type('block_reasons', 'Top Block Reasons', response.block_reasons);
            populate_type('user_agents', 'User Agents', response.user_agents);
            //populate_type('referrers', 'Referrers', response.referrers);
            populate_type('ips', 'IP Addresses', response.ips);
            populate_world_map(response.countries);
        });
    }

    function populate_type(type_name, type_title, type_data) {
        $('#chart_' + type_name).highcharts(get_pie_options(type_title, format_data_for_chart(type_data)));
    }

    function format_data_for_chart(input) {
        var chart_data = [];

        $.each(input, function (key, data) {
            chart_data.push([data.label, Number(data.data)]);
        });

        return chart_data;
    }

    function get_pie_options(title, data) {
        var options = {
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: title
            },
            tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true
                }
            },
            series: [{
                type: 'pie',
                data: data
            }],
            credits: {
                enabled: false
            }
        };

        return options;
    }

    function populate_world_map(data) {

        $('#chart_countries').highcharts('Map', {

            title: {
                text: 'Top Countries'
            },
            legend: {
                layout: 'vertical',
                align: 'left',
                verticalAlign: 'bottom'
            },
            mapNavigation: {
                enabled: true,
                buttonOptions: {
                    verticalAlign: 'right'
                }
            },

            colorAxis: {},

            series: [{
                //name: 'Population density',
                data: data,
                mapData: Highcharts.maps['custom/world-highres'],
                joinBy: ['iso-a2', 'code'],
                //name: 'Random data',
                countries: {
                    hover: {
                        color: '#BADA55'
                    }
                },
                dataLabels: {
                    enabled: true
                }
            }],
            credits: {
                enabled: false
            }
        });
    }

    function showdatepicker() {
        $('.wpbb_datepicker').datepicker( {
            changeMonth: true,
            showOtherMonths: true,
            selectOtherMonths: true,
            changeYear: true,
            dateFormat: 'mm/dd/yy',
            onClose: function(dateText, inst) { 
                var day = $("#ui-datepicker-div .ui-datepicker-day :selected").val();
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $('#wpbb_datepicker_from').datepicker({defaultDate: -30});
                $('#wpbb_datepicker_to').datepicker({defaultDate: new Date()});
            }
        });
    }

    function populateDefaultValues() {
        var today = new Date();
        var month = today.getMonth() - 1;
        var year = today.getFullYear();
        if (month < 0) {
            month = 11;
            year -= 1;
        }
        var oneMonthAgo = new Date(year, month, today.getDate());

        $('#wpbb_datepicker_to').val($.datepicker.formatDate('mm/dd/yy', today));
        $('#wpbb_datepicker_from').val($.datepicker.formatDate('mm/dd/yy', oneMonthAgo));
    }

}(jQuery));