Subversion Repositories munaweb

Rev

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