Subversion Repositories munaweb

Rev

Rev 193 | Details | Compare with Previous | Last modification | View Log | RSS feed

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