


var KendoComponents = {};

KendoComponents.resultGraphData = {};
KendoComponents.role_community = false;



KendoComponents.init = function(role_community) {
    kendo.culture("".replace('_', '-'));

    KendoComponents.role_community = role_community;

    function getSelectedBusinessUnit() {
        return $("#business-unit-dashboard-dropdown-2").data('kendoDropDownList').value();
    }

    $("#business-unit-dashboard-dropdown-2").kendoDropDownList({
        dataTextField: "groupname",
        dataValueField: "groupid",
        template: '#: groupid # | #: groupname #',
        valueTemplate: '#: groupid # | #: groupname #',
        height: 100,
        select: function(e) {

            var dataItem = this.dataItem(e.item.index());

            for (var i = 0; i < KendoComponents.resultGraphData.length; i++) {
                if (KendoComponents.resultGraphData[i].groupid == dataItem.groupid) {
                    KendoComponents.updateSearchResultGraphs(KendoComponents.resultGraphData[i]);
                    break;
                }
            }

            
        }
    });

    

    $("#start-month-picker").kendoDatePicker({
        depth: "year",
        start: "year",
        format: "MMMM yyyy",
        parseFormats: ["yy/MM"],
        footer: " ",
        min: new Date(2015, 0, 1),
        change: function(e) {
            if (validateDates()) {
                $("#date-error-label").hide();
                document.getElementById("date-selectors").style.backgroundColor = "transparent";
                //            } else {
                //                $("#date-error-label").show();
                //                document.getElementById("date-selectors").style.backgroundColor = "rgb(247, 233, 233)";
            }
        }
    });

    $("#end-month-picker").kendoDatePicker({
        depth: "year",
        start: "year",
        format: "MMMM yyyy",
        parseFormats: ["yy/MM"],
        footer: " ",
        min: new Date(2015, 0, 1),
        change: function(e) {
            if (validateDates()) {
                $("#date-error-label").hide();
                document.getElementById("date-selectors").style.backgroundColor = "transparent";
            } else {
                $("#date-error-label").show();
                document.getElementById("date-selectors").style.backgroundColor = "rgb(247, 233, 233)";
            }
        }
    });

    function toggleSuggestionLimitMessage(dataBoundEvent) {
        var suggestionLimit = 200;
        var dropdown = dataBoundEvent.sender;
        var dataItems = dropdown.dataSource.data();
        var $message = dropdown.element.closest('.form-group').find('.too-many-results-message');
        $message.toggle(dataItems.length > suggestionLimit);
    }

    $("#date-error-label").hide();
    if (!KendoComponents.role_community) {

        if (document.getElementById("concern-multiselect") != null) {
            var concernMultiselect = $("#concern-multiselect").kendoMultiSelect({
                autoBind: true,
                dataTextField: "name",
                dataValueField: "id",
                dataSource: {
                    serverFiltering: true,
                    transport: {
                        dataType: "jsonp",
                        read: baseurl + '/secure/concern.do?time=' + getTimeStamp(),
                        parameterMap: function(options, operation) {
                            return {
                                name: concernMultiselect ? concernMultiselect.input.val() : ''
                            }
                        }
                    },
                    schema: {
                        data: "items"
                    }
                },
                delay: 500,
                select: function(e) {
                    if ($("#search-alert").is(":visible")) $("#search-alert").hide();
                    Map.setAutomaticExtent(true);
                },
                change: function(e) {
                    $("#managers-multiselect").data("kendoMultiSelect").dataSource.read({
                        concernid: KendoComponents.getConcernIds(),
                        group: []
                    });
                    $("#invoices-multiselect").data("kendoMultiSelect").dataSource.read({
                        concernid: KendoComponents.getConcernIds(),
                        managerid: KendoComponents.getManagerIds(),
                        group: []
                    });
                    $("#consumers-multiselect").data("kendoMultiSelect").dataSource.read({
                        concernid: KendoComponents.getConcernIds(),
                        managerid: KendoComponents.getManagerIds(),
                        invoiceid: KendoComponents.getInvoiceIds(),
                        group: []
                    });
                },
                dataBound: function(e) {
                    toggleSuggestionLimitMessage(e);
                }
            }).data('kendoMultiSelect');
        }

        if (document.getElementById("managers-multiselect") != null) {
            var managersMultiselect = $("#managers-multiselect").kendoMultiSelect({
                autoBind: !role_admin,
                dataTextField: "name",
                dataValueField: "id",
                dataSource: {
                    serverFiltering: true,
                    transport: {
                        dataType: "jsonp",
                        read: baseurl + '/secure/manager.do?time=' + getTimeStamp(),
                        parameterMap: function(options, operation) {
                            var _name = managersMultiselect ? managersMultiselect.input.val() : '';
                            return {
                                concernid: KendoComponents.getConcernIds(),
                                managerid: KendoComponents.getManagerIds(),
                                name: _name
                            }
                        }
                    },
                    schema: {
                        data: "items"
                    },
                    requestEnd: function(e) {
                        if (e.type === "read") {
                            if (!role_admin && e.response.items.length === 0) {
                                $("#managers-multiselect-wrapper").hide();
                            } else {
                                $("#managers-multiselect-wrapper").show();
                            }
                        }
                    }
                },
                delay: 500,
                select: function(e) {
                    if ($("#search-alert").is(":visible")) $("#search-alert").hide();
                    Map.setAutomaticExtent(true);
                },
                change: function(e) {
                    $("#invoices-multiselect").data("kendoMultiSelect").dataSource.read({
                        concernid: KendoComponents.getConcernIds(),
                        managerid: KendoComponents.getManagerIds(),
                        group: []
                    });
                    $("#consumers-multiselect").data("kendoMultiSelect").dataSource.read({
                        concernid: KendoComponents.getConcernIds(),
                        managerid: KendoComponents.getManagerIds(),
                        invoiceid: KendoComponents.getInvoiceIds(),
                        group: []
                    });
                },
                dataBound: function(e) {
                    toggleSuggestionLimitMessage(e);
                }
            }).data('kendoMultiSelect');
        }

        if (document.getElementById("invoices-multiselect") != null) {
            var invoicesMultiselect = $("#invoices-multiselect").kendoMultiSelect({
                autoBind: !role_admin,
                dataTextField: "name",
                dataValueField: "id",
                dataSource: {
                    serverFiltering: true,
                    transport: {
                        dataType: "jsonp",
                        read: {
                            url: baseurl + '/secure/invoice.do?time=' + getTimeStamp()
                        },
                        parameterMap: function(options, operation) {
                            var _name = invoicesMultiselect ? invoicesMultiselect.input.val() : '';
                            return {
                                concernid: KendoComponents.getConcernIds(),
                                managerid: KendoComponents.getManagerIds(),
                                invoiceid: KendoComponents.getInvoiceIds(),
                                name: _name
                            }
                        }
                    },
                    schema: {
                        data: "items"
                    }
                },
                delay: 500,
                change: function(e) {
                    $("#consumers-multiselect").data("kendoMultiSelect").dataSource.read({
                        concernid: KendoComponents.getConcernIds(),
                        managerid: KendoComponents.getManagerIds(),
                        invoiceid: KendoComponents.getInvoiceIds(),
                        group: []
                    });

                    KendoComponents.sendDataToMap();
                },
                select: function(e) {
                    if ($("#search-alert").is(":visible")) $("#search-alert").hide();
                    Map.setAutomaticExtent(true);
                },
                dataBound: function(e) {
                    KendoComponents.sendDataToMap();

                    toggleSuggestionLimitMessage(e);
                }
            }).data('kendoMultiSelect');
        }

        if (document.getElementById("consumers-multiselect") != null) {
            var consumersMultiselect = $("#consumers-multiselect").kendoMultiSelect({
                autoBind: !role_admin,
                dataTextField: "name",
                dataValueField: "id",
                dataSource: {
                    serverFiltering: true,
                    transport: {
                        dataType: "jsonp",
                        read: {
                            url: baseurl + '/secure/customer.do?time=' + getTimeStamp()
                        },
                        parameterMap: function(options, operation) {
                            var _name = consumersMultiselect ? consumersMultiselect.input.val() : '';
                            return {
                                concernid: KendoComponents.getConcernIds(),
                                managerid: KendoComponents.getManagerIds(),
                                invoiceid: KendoComponents.getInvoiceIds(),
                                name: _name
                            }
                        }
                    },
                    schema: {
                        data: "items"
                    }
                },
                delay: 500,
                change: function(e) {
                    KendoComponents.sendDataToMap();
                },
                select: function(e) {
                    if ($("#search-alert").is(":visible")) $("#search-alert").hide();
                    Map.setAutomaticExtent(true);
                },
                dataBound: function(e) {
                    KendoComponents.sendDataToMap();

                    toggleSuggestionLimitMessage(e);
                }
            }).data('kendoMultiSelect');
        }
    } else {
        $("#consumers-multiselect").kendoMultiSelect({
            autoBind: false,
            dataTextField: "name",
            dataValueField: "id",
            delay: 500,
            filter: 'contains',
            select: function(e) {
                if ($("#search-alert").is(":visible")) $("#search-alert").hide();
                Map.setAutomaticExtent(true);
            },
            dataBound: function(e) {
                KendoComponents.sendDataToMap();

                toggleSuggestionLimitMessage(e);
            }
        });

        $("#modalSearch-community-multiselect").kendoMultiSelect({
            dataTextField: "name",
            dataValueField: "account",
            dataSource: {
                transport: {
                    read: {
                        dataType: "json",
                        url: baseurl + "/secure/getcommunities.do"
                    }
                }
            }
        });
    }


    $("#products-multiselect").kendoMultiSelect({
        dataTextField: "name",
        dataValueField: "id",
        filter: "contains",
        dataSource: products
    });

    $('#graph-tab [id^="search-result-chart"]').each(function() {
        var $graph = $(this);
        $graph.parent().resizable({
            resize: function() {
                KendoComponents.resizeGraph($graph);
            }
        });
    });
};

KendoComponents.clearSelections = function() {
    // Clear data selectors
    $("#start-month-picker").data("kendoDatePicker").value('');
    $("#end-month-picker").data("kendoDatePicker").value('');
    // Clear values of customer selections
    KendoComponents.setMultiSelectIds('concern-multiselect', '');
    KendoComponents.setMultiSelectIds('managers-multiselect', '');
    KendoComponents.setMultiSelectIds('invoices-multiselect', '');
    KendoComponents.setMultiSelectIds('consumers-multiselect', '');
    KendoComponents.setMultiSelectIds('products-multiselect', '');

    // If user is admin or inside, empty the datasets of three lowest level.
    if (role_admin) {
        if (document.getElementById("managers-multiselect") != null)
            $("#managers-multiselect").data("kendoMultiSelect").dataSource.data([]);
        if (document.getElementById("invoices-multiselect") != null)
            $("#invoices-multiselect").data("kendoMultiSelect").dataSource.data([]);
        $("#consumers-multiselect").data("kendoMultiSelect").dataSource.data([]);
    }
    // update map.
    KendoComponents.sendDataToMap();

    return false;
};

KendoComponents.sendDataToMap = function() {
    if(KendoComponents.getConcernIds().length === 0
        && KendoComponents.getManagerIds().length === 0
        && KendoComponents.getInvoiceIds().length === 0
        && KendoComponents.getConsumerIds().length === 0) {
        Map.addInvoicesAndCustomers({});
        return;
    }

    var _invoices;
    if (KendoComponents.role_community) {
        _invoices = [];
    } else if (KendoComponents.getInvoiceIds().length === 0){
        if ($("#invoices-multiselect").data("kendoMultiSelect") != null)
        {
            _invoices = $("#invoices-multiselect").data("kendoMultiSelect").dataSource.data();
        }
    } else {
        _invoices = $("#invoices-multiselect").data("kendoMultiSelect").dataItems();
    }

    var _customers;
    // 15.12.2016: Always show all customers.
    //if(KendoComponents.getConsumerIds().length === 0) {
        _customers = $("#consumers-multiselect").data("kendoMultiSelect").dataSource.data();
    //} else {
    //    _customers = $("#consumers-multiselect").data("kendoMultiSelect").dataItems()
    //}
    
    
    Map.addInvoicesAndCustomers({
        invoices: _invoices,
        customers: _customers
    });
};

/**
 * Read and format string from start and end date selectors.
 */
KendoComponents.PeriodStringDateFormat = "MM/yy"
KendoComponents.getPeriodString = function() {
    return KendoComponents.getSearchStartDateValue(KendoComponents.PeriodStringDateFormat) 
        + " - " 
        + KendoComponents.getSearchEndDateValue(KendoComponents.PeriodStringDateFormat);
};

KendoComponents.getProductIds = function() {
    return $("#products-multiselect").data("kendoMultiSelect").value();
};

KendoComponents.setMultiSelectIds = function(multiSelectName, idsSeparatedWithComma) {
    if (document.getElementById(multiSelectName) == null) return;
    $("#" + multiSelectName).data("kendoMultiSelect").value(idsSeparatedWithComma.split(','));
};

KendoComponents.getMultiSelectIds = function(multiSelectName) {
    if (document.getElementById(multiSelectName) == null) return "";
    var ids = $("#" + multiSelectName).data("kendoMultiSelect").value();
    if (ids == null || ids.length == 0) return "";
    return ids.join();
};

KendoComponents.getProductIds = function() {
    return KendoComponents.getMultiSelectIds("products-multiselect");
};

KendoComponents.getConcernIds = function() {
    return KendoComponents.getMultiSelectIds("concern-multiselect");
};

KendoComponents.getManagerIds = function() {
    return KendoComponents.getMultiSelectIds("managers-multiselect");
};

KendoComponents.getInvoiceIds = function() {
    return KendoComponents.getMultiSelectIds("invoices-multiselect");
};

KendoComponents.getConsumerIds = function() {
    return KendoComponents.getMultiSelectIds("consumers-multiselect");
};

KendoComponents.formatNumber = function(number, decimals) {
    var num = number.toFixed(decimals);
    return $.number(number, decimals, '.', ' ');
};

KendoComponents.getSelectedInvoices = function() {
    var invoices = [];
    var allItems = $("#invoices-multiselect").data("kendoMultiSelect").dataSource.data().slice();
    var selectedIds = KendoComponents.getInvoiceIds();
    if (selectedIds.length == 0)
        return allItems;
    for (id in selectedIds)
        for (item in allItems)
            if (allItems[item].id == selectedIds[id])
                invoices.push(item);

    return invoices;
};

KendoComponents.getSelectedConsumers = function() {
    var consumers = [];
    var allItems = $("#consumers-multiselect").data("kendoMultiSelect").dataSource.data().slice();
    var selectedIds = KendoComponents.getConsumerIds();
    if (selectedIds.length == 0)
        return allItems;
    for (id in selectedIds)
        for (item in allItems)
            if (allItems[item].id == selectedIds[id])
                consumers.push(item);

    return consumers;
};

/**
 * Base method for update functions below.
 */
KendoComponents.updateKendoComponentDataSource = function(componentName, componentId, data) {
    var component = $("#" + componentId).data(componentName);
    var dataSource = new kendo.data.DataSource({
        data: data
    });
    component.setDataSource(dataSource);
    dataSource.fetch();

    if (componentName == "kendoDropDownList")
        component.select(0);

    component.refresh();
};

/**
 * Udates KendoUI Multiselect components datasource
 */
KendoComponents.updateMultiSelectDataSource = function(componentId, data) {
    KendoComponents.updateKendoComponentDataSource("kendoMultiSelect", componentId, data);
};

/**
 * Udates KendoUI dropdown components datasource
 */
KendoComponents.updateDropdownDataSource = function(componentId, data) {
    KendoComponents.updateKendoComponentDataSource("kendoDropDownList", componentId, data);
};

KendoComponents.updateSearchResultGraphs = function(object) {
    function isAllZeros(key) {
        return object.data.every(function(data) {
            return data[key] == 0;
        });
    }

    var sharedSettings = {
        categoryAxis: [{
            name: 'year',
            categories: object.data.map(function(d) { return d.date; }),
            labels: {
                visible: true,
                background: "white",
                rotation: 270,
                padding: {
                    right: -10 // Counteract majorTicks.size. Use right due to rotation.
                }
            },
            majorGridLines: {
                visible: false
            },
            minorGridLines: {
                visible: false
            },
            majorTicks: {
                size: 15
            },
            minorTicks: {
                visible: true,
                step: 2
            }
        }, {
            // A dummy category axis so that the columns will stay put even though 
            // axisCrossingValues are changed.
            name: 'dummy',
            visible: false,
            categories: object.data.map(function(d) { return d.date; }),
        }],
        valueAxis: {
            majorGridLines: {
                visible: true
            },
            minorGridLines: {
                visible: false
            },
            axisCrossingValues: [-Number.MAX_VALUE, 0]
        },
        seriesDefaults: {
            border: {
                width: 1,
                color: function(e) {
                    return e.series.color;
                }
            },
            labels: {
                visible: true,
                background: true ? 'rgba(255, 255, 255, 0.5)' : 'transparent',
                rotation: 270,
                position: "outsideEnd",
                
            },
            overlay: {
                gradient: 'none'
            },
            spacing: 1
        },
        transitions: false,
        legendItemClick: function(e) {
            e.preventDefault();
        }
    };

    // All label templates must be run through this function. Currently, it only adds a zero-width
    // space to it, which should not affect rendering, but allows us to reliably find the label
    // elements in post-processing.
    function labelTemplate(template) {
        return '\u200B' + template;
    }

    if (document.getElementById("search-result-chart-1") != null) {
        $("#search-result-chart-1").empty();
        if(typeof object.data[0].total !== 'undefined') {
            $("#search-result-chart-1").show();
            $("#search-result-chart-1").parentsUntil("#results").show();
            $("#search-result-chart-1").kendoChart($.extend(true, {}, sharedSettings, {
                title: "Kustannukset €",
                legend: {
                    visible: false
                },
                valueAxis: {
                    labels: {
                        template: "#= value # €"
                    }
                },
                series: [{
                    type: "column",
                    data: object.data,
                    field: "total",
                    //categoryField: 'date',
                    categoryAxis: 'dummy',
                    color: "#29AAE3",
                    tooltip: {
                        visible: true,
                        template: "#= data.dataItem.date #: #= KendoComponents.formatNumber(value, 2) # €"
                    },
                    labels: {
                        template: labelTemplate("#= KendoComponents.formatNumber(value, 2) # €"),
                        padding: {
                            bottom: -2,
                            top: -2
                        }
                    }
                }]
            }));
        } else {
            $("#search-result-chart-1").hide();
            $("#search-result-chart-1").parentsUntil("#results").hide();
        }
    }

    $("#search-result-chart-2").empty();
    $("#search-result-chart-2").kendoChart($.extend(true, {}, sharedSettings, {
        title: "Punnittu paino (t)",
        legend: {
            visible: false,
            position: "custom",
            orientation: "horizontal",
            width: 1000,
            height: 10
        },
        valueAxis: {
            labels: {
                template: "#= value # t"
            }
        },
        
        seriesDefaults: {
            type: "column",
            tooltip: {
                visible: true,
                template: "#= data.dataItem.date #: #= KendoComponents.formatNumber(value, 3) # t"
            }
        },
        series: [{
            field: "weight",
            //categoryField: 'date',
            categoryAxis: 'dummy',
            data: object.data,
            name: 'Punnittu paino',
            color: "#68696B",
            
            labels: {
                visible: true,
                template: labelTemplate("#= KendoComponents.formatNumber(value, 3) # t"),
                
                position: "outsideEnd",
                
                padding: {
                    bottom: -2,
                    top: -2
                }
            }
        }
        
        ]
    }));

    $("#search-result-chart-3").empty();
    $("#search-result-chart-3").kendoChart($.extend(true, {}, sharedSettings, {
        title: "Tulossa kierrätysprosentti vuonna 2024",
        legend: {
            visible: true,
            position: "custom",
            orientation: "horizontal",
            width: 1000,
            height: 10
        },
        
        chartArea: {
            margin: {
                right: 25
            }
        },
        
        valueAxis: {
            max: 100,
            
            labels: {
                template: "#= value # %"
            }
        },
        series: [{
            name: "Materiaalihyötyaste",
            type: "column",
            field: "recycling",
            //categoryField: 'date',
            categoryAxis: 'dummy',
            data: object.data,
            color: "#8CC63E",
            stack: {
                group: 'utilization'
            },
            tooltip: {
                visible: true,
                template: "#= data.dataItem.date #: #= KendoComponents.formatNumber(value, 2) # %"
            },
            labels: {
                template: labelTemplate("#= value != 0 ? KendoComponents.formatNumber(value, 2) + ' %' : '' #"),
                padding: {
                    bottom: -2,
                    top: -2
                },
                border: {
                    color: "transparent"
                },
                
                
                position: "insideEnd"
                
                
                
                , visible: false
            },
            visibleInLegend: !isAllZeros('recycling')
        }
        
        , {
            name: "Energiahyötyaste",
            type: "column",
            field: "utilization",
            //categoryField: 'date',
            categoryAxis: 'dummy',
            data: object.data,
            color: "#cf691e",
            stack: {
                group: 'utilization'
            },
            tooltip: {
                visible: true,
                template: "#= data.dataItem.date #: #= KendoComponents.formatNumber(value, 2) # %"
            },
            labels: {
                
                template: labelTemplate("#= KendoComponents.formatNumber(data.dataItem.recycling, 2) + ' % / ' + KendoComponents.formatNumber(data.dataItem.utilization, 2) + ' %' #"),
                
                
                padding: {
                    bottom: -2,
                    top: -2
                },
                
                position: !isAllZeros('recycling') ? 'insideBase' : 'insideEnd',
                
                
                
                visual: function(e) {
                    var recyclingSign = e.text[0] === '-' ? -1 : 1;
                    var utilizationSign = e.text.indexOf('/ -') >= 0 ? -1 : 1;
                    var visual = e.createVisual();

                    if(utilizationSign < 0) {
                        // Flip the text
                        var parts = e.text.split(' / ', 2);
                        visual.children[1].content(parts[1] + ' / ' + parts[0]);
                    }

                    var transform = visual.transform();
                    var bbox = visual.bbox();
                    var direction = utilizationSign > 0 ? -1 : 1;
                    if(transform) {
                        transform.translate(direction * bbox.size.height / 2, 0);
                    }
                    return visual;
                }
                
            },
            visibleInLegend: !isAllZeros('utilization')
        }
        
        ]
    }));

    $("#search-result-chart-4").empty().kendoChart($.extend(true, {}, sharedSettings, {
        title: "null",
        legend: {
            visible: false,
        },
        valueAxis: {
            max: 0.5,
            labels: {
                template: "#= value # kg"
            }
        },
        series: [{
            type: "column",
            field: "handlingco2Weight",
            //categoryField: 'date',
            categoryAxis: 'dummy',
            data: object.data,
            color: "#C64A1A",
            tooltip: {
                visible: true,
                template: "#= data.dataItem.date #: #= KendoComponents.formatNumber(value, 2) # kg"
            },
            labels: {
                template: labelTemplate("#= KendoComponents.formatNumber(value, 2) # kg"),
                padding: {
                    bottom: -2,
                    top: -2
                },
                border: {
                    color: "transparent"
                },
                position: "outsideEnd"
            }
        }]
    }));

    $("#search-result-chart-fill-rate").empty().kendoChart($.extend(true, {}, sharedSettings, {
        title: "Täyttöaste",
        legend: {
            visible: false,
        },
        valueAxis: {
            max: 100,
            labels: {
                template: "#= value # %"
            }
        },
        series: [{
            type: "column",
            field: "fillRate",
            //categoryField: 'date',
            categoryAxis: 'dummy',
            data: object.data,
            color: "#8CC63E",
            tooltip: {
                visible: true,
                template: "#= data.dataItem.date #: #= KendoComponents.formatNumber(value, 2) # %"
            },
            labels: {
                template: labelTemplate("#= KendoComponents.formatNumber(value, 2) # %"),
                padding: {
                    bottom: -2,
                    top: -2
                },
                border: {
                    color: "transparent"
                },
                position: "outsideEnd"
            }
        }]
    }));
    
    KendoComponents.resizeGraphs();
};

KendoComponents.resizeGraph = function($graph) {
    var graph = $graph.data('kendoChart');
    if(typeof graph === 'undefined' || graph === null || !($graph.is(":visible")) ) {
        return;
    }
    
    var $wrapper = $(graph.wrapper);
    var $parent = $wrapper.parent();
    if($parent.is('[style]')) {
        // parent has been manually resized
        var height = $parent.height() - $parent.children(':not(.k-chart)').height();
    } else {
        var height = $wrapper.width() / Math.sqrt(2); // Same as A-series papers
    }
    graph.setOptions({
        chartArea: {
            height: height
        }
    });
    graph.redraw();
    
    transformChartLegend($graph);

    
    moveSeriesLabels($graph);
    
}

KendoComponents.resizeGraphs = function() {
    var graphs = [
        $("#search-result-chart-1"),
        $("#search-result-chart-2"),
        $("#search-result-chart-3"),
        $("#search-result-chart-4"),
        $('#search-result-chart-fill-rate')
    ];
    
    for(var i = 0; i < graphs.length; ++i) {
        KendoComponents.resizeGraph(graphs[i]);
    }
}

function transformChartLegend($chart) {
    var graph = $chart.data("kendoChart");

    if(graph && graph.options.legend.visible) {
        var $g = $chart.find('svg > g > g:nth-of-type(4)');
        if($g.length === 0) { // If the legend is actually hidden (everything is zero), exit
            return;
        }

        var offsetX = $chart.width() - 30;
        var offsetY = $chart.height() / 2 + $g.get(0).getBBox().width / 2;
        
        graph.options.legend.offsetX = offsetX;
        graph.options.legend.offsetY = offsetY;
        graph.redraw();
        
        $g = $chart.find('svg > g > g:nth-of-type(4)'); // redraw detaches the original
        $g.attr('class', 'chart-legend');
        $g.attr('transform', 'rotate(-90, ' + offsetX + ', ' + offsetY + ')');
    }
}


function moveSeriesLabels($chart) {
    var $svg = $chart.find('svg');
    if($svg.length === 0) {
        return;
    }
    
    function contains(container, containee) {
        return container.top <= containee.top
            && container.bottom >= containee.bottom
            && container.left <= containee.left
            && container.right >= containee.right;
    }

    function intersects(a, b) {
        return a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;
    }

    var $labels = $svg.find('text:contains(\u200B)');

    var plotArea = $svg.find('> g > path:last').get(0);
    var plotRect = plotArea.getBoundingClientRect();
    $labels.each(function() {
        var labelRect = this.getBoundingClientRect();
        if(!contains(plotRect, labelRect)) {
            
            var diff = plotRect.top - labelRect.top;
            if(diff < 0) {
                diff = plotRect.bottom - labelRect.bottom;
            }
            diff = diff > 0 ? diff + 1 : diff - 1; // Add some slack
            diff = -diff;
            
            

            function getCoordinate(text, xy) {
                var value = +text[xy];
                if(isNaN(value)) {
                    value = text[xy].baseVal.getItem(0).value;
                }
                return value;
            }

            function setCoordinate(text, xy, value) {
                if(typeof text[xy] === 'object') {
                    text[xy].baseVal.getItem(0).value = value;
                } else {
                    text[xy] = value;
                }
            }

            var x = getCoordinate(this, 'x');
            x += diff;
            setCoordinate(this, 'x', x);

            $(this).parent().find('path').attr('transform', 'translate(' + diff + ' 0)');
        }
    });

    // Hide labels if they are outside of the chart area.
    $labels.each(function() {
        var labelRect = this.getBoundingClientRect();
        if(!contains(plotRect, labelRect)) {
            $(this).parent().hide();
        }
    });

    // Hide labels that collide. Only one of the colliding labels is hidden.
    $labels.each(function() {
        var that = this;
        $labels.each(function() {
            if(that === this)
                return;
            var thatIsVisible = $(that).css('display') !== 'none';
            var thisIsVisible = $(this).css('display') !== 'none';
            if(thatIsVisible && thisIsVisible && intersects(that.getBoundingClientRect(), this.getBoundingClientRect())) {
                $(this).hide();
            }
        });
    });
}


/**
 * Base method for date component getters above.
 */
KendoComponents.getDateValueFromKendo = function(componentId, format) {
    var value = $("#" + componentId).data("kendoDatePicker").value();

    if (format) {
        return kendo.toString(value, format);
    } else {
        return value;
    }
};

KendoComponents.getSearchStartDateValue = function(format) {
    return KendoComponents.getDateValueFromKendo("start-month-picker", format);
};

KendoComponents.getSearchEndDateValue = function(format) {
    return KendoComponents.getDateValueFromKendo("end-month-picker", format);
};

KendoComponents.openMultiSelect = function(multiSelectName) {
    $("#" + multiSelectName).data("kendoMultiSelect").open();
}


