<?xml version="1.0" encoding="UTF-8"?>
<Export generator="Cache" version="25">

<CSP name="DeepSeeLightPivotTable.css" application="">
<![CDATA[{{replace:css}}]]>
</CSP>

<CSP name="DeepSeeLightPivotTable.js" application="">
<![CDATA[{{replace:js}}]]>
</CSP>

<Class name="DeepSee.LightPivotTable">
<Super>%DeepSee.Component.Portlet.abstractPortlet</Super>
<TimeChanged>63749,65155.748273</TimeChanged>
<TimeCreated>63515,61322.546099</TimeCreated>

<Parameter name="INCLUDEFILES">
<Default>style:DeepSeeLightPivotTable.css,script:DeepSeeLightPivotTable.js</Default>
</Parameter>

<Property name="DataSourceApp">
<Type>%String</Type>
</Property>

<Property name="ExportCSV">
<Type>%Boolean</Type>
</Property>

<Property name="ShowSummary">
<Type>%Boolean</Type>
</Property>

<Property name="Pagination">
<Type>%Integer</Type>
</Property>

<Property name="FixTotals">
<Type>%Boolean</Type>
</Property>

<Property name="ListingColumnMinWidth">
<Type>%Integer</Type>
</Property>

<Property name="MaxHeaderWidth">
<Type>%Integer</Type>
</Property>

<Property name="ColumnResizing">
<Type>%Boolean</Type>
</Property>

<Property name="EnableSearch">
<Type>%Boolean</Type>
</Property>

<Property name="StretchColumns">
<Type>%Boolean</Type>
</Property>

<Property name="ShowRowNumbers">
<Type>%Boolean</Type>
</Property>

<Property name="ExcelExportClass">
<Type>%String</Type>
</Property>

<Method name="%OnGetPortletName">
<ClassMethod>1</ClassMethod>
<ReturnType>%String</ReturnType>
<Implementation><![CDATA[    quit "Light pivot table"
]]></Implementation>
</Method>

<Method name="%OnGetPortletIcon">
<ClassMethod>1</ClassMethod>
<ReturnType>%String</ReturnType>
<Implementation><![CDATA[    quit "deepsee/ds2_dialpad_44.png"
]]></Implementation>
</Method>

<Method name="%OnGetPortletSettings">
<ClassMethod>1</ClassMethod>
<FormalSpec>*pInfo:%List</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
    kill pInfo // $LB(name,value,type,caption,title)

    set pInfo($I(pInfo)) = $LB("DataSourceApp", "MDX2JSON", "%String", "MDX2JSON app", "Web application name with MDX2JSON router. Example: ""SAMPLES""")
    set pInfo($I(pInfo)) = $LB("ShowSummary", 1, "%Boolean", "Show summary", "Show summary row")
    set pInfo($I(pInfo)) = $LB("ExportCSV", 1, "%Boolean", "Export to CSV", "Show export to CSV format button")
    set pInfo($I(pInfo)) = $LB("Pagination", 200, "%Integer", "Pagination", "Enable pagination")
    set pInfo($I(pInfo)) = $LB("FixTotals", 0, "%Boolean", "Fix totals", "Fix totals in header")
    set pInfo($I(pInfo)) = $LB("ListingColumnMinWidth", 0, "%Integer", "Min cell width for listing", "Minimal column width in listing")
    set pInfo($I(pInfo)) = $LB("MaxHeaderWidth", 0, "%Integer", "Max column width", "Maximal column width for headers")
    set pInfo($I(pInfo)) = $LB("ColumnResizing", 1, "%Boolean", "Column resizing", "Allow resizing columns with cursor")
    set pInfo($I(pInfo)) = $LB("EnableSearch", 1, "%Boolean", "Enable listing search", "Show search tools in listing mode")
    set pInfo($I(pInfo)) = $LB("StretchColumns", 0, "%Boolean", "Stretch columns", "Stretch columns to fill all available width")
    set pInfo($I(pInfo)) = $LB("ShowRowNumbers", 0, "%Boolean", "Show row nums", "Show row number in listing")
    set pInfo($I(pInfo)) = $LB("ExcelExportClass", "_DeepSee.UI.MDXExcel.cls", "%String", "Excel export class", "Class which exports MDX to Excel")

    quit $$$OK
]]></Implementation>
</Method>

<Method name="getConnectedController">
<Language>javascript</Language>
<ClientMethod>1</ClientMethod>
<Implementation><![CDATA[
    var controller = this.getController();

    if (null === controller) {
        this.connectToController();
        controller = this.getController();
    }

    return controller;
]]></Implementation>
</Method>

<Method name="notifyViewHandler">
<FormalSpec>reason,data1,data2,data3</FormalSpec>
<Language>javascript</Language>
<ClientMethod>1</ClientMethod>
<Implementation><![CDATA[
    if (!this.LightPivotTable) return;

    var controller = this.getConnectedController();

    if (reason === "dataChange") {

        // prevents refreshing twice at start
        if (!this._INITIALIZED) { this._INITIALIZED = true; return; }

        this.LightPivotTable.CONFIG["defaultFilterSpecs"] = [];

        // updateFilters
        // Getting filters from controller, if it has filters added from URL or default...
        // such filters are marked as "transient"
        if (controller.filters.length) {
            for (i in controller.filters) {
                if (controller.filters[i].enabled && controller.filters[i].transient)
                    this.LightPivotTable.CONFIG["defaultFilterSpecs"].push(controller.filters[i].spec);
            }
        }
        // ... if not, we'll get filters from widget's controls
        // Only if the controller didn't have transient filters - (!defaultFilters.length)
        if (!this.LightPivotTable.CONFIG["defaultFilterSpecs"].length && widget.filterState instanceof Object) {
            for (i in widget.filterState)
                if (widget.filterState[i]) this.LightPivotTable.CONFIG["defaultFilterSpecs"].push(widget.constructMDXClause(i, widget.filterState[i]));
        }
        if (controller.contextFilterSpec) {
            this.LightPivotTable.CONFIG["defaultFilterSpecs"].push(controller.contextFilterSpec);
        }

        this.LightPivotTable.refresh();

    }
]]></Implementation>
</Method>

<Method name="renderContents">
<Language>javascript</Language>
<ClientMethod>1</ClientMethod>
<Implementation><![CDATA[    this.InitLPT();
]]></Implementation>
</Method>

<Method name="registerLPTOnCreateCallback">
<Description>
Call this method when widget is created to handle moment when pivot table will be created.
If LPT has been created before, method fires given callback immidiately.</Description>
<FormalSpec>callback</FormalSpec>
<Language>javascript</Language>
<ClientMethod>1</ClientMethod>
<Implementation><![CDATA[
	if (typeof callback !== "function") return;
	if (this.LightPivotTable) callback(this.LightPivotTable);
		else this._registeredLPTOnCreateCallback = callback;
]]></Implementation>
</Method>

<Method name="InitLPT">
<Language>javascript</Language>
<ClientMethod>1</ClientMethod>
<Implementation><![CDATA[
    var container = document.getElementById(this.id),
        basicContainer = container,
        self = this;

    if (!container) {
        console.error("Light pivot table: Unable to get widget with ID=" + this.id);
        return;
    }

    for (i in container.childNodes) {
        if (container.childNodes[i].className === "lpt-container") {
            container = container.childNodes[i];
            break;
        }
    }

    var controller = this.getConnectedController(),
        source,
        setup,
        filterValue,
        _ = this,
        widget = this, // It's lie. It changes later.
        widgetKey,
        i, info = {},
        defaultFilters = [],
        exportToExcel = !!parseInt(container.getAttribute("export-csv"));

    // Following "parent" until we find widget object
    while (!widget["widgetKey"]) {
        widget = widget["parent"];
    }

    widgetKey = widget["widgetKey"];

    if (exportToExcel) {
        var widgetHead = document.getElementById(basicContainer.getAttribute("id").replace(/\/.*/, "/header"));
        if (widgetHead) {
            var f,
                widgetTr = (f = function (el) {var r; if (el.tagName === "TR") return el; for (var i in el.childNodes) { r = f(el.childNodes[i]); if (r) return r; } return null; })(widgetHead);
            if (widgetTr) {
                var td = document.createElement("TD");
                td.selfW = _;
                td.setAttribute("style", "padding-right:6px;vertical-align:bottom;");
                td.innerHTML = "<div class=\"zendiv\" onclick=\"this.parentNode.selfW.exportCSV.call(this.parentNode.selfW)\"><img class=\"imageLink\" src=\"deepsee/ds2_action_44.png\" title=\"Export to CSV format\"></div>";
                widgetTr.appendChild(td);
            }
        }
    }

    var post = function (url, data, callback) {

        var xhr = new XMLHttpRequest();
        xhr.open("POST", url);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                callback((function () {
                    try {
                        return JSON.parse(xhr.responseText) || {}
                    } catch (e) {
                        return {
                            error: "<h1>Unable to parse server response</h1><p>" + xhr.responseText
                                + "</p>"
                            };
                    }
                })());
            } else if (xhr.readyState === 4 && xhr.status !== 200) {
                callback({ error: xhr.responseText
                    || "Error while trying to retrieve data from server." });
            }
        };
        xhr.send(JSON.stringify(data));

    };

    post(
        (source = location.origin + "/" + container.getAttribute("data-source"))
        + "/Widgets?Namespace=" + container.getAttribute("namespace"),
        {
            Dashboard: zenPage["dashboardName"]
        },
        function (data) {
            if (data.error) {
                container.innerHTML = "<br/><br/><h3>Unable to get data from server.</h3><p>Check if data source is configured and accessible: " + source + "/Widgets" + "</p>"
            } else {
                for (i in data.children) {
                    if (data.children[i].key === widgetKey) {
                        info = data.children[i];
                        break;
                    }
                }
                //console.log(info);
                setup = {
                    container: container,
                    dataSource: {
                        pivot: info["dataSource"],
                        basicMDX: info["mdx"],
                        MDX2JSONSource: source,
                        namespace: container.getAttribute("namespace")
                    },
                    triggers: {
                        rowSelect: function (selectedRows) {
                            var ss = [];
                            selectedRows.forEach(function (e) { ss.push(e + ",," + (e + 1) + ",,,1") });
                            controller.setProperty("selectedRange", ss.join("\n"));
                        }
                    }
                };
                // widget controls processing
                for (var c in info.controls) {
                    if (info.controls[c].action === "setRowCount") {
                        setup.rowCount = info.controls[c].value;
                    }
                }
                // Getting filters from controller, if it has filters added from URL or default...
                // such filters are marked as "transient"
                if (controller.filters.length) {
                    for (i in controller.filters) {
                        if (controller.filters[i].enabled && controller.filters[i].transient)
                            defaultFilters.push(controller.filters[i].spec);
                    }
                }
                // ... if not, we'll get filters from widget's controls
                // Only if the controller didn't have transient filters - (!defaultFilters.length)
                if (!defaultFilters.length && widget.filterState instanceof Object) {
                    for (i in widget.filterState)
                        if (widget.filterState[i]) defaultFilters.push(widget.constructMDXClause(i,widget.filterState[i]));
                }
                
                if (controller.contextFilterSpec) {
                    defaultFilters.push(controller.contextFilterSpec);
                }
                if (defaultFilters.length) { setup["defaultFilterSpecs"] = defaultFilters; }
                if (controller && controller["data"] && controller["data"]["rowCaptions"] && typeof controller["data"]["rowCaptions"][0] === "string") setup.caption = controller["data"]["rowCaptions"][0];
                if (controller && controller["data"] && !setup.caption) setup.caption = controller["data"]["defaultCaption"] || "";
                if (info["drillDownDataSource"]) setup["drillDownTarget"] = info["drillDownDataSource"];
                setup["showSummary"] = !!parseInt(container.getAttribute("show-summary"));
                setup["attachTotals"] = !!parseInt(container.getAttribute("fixTotals"));
                setup["columnResizing"] = !!parseInt(container.getAttribute("columnResizing"));
                setup["enableSearch"] = !!parseInt(container.getAttribute("enableSearch"));
                setup["stretchColumns"] = !!parseInt(container.getAttribute("stretchColumns"));
                setup["showRowNumbers"] = !!parseInt(container.getAttribute("showRowNumbers"));
                if (parseInt(container.getAttribute("pagination"))) {
                    setup["pagination"] = parseInt(container.getAttribute("pagination"))
                }
                if (parseInt(container.getAttribute("listingColumnMinWidth"))) {
                    setup["listingColumnMinWidth"] = parseInt(container.getAttribute("listingColumnMinWidth"))
                }
                if (parseInt(container.getAttribute("maxHeaderWidth"))) {
                    setup["maxHeaderWidth"] = parseInt(container.getAttribute("maxHeaderWidth"))
                }

                _.LightPivotTable = new LightPivotTable(setup);
                if (_._registeredLPTOnCreateCallback) _._registeredLPTOnCreateCallback(_.LightPivotTable);

                // hack to enable some change events
                setTimeout(function () { _._INITIALIZED = true; }, 800);
            }
        }
    );
]]></Implementation>
</Method>

<Method name="onCreate">
<Language>javascript</Language>
<ClientMethod>1</ClientMethod>
<Implementation><![CDATA[
    // filtering first datachange event (useless update)
    this._INITIALIZED = false;
    // filtering frequent size updates as an expensive operation
    this._SIZE_ADJUST_TIMEOUT = 0;
    // fix for widget panel height
    this._WIDGET_HEADER_HEIGHT = 0;
    this._WIDGET_HEADER_FIXER_INTERVAL = 0;

    // fix location.origin for IE
    if (!window.location.origin) {
        window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
    }
]]></Implementation>
</Method>

<Method name="exportCSV">
<Language>javascript</Language>
<ClientMethod>1</ClientMethod>
<Implementation><![CDATA[
    var container = document.getElementById(this.id),
        controller = this.getConnectedController(),
        page = this.ExcelExportClass;

    if (!this.LightPivotTable) return;

    if (true) { // *.XLS export, false - *.CSV.

        var controls = this.id.replace(/\/.*/, "") + "/control/",
            control, i = 1, n,
            //filter = document.getElementById(controls + i),
            widget = this.parent.parent,

            filterNames = [],
            filterValues = [];

        /*if (filter) do {
            if ((n = (filter.getElementsByTagName("input")[0] || {}).name) === "$V_applyFilter" || n === "$V_setFilter") {
                filterNames.push((filter.parentNode.getElementsByClassName("zenLabel")[0] || {}).innerText || "");
                filterValues.push("SET");
            }
            filter = document.getElementById(controls + (++i));
        } while (filter);*/

        for (j in widget.controlIndices) {
			control = zenPage.getComponent(widget.controlIndices[j]);
			if (control) {
				filterNames.push(control.label);
				filterValues.push(control.text);
			}
		}

		var mdx = this.LightPivotTable.getActualMDX(),
		    nonce, url;

		if (zenPage.CreateQueryNonce) {
            nonce = zenPage.CreateQueryNonce(mdx);
            if (nonce.toString().indexOf('ERROR:') >= 0) {
                alert(nonce);
                return;
            }
            url = page + '?NONCE=' + encodeURIComponent(nonce);
		} else {
            url = page + '?MDX=' + encodeURIComponent(mdx);
		}

        window.open(
            url
            + "&ROWTOTALS=" + container.getElementsByTagName("div")[0].getAttribute("show-summary")
            + "&ROWTOTALAGG=sum"
            + "&COLUMNTOTALAGG=sum"
            + "&FILTERNAMES=" + encodeURIComponent(filterNames.join("\n"))
            + "&FILTERVALUES=" + encodeURIComponent(filterValues.join("\n"))
            + "&FILTERLABELS=" + encodeURIComponent(filterNames.join("\n"))
            + "&TITLE=Exported%20data"
            + "&SUBTITLE="
            + "&CSPSHARE=1"
            + "&CSPCHD=" + container.getElementsByTagName("div")[0].getAttribute("session")
        );
        return;
    }

    var link = document.createElement("a"),
        csvData = [], preservedGroups = {},
        rawData = this.LightPivotTable.dataController.getData(),
        row, cell;

    if (!rawData || !(rawData.rawData instanceof Array)) return;
    rawData = rawData.rawData;

    for (var y = 0; y < rawData.length; y++) {
        row = [];
        for (var x = 0; x < rawData[y].length; x++) {
            if (rawData[y][x].group) {
                if (preservedGroups.hasOwnProperty(rawData[y][x].group)) {
                    row.push("");
                    continue;
                } else {
                    preservedGroups[rawData[y][x].group] = true;
                }
            }
            cell = (rawData[y][x].value || "").toString();
            if (isFinite(cell)) cell = cell.replace(/\./g, ",");
            if (cell.indexOf("\"") > -1 || cell.indexOf(";") > -1) {
                cell = "\"" + cell.replace(/"/g, "\"\"") + "\"";
            }
            row.push(cell);
        }
        csvData.push(row.join(";"));
    }

    link.setAttribute("href", "data:application/csv;charset=UTF-8,\uFEFF"+encodeURIComponent(csvData.join("\r\n")));
    link.setAttribute("download", "EXPORT.csv");
    link.click();
]]></Implementation>
</Method>

<Method name="%DrawHTML">
<Implementation><![CDATA[
    set ..renderFlag = ..renderFlag + 1

    // copy ..settings into properties
    #dim propName As %String = $order(..settings(""))
    while (propName '= "")
    {
        if ("" '= $get(..settings(propName)))
            try
            {
                set $property($this, propName) = ..settings(propName)
            }
            catch {}

        set propName = $order(..settings(propName))
    }

    &html<
        <div stretchColumns="#(..StretchColumns)#" showRowNumbers="#(..ShowRowNumbers)#" namespace="#($NAMESPACE)#" enableSearch="#(..EnableSearch)#" columnResizing="#(..ColumnResizing)#" session="#(%session.CSPSessionCookie)#" maxHeaderWidth="#(..MaxHeaderWidth)#" listingColumnMinWidth="#(..ListingColumnMinWidth)#" fixTotals="#(..FixTotals)#" pagination="#(..Pagination)#" export-csv="#(..ExportCSV)#" data-source="#(..DataSourceApp)#" show-summary="#(..ShowSummary)#" class="lpt-container" style="position: absolute; left: 0; bottom: 0; width: 100%; height: 100%;">

        </div>
    >
]]></Implementation>
</Method>

<Method name="adjustContentSize">
<FormalSpec>load,width,height,flag</FormalSpec>
<Language>javascript</Language>
<ClientMethod>1</ClientMethod>
<Implementation><![CDATA[
    var _ = this;

    //////// cheating to fix instrument panel height /////////
    var outContainer = document.getElementById(_.id),
        widgetHead = document.getElementById(outContainer.getAttribute("id").replace(/\/.*/, "/header")),
        inContainer;

    if (!_._WIDGET_HEADER_FIXER_INTERVAL) {
        var firstLoad = true;
        _._WIDGET_HEADER_FIXER_INTERVAL = setInterval(function () {
            if (firstLoad) {
                _._WIDGET_HEADER_HEIGHT = widgetHead.offsetHeight;
            } else if (_._WIDGET_HEADER_HEIGHT !== widgetHead.offsetHeight) {
                _._WIDGET_HEADER_HEIGHT = widgetHead.offsetHeight;
                _.adjustContentSize(false, 0, 0, null);
            }
            firstLoad = false;
        }, 500);
    }

    if (load) return;

    // cheating to fix widget size when widget head change size
    var dragChildren = outContainer.parentNode.parentNode.parentNode.parentNode.parentNode
    .parentNode.parentNode.parentNode.parentNode.parentNode;
    dragChildren = dragChildren.className === "dragChildren"
        ? dragChildren
        : (dragChildren.getElementsByClassName("dragChildren") || [])[0];
    // -

    if (outContainer) {
        for (var i in outContainer.childNodes) {
            if (outContainer.childNodes[i].className === "lpt-container") {
                inContainer = outContainer.childNodes[i];
                if (widgetHead && dragChildren) {
                    inContainer.style.height = dragChildren.offsetHeight - widgetHead.offsetHeight + "px";
                    //console.log(dragChildren.offsetHeight - widgetHead.offsetHeight);
                } else {
                    inContainer.style.height = outContainer.clientHeight + "px";
                    break;
                }
            }
        }
    }
    /////////////////////////////////////////////////////////////

    if (!this.LightPivotTable || flag === true) {
        return;
    }

    if (this._SIZE_ADJUST_TIMEOUT) {
        clearTimeout(this._SIZE_ADJUST_TIMEOUT);
        this._SIZE_ADJUST_TIMEOUT = 0;
    }

    // filtering frequent size updates
    this._SIZE_ADJUST_TIMEOUT = setTimeout(function () {

        _._SIZE_ADJUST_TIMEOUT = 0;

        _.LightPivotTable.updateSizes();

    }, 100);
]]></Implementation>
</Method>
</Class>

</Export>