﻿// Lists manager script - JQuery adaptation
var isExporting = false;
var tabListManagerValue = "init";
var crtListMgr;

jQuery.ListManager = function (configData) {
    this.crtPage = 1;
    this.searchData = "@@@";
    this.varName = configData["varName"];
    this.searchMethod = configData["searchMethod"];
    this.resultDiv = $("#" + configData["resultDiv"]);
    this.maxDisplayedElts = configData["maxDisplayedElts"];
    this.timerInterval = configData["timerInterval"];
    this.searchDataMethod = configData["searchDataMethod"];
    this.noResultDisplay = configData["noResultDisplay"];
    this.tableModeHeader = configData["tableModeHeader"];
    this.tableModeHeaderDisplayedList = configData["tableModeHeaderDisplayedList"];
    this.tableExportModeHeader = configData["tableExportModeHeader"];
    this.tableSortPropertyNames = configData["tableSortPropertyNames"];
    this.sortPropertyNames = "";
    this.ascOrder = true;
    this.getTableModeValuesMethod = configData["getTableModeValuesMethod"];
    this.getTableModeRowCssOverride = configData["getTableModeRowCssOverride"];
    this.onRowClickAction = configData["onRowClickAction"];
    this.endDisplayCallBack = configData["endDisplayCallBack"];
    this.addStyle = configData["addStyle"];
    this.allowExport = configData["allowExport"];

    this.startTimer = function () {
        crtListMgr = this;
        window.setTimeout(function () { crtListMgr.timerEvent() }, this.timerInterval);
    }

    this.refreshData = function () {
        crtListMgr.searchData = "@@@";
        crtListMgr.timerEvent(crtListMgr);
    }

    this.getNbSkip = function () {
        if (isExporting) {return -1;}
        return (this.crtPage - 1) * this.maxDisplayedElts;
    }

    this.getSortProperty = function () {
        return this.sortPropertyNames;
    }

    this.getAscOrder = function () {
        return this.ascOrder;
    }

    this.getAddStyle = function () {
        return this.addStyle;
    }

    this.setSortPropertyNames = function (property, descOrderArg) {
        if (this.sortPropertyNames == property) {
            if (descOrderArg) {
                this.ascOrder = (descOrderArg == "desc");
            }
            else {
                this.ascOrder = (!this.ascOrder);
            }
        }
        else {
            this.sortPropertyNames = property;
            if (descOrderArg) {
                this.ascOrder = (descOrderArg == "desc");
            }
            else {
                this.ascOrder = true;
            }
        }
    }

    this.getNbMaxRes = function () {
        if (isExporting) { return -1; }
        return (this.maxDisplayedElts + 1);
    }

    this.timerEvent = function () {
        // if searchDataMethod returns null (when filter data like dates are not correct), no research is done 
        // and resultDiv is not updated
        if (crtListMgr.searchDataMethod() != null) {
            var oldSearchData = crtListMgr.searchData;
            crtListMgr.searchData = crtListMgr.searchDataMethod() + crtListMgr.sortPropertyNames + crtListMgr.ascOrder;
            if (crtListMgr.searchData == oldSearchData) {
                if (!crtListMgr.searchDone) {
                    crtListMgr.resultDiv.html(loadingLabel);
                    crtListMgr.searchMethod();
                    crtListMgr.searchDone = true;
                }
            }
            else {
                crtListMgr.crtPage = 1;
                crtListMgr.searchDone = false;
            }
            window.setTimeout(function () { crtListMgr.timerEvent(crtListMgr) }, crtListMgr.timerInterval);
        }
    }

    this.goToPage = function (pageNumber) {
        this.searchData = this.searchDataMethod() + this.sortPropertyNames + this.ascOrder;
        this.crtPage = Math.max(pageNumber, 1);
        this.searchDone = true;
        this.resultDiv.html(loadingLabel);
        this.searchMethod();
    }

    this.goToPageOffset = function (pageOffset) {
        this.goToPage(this.crtPage + pageOffset);
    }

    this.dataCallback = function (results) {
        var nbResults = -1;
        var noResultMsgDisplayed = false;
        // If list count is returned
        if (results != null && results.length >= 0 && typeof (results[0]) == "number") {
            if (results[0] <= 0) {
                noResultMsgDisplayed = true;
            }
            else {
                nbResults = results[0];
            }
        }
        else if (results == null || results.length <= 0) {
            noResultMsgDisplayed = true;
        }

        if (noResultMsgDisplayed) {
            crtListMgr.resultDiv.html(crtListMgr.noResultDisplay);
        }
        else {
            var nextPageAvailable = false;
            var maxElts = crtListMgr.maxDisplayedElts;
            if (nbResults > 0) { // If list count is set, there's an element more than usual
                maxElts++;
            }
            if (results.length > maxElts) {
                results.length = results.length - 1;
                nextPageAvailable = true;
            }
            var innerCode = "";
            // Display top navigation links (if not exporting)
            if (!isExporting) {
                innerCode += getPagesNavigLinks(crtListMgr.varName, crtListMgr.crtPage, nextPageAvailable, nbResults, crtListMgr.maxDisplayedElts, crtListMgr.allowExport);
                innerCode += "<div class='fClear'></div>";
            }

            // Display Headers
            innerCode += "<table class='tableList'" + (isExporting ? " border='1'" : "") + "><thead><tr class='tableListHeader'>";
            tableHeader = (isExporting ? crtListMgr.tableExportModeHeader : crtListMgr.tableModeHeader);
            $.each(tableHeader, function (i, header) {
                if (crtListMgr.tableSortPropertyNames && crtListMgr.tableSortPropertyNames[i] != null) {
                    if (isExporting) {
						innerCode += "<th style='background-color:#A2B1B8;height:20px;font-size:16px;'>" + header + "</th>";
					}
					else {
						innerCode += "<th class='link' onclick='" + crtListMgr.varName + ".setSortPropertyNames(\"" + crtListMgr.tableSortPropertyNames[i] + "\");'><span class='underline'>" + header + "</span>";
						if (crtListMgr.tableSortPropertyNames[i] == crtListMgr.sortPropertyNames) {
	                        if (crtListMgr.ascOrder) {
	                            innerCode += " <img src='graphics/button_asc.gif'/></th>";
	                        }
	                        else {
	                            innerCode += " <img src='graphics/button_desc.gif'/></th>";
	                        }
						}
                    }
                }
                else {
                    innerCode += "<th " + (isExporting ? "style='background-color:#A2B1B8;height:20px;font-size:16px'" : "") + " >" + header + "</th>";
                }
            });
            innerCode += "</tr></thead><tbody>";

            // Display Results (table content)
            var odd = false;
            $.each(results, function (i, result) {
                // Don't treat list count
                if (typeof (result) != "number") {
                    var values = crtListMgr.getTableModeValuesMethod(result, isExporting);
                    if (!isExporting) {
                        var clickAction = "";
                        if (crtListMgr.onRowClickAction) {
                            clickAction = " onclick=\"" + crtListMgr.onRowClickAction(result) + "\"";
                        }

                        var rowCss = "tableListData" + ((odd = !odd) ? "Odd" : "");
                        var customClass = "";
                        if (crtListMgr.getTableModeRowCssOverride) {
                            customClass = crtListMgr.getTableModeRowCssOverride(result, odd);
                        }

                        rowCss += " " + customClass;
                        innerCode += "<tr style=" + crtListMgr.addStyle + " class='" + rowCss + "' onmouseover=\"$(this).removeClass('" + customClass + "');$(this).addClass('tableListDataOver');\" onmouseout=\"$(this).removeClass('tableListDataOver');$(this).addClass('" + customClass + "');\"" + clickAction + ">";

                        $.each(values, function (i, value) {
                            innerCode += "<td>" + value + "</td>";
                        });
                    }
                    else {
                        // Mapping between display and export columns (some columns are different)
                        var mapping = new Array();
                        for (i = 0; i < crtListMgr.tableExportModeHeader.length; i++) {
                            for (j = 0; j < crtListMgr.tableModeHeader.length; j++) {
                                if (crtListMgr.tableModeHeader[j] == crtListMgr.tableExportModeHeader[i]) {
                                    mapping[i] = j;
                                }
                            }
                        }
                        trColor = (odd ? "#C4E4F1" : "#ffffff");
                        odd = !odd;
                        innerCode += "<tr>";
                        for (i = 0; i < crtListMgr.tableExportModeHeader.length; i++) {
                            innerCode += "<td style='background-color:" + trColor + "'>" + values[mapping[i]] + "</td>";
                        }
                    }
                    innerCode += "</tr>";
                }
            });

            innerCode += "</tbody></table>";

            // Check: XLS export?
            if (isExporting) {
                crtListMgr.exportCallBack(innerCode);
                isExporting = false; // export done => set isExporting param back to false in order to go back to display mode
            }
            else {
                innerCode += "<div class='tableListBottom'><div class='tableListBottomLeft'></div><div class='tableListBottomRight'></div></div>";
                // Display bottom navigation links
                innerCode += getPagesNavigLinks(crtListMgr.varName, crtListMgr.crtPage, nextPageAvailable, nbResults, crtListMgr.maxDisplayedElts, crtListMgr.allowExport);

                // Set div inner HTML
                crtListMgr.resultDiv.html(innerCode);

                // Call endDisplayCallBack if set
                if (this.endDisplayCallBack && typeof this.endDisplayCallBack == "function") {
                    setTimeout(this.endDisplayCallBack, 10);
                }
            }
        }
        hideLoadingDiv();
    }

    this.exportExcel = function () {
        isExporting = true;
        displayLoadingDiv();
        this.searchMethod();
    }

    this.exportCallBack = function (results) {
        $('#tabListExport').val(encodeURIComponent(results));
        $('#tabListForm').submit();
    }
};

/* --- UTILS CALLBACKS --- */
function getPagesNavigLinks(tabListName, crtPage, nextPageAvailable, nbResults, maxDisplayedElts, exportEnabled) {
    var pageMax = crtPage;
    if (nextPageAvailable) {
        pageMax++;
    }
    if (nbResults > 0) {
        pageMax = Math.floor(((nbResults - 1) / maxDisplayedElts) + 1);
    }

    var result = "<div class='tabListManagerActionDiv'>";
    // Display navigation only if pageMax > 1
    if (pageMax > 0) {
        // If previous page available: display "previous" link
        if (crtPage > 1) {
            result += "<a class='onHoverLine' href='#' onclick='" + tabListName + ".goToPageOffset(-1);'>&lt;&lt; " + previousLabel + "</a>";
        }
        for (i=1; i <= pageMax; i++) {
            if (i == crtPage && pageMax>1) {
                result += "&nbsp;&nbsp;<b>[" + i + "]</b>";
            }
            else if(i != crtPage && pageMax>1){
                result += "&nbsp;&nbsp;<a class='onHoverLine' href='#' onclick='" + tabListName + ".goToPage(" + i + ");'>" + i + "</a>";
            }
        }
        if (nextPageAvailable) {
            result += "&nbsp;&nbsp;<a class='onHoverLine' href='#' onclick='" + tabListName + ".goToPageOffset(1);'>" + nextLabel + " &gt;&gt;</a>";
        }
        if (nbResults > 0) {
            result += "&nbsp;&nbsp;&nbsp;&nbsp;<i>(" + nbResultsLabel + " " + nbResults + ")</i>";
        }
    }
    // If only one page, display only nb results
    else if (nbResults > 0) {
        result += "&nbsp;&nbsp;&nbsp;&nbsp;<i>" + nbResultsLabel + " " + nbResults + "</i>";
    }
    // Else, return ""
    else {
        return "";
    }
    
    if (exportEnabled) {
        result += "<span class='exportSpan link' onclick='" + tabListName + ".exportExcel();'>" + tabListManagerExportLabel + "</span>" +
        	"<form action='tabListReport.aspx' method='post' id='tabListForm'><input type='hidden' value='' name='tabListExport' id='tabListExport'/></form>";
    }
    result += "</div>";
    
    return result;
}
