Subversion Repositories munaweb

Rev

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