-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.js.download
1648 lines (1435 loc) · 60 KB
/
common.js.download
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
/*
* (c) Copyright 2005-2013 PaperCut Software International Pty. Ltd.
*/
/* Modernizr 2.6.1 (Custom Build) | MIT & BSD
* Build: http://modernizr.com/download/#-inlinesvg-shiv-cssclasses-prefixed-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes
*/
;window.Modernizr=function(a,b,c){function B(a){j.cssText=a}function C(a,b){return B(m.join(a+";")+(b||""))}function D(a,b){return typeof a===b}function E(a,b){return!!~(""+a).indexOf(b)}function F(a,b){for(var d in a){var e=a[d];if(!E(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function G(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:D(f,"function")?f.bind(d||b):f}return!1}function H(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+o.join(d+" ")+d).split(" ");return D(b,"string")||D(b,"undefined")?F(e,b):(e=(a+" "+p.join(d+" ")+d).split(" "),G(e,b,c))}var d="2.6.1",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n="Webkit Moz O ms",o=n.split(" "),p=n.toLowerCase().split(" "),q={svg:"http://www.w3.org/2000/svg"},r={},s={},t={},u=[],v=u.slice,w,x=function(a,c,d,e){var f,i,j,k=b.createElement("div"),l=b.body,m=l?l:b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),k.appendChild(j);return f=["­",'<style id="s',h,'">',a,"</style>"].join(""),k.id=h,(l?k:m).innerHTML+=f,m.appendChild(k),l||(m.style.background="",g.appendChild(m)),i=c(k,a),l?k.parentNode.removeChild(k):m.parentNode.removeChild(m),!!i},y=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=D(e[d],"function"),D(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),z={}.hasOwnProperty,A;!D(z,"undefined")&&!D(z.call,"undefined")?A=function(a,b){return z.call(a,b)}:A=function(a,b){return b in a&&D(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=v.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(v.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(v.call(arguments)))};return e}),r.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="<svg/>",(a.firstChild&&a.firstChild.namespaceURI)==q.svg};for(var I in r)A(r,I)&&(w=I.toLowerCase(),e[w]=r[I](),u.push((e[w]?"":"no-")+w));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)A(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},B(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^<|^(?:a|b|button|code|div|fieldset|form|h1|h2|h3|h4|h5|h6|i|iframe|img|input|label|li|link|ol|option|p|param|q|script|select|span|strong|style|table|tbody|td|textarea|tfoot|th|thead|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=m,e._domPrefixes=p,e._cssomPrefixes=o,e.hasEvent=y,e.testProp=function(a){return F([a])},e.testAllProps=H,e.testStyles=x,e.prefixed=function(a,b,c){return b?H(a,b,c):H(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+u.join(" "):""),e}(this,this.document);
/*!
* jQuery imagesLoaded plugin v2.1.1
* http://github.com/desandro/imagesloaded
*
* MIT License. by Paul Irish et al.
*/
(function(c,q){var m="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";c.fn.imagesLoaded=function(f){function n(){var b=c(j),a=c(h);d&&(h.length?d.reject(e,b,a):d.resolve(e));c.isFunction(f)&&f.call(g,e,b,a)}function p(b){k(b.target,"error"===b.type)}function k(b,a){b.src===m||-1!==c.inArray(b,l)||(l.push(b),a?h.push(b):j.push(b),c.data(b,"imagesLoaded",{isBroken:a,src:b.src}),r&&d.notifyWith(c(b),[a,e,c(j),c(h)]),e.length===l.length&&(setTimeout(n),e.unbind(".imagesLoaded",
p)))}var g=this,d=c.isFunction(c.Deferred)?c.Deferred():0,r=c.isFunction(d.notify),e=g.find("img").add(g.filter("img")),l=[],j=[],h=[];c.isPlainObject(f)&&c.each(f,function(b,a){if("callback"===b)f=a;else if(d)d[b](a)});e.length?e.bind("load.imagesLoaded error.imagesLoaded",p).each(function(b,a){var d=a.src,e=c.data(a,"imagesLoaded");if(e&&e.src===d)k(a,e.isBroken);else if(a.complete&&a.naturalWidth!==q)k(a,0===a.naturalWidth||0===a.naturalHeight);else if(a.readyState||a.complete)a.src=m,a.src=d}):
n();return d?d.promise(g):g}})(jQuery);
/* Masonry library overrides imagesLoaded, so we'll use our own handle. */
$.fn.pcImagesLoaded = $.fn.imagesLoaded;
/* Add CSRF protection token to AJAX requests. */
$(function() {
var absoluteUrl = new RegExp('^(?:[a-z]+:)?//', 'i');
if (window.csrfToken) {
$.ajaxSetup({
beforeSend: function(jqXhr) {
var sendToken = false;
if (absoluteUrl.test(this.url)) {
// absolute URL, only send token if the XHR is going to the page's server
var l = document.createElement('a');
l.href = this.url;
if (l.hostname == window.location.hostname && l.port == window.location.port) {
sendToken = true;
}
} else {
// relative URL, can send
sendToken = true;
}
if (sendToken) {
jqXhr.setRequestHeader('X-CSRF-Token', csrfToken);
}
}
});
}
});
/* Whenever forms submit, disable all submit buttons to avoid double presses */
$(function () {
$("form").submit(function () {
if (this.target && this.target != '_self') {
/*
* Workaround for WebKit bug preventing a form submitting twice to the same action.
* https://bugs.webkit.org/show_bug.cgi?id=28633
*/
if ($.browser.webkit) {
/*
* Could test $.browser.version here if we knew which versions the bug affected.
* - confirmed on 533.2
* - NOT on 533.4 (Chrome 5)
*/
this.action += (this.action.indexOf('?') == -1 ? '?' : '&');
this.action += 't=' + new Date().getTime();
}
// Don't disable if opening in a new window.
return;
}
// Need to delay here so submit starts before we disable buttons, otherwise the pressed button is not sent to server!
setTimeout(function () {
$("input[type=submit]").attr("disabled", "true");
}, 10);
});
});
/* JS workaround for choosing the default submit button in a multi-submit form. */
$(function() {
$('input[type=submit].default-submit').each(function() {
var $submitButton = $(this);
$submitButton.closest('form').find('input[type!=submit], select').keypress(function(e) {
if (isKeypressEventEnterKey(e)) {
$submitButton.click();
return false;
}
});
});
});
// pagination link improvements
$(function() {
var jqPagination = $('.table-box span.pagination');
// unlinked arrows to icons (first page)
jqPagination.contents().filter(function() {
// text node containing "<<"
return (this.nodeType == 3) && (this.data.indexOf('<<') != -1);
}).replaceWith('<img class="icon16" src="/images/icons2/16x16/nav-gray-left2.png" /> <img class="icon16" src="/images/icons2/16x16/nav-gray-left.png" /> ');
// unlinked arrows to icons (last page)
jqPagination.contents().filter(function() {
// text node containing ">>"
return (this.nodeType == 3) && (this.data.indexOf('>>') != -1);
}).replaceWith(' <img class="icon16" src="/images/icons2/16x16/nav-gray-right.png" /> <img class="icon16" src="/images/icons2/16x16/nav-gray-right2.png" />');
jqPagination.children('a').each(function() {
if ($(this).text().indexOf('<<') != -1) $(this).contents().replaceWith('<img class="icon16" src="/images/icons2/16x16/nav-green-left2.png" />');
if ($(this).text().indexOf('<') != -1) $(this).contents().replaceWith('<img class="icon16" src="/images/icons2/16x16/nav-green-left.png" />');
if ($(this).text().indexOf('>>') != -1) $(this).contents().replaceWith('<img class="icon16" src="/images/icons2/16x16/nav-green-right2.png" />');
if ($(this).text().indexOf('>') != -1) $(this).contents().replaceWith('<img class="icon16" src="/images/icons2/16x16/nav-green-right.png" />');
});
// thi^H^H^Hmove outside the box
jqPagination.remove().insertBefore('.table-box');
// replicate below table
jqPagination.clone().appendTo('.table-box .table-footer td.pagination');
});
/* function for light box */
$(function() {
$('a[rel*=lightbox]').each(function() {
$(this).attr('title', $(this).children('img').attr('title'));
$(this).lightBox({
imageLoading: '/images/lightbox/loading.gif',
imageBtnClose: '/images/lightbox/close.gif',
imageBlank: '/images/lightbox/blank.gif',
fixedNavigation: true
});
});
});
/*
* Limit the length of textareas with the 'maxlenth' attribute by binding the MaxLength function to their onkeyup event.
*/
$(function() {
$('textarea[maxlength]').bind("keyup", function(e) {
MaxLength(this, $(this).attr('maxlength'));
});
});
function search(searchTerm, className) {
$("." + className + " div").each(function(){
var x = $(this).text();
if ($(this).text().toLowerCase().indexOf(searchTerm.toLowerCase()) >=0) {
$(this).show();
} else {
$(this).hide();
}
});
}
/*
* Browser specific hacks.
*/
$(function() {
if ($.browser.msie) {
/* IE6 */
if ($.browser.version.charAt(0) == '6') {
$('table.results th:last-child').addClass('last-child');
$('table.results td:first-child').addClass('first-child');
}
/* IE7 */
if ($.browser.version.charAt(0) == '7') {
$('table.results th:last-child').addClass('last-child');
}
}
});
$(function() {
if ($('').areYouSure && window.messages) {
$('.dirty-check').areYouSure({
'message': messages.dirtyFormWarning
});
}
});
// http://stackoverflow.com/a/7337485/31440
$.fn.outerHTML = function(arg) {
var ret;
// If no items in the collection, return
if (!this.length) {
return typeof arg == "undefined" ? this : null;
}
// Getter overload (no argument passed)
if (!arg) {
return this[0].outerHTML || (ret = this.wrap('<div>').parent().html(), this.unwrap(), ret);
}
// Setter overload
$.each(this, function (i, el) {
var fnRet,
pass = el,
inOrOut = el.outerHTML ? "outerHTML" : "innerHTML";
if (!el.outerHTML) {
el = $(el).wrap('<div>').parent()[0];
}
if (jQuery.isFunction(arg)) {
if ((fnRet = arg.call(pass, i, el[inOrOut])) !== false) {
el[inOrOut] = fnRet;
} else {
el[inOrOut] = arg;
}
if (!el.outerHTML) {
$(el).children().unwrap();
}
}
});
return this;
}
/**
* E.g.: format('Hello {0}', 'World')
*/
function format(template) {
var msg = template;
for (var i = 1; i < arguments.length; i++) {
msg = msg.replace('{' + (i - 1) + '}', arguments[i]);
}
return msg;
}
/**
* E.g. formatNav('Options', 'User/Group Sync') --> 'Options ▸ User/Group Sync'
*/
function formatNav() {
var msg = '';
for (var i = 0; i < arguments.length; i++) {
if (i > 0) {
msg += ' ▸ ';
}
msg += arguments[i];
}
return msg;
}
function formatWithTapestryLink(options) {
var textWithLink = format(options.textTemplate, options.tapestryLink.clone().css('display', '').outerHTML());
options.target.html(textWithLink);
}
/*
* Used to limit the typeable length of a text area.
* This should be called from the onKeyUp event.
*/
function MaxLength(field, maxlength) {
if ($(field).val().length > maxlength) {
$(field).val($(field).val().substring(0, maxlength));
}
}
var __animSpeed = "slow";
function isVisibleJQ(jq) {
if (jq.length > 0) {
return jq.get(0).style.display != "none";
} else {
return false;
}
}
function fadeIn(jq, animate) {
if (isVisibleJQ(jq)) {
return;
}
if (animate) {
jq.fadeIn(__animSpeed);
// HACK!!: On IE8 enabling the virtual queue on PrinterDetails won't display the settings (the fadeIn doesn't work).
// This hack forces the element to be displayed after the fadeIn().
jq.show();
} else {
jq.show();
}
}
function fadeOut(jq, animate) {
if (!isVisibleJQ(jq)) {
return;
}
if (animate) {
jq.fadeOut(__animSpeed);
} else {
jq.hide();
}
}
function show(jq, animate) {
if (isVisibleJQ(jq)) {
return;
}
if (animate) {
jq.show(__animSpeed);
} else {
jq.show();
}
}
function hide(jq, animate) {
if (!isVisibleJQ(jq)) {
return;
}
if (animate) {
jq.hide(__animSpeed);
} else {
jq.hide();
}
}
function fadeElement(el, display, animate) {
if (display) {
fadeIn($(el), animate);
} else {
fadeOut($(el), animate);
}
}
function showHideElement(el, display, animate) {
if (display) {
show($(el), animate);
} else {
hide($(el), animate);
}
}
function displayIfChecked(checkBoxId, blockId, animate, hideIfChecked) {
var checkBoxEl = document.getElementById(checkBoxId);
if (!checkBoxEl) {
return;
}
var block = document.getElementById(blockId);
if (!block) {
return;
}
var display = checkBoxEl.checked;
if (hideIfChecked) {
display = !display;
}
fadeElement(block, display, animate);
}
function enableIfChecked(checkBoxId, inputId) {
var chk = document.getElementById(checkBoxId);
if (!chk) {
return;
}
var input = document.getElementById(inputId);
if (!input) {
return;
}
input.disabled = !chk.checked;
}
/**
* Enable the input field if either of the checkboxes are checked.
* (i.e. disable if neither are checked)
*/
function enableIfEitherChecked(checkBox1Id, checkBox2Id, inputId) {
var chk1 = document.getElementById(checkBox1Id);
if (!chk1) {
return;
}
var chk2 = document.getElementById(checkBox2Id);
if (!chk2) {
return;
}
var input = document.getElementById(inputId);
if (!input) {
return;
}
input.disabled = (!chk1.checked && !chk2.checked);
}
/**
* Hides "block" when "checkbox" is disabled and vice versa.
*
* @param checkbox A checkbox (id, node or jQ)
* @param block The block to hide and show (id, node or jQ)
*/
function checkboxHideShow(checkbox, block) {
checkbox = jq(checkbox);
block = jq(block);
if (checkbox.length == 0 || block.length == 0) {
return;
}
// first time setup without animation
fadeElement(block[0], checkbox[0].checked, false);
// bind click event with animation
checkbox.click(function() {
fadeElement(block[0], checkbox[0].checked, true);
});
}
/**
* It selects all the inputs/checkboxes.
*
* @param currentElement The select all checkbox
* @param inputs All the check boxes that will be selected
*/
function selectAllClicked(currentElement, inputs) {
var selectAll = currentElement;
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = selectAll.checked;
}
}
/**
* It tests whether all the checkboxes have been selected or not.
* @param inputs All the checkboxes
* @param selectAllCheckbox The select all checkbox element.
*/
function testSelectAll(inputs, selectAllCheckbox) {
if (inputs.length == 1) {
return;
}
var allChecked = true;
for (var i = 0; i < (inputs.length); i++) {
if (!inputs[i].checked) {
allChecked = false;
break;
}
}
selectAllCheckbox.attr('checked', allChecked);
}
/**
* Shows "block" when "option" (HTML select option) is selected and hides it when deselected.
*
* @param option A select option (id, node or jQ)
* @param block The block to hide and show (id, node or jQ)
*/
function selectOptionHideShow(option, block) {
option = jq(option);
block = jq(block);
if (option.length == 0 || block.length == 0) {
return;
}
var select = option.parent();
// first time setup without animation
fadeElement(block[0], select.find('option:selected')[0] == option[0], false);
// bind change event with animation
select.change(function() {
fadeElement(block[0], select.find('option:selected')[0] == option[0], true);
});
}
/**
* Disables "input" when "checkbox" is disabled and vice versa.
*
* @param checkbox A checkbox (id, node or jQ)
* @param input The input to enable and disable (id, node or jQ)
*/
function checkboxEnableDisableInput(checkbox, input) {
checkbox = jq(checkbox);
input = jq(input);
if (checkbox.length == 0 || input.length == 0) {
return;
}
input[0].disabled = !checkbox[0].checked;
checkbox.click(function() {
input[0].disabled = !checkbox[0].checked;
});
}
/**
* Disables "input" when "radio" is disabled and vice versa.
*
* @param radio A radio button (id, node or jQ)
* @param input The input to enable and disable (id, node or jQ)
*/
function radioEnableDisableInput(radio, input) {
radio = jq(radio);
input = jq(input);
if (radio.length == 0 || input.length == 0) {
return;
}
// radio buttons don't issue change event on deselect, so we need to watch all buttons in the group
var $radioGroupInputs = $("input[type=radio][name='" + radio.attr('name') + "']")
input[0].disabled = !radio.is(':checked');
$radioGroupInputs.on('change', function() {
input[0].disabled = !radio.is(':checked');
});
}
function enlarge(divId) {
$("#" + divId).width("60%");
$('body').width($('body').width() + 200);
}
/**
* Convert "el" to a jQuery object. "el" may be an existing jQuery object (returns itself), a DOM node (returns the node
* wrapped in a jQuery object, or a DOM id (uses jQuery to look up and return by id).
*
* @param o An object.
* @return A jQuery object.
*/
function jq(o) {
if (o.jquery) {
return o;
} else if (typeof o === "string") {
return $('#' + o);
} else {
return $(o);
}
}
jQuery.fn.extend({
uploadProgress: function(options) {
var progressUpdate;
var $form = jQuery(this);
// default options
options = jQuery.extend({
$uploadButton: $('#upload'),
$progressDisplay: $('#upload-progress'),
success: function() {},
failed: function() {}
}, options);
var $iframe = $('<iframe id="upload-frame" name="upload-frame" src="about:blank" ' +
'style="width: 0; height: 0; border: none; overflow: hidden;"></iframe>');
// progress display table
options.$progressDisplay.hide().html('' +
'<table class="working">' +
' <tbody>' +
' <tr>' +
' <td class="working-1"> </td>' +
' <td class="working-2"> </td>' +
' <td class="working-3"> </td>' +
' <td class="working-4"> </td>' +
' <td class="working-5"> </td>' +
' <td class="working-6"> </td>' +
' <td class="working-7"> </td>' +
' </tr>' +
' </tbody>' +
'</table>' +
'<div class="percentage"></div>');
options.$progressDisplay.after($iframe);
options.$uploadButton.click(function() {
$form.submit(function() {
this.target = $iframe.attr('id');
this.action = options.uploadFormSubmitURL;
startUpdater('upload/' + options.uploadUID);
$iframe.load(function() {
options.success();
setTimeout(function() {
$iframe.remove();
}, 100);
});
});
});
return this;
function startUpdater(url) {
options.$progressDisplay.show();
working();
progressUpdate = setInterval(function() {
$.get(url, function(responseXML) {
var percentComplete = $('percent_complete', responseXML).text();
setProgress(percentComplete);
});
}, 3000);
}
function setProgress(percent) {
if (percent == null) {
working();
} else {
var $p = options.$progressDisplay.children('.percentage');
working(false);
var duration = (percent == 100) ? 'fast' : 3000;
$p.animate({width: percent + '%'}, {easing: 'linear', duration: duration});
if (percent == 100) {
clearTimeout(progressUpdate);
$p.addClass('done');
} else {
$p.removeClass('done');
}
}
}
function working(active) {
var $w = options.$progressDisplay.children('.working');
if (active == null) {
active = true;
}
if (active) {
options.$progressDisplay.children('.percentage').hide().css('width', '0');
$w.show().css('margin-left', '-85px');
$w.animate({ marginLeft: '300px' }, { easing: 'linear', duration: 3000 });
workingTimeout = setTimeout(function() { working() }, 3200);
} else {
clearTimeout(workingTimeout);
$w.stop().hide();
}
}
}
});
/**
* Return true if an DIVs text on overflow:auto has overflowed.
*/
function divHasOverflow(div) {
//allow 1 pixel diff before deciding that div has overflown
return div.scrollWidth > (div.clientWidth + 1) || div.scrollHeight > (div.clientHeight + 1);
};
/*
* jQuery plugin: Image preloader.
* Preloads all provided image arguments.
* Usage: $.preLoadImages('/path/to/image1.png', 'image2.png');
*/
(function($) {
var cache = [];
// Arguments are image paths relative to the current page.
$.preLoadImages = function() {
var args_len = arguments.length;
for (var i = args_len; i--;) {
var cacheImage = document.createElement('img');
cacheImage.src = arguments[i];
cache.push(cacheImage);
}
};
})(jQuery);
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
/**
* Format a number amount into a string. E.g. 1234.56 -> "$1,234.56".
*
* @param amount {Number} The cost as a number.
* @param currencyFormatSymbols {object} Symbols used to format the cost.
* @returns {String} The formatted cost.
*/
function formatCost(amount, currencyFormatSymbols) {
if (amount === null || amount === '' || isNaN(amount) || amount != parseFloat(amount)) {
// not a number
return '';
}
var isNegative = amount < 0;
// decimal places, remove sign
var formattedAmount = String(Math.abs(amount).toFixed(currencyFormatSymbols.numDecimalsCredit));
// XXX doesn't handle grouping chars
// decimal char
formattedAmount = formattedAmount.replace('.', currencyFormatSymbols.decimalSeparator);
// prefix and suffix
if (isNegative) {
formattedAmount = currencyFormatSymbols.negativePrefix + formattedAmount + currencyFormatSymbols.negativeSuffix;
} else {
formattedAmount = currencyFormatSymbols.positivePrefix + formattedAmount + currencyFormatSymbols.positiveSuffix;
}
return formattedAmount;
}
/**
* Parse a string representation of currency credit into a number. E.g. "$1,234.56" -> 1234.56.
*
* @param amountStr {String} The formatted amount to parse, e.g. "$1,234.56".
* @param currencyFormatSymbols {object} Symbols used to parse the currency.
* @returns {Number} The parsed number, or NaN if parsing failed.
*/
function parseCurrency(amountStr, currencyFormatSymbols) {
var isNegative = amountStr.indexOf(currencyFormatSymbols.negativePrefix) == 0;
amountStr = amountStr.replace(currencyFormatSymbols.groupingSeparator, '');
if (isNegative) {
amountStr = amountStr.replace(currencyFormatSymbols.negativePrefix, '');
amountStr = amountStr.replace(currencyFormatSymbols.negativeSuffix, '');
} else {
amountStr = amountStr.replace(currencyFormatSymbols.positivePrefix, '');
amountStr = amountStr.replace(currencyFormatSymbols.positiveSuffix, '');
}
amountStr = amountStr.replace(currencyFormatSymbols.decimalSeparator, '.');
amountStr = (isNegative ? '-' : '') + amountStr;
var amount = parseFloat(amountStr);
return amount;
}
/**
* @param e The keypress event.
* @returns {Boolean} True if this event indicates that the enter key was pressed.
*/
function isKeypressEventEnterKey(e) {
return (e.which && e.which == 13) || (e.keyCode && e.keyCode == 13);
}
/**
* jQuery plugin: extend a text input with username autocomplete.
*
* Usage:
* $('input#username').usernameAutocomplete(options);
* Options (all optional):
* maxHeight {Number}: the maximum height of the results box, in px.
* selected {function}: function called when a result is selected.
* Args: item - a dictionary with keys 'username', 'fullName'.
* Full example:
* $('input#username').usernameAutocomplete({
* maxHeight: 300,
* selected: function(item) {
* $('#full-name').text(item.fullName);
* }
* });
*/
jQuery.fn.extend({
usernameAutocomplete: function(options) {
if (this.length == 0) return this;
if (!options) options = {};
if (options.maxHeight) {
var css = 'overflow-x: hidden; overflow-y: scroll; ';
css += getMaxHeightCSS(options.maxHeight);
setGlobalCSS( { '.ui-autocomplete': css } );
}
this.attr('autocomplete', 'off');
this.autocomplete({
source: function(term, callback) {
var requestData = { t: term.term };
$.getJSON('/rpc/api/rest/internal/users', requestData, function(responseData) {
callback(responseData);
});
},
focus: function(event, ui) {
$(this).val(ui.item.username);
return false;
},
select: function(event, ui) {
$(this).val(ui.item.username);
if (options.selected) options.selected(ui.item);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
var usernameFormatted = highlightTerm(item.username, this.term);
var fullNameFormatted = highlightTerm(item.fullName, this.term);
var itemFormatted = '<div class="username">' + usernameFormatted + '</div><div class="full-name">'
+ fullNameFormatted + '</div>';
return $('<li></li>')
.data('item.autocomplete', item)
.append('<a>' + itemFormatted + '</a>')
.appendTo(ul);
};
return this;
function highlightTerm(item, term) {
return item.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)("
+ $.ui.autocomplete.escapeRegex(term)
+ ")(?![^<>]*>)(?![^&;]+;)", 'gi'
), '<strong>$1</strong>');
}
}
});
/**
* jQuery plugin: extend a text input with shared account autocomplete.
*
* Usage:
* $('input#shared-account').sharedAccountAutocomplete();
* With max height:
* $('input#username').sharedAccountAutocomplete({
* maxHeight: 300
* });
*/
jQuery.fn.extend({
sharedAccountAutocomplete: function(options) {
if (this.length == 0) return this;
if (!options) options = {};
if (options.maxHeight) {
var css = 'overflow-x: hidden; overflow-y: scroll; ';
css += getMaxHeightCSS(options.maxHeight);
setGlobalCSS( { '.ui-autocomplete': css } );
}
this.attr('autocomplete', 'off');
this.autocomplete({
source: function(term, callback) {
var requestData = { t: term.term };
$.getJSON('/rpc/api/rest/internal/shared-accounts', requestData, function(responseData) {
callback(responseData);
});
},
focus: function(event, ui) {
$(this).val(ui.item.name);
return false;
}, select: function(event, ui) {
$(this).val(ui.item.name);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
var nameFormatted = highlightTerm(item.name, this.term);
var itemFormatted = '<div class="shared-account-name">' + nameFormatted + '</div>';
return $('<li></li>')
.data('item.autocomplete', item)
.append('<a>' + itemFormatted + '</a>')
.appendTo(ul);
};
return this;
function highlightTerm(item, term) {
return item.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)("
+ $.ui.autocomplete.escapeRegex(term)
+ ")(?![^<>]*>)(?![^&;]+;)", 'gi'
), '<strong>$1</strong>');
}
}
});
/**
* Usage:
* setGlobalCSS( { selector: rule } );
* E.g.:
* setGlobalCSS( { 'p': 'color: #FFF' } );
*
* Calling multiple times with the same selector will result in the existing selector being replaced.
*
* @param css Map of CSS rules to add.
*/
function setGlobalCSS(css) {
if ($('head style[title=global]').length > 0) {
// sheet already exists
} else {
// create sheet
$('<style type="text/css" rel="stylesheet" media="screen" title="global" />').appendTo('head');
}
var styleSheet;
// get reference to sheet
// NOTE: can't use $.each on document.styleSheets in IE, see jQuery #4366: http://bugs.jquery.com/ticket/4366
for (var i = 0; i < document.styleSheets.length; i++) {
if ($(document.styleSheets[i]).attr('title') == 'global') {
styleSheet = document.styleSheets[i];
}
}
var cssRules = styleSheet.cssRules ? styleSheet.cssRules : styleSheet.rules;
var deleteRule = styleSheet.deleteRule ? function(index) {
styleSheet.deleteRule(index);
} : function(index) {
styleSheet.removeRule(index);
}
var insertRule = styleSheet.insertRule ? function(selector, rule, index) {
styleSheet.insertRule(selector + '{' + rule + ';}', 0);
} : function(selector, rule, index) {
styleSheet.addRule(selector, rule, index);
}
$.each(css, function(selector, rule) {
// remove existing selector
for (var i = 0; i < cssRules.length; i++){
if (cssRules[i].selectorText == selector) {
deleteRule(i);
}
}
insertRule(selector, rule, 0);
});
}
/**
* @param maxHeight {Number} The maximum height in pixels
* @return {String} Browser independent CSS value to apply maximum height.
*/
function getMaxHeightCSS(maxHeight) {
var css = 'max-height: ' + maxHeight + 'px;'
if ($.browser.msie) {
if ($.browser.version.charAt(0) == '6' || $.browser.version.charAt(0) == '7') {
// IE6,7 - use expression instead
css = 'height: expression( this.scrollHeight > ' + (maxHeight - 1) + ' ? "' + maxHeight + 'px" : "auto" );';
}
}
return css;
}
function createStatusMessage(cssClass, iconName, htmlMsg) {
return $('<div />').addClass(cssClass)
.append($('<table />').css('border-collapse', 'collapse')
.append($('<tr />')
.append($('<td />')
.append($('<img />').attr('src', '/images/icons2/24x24/' + iconName + '.png')))
.append($('<td />')
.append(htmlMsg))));
}
function addInfoMessage(msg, $parent) {
if ($parent === undefined) $parent = $('.status-messages');
createStatusMessage('infoMessage', 'check', msg)
.hide()
.css({ opacity: 0 })
.appendTo($parent)
.animate({ height: 'toggle' }, { queue: false, easing: 'linear', duration: 100 })
.animate({ opacity: 1 }, { queue: false, duration: 500 })
.delay(7000)
.promise().done(function() {
$(this).animate({ height: 'toggle' }, { queue: false, easing: 'linear', duration: 500 })
.animate({ opacity: 0 }, { queue: false, duration: 1000 })
.promise().done(function() {
$(this).remove();
});
});
}
function addWarnMessage(msg, $parent) {
if ($parent === undefined || $parent.length == 0) $parent = $('.status-messages');
createStatusMessage('warnMessage', 'warning', msg)
.hide()
.css({ opacity: 0 })
.appendTo($parent)
.animate({ height: 'toggle' }, { queue: false, easing: 'linear', duration: 100 })
.animate({ opacity: 1 }, { queue: false, duration: 500 });
}
function addErrorMessage(msg, $parent) {
if ($parent === undefined || $parent.length == 0) $parent = $('.status-messages');
createStatusMessage('errorMessage', 'error', msg)
.hide()
.css({ opacity: 0 })
.appendTo($parent)
.animate({ height: 'toggle' }, { queue: false, easing: 'linear', duration: 100 })
.animate({ opacity: 1 }, { queue: false, duration: 500 });
}
if ($.widget) {
$.widget('ui.archiveViewer', {
version: '0.0.1',
options: {
archivePath: null,
jobUid: null,
totalPages: null,
pageLimit: null,
copies: null,
page: 1,
transitionSpeedMs: 500,
grayscale: false,
// Signals whether admin has the right to remove archive
canAdminRemoveArchive: false,
// Signals whether reloading after closing the widget is required
reloadAfterClose: false
},
_create: function() {
this.options.archivePath = this.options.archivePath || this.element.data('archive-path');
this.options.jobUid = this.options.jobUid || this.element.data('job-uid');
this.options.totalPages = this.options.totalPages || this.element.data('total-pages') || 1;
this.options.copies = this.options.copies || this.element.data('copies') || 1;