Subversion Repositories munaweb

Rev

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