var dateFormat = "yy-mm-dd";
var dataObj = {};
bidHistryGraph = {
    nutGraph: function(_id, _data, _title) {
        Highcharts.setOptions({
            colors: ['#3c88dc', '#639edf', '#89b6e8', '#bd10e0']
        });
        if(_data == '' || _data == undefined){
            _data =[{
                name: 'No Data',
                y: 100 ,
                color: '#f2f2f2',
                sliced: true,
                selected: true,
            }];
        }
        $('#'+_id).highcharts({
            chart: {
                type: 'pie',
                height:280,
                width: 420,
            },
            credits: {
                enabled: false
            },
            title: {
                verticalAlign: 'middle',
                floating: true,
                text: _title,
                style: {
                    font: 'normal 13px Verdana',
                    color : 'black'
                }
            },
            tooltip: {
                pointFormat: ''
            },
            plotOptions: {
                pie: {
                    innerSize: 170,
                    dataLabels: {
                        enabled: false,
                    }
                }
            },
            series: [{
                name: 'Delivered amount',
                data: _data
            }],

            exporting: {
                buttons: {
                    contextButton: {
                            enabled: false
                        },
                }
            }

        });
    },
    areaGraph: function(_id, cat, _data) {
        Highcharts.setOptions({
            colors: ['#3c88dc', '#639edf', '#89b6e8', '#bd10e0']
        });
        $('#'+_id).highcharts( {
            chart: {
                type: 'area',
                backgroundColor: '#ebebea',
                marginTop:50,
            },
            title: {
                text: ''
            },
            credits: {
                enabled: false
            },
            xAxis: {
                categories: cat,
                tickmarkPlacement: 'on',
                title: {
                    enabled: false
                }
            },
            tooltip: {
                formatter: function () {
                    return this.x + ': ' + this.y;
                }
            },
            exporting: {
                enabled: false 
            },
            plotOptions: {
                area: {
                    stacking: '',
                    lineColor: '#666666',
                    lineWidth: 0,
                    marker: {
                        lineWidth: 0,
                        lineColor: '#666666'
                    }
                }
            },
            series: _data,
        });
    },

    graphcolumn: function(_id, cat, _data) {
        Highcharts.setOptions({
            colors: ['#A9A9A9','#3c88dc'],
        });
        $('#'+_id).highcharts( {
            
            chart: {
                type: 'column',
                height:300,
                width: (dataObj.width>0?dataObj.width:700),
                top: 130,
            },
            title: {
                text: ''
            },
            xAxis: {
                categories: cat,
                top: 130,
                height:100,
                // width: 400,
            },
            credits: {
                enabled: false
            },                  
            yAxis: {
                gridLineWidth: 0,
                minorGridLineWidth: 0,
                allowDecimals: false,
                min:0,
                top: 130,
                height:100,
                width: 200,
                title: {
                    text: ''
                }
            },
            plotOptions: {
                column: {
                    stacking: 'normal'
                }
            },
            series: _data,
            exporting: { enabled: false } 
        });
    },
    dayGrpah: function(_id, cat,rented ,unrented) {
        Highcharts.setOptions({
            colors: ['#A9A9A9','#3c88dc'],
        });
        $('#'+_id).highcharts( {
            chart: {
                type: 'column',
                height:300,
                width: (dataObj.width>0?dataObj.width:700),
                top: 130,
            },
            title: {
                text: ''
            },
            xAxis: {
                categories: cat,
                top: 130,
                height:100,
                // width: 400,
            },                  
            yAxis: {
                min:0,
                max:20,
                top: 130,
                height:100,
               // width: 200,
                title: {
                    text: ''
                }
            },
            plotOptions: {
                column: {
                    stacking: 'normal'
                }
            },
            series: [{
                name: 'Not Rented',
                data: unrented
            }, {
                name: 'Rented',
                data: rented
            }],exporting: { 
                enabled: false 
            } 
        });
    },
    graphpie: function(_id, rent, unrent) {
        Highcharts.setOptions({
            colors: ['#A9A9A9','#3c88dc'],
        });
        $('#'+_id).highcharts({
            chart: {
                type: 'pie',
                height: 250,
            },
            title: {
                text: false
            },
            credits: {
                enabled: false
            },
            exporting: {
                enabled: false
            },
            tooltip: {
                pointFormat: ''
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: false,
                    }
                }
            },
            series: [{
                name: 'Brands',
                colorByPoint: true,
                data: [{
                        name: 'Not Rented',
                        y: unrent,
                        
                    },
                    {
                        name: 'Rented',
                        y: rent,
                        sliced: true,
                        selected: true
                    }
                ]
            }]
        });
    },
    pieGraph: function(_id, _data, _colors) {
        if(_data == ''){
            _data =[{
                name: 'No Data',
                y: 100 ,
                color: '#f2f2f2',
                sliced: true,
                selected: true,
            }];
        }
        if(_colors == undefined){
            Highcharts.setOptions({
                colors: ['#3c88dc', '#639edf', '#89b6e8', '#bd10e0']
            });
        }else{
            Highcharts.setOptions({
                colors: _colors
            });
        }
        $('#'+_id).highcharts({
            chart: {
                type: 'pie',
            },
            title: {
                text: false
            },
            credits: {
                enabled: false
            },
            exporting: {
                enabled: false
            },
            tooltip: {
                pointFormat: ''
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: false,
                    }
                }
            },
            series: [{
                name: 'Brands',
                colorByPoint: true,
                data: _data
            }]
        });
    },
    emptyGraph: function(_id, cat, r, t) {
        Highcharts.setOptions({
            colors: ['#A9A9A9', '#3c88dc'],
        });
        $('#' + _id).highcharts({
            chart: {
                type: 'column',
                height: 300,
                width: 700,
                top: 130,
            },
            title: {
                text: ''
            },
            xAxis: {
                categories: cat,
                top: 130,
                height: 100,
                // width: 400,
            },
            credits: {
                enabled: false
            },
            yAxis: {
                gridLineWidth: 0,
                minorGridLineWidth: 0,
                min: 0,
                max: 31,
                top: 130,
                height: 100,
                // width: 400,
                title: {
                    text: ''
                }
            },
            plotOptions: {
                column: {
                    stacking: 'percent'
                }
            },
            series: [{
                    name: 'Not On Bid',
                    data: r
                },
                {
                    name: 'On Bid',
                    data: t
                }
            ],
            exporting: {
                buttons: {
                    contextButton: {
                        enabled: false
                    },
                }
            },
            noData: {
                style: {
                    fontWeight: 'bold',
                    fontSize: '15px',
                    color: '#303030'
                }
            }
        });
    }
}





$.datepicker.setDefaults({
    dateFormat: 'yy-mm-dd'
});
function showDatePicker(_id) {
    _id = _id==undefined?'':_id;
    $('#custom_date_range'+_id).show();
    $('#custom_date'+_id).hide();
}
function cancelDatePicker(_id) {
    _id = _id==undefined?'':_id;
    $('#custom_date_range'+_id).hide();
    $('#custom_date'+_id).show();
    $('#custom_date_range'+_id+' input[name=from_date]').val(''); 
    $('#custom_date_range'+_id+' input[name=to_date]').val('');
}
function sum(input){
    if (toString.call(input) !== "[object Array]")
        return false;
    var total =  0;
    for(var i=0;i<input.length;i++){                  
    if(isNaN(input[i])){
            continue;
        }
        total += Number(input[i]);
    }
    return total;
}
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
function months(d) {
    var t = new Date(d);
    return monthShortNames[t.getMonth()];
} 
function dateFormat2(d) {
    var t = new Date(d);
    return t.getDate();
} 
function dateFunction(_id) {
    var start = $("#from_date"+_id).datepicker("getDate");
    var end = $("#to_date"+_id).datepicker("getDate");
    days = (end - start) / (1000 * 60 * 60 * 24);
    if (Math.round(days) < 30) {
        $('.day-month-filter').find('li').each(function() {
            $(this).removeClass('active');
            $('.day-month-filter').find('li').eq(0).addClass('active');
        })
        return 'D';
    } else if (Math.round(days) > 30 && Math.round(days) < 365) {
        $('.day-month-filter').find('li').each(function() {
            $(this).removeClass('active');
        });
        $('.day-month-filter').find('li').eq(1).addClass('active');
        return 'M';
    } else if (Math.round(days) > 365) {
        $('.day-month-filter').find('li').each(function() {
            $(this).removeClass('active');
        })
        $('.day-month-filter').find('li').eq(2).addClass('active');
        return 'Y';
    }
} 
function get_date_restriction( element ) {
    let date;
    try {
      date = $.datepicker.parseDate( dateFormat, element.value );
    } catch( error ) {
        console.log(error);
      date = null;
    }
    console.log(date);
    return date;
}
function custom_graph(_id) {
    var from = $("#from_date"+_id).val();
    var to = $(" #to_date"+_id).val();
    var day = dateFunction(_id);
    window['graphConfig'+_id].from = from;
    window['graphConfig'+_id].to = to;
    window['graphConfig'+_id].filter = day;
    generate_graph( window['graphConfig'+_id] );
}
function get_graph(_self, _filterBy, _id) {
    $(_self).parent().find('li').each(function() {
        $(this).removeClass('active');
    })
    $(_self).addClass('active');
    if( window['graphConfig'+_id].from != undefined )
        window['graphConfig'+_id].from = false;
    if( window['graphConfig'+_id].to != undefined )
        window['graphConfig'+_id].to = false;
    window['graphConfig'+_id].filter = _filterBy;
    generate_graph(window['graphConfig'+_id]);
}

//function generate_graph(_id, _filter, url, from, to, userId ){
function generate_graph( config ){
    let _url = BASEURL,
    _id = '',
    _filter = 'M',
    graphContainer = '#graphContainer';
    let postData = {};
    if(config){
        if(config.url)
            _url = config.url;
        if(config.id)
            _id = config.id;
        if(config.filter)
            _filter = config.filter;
        if(config.from)
            postData.from = config.from;
        if(config.to)
            postData.to = config.to;
        if(config.userId)
            postData.userId = config.userId;
        if(config.fd)
            postData.fd = config.fd;
        if(config.graphContainer)
            graphContainer = config.graphContainer;
    }
    postData.filter = _filter;
    postData.id = _id;
    if( config.customFunction != undefined ){
        window[ config.customFunction ](postData);
    }
    $.ajax({
        beforeSend : function() {
            $(graphContainer + ' #graph_loader'+_id).addClass('data-loader');
        },
        type: 'POST',
        url: _url,
        data: postData,
        dataType : "json",
        success: function(html) {
            $(graphContainer + ' #graph_loader'+_id).removeClass('data-loader');
            
            let cat = [],
            unrented = [],
            rented = [],
            rented2 = [],
            rented3 = [],
            areaData = [],
            set = [],
            notRented = 0,
            onlyRented = 0;
            
            res = html;
            if( res.unrent != undefined ){
                $.each(res.unrent, function(i,e){
                    if(_filter == 'D')
                        i = i.replace('.', '');
                    cat.push(i);
                    unrented.push(e); 
                });
                if( res.chartName != undefined ){
                  if(res.chartName.unrented != undefined){
                    let recordsData = { name: res.chartName.unrented, data: unrented.map(Number) };
                    areaData.push( recordsData );
                  }
                }
                notRented = sum(unrented);
            }
            if(res.records != undefined){
                $.each(res.records, function(i,e){
                    rented.push(e); 
                    if(e != 0){
                        set.push(e); 
                    }
                });
                if( res.chartName != undefined ){
                  if(res.chartName.records != undefined){
                    let recordsData = { name: res.chartName.records, data: rented.map(Number) };
                    areaData.push( recordsData );
                  }
                }
                onlyRented = sum(rented);
            }
            if(res.records2 != undefined){
                $.each(res.records2, function(i,e){
                    rented2.push(e); 
                });
                if( res.chartName != undefined ){
                  if(res.chartName.records2 != undefined){
                    let recordsData = { name: res.chartName.records2, data: rented2.map(Number) };
                    areaData.push( recordsData );
                  }
                }
            }
            if(res.records3 != undefined){
                $.each(res.records3, function(i,e){
                    rented3.push(e); 
                });
                if( res.chartName != undefined ){
                  if(res.chartName.records3 != undefined){
                    let recordsData = { name: res.chartName.records3, data: rented3.map(Number) };
                    areaData.push( recordsData );
                  }
                }
            }
            if(res.records_total != undefined){
                areaData = [];
                unrented = [];
                rented = [];
                let max_number = 0;
                $.each(res.records_total, function(i,e){
                    if(e > max_number)
                        max_number = parseInt(e);
                    rented.push(e); 
                });
                if(max_number <= 0){
                    max_number = 10;
                }
                for($i=0; $i<rented.length; $i++){
                    unrented.push( (max_number - rented[$i]) );
                }
                areaData.push( { name: res.chartName.records_total.replace('On ', 'Not On '), data: unrented.map(Number) } );
                
                if( res.chartName != undefined ){
                  if(res.chartName.records_total != undefined){
                    let recordsData = { name: res.chartName.records_total, data: rented.map(Number) };
                    areaData.push( recordsData );
                  }
                }
            }
            //console.log(areaData);
            
            if( config.graphType == 'area' ){
                bidHistryGraph.areaGraph(graphContainer.substr(1)+' .graphDiv', cat, areaData);
            }else{
                let pieName = 'Rent'
                if( res.chartName != undefined ){
                  if(res.chartName.pieName != undefined){
                    pieName = res.chartName.pieName;
                  }
                }
                bidHistryGraph.graphcolumn( graphContainer.substr(1)+' .graphDiv', cat, areaData );
                $(graphContainer+" #daysCount").html('<span class="rented-not-rented-wrap"><span class="rented-domains"> Days '+pieName+' : ' + onlyRented + '</span><span class="not-rented-domains">Days Not '+pieName+' : ' + notRented + '</span></span>');
                bidHistryGraph.graphpie(graphContainer.substr(1)+' .pieChart', onlyRented, notRented);
            }
        },error: function() {
            alertigo('failed, Please try again',{ color: 'red' });
            $(graphContainer + ' #graph_loader'+_id).removeClass('data-loader');
            $("#rent-tab4-"+_id).removeClass('data-loader');
        }
    });
}

function ExpandChart1(_func, _id) {
    window['graphConfig'+_func] = graphConfig;
    window['graphConfig'+_func].id = _func;
    window['graphConfig'+_func].from = false;
    window['graphConfig'+_func].to = false;
    window['graphConfig'+_func].format = 'M';
    window['graphConfig'+_func].graphContainer = '#'+_id;
    
    if($('#actionMenu'+_func).hasClass('active')){
        $('#'+_id).slideUp(500);
        setTimeout(function() {
            $('#actionMenu'+_func).removeClass('active');
        }, 500);
    } else {
        if($('.tabpane-graph-rectangle').hasClass('active')){
            $('.history-expand').slideUp(600);
            setTimeout(function() {
                $('.tabpane-graph-rectangle').removeClass('active');
            }, 700);

            $('#'+_id).delay(800).slideDown(800);
            setTimeout(function() {
                $('#actionMenu'+_func).addClass('active');
            }, 800);
            generate_graph(window['graphConfig'+_func]);
        }else{
            $('#actionMenu'+_func).addClass('active');
            $('#'+_id).slideDown(800);
            generate_graph(window['graphConfig'+_func]);
        }
    }
    let from = $("#from_date"+_func).datepicker().on( "change", function() {
        to.datepicker( "option", "minDate", get_date_restriction( this ) );
    });
    let to = $("#to_date"+_func).datepicker().on( "change", function() {
        from.datepicker( "option", "maxDate", get_date_restriction( this ) );
    });
}
function statistic_graph(_func, _id, _div, _customFunction='') {
    let graphConfig = {
        'url': BASEURL+'statistics/statistics_graph',
        'filter': 'M',
        'graphType': 'area'
    }
    if( _customFunction && _customFunction!==''){
        graphConfig.customFunction = _customFunction;
    }
    
    window['graphConfig'+_func] = graphConfig;
    window['graphConfig'+_func].fd = _id;
    window['graphConfig'+_func].id = _func;
    window['graphConfig'+_func].from = false;
    window['graphConfig'+_func].to = false;
    window['graphConfig'+_func].format = 'M';
    window['graphConfig'+_func].graphContainer = '#'+_div;
    generate_graph(window['graphConfig'+_func]);
    let from = $("#from_date"+_func).datepicker().on( "change", function() {
        to.datepicker( "option", "minDate", get_date_restriction( this ) );
    });
    let to = $("#to_date"+_func).datepicker().on( "change", function() {
        from.datepicker( "option", "maxDate", get_date_restriction( this ) );
    });
}