/
controller.js
executable file
·3384 lines (2956 loc) · 137 KB
/
controller.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
/* **************************************************************
Copyright 2011 Zoovy, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************** */
function initApp(params) {
params = params || {};
if(typeof Prototype == 'object') {
alert("Oh No! you appear to have the prototype ajax library installed. This library is not compatible. Please change to a non-prototype theme (2011 series).");
}
//zglobals is not required in the UI, but is for any
// else if(typeof zGlobals != 'object' && !params.thisSessionIsAdmin) {
//zGlobals not required in an admin session.
// alert("Uh Oh! A required include (config.js) is not present. This document is required.");
// }
else {
function create(parent) {
var F = function() {};
F.prototype = parent;
return new F();
}
var self = this;
$.extend(true,self,controller(self),{'vars':params}); //extend self, not initApp.prototype, so that any variables/functions inside this instance are unique to the instance.
initApp.prototype.model = create(new model(self));
self.u.dump('Welcome fellow developer!\nThis project was built with an open-source MVC which can be found here:\nhttps://github.com/zoovy/AnyCommerce-Development','greet');
self.initialize();
}
}
function controller(_app) {
return {
cmr : [],
rq : [],
initialize: function() {
window.dump = _app.u.dump; //after 'quiet' code so that if _app.u.dump is nuked, so is dump();
window.makeImage = _app.u.makeImage; //FUTURE -> get rid of this. temporary work around for variations code in includes.
// dump(" -> initializing app");
_app.u.updatejQuerySupport(); //update the $.support object w/ some additional helpful info. Needs to be very early in the process since handleSession will use it.
_app.vars = _app.vars || {};
if(_app.vars.addjQueryPointer) {jQuery._app = _app;}
_app.vars.platform = _app.vars.platform ? _app.vars.platform : 'webapp'; //webapp, ios, android
_app.vars.cid = null; //gets set on login. ??? I'm sure there's a reason why this is being saved outside the normal object. Figure it out and document it.
_app.vars.fbUser = {};
//used in conjunction with support/admin login. nukes entire local cache.
if(_app.u.getParameterByName('flush') == 1) {
_app.u.dump(" !!! Flush is enabled. session and local storage get nuked !!!");
if($.support.sessionStorage) {
window.sessionStorage.clear();
}
if($.support.localStorage) {
window.localStorage.clear();
}
}
if(_app.u.getParameterByName('quiet') == 1){
_app.u.dump = function(){};
}
if (_app.u.getParameterByName('apidomain')) {
// ?apidomain=www.domain.com will set jqurl to an alternate source (ex: testing)
_app.vars.jqurl = "https://"+_app.u.getParameterByName('apidomain')+":9000/jsonapi/";
}
//needs to be after the 'flush' above, or there's no way to flush the cart/session.
_app.vars.carts = _app.model.dpsGet('app','carts'); //get existing carts. Does NOT create one if none exists. that's app-specific behavior. Don't default to a blank array either. fetchCartID checks memory first.
_app.handleSession(); //get existing session or create a new one.
_app.vars.debug = _app.u.getParameterByName('debug'); //set a var for this so the URI doesn't have to be checked each time.
// can be used to pass additional variables on all request and that get logged for certain requests (like createOrder).
// default to blank, not 'null', or += below will start with 'undefined'.
//vars should be passed as key:value; _v will start with zmvc:version.release.
_app.vars.passInDispatchV = _app.vars.passInDispatchV || '';
_app.vars.passInDispatchV += 'browser:'+_app.u.getBrowserInfo()+";OS:"+_app.u.getOSInfo()+';compatMode:'+document.compatMode;
_app.vars.release = _app.vars.release || 'unspecified'; //will get overridden if set in P. this is default.
_app.u.dump(" -> version: "+_app.model.version+" and release "+_app.vars.release);
_app.ext = _app.ext || {}; //for holding extensions
_app.data = {}; //used to hold all data retrieved from ajax requests.
_app.vars.extensions = _app.vars.extensions || []; //the list of extensions that are/will be loaded
/*
_app.templates holds a copy of each of the templates declared in an extension but defined in the view. The template is stored in memory for speed.
*/
_app.templates = {};
//queues are arrays, not objects, because order matters here. the model.js file outlines what each of these is used for.
_app.q = {mutable : new Array(), passive: new Array(), immutable : new Array()};
_app.globalAjax = {
dataType : 'json',
overrideAttempts : 0, //incremented when an override occurs. allows for a cease after X attempts.
lastDispatch : null, //timestamp.
// passiveInterval : setInterval(function(){_app.model.dispatchThis('passive')},5000), //auto-dispatch the passive q every five seconds. //### TODO -> commented out for testing.
numRequestsPerPipe : 50,
requests : {"mutable":{},"immutable":{},"passive":{}} //'holds' each ajax request. completed requests are removed.
}; //holds ajax related vars.
//the var for thisSessionIsAdmin should only be used here and in extension inits. it's just an indicator and will be true whether logged in or not.
// _app.u.thisIsAnAdminSession() will only be true after login has occured.
if(_app.vars.thisSessionIsAdmin) {
_app.handleAdminVars(); //needs to be late because it'll use some vars set above.
}
_app.model.addExtensions(_app.vars.extensions);
// *** 201402 -> this is executed after the app is instantiated.
// if(typeof _app.vars.initComplete == 'function') {
// _app.vars.initComplete(_app);
// }
}, //initialize
//will load _session from localStorage or create a new one.
handleSession : function() {
if(_app.vars._session) {} //already defined.
else if(_app.u.getParameterByName('_session')) { //get from URI, if set.
_app.vars._session = _app.u.getParameterByName('_session');
_app.u.dump(" -> session found on URI: "+_app.vars._session);
}
//in case localstorage is disabled.
else if(!$.support.localStorage) {
_app.vars._session = _app.model.readCookie('_session');
dump("check cookie for _session: "+_app.vars._session);
}
else {
_app.vars._session = _app.model.dpsGet('controller','_session');
dump(" -> check localstorage for _session: "+_app.vars._session);
}
// *** 201403 -> moved this code from the else above to outside it so a session would ALWAYS be generated.
// this solved an obscure case where localStorage was supported but 'full' (unable to be written to).
if(!_app.vars._session) {
//create a new session id.
_app.vars._session = _app.u.guidGenerator();
_app.u.dump(" -> generated new session: "+_app.vars._session);
_app.model.dpsSet('controller','_session',_app.vars._session);
if(!$.support.localStorage) {
_app.model.writeCookie('_session',_app.vars._session); //for browsers w/ localstorage disabled.
}
}
}, //handleSession
//This is run on init, BEFORE a user has logged in to see if login info is in localstorage or on URI.
//after login, the admin vars are set in the model.
handleAdminVars : function(){
// _app.u.dump("BEGIN handleAdminVars");
var localVars = {}
if(_app.model.fetchData('authAdminLogin')) {localVars = _app.data.authAdminLogin}
// _app.u.dump(" -> localVars: "); _app.u.dump(localVars);
function setVars(id){
// _app.u.dump("GOT HERE!");
// _app.u.dump("-> "+id+": "+_app.u.getParameterByName(id));
if(_app.vars[id]) {} //already set, do nothing.
//check url. these get priority of local so admin/support can overwrite.
//uri ONLY gets checked for support. This is so that on redirects back to our UI from a partner interface don't update auth vars.
else if(_app.u.getParameterByName('trigger') == 'support' && _app.u.getParameterByName(id)) {_app.vars[id] = _app.u.getParameterByName(id);}
else if(localVars[id]) {_app.vars[id] = localVars[id]}
else {_app.vars[id] = ''}//set to blank by default.
}
setVars('deviceid');
setVars('userid');
setVars('authtoken');
setVars('domain');
setVars('username');
_app.vars.username = _app.vars.username.toLowerCase();
}, //handleAdminVars
// ////////////////////////////////// CALLS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\
/*
calls all have an 'init' as well as a 'dispatch'.
the init allows for the call to check if the data being retrieved is already in the session or local storage and, if so, avoid a request.
If the data is not there, or there's no data to be retrieved (a Set, for instance) the init will execute the dispatch.
*/
calls : {
appCartCreate : {
init : function(_tag,Q) {
this.dispatch(_tag,Q);
return 1;
},
dispatch : function(_tag,Q) {
_app.model.addDispatchToQ({"_cmd":"appCartCreate","_tag":_tag},Q || 'immutable');
}
},//appCartCreate
appNavcatDetail : {
init : function(obj,_tag,Q) {
if(obj && obj.path) {
var r = 0; //will return 1 if a request is needed. if zero is returned, all data needed was in local.
_tag = _tag || {};
_tag.datapointer = 'appNavcatDetail|'+obj.path;
if(_app.model.fetchData(_tag.datapointer)) {
//data is now in memory. based on the detail param, see if the category record available is enough.
var catData = _app.data[_tag.datapointer];
//if max is already available, just use it.
if(catData.detail == 'max') {
_app.u.handleCallback(_tag);
}
else if(obj.detail == 'more' && catData.detail == 'more') {
_app.u.handleCallback(_tag);
}
else if(!obj.detail || obj.detail == 'fast') {
//if no detail is specified or it's set to 'fast', whatever we have in memory is enough or more than enough.
_app.u.handleCallback(_tag);
}
else {
r += 1;
this.dispatch(obj,_tag,Q);
}
}
else {
//no data in memory/local. go get it.
r += 1;
this.dispatch(obj,_tag,Q);
}
}
else {
_app.u.throwGMessage("In calls.appNavcatDetail, obj.path not passed.");
_app.u.dump(obj);
}
return r;
},
dispatch : function(obj,_tag,Q) {
obj._cmd = "appNavcatDetail";
obj._tag = _tag;
_app.model.addDispatchToQ(obj,Q);
}
},//appNavcatDetail
//get a product record.
//required params: obj.pid.
//optional params: obj.withInventory and obj.withVariations
appProductGet : {
init : function(obj,_tag,Q) {
var r = 0; //will return 1 if a request is needed. if zero is returned, all data needed was in local.
if(obj && obj.pid) {
if(typeof obj.pid === 'string') {obj.pid = obj.pid.toUpperCase();} //will error if obj.pid is a number.
_tag = _tag || {};
_tag.datapointer = "appProductGet|"+obj.pid;
//The fetchData will put the data into memory if present, so safe to check _app.data... after here.
if(_app.model.fetchData(_tag.datapointer) == false) {
r = 1;
this.dispatch(obj,_tag,Q)
}
//if variations or options are requested, check to see if they've been retrieved before proceeding.
else if((obj.withVariations && _app.data[_tag.datapointer]['@variations'] === undefined) || (obj.withInventory && _app.data[_tag.datapointer]['@inventory'] === undefined)) {
r = 1;
this.dispatch(obj,_tag,Q);
}
//if the product record is in memory BUT the inventory is zero, go get updated record in case it's back in stock.
else if(_app.ext.store_product && (_app.ext.store_product.u.getProductInventory(_app.data[_tag.datapointer]) === 0)) {
r = 1;
this.dispatch(obj,_tag,Q);
}
else {
_app.u.handleCallback(_tag);
}
if(obj.withInventory) {obj.inventory=1}
}
else {
_app.u.throwGMessage("In calls.appProductGet, required parameter pid was not passed");
_app.u.dump(obj);
}
return r;
},
dispatch : function(obj,_tag,Q) {
obj["_cmd"] = "appProductGet";
obj["_tag"] = _tag;
_app.model.addDispatchToQ(obj,Q);
}
}, //appProductGet
appProfileInfo : {
init : function(obj,_tag,Q) {
var r = 0; //will return 1 if a request is needed. if zero is returned, all data needed was in local.
if(typeof obj == 'object' && (obj.profile || obj.domain)) {
_tag = _tag || {};
_tag.datapointer = 'appProfileInfo|'+(obj.profile || obj.domain);
if(_app.model.fetchData(_tag.datapointer) == false) {
r = 1;
this.dispatch(obj,_tag,Q);
}
else {
_app.u.handleCallback(_tag);
}
}
else {
_app.u.throwGMessage("In calls.appProfileGet, obj either missing or missing profile ["+obj.profile+"] or domain ["+obj.domain+"] var.");
_app.u.dump(obj);
}
return r;
}, // init
dispatch : function(obj,_tag,Q) {
obj._cmd = "appProfileInfo";
obj._tag = _tag;
_app.model.addDispatchToQ(obj,Q);
} // dispatch
}, //appProfileInfo
authAdminLogin : {
init : function(obj,_tag) {
this.dispatch(obj,_tag);
return 1;
},
dispatch : function(obj,_tag){
_app.u.dump("Attempting to log in");
obj._cmd = 'authAdminLogin';
obj.authid = obj.password;
obj.authtype = obj.authtype || 'password';
// ** 201402 -> md5 is no longer used for login.
/* if(obj.authtype == 'md5') {
_app.vars.userid = obj.userid.toLowerCase(); // important!
obj.ts = _app.u.ymdNow();
obj.authid = Crypto.MD5(obj.password+obj.ts);
obj.device_notes = "";
delete obj.password;
}
*/
obj._tag = _tag || {};
if(obj.persistentAuth) {obj._tag.datapointer = "authAdminLogin"} //this is only saved locally IF 'keep me logged in' is true OR it's passed in _tag
_app.model.addDispatchToQ(obj,'immutable');
}
}, //authentication
// ### FUTURE -> remove this call.
buyerAddressList : {
init : function(_tag,Q) {
var r = 0;
_tag = _tag || {};
_tag.datapointer = "buyerAddressList";
if(_app.model.fetchData("buyerAddressList") == false) {
r = 1;
this.dispatch(_tag,Q);
}
else {
_app.u.handleCallback(_tag);
}
return r;
},
dispatch : function(_tag,Q) {
_app.model.addDispatchToQ({"_cmd":"buyerAddressList","_tag": _tag},Q || 'mutable');
}
}, //buyerAddressList
// ### FUTURE -> remove this call.
buyerProductListDetail : {
init : function(listID,_tag,Q) {
var r = 0;
if(listID) {
_tag = _tag || {};
_tag.datapointer = "buyerProductListDetail|"+listID
this.dispatch(listID,_tag,Q);
r = 1;
}
else {
$('#globalMessaging').anymessage({'message':'buyerProductListDetail requires listID','gMessage':true});
}
return r;
},
dispatch : function(listID,_tag,Q) {
_app.model.addDispatchToQ({"_cmd":"buyerProductListDetail","listid":listID,"_tag" : _tag},Q);
}
},//buyerProductListDetail
//obj must include listid
//obj can include sku, qty,priority, note and replace. see github for more info.
//sku can be a fully qualified stid (w/ options)
// ### FUTURE -> remove this call.
buyerProductListAppendTo : {
init : function(obj,_tag,Q) {
var r = 0;
if(obj && obj.listid) {
r = 1;
this.dispatch(obj,_tag,Q);
}
else {
$('#globalMessaging').anymessage({'message':'buyerProductListDetail requires listid','gMessage':true});
}
return r;
},
dispatch : function(obj,_tag,Q) {
obj['_cmd'] = "buyerProductListAppendTo"
obj['_tag'] = _tag || {};
_app.model.addDispatchToQ(obj,Q || 'immutable');
}
},//buyerProductListAppendTo
// ### FUTURE -> get rid of this as a 'call'. use logBuyerOut.
buyerLogout : {
init : function(_tag) {
// logging out clears these fields as they contain buyer specific data.
_app.model.destroy('appBuyerLogin');
_app.model.destroy('buyerWalletList');
_app.model.destroy('buyerAddressList');
_app.model.destroy('appPaymentMethods');
_app.model.destroy('whoAmI');
_app.model.destroy('cartDetail|'+_app.model.fetchCartID());
this.dispatch(_tag);
return 1;
},
dispatch : function(_tag) {
obj = {};
obj["_cmd"] = "buyerLogout";
obj["_tag"] = _tag || {};
obj["_tag"]["datapointer"] = "buyerLogout";
_app.model.addDispatchToQ(obj,'immutable');
}
}, //appBuyerLogout
//WILL look in local
// ### FUTURE -> this call needs to support a 'create' or need a new call for it. should default to zero. if one (would be used on a storefront probably), if no cart exists, it will be created.
cartDetail : {
init : function(cartID,_tag,Q) {
var r = 0;
if(cartID) {
_tag = _tag || {};
_tag.datapointer = "cartDetail|"+cartID;
if(_app.model.fetchData(_tag.datapointer)) {
_app.u.handleCallback(_tag);
}
else {
r = 1;
this.dispatch(cartID,_tag,Q);
}
}
else {
$('#globalMessaging').anymessage({"message":"In calls.cartDetail, no cartID specified.","gMessage":true});
}
return r;
},
dispatch : function(cartID,_tag,Q) {
_app.model.addDispatchToQ({"_cmd":"cartDetail","_cartid":cartID,"_tag": _tag,"create":0},Q || 'mutable');
}
}, // refreshCart removed comma from here line 383
//used to get a clean copy of the cart. ignores local/memory. used in various places, like checkout. intended to work specifically with the 'active' cart.
//this is old and, arguably, should be a utility. however it's used a lot so for now, left as is. ### search and destroy when convenient.
refreshCart : {
init : function(_tag,Q) {
var cartID = _app.model.fetchCartID();
if(cartID) {
_app.model.destroy('cartDetail|'+cartID);
_app.calls.cartDetail.init(cartID,_tag,Q);
}
}
}, // refreshCart
// ### FUTURE -> remove this call.
ping : {
init : function(_tag,Q) {
this.dispatch(_tag,Q);
return 1;
},
dispatch : function(_tag,Q) {
_app.model.addDispatchToQ({"_cmd":"ping","_tag":_tag},Q || 'mutable'); //get new session id.
}
} //ping
}, // calls
// ////////////////////////////////// CALLBACKS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\
/*
Callbacks require should have an onSuccess.
Optionally, callbacks can have on onError. if you have a custom onError, no error messaging is displayed. This give the developer the opportunity to easily suppress errors for a given request/callback.
_app.u.throwMessage(responseData); is the default error handler.
*/
callbacks : {
fileDownloadInModal : {
onSuccess : function(_rtag) {
_app.u.dump("BEGIN callbacks.fileDownloadInModal");
_app.u.fileDownloadInModal({
'filename':_app.data[_rtag.datapointer].FILENAME || _rtag.filename,
'mime_type':_app.data[_rtag.datapointer].MIMETYPE,
'body':_app.data[_rtag.datapointer].body,
'skipDecode':_rtag.skipDecode || false
});
if(_rtag.button && _rtag.button instanceof jQuery) {
if(_rtag.button.is('button') && _rtag.button.hasClass('ui-button')) {
_rtag.button.button('enable');
}
else if(_rtag.button.is('button')) {
_rtag.button.prop('disabled','').removeProp('disabled');
}
}
if(_rtag.jqObj && _rtag.jqObj instanceof jQuery) {
_rtag.jqObj.hideLoading();
}
}
},
//very similar to the original translate selector in the control and intented to replace it.
//This executes the handleAppEvents in addition to the normal translation.
//jqObj is required and should be a jquery object.
//tlc is a VERY common callback. To keep it tight but flexible, before and onComplete functions can be passed to handle special cases.
tlc : {
onMissing : function(rd) {
rd._rtag.jqObj.anymessage(rd);
},
onSuccess : function(_rtag) {
// _app.u.dump("BEGIN callbacks.tlc ------------------------"); _app.u.dump(_rtag);
if(_rtag && _rtag.jqObj && typeof _rtag.jqObj == 'object') {
//allows for the callback to perform a lot of the common handling, but to append a little extra functionality at the end of a success.
if(typeof _rtag.before == 'function') {
_rtag.before(_rtag);
}
var $target = _rtag.jqObj
$target.hideLoading(); //shortcut
if(_rtag.templateID && !_rtag.templateid) {_rtag.templateid = _rtag.templateID} //anycontent used templateID. tlc uses templateid. rather than put this into the core tranlsator, it's here as a stopgap.
//anycontent will disable hideLoading and loadingBG classes.
//to maintain flexibility, pass all anycontent params in thru _tag
$target.tlc(_rtag);
$target.anyform(_rtag);
_app.u.handleCommonPlugins($target);
_app.u.handleButtons($target);
//allows for the callback to perform a lot of the common handling, but to append a little extra functionality at the end of a success.
if(typeof _rtag.onComplete == 'function') {
_rtag.onComplete(_rtag);
}
}
else {
$('#globalMessaging').anymessage({'message':'In admin.callbacks.tlc, jqOjb not set or not an object ['+typeof _rtag.jqObj+'].','gMessage':true});
}
},
onError : function(rd) {
if(rd._rtag && rd._rtag.jqObj && typeof rd._rtag.jqObj == 'object'){
rd._rtag.jqObj.hideLoading().anymessage({'message':rd});
}
else {
$('#globalMessage').anymessage({'message':rd});
}
}
}, //translateSelector
//very similar to the original translate selector in the control and intented to replace it.
//This executes the handleAppEvents in addition to the normal translation.
//jqObj is required and should be a jquery object.
anycontent : {
onMissing : function(rd) {
dump(" -----------> rd: "); dump(rd);
rd._rtag.jqObj.anymessage(rd);
rd._rtag.jqObj.hideLoading();
if(typeof rd._rtag.onMissing === 'function') {
rd._rtag.onMissing(rd);
}
},
onSuccess : function(_rtag) {
_app.u.dump("BEGIN callbacks.anycontent"); // _app.u.dump(_rtag);
if(_rtag && _rtag.jqObj && typeof _rtag.jqObj == 'object') {
var $target = _rtag.jqObj; //shortcut
//anycontent will disable hideLoading and loadingBG classes.
//to maintain flexibility, pass all anycontent params in thru _tag
$target.anycontent(_rtag);
_app.u.handleCommonPlugins($target);
_app.u.handleButtons($target);
// use either delegated events OR app events, not both.
//avoid using this. ### FUTURE -> get rid of these. the delegation should occur in the function that calls this. more control that way and things like dialogs being appendedTo a parent can be handled more easily.
if(_rtag.addEventDelegation) {
_app.u.addEventDelegation($target);
}
else if(_rtag.skipAppEvents) {}
else {
_app.u.handleAppEvents($target);
}
if(_rtag.applyEditTrackingToInputs) {
_app.ext.admin.u.applyEditTrackingToInputs($target); //applies 'edited' class when a field is updated. unlocks 'save' button.
}
if(_rtag.handleFormConditionalDelegation) {
_app.ext.admin.u.handleFormConditionalDelegation($('form',$target)); //enables some form conditional logic 'presets' (ex: data-panel show/hide feature)
}
//allows for the callback to perform a lot of the common handling, but to append a little extra functionality at the end of a success.
if(typeof _rtag.onComplete == 'function') {
_rtag.onComplete(_rtag);
}
}
else {
$('#globalMessaging').anymessage({'message':'In admin.callbacks.anycontent, jqOjb not set or not an object ['+typeof _rtag.jqObj+'].','gMessage':true});
}
},
onError : function(rd) {
if(rd._rtag && rd._rtag.jqObj && typeof rd._rtag.jqObj == 'object'){
rd._rtag.jqObj.hideLoading().anymessage({'message':rd});
}
else {
$('#globalMessage').anymessage({'message':rd});
}
}
}, //translateSelector
translateSelector : {
onSuccess : function(_rtag) {
if(typeof jQuery().hideLoading == 'function'){$(_rtag.selector).hideLoading();}
_app.renderFunctions.translateSelector(_rtag.selector,_app.data[_rtag.datapointer]);
}
},
transmogrify : {
onSuccess : function(_rtag) {
var $parent = $(_app.u.jqSelector('#',_rtag.parentID));
if(typeof jQuery().hideLoading == 'function'){$parent.hideLoading();}
$parent.append(_app.renderFunctions.transmogrify({'id':_rtag.parentID+"_"+_rtag.datapointer},_rtag.templateID,_app.data[_rtag.datapointer]));
}
}, //translateTemplate
//pass the following on _tag:
// parentID is the container id that the template instance is already in (should be created before call)
// templateID is the template that will get translated.
// the _app.data.datapointer is what'll get passed in to the translate function as the data src. (ex: getProduct|PID)
translateTemplate : {
onSuccess : function(_rtag) {
// _app.u.dump("BEGIN callbacks.translateTemplate"); _app.u.dump(_rtag);
// _app.u.dump("typeof jQuery.hideLoading: "+typeof jQuery().hideLoading);
if(typeof jQuery().hideLoading == 'function'){$(_app.u.jqSelector('#',_rtag.parentID)).hideLoading();}
_app.renderFunctions.translateTemplate(_app.data[_rtag.datapointer],_rtag.parentID);
}
}, //translateTemplate
// a generic callback to allow for success messaging to be added.
// pass message for what will be displayed. For error messages, the system messaging is used.
showMessaging : {
onSuccess : function(_rtag,macroResponses) {
_app.u.dump("BEGIN _app.callbacks.showMessaging");
if(_rtag.jqObj) {
// _app.u.dump(" -> jqObj is present.");
// _app.u.dump(" -> jqObj.data(): "); _app.u.dump(_rtag.jqObj.data());
_rtag.jqObj.hideLoading();
if(_rtag.jqObjEmpty) {
_rtag.jqObj.empty();
}
//you can't restore AND empty. it's empty, there's nothing to restore.
else {
if(_rtag.restoreInputsFromTrackingState) {
// _app.u.dump(" -> restoreInputsFromTrackingState.");
_app.ext.admin.u.restoreInputsFromTrackingState(_rtag.jqObj);
}
if(_rtag.removeFromDOMItemsTaggedForDelete) {
// _app.u.dump(" -> removeFromDOMItemsTaggedForDelete.");
_app.ext.admin.u.removeFromDOMItemsTaggedForDelete(_rtag.jqObj);
}
}
}
if(macroResponses && macroResponses['@RESPONSES']) {
var $target = _rtag.jqObj || $("#globalMessaging");
macroResponses.persistent = _rtag.persistent === false ? false : true; //these responses should be displayed till turned off.
$target.anymessage(macroResponses);
}
else {
var msg = _app.u.successMsgObject(_rtag.message);
msg['_rtag'] = _rtag; //pass in _rtag as well, as that contains info for parentID.
_app.u.throwMessage(msg);
}
//allows for the callback to perform a lot of the common handling, but to append a little extra functionality at the end of a success.
if(typeof _rtag.onComplete == 'function') {
_rtag.onComplete(_rtag);
}
}
}, //showMessaging
disableLoading : {
onSuccess : function(_rtag) {
$('#'+_rtag.targetID).hideLoading();
},
onError : function(responseData) {
_app.u.throwMessage(responseData);
$('#'+responseData._rtag.targetID).hideLoading(); //even with the error, it's bad form to leave the loading bg.
}
},
/*
By default, error messaging is thrown to the appMessaging class. Sometimes, this needs to be suppressed. Add this callback and no errors will show.
ex: whoAmI call executed during app init. Don't want "we have no idea who you are" displayed as an error.
*/
suppressErrors : {
onSuccess : function(_rtag) {
//dummy callback. do nothing.
},
onError : function(responseData,uuid) {
//dummy callback. do nothing.
_app.u.dump("CAUTION! response for uuid ["+uuid+"] contained errors but they were suppresed. This may be perfectly normal (passive requests) but should be investigated.");
}
} //suppressErrors
}, //callbacks
//////////////////////////////////// ROUTER \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
router : {
initRoutes : [], //get run once, at router init. allows for handling of URI vars et all.
hashRoutes : [], //an object, not an array. order is not required because route matches are implicit unless they define themselves otherwise.
aliases : {}, //functions executed by route.
initObj : {},
//proper way to add a route to the routes table. will have validation.
appendHash : function(obj) {return this._addInitOrHash('hash','append',obj);},
prependHash : function(obj) {return this._addInitOrHash('hash','prepend',obj);},
appendInit : function(obj) {return this._addInitOrHash('init','append',obj);},
prependInit : function(obj) {return this._addInitOrHash('init','prepend',obj);},
_addInitOrHash : function(mode,method,obj) {
var r = false; //what is returned.
obj = obj || {};
if((method == 'append' || method == 'prepend') && (mode == 'init' || mode == 'hash')) {
if(obj.type && obj.callback) { //route isn't validated against because a blank route is a valid route (homepage)
if(_app.router.matchFunctions[obj.type]) {
method == 'prepend' ? this[mode+'Routes'].unshift(obj) : this[mode+'Routes'].push(obj);
r = true;
}
else {
_app.u.dump("In _addInitOrHash, for route "+obj.route+" type was set as "+obj.type+" which is not valid","warn");
}
}
else {
_app.u.dump("In _addInitOrHash, type ["+obj.type+"] or route ["+obj.route+"] or callback [typeof: "+(typeof obj.callback)+"] was not defined and all are required.","warn");
}
}
else {
_app.u.dump("In _addInitOrHash, method ["+method+"] and/or mode ["+mode+"] either not specified or not valid.","warn");
}
return r;
},
//proper way to add an alias. will have validation.
addAlias : function(name,callback) {
if(name && callback) {
_app.router.aliases[name] = callback;
}
else {
// eithr name or callback not specified. ### TODO -> add error.
}
},
_buildMatchParams : function(route,hash,keysArr) {
var regex = new RegExp(/{{(.*?)}}/g), vars = {}, matchVarsArr = [], isMatch;
while(isMatch = regex.exec(route)) {matchVarsArr.push(isMatch[1]);} //isMatch[0] is the match value
if(matchVarsArr && matchVarsArr.length) {
for(var i = 0, L = matchVarsArr.length; i < L; i += 1) {
vars[matchVarsArr[i]] = keysArr[i];
}
}
return vars;
},
//The route type functions all get passed the same vars, routeObj and hash.
//the function should return false is the hash does not match the route.
//the function should return an object if a match is
matchFunctions : {
'exact' : function(routeObj,hash){
var r = false;
if(routeObj.route == hash) {
r = {'exact':hash};
}
return r;
},
'match' : function(routeObj,hash){
var r;
if(routeObj.route == '') {r = false; dump("routeobj.route was blank"); dump(routeObj);} //can't 'match' against blank.
else if(routeObj.route) {
var pattern = routeObj.route.replace(/{{(.*?)}}/g,'([^\\/]+)');
if(routeObj.route.charAt(routeObj.route.length - 1) == '*' ) {pattern += "(/\?.*)?";} //allows for wildcards to be set. so admin/ext/a?some=params can be declared w/ admin/{{ext}}/{{a}}*
var r = false, regex = new RegExp(pattern), isMatch = regex.exec(hash);
//regex.exec[0] will be the match value. so comparing that to the hash will ensure no substring matches get thru.
//substring matches can be accomplished w/ a regex in the route.
if(isMatch && isMatch[0] == hash) {
//IE8 requires the second param be passed into splice
r = {'match' : isMatch, 'params' : _app.router._buildMatchParams(routeObj.route,hash,isMatch.splice(1,isMatch.length - 1))}; //isMatch is spliced because the first val is the 'match value'.
}
}
else {
//unknown error.
dump("in matchFunctions.match, an unknown error occured based on the value of routeObj.route: "+routeObj.route); dump(routeObj);
r = false
}
return r;
},
'function' : function(routeObj,hash){
// ### TODO -> need to write this.
return routeObj.route(routeObj,hash);
},
'regexp' : function(routeObj,hash){
var regex = new RegExp(routeObj.route), r = false, isMatch = regex.exec(hash);
if(isMatch) {
r = {'regexp' : isMatch};
}
return r;
}
},
//compares an individual route in the routes array against the hash to check for a match.
//The matchFunction response and the routeObj are copied and returned.
_doesThisRouteMatchHash : function(routeObj,hash) {
var r = null;
routeObj = routeObj || {};
//don't test for .route here because it could be blank, and that's valid.
if(routeObj.type && typeof _app.router.matchFunctions[routeObj.type] == 'function') {
r = _app.router.matchFunctions[routeObj.type](routeObj,hash);
if(r) {
r = $.extend({},routeObj,r); //r last trumps whatever was in the routeObj. allows r to 'change' things.
}
}
else {
_app.u.dump("for route ["+routeObj.route+"], routeObj.type is not set ["+routeObj.type+"] OR typeof is not a function ["+(typeof _app.router.matchFunctions[routeObj.type])+"].","warn");
_app.u.dump(routeObj);
}
return r;
},
//Goes through the entire list of routes, in order.
//executes the match method (exact, function, regexp, etc) to see if hash is a match.
//once a match is found, processing is stopped, which means only 1 match per hash.
// -> may at some point enable stacking, but it'll be off by default.
_getRouteObj : function(matchValue,mode) {
var route = null, routesArr = _app.router[mode+'Routes'];
for(var i = 0,L = routesArr.length; i < L; i += 1) {
var isMatchArr = _app.router._doesThisRouteMatchHash(routesArr[i],matchValue); //will return an array where 0 is the 'match' from the regex and subsequent entries are the matched values. (ex: for product/PID , spot 1 is PID)
if(isMatchArr) {
route = isMatchArr;
if(mode == 'hash') break;
}
}
return route;
},
_executeCallback : function(routeObj) {
//if the callback is a string, then it should correspond to a handler.
if(routeObj.callback) {
if(typeof routeObj.callback === 'string') {
if(_app.router.aliases[routeObj.callback]) {
_app.router.aliases[routeObj.callback](routeObj,_app.router.initObj);
}
else {
//no matching handler found.
_app.u.dump("In _executeCallback, handler ["+routeObj.callback+"] specified does not exist.","warn");
}
}
else if(typeof routeObj.callback == 'function') {
routeObj.callback(routeObj,_app.router.initObj);
}
else {
_app.u.dump("In _execute handler, invalid type for routeObj.callback. typeof: "+(typeof routeObj.callback),"error");
//unrecognized type for calback.
}
}
else {} //no callback defined
},
//will return the URI params that appear BEFORE the hash or false if none are present.
getURIParams : function() {
var uriParams = false;
var ps = window.location.href.replace(location.hash,''); //only want the uri params before the hash.
if(ps.indexOf('?') >= 1) {
ps = ps.split('?')[1]; //ignore everything before the first questionmark.
if(ps.indexOf('#') == 0){} //'could' happen if uri is ...admin.html?#doSomething. no params, so do nothing.
else {
if(ps.indexOf('#') >= 1) {ps = ps.split('#')[0]} //uri params should be before the #
uriParams = {}
uriParams = _app.u.kvp2Array(ps);
}
}
return uriParams;
},
init : function() {
if($(document.body).data('isRouted')) {} //only allow the router to get initiated once.
else {
//initObj is a blank object by default, but may be updated outside this process. so instead of setting it to an object, it's extended to merge the two.
$.extend(_app.router.initObj,{
hash : location.hash,
uriParams : _app.router.getURIParams(),
hashParams : (location.hash.indexOf('?') >= 0 ? _app.u.kvp2Array(decodeURIComponent(location.hash.split("?")[1])) : {})
});
var routeObj = _app.router._getRouteObj(document.location.href,'init'); //strips out the #! and trailing slash, if present.
if(routeObj) {
_app.router._executeCallback(routeObj);
}
else {
_app.u.dump(" -> Uh Oh! no valid route found for "+location.hash);
//what to do here?
}
//this would get added at end of INIT. that way, init can modify the hash as needed w/out impacting.
if (window.addEventListener) {
dump(" -> addEventListener is supported and added for hash change.");
window.addEventListener("hashchange", _app.router.handleHashChange, false);
$(document.body).data('isRouted',true);
}
//IE 8
else if(window.attachEvent) {
//A little black magic here for IE8 due to a hash related bug in the browser.
//make sure a hash is set. Then set the hash to itself (yes, i know, but that part is key). Then wait a short period and add the hashChange event.
window.location.hash = window.location.hash || '#!home'; //solve an issue w/ the hash change reloading the page.
window.location.hash = window.location.hash;
setTimeout(function(){
window.attachEvent("onhashchange", _app.router.handleHashChange);
},1000);
$(document.body).data('isRouted',true);
}
else {
$("#globalMessaging").anymessage({"message":"Browser doesn't support addEventListener OR attachEvent.","gMessage":true});
}
}
},
handleHashChange : function() {
//_ignoreHashChange set to true to disable the router. be careful.
if(location.hash.indexOf('#!') == 0 && !_app.vars.ignoreHashChange) {
// ### TODO -> test this with hash params set by navigateTo. may need to uri encode what is after the hash.
// *** 201403 use .href.split instead of .hash for routing- Firefox automatically decodes the hash string, which breaks any URIComponent encoded characters, like "%2F" -> "/" -mc
// http://stackoverflow.com/questions/4835784/firefox-automatically-decoding-encoded-parameter-in-url-does-not-happen-in-ie
var routeObj = _app.router._getRouteObj(location.href.split('#!')[1],'hash'); //if we decide to strip trailing slash, use .replace(/\/$/, "")
if(routeObj) {
routeObj.hash = location.hash;
routeObj.hashParams = (location.hash.indexOf('?') >= 0 ? _app.u.kvp2Array(location.hash.split("?")[1]) : {});
window[_app.vars.analyticsPointer]('send', 'screenview', {'screenName' : routeObj.hash} );
_app.router._executeCallback(routeObj);
}
else {
_app.u.dump(" -> Uh Oh! no valid route found for "+location.hash);
if(typeof _app.router.aliases['404'] == 'function') {
_app.router._executeCallback({'callback':'404','hash':location.hash});
}
}
}
else {
if(_app.vars.ignoreHashChange) {_app.u.dump(" -> ignoreHashChange is true. Router is disabled.")}
else {_app.u.dump(" -> not a hashbang")}
//is not a hashbang. do nothing.
}
}
},
//////////////////////////////////// UTIL [u] \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\