Passed
Branchmaster (0ac829)
by Plamen
01:23
created

table.js ➔ ... ➔ this.DrawRow   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 1
Metric Value
cc 5
eloc 11
c 5
b 1
f 1
nc 4
nop 2
dl 0
loc 14
rs 9.3333
1
var strAsc = String.fromCharCode(9650); //▲
2
var strDesc = String.fromCharCode(9660);//▼
3
var xmlhttp;
4
var d;
5
6
var table = new function () {
7
    this.rq = null;
8
    this.tail = [];
9
10
    this.ReloadData = function (tableId) {
11
        var request = {};
12
        this.BuildRequest(request, tableId);
13
        this.LoadData(tableId, request);
14
    };
15
16
    this.BuildRequest = function (request, crntTableId, skipPropertyArray) {
17
        this.rq = request;
18
        this.checkSkip = function (skipProperty) {
19
            var result = false;
20
            if (skipPropertyArray && Object.prototype
21
                    .toString.call(skipPropertyArray) === '[object Array]') {
22
                if (skipPropertyArray.indexOf(skipProperty) >= 0) {
23
                    result = true;
24
                }
25
            }
26
            return result;
27
        };
28
        this.getSort = function () {
29
            var table = document.getElementById(crntTableId);
30
            var thTags = table.getElementsByTagName("thead")[0]
31
                    .getElementsByTagName("th");
32
            for (var i = 0; i < thTags.length; i++) {
33
                if (thTags[i].getElementsByTagName("a")[0] && thTags[i]
34
                        .getElementsByTagName("a")[0].getElementsByTagName("span")
35
                        .length === 1
36
                        ) {
37
                    var order = thTags[i].getElementsByTagName("a")[0]
38
                            .getElementsByTagName("span")[0].innerHTML;
39
                    if (order.length === 1) {
40
                        this.rq.colNo = i;
41
                        this.rq.colOrd = (order === window.strDesc) ?
42
                                "desc" : "asc";
43
                    }
44
                }
45
            }
46
        };
47
        this.getFilter = function () {
48
            var r = this.getFilterFieldsByTbaleID(crntTableId);
49
            if (r.filter !== null) {
50
                this.rq.filter = r.filter;
51
            }
52
            if (r.filterBy !== null) {
53
                this.rq.filterBy = r.filterBy;
54
            }
55
        };
56
57
        /* Build request object */
58
        if (!this.checkSkip("sort")) {
59
            this.getSort();
60
        }
61
        if (!this.checkSkip("filter")) {
62
            this.getFilter();
63
        }
64
65
        this.rq.tableId = crntTableId;
66
        return this.rq;
67
    };
68
69
    this.RequestToUrl = function (rq) {
70
        var url = location.pathname + ".json" + location.search;
71
        if (typeof rq === "object") {
72
            var getUrlVarName = {
73
                colNo: "col", colOrd: "ord", filter: "filter",
74
                filterBy: "filter-by", pageNo: "pg", exportType: "export",
75
                tableId: "table-id"
76
            };
77
            var flagFirst = location.search.length < 1 ? true : false;
78
            for (var r in rq) {
79
                if (!rq.hasOwnProperty(r)) {
80
                    continue; // Skip keys from the prototype.
81
                }
82
                var clue = flagFirst === true ? "?" : "&";
83
                url += clue + getUrlVarName[r] + "=" + rq[r];
84
                flagFirst = false;
85
            }
86
        }
87
        return url;
88
    };
89
90
    this.Filter = function (field) {
91
        var request = {};
92
        var isSelect = field.tagName.toLowerCase() === "select";
93
        if (isSelect) {
94
            var f = field.parentNode.parentNode.getElementsByTagName("input")[0];
95
            if ('' === f.value) {
96
                return;
97
            }
98
            var crntTableId = f.getAttribute("data-table-id");
99
        } else {
100
            crntTableId = field.getAttribute("data-table-id");
101
        }
102
        var exRq = this.rq;
103
        this.BuildRequest(request, crntTableId);
104
        if (exRq === null) {
105
            this.LoadData(crntTableId, request);
106
        } else if (request.filter !== exRq.filter ||
107
                request.filterBy !== exRq.filterBy
108
                ) {
109
            this.LoadData(crntTableId, request);
110
        }
111
    };
112
113
    this.GoPage = function (lnk) {
114
        var request = {};
115
        var table = this.getParent(lnk, "table");
116
        var crntTableId = table.getAttribute("id");
117
        this.BuildRequest(request, crntTableId);
118
        //check & serve pagination jump links
119
        var jumpDir = lnk.innerHTML.trim().substr(0, 1);
120
        if (jumpDir === "+" || jumpDir === "-") {
121
            var current = table.querySelector("tfoot .paging .a").innerHTML;
122
            var jump = lnk.innerHTML.replace("K", "000").replace("M", "000000000");
123
            var jumpPage = (parseInt(current) + parseInt(jump));
124
            lnk.parentNode.setAttribute("data-page", jumpPage);
125
            lnk.style.transform = "none";
126
        }
127
        request.pageNo = lnk.parentNode.hasAttribute("data-page") ?
128
                lnk.parentNode.getAttribute("data-page") :
129
                lnk.innerHTML;
130
        this.LoadData(crntTableId, request);
131
        return false;
132
    };
133
134
    this.Export = function (lnk, eType) {
135
        var request = {};
136
        var crntTableId = this.getParent(lnk, "table").getAttribute("id");
137
        this.BuildRequest(request, crntTableId);
138
        request.exportType = ["CSV", "Excel"].indexOf(eType) >= 0 ? eType : "csv";
139
        window.open(this.RequestToUrl(request));
140
        return false;
141
    };
142
143
    this.Sort = function (colNo, lnk) {
144
        var request = {};
145
        var crntTableId = this.getParent(lnk, "table").getAttribute("id");
146
        this.BuildRequest(request, crntTableId);
147
        if (Math.round(colNo) === request.colNo) {
148
            request.colOrd = request.colOrd === "asc" ? "desc" : "asc";
149
        } else {
150
            request.colNo = Math.round(colNo);
151
            request.colOrd = "asc";
152
        }
153
        this.LoadData(crntTableId, request);
154
        /* Clear and add new sort arrow */
155
        var headSpans = this.getParent(lnk, "thead").getElementsByTagName("span");
156
        for (var i = 0; i < headSpans.length; i++) {
157
            headSpans[i].innerHTML = "";
158
        }
159
        lnk.getElementsByTagName("span")[0].innerHTML = (request.colOrd === "desc" ? window.strDesc : window.strAsc);
160
    };
161
162
    this.DrawSection = function (tableContainer, dt, tSection) {
163
        var section = tSection === "tfoot" ? "tfoot" : "tbody";
164
        tSection = document.getElementById(tableContainer).
165
                getElementsByTagName(section)[0];
166
        this.clearSection(tSection);
167
        for (var i = 0; i < dt.length; i++) {
168
            var row = dt[i];
169
            var tRow = document.createElement("tr");
170
171
            this.DrawRow(row, tRow);
172
173
            tSection.appendChild(tRow);
174
            if (section === "tfoot") {
175
                this.footerProcessPaginationLinks(tSection);
176
            }
177
            this.AppendRowCalback(tableContainer);
178
        }
179
    };
180
181
    this.DrawRow = function (row, tRow) {
182
        var length = row.length;
183
        for (var i = 0; i < length; i++) {
184
            var tCell = document.createElement("td");
185
            if (typeof row[i] === "string" ||
186
                    typeof row[i] === "number"
187
                    ) {
188
                tCell.innerHTML = row[i];
189
            } else if (typeof row[i] === "object") {
190
                this.DrawCellFromObject(row, row[i], tCell);
191
            }
192
            tRow.appendChild(tCell);
193
        }
194
    };
195
196
    this.DrawCellFromObject = function (row, cell, tCell) {
197
        for (var attr in row[cell]) {
198
            if (!row[cell].hasOwnProperty(attr)) {
199
                continue; // Skip keys from the prototype.
200
            }
201
            if (typeof row[cell][attr] === "string") {
202
                tCell.innerHTML = row[cell][attr];
203
            } else if (typeof row[cell][attr] === "object") {
204
                for (var v in row[cell][attr]) {
205
                    if (!row[cell][attr].hasOwnProperty(v)) {
206
                        continue; // Skip keys from the prototype.
207
                    }
208
                    tCell.setAttribute(v, row[cell][attr][v]);
209
                }
210
            }
211
        }
212
    };
213
214
    this.footerProcessPaginationLinks = function (tSection) {
215
        var pLinks = tSection.querySelectorAll(".paging a");
216
        if (pLinks.length > 0) {
217
            for (var j = 0; j < pLinks.length; j++) {
218
                pLinks[j].setAttribute("href", "javascript:void(0);");
219
                pLinks[j].setAttribute("onclick", "return table.GoPage(this);");
220
            }
221
        }
222
    };
223
224
    this.clearSection = function (tSection) {
225
        if (this.iePrior(9)) {
226
            if (tSection.firstChild) {
227
                while (tSection.firstChild) {
228
                    tSection.removeChild(tSection.firstChild);
229
                }
230
            }
231
        } else {
232
            tSection.innerHTML = "";
233
        }
234
    };
235
236
    this.SetTheTableColumnsHoverEffect = function (tableContainer) {
237
        if (this.iePrior(9)) {
238
            return;
239
        }
240
        var tContainer = document.getElementById(tableContainer);
241
        var tHcells = tContainer.rows[0].cells;
242
        for (var i = 0; i < tHcells.length; i++) {
243
            if (tHcells[i].firstChild.tagName === "A") {
244
                tHcells[i].firstChild.setAttribute("onmouseover", "table.ColumnHover('" + tableContainer + "'," + i + ");");
245
                tHcells[i].firstChild.setAttribute("onmouseout", "table.ColumnHover('" + tableContainer + "');");
246
            }
247
        }
248
        var pLinks = tContainer.querySelectorAll("tfoot .paging a");
249
        if (pLinks.length > 0) {
250
            for (var j = 0; j < pLinks.length; j++) {
251
                pLinks[j].setAttribute("href", "javascript:void(0);");
252
                pLinks[j].setAttribute("onclick", "return table.GoPage(this);");
253
            }
254
        }
255
    };
256
257
    this.ColumnHover = function (tableContainer, index) {
258
        if (this.iePrior(9)) {
259
            return;
260
        }
261
        var tRow = document.getElementById(tableContainer).rows;
262
        index = Math.round(index);
263
        for (var i = 0; i < (tRow.length - 1); i++) {
264
            if (index >= 0) {
265
                tRow[i].cells[index].setAttribute("lang", "col-hover");
266
            } else {
267
                for (var j = 0; j < tRow[i].cells.length; j++) {
268
                    if (tRow[i].cells[j].lang) {
269
                        tRow[i].cells[j].removeAttribute("lang");
270
                    }
271
                }
272
            }
273
        }
274
    };
275
276
    this.getFilterFieldsByTbaleID = function (tableID) {
277
        var fields = {filterBy: null, filter: null};
278
        var filterDiv = this.getFilterDivByTableIDOrNull(tableID);
279
        if (filterDiv !== null) {
280
            var selectObj = filterDiv.getElementsByTagName("select")[0];
281
            var textObj = filterDiv.getElementsByTagName("input")[0];
282
            fields.filterBy = (selectObj === null || selectObj.options[selectObj.selectedIndex].value === "all") ? null : selectObj.options[selectObj.selectedIndex].value;
283
            fields.filter = (textObj === null || textObj.value.length === 0) ? null : encodeURIComponent(textObj.value.trim());
284
        }
285
        return fields;
286
    };
287
288
    this.getFilterDivByTableIDOrNull = function (tableID) {
289
        var res = null;
290
        if (document.getElementById(tableID).parentNode.getElementsByTagName("div").length > 0) {
291
            for (var i = 0; i < document.getElementById(tableID).parentNode.getElementsByTagName("div").length; i++) {
292
                if (document.getElementById(tableID).parentNode.getElementsByTagName("div")[i].getAttribute("class") === "filter") {
293
                    return document.getElementById(tableID).parentNode.getElementsByTagName("div")[i];
294
                }
295
            }
296
297
        }
298
        return res;
299
    };
300
301
    this.LoadData = function (tableContainer, rq) {
302
        this.setVisability(tableContainer, false);
303
        if (window.XMLHttpRequest) {
304
            xmlhttp = new XMLHttpRequest();/* code for IE7+, Firefox, Chrome, Opera, Safari */
305
        } else { /** global: ActiveXObject */
306
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");/*code for IE6, IE5 */
0 ignored issues
show
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
307
        }
308
        for (var i = 0; i < this.tail.length; i++) {
309
            var ex_xmlhttp = this.tail.shift();
310
            ex_xmlhttp.abort();
311
        }
312
        xmlhttp.onreadystatechange = function () {
313
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
314
                d = JSON.parse(xmlhttp.responseText);
315
                table.DrawSection(tableContainer, d.body);
316
                table.DrawSection(tableContainer, d.footer, "tfoot");
317
                table.LoadEndCalback(tableContainer);
318
                table.setVisability(tableContainer, true);
319
                if (typeof rq === "object") {
320
                    table.ColumnHover(tableContainer, rq.colNo);
321
                }
322
            }
323
        };
324
        xmlhttp.open("GET", this.RequestToUrl(rq), true);
325
        xmlhttp.send();
326
        this.tail.push(xmlhttp); //put in tail to may later abort any previous
327
    };
328
329
    this.setVisability = function (tableContainer, rq) {
330
        var tbl = document.getElementById(tableContainer);
331
        if (rq === true) {
332
            tbl.style.filter = "none";
333
            tbl.style.opacity = "1";
334
            tbl.style.cursor = "auto";
335
        } else if (rq === false) {
336
            tbl.style.filter = "blur(1px)";
337
            tbl.style.opacity = "0.8";
338
            tbl.style.cursor = "wait";
339
        } else {
340
            console.log("table error in the rq value"); /*Shows error*/
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
341
        }
342
    };
343
344
    this.getParent = function (obj, objType) {
345
        while (obj && obj.tagName !== objType.toUpperCase()) {
346
            obj = obj.parentNode;
347
        }
348
        return obj;
349
    };
350
351
    this.init = function (tableId) {
352
        this.SetTheTableColumnsHoverEffect(tableId);
353
    };
354
355
    this.iePrior = function (v) {
356
        var rv = false;
357
        if (/** global: navigator */ navigator.appName === 'Microsoft Internet Explorer') {
0 ignored issues
show
Bug introduced by
The variable navigator seems to be never declared. If this is a global, consider adding a /** global: navigator */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
358
            var ua = navigator.userAgent;
359
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
360
            if (re.exec(ua) !== null) {
361
                rv = parseFloat(RegExp.$1);
362
            }
363
            rv = rv < v ? true : false;
364
        }
365
        return rv;
366
    };
367
    this.loadJS = function (src) {
368
        var s = document.createElement('script');
369
        s.src = src;
370
        document.getElementsByTagName('head')[0].appendChild(s);
371
    };
372
    this.loadCSS = function (src) {
373
        var s = document.createElement('link');
374
        s.href = src;
375
        s.rel = "stylesheet";
376
        document.getElementsByTagName('head')[0].appendChild(s);
377
    };
378
379
    this.LoadEndCalback = function (tableId) {
380
        if (tableId) {/*Allows override*/
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
381
        }
382
    };
383
    this.AppendRowCalback = function (tableId) {
384
        if (tableId) {/*Allows override*/
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
385
        }
386
    };
387
};
388
389
/** Moves custom created filter to the Table's filter
390
 * @param {string} filterId
391
 * @param {string} tableId
392
 * @param {boolean} delay - needed in case the table is istill not executed */
393
function moveSelectorToTheTableFilter(filterId, tableId, delay) {
394
    if (delay === true) {
395
        setTimeout(function () {
396
            var filterDiv = document.getElementById(tableId)
397
                    .getElementsByTagName("div")[0];
398
            filterDiv.appendChild(document.getElementById(filterId));
399
        }, 500);
400
    } else {
401
        var filterDiv = document.getElementById(tableId)
402
                .getElementsByTagName("div")[0];
403
        filterDiv.appendChild(document.getElementById(filterId));
404
    }
405
}
406
function changeListCustomFilter(selectObj) {
407
    var fId = selectObj.options[selectObj.selectedIndex].value;
408
    var hasValue = fId !== "{!--Empty--!}";
409
    var varName = selectObj.getAttribute("name");
410
    var varPos = document.URL.indexOf(varName);
411
    if (varPos > 0) {
412
        var url = hasValue ?
413
                document.URL.substring(0, varPos) :
414
                document.URL.substring(0, (varPos - 1));
415
    } else {
416
        var separator = document.URL.indexOf("?") > 0 ? "&" : "?";
417
        url = document.URL + (hasValue ? separator : "");
418
    }
419
    var newUrl = url + (hasValue ? (varName + "=" + fId) : "");
420
    location.assign(newUrl);
421
}
422
423
424
function tablesLoadData() {
425
    var tables = document.getElementsByTagName("table");
426
    var envPrior9 = table.iePrior(9);
427
    for (var i = 0; i < tables.length; i++) {
428
        var isProcessable = envPrior9 ?
429
                typeof tables[i]["data-table"] !== 'undefined' :
430
                tables[i].hasAttribute("data-table");
431
        if (isProcessable && tables[i].getAttribute("data-table") === "js") {
432
            table.LoadData(tables[i].id);
433
            table.SetTheTableColumnsHoverEffect(tables[i].id);
434
        }
435
    }
436
    if (table.iePrior(10)) {
437
        table.loadJS("/add/helpers/table/add/json2.js");
438
    }
439
440
    /*if(table.iePrior(8)){ //can be used to add apropriate tables links modifications
441
     // loadCSS("/add/helpers/table/add/ie7-and-down.css");
442
     }*/
443
}
444
445
/*if(window.addEventListener){window.addEventListener('load',tablesLoadData,false);} else if(window.attachEvent){window.attachEvent('onload',tablesLoadData);}*/