Subversion Repositories munaweb

Rev

Rev 19 | Rev 32 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 - 1
//
2
// Globals
3
//
4
var configServiceEndpoint = 'https://api.ebay.com/ws/api.dll';
5
var configRuName = 'Uwe_Jacobs-UweJacob-MUNATr-jwkrg';
6
var configWarningLevel = "Low";
7
var configAppid = 'UweJacob-MUNATrad-PRD-d132041a0-85284729';
8
var configDevid = '00fd6fda-3751-4095-b733-3899b20431ad';
9
var configCertid = 'PRD-132041a078aa-1ee6-4300-9454-6c5b';
10
var configSigninUrl = 'https://signin.ebay.com/ws/eBayISAPI.dll';
3 - 11
var configeBayLoginUrl = 'https://ujsoftware.linkpc.net/ebay/ebayLogin.php';
12
var configOauthTokenUrl = 'https://api.ebay.com/identity/v1/oauth2/token';
2 - 13
var configDiscogsToken = 'zFvVdCdHTtQnDHCxEFTJiBhalyHFUsjdyFPCjbqP&ty';
14
var configXmlRequestEntriesPerPage = '100';
15
var configUSPSUserId = '275MUNAT7574';
16
var configLinkedPayPal = 'paypal@munatrading.com';
17
var configListingUrl = 'https://ujsoftware.linkpc.net/ebay/listings/';
18
var configDiscogsBaseUrl = 'https://www.discogs.com';
19
var configDiscogsApiUrl = 'https://api.discogs.com/database/search';
20
var configDiscogsUserAgent = 'MUNA_Trading/1.0 +http://www.munatrading.com';
21
var configProxyUrl = 'https://ujsoftware.linkpc.net/proxy.php';
7 - 22
var configShopifyApiKey = '41f0d3bf0e8e114496b198938996d9d8';
23
var configShopifyPassword = 'f169694c488f45ccf187c92676765889';
24
var configShopifyUrl = 'https://' + configShopifyApiKey + ':' + configShopifyPassword + '@muna-trading.myshopify.com/admin/';
2 - 25
var configShopifyProductsUrl = 'products.json';
26
var configShopifyOrdersUrl = 'orders.json';
27
var configShopifyTransactionsUrl1 = 'orders/';
28
var configShopifyTransactionsUrl2 = '/transactions.json';
29
var configShopifyOrderLimit = 250;
30
var configeBayTradingVersion = '1085';
31
var configeBayMarketingVersion = 'v1.4.0';
32
var configeBayFinding = 'https://svcs.ebay.com/services/search/FindingService/v1';
33
var configeBayFindingVersion = '1.13.0';
17 - 34
var configeBayPostOrder = 'https://api.ebay.com/post-order/v2';
2 - 35
var configeBayShopping = 'http://open.api.ebay.com/shopping';
36
var configeBayShoppingVersion = '1063';
37
var configeBayAdCampaign = 'https://api.ebay.com/sell/marketing/v1/ad_campaign/';
38
var configUPSAccessKey = 'DD53C5F37DF74D28';
39
var configUPSUrl = 'https://onlinetools.ups.com/ups.app/xml/Track';
40
var configUPSUsername = 'muna_trading';
41
var configUPSPassword = 'ZX83tbf!w7';
42
var configUSPSUrl = 'https://secure.shippingapis.com/ShippingApi.dll';
43
var configGoogleMapsKey = 'AIzaSyBeSjH1CypAnYMYy_LIHqe8ngaAC6O-FWE';
44
 
45
var configTaxStateId = 'VA';
46
var configTaxRate = '6.000';
47
var configZip = '20120';
48
var configGetRecommendations = true;
49
var configDoesNotApply = 'Does not apply';
50
var configDefaultCountry = 'United States';
51
var configDefaultLanguage = 'English';
52
var configImage1Extension = ' Front.jpg';
53
var configImage2Extension = ' Rear.jpg';
54
var configdescriptionImageExtension = ' Front and Rear - small.jpg';
55
var configeBaySellerName = 'muna_trading';
56
var configAutoAcceptPrice = 0.85000;
57
var configMinBestOfferPrice = 0.65000;
58
 
59
var sessionId = '';
60
var eBayAuthToken = '';
61
var eBayAuthExpiration = '';
62
var eBayAuthTokenFlag = false;
63
 
64
//
65
// Prototypes
66
//
67
String.prototype.hashCode = function() {
68
	var hash = 0,
69
		i, chr;
70
	if (this.length === 0) return hash;
71
	for (i = 0; i < this.length; i++) {
72
		chr = this.charCodeAt(i);
73
		hash = ((hash << 5) - hash) + chr;
74
		hash |= 0; // Convert to 32bit integer
75
	}
76
 
77
	return (hash < 0 ? (hash * -1) : hash);
78
};
79
 
80
Number.prototype.pad = function(size) {
81
	var s = String(this);
82
	while (s.length < (size || 2)) {
83
		s = "0" + s;
84
	}
85
	return s;
86
};
87
 
88
String.prototype.toProperCase = function () {
89
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
90
};
91
 
92
Date.prototype.yyyymmdd = function() {
93
	var mm = this.getMonth() + 1; // getMonth() is zero-based
94
	var dd = this.getDate();
95
 
96
	return [this.getFullYear(), (mm > 9 ? '' : '0') + mm, (dd > 9 ? '' : '0') + dd].join('-');
97
};
98
 
99
String.prototype.contains = function(it) { return this.indexOf(it) != -1; };
100
 
19 - 101
String.prototype.b64encode = function() {
102
    return btoa(unescape(encodeURIComponent(this)));
17 - 103
};
19 - 104
String.prototype.b64decode = function() {
105
    return decodeURIComponent(escape(atob(this)));
17 - 106
};
107
 
2 - 108
//
109
// Functions
110
//
6 - 111
function getJsonArray(val) {
112
    if (val === undefined) {
113
        return ([]);
114
    }
115
 
116
    return(val instanceof Array ? val : [val]);
117
}
118
 
2 - 119
function round(value, decimals) {
120
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
121
}
122
 
123
// Polyfill for Internet Explorer
124
Math.trunc = Math.trunc || function(x) {
125
	var n = x - x % 1;
126
	return n === 0 && (x < 0 || (x === 0 && (1 / x !== 1 / 0))) ? -0 : n;
127
};
128
 
129
function tableCell(str) {
130
	return ('<td>' + str + '</td>');
131
}
132
 
133
function tableCellHidden(str) {
134
	return ('<td class="w3-hide">' + str + '</td>');
135
}
136
 
137
function tableHeader(str) {
138
	return ('<th>' + str + '</th>');
139
}
140
 
141
function tableCellLabel(str) {
142
	return ('<td id="' + str + '"></td>');
143
}
144
 
145
function tableCellLabelHidden(str, val) {
146
	return ('<td id="' + str + '" class="w3-hide">' + val + '</td>');
147
}
148
 
149
function tableCellAndLabel(str, label) {
150
	return ('<td id="' + label + '">' + str + '</td>');
151
}
152
 
153
function tableHeaderHidden(str) {
154
	return ('<th class="w3-hide">' + str + '</th>');
155
}
156
 
6 - 157
function tableHeaderCheckbox() {
2 - 158
	return ('<th class="sorter-checkbox filter-false"><input type="checkbox"></th>');
159
}
160
 
161
function tableCellCheckbox() {
162
	return ('<td><input type="checkbox"></td>');
163
}
164
 
165
function escapeHtml(unsafe) {
166
	return unsafe
167
		.replace(/&/g, "&amp;")
168
		.replace(/</g, "&lt;")
169
		.replace(/>/g, "&gt;")
170
		.replace(/"/g, "&quot;")
171
		.replace(/'/g, "&#039;");
172
}
173
 
174
function pad(num, size) {
175
    var s = num+"";
176
    while (s.length < size) s = "0" + s;
177
    return s;
178
}
179
 
180
function isset () {
181
  var a = arguments;
182
  var l = a.length;
183
  var i = 0;
184
  var undef;
185
 
186
  if (l === 0) {
187
    return false;
188
  }
189
 
190
  while (i !== l) {
191
    if (a[i] === undef || a[i] === null) {
192
      return false;
193
    }
194
    i++;
195
  }
196
 
197
  return true;
198
}
199
 
200
function getJsonValue(obj){
201
  return (isset(obj) ? obj : "");
202
}
203
 
204
function writeCookie() {
205
	document.cookie = 'eBayAuthToken=' + encodeURIComponent(eBayAuthToken) + ';expires=' + eBayAuthExpiration + ';';
206
}
207
 
208
function readCookie() {
209
	var name = 'eBayAuthToken=';
210
	var decodedCookie = decodeURIComponent(document.cookie);
211
	var ca = decodedCookie.split(';');
212
	for (var i = 0; i < ca.length; i++) {
213
		var c = ca[i];
214
		while (c.charAt(0) == ' ') {
215
			c = c.substring(1);
216
		}
217
		if (c.indexOf(name) === 0) {
218
			return c.substring(name.length, c.length);
219
		}
220
	}
221
	return "";
222
}
223
 
224
function isNumeric(input) {
225
	return (input - 0) == input && ('' + input).trim().length > 0;
226
}
227
 
228
function getRadioValue(name) {
229
	var group = document.getElementsByName(name);
230
 
231
	for (var i = 0; i < group.length; i++) {
232
		if (group[i].checked) {
233
			return group[i].value;
234
		}
235
	}
236
 
237
	return '';
238
}
239
 
240
function removeDuplicateRows($table){
241
    function getVisibleRowText($row){
242
        return $row.find('td:visible').text().toLowerCase();
243
    }
244
 
245
    $table.find('tr').each(function(index, row){
246
        var $row = $(row);
247
 
248
        $row.nextAll('tr').each(function(index, next){
249
            var $next = $(next);
250
            if(getVisibleRowText($next) == getVisibleRowText($row)) {
251
                $next.remove();
252
            }
253
        });
254
    });
255
}
256
 
257
function isValidUpcOrEanCode(str) {
258
	if (!isNumeric(str)) {
259
		return(false);
260
	}
261
 
262
	if (str.length == 12) {
263
		return(isValidUpcCode(str));
264
	} else if (str.length == 13) {
265
		return(isValidEanCode(str) === 0 ? true : false);
266
	}
267
 
268
	return(false);
269
}
270
 
271
function isValidEanCode(ean) {
272
    var result = 0;
273
    for (var counter = (ean.length - 1); counter >= 0; counter--) {
274
        result = result + parseInt(ean.charAt(counter)) * (1 + (2 * (counter % 2)));
275
    }
276
 
277
    return (10 - (result % 10)) % 10;
278
}
279
 
280
function isValidUpcCode(upc) {
281
	if (!isNumeric(upc) || upc.length !== 12) {
282
		return false;
283
	}
284
 
6 - 285
	res = calculateUpcRes(upc.substr(0, 11));
286
 
287
	if (parseInt(upc.substr(11, 1)) != res) {
288
		return false;
289
	}
290
 
291
	return true;
292
}
293
 
294
function calculateUpcRes(upc) {
295
	var i;
296
 
297
	if (!isNumeric(upc) || upc.length !== 11) {
298
		return -1;
299
	}
300
 
2 - 301
	var sum = 0;
302
 
303
	for (i = 0; i < 11; i += 2) {
304
		sum += (parseInt(upc.substr(i, 1)) * 3);
305
	}
306
 
307
	for (i = 1; i < 11; i += 2) {
308
		sum += parseInt(upc.substr(i, 1));
309
	}
310
 
311
	var res = sum % 10;
312
 
313
	if (res > 0) {
314
		res = 10 - res;
315
	}
316
 
6 - 317
	return res;
2 - 318
}
319
 
6 - 320
 
2 - 321
function isValidISBNCode(isbn) {
322
	var sum, weight, digit, check, i;
323
 
324
	if (isbn.length == 13) {
325
		sum = 0;
326
		for (i = 0; i < 12; i++) {
327
			digit = parseInt(isbn[i]);
328
			if (i % 2 == 1) {
329
				sum += 3 * digit;
330
			} else {
331
				sum += digit;
332
			}
333
		}
334
		check = (10 - (sum % 10)) % 10;
335
		return (check == isbn[isbn.length - 1]);
336
	}
337
 
338
	if (isbn.length == 10) {
339
		weight = 10;
340
		sum = 0;
341
		for (i = 0; i < 9; i++) {
342
			digit = parseInt(isbn[i]);
343
			sum += weight * digit;
344
			weight--;
345
		}
346
		check = 11 - (sum % 11);
347
		if (check == 10) {
348
			check = 'X';
349
		}
350
		return (check == isbn[isbn.length - 1].toUpperCase());
351
	}
352
 
353
	return false;
354
}
355
 
356
function escapeXml(unsafe) {
357
	return unsafe.replace(/[<>&'"]/g, function(c) {
358
		switch (c) {
359
			case '<':
360
				return '&lt;';
361
			case '>':
362
				return '&gt;';
363
			case '&':
364
				return '&amp;';
365
			case '\'':
366
				return '&apos;';
367
			case '"':
368
				return '&quot;';
369
		}
370
	});
371
}
372
 
373
 
374
/*
375
/ eBay Login
376
*/
377
function eBayLogin() {
378
	if (eBayAuthTokenFlag === false) {
379
		getSessionID();
380
	}
381
}
382
 
383
function getSessionID() {
384
	// Expects function requireNewLogin
385
	// Expects <div id="results">
386
 
387
	var i;
388
	var xw = new XMLWriter('UTF-8', '1.0');
389
 
390
	xw.writeStartDocument();
391
	xw.writeStartElement('GetSessionIDRequest');
392
	xw.writeAttributeString('xmlns', 'urn:ebay:apis:eBLBaseComponents');
393
	xw.writeElementString('RuName', configRuName);
394
	xw.writeEndElement(); /* GetSessionIDRequest */
395
	xw.writeEndDocument();
396
 
397
	var my_xml = xw.flush();
398
	xw.close();
399
 
400
	var xhr = new XMLHttpRequest();
401
	xhr.open('POST', configProxyUrl, true);
402
	xhr.setRequestHeader('Content-Type', 'text/xml');
403
	xhr.setRequestHeader('X-EBAY-API-APP-NAME', configAppid);
404
	xhr.setRequestHeader('X-EBAY-API-DEV-NAME', configDevid);
405
	xhr.setRequestHeader('X-EBAY-API-CERT-NAME', configCertid);
3 - 406
	xhr.setRequestHeader('X-EBAY-API-COMPATIBILITY-LEVEL', configeBayTradingVersion);
2 - 407
	xhr.setRequestHeader('X-EBAY-API-CALL-NAME', 'GetSessionID');
408
	xhr.setRequestHeader('X-EBAY-API-SITEID', '0');
409
	xhr.setRequestHeader('X-Proxy-URL', configServiceEndpoint);
410
 
411
	xhr.onload = function() {
5 - 412
        var xmlDoc = xhr.responseXML;
413
		var returnCode = xmlDoc.getElementsByTagName("Ack")[0].childNodes[0].nodeValue;
2 - 414
 
415
		if (returnCode == 'Success') {
5 - 416
			sessionId = xmlDoc.getElementsByTagName("SessionID")[0].childNodes[0].nodeValue;
2 - 417
 
418
			var win = window.open(configSigninUrl + '?SignIn&RuName=' + configRuName + '&SessID=' + sessionId, "eBay Login", "");
419
			var pollTimer = window.setInterval(function() {
420
				if (win.closed !== false) {
421
					window.clearInterval(pollTimer);
422
					getToken();
3 - 423
        		}
2 - 424
			}, 200);
425
		} else {
426
			requireNewLogin();
6 - 427
 
2 - 428
			var x = document.getElementById("results");
429
			if (x.className.indexOf("w3-show") == -1) {
430
				x.className += " w3-show";
431
			}
432
 
433
			x.innerHTML = "<p><strong>" + returnCode + ":</strong></p>";
5 - 434
			var errors = xmlDoc.getElementsByTagName("Errors");
2 - 435
			x.innerHTML += "<p>";
5 - 436
			for (i = 0; i < errors.length; i++) {
437
				x.innerHTML += errors[0].getElementsByTagName("SeverityCode")[0].innerHTML + " (" + errors[0].getElementsByTagName("ErrorCode")[0].innerHTML + "): " + escapeHtml(errors[0].getElementsByTagName("LongMessage")[0].innerHTML) + "<br/>";
2 - 438
			}
439
			x.innerHTML += "</p>";
440
		}
441
	};
442
 
443
	xhr.send(my_xml);
444
}
445
 
446
function getToken() {
447
	var x;
448
	var i;
449
	var xw = new XMLWriter('UTF-8', '1.0');
450
 
451
	xw.writeStartDocument();
452
	xw.writeStartElement('FetchTokenRequest');
453
	xw.writeAttributeString('xmlns', 'urn:ebay:apis:eBLBaseComponents');
454
	xw.writeElementString('SessionID', sessionId);
455
	xw.writeEndElement(); /* FetchTokenRequest */
456
	xw.writeEndDocument();
457
 
458
	var my_xml = xw.flush();
459
	xw.close();
460
 
461
	var xhr = new XMLHttpRequest();
462
	xhr.open('POST', configProxyUrl, true);
463
	xhr.setRequestHeader('Content-Type', 'text/xml');
464
	xhr.setRequestHeader('X-EBAY-API-APP-NAME', configAppid);
465
	xhr.setRequestHeader('X-EBAY-API-DEV-NAME', configDevid);
466
	xhr.setRequestHeader('X-EBAY-API-CERT-NAME', configCertid);
3 - 467
	xhr.setRequestHeader('X-EBAY-API-COMPATIBILITY-LEVEL', configeBayTradingVersion);
2 - 468
	xhr.setRequestHeader('X-EBAY-API-CALL-NAME', 'FetchToken');
469
	xhr.setRequestHeader('X-EBAY-API-SITEID', '0');
470
	xhr.setRequestHeader('X-Proxy-URL', configServiceEndpoint);
471
 
472
	xhr.onload = function() {
5 - 473
        var xmlDoc = xhr.responseXML;
474
		var returnCode = xmlDoc.getElementsByTagName("Ack")[0].childNodes[0].nodeValue;
2 - 475
 
476
		if (returnCode == 'Success') {
5 - 477
			eBayAuthToken = xmlDoc.getElementsByTagName("eBayAuthToken")[0].childNodes[0].nodeValue;
478
			eBayAuthExpiration = new Date(xmlDoc.getElementsByTagName("HardExpirationTime")[0].childNodes[0].nodeValue).toUTCString();
2 - 479
			writeCookie();
480
			connected();
481
		} else {
482
			requireNewLogin();
483
 
484
			x = document.getElementById("results");
485
			if (x.className.indexOf("w3-show") == -1) {
486
				x.className += " w3-show";
487
			}
488
 
489
			x.innerHTML = "<p><strong>" + returnCode + ":</strong></p>";
490
 
5 - 491
			x.innerHTML = "<p><strong>" + returnCode + ":</strong></p>";
492
			var errors = xmlDoc.getElementsByTagName("Errors");
2 - 493
			x.innerHTML += "<p>";
5 - 494
			for (i = 0; i < errors.length; i++) {
495
				x.innerHTML += errors[0].getElementsByTagName("SeverityCode")[0].innerHTML + " (" + errors[0].getElementsByTagName("ErrorCode")[0].innerHTML + "): " + escapeHtml(errors[0].getElementsByTagName("LongMessage")[0].innerHTML) + "<br/>";
2 - 496
			}
497
			x.innerHTML += "</p>";
498
		}
499
	};
500
 
501
	xhr.send(my_xml);
502
}
503
 
3 - 504
function getUrlParameter(win, name) {
505
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
506
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
507
    var results = regex.exec(win.location.search);
508
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
6 - 509
}
3 - 510
 
2 - 511
function feebackStarImage(score) {
512
	if (score > 999999) {
513
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconShootSlvr_25x25.gif" alt="Silver shooting star">';
514
	} else if (score > 499999) {
515
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconShootGrn_25x25.gif" alt="Green shooting star">';
516
	} else if (score > 99999) {
517
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconShootRed_25x25.gif" alt="Red shooting star">';
518
	} else if (score > 49999) {
519
		return '<img src="https://ir.ebaystatic.com/pictures/aw/icon/iconShootPrpl_25x25.gif" alt="Purple shooting star">';
520
	} else if (score > 24999) {
521
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconShootTeal_25x25.gif" alt="Turquoise shooting star">';
522
	} else if (score > 9999) {
523
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconShootYllw_25x25.gif" alt="Yellow shooting star">';
524
	} else if (score > 4999) {
525
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconGreenStar_25x25.gif" alt="Green star">';
526
	} else if (score > 999) {
527
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconRedStar_25x25.gif" alt="Red star">';
528
	} else if (score > 499) {
529
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconPurpleStar_25x25.gif" alt="Purple star">';
530
	} else if (score > 99) {
531
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconTealStar_25x25.gif" alt="Turquoise star">';
532
	} else if (score > 49) {
533
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconBlueStar_25x25.gif" alt="Blue star">';
534
	} else if (score > 9) {
535
		return '<img src="https://ir.ebaystatic.com/pictures/aw/pics/icon/iconYellowStar_25x25.gif" alt="Yellow star">';
536
	}
537
	return '';
538
}
539
 
540
function exportTableToCSV(tablename, filename) {
25 - 541
    var csv = ["\uFEFF"];
2 - 542
    var rows = document.getElementById(tablename).querySelectorAll("table tr");
6 - 543
    var dq = '"';
544
    var nq = "'";
2 - 545
 
546
    for (var i = 0; i < rows.length; i++) {
547
        var row = [], cols = rows[i].querySelectorAll("td, th");
548
 
549
        for (var j = 0; j < cols.length; j++) {
6 - 550
            if (cols[j].className.indexOf("w3-hide") == -1) {
551
                if (isNaN(cols[j].innerText)) {
552
                    row.push(dq + cols[j].innerText.replace(/"/g, '""') + dq);
553
                } else {
10 - 554
                    if (cols[j].innerText.includes(".")) {
555
                        row.push(cols[j].innerText);
556
                    } else {
14 - 557
                        row.push((cols[j].innerText.length > 7 ? nq : "") + cols[j].innerText);
10 - 558
                    }
6 - 559
                }
560
            }
2 - 561
        }
562
 
563
        csv.push(row.join(","));
564
    }
565
 
566
    // Download CSV file
567
    downloadCSV(csv.join("\n"), filename);
568
}
569
 
570
function downloadCSV(csv, filename) {
571
    var csvFile;
572
    var downloadLink;
573
 
574
    // CSV file
25 - 575
    csvFile = new Blob([csv], {type: "text/csv;charset=utf-8"});
2 - 576
 
577
    // Download link
578
    downloadLink = document.createElement("a");
579
 
580
    // File name
581
    downloadLink.download = filename;
582
 
583
    // Create a link to the file
584
    downloadLink.href = window.URL.createObjectURL(csvFile);
585
 
586
    // Hide download link
587
    downloadLink.style.display = "none";
588
 
589
    // Add the link to DOM
590
    document.body.appendChild(downloadLink);
591
 
592
    // Click download link
593
    downloadLink.click();
594
}
595
 
596
/* Progress Bar HTML
597
<div id="progressBarDiv" class="w3-container w3-padding w3-margin w3-card-4 w3-hide">
598
	<h2 id="progressBarHeader"></h2>
599
  <div class="w3-light-grey">
600
      <div id="progressBar" class="w3-container w3-green w3-center" style="width:0%">0%</div>
601
  </div>
602
</div>
603
*/
604
function initProgressBar(title) {
605
  	var elem = document.getElementById("progressBar");
606
	  elem.style.width = 0 + '%';
607
  	elem.innerHTML = 0 + '%';
608
 
609
  	elem = document.getElementById("progressBarDiv");
610
	  if (elem.className.indexOf("w3-show") == -1) {
611
		    elem.className += " w3-show";
612
  	}
613
 
614
	  elem = document.getElementById("progressBarHeader");
615
  	elem.innerHTML = title;
616
}
617
 
618
function updateProgressBar(maximum, current) {
10 - 619
	var elem = document.getElementById("progressBar");
620
	var width = (current / maximum) * 100;
621
	elem.style.width = width + '%';
622
	elem.innerHTML = width.toFixed(0) + '%';
2 - 623
}
624
 
625
function endProgressBar() {
626
    var elem = document.getElementById("progressBarDiv");
627
		elem.className = elem.className.replace(" w3-show", "");
628
}
629
 
10 - 630
// Progress Bar Modal
631
/*
632
<div class="modal" id="progressBarDiv">
633
  <div class="modal-dialog">
634
    <div class="modal-content">
635
      <div class="modal-header">
636
        <h4 id="progressBarHeader"></h4>
637
      </div>
638
      <div class="modal-body">
639
        <div class="progress">
640
          <div id="progressBar" class="progress-bar" style="width:0%">0%</div>
641
        </div>
642
      </div>
643
    </div>
644
  </div>
645
</div>
646
*/
647
function initProgressBarModal(title) {
648
  	var elem = document.getElementById("progressBar");
649
    elem.style.width = '0%';
650
  	elem.innerHTML = '0%';
651
 
652
    elem = document.getElementById("progressBarHeader");
653
  	elem.innerHTML = title;
19 - 654
 
10 - 655
  	$("#progressBarDiv").modal("show");
656
}
657
 
658
function endProgressBarModal() {
659
  	$("#progressBarDiv").modal("hide");
660
}
661
 
662
function extractTextContent(s) {
663
  var span = document.createElement('span');
664
  span.innerHTML = s;
665
  return span.textContent || span.innerText;
666
}
667
 
6 - 668
// xxxxx WIP
2 - 669
function sortHTMLTable(table, column = 0, type = 's', hasFooter = false) {
670
  var rows, switching, i, x, y, shouldSwitch;
671
  var nonData = (hasFooter ? 2 : 1);
672
  table = document.getElementById(table);
673
  switching = true;
674
  /* Make a loop that will continue until
675
  no switching has been done: */
676
  while (switching) {
677
    // Start by saying: no switching is done:
678
    switching = false;
679
    rows = table.rows;
680
    /* Loop through all table rows (except the
681
    first, which contains table headers): */
682
    for (i = 1; i < (rows.length - nonData); i++) {
683
      // Start by saying there should be no switching:
684
      shouldSwitch = false;
685
      /* Get the two elements you want to compare,
686
      one from current row and one from the next: */
687
      x = rows[i].getElementsByTagName("TD")[column];
688
      y = rows[i + 1].getElementsByTagName("TD")[column];
689
      // Check if the two rows should switch place:
690
      if (type == 'i') { // integer
691
        if (Number(x.innerHTML) > Number(y.innerHTML)) {
692
          // If so, mark as a switch and break the loop:
693
          shouldSwitch = true;
694
          break;
695
        }
696
      } else if (type == 'f') { // float
697
        if (Number(x.innerHTML).toFixed(2) > Number(y.innerHTML).toFixed(2)) {
698
          // If so, mark as a switch and break the loop:
699
          shouldSwitch = true;
700
          break;
701
        }
702
      } else if (type == 'c') { // currency
703
        if (Number(x.innerHTML.substr(1)).toFixed(2) > Number(y.innerHTML.substr(1)).toFixed(2)) {
704
          // If so, mark as a switch and break the loop:
705
          shouldSwitch = true;
706
          break;
707
        }
708
      } else if ('d') { // date
709
        if (Date(x.innerHTML) > Date(y.innerHTML)) {
710
          // If so, mark as a switch and break the loop:
711
          shouldSwitch = true;
712
          break;
713
        }
714
      } else { // string
715
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
716
          // If so, mark as a switch and break the loop:
717
          shouldSwitch = true;
718
          break;
719
        }
720
      }
721
    }
722
    if (shouldSwitch) {
723
      /* If a switch has been marked, make the switch
724
      and mark that a switch has been done: */
725
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
726
      switching = true;
727
    }
728
  }
7 - 729
}
730
 
731
// Update table sorter counters after processed deleting rows
732
// <p>Showing <span id="filtered-rows">0</span> of <span id="total-rows">0</span> / <span id="selected-rows">0</span> selected.</p>
733
function tableSorterUpdateCounters(tableName) {
734
    $("#" + tableName).trigger("update").trigger("appendCache").trigger("applyWidgets").trigger('search', false);
19 - 735
 
7 - 736
    var rowCount = $('#' + tableName + ' tbody tr').length;
737
    var filteredCount = rowCount - $('#' + tableName + ' tbody tr:hidden').length;
738
    var checkedCount = $('#' + tableName + ' tbody .checked').length;
19 - 739
 
7 - 740
    $('#total-rows').html(rowCount);
741
    $('#filtered-rows').html(filteredCount);
742
    $('#selected-rows').html(checkedCount);
743
    $("#" + tableName).find('thead input[type=checkbox]').prop('checked', false);
744
    $("#" + tableName).find('thead input[type=checkbox]').prop('indeterminate', false);
10 - 745
}
746
 
747
// flattens an object (recursively!), similarly to Array#flatten
748
// e.g. flatten({ a: { b: { c: "hello!" } } }); // => "hello!"
749
function flatten(object) {
750
  var check = _.isPlainObject(object) && _.size(object) === 1;
751
  return check ? flatten(_.values(object)[0]) : object;
752
}
753
 
754
function XMLparse(xml, flattenFlag = true) {
755
  var data = {};
756
 
17 - 757
  if (xml === null) {
758
    return data;
759
  }
19 - 760
 
10 - 761
  var isText = xml.nodeType === 3,
762
      isElement = xml.nodeType === 1,
763
      body = xml.textContent && xml.textContent.trim(),
764
      hasChildren = xml.children && xml.children.length,
765
      hasAttributes = xml.attributes && xml.attributes.length;
766
 
767
  // if it's text just return it
768
  if (isText) { return xml.nodeValue.trim(); }
769
 
770
  // if it doesn't have any children or attributes, just return the contents
771
  if (!hasChildren && !hasAttributes) { return body; }
772
 
773
  // if it doesn't have children but _does_ have body content, we'll use that
774
  if (!hasChildren && body.length) { data.text = body; }
775
 
776
  // if it's an element with attributes, add them to data.attributes
777
  if (isElement && hasAttributes) {
778
    data.attributes = _.reduce(xml.attributes, function(obj, name, id) {
779
      var attr = xml.attributes.item(id);
780
      obj[attr.name] = attr.value;
781
      return obj;
782
    }, {});
783
  }
784
 
785
  // recursively call #XMLparse over children, adding results to data
786
  _.each(xml.children, function(child) {
787
    var name = child.nodeName;
788
 
789
    // if we've not come across a child with this nodeType, add it as an object
790
    // and return here
791
    if (!_.has(data, name)) {
792
      data[name] = XMLparse(child, flattenFlag);
793
      return;
794
    }
795
 
796
    // if we've encountered a second instance of the same nodeType, make our
797
    // representation of it an array
798
    if (!_.isArray(data[name])) { data[name] = [data[name]]; }
799
 
800
    // and finally, append the new child
801
    data[name].push(XMLparse(child, flattenFlag));
802
  });
803
 
804
   // if we can, let's fold some attributes into the body
805
   _.each(data.attributes, function(value, key) {
806
   if (data[key] != null) { return; }
807
     data[key] = value;
808
     delete data.attributes[key];
809
   });
810
 
811
  // if data.attributes is now empty, get rid of it
812
  if (_.isEmpty(data.attributes)) { delete data.attributes; }
813
 
814
  // simplify to reduce number of final leaf nodes and return
815
  return (flattenFlag ? flatten(data) : data);
17 - 816
}
817
 
818
/* HTML include */
819
function includeHTML() {
820
    var z, i, elmnt, file, xhttp;
821
    /* Loop through a collection of all HTML elements: */
822
    z = document.getElementsByTagName("*");
823
    for (i = 0; i < z.length; i++) {
824
        elmnt = z[i];
825
        /* search for elements with a certain atrribute:*/
826
        file = elmnt.getAttribute("w3-include-html");
827
        if (file) {
828
            /* Make an HTTP request using the attribute value as the file name: */
829
            xhttp = new XMLHttpRequest();
830
            xhttp.onreadystatechange = function() {
831
                if (this.readyState == 4) {
832
                    if (this.status == 200) {
833
                        elmnt.innerHTML = this.responseText;
834
                    }
835
                    if (this.status == 404) {
836
                        elmnt.innerHTML = "<p>Page not found.</p>";
837
                    }
838
                    /* Remove the attribute, and call this function once more: */
839
                    elmnt.removeAttribute("w3-include-html");
840
                    includeHTML();
841
                }
842
            };
843
            xhttp.open("GET", file, true);
844
            xhttp.send();
845
            /* Exit the function: */
846
            return;
847
        }
848
    }
849
}