/
pe-ap.js
1495 lines (1455 loc) · 53.9 KB
/
pe-ap.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
/*!
* Web Experience Toolkit (WET) / Boîte à outils de l'expérience Web (BOEW)
* www.tbs.gc.ca/ws-nw/wet-boew/terms / www.sct.gc.ca/ws-nw/wet-boew/conditions
*/
/*
* Dependencies for pe
* - desktop will more than likely be more intensive in terms of capabilities
* - mobile will be thinner
*/
/*
* pe, a progressive javascript library agnostic framework
*/
/*global ResizeEvents: false, jQuery: false, wet_boew_properties: false, wet_boew_theme: false, fdSlider: false, document: false, window: false, setTimeout: false, navigator: false, localStorage: false*/
(function ($) {
"use strict";
var pe, _pe;
/**
* pe object
* @namespace pe
* @version 3.0
*/
pe = (typeof window.pe !== 'undefined' && window.pe !== null) ? window.pe : {
fn: {}
};
_pe = {
/** Global object init properties */
/**
* @memberof pe
* @type {string} Page language, defaults to 'en' if not available
*/
language: ($('html').attr('lang').length > 0 ? $('html').attr('lang') : 'en'),
touchscreen: 'ontouchstart' in document.documentElement,
mobileview: (wet_boew_theme !== null && typeof wet_boew_theme.mobileview === 'function'),
suffix: $('body script[src*="/pe-ap-min.js"]').length > 0 ? '-min' : '', // determine if pe is minified
header: $('#wb-head'),
main: $('#wb-main'),
secnav: $('#wb-sec'),
footer: $('#wb-foot'),
urlpage: '',
urlhash: '',
urlquery: '',
svg: ($('<svg xmlns="http://www.w3.org/2000/svg" />').get(0).ownerSVGElement !== undefined),
document: $(document),
/**
* @memberof pe
* @type {number} - IE major number if browser is IE, 0 otherwise
*/
ie: (/(MSIE) ([\w.]+)/.exec(navigator.userAgent) || [])[2] || '0',
/**
* A private function for initializing for pe.
* @function
* @memberof pe
* @returns {void}
*/
_init: function () {
var hlinks, hlinks_same, hlinks_other, $this, url, target, init_on_mobileinit = false;
// Load polyfills that need to be loaded before anything else
pe.polyfills.init();
// Get the hash and query parameters from the URL
pe.urlpage = pe.url(window.location.href);
pe.urlhash = pe.urlpage.hash;
pe.urlquery = pe.urlpage.params;
// Identify whether or not the device supports JavaScript and has a touchscreen
$('html').removeClass('no-js').addClass(wet_boew_theme !== null ? wet_boew_theme.theme : '').addClass(pe.touchscreen ? 'touchscreen' : '');
hlinks = pe.main.find("a").filter(function () {
return this.href.indexOf('#') !== -1;
});
hlinks_other = hlinks.filter(function () {
return $(this).attr('href').indexOf('#') !== 0; // Other page links with hashes
});
hlinks_same = hlinks.filter(function () {
return $(this).attr('href').indexOf('#') === 0; // Same page links with hashes
});
// Is this a mobile device?
if (pe.mobilecheck()) {
pe.mobile = true;
$('body > div').attr('data-role', 'page').addClass('ui-page-active');
pe.document.on('mobileinit', function () {
$.extend($.mobile, {
ajaxEnabled: false,
pushStateEnabled: false,
autoInitializePage: (init_on_mobileinit ? true : false)
});
if (init_on_mobileinit) {
pe.mobilelang();
}
});
// Replace hash with ?hashtarget= for links to other pages
hlinks_other.each(function () {
var $this = $(this),
newurl,
urlparams,
urlparam;
url = pe.url($this.attr('href'));
urlparams = url.params;
if (($this.attr('data-replace-hash') === undefined && (url.hash.length > 0 && window.location.hostname === url.host)) || ($this.attr('data-replace-hash') !== undefined && $this.attr('data-replace-hash') === true)) {
newurl = url.path + '?';
for (urlparam in urlparams) { // Rebuild the query string
if (urlparams.hasOwnProperty(urlparam) && urlparam !== 'hashtarget') {
newurl += urlparam + '=' + urlparams[urlparam] + '&';
}
}
$this.attr('href', newurl + 'hashtarget=' + url.hash); // Append hashtarget to the query string
}
});
pe.document.on('pageinit', function () {
// On click, puts focus on and scrolls to the target of same page links
hlinks_same.off('click vclick').on('click vclick', function () {
$this = $($(this).attr("href").replace(/[.:]/, '\\$1'));
$this.filter(':not(a, button, input, textarea, select)').attr('tabindex', '-1');
if ($this.length > 0) {
$.mobile.silentScroll(pe.focus($this).offset().top);
}
});
// If hashtarget is in the query string then put focus on and scroll to the target
if (pe.urlquery.hashtarget !== undefined) {
target = pe.main.find('#' + pe.urlquery.hashtarget.replace(/[.:]/, '\\$1'));
target.filter(':not(a, button, input, textarea, select)').attr('tabindex', '-1');
if (target.length > 0) {
setTimeout(function () {
$.mobile.silentScroll(pe.focus(target).offset().top);
}, 0);
}
}
});
pe.add.css([pe.add.themecsslocation + 'jquery.mobile' + pe.suffix + '.css']);
pe.add._load([pe.add.liblocation + 'jquery.mobile/jquery.mobile.min.js']);
} else {
// On click, puts focus on the target of same page links (fix for browsers that don't do this automatically)
hlinks_same.on("click vclick", function () {
$this = $($(this).attr('href').replace(/[.:]/, '\\$1'));
$this.filter(':not(a, button, input, textarea, select)').attr('tabindex', '-1');
if ($this.length > 0) {
pe.focus($this);
}
});
// Puts focus on the target of a different page link with a hash (fix for browsers that don't do this automatically)
if (pe.urlhash.length > 0) {
$this = $(pe.urlhash.replace(/[.:]/, '\\$1'));
$this.filter(':not(a, button, input, textarea, select)').attr('tabindex', '-1');
if ($this.length > 0) {
pe.focus($this);
}
}
}
// Load ajax content
$.when.apply($, $.map($('*[data-ajax-replace], *[data-ajax-append]'), function (o) {
var $o = $(o),
replace = false,
url;
if ($o.attr('data-ajax-replace') !== undefined) {
replace = true;
url = $o.attr('data-ajax-replace');
} else if ($o.attr('data-ajax-append') !== undefined) {
url = $o.attr('data-ajax-append');
}
return $.get(url, function (data) {
if (replace) {
$o.empty();
}
$o.append($(data));
}, 'html');
})).always(function () {
// Wait for localisation and ajax content to load plugins
pe.document.one('languageloaded', function () {
// Check to see if PE enhancements should be disabled
if (pe.pedisable() === true) {
return false; // Disable PE enhancements
}
if (wet_boew_theme !== null) {
// Initialize the theme
wet_boew_theme.init();
//Load the mobile view
if (pe.mobile) {
pe.document.one('mobileviewloaded', function () {
if (typeof $.mobile !== 'undefined') {
pe.mobilelang();
$.mobile.initializePage();
} else {
init_on_mobileinit = true;
}
});
wet_boew_theme.mobileview();
}
} else if (pe.mobile) {
if (typeof $.mobile !== 'undefined') {
pe.mobilelang();
$.mobile.initializePage();
} else {
init_on_mobileinit = true;
}
}
pe.dance();
});
pe.add.language(pe.language);
});
},
/**
* Mobile identification
* @memberof pe
* @type {boolean} true if browser is not IE < 9 and browser window size is less than 767px wide.
*/
mobile: false,
mobilecheck: function () {
return (pe.mobileview && (screen.width < 768 || (window.innerWidth < 768 && (window.innerHeight === document.documentElement.clientHeight || window.outerWidth - window.innerWidth < 50))) && !(pe.ie > 0 && pe.ie < 9));
},
mobilelang: function () {
// Apply internationalization to jQuery Mobile
$.mobile.collapsible.prototype.options.expandCueText = pe.dic.get('%jqm-expand');
$.mobile.collapsible.prototype.options.collapseCueText = pe.dic.get('%jqm-collapse');
$.mobile.dialog.prototype.options.closeBtnText = pe.dic.get('%close');
$.mobile.page.prototype.options.backBtnText = pe.dic.get('%back');
$.mobile.textinput.prototype.options.clearSearchButtonText = pe.dic.get('%jqm-clear-search');
$.mobile.selectmenu.prototype.options.closeText = pe.dic.get('%close');
$.mobile.listview.prototype.options.filterPlaceholder = pe.dic.get('%jqm-filter');
},
/**
* The pe aware page query to append items to
* @memberof pe
* @function
* @return {jQuery object}
*/
pagecontainer: function () {
return $('#wb-body-sec-sup,#wb-body-sec,#wb-body').add('body').eq(0);
},
/**
* Initializes the Resize dependency, and attaches a given function to various resize events.
* @memberof pe
* @function
* @param {function} fn The function to run when a resize event fires.
* @return {void}
*/
resize: function (fn) {
ResizeEvents.initialise(); // ensure resize function initialized
ResizeEvents.eventElement.bind('x-text-resize x-zoom-resize x-window-resize', function () {
fn();
});
return;
},
/**
* URL swiss-army knife helper function for developers.
* @memberof pe
* @see pe.url
* @function pe.url(1)
* @param {string} uri A relative or absolute URL to manipulate.
*/
url: function (uri) {
var el = document.createElement('div'), a;
el.innerHTML = '<a href="' + uri + '">x</a>';
a = el.firstChild;
return {
/**
* @namespace pe.url
*/
/**
* The original URL converted to an absolute URL.
* @memberof pe.url
* @type {string}
*/
source: a.href,
/**
* The protocol of the URL. eg. http or https
* @memberof pe.url
* @type {string}
*/
protocol: a.protocol.replace(':', ''),
/**
* The full host name of the URL.
* @memberof pe.url
* @type {string}
* @example
* pe.url('http://www.canada.ca/index.html').host
* returns 'www.canada.ca'
*/
host: a.hostname,
/**
* The port of the URL.
* @memberof pe.url
* @type {string} If no port is specified, this will return "80".
*/
port: a.port === '0' ? '80' : a.port,
/**
* The query string part of the URL.
* @memberof pe.url
* @type {string}
* @see #params
* @example
* pe.url('http://www.canada.ca?a=1&b=2').query
* returns '?a=1&b=2'
*/
query: a.search,
/**
* A collection of the parameters of the query string part of the URL.
* @memberof pe.url
* @type {object (key/value map of strings)}
* @see #query
* @example
* pe.url('http://www.canada.ca?a=1&b=2').params
* returns
* {
* a: '1',
* b: '2'
* }
*/
params: (function () {
var key, ret, s, seg, _i, _len;
ret = {};
seg = a.search.replace(/^\?/, '').split('&');
for (_i = 0, _len = seg.length; _i < _len; _i += 1) {
key = seg[_i];
if (key) {
s = key.split('=');
ret[s[0]] = s[1];
}
}
return ret;
}
()),
/**
* The file name, if any, of the URL.
* @memberof pe.url
* @type {string}
* @example
* pe.url('http://www.canada.gc.ca/aboutcanada-ausujetcanada/hist/menu-eng.html').file
* returns 'menu-eng.html'
*/
file: a.pathname.match(/\/([^\/?#]+)$/i) ? a.pathname.match(/\/([^\/?#]+)$/i)[1] : '',
/**
* The anchor of the URL.
* @memberof pe.url
* @type {string}
* @example
* pe.url('http://www.canada.ca#wb-main-in').hash
* returns 'wb-main-in'
*/
hash: a.hash.replace('#', ''),
/**
* The path of the URL.
* @memberof pe.url
* @type {string}
* @example
* pe.url('http://www.canada.gc.ca/aboutcanada-ausujetcanada/hist/menu-eng.html').path
* returns '/aboutcanada-ausujetcanada/hist/menu-eng.html'
*/
path: a.pathname.replace(/^([^\/])/, '/$1'),
/**
* The relative path of the URL.
* @memberof pe.url
* @type {string}
* @example
* pe.url('http://www.canada.gc.ca/aboutcanada-ausujetcanada/hist/menu-eng.html').relative
* returns '/aboutcanada-ausujetcanada/hist/menu-eng.html'
*/
relative: a.href.match(/tps?:\/\/[^\/]+(.+)/) ? a.href.match(/tps?:\/\/[^\/]+(.+)/)[1] : '',
/**
* The path of the URL broken up into an array.
* @memberof pe.url
* @type {string[]}
* @example
* pe.url('http://www.canada.gc.ca/aboutcanada-ausujetcanada/hist/menu-eng.html').segments
* returns ['aboutcanada-ausujetcanada', 'hist', 'menu-eng.html']
*/
segments: a.pathname.replace(/^\//, '').split('/'),
/**
* The URL minus the anchor.
* @memberof pe.url
* @type {string}
* @function
* @example
* pe.url('http://www.canada.gc.ca/aboutcanada-ausujetcanada/hist/menu-eng.html#wb-main-in').removehash()
* returns 'http://www.canada.gc.ca/aboutcanada-ausujetcanada/hist/menu-eng.html'
* pe.url( pe.url('http://www.canada.gc.ca/aboutcanada-ausujetcanada/hist/menu-eng.html#wb-main-in').removehash() ).relative
* returns '/aboutcanada-ausujetcanada/hist/menu-eng.html'
*/
removehash: function () {
return this.source.replace(/#([A-Za-z0-9\-_=&]+.:)/, '');
}
};
},
/**
* @memberof pe
* @function
* @return {boolean}
*/
cssenabled: function () {
return $('link').get(0).disabled;
},
/**
* Returns a class-based set limit on plugin instances
* @memberof pe
* @function
* @param {DOM object} elm The element to search for a class of the form blimit-5
* @return {number} 0 if none found, which means the plugin default
*/
limit: function (elm) {
var count;
count = $(elm).attr('class').match(/\blimit-\d+/);
if (!count) {
return 0;
}
return Number(count[0].replace(/limit-/i, ''));
},
/**
* A generic function to focus elements in the DOM in a screen reader compatible way / selector or object.
* @memberof pe
* @function
* @param {jQuery object | DOM object} elm The element to recieve focus.
* @return {jQuery object | DOM object} elm For chainability.
*/
focus: function (elm) {
setTimeout(function () {
return (typeof elm.jquery !== 'undefined' ? elm.focus() : $(elm).focus());
}, 0);
return elm;
},
/**
* @namespace pe.string
*/
string: {
/*
@returns: modified text with htmlified text into a HTML links ( mailto, anchors, etc )
@credits: Dustin Diaz | http://www.dustindiaz.com/basement/ify.html
@license: public BSD
*/
ify: (function () {
return {
'link': function (t) {
return t.replace(/[a-z]+:\/\/[a-z0-9\-_]+\.[a-z0-9\-_@:~%&\?\+#\/.=]+[^:\.,\)\s*$]/ig, function (m) {
return '<a href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
});
},
'at': function (t) {
return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15}(\/[a-zA-Z0-9\-_]+)*)/g, function (m, m1, m2) {
return m1 + '@<a href="http://twitter.com/' + m2 + '">' + m2 + '</a>';
});
},
'hash': function (t) {
return t.replace(/(^|[^&\w'"]+)\#([a-zA-Z0-9_]+)/g, function (m, m1, m2) {
return m1 + '#<a href="http://search.twitter.com/search?q=%23' + m2 + '">' + m2 + '</a>';
});
},
/**
* Formats tweets for display on a webpage. Adds markup for links in the tweet. Adds markup for user names (@). Adds markup for topics (#).
* @memberof pe.string
* @function ify.clean
* @param {string} tweet The tweet to format.
* @return {string}
* @example
* pe.string.ify.clean('@ded the cdn url is http://cdn.enderjs.com')
* returns '@<a href="http://twitter.com/ded">ded</a> the cdn url is <a href="http://cdn.enderjs.com">http://cdn.enderjs.com</a>'
* ie. '@<a href="http://twitter.com/ded">ded</a> the cdn url is <a href="http://cdn.enderjs.com">http://cdn.enderjs.com</a>'
*/
'clean': function (tweet) {
return this.hash(this.at(this.link(tweet)));
}
};
}
()),
/**
* Left-pads a number with zeros.
* @memberof pe.string
* @function
* @param {number} number The original number to pad.
* @param {number} length The width of the resulting padded number, not the number of zeros to add to the front of the string.
* @return {string} The padded string
*/
pad: function (number, length) {
var str;
str = String(number);
while (str.length < length) {
str = '0' + str;
}
return str;
}
},
/**
* @namespace pe.array
*/
array: {
/**
* Eliminates duplicate strings in an array
* @memberof pe.sarray
* @function
* @param {array} arr Array of strings or primitives
* @return {array} Array with duplicate strings or primitives removed
*/
noduplicates: function (arr) {
var i,
_ilen,
j,
out = [],
obj = {};
for (i = 0, _ilen = arr.length; i !== _ilen; i += 1) {
obj[arr[i]] = 0;
}
for (j in obj) {
if (obj.hasOwnProperty(j)) {
out.push(j);
}
}
return out;
},
/**
* Creates a new string array with the differences between two other string arrays
* @memberof pe.array
* @function
* @param {array} arr1 Array of strings
* @param {array} arr2 Array of strings
* @return {array} Array with differences between arr1 and arr2
*/
diff: function (arr1, arr2) {
var i,
_ilen,
_iarr,
j,
_jlen,
match,
out = [];
for (i = 0, _ilen = arr1.length; i !== _ilen; i += 1) {
_iarr = arr1[i];
match = false;
for (j = 0, _jlen = arr2.length; j !== _jlen; j += 1) {
if (arr2[j] === _iarr) {
match = true;
break;
}
}
if (!match) {
out.push(_iarr);
}
}
},
/**
* Returns the keys in an associative array
* @memberof pe.array
* @function
* @param {object} obj The associative array
* @return {array} Keys of the associative array
*/
keys: function (obj) {
var keys = [];
$.each(obj, function (key) {
keys.push(key);
});
return keys;
}
},
/**
* A suite of date related functions for easier parsing of dates
* @namespace pe.date
*/
date: {
/**
* Converts the date to a date-object. The input can be:
* <ul>
* <li>a Date object: returned without modification.</li>
* <li>an array: Interpreted as [year,month,day]. NOTE: month is 0-11.</li>
* <li>a number: Interpreted as number of milliseconds since 1 Jan 1970 (a timestamp).</li>
* <li>a string: Any format supported by the javascript engine, like 'YYYY/MM/DD', 'MM/DD/YYYY', 'Jan 31 2009' etc.</li>
* <li>an object: Interpreted as an object with year, month and date attributes. **NOTE** month is 0-11.</li>
* </ul>
* @memberof pe.date
* @function
* @param {Date | number[] | number | string | object} d
* @return {Date | NaN}
*/
convert: function (d) {
if (d.constructor === Date) {
return d;
}
if (d.constructor === Array) {
return new Date(d[0], d[1], d[2]);
}
if (d.constructor === Number) {
return new Date(d);
}
if (d.constructor === String) {
return new Date(d);
}
if (typeof d === 'object') {
return new Date(d.year, d.month, d.date);
}
return NaN;
},
/**
* Compares two dates (input can be any type supported by the convert function). NOTE: This function uses pe.date.isFinite, and the code inside isFinite does an assignment (=).
* @memberof pe.date
* @function
* @param {Date | number[] | number | string | object} a
* @param {Date | number[] | number | string | object} b
* @return {number | NaN}
* @example returns
* -1 if a < b
* 0 if a = b
* 1 if a > b
* NaN if a or b is an illegal date
*/
compare: function (a, b) {
if (isFinite(a = this.convert(a).valueOf()) && isFinite(b = this.convert(b).valueOf())) {
return (a > b) - (a < b);
}
return NaN;
},
/**
* Checks if date in d is between dates in start and end. NOTE: This function uses pe.date.isFinite, and the code inside isFinite does an assignment (=).
* @memberof pe.date
* @function
* @param {Date | number[] | number | string | object} d
* @param {Date | number[] | number | string | object} start
* @param {Date | number[] | number | string | object} end
* @return {boolean | NaN}
*/
in_range: function (d, start, end) {
if (isFinite(d = this.convert(d).valueOf()) && isFinite(start = this.convert(start).valueOf()) && isFinite(end = this.convert(end).valueOf())) {
return start <= d && d <= end;
}
return NaN;
},
/**
* Cross-browser safe way of translating a date to iso format
* @memberof pe.date
* @function
* @param {Date | number[] | number | string | object} d
* @param {boolean} timepresent Optional. Whether to include the time in the result, or just the date. False if blank.
* @return {string}
* @example
* pe.date.to_iso_format(new Date())
* returns '2012-04-27'
* pe.date.to_iso_format(new Date(), true)
* returns '2012-04-27 13:46'
*/
to_iso_format: function (d, timepresent) {
var date;
date = this.convert(d);
if (timepresent) {
return date.getFullYear() + '-' + pe.string.pad(date.getMonth() + 1, 2, '0') + '-' + pe.string.pad(date.getDate(), 2, '0') + ' ' + pe.string.pad(date.getHours(), 2, '0') + ':' + pe.string.pad(date.getMinutes(), 2, '0');
}
return date.getFullYear() + '-' + pe.string.pad(date.getMonth() + 1, 2, "0") + '-' + pe.string.pad(date.getDate(), 2, '0');
}
},
/**
* A generic function for enabling/disabling PE enhancements
* @memberof pe
* @function
* @return true if PE enhancements should be disabled, false if should be enabled
*/
pedisable: function () {
// Prevent PE from loading if IE6 or ealier (unless overriden) or pedisable=true is in the query string or localStorage
var lsenabled = (typeof localStorage !== 'undefined'),
disablels = (lsenabled ? localStorage.getItem('pedisable') : null),
disable = (pe.urlquery.pedisable !== undefined ? pe.urlquery.pedisable : disablels),
tphp = document.getElementById('wb-tphp'),
li = document.createElement('li'),
qparams = pe.urlquery,
qparam,
newquery = '?';
for (qparam in qparams) { // Rebuild the query string
if (qparams.hasOwnProperty(qparam) && qparam !== 'pedisable') {
newquery += qparam + '=' + qparams[qparam] + '&';
}
}
if ((pe.ie > 0 && pe.ie < 7 && disable !== "false") || disable === "true") {
$('html').addClass('no-js pe-disable');
if (lsenabled) {
localStorage.setItem('pedisable', 'true'); // Set PE to be disable in localStorage
}
li.innerHTML = '<a href="' + newquery + 'pedisable=false">' + pe.dic.get('%pe-enable') + '</a>';
tphp.appendChild(li); // Add link to re-enable PE
return true;
} else if (disable === "false" || disablels !== null) {
if (lsenabled) {
localStorage.setItem('pedisable', 'false'); // Set PE to be enabled in localStorage
}
}
li.innerHTML = '<a href="' + newquery + 'pedisable=true">' + pe.dic.get('%pe-disable') + '</a>';
tphp.appendChild(li); // Add link to disable PE
return false;
},
/**
* A suite of menu related functions for easier handling of menus
* @namespace pe.menu
*/
menu: {
/**
* Applies a specific class to the current link/section in a menu based on the current URL or the links in a breadcrumb trail.
* @memberof pe.menu
* @param {jQuery object | DOM object} menusrc Menu to apply the class to
* @param {jQuery object | DOM object} bc Breadcrumb trail
* @param {string} navclass Optional. Class to apply. Defaults to "nav-current".
* @function
* @return {jQuery object} Link where match found
*/
navcurrent: function (menusrc, bcsrc, navclass) {
var navlink,
navurl,
navtext,
i,
_len,
pageurl = pe.url(window.location.href).removehash(),
bcurl = [],
bctext = [],
match;
menusrc = (typeof menusrc.jquery !== 'undefined' ? menusrc : $(menusrc));
bcsrc = $((typeof bcsrc.jquery !== 'undefined' ? bcsrc : $(bcsrc)).find('a').get().reverse());
navclass = (typeof navclass === 'undefined') ? 'nav-current' : navclass;
// Retrieve the path and link text for each breacrumb link
bcsrc.each(function (index) {
var $this = $(this);
bcurl[index] = $this.attr('href');
bctext[index] = $this.text();
});
$(menusrc.find('a').get().reverse()).each(function () {
navlink = $(this);
navurl = navlink.attr('href');
navtext = navlink.text();
match = (pageurl.indexOf(navurl) !== -1);
for (i = 0, _len = bcurl.length; !match && i !== _len; i += 1) {
if (bcurl[i] !== "#" && (bcurl[i] === navurl || bctext[i] === navtext)) {
match = true;
break;
}
}
if (match) {
navlink.addClass(navclass);
return false;
}
});
return (match ? navlink : $());
},
/**
* Builds jQuery Mobile nested accordion menus from an existing menu
* @memberof pe.menu
* @param {jQuery object | DOM object} menusrc Existing menu to process
* @param {number} hlevel Heading level to process (e.g., h3 = 3)
* @param {string} theme Letter representing the jQuery Mobile theme
* @param {boolean} menubar Optional. Is the heading level to process in a menu bar? Defaults to false.
* @function
* @return {jQuery object} Mobile menu
*/
buildmobile: function (menusrc, hlevel, theme, mbar, expandall) {
var menu = $('<div data-role="controlgroup"></div>'),
heading = 'h' + hlevel,
headingOpen = '<' + heading + '>',
headingClose = '</' + heading + '>',
menuitems = (typeof menusrc.jquery !== 'undefined' ? menusrc : $(menusrc)).find('> div, > ul, ' + heading),
next,
subsection,
hlink,
nested,
hasHeading,
menubar = (mbar !== undefined ? mbar : false),
expand = (expandall !== undefined ? expandall : false),
mainText = pe.dic.get('%main-page'),
collapsibleSet = '<div data-role="collapsible-set" data-theme="' + theme + '"></div>',
listView = '<ul data-role="listview" data-theme="' + theme + '"></ul>';
if (menuitems.get(0).tagName.toLowerCase() === 'ul') {
menu.append($(listView).append(menuitems.first().children('li')));
} else {
hasHeading = menuitems.filter(heading).length !== 0;
menuitems.each(function () {
var $this = $(this),
tagName = this.tagName.toLowerCase();
// If the menu item is a heading
if (tagName === heading) {
hlink = $this.children('a');
subsection = $('<div data-role="collapsible"' + (expand || hlink.hasClass('nav-current') ? ' data-collapsed="false"' : '') + '>' + headingOpen + $this.text() + headingClose + '</div>');
next = $this.next();
if (next.get(0).tagName.toLowerCase() === 'ul') {
// The original menu item was not in a menu bar
if (!menubar) {
next.append($('<li></li>').append($this.children('a').html(hlink[0].innerHTML + ' - ' + mainText)));
}
nested = next.find('li ul');
// If a nested list is detected
nested.each(function (index) {
var $this = $(this),
hlink_html,
headingIndexOpen = '<h' + (hlevel + 1 + index) + '>',
headingIndexClose = '</h' + (hlevel + 1 + index) + '>';
if ((hlevel + 1 + index) < 7) {
// Make the nested list into a collapsible section
hlink = $this.prev('a');
hlink_html = hlink[0].innerHTML;
$this.attr({ 'data-role': 'listview', 'data-theme': theme }).wrap('<div data-role="collapsible"' + (expand || hlink.hasClass('nav-current') ? ' data-collapsed="false"' : '') + '></div>');
$this.parent().prepend(headingIndexOpen + hlink_html + headingIndexClose);
$this.append('<li><a href="' + hlink.attr('href') + '">' + hlink_html + ' - ' + mainText + '</a></li>');
hlink.remove();
} else {
$this.attr({ 'data-role': 'listview', 'data-theme': theme });
}
});
subsection.append($(listView).append(next.children('li')));
subsection.find('ul').wrap('<div data-role="controlgroup">' + (nested.length > 0 ? collapsibleSet : '') + '</div>');
} else { // If the section contains sub-sections
if (menubar) {
subsection.append(pe.menu.buildmobile($this.parent().find('.mb-sm'), hlevel + 1, theme, false, expand));
} else {
subsection.append(pe.menu.buildmobile($this.parent(), hlevel + 1, theme, false, expand));
}
// If the original menu item was not in a menu bar
if (!menubar) {
subsection.find('div[data-role="collapsible-set"]').eq(0).append($this.children('a').html(hlink[0].innerHTML + ' - ' + mainText).attr({'data-role': 'button', 'data-theme': theme, 'data-icon': 'arrow-r', 'data-iconpos': 'right'}));
}
}
menu.append(subsection);
} else if (tagName === 'div') { // If the menu item is a div
next = $this.children('a, ul');
if (next.length > 0) {
if (next.get(0).tagName.toLowerCase() === 'a') {
if (hasHeading) {
menu.append('<a href="' + next.attr('href') + '" data-role="button" data-theme="' + theme + '" data-icon="arrow-r" data-iconpos="right">' + next.html() + '</a>');
} else {
menu.append('<ul data-role="listview" data-theme="' + theme + '"><li><a href="' + next.attr('href') + '">' + next.html() + '</a></li></ul>');
}
} else {
menu.append($this.children('ul').attr({ 'data-role': 'listview', 'data-theme': theme }));
}
}
}
});
menu.children().wrapAll(collapsibleSet);
}
return menu;
},
/**
* Closes collapsible menus built by pe.menu.mobile that have a descendant matching the selector
* @memberof pe.menu
* @param {jQuery object | DOM object} menusrc Mobile menu to correct
* @param {string} selector Selector for the link(s) to expand/collapse.
* @param {boolean} expand Expand (true) or collapse (false) the selected collapsible menus.
* @param {boolean} allparents Expand/collapse all ancestor collapsible menus (true) or just the nearest parent (false).
* @function
* @return {void} Mobile menu
*/
expandcollapsemobile: function (menusrc, selector, expand, allparents) {
var elm = $((typeof menusrc.jquery !== 'undefined' ? menusrc : $(menusrc))).find(selector);
if (allparents) {
elm.parents('div[data-role="collapsible"]').attr('data-collapsed', expand);
} else {
elm.closest('div[data-role="collapsible"]').attr('data-collapsed', expand);
}
},
/**
* Correct the corners for each sections and sub-section in the menu build by pe.menu.buildmobile
* @memberof pe.menu
* @param {jQuery object | DOM object} menusrc Mobile menu to correct
* @function
* @return {void}
*/
correctmobile: function (menusrc) {
var original = (typeof menusrc.jquery !== 'undefined' ? menusrc : $(menusrc)),
parent = original.parent();
original.detach().find('.ui-collapsible-set').each(function () {
var $this = $(this);
if ($this.find('> ul .ui-collapsible').length > 0) {
$this = $this.children('ul');
}
$this.children().each(function () {
var $this = $(this),
target = (this.tagName.toLowerCase() === 'a' ? $this : $this.find('a').first());
if ($this.prev().length > 0) {
target.removeClass('ui-corner-top');
} else {
target.addClass('ui-corner-top');
}
if ($this.next().length > 0) {
target.removeClass('ui-corner-bottom');
} else {
target.addClass('ui-corner-bottom');
}
});
});
original.appendTo(parent);
}
},
/**
* Functions for loading required polyfills
* @memberof pe
* @function
* @return {void}
*/
polyfills: {
/**
* Polyfills to be loaded before everything else (pre-kill switch)
* @memberof pe.polyfills
*/
init: function () {
// localstorage
var lib = pe.add.liblocation;
if (!window.localStorage) {
pe.add._load(lib + 'polyfills/localstorage' + pe.suffix + '.js', 'localstorage-loaded');
$('html').addClass('polyfill-localstorage');
} else {
$('html').addClass('localstorage');
}
},
/**
* Determines which polyfills need to be loaded then loads them if they don't have dependencies
* Polyfills with dependencies are passed in the msg event's event.payload[0] and polyfills that need to be initalized are passed in event.payload[1]
* @memberof pe.polyfills
* @param {array} force Array of polyfills to force loading for if native support does not exist (because required by plugins to be loaded)
* @param {string} msg Message to inclue in the event that is triggered when the non-dependency polyfills are loaded
* @function
*/
polyload: function (force, msg, checkdom) {
var polyfills = this.polyfill,
polyname,
polyprefs,
elms,
polydep = {},
loadnow = [],
deps,
dep_paths,
dep_needed,
lib = pe.add.liblocation,
payload = [],
needsinit = [],
js = [],
i,
_len;
// Process each polyfill
for (polyname in polyfills) {
if (polyfills.hasOwnProperty(polyname)) {
polyprefs = polyfills[polyname];
elms = checkdom ? $(polyprefs.selector) : $();
// Check to see if the polyfill might be needed
if (elms.length !== 0 || $.inArray(polyname, force) !== -1) {
if (typeof polyprefs.supported === 'undefined') { // Native support hasn't been checked yet
polyprefs.supported = (typeof polyprefs.support_check === 'function' ? polyprefs.support_check() : polyprefs.support_check);
// Check to see if there is native support
if (!polyprefs.supported) { // No native support
deps = polyprefs.depends;
if (typeof deps !== 'undefined') { // Polyfill has dependencies
// Check to see if dependencies are already loaded
dep_paths = pe.add.depends(deps);
dep_needed = [];
for (i = 0, _len = deps.length; i !== _len; i += 1) {
if ($.inArray(deps[i], pe.add.staged) === -1) {
dep_needed.push(deps[i]);
}
}
if (dep_needed.length !== 0) {
// Polyfill is needed but has unloaded dependencies so load later
polydep[polyname] = dep_needed;
} else {
// Polyfill is needed and all dependencies are loaded so load now
loadnow.push(polyname);
}
} else { // Polyfill has no dependencies
// Polyfill is needed and has no dependencies so load now
loadnow.push(polyname);
}
$('html').addClass('polyfill-' + polyname);
elms.addClass('polyfill'); // Add the 'polyfill' class to each element to be affected by the polyfill
} else { // Native support
$('html').addClass(polyname);
}
} else if (!polyprefs.supported && typeof polyprefs.loaded === 'undefined') { // No native support and polyfill hasn't been loaded yet
// Polyfill is needed and hasn't been loaded yet (any dependencies assumed to be taken care of already since at least second time through)
loadnow.push(polyname);
}
}
}
}
for (i = 0, _len = loadnow.length; i !== _len; i += 1) {
polyprefs = polyfills[loadnow[i]];
js[js.length] = (typeof polyprefs.load !== 'undefined' ? polyprefs.load : lib + 'polyfills/' + loadnow[i] + pe.suffix + '.js');
if (typeof polyprefs.init !== 'undefined') {
needsinit.push(loadnow[i]);
}
polyprefs.loaded = true;
}
// Push the polydep object and needsinit array into payload
payload.push(polydep);
payload.push(needsinit);
// Load the polyfill scripts
pe.add._load_arr(js, msg, payload);
},