Subversion Repositories munaweb

Rev

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