/*
    $Revision$
    $Id$

    File:           alg_locatie.js

    Description:    Sample console for Facilitor Desire Stage 1. It's gonna be big!


*/

/* Configuration parameters, eventually to be defined elsewhere */
const api_locations_filter = "";
const api_buildings_filter = "&buildingfunction=^81"; // exclude de Vervallen gebouwen
const api_disciplinetypes_filter = "";
const api_issuedisciplines_filter = "";
const api_issuetypes_filter = "";
const api_contracts_filter = "";
const api_floors_filter = "";
const api_issues_filter = "&issuetype=^2801"; // exclude de Tolkdiensten
const api_orders_filter = "";
const api_reportsx_filter = "&id=2246"; // test this one
const api_reports_filter = ""; // test-only

var lcl = {
    NL: {
        "title_show_about": "Over",
        "title_show_user": "Gebruiker",
        "title_list_locations": "Locaties",
        "title_show_location": "Locatie",
        "title_list_contracts": "Contracten",
        "title_show_contract": "Contract",
        "title_list_buildings": "Gebouwen",
        "title_show_building": "Gebouw",
        "title_filter_floors": "Verdiepingen",
        "title_filter_disciplinetypes": "Vakgroeptypen",
        "title_filter_issuedisciplines": "Vakgroepen",
        "title_filter_issuetypes": "Standaardmeldingen",
        "title_list_issues": "Meldingen",
        "title_show_issue": "Melding",
        "title_show_issue_object": "Object",
        "title_list_issue_orders": "Opdrachten",
        "title_show_order": "Opdracht"
    },
    DE: {
        "title_show_about": "Betrifft",
        "title_show_user": "Gebraucher",
        "title_list_locations": "Standorte",
        "title_show_location": "Standort",
        "title_list_contracts": "Verträge",
        "title_show_contract": "Vertrag",
        "title_list_buildings": "Gebäude",
        "title_show_building": "Gebäude",
        "title_filter_floors": "Stockwerke",
        "title_filter_disciplinetypes": "Innendiensttypen",
        "title_filter_issuedisciplines": "Innendienste",
        "title_filter_issuetypes": "Standard Meldungen",
        "title_list_issues": "Meldungen",
        "title_show_issue": "Meldung",
        "title_show_issue_object": "Object",
        "title_list_issue_orders": "Aufträge",
        "title_show_order": "Auftrag"
    },
    EN: {
        "title_show_about": "About",
        "title_show_user": "User",
        "title_list_locations": "Locations",
        "title_show_location": "Location",
        "title_list_contracts": "Contracts",
        "title_show_contract": "Contract",
        "title_list_buildings": "Buildings",
        "title_show_building": "Building",
        "title_filter_floors": "Floors",
        "title_filter_disciplinetypes": "Discipline types",
        "title_filter_issuedisciplines": "Disciplines",
        "title_filter_issuetypes": "Issue types",
        "title_list_issues": "Issues",
        "title_show_issue": "Issue",
        "title_show_issue_object": "Object",
        "title_list_issue_orders": "Orders",
        "title_show_order": "Order"
    },
    FR: {
        "title_show_about": "A propos",
        "title_show_user": "Utilisateur",
        "title_list_locations": "Emplacements",
        "title_show_location": "Emplacement",
        "title_list_contracts": "Contracts",
        "title_show_contract": "Contract",
        "title_list_buildings": "Immeubles",
        "title_show_building": "Immeuble",
        "title_filter_floors": "étages",
        "title_filter_disciplinetypes": "Types de départements",
        "title_filter_issuedisciplines": "Départements",
        "title_filter_issuetypes": "Appel standard",
        "title_list_issues": "Appels",
        "title_show_issue": "Appel",
        "title_show_issue_object": "équipement",
        "title_list_issue_orders": "Missions",
        "title_show_order": "Mission"
    }
};
// un-comment environment value setting below to see all console.logs
// environment = "development";

$(function() {
    "use strict";
    // targets ( usualy divs where data is placed)
    targets = {
        show_about: new Target({
            title: "title_show_about",
            selector: "show-about",
            mode: "show",
            columns: {
                version: {},
                customer: {},
                applicationname: {},
                url: {},
                login: {}
            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                api2({
                    url: "persons",
                    target: "show_user",
                    filter: "?login=" + dataInfo(obj, 0, "login")
                });
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        show_user: new Target({
            title: "title_show_user",
            selector: "show-user",
            mode: "show",
            columns: {
                id: {},
                name: {},
                language: {}
            },
            ready: function(obj) {
                language = dataInfo(obj, 0, "language") || "NL";
                $("h2[name=formtitle]", "#" + targets.show_user.selector).html((lcl[language][targets.show_user.title] || ""));
                $("h2[name=formtitle]", "#" + targets.show_about.selector).html((lcl[language][targets.show_about.title] || ""));
                api2({
                    url: "locations",
                    target: "list_locations",
                    filter: "?limit=1000&scope=fo" + api_locations_filter
                });
                api2({
                    url: "buildings",
                    target: "list_buildings",
                    filter: "?limit=1000&scope=fo" + api_buildings_filter
                });
                api2({
                    url: "disciplinetypes",
                    target: "filter_disciplinetypes",
                    filter: "?limit=1000&scope=fo" + api_disciplinetypes_filter
                });
            }
        }),
        list_locations: new Target({
            title: "title_list_locations",
            selector: "list-locations",
            mode: "list",
            columns: {
                id: {},
                code: {},
                visitaddress: {},
                visitzipcode: {},
                visitcity: {},
                district: {}
            },
            trigger: function(event) {
                console.log("trigger list_locations");
                var $this = $(this),
                    $this_tr = $this.closest("tr[recid]"),
                    index;
                if ($this_tr.length) {
                    if (event.ctrlKey) {
                        // show locations in Facilitor
                        windowObjectReference = window.open(settings.facilitor_url + "?u=locatie&k=" + $this_tr.attr("recid"));
                    } else {
                        if ($this_tr.hasClass("table-success")) {
                            $this_tr.removeClass("table-success");
                            index = targets.list_locations.selected_ids.indexOf($this_tr.attr("recid"));
                            if (index !== -1) {
                                targets.list_locations.selected_ids.splice(index, 1);
                            }
                        } else {
                            targets.list_locations.data_table
                                .rows(".table-success").nodes().to$().removeClass("table-success");
                            $this_tr.addClass("table-success");
                            targets.list_locations.selected_ids = targets.list_locations.selected_ids || [];
                            targets.list_locations.selected_ids = [$this_tr.attr("recid")];
                        }
                    }
                }
                $("#" + targets.filter_floors.selector).closest(".row").attr("hidden", true);
                api2({
                    url: "locations",
                    single: "location",
                    target: "show_location",
                    filter: "?limit=1&scope=fo&include=custom_fields&id=" + $this_tr.attr("recid")
                });
                api2({
                    url: "contracts",
                    target: "list_contracts",
                    filter: "?include=concerns&scope=fo&location=" + $this_tr.attr("recid") + api_contracts_filter
                });
                // redraw list_buildings table and select first row in case there is only 1 result
                console.log("start redrawtable of list_buildings");
                redrawTable({
                    target: "list_buildings"
                });
            },
            ready: function(obj) {
                $("#" + targets[obj.target].selector).closest(".row").attr("hidden", false);
                targets.list_locations.data_table = $('table', '#' + targets.list_locations.selector).DataTable(tColumnDefs(obj));
                initAutocomplete("building-map", "building-view");
                // select first row in case there is only 1 result
                autoselectRow({
                    target: obj.target
                });
                function resizeCards() {
                    resizeCard(targets.show_contract.selector, targets.list_contracts.selector)();
                    resizeCard("building-map", targets.list_locations.selector)();
                    resizeCard(targets.show_building.selector, targets.list_buildings.selector)();
                    resizeCard(targets.show_issue.selector, targets.list_issues.selector)();
                }
                $("#" + targets[obj.target].selector).closest("div.card").off("resize").on("resize", resizeCard("building-map", targets.list_locations.selector));
                $("input[type=search]", "#" + targets[obj.target].selector).off("input").on("input", resizeCard("building-map", targets.list_locations.selector));
                $("input#fluidSwitch").on("change", resizeCards);
                resizeCard("building-map", targets.list_locations.selector)();
            }
        }),
        show_location: new Target({
            title: "title_show_location",
            selector: "show-location",
            mode: "show",
            columns: {
                id: {},
                code: {
                    hidden: true
                },
                name: {},
                district: {}
            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                $("#" + targets.show_building.selector).attr("hidden", true);
                $("#" + targets[obj.target].selector).attr("hidden", false);
                // specific form title
                $("h2[name=formtitle]", $("#" + targets[obj.target].selector)).html(lcl[language][targets[obj.target].title] + " " + columnInfo(obj, undefined, "code").column_data);
                // resize textarea
                $("textarea", $("#" + targets[obj.target].selector)).each(function() {
                    $(this).innerHeight($(this).prop("scrollHeight") + "px");
                });
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        list_contracts: new Target({
            title: "title_list_contracts",
            selector: "list-contracts",
            mode: "list",
            columns: {
                id: {},
                name: {},
                place: {},
                contracttype: {},
                description: {},
                contractor: {},
                department: {},
                status: {},
                enddate: {}
            },
            trigger: function(event) {
                var $this = $(this),
                    $this_tr = $this.closest("tr[recid]");
                if ($this_tr.length) {
                    if (event.ctrlKey) {
                        // show locations in Facilitor
                        windowObjectReference = window.open(settings.facilitor_url + "?u=contract&k=" + $this_tr.attr("recid"));
                    } else {
                        targets.list_contracts.data_table
                            .rows(".table-success").nodes().to$().removeClass("table-success");
                        $this_tr.addClass("table-success");
                    }
                }
                api2({
                    url: "contracts",
                    single: "contract",
                    target: "show_contract",
                    filter: "?limit=1&scope=fo&include=custom_fields&id=" + $this_tr.attr("recid")
                });
            },
            ready: function(obj) {
                $("#" + targets.show_contract.selector).html("");
                $("#" + targets.list_contracts.selector).closest(".row").attr("hidden", false);
                targets.list_contracts.data_table = $('table', '#' + targets.list_contracts.selector).DataTable(tColumnDefs(obj));
                autoselectRow({
                    target: obj.target
                });
                $("input[type=search]", "#" + targets.list_contracts.selector).off("input").on("input", resizeCard(targets.show_contract.selector, targets.list_contracts.selector));
                resizeCard(targets.show_contract.selector, targets.list_contracts.selector)();
            }
        }),
        show_contract: new Target({
            title: "title_show_contract",
            selector: "show-contract",
            mode: "show",
            show_custom_fields: true,
            columns: {
                id: {},
                name: {
                    hidden: true
                },
                place: {},
                contracttype: {},
                description: {},
                contractor: {},
                department: {},
                status: {},
                enddate: {}
            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                $("#" + targets.show_contract.selector).attr("hidden", false);
                // specific form title
                $("h2[name=formtitle]", $("#" + targets.show_contract.selector)).html(lcl[language][targets.show_contract.title] + " " + columnInfo(obj, undefined, "name").column_data);
                // resize textarea
                $("textarea", $("#" + targets.show_contract.selector)).each(function() {
                    $(this).innerHeight($(this).prop("scrollHeight") + "px");
                });
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        list_buildings: new Target({
            title: "title_list_buildings",
            selector: "list-buildings",
            mode: "list",
            columns: {
                id: {
                    label: "Id"
                },
                code: {
                    label: "Code"
                },
                name: {
                    label: "Naam"
                },
                location: {
                    label: "Locatie"
                },
                buildingfunction: {
                    label: "Functie"
                }
            },
            trigger: function(event) {
                var $this = $(this),
                    $this_tr = $this.closest("tr[recid]"),
                    $this_gebouwcode = $("td[name=code]", $this_tr);
                if ($this_tr.length) {
                    if (event.ctrlKey) {
                        // show locations in Facilitor
                        windowObjectReference = window.open(settings.facilitor_url + "?u=gebouw&k=" + $this_tr.attr("recid"));
                    } else {
                        targets.list_buildings.data_table
                            .rows(".table-success").nodes().to$().removeClass("table-success");
                        $this_tr.addClass("table-success");
                    }
                }
                codeAddress($("td[name='location']", $this_tr).html());
                $("#" + targets.filter_disciplinetypes.selector + ",#" + targets.filter_issuedisciplines.selector + ",#" + targets.report.selector).closest(".row").attr("hidden", false);
                // reset classes for all buttons
                resetAllButtonClasses({
                    context: "#filter-disciplinetypes, #filter-issuedisciplines, #filter-issuetypes"
                });
                $("#" + targets.filter_floors.selector).closest(".row").attr("hidden", true);
                api2({
                    url: "floors",
                    target: "filter_floors",
                    filter: "?scope=fo&building=" + $this_tr.attr("recid") + api_floors_filter
                });
                api2({
                    url: "buildings",
                    target: "show_building",
                    single: "building",
                    filter: "?limit=1&scope=fo&include=custom_fields&id=" + $this_tr.attr("recid")
                });
                api2({
                    url: "issues",
                    target: "list_issues",
                    filter: "?limit=1000&scope=fo&building=" + $this_tr.attr("recid") + api_issues_filter
                });
                // get the default report for the selected building
                api2({
                    url: "reports",
                    target: "report",
                    filter: "?usrrap_key=" + targets.reportx.data.id + "&melding_gebouwcode=" + $this_gebouwcode.html()
                });

            },
            ready: function(obj) {
                $("#" + targets.list_issue_orders.selector + ",#" + targets.filter_disciplinetypes.selector + ",#" + targets.filter_issuedisciplines.selector + ",#" + targets.report.selector + ",#" + targets.list_issues.selector).closest(".row").attr("hidden", true);
                targets.list_buildings.data_table = $('table', '#list-buildings').DataTable(tColumnDefs(obj));
                $("#" + targets.list_buildings.selector).closest("div.card").off("resize").on("resize", resizeCard(targets.show_building.selector, targets.list_buildings.selector));
                $("input[type=search]", "#" + targets.list_buildings.selector).off("input").on("input", resizeCard(targets.show_building.selector, targets.list_buildings.selector));
                resizeCard(targets.show_building.selector, targets.list_buildings.selector)();
            }
        }),
        show_building: new Target({
            title: "title_show_building",
            selector: "show-building",
            mode: "show",
            show_custom_fields: true,
            columns: {
                id: {},
                code: {
                    hidden: true
                },
                name: {},
                buildingfunction: {},
                remark: {
                    type: "textarea"
                },
                visitable: {},
                workdays: {
                    type: "check"
                },
                openfrom: {},
                opento: {},
                email: {}
            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                $("#" + targets.show_location.selector).attr("hidden", true);
                $("#" + targets[obj.target].selector).attr("hidden", false);
                // specific form title
                $("h2[name=formtitle]", $("#" + targets[obj.target].selector)).html(lcl[language][targets[obj.target].title] + " " + columnInfo(obj, undefined, "code").column_data);
                // resize textarea
                $("textarea", $("#" + targets.show_issue.selector)).each(function() {
                    $(this).innerHeight($(this).prop("scrollHeight") + "px");
                });
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        filter_disciplinetypes: new Target({
            title: "title_filter_disciplinetypes",
            selector: "filter-disciplinetypes",
            filter: true,
            color_column: "rgb",
            mode: "list",
            columns: {
                id: {
                    label: "Id"
                },
                name: {
                    label: "Naam"
                },
                rgb: {
                    hidden: true
                },
                symbolname: {
                    hidden: true
                }
            },
            trigger: function(event) {
                var $this = $(this);
                if (event.altKey) {
                    // reset classes for all buttons
                    resetAllButtonClasses({
                        context: "#filter-disciplinetypes, #filter-issuedisciplines, #filter-issuetypes"
                    });
                }
                // set classes for button dependent on button_selected_class
                setButtonClasses({
                    $this: $this
                });
                // set full or no class on child buttons dependent on the parent button
                setChildSelectedClass({
                    $this: $this,
                    name: "disciplinetype",
                    context: "#filter-issuetypes, #filter-issuedisciplines"
                });
                // save id's of selected issuetypes in filter_issuetypes object
                saveSelectedbuttonIds({
                    target: "filter_issuetypes",
                    context: "#filter-issuetypes"
                });
                // redraw list_issues table and select first row in case there is only 1 result
                redrawTable({
                    target: "list_issues"
                });

            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                api2({
                    url: "issuedisciplines",
                    target: "filter_issuedisciplines",
                    filter: "?limit=1000&scope=fo" + api_issuedisciplines_filter
                });
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        filter_issuedisciplines: new Target({
            title: "title_filter_issuedisciplines",
            selector: "filter-issuedisciplines",
            filter: true,
            color_column: "colors",
            mode: "list",
            columns: {
                id: {
                    label: "Id"
                },
                name: {
                    label: "Naam"
                },
                disciplinetype: {
                    label: "Type",
                    hidden: true
                },
                colors: {
                    hidden: true
                },
                symbolname: {
                    hidden: true
                }
            },
            trigger: function(event) {
                var $this = $(this);
                var disciplinetype = $("div[name=disciplinetype]", $this).attr("recid");
                if (event.altKey) {
                    // reset classes for all buttons
                    resetAllButtonClasses({
                        context: "#filter-disciplinetypes, #filter-issuedisciplines, #filter-issuetypes"
                    });
                    targets.filter_issuetypes.selected_ids = [];
                }
                // set classes for button dependent on button_selected_class
                setButtonClasses({
                    $this: $this
                });
                // set full or no class on child buttons dependent on the parent button
                setChildSelectedClass({
                    $this: $this,
                    name: "discipline",
                    context: "#filter-issuetypes"
                }).each(function() {
                    var $this = $(this).closest("button"),
                        index, recid = $this.attr("recid");
                    if ($this.hasClass(settings.btn_selected_class)) {
                        targets.filter_issuetypes.selected_ids.push(recid);
                    } else {
                        index = targets.filter_issuetypes.selected_ids.indexOf(recid);
                        if (index > -1) {
                            targets.filter_issuetypes.selected_ids.splice(index, 1);
                        }
                    }
                });
                // set partial, full or no class on parent button dependent on the number of selected child buttons
                setParentSelectedClass({
                    name: "disciplinetype",
                    value: disciplinetype,
                    context: "#filter-issuedisciplines",
                    parent: "#filter-disciplinetypes"
                });
                // redraw list_issues table and select first row in case there is only 1 result
                redrawTable({
                    target: "list_issues"
                });
            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                api2({
                    url: "issuetypes",
                    target: "filter_issuetypes",
                    filter: "?limit=1000&scope=fo" + api_issuetypes_filter
                });
                setChildrenColor({ name: "disciplinetype", context: "#" + targets.filter_issuedisciplines.selector, parent: "#" + targets.filter_disciplinetypes.selector });
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        filter_issuetypes: new Target({
            title: "title_filter_issuetypes",
            selector: "filter-issuetypes",
            filter: true,
            icon_column: "symbolname",
            color_column: "colors",
            mode: "list",
            columns: {
                id: {
                    label: "Id"
                },
                description: {
                    label: "Nr"
                },
                disciplinetype: {
                    label: "Type",
                    hidden: true
                },
                discipline: {
                    label: "Melder",
                    hidden: true
                },
                symbolname: {
                    hidden: true
                },
                colors: {
                    hidden: true
                }
            },
            trigger: function(event) {
                var $this = $(this),
                    index, recid = $(this).attr("recid");
                var disciplinetype = $("div[name=disciplinetype]", $this).attr("recid");
                var discipline = $("div[name=discipline]", $this).attr("recid");
                if (event.altKey) {
                    // reset classes for all buttons
                    resetAllButtonClasses({
                        context: "#filter-disciplinetypes, #filter-issuedisciplines, #filter-issuetypes"
                    });
                    targets.filter_issuetypes.selected_ids = [];
                }
                // set classes for button dependent on button_selected_class
                setButtonClasses({
                    $this: $this
                });
                if ($this.hasClass(settings.btn_selected_class)) {
                    targets.filter_issuetypes.selected_ids.push(recid);
                } else {
                    index = targets.filter_issuetypes.selected_ids.indexOf(recid);
                    if (index > -1) {
                        targets.filter_issuetypes.selected_ids.splice(index, 1);
                    }
                }
                // redraw list_issues table and select first row in case there is only 1 result
                redrawTable({
                    target: "list_issues"
                });

                // set partial, full or no class on parent button dependent on the number of selected child buttons
                setParentSelectedClass({
                    name: "disciplinetype",
                    value: disciplinetype,
                    context: "#filter-issuetypes",
                    parent: "#filter-disciplinetypes"
                });
                setParentSelectedClass({
                    name: "discipline",
                    value: discipline,
                    context: "#filter-issuetypes",
                    parent: "#filter-issuedisciplines"
                });
            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                setChildrenColor({ name: "discipline", context: "#" + targets.filter_issuetypes.selector, parent: "#" + targets.filter_issuedisciplines.selector });
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        reportx: new Target({
            selector: "show-reportx",
            mode: "show",
            columns: {
                id: {},
                name: {
                    hidden: true
                },
                description: {
                    hidden: true
                },
                viewname: {
                    hidden: true
                },
                count: {
                    hidden: true
                },
                pivot: {
                    hidden: true
                },
                ratio: {
                    hidden: true
                },
                graph: {
                    hidden: true
                },
                graph_type: {
                    hidden: true
                }
            },
            ready: function(obj) {
                var self = this;
                // specific form title
                $("h2[name=formtitle]", $("#" + self.selector)).html(columnInfo(obj, undefined, "name").column_data);
                // save data for report
                self.data = obj.data.report;
                api2({
                    url: "reports",
                    target: "report",
                    filter: "?usrrap_key=" + self.data.id + api_reports_filter
                });
            }
        }),
        report: new Target({
            title: "title_show_report",
            selector: "show-report",
            mode: "show",
            show_custom_fields: false,
            report: true,
            ready: function(obj) {
                var self = this,
                    background_colors = [
                        'rgba(255, 99, 132, 0.5)',
                        'rgba(54, 162, 235, 0.5)',
                        'rgba(220,20,60, 0.5)',
                        'rgba(75, 192, 192, 0.5)',
                        'rgba(153, 102, 255, 0.5)',
                        'rgba(95,158,160, 0.5)',
                        'rgba(148,0,211, 0.5)',
                        'rgba(192,192,192, 0.5)',
                        'rgba(128,128,0, 0.5)',
                        'rgba(139,0,0, 0.5)',
                        'rgba(50,205,50, 0.5)',
                        'rgba(255, 159, 64, 0.5)'
                    ],
                    background_colors_used = obj.data.Mld_v_udr_meldings.map(function(value, index) {
                        return background_colors[index % 5];
                    }),
                    border_colors = [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(220,20,60, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(95,158,160, 1)',
                        'rgba(148,0,211, 1)',
                        'rgba(192,192,192, 1)',
                        'rgba(128,128,0, 1)',
                        'rgba(139,0,0, 1)',
                        'rgba(50,205,50, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    border_colors_used = obj.data.Mld_v_udr_meldings.map(function(value, index) {
                        return border_colors[index % 5];
                    });
                console.log("ready trigger start: " + obj.target);
                // save data for report
                self.data = obj.data.Mld_v_udr_meldings;
                // existing graph
                console.log({ chartsettings: self.chartsettings });
                self.chartsettings = {
                    type: ['', 'bar', 'area', 'pie', 'line', 'radar'][targets.reportx.data.graph_type.id],
                    data: {
                        labels: obj.data.Mld_v_udr_meldings.map(function(value) {
                            return value.melding_datum;
                        }),
                        datasets: [{
                            label: '#',
                            data: obj.data.Mld_v_udr_meldings.map(function(value) {
                                return value.scf_count;
                            }),
                            backgroundColor: background_colors_used,
                            borderColor: border_colors_used,
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                        }
                    }
                };
                if (self.myChart) {
                    // remove existing labels/datasets
                    self.myChart.type = self.chartsettings.type;
                    self.myChart.data = self.chartsettings.data;
                    self.myChart.update();
                    // new graph
                } else {
                    self.ctx = document.getElementById(self.selector).getContext('2d');
                    self.myChart = new Chart(self.ctx, self.chartsettings);
                }
                if (targets.reportx.data.graph_type.id == 3) {
                    self.chartsettings.options.scales = {};
                }
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        filter_floors: new Target({
            title: "title_filter_floors",
            selector: "filter-floors",
            filter: true,
            btn_size_class: "col-sm pl-0 pr-0",
            btn_has_icon: false,
            mode: "list",
            columns: {
                id: {},
                name: {
                    hidden: true
                },
                code: {},
                sequence: {
                    hidden: true
                },
                building: {
                    hidden: true
                }
            },
            trigger: function() {
                var $this = $(this),
                    building;
                // reset classes for all buttons
                resetAllButtonClasses({
                    context: "#filter-floors"
                });
                setButtonClasses({
                    $this: $this
                });
                building = $("div[name=building]", $this).attr("recid");
                $("img", $("#" + targets.filter_floors.selector).parent()).attr({
                    src: '../cad/mySlnk2IMG.asp?labelPos=2&vKey=' + $this.attr("recid") + '&gKey=' + building + '&scenario_key=0&thema=3&label=-1&werkplek=0&mode=0&contmode=0&discs=209&sizeX=' + $("#"+targets.filter_floors.selector).innerWidth() + '&sizeY=500&offsetX=35&offsetY=14&scale=950&paperColor=16777214',
                    hidden: false
                });
            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                console.log("obj.data[obj.table].length: " + obj.data[obj.table].length);
                if (obj.data[obj.table].length) {
                    $("#" + targets[obj.target].selector).closest(".row").attr("hidden", false);
                    // select (click) the first floor button
                    $("button:first", "#" + targets[obj.target].selector).click();
                }
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        list_issues: new Target({
            title: "title_list_issues",
            selector: "list-issues",
            mode: "list",
            columns: {
                id: {},
                name: {},
                issuetype: {},
                requestor: {},
                issuedate: {
                    type: "date" /* overbodig denk ik, maar toont alleen tijd. Dan liever alleen datum (tijdstip komt in de detail)*/
                },
                subject: {}
            },
            trigger: function(event) {
                var $this = $(this),
                    $this_tr = $this.closest("tr[recid]");
                if ($this_tr.length) {
                    if (event.ctrlKey) {
                        // show locations in Facilitor
                        windowObjectReference = window.open(settings.facilitor_url + "?u=melding&k=" + $this_tr.attr("recid"));
                    } else {
                        targets.list_issues.data_table
                            .rows(".table-success").nodes().to$().removeClass("table-success");
                        $this_tr.addClass("table-success");
                    }
                }
                api2({
                    url: "issues",
                    single: "issue",
                    target: "show_issue",
                    filter: "?limit=1&scope=fo&include=issueobjects,custom_fields&id=" + $this_tr.attr("recid")
                });
                api2({
                    url: "orders",
                    target: "list_issue_orders",
                    filter: "?scope=fo&status=1,2,3,4,5,6,7,8,9,10&issue=" + $this_tr.attr("recid") + api_orders_filter
                });
            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                $("#" + targets.show_issue.selector).html("");
                $("#" + targets.list_issue_orders.selector).closest(".row").attr("hidden", true);
                $("#" + targets.list_issues.selector).closest(".row").attr("hidden", false);
                var disciplinetypes = {},
                    disciplines = {},
                    key_count;
                // save id's of issuetypes used in table and return the occurences per issuetype
                key_count = saveUsedtabledataIds({
                    name: "issuetype",
                    target: "filter_issuetypes",
                    context: "#list-issues"
                });
                // set button classes for all buttons used in table and fill array with id's of disciplinetypes and disciplines
                $.each(targets.filter_issuetypes.selected_ids, function(index, value) {
                    var $this = $("button[recid=" + value + "]", "#" + targets.filter_issuetypes.selector);
                    var disciplinetype = $("div[name=disciplinetype]", $this).attr("recid");
                    var discipline = $("div[name=discipline]", $this).attr("recid");
                    disciplinetypes[disciplinetype] = disciplinetypes[disciplinetype] ? disciplinetypes[disciplinetype] + key_count[value] : key_count[value];
                    disciplines[discipline] = disciplines[discipline] ? disciplines[discipline] + key_count[value] : key_count[value];
                    $("div[name=badge]", $this).html('<span class="badge badge-pill badge-danger">' + key_count[value] + '</span>');
                    // set classes for button dependent on button_selected_class
                    setButtonClasses({
                        $this: $this
                    });
                });
                $.each(disciplinetypes, function(key, value) {
                    // set partial, full or no class on parent button dependent on the number of selected child buttons
                    setParentSelectedClass({
                        name: "disciplinetype",
                        value: key,
                        context: "#filter-issuetypes",
                        parent: "#filter-disciplinetypes"
                    }).children('div[name=badge]').html('<span class="badge badge-pill badge-danger">' + value + '</span></div>');
                });
                $.each(disciplines, function(key, value) {
                    // set partial, full or no class on parent button dependent on the number of selected child buttons
                    setParentSelectedClass({
                        name: "discipline",
                        value: key,
                        context: "#filter-issuetypes",
                        parent: "#filter-issuedisciplines"
                    }).children('div[name=badge]').html('<span class="badge badge-pill badge-danger">' + value + '</span></div>');
                });
                // set hidden attr for buttons dependent on button_selected_class
                setButtonHidden({
                    context: "#filter-issuetypes, #filter-issuedisciplines, #filter-disciplinetypes"
                });

                targets.list_issues.data_table = $('table', '#list-issues').DataTable(tColumnDefs(obj));
                // redraw list_issues table and select first row in case there is only 1 result
                redrawTable({
                    target: "list_issues"
                });
                $("#list-issue-orders, #show-issue").html(
                    function() {
                        return ($("h2", $(this)).length ? "<h2>" + $("h2", $(this)).html() + "</h2><p>Leeg</p>" : "");
                    });
                $("#show-issue-object").html("<h2>object</h2><p>Leeg</p>");
                $("#" + targets.list_issues.selector).closest("div.card").off("resize").on("resize", resizeCard(targets.show_issue.selector, targets.list_issues.selector));
                $("input[type=search]", "#" + targets.list_issues.selector).off("input").on("input", resizeCard(targets.show_issue.selector, targets.list_issues.selector));
                resizeCard(targets.show_issue.selector, targets.list_issues.selector)();
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        show_issue: new Target({
            title: "title_show_issue",
            selector: "show-issue",
            mode: "show",
            show_custom_fields: true,
            columns: {
                id: {},
                name: {
                    hidden: true
                },
                subject: {},
                issuetype: {},
                description: {
                    type: "textarea"
                },
                requestor: {},
                contact: {},
                issuedate: {},
                enddate: {},
                progress: {
                    label: "Voortgang",
                    type: "progressbar",
                    valuemin: 0,
                    valuemax: 100
                }
            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                var days1, days2, valuenow, data_row;
                $("#" + targets.show_issue.selector).attr("hidden", false);
                // specific form title
                $("h2[name=formtitle]", $("#" + targets.show_issue.selector)).html(lcl[language][targets.show_issue.title] + " " + columnInfo(obj, undefined, "name").column_data);
                // resize textarea
                $("textarea", $("#" + targets.show_issue.selector)).each(function() {
                    $(this).innerHeight($(this).prop("scrollHeight") + "px");
                });
                // specific progressbar
                days1 = ((new Date().getTime() - new Date(columnInfo(obj, undefined, "issuedate").column_data).getTime()) / day_in_ms).toFixed(2);
                days2 = ((new Date(columnInfo(obj, undefined, "enddate").column_data).getTime() - new Date(columnInfo(obj, undefined, "issuedate").column_data).getTime()) / day_in_ms).toFixed(2);
                valuenow = (days1 - days2 > 0 || days2 == 0 ? targets[obj.target].columns.progress.valuemax : (days1 / days2 * 100).toFixed(2));
                console.log({
                    days1: days1,
                    days2: days2,
                    valuenow: valuenow,
                    issuedate: columnInfo(obj, undefined, "issuedate").column_data,
                    issuedateFmt: new Date(columnInfo(obj, undefined, "issuedate").column_data)
                });
                $("#" + targets.show_issue.selector + "-progress")
                    .attr({
                        "aria-valuenow": valuenow
                    })
                    .css({
                        width: valuenow + "%"
                    })
                    .toggleClass("bg-danger", valuenow == targets[obj.target].columns.progress.valuemax);
                data_row = rowInfo(obj);

                if (data_row.issueobjects && data_row.issueobjects.length) {
                    api2({
                        url: "objects",
                        single: "object",
                        target: "show_issue_object",
                        filter: "?limit=1&include=custom_fields&id=" + data_row.issueobjects[0].object.id
                    });
                } else {
                    $("#" + targets.show_issue_object.selector).html("");
                }
                console.log("ready trigger stop: " + obj.target);
            }
        }),
        show_issue_object: new Target({
            title: "title_show_issue_object",
            selector: "show-issue-object",
            mode: "show",
            columns: {
                id: {},
                name: {},
                type: {},
                description: {}
            },
            ready: function(obj) {
                $("#" + targets[obj.target].selector).attr("hidden", false);
            }
        }),
        list_issue_orders: new Target({
            title: "title_list_issue_orders",
            selector: "list-issue-orders",
            mode: "list",
            columns: {
                id: {},
                sequence: {},
                issueordertype: {},
                company: {},
                status: {},
                description: {}
            },
            trigger: function(event) {
                var $this = $(this),
                    $this_tr = $this.closest("tr[recid]");
                if ($this_tr.length) {
                    if (event.ctrlKey) {
                        // show locations in Facilitor
                        windowObjectReference = window.open(settings.facilitor_url + "?u=opdracht&k=" + $this_tr.attr("recid"));
                    } else {
                        targets.list_issue_orders.data_table
                            .rows(".table-success").nodes().to$().removeClass("table-success");
                        $this_tr.addClass("table-success");
                    }
                }
                api2({
                    url: "orders",
                    single: "order",
                    target: "show_order",
                    filter: "?limit=1&scope=fo&include=custom_fields&id=" + $this_tr.attr("recid")
                });
            },
            ready: function(obj) {
                $("#" + targets.show_order.selector).html("");
                $("#" + targets[obj.target].selector).closest(".row").attr("hidden", false);
                targets[obj.target].data_table = $('table', '#list-issue-orders').DataTable(tColumnDefs(obj));
                // select first row in case there is only 1 result
                autoselectRow({
                    target: obj.target
                });
                $("input[type=search]", "#" + targets.list_issue_orders.selector).off("input").on("input", resizeCard(targets.show_order.selector, targets.list_issue_orders.selector));
                resizeCard(targets.show_order.selector, targets.list_issue_orders.selector)();
            }
        }),
        show_order: new Target({
            title: "title_show_order",
            selector: "show-order",
            mode: "show",
            show_custom_fields: true,
            columns: {
                id: {},
                company: {},
                account: {},
                description: {
                    type: "textarea"
                },
                startdate: {},
                issue: {
                    hidden: true
                },
                sequence: {
                    hidden: true
                },
                hours: {},
                hourrate: {},
                remark: {
                    type: "textarea"
                }
            },
            ready: function(obj) {
                console.log("ready trigger start: " + obj.target);
                $("#" + targets[obj.target].selector).attr("hidden", false);
                // specific form title
                $("h2[name=formtitle]", $("#" + targets[obj.target].selector)).html(lcl[language][targets[obj.target].title] + " " + columnInfo(obj, undefined, "issue").column_data + "/" + columnInfo(obj, undefined, "sequence").column_data);
                // resize textarea
                $("textarea", $("#" + targets[obj.target].selector)).each(function() {
                    $(this).innerHeight($(this).prop("scrollHeight") + "px");
                });
                console.log("ready trigger stop: " + obj.target);
            }
        })
    };
    // models required for this dashboard
    models = {
        about: {},
        persons: {},
        issues: {},
        reportsx: {},
        reports: {},
        locations: {},
        buildings: {},
        contracts: {},
        floors: {},
        orders: {},
        objects: {},
        disciplinetypes: {},
        issuedisciplines: {},
        issuetypes: {}
    };
    // function to filter data on DataTables
    $.fn.dataTable.ext.search.push(
        function(settings, data, dataIndex) {
            var target = $("#" + settings.sTableId).attr("name");
            // filter list_issues rows on selected disciplinetype buttons, non selected = show all rows
            if (target == "list_issues") {
                if (!!targets.list_issues.data_table && !!targets.filter_issuetypes.selected_ids && ($("button." + window.settings.btn_selected_class, "#filter-disciplinetypes").length > 0)) {
                    var value = $('td[name=issuetype]', targets.list_issues.data_table
                            .row(dataIndex) //get the row to evaluate
                            .nodes() //extract the HTML - node() does not support to$
                            .to$()) //get as jQuery object
                        .attr('recid');
                    return targets.filter_issuetypes.selected_ids.indexOf(value) != -1;
                }
            }
            // filter list_buildings rows on selected location, non selected = show all rows
            if (target == "list_buildings") {
                if (!!targets.list_buildings.data_table && !!targets.list_locations.selected_ids && targets.list_locations.selected_ids.length > 0) {
                    var value = $('td[name=location]', targets.list_buildings.data_table
                            .row(dataIndex) //get the row to evaluate
                            .nodes() //extract the HTML - node() does not support to$
                            .to$()) //get as jQuery object
                        .attr('recid');
                    return targets.list_locations.selected_ids.indexOf(value) != -1;
                }
            }
            return true;
        }
    );
    // get model definitions with ajax
    for (var model in models) {
        api2({
            url: model + ".api",
            model: model,
            filter: "?scope=fo&usrrap_key=2246"
        });
    }
    // first get about-info through ajax
    api2({
        url: "about",
        target: "show_about"
    });
    // get the default report
    api2({
        url: "reportsx",
        single: "report",
        target: "reportx",
        filter: "?1=1" + api_reportsx_filter
    });
});