comparison program/js/common.js @ 0:4681f974d28b

vanilla 1.3.3 distro, I hope
author Charlie Root
date Thu, 04 Jan 2018 15:52:31 -0500
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4681f974d28b
1 /**
2 * Roundcube common js library
3 *
4 * This file is part of the Roundcube Webmail client
5 *
6 * @licstart The following is the entire license notice for the
7 * JavaScript code in this file.
8 *
9 * Copyright (c) 2005-2014, The Roundcube Dev Team
10 *
11 * The JavaScript code in this page is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GNU GPL) as published by the Free Software
14 * Foundation, either version 3 of the License, or (at your option)
15 * any later version. The code is distributed WITHOUT ANY WARRANTY;
16 * without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
18 *
19 * As additional permission under GNU GPL version 3 section 7, you
20 * may distribute non-source (e.g., minimized or compacted) forms of
21 * that code without the copy of the GNU GPL normally required by
22 * section 4, provided you include this license notice and a URL
23 * through which recipients can access the Corresponding Source.
24 *
25 * @licend The above is the entire license notice
26 * for the JavaScript code in this file.
27 */
28
29 // Constants
30 var CONTROL_KEY = 1;
31 var SHIFT_KEY = 2;
32 var CONTROL_SHIFT_KEY = 3;
33
34 /**
35 * Default browser check class
36 * @constructor
37 */
38 function roundcube_browser()
39 {
40 var n = navigator;
41
42 this.agent = n.userAgent;
43 this.agent_lc = n.userAgent.toLowerCase();
44 this.name = n.appName;
45 this.vendor = n.vendor ? n.vendor : '';
46 this.vendver = n.vendorSub ? parseFloat(n.vendorSub) : 0;
47 this.product = n.product ? n.product : '';
48 this.platform = String(n.platform).toLowerCase();
49 this.lang = n.language ? n.language.substring(0,2) :
50 n.browserLanguage ? n.browserLanguage.substring(0,2) :
51 n.systemLanguage ? n.systemLanguage.substring(0,2) : 'en';
52
53 this.win = this.platform.indexOf('win') >= 0;
54 this.mac = this.platform.indexOf('mac') >= 0;
55 this.linux = this.platform.indexOf('linux') >= 0;
56 this.unix = this.platform.indexOf('unix') >= 0;
57
58 this.dom = document.getElementById ? true : false;
59 this.dom2 = document.addEventListener && document.removeEventListener;
60
61 this.edge = this.agent_lc.indexOf(' edge/') > 0;
62 this.webkit = !this.edge && this.agent_lc.indexOf('applewebkit') > 0;
63 this.ie = (document.all && !window.opera) || (this.win && this.agent_lc.indexOf('trident/') > 0);
64
65 if (window.opera) {
66 this.opera = true; // Opera < 15
67 this.vendver = opera.version();
68 }
69 else if (!this.ie && !this.edge) {
70 this.chrome = this.agent_lc.indexOf('chrome') > 0;
71 this.opera = this.webkit && this.agent.indexOf(' OPR/') > 0; // Opera >= 15
72 this.safari = !this.chrome && !this.opera && (this.webkit || this.agent_lc.indexOf('safari') > 0);
73 this.konq = this.agent_lc.indexOf('konqueror') > 0;
74 this.mz = this.dom && !this.chrome && !this.safari && !this.konq && !this.opera && this.agent.indexOf('Mozilla') >= 0;
75 this.iphone = this.safari && (this.agent_lc.indexOf('iphone') > 0 || this.agent_lc.indexOf('ipod') > 0);
76 this.ipad = this.safari && this.agent_lc.indexOf('ipad') > 0;
77 }
78
79 if (!this.vendver) {
80 // common version strings
81 this.vendver = /(opera|opr|khtml|chrome|safari|applewebkit|msie)(\s|\/)([0-9\.]+)/.test(this.agent_lc) ? parseFloat(RegExp.$3) : 0;
82
83 // any other (Mozilla, Camino, IE>=11)
84 if (!this.vendver)
85 this.vendver = /rv:([0-9\.]+)/.test(this.agent) ? parseFloat(RegExp.$1) : 0;
86 }
87
88 // get real language out of safari's user agent
89 if (this.safari && (/;\s+([a-z]{2})-[a-z]{2}\)/.test(this.agent_lc)))
90 this.lang = RegExp.$1;
91
92 this.tablet = /ipad|android|xoom|sch-i800|playbook|tablet|kindle/i.test(this.agent_lc);
93 this.mobile = /iphone|ipod|blackberry|iemobile|opera mini|opera mobi|mobile/i.test(this.agent_lc);
94 this.touch = this.mobile || this.tablet;
95 this.pointer = typeof window.PointerEvent == "function";
96 this.cookies = n.cookieEnabled;
97
98 // test for XMLHTTP support
99 this.xmlhttp_test = function()
100 {
101 var activeX_test = new Function("try{var o=new ActiveXObject('Microsoft.XMLHTTP');return true;}catch(err){return false;}");
102 this.xmlhttp = window.XMLHttpRequest || (('ActiveXObject' in window) && activeX_test());
103 return this.xmlhttp;
104 };
105
106 // set class names to html tag according to the current user agent detection
107 // this allows browser-specific css selectors like "html.chrome .someclass"
108 this.set_html_class = function()
109 {
110 var classname = ' js';
111
112 if (this.ie)
113 classname += ' ie ie'+parseInt(this.vendver);
114 else if (this.opera)
115 classname += ' opera';
116 else if (this.konq)
117 classname += ' konqueror';
118 else if (this.safari)
119 classname += ' chrome';
120 else if (this.chrome)
121 classname += ' chrome';
122 else if (this.mz)
123 classname += ' mozilla';
124
125 if (this.iphone)
126 classname += ' iphone';
127 else if (this.ipad)
128 classname += ' ipad';
129 else if (this.webkit)
130 classname += ' webkit';
131
132 if (this.mobile)
133 classname += ' mobile';
134 if (this.tablet)
135 classname += ' tablet';
136
137 if (document.documentElement)
138 document.documentElement.className += classname;
139 };
140 };
141
142
143 // static functions for DOM event handling
144 var rcube_event = {
145
146 /**
147 * returns the event target element
148 */
149 get_target: function(e)
150 {
151 e = e || window.event;
152 return e && e.target ? e.target : e.srcElement;
153 },
154
155 /**
156 * returns the event key code
157 */
158 get_keycode: function(e)
159 {
160 e = e || window.event;
161 return e && e.keyCode ? e.keyCode : (e && e.which ? e.which : 0);
162 },
163
164 /**
165 * returns the event key code
166 */
167 get_button: function(e)
168 {
169 e = e || window.event;
170 return e && e.button !== undefined ? e.button : (e && e.which ? e.which : 0);
171 },
172
173 /**
174 * returns modifier key (constants defined at top of file)
175 */
176 get_modifier: function(e)
177 {
178 var opcode = 0;
179 e = e || window.event;
180
181 if (bw.mac && e)
182 opcode += (e.metaKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
183 else if (e)
184 opcode += (e.ctrlKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
185
186 return opcode;
187 },
188
189 /**
190 * Return absolute mouse position of an event
191 */
192 get_mouse_pos: function(e)
193 {
194 if (!e) e = window.event;
195 var mX = (e.pageX) ? e.pageX : e.clientX,
196 mY = (e.pageY) ? e.pageY : e.clientY;
197
198 if (document.body && document.all) {
199 mX += document.body.scrollLeft;
200 mY += document.body.scrollTop;
201 }
202
203 if (e._offset) {
204 mX += e._offset.left;
205 mY += e._offset.top;
206 }
207
208 return { x:mX, y:mY };
209 },
210
211 /**
212 * Add an object method as event listener to a certain element
213 */
214 add_listener: function(p)
215 {
216 if (!p.object || !p.method) // not enough arguments
217 return;
218 if (!p.element)
219 p.element = document;
220
221 if (!p.object._rc_events)
222 p.object._rc_events = {};
223
224 var key = p.event + '*' + p.method;
225 if (!p.object._rc_events[key])
226 p.object._rc_events[key] = function(e){ return p.object[p.method](e); };
227
228 if (p.element.addEventListener)
229 p.element.addEventListener(p.event, p.object._rc_events[key], false);
230 else if (p.element.attachEvent) {
231 // IE allows multiple events with the same function to be applied to the same object
232 // forcibly detach the event, then attach
233 p.element.detachEvent('on'+p.event, p.object._rc_events[key]);
234 p.element.attachEvent('on'+p.event, p.object._rc_events[key]);
235 }
236 else
237 p.element['on'+p.event] = p.object._rc_events[key];
238 },
239
240 /**
241 * Remove event listener
242 */
243 remove_listener: function(p)
244 {
245 if (!p.element)
246 p.element = document;
247
248 var key = p.event + '*' + p.method;
249 if (p.object && p.object._rc_events && p.object._rc_events[key]) {
250 if (p.element.removeEventListener)
251 p.element.removeEventListener(p.event, p.object._rc_events[key], false);
252 else if (p.element.detachEvent)
253 p.element.detachEvent('on'+p.event, p.object._rc_events[key]);
254 else
255 p.element['on'+p.event] = null;
256 }
257 },
258
259 /**
260 * Prevent event propagation and bubbling
261 */
262 cancel: function(evt)
263 {
264 var e = evt ? evt : window.event;
265
266 if (e.preventDefault)
267 e.preventDefault();
268 else
269 e.returnValue = false;
270
271 if (e.stopPropagation)
272 e.stopPropagation();
273
274 e.cancelBubble = true;
275
276 return false;
277 },
278
279 /**
280 * Determine whether the given event was trigered from keyboard
281 */
282 is_keyboard: function(e)
283 {
284 return e && (
285 (e.type && String(e.type).match(/^key/)) // DOM3-compatible
286 || (!e.pageX && (e.pageY || 0) <= 0 && !e.clientX && (e.clientY || 0) <= 0) // others
287 );
288 },
289
290 /**
291 * Accept event if triggered from keyboard action (e.g. <Enter>)
292 */
293 keyboard_only: function(e)
294 {
295 return rcube_event.is_keyboard(e) ? true : rcube_event.cancel(e);
296 },
297
298 touchevent: function(e)
299 {
300 return { pageX:e.pageX, pageY:e.pageY, offsetX:e.pageX - e.target.offsetLeft, offsetY:e.pageY - e.target.offsetTop, target:e.target, istouch:true };
301 }
302
303 };
304
305
306 /**
307 * rcmail objects event interface
308 */
309 function rcube_event_engine()
310 {
311 this._events = {};
312 };
313
314 rcube_event_engine.prototype = {
315
316 /**
317 * Setter for object event handlers
318 *
319 * @param {String} Event name
320 * @param {Function} Handler function
321 */
322 addEventListener: function(evt, func, obj)
323 {
324 if (!this._events)
325 this._events = {};
326 if (!this._events[evt])
327 this._events[evt] = [];
328
329 this._events[evt].push({func:func, obj:obj ? obj : window});
330
331 return this; // chainable
332 },
333
334 /**
335 * Removes a specific event listener
336 *
337 * @param {String} Event name
338 * @param {Int} Listener ID to remove
339 */
340 removeEventListener: function(evt, func, obj)
341 {
342 if (obj === undefined)
343 obj = window;
344
345 for (var h,i=0; this._events && this._events[evt] && i < this._events[evt].length; i++)
346 if ((h = this._events[evt][i]) && h.func == func && h.obj == obj)
347 this._events[evt][i] = null;
348 },
349
350 /**
351 * This will execute all registered event handlers
352 *
353 * @param {String} Event to trigger
354 * @param {Object} Event object/arguments
355 */
356 triggerEvent: function(evt, e)
357 {
358 var ret, h;
359
360 if (e === undefined)
361 e = this;
362 else if (typeof e === 'object')
363 e.event = evt;
364
365 if (!this._event_exec)
366 this._event_exec = {};
367
368 if (this._events && this._events[evt] && !this._event_exec[evt]) {
369 this._event_exec[evt] = true;
370 for (var i=0; i < this._events[evt].length; i++) {
371 if ((h = this._events[evt][i])) {
372 if (typeof h.func === 'function')
373 ret = h.func.call ? h.func.call(h.obj, e) : h.func(e);
374 else if (typeof h.obj[h.func] === 'function')
375 ret = h.obj[h.func](e);
376
377 // cancel event execution
378 if (ret !== undefined && !ret)
379 break;
380 }
381 }
382 if (ret && ret.event) {
383 try {
384 delete ret.event;
385 } catch (err) {
386 // IE6-7 doesn't support deleting HTMLFormElement attributes (#1488017)
387 $(ret).removeAttr('event');
388 }
389 }
390 }
391
392 delete this._event_exec[evt];
393
394 if (e.event) {
395 try {
396 delete e.event;
397 } catch (err) {
398 // IE6-7 doesn't support deleting HTMLFormElement attributes (#1488017)
399 $(e).removeAttr('event');
400 }
401 }
402
403 return ret;
404 }
405
406 }; // end rcube_event_engine.prototype
407
408
409 // check if input is a valid email address
410 // By Cal Henderson <cal@iamcal.com>
411 // http://code.iamcal.com/php/rfc822/
412 function rcube_check_email(input, inline, count)
413 {
414 if (!input)
415 return count ? 0 : false;
416
417 if (count) inline = true;
418
419 var qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]',
420 dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]',
421 atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+',
422 quoted_pair = '\\x5c[\\x00-\\x7f]',
423 quoted_string = '\\x22('+qtext+'|'+quoted_pair+')*\\x22',
424 ipv4 = '\\[(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}\\]',
425 ipv6 = '\\[IPv6:[0-9a-f:.]+\\]',
426 ip_addr = '(' + ipv4 + ')|(' + ipv6 + ')',
427 // Use simplified domain matching, because we need to allow Unicode characters here
428 // So, e-mail address should be validated also on server side after idn_to_ascii() use
429 //domain_literal = '\\x5b('+dtext+'|'+quoted_pair+')*\\x5d',
430 //sub_domain = '('+atom+'|'+domain_literal+')',
431 // allow punycode/unicode top-level domain
432 domain = '(('+ip_addr+')|(([^@\\x2e]+\\x2e)+([^\\x00-\\x40\\x5b-\\x60\\x7b-\\x7f]{2,}|xn--[a-z0-9]{2,})))',
433 // ICANN e-mail test (http://idn.icann.org/E-mail_test)
434 icann_domains = [
435 '\\u0645\\u062b\\u0627\\u0644\\x2e\\u0625\\u062e\\u062a\\u0628\\u0627\\u0631',
436 '\\u4f8b\\u5b50\\x2e\\u6d4b\\u8bd5',
437 '\\u4f8b\\u5b50\\x2e\\u6e2c\\u8a66',
438 '\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1\\x2e\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae',
439 '\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923\\x2e\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937\\u093e',
440 '\\u4f8b\\u3048\\x2e\\u30c6\\u30b9\\u30c8',
441 '\\uc2e4\\ub840\\x2e\\ud14c\\uc2a4\\ud2b8',
442 '\\u0645\\u062b\\u0627\\u0644\\x2e\\u0622\\u0632\\u0645\\u0627\\u06cc\\u0634\u06cc',
443 '\\u043f\\u0440\\u0438\\u043c\\u0435\\u0440\\x2e\\u0438\\u0441\\u043f\\u044b\\u0442\\u0430\\u043d\\u0438\\u0435',
444 '\\u0b89\\u0ba4\\u0bbe\\u0bb0\\u0ba3\\u0bae\\u0bcd\\x2e\\u0baa\\u0bb0\\u0bbf\\u0b9f\\u0bcd\\u0b9a\\u0bc8',
445 '\\u05d1\\u05f2\\u05b7\\u05e9\\u05e4\\u05bc\\u05d9\\u05dc\\x2e\\u05d8\\u05e2\\u05e1\\u05d8'
446 ],
447 icann_addr = 'mailtest\\x40('+icann_domains.join('|')+')',
448 word = '('+atom+'|'+quoted_string+')',
449 delim = '[,;\\s\\n]',
450 local_part = word+'(\\x2e'+word+')*',
451 addr_spec = '(('+local_part+'\\x40'+domain+')|('+icann_addr+'))',
452 rx_flag = count ? 'ig' : 'i',
453 rx = inline ? new RegExp('(^|<|'+delim+')'+addr_spec+'($|>|'+delim+')', rx_flag) : new RegExp('^'+addr_spec+'$', 'i');
454
455 if (count)
456 return input.match(rx).length;
457
458 return rx.test(input);
459 };
460
461 // recursively copy an object
462 function rcube_clone_object(obj)
463 {
464 var out = {};
465
466 for (var key in obj) {
467 if (obj[key] && typeof obj[key] === 'object')
468 out[key] = rcube_clone_object(obj[key]);
469 else
470 out[key] = obj[key];
471 }
472
473 return out;
474 };
475
476 // make a string URL safe (and compatible with PHP's rawurlencode())
477 function urlencode(str)
478 {
479 if (window.encodeURIComponent)
480 return encodeURIComponent(str).replace('*', '%2A');
481
482 return escape(str)
483 .replace('+', '%2B')
484 .replace('*', '%2A')
485 .replace('/', '%2F')
486 .replace('@', '%40');
487 };
488
489
490 // get any type of html objects by id/name
491 function rcube_find_object(id, d)
492 {
493 var n, f, obj, e;
494
495 if (!d) d = document;
496
497 if (d.getElementById)
498 if (obj = d.getElementById(id))
499 return obj;
500
501 if (!obj && d.getElementsByName && (e = d.getElementsByName(id)))
502 obj = e[0];
503
504 if (!obj && d.all)
505 obj = d.all[id];
506
507 if (!obj && d.images.length)
508 obj = d.images[id];
509
510 if (!obj && d.forms.length) {
511 for (f=0; f<d.forms.length; f++) {
512 if (d.forms[f].name == id)
513 obj = d.forms[f];
514 else if(d.forms[f].elements[id])
515 obj = d.forms[f].elements[id];
516 }
517 }
518
519 if (!obj && d.layers) {
520 if (d.layers[id])
521 obj = d.layers[id];
522 for (n=0; !obj && n<d.layers.length; n++)
523 obj = rcube_find_object(id, d.layers[n].document);
524 }
525
526 return obj;
527 };
528
529 // determine whether the mouse is over the given object or not
530 function rcube_mouse_is_over(ev, obj)
531 {
532 var mouse = rcube_event.get_mouse_pos(ev),
533 pos = $(obj).offset();
534
535 return (mouse.x >= pos.left) && (mouse.x < (pos.left + obj.offsetWidth)) &&
536 (mouse.y >= pos.top) && (mouse.y < (pos.top + obj.offsetHeight));
537 };
538
539
540 // cookie functions by GoogieSpell
541 function setCookie(name, value, expires, path, domain, secure)
542 {
543 var curCookie = name + "=" + escape(value) +
544 (expires ? "; expires=" + expires.toGMTString() : "") +
545 (path ? "; path=" + path : "") +
546 (domain ? "; domain=" + domain : "") +
547 (secure ? "; secure" : "");
548
549 document.cookie = curCookie;
550 };
551
552 function getCookie(name)
553 {
554 var dc = document.cookie,
555 prefix = name + "=",
556 begin = dc.indexOf("; " + prefix);
557
558 if (begin == -1) {
559 begin = dc.indexOf(prefix);
560 if (begin != 0)
561 return null;
562 }
563 else {
564 begin += 2;
565 }
566
567 var end = dc.indexOf(";", begin);
568 if (end == -1)
569 end = dc.length;
570
571 return unescape(dc.substring(begin + prefix.length, end));
572 };
573
574 // deprecated aliases, to be removed, use rcmail.set_cookie/rcmail.get_cookie
575 roundcube_browser.prototype.set_cookie = setCookie;
576 roundcube_browser.prototype.get_cookie = getCookie;
577
578 var bw = new roundcube_browser();
579 bw.set_html_class();
580
581
582 // Add escape() method to RegExp object
583 // http://dev.rubyonrails.org/changeset/7271
584 RegExp.escape = function(str)
585 {
586 return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
587 };
588
589 // Extend Date prototype to detect Standard timezone without DST
590 // from http://www.michaelapproved.com/articles/timezone-detect-and-ignore-daylight-saving-time-dst/
591 Date.prototype.getStdTimezoneOffset = function()
592 {
593 var m = 12,
594 d = new Date(null, m, 1),
595 tzo = d.getTimezoneOffset();
596
597 while (--m) {
598 d.setUTCMonth(m);
599 if (tzo != d.getTimezoneOffset()) {
600 return Math.max(tzo, d.getTimezoneOffset());
601 }
602 }
603
604 return tzo;
605 }
606
607 // define String's startsWith() method for old browsers
608 if (!String.prototype.startsWith) {
609 String.prototype.startsWith = function(search, position) {
610 position = position || 0;
611 return this.slice(position, search.length) === search;
612 };
613 }
614
615 // array utility function
616 jQuery.last = function(arr) {
617 return arr && arr.length ? arr[arr.length-1] : undefined;
618 }
619
620 // jQuery plugin to set HTML5 placeholder and title attributes on input elements
621 jQuery.fn.placeholder = function(text) {
622 return this.each(function() {
623 $(this).prop({title: text, placeholder: text});
624 });
625 };
626
627 // function to parse query string into an object
628 var rcube_parse_query = function(query)
629 {
630 if (!query)
631 return {};
632
633 var params = {}, e, k, v,
634 re = /([^&=]+)=?([^&]*)/g,
635 decodeRE = /\+/g, // Regex for replacing addition symbol with a space
636 decode = function (str) { return decodeURIComponent(str.replace(decodeRE, ' ')); };
637
638 query = query.replace(/\?/, '');
639
640 while (e = re.exec(query)) {
641 k = decode(e[1]);
642 v = decode(e[2]);
643
644 if (k.substring(k.length - 2) === '[]') {
645 k = k.substring(0, k.length - 2);
646 (params[k] || (params[k] = [])).push(v);
647 }
648 else
649 params[k] = v;
650 }
651
652 return params;
653 };
654
655
656 // Base64 code from Tyler Akins -- http://rumkin.com
657 var Base64 = (function () {
658 var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
659
660 // private method for UTF-8 encoding
661 var utf8_encode = function(string) {
662 string = string.replace(/\r\n/g, "\n");
663 var utftext = '';
664
665 for (var n = 0; n < string.length; n++) {
666 var c = string.charCodeAt(n);
667
668 if (c < 128) {
669 utftext += String.fromCharCode(c);
670 }
671 else if(c > 127 && c < 2048) {
672 utftext += String.fromCharCode((c >> 6) | 192);
673 utftext += String.fromCharCode((c & 63) | 128);
674 }
675 else {
676 utftext += String.fromCharCode((c >> 12) | 224);
677 utftext += String.fromCharCode(((c >> 6) & 63) | 128);
678 utftext += String.fromCharCode((c & 63) | 128);
679 }
680 }
681
682 return utftext;
683 };
684
685 // private method for UTF-8 decoding
686 var utf8_decode = function (utftext) {
687 var i = 0, string = '', c = 0, c2 = 0, c3 = 0;
688
689 while (i < utftext.length) {
690 c = utftext.charCodeAt(i);
691 if (c < 128) {
692 string += String.fromCharCode(c);
693 i++;
694 }
695 else if (c > 191 && c < 224) {
696 c2 = utftext.charCodeAt(i + 1);
697 string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
698 i += 2;
699 }
700 else {
701 c2 = utftext.charCodeAt(i + 1);
702 c3 = utftext.charCodeAt(i + 2);
703 string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
704 i += 3;
705 }
706 }
707
708 return string;
709 };
710
711 var obj = {
712 /**
713 * Encodes a string in base64
714 * @param {String} input The string to encode in base64.
715 */
716 encode: function (input) {
717 // encode UTF8 as btoa() may fail on some characters
718 input = utf8_encode(input);
719
720 if (typeof(window.btoa) === 'function') {
721 try {
722 return btoa(input);
723 }
724 catch (e) {};
725 }
726
727 var chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0, output = '', len = input.length;
728
729 while (i < len) {
730 chr1 = input.charCodeAt(i++);
731 chr2 = input.charCodeAt(i++);
732 chr3 = input.charCodeAt(i++);
733
734 enc1 = chr1 >> 2;
735 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
736 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
737 enc4 = chr3 & 63;
738
739 if (isNaN(chr2))
740 enc3 = enc4 = 64;
741 else if (isNaN(chr3))
742 enc4 = 64;
743
744 output = output
745 + keyStr.charAt(enc1) + keyStr.charAt(enc2)
746 + keyStr.charAt(enc3) + keyStr.charAt(enc4);
747 }
748
749 return output;
750 },
751
752 /**
753 * Decodes a base64 string.
754 * @param {String} input The string to decode.
755 */
756 decode: function (input) {
757 if (typeof(window.atob) === 'function') {
758 try {
759 return utf8_decode(atob(input));
760 }
761 catch (e) {};
762 }
763
764 var chr1, chr2, chr3, enc1, enc2, enc3, enc4, len, i = 0, output = '';
765
766 // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
767 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
768 len = input.length;
769
770 while (i < len) {
771 enc1 = keyStr.indexOf(input.charAt(i++));
772 enc2 = keyStr.indexOf(input.charAt(i++));
773 enc3 = keyStr.indexOf(input.charAt(i++));
774 enc4 = keyStr.indexOf(input.charAt(i++));
775
776 chr1 = (enc1 << 2) | (enc2 >> 4);
777 chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
778 chr3 = ((enc3 & 3) << 6) | enc4;
779
780 output = output + String.fromCharCode(chr1);
781
782 if (enc3 != 64)
783 output = output + String.fromCharCode(chr2);
784 if (enc4 != 64)
785 output = output + String.fromCharCode(chr3);
786 }
787
788 return utf8_decode(output);
789 }
790 };
791
792 return obj;
793 })();