forked from andyjennings314/IMATTC
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathIMATTC.user.js
982 lines (907 loc) · 53.8 KB
/
IMATTC.user.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
// ==UserScript==
// @name IMATTC
// @version 1.8.0
// @description A usability overhaul for the Ingress Mission Authoring Tool
// @author @Chyld314
// @match https://mission-author-dot-betaspike.appspot.com/
// @match https://mission-author-dot-betaspike.appspot.com/edit*
// @match http://missions.ingress.com/
// @match http://missions.ingress.com/edit*
// @match https://missions.ingress.com/
// @match https://missions.ingress.com/edit*
// @require https://code.jquery.com/ui/1.10.4/jquery-ui.min.js
// @grant none
// @downloadURL https://github.com/andyjennings314/IMATTC/raw/master/IMATTC.user.js
// @updateURL https://github.com/andyjennings314/IMATTC/raw/master/IMATTC.user.js
// ==/UserScript==
if (!$) {
var insertJq = document.createElement('script');
insertJq.setAttribute("type", "text/javascript");
insertJq.setAttribute("src", "https://code.jquery.com/jquery-1.12.4.min.js");
document.getElementsByTagName("head")[0].appendChild(insertJq);
}
$(function() {
'use strict';
//Latest version of Bootstrap, and correct version of jQuery
$("link[href='vendor/bootstrap/css/bootstrap.css']").attr("href", "https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css");
//$('body').append('<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>');
// Modify time conversion variables to ones with actual granularity
TimeConversionConstants.MINUTE_GRANULARITY_MINUTES = 1;
TimeConversionConstants.HOUR_GRANULARITY_MINUTES = 15;
TimeConversionConstants.DAY_GRANULARITY_HOURS = 12;
//Build CSS rules
var newCssRules = "<style>"
+ ".navbar-my-missions {cursor: pointer;}"
+ ".list > .bordered-panel {padding: 15px;}"
+ ".list .missions-list,.missions-list .panel-body .row {display: flex;flex-wrap: wrap;}"
+ ".list .create-mission-button {margin: 0 5px;float: none!important;display: inline-block;}"
+ ".missions-list, .name-view .bordered-panel, .type-view .bordered-panel {opacity: 0; transition: opacity 0.5s}"
+ ".missions-list.ready, .name-view .bordered-panel.ready, .type-view .bordered-panel.ready {opacity:1}"
+ ".missions-list .mission {border-width: 2px; margin: 10px 0 0; position: relative; padding: 5px; display: block;}"
+ ".list .mission .action-button {width: 100%; min-width: initial; max-width: initial;}"
+ ".mission-header-container {display: flex; align-items: stretch;}"
+ ".mission-header-container div:nth-of-type(1){padding-right: 5px; width: 60px}"
+ ".mission-header-container div:nth-of-type(2){width: calc(100% - 115px)}"
+ ".mission-header-container div:nth-of-type(3){padding-left: 5px; width: 45px}"
+ ".button, button {background-image: none;}"
+ ".mission .name.glyphicon {font-size: 40px;}"
+ ".mission .name:not(.glyphicon) {text-align: center; display: block;}"
+ ".mission table {margin: 5px 0 10px;}"
+ ".missions-list .panel-default { border-color: #5afbea; background-color: black; border-radius: 0;}"
+ ".missions-list .panel-default>.panel-heading {color: #5afbea; background: #1f4549; border-radius: 0;}"
+ ".missions-list .panel-default>.panel-heading a:hover {color: #5afbea;}"
+ ".missions-list .panel-default>.panel-heading+.panel-collapse>.panel-body {border-top-color: black; padding-top: 0;}"
+ ".missions-list .panel-heading a:after { font-family: 'Glyphicons Halflings'; content: '\\e114'; float: right; color: 5afbea; position: relative; left: 10px; }"
+ ".missions-list .panel-heading h4.collapsed a:after {content: '\\e080'; }"
+ ".ui-state-highlight { border: 2px solid #5afbea; background: #1f4549; margin-top: 10px;display: block;padding: 0 15px; min-height: 100px;}"
+ ".modal {color: black;}"
+ ".banner-preview .modal-body {background-color: #222;}"
+ ".banner-preview .row {display: flex; flex-direction: row-reverse; flex-wrap:wrap-reverse!important}"
+ ".banner-preview img {border-radius: 50%;border: 3px solid goldenrod;}"
+ ".banner-preview .col-xs-2 {padding-bottom: 15px;}";
newCssRules += ".mission-list-item-published {background-image: none; background: #001a00; border-color: darkgreen;color: lightgreen;}"
+ ".list .mission .mission-title-published {color: lightgreen;}"
+ ".mission-list-item-published .table-bordered * {border-color: lightgreen;}"
+ ".mission-list-item-published .button {color: lightgreen; border-color: lightgreen; background-color: #004d00;}"
+ ".mission-list-item-published .button:hover {background-color: #003300;}"
+ ".mission-list-item-published .button .caret {border-bottom-color: lightgreen;}";
newCssRules += ".mission-list-item-draft {background-image: none; background-color: #170703; border-color: #a42e12;color: #f7ba5f;}"
+ ".list .mission .mission-title-draft {color: #f7ba5f;}"
+ ".mission-list-item-draft .table-bordered * {border-color: #f7ba5f;}"
+ ".mission-list-item-draft .button {color: #f7ba5f; border-color: #f7ba5f; background-color: #8a280f;}"
+ ".mission-list-item-draft .button:hover {background-color: #73210d;}"
+ ".mission-list-item-draft .button .caret {border-bottom-color: #f7ba5f;}";
newCssRules += ".mission-list-item-draft_of_published_mission {background-image: none; background-color: #1a1a00; border-color: olive;color: greenyellow;}"
+ ".list .mission .mission-title-draft_of_published_mission {color: greenyellow;}"
+ ".mission-list-item-draft_of_published_mission .table-bordered * {border-color: greenyellow;}"
+ ".mission-list-item-draft_of_published_mission .button {color: greenyellow; border-color: greenyellow; background-color: #666600;}"
+ ".mission-list-item-draft_of_published_mission .button:hover {background-color: #4d4d00;}"
+ ".mission-list-item-draft_of_published_mission .button .caret {border-bottom-color: greenyellow;}";
newCssRules += ".mission-list-item-submitted {background-image: none; background-color: #181201; border-color: darkgoldenrod;color: gold;}"
+ ".list .mission .mission-title-submitted {color: gold;}"
+ ".mission-list-item-submitted .table-bordered * {border-color: gold;}"
+ ".mission-list-item-submitted .button {color: gold; border-color: gold; background-color: #916a08;}"
+ ".mission-list-item-submitted .button:hover {background-color: #785807;}"
+ ".mission-list-item-submitted .button .caret {border-bottom-color: gold;}";
newCssRules += ".mission-list-item-disabled {background-image: none; background-color: #0d0d0d; border-color: #6b6b6b; color: red;}"
+ ".list .mission .mission-title-disabled {color: red;}"
+ ".mission-list-item-disabled .table-bordered * {border-color: red;}"
+ ".mission-list-item-disabled .button {color: red; border-color: red; background-color: #595959;}"
+ ".mission-list-item-disabled .button:hover {background-color: #4d4d4d;}"
+ ".mission-list-item-disabled .button .caret {border-bottom-color: red;}";
newCssRules += ".mission-list-item-submitted_and_published {background-image: none; background-color: #0f1405; border-color: olivedrab;color: springgreen;}"
+ ".list .mission .mission-title-submitted_and_published {color: springgreen;}"
+ ".mission-list-item-submitted_and_published .table-bordered * {border-color: springgreen;}"
+ ".mission-list-item-submitted_and_published .button {color: springgreen; border-color: springgreen; background-color: #5c7a1f;}"
+ ".mission-list-item-submitted_and_published .button:hover {background-color: #4d6619;}"
+ ".mission-list-item-submitted_and_published .button .caret {border-bottom-color: springgreen;}";
newCssRules += ".dropup {position: relative;}"
+ ".dropup .dropdown-menu {top: initial; bottom: 30px; left: 0; right: 0; text-align: center;}"
+ ".dropdown-menu > li > a {cursor: pointer;}"
+ ".editor .view {width: initial;height: initial;text-align: center;margin: 0;}"
+ ".editor .type-view, .editor .name-view {width: 100%;}"
+ ".pagination>li>a {background: #0b0c0d;border-color: #5afbea;color: #5afbea; font-size: 18px;}"
+ ".pagination>li>a:hover {background: #2b2c2d;border-color: #5afbea;color: #5afbea;}"
+ ".pagination>li>a[disabled] {color: #ACAFAF;}"
+ ".pagination>li>a[disabled]:hover {cursor: default; background: #0b0c0d;border-color: #5afbea;color: #ACAFAF;}"
+ ".pagination>.active>a, .pagination>.active>a:hover {background-color: #5afbea;border-color: #5afbea;color: #0b0c0d;}"
+ ".type-view .btn.focus, .type-view .btn:focus, .type-view .btn:hover {color: unset;}"
+ ".type-view .btn.active.focus, .type-view .btn.active:focus, .type-view .btn.active:hover {color: #ebbc4a;}"
+ ".type-view .bordered-panel p {font-size: 20px;}"
+ ".stopthat {color: red; font-weight: bold;}"
+ "input.form-control, textarea.form-control {border: 1px solid #5afbea; background: none; border-radius: 0; color: white;}"
+ ".upload-logo .input-row .upload-label {display: block;padding: 0 0 10px;}"
+ ".upload-logo .input-row {display: block;}"
+ ".upload-logo .input-row .upload-logo-cell, .upload-logo .input-row .clear-logo-button {display: inline-block;padding: 0; max-width: 50%;}"
+ ".editor .waypoints-view .waypoints .waypoint.unselected {background-color: #000;}"
+ ".editor .waypoints-view .waypoints .waypoint .number {cursor: move;}"
+ ".preview-mission .body-panel .panel-container .map {height: unset;}"
+ ".preview-mission .body-panel .panel-container .category-dropdown {margin-top: 20px;}"
+ ".preview-mission .mission-header {margin: 0; width: 65%; float: left;)}"
+ ".preview-mission .mission-stats, .preview-mission .mission-description {max-width: 35%;float: right; display: inline-block;}"
+ "#previewMissionModel .loading-screen { top: 0; right: 0; position: relative; height: 40px;}"
+ "#previewMissionModel .loading.spin { position: fixed; left: 50%; top: 80px; }"
+ "</style>";
$("head").append(newCssRules);
});
function init() {
//
const w = typeof unsafeWindow === 'undefined' ? window : unsafeWindow;
let tryNumber = 15;
const initWatcher = setInterval(() => {
if (tryNumber === 0) {
clearInterval(initWatcher);
alert("IMATTC initialisation failed, please refresh the page");
}
if (w.angular) {
let err = false;
try {
initAngular();
} catch (error) {
clearInterval(initWatcher);
err = error;
console.log(error);
}
if (!err) {
try {
clearInterval(initWatcher);
pageChange()
} catch (error) {
console.log(error);
}
}
}
tryNumber--;
}, 1000);
function initAngular() {
const el = w.document.querySelector("*[ng-app]");
w.$app = w.angular.element(el);
w.$injector = w.$app.injector();
w.$rootScope = w.$app.scope();
w.$filter = w.$app.injector().get('$filter');
w.$compile = w.$app.injector().get('$compile');
w.$location = w.$app.injector().get('$location');
w.$timeout = w.$app.injector().get('$timeout');
w.$q = w.$app.injector().get('$q');
w.$http = w.$app.injector().get('$http');
w.WireUtil = w.$app.injector().get('WireUtil');
w.Api = w.$app.injector().get('Api');
w.$rootScope.$on('$routeChangeStart', function(next, last) {
setTimeout(() => {
pageChange()
}, 500);
});
w.$scope = element => w.angular.element(element).scope();
}
function pageChange() {
var loadingElement = $('div.loading-screen');
var loadingScope = w.$scope(loadingElement);
if (!loadingScope.hasPendingRequests()) {
whenItsLoaded()
} else {
setTimeout(() => {
pageChange();
}, 250);
}
}
function whenItsLoaded() {
var missionScope = w.$scope($('div.list'));
if (missionScope) {
missionListSetup(missionScope);
} else {
var editScope = w.$scope($('div.editor'));
if (editScope) {
missionEditSetup(editScope);
} else {
var previewScope = w.$scope($('div.preview-mission'));
if (previewScope){
missionPreviewSetup(previewScope);
}
}
}
}
function missionPreviewSetup(previewScope) {
//$('body').css('margin-top','0');
};
function missionEditSetup(editScope) {
var editStep = editScope.mission.ui.view;
//overwrite submitMission function to inject categorisation
editScope.submitMission = function() {
var b = WireUtil.convertMissionLocalToWire(editScope.mission)
, d = angular.copy(b);
d.submit = true;
editScope.saving = true;
editScope.savingFailed = false;
editScope.saved = false;
w.$http.post(w.Api.SAVE_MISSION, d).success(function(d) {
editScope.saving = false;
editScope.saved = true;
editScope.savedWireMission = b;
//if a category is selected, push the mission to that category
if (editScope.selectedCategoryID) {
editScope.categoryContent[editScope.selectedCategoryID].missions.push(editScope.savedWireMission.mission_guid);
editScope.categoryContent[editScope.selectedCategoryID].collapse = false;
editScope.selectedCategoryID = null;
w.localStorage.setItem('allCategories', JSON.stringify(editScope.categoryContent));
}
w.$location.url("/")
}).error(function(b) {
editScope.saving = false;
editScope.savingFailed = true
})
}
editScope.isBreadcrumbDisabled = function(step){
var validGoTo = false;
switch (step) {
case editScope.EditorScreenViews.TYPE:
case editScope.EditorScreenViews.NAME:
validGoTo = editScope.isTypeValid();
break;
case editScope.EditorScreenViews.WAYPOINTS:
validGoTo = editScope.isTypeValid() && !editScope.detailsErrors.hasErrors;
break;
case editScope.EditorScreenViews.PREVIEW:
validGoTo = editScope.isTypeValid() && !editScope.detailsErrors.hasErrors && !editScope.waypointErrors.hasErrors
}
return !validGoTo;
}
//Replace breadcrumb with something a bit clearer
$(".view").empty();
var newBreadcrumb = "<ul class='pagination'>"
+ "<li" + (editScope.IsViewActive(editScope.EditorScreenViews.TYPE) ? " class='active'" : "")
+ "><a role='button' ng-disabled='isBreadcrumbDisabled(EditorScreenViews.TYPE)' ng-click='bulletSetView(EditorScreenViews.TYPE)'>Mission Type</a></li>"
+ "<li" + (editScope.IsViewActive(editScope.EditorScreenViews.NAME) ? " class='active'" : "")
+ "><a role='button' ng-disabled='isBreadcrumbDisabled(EditorScreenViews.NAME)' ng-click='bulletSetView(EditorScreenViews.NAME)'>Mission Details</a></li>"
+ "<li" + (editScope.IsViewActive(editScope.EditorScreenViews.WAYPOINTS) ? " class='active'" : "")
+ "><a role='button' ng-disabled='isBreadcrumbDisabled(EditorScreenViews.WAYPOINTS)' ng-click='bulletSetView(EditorScreenViews.WAYPOINTS)'>Waypoints</a></li>"
+ "<li" + (editScope.IsViewActive(editScope.EditorScreenViews.PREVIEW) ? " class='active'" : "")
+ "><a role='button' ng-disabled='isBreadcrumbDisabled(EditorScreenViews.PREVIEW)' ng-click='bulletSetView(EditorScreenViews.PREVIEW)'>Preview</a></li>"
+ "</ul>";
var compiledBread = $compile(newBreadcrumb)(editScope);
$(".view").append(compiledBread);
//view specific fixes
var editCode, editTarget, compiledContent;
switch (editStep){
case editScope.EditorScreenViews.TYPE:
editTarget = $(".type-view .bordered-panel");
//Overhauled UI on Mission Type page, including more editorialising on non-linear missions in banners
$(".type-view .bordered-panel").empty().addClass('ready');
editCode = "<div class='btn-group btn-group-justified'>"
+ "<div class='btn-group'><button class='btn btn-lg' ng-click='mission.definition._sequential = true; mission.definition._hidden = false' ng-class='{active: mission.definition._sequential && !mission.definition._hidden}'><i class='glyphicon glyphicon-arrow-right'></i> SEQUENTIAL</button></div>"
+ "<div class='btn-group'><button class='btn btn-lg' ng-click='mission.definition._sequential = true; mission.definition._hidden = true' ng-class='{active: mission.definition._sequential && mission.definition._hidden}'><i class='glyphicon glyphicon-eye-close'></i> HIDDEN SEQUENTIAL</button></div>"
+ "<div class='btn-group'><button class='btn btn-lg' ng-click='mission.definition._sequential = false; mission.definition._hidden = false' ng-class='{active: !mission.definition._sequential}'><i class='glyphicon glyphicon-random'></i> ANY ORDER</button></div>"
+ "</div><br />"
+ "<p ng-show='mission.definition._sequential && !mission.definition._hidden'>Agents visit portals and field trip markers in a set order.<br/><br/>Best suited to missions in a banner series, or one-offs with a pre-determined route.</p>"
+ "<p ng-show='mission.definition._sequential && mission.definition._hidden'>Agents visit portals and field trip markers in a set order, but the location of every waypoint beyond the first is hidden, meaning players rely on clues in the waypoint text.<br/><br/>Good for more puzzle-based missions, but please ensure you provide adequate clues for agents to find all the waypoints.</p>"
+ "<p ng-show='!mission.definition._sequential'>Agents visit portals and field trip markers in any order. Excellent for one-off missions where a specific route isn't required, but terrible for missions in banner serieses.<br /><br /><span class='stopthat'>It is strongly advised that if you are making missions for a banner, you set them as Sequential missions - your rating on IngressMosaik will thank you! </span></p>";
break;
case editScope.EditorScreenViews.NAME:
editTarget = $(".name-view .bordered-panel");
//Overhauled UI on Mission Name/Image pages
$(".name-view .bordered-panel").empty().addClass('ready');
editCode = "<div class='row'><div class='col-sm-8 form-horizontal'><div class='form-group'>"
+ "<label for='missionName' class='col-sm-2 control-label'>Mission Name</label>"
+ "<div class='col-sm-10'><input type='text' id='missionName' ng-model='mission.definition.name' class='form-control' placeholder='Add mission name' ng-class='{\"invalid\": !mission.definition.name}' maxlength='" + editScope.MissionRules.MAX_MISSION_NAME_LENGTH + "'>"
+ "</div></div><div class='form-group'>"
+ "<label for='missionDesc' class='col-sm-2 control-label'>Mission Description</label>"
+ "<div class='col-sm-10'><textarea id='missionDesc' class='form-control' rows='4' ng-model='mission.definition.description' placeholder='Add mission description' ng-class='{\"invalid\": !mission.definition.description}' maxlength='" + editScope.MissionRules.MAX_MISSION_DESCRIPTION_LENGTH + "'></textarea>"
+ "</div></div></div><div class='col-sm-4'"
+ "<div mission-logo-upload max-size='{{LogoParams.MAX_SIZE_BYTES}}' success='logoUploadSuccess' error='logoUploadFailure' pre-post='ensureMissionHasGuid' accept='image/*' type-restriction='image/(gif|jpeg|jpg|png)' mission='mission'></div>"
+ "</div></div>";
break;
case editScope.EditorScreenViews.WAYPOINTS:
//Adding drag-and-drop mission reordering
//First, watch whether the user can see the list of waypoints
editScope.$watch('shouldShowWaypointList()', function() {
//if so, wait half a second and apply the JQueryUI sortable parameter to the list thereof
if (editScope.shouldShowWaypointList()){
setTimeout(() => {
//checks start position on start, end position on end, and sends them to the native change position function
$('#waypoints').sortable({
handle: '.number',
axis: 'y',
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
update: function (event, ui) {
var start_pos = ui.item.data('start_pos');
var end_pos = ui.item.index();
editScope.$apply(function(){
editScope.changeWaypointPosition(start_pos, end_pos);
});
editScope.mission.definition.waypoints.forEach(function(waypoint){
editScope.setSelectedWaypoint(waypoint);
});
editScope.setSelectedWaypoint(editScope.mission.definition.waypoints[end_pos]);
}
});
}, 500);
}
});
break;
case editScope.EditorScreenViews.PREVIEW:
//If there are user generated categories, add a dropdown to add the new mission to one
editScope.categoryContent = JSON.parse(w.localStorage.getItem('allCategories')) || [];
if (editScope.categoryContent.length > 0 && editScope.mission.mission_guid){
var showCategory = true;
editScope.categoryContent.forEach(function(category){
for (var i = 0; i < category.missions.length; i++){
if (category.missions[i] == editScope.mission.mission_guid){
showCategory = false;
break;
}
}
})
if (showCategory){
editScope.selectedCategoryID = null;
editTarget = $(".body-panel > .panel-container");
editCode = "<div class='category-dropdown'>"
+ "<select class='form-control' ng-model='selectedCategoryID'>"
+ "<option value='null'>OPTIONAL: Select a category to add this mission to</option>";
for (var i = 0; i < editScope.categoryContent.length; i++) {
editCode += "<option value='" + i + "'>" + editScope.categoryContent[i].name + "</option>";
}
editCode += "</select></div>";
}
}
break;
}
if (editCode){
compiledContent = $compile(editCode)(editScope);
editTarget.append(compiledContent);
}
//Runs pageChange() function when changing between Edit states
editScope.setView = function(b) {
editScope.pendingSave && (w.$timeout.cancel(editScope.pendingSave), editScope.pendingSave = null);
editScope.save(b);
setTimeout(() => {
pageChange();
}, 500);
}
}
function missionListSetup(missionScope) {
missionScope.getFullMissionData = function(missions){
var dfd = w.$q.defer();
var missionPromises = [];
angular.forEach(missions, function(mission) {
if (mission.missionListState != "DRAFT" && mission.missionListState != "SUBMITTED"){
var mId = mission.mission_guid;
missionPromises.push($http.post(window.origin + "/api/author/getMissionForProfile", {mission_guid: mId}));
} else {
var mId = mission.draft_mission_id || mission.submitted_mission_id;
missionPromises.push($http.post(window.origin + "/api/author/getMission", {mission_id: mId}));
}
});
w.$q.all(missionPromises).then(function(results) {
var missionData = [];
for (var i = 0; i < results.length; i++){
if (results[i] !== undefined){
var f = WireUtil.convertMissionWireToLocal(results[i].data.mission, results[i].data.pois);
missionData.push(f.definition);
} else {missionData.push(null)}
}
dfd.resolve(missionData);
},
function(data, status) {
console.error('error: ', status, data);
}
)
return dfd.promise;
}
missionScope.categoryContent = [];
missionScope.categorisedMissions = [];
missionScope.uncategorisedMissions = [];
missionScope.uncategorisedSort = 'initial';
missionScope.missions = w.$filter("orderBy")(missionScope.missions, 'definition.name');
missionScope.loadingPreview = false;
missionScope.unsortedCollapse = {collapse: w.localStorage.getItem('unsortedCollapse') || true};
//handling for legacy data format
if (!!w.localStorage.getItem('categoryNames')){
let oldegoriesLength = parseInt(w.localStorage.getItem('categoriesLength')) || 0,
categoryNames = w.localStorage.getItem('categoryNames') ? w.localStorage.getItem('categoryNames').split(',') : [],
thisCategory;
//create categories in new format
for (var i= 0; i < oldegoriesLength; i++){
thisCategory = {
id: i,
name: categoryNames[i],
missions: w.localStorage.getItem('categoryContent' + i) ? w.localStorage.getItem('categoryContent' + i).split(',') : [],
collapse: true,
sortCriteria: 'initial'
};
missionScope.categoryContent.push(thisCategory);
w.localStorage.removeItem('categoryContent' + i);
}
w.localStorage.setItem('allCategories', JSON.stringify(missionScope.categoryContent));
//now tidy up the legacy data
w.localStorage.removeItem('categoryNames');
w.localStorage.removeItem('categoriesLength');
}
//get data for all categories
missionScope.categoryContent = JSON.parse(w.localStorage.getItem('allCategories')) || [];
missionScope.selectedCategoryMissionId = null;
//Add position in initial array
for (var i = 0; i < missionScope.missions.length; i++) {
missionScope.missions[i].position = i;
}
//function to calculate distances between two sets of coordinates taken from geodatasource.com
missionScope.distance = function(lat1, lon1, lat2, lon2, unit) {
if ((lat1 == lat2) && (lon1 == lon2)) {
return 0;
}
else {
var radlat1 = Math.PI * lat1/180;
var radlat2 = Math.PI * lat2/180;
var theta = lon1-lon2;
var radtheta = Math.PI * theta/180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = dist * 180/Math.PI;
dist = dist * 60 * 1.1515;
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist;
}
}
missionScope.previewMission = function(guid) {
$('#previewMissionModel .modal-body .notloading').empty();
missionScope.loadingPreview = true;
var mission = w.$filter('filter')(missionScope.missions, {mission_guid: guid})[0];
if (mission){
missionScope.getFullMissionData([mission]).then(function(data){
mission.definition = data[0];
//calculate approx. mission length
var distance = 0;
for (var i = 1; i < mission.definition.waypoints.length; i++){
distance += missionScope.distance(
mission.definition.waypoints[i-1]._poi.location.latitude,
mission.definition.waypoints[i-1]._poi.location.longitude,
mission.definition.waypoints[i]._poi.location.latitude,
mission.definition.waypoints[i]._poi.location.longitude,
"K")
}
missionScope.loadingPreview = false;
w.$injector.invoke(function($compile) {
var modalContent = "<div preview-mission mission='missions["+mission.position+"]' mission-preview-state='\""+MissionPreviewStates.PROFILE+"\"'></div>";
var compiledContent = $compile(modalContent)(missionScope);
// Put the output of the compilation in to the page using jQuery
$('#previewMissionModel .modal-body .notloading').append(compiledContent);
if (distance < 1){
distance = (Math.floor(distance * 100000) / 100) + "m";
} else {
distance = (Math.floor(distance * 100) / 100) + "km";
}
setTimeout(function(){$('.mission-stats-row').append('<div class="mission-stats-item"><span class="stats-value">'+distance+'</span></div>');}, 10);
})
})
}
}
missionScope.previewBanner = function(category) {
$('#previewMissionModel .modal-body .notloading').empty();
missionScope.loadingPreview = true;
missionScope.getFullMissionData(missionScope.categorisedMissions[category]).then(function(data){
missionScope.banner = {
definition: {
name: missionScope.categoryContent[category].name,
author_nickname: data[0].author_nickname,
description: data[0].description,
_sequential: data[0]._sequential,
logo_url: data[0].logo_url,
waypoints: []
},
stats: {
num_completed: missionScope.categorisedMissions[category][data.length -1].stats ? missionScope.categorisedMissions[category][data.length -1].stats.num_completed : 0,
rating: 0,
median_completion_time: 0
},
};
for (var i = 0; i < missionScope.categorisedMissions[category].length; i++){
missionScope.banner.stats.rating += missionScope.categorisedMissions[category][i].stats ? missionScope.categorisedMissions[category][i].stats.rating : 0;
missionScope.banner.stats.median_completion_time += missionScope.categorisedMissions[category][i].stats ? missionScope.categorisedMissions[category][i].stats.median_completion_time : 0;
data[i].waypoints.forEach(function(wp){
missionScope.banner.definition.waypoints.push(wp)
})
}
missionScope.banner.stats.rating = Math.round(missionScope.banner.stats.rating / data.length);
//calculate approx. banner length
var distance = 0;
for (var j = 1; j < missionScope.banner.definition.waypoints.length; j++){
distance += missionScope.distance(
missionScope.banner.definition.waypoints[j-1]._poi.location.latitude,
missionScope.banner.definition.waypoints[j-1]._poi.location.longitude,
missionScope.banner.definition.waypoints[j]._poi.location.latitude,
missionScope.banner.definition.waypoints[j]._poi.location.longitude,
"K")
}
missionScope.loadingPreview = false;
w.$injector.invoke(function($compile) {
var modalContent = "<div preview-mission mission='banner' mission-preview-state='\""+MissionPreviewStates.PROFILE+"\"'></div>";
var compiledContent = $compile(modalContent)(missionScope);
// Put the output of the compilation in to the page using jQuery
$('#previewMissionModel .modal-body .notloading').append(compiledContent);
if (distance < 1){
distance = (Math.floor(distance * 100000) / 100) + "m";
} else {
distance = (Math.floor(distance * 100) / 100) + "km";
}
setTimeout(function(){$('.mission-stats-row').append('<div class="mission-stats-item"><span class="stats-value">'+distance+'</span></div>');}, 10);
})
})
}
missionScope.selectACategory = function(mission) {
missionScope.selectedCategoryMissionId = mission.mission_guid;
$('#addCateModel .modal-title').text('Add \"' + mission.definition.name + '\" to...');
}
missionScope.addToCategory = function() {
$(".modal-backdrop.fade").remove();
$("body").removeClass("modal-open");
var categoryID = missionScope.selectedCategoryID;
missionScope.categoryContent[categoryID].missions.push(missionScope.selectedCategoryMissionId);
missionScope.categoryContent[categoryID].collapse = false;
missionScope.selectedCategoryMissionId = null;
missionScope.selectedCategoryID = null;
w.localStorage.setItem('allCategories', JSON.stringify(missionScope.categoryContent));
generateAllMissions();
}
missionScope.removeFromCategory = function(category, mission) {
for (var i = 0; i < missionScope.categoryContent[category].missions.length; i++) {
if (missionScope.categoryContent[category].missions[i] == mission.mission_guid) {
missionScope.categoryContent[category].missions.splice(i, 1);
}
}
w.localStorage.setItem('allCategories', JSON.stringify(missionScope.categoryContent));
generateAllMissions();
}
missionScope.createCategory = function() {
var categoryName = prompt("Please enter a name for your new category", "New category name");
if (categoryName == null || categoryName == "") {
//no result
} else {
//create category elements
var newCategory = {
id: missionScope.categoryContent.length,
name: categoryName,
missions: [],
collapse: false,
sortCriteria: 'initial'
};
missionScope.categoryContent.push(newCategory);
w.localStorage.setItem('allCategories', JSON.stringify(missionScope.categoryContent));
generateAllMissions();
}
}
missionScope.nukeCategories = function() {
missionScope.categoryContent = [];
w.localStorage.setItem('allCategories', null);
generateAllMissions();
}
missionScope.deleteCategory = function(category) {
if (confirm("Are you sure you want to delete the " + missionScope.categoryContent[category].name + " category? Any missions you've placed in this category will be retured to Unsorted missions.")) {
//nuke localStorage category
missionScope.categoryContent.splice(category, 1);
w.localStorage.setItem('allCategories', JSON.stringify(missionScope.categoryContent));
generateAllMissions();
}
}
missionScope.sortCategory = function(category){
if (category == 'all'){
missionScope.missions = w.$filter("orderBy")(missionScope.missions, missionScope.sortCriteria[0] == 'initial' ? 'position' : missionScope.sortCriteria[0]);
} else if (category == 'unsorted'){
missionScope.uncategorisedSort = missionScope.sortCriteria[missionScope.categoryContent.length];
} else {
missionScope.categoryContent[category].sortCriteria = missionScope.sortCriteria[category];
}
generateAllMissions();
}
missionScope.toggleCollapse = function(collapse, unsorted){
collapse.collapse = !collapse.collapse;
unsorted ? w.localStorage.setItem('unsortedCollapse', collapse.collapse)
: w.localStorage.setItem('allCategories', JSON.stringify(missionScope.categoryContent));
}
missionScope.dragMissions = function(start_pos, start_cat, end_pos, end_cat) {
//first, parse category IDs and get categories
var startCategory, endCategory, startCatID, endCatID, thismission;
startCatID = isNaN(parseInt(start_cat.split('category')[1])) ? start_cat.split('category')[1] : parseInt(start_cat.split('category')[1]);
endCatID = isNaN(parseInt(end_cat.split('category')[1])) ? end_cat.split('category')[1] : parseInt(end_cat.split('category')[1]);
startCategory = startCatID == 'unsorted' ? missionScope.uncategorisedMissions : missionScope.categoryContent[startCatID];
endCategory = endCatID == 'unsorted' ? missionScope.uncategorisedMissions : missionScope.categoryContent[endCatID];
thismission = angular.copy(startCatID == 'unsorted' ? startCategory[start_pos-1].mission_guid : missionScope.categorisedMissions[startCatID][start_pos-1].mission_guid)
//then remove start mission
if (startCatID != 'unsorted'){
for (var i=0; i < startCategory.missions.length; i++){
if (startCategory.missions[i] == thismission){
startCategory.missions.splice(i,1);
break;
}
}
}
//then place end mission
//unsortedMissions category has no sort criteria, so if end target is category, handle dropping mission in category
if (endCategory.sortCriteria){
if (endCategory.sortCriteria == 'initial'){
//if category is in Initial sorting, respect that sorting
endCategory.missions.splice(end_pos-1, 0, thismission);
} else {
//if category is not in Inital sorting, dump mission at the end and set it to initial
endCategory.missions.push(thismission);
endCategory.sortCriteria = "initial";
}
}
//then regenerate everything
w.localStorage.setItem('allCategories', JSON.stringify(missionScope.categoryContent));
generateAllMissions();
}
var generateSort = function (category){
var criteria = [
{name: "Initial", value: "initial"},
{name: "Alphabetical (ascending)", value: "definition.name"},
{name: "Alphabetical (descending)", value: "-definition.name"},
{name: "Creation order", value: "created_ms"},
{name: "Mission state", value: "missionListState"}
];
missionScope.sortCriteria.push("");
var sortContent = "<select style='width: 50%; display: inline-block; margin: 5px 0;' class='form-control' ng-model='sortCriteria[";
//object literal switch for sort parameter
let parameterLiteral = {
"all" : "0",
"unsorted" : missionScope.categoryContent.length,
"default" : category,
}
sortContent += parameterLiteral[category] || parameterLiteral["default"];
sortContent += "]' ng-change='sortCategory("+(Number.isInteger(category)? category : "\""+category+"\"")+")' >";
sortContent += "<option value=''>Sort"+(Number.isInteger(category)? " category" : "" )+" by...</option>";
for (var i = 0; i < criteria.length; i++) {
sortContent += "<option value='" + criteria[i].value + "'>" + criteria[i].name + "</option>";
}
sortContent += "</select>";
return sortContent;
}
var generateMission = function(mission, id, selectedCategory) {
let missionState = mission.missionListState.toLowerCase();
let newMissionCode = "<div class='missionbox col-xs-12 col-sm-6 col-md-3'><div class='mission mission-list-item-" + missionState + "'>"
+ "<div class='mission-header-container'><div>"
+ "<img class='mission-image' src='" + (mission.definition.logo_url ? mission.definition.logo_url + "=s60-c" : "/images/button_logo.png") + "'>"
+ "</div><div>"
+ "<span class='name mission-title-" + missionState + "'>" + mission.definition.name + "</span>"
+ "</div><div>"
+ "<i class='name mission-title-" + missionState + " glyphicon glyphicon-";
//object literal switch for which icon to show
let iconLiteral = {
"draft" : "wrench' title='Unpublished draft mission'",
"draft_of_published_mission" : "wrench' title='Published mission with unpublished edits'",
"published" : "ok' title='Published mission'",
"submitted" : "time' title='Unpublished mission under review'",
"submitted_and_published" : "time' title='Published mission, changes under review'",
};
newMissionCode +=iconLiteral[missionState];
newMissionCode += "></i>"
+ "</div></div>"
+ "<span class='name mission-time-" + missionState + "'>" + missionScope.getInfoTime(mission) + "</span>"
+ "<table class='table table-bordered'";
!mission.stats && (newMissionCode += " style='width: 20%;' ");
newMissionCode += "><tr><td>";
//object literal switch for mission type
let mtypeLiteral = {
"SEQUENTIAL" : "<i class='glyphicon glyphicon-arrow-right' title='Sequential waypoints'></i>",
"HIDDEN_SEQUENTIAL" : "<i class='glyphicon glyphicon-eye-close' title='Hidden sequential waypoints'></i>",
"NON_SEQUENTIAL" : "<i class='glyphicon glyphicon-random' title='Non-linear waypoints (should not be used if the mission is part of a banner)'></i>",
};
newMissionCode += mtypeLiteral[mission.definition.mission_type];
newMissionCode += "</td>";
mission.stats && (
newMissionCode += "<td><i class='glyphicon glyphicon-time'></i> " + missionScope.getMissionTimeString(mission) + "</td>"
+ "<td><i class='glyphicon glyphicon-thumbs-up'></i> " + missionScope.getMissionRatingString(mission) + "</td>"
+ "<td><i class='glyphicon glyphicon-user'></i> " + mission.stats.num_completed + "</td>"
)
newMissionCode += "</tr></table>"
+ "<div class='dropup'><button class='button action-button dropdown-toggle' type='button' id='dropdownMenu1' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true'>Perform Mission Action</button>"
+ "<ul class='dropdown-menu' aria-labelledby='dropdownMenu1'>";
missionScope.getButton1Title(mission) && (newMissionCode += "<li><a role='button' ng-click='button1Clicked(missions[" + id + "])'>" + missionScope.getButton1Title(mission) + "</a></li>");
missionScope.getButton2Title(mission) && (newMissionCode += "<li><a role='button' ng-click='button2Clicked(missions[" + id + "])'>" + missionScope.getButton2Title(mission) + "</a></li>");
newMissionCode += "<li role='separator' class='divider'></li>";
//if mission is live, link to mission in Ingress intel and MAT preview thing
if (missionState != "draft" && missionState != "submitted") {
newMissionCode += "<li><a role='button' ng-click='previewMission(\"" + mission.mission_guid + "\")' data-toggle='modal' data-target='#previewMissionModel'>Preview Mission</a></li>";
newMissionCode += "<li><a role='button' href='https://intel.ingress.com/mission/" + mission.mission_guid + "' target='_blank'>Open Mission In Intel</a></li>";
}
if (selectedCategory === false) {
//adding unsorted mission to category
newMissionCode += "<li><a role='button' ng-click='selectACategory(missions[" + id + "])' data-toggle='modal' data-target='#addCateModel'>Add To Category...</a></li>";
} else {
//removing a mission from a category
newMissionCode += "<li><a role='button' ng-click='removeFromCategory(" + selectedCategory + ", missions[" + id + "])'>Remove From Category</a></li>";
}
newMissionCode += "</ul></div>"
newMissionCode += "</div></div>";
return newMissionCode;
}
var generateAllMissions = function() {
let scrollPosition = w.pageYOffset;
$(".missions-list").empty();
missionScope.categoryContent.length == 0 && ($(".missions-list").addClass("row"));
missionScope.sortCriteria = [];
w.$injector.invoke(function($compile) {
var missionContent = "";
if (missionScope.categoryContent.length > 0) {
//if there are user-defined categories, first sort the categorised/uncategorised missions
missionScope.categorisedMissions = [];
missionScope.uncategorisedMissions = angular.copy(missionScope.missions);
//loop through each category of GUIDs, and add actual missions to scope
missionScope.categoryContent.forEach(function(category) {
var catobj = [];
category.missions.forEach(function(guid) {
//TODO: Do this with filters, not loops
for (var i = 0; i < missionScope.uncategorisedMissions.length ; i++) {
//once the right mission is found, add position, push it to the holding array and remove from uncategorised
if (missionScope.uncategorisedMissions[i].mission_guid == guid) {
catobj.push(missionScope.uncategorisedMissions[i]);
missionScope.uncategorisedMissions.splice(i, 1);
break;
}
}
})
missionScope.categorisedMissions.push(catobj);
})
//then get the categories sorted
missionScope.categoryContent.forEach(function(category) {
category.sortCriteria != 'initial' && (missionScope.categorisedMissions[category.id] = w.$filter("orderBy")(missionScope.categorisedMissions[category.id], category.sortCriteria));
})
missionScope.uncategorisedSort != 'initial' && (missionScope.uncategorisedMissions = w.$filter("orderBy")(missionScope.uncategorisedMissions, missionScope.uncategorisedSort));
//once all the categorisation is done, create the HTML for the categories!
missionContent += "<div class='panel-group' id='accordion' role='tablist' aria-multiselectable='true' style='width: 100%'>";
for (var i = 0; i < missionScope.categoryContent.length; i++) {
missionContent += "<div class='panel panel-default'><div class='panel-heading' role='tab'>"
+ "<h4 class='panel-title' ng-class='{\"collapsed\" : categoryContent[" + i + "].collapse}'><a ng-click='toggleCollapse(categoryContent[" + i + "], false)' role='button' data-toggle='collapse'>"
+ missionScope.categoryContent[i].name
+ "</a></h4></div><div class='panel-collapse collapse' ng-class='{\"in\" : !categoryContent[" + i + "].collapse}' role='tabpanel'><div class='panel-body'>"
+ "<div id='category"+ i +"' class='row'><div class='col-xs-12 categoryFunctions'>"
+ generateSort(i)
+ "<button class='btn btn-default'style='float: right!important;margin: 5px 0;' ng-click='deleteCategory(" + i + ")'>Delete Category</button>";
if (!missionScope.categoryContent[i].missions || missionScope.categoryContent[i].missions.length == 0) {
//no missions so far!
missionContent += "</div><div class='col-xs-12'>No missions added to the category yet</div>";
} else {
missionContent += "<button class='btn btn-default'style='float: right!important;margin: 5px;' data-toggle='modal' data-target='#previewBanner" + i + "'>Preview Images</button>"
+ "<button class='btn btn-default'style='float: right!important;margin: 5px;' ng-click='previewBanner(" + i + ")' data-toggle='modal' data-target='#previewMissionModel'>Preview Route</button></div>";
var bannerModal = "<div class='modal fade' id='previewBanner" + i + "' tabindex='-1' role='dialog'><div class='modal-dialog modal-lg' role='document'><div class='modal-content banner-preview'><div class='modal-header'><button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>×</span></button><h4 class='modal-title'>Preview \"" + missionScope.categoryContent[i].collapse + "\"</h4></div><div class='modal-body'><div class='row'>";
for (var j = 0; j < missionScope.categoryContent[i].missions.length; j++) {
var mission = missionScope.categorisedMissions[i][j];
if (mission == undefined){
missionScope.categoryContent[i].missions.splice(j,1);
j--;
w.localStorage.setItem('allCategories', JSON.stringify(missionScope.categoryContent));
} else {
missionContent += generateMission(mission, mission.position, i);
bannerModal += "<div class='col-xs-2'><img class='img-responsive' src='" + (mission.definition.logo_url ? mission.definition.logo_url : "/images/button_logo.png") + "' /></div>";
}
}
bannerModal += "</div></div></div></div></div>";
missionContent += bannerModal;
}
missionContent += "</div></div></div></div>";
}
//add unsorted missions if there are any
missionContent += "<div class='panel panel-default'><div class='panel-heading' role='tab' id='header-unsorted'>"
+ "<h4 class='panel-title' ng-class='{\"collapsed\" : unsortedCollapse.collapse}'><a ng-click='toggleCollapse(unsortedCollapse, true)' role='button' data-toggle='collapse'>Unsorted Missions</a></h4></div><div class='panel-collapse collapse' ng-class='{\"in\" : !unsortedCollapse.collapse}' role='tabpanel'><div class='panel-body'>"
+ "<div id='categoryunsorted' class='row'><div class='col-xs-12 categoryFunctions'>"
+ generateSort('unsorted')
+ "</div>";
for (var i = 0; i < missionScope.uncategorisedMissions.length; i++) {
missionContent += generateMission(missionScope.uncategorisedMissions[i], missionScope.uncategorisedMissions[i].position, false);
}
missionContent += "</div></div></div></div></div>";
} else {
//if no user-defined categories, just loop through the missions
missionContent += "<div class='col-xs-12'>"
+ generateSort('all')
+ "</div>";
for (var i = 0; i < missionScope.missions.length; i++) {
var mission = missionScope.missions[i];
missionContent += generateMission(mission, i, false);
}
}
//modal for adding missions to categories
missionContent += "<div class='modal fade' id='addCateModel' tabindex='-1' role='dialog'><div class='modal-dialog' role='document'><div class='modal-content'><div class='modal-header'><button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>×</span></button><h4 class='modal-title'>{{missionTitle}}</h4></div><div class='modal-body'>"
+ "<select class='form-control' ng-model='selectedCategoryID' ng-change='addToCategory()' >";
for (var i = 0; i < missionScope.categoryContent.length; i++) {
missionContent += "<option value='" + i + "' data-dismiss='modal'>" + missionScope.categoryContent[i].name + "</option>";
}
missionContent += "</select></div></div></div></div>";
//modal for previewing missions
missionContent += "<div class='modal fade' id='previewMissionModel' tabindex='-1' role='dialog'><div class='modal-dialog modal-lg' role='document'><div class='modal-content'><div class='modal-header'><button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>×</span></button><h4 class='modal-title'>Preview Mission</h4></div><div class='modal-body' style='background:#151515'>"
+ "<div class='loading-screen' ng-show='loadingPreview'><div class='loading spin'></div></div><div class='notloading'></div>"
+ "</div></div></div></div>";
// Pass our fragment content to $compile, and call the function that $compile returns with the scope.
var compiledContent = $compile(missionContent)(missionScope);
// Put the output of the compilation in to the page using jQuery
$('.missions-list').append(compiledContent);
setTimeout(() => {
w.scrollTo(0, scrollPosition);
}, 250);
//now enable drag-drop for the missions!
if (missionScope.categoryContent.length > 0) {
$('.row[id^=category]').sortable({
items: "div.missionbox",
connectWith: ".row[id^=category]",
tolerance: "pointer",
placeholder: "ui-state-highlight col-xs-12 col-sm-6 col-md-3",
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
ui.item.data('start_cat', ui.item[0].parentElement.id);
},
update: function (event, ui) {
var start_pos = ui.item.data('start_pos'),
start_cat = ui.item.data('start_cat'),
end_pos = ui.item.index(),
end_cat = ui.item[0].parentElement.id;
!ui.sender && missionScope.dragMissions(start_pos, start_cat, end_pos, end_cat);
}
});
}
});
}
missionScope.exportData = function() {
navigator.clipboard.writeText(JSON.stringify(missionScope.categoryContent)).then(function() {
alert('Category data copied to your clipboard - please paste this in the Import Data box in the browser you want to export this to')
}, function() {
alert('Something went wrong')
});
};
missionScope.importData = function() {
var dataInput = prompt("Please paste in the text you got from the Data Export on your other device");
if (dataInput == null || dataInput == "") {
//don't do anything
} else {
//try to parse data, then turn it into object
try {
missionScope.categoryContent = JSON.parse(dataInput);
w.localStorage.setItem('allCategories', JSON.stringify(missionScope.categoryContent));
generateAllMissions();
} catch (e){
alert('Something went wrong!!');
}
}
}
//compiling the buttons
w.$injector.invoke(function($compile) {
var buttonContent = "<div class='bordered-panel'>";
//button for adding categories
buttonContent += "<button ng-click='createCategory()' class='yellow create-mission-button'>Create New Category</button>"
+ "<button ng-click='exportData()' class='yellow create-mission-button'>Export Category Data</button>"
+ "<button ng-click='importData()' class='yellow create-mission-button'>Import Category Data</button>";
//buttonContent += "<button ng-click='nukeCategories()' class='yellow create-mission-button'>NUKE EVERYTHING</button>";
//tally up available missions, and missions in draft states
var draftMissions = w.$filter('filter')(missionScope.missions, {missionListState: "DRAFT"}, true).length;
var dopMissions = w.$filter('filter')(missionScope.missions, {missionListState: "DRAFT_OF_PUBLISHED_MISSION"}, true).length;
var submittedMissions = w.$filter('filter')(missionScope.missions, {missionListState: "SUBMITTED"}, true).length;
var sapMissions = w.$filter('filter')(missionScope.missions, {missionListState: "SUBMITTED_AND_PUBLISHED"}, true).length;
var publishedMissions = w.$filter('filter')(missionScope.missions, {missionListState: "PUBLISHED"}, true).length;
var remainder = (w.$rootScope.user.mission_limit || 180) - (dopMissions + submittedMissions + sapMissions + publishedMissions);
buttonContent += "<h4 style='line-height: 2;'>";
remainder > 0 && (buttonContent += "<span class='label'>"+remainder+" missions remaining</span> ");
draftMissions > 0 && (buttonContent += "<span class='label mission-list-item-draft'>"+draftMissions+" unpublished drafts</span> ");
submittedMissions > 0 && (buttonContent += "<span class='label mission-list-item-submitted'>"+submittedMissions+" under review</span> ");
dopMissions > 0 && (buttonContent += "<span class='label mission-list-item-draft_of_published_mission'>"+dopMissions+" being amended</span> ");
sapMissions > 0 && (buttonContent += "<span class='label mission-list-item-submitted_and_published'>"+sapMissions+" changes under review</span> ");
publishedMissions > 0 && (buttonContent += "<span class='label mission-list-item-published'>"+publishedMissions+" published</span>");
buttonContent += "</h4>"
buttonContent += "</div>";
// Pass our fragment content to $compile, and call the function that $compile returns with the scope.
var compiledContent = $compile(buttonContent)(missionScope);
// Put the output of the compilation in to the page using jQuery
$('.list').prepend(compiledContent);
});
$('.list .bordered-panel').prepend($('.list div:not(.bordered-panel) button.yellow.create-mission-button'));
//initiating the missions
$(".missions-list").removeClass("row").addClass('ready');
generateAllMissions();
}
}
setTimeout(() => {
init();
}, 500);