Passed
Branchmaster (62f4a8)
by Plamen
01:28
created

table.js ➔ TableHelperDraw_SectionClear   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 11
rs 10
1
var TableInitSetColumnsHoverEffect = function(tContainer, tableId){
2
    var tHcells = tContainer.rows[0].cells;
3
    for(var i = 0; i < tHcells.length; i++){
4
        if(tHcells[i].firstChild.tagName === "A"){
5
            tHcells[i].firstChild.setAttribute("onmouseover", "table.ColumnHover('" + tableId + "'," + i + ");");
6
            tHcells[i].firstChild.setAttribute("onmouseout", "table.ColumnHover('" + tableId + "');");
7
        }
8
    }
9
};
10
var TableHelperBuildRequest = function(rq, crntTableId, strDesc){
11
    rq.tableId = crntTableId;
12
    TableHelperBuildRequest_Sort(rq, strDesc);
13
    TableHelperBuildRequest_Filter(rq);
14
};
15
var TableHelperBuildRequest_Sort = function(rq, strDesc){
16
    function sortBySpan(span, i){
17
        var order = span.innerHTML;
18
        if(order.length === 1){
19
            rq.colNo = i;
20
            rq.colOrd = order === strDesc ? "desc" : "asc";
21
        }
22
        return rq.colNo === i;
23
    }
24
    
25
    var thTags = document.getElementById(rq.tableId)
26
            .getElementsByTagName("thead")[0]
27
            .getElementsByTagName("th");
28
    var length = thTags.length;
29
    for(var i = 0; i < length; i++){
30
        var link = thTags[i].getElementsByTagName("a")[0];
31
        if(link){
32
            var span = link.getElementsByTagName("span")[0];
33
            if(span && sortBySpan(span, i)){
34
                break;
35
            }
36
        }
37
    }
38
};
39
var TableHelperBuildRequest_Filter = function(rq){
40
    function getFilterFieldsByTableID(tableID){
41
        var fields = {filterBy: null, filter: null};
42
        var filterDiv = getFilterDivByTableIDOrNull(tableID);
43
        if(filterDiv !== null){
44
            setFilterBy(fields, filterDiv);
45
            setFilterValue(fields, filterDiv);
46
        }
47
        return fields;
48
    }
49
    function getFilterDivByTableIDOrNull(tableID){
50
        var res = null;
51
        if(document.getElementById(tableID).parentNode.getElementsByTagName("div").length > 0){
52
            for(var i = 0; i < document.getElementById(tableID).parentNode.getElementsByTagName("div").length; i++){
53
                if(document.getElementById(tableID).parentNode.getElementsByTagName("div")[i].getAttribute("class") === "filter"){
54
                    return document.getElementById(tableID).parentNode.getElementsByTagName("div")[i];
55
                }
56
            }
57
58
        }
59
        return res;
60
    }
61
    function setFilterBy(fields, filterDiv){
62
        var slctObj = filterDiv.getElementsByTagName("select")[0];
63
        if(slctObj && slctObj.options[slctObj.selectedIndex].value !== "all"){
64
            fields.filterBy = slctObj.options[slctObj.selectedIndex].value;
65
        }
66
    }
67
    function setFilterValue(fields, filterDiv){
68
        var textObj = filterDiv.getElementsByTagName("input")[0];
69
        if(textObj && textObj.value && textObj.value.length !== 0){
70
            fields.filter = encodeURIComponent(textObj.value.trim());
71
        }
72
    }
73
74
    var r = getFilterFieldsByTableID(rq.tableId);
75
    if(r.filter !== null){
76
        rq.filter = r.filter;
77
    }
78
    if(r.filterBy !== null){
79
        rq.filterBy = r.filterBy;
80
    }
81
};
82
var TableHelperColumnHover = function(tableContainer, index){
83
    var rows = document.getElementById(tableContainer).rows;
84
    var upto = rows.length - 1;
85
    if(typeof index === "undefined"){
86
        TableHelperColumnHoverRelease(rows, upto);
87
    } else {
88
        for(var i = 0; i < upto; i++){
89
            rows[i].cells[index].setAttribute("lang", "col-hover");
90
        }
91
    }
92
};
93
var TableHelperColumnHoverRelease = function(rows, upto){
94
    for(var i = 0; i < upto; i++){
95
        for(var j = 0; j < rows[i].cells.length; j++){
96
            if(rows[i].cells[j].lang){
97
                rows[i].cells[j].removeAttribute("lang");
98
            }
99
        }
100
    }
101
};
102
var TableHelperSetVisability = function(tableContainer, flag){
103
    var tbl = document.getElementById(tableContainer);
104
    if(flag === true){
105
        tbl.style.filter = "none";
106
        tbl.style.opacity = "1";
107
        tbl.style.cursor = "auto";
108
    }else if(flag === false){
109
        tbl.style.filter = "blur(1px)";
110
        tbl.style.opacity = "0.8";
111
        tbl.style.cursor = "wait";
112
    }else{
113
        console.error("table error in the flag value");
114
    }
115
};
116
var TableHelperProcessPaginationLinks = function(tfoot){
117
    var pLinks = tfoot.querySelectorAll(".paging a");
118
    if(pLinks.length > 0){
119
        for(var j = 0; j < pLinks.length; j++){
120
            pLinks[j].setAttribute("href", "javascript:void(0);");
121
            pLinks[j].setAttribute("onclick", "return table.GoPage(this);");
122
        }
123
    }
124
};
125
var TableHelperIePrior = function(v){
126
    var rv = false;
127
    if(window.navigator.appName === 'Microsoft Internet Explorer'){
128
        var ua = window.navigator.userAgent;
129
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
130
        if(re.exec(ua) !== null){
131
            rv = parseFloat(RegExp.$1);
132
        }
133
        rv = rv < v ? true : false;
134
    }
135
    return rv;
136
};
137
var TableHelperRequestToUrl = function(rq){
138
    var url = location.pathname + ".json" + location.search;
139
    if(typeof rq === "object"){
140
        var getUrlVarName = {
141
            colNo: "col", colOrd: "ord", filter: "filter",
142
            filterBy: "filter-by", pageNo: "pg", exportType: "export",
143
            tableId: "table-id"
144
        };
145
        var flagFirst = location.search.length < 1 ? true : false;
146
        for(var r in rq){
1 ignored issue
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
147
            var clue = flagFirst === true ? "?" : "&";
148
            url += clue + getUrlVarName[r] + "=" + rq[r];
149
            flagFirst = false;
150
        }
151
    }
152
    return url;
153
};
154
var TableHelperGetParent = function(obj, objType){
155
    while(obj && obj.tagName !== objType.toUpperCase()){
156
        obj = obj.parentNode;
157
    }
158
    return obj;
159
};
160
var TableHelperFilterGetTableId = function(field){
161
    if(field.tagName.toLowerCase() !== "select"){
162
        return field.getAttribute("data-table-id");
163
    }
164
    var f = field.parentNode.parentNode.getElementsByTagName("input")[0];
165
    return '' === f.value ? null : f.getAttribute("data-table-id");
166
};
167
var TableHelperDraw_Section = function(tableContainer, dt, tSection){
168
    var section = tSection === "tfoot" ? "tfoot" : "tbody";
169
    var tSec = document.getElementById(tableContainer)
170
                .getElementsByTagName(section)[0];
171
    TableHelperDraw_SectionClear(tSec, TableHelperIePrior(9));
172
    for(var i = 0; i < dt.length; i++){
173
        var row = dt[i];
174
        var tRow = document.createElement("tr");
175
        TableHelperDraw_SectionRow(row, tRow);
176
        tSec.appendChild(tRow);
177
        if(section === "tfoot"){
178
            TableHelperProcessPaginationLinks(tSec);
179
        }
180
    }
181
};
182
var TableHelperDraw_SectionClear = function(tSection, iePrior9){
183
    if(iePrior9){
184
        if(tSection.firstChild){
185
            while(tSection.firstChild){
186
                tSection.removeChild(tSection.firstChild);
187
            }
188
        }
189
    }else{
190
        tSection.innerHTML = "";
191
    }
192
};
193
var TableHelperDraw_SectionRow = function(row, tRow){
194
    for(var cell in row){
1 ignored issue
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
195
        var tCell = document.createElement("td");
196
        if(typeof row[cell] === "string" || typeof row[cell] === "number"){
197
            tCell.innerHTML = row[cell];
198
        }else if(typeof row[cell] === "object"){
199
            TableHelperDraw_SectionRowCellFromObject(row, cell, tCell);
200
        }
201
        tRow.appendChild(tCell);
202
    }
203
};
204
var TableHelperDraw_SectionRowCellFromObject = function(row, cell, tCell){
205
    for(var attr in row[cell]){
1 ignored issue
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
206
        if(typeof row[cell][attr] === "string"){
207
            tCell.innerHTML = row[cell][attr];
208
        }else if(typeof row[cell][attr] === "object"){
209
            for(var v in row[cell][attr]){
1 ignored issue
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
210
                tCell.setAttribute(v, row[cell][attr][v]);
211
            }
212
        }
213
    }
214
};
215
216
//https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
217
var TableSingleton = (function(){
218
    // Instance stores a reference to the Singleton
219
    var instance;
220
    function initInstance(){
221
        // Singleton
222
        // Private methods and variables
223
        var tail = [];
224
        function LoadData(tableContainer, rq){
225
            TableHelperSetVisability(tableContainer, false);
226
            if(window.XMLHttpRequest){
227
                var xmlhttp = new XMLHttpRequest();/* code for IE7+, Firefox, Chrome, Opera, Safari */
228
            }else{ 
229
                xmlhttp = new window.ActiveXObject("Microsoft.XMLHTTP");/*code for IE6, IE5 */
230
            }
231
            for(var i = 0; i < tail.length; i++){
232
                var ex_xmlhttp = tail.shift();
233
                ex_xmlhttp.abort();
234
            }
235
            xmlhttp.onreadystatechange = function(){
236
                if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
237
                    var d = JSON.parse(xmlhttp.responseText);
238
                    instance.rq = rq;
239
                    instance.Draw(tableContainer, d);
240
                    instance.LoadEndCalback(tableContainer);
241
                    TableHelperSetVisability(tableContainer, true);
242
                }
243
            };
244
            xmlhttp.open("GET", RequestToUrl(rq), true);
245
            xmlhttp.send();
246
            tail.push(xmlhttp); //put at tail to can abort later any previous
247
        }
248
        function Init(tableId){
249
            var tContainer = document.getElementById(tableId);
250
            if(iePrior(9)){
251
                TableInitSetColumnsHoverEffect(tContainer, tableId);
252
            }
253
            var tfoot = tContainer.getElementsByTagName("tfoot")[0];
254
            TableHelperProcessPaginationLinks(tfoot);
255
        }
256
        function Draw(tableContainer, d){
257
            TableHelperDraw_Section(tableContainer, d.body);
258
            TableHelperDraw_Section(tableContainer, d.footer, "tfoot");
259
            if(this.rq !== null){
260
                var hover = document.getElementById(this.rq.tableId)
261
                            .getElementsByTagName("th")[this.rq.colNo].lang;
262
                if(hover){
263
                    instance.ColumnHover(tableContainer, this.rq.colNo);
264
                }
265
            }
266
        }
267
268
        var BuildRequest = TableHelperBuildRequest;
269
        var FilterGetTableId = TableHelperFilterGetTableId;
270
        var getParent = TableHelperGetParent;
271
        var iePrior = TableHelperIePrior;
272
        var RequestToUrl = TableHelperRequestToUrl;
273
274
        return {
275
            rq: null,
276
            strAsc: String.fromCharCode(9650), //&#9650;
277
            strDesc: String.fromCharCode(9660),//&#9660; 
278
            ReloadData: function(tableId){
279
                var request = {};
280
                BuildRequest(request, tableId, this.strDesc);
281
                LoadData(tableId, request);
282
            },
283
            Filter: function(field){
284
                var crntTableId = FilterGetTableId(field);
285
                if(crntTableId !== null){
286
                    var request = {};
287
                    var exRq = this.rq;
288
                    BuildRequest(request, crntTableId, this.strDesc);
289
                    if(exRq === null ||
290
                        request.filter !== exRq.filter ||
291
                        request.filterBy !== exRq.filterBy
292
                    ){
293
                        LoadData(crntTableId, request);
294
                    }
295
                }
296
            },
297
            GoPage: function(lnk){
298
                var request = {};
299
                var table = getParent(lnk, "table");
300
                var crntTableId = table.getAttribute("id");
301
                BuildRequest(request, crntTableId, this.strDesc);
302
                //check & serve pagination jump links
303
                var jumpDir = lnk.innerHTML.trim().substr(0, 1);
304
                if(jumpDir === "+" || jumpDir === "-"){
305
                    var current = table.querySelector("tfoot .paging .a").innerHTML;
306
                    var jump = lnk.innerHTML.replace("K", "000").replace("M", "000000000");
307
                    var jumpPage = (parseInt(current) + parseInt(jump));
308
                    lnk.parentNode.setAttribute("data-page", jumpPage);
309
                    lnk.style.transform = "none";
310
                }
311
                request.pageNo = lnk.parentNode.hasAttribute("data-page") ?
312
                                    lnk.parentNode.getAttribute("data-page") :
313
                                    lnk.innerHTML;
314
                LoadData(crntTableId, request, this.strDesc);
0 ignored issues
show
Bug introduced by
The call to LoadData seems to have too many arguments starting with this.strDesc.
Loading history...
315
                return false;
316
            },
317
            Export: function(lnk, eType){
318
                var request = {};
319
                var crntTableId = getParent(lnk, "table").getAttribute("id");
320
                BuildRequest(request, crntTableId, this.strDesc);
321
                request.exportType = ["CSV", "Excel"].indexOf(eType) >= 0 ?
322
                                        eType : 
323
                                        "csv";
324
                window.open(RequestToUrl(request));
325
                return false;
326
            },
327
            Sort: function(colNo, lnk){
328
                var request = {};
329
                var crntTableId = getParent(lnk, "table").getAttribute("id");
330
                BuildRequest(request, crntTableId, this.strDesc);
331
                if(Math.round(colNo) === request.colNo){
332
                    request.colOrd = (request.colOrd === "asc" ? "desc" : "asc");
333
                }else{
334
                    request.colNo = Math.round(colNo);
335
                    request.colOrd = "asc";
336
                }
337
                LoadData(crntTableId, request);
338
                /* Clear and add new sort arrow */
339
                var headSpans = getParent(lnk, "thead").getElementsByTagName("span");
340
                var length = headSpans.length;
341
                for(var i = 0; i < length; i++){
342
                    headSpans[i].innerHTML = "";
343
                }
344
                lnk.getElementsByTagName("span")[0].innerHTML = (request.colOrd === "desc" ? this.strDesc : this.strAsc);
345
            },
346
347
            ColumnHover: function(tableContainer, index){
348
                if(!iePrior(9)){
349
                    TableHelperColumnHover.call(this, tableContainer, index);
350
                }
351
            },
352
            Draw: Draw,
353
            LoadEndCalback: function(){},/*Allows override: function(tableId){if(tableId){...}}*/
354
            init: Init
355
        };
356
    }
357
    return {
358
        //Get the Singleton instance if one exists, or create one if it doesn't
359
        getInstance: function(){
360
            if(!instance){
361
                instance = initInstance();
362
            }
363
            return instance;
364
        }
365
    };
366
})();
367
var table = TableSingleton.getInstance();
368