Passed
Push — master ( 392893...ddb241 )
by Plamen
01:26
created

TableHelper.iePrior   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 12
rs 9.95
1
var TableHelper = {
2
    Init: {
3
        SetColumnsHoverEffect: function (tContainer, tableId){
4
            var tHcells = tContainer.rows[0].cells;
5
            for(var i = 0; i < tHcells.length; i++){
6
                if(tHcells[i].firstChild.tagName === "A"){
7
                    tHcells[i].firstChild.setAttribute("onmouseover", "table.ColumnHover('" + tableId + "'," + i + ");");
8
                    tHcells[i].firstChild.setAttribute("onmouseout", "table.ColumnHover('" + tableId + "');");
9
                }
10
            }
11
        }
12
    },
13
    BuildRequest: {
14
        Sort: function (rq, strDesc){
15
            function sortBySpan(span, i){
16
                var order = span.innerHTML;
17
                if(order.length === 1){
18
                    rq.colNo = i;
19
                    rq.colOrd = order === strDesc ? "desc" : "asc";
20
                }
21
                return rq.colNo === i;
22
            }
23
24
            var thTags = document.getElementById(rq.tableId)
25
                    .getElementsByTagName("thead")[0]
26
                    .getElementsByTagName("th");
27
            var length = thTags.length;
28
            for(var i = 0; i < length; i++){
29
                var link = thTags[i].getElementsByTagName("a")[0];
30
                if(link){
31
                    var span = link.getElementsByTagName("span")[0];
32
                    if(span && sortBySpan(span, i)){
33
                        break;
34
                    }
35
                }
36
            }
37
        },
38
        Filter: function (rq){
39
            function getFilterFieldsByTableID(tableID){
40
                var fields = {filterBy: null, filter: null};
41
                var filterDiv = getFilterDivByTableIDOrNull(tableID);
42
                if(filterDiv !== null){
43
                    setFilterBy(fields, filterDiv);
44
                    setFilterValue(fields, filterDiv);
45
                }
46
                return fields;
47
            }
48
            function getFilterDivByTableIDOrNull(tableID){
49
                var res = null;
50
                if(document.getElementById(tableID).parentNode.getElementsByTagName("div").length > 0){
51
                    for(var i = 0; i < document.getElementById(tableID).parentNode.getElementsByTagName("div").length; i++){
52
                        if(document.getElementById(tableID).parentNode.getElementsByTagName("div")[i].getAttribute("class") === "filter"){
53
                            return document.getElementById(tableID).parentNode.getElementsByTagName("div")[i];
54
                        }
55
                    }
56
57
                }
58
                return res;
59
            }
60
            function setFilterBy(fields, filterDiv){
61
                var slctObj = filterDiv.getElementsByTagName("select")[0];
62
                if(slctObj && slctObj.options[slctObj.selectedIndex].value !== "all"){
63
                    fields.filterBy = slctObj.options[slctObj.selectedIndex].value;
64
                }
65
            }
66
            function setFilterValue(fields, filterDiv){
67
                var textObj = filterDiv.getElementsByTagName("input")[0];
68
                if(textObj && textObj.value && textObj.value.length !== 0){
69
                    fields.filter = encodeURIComponent(textObj.value.trim());
70
                }
71
            }
72
73
            var r = getFilterFieldsByTableID(rq.tableId);
74
            if(r.filter !== null){
75
                rq.filter = r.filter;
76
            }
77
            if(r.filterBy !== null){
78
                rq.filterBy = r.filterBy;
79
            }
80
        }
81
    },
82
    
83
    iePrior: function(v){
84
        var rv = false;
85
        if(window.navigator.appName === 'Microsoft Internet Explorer'){
86
            var ua = window.navigator.userAgent;
87
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
88
            if(re.exec(ua) !== null){
89
                rv = parseFloat(RegExp.$1);
90
            }
91
            rv = rv < v ? true : false;
92
        }
93
        return rv;
94
    },
95
    ColumnHover: function(tableContainer, index){
96
        var rows = document.getElementById(tableContainer).rows;
97
        var upto = rows.length - 1;
98
        if(typeof index === "undefined"){
99
            ColumnHoverRelease(rows, upto);
100
        } else {
101
            for(var i = 0; i < upto; i++){
102
                rows[i].cells[index].setAttribute("lang", "col-hover");
103
            }
104
        }
105
        function ColumnHoverRelease(rows, upto){
106
            for(var i = 0; i < upto; i++){
107
                for(var j = 0; j < rows[i].cells.length; j++){
108
                    if(rows[i].cells[j].lang){
109
                        rows[i].cells[j].removeAttribute("lang");
110
                    }
111
                }
112
            }
113
        };
114
    },
115
    ProcessPaginationLinks: function(tfoot){
116
        var pLinks = tfoot.querySelectorAll(".paging a");
117
        if(pLinks.length > 0){
118
            for(var j = 0; j < pLinks.length; j++){
119
                pLinks[j].setAttribute("href", "javascript:void(0);");
120
                pLinks[j].setAttribute("onclick", "return table.GoPage(this);");
121
            }
122
        }
123
    }
124
};
125
126
var TableHelperSetVisability = function(tableContainer, flag){
127
    var tbl = document.getElementById(tableContainer);
128
    if(flag === true){
129
        tbl.style.filter = "none";
130
        tbl.style.opacity = "1";
131
        tbl.style.cursor = "auto";
132
    }else if(flag === false){
133
        tbl.style.filter = "blur(1px)";
134
        tbl.style.opacity = "0.8";
135
        tbl.style.cursor = "wait";
136
    }else{
137
        console.error("table error in the flag value");
138
    }
139
};
140
141
var TableHelperGoPageGetNo = function(lnk, tableId){
142
    //check & serve pagination jump links
143
    var jumpDir = lnk.innerHTML.trim().substr(0, 1);
144
    if(jumpDir === "+" || jumpDir === "-"){
145
        var current = document.getElementById(tableId)
146
                        .querySelector("tfoot .paging .a").innerHTML;
147
        var jump = lnk.innerHTML.replace("K", "000").replace("M", "000000000");
148
        var jumpPage = (parseInt(current) + parseInt(jump));
149
        lnk.parentNode.setAttribute("data-page", jumpPage);
150
        lnk.style.transform = "none";
151
    }
152
    return lnk.parentNode.hasAttribute("data-page") ?
153
            lnk.parentNode.getAttribute("data-page") :
154
            lnk.innerHTML;
155
};
156
var TableHelperRequestToUrl = function(rq){
157
    var url = location.pathname + ".json" + location.search;
158
    if(typeof rq === "object"){
159
        var getUrlVarName = {
160
            colNo: "col", colOrd: "ord", filter: "filter",
161
            filterBy: "filter-by", pageNo: "pg", exportType: "export",
162
            tableId: "table-id"
163
        };
164
        var flagFirst = location.search.length < 1 ? true : false;
165
        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...
166
            var clue = flagFirst === true ? "?" : "&";
167
            url += clue + getUrlVarName[r] + "=" + rq[r];
168
            flagFirst = false;
169
        }
170
    }
171
    return url;
172
};
173
var TableHelperGetParent = function(obj, objType){
174
    while(obj && obj.tagName !== objType.toUpperCase()){
175
        obj = obj.parentNode;
176
    }
177
    return obj;
178
};
179
var TableHelperFilterGetTableId = function(field){
180
    if(field.tagName.toLowerCase() !== "select"){
181
        return field.getAttribute("data-table-id");
182
    }
183
    var f = field.parentNode.parentNode.getElementsByTagName("input")[0];
184
    return '' === f.value ? null : f.getAttribute("data-table-id");
185
};
186
var TableHelperDraw_Section = function(tableContainer, dt, tSection){
187
    var section = tSection === "tfoot" ? "tfoot" : "tbody";
188
    var tSec = document.getElementById(tableContainer)
189
                .getElementsByTagName(section)[0];
190
    TableHelperDraw_SectionClear(tSec, TableHelper.iePrior(9));
191
    for(var i = 0; i < dt.length; i++){
192
        var row = dt[i];
193
        var tRow = document.createElement("tr");
194
        TableHelperDraw_SectionRow(row, tRow);
195
        tSec.appendChild(tRow);
196
        if(section === "tfoot"){
197
            TableHelper.ProcessPaginationLinks(tSec);
198
        }
199
    }
200
};
201
var TableHelperDraw_SectionClear = function(tSection, iePrior9){
202
    if(iePrior9){
203
        if(tSection.firstChild){
204
            while(tSection.firstChild){
205
                tSection.removeChild(tSection.firstChild);
206
            }
207
        }
208
    }else{
209
        tSection.innerHTML = "";
210
    }
211
};
212
var TableHelperDraw_SectionRow = function(row, tRow){
213
    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...
214
        var tCell = document.createElement("td");
215
        if(typeof row[cell] === "string" || typeof row[cell] === "number"){
216
            tCell.innerHTML = row[cell];
217
        }else if(typeof row[cell] === "object"){
218
            TableHelperDraw_SectionRowCellFromObject(row, cell, tCell);
219
        }
220
        tRow.appendChild(tCell);
221
    }
222
};
223
var TableHelperDraw_SectionRowCellFromObject = function(row, cell, tCell){
224
    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...
225
        if(typeof row[cell][attr] === "string"){
226
            tCell.innerHTML = row[cell][attr];
227
        }else if(typeof row[cell][attr] === "object"){
228
            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...
229
                tCell.setAttribute(v, row[cell][attr][v]);
230
            }
231
        }
232
    }
233
};
234
235
//https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
236
var TableSingleton = (function(){
237
    // Instance stores a reference to the Singleton
238
    var instance;
239
    function initInstance(){
240
        // Singleton
241
        // Private methods and variables
242
        var tail = null;
243
        function Init(tableId){
244
            var tContainer = document.getElementById(tableId);
245
            if(!TableHelper.iePrior(9)){
246
                TableHelper.Init.SetColumnsHoverEffect(tContainer, tableId);
247
            }
248
            var tfoot = tContainer.getElementsByTagName("tfoot")[0];
249
            TableHelper.ProcessPaginationLinks(tfoot);
250
        }
251
        function BuildRequest(rq, crntTableId, strDesc){
252
            rq.tableId = crntTableId;
253
            TableHelper.BuildRequest.Sort(rq, strDesc);
254
            TableHelper.BuildRequest.Filter(rq);
255
        };
256
        function LoadData(tableContainer, rq){
257
            if(tail!==null){ tail.abort();}
258
            TableHelperSetVisability(tableContainer, false);
259
            var xmlhttp = window.XMLHttpRequest ? 
260
                            new XMLHttpRequest() : /* code for IE7+, Firefox, Chrome, Opera, Safari */
261
                            new window.ActiveXObject("Microsoft.XMLHTTP");/*code for IE6, IE5 */
262
            xmlhttp.onreadystatechange = function(){
263
                if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
264
                    Draw(tableContainer, JSON.parse(xmlhttp.responseText));
265
                    TableHelperSetVisability(tableContainer, true);
266
                    instance.LoadEndCalback(tableContainer);
267
                }
268
            };
269
            xmlhttp.open("GET", RequestToUrl(rq), true);
270
            xmlhttp.send();
271
            tail = xmlhttp; //put at tail to can abort later any previous
272
        }
273
        function Draw(tableContainer, d){
274
            TableHelperDraw_Section(tableContainer, d.body);
275
            TableHelperDraw_Section(tableContainer, d.footer, "tfoot");
276
            if(instance.rq !== null){
277
                var hover = document.getElementById(instance.rq.tableId)
278
                            .getElementsByTagName("th")[instance.rq.colNo].lang;
279
                if(hover){
280
                    instance.ColumnHover(tableContainer, instance.rq.colNo);
281
                }
282
            }
283
        }
284
285
        var FilterGetTableId = TableHelperFilterGetTableId;
286
        var GoPageGetNo = TableHelperGoPageGetNo;
287
        var getParent = TableHelperGetParent;
288
        var RequestToUrl = TableHelperRequestToUrl;
289
290
        return {
291
            rq: null,
292
            strAsc: String.fromCharCode(9650), //&#9650;
293
            strDesc: String.fromCharCode(9660),//&#9660; 
294
            ReloadData: function(tableId){
295
                var request = {};
296
                BuildRequest(request, tableId, this.strDesc);
297
                LoadData(tableId, request);
298
            },
299
            Filter: function(field){
300
                var crntTableId = FilterGetTableId(field);
301
                if(crntTableId !== null){
302
                    var request = {};
303
                    var exRq = this.rq;
304
                    BuildRequest(request, crntTableId, this.strDesc);
305
                    if(exRq === null ||
306
                        request.filter !== exRq.filter ||
307
                        request.filterBy !== exRq.filterBy
308
                    ){
309
                        LoadData(crntTableId, request);
310
                    }
311
                }
312
            },
313
            GoPage: function(lnk){
314
                var request = {};
315
                var crntTableId = getParent(lnk, "table").getAttribute("id");
316
                BuildRequest(request, crntTableId, this.strDesc);
317
                request.pageNo = GoPageGetNo(lnk, crntTableId);
318
                LoadData(crntTableId, request);
319
                return false;
320
            },
321
            Export: function(lnk, eType){
322
                var request = {};
323
                var crntTableId = getParent(lnk, "table").getAttribute("id");
324
                BuildRequest(request, crntTableId, this.strDesc);
325
                request.exportType = ["CSV", "Excel"].indexOf(eType) >= 0 ?
326
                                        eType : 
327
                                        "csv";
328
                window.open(RequestToUrl(request));
329
                return false;
330
            },
331
            Sort: function(colNo, lnk){
332
                var request = {};
333
                var crntTableId = getParent(lnk, "table").getAttribute("id");
334
                BuildRequest(request, crntTableId, this.strDesc);
335
                if(Math.round(colNo) === request.colNo){
336
                    request.colOrd = (request.colOrd === "asc" ? "desc" : "asc");
337
                }else{
338
                    request.colNo = Math.round(colNo);
339
                    request.colOrd = "asc";
340
                }
341
                LoadData(crntTableId, request);
342
                /* Clear and add new sort arrow */
343
                var headSpans = getParent(lnk, "thead").getElementsByTagName("span");
344
                var length = headSpans.length;
345
                for(var i = 0; i < length; i++){
346
                    headSpans[i].innerHTML = "";
347
                }
348
                lnk.getElementsByTagName("span")[0].innerHTML = (request.colOrd === "desc" ? this.strDesc : this.strAsc);
349
            },
350
            ColumnHover: TableHelper.ColumnHover, //function(tableContainer, index)
351
            LoadEndCalback: function(){},/*Allows override: function(tableId){if(tableId){...}}*/
352
            init: Init
353
        };
354
    }
355
    return {
356
        //Get the Singleton instance if one exists, or create one if it doesn't
357
        getInstance: function(){
358
            if(!instance){
359
                instance = initInstance();
360
            }
361
            return instance;
362
        }
363
    };
364
})();
365
var table = TableSingleton.getInstance();
366