-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathpucaPower.js
1400 lines (1083 loc) · 54.5 KB
/
pucaPower.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Puca Power
// @version 1.4.4
// @namespace https://github.com/llamasoft/Puca-Power
// @supportURL https://github.com/llamasoft/Puca-Power
// @description A JavaScript utility for better trading on PucaTrade.com
// @downloadURL https://llamasoft.github.io/Puca-Power/pucaPower.js
// @grant unsafeWindow
// @include https://pucatrade.com/trades
// @include https://pucatrade.com/trades/
// @run-at document-idle
// ==/UserScript==
var pucaPower = {
/* ===== INTERNAL VARIABLES ===== */
version: 'v1.4.4',
updateDate: '2016-05-11',
formUrl: 'https://llamasoft.github.io/Puca-Power/controls.html',
// Default values for internal settings
// If you change this structure, you need to update the following:
// loadDefaultSettings
// applySettingsToPage
// loadSettingsFromPage
// setupListeners
// controls.html
defaults: {
// Reload the trade table after reloadInterval seconds since the last reload
// NOTE: This may be different than "reload every reloadInterval seconds" because
// there are actions that reload the table that are beyond our control
// (e.g. sending a card, changing country filters, searching for a card)
reloadInterval: 60,
maxPages: 10,
alert: {
onBundle: true,
bundleThreshold: 500,
colorizeBundleRows: true,
colorizeBundleColor: '#CCFF99',
onOutgoing: true,
colorizeOutgoingRows: true,
colorizeOutgoingColor: '#FFEBB5',
onNewOnly: false,
playSound: true,
soundFile: 'https://llamasoft.github.io/Puca-Power/alert.mp3',
titleText: '\u2605 Trade alert! \u2605',
showNotification: true,
notificationTimeout: 7.5 * 1000
},
filter: {
cardsByValue: false,
cardsMinValue: 50,
membersByPoints: false,
membersMinPoints: 400
}
},
// Settings structures
reloadInterval: null,
maxPages: null,
alert: null,
filter: null,
// Selector string to pull the trade table rows
tableStr: 'table.infinite tbody',
tableRowStr: 'table.infinite tbody tr[id^="uc_"]',
// Map of asynchronous events that we may need to wait on
events: {
tableLoadComplete: false,
outgoingLoadComplete: false
},
// Array of objects of the loaded trade data
// Each entry is {tradeID, memberID, memberName, memberPts, country, cardName, cardPts}
tableData: [],
// Object of card information
// Each entry is {cardSet, cardName, cardPts}, key is trade ID
cardData: {},
// Object of objects of the table data grouped by memberID
// Each object has:
// memberName - The displayed name of the member
// memberPts - The number of points the user has available
// country - The country associated with the member
// cardQty - The number of cards the user wants from you
// tradeIDs - The trade IDs and values associated with the cards they want
// totalCardPts - The sum value of all the cards the user wants from you
// hasAlert - A flag that's true if the user has some kind of alert (see below)
// hasBundleAlert - Flag the notes if the member qualifies as a trade bundle
// hasOutgoingAlert - Flag that notes if the member has unsent outgoing trades
memberData: {},
// Object of objects of the outgoing (unshipped) trades
// Each object is {memberName, cardQty, totalCardPts}, key is memberID
outgoingTrades: {},
// Object of trade IDs and trade value, key is trade ID
seenAlerts: {},
sentTrades: 0,
// Enable debug messages
// debugLevel 0 - Errors and trade alerts
// debugLevel 1 - Important messages only
// debugLevel 2 - Semi-important messages
// debugLevel 3 - Informational messages
// debugLevel >3 - Probably noise
debugLevel: 0,
debug: function (msgLevel, msg) {
var padding;
if ( msgLevel <= this.debugLevel ) {
// String.prototype.repeat is proposed, but not always supported
padding = new Array( Math.min(msgLevel, 10) + 1 ).join(' ');
console.log(padding + '[' + msgLevel + '] - ' + msg);
}
},
/* ===== SETTINGS FUNCTIONS ===== */
// Reset all settings to default values
// Calls applySettingsToPage()
loadDefaultSettings: function () {
this.debug(2, 'Resetting settings to default values');
this.reloadInterval = this.defaults.reloadInterval;
this.maxPages = this.defaults.maxPages;
this.alert = this.defaults.alert;
this.filter = this.defaults.filter;
this.applySettingsToPage();
},
// Clear local storage settings
clearLocalSettings: function () {
this.debug(2, 'Deleting local settings');
delete localStorage.pucaPowerSettings;
},
// Save current settings to local storage
saveSettingsToLocal: function () {
if ( typeof Storage === 'undefined' ) {
this.debug(2, 'No local storage, cannot save settings');
this.addNote('Your settings were applied but could not be saved locally', 'text-warning');
return;
}
this.debug(2, 'Saving settings to local storage');
localStorage.pucaPowerSettings = JSON.stringify({
version: this.version,
reloadInterval: this.reloadInterval,
maxPages: this.maxPages,
alert: this.alert,
filter: this.filter,
debugLevel: this.debugLevel
});
this.addNote('Your settings were saved and applied', 'text-success');
},
// Load settings from local storage
// Calls clearLocalSettings() on error
loadSettingsFromLocal: function () {
if ( typeof Storage === 'undefined' ) {
this.debug(2, 'No local storage, cannot load settings');
return;
}
if ( !localStorage.pucaPowerSettings ) {
this.debug(2, 'No local settings found, skipping load');
return;
}
this.debug(3, 'Loading settings from local storage');
var settings = JSON.parse(localStorage.pucaPowerSettings);
if ( !settings ) {
this.debug(1, 'Failed to parse settings, purging settings');
this.clearLocalSettings();
return;
}
// Using the default settings as a starting point, overlay the settings we could load
// This is endended from a new object to prevent clobbering of the defaults object
settings = $.extend(true, {}, this.defaults, settings);
this.reloadInterval = settings.reloadInterval;
this.maxPages = settings.maxPages;
this.alert = settings.alert;
this.filter = settings.filter;
this.debugLevel = settings.debugLevel;
},
// Load settings from controls on the page
// Implicitly calls applySettingsToPage()
loadSettingsFromPage: function () {
this.debug(4, 'Loading settings from page');
var safeParse = function (value, nanFallback, negFallback) {
var temp = parseInt(value, 10);
if ( isNaN(temp) ) { temp = nanFallback; }
if ( temp <= 0 ) { temp = negFallback; }
return temp;
};
this.reloadInterval = safeParse(
$('input#reloadInterval').val(),
this.reloadInterval,
this.defaults.reloadInterval
);
// Don't be a menace
if ( this.reloadInterval < 20 ) { this.reloadInterval = 20; }
// TODO: maxPages
this.alert = {
onBundle: $('input#alertOnBundle').prop('checked'),
bundleThreshold:
safeParse(
$('input#alertBundleThreshold').val(),
this.alert.bundleThreshold,
this.defaults.alert.bundleThreshold
),
colorizeBundleRows: $('input#alertColorizeBundleRows').prop('checked'),
colorizeBundleColor: $('input#alertColorizeBundleColor').val(),
onOutgoing: $('input#alertOnOutgoing').prop('checked'),
colorizeOutgoingRows: $('input#alertColorizeOutgoingRows').prop('checked'),
colorizeOutgoingColor: $('input#alertColorizeOutgoingColor').val(),
playSound: $('input#alertPlaySound').prop('checked'),
soundFile: $('input#alertSoundFile').val().trim(),
onNewOnly: $('input#alertOnNewOnly').prop('checked'),
titleText: this.defaults.alert.titleText,
showNotification: $('input#alertShowNotification').prop('checked'),
notificationTimeout: this.defaults.alert.notificationTimeout
};
this.filter = {
cardsByValue: $('input#filterCardsByValue').prop('checked'),
cardsMinValue:
safeParse(
$('input#filterCardsMinValue').val(),
this.filter.cardsMinValue,
this.defaults.filter.cardsMinValue
),
membersByPoints: $('input#filterMembersByPoints').prop('checked'),
membersMinPoints:
safeParse(
$('input#filterMembersMinPoints').val(),
this.filter.membersMinPoints,
this.defaults.filter.membersMinPoints
)
};
// In case safeParse() changed anything
this.applySettingsToPage();
},
// Update HTML inputs to match current settings
// Calls updatePageState() on completion
applySettingsToPage: function () {
this.debug(4, 'Applying active settings to page');
$('input#reloadInterval').val(this.reloadInterval);
// TODO: maxPages
// Trade bundle settings
$('input#alertOnBundle').prop('checked', this.alert.onBundle);
$('input#alertBundleThreshold').val(this.alert.bundleThreshold);
$('input#alertColorizeBundleRows').prop('checked', this.alert.colorizeBundleRows);
$('input#alertColorizeBundleColor').val(this.alert.colorizeBundleColor);
// Outgoing trades settings
$('input#alertOnOutgoing').prop('checked', this.alert.onOutgoing);
$('input#alertColorizeOutgoingRows').prop('checked', this.alert.colorizeOutgoingRows);
$('input#alertColorizeOutgoingColor').val(this.alert.colorizeOutgoingColor);
// Alert settings
$('input#alertPlaySound').prop('checked', this.alert.playSound);
$('audio#alertSound').attr('src', this.alert.soundFile);
$('input#alertSoundFile').val(this.alert.soundFile);
$('input#alertShowNotification').prop('checked', this.alert.showNotification);
$('input#alertOnNewOnly').prop('checked', this.alert.onNewOnly);
// Filter settings
$('input#filterCardsByValue').prop('checked', this.filter.cardsByValue);
$('input#filterCardsMinValue').val(this.filter.cardsMinValue);
$('input#filterMembersByPoints').prop('checked', this.filter.membersByPoints);
$('input#filterMembersMinPoints').val(this.filter.membersMinPoints);
this.updatePageState();
},
// Enable or disable inputs based on current options
// Called from applySettingsToPage()
updatePageState: function () {
var isChecked;
var isEnabled;
// Alert on bundle checkbox is connected to its colorize checkboxes
isChecked = $('input#alertOnBundle').prop('checked');
$('input#alertBundleThreshold').prop('disabled', !isChecked);
$('input#alertColorizeBundleRows').prop('disabled', !isChecked);
$('input#alertColorizeBundleColor').prop('disabled', !isChecked);
// Colorize bundle rows checkbox is connected to the color picker
isChecked = $('input#alertColorizeBundleRows').prop('checked');
isEnabled = !$('input#alertColorizeBundleRows').prop('disabled');
$('input#alertColorizeBundleColor').prop('disabled', !(isEnabled && isChecked));
// Alert on outgoing trades checkbox is connected to its colorize checkboxes
isChecked = $('input#alertOnOutgoing').prop('checked');
$('input#alertColorizeOutgoingRows').prop('disabled', !isChecked);
$('input#alertColorizeOutgoingColor').prop('disabled', !isChecked);
// Colorize outgoing rows checkbox is connected to the color picker
isChecked = $('input#alertColorizeOutgoingRows').prop('checked');
isEnabled = !$('input#alertColorizeOutgoingRows').prop('disabled');
$('input#alertColorizeOutgoingColor').prop('disabled', !(isEnabled && isChecked));
// The play alert sound checkbox is connected to the sound file input
isChecked = $('input#alertPlaySound').prop('checked');
$('input#alertSoundFile').prop('disabled', !isChecked);
// The card value filter checkbox is connected to the minimum card value input
isChecked = $('input#filterCardsByValue').prop('checked');
$('input#filterCardsMinValue').prop('disabled', !isChecked);
// The member filter checkbox is connected to the minimum member points input
isChecked = $('input#filterMembersByPoints').prop('checked');
$('input#filterMembersMinPoints').prop('disabled', !isChecked);
},
/* ===== TABLE PARSING FUNCTIONS ===== */
// Load the trade table data into manageable structures (tableData and memberData)
// This is usually called after loadTableData() completes
parseTradeTable: function () {
// Don't bother parsing the data if auto-match is turned off
if ( !$('input.niceToggle.intersect').prop('checked') ) {
this.debug(2, 'Skipping trade table parse, auto-match is off');
return;
}
this.debug(2, 'Parsing trade table data');
this.tableData = [];
this.cardData = {};
this.memberData = {};
// Parse all rows, hidden or not (scrolling may have added more entries)
var tableRows = $(this.tableRowStr);
var i;
var tradeID;
var curRow, curFields;
var cardSet, cardName, cardPts;
var memberID, memberName, memberPts;
var country;
// For each row in the trade table
for (i = 0; i < tableRows.length; i++) {
curRow = $(tableRows).eq(i);
curFields = $(curRow).find('td');
// Extract the relevant table fields
tradeID = $(curRow).attr('id');
cardSet = $(curFields).eq(0).find('div.hidden').text().trim();
cardName = $(curFields).eq(1).text().trim();
cardPts = parseInt( $(curFields).eq(2).text(), 10 );
// The member field can have multiple <a> elements, but the last one is always the profile link
// The other <a> elements are usually the membership level and upgrade link
// The past part of the profile URL is the member ID; it is unique, memberName isn't
memberID = $(curFields).eq(4).find('a').last().attr('href').split('/').pop();
memberName = $(curFields).eq(4).text().trim();
memberPts = parseInt( $(curFields).eq(5).text(), 10 );
// Pulling from curRow, not curFields because the country column position
// depends on membership level as rare-level users have an extra column
country = $(curRow).find('i.flag').attr('title').trim();
// Make sure that this row isn't a duplicate
if ( tradeID in this.cardData ) {
this.debug(3, 'Duplicate tradeID (' + tradeID + ') removed');
$(curRow).remove();
continue;
}
// Data per row
this.tableData.push({
tradeID: tradeID,
memberID: memberID,
memberName: memberName,
memberPts: memberPts,
country: country,
cardName: cardName,
cardPts: cardPts
});
// Data per card
this.cardData[tradeID] = {
cardSet: cardSet,
cardName: cardName,
cardPts: cardPts
};
// Data per member
if ( !(memberID in this.memberData) ) {
// Make a new entry
this.memberData[memberID] = {
memberName: memberName,
memberPts: memberPts,
country: country,
cardQty: 0,
tradeIDs: {},
totalCardPts: 0,
hasAlert: false,
hasBundleAlert: false,
hasOutgoingAlert: false
};
}
// Now that we're certain the entry exists, update the data
this.memberData[memberID].cardQty++;
this.memberData[memberID].totalCardPts += cardPts;
this.memberData[memberID].tradeIDs[tradeID] = cardPts;
}
},
// Loads the and parses the outgoing trade information
// into a manageable structure (outgoingTrades)
lastOutgoingLoad: 0,
loadOutgoingTrades: function (force) {
this.debug(2, 'Fetching outgoing trades');
// Skip if not forced and it's been less than 2 minutes since last run
if ( !force && Date.now() - this.lastOutgoingLoad < 2 * 60 * 1000 ) { return; }
this.events.outgoingLoadComplete = false;
this.lastOutgoingLoad = Date.now();
// Initiate an AJAX request to get the outgoing trades
// When it returns, parse the outgoing trades table then
// call reloadComplete() to parse/filter trades
$.get('/trades/active', function (data) {
this.debug(3, 'Got outgoing trades');
var i;
var tableRows = $(data).find('table.datatable tbody tr[id^="user_card"]:contains("Unshipped")');
var curRow, curFields;
var memberID, memberName;
var cardPts;
this.outgoingTrades = {};
// Gold membership adds columns to the Active Trades page, so we need to get our column index for the receiver manually
// We do this in two steps because the entire table doesn't exist if the user has no outgoing trades
// If the table doesn't exist, the 0th index is undefined; undefined.cellIndex is an error
var memberColumnIndex = $(data).find('table.datatable thead tr th:contains("Receiver")')[0];
if ( typeof memberColumnIndex !== 'undefined' ) {
memberColumnIndex = memberColumnIndex.cellIndex;
}
// For each row of unshipped trades
for (i = 0; i < tableRows.length; i++) {
curRow = $(tableRows).eq(i);
curFields = $(curRow).find('td');
cardPts = parseInt( $(curFields).eq(3).text(), 10 );
// Some member entries can become bugged and somehow lack a profile link
// We don't care why they're bugged, but trying to parse them would be dumb
if ( $(curFields).eq(memberColumnIndex).find('a.trader').length < 1 ) {
this.debug(0, 'Warning: bugged outgoing trade detected, html = ' + $(curFields).html().replace(/\s+/g, ' '));
this.debug(0, 'Table headings html = ' + $(data).find('table.datatable thead').html().replace(/\s+/g, ' '));
this.debug(0, 'Using memberColumnIndex of ' + memberColumnIndex);
continue;
}
memberID = $(curFields).eq(memberColumnIndex).find('a.trader').attr('href').split('/').pop();
// Thank you StackOverflow! http://stackoverflow.com/a/8851526/477563
memberName = $(curFields).eq(memberColumnIndex).find('a.trader')
.children().remove().end().text().trim();
if ( !this.outgoingTrades[memberID] ) {
this.outgoingTrades[memberID] = {
memberName: memberName,
cardQty: 1,
totalCardPts: cardPts
};
} else {
this.outgoingTrades[memberID].cardQty++;
this.outgoingTrades[memberID].totalCardPts += cardPts;
}
}
this.events.outgoingLoadComplete = true;
this.reloadComplete();
}.bind(this));
},
/* ===== ALERT/NOTIFICATION FUNCTIONS ===== */
clearAllNotes: function () {
$('li.noteItem:not(#defaultNote)').remove();
$('li#defaultNote').show();
},
getNotes: function () {
return $('li.noteItem');
},
addNote: function (alertText, alertClass) {
this.debug(4, 'Adding note: ' + alertText);
$('li#defaultNote').hide();
$('ul#noteList').append( $('<li class="noteItem">').html(alertText).addClass(alertClass) );
},
titleAlertTimeout: null,
setTitleAlert: function (msg, delay) {
if ( this.titleAlertTimeout ) { return; }
if ( typeof delay === 'undefined' ) { delay = 5000; }
this.origTitle = document.title;
document.title = msg;
this.titleAlertTimeout = setTimeout(this.removeTitleAlert.bind(this), delay);
},
removeTitleAlert: function () {
this.titleAlertTimeout = null;
document.title = this.origTitle;
},
hasPlayedSound: true,
playAlertSound: function () {
if ( this.alert.playSound && !this.hasPlayedSound ) {
$('audio#alertSound').trigger('play');
this.hasPlayedSound = true;
}
},
hasShownNotification: true,
showNotification: function(msg, timeout) {
if ( this.alert.showNotification && !this.hasShownNotification ) {
if ('Notification' in window && Notification.permission ) {
var note = new Notification(msg, { icon: 'https://pucatrade.com/favicon.ico' });
setTimeout(function() { note.close() }, timeout);
note.addEventListener('click', function() {
window.focus();
note.close();
});
}
this.hasShownNotification = true;
}
},
// Checks all pending trades for alerts based on user settings
prevAlerts: {},
isFirstAlertCheck: true,
checkForAlerts: function () {
this.debug(2, 'Checking for alerts');
var i;
var pendingAlerts = [];
var curAlert = {}; // { msg, style, value, memberID }
var newAlertQty = 0;
var memberID, memberName, memberPts;
var tradeIDs, firstTradeID, cardQty, totalCardPts, tradeValue;
var rowColor;
// First iterate the individual members by ID
for ( i in this.memberData ) {
if ( !this.memberData.hasOwnProperty(i) ) { continue; }
memberID = i;
memberName = this.memberData[i].memberName;
memberPts = this.memberData[i].memberPts;
tradeIDs = this.memberData[i].tradeIDs;
firstTradeID = Object.keys(tradeIDs).shift();
cardQty = this.memberData[i].cardQty;
totalCardPts = this.memberData[i].totalCardPts;
// If the total card value is under the alert threshold
// or the member can afford all cards they want, trust the total value
// Calling getBestBundle is expensive, so it should only be used sparingly
if ( totalCardPts < this.alert.bundleThreshold || totalCardPts < memberPts ) {
tradeValue = totalCardPts;
} else {
// It's possible that the member cannot afford all the cards they want
// Find the largest bundle of trades the member can actually afford
tradeValue = this.getBestBundle(tradeIDs, memberPts).value;
if ( tradeValue < this.alert.bundleThreshold ) {
this.debug(2, memberName + ' (' + memberID + ') cannot afford ' + this.alert.bundleThreshold);
}
}
curAlert = {
memberID: memberID,
style: (totalCardPts > memberPts ? 'text-warning' : ''),
value: tradeValue,
isNew: false
};
curAlert.isNew = false;
// Did we see this member last check?
if ( memberID in this.prevAlerts ) {
// Yes, but do they want anything new?
for ( tradeID in tradeIDs ) {
if ( !(tradeID in this.prevAlerts[memberID]) ) {
curAlert.isNew = true;
break;
}
}
} else {
// This member wasn't in our last alerts, that means they're new
curAlert.isNew = true;
}
var alertStar = (
( curAlert.isNew && !this.isFirstAlertCheck )
? '<abbr title="this alert is new or has added new cards">★</abbr>'
: ''
);
// Note: the last alert a member qualifies for takes priority
// Does this qualify as a bundle alert?
if ( this.alert.onBundle && tradeValue >= this.alert.bundleThreshold ) {
this.memberData[i].hasAlert = true;
this.memberData[i].hasBundleAlert = true;
// Queue the alert
// If the trade value is limited by the user's points, mark the entry
// If this trade is new/changed, mark the entry with a star (except on first load)
curAlert.msg =
'<span onclick="pucaPower.snapTo(\'#' + firstTradeID + '\');">'
+ '<strong>' + memberName + '</strong> '
+ 'wants ' + cardQty + ' cards for '
+ '<strong class="' + curAlert.style + '">' + totalCardPts + ' points</strong> '
+ alertStar
+ '</span>'
;
}
// Does this member have outgoing trades?
if ( this.alert.onOutgoing && memberID in this.outgoingTrades ) {
this.memberData[i].hasAlert = true;
this.memberData[i].hasOutgoingAlert = true;
// The value is increased by how much we're already sending them
curAlert.value += this.outgoingTrades[memberID].totalCardPts;
curAlert.msg =
'<span onclick="pucaPower.snapTo(\'#' + firstTradeID + '\');">'
+ '<strong>' + memberName + '</strong> '
+ 'has outgoing trades and wants ' + cardQty + ' more cards for '
+ '<strong>' + totalCardPts + ' points</strong> ' + alertStar
+ '</span>'
;
}
if ( typeof curAlert.msg !== 'undefined' ) {
pendingAlerts.push(curAlert);
newAlertQty += curAlert.isNew;
}
}
// Iterate the table elements and colorize alerts
for (i = 0; i < this.tableData.length; i++) {
memberID = this.tableData[i].memberID;
memberPts = this.memberData[memberID].memberPts;
totalCardPts = this.memberData[memberID].totalCardPts;
rowColor = null;
if ( this.memberData[memberID].hasAlert ) {
this.seenAlerts[ this.tableData[i].tradeID ] = this.tableData[i].cardPts;
// Colorize if part of a bundle
if ( this.alert.colorizeBundleRows && this.memberData[memberID].hasBundleAlert ) {
rowColor = this.alert.colorizeBundleColor;
}
// Colorize if has outgoing trades (will override bundle)
if ( this.alert.colorizeOutgoingRows && this.memberData[memberID].hasOutgoingAlert ) {
rowColor = this.alert.colorizeOutgoingColor;
}
// If we have a pending color, apply it
if ( rowColor !== null ) {
$('#'+ this.tableData[i].tradeID).find('td').css('background-color', rowColor);
}
// Put a mark next to the member's points if they can't afford all the cards they want
if ( memberPts < totalCardPts ) {
if ( !$('#'+ this.tableData[i].tradeID).data('hasPointWarning') ) {
$('#'+ this.tableData[i].tradeID).data('hasPointWarning', true);
$('#'+ this.tableData[i].tradeID).find('td.points').prepend('<i class="icon-warning-sign"></i> ');
$('#'+ this.tableData[i].tradeID).find('td.points').append(' <i class="icon-warning-sign"></i>');
}
}
}
}
if ( pendingAlerts.length > 0 ) {
if ( !this.alert.onNewOnly || (this.alert.onNewOnly && newAlertQty > 0) ) {
this.playAlertSound();
this.setTitleAlert(this.alert.titleText);
this.showNotification(this.alert.titleText, this.alert.notificationTimeout);
}
window._gaq.push(['pucaPowerGA._trackEvent', 'PucaPower', 'Alert']);
}
// Sort new alerts to the top (isNew descending), then alerts by value (value descending)
pendingAlerts.sort(function (a, b) { return (b.isNew - a.isNew) || (b.value - a.value); });
// Display the alerts, highest value first
// Update the prevAlert structure for next alert check
this.prevAlerts = {};
for (i = 0; i < pendingAlerts.length; i++) {
curAlert = pendingAlerts[i];
this.debug(0, $(curAlert.msg).text());
this.addNote(curAlert.msg);
this.prevAlerts[curAlert.memberID] = this.memberData[curAlert.memberID].tradeIDs;
}
this.debug(1, 'Found ' + pendingAlerts.length + ' alerts, ' + newAlertQty + ' new or expanded');
this.isFirstAlertCheck = false;
},
/* ===== MISC/UTILITY FUNCTIONS ===== */
donationRequest: function () {
// If a donation request already exists, don't make another
if ( $('li.donationRequest').length > 0 ) { return; }
var paypal = '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5GF3TD343BS4A">PayPal</a>';
var bitcoin = '<a href="https://www.coinbase.com/checkouts/630f3600438a42cce9fc9aba8b23f744">Bitcoin</a>';
var pucatrade = '<a href="https://pucatrade.com/profiles/show/59386">Puca Trade</a>';
if ( this.sentTrades > 0 ) {
this.addNote('Puca Power has helped you send <strong>' + this.sentTrades + ' trades</strong> this session.');
}
// The sum of all unique alerted trades
var alertPoints = Object.keys(this.seenAlerts).reduce(function (sum, cur) { return sum + this.seenAlerts[cur]; }.bind(this), 0);
if ( alertPoints > 0 ) {
this.addNote('Puca Power has alerted you to <strong>' + alertPoints + ' points</strong> in trades this session.');
}
this.addNote(
'<strong>Do you like Puca Power?</strong> <i class="icon-heart"></i> '
+ 'Consider donating via ' + paypal + ', ' + bitcoin + ', or ' + pucatrade + '!',
'donationRequest'
);
},
news: function () {
// Only display news for up to two weeks
if ( Date.now() - new Date(this.updateDate).getTime() <= 14 * 24 * 60 * 60 * 1000 ) {
this.addNote('Version ' + this.version + ' released on ' + this.updateDate + '! See the change log for full details.', 'text-success');
}
},
// Returns the maximal combination of trades (a bundle) that doesn't exceed memberPts
// If targetValue is specified, return the first bundle that meets or exceeds it
getBestBundle: function (trades, memberPts, targetValue) {
// { combinedValue: { itemID: value, ... }, ... }
// Indexing by the combined trade value helps greatly reduce the search space
// Because we only care about the maximum bundle value, we don't care about
// two different bundles of trades that yield the same total value
// i.e. {A: 10, B: 20} is just as good as {C: 15, D: 15}, so only track one
// The only preference we make is that fewer trades is better
var bundles = { 0: {} };
var bestBundleValue = 0;
// Users with massive numbers of small trades can potentially cause this function to run long
// Set a resonable timeout threshold (in milliseconds) and return our best answer if we run out of time
var maxRuntime = 100;
var startTime = Date.now();
// Iterate trades from largest to smallest by value
// This causes the most rejects early on for going over a member's total points, culling
// bad entries much faster than ordering by smallest to largest
// This also gets our best estimate as large as possible early on in case we have to bail
var sortedTradeIDs = Object.keys(trades).sort(function(a, b) { return trades[b] - trades[a]; });
var tradeQty = sortedTradeIDs.length;
// For each trade the member wants...
for ( var tradeNum = 0; tradeNum < tradeQty; tradeNum++ ) {
if ( Date.now() - startTime > maxRuntime ) { break; }
var curTradeID = trades[ sortedTradeIDs[tradeNum] ];
var curTradeValue = parseInt(trades[curTradeID], 10);
// Attempt to add it to all possible trade bundles
for ( var bundleValue in bundles ) {
if ( Date.now() - startTime > maxRuntime ) { break; }
// Skip any bundles that already contain this trade
// This should never happen as we only iterate trades once but better safe than infinite
if ( curTradeID in bundles[bundleValue] ) { continue; }
// If the new bundle value exceeds the member's points, skip it
var newValue = parseInt(bundleValue, 10) + curTradeValue;
if ( newValue > memberPts ) { continue; }
// Copy and extend the bundle with our current trade included
var newBundle = $.extend({}, bundles[bundleValue]);
newBundle[curTradeID] = curTradeValue;
// Check if a bundle of this value already exists
if ( newValue in bundles ) {
// A bundle of this value exists
var newTradeQty = Object.keys( newBundle ).length;
var oldTradeQty = Object.keys( bundles[newValue] ).length;
// Only replace it if this bundle has fewer trades
if ( newTradeQty < oldTradeQty ) {
bundles[newValue] = newBundle;
bestBundleValue = newValue;
}
} else {
// This is a new bundle value
bundles[newValue] = newBundle;
if ( newValue > bestBundleValue ) {
bestBundleValue = newValue;
}
}
}
// Break early if targetValue is set and we currently exceed it
if ( typeof targetValue !== 'undefined' && bestBundleValue >= targetValue ) { break; }
}
// If we stopped because we went over time, the user may like to know about it
if ( Date.now() - startTime > maxRuntime ) {
this.debug(0, 'Bailed from bundle value calculation for taking too long, user had ' + tradeQty + ' trades');
}
return {value: bestBundleValue, tradeIDs: bundles[bestBundleValue]};
},
// Enables the auto-match feature of the trade table
// This is required if we want any of the alerts to be valid
enableAutoMatch: function () {
if ( !$('input.niceToggle.intersect').prop('checked') ) {
this.debug(2, 'Enabling auto-match');
$('input.niceToggle.intersect').prop('checked', true);
$('label.niceToggle.intersect').addClass('on');
// lastVars may or may not be defined yet
window.lastVars = $.extend({ intersect: true }, window.lastVars);
}
},
// Snaps an element/selector into view
// If no element/selector is specified, snap to top of current page
snapTo: function (selector) {
if ( typeof selector === 'undefined' ) {
// No selector? Default to top of page
selector = 'html';
} else {
// Push browser history for current selector
// This allows us to snap to top when we pop this state
history.pushState({snapTo: selector}, '');
}
try {
// Snap the thing into view, catching an exception if thing doesn't exist
$('html, body').animate({
scrollTop: $(selector).first().offset().top
}, 0);
} catch (e) {
this.debug(0, 'Failed to snap ' + selector + ' into view: ' + e);
}
},
/* ===== FILTER FUNCTIONS ===== */
filterTrades: function () {
this.debug(2, 'Filtering trades');
var i;
var filterQty = 0;
var memberID, memberName, memberPts, hasAlert;
var cardName, cardPts;
var matchedFilter;
for (i = 0; i < this.tableData.length; i++) {
memberID = this.tableData[i].memberID;
memberName = this.tableData[i].memberName;
memberPts = this.memberData[memberID].memberPts;
hasAlert = this.memberData[memberID].hasAlert;
cardName = this.tableData[i].cardName;
cardPts = this.tableData[i].cardPts;
matchedFilter = false;
// Skip entries that have pending alerts
if ( hasAlert ) { continue; }
// Filter cards by value
if ( this.filter.cardsByValue && cardPts < this.filter.cardsMinValue ) {
this.debug(5, 'Filtering trade: ' + cardName + ' (' + cardPts + ')');
matchedFilter = true;
// Filter members by points
} else if ( this.filter.membersByPoints && memberPts < this.filter.membersMinPoints ) {
this.debug(4, 'Filtering member: ' + memberName + ' (' + memberPts + ')');
matchedFilter = true;
}
// If we found at least one filter criteria, remove the trade offer
if ( matchedFilter ) {
filterQty++;
$('#'+ this.tableData[i].tradeID).remove();
}
}
if ( filterQty > 0 ) {
this.addNote('Filtered ' + filterQty + ' trades', 'muted');
}
// Update the "Total" label on the table
$('p#total').text('Total: ' + (this.tableData.length - filterQty));