﻿var graph = function (_container, _graph_name, _graph_type, _main_cbo, _combos) {
    var chart;
    var options;
    var graph_name = new String(_graph_name);
    var graph_type = new String(_graph_type);
    var combos = new String(_combos);
    var container = new String(_container);
    var main_cbo = new String(_main_cbo);
    var selector_width = "800px";
    var selector_height = "200px";
    var graph_width = "800px";
    var graph_height = "400px";

    function update_selectors(r) {
        $.each(r, function (sel_num, selector) {
            var found = $("#" + container).find("#" + selector.cbo_name);
            if (found.length > 0) {
                cbo = $(found[0]);
                if (selector.cbo_type == "M") {
                    cbo.dropdownchecklist("destroy");
                }
                cbo.empty();
                setData_selectors(selector, cbo);
            }
        });
    }

    function request_graphic() {
        var gb = ($("#" + container).find("#goGraph"));
        gb = $(gb[0]);
        gb.hide();

        var data = getParameters(combos);
        chart.showLoading();

        $.ajax({
            url: "/Secure/graphics.asmx/get_graph",
            type: "POST",
            //dataType: "json",
            contentType: "application/json; charset=utf-8",
            processData: true,
            data: data,
            success: function (r) {
                r = eval("(" + r.d + ");");

                for (var i = chart.series.length - 1; i >= 0; i--)
                    chart.series[i].remove(false);

                if (graph_type == "column")
                    chart.xAxis[0].setCategories(r["xAxis"].categories, false);

                for (var i = 0; i < r["series"].length; i++)
                    chart.addSeries({
                        type: graph_type,
                        name: r["series"][i]["name"],
                        data: r["series"][i]["data"]
                    }, false);

                chart.redraw();
                chart.hideLoading();
                gb.show();
            },
            error: function (e) {
                alert("error: " + e.responseText);
            },
            cache: false
        });
    }

    function show_selectors(cbo) {
        var option = $("#" + container).find("#" + cbo + " option:selected");
        if (option.length > 0) {
            option = option[0];
            var cbos_hide = (option.hide ? option.hide : "");

            $("#" + container).find("select[graph_selector]").each(function (i) {
                if (cbos_hide.toString().indexOf(this.graph_selector) >= 0) {
                    if (this.multiple)
                        $(this).dropdownchecklist("disable");
                    else
                        $(this).attr("disabled", true);
                }
                else {
                    if (this.multiple)
                        $(this).dropdownchecklist("enable");
                    else
                        $(this).attr("disabled", false);
                }
            });
        }
    }

    function setData_selectors(s, c) {
        var selected;

        if (s.cbo_selected == "(all)" || s.cbo_selected == "")
            selected = [];
        else
            selected = s.cbo_selected.toString().split(",");

        $.each(s.cbo_data, function (opt_num, option) {
            if (s.cbo_selected == "(all)") selected.push(option["value"].toString());
            add_data = "";
            if (option["hide"]) add_data = "hide = '" + option["hide"] + "'";
            c.append("<option " + add_data + " value='" + option["value"] + "'" + ">" + option["text"] + "</option>");
        });

        if (s.cbo_type == "M") {
            c.val(selected);
            c.dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 100, width: 120 });
        }
        else
            c.width("140");
    }

    function create_graph(g) {
        var graph_container = $("<div style='width: " + graph_width + "; height: " + graph_height + ";' id='" + container + "-graph'></div>");
        $("#" + container).append(graph_container);
        g.chart.renderTo = container + "-graph";
        chart = new Highcharts.Chart(g);
        options = g;
        request_graphic();
    }

    function create_selectors(r) {
        var selector_container = $("<div style='width: " + selector_width + "; height: " + selector_height + ";' id='" + container + "-selector'></div>");
        $("#" + container).append(selector_container);

        var multiple = "", children = "", cbo, tr, gb;
        var table = $("<table align='center'></table>");

        $.each(r, function (sel_num, selector) {
            multiple = (selector.cbo_type == "M") ? "multiple = 'multiple'" : "";
            cbo = $("<select graph_selector = '" + selector.cbo_name + "' ndata = '" + selector.cbo_ndata + "' id = '" + selector.cbo_name + "' " + multiple + ">" + "</select>&nbsp;&nbsp;");
            cbo.blur(function (event) {
                event.preventDefault();
                show_selectors(selector.cbo_name);
                request_selectors("update", selector.children); //Sólo aplica cuando tiene hijos que actualizar                
            });

            if (sel_num % 2 == 0) tr = $("<tr></tr>");
            tr.append($("<td align='right'>" + selector.cbo_label + "</td>").css("width", "80"))
                        .append($("<td align='left'></td>")
                        .css("width", "150")
                        .append(cbo));
            table.append(tr);

            setData_selectors(selector, cbo);
        });

        selector_container.append(table);
        show_selectors(main_cbo);

        //Adds graphic button
        gb = $("<button id='goGraph'>Graficar</button>");
        gb.hide()
                    .click(function () {
                        request_graphic();
                        return false;
                    });
        tr = $("<tr></tr>");
        tr.append($("<td align='right' colspan='4'></td>").append(gb));
        table.append(tr);
    }

    function create(r, g) {
        create_selectors(r);
        create_graph(g);
    }

    function getParameters(c) {
        var params =
                "{" +
                    "\"cbos\"           : \"" + c + "\"" +
                    ",\"graph_name\"    : \"" + graph_name + "\"" +
                    ",\"graph_type\"    : \"" + graph_type + "\"";

        var z = $("#" + container).find("#" + c);
        if (z.length > 0) z = $(z[0]);

        var cbos = combos.split(",");
        for (var i = 0; i < cbos.length; i++) {
            params += ",\"" + cbos[i] + "_id\" : ";
            var found = $("#" + container).find("#" + cbos[i]);
            if (found.length > 0) {
                found = $(found[0]);
                if (c == combos || z.attr("ndata").indexOf(cbos[i]) >= 0)
                    params += "\"" + (!found.val() ? "-1" : found.val()) + "\"";
                else
                    params += "\"\"";
            }
            else
                params += "\"\"";
        }
        params += "}";
        return params;
    }

    function request_selectors(o, c) {
        if (c == "") return;

        var data = getParameters(c);
        $.ajax({
            url: "/Secure/graphics.asmx/intial",
            type: "POST",
            //dataType: "json",
            contentType: "application/json; charset=utf-8",
            processData: true,
            data: data,
            success: function (r) {
                r = eval("(" + r.d + ");");
                g = r["graphs_info"];
                r = r["cbos_info"];
                if (o == "init")
                    create(r, g);
                else
                    update_selectors(r);
            },
            error: function (e) {
                alert("error: " + e.responseText);
            }
        });
    }

    function init() {
        request_selectors("init", combos);
    }

    init();
}
