Passed
Branchmaster (dfb0de)
by Plamen
01:34
created

add/table.js (1 issue)

Labels
Severity
1
var strAsc = String.fromCharCode(9650); //▲
2
var strDesc = String.fromCharCode(9660);//▼
3
var xmlhttp; var d;
4
5
var table = new function(){
6
    this.rq = null;
7
    this.tail = [];
8
9
    this.ReloadData = function(tableId){
10
        var request = {};
11
        this.BuildRequest(request,tableId);
12
        this.LoadData(tableId,request);
13
    };
14
15
    this.BuildRequest = function(request, crntTableId, skipPropertyArray){
16
        this.rq = request;
17
        this.checkSkip = function(skipProperty){
18
            var result = false;
19
            if(skipPropertyArray && Object.prototype
20
                .toString.call(skipPropertyArray) === '[object Array]'){
21
                if(skipPropertyArray.indexOf(skipProperty)>=0){
22
                    result = true;
23
                }
24
            }
25
            return result;
26
        };
27
        this.getSort = function(){
28
            var table = document.getElementById(crntTableId);
29
            var thTags = table.getElementsByTagName("thead")[0]
30
                        .getElementsByTagName("th");
31
            for(var i = 0; i < thTags.length; i++ ){
32
                if(thTags[i].getElementsByTagName("a")[0] && thTags[i]
33
                    .getElementsByTagName("a")[0].getElementsByTagName("span")
34
                    .length === 1
35
                ){
36
                    var order = thTags[i].getElementsByTagName("a")[0]
37
                                .getElementsByTagName("span")[0].innerHTML;
38
                    if(order.length === 1){
39
                        this.rq.colNo = i;
40
                        this.rq.colOrd = (order === window.strDesc) ?
41
                                            "desc" : "asc";
42
                    }
43
                }
44
            }
45
        };
46
        this.getFilter = function(){
47
            var r = this.getFilterFieldsByTbaleID(crntTableId);
48
            if(r.filter !== null){
49
                this.rq.filter = r.filter;
50
            }
51
            if(r.filterBy !== null){
52
                this.rq.filterBy = r.filterBy;
53
            }
54
        };
55
56
        /* Build request object */
57
        if(!this.checkSkip("sort")){            this.getSort();         }
58
        if(!this.checkSkip("filter")){          this.getFilter();       }
59
60
        this.rq.tableId = crntTableId;
61
        return this.rq;
62
    };
63
64
    this.RequestToUrl = function(rq){
65
        var url=location.pathname + ".json" + location.search;
66
        if(typeof rq === "object"){
67
            var getUrlVarName = {
68
                colNo: "col", colOrd: "ord", filter: "filter", 
69
                filterBy: "filter-by", pageNo: "pg", exportType: "export",
70
                tableId: "table-id"
71
            };
72
            var flagFirst = location.search.length < 1 ? true : false;
73
            for(var r in rq){
74
                if ( ! rq.hasOwnProperty(r)) {
75
                    continue; // Skip keys from the prototype.
76
                }
77
                var clue = flagFirst===true ? "?" : "&";
78
                url += clue + getUrlVarName[r] + "=" + rq[r];
79
                flagFirst = false;
80
            }
81
        }
82
        return url;
83
    };
84
85
    this.Filter = function(field){
86
        var request = {};
87
        var isSelect = field.tagName.toLowerCase() === "select";
88
        if(isSelect){
89
            var f = field.parentNode.parentNode.getElementsByTagName("input")[0];
90
            if('' === f.value){
91
                return;
92
            }
93
            var crntTableId = f.getAttribute("data-table-id");
94
        } else {
95
            var crntTableId = field.getAttribute("data-table-id");
96
        }
97
        var exRq = this.rq;
98
        this.BuildRequest(request,crntTableId);
99
        if(exRq===null){
100
            this.LoadData(crntTableId,request);
101
        } else if(  request.filter !== exRq.filter ||
102
                    request.filterBy !== exRq.filterBy
103
        ){
104
            this.LoadData(crntTableId,request);
105
        }
106
    };
107
108
    this.GoPage = function(lnk){
109
        var request = {};
110
        var table = this.getParent(lnk,"table");
111
        var crntTableId = table.getAttribute("id");
112
        this.BuildRequest(request,crntTableId);
113
        //check & serve pagination jump links
114
        var jumpDir=lnk.innerHTML.trim().substr(0,1);
115
        if(jumpDir==="+" || jumpDir==="-"){
116
            var current = table.querySelector("tfoot .paging .a").innerHTML;
117
            var jump = lnk.innerHTML.replace("K","000").replace("M","000000000");
118
            var jumpPage = (parseInt(current)+parseInt(jump));
119
            lnk.parentNode.setAttribute("data-page",jumpPage);
120
            lnk.style.transform="none";
121
        }
122
        request.pageNo = lnk.parentNode.hasAttribute("data-page") ?
123
                         lnk.parentNode.getAttribute("data-page") :
124
                         lnk.innerHTML;
125
        this.LoadData(crntTableId,request);
126
        return false;
127
    };
128
129
    this.Export = function(lnk,eType){
130
        var request = {};
131
        var crntTableId = this.getParent(lnk,"table").getAttribute("id");
132
        this.BuildRequest(request,crntTableId);
133
        request.exportType = ["CSV","Excel"].indexOf(eType)>=0 ? eType : "csv";
134
        window.open(this.RequestToUrl(request));
135
        return false;
136
    };
137
138
    this.Sort = function(colNo,lnk){
139
        var request = {};
140
        var crntTableId = this.getParent(lnk,"table").getAttribute("id");
141
        this.BuildRequest(request,crntTableId);
142
        if(Math.round(colNo) === request.colNo){
143
            request.colOrd = request.colOrd === "asc" ? "desc" : "asc";
144
        } else {
145
            request.colNo=Math.round(colNo);
146
            request.colOrd = "asc";
147
        }
148
        this.LoadData(crntTableId,request);
149
        /* Clear and add new sort arrow */
150
        var headSpans = this.getParent(lnk,"thead").getElementsByTagName("span");
151
        for(var i=0; i < headSpans.length; i++){
152
            headSpans[i].innerHTML = "";
153
        }
154
        lnk.getElementsByTagName("span")[0].innerHTML = (request.colOrd === "desc" ? window.strDesc : window.strAsc);
155
    };
156
157
    this.DrawSection = function(tableContainer, dt, tSection){
158
        var section = tSection === "tfoot" ? "tfoot" : "tbody";
159
        tSection =  document.getElementById(tableContainer).
160
                        getElementsByTagName(section)[0];
161
        this.clearSection(tSection);
162
        for(var i=0; i < dt.length; i++) {
163
            var row = dt[i];
164
            var tRow = document.createElement("tr");
165
166
            this.DrawRow(row, tRow);
167
168
            tSection.appendChild(tRow);
169
            if(section === "tfoot"){
170
                this.footerProcessPaginationLinks(tSection);
171
            }
172
            this.AppendRowCalback(tableContainer);
173
        }
174
    };
175
176
    this.DrawRow = function(row, tRow){
177
        for(var cell in row){
178
            if ( ! row.hasOwnProperty(cell)) {
179
                continue; // Skip keys from the prototype.
180
            }
181
            var tCell = document.createElement("td");
182
            if(typeof row[cell] === "string" || typeof row[cell] === "number"){
183
                tCell.innerHTML = row[cell];
184
            } else if(typeof row[cell] === "object"){
185
                this.DrawCellFromObject(row, cell, tCell);
186
            }
187
            tRow.appendChild(tCell);
188
        }
189
    };
190
191
    this.DrawCellFromObject = function(row, cell, tCell){
192
        for(var attr in row[cell]){
193
            if ( ! row[cell].hasOwnProperty(attr)) {
194
                continue; // Skip keys from the prototype.
195
            }
196
            if(typeof row[cell][attr] === "string"){
197
                tCell.innerHTML = row[cell][attr];
198
            } else if(typeof row[cell][attr] === "object"){
199
                for(var v in row[cell][attr]){
200
                    if ( ! row[cell][attr].hasOwnProperty(v)) {
201
                        continue; // Skip keys from the prototype.
202
                    }
203
                    tCell.setAttribute(v,row[cell][attr][v]);
204
                }
205
            }
206
        }
207
    };
208
209
    this.footerProcessPaginationLinks = function(tSection){
210
        var pLinks = tSection.querySelectorAll(".paging a");
211
        if(pLinks.length>0){
212
            for(var j=0; j < pLinks.length; j++){
213
                pLinks[j].setAttribute("href","javascript:void(0);");
214
                pLinks[j].setAttribute("onclick","return table.GoPage(this);");
215
            }
216
        }
217
    };
218
219
    this.clearSection = function(tSection){
220
        if(this.iePrior(9)){
221
            if(tSection.firstChild){
222
                while (tSection.firstChild) {
223
                    tSection.removeChild(tSection.firstChild);
224
                }
225
            }
226
        } else {
227
            tSection.innerHTML="";
228
        }
229
    };
230
231
    this.SetTheTableColumnsHoverEffect = function (tableContainer){
232
        if(this.iePrior(9)) {return;}
233
        var tContainer = document.getElementById(tableContainer);
234
        var tHcells = tContainer.rows[0].cells;
235
        for(var i=0; i < tHcells.length; i++){
236
            if(tHcells[i].firstChild.tagName === "A"){
237
                tHcells[i].firstChild.setAttribute("onmouseover","table.ColumnHover('"+tableContainer+"',"+i+");");
238
                tHcells[i].firstChild.setAttribute("onmouseout","table.ColumnHover('"+tableContainer+"');");
239
            }
240
        }
241
        var pLinks = tContainer.querySelectorAll("tfoot .paging a");
242
        if(pLinks.length>0){
243
            for(var j=0; j < pLinks.length; j++){
244
                pLinks[j].setAttribute("href","javascript:void(0);");
245
                pLinks[j].setAttribute("onclick","return table.GoPage(this);");
246
            }
247
        }
248
    };
249
250
    this.ColumnHover = function(tableContainer,index){
251
        if(this.iePrior(9)) {return;}
252
        var tRow = document.getElementById(tableContainer).rows;
253
        index = Math.round(index);
254
        for(var i=0; i < (tRow.length-1); i++){
255
            if(index >= 0){
256
                tRow[i].cells[index].setAttribute("lang","col-hover");
257
            } else {
258
                for(var j=0; j < tRow[i].cells.length; j++){
259
                    if(tRow[i].cells[j].lang){
260
                        tRow[i].cells[j].removeAttribute("lang");
261
                    }
262
                }
263
            }
264
        }
265
    };
266
267
    this.getFilterFieldsByTbaleID = function(tableID){
268
        var fields = {filterBy:null, filter:null};
269
        var filterDiv = this.getFilterDivByTableIDOrNull(tableID);
270
        if(filterDiv!==null) {
271
            var selectObj = filterDiv.getElementsByTagName("select")[0];
272
            var textObj = filterDiv.getElementsByTagName("input")[0];
273
            fields.filterBy = (selectObj===null || selectObj.options[selectObj.selectedIndex].value==="all") ? null : selectObj.options[selectObj.selectedIndex].value;
274
            fields.filter = (textObj===null || textObj.value.length === 0) ? null : encodeURIComponent(textObj.value.trim());
275
        }
276
        return fields;
277
    };
278
279
    this.getFilterDivByTableIDOrNull = function(tableID){
280
        var res = null;
281
        if(document.getElementById(tableID).parentNode.getElementsByTagName("div").length > 0){
282
            for (var i = 0; i < document.getElementById(tableID).parentNode.getElementsByTagName("div").length; i++) {
283
                if(document.getElementById(tableID).parentNode.getElementsByTagName("div")[i].getAttribute("class")==="filter"){
284
                    return document.getElementById(tableID).parentNode.getElementsByTagName("div")[i];
285
                }
286
            }
287
288
        }
289
        return res;
290
    };
291
292
    this.LoadData = function(tableContainer,rq){
293
        this.setVisability(tableContainer, false);
294
        if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();/* code for IE7+, Firefox, Chrome, Opera, Safari */
295
        } else { /** global: ActiveXObject */
296
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");/*code for IE6, IE5 */}
0 ignored issues
show
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...
297
        for (var i = 0; i < this.tail.length; i++) {
298
            var ex_xmlhttp = this.tail.shift();
299
            ex_xmlhttp.abort();
300
        }
301
        xmlhttp.onreadystatechange = function() {
302
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
303
                d = JSON.parse(xmlhttp.responseText);
304
                table.DrawSection(tableContainer,d.body);
305
                table.DrawSection(tableContainer,d.footer,"tfoot");
306
                table.LoadEndCalback(tableContainer);
307
                table.setVisability(tableContainer, true);
308
                if(typeof rq === "object"){
309
                    table.ColumnHover(tableContainer,rq.colNo);
310
                }
311
            }
312
        };
313
        xmlhttp.open("GET", this.RequestToUrl(rq), true);
314
        xmlhttp.send();
315
        this.tail.push(xmlhttp); //put in tail to may later abort any previous
316
    };
317
318
    this.setVisability = function(tableContainer,rq){
319
        var tbl = document.getElementById(tableContainer);
320
        if(rq===true){
321
            tbl.style.filter = "none";
322
            tbl.style.opacity = "1";
323
            tbl.style.cursor = "auto";
324
        } else if(rq===false){
325
            tbl.style.filter = "blur(1px)";
326
            tbl.style.opacity = "0.8";
327
            tbl.style.cursor = "wait";
328
        } else { console.log("table error in the rq value"); /*Shows error*/}
329
    };
330
331
    this.getParent = function (obj,objType){
332
        while( obj && obj.tagName !== objType.toUpperCase() ){
333
            obj = obj.parentNode;
334
        } return obj;
335
    };
336
337
    this.init = function(tableId){
338
        this.SetTheTableColumnsHoverEffect(tableId);
339
    };
340
341
    this.iePrior = function(v) {var rv=false; if(/** global: navigator */ navigator.appName==='Microsoft Internet Explorer') {var ua=navigator.userAgent; var re=new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if(re.exec(ua)!==null){rv=parseFloat(RegExp.$1);} rv=rv<v?true:false; } return rv;};
342
    this.loadJS = function(src){ var s = document.createElement('script'); s.src = src; document.getElementsByTagName('head')[0].appendChild(s);};
343
    this.loadCSS = function(src){ var s = document.createElement('link'); s.href = src; s.rel="stylesheet"; document.getElementsByTagName('head')[0].appendChild(s);};
344
345
    this.LoadEndCalback = function(tableId){/* Allows override if(tableId){}*/};
346
    this.AppendRowCalback = function(tableId){/* Allows override if(tableId){}*/};
347
};
348
349
/** Moves custom created filter to the Table's filter
350
 * @param {string} filterId
351
 * @param {string} tableId
352
 * @param {boolean} delay - needed in case the table is istill not executed */
353
function moveSelectorToTheTableFilter(filterId, tableId, delay){
354
    if(delay===true){
355
        setTimeout(function(){
356
            var filterDiv = document.getElementById(tableId)
357
                            .getElementsByTagName("div")[0];
358
            filterDiv.appendChild(document.getElementById(filterId));
359
        },500);
360
    } else {
361
        var filterDiv = document.getElementById(tableId)
362
                        .getElementsByTagName("div")[0];
363
        filterDiv.appendChild(document.getElementById(filterId));
364
    }
365
}
366
function changeListCustomFilter(selectObj){
367
    var fId = selectObj.options[selectObj.selectedIndex].value;
368
    var varName = selectObj.getAttribute("name");
369
    var varPos = document.URL.indexOf(varName);
370
    if(varPos>0){
371
        var url = fId!=="{!--Empty--!}" ? document.URL.substring(0,varPos) : document.URL.substring(0,(varPos-1));
372
    } else {
373
        var separator = document.URL.indexOf("?")>0 ? "&" : "?";
374
        url = document.URL + (fId!=="{!--Empty--!}" ? separator : "");
375
    }
376
    var newUrl = url + (fId!=="{!--Empty--!}" ? (varName + "=" + fId) : "");
377
    location.assign(newUrl);
378
}
379
380
381
function tablesLoadData(){
382
    var tables = document.getElementsByTagName("table");
383
    var envPrior9 = table.iePrior(9);
384
    for (var i = 0; i < tables.length; i++) {
385
        var isProcessable = envPrior9 ?
386
                            typeof tables[i]["data-table"]!== 'undefined' :
387
                            tables[i].hasAttribute("data-table");
388
        if(isProcessable && tables[i].getAttribute("data-table") === "js"){
389
            table.LoadData(tables[i].id);
390
            table.SetTheTableColumnsHoverEffect(tables[i].id);
391
        }
392
    }
393
    if(table.iePrior(10)){
394
        table.loadJS("/add/helpers/table/add/json2.js");
395
    }
396
397
    /*if(table.iePrior(8)){ //can be used to add apropriate tables links modifications
398
        // loadCSS("/add/helpers/table/add/ie7-and-down.css");
399
    }*/
400
}
401
402
/*if(window.addEventListener){window.addEventListener('load',tablesLoadData,false);} else if(window.attachEvent){window.attachEvent('onload',tablesLoadData);}*/