code
stringlengths
1
2.08M
language
stringclasses
1 value
<?php /** This file is part of KCFinder project * * @desc Base JavaScript object properties * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> var browser = { opener: {}, support: {}, files: [], clipboard: [], labels: [], shows: [], orders: [], cms: "" };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Upload files using drag and drop * @package KCFinder * @version 2.51 * @author Forum user (updated by Pavel Tzonkov) * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.initDropUpload = function() { if ((typeof(XMLHttpRequest) == 'undefined') || (typeof(document.addEventListener) == 'undefined') || (typeof(File) == 'undefined') || (typeof(FileReader) == 'undefined') ) return; if (!XMLHttpRequest.prototype.sendAsBinary) { XMLHttpRequest.prototype.sendAsBinary = function(datastr) { var ords = Array.prototype.map.call(datastr, function(x) { return x.charCodeAt(0) & 0xff; }); var ui8a = new Uint8Array(ords); this.send(ui8a.buffer); } } var uploadQueue = [], uploadInProgress = false, filesCount = 0, errors = [], files = $('#files'), folders = $('div.folder > a'), boundary = '------multipartdropuploadboundary' + (new Date).getTime(), currentFile, filesDragOver = function(e) { if (e.preventDefault) e.preventDefault(); $('#files').addClass('drag'); return false; }, filesDragEnter = function(e) { if (e.preventDefault) e.preventDefault(); return false; }, filesDragLeave = function(e) { if (e.preventDefault) e.preventDefault(); $('#files').removeClass('drag'); return false; }, filesDrop = function(e) { if (e.preventDefault) e.preventDefault(); if (e.stopPropagation) e.stopPropagation(); $('#files').removeClass('drag'); if (!$('#folders span.current').first().parent().data('writable')) { browser.alert("Cannot write to upload folder."); return false; } filesCount += e.dataTransfer.files.length for (var i = 0; i < e.dataTransfer.files.length; i++) { var file = e.dataTransfer.files[i]; file.thisTargetDir = browser.dir; uploadQueue.push(file); } processUploadQueue(); return false; }, folderDrag = function(e) { if (e.preventDefault) e.preventDefault(); return false; }, folderDrop = function(e, dir) { if (e.preventDefault) e.preventDefault(); if (e.stopPropagation) e.stopPropagation(); if (!$(dir).data('writable')) { browser.alert("Cannot write to upload folder."); return false; } filesCount += e.dataTransfer.files.length for (var i = 0; i < e.dataTransfer.files.length; i++) { var file = e.dataTransfer.files[i]; file.thisTargetDir = $(dir).data('path'); uploadQueue.push(file); } processUploadQueue(); return false; }; files.get(0).removeEventListener('dragover', filesDragOver, false); files.get(0).removeEventListener('dragenter', filesDragEnter, false); files.get(0).removeEventListener('dragleave', filesDragLeave, false); files.get(0).removeEventListener('drop', filesDrop, false); files.get(0).addEventListener('dragover', filesDragOver, false); files.get(0).addEventListener('dragenter', filesDragEnter, false); files.get(0).addEventListener('dragleave', filesDragLeave, false); files.get(0).addEventListener('drop', filesDrop, false); folders.each(function() { var folder = this, dragOver = function(e) { $(folder).children('span.folder').addClass('context'); return folderDrag(e); }, dragLeave = function(e) { $(folder).children('span.folder').removeClass('context'); return folderDrag(e); }, drop = function(e) { $(folder).children('span.folder').removeClass('context'); return folderDrop(e, folder); }; this.removeEventListener('dragover', dragOver, false); this.removeEventListener('dragenter', folderDrag, false); this.removeEventListener('dragleave', dragLeave, false); this.removeEventListener('drop', drop, false); this.addEventListener('dragover', dragOver, false); this.addEventListener('dragenter', folderDrag, false); this.addEventListener('dragleave', dragLeave, false); this.addEventListener('drop', drop, false); }); function updateProgress(evt) { var progress = evt.lengthComputable ? Math.round((evt.loaded * 100) / evt.total) + '%' : Math.round(evt.loaded / 1024) + " KB"; $('#loading').html(browser.label("Uploading file {number} of {count}... {progress}", { number: filesCount - uploadQueue.length, count: filesCount, progress: progress })); } function processUploadQueue() { if (uploadInProgress) return false; if (uploadQueue && uploadQueue.length) { var file = uploadQueue.shift(); currentFile = file; $('#loading').html(browser.label("Uploading file {number} of {count}... {progress}", { number: filesCount - uploadQueue.length, count: filesCount, progress: "" })); $('#loading').css('display', 'inline'); var reader = new FileReader(); reader.thisFileName = file.name; reader.thisFileType = file.type; reader.thisFileSize = file.size; reader.thisTargetDir = file.thisTargetDir; reader.onload = function(evt) { uploadInProgress = true; var postbody = '--' + boundary + '\r\nContent-Disposition: form-data; name="upload[]"'; if (evt.target.thisFileName) postbody += '; filename="' + _.utf8encode(evt.target.thisFileName) + '"'; postbody += '\r\n'; if (evt.target.thisFileSize) postbody += 'Content-Length: ' + evt.target.thisFileSize + '\r\n'; postbody += 'Content-Type: ' + evt.target.thisFileType + '\r\n\r\n' + evt.target.result + '\r\n--' + boundary + '\r\nContent-Disposition: form-data; name="dir"\r\n\r\n' + _.utf8encode(evt.target.thisTargetDir) + '\r\n--' + boundary + '\r\n--' + boundary + '--\r\n'; var xhr = new XMLHttpRequest(); xhr.thisFileName = evt.target.thisFileName; if (xhr.upload) { xhr.upload.thisFileName = evt.target.thisFileName; xhr.upload.addEventListener("progress", updateProgress, false); } xhr.open('POST', browser.baseGetData('upload'), true); xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary); xhr.setRequestHeader('Content-Length', postbody.length); xhr.onload = function(e) { $('#loading').css('display', 'none'); if (browser.dir == reader.thisTargetDir) browser.fadeFiles(); uploadInProgress = false; processUploadQueue(); if (xhr.responseText.substr(0, 1) != '/') errors[errors.length] = xhr.responseText; } xhr.sendAsBinary(postbody); }; reader.onerror = function(evt) { $('#loading').css('display', 'none'); uploadInProgress = false; processUploadQueue(); errors[errors.length] = browser.label("Failed to upload {filename}!", { filename: evt.target.thisFileName }); }; reader.readAsBinaryString(file); } else { filesCount = 0; var loop = setInterval(function() { if (uploadInProgress) return; clearInterval(loop); if (currentFile.thisTargetDir == browser.dir) browser.refresh(); boundary = '------multipartdropuploadboundary' + (new Date).getTime(); if (errors.length) { browser.alert(errors.join('\n')); errors = []; } }, 333); } } };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Settings panel functionality * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.initSettings = function() { if (!this.shows.length) { var showInputs = $('#show input[type="checkbox"]').toArray(); $.each(showInputs, function (i, input) { browser.shows[i] = input.name; }); } var shows = this.shows; if (!_.kuki.isSet('showname')) { _.kuki.set('showname', 'on'); $.each(shows, function (i, val) { if (val != "name") _.kuki.set('show' + val, 'off'); }); } $('#show input[type="checkbox"]').click(function() { var kuki = $(this).get(0).checked ? 'on' : 'off'; _.kuki.set('show' + $(this).get(0).name, kuki) if ($(this).get(0).checked) $('#files .file div.' + $(this).get(0).name).css('display', 'block'); else $('#files .file div.' + $(this).get(0).name).css('display', 'none'); }); $.each(shows, function(i, val) { var checked = (_.kuki.get('show' + val) == 'on') ? 'checked' : ''; $('#show input[name="' + val + '"]').get(0).checked = checked; }); if (!this.orders.length) { var orderInputs = $('#order input[type="radio"]').toArray(); $.each(orderInputs, function (i, input) { browser.orders[i] = input.value; }); } var orders = this.orders; if (!_.kuki.isSet('order')) _.kuki.set('order', 'name'); if (!_.kuki.isSet('orderDesc')) _.kuki.set('orderDesc', 'off'); $('#order input[value="' + _.kuki.get('order') + '"]').get(0).checked = true; $('#order input[name="desc"]').get(0).checked = (_.kuki.get('orderDesc') == 'on'); $('#order input[type="radio"]').click(function() { _.kuki.set('order', $(this).get(0).value); browser.orderFiles(); }); $('#order input[name="desc"]').click(function() { _.kuki.set('orderDesc', $(this).get(0).checked ? 'on' : 'off'); browser.orderFiles(); }); if (!_.kuki.isSet('view')) _.kuki.set('view', 'thumbs'); if (_.kuki.get('view') == 'list') { $('#show input').each(function() { this.checked = true; }); $('#show input').each(function() { this.disabled = true; }); } $('#view input[value="' + _.kuki.get('view') + '"]').get(0).checked = true; $('#view input').click(function() { var view = $(this).attr('value'); if (_.kuki.get('view') != view) { _.kuki.set('view', view); if (view == 'list') { $('#show input').each(function() { this.checked = true; }); $('#show input').each(function() { this.disabled = true; }); } else { $.each(browser.shows, function(i, val) { $('#show input[name="' + val + '"]').get(0).checked = (_.kuki.get('show' + val) == "on"); }); $('#show input').each(function() { this.disabled = false; }); } } browser.refresh(); }); };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Miscellaneous functionality * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.drag = function(ev, dd) { var top = dd.offsetY, left = dd.offsetX; if (top < 0) top = 0; if (left < 0) left = 0; if (top + $(this).outerHeight() > $(window).height()) top = $(window).height() - $(this).outerHeight(); if (left + $(this).outerWidth() > $(window).width()) left = $(window).width() - $(this).outerWidth(); $(this).css({ top: top, left: left }); }; browser.showDialog = function(e) { $('#dialog').css({left: 0, top: 0}); this.shadow(); if ($('#dialog div.box') && !$('#dialog div.title').get(0)) { var html = $('#dialog div.box').html(); var title = $('#dialog').data('title') ? $('#dialog').data('title') : ""; html = '<div class="title"><span class="close"></span>' + title + '</div>' + html; $('#dialog div.box').html(html); $('#dialog div.title span.close').mousedown(function() { $(this).addClass('clicked'); }); $('#dialog div.title span.close').mouseup(function() { $(this).removeClass('clicked'); }); $('#dialog div.title span.close').click(function() { browser.hideDialog(); browser.hideAlert(); }); } $('#dialog').drag(browser.drag, {handle: '#dialog div.title'}); $('#dialog').css('display', 'block'); if (e) { var left = e.pageX - parseInt($('#dialog').outerWidth() / 2); var top = e.pageY - parseInt($('#dialog').outerHeight() / 2); if (left < 0) left = 0; if (top < 0) top = 0; if (($('#dialog').outerWidth() + left) > $(window).width()) left = $(window).width() - $('#dialog').outerWidth(); if (($('#dialog').outerHeight() + top) > $(window).height()) top = $(window).height() - $('#dialog').outerHeight(); $('#dialog').css({ left: left + 'px', top: top + 'px' }); } else $('#dialog').css({ left: parseInt(($(window).width() - $('#dialog').outerWidth()) / 2) + 'px', top: parseInt(($(window).height() - $('#dialog').outerHeight()) / 2) + 'px' }); $(document).unbind('keydown'); $(document).keydown(function(e) { if (e.keyCode == 27) browser.hideDialog(); }); }; browser.hideDialog = function() { this.unshadow(); if ($('#clipboard').hasClass('selected')) $('#clipboard').removeClass('selected'); $('#dialog').css('display', 'none'); $('div.folder > a > span.folder').removeClass('context'); $('#dialog').html(''); $('#dialog').data('title', null); $('#dialog').unbind(); $('#dialog').click(function() { return false; }); $(document).unbind('keydown'); $(document).keydown(function(e) { return !browser.selectAll(e); }); browser.hideAlert(); }; browser.showAlert = function(shadow) { $('#alert').css({left: 0, top: 0}); if (typeof shadow == 'undefined') shadow = true; if (shadow) this.shadow(); var left = parseInt(($(window).width() - $('#alert').outerWidth()) / 2), top = parseInt(($(window).height() - $('#alert').outerHeight()) / 2); var wheight = $(window).height(); if (top < 0) top = 0; $('#alert').css({ left: left + 'px', top: top + 'px', display: 'block' }); if ($('#alert').outerHeight() > wheight) { $('#alert div.message').css({ height: wheight - $('#alert div.title').outerHeight() - $('#alert div.ok').outerHeight() - 20 + 'px' }); } $(document).unbind('keydown'); $(document).keydown(function(e) { if (e.keyCode == 27) { browser.hideDialog(); browser.hideAlert(); $(document).unbind('keydown'); $(document).keydown(function(e) { return !browser.selectAll(e); }); } }); }; browser.hideAlert = function(shadow) { if (typeof shadow == 'undefined') shadow = true; if (shadow) this.unshadow(); $('#alert').css('display', 'none'); $('#alert').html(''); $('#alert').data('title', null); }; browser.alert = function(msg, shadow) { msg = msg.replace(/\r?\n/g, "<br />"); var title = $('#alert').data('title') ? $('#alert').data('title') : browser.label("Attention"); $('#alert').html('<div class="title"><span class="close"></span>' + title + '</div><div class="message">' + msg + '</div><div class="ok"><button>' + browser.label("OK") + '</button></div>'); $('#alert div.ok button').click(function() { browser.hideAlert(shadow); }); $('#alert div.title span.close').mousedown(function() { $(this).addClass('clicked'); }); $('#alert div.title span.close').mouseup(function() { $(this).removeClass('clicked'); }); $('#alert div.title span.close').click(function() { browser.hideAlert(shadow); }); $('#alert').drag(browser.drag, {handle: "#alert div.title"}); browser.showAlert(shadow); }; browser.confirm = function(question, callBack) { $('#dialog').data('title', browser.label("Question")); $('#dialog').html('<div class="box"><div class="question">' + browser.label(question) + '<div class="buttons"><button>' + browser.label("No") + '</button> <button>' + browser.label("Yes") + '</button></div></div></div>'); browser.showDialog(); $('#dialog div.buttons button').first().click(function() { browser.hideDialog(); }); $('#dialog div.buttons button').last().click(function() { if (callBack) callBack(function() { browser.hideDialog(); }); else browser.hideDialog(); }); $('#dialog div.buttons button').get(1).focus(); }; browser.shadow = function() { $('#shadow').css('display', 'block'); }; browser.unshadow = function() { $('#shadow').css('display', 'none'); }; browser.showMenu = function(e) { var left = e.pageX; var top = e.pageY; if (($('#dialog').outerWidth() + left) > $(window).width()) left = $(window).width() - $('#dialog').outerWidth(); if (($('#dialog').outerHeight() + top) > $(window).height()) top = $(window).height() - $('#dialog').outerHeight(); $('#dialog').css({ left: left + 'px', top: top + 'px', display: 'none' }); $('#dialog').fadeIn(); }; browser.fileNameDialog = function(e, post, inputName, inputValue, url, labels, callBack, selectAll) { var html = '<form method="post" action="javascript:;">' + '<div class="box">' + '<input name="' + inputName + '" type="text" /><br />' + '<div style="text-align:right">' + '<input type="submit" value="' + _.htmlValue(this.label("OK")) + '" /> ' + '<input type="button" value="' + _.htmlValue(this.label("Cancel")) + '" onclick="browser.hideDialog(); browser.hideAlert(); return false" />' + '</div></div></form>'; $('#dialog').html(html); $('#dialog').data('title', this.label(labels.title)); $('#dialog input[name="' + inputName + '"]').attr('value', inputValue); $('#dialog').unbind(); $('#dialog').click(function() { return false; }); $('#dialog form').submit(function() { var name = this.elements[0]; name.value = $.trim(name.value); if (name.value == '') { browser.alert(browser.label(labels.errEmpty), false); name.focus(); return; } else if (/[\/\\]/g.test(name.value)) { browser.alert(browser.label(labels.errSlash), false); name.focus(); return; } else if (name.value.substr(0, 1) == ".") { browser.alert(browser.label(labels.errDot), false); name.focus(); return; } eval('post.' + inputName + ' = name.value;'); $.ajax({ type: 'POST', dataType: 'json', url: url, data: post, async: false, success: function(data) { if (browser.check4errors(data, false)) return; if (callBack) callBack(data); browser.hideDialog(); }, error: function() { browser.alert(browser.label("Unknown error."), false); } }); return false; }); browser.showDialog(e); $('#dialog').css('display', 'block'); $('#dialog input[type="submit"]').click(function() { return $('#dialog form').submit(); }); var field = $('#dialog input[type="text"]'); var value = field.attr('value'); if (!selectAll && /^(.+)\.[^\.]+$/ .test(value)) { value = value.replace(/^(.+)\.[^\.]+$/, "$1"); _.selection(field.get(0), 0, value.length); } else { field.get(0).focus(); field.get(0).select(); } }; browser.orderFiles = function(callBack, selected) { var order = _.kuki.get('order'); var desc = (_.kuki.get('orderDesc') == 'on'); if (!browser.files || !browser.files.sort) browser.files = []; browser.files = browser.files.sort(function(a, b) { var a1, b1, arr; if (!order) order = 'name'; if (order == 'date') { a1 = a.mtime; b1 = b.mtime; } else if (order == 'type') { a1 = _.getFileExtension(a.name); b1 = _.getFileExtension(b.name); } else if (order == 'size') { a1 = a.size; b1 = b.size; } else eval('a1 = a.' + order + '.toLowerCase(); b1 = b.' + order + '.toLowerCase();'); if ((order == 'size') || (order == 'date')) { if (a1 < b1) return desc ? 1 : -1; if (a1 > b1) return desc ? -1 : 1; } if (a1 == b1) { a1 = a.name.toLowerCase(); b1 = b.name.toLowerCase(); arr = [a1, b1]; arr = arr.sort(); return (arr[0] == a1) ? -1 : 1; } arr = [a1, b1]; arr = arr.sort(); if (arr[0] == a1) return desc ? 1 : -1; return desc ? -1 : 1; }); browser.showFiles(callBack, selected); browser.initFiles(); }; browser.humanSize = function(size) { if (size < 1024) { size = size.toString() + ' B'; } else if (size < 1048576) { size /= 1024; size = parseInt(size).toString() + ' KB'; } else if (size < 1073741824) { size /= 1048576; size = parseInt(size).toString() + ' MB'; } else if (size < 1099511627776) { size /= 1073741824; size = parseInt(size).toString() + ' GB'; } else { size /= 1099511627776; size = parseInt(size).toString() + ' TB'; } return size; }; browser.baseGetData = function(act) { var data = 'browse.php?type=' + encodeURIComponent(this.type) + '&lng=' + this.lang; if (act) data += "&act=" + act; if (this.cms) data += "&cms=" + this.cms; return data; }; browser.label = function(index, data) { var label = this.labels[index] ? this.labels[index] : index; if (data) $.each(data, function(key, val) { label = label.replace('{' + key + '}', val); }); return label; }; browser.check4errors = function(data, shadow) { if (!data.error) return false; var msg; if (data.error.join) msg = data.error.join("\n"); else msg = data.error; browser.alert(msg, shadow); return true; }; browser.post = function(url, data) { var html = '<form id="postForm" method="POST" action="' + url + '">'; $.each(data, function(key, val) { if ($.isArray(val)) $.each(val, function(i, aval) { html += '<input type="hidden" name="' + _.htmlValue(key) + '[]" value="' + _.htmlValue(aval) + '" />'; }); else html += '<input type="hidden" name="' + _.htmlValue(key) + '" value="' + _.htmlValue(val) + '" />'; }); html += '</form>'; $('#dialog').html(html); $('#dialog').css('display', 'block'); $('#postForm').get(0).submit(); }; browser.fadeFiles = function() { $('#files > div').css({ opacity: '0.4', filter: 'alpha(opacity:40)' }); };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Object initializations * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.init = function() { if (!this.checkAgent()) return; $('body').click(function() { browser.hideDialog(); }); $('#shadow').click(function() { return false; }); $('#dialog').unbind(); $('#dialog').click(function() { return false; }); $('#alert').unbind(); $('#alert').click(function() { return false; }); this.initOpeners(); this.initSettings(); this.initContent(); this.initToolbar(); this.initResizer(); this.initDropUpload(); }; browser.checkAgent = function() { if (!$.browser.version || ($.browser.msie && (parseInt($.browser.version) < 7) && !this.support.chromeFrame) || ($.browser.opera && (parseInt($.browser.version) < 10)) || ($.browser.mozilla && (parseFloat($.browser.version.replace(/^(\d+(\.\d+)?)([^\d].*)?$/, "$1")) < 1.8)) ) { var html = '<div style="padding:10px">Your browser is not capable to display KCFinder. Please update your browser or install another one: <a href="http://www.mozilla.com/firefox/" target="_blank">Mozilla Firefox</a>, <a href="http://www.apple.com/safari" target="_blank">Apple Safari</a>, <a href="http://www.google.com/chrome" target="_blank">Google Chrome</a>, <a href="http://www.opera.com/browser" target="_blank">Opera</a>.'; if ($.browser.msie) html += ' You may also install <a href="http://www.google.com/chromeframe" target="_blank">Google Chrome Frame ActiveX plugin</a> to get Internet Explorer 6 working.'; html += '</div>'; $('body').html(html); return false; } return true; }; browser.initOpeners = function() { if (this.opener.TinyMCE && (typeof(tinyMCEPopup) == 'undefined')) this.opener.TinyMCE = null; if (this.opener.TinyMCE) this.opener.callBack = true; if ((!this.opener.name || (this.opener.name == 'fckeditor')) && window.opener && window.opener.SetUrl ) { this.opener.FCKeditor = true; this.opener.callBack = true; } if (this.opener.CKEditor) { if (window.parent && window.parent.CKEDITOR) this.opener.CKEditor.object = window.parent.CKEDITOR; else if (window.opener && window.opener.CKEDITOR) { this.opener.CKEditor.object = window.opener.CKEDITOR; this.opener.callBack = true; } else this.opener.CKEditor = null; } if (!this.opener.CKEditor && !this.opener.FCKEditor && !this.TinyMCE) { if ((window.opener && window.opener.KCFinder && window.opener.KCFinder.callBack) || (window.parent && window.parent.KCFinder && window.parent.KCFinder.callBack) ) this.opener.callBack = window.opener ? window.opener.KCFinder.callBack : window.parent.KCFinder.callBack; if (( window.opener && window.opener.KCFinder && window.opener.KCFinder.callBackMultiple ) || ( window.parent && window.parent.KCFinder && window.parent.KCFinder.callBackMultiple ) ) this.opener.callBackMultiple = window.opener ? window.opener.KCFinder.callBackMultiple : window.parent.KCFinder.callBackMultiple; } }; browser.initContent = function() { $('div#folders').html(this.label("Loading folders...")); $('div#files').html(this.label("Loading files...")); $.ajax({ type: 'GET', dataType: 'json', url: browser.baseGetData('init'), async: false, success: function(data) { if (browser.check4errors(data)) return; browser.dirWritable = data.dirWritable; $('#folders').html(browser.buildTree(data.tree)); browser.setTreeData(data.tree); browser.initFolders(); browser.files = data.files ? data.files : []; browser.orderFiles(); }, error: function() { $('div#folders').html(browser.label("Unknown error.")); $('div#files').html(browser.label("Unknown error.")); } }); }; browser.initResizer = function() { var cursor = ($.browser.opera) ? 'move' : 'col-resize'; $('#resizer').css('cursor', cursor); $('#resizer').drag('start', function() { $(this).css({opacity:'0.4', filter:'alpha(opacity:40)'}); $('#all').css('cursor', cursor); }); $('#resizer').drag(function(e) { var left = e.pageX - parseInt(_.nopx($(this).css('width')) / 2); left = (left >= 0) ? left : 0; left = (left + _.nopx($(this).css('width')) < $(window).width()) ? left : $(window).width() - _.nopx($(this).css('width')); $(this).css('left', left); }); var end = function() { $(this).css({opacity:'0', filter:'alpha(opacity:0)'}); $('#all').css('cursor', ''); var left = _.nopx($(this).css('left')) + _.nopx($(this).css('width')); var right = $(window).width() - left; $('#left').css('width', left + 'px'); $('#right').css('width', right + 'px'); _('files').style.width = $('#right').innerWidth() - _.outerHSpace('#files') + 'px'; _('resizer').style.left = $('#left').outerWidth() - _.outerRightSpace('#folders', 'm') + 'px'; _('resizer').style.width = _.outerRightSpace('#folders', 'm') + _.outerLeftSpace('#files', 'm') + 'px'; browser.fixFilesHeight(); }; $('#resizer').drag('end', end); $('#resizer').mouseup(end); }; browser.resize = function() { _('left').style.width = '25%'; _('right').style.width = '75%'; _('toolbar').style.height = $('#toolbar a').outerHeight() + "px"; _('shadow').style.width = $(window).width() + 'px'; _('shadow').style.height = _('resizer').style.height = $(window).height() + 'px'; _('left').style.height = _('right').style.height = $(window).height() - $('#status').outerHeight() + 'px'; _('folders').style.height = $('#left').outerHeight() - _.outerVSpace('#folders') + 'px'; browser.fixFilesHeight(); var width = $('#left').outerWidth() + $('#right').outerWidth(); _('status').style.width = width + 'px'; while ($('#status').outerWidth() > width) _('status').style.width = _.nopx(_('status').style.width) - 1 + 'px'; while ($('#status').outerWidth() < width) _('status').style.width = _.nopx(_('status').style.width) + 1 + 'px'; if ($.browser.msie && ($.browser.version.substr(0, 1) < 8)) _('right').style.width = $(window).width() - $('#left').outerWidth() + 'px'; _('files').style.width = $('#right').innerWidth() - _.outerHSpace('#files') + 'px'; _('resizer').style.left = $('#left').outerWidth() - _.outerRightSpace('#folders', 'm') + 'px'; _('resizer').style.width = _.outerRightSpace('#folders', 'm') + _.outerLeftSpace('#files', 'm') + 'px'; }; browser.fixFilesHeight = function() { _('files').style.height = $('#left').outerHeight() - $('#toolbar').outerHeight() - _.outerVSpace('#files') - (($('#settings').css('display') != "none") ? $('#settings').outerHeight() : 0) + 'px'; };
JavaScript
/** This file is part of KCFinder project * * @desc Helper object * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */ var _ = function(id) { return document.getElementById(id); }; _.nopx = function(val) { return parseInt(val.replace(/^(\d+)px$/, "$1")); }; _.unselect = function() { if (document.selection && document.selection.empty) document.selection.empty() ; else if (window.getSelection) { var sel = window.getSelection(); if (sel && sel.removeAllRanges) sel.removeAllRanges(); } }; _.selection = function(field, start, end) { if (field.createTextRange) { var selRange = field.createTextRange(); selRange.collapse(true); selRange.moveStart('character', start); selRange.moveEnd('character', end-start); selRange.select(); } else if (field.setSelectionRange) { field.setSelectionRange(start, end); } else if (field.selectionStart) { field.selectionStart = start; field.selectionEnd = end; } field.focus(); }; _.htmlValue = function(value) { return value .replace(/\&/g, "&amp;") .replace(/\"/g, "&quot;") .replace(/\'/g, "&#39;"); }; _.htmlData = function(value) { return value .replace(/\&/g, "&amp;") .replace(/\</g, "&lt;") .replace(/\>/g, "&gt;") .replace(/\ /g, "&nbsp;"); } _.jsValue = function(value) { return value .replace(/\\/g, "\\\\") .replace(/\r?\n/, "\\\n") .replace(/\"/g, "\\\"") .replace(/\'/g, "\\'"); }; _.basename = function(path) { var expr = /^.*\/([^\/]+)\/?$/g; return expr.test(path) ? path.replace(expr, "$1") : path; }; _.dirname = function(path) { var expr = /^(.*)\/[^\/]+\/?$/g; return expr.test(path) ? path.replace(expr, "$1") : ''; }; _.inArray = function(needle, arr) { if ((typeof arr == 'undefined') || !arr.length || !arr.push) return false; for (var i = 0; i < arr.length; i++) if (arr[i] == needle) return true; return false; }; _.getFileExtension = function(filename, toLower) { if (typeof(toLower) == 'undefined') toLower = true; if (/^.*\.[^\.]*$/.test(filename)) { var ext = filename.replace(/^.*\.([^\.]*)$/, "$1"); return toLower ? ext.toLowerCase(ext) : ext; } else return ""; }; _.escapeDirs = function(path) { var fullDirExpr = /^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/, prefix = ""; if (fullDirExpr.test(path)) { var port = path.replace(fullDirExpr, "$4"); prefix = path.replace(fullDirExpr, "$1://$2") if (port.length) prefix += ":" + port; prefix += "/"; path = path.replace(fullDirExpr, "$5"); } var dirs = path.split('/'); var escapePath = ''; for (var i = 0; i < dirs.length; i++) escapePath += encodeURIComponent(dirs[i]) + '/'; return prefix + escapePath.substr(0, escapePath.length - 1); }; _.outerSpace = function(selector, type, mbp) { if (!mbp) mbp = "mbp"; var r = 0; if (/m/i.test(mbp)) { var m = _.nopx($(selector).css('margin-' + type)); if (m) r += m; } if (/b/i.test(mbp)) { var b = _.nopx($(selector).css('border-' + type + '-width')); if (b) r += b; } if (/p/i.test(mbp)) { var p = _.nopx($(selector).css('padding-' + type)); if (p) r += p; } return r; }; _.outerLeftSpace = function(selector, mbp) { return _.outerSpace(selector, 'left', mbp); }; _.outerTopSpace = function(selector, mbp) { return _.outerSpace(selector, 'top', mbp); }; _.outerRightSpace = function(selector, mbp) { return _.outerSpace(selector, 'right', mbp); }; _.outerBottomSpace = function(selector, mbp) { return _.outerSpace(selector, 'bottom', mbp); }; _.outerHSpace = function(selector, mbp) { return (_.outerLeftSpace(selector, mbp) + _.outerRightSpace(selector, mbp)); }; _.outerVSpace = function(selector, mbp) { return (_.outerTopSpace(selector, mbp) + _.outerBottomSpace(selector, mbp)); }; _.kuki = { prefix: '', duration: 356, domain: '', path: '', secure: false, set: function(name, value, duration, domain, path, secure) { name = this.prefix + name; if (duration == null) duration = this.duration; if (secure == null) secure = this.secure; if ((domain == null) && this.domain) domain = this.domain; if ((path == null) && this.path) path = this.path; secure = secure ? true : false; var date = new Date(); date.setTime(date.getTime() + (duration * 86400000)); var expires = date.toGMTString(); var str = name + '=' + value + '; expires=' + expires; if (domain != null) str += '; domain=' + domain; if (path != null) str += '; path=' + path; if (secure) str += '; secure'; return (document.cookie = str) ? true : false; }, get: function(name) { name = this.prefix + name; var nameEQ = name + '='; var kukis = document.cookie.split(';'); var kuki; for (var i = 0; i < kukis.length; i++) { kuki = kukis[i]; while (kuki.charAt(0) == ' ') kuki = kuki.substring(1, kuki.length); if (kuki.indexOf(nameEQ) == 0) return kuki.substring(nameEQ.length, kuki.length); } return null; }, del: function(name) { return this.set(name, '', -1); }, isSet: function(name) { return (this.get(name) != null); } }; _.md5 = function(string) { var RotateLeft = function(lValue, iShiftBits) { return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits)); }; var AddUnsigned = function(lX,lY) { var lX4, lY4, lX8, lY8, lResult; lX8 = (lX & 0x80000000); lY8 = (lY & 0x80000000); lX4 = (lX & 0x40000000); lY4 = (lY & 0x40000000); lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF); if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8); if (lX4 | lY4) return (lResult & 0x40000000) ? (lResult ^ 0xC0000000 ^ lX8 ^ lY8) : (lResult ^ 0x40000000 ^ lX8 ^ lY8); else return (lResult ^ lX8 ^ lY8); }; var F = function(x, y, z) { return (x & y) | ((~x) & z); }; var G = function(x, y, z) { return (x & z) | (y & (~z)); }; var H = function(x, y, z) { return (x ^ y ^ z); }; var I = function(x, y, z) { return (y ^ (x | (~z))); }; var FF = function(a, b, c, d, x, s, ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); }; var GG = function(a, b, c, d, x, s, ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); }; var HH = function(a, b, c, d, x, s, ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); }; var II = function(a, b, c, d, x, s, ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); }; var ConvertToWordArray = function(string) { var lWordCount; var lMessageLength = string.length; var lNumberOfWords_temp1 = lMessageLength + 8; var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64; var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16; var lWordArray = [lNumberOfWords - 1]; var lBytePosition = 0; var lByteCount = 0; while (lByteCount < lMessageLength) { lWordCount = (lByteCount - (lByteCount % 4)) / 4; lBytePosition = (lByteCount % 4) * 8; lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition)); lByteCount++; } lWordCount = (lByteCount - (lByteCount % 4)) / 4; lBytePosition = (lByteCount % 4) * 8; lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition); lWordArray[lNumberOfWords - 2] = lMessageLength << 3; lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29; return lWordArray; }; var WordToHex = function(lValue) { var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount; for (lCount = 0; lCount <= 3; lCount++) { lByte = (lValue >>> (lCount * 8)) & 255; WordToHexValue_temp = "0" + lByte.toString(16); WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2,2); } return WordToHexValue; }; var x = []; var k, AA, BB, CC, DD, a, b, c, d; var S11 = 7, S12 = 12, S13 = 17, S14 = 22; var S21 = 5, S22 = 9, S23 = 14, S24 = 20; var S31 = 4, S32 = 11, S33 = 16, S34 = 23; var S41 = 6, S42 = 10, S43 = 15, S44 = 21; string = _.utf8encode(string); x = ConvertToWordArray(string); a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; for (k = 0; k < x.length; k += 16) { AA = a; BB = b; CC = c; DD = d; a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478); d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756); c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB); b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE); a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF); d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A); c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613); b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501); a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8); d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF); c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1); b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE); a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122); d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193); c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E); b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821); a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562); d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340); c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51); b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA); a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D); d = GG(d, a, b, c, x[k + 10], S22, 0x2441453); c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681); b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8); a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6); d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6); c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87); b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED); a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905); d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8); c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9); b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A); a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942); d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681); c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122); b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C); a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44); d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9); c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60); b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70); a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6); d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA); c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085); b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05); a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039); d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5); c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8); b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665); a = II(a, b, c, d, x[k + 0], S41, 0xF4292244); d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97); c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7); b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039); a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3); d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92); c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D); b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1); a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F); d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0); c = II(c, d, a, b, x[k + 6], S43, 0xA3014314); b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1); a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82); d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235); c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB); b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391); a = AddUnsigned(a, AA); b = AddUnsigned(b, BB); c = AddUnsigned(c, CC); d = AddUnsigned(d, DD); } var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d); return temp.toLowerCase(); }; _.utf8encode = function(string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; };
JavaScript
/*! * jQuery Right-Click Plugin * * Version 1.01 * * Cory S.N. LaViska * A Beautiful Site (http://abeautifulsite.net/) * 20 December 2008 * * Visit http://abeautifulsite.net/notebook/68 for more information * * License: * This plugin is dual-licensed under the GNU General Public License and the MIT License * and is copyright 2008 A Beautiful Site, LLC. */ if(jQuery){(function(){$.extend($.fn,{rightClick:function(a){$(this).each(function(){$(this).mousedown(function(c){var b=c;if($.browser.safari&&navigator.userAgent.indexOf("Mac")!=-1&&parseInt($.browser.version,10)<=525){if(b.button==2){a.call($(this),b);return false}else{return true}}else{$(this).mouseup(function(){$(this).unbind("mouseup");if(b.button==2){a.call($(this),b);return false}else{return true}})}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},rightMouseDown:function(a){$(this).each(function(){$(this).mousedown(function(b){if(b.button==2){a.call($(this),b);return false}else{return true}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},rightMouseUp:function(a){$(this).each(function(){$(this).mouseup(function(b){if(b.button==2){a.call($(this),b);return false}else{return true}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},noContext:function(){$(this).each(function(){$(this)[0].oncontextmenu=function(){return false}});return $(this)}})})(jQuery)};
JavaScript
// If this file exists in theme directory, it will be loaded in <head> section var imgLoading = new Image(); imgLoading.src = 'themes/oxygen/img/loading.gif';
JavaScript
// If this file exists in theme directory, it will be loaded in <head> section var imgLoading = new Image(); imgLoading.src = 'themes/dark/img/loading.gif';
JavaScript
/** * Galleria Flickr Plugin 2012-04-04 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function($) { /*global jQuery, Galleria, window */ Galleria.requires(1.25, 'The Flickr Plugin requires Galleria version 1.2.5 or later.'); // The script path var PATH = Galleria.utils.getScriptPath(); /** @class @constructor @example var flickr = new Galleria.Flickr(); @author http://aino.se @requires jQuery @requires Galleria @param {String} [api_key] Flickr API key to be used, defaults to the Galleria key @returns Instance */ Galleria.Flickr = function( api_key ) { this.api_key = api_key || '2a2ce06c15780ebeb0b706650fc890b2'; this.options = { max: 30, // photos to return imageSize: 'medium', // photo size ( thumb,small,medium,big,original ) thumbSize: 'thumb', // thumbnail size ( thumb,small,medium,big,original ) sort: 'interestingness-desc', // sort option ( date-posted-asc, date-posted-desc, date-taken-asc, date-taken-desc, interestingness-desc, interestingness-asc, relevance ) description: false, // set this to true to get description as caption complete: function(){}, // callback to be called inside the Galleria.prototype.load backlink: false // set this to true if you want to pass a link back to the original image }; }; Galleria.Flickr.prototype = { // bring back the constructor reference constructor: Galleria.Flickr, /** Search for anything at Flickr @param {String} phrase The string to search for @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ search: function( phrase, callback ) { return this._find({ text: phrase }, callback ); }, /** Search for anything at Flickr by tag @param {String} tag The tag(s) to search for @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ tags: function( tag, callback ) { return this._find({ tags: tag }, callback); }, /** Get a user's public photos @param {String} username The username as shown in the URL to fetch @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ user: function( username, callback ) { return this._call({ method: 'flickr.urls.lookupUser', url: 'flickr.com/photos/' + username }, function( data ) { this._find({ user_id: data.user.id, method: 'flickr.people.getPublicPhotos' }, callback); }); }, /** Get photos from a photoset by ID @param {String|Number} photoset_id The photoset id to fetch @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ set: function( photoset_id, callback ) { return this._find({ photoset_id: photoset_id, method: 'flickr.photosets.getPhotos' }, callback); }, /** Get photos from a gallery by ID @param {String|Number} gallery_id The gallery id to fetch @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ gallery: function( gallery_id, callback ) { return this._find({ gallery_id: gallery_id, method: 'flickr.galleries.getPhotos' }, callback); }, /** Search groups and fetch photos from the first group found Useful if you know the exact name of a group and want to show the groups photos. @param {String} group The group name to search for @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ groupsearch: function( group, callback ) { return this._call({ text: group, method: 'flickr.groups.search' }, function( data ) { this.group( data.groups.group[0].nsid, callback ); }); }, /** Get photos from a group by ID @param {String} group_id The group id to fetch @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ group: function ( group_id, callback ) { return this._find({ group_id: group_id, method: 'flickr.groups.pools.getPhotos' }, callback ); }, /** Set flickr options @param {Object} options The options object to blend @returns Instance */ setOptions: function( options ) { $.extend(this.options, options); return this; }, // call Flickr and raise errors _call: function( params, callback ) { var url = 'http://api.flickr.com/services/rest/?'; var scope = this; params = $.extend({ format : 'json', jsoncallback : '?', api_key: this.api_key }, params ); $.each(params, function( key, value ) { url += '&' + key + '=' + value; }); $.getJSON(url, function(data) { if ( data.stat === 'ok' ) { callback.call(scope, data); } else { Galleria.raise( data.code.toString() + ' ' + data.stat + ': ' + data.message, true ); } }); return scope; }, // "hidden" way of getting a big image (~1024) from flickr _getBig: function( photo ) { if ( photo.url_l ) { return photo.url_l; } else if ( parseInt( photo.width_o, 10 ) > 1280 ) { return 'http://farm'+photo.farm + '.static.flickr.com/'+photo.server + '/' + photo.id + '_' + photo.secret + '_b.jpg'; } return photo.url_o || photo.url_z || photo.url_m; }, // get image size by option name _getSize: function( photo, size ) { var img; switch(size) { case 'thumb': img = photo.url_t; break; case 'small': img = photo.url_s; break; case 'big': img = this._getBig( photo ); break; case 'original': img = photo.url_o ? photo.url_o : this._getBig( photo ); break; default: img = photo.url_z || photo.url_m; break; } return img; }, // ask flickr for photos, parse the result and call the callback with the galleria-ready data array _find: function( params, callback ) { params = $.extend({ method: 'flickr.photos.search', extras: 'url_t,url_m,url_o,url_s,url_l,url_z,description', sort: this.options.sort }, params ); return this._call( params, function(data) { var gallery = [], photos = data.photos ? data.photos.photo : data.photoset.photo, len = Math.min( this.options.max, photos.length ), photo, i; for ( i=0; i<len; i++ ) { photo = photos[i]; gallery.push({ thumb: this._getSize( photo, this.options.thumbSize ), image: this._getSize( photo, this.options.imageSize ), big: this._getBig( photo ), title: photos[i].title, description: this.options.description && photos[i].description ? photos[i].description._content : '', link: this.options.backlink ? 'http://flickr.com/photos/' + photo.owner + '/' + photo.id : '' }); } callback.call( this, gallery ); }); } }; /** Galleria modifications We fake-extend the load prototype to make Flickr integration as simple as possible */ // save the old prototype in a local variable var load = Galleria.prototype.load; // fake-extend the load prototype using the flickr data Galleria.prototype.load = function() { // pass if no data is provided or flickr option not found if ( arguments.length || typeof this._options.flickr !== 'string' ) { load.apply( this, Galleria.utils.array( arguments ) ); return; } // define some local vars var self = this, args = Galleria.utils.array( arguments ), flickr = this._options.flickr.split(':'), f, opts = $.extend({}, self._options.flickrOptions), loader = typeof opts.loader !== 'undefined' ? opts.loader : $('<div>').css({ width: 48, height: 48, opacity: 0.7, background:'#000 url('+PATH+'loader.gif) no-repeat 50% 50%' }); if ( flickr.length ) { // validate the method if ( typeof Galleria.Flickr.prototype[ flickr[0] ] !== 'function' ) { Galleria.raise( flickr[0] + ' method not found in Flickr plugin' ); return load.apply( this, args ); } // validate the argument if ( !flickr[1] ) { Galleria.raise( 'No flickr argument found' ); return load.apply( this, args ); } // apply the preloader window.setTimeout(function() { self.$( 'target' ).append( loader ); },100); // create the instance f = new Galleria.Flickr(); // apply Flickr options if ( typeof self._options.flickrOptions === 'object' ) { f.setOptions( self._options.flickrOptions ); } // call the flickr method and trigger the DATA event f[ flickr[0] ]( flickr[1], function( data ) { self._data = data; loader.remove(); self.trigger( Galleria.DATA ); f.options.complete.call(f, data); }); } else { // if flickr array not found, pass load.apply( this, args ); } }; }( jQuery ) );
JavaScript
/** * Galleria Picasa Plugin 2012-04-04 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function($) { /*global jQuery, Galleria, window */ Galleria.requires(1.25, 'The Picasa Plugin requires Galleria version 1.2.5 or later.'); // The script path var PATH = Galleria.utils.getScriptPath(); /** @class @constructor @example var picasa = new Galleria.Picasa(); @author http://aino.se @requires jQuery @requires Galleria @returns Instance */ Galleria.Picasa = function() { this.options = { max: 30, // photos to return imageSize: 'medium', // photo size ( thumb,small,medium,big,original ) or a number thumbSize: 'thumb', // thumbnail size ( thumb,small,medium,big,original ) or a number complete: function(){} // callback to be called inside the Galleria.prototype.load }; }; Galleria.Picasa.prototype = { // bring back the constructor reference constructor: Galleria.Picasa, /** Search for anything at Picasa @param {String} phrase The string to search for @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ search: function( phrase, callback ) { return this._call( 'search', 'all', { q: phrase }, callback ); }, /** Get a user's public photos @param {String} username The username to fetch photos from @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ user: function( username, callback ) { return this._call( 'user', 'user/' + username, callback ); }, /** Get photos from an album @param {String} username The username that owns the album @param {String} album The album ID @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ useralbum: function( username, album, callback ) { return this._call( 'useralbum', 'user/' + username + '/album/' + album, callback ); }, /** Set picasa options @param {Object} options The options object to blend @returns Instance */ setOptions: function( options ) { $.extend(this.options, options); return this; }, // call Picasa _call: function( type, url, params, callback ) { url = 'https://picasaweb.google.com/data/feed/api/' + url + '?'; if (typeof params == 'function') { callback = params; params = {}; } var self = this; params = $.extend({ 'kind': 'photo', 'access': 'public', 'max-results': this.options.max, 'thumbsize': this._getSizes().join(','), 'alt': 'json-in-script', 'callback': '?' }, params ); $.each(params, function( key, value ) { url += '&' + key + '=' + value; }); // since Picasa throws 404 when the call is malformed, we must set a timeout here: var data = false; Galleria.utils.wait({ until: function() { return data; }, success: function() { self._parse.call( self, data.feed.entry, callback ); }, error: function() { var msg = ''; if ( type == 'user' ) { msg = 'user not found.'; } else if ( type == 'useralbum' ) { msg = 'album or user not found.'; } Galleria.raise('Picasa request failed' + (msg ? ': ' + msg : '.')); }, timeout: 5000 }); $.getJSON( url, function( result ) { data = result; }); return self; }, // parse image sizes and return an array of three _getSizes: function() { var self = this, norm = { small: '72c', thumb: '104u', medium: '640u', big: '1024u', original: '1600u' }, op = self.options, t = {}, n, sz = [32,48,64,72,94,104,110,128,144,150,160,200,220,288,320,400,512,576,640,720,800,912,1024,1152,1280,1440,1600]; $(['thumbSize', 'imageSize']).each(function() { if( op[this] in norm ) { t[this] = norm[ op[this] ]; } else { n = Galleria.utils.parseValue( op[this] ); if (n > 1600) { n = 1600; } else { $.each( sz, function(i) { if ( n < this ) { n = sz[i-1]; return false; } }); } t[this] = n; } }); return [ t.thumbSize, t.imageSize, '1280u']; }, // parse the result and call the callback with the galleria-ready data array _parse: function( data, callback ) { var self = this, gallery = [], img; $.each( data, function() { img = this.media$group.media$thumbnail; gallery.push({ thumb: img[0].url, image: img[1].url, big: img[2].url, title: this.summary.$t }); }); callback.call( this, gallery ); } }; /** Galleria modifications We fake-extend the load prototype to make Picasa integration as simple as possible */ // save the old prototype in a local variable var load = Galleria.prototype.load; // fake-extend the load prototype using the picasa data Galleria.prototype.load = function() { // pass if no data is provided or picasa option not found if ( arguments.length || typeof this._options.picasa !== 'string' ) { load.apply( this, Galleria.utils.array( arguments ) ); return; } // define some local vars var self = this, args = Galleria.utils.array( arguments ), picasa = this._options.picasa.split(':'), p, opts = $.extend({}, self._options.picasaOptions), loader = typeof opts.loader !== 'undefined' ? opts.loader : $('<div>').css({ width: 48, height: 48, opacity: 0.7, background:'#000 url('+PATH+'loader.gif) no-repeat 50% 50%' }); if ( picasa.length ) { // validate the method if ( typeof Galleria.Picasa.prototype[ picasa[0] ] !== 'function' ) { Galleria.raise( picasa[0] + ' method not found in Picasa plugin' ); return load.apply( this, args ); } // validate the argument if ( !picasa[1] ) { Galleria.raise( 'No picasa argument found' ); return load.apply( this, args ); } // apply the preloader window.setTimeout(function() { self.$( 'target' ).append( loader ); },100); // create the instance p = new Galleria.Picasa(); // apply Flickr options if ( typeof self._options.picasaOptions === 'object' ) { p.setOptions( self._options.picasaOptions ); } // call the picasa method and trigger the DATA event var arg = []; if ( picasa[0] == 'useralbum' ) { arg = picasa[1].split('/'); if (arg.length != 2) { Galleria.raise( 'Picasa useralbum not correctly formatted (should be [user]/[album])'); return; } } else { arg.push( picasa[1] ); } arg.push(function(data) { self._data = data; loader.remove(); self.trigger( Galleria.DATA ); p.options.complete.call(p, data); }); p[ picasa[0] ].apply( p, arg ); } else { // if flickr array not found, pass load.apply( this, args ); } }; }( jQuery ) );
JavaScript
/** * Galleria History Plugin 2012-04-04 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function( $, window ) { /*global jQuery, Galleria, window */ Galleria.requires(1.25, 'The History Plugin requires Galleria version 1.2.5 or later.'); Galleria.History = (function() { var onloads = [], init = false, loc = window.location, doc = window.document, ie = Galleria.IE, support = 'onhashchange' in window && ( doc.mode === undefined || doc.mode > 7 ), iframe, get = function( winloc ) { if( iframe && !support && Galleria.IE ) { winloc = winloc || iframe.location; } else { winloc = loc; } return parseInt( winloc.hash.substr(2), 10 ); }, saved = get( loc ), callbacks = [], onchange = function() { $.each( callbacks, function( i, fn ) { fn.call( window, get() ); }); }, ready = function() { $.each( onloads, function(i, fn) { fn(); }); init = true; }, setHash = function( val ) { return '/' + val; }; // always remove support if IE < 8 if ( support && ie < 8 ) { support = false; } if ( !support ) { $(function() { var interval = window.setInterval(function() { var hash = get(); if ( !isNaN( hash ) && hash != saved ) { saved = hash; loc.hash = setHash( hash ); onchange(); } }, 50); if ( ie ) { $('<iframe tabindex="-1" title="empty">').hide().attr( 'src', 'about:blank' ).one('load', function() { iframe = this.contentWindow; ready(); }).insertAfter(doc.body); } else { ready(); } }); } else { ready(); } return { change: function( fn ) { callbacks.push( fn ); if( support ) { window.onhashchange = onchange; } }, set: function( val ) { if ( isNaN( val ) ) { return; } if ( !support && ie ) { this.ready(function() { var idoc = iframe.document; idoc.open(); idoc.close(); iframe.location.hash = setHash( val ); }); } loc.hash = setHash( val ); }, ready: function(fn) { if (!init) { onloads.push(fn); } else { fn(); } } }; }()); }( jQuery, this ));
JavaScript
/** * Galleria v 1.2.7 2012-04-04 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function( $ ) { /*global jQuery, navigator, Galleria:true, Image */ // some references var undef, window = this, doc = window.document, $doc = $( doc ), $win = $( window ), // native prototypes protoArray = Array.prototype, // internal constants VERSION = 1.27, DEBUG = true, TIMEOUT = 30000, DUMMY = false, NAV = navigator.userAgent.toLowerCase(), HASH = window.location.hash.replace(/#\//, ''), F = function(){}, FALSE = function() { return false; }, IE = (function() { var v = 3, div = doc.createElement( 'div' ), all = div.getElementsByTagName( 'i' ); do { div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->'; } while ( all[0] ); return v > 4 ? v : undef; }() ), DOM = function() { return { html: doc.documentElement, body: doc.body, head: doc.getElementsByTagName('head')[0], title: doc.title }; }, // list of Galleria events _eventlist = 'data ready thumbnail loadstart loadfinish image play pause progress ' + 'fullscreen_enter fullscreen_exit idle_enter idle_exit rescale ' + 'lightbox_open lightbox_close lightbox_image', _events = (function() { var evs = []; $.each( _eventlist.split(' '), function( i, ev ) { evs.push( ev ); // legacy events if ( /_/.test( ev ) ) { evs.push( ev.replace( /_/g, '' ) ); } }); return evs; }()), // legacy options // allows the old my_setting syntax and converts it to camel case _legacyOptions = function( options ) { var n; if ( typeof options !== 'object' ) { // return whatever it was... return options; } $.each( options, function( key, value ) { if ( /^[a-z]+_/.test( key ) ) { n = ''; $.each( key.split('_'), function( i, k ) { n += i > 0 ? k.substr( 0, 1 ).toUpperCase() + k.substr( 1 ) : k; }); options[ n ] = value; delete options[ key ]; } }); return options; }, _patchEvent = function( type ) { // allow 'image' instead of Galleria.IMAGE if ( $.inArray( type, _events ) > -1 ) { return Galleria[ type.toUpperCase() ]; } return type; }, // video providers _video = { youtube: { reg: /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&amp;(?:amp;)?)*v(?:&lt;[A-Z]+&gt;)?=([0-9a-zA-Z\-\_]+))/i, embed: function(id) { return 'http://www.youtube.com/embed/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=json-in-script&callback=?', function(data) { try { success( data.entry.media$group.media$thumbnail[0].url ); } catch(e) { fail(); } }).error(fail); } }, vimeo: { reg: /https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i, embed: function(id) { return 'http://player.vimeo.com/video/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('http://vimeo.com/api/v2/video/' + id + '.json?callback=?', function(data) { try { success( data[0].thumbnail_medium ); } catch(e) { fail(); } }).error(fail); } }, dailymotion: { reg: /https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/, embed: function(id) { return 'http://www.dailymotion.com/embed/video/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('https://api.dailymotion.com/video/'+id+'?fields=thumbnail_medium_url&callback=?', function(data) { try { success( data.thumbnail_medium_url ); } catch(e) { fail(); } }).error(fail); } } }, // utility for testing the video URL and getting the video ID _videoTest = function( url ) { var match; for ( var v in _video ) { match = url && url.match( _video[v].reg ); if( match && match.length ) { return { id: match[2], provider: v }; } } return false; }, // the internal timeouts object // provides helper methods for controlling timeouts _timeouts = { trunk: {}, add: function( id, fn, delay, loop ) { id = id || new Date().getTime(); loop = loop || false; this.clear( id ); if ( loop ) { var old = fn; fn = function() { old(); _timeouts.add( id, fn, delay ); }; } this.trunk[ id ] = window.setTimeout( fn, delay ); }, clear: function( id ) { var del = function( i ) { window.clearTimeout( this.trunk[ i ] ); delete this.trunk[ i ]; }, i; if ( !!id && id in this.trunk ) { del.call( _timeouts, id ); } else if ( typeof id === 'undefined' ) { for ( i in this.trunk ) { if ( this.trunk.hasOwnProperty( i ) ) { del.call( _timeouts, i ); } } } } }, // the internal gallery holder _galleries = [], // the internal instance holder _instances = [], // flag for errors _hasError = false, // canvas holder _canvas = false, // instance pool, holds the galleries until themeLoad is triggered _pool = [], // themeLoad trigger _themeLoad = function( theme ) { Galleria.theme = theme; // run the instances we have in the pool $.each( _pool, function( i, instance ) { if ( !instance._initialized ) { instance._init.call( instance ); } }); }, // the Utils singleton Utils = (function() { return { array : function( obj ) { return protoArray.slice.call(obj, 0); }, create : function( className, nodeName ) { nodeName = nodeName || 'div'; var elem = doc.createElement( nodeName ); elem.className = className; return elem; }, getScriptPath : function( src ) { // the currently executing script is always the last src = src || $('script:last').attr('src'); var slices = src.split('/'); if (slices.length == 1) { return ''; } slices.pop(); return slices.join('/') + '/'; }, // CSS3 transitions, added in 1.2.4 animate : (function() { // detect transition var transition = (function( style ) { var props = 'transition WebkitTransition MozTransition OTransition'.split(' '), i; // disable css3 animations in opera until stable if ( window.opera ) { return false; } for ( i = 0; props[i]; i++ ) { if ( typeof style[ props[ i ] ] !== 'undefined' ) { return props[ i ]; } } return false; }(( doc.body || doc.documentElement).style )); // map transitionend event var endEvent = { MozTransition: 'transitionend', OTransition: 'oTransitionEnd', WebkitTransition: 'webkitTransitionEnd', transition: 'transitionend' }[ transition ]; // map bezier easing conversions var easings = { _default: [0.25, 0.1, 0.25, 1], galleria: [0.645, 0.045, 0.355, 1], galleriaIn: [0.55, 0.085, 0.68, 0.53], galleriaOut: [0.25, 0.46, 0.45, 0.94], ease: [0.25, 0, 0.25, 1], linear: [0.25, 0.25, 0.75, 0.75], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }; // function for setting transition css for all browsers var setStyle = function( elem, value, suffix ) { var css = {}; suffix = suffix || 'transition'; $.each( 'webkit moz ms o'.split(' '), function() { css[ '-' + this + '-' + suffix ] = value; }); elem.css( css ); }; // clear styles var clearStyle = function( elem ) { setStyle( elem, 'none', 'transition' ); if ( Galleria.WEBKIT && Galleria.TOUCH ) { setStyle( elem, 'translate3d(0,0,0)', 'transform' ); if ( elem.data('revert') ) { elem.css( elem.data('revert') ); elem.data('revert', null); } } }; // various variables var change, strings, easing, syntax, revert, form, css; // the actual animation method return function( elem, to, options ) { // extend defaults options = $.extend({ duration: 400, complete: F, stop: false }, options); // cache jQuery instance elem = $( elem ); if ( !options.duration ) { elem.css( to ); options.complete.call( elem[0] ); return; } // fallback to jQuery's animate if transition is not supported if ( !transition ) { elem.animate(to, options); return; } // stop if ( options.stop ) { // clear the animation elem.unbind( endEvent ); clearStyle( elem ); } // see if there is a change change = false; $.each( to, function( key, val ) { css = elem.css( key ); if ( Utils.parseValue( css ) != Utils.parseValue( val ) ) { change = true; } // also add computed styles for FF elem.css( key, css ); }); if ( !change ) { window.setTimeout( function() { options.complete.call( elem[0] ); }, options.duration ); return; } // the css strings to be applied strings = []; // the easing bezier easing = options.easing in easings ? easings[ options.easing ] : easings._default; // the syntax syntax = ' ' + options.duration + 'ms' + ' cubic-bezier(' + easing.join(',') + ')'; // add a tiny timeout so that the browsers catches any css changes before animating window.setTimeout( (function(elem, endEvent, to, syntax) { return function() { // attach the end event elem.one(endEvent, (function( elem ) { return function() { // clear the animation clearStyle(elem); // run the complete method options.complete.call(elem[0]); }; }( elem ))); // do the webkit translate3d for better performance on iOS if( Galleria.WEBKIT && Galleria.TOUCH ) { revert = {}; form = [0,0,0]; $.each( ['left', 'top'], function(i, m) { if ( m in to ) { form[ i ] = ( Utils.parseValue( to[ m ] ) - Utils.parseValue(elem.css( m )) ) + 'px'; revert[ m ] = to[ m ]; delete to[ m ]; } }); if ( form[0] || form[1]) { elem.data('revert', revert); strings.push('-webkit-transform' + syntax); // 3d animate setStyle( elem, 'translate3d(' + form.join(',') + ')', 'transform'); } } // push the animation props $.each(to, function( p, val ) { strings.push(p + syntax); }); // set the animation styles setStyle( elem, strings.join(',') ); // animate elem.css( to ); }; }(elem, endEvent, to, syntax)), 2); }; }()), removeAlpha : function( elem ) { if ( IE < 9 && elem ) { var style = elem.style, currentStyle = elem.currentStyle, filter = currentStyle && currentStyle.filter || style.filter || ""; if ( /alpha/.test( filter ) ) { style.filter = filter.replace( /alpha\([^)]*\)/i, '' ); } } }, forceStyles : function( elem, styles ) { elem = $(elem); if ( elem.attr( 'style' ) ) { elem.data( 'styles', elem.attr( 'style' ) ).removeAttr( 'style' ); } elem.css( styles ); }, revertStyles : function() { $.each( Utils.array( arguments ), function( i, elem ) { elem = $( elem ); elem.removeAttr( 'style' ); elem.attr('style',''); // "fixes" webkit bug if ( elem.data( 'styles' ) ) { elem.attr( 'style', elem.data('styles') ).data( 'styles', null ); } }); }, moveOut : function( elem ) { Utils.forceStyles( elem, { position: 'absolute', left: -10000 }); }, moveIn : function() { Utils.revertStyles.apply( Utils, Utils.array( arguments ) ); }, elem : function( elem ) { if (elem instanceof $) { return { $: elem, dom: elem[0] }; } else { return { $: $(elem), dom: elem }; } }, hide : function( elem, speed, callback ) { callback = callback || F; var el = Utils.elem( elem ), $elem = el.$; elem = el.dom; // save the value if not exist if (! $elem.data('opacity') ) { $elem.data('opacity', $elem.css('opacity') ); } // always hide var style = { opacity: 0 }; if (speed) { var complete = IE < 9 && elem ? function() { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; } else { $elem.css( style ); } } }, show : function( elem, speed, callback ) { callback = callback || F; var el = Utils.elem( elem ), $elem = el.$; elem = el.dom; // bring back saved opacity var saved = parseFloat( $elem.data('opacity') ) || 1, style = { opacity: saved }; // animate or toggle if (speed) { if ( IE < 9 ) { $elem.css('opacity', 0); elem.style.visibility = 'visible'; } var complete = IE < 9 && elem ? function() { if ( style.opacity == 1 ) { Utils.removeAlpha( elem ); } callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && style.opacity == 1 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'visible'; } else { $elem.css( style ); } } }, // enhanced click for mobile devices // we bind a touchend and hijack any click event in the bubble // then we execute the click directly and save it in a separate data object for later optimizeTouch: (function() { var node, evs, fakes, travel, evt = {}, handler = function( e ) { e.preventDefault(); evt = $.extend({}, e, true); }, attach = function() { this.evt = evt; }, fake = function() { this.handler.call(node, this.evt); }; return function( elem ) { $(elem).bind('touchend', function( e ) { node = e.target; travel = true; while( node.parentNode && node != e.currentTarget && travel ) { evs = $(node).data('events'); fakes = $(node).data('fakes'); if (evs && 'click' in evs) { travel = false; e.preventDefault(); // fake the click and save the event object $(node).click(handler).click(); // remove the faked click evs.click.pop(); // attach the faked event $.each( evs.click, attach); // save the faked clicks in a new data object $(node).data('fakes', evs.click); // remove all clicks delete evs.click; } else if ( fakes ) { travel = false; e.preventDefault(); // fake all clicks $.each( fakes, fake ); } // bubble node = node.parentNode; } }); }; }()), addTimer : function() { _timeouts.add.apply( _timeouts, Utils.array( arguments ) ); return this; }, clearTimer : function() { _timeouts.clear.apply( _timeouts, Utils.array( arguments ) ); return this; }, wait : function(options) { options = $.extend({ until : FALSE, success : F, error : function() { Galleria.raise('Could not complete wait function.'); }, timeout: 3000 }, options); var start = Utils.timestamp(), elapsed, now, fn = function() { now = Utils.timestamp(); elapsed = now - start; if ( options.until( elapsed ) ) { options.success(); return false; } if (typeof options.timeout == 'number' && now >= start + options.timeout) { options.error(); return false; } window.setTimeout(fn, 10); }; window.setTimeout(fn, 10); }, toggleQuality : function( img, force ) { if ( ( IE !== 7 && IE !== 8 ) || !img || img.nodeName.toUpperCase() != 'IMG' ) { return; } if ( typeof force === 'undefined' ) { force = img.style.msInterpolationMode === 'nearest-neighbor'; } img.style.msInterpolationMode = force ? 'bicubic' : 'nearest-neighbor'; }, insertStyleTag : function( styles ) { var style = doc.createElement( 'style' ); DOM().head.appendChild( style ); if ( style.styleSheet ) { // IE style.styleSheet.cssText = styles; } else { var cssText = doc.createTextNode( styles ); style.appendChild( cssText ); } }, // a loadscript method that works for local scripts loadScript: function( url, callback ) { var done = false, script = $('<scr'+'ipt>').attr({ src: url, async: true }).get(0); // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') ) { done = true; // Handle memory leak in IE script.onload = script.onreadystatechange = null; if (typeof callback === 'function') { callback.call( this, this ); } } }; DOM().head.appendChild( script ); }, // parse anything into a number parseValue: function( val ) { if (typeof val === 'number') { return val; } else if (typeof val === 'string') { var arr = val.match(/\-?\d|\./g); return arr && arr.constructor === Array ? arr.join('')*1 : 0; } else { return 0; } }, // timestamp abstraction timestamp: function() { return new Date().getTime(); }, // this is pretty crap, but works for now // it will add a callback, but it can't guarantee that the styles can be fetched // using getComputedStyle further checking needed, possibly a dummy element loadCSS : function( href, id, callback ) { var link, ready = false, length, lastChance = function() { var fake = new Image(); fake.onload = fake.onerror = function(e) { fake = null; ready = true; }; fake.src = href; }; // look for manual css $('link[rel=stylesheet]').each(function() { if ( new RegExp( href ).test( this.href ) ) { link = this; return false; } }); if ( typeof id === 'function' ) { callback = id; id = undef; } callback = callback || F; // dirty // if already present, return if ( link ) { callback.call( link, link ); return link; } // save the length of stylesheets to check against length = doc.styleSheets.length; // check for existing id if( $('#'+id).length ) { $('#'+id).attr('href', href); length--; ready = true; } else { link = $( '<link>' ).attr({ rel: 'stylesheet', href: href, id: id }).get(0); window.setTimeout(function() { var styles = $('link[rel="stylesheet"], style'); if ( styles.length ) { styles.get(0).parentNode.insertBefore( link, styles[0] ); } else { DOM().head.appendChild( link ); } if ( IE ) { // IE has a limit of 31 stylesheets in one document if( length >= 31 ) { Galleria.raise( 'You have reached the browser stylesheet limit (31)', true ); return; } link.onreadystatechange = function(e) { if ( !ready && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') ) { ready = true; } }; } else { // final test via ajax var dum = doc.createElement('a'), loc = window.location; dum.href = href; if ( !( /file/.test( loc.protocol ) ) && loc.hostname == dum.hostname && loc.port == dum.port && loc.protocol == dum.protocol ) { // Same origin policy should apply $.ajax({ url: href, success: function() { ready = true; }, error: lastChance }); } else { lastChance(); } } }, 10); } if ( typeof callback === 'function' ) { Utils.wait({ until: function() { return ready && doc.styleSheets.length > length; }, success: function() { window.setTimeout( function() { callback.call( link, link ); }, 100); }, error: function() { Galleria.raise( 'Theme CSS could not load', true ); }, timeout: 10000 }); } return link; } }; }()), // the transitions holder _transitions = (function() { var _slide = function(params, complete, fade, door) { var easing = this.getOptions('easing'), distance = this.getStageWidth(), from = { left: distance * ( params.rewind ? -1 : 1 ) }, to = { left: 0 }; if ( fade ) { from.opacity = 0; to.opacity = 1; } else { from.opacity = 1; } $(params.next).css(from); Utils.animate(params.next, to, { duration: params.speed, complete: (function( elems ) { return function() { complete(); elems.css({ left: 0 }); }; }( $( params.next ).add( params.prev ) )), queue: false, easing: easing }); if (door) { params.rewind = !params.rewind; } if (params.prev) { from = { left: 0 }; to = { left: distance * ( params.rewind ? 1 : -1 ) }; if ( fade ) { from.opacity = 1; to.opacity = 0; } $(params.prev).css(from); Utils.animate(params.prev, to, { duration: params.speed, queue: false, easing: easing, complete: function() { $(this).css('opacity', 0); } }); } }; return { fade: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); if (params.prev) { $(params.prev).css('opacity',1).show(); Utils.animate(params.prev, { opacity: 0 },{ duration: params.speed }); } }, flash: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }); if (params.prev) { Utils.animate( params.prev, { opacity: 0 },{ duration: params.speed/2, complete: function() { Utils.animate( params.next, { opacity:1 },{ duration: params.speed, complete: complete }); } }); } else { Utils.animate( params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); } }, pulse: function(params, complete) { if (params.prev) { $(params.prev).hide(); } $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity:1 },{ duration: params.speed, complete: complete }); }, slide: function(params, complete) { _slide.apply( this, Utils.array( arguments ) ); }, fadeslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [true] ) ); }, doorslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [false, true] ) ); } }; }()); /** The main Galleria class @class @constructor @example var gallery = new Galleria(); @author http://aino.se @requires jQuery */ Galleria = function() { var self = this; // internal options this._options = {}; // flag for controlling play/pause this._playing = false; // internal interval for slideshow this._playtime = 5000; // internal variable for the currently active image this._active = null; // the internal queue, arrayified this._queue = { length: 0 }; // the internal data array this._data = []; // the internal dom collection this._dom = {}; // the internal thumbnails array this._thumbnails = []; // the internal layers array this._layers = []; // internal init flag this._initialized = false; // internal firstrun flag this._firstrun = false; // global stagewidth/height this._stageWidth = 0; this._stageHeight = 0; // target holder this._target = undef; // instance id this._id = parseInt(Math.random()*10000, 10); // add some elements var divs = 'container stage images image-nav image-nav-left image-nav-right ' + 'info info-text info-title info-description ' + 'thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right ' + 'loader counter tooltip', spans = 'current total'; $.each( divs.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId ); }); $.each( spans.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId, 'span' ); }); // the internal keyboard object // keeps reference of the keybinds and provides helper methods for binding keys var keyboard = this._keyboard = { keys : { 'UP': 38, 'DOWN': 40, 'LEFT': 37, 'RIGHT': 39, 'RETURN': 13, 'ESCAPE': 27, 'BACKSPACE': 8, 'SPACE': 32 }, map : {}, bound: false, press: function(e) { var key = e.keyCode || e.which; if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) { keyboard.map[key].call(self, e); } }, attach: function(map) { var key, up; for( key in map ) { if ( map.hasOwnProperty( key ) ) { up = key.toUpperCase(); if ( up in keyboard.keys ) { keyboard.map[ keyboard.keys[up] ] = map[key]; } else { keyboard.map[ up ] = map[key]; } } } if ( !keyboard.bound ) { keyboard.bound = true; $doc.bind('keydown', keyboard.press); } }, detach: function() { keyboard.bound = false; keyboard.map = {}; $doc.unbind('keydown', keyboard.press); } }; // internal controls for keeping track of active / inactive images var controls = this._controls = { 0: undef, 1: undef, active : 0, swap : function() { controls.active = controls.active ? 0 : 1; }, getActive : function() { return controls[ controls.active ]; }, getNext : function() { return controls[ 1 - controls.active ]; } }; // internal carousel object var carousel = this._carousel = { // shortcuts next: self.$('thumb-nav-right'), prev: self.$('thumb-nav-left'), // cache the width width: 0, // track the current position current: 0, // cache max value max: 0, // save all hooks for each width in an array hooks: [], // update the carousel // you can run this method anytime, f.ex on window.resize update: function() { var w = 0, h = 0, hooks = [0]; $.each( self._thumbnails, function( i, thumb ) { if ( thumb.ready ) { w += thumb.outerWidth || $( thumb.container ).outerWidth( true ); hooks[ i+1 ] = w; h = Math.max( h, thumb.outerHeight || $( thumb.container).outerHeight( true ) ); } }); self.$( 'thumbnails' ).css({ width: w, height: h }); carousel.max = w; carousel.hooks = hooks; carousel.width = self.$( 'thumbnails-list' ).width(); carousel.setClasses(); self.$( 'thumbnails-container' ).toggleClass( 'galleria-carousel', w > carousel.width ); // one extra calculation carousel.width = self.$( 'thumbnails-list' ).width(); // todo: fix so the carousel moves to the left }, bindControls: function() { var i; carousel.next.bind( 'click', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i < carousel.hooks.length; i++ ) { if ( carousel.hooks[i] - carousel.hooks[ carousel.current ] > carousel.width ) { carousel.set(i - 2); break; } } } else { carousel.set( carousel.current + self._options.carouselSteps); } }); carousel.prev.bind( 'click', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i >= 0; i-- ) { if ( carousel.hooks[ carousel.current ] - carousel.hooks[i] > carousel.width ) { carousel.set( i + 2 ); break; } else if ( i === 0 ) { carousel.set( 0 ); break; } } } else { carousel.set( carousel.current - self._options.carouselSteps ); } }); }, // calculate and set positions set: function( i ) { i = Math.max( i, 0 ); while ( carousel.hooks[i - 1] + carousel.width >= carousel.max && i >= 0 ) { i--; } carousel.current = i; carousel.animate(); }, // get the last position getLast: function(i) { return ( i || carousel.current ) - 1; }, // follow the active image follow: function(i) { //don't follow if position fits if ( i === 0 || i === carousel.hooks.length - 2 ) { carousel.set( i ); return; } // calculate last position var last = carousel.current; while( carousel.hooks[last] - carousel.hooks[ carousel.current ] < carousel.width && last <= carousel.hooks.length ) { last ++; } // set position if ( i - 1 < carousel.current ) { carousel.set( i - 1 ); } else if ( i + 2 > last) { carousel.set( i - last + carousel.current + 2 ); } }, // helper for setting disabled classes setClasses: function() { carousel.prev.toggleClass( 'disabled', !carousel.current ); carousel.next.toggleClass( 'disabled', carousel.hooks[ carousel.current ] + carousel.width >= carousel.max ); }, // the animation method animate: function(to) { carousel.setClasses(); var num = carousel.hooks[ carousel.current ] * -1; if ( isNaN( num ) ) { return; } Utils.animate(self.get( 'thumbnails' ), { left: num },{ duration: self._options.carouselSpeed, easing: self._options.easing, queue: false }); } }; // tooltip control // added in 1.2 var tooltip = this._tooltip = { initialized : false, open: false, timer: 'tooltip' + self._id, swapTimer: 'swap' + self._id, init: function() { tooltip.initialized = true; var css = '.galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3' + 'opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}'; Utils.insertStyleTag(css); self.$( 'tooltip' ).css('opacity', 0.8); Utils.hide( self.get('tooltip') ); }, // move handler move: function( e ) { var mouseX = self.getMousePosition(e).x, mouseY = self.getMousePosition(e).y, $elem = self.$( 'tooltip' ), x = mouseX, y = mouseY, height = $elem.outerHeight( true ) + 1, width = $elem.outerWidth( true ), limitY = height + 15; var maxX = self.$( 'container').width() - width - 2, maxY = self.$( 'container').height() - height - 2; if ( !isNaN(x) && !isNaN(y) ) { x += 10; y -= 30; x = Math.max( 0, Math.min( maxX, x ) ); y = Math.max( 0, Math.min( maxY, y ) ); if( mouseY < limitY ) { y = limitY; } $elem.css({ left: x, top: y }); } }, // bind elements to the tooltip // you can bind multiple elementIDs using { elemID : function } or { elemID : string } // you can also bind single DOM elements using bind(elem, string) bind: function( elem, value ) { // todo: revise if alternative tooltip is needed for mobile devices if (Galleria.TOUCH) { return; } if (! tooltip.initialized ) { tooltip.init(); } var hover = function( elem, value) { tooltip.define( elem, value ); $( elem ).hover(function() { Utils.clearTimer( tooltip.swapTimer ); self.$('container').unbind( 'mousemove', tooltip.move ).bind( 'mousemove', tooltip.move ).trigger( 'mousemove' ); tooltip.show( elem ); Utils.addTimer( tooltip.timer, function() { self.$( 'tooltip' ).stop().show().animate({ opacity:1 }); tooltip.open = true; }, tooltip.open ? 0 : 500); }, function() { self.$( 'container' ).unbind( 'mousemove', tooltip.move ); Utils.clearTimer( tooltip.timer ); self.$( 'tooltip' ).stop().animate({ opacity: 0 }, 200, function() { self.$( 'tooltip' ).hide(); Utils.addTimer( tooltip.swapTimer, function() { tooltip.open = false; }, 1000); }); }).click(function() { $( this ).trigger( 'mouseout' ); }); }; if ( typeof value === 'string' ) { hover( ( elem in self._dom ? self.get( elem ) : elem ), value ); } else { // asume elemID here $.each( elem, function( elemID, val ) { hover( self.get(elemID), val ); }); } }, show: function( elem ) { elem = $( elem in self._dom ? self.get(elem) : elem ); var text = elem.data( 'tt' ), mouseup = function( e ) { // attach a tiny settimeout to make sure the new tooltip is filled window.setTimeout( (function( ev ) { return function() { tooltip.move( ev ); }; }( e )), 10); elem.unbind( 'mouseup', mouseup ); }; text = typeof text === 'function' ? text() : text; if ( ! text ) { return; } self.$( 'tooltip' ).html( text.replace(/\s/, '&nbsp;') ); // trigger mousemove on mouseup in case of click elem.bind( 'mouseup', mouseup ); }, define: function( elem, value ) { // we store functions, not strings if (typeof value !== 'function') { var s = value; value = function() { return s; }; } elem = $( elem in self._dom ? self.get(elem) : elem ).data('tt', value); tooltip.show( elem ); } }; // internal fullscreen control var fullscreen = this._fullscreen = { scrolled: 0, crop: undef, transition: undef, active: false, keymap: self._keyboard.map, // The native fullscreen handler os: { callback: F, support: (function() { var html = DOM().html; return html.requestFullscreen || html.mozRequestFullScreen || html.webkitRequestFullScreen; }()), enter: function( callback ) { fullscreen.os.callback = callback || F; var html = DOM().html; if ( html.requestFullscreen ) { html.requestFullscreen(); } else if ( html.mozRequestFullScreen ) { html.mozRequestFullScreen(); } else if ( html.webkitRequestFullScreen ) { html.webkitRequestFullScreen(); } }, exit: function( callback ) { fullscreen.os.callback = callback || F; if ( doc.exitFullscreen ) { doc.exitFullscreen(); } else if ( doc.mozCancelFullScreen ) { doc.mozCancelFullScreen(); } else if ( doc.webkitCancelFullScreen ) { doc.webkitCancelFullScreen(); } }, listen: function() { if ( !fullscreen.os.support ) { return; } var handler = function() { if ( doc.fullscreen || doc.mozFullScreen || doc.webkitIsFullScreen ) { fullscreen._enter( fullscreen.os.callback ); } else { fullscreen._exit( fullscreen.os.callback ); } }; doc.addEventListener( 'fullscreenchange', handler, false ); doc.addEventListener( 'mozfullscreenchange', handler, false ); doc.addEventListener( 'webkitfullscreenchange', handler, false ); } }, enter: function( callback ) { if ( self._options.trueFullscreen && fullscreen.os.support ) { fullscreen.os.enter( callback ); } else { fullscreen._enter( callback ); } }, _enter: function( callback ) { fullscreen.active = true; // hide the image until rescale is complete Utils.hide( self.getActiveImage() ); self.$( 'container' ).addClass( 'fullscreen' ); fullscreen.scrolled = $win.scrollTop(); // begin styleforce Utils.forceStyles(self.get('container'), { position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10000 }); var htmlbody = { height: '100%', overflow: 'hidden', margin:0, padding:0 }, data = self.getData(), options = self._options; Utils.forceStyles( DOM().html, htmlbody ); Utils.forceStyles( DOM().body, htmlbody ); // temporarily attach some keys // save the old ones first in a cloned object fullscreen.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: self.exitFullscreen, right: self.next, left: self.prev }); // temporarily save the crop fullscreen.crop = options.imageCrop; // set fullscreen options if ( options.fullscreenCrop != undef ) { options.imageCrop = options.fullscreenCrop; } // swap to big image if it's different from the display image if ( data && data.big && data.image !== data.big ) { var big = new Galleria.Picture(), cached = big.isCached( data.big ), index = self.getIndex(), thumb = self._thumbnails[ index ]; self.trigger( { type: Galleria.LOADSTART, cached: cached, rewind: false, index: index, imageTarget: self.getActiveImage(), thumbTarget: thumb, galleriaData: data }); big.load( data.big, function( big ) { self._scaleImage( big, { complete: function( big ) { self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: index, rewind: false, imageTarget: big.image, thumbTarget: thumb }); var image = self._controls.getActive().image; if ( image ) { $( image ).width( big.image.width ).height( big.image.height ) .attr( 'style', $( big.image ).attr('style') ) .attr( 'src', big.image.src ); } } }); }); } // init the first rescale and attach callbacks self.rescale(function() { Utils.addTimer(false, function() { // show the image after 50 ms Utils.show( self.getActiveImage() ); if (typeof callback === 'function') { callback.call( self ); } }, 100); self.trigger( Galleria.FULLSCREEN_ENTER ); }); // bind the scaling to the resize event $win.resize( function() { fullscreen.scale(); } ); }, scale : function() { self.rescale(); }, exit: function( callback ) { if ( self._options.trueFullscreen && fullscreen.os.support ) { fullscreen.os.exit( callback ); } else { fullscreen._exit( callback ); } }, _exit: function( callback ) { fullscreen.active = false; Utils.hide( self.getActiveImage() ); self.$('container').removeClass( 'fullscreen' ); // revert all styles Utils.revertStyles( self.get('container'), DOM().html, DOM().body ); // scroll back window.scrollTo(0, fullscreen.scrolled); // detach all keyboard events and apply the old keymap self.detachKeyboard(); self.attachKeyboard( fullscreen.keymap ); // bring back cached options self._options.imageCrop = fullscreen.crop; //self._options.transition = fullscreen.transition; // return to original image var big = self.getData().big, image = self._controls.getActive().image; if ( !self.getData().iframe && image && big && big == image.src ) { window.setTimeout(function(src) { return function() { image.src = src; }; }( self.getData().image ), 1 ); } self.rescale(function() { Utils.addTimer(false, function() { // show the image after 50 ms Utils.show( self.getActiveImage() ); if ( typeof callback === 'function' ) { callback.call( self ); } $win.trigger( 'resize' ); }, 50); self.trigger( Galleria.FULLSCREEN_EXIT ); }); $win.unbind('resize', fullscreen.scale); } }; // invoke the native listeners fullscreen.os.listen(); // the internal idle object for controlling idle states var idle = this._idle = { timer: 'idle' + self._id, trunk: [], bound: false, add: function(elem, to) { if (!elem) { return; } if (!idle.bound) { idle.addEvent(); } elem = $(elem); var from = {}, style; for ( style in to ) { if ( to.hasOwnProperty( style ) ) { from[ style ] = elem.css( style ); } } elem.data('idle', { from: from, to: to, complete: true, busy: false }); idle.addTimer(); idle.trunk.push(elem); }, remove: function(elem) { elem = jQuery(elem); $.each(idle.trunk, function(i, el) { if ( el && el.length && !el.not(elem).length ) { self._idle.show(elem); self._idle.trunk.splice(i, 1); } }); if (!idle.trunk.length) { idle.removeEvent(); Utils.clearTimer( idle.timer ); } }, addEvent : function() { idle.bound = true; self.$('container').bind('mousemove click', idle.showAll ); }, removeEvent : function() { idle.bound = false; self.$('container').unbind('mousemove click', idle.showAll ); }, addTimer : function() { Utils.addTimer( idle.timer, function() { idle.hide(); }, self._options.idleTime ); }, hide : function() { if ( !self._options.idleMode || self.getIndex() === false || self.getData().iframe ) { return; } self.trigger( Galleria.IDLE_ENTER ); $.each( idle.trunk, function(i, elem) { var data = elem.data('idle'); if (! data) { return; } elem.data('idle').complete = false; Utils.animate( elem, data.to, { duration: self._options.idleSpeed }); }); }, showAll : function() { Utils.clearTimer( idle.timer ); $.each( idle.trunk, function( i, elem ) { idle.show( elem ); }); }, show: function(elem) { var data = elem.data('idle'); if (!data.busy && !data.complete) { data.busy = true; self.trigger( Galleria.IDLE_EXIT ); Utils.clearTimer( idle.timer ); Utils.animate( elem, data.from, { duration: self._options.idleSpeed/2, complete: function() { $(this).data('idle').busy = false; $(this).data('idle').complete = true; } }); } idle.addTimer(); } }; // internal lightbox object // creates a predesigned lightbox for simple popups of images in galleria var lightbox = this._lightbox = { width : 0, height : 0, initialized : false, active : null, image : null, elems : {}, keymap: false, init : function() { // trigger the event self.trigger( Galleria.LIGHTBOX_OPEN ); if ( lightbox.initialized ) { return; } lightbox.initialized = true; // create some elements to work with var elems = 'overlay box content shadow title info close prevholder prev nextholder next counter image', el = {}, op = self._options, css = '', abs = 'position:absolute;', prefix = 'lightbox-', cssMap = { overlay: 'position:fixed;display:none;opacity:'+op.overlayOpacity+';filter:alpha(opacity='+(op.overlayOpacity*100)+ ');top:0;left:0;width:100%;height:100%;background:'+op.overlayBackground+';z-index:99990', box: 'position:fixed;display:none;width:400px;height:400px;top:50%;left:50%;margin-top:-200px;margin-left:-200px;z-index:99991', shadow: abs+'background:#000;width:100%;height:100%;', content: abs+'background-color:#fff;top:10px;left:10px;right:10px;bottom:10px;overflow:hidden', info: abs+'bottom:10px;left:10px;right:10px;color:#444;font:11px/13px arial,sans-serif;height:13px', close: abs+'top:10px;right:10px;height:20px;width:20px;background:#fff;text-align:center;cursor:pointer;color:#444;font:16px/22px arial,sans-serif;z-index:99999', image: abs+'top:10px;left:10px;right:10px;bottom:30px;overflow:hidden;display:block;', prevholder: abs+'width:50%;top:0;bottom:40px;cursor:pointer;', nextholder: abs+'width:50%;top:0;bottom:40px;right:-1px;cursor:pointer;', prev: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;left:20px;display:none;text-align:center;color:#000;font:bold 16px/36px arial,sans-serif', next: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;right:20px;left:auto;display:none;font:bold 16px/36px arial,sans-serif;text-align:center;color:#000', title: 'float:left', counter: 'float:right;margin-left:8px;' }, hover = function(elem) { return elem.hover( function() { $(this).css( 'color', '#bbb' ); }, function() { $(this).css( 'color', '#444' ); } ); }, appends = {}; // IE8 fix for IE's transparent background event "feature" if ( IE && IE > 7 ) { cssMap.nextholder += 'background:#000;filter:alpha(opacity=0);'; cssMap.prevholder += 'background:#000;filter:alpha(opacity=0);'; } // create and insert CSS $.each(cssMap, function( key, value ) { css += '.galleria-'+prefix+key+'{'+value+'}'; }); css += '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'prevholder,'+ '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'nextholder{'+ 'width:100px;height:100px;top:50%;margin-top:-70px}'; Utils.insertStyleTag( css ); // create the elements $.each(elems.split(' '), function( i, elemId ) { self.addElement( 'lightbox-' + elemId ); el[ elemId ] = lightbox.elems[ elemId ] = self.get( 'lightbox-' + elemId ); }); // initiate the image lightbox.image = new Galleria.Picture(); // append the elements $.each({ box: 'shadow content close prevholder nextholder', info: 'title counter', content: 'info image', prevholder: 'prev', nextholder: 'next' }, function( key, val ) { var arr = []; $.each( val.split(' '), function( i, prop ) { arr.push( prefix + prop ); }); appends[ prefix+key ] = arr; }); self.append( appends ); $( el.image ).append( lightbox.image.container ); $( DOM().body ).append( el.overlay, el.box ); Utils.optimizeTouch( el.box ); // add the prev/next nav and bind some controls hover( $( el.close ).bind( 'click', lightbox.hide ).html('&#215;') ); $.each( ['Prev','Next'], function(i, dir) { var $d = $( el[ dir.toLowerCase() ] ).html( /v/.test( dir ) ? '&#8249;&nbsp;' : '&nbsp;&#8250;' ), $e = $( el[ dir.toLowerCase()+'holder'] ); $e.bind( 'click', function() { lightbox[ 'show' + dir ](); }); // IE7 and touch devices will simply show the nav if ( IE < 8 || Galleria.TOUCH ) { $d.show(); return; } $e.hover( function() { $d.show(); }, function(e) { $d.stop().fadeOut( 200 ); }); }); $( el.overlay ).bind( 'click', lightbox.hide ); // the lightbox animation is slow on ipad if ( Galleria.IPAD ) { self._options.lightboxTransitionSpeed = 0; } }, rescale: function(event) { // calculate var width = Math.min( $win.width()-40, lightbox.width ), height = Math.min( $win.height()-60, lightbox.height ), ratio = Math.min( width / lightbox.width, height / lightbox.height ), destWidth = Math.round( lightbox.width * ratio ) + 40, destHeight = Math.round( lightbox.height * ratio ) + 60, to = { width: destWidth, height: destHeight, 'margin-top': Math.ceil( destHeight / 2 ) *- 1, 'margin-left': Math.ceil( destWidth / 2 ) *- 1 }; // if rescale event, don't animate if ( event ) { $( lightbox.elems.box ).css( to ); } else { $( lightbox.elems.box ).animate( to, { duration: self._options.lightboxTransitionSpeed, easing: self._options.easing, complete: function() { var image = lightbox.image, speed = self._options.lightboxFadeSpeed; self.trigger({ type: Galleria.LIGHTBOX_IMAGE, imageTarget: image.image }); $( image.container ).show(); $( image.image ).animate({ opacity: 1 }, speed); Utils.show( lightbox.elems.info, speed ); } }); } }, hide: function() { // remove the image lightbox.image.image = null; $win.unbind('resize', lightbox.rescale); $( lightbox.elems.box ).hide(); Utils.hide( lightbox.elems.info ); self.detachKeyboard(); self.attachKeyboard( lightbox.keymap ); lightbox.keymap = false; Utils.hide( lightbox.elems.overlay, 200, function() { $( this ).hide().css( 'opacity', self._options.overlayOpacity ); self.trigger( Galleria.LIGHTBOX_CLOSE ); }); }, showNext: function() { lightbox.show( self.getNext( lightbox.active ) ); }, showPrev: function() { lightbox.show( self.getPrev( lightbox.active ) ); }, show: function(index) { lightbox.active = index = typeof index === 'number' ? index : self.getIndex() || 0; if ( !lightbox.initialized ) { lightbox.init(); } // temporarily attach some keys // save the old ones first in a cloned object if ( !lightbox.keymap ) { lightbox.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: lightbox.hide, right: lightbox.showNext, left: lightbox.showPrev }); } $win.unbind('resize', lightbox.rescale ); var data = self.getData(index), total = self.getDataLength(), n = self.getNext( index ), ndata, p, i; Utils.hide( lightbox.elems.info ); try { for ( i = self._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( 'big' in ndata ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} lightbox.image.isIframe = !!data.iframe; $(lightbox.elems.box).toggleClass( 'iframe', !!data.iframe ); lightbox.image.load( data.iframe || data.big || data.image, function( image ) { lightbox.width = image.isIframe ? $(window).width() : image.original.width; lightbox.height = image.isIframe ? $(window).height() : image.original.height; $( image.image ).css({ width: image.isIframe ? '100%' : '100.1%', height: image.isIframe ? '100%' : '100.1%', top: 0, zIndex: 99998, opacity: 0, visibility: 'visible' }); lightbox.elems.title.innerHTML = data.title || ''; lightbox.elems.counter.innerHTML = (index + 1) + ' / ' + total; $win.resize( lightbox.rescale ); lightbox.rescale(); }); $( lightbox.elems.overlay ).show().css( 'visibility', 'visible' ); $( lightbox.elems.box ).show(); } }; return this; }; // end Galleria constructor Galleria.prototype = { // bring back the constructor reference constructor: Galleria, /** Use this function to initialize the gallery and start loading. Should only be called once per instance. @param {HTMLElement} target The target element @param {Object} options The gallery options @returns Instance */ init: function( target, options ) { var self = this; options = _legacyOptions( options ); // save the original ingredients this._original = { target: target, options: options, data: null }; // save the target here this._target = this._dom.target = target.nodeName ? target : $( target ).get(0); // save the original content for destruction this._original.html = this._target.innerHTML; // push the instance _instances.push( this ); // raise error if no target is detected if ( !this._target ) { Galleria.raise('Target not found', true); return; } // apply options this._options = { autoplay: false, carousel: true, carouselFollow: true, carouselSpeed: 400, carouselSteps: 'auto', clicknext: false, dailymotion: { foreground: '%23EEEEEE', highlight: '%235BCEC5', background: '%23222222', logo: 0, hideInfos: 1 }, dataConfig : function( elem ) { return {}; }, dataSelector: 'img', dataSource: this._target, debug: undef, dummy: undef, // 1.2.5 easing: 'galleria', extend: function(options) {}, fullscreenCrop: undef, // 1.2.5 fullscreenDoubleTap: true, // 1.2.4 toggles fullscreen on double-tap for touch devices fullscreenTransition: undef, // 1.2.6 height: 0, idleMode: true, // 1.2.4 toggles idleMode idleTime: 3000, idleSpeed: 200, imageCrop: false, imageMargin: 0, imagePan: false, imagePanSmoothness: 12, imagePosition: '50%', imageTimeout: undef, // 1.2.5 initialTransition: undef, // 1.2.4, replaces transitionInitial keepSource: false, layerFollow: true, // 1.2.5 lightbox: false, // 1.2.3 lightboxFadeSpeed: 200, lightboxTransitionSpeed: 200, linkSourceImages: true, maxScaleRatio: undef, minScaleRatio: undef, overlayOpacity: 0.85, overlayBackground: '#0b0b0b', pauseOnInteraction: true, popupLinks: false, preload: 2, queue: true, responsive: false, show: 0, showInfo: true, showCounter: true, showImagenav: true, swipe: true, // 1.2.4 thumbCrop: true, thumbEventType: 'click', thumbFit: true, thumbMargin: 0, thumbQuality: 'auto', thumbnails: true, touchTransition: undef, // 1.2.6 transition: 'fade', transitionInitial: undef, // legacy, deprecate in 1.3. Use initialTransition instead. transitionSpeed: 400, trueFullscreen: true, // 1.2.7 useCanvas: false, // 1.2.4 vimeo: { title: 0, byline: 0, portrait: 0, color: 'aaaaaa' }, wait: 5000, // 1.2.7 width: 'auto', youtube: { modestbranding: 1, autohide: 1, color: 'white', hd: 1, rel: 0, showinfo: 0 } }; // legacy support for transitionInitial this._options.initialTransition = this._options.initialTransition || this._options.transitionInitial; // turn off debug if ( options && options.debug === false ) { DEBUG = false; } // set timeout if ( options && typeof options.imageTimeout === 'number' ) { TIMEOUT = options.imageTimeout; } // set dummy if ( options && typeof options.dummy === 'string' ) { DUMMY = options.dummy; } // hide all content $( this._target ).children().hide(); // now we just have to wait for the theme... if ( typeof Galleria.theme === 'object' ) { this._init(); } else { // push the instance into the pool and run it when the theme is ready _pool.push( this ); } return this; }, // this method should only be called once per instance // for manipulation of data, use the .load method _init: function() { var self = this, options = this._options; if ( this._initialized ) { Galleria.raise( 'Init failed: Gallery instance already initialized.' ); return this; } this._initialized = true; if ( !Galleria.theme ) { Galleria.raise( 'Init failed: No theme found.', true ); return this; } // merge the theme & caller options $.extend( true, options, Galleria.theme.defaults, this._original.options, Galleria.configure.options ); // check for canvas support (function( can ) { if ( !( 'getContext' in can ) ) { can = null; return; } _canvas = _canvas || { elem: can, context: can.getContext( '2d' ), cache: {}, length: 0 }; }( doc.createElement( 'canvas' ) ) ); // bind the gallery to run when data is ready this.bind( Galleria.DATA, function() { // Warn for quirks mode if ( Galleria.QUIRK ) { Galleria.raise('Your page is in Quirks mode, Galleria may not render correctly. Please validate your HTML.'); } // save the new data this._original.data = this._data; // lets show the counter here this.get('total').innerHTML = this.getDataLength(); // cache the container var $container = this.$( 'container' ); // the gallery is ready, let's just wait for the css var num = { width: 0, height: 0 }; var testHeight = function() { return self.$( 'stage' ).height(); }; // check container and thumbnail height Utils.wait({ until: function() { // keep trying to get the value num = self._getWH(); $container.width( num.width ).height( num.height ); return testHeight() && num.width && num.height > 50; }, success: function() { self._width = num.width; self._height = num.height; // for some strange reason, webkit needs a single setTimeout to play ball if ( Galleria.WEBKIT ) { window.setTimeout( function() { self._run(); }, 1); } else { self._run(); } }, error: function() { // Height was probably not set, raise hard errors if ( testHeight() ) { Galleria.raise('Could not extract sufficient width/height of the gallery container. Traced measures: width:' + num.width + 'px, height: ' + num.height + 'px.', true); } else { Galleria.raise('Could not extract a stage height from the CSS. Traced height: ' + testHeight() + 'px.', true); } }, timeout: typeof this._options.wait == 'number' ? this._options.wait : false }); }); // build the gallery frame this.append({ 'info-text' : ['info-title', 'info-description'], 'info' : ['info-text'], 'image-nav' : ['image-nav-right', 'image-nav-left'], 'stage' : ['images', 'loader', 'counter', 'image-nav'], 'thumbnails-list' : ['thumbnails'], 'thumbnails-container' : ['thumb-nav-left', 'thumbnails-list', 'thumb-nav-right'], 'container' : ['stage', 'thumbnails-container', 'info', 'tooltip'] }); Utils.hide( this.$( 'counter' ).append( this.get( 'current' ), doc.createTextNode(' / '), this.get( 'total' ) ) ); this.setCounter('&#8211;'); Utils.hide( self.get('tooltip') ); // add a notouch class on the container to prevent unwanted :hovers on touch devices this.$( 'container' ).addClass( Galleria.TOUCH ? 'touch' : 'notouch' ); // add images to the controls $.each( new Array(2), function( i ) { // create a new Picture instance var image = new Galleria.Picture(); // apply some styles, create & prepend overlay $( image.container ).css({ position: 'absolute', top: 0, left: 0 }).prepend( self._layers[i] = $( Utils.create('galleria-layer') ).css({ position: 'absolute', top:0, left:0, right:0, bottom:0, zIndex:2 })[0] ); // append the image self.$( 'images' ).append( image.container ); // reload the controls self._controls[i] = image; }); // some forced generic styling this.$( 'images' ).css({ position: 'relative', top: 0, left: 0, width: '100%', height: '100%' }); this.$( 'thumbnails, thumbnails-list' ).css({ overflow: 'hidden', position: 'relative' }); // bind image navigation arrows this.$( 'image-nav-right, image-nav-left' ).bind( 'click', function(e) { // tune the clicknext option if ( options.clicknext ) { e.stopPropagation(); } // pause if options is set if ( options.pauseOnInteraction ) { self.pause(); } // navigate var fn = /right/.test( this.className ) ? 'next' : 'prev'; self[ fn ](); }); // hide controls if chosen to $.each( ['info','counter','image-nav'], function( i, el ) { if ( options[ 'show' + el.substr(0,1).toUpperCase() + el.substr(1).replace(/-/,'') ] === false ) { Utils.moveOut( self.get( el.toLowerCase() ) ); } }); // load up target content this.load(); // now it's usually safe to remove the content // IE will never stop loading if we remove it, so let's keep it hidden for IE (it's usually fast enough anyway) if ( !options.keepSource && !IE ) { this._target.innerHTML = ''; } // re-append the errors, if they happened before clearing if ( this.get( 'errors' ) ) { this.appendChild( 'target', 'errors' ); } // append the gallery frame this.appendChild( 'target', 'container' ); // parse the carousel on each thumb load if ( options.carousel ) { var count = 0, show = options.show; this.bind( Galleria.THUMBNAIL, function() { this.updateCarousel(); if ( ++count == this.getDataLength() && typeof show == 'number' && show > 0 ) { this._carousel.follow( show ); } }); } // bind window resize for responsiveness if ( options.responsive ) { $win.bind( 'resize', function() { if ( !self.isFullscreen() ) { self.resize(); } }); } // bind swipe gesture if ( options.swipe ) { (function( images ) { var swipeStart = [0,0], swipeStop = [0,0], limitX = 30, limitY = 100, multi = false, tid = 0, data, ev = { start: 'touchstart', move: 'touchmove', stop: 'touchend' }, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }, moveHandler = function( e ) { if ( e.originalEvent.touches && e.originalEvent.touches.length > 1 ) { return; } data = getData( e ); swipeStop = [ data.pageX, data.pageY ]; if ( !swipeStart[0] ) { swipeStart = swipeStop; } if ( Math.abs( swipeStart[0] - swipeStop[0] ) > 10 ) { e.preventDefault(); } }, upHandler = function( e ) { images.unbind( ev.move, moveHandler ); // if multitouch (possibly zooming), abort if ( ( e.originalEvent.touches && e.originalEvent.touches.length ) || multi ) { multi = !multi; return; } if ( Utils.timestamp() - tid < 1000 && Math.abs( swipeStart[0] - swipeStop[0] ) > limitX && Math.abs( swipeStart[1] - swipeStop[1] ) < limitY ) { e.preventDefault(); self[ swipeStart[0] > swipeStop[0] ? 'next' : 'prev' ](); } swipeStart = swipeStop = [0,0]; }; images.bind(ev.start, function(e) { if ( e.originalEvent.touches && e.originalEvent.touches.length > 1 ) { return; } data = getData(e); tid = Utils.timestamp(); swipeStart = swipeStop = [ data.pageX, data.pageY ]; images.bind(ev.move, moveHandler ).one(ev.stop, upHandler); }); }( self.$( 'images' ) )); // double-tap/click fullscreen toggle if ( options.fullscreenDoubleTap ) { this.$( 'stage' ).bind( 'touchstart', (function() { var last, cx, cy, lx, ly, now, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }; return function(e) { now = Galleria.utils.timestamp(); cx = getData(e).pageX; cy = getData(e).pageY; if ( ( now - last < 500 ) && ( cx - lx < 20) && ( cy - ly < 20) ) { self.toggleFullscreen(); e.preventDefault(); self.$( 'stage' ).unbind( 'touchend', arguments.callee ); return; } last = now; lx = cx; ly = cy; }; }())); } } // optimize touch for container Utils.optimizeTouch( this.get( 'container' ) ); // bind the ons $.each( Galleria.on.binds, function(i, bind) { self.bind( bind.type, bind.callback ); }); return this; }, // parse width & height from CSS or options _getWH : function() { var $container = this.$( 'container' ), $target = this.$( 'target' ), self = this, num = {}, arr; $.each(['width', 'height'], function( i, m ) { // first check if options is set if ( self._options[ m ] && typeof self._options[ m ] === 'number') { num[ m ] = self._options[ m ]; } else { arr = [ Utils.parseValue( $container.css( m ) ), // the container css height Utils.parseValue( $target.css( m ) ), // the target css height $container[ m ](), // the container jQuery method $target[ m ]() // the target jQuery method ]; // if first time, include the min-width & min-height if ( !self[ '_'+m ] ) { arr.splice(arr.length, Utils.parseValue( $container.css( 'min-'+m ) ), Utils.parseValue( $target.css( 'min-'+m ) ) ); } // else extract the measures from different sources and grab the highest value num[ m ] = Math.max.apply( Math, arr ); } }); // allow setting a height ratio instead of exact value // useful when doing responsive galleries if ( self._options.height && self._options.height < 2 ) { num.height = num.width * self._options.height; } return num; }, // Creates the thumbnails and carousel // can be used at any time, f.ex when the data object is manipulated _createThumbnails : function() { this.get( 'total' ).innerHTML = this.getDataLength(); var i, src, thumb, data, special, $container, self = this, o = this._options, // get previously active thumbnail, if exists active = (function() { var a = self.$('thumbnails').find('.active'); if ( !a.length ) { return false; } return a.find('img').attr('src'); }()), // cache the thumbnail option optval = typeof o.thumbnails === 'string' ? o.thumbnails.toLowerCase() : null, // move some data into the instance // for some reason, jQuery cant handle css(property) when zooming in FF, breaking the gallery // so we resort to getComputedStyle for browsers who support it getStyle = function( prop ) { return doc.defaultView && doc.defaultView.getComputedStyle ? doc.defaultView.getComputedStyle( thumb.container, null )[ prop ] : $container.css( prop ); }, fake = function(image, index, container) { return function() { $( container ).append( image ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: image, index: index, galleriaData: self.getData( index ) }); }; }, onThumbEvent = function( e ) { // pause if option is set if ( o.pauseOnInteraction ) { self.pause(); } // extract the index from the data var index = $( e.currentTarget ).data( 'index' ); if ( self.getIndex() !== index ) { self.show( index ); } e.preventDefault(); }, onThumbLoad = function( thumb ) { // scale when ready thumb.scale({ width: thumb.data.width, height: thumb.data.height, crop: o.thumbCrop, margin: o.thumbMargin, canvas: o.useCanvas, complete: function( thumb ) { // shrink thumbnails to fit var top = ['left', 'top'], arr = ['Width', 'Height'], m, css, data = self.getData( thumb.index ), special = data.thumb.split(':'); // calculate shrinked positions $.each(arr, function( i, measure ) { m = measure.toLowerCase(); if ( (o.thumbCrop !== true || o.thumbCrop === m ) && o.thumbFit ) { css = {}; css[ m ] = thumb[ m ]; $( thumb.container ).css( css ); css = {}; css[ top[ i ] ] = 0; $( thumb.image ).css( css ); } // cache outer measures thumb[ 'outer' + measure ] = $( thumb.container )[ 'outer' + measure ]( true ); }); // set high quality if downscale is moderate Utils.toggleQuality( thumb.image, o.thumbQuality === true || ( o.thumbQuality === 'auto' && thumb.original.width < thumb.width * 3 ) ); // get "special" thumbs from provider if( data.iframe && special.length == 2 && special[0] in _video ) { _video[ special[0] ].getThumb( special[1], (function(img) { return function(src) { img.src = src; }; }( thumb.image ) )); } // trigger the THUMBNAIL event self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: thumb.image, index: thumb.data.order, galleriaData: self.getData( thumb.data.order ) }); } }); }; this._thumbnails = []; this.$( 'thumbnails' ).empty(); // loop through data and create thumbnails for( i = 0; this._data[ i ]; i++ ) { data = this._data[ i ]; if ( o.thumbnails === true && (data.thumb || data.image) ) { // add a new Picture instance thumb = new Galleria.Picture(i); // save the index thumb.index = i; // get source from thumb or image src = data.thumb || data.image; // append the thumbnail this.$( 'thumbnails' ).append( thumb.container ); // cache the container $container = $( thumb.container ); thumb.data = { width : Utils.parseValue( getStyle( 'width' ) ), height : Utils.parseValue( getStyle( 'height' ) ), order : i }; // grab & reset size for smoother thumbnail loads if ( o.thumbFit && o.thumbCrop !== true ) { $container.css( { width: 'auto', height: 'auto' } ); } else { $container.css( { width: thumb.data.width, height: thumb.data.height } ); } // load the thumbnail special = src.split(':'); if ( special.length == 2 && special[0] in _video ) { thumb.load('data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D', { height: thumb.data.height, width: thumb.data.height*1.25 }, onThumbLoad); } else { thumb.load( src, onThumbLoad ); } // preload all images here if ( o.preload === 'all' ) { thumb.preload( data.image ); } // create empty spans if thumbnails is set to 'empty' } else if ( data.iframe || optval === 'empty' || optval === 'numbers' ) { thumb = { container: Utils.create( 'galleria-image' ), image: Utils.create( 'img', 'span' ), ready: true }; // create numbered thumbnails if ( optval === 'numbers' ) { $( thumb.image ).text( i + 1 ); } if( data.iframe ) { $( thumb.image ).addClass('iframe'); } this.$( 'thumbnails' ).append( thumb.container ); // we need to "fake" a loading delay before we append and trigger // 50+ should be enough window.setTimeout( ( fake )( thumb.image, i, thumb.container ), 50 + ( i*20 ) ); // create null object to silent errors } else { thumb = { container: null, image: null }; } // add events for thumbnails // you can control the event type using thumb_event_type // we'll add the same event to the source if it's kept $( thumb.container ).add( o.keepSource && o.linkSourceImages ? data.original : null ) .data('index', i).bind( o.thumbEventType, onThumbEvent ); if (active === src) { $( thumb.container ).addClass( 'active' ); } this._thumbnails.push( thumb ); } }, // the internal _run method should be called after loading data into galleria // makes sure the gallery has proper measurements before postrun & ready _run : function() { var self = this; self._createThumbnails(); // make sure we have a stageHeight && stageWidth Utils.wait({ timeout: 10000, until: function() { // Opera crap if ( Galleria.OPERA ) { self.$( 'stage' ).css( 'display', 'inline-block' ); } self._stageWidth = self.$( 'stage' ).width(); self._stageHeight = self.$( 'stage' ).height(); return( self._stageWidth && self._stageHeight > 50 ); // what is an acceptable height? }, success: function() { // save the instance _galleries.push( self ); // postrun some stuff after the gallery is ready // show counter Utils.show( self.get('counter') ); // bind carousel nav if ( self._options.carousel ) { self._carousel.bindControls(); } // start autoplay if ( self._options.autoplay ) { self.pause(); if ( typeof self._options.autoplay === 'number' ) { self._playtime = self._options.autoplay; } self.trigger( Galleria.PLAY ); self._playing = true; } // if second load, just do the show and return if ( self._firstrun ) { if ( typeof self._options.show === 'number' ) { self.show( self._options.show ); } return; } self._firstrun = true; // initialize the History plugin if ( Galleria.History ) { // bind the show method Galleria.History.change(function( value ) { // if ID is NaN, the user pressed back from the first image // return to previous address if ( isNaN( value ) ) { window.history.go(-1); // else show the image } else { self.show( value, undef, true ); } }); } self.trigger( Galleria.READY ); // call the theme init method Galleria.theme.init.call( self, self._options ); // Trigger Galleria.ready $.each( Galleria.ready.callbacks, function() { this.call( self, self._options ); }); // call the extend option self._options.extend.call( self, self._options ); // show the initial image // first test for permalinks in history if ( /^[0-9]{1,4}$/.test( HASH ) && Galleria.History ) { self.show( HASH, undef, true ); } else if( self._data[ self._options.show ] ) { self.show( self._options.show ); } }, error: function() { Galleria.raise('Stage width or height is too small to show the gallery. Traced measures: width:' + self._stageWidth + 'px, height: ' + self._stageHeight + 'px.', true); } }); }, /** Loads data into the gallery. You can call this method on an existing gallery to reload the gallery with new data. @param {Array|string} [source] Optional JSON array of data or selector of where to find data in the document. Defaults to the Galleria target or dataSource option. @param {string} [selector] Optional element selector of what elements to parse. Defaults to 'img'. @param {Function} [config] Optional function to modify the data extraction proceedure from the selector. See the dataConfig option for more information. @returns Instance */ load : function( source, selector, config ) { var self = this; // empty the data array this._data = []; // empty the thumbnails this._thumbnails = []; this.$('thumbnails').empty(); // shorten the arguments if ( typeof selector === 'function' ) { config = selector; selector = null; } // use the source set by target source = source || this._options.dataSource; // use selector set by option selector = selector || this._options.dataSelector; // use the dataConfig set by option config = config || this._options.dataConfig; // if source is a true object, make it into an array if( /^function Object/.test( source.constructor ) ) { source = [source]; } // check if the data is an array already if ( source.constructor === Array ) { if ( this.validate( source ) ) { this._data = source; this._parseData().trigger( Galleria.DATA ); } else { Galleria.raise( 'Load failed: JSON Array not valid.' ); } return this; } // add .video and .iframe to the selector (1.2.7) selector += ',.video,.iframe'; // loop through images and set data $( source ).find( selector ).each( function( i, elem ) { elem = $( elem ); var data = {}, parent = elem.parent(), href = parent.attr( 'href' ), rel = parent.attr( 'rel' ); if( href && ( elem[0].nodeName == 'IMG' || elem.hasClass('video') ) && _videoTest( href ) ) { data.video = href; } else if( href && elem.hasClass('iframe') ) { data.iframe = href; } else { data.image = data.big = href; } if ( rel ) { data.big = rel; } // alternative extraction from HTML5 data attribute, added in 1.2.7 $.each( 'big title description link layer'.split(' '), function( i, val ) { if ( elem.data(val) ) { data[ val ] = elem.data(val); } }); // mix default extractions with the hrefs and config // and push it into the data array self._data.push( $.extend({ title: elem.attr('title') || '', thumb: elem.attr('src'), image: elem.attr('src'), big: elem.attr('src'), description: elem.attr('alt') || '', link: elem.attr('longdesc'), original: elem.get(0) // saved as a reference }, data, config( elem ) ) ); }); // trigger the DATA event and return if ( this.getDataLength() ) { this._parseData().trigger( Galleria.DATA ); } else { Galleria.raise('Load failed: no data found.'); } return this; }, // make sure the data works properly _parseData : function() { var self = this, current; $.each( this._data, function( i, data ) { current = self._data[ i ]; // copy image as thumb if no thumb exists if ( 'thumb' in data === false ) { current.thumb = data.image; } // copy image as big image if no biggie exists if ( !'big' in data ) { current.big = data.image; } // parse video if ( 'video' in data ) { var result = _videoTest( data.video ); if ( result ) { current.iframe = _video[ result.provider ].embed( result.id ) + (function() { // add options if ( typeof self._options[ result.provider ] == 'object' ) { var str = '?', arr = []; $.each( self._options[ result.provider ], function( key, val ) { arr.push( key + '=' + val ); }); // small youtube specifics, perhaps move to _video later if ( result.provider == 'youtube' ) { arr = ['wmode=opaque'].concat(arr); } return str + arr.join('&'); } return ''; }()); delete current.video; if( !('thumb' in current) || !current.thumb ) { current.thumb = result.provider+':'+result.id; } } } }); return this; }, /** Destroy the Galleria instance and recover the original content @example this.destroy(); @returns Instance */ destroy: function() { this.get('target').innerHTML = this._original.html; return this; }, /** Adds and/or removes images from the gallery Works just like Array.splice https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice @example this.splice( 2, 4 ); // removes 4 images after the second image @returns Instance */ splice: function() { var self = this, args = Utils.array( arguments ); window.setTimeout(function() { protoArray.splice.apply( self._data, args ); self._parseData()._createThumbnails(); },2); return self; }, /** Append images to the gallery Works just like Array.push https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push @example this.push({ image: 'image1.jpg' }); // appends the image to the gallery @returns Instance */ push: function() { var self = this, args = Utils.array( arguments ); window.setTimeout(function() { protoArray.push.apply( self._data, args ); self._parseData()._createThumbnails(); },2); return self; }, _getActive: function() { return this._controls.getActive(); }, validate : function( data ) { // todo: validate a custom data array return true; }, /** Bind any event to Galleria @param {string} type The Event type to listen for @param {Function} fn The function to execute when the event is triggered @example this.bind( 'image', function() { Galleria.log('image shown') }); @returns Instance */ bind : function(type, fn) { // allow 'image' instead of Galleria.IMAGE type = _patchEvent( type ); this.$( 'container' ).bind( type, this.proxy(fn) ); return this; }, /** Unbind any event to Galleria @param {string} type The Event type to forget @returns Instance */ unbind : function(type) { type = _patchEvent( type ); this.$( 'container' ).unbind( type ); return this; }, /** Manually trigger a Galleria event @param {string} type The Event to trigger @returns Instance */ trigger : function( type ) { type = typeof type === 'object' ? $.extend( type, { scope: this } ) : { type: _patchEvent( type ), scope: this }; this.$( 'container' ).trigger( type ); return this; }, /** Assign an "idle state" to any element. The idle state will be applied after a certain amount of idle time Useful to hide f.ex navigation when the gallery is inactive @param {HTMLElement|string} elem The Dom node or selector to apply the idle state to @param {Object} styles the CSS styles to apply @example addIdleState( this.get('image-nav'), { opacity: 0 }); @example addIdleState( '.galleria-image-nav', { top: -200 }); @returns Instance */ addIdleState: function( elem, styles ) { this._idle.add.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Removes any idle state previously set using addIdleState() @param {HTMLElement|string} elem The Dom node or selector to remove the idle state from. @returns Instance */ removeIdleState: function( elem ) { this._idle.remove.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Force Galleria to enter idle mode. @returns Instance */ enterIdleMode: function() { this._idle.hide(); return this; }, /** Force Galleria to exit idle mode. @returns Instance */ exitIdleMode: function() { this._idle.showAll(); return this; }, /** Enter FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ enterFullscreen: function( callback ) { this._fullscreen.enter.apply( this, Utils.array( arguments ) ); return this; }, /** Exits FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ exitFullscreen: function( callback ) { this._fullscreen.exit.apply( this, Utils.array( arguments ) ); return this; }, /** Toggle FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied or removed. @returns Instance */ toggleFullscreen: function( callback ) { this._fullscreen[ this.isFullscreen() ? 'exit' : 'enter'].apply( this, Utils.array( arguments ) ); return this; }, /** Adds a tooltip to any element. You can also call this method with an object as argument with elemID:value pairs to apply tooltips to (see examples) @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @example this.bindTooltip( this.get('thumbnails'), 'My thumbnails'); @example this.bindTooltip( this.get('thumbnails'), function() { return 'My thumbs' }); @example this.bindTooltip( { image_nav: 'Navigation' }); @returns Instance */ bindTooltip: function( elem, value ) { this._tooltip.bind.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Note: this method is deprecated. Use refreshTooltip() instead. Redefine a tooltip. Use this if you want to re-apply a tooltip value to an already bound tooltip element. @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @returns Instance */ defineTooltip: function( elem, value ) { this._tooltip.define.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Refresh a tooltip value. Use this if you want to change the tooltip value at runtime, f.ex if you have a play/pause toggle. @param {HTMLElement} elem The DOM Node that has a tooltip that should be refreshed @returns Instance */ refreshTooltip: function( elem ) { this._tooltip.show.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Open a pre-designed lightbox with the currently active image. You can control some visuals using gallery options. @returns Instance */ openLightbox: function() { this._lightbox.show.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Close the lightbox. @returns Instance */ closeLightbox: function() { this._lightbox.hide.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Get the currently active image element. @returns {HTMLElement} The image element */ getActiveImage: function() { return this._getActive().image || undef; }, /** Get the currently active thumbnail element. @returns {HTMLElement} The thumbnail element */ getActiveThumb: function() { return this._thumbnails[ this._active ].image || undef; }, /** Get the mouse position relative to the gallery container @param e The mouse event @example var gallery = this; $(document).mousemove(function(e) { console.log( gallery.getMousePosition(e).x ); }); @returns {Object} Object with x & y of the relative mouse postion */ getMousePosition : function(e) { return { x: e.pageX - this.$( 'container' ).offset().left, y: e.pageY - this.$( 'container' ).offset().top }; }, /** Adds a panning effect to the image @param [img] The optional image element. If not specified it takes the currently active image @returns Instance */ addPan : function( img ) { if ( this._options.imageCrop === false ) { return; } img = $( img || this.getActiveImage() ); // define some variables and methods var self = this, x = img.width() / 2, y = img.height() / 2, destX = parseInt( img.css( 'left' ), 10 ), destY = parseInt( img.css( 'top' ), 10 ), curX = destX || 0, curY = destY || 0, distX = 0, distY = 0, active = false, ts = Utils.timestamp(), cache = 0, move = 0, // positions the image position = function( dist, cur, pos ) { if ( dist > 0 ) { move = Math.round( Math.max( dist * -1, Math.min( 0, cur ) ) ); if ( cache !== move ) { cache = move; if ( IE === 8 ) { // scroll is faster for IE img.parent()[ 'scroll' + pos ]( move * -1 ); } else { var css = {}; css[ pos.toLowerCase() ] = move; img.css(css); } } } }, // calculates mouse position after 50ms calculate = function(e) { if (Utils.timestamp() - ts < 50) { return; } active = true; x = self.getMousePosition(e).x; y = self.getMousePosition(e).y; }, // the main loop to check loop = function(e) { if (!active) { return; } distX = img.width() - self._stageWidth; distY = img.height() - self._stageHeight; destX = x / self._stageWidth * distX * -1; destY = y / self._stageHeight * distY * -1; curX += ( destX - curX ) / self._options.imagePanSmoothness; curY += ( destY - curY ) / self._options.imagePanSmoothness; position( distY, curY, 'Top' ); position( distX, curX, 'Left' ); }; // we need to use scroll in IE8 to speed things up if ( IE === 8 ) { img.parent().scrollTop( curY * -1 ).scrollLeft( curX * -1 ); img.css({ top: 0, left: 0 }); } // unbind and bind event this.$( 'stage' ).unbind( 'mousemove', calculate ).bind( 'mousemove', calculate ); // loop the loop Utils.addTimer( 'pan' + self._id, loop, 50, true); return this; }, /** Brings the scope into any callback @param fn The callback to bring the scope into @param [scope] Optional scope to bring @example $('#fullscreen').click( this.proxy(function() { this.enterFullscreen(); }) ) @returns {Function} Return the callback with the gallery scope */ proxy : function( fn, scope ) { if ( typeof fn !== 'function' ) { return F; } scope = scope || this; return function() { return fn.apply( scope, Utils.array( arguments ) ); }; }, /** Removes the panning effect set by addPan() @returns Instance */ removePan: function() { // todo: doublecheck IE8 this.$( 'stage' ).unbind( 'mousemove' ); Utils.clearTimer( 'pan' + this._id ); return this; }, /** Adds an element to the Galleria DOM array. When you add an element here, you can access it using element ID in many API calls @param {string} id The element ID you wish to use. You can add many elements by adding more arguments. @example addElement('mybutton'); @example addElement('mybutton','mylink'); @returns Instance */ addElement : function( id ) { var dom = this._dom; $.each( Utils.array(arguments), function( i, blueprint ) { dom[ blueprint ] = Utils.create( 'galleria-' + blueprint ); }); return this; }, /** Attach keyboard events to Galleria @param {Object} map The map object of events. Possible keys are 'UP', 'DOWN', 'LEFT', 'RIGHT', 'RETURN', 'ESCAPE', 'BACKSPACE', and 'SPACE'. @example this.attachKeyboard({ right: this.next, left: this.prev, up: function() { console.log( 'up key pressed' ) } }); @returns Instance */ attachKeyboard : function( map ) { this._keyboard.attach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Detach all keyboard events to Galleria @returns Instance */ detachKeyboard : function() { this._keyboard.detach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Fast helper for appending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be appended @param {string} childID the element ID that should be appended @example this.addElement('myElement'); this.appendChild( 'info', 'myElement' ); @returns Instance */ appendChild : function( parentID, childID ) { this.$( parentID ).append( this.get( childID ) || childID ); return this; }, /** Fast helper for prepending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be prepended @param {string} childID the element ID that should be prepended @example this.addElement('myElement'); this.prependChild( 'info', 'myElement' ); @returns Instance */ prependChild : function( parentID, childID ) { this.$( parentID ).prepend( this.get( childID ) || childID ); return this; }, /** Remove an element by blueprint @param {string} elemID The element to be removed. You can remove multiple elements by adding arguments. @returns Instance */ remove : function( elemID ) { this.$( Utils.array( arguments ).join(',') ).remove(); return this; }, // a fast helper for building dom structures // leave this out of the API for now append : function( data ) { var i, j; for( i in data ) { if ( data.hasOwnProperty( i ) ) { if ( data[i].constructor === Array ) { for( j = 0; data[i][j]; j++ ) { this.appendChild( i, data[i][j] ); } } else { this.appendChild( i, data[i] ); } } } return this; }, // an internal helper for scaling according to options _scaleImage : function( image, options ) { image = image || this._controls.getActive(); // janpub (JH) fix: // image might be unselected yet // e.g. when external logics rescales the gallery on window resize events if( !image ) { return; } var self = this, complete, scaleLayer = function( img ) { $( img.container ).children(':first').css({ top: Math.max(0, Utils.parseValue( img.image.style.top )), left: Math.max(0, Utils.parseValue( img.image.style.left )), width: Utils.parseValue( img.image.width ), height: Utils.parseValue( img.image.height ) }); }; options = $.extend({ width: this._stageWidth, height: this._stageHeight, crop: this._options.imageCrop, max: this._options.maxScaleRatio, min: this._options.minScaleRatio, margin: this._options.imageMargin, position: this._options.imagePosition }, options ); if ( this._options.layerFollow && this._options.imageCrop !== true ) { if ( typeof options.complete == 'function' ) { complete = options.complete; options.complete = function() { complete.call( image, image ); scaleLayer( image ); }; } else { options.complete = scaleLayer; } } else { $( image.container ).children(':first').css({ top: 0, left: 0 }); } image.scale( options ); return this; }, /** Updates the carousel, useful if you resize the gallery and want to re-check if the carousel nav is needed. @returns Instance */ updateCarousel : function() { this._carousel.update(); return this; }, /** Resize the entire gallery container @param {Object} [measures] Optional object with width/height specified @param {Function} [complete] The callback to be called when the scaling is complete @returns Instance */ resize : function( measures, complete ) { if ( typeof measures == 'function' ) { complete = measures; measures = undef; } measures = $.extend( { width:0, height:0 }, measures ); var self = this, $container = this.$( 'container' ), aspect = this._options.responsive == 'aspect' && ( !measures.width || !measures.height ), ratio; $.each( measures, function( m, val ) { if ( !val ) { $container[ m ]( 'auto' ); measures[ m ] = self._getWH()[ m ]; } }); // experimental aspect option, not documented yet. Use ratio-based height instead! if ( aspect ) { ratio = Math.min( measures.width/this._width, measures.height/this._height ); } $.each( measures, function( m, val ) { $container[ m ]( ratio ? ratio * self[ '_' + m ] : val ); }); return this.rescale( complete ); }, /** Rescales the gallery @param {number} width The target width @param {number} height The target height @param {Function} complete The callback to be called when the scaling is complete @returns Instance */ rescale : function( width, height, complete ) { var self = this; // allow rescale(fn) if ( typeof width === 'function' ) { complete = width; width = undef; } var scale = function() { // set stagewidth self._stageWidth = width || self.$( 'stage' ).width(); self._stageHeight = height || self.$( 'stage' ).height(); // scale the active image self._scaleImage(); if ( self._options.carousel ) { self.updateCarousel(); } self.trigger( Galleria.RESCALE ); if ( typeof complete === 'function' ) { complete.call( self ); } }; if ( Galleria.WEBKIT && !Galleria.TOUCH && !width && !height ) { Utils.addTimer( false, scale, 10 );// webkit is too fast } else { scale.call( self ); } return this; }, /** Refreshes the gallery. Useful if you change image options at runtime and want to apply the changes to the active image. @returns Instance */ refreshImage : function() { this._scaleImage(); if ( this._options.imagePan ) { this.addPan(); } return this; }, /** Shows an image by index @param {number|boolean} index The index to show @param {Boolean} rewind A boolean that should be true if you want the transition to go back @returns Instance */ show : function( index, rewind, _history ) { // do nothing if index is false or queue is false and transition is in progress if ( index === false || ( !this._options.queue && this._queue.stalled ) ) { return; } index = Math.max( 0, Math.min( parseInt( index, 10 ), this.getDataLength() - 1 ) ); rewind = typeof rewind !== 'undefined' ? !!rewind : index < this.getIndex(); _history = _history || false; // do the history thing and return if ( !_history && Galleria.History ) { Galleria.History.set( index.toString() ); return; } this._active = index; protoArray.push.call( this._queue, { index : index, rewind : rewind }); if ( !this._queue.stalled ) { this._show(); } return this; }, // the internal _show method does the actual showing _show : function() { // shortcuts var self = this, queue = this._queue[ 0 ], data = this.getData( queue.index ); if ( !data ) { return; } var src = data.iframe || ( this.isFullscreen() && 'big' in data ? data.big : data.image ), // use big image if fullscreen mode active = this._controls.getActive(), next = this._controls.getNext(), cached = next.isCached( src ), thumb = this._thumbnails[ queue.index ], mousetrigger = function() { $( next.image ).trigger( 'mouseup' ); }; // to be fired when loading & transition is complete: var complete = (function( data, next, active, queue, thumb ) { return function() { var win; // remove stalled self._queue.stalled = false; // optimize quality Utils.toggleQuality( next.image, self._options.imageQuality ); // remove old layer self._layers[ self._controls.active ].innerHTML = ''; // swap $( active.container ).css({ zIndex: 0, opacity: 0 }).show(); if( active.isIframe ) { $( active.container ).find( 'iframe' ).remove(); } self.$('container').toggleClass('iframe', !!data.iframe); $( next.container ).css({ zIndex: 1, left: 0, top: 0 }).show(); self._controls.swap(); // add pan according to option if ( self._options.imagePan ) { self.addPan( next.image ); } // make the image link or add lightbox // link takes precedence over lightbox if both are detected if ( data.link || self._options.lightbox || self._options.clicknext ) { $( next.image ).css({ cursor: 'pointer' }).bind( 'mouseup', function() { // clicknext if ( self._options.clicknext && !Galleria.TOUCH ) { if ( self._options.pauseOnInteraction ) { self.pause(); } self.next(); return; } // popup link if ( data.link ) { if ( self._options.popupLinks ) { win = window.open( data.link, '_blank' ); } else { window.location.href = data.link; } return; } if ( self._options.lightbox ) { self.openLightbox(); } }); } // remove the queued image protoArray.shift.call( self._queue ); // if we still have images in the queue, show it if ( self._queue.length ) { self._show(); } // check if we are playing self._playCheck(); // trigger IMAGE event self.trigger({ type: Galleria.IMAGE, index: queue.index, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); }; }( data, next, active, queue, thumb )); // let the carousel follow if ( this._options.carousel && this._options.carouselFollow ) { this._carousel.follow( queue.index ); } // preload images if ( this._options.preload ) { var p, i, n = this.getNext(), ndata; try { for ( i = this._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( this.isFullscreen() && 'big' in ndata ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} } // show the next image, just in case Utils.show( next.container ); next.isIframe = !!data.iframe; // add active classes $( self._thumbnails[ queue.index ].container ) .addClass( 'active' ) .siblings( '.active' ) .removeClass( 'active' ); // trigger the LOADSTART event self.trigger( { type: Galleria.LOADSTART, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); // begin loading the next image next.load( src, function( next ) { // add layer HTML var layer = $( self._layers[ 1-self._controls.active ] ).html( data.layer || '' ).hide(); self._scaleImage( next, { complete: function( next ) { // toggle low quality for IE if ( 'image' in active ) { Utils.toggleQuality( active.image, false ); } Utils.toggleQuality( next.image, false ); // stall the queue self._queue.stalled = true; // remove the image panning, if applied // TODO: rethink if this is necessary self.removePan(); // set the captions and counter self.setInfo( queue.index ); self.setCounter( queue.index ); // show the layer now if ( data.layer ) { layer.show(); // inherit click events set on image if ( data.link || self._options.lightbox || self._options.clicknext ) { layer.css( 'cursor', 'pointer' ).unbind( 'mouseup' ).mouseup( mousetrigger ); } } // trigger the LOADFINISH event self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: self._thumbnails[ queue.index ].image, galleriaData: self.getData( queue.index ) }); var transition = self._options.transition; // can JavaScript loop through objects in order? yes. $.each({ initial: active.image === null, touch: Galleria.TOUCH, fullscreen: self.isFullscreen() }, function( type, arg ) { if ( arg && self._options[ type + 'Transition' ] !== undef ) { transition = self._options[ type + 'Transition' ]; return false; } }); // validate the transition if ( transition in _transitions === false ) { complete(); } else { var params = { prev: active.container, next: next.container, rewind: queue.rewind, speed: self._options.transitionSpeed || 400 }; // call the transition function and send some stuff _transitions[ transition ].call(self, params, complete ); } } }); }); }, /** Gets the next index @param {number} [base] Optional starting point @returns {number} the next index, or the first if you are at the first (looping) */ getNext : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === this.getDataLength() - 1 ? 0 : base + 1; }, /** Gets the previous index @param {number} [base] Optional starting point @returns {number} the previous index, or the last if you are at the first (looping) */ getPrev : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === 0 ? this.getDataLength() - 1 : base - 1; }, /** Shows the next image in line @returns Instance */ next : function() { if ( this.getDataLength() > 1 ) { this.show( this.getNext(), false ); } return this; }, /** Shows the previous image in line @returns Instance */ prev : function() { if ( this.getDataLength() > 1 ) { this.show( this.getPrev(), true ); } return this; }, /** Retrieve a DOM element by element ID @param {string} elemId The delement ID to fetch @returns {HTMLElement} The elements DOM node or null if not found. */ get : function( elemId ) { return elemId in this._dom ? this._dom[ elemId ] : null; }, /** Retrieve a data object @param {number} index The data index to retrieve. If no index specified it will take the currently active image @returns {Object} The data object */ getData : function( index ) { return index in this._data ? this._data[ index ] : this._data[ this._active ]; }, /** Retrieve the number of data items @returns {number} The data length */ getDataLength : function() { return this._data.length; }, /** Retrieve the currently active index @returns {number|boolean} The active index or false if none found */ getIndex : function() { return typeof this._active === 'number' ? this._active : false; }, /** Retrieve the stage height @returns {number} The stage height */ getStageHeight : function() { return this._stageHeight; }, /** Retrieve the stage width @returns {number} The stage width */ getStageWidth : function() { return this._stageWidth; }, /** Retrieve the option @param {string} key The option key to retrieve. If no key specified it will return all options in an object. @returns option or options */ getOptions : function( key ) { return typeof key === 'undefined' ? this._options : this._options[ key ]; }, /** Set options to the instance. You can set options using a key & value argument or a single object argument (see examples) @param {string} key The option key @param {string} value the the options value @example setOptions( 'autoplay', true ) @example setOptions({ autoplay: true }); @returns Instance */ setOptions : function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._options, key ); } else { this._options[ key ] = value; } return this; }, /** Starts playing the slideshow @param {number} delay Sets the slideshow interval in milliseconds. If you set it once, you can just call play() and get the same interval the next time. @returns Instance */ play : function( delay ) { this._playing = true; this._playtime = delay || this._playtime; this._playCheck(); this.trigger( Galleria.PLAY ); return this; }, /** Stops the slideshow if currently playing @returns Instance */ pause : function() { this._playing = false; this.trigger( Galleria.PAUSE ); return this; }, /** Toggle between play and pause events. @param {number} delay Sets the slideshow interval in milliseconds. @returns Instance */ playToggle : function( delay ) { return ( this._playing ) ? this.pause() : this.play( delay ); }, /** Checks if the gallery is currently playing @returns {Boolean} */ isPlaying : function() { return this._playing; }, /** Checks if the gallery is currently in fullscreen mode @returns {Boolean} */ isFullscreen : function() { return this._fullscreen.active; }, _playCheck : function() { var self = this, played = 0, interval = 20, now = Utils.timestamp(), timer_id = 'play' + this._id; if ( this._playing ) { Utils.clearTimer( timer_id ); var fn = function() { played = Utils.timestamp() - now; if ( played >= self._playtime && self._playing ) { Utils.clearTimer( timer_id ); self.next(); return; } if ( self._playing ) { // trigger the PROGRESS event self.trigger({ type: Galleria.PROGRESS, percent: Math.ceil( played / self._playtime * 100 ), seconds: Math.floor( played / 1000 ), milliseconds: played }); Utils.addTimer( timer_id, fn, interval ); } }; Utils.addTimer( timer_id, fn, interval ); } }, /** Modify the slideshow delay @param {number} delay the number of milliseconds between slides, @returns Instance */ setPlaytime: function( delay ) { this._playtime = delay; return this; }, setIndex: function( val ) { this._active = val; return this; }, /** Manually modify the counter @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index @returns Instance */ setCounter: function( index ) { if ( typeof index === 'number' ) { index++; } else if ( typeof index === 'undefined' ) { index = this.getIndex()+1; } this.get( 'current' ).innerHTML = index; if ( IE ) { // weird IE bug var count = this.$( 'counter' ), opacity = count.css( 'opacity' ); if ( parseInt( opacity, 10 ) === 1) { Utils.removeAlpha( count[0] ); } else { this.$( 'counter' ).css( 'opacity', opacity ); } } return this; }, /** Manually set captions @param {number} [index] Optional data index to fectch and apply as caption, if no index found it assumes the currently active index @returns Instance */ setInfo : function( index ) { var self = this, data = this.getData( index ); $.each( ['title','description'], function( i, type ) { var elem = self.$( 'info-' + type ); if ( !!data[type] ) { elem[ data[ type ].length ? 'show' : 'hide' ]().html( data[ type ] ); } else { elem.empty().hide(); } }); return this; }, /** Checks if the data contains any captions @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index. @returns {boolean} */ hasInfo : function( index ) { var check = 'title description'.split(' '), i; for ( i = 0; check[i]; i++ ) { if ( !!this.getData( index )[ check[i] ] ) { return true; } } return false; }, jQuery : function( str ) { var self = this, ret = []; $.each( str.split(','), function( i, elemId ) { elemId = $.trim( elemId ); if ( self.get( elemId ) ) { ret.push( elemId ); } }); var jQ = $( self.get( ret.shift() ) ); $.each( ret, function( i, elemId ) { jQ = jQ.add( self.get( elemId ) ); }); return jQ; }, /** Converts element IDs into a jQuery collection You can call for multiple IDs separated with commas. @param {string} str One or more element IDs (comma-separated) @returns jQuery @example this.$('info,container').hide(); */ $ : function( str ) { return this.jQuery.apply( this, Utils.array( arguments ) ); } }; // End of Galleria prototype // Add events as static variables $.each( _events, function( i, ev ) { // legacy events var type = /_/.test( ev ) ? ev.replace( /_/g, '' ) : ev; Galleria[ ev.toUpperCase() ] = 'galleria.'+type; } ); $.extend( Galleria, { // Browser helpers IE9: IE === 9, IE8: IE === 8, IE7: IE === 7, IE6: IE === 6, IE: IE, WEBKIT: /webkit/.test( NAV ), CHROME: /chrome/.test( NAV ), SAFARI: /safari/.test( NAV ) && !(/chrome/.test( NAV )), QUIRK: ( IE && doc.compatMode && doc.compatMode === "BackCompat" ), MAC: /mac/.test( navigator.platform.toLowerCase() ), OPERA: !!window.opera, IPHONE: /iphone/.test( NAV ), IPAD: /ipad/.test( NAV ), ANDROID: /android/.test( NAV ), TOUCH: ('ontouchstart' in doc) }); // Galleria static methods /** Adds a theme that you can use for your Gallery @param {Object} theme Object that should contain all your theme settings. <ul> <li>name - name of the theme</li> <li>author - name of the author</li> <li>css - css file name (not path)</li> <li>defaults - default options to apply, including theme-specific options</li> <li>init - the init function</li> </ul> @returns {Object} theme */ Galleria.addTheme = function( theme ) { // make sure we have a name if ( !theme.name ) { Galleria.raise('No theme name specified'); } if ( typeof theme.defaults !== 'object' ) { theme.defaults = {}; } else { theme.defaults = _legacyOptions( theme.defaults ); } var css = false, reg; if ( typeof theme.css === 'string' ) { // look for manually added CSS $('link').each(function( i, link ) { reg = new RegExp( theme.css ); if ( reg.test( link.href ) ) { // we found the css css = true; // the themeload trigger _themeLoad( theme ); return false; } }); // else look for the absolute path and load the CSS dynamic if ( !css ) { $('script').each(function( i, script ) { // look for the theme script reg = new RegExp( 'galleria\\.' + theme.name.toLowerCase() + '\\.' ); if( reg.test( script.src )) { // we have a match css = script.src.replace(/[^\/]*$/, '') + theme.css; Utils.addTimer( "css", function() { Utils.loadCSS( css, 'galleria-theme', function() { // the themeload trigger _themeLoad( theme ); }); }, 1); } }); } if ( !css ) { Galleria.raise('No theme CSS loaded'); } } else { // pass _themeLoad( theme ); } return theme; }; /** loadTheme loads a theme js file and attaches a load event to Galleria @param {string} src The relative path to the theme source file @param {Object} [options] Optional options you want to apply @returns Galleria */ Galleria.loadTheme = function( src, options ) { var loaded = false, length = _galleries.length, err = window.setTimeout( function() { Galleria.raise( "Theme at " + src + " could not load, check theme path.", true ); }, 5000 ); // first clear the current theme, if exists Galleria.theme = undef; // load the theme Utils.loadScript( src, function() { window.clearTimeout( err ); // check for existing galleries and reload them with the new theme if ( length ) { // temporary save the new galleries var refreshed = []; // refresh all instances // when adding a new theme to an existing gallery, all options will be resetted but the data will be kept // you can apply new options as a second argument $.each( Galleria.get(), function(i, instance) { // mix the old data and options into the new instance var op = $.extend( instance._original.options, { data_source: instance._data }, options); // remove the old container instance.$('container').remove(); // create a new instance var g = new Galleria(); // move the id g._id = instance._id; // initialize the new instance g.init( instance._original.target, op ); // push the new instance refreshed.push( g ); }); // now overwrite the old holder with the new instances _galleries = refreshed; } }); return Galleria; }; /** Retrieves a Galleria instance. @param {number} [index] Optional index to retrieve. If no index is supplied, the method will return all instances in an array. @returns Instance or Array of instances */ Galleria.get = function( index ) { if ( !!_instances[ index ] ) { return _instances[ index ]; } else if ( typeof index !== 'number' ) { return _instances; } else { Galleria.raise('Gallery index ' + index + ' not found'); } }; /** Configure Galleria options via a static function. The options will be applied to all instances @param {string|object} key The options to apply or a key @param [value] If key is a string, this is the value @returns Galleria */ Galleria.configure = function( key, value ) { var opts = {}; if( typeof key == 'string' && value ) { opts[key] = value; key = opts; } else { $.extend( opts, key ); } Galleria.configure.options = opts; $.each( Galleria.get(), function(i, instance) { instance.setOptions( opts ); }); return Galleria; }; Galleria.configure.options = {}; /** Bind a Galleria event to the gallery @param {string} type A string representing the galleria event @param {function} callback The function that should run when the event is triggered @returns Galleria */ Galleria.on = function( type, callback ) { if ( !type ) { return; } Galleria.on.binds.push({ type: type, callback: callback || F }); $.each( Galleria.get(), function(i, instance) { instance.bind( type, callback ); }); return Galleria; }; Galleria.on.binds = []; /** Run Galleria Alias for $(selector).galleria(options) @param {string} selector A selector of element(s) to intialize galleria to @param {object} options The options to apply @returns Galleria */ Galleria.run = function( selector, options ) { $( selector || '#galleria' ).galleria( options ); return Galleria; }; /** Creates a transition to be used in your gallery @param {string} name The name of the transition that you will use as an option @param {Function} fn The function to be executed in the transition. The function contains two arguments, params and complete. Use the params Object to integrate the transition, and then call complete when you are done. @returns Galleria */ Galleria.addTransition = function( name, fn ) { _transitions[name] = fn; return Galleria; }; /** The Galleria utilites */ Galleria.utils = Utils; /** A helper metod for cross-browser logging. It uses the console log if available otherwise it falls back to alert @example Galleria.log("hello", document.body, [1,2,3]); */ Galleria.log = (function() { if( 'console' in window && 'log' in window.console ) { return window.console.log; } else { return function() { window.alert( Utils.array( arguments ).join(', ') ); }; } }()); /** A ready method for adding callbacks when a gallery is ready Each method is call before the extend option for every instance @param {function} callback The function to call @returns Galleria */ Galleria.ready = function( fn ) { $.each( _galleries, function( i, gallery ) { fn.call( gallery, gallery._options ); }); Galleria.ready.callbacks.push( fn ); return Galleria; }; Galleria.ready.callbacks = []; /** Method for raising errors @param {string} msg The message to throw @param {boolean} [fatal] Set this to true to override debug settings and display a fatal error */ Galleria.raise = function( msg, fatal ) { var type = fatal ? 'Fatal error' : 'Error', self = this, css = { color: '#fff', position: 'absolute', top: 0, left: 0, zIndex: 100000 }, echo = function( msg ) { var html = '<div style="padding:4px;margin:0 0 2px;background:#' + ( fatal ? '811' : '222' ) + '";>' + ( fatal ? '<strong>' + type + ': </strong>' : '' ) + msg + '</div>'; $.each( _instances, function() { var cont = this.$( 'errors' ), target = this.$( 'target' ); if ( !cont.length ) { target.css( 'position', 'relative' ); cont = this.addElement( 'errors' ).appendChild( 'target', 'errors' ).$( 'errors' ).css(css); } cont.append( html ); }); if ( !_instances.length ) { $('<div>').css( $.extend( css, { position: 'fixed' } ) ).append( html ).appendTo( DOM().body ); } }; // if debug is on, display errors and throw exception if fatal if ( DEBUG ) { echo( msg ); if ( fatal ) { throw new Error(type + ': ' + msg); } // else just echo a silent generic error if fatal } else if ( fatal ) { if ( _hasError ) { return; } _hasError = true; fatal = false; echo( 'Gallery could not load.' ); } }; // Add the version Galleria.version = VERSION; /** A method for checking what version of Galleria the user has installed and throws a readable error if the user needs to upgrade. Useful when building plugins that requires a certain version to function. @param {number} version The minimum version required @param {string} [msg] Optional message to display. If not specified, Galleria will throw a generic error. @returns Galleria */ Galleria.requires = function( version, msg ) { msg = msg || 'You need to upgrade Galleria to version ' + version + ' to use one or more components.'; if ( Galleria.version < version ) { Galleria.raise(msg, true); } return Galleria; }; /** Adds preload, cache, scale and crop functionality @constructor @requires jQuery @param {number} [id] Optional id to keep track of instances */ Galleria.Picture = function( id ) { // save the id this.id = id || null; // the image should be null until loaded this.image = null; // Create a new container this.container = Utils.create('galleria-image'); // add container styles $( this.container ).css({ overflow: 'hidden', position: 'relative' // for IE Standards mode }); // saves the original measurements this.original = { width: 0, height: 0 }; // flag when the image is ready this.ready = false; // flag for iframe Picture this.isIframe = false; }; Galleria.Picture.prototype = { // the inherited cache object cache: {}, // show the image on stage show: function() { Utils.show( this.image ); }, // hide the image hide: function() { Utils.moveOut( this.image ); }, clear: function() { this.image = null; }, /** Checks if an image is in cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns {boolean} */ isCached: function( src ) { return !!this.cache[src]; }, /** Preloads an image into the cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns Galleria.Picture */ preload: function( src ) { $( new Image() ).load((function(src, cache) { return function() { cache[ src ] = src; }; }( src, this.cache ))).attr( 'src', src ); }, /** Loads an image and call the callback when ready. Will also add the image to cache. @param {string} src The image source path, ex '/path/to/img.jpg' @param {Object} [size] The forced size of the image, defined as an object { width: xx, height:xx } @param {Function} callback The function to be executed when the image is loaded & scaled @returns The image container (jQuery object) */ load: function(src, size, callback) { if ( typeof size == 'function' ) { callback = size; size = null; } if( this.isIframe ) { var id = 'if'+new Date().getTime(); this.image = $('<iframe>', { src: src, frameborder: 0, id: id, allowfullscreen: true, css: { visibility: 'hidden' } })[0]; $( this.container ).find( 'iframe,img' ).remove(); this.container.appendChild( this.image ); $('#'+id).load( (function( self, callback ) { return function() { window.setTimeout(function() { $( self.image ).css( 'visibility', 'visible' ); if( typeof callback == 'function' ) { callback.call( self, self ); } }, 10); }; }( this, callback ))); return this.container; } this.image = new Image(); var i = 0, reload = false, resort = false, // some jquery cache $container = $( this.container ), $image = $( this.image ), // the onload method onload = (function( self, callback, src ) { return function() { var complete = function() { $( this ).unbind( 'load' ); // save the original size self.original = size || { height: this.height, width: this.width }; self.container.appendChild( this ); self.cache[ src ] = src; // will override old cache if (typeof callback == 'function' ) { window.setTimeout(function() { callback.call( self, self ); },1); } }; // Delay the callback to "fix" the Adblock Bug // http://code.google.com/p/adblockforchrome/issues/detail?id=3701 if ( ( !this.width || !this.height ) ) { window.setTimeout( (function( img ) { return function() { if ( img.width && img.height ) { complete.call( img ); } else { // last resort, this should never happen but just in case it does... if ( !resort ) { $(new Image()).load( onload ).attr( 'src', img.src ); resort = true; } else { Galleria.raise('Could not extract width/height from image: ' + img.src + '. Traced measures: width:' + img.width + 'px, height: ' + img.height + 'px.'); } } }; }( this )), 2); } else { complete.call( this ); } }; }( this, callback, src )); // remove any previous images $container.find( 'iframe,img' ).remove(); // append the image $image.css( 'display', 'block'); // hide it for now Utils.hide( this.image ); // remove any max/min scaling $.each('minWidth minHeight maxWidth maxHeight'.split(' '), function(i, prop) { $image.css(prop, (/min/.test(prop) ? '0' : 'none')); }); if ( this.cache[ src ] ) { // quick load on cache $image.load( onload ).attr( 'src', src ); return this.container; } // begin load and insert in cache when done $image.load( onload ).error( function() { if ( !reload ) { reload = true; // reload the image with a timestamp window.setTimeout((function(image, src) { return function() { image.attr('src', src + '?' + Utils.timestamp() ); }; }( $(this), src )), 50); } else { // apply the dummy image if it exists if ( DUMMY ) { $( this ).attr( 'src', DUMMY ); } else { Galleria.raise('Image not found: ' + src); } } }).attr( 'src', src ); // return the container return this.container; }, /** Scales and crops the image @param {Object} options The method takes an object with a number of options: <ul> <li>width - width of the container</li> <li>height - height of the container</li> <li>min - minimum scale ratio</li> <li>max - maximum scale ratio</li> <li>margin - distance in pixels from the image border to the container</li> <li>complete - a callback that fires when scaling is complete</li> <li>position - positions the image, works like the css background-image property.</li> <li>crop - defines how to crop. Can be true, false, 'width' or 'height'</li> <li>canvas - set to true to try a canvas-based rescale</li> </ul> @returns The image container object (jQuery) */ scale: function( options ) { var self = this; // extend some defaults options = $.extend({ width: 0, height: 0, min: undef, max: undef, margin: 0, complete: F, position: 'center', crop: false, canvas: false }, options); if( this.isIframe ) { $( this.image ).width( options.width ).height( options.height ).removeAttr( 'width' ).removeAttr( 'height' ); $( this.container ).width( options.width ).height( options.height) ; options.complete.call(self, self); try { if( this.image.contentWindow ) { $( this.image.contentWindow ).trigger('resize'); } } catch(e) {} return this.container; } // return the element if no image found if (!this.image) { return this.container; } // store locale variables var width, height, $container = $( self.container ), data; // wait for the width/height Utils.wait({ until: function() { width = options.width || $container.width() || Utils.parseValue( $container.css('width') ); height = options.height || $container.height() || Utils.parseValue( $container.css('height') ); return width && height; }, success: function() { // calculate some cropping var newWidth = ( width - options.margin * 2 ) / self.original.width, newHeight = ( height - options.margin * 2 ) / self.original.height, min = Math.min( newWidth, newHeight ), max = Math.max( newWidth, newHeight ), cropMap = { 'true' : max, 'width' : newWidth, 'height': newHeight, 'false' : min, 'landscape': self.original.width > self.original.height ? max : min, 'portrait': self.original.width < self.original.height ? max : min }, ratio = cropMap[ options.crop.toString() ], canvasKey = ''; // allow max_scale_ratio if ( options.max ) { ratio = Math.min( options.max, ratio ); } // allow min_scale_ratio if ( options.min ) { ratio = Math.max( options.min, ratio ); } $.each( ['width','height'], function( i, m ) { $( self.image )[ m ]( self[ m ] = self.image[ m ] = Math.round( self.original[ m ] * ratio ) ); }); $( self.container ).width( width ).height( height ); if ( options.canvas && _canvas ) { _canvas.elem.width = self.width; _canvas.elem.height = self.height; canvasKey = self.image.src + ':' + self.width + 'x' + self.height; self.image.src = _canvas.cache[ canvasKey ] || (function( key ) { _canvas.context.drawImage(self.image, 0, 0, self.original.width*ratio, self.original.height*ratio); try { data = _canvas.elem.toDataURL(); _canvas.length += data.length; _canvas.cache[ key ] = data; return data; } catch( e ) { return self.image.src; } }( canvasKey ) ); } // calculate image_position var pos = {}, mix = {}, getPosition = function(value, measure, margin) { var result = 0; if (/\%/.test(value)) { var flt = parseInt( value, 10 ) / 100, m = self.image[ measure ] || $( self.image )[ measure ](); result = Math.ceil( m * -1 * flt + margin * flt ); } else { result = Utils.parseValue( value ); } return result; }, positionMap = { 'top': { top: 0 }, 'left': { left: 0 }, 'right': { left: '100%' }, 'bottom': { top: '100%' } }; $.each( options.position.toLowerCase().split(' '), function( i, value ) { if ( value === 'center' ) { value = '50%'; } pos[i ? 'top' : 'left'] = value; }); $.each( pos, function( i, value ) { if ( positionMap.hasOwnProperty( value ) ) { $.extend( mix, positionMap[ value ] ); } }); pos = pos.top ? $.extend( pos, mix ) : mix; pos = $.extend({ top: '50%', left: '50%' }, pos); // apply position $( self.image ).css({ position : 'absolute', top : getPosition(pos.top, 'height', height), left : getPosition(pos.left, 'width', width) }); // show the image self.show(); // flag ready and call the callback self.ready = true; options.complete.call( self, self ); }, error: function() { Galleria.raise('Could not scale image: '+self.image.src); }, timeout: 1000 }); return this; } }; // our own easings $.extend( $.easing, { galleria: function (_, t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t + b; } return c/2*((t-=2)*t*t + 2) + b; }, galleriaIn: function (_, t, b, c, d) { return c*(t/=d)*t + b; }, galleriaOut: function (_, t, b, c, d) { return -c *(t/=d)*(t-2) + b; } }); // the plugin initializer $.fn.galleria = function( options ) { var selector = this.selector; // try domReady if element not found if ( !$(this).length ) { $(function() { if ( $( selector ).length ) { // if found on domReady, go ahead $( selector ).galleria( options ); } else { // if not, try fetching the element for 5 secs, then raise a warning. Galleria.utils.wait({ until: function() { return $( selector ).length; }, success: function() { $( selector ).galleria( options ); }, error: function() { Galleria.raise('Init failed: Galleria could not find the element "'+selector+'".'); }, timeout: 5000 }); } }); return this; } return this.each(function() { // fail silent if already run if ( !$.data(this, 'galleria') ) { $.data( this, 'galleria', new Galleria().init( this, options ) ); } }); }; // phew }( jQuery ) );
JavaScript
/** * Galleria Classic Theme 2012-04-04 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function($) { /*global jQuery, Galleria */ Galleria.addTheme({ name: 'classic', author: 'Galleria', css: 'galleria.classic.css', defaults: { transition: 'slide', thumbCrop: 'height', // set this to false if you want to show the caption all the time: _toggleInfo: true }, init: function(options) { Galleria.requires(1.25, 'This version of Classic theme requires Galleria 1.2.5 or later'); // add some elements this.addElement('info-link','info-close'); this.append({ 'info' : ['info-link','info-close'] }); // cache some stuff var info = this.$('info-link,info-close,info-text'), touch = Galleria.TOUCH, click = touch ? 'touchstart' : 'click'; // show loader & counter with opacity this.$('loader,counter').show().css('opacity', 0.4); // some stuff for non-touch browsers if (! touch ) { this.addIdleState( this.get('image-nav-left'), { left:-50 }); this.addIdleState( this.get('image-nav-right'), { right:-50 }); this.addIdleState( this.get('counter'), { opacity:0 }); } // toggle info if ( options._toggleInfo === true ) { info.bind( click, function() { info.toggle(); }); } else { info.show(); this.$('info-link, info-close').hide(); } // bind some stuff this.bind('thumbnail', function(e) { if (! touch ) { // fade thumbnails $(e.thumbTarget).css('opacity', 0.6).parent().hover(function() { $(this).not('.active').children().stop().fadeTo(100, 1); }, function() { $(this).not('.active').children().stop().fadeTo(400, 0.6); }); if ( e.index === this.getIndex() ) { $(e.thumbTarget).css('opacity',1); } } else { $(e.thumbTarget).css('opacity', this.getIndex() ? 1 : 0.6); } }); this.bind('loadstart', function(e) { if (!e.cached) { this.$('loader').show().fadeTo(200, 0.4); } this.$('info').toggle( this.hasInfo() ); $(e.thumbTarget).css('opacity',1).parent().siblings().children().css('opacity', 0.6); }); this.bind('loadfinish', function(e) { this.$('loader').fadeOut(200); }); } }); }(jQuery));
JavaScript
/** * @preserve Galleria Twelve Theme 2011-06-09 * http://galleria.aino.se * * Copyright (c) 2011, Aino */ /*global jQuery, Galleria */ (function($) { Galleria.addTheme({ name: 'twelve', author: 'Galleria', css: 'galleria.twelve.css', defaults: { transition: 'pulse', transitionSpeed: 500, imageCrop: true, thumbCrop: true, carousel: false, // theme specific defaults: _locale: { show_thumbnails: 'Show thumbnails', hide_thumbnails: 'Hide thumbnails', play: 'Play slideshow', pause: 'Pause slideshow', enter_fullscreen: 'Enter fullscreen', exit_fullscreen: 'Exit fullscreen', popout_image: 'Popout image', showing_image: 'Showing image %s of %s' }, _showFullscreen: true, _showPopout: true, _showProgress: true, _showTooltip: true }, init: function(options) { // add some elements this.addElement('bar','fullscreen','play','popout','thumblink','s1','s2','s3','s4','progress'); this.append({ 'stage' : 'progress', 'container': ['bar','tooltip'], 'bar' : ['fullscreen','play','popout','thumblink','info','s1','s2','s3','s4'] }); this.prependChild('info','counter'); // copy the scope var gallery = this, // cache some stuff thumbs = this.$('thumbnails-container'), thumb_link = this.$('thumblink'), fs_link = this.$('fullscreen'), play_link = this.$('play'), pop_link = this.$('popout'), bar = this.$('bar'), progress = this.$('progress'), transition = options.transition, lang = options._locale, // statics OPEN = false, FULLSCREEN = false, PLAYING = !!options.autoplay, CONTINUE = false, // helper functions scaleThumbs = function() { thumbs.height( gallery.getStageHeight() ).width( gallery.getStageWidth() ).css('top', OPEN ? 0 : gallery.getStageHeight()+30 ); }, toggleThumbs = function(e) { if (OPEN && CONTINUE) { gallery.play(); } else { CONTINUE = PLAYING; gallery.pause(); } Galleria.utils.animate( thumbs, { top: OPEN ? gallery.getStageHeight()+30 : 0 } , { easing:'galleria', duration:400, complete: function() { gallery.defineTooltip('thumblink', OPEN ? lang.show_thumbnails : lang.hide_thumbnails); thumb_link[OPEN ? 'removeClass' : 'addClass']('open'); OPEN = !OPEN; } }); }; // scale the thumbnail container scaleThumbs(); // bind the tooltips if (options._showTooltip) { gallery.bindTooltip({ 'thumblink': lang.show_thumbnails, 'fullscreen': lang.enter_fullscreen, 'play': lang.play, 'popout': lang.popout_image, 'caption': function() { var data = gallery.getData(); var str = ''; if (data) { if (data.title && data.title.length) { str+='<strong>'+data.title+'</strong>'; } if (data.description && data.description.length) { str+='<br>'+data.description; } } return str; }, 'counter': function() { return lang.showing_image.replace( /\%s/, gallery.getIndex() + 1 ).replace( /\%s/, gallery.getDataLength() ); } }); } if ( !options.showInfo ) { this.$( 'info' ).hide(); } // bind galleria events this.bind( 'play', function() { PLAYING = true; play_link.addClass('playing'); }); this.bind( 'pause', function() { PLAYING = false; play_link.removeClass('playing'); progress.width(0); }); if (options._showProgress) { this.bind( 'progress', function(e) { progress.width( e.percent/100 * this.getStageWidth() ); }); } this.bind( 'loadstart', function(e) { if (!e.cached) { this.$('loader').show(); } }); this.bind( 'loadfinish', function(e) { progress.width(0); this.$('loader').hide(); this.refreshTooltip('counter','caption'); }); this.bind( 'thumbnail', function(e) { $(e.thumbTarget).hover(function() { gallery.setInfo(e.thumbOrder); gallery.setCounter(e.thumbOrder); }, function() { gallery.setInfo(); gallery.setCounter(); }).click(function() { toggleThumbs(); }); }); this.bind( 'fullscreen_enter', function(e) { FULLSCREEN = true; gallery.setOptions('transition', false); fs_link.addClass('open'); bar.css('bottom',0); this.defineTooltip('fullscreen', lang.exit_fullscreen); if ( !Galleria.TOUCH ) { this.addIdleState(bar, { bottom: -31 }); } }); this.bind( 'fullscreen_exit', function(e) { FULLSCREEN = false; Galleria.utils.clearTimer('bar'); gallery.setOptions('transition',transition); fs_link.removeClass('open'); bar.css('bottom',0); this.defineTooltip('fullscreen', lang.enter_fullscreen); if ( !Galleria.TOUCH ) { this.removeIdleState(bar, { bottom:-31 }); } }); this.bind( 'rescale', scaleThumbs); if ( !Galleria.TOUCH ) { // STB //this.addIdleState(this.get('image-nav-left'), {left:-36}); //this.addIdleState(this.get('image-nav-right'), {right:-36}); } // bind thumblink thumb_link.click( toggleThumbs ); // bind popup if (options._showPopout) { pop_link.click(function(e) { gallery.openLightbox(); e.preventDefault(); }); } else { pop_link.remove(); if (options._showFullscreen) { this.$('s4').remove(); this.$('info').css('right',40); fs_link.css('right',0); } } // bind play button play_link.click(function() { gallery.defineTooltip('play', PLAYING ? lang.play : lang.pause); if (PLAYING) { gallery.pause(); } else { if (OPEN) { thumb_link.click(); } gallery.play(); } }); // bind fullscreen if (options._showFullscreen) { fs_link.click(function() { if (FULLSCREEN) { gallery.exitFullscreen(); } else { gallery.enterFullscreen(); } }); } else { fs_link.remove(); if (options._show_popout) { this.$('s4').remove(); this.$('info').css('right',40); pop_link.css('right',0); } } if (!options._showFullscreen && !options._showPopout) { this.$('s3,s4').remove(); this.$('info').css('right',10); } if (options.autoplay) { this.trigger( 'play' ); } } }); }( jQuery ));
JavaScript
/** * Galleria v 1.2.8 2012-08-09 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function( $ ) { /*global jQuery, navigator, Galleria:true, Image */ // some references var undef, window = this, doc = window.document, $doc = $( doc ), $win = $( window ), // native prototypes protoArray = Array.prototype, // internal constants VERSION = 1.28, DEBUG = true, TIMEOUT = 30000, DUMMY = false, NAV = navigator.userAgent.toLowerCase(), HASH = window.location.hash.replace(/#\//, ''), F = function(){}, FALSE = function() { return false; }, IE = (function() { var v = 3, div = doc.createElement( 'div' ), all = div.getElementsByTagName( 'i' ); do { div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->'; } while ( all[0] ); return v > 4 ? v : undef; }() ), DOM = function() { return { html: doc.documentElement, body: doc.body, head: doc.getElementsByTagName('head')[0], title: doc.title }; }, // list of Galleria events _eventlist = 'data ready thumbnail loadstart loadfinish image play pause progress ' + 'fullscreen_enter fullscreen_exit idle_enter idle_exit rescale ' + 'lightbox_open lightbox_close lightbox_image', _events = (function() { var evs = []; $.each( _eventlist.split(' '), function( i, ev ) { evs.push( ev ); // legacy events if ( /_/.test( ev ) ) { evs.push( ev.replace( /_/g, '' ) ); } }); return evs; }()), // legacy options // allows the old my_setting syntax and converts it to camel case _legacyOptions = function( options ) { var n; if ( typeof options !== 'object' ) { // return whatever it was... return options; } $.each( options, function( key, value ) { if ( /^[a-z]+_/.test( key ) ) { n = ''; $.each( key.split('_'), function( i, k ) { n += i > 0 ? k.substr( 0, 1 ).toUpperCase() + k.substr( 1 ) : k; }); options[ n ] = value; delete options[ key ]; } }); return options; }, _patchEvent = function( type ) { // allow 'image' instead of Galleria.IMAGE if ( $.inArray( type, _events ) > -1 ) { return Galleria[ type.toUpperCase() ]; } return type; }, // video providers _video = { youtube: { reg: /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&amp;(?:amp;)?)*v(?:&lt;[A-Z]+&gt;)?=([0-9a-zA-Z\-\_]+))/i, embed: function(id) { return 'http://www.youtube.com/embed/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=json-in-script&callback=?', function(data) { try { success( data.entry.media$group.media$thumbnail[0].url ); } catch(e) { fail(); } }).error(fail); } }, vimeo: { reg: /https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i, embed: function(id) { return 'http://player.vimeo.com/video/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('http://vimeo.com/api/v2/video/' + id + '.json?callback=?', function(data) { try { success( data[0].thumbnail_medium ); } catch(e) { fail(); } }).error(fail); } }, dailymotion: { reg: /https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/, embed: function(id) { return 'http://www.dailymotion.com/embed/video/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('https://api.dailymotion.com/video/'+id+'?fields=thumbnail_medium_url&callback=?', function(data) { try { success( data.thumbnail_medium_url ); } catch(e) { fail(); } }).error(fail); } } }, // utility for testing the video URL and getting the video ID _videoTest = function( url ) { var match; for ( var v in _video ) { match = url && url.match( _video[v].reg ); if( match && match.length ) { return { id: match[2], provider: v }; } } return false; }, // native fullscreen handler _nativeFullscreen = { support: (function() { var html = DOM().html; return html.requestFullscreen || html.mozRequestFullScreen || html.webkitRequestFullScreen; }()), callback: F, enter: function( instance, callback ) { this.instance = instance; this.callback = callback || F; var html = DOM().html; if ( html.requestFullscreen ) { html.requestFullscreen(); } else if ( html.mozRequestFullScreen ) { html.mozRequestFullScreen(); } else if ( html.webkitRequestFullScreen ) { html.webkitRequestFullScreen(); } }, exit: function( callback ) { this.callback = callback || F; if ( doc.exitFullscreen ) { doc.exitFullscreen(); } else if ( doc.mozCancelFullScreen ) { doc.mozCancelFullScreen(); } else if ( doc.webkitCancelFullScreen ) { doc.webkitCancelFullScreen(); } }, instance: null, listen: function() { if ( !this.support ) { return; } var handler = function() { if ( !_nativeFullscreen.instance ) { return; } var fs = _nativeFullscreen.instance._fullscreen; if ( doc.fullscreen || doc.mozFullScreen || doc.webkitIsFullScreen ) { fs._enter( _nativeFullscreen.callback ); } else { fs._exit( _nativeFullscreen.callback ); } }; doc.addEventListener( 'fullscreenchange', handler, false ); doc.addEventListener( 'mozfullscreenchange', handler, false ); doc.addEventListener( 'webkitfullscreenchange', handler, false ); } }, // the internal gallery holder _galleries = [], // the internal instance holder _instances = [], // flag for errors _hasError = false, // canvas holder _canvas = false, // instance pool, holds the galleries until themeLoad is triggered _pool = [], // themeLoad trigger _themeLoad = function( theme ) { Galleria.theme = theme; // run the instances we have in the pool $.each( _pool, function( i, instance ) { if ( !instance._initialized ) { instance._init.call( instance ); } }); }, // the Utils singleton Utils = (function() { return { // legacy support for clearTimer clearTimer: function( id ) { $.each( Galleria.get(), function() { this.clearTimer( id ); }); }, // legacy support for addTimer addTimer: function( id ) { $.each( Galleria.get(), function() { this.addTimer( id ); }); }, array : function( obj ) { return protoArray.slice.call(obj, 0); }, create : function( className, nodeName ) { nodeName = nodeName || 'div'; var elem = doc.createElement( nodeName ); elem.className = className; return elem; }, getScriptPath : function( src ) { // the currently executing script is always the last src = src || $('script:last').attr('src'); var slices = src.split('/'); if (slices.length == 1) { return ''; } slices.pop(); return slices.join('/') + '/'; }, // CSS3 transitions, added in 1.2.4 animate : (function() { // detect transition var transition = (function( style ) { var props = 'transition WebkitTransition MozTransition OTransition'.split(' '), i; // disable css3 animations in opera until stable if ( window.opera ) { return false; } for ( i = 0; props[i]; i++ ) { if ( typeof style[ props[ i ] ] !== 'undefined' ) { return props[ i ]; } } return false; }(( doc.body || doc.documentElement).style )); // map transitionend event var endEvent = { MozTransition: 'transitionend', OTransition: 'oTransitionEnd', WebkitTransition: 'webkitTransitionEnd', transition: 'transitionend' }[ transition ]; // map bezier easing conversions var easings = { _default: [0.25, 0.1, 0.25, 1], galleria: [0.645, 0.045, 0.355, 1], galleriaIn: [0.55, 0.085, 0.68, 0.53], galleriaOut: [0.25, 0.46, 0.45, 0.94], ease: [0.25, 0, 0.25, 1], linear: [0.25, 0.25, 0.75, 0.75], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }; // function for setting transition css for all browsers var setStyle = function( elem, value, suffix ) { var css = {}; suffix = suffix || 'transition'; $.each( 'webkit moz ms o'.split(' '), function() { css[ '-' + this + '-' + suffix ] = value; }); elem.css( css ); }; // clear styles var clearStyle = function( elem ) { setStyle( elem, 'none', 'transition' ); if ( Galleria.WEBKIT && Galleria.TOUCH ) { setStyle( elem, 'translate3d(0,0,0)', 'transform' ); if ( elem.data('revert') ) { elem.css( elem.data('revert') ); elem.data('revert', null); } } }; // various variables var change, strings, easing, syntax, revert, form, css; // the actual animation method return function( elem, to, options ) { // extend defaults options = $.extend({ duration: 400, complete: F, stop: false }, options); // cache jQuery instance elem = $( elem ); if ( !options.duration ) { elem.css( to ); options.complete.call( elem[0] ); return; } // fallback to jQuery's animate if transition is not supported if ( !transition ) { elem.animate(to, options); return; } // stop if ( options.stop ) { // clear the animation elem.unbind( endEvent ); clearStyle( elem ); } // see if there is a change change = false; $.each( to, function( key, val ) { css = elem.css( key ); if ( Utils.parseValue( css ) != Utils.parseValue( val ) ) { change = true; } // also add computed styles for FF elem.css( key, css ); }); if ( !change ) { window.setTimeout( function() { options.complete.call( elem[0] ); }, options.duration ); return; } // the css strings to be applied strings = []; // the easing bezier easing = options.easing in easings ? easings[ options.easing ] : easings._default; // the syntax syntax = ' ' + options.duration + 'ms' + ' cubic-bezier(' + easing.join(',') + ')'; // add a tiny timeout so that the browsers catches any css changes before animating window.setTimeout( (function(elem, endEvent, to, syntax) { return function() { // attach the end event elem.one(endEvent, (function( elem ) { return function() { // clear the animation clearStyle(elem); // run the complete method options.complete.call(elem[0]); }; }( elem ))); // do the webkit translate3d for better performance on iOS if( Galleria.WEBKIT && Galleria.TOUCH ) { revert = {}; form = [0,0,0]; $.each( ['left', 'top'], function(i, m) { if ( m in to ) { form[ i ] = ( Utils.parseValue( to[ m ] ) - Utils.parseValue(elem.css( m )) ) + 'px'; revert[ m ] = to[ m ]; delete to[ m ]; } }); if ( form[0] || form[1]) { elem.data('revert', revert); strings.push('-webkit-transform' + syntax); // 3d animate setStyle( elem, 'translate3d(' + form.join(',') + ')', 'transform'); } } // push the animation props $.each(to, function( p, val ) { strings.push(p + syntax); }); // set the animation styles setStyle( elem, strings.join(',') ); // animate elem.css( to ); }; }(elem, endEvent, to, syntax)), 2); }; }()), removeAlpha : function( elem ) { if ( IE < 9 && elem ) { var style = elem.style, currentStyle = elem.currentStyle, filter = currentStyle && currentStyle.filter || style.filter || ""; if ( /alpha/.test( filter ) ) { style.filter = filter.replace( /alpha\([^)]*\)/i, '' ); } } }, forceStyles : function( elem, styles ) { elem = $(elem); if ( elem.attr( 'style' ) ) { elem.data( 'styles', elem.attr( 'style' ) ).removeAttr( 'style' ); } elem.css( styles ); }, revertStyles : function() { $.each( Utils.array( arguments ), function( i, elem ) { elem = $( elem ); elem.removeAttr( 'style' ); elem.attr('style',''); // "fixes" webkit bug if ( elem.data( 'styles' ) ) { elem.attr( 'style', elem.data('styles') ).data( 'styles', null ); } }); }, moveOut : function( elem ) { Utils.forceStyles( elem, { position: 'absolute', left: -10000 }); }, moveIn : function() { Utils.revertStyles.apply( Utils, Utils.array( arguments ) ); }, elem : function( elem ) { if (elem instanceof $) { return { $: elem, dom: elem[0] }; } else { return { $: $(elem), dom: elem }; } }, hide : function( elem, speed, callback ) { callback = callback || F; var el = Utils.elem( elem ), $elem = el.$; elem = el.dom; // save the value if not exist if (! $elem.data('opacity') ) { $elem.data('opacity', $elem.css('opacity') ); } // always hide var style = { opacity: 0 }; if (speed) { var complete = IE < 9 && elem ? function() { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; } else { $elem.css( style ); } } }, show : function( elem, speed, callback ) { callback = callback || F; var el = Utils.elem( elem ), $elem = el.$; elem = el.dom; // bring back saved opacity var saved = parseFloat( $elem.data('opacity') ) || 1, style = { opacity: saved }; // animate or toggle if (speed) { if ( IE < 9 ) { $elem.css('opacity', 0); elem.style.visibility = 'visible'; } var complete = IE < 9 && elem ? function() { if ( style.opacity == 1 ) { Utils.removeAlpha( elem ); } callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && style.opacity == 1 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'visible'; } else { $elem.css( style ); } } }, // enhanced click for mobile devices // we bind a touchend and hijack any click event in the bubble // then we execute the click directly and save it in a separate data object for later optimizeTouch: (function() { var node, evs, fakes, travel, evt = {}, handler = function( e ) { e.preventDefault(); evt = $.extend({}, e, true); }, attach = function() { this.evt = evt; }, fake = function() { this.handler.call(node, this.evt); }; return function( elem ) { $(elem).bind('touchend', function( e ) { node = e.target; travel = true; while( node.parentNode && node != e.currentTarget && travel ) { evs = $(node).data('events'); fakes = $(node).data('fakes'); if (evs && 'click' in evs) { travel = false; e.preventDefault(); // fake the click and save the event object $(node).click(handler).click(); // remove the faked click evs.click.pop(); // attach the faked event $.each( evs.click, attach); // save the faked clicks in a new data object $(node).data('fakes', evs.click); // remove all clicks delete evs.click; } else if ( fakes ) { travel = false; e.preventDefault(); // fake all clicks $.each( fakes, fake ); } // bubble node = node.parentNode; } }); }; }()), wait : function(options) { options = $.extend({ until : FALSE, success : F, error : function() { Galleria.raise('Could not complete wait function.'); }, timeout: 3000 }, options); var start = Utils.timestamp(), elapsed, now, fn = function() { now = Utils.timestamp(); elapsed = now - start; if ( options.until( elapsed ) ) { options.success(); return false; } if (typeof options.timeout == 'number' && now >= start + options.timeout) { options.error(); return false; } window.setTimeout(fn, 10); }; window.setTimeout(fn, 10); }, toggleQuality : function( img, force ) { if ( ( IE !== 7 && IE !== 8 ) || !img || img.nodeName.toUpperCase() != 'IMG' ) { return; } if ( typeof force === 'undefined' ) { force = img.style.msInterpolationMode === 'nearest-neighbor'; } img.style.msInterpolationMode = force ? 'bicubic' : 'nearest-neighbor'; }, insertStyleTag : function( styles ) { var style = doc.createElement( 'style' ); DOM().head.appendChild( style ); if ( style.styleSheet ) { // IE style.styleSheet.cssText = styles; } else { var cssText = doc.createTextNode( styles ); style.appendChild( cssText ); } }, // a loadscript method that works for local scripts loadScript: function( url, callback ) { var done = false, script = $('<scr'+'ipt>').attr({ src: url, async: true }).get(0); // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') ) { done = true; // Handle memory leak in IE script.onload = script.onreadystatechange = null; if (typeof callback === 'function') { callback.call( this, this ); } } }; DOM().head.appendChild( script ); }, // parse anything into a number parseValue: function( val ) { if (typeof val === 'number') { return val; } else if (typeof val === 'string') { var arr = val.match(/\-?\d|\./g); return arr && arr.constructor === Array ? arr.join('')*1 : 0; } else { return 0; } }, // timestamp abstraction timestamp: function() { return new Date().getTime(); }, loadCSS : function( href, id, callback ) { var link, length; // look for manual css $('link[rel=stylesheet]').each(function() { if ( new RegExp( href ).test( this.href ) ) { link = this; return false; } }); if ( typeof id === 'function' ) { callback = id; id = undef; } callback = callback || F; // dirty // if already present, return if ( link ) { callback.call( link, link ); return link; } // save the length of stylesheets to check against length = doc.styleSheets.length; // check for existing id if( $( '#' + id ).length ) { $( '#' + id ).attr( 'href', href ); length--; } else { link = $( '<link>' ).attr({ rel: 'stylesheet', href: href, id: id }).get(0); var styles = $('link[rel="stylesheet"], style'); if ( styles.length ) { styles.get(0).parentNode.insertBefore( link, styles[0] ); } else { DOM().head.appendChild( link ); } if ( IE ) { // IE has a limit of 31 stylesheets in one document if( length >= 31 ) { Galleria.raise( 'You have reached the browser stylesheet limit (31)', true ); return; } } } if ( typeof callback === 'function' ) { // First check for dummy element (new in 1.2.8) var $loader = $('<s>').attr( 'id', 'galleria-loader' ).hide().appendTo( DOM().body ); Utils.wait({ until: function() { return $loader.height() == 1; }, success: function() { $loader.remove(); callback.call( link, link ); }, error: function() { $loader.remove(); // If failed, tell the dev to download the latest theme Galleria.raise( 'Theme CSS could not load after 20 sec. Please download the latest theme at http://galleria.io/customer/', true ); }, timeout: 20000 }); } return link; } }; }()), // the transitions holder _transitions = (function() { var _slide = function(params, complete, fade, door) { var easing = this.getOptions('easing'), distance = this.getStageWidth(), from = { left: distance * ( params.rewind ? -1 : 1 ) }, to = { left: 0 }; if ( fade ) { from.opacity = 0; to.opacity = 1; } else { from.opacity = 1; } $(params.next).css(from); Utils.animate(params.next, to, { duration: params.speed, complete: (function( elems ) { return function() { complete(); elems.css({ left: 0 }); }; }( $( params.next ).add( params.prev ) )), queue: false, easing: easing }); if (door) { params.rewind = !params.rewind; } if (params.prev) { from = { left: 0 }; to = { left: distance * ( params.rewind ? 1 : -1 ) }; if ( fade ) { from.opacity = 1; to.opacity = 0; } $(params.prev).css(from); Utils.animate(params.prev, to, { duration: params.speed, queue: false, easing: easing, complete: function() { $(this).css('opacity', 0); } }); } }; return { active: false, init: function( effect, params, complete ) { if ( _transitions.effects.hasOwnProperty( effect ) ) { _transitions.effects[ effect ].call( this, params, complete ); } }, effects: { fade: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); if (params.prev) { $(params.prev).css('opacity',1).show(); Utils.animate(params.prev, { opacity: 0 },{ duration: params.speed }); } }, flash: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }); if (params.prev) { Utils.animate( params.prev, { opacity: 0 },{ duration: params.speed/2, complete: function() { Utils.animate( params.next, { opacity:1 },{ duration: params.speed, complete: complete }); } }); } else { Utils.animate( params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); } }, pulse: function(params, complete) { if (params.prev) { $(params.prev).hide(); } $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity:1 },{ duration: params.speed, complete: complete }); }, slide: function(params, complete) { _slide.apply( this, Utils.array( arguments ) ); }, fadeslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [true] ) ); }, doorslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [false, true] ) ); } } }; }()); _nativeFullscreen.listen(); /** The main Galleria class @class @constructor @example var gallery = new Galleria(); @author http://aino.se @requires jQuery */ Galleria = function() { var self = this; // internal options this._options = {}; // flag for controlling play/pause this._playing = false; // internal interval for slideshow this._playtime = 5000; // internal variable for the currently active image this._active = null; // the internal queue, arrayified this._queue = { length: 0 }; // the internal data array this._data = []; // the internal dom collection this._dom = {}; // the internal thumbnails array this._thumbnails = []; // the internal layers array this._layers = []; // internal init flag this._initialized = false; // internal firstrun flag this._firstrun = false; // global stagewidth/height this._stageWidth = 0; this._stageHeight = 0; // target holder this._target = undef; // bind hashes this._binds = []; // instance id this._id = parseInt(Math.random()*10000, 10); // add some elements var divs = 'container stage images image-nav image-nav-left image-nav-right ' + 'info info-text info-title info-description ' + 'thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right ' + 'loader counter tooltip', spans = 'current total'; $.each( divs.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId ); }); $.each( spans.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId, 'span' ); }); // the internal keyboard object // keeps reference of the keybinds and provides helper methods for binding keys var keyboard = this._keyboard = { keys : { 'UP': 38, 'DOWN': 40, 'LEFT': 37, 'RIGHT': 39, 'RETURN': 13, 'ESCAPE': 27, 'BACKSPACE': 8, 'SPACE': 32 }, map : {}, bound: false, press: function(e) { var key = e.keyCode || e.which; if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) { keyboard.map[key].call(self, e); } }, attach: function(map) { var key, up; for( key in map ) { if ( map.hasOwnProperty( key ) ) { up = key.toUpperCase(); if ( up in keyboard.keys ) { keyboard.map[ keyboard.keys[up] ] = map[key]; } else { keyboard.map[ up ] = map[key]; } } } if ( !keyboard.bound ) { keyboard.bound = true; $doc.bind('keydown', keyboard.press); } }, detach: function() { keyboard.bound = false; keyboard.map = {}; $doc.unbind('keydown', keyboard.press); } }; // internal controls for keeping track of active / inactive images var controls = this._controls = { 0: undef, 1: undef, active : 0, swap : function() { controls.active = controls.active ? 0 : 1; }, getActive : function() { return controls[ controls.active ]; }, getNext : function() { return controls[ 1 - controls.active ]; } }; // internal carousel object var carousel = this._carousel = { // shortcuts next: self.$('thumb-nav-right'), prev: self.$('thumb-nav-left'), // cache the width width: 0, // track the current position current: 0, // cache max value max: 0, // save all hooks for each width in an array hooks: [], // update the carousel // you can run this method anytime, f.ex on window.resize update: function() { var w = 0, h = 0, hooks = [0]; $.each( self._thumbnails, function( i, thumb ) { if ( thumb.ready ) { w += thumb.outerWidth || $( thumb.container ).outerWidth( true ); hooks[ i+1 ] = w; h = Math.max( h, thumb.outerHeight || $( thumb.container).outerHeight( true ) ); } }); self.$( 'thumbnails' ).css({ width: w, height: h }); carousel.max = w; carousel.hooks = hooks; carousel.width = self.$( 'thumbnails-list' ).width(); carousel.setClasses(); self.$( 'thumbnails-container' ).toggleClass( 'galleria-carousel', w > carousel.width ); // one extra calculation carousel.width = self.$( 'thumbnails-list' ).width(); // todo: fix so the carousel moves to the left }, bindControls: function() { var i; carousel.next.bind( 'click', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i < carousel.hooks.length; i++ ) { if ( carousel.hooks[i] - carousel.hooks[ carousel.current ] > carousel.width ) { carousel.set(i - 2); break; } } } else { carousel.set( carousel.current + self._options.carouselSteps); } }); carousel.prev.bind( 'click', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i >= 0; i-- ) { if ( carousel.hooks[ carousel.current ] - carousel.hooks[i] > carousel.width ) { carousel.set( i + 2 ); break; } else if ( i === 0 ) { carousel.set( 0 ); break; } } } else { carousel.set( carousel.current - self._options.carouselSteps ); } }); }, // calculate and set positions set: function( i ) { i = Math.max( i, 0 ); while ( carousel.hooks[i - 1] + carousel.width >= carousel.max && i >= 0 ) { i--; } carousel.current = i; carousel.animate(); }, // get the last position getLast: function(i) { return ( i || carousel.current ) - 1; }, // follow the active image follow: function(i) { //don't follow if position fits if ( i === 0 || i === carousel.hooks.length - 2 ) { carousel.set( i ); return; } // calculate last position var last = carousel.current; while( carousel.hooks[last] - carousel.hooks[ carousel.current ] < carousel.width && last <= carousel.hooks.length ) { last ++; } // set position if ( i - 1 < carousel.current ) { carousel.set( i - 1 ); } else if ( i + 2 > last) { carousel.set( i - last + carousel.current + 2 ); } }, // helper for setting disabled classes setClasses: function() { carousel.prev.toggleClass( 'disabled', !carousel.current ); carousel.next.toggleClass( 'disabled', carousel.hooks[ carousel.current ] + carousel.width >= carousel.max ); }, // the animation method animate: function(to) { carousel.setClasses(); var num = carousel.hooks[ carousel.current ] * -1; if ( isNaN( num ) ) { return; } Utils.animate(self.get( 'thumbnails' ), { left: num },{ duration: self._options.carouselSpeed, easing: self._options.easing, queue: false }); } }; // tooltip control // added in 1.2 var tooltip = this._tooltip = { initialized : false, open: false, timer: 'tooltip' + self._id, swapTimer: 'swap' + self._id, init: function() { tooltip.initialized = true; var css = '.galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3;' + 'opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}'; Utils.insertStyleTag(css); self.$( 'tooltip' ).css({ opacity: 0.8, visibility: 'visible', display: 'none' }); }, // move handler move: function( e ) { var mouseX = self.getMousePosition(e).x, mouseY = self.getMousePosition(e).y, $elem = self.$( 'tooltip' ), x = mouseX, y = mouseY, height = $elem.outerHeight( true ) + 1, width = $elem.outerWidth( true ), limitY = height + 15; var maxX = self.$( 'container').width() - width - 2, maxY = self.$( 'container').height() - height - 2; if ( !isNaN(x) && !isNaN(y) ) { x += 10; y -= 30; x = Math.max( 0, Math.min( maxX, x ) ); y = Math.max( 0, Math.min( maxY, y ) ); if( mouseY < limitY ) { y = limitY; } $elem.css({ left: x, top: y }); } }, // bind elements to the tooltip // you can bind multiple elementIDs using { elemID : function } or { elemID : string } // you can also bind single DOM elements using bind(elem, string) bind: function( elem, value ) { // todo: revise if alternative tooltip is needed for mobile devices if (Galleria.TOUCH) { return; } if (! tooltip.initialized ) { tooltip.init(); } var mouseout = function() { self.$( 'container' ).unbind( 'mousemove', tooltip.move ); self.clearTimer( tooltip.timer ); self.$( 'tooltip' ).stop().animate({ opacity: 0 }, 200, function() { self.$( 'tooltip' ).hide(); self.addTimer( tooltip.swapTimer, function() { tooltip.open = false; }, 1000); }); }; var hover = function( elem, value) { tooltip.define( elem, value ); $( elem ).hover(function() { self.clearTimer( tooltip.swapTimer ); self.$('container').unbind( 'mousemove', tooltip.move ).bind( 'mousemove', tooltip.move ).trigger( 'mousemove' ); tooltip.show( elem ); self.addTimer( tooltip.timer, function() { self.$( 'tooltip' ).stop().show().animate({ opacity: 1 }); tooltip.open = true; }, tooltip.open ? 0 : 500); }, mouseout).click(mouseout); }; if ( typeof value === 'string' ) { hover( ( elem in self._dom ? self.get( elem ) : elem ), value ); } else { // asume elemID here $.each( elem, function( elemID, val ) { hover( self.get(elemID), val ); }); } }, show: function( elem ) { elem = $( elem in self._dom ? self.get(elem) : elem ); var text = elem.data( 'tt' ), mouseup = function( e ) { // attach a tiny settimeout to make sure the new tooltip is filled window.setTimeout( (function( ev ) { return function() { tooltip.move( ev ); }; }( e )), 10); elem.unbind( 'mouseup', mouseup ); }; text = typeof text === 'function' ? text() : text; if ( ! text ) { return; } self.$( 'tooltip' ).html( text.replace(/\s/, '&nbsp;') ); // trigger mousemove on mouseup in case of click elem.bind( 'mouseup', mouseup ); }, define: function( elem, value ) { // we store functions, not strings if (typeof value !== 'function') { var s = value; value = function() { return s; }; } elem = $( elem in self._dom ? self.get(elem) : elem ).data('tt', value); tooltip.show( elem ); } }; // internal fullscreen control var fullscreen = this._fullscreen = { scrolled: 0, crop: undef, transition: undef, active: false, keymap: self._keyboard.map, parseCallback: function( callback, enter ) { return _transitions.active ? function() { if ( typeof callback == 'function' ) { callback(); } var active = self._controls.getActive(), next = self._controls.getNext(); self._scaleImage( next ); self._scaleImage( active ); if ( enter && self._options.trueFullscreen ) { // Firefox bug, revise later $( active.container ).add( next.container ).trigger( 'transitionend' ); } } : callback; }, enter: function( callback ) { callback = fullscreen.parseCallback( callback, true ); if ( self._options.trueFullscreen && _nativeFullscreen.support ) { _nativeFullscreen.enter( self, callback ); } else { fullscreen._enter( callback ); } }, _enter: function( callback ) { fullscreen.active = true; // hide the image until rescale is complete Utils.hide( self.getActiveImage() ); self.$( 'container' ).addClass( 'fullscreen' ); fullscreen.scrolled = $win.scrollTop(); // begin styleforce Utils.forceStyles(self.get('container'), { position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10000 }); var htmlbody = { height: '100%', overflow: 'hidden', margin:0, padding:0 }, data = self.getData(), options = self._options; Utils.forceStyles( DOM().html, htmlbody ); Utils.forceStyles( DOM().body, htmlbody ); // temporarily attach some keys // save the old ones first in a cloned object fullscreen.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: self.exitFullscreen, right: self.next, left: self.prev }); // temporarily save the crop fullscreen.crop = options.imageCrop; // set fullscreen options if ( options.fullscreenCrop != undef ) { options.imageCrop = options.fullscreenCrop; } // swap to big image if it's different from the display image if ( data && data.big && data.image !== data.big ) { var big = new Galleria.Picture(), cached = big.isCached( data.big ), index = self.getIndex(), thumb = self._thumbnails[ index ]; self.trigger( { type: Galleria.LOADSTART, cached: cached, rewind: false, index: index, imageTarget: self.getActiveImage(), thumbTarget: thumb, galleriaData: data }); big.load( data.big, function( big ) { self._scaleImage( big, { complete: function( big ) { self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: index, rewind: false, imageTarget: big.image, thumbTarget: thumb }); var image = self._controls.getActive().image; if ( image ) { $( image ).width( big.image.width ).height( big.image.height ) .attr( 'style', $( big.image ).attr('style') ) .attr( 'src', big.image.src ); } } }); }); } // init the first rescale and attach callbacks self.rescale(function() { self.addTimer(false, function() { // show the image after 50 ms Utils.show( self.getActiveImage() ); if (typeof callback === 'function') { callback.call( self ); } }, 100); self.trigger( Galleria.FULLSCREEN_ENTER ); }); // bind the scaling to the resize event $win.resize( function() { fullscreen.scale(); } ); }, scale : function() { self.rescale(); }, exit: function( callback ) { callback = fullscreen.parseCallback( callback ); if ( self._options.trueFullscreen && _nativeFullscreen.support ) { _nativeFullscreen.exit( callback ); } else { fullscreen._exit( callback ); } }, _exit: function( callback ) { fullscreen.active = false; Utils.hide( self.getActiveImage() ); self.$('container').removeClass( 'fullscreen' ); // revert all styles Utils.revertStyles( self.get('container'), DOM().html, DOM().body ); // scroll back window.scrollTo(0, fullscreen.scrolled); // detach all keyboard events and apply the old keymap self.detachKeyboard(); self.attachKeyboard( fullscreen.keymap ); // bring back cached options self._options.imageCrop = fullscreen.crop; //self._options.transition = fullscreen.transition; // return to original image var big = self.getData().big, image = self._controls.getActive().image; if ( !self.getData().iframe && image && big && big == image.src ) { window.setTimeout(function(src) { return function() { image.src = src; }; }( self.getData().image ), 1 ); } self.rescale(function() { self.addTimer(false, function() { // show the image after 50 ms Utils.show( self.getActiveImage() ); if ( typeof callback === 'function' ) { callback.call( self ); } $win.trigger( 'resize' ); }, 50); self.trigger( Galleria.FULLSCREEN_EXIT ); }); $win.unbind('resize', fullscreen.scale); } }; // the internal idle object for controlling idle states var idle = this._idle = { trunk: [], bound: false, active: false, add: function(elem, to, from, hide) { if (!elem) { return; } if (!idle.bound) { idle.addEvent(); } elem = $(elem); if ( typeof from == 'boolean' ) { hide = from; from = {}; } from = from || {}; var extract = {}, style; for ( style in to ) { if ( to.hasOwnProperty( style ) ) { extract[ style ] = elem.css( style ); } } elem.data('idle', { from: $.extend( extract, from ), to: to, complete: true, busy: false }); if ( !hide ) { idle.addTimer(); } else { elem.css( to ); } idle.trunk.push(elem); }, remove: function(elem) { elem = $(elem); $.each(idle.trunk, function(i, el) { if ( el && el.length && !el.not(elem).length ) { elem.css( elem.data( 'idle' ).from ); idle.trunk.splice(i, 1); } }); if (!idle.trunk.length) { idle.removeEvent(); self.clearTimer( idle.timer ); } }, addEvent : function() { idle.bound = true; self.$('container').bind( 'mousemove click', idle.showAll ); if ( self._options.idleMode == 'hover' ) { self.$('container').bind( 'mouseleave', idle.hide ); } }, removeEvent : function() { idle.bound = false; self.$('container').bind( 'mousemove click', idle.showAll ); if ( self._options.idleMode == 'hover' ) { self.$('container').unbind( 'mouseleave', idle.hide ); } }, addTimer : function() { if( self._options.idleMode == 'hover' ) { return; } self.addTimer( 'idle', function() { idle.hide(); }, self._options.idleTime ); }, hide : function() { if ( !self._options.idleMode || self.getIndex() === false || self.getData().iframe ) { return; } self.trigger( Galleria.IDLE_ENTER ); var len = idle.trunk.length; $.each( idle.trunk, function(i, elem) { var data = elem.data('idle'); if (! data) { return; } elem.data('idle').complete = false; Utils.animate( elem, data.to, { duration: self._options.idleSpeed, complete: function() { if ( i == len-1 ) { idle.active = false; } } }); }); }, showAll : function() { self.clearTimer( 'idle' ); $.each( idle.trunk, function( i, elem ) { idle.show( elem ); }); }, show: function(elem) { var data = elem.data('idle'); if ( !idle.active || ( !data.busy && !data.complete ) ) { data.busy = true; self.trigger( Galleria.IDLE_EXIT ); self.clearTimer( 'idle' ); Utils.animate( elem, data.from, { duration: self._options.idleSpeed/2, complete: function() { idle.active = true; $(elem).data('idle').busy = false; $(elem).data('idle').complete = true; } }); } idle.addTimer(); } }; // internal lightbox object // creates a predesigned lightbox for simple popups of images in galleria var lightbox = this._lightbox = { width : 0, height : 0, initialized : false, active : null, image : null, elems : {}, keymap: false, init : function() { // trigger the event self.trigger( Galleria.LIGHTBOX_OPEN ); if ( lightbox.initialized ) { return; } lightbox.initialized = true; // create some elements to work with var elems = 'overlay box content shadow title info close prevholder prev nextholder next counter image', el = {}, op = self._options, css = '', abs = 'position:absolute;', prefix = 'lightbox-', cssMap = { overlay: 'position:fixed;display:none;opacity:'+op.overlayOpacity+';filter:alpha(opacity='+(op.overlayOpacity*100)+ ');top:0;left:0;width:100%;height:100%;background:'+op.overlayBackground+';z-index:99990', box: 'position:fixed;display:none;width:400px;height:400px;top:50%;left:50%;margin-top:-200px;margin-left:-200px;z-index:99991', shadow: abs+'background:#000;width:100%;height:100%;', content: abs+'background-color:#fff;top:10px;left:10px;right:10px;bottom:10px;overflow:hidden', info: abs+'bottom:10px;left:10px;right:10px;color:#444;font:11px/13px arial,sans-serif;height:13px', close: abs+'top:10px;right:10px;height:20px;width:20px;background:#fff;text-align:center;cursor:pointer;color:#444;font:16px/22px arial,sans-serif;z-index:99999', image: abs+'top:10px;left:10px;right:10px;bottom:30px;overflow:hidden;display:block;', prevholder: abs+'width:50%;top:0;bottom:40px;cursor:pointer;', nextholder: abs+'width:50%;top:0;bottom:40px;right:-1px;cursor:pointer;', prev: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;left:20px;display:none;text-align:center;color:#000;font:bold 16px/36px arial,sans-serif', next: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;right:20px;left:auto;display:none;font:bold 16px/36px arial,sans-serif;text-align:center;color:#000', title: 'float:left', counter: 'float:right;margin-left:8px;' }, hover = function(elem) { return elem.hover( function() { $(this).css( 'color', '#bbb' ); }, function() { $(this).css( 'color', '#444' ); } ); }, appends = {}; // IE8 fix for IE's transparent background event "feature" if ( IE && IE > 7 ) { cssMap.nextholder += 'background:#000;filter:alpha(opacity=0);'; cssMap.prevholder += 'background:#000;filter:alpha(opacity=0);'; } // create and insert CSS $.each(cssMap, function( key, value ) { css += '.galleria-'+prefix+key+'{'+value+'}'; }); css += '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'prevholder,'+ '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'nextholder{'+ 'width:100px;height:100px;top:50%;margin-top:-70px}'; Utils.insertStyleTag( css ); // create the elements $.each(elems.split(' '), function( i, elemId ) { self.addElement( 'lightbox-' + elemId ); el[ elemId ] = lightbox.elems[ elemId ] = self.get( 'lightbox-' + elemId ); }); // initiate the image lightbox.image = new Galleria.Picture(); // append the elements $.each({ box: 'shadow content close prevholder nextholder', info: 'title counter', content: 'info image', prevholder: 'prev', nextholder: 'next' }, function( key, val ) { var arr = []; $.each( val.split(' '), function( i, prop ) { arr.push( prefix + prop ); }); appends[ prefix+key ] = arr; }); self.append( appends ); $( el.image ).append( lightbox.image.container ); $( DOM().body ).append( el.overlay, el.box ); Utils.optimizeTouch( el.box ); // add the prev/next nav and bind some controls hover( $( el.close ).bind( 'click', lightbox.hide ).html('&#215;') ); $.each( ['Prev','Next'], function(i, dir) { var $d = $( el[ dir.toLowerCase() ] ).html( /v/.test( dir ) ? '&#8249;&nbsp;' : '&nbsp;&#8250;' ), $e = $( el[ dir.toLowerCase()+'holder'] ); $e.bind( 'click', function() { lightbox[ 'show' + dir ](); }); // IE7 and touch devices will simply show the nav if ( IE < 8 || Galleria.TOUCH ) { $d.show(); return; } $e.hover( function() { $d.show(); }, function(e) { $d.stop().fadeOut( 200 ); }); }); $( el.overlay ).bind( 'click', lightbox.hide ); // the lightbox animation is slow on ipad if ( Galleria.IPAD ) { self._options.lightboxTransitionSpeed = 0; } }, rescale: function(event) { // calculate var width = Math.min( $win.width()-40, lightbox.width ), height = Math.min( $win.height()-60, lightbox.height ), ratio = Math.min( width / lightbox.width, height / lightbox.height ), destWidth = Math.round( lightbox.width * ratio ) + 40, destHeight = Math.round( lightbox.height * ratio ) + 60, to = { width: destWidth, height: destHeight, 'margin-top': Math.ceil( destHeight / 2 ) *- 1, 'margin-left': Math.ceil( destWidth / 2 ) *- 1 }; // if rescale event, don't animate if ( event ) { $( lightbox.elems.box ).css( to ); } else { $( lightbox.elems.box ).animate( to, { duration: self._options.lightboxTransitionSpeed, easing: self._options.easing, complete: function() { var image = lightbox.image, speed = self._options.lightboxFadeSpeed; self.trigger({ type: Galleria.LIGHTBOX_IMAGE, imageTarget: image.image }); $( image.container ).show(); $( image.image ).animate({ opacity: 1 }, speed); Utils.show( lightbox.elems.info, speed ); } }); } }, hide: function() { // remove the image lightbox.image.image = null; $win.unbind('resize', lightbox.rescale); $( lightbox.elems.box ).hide(); Utils.hide( lightbox.elems.info ); self.detachKeyboard(); self.attachKeyboard( lightbox.keymap ); lightbox.keymap = false; Utils.hide( lightbox.elems.overlay, 200, function() { $( this ).hide().css( 'opacity', self._options.overlayOpacity ); self.trigger( Galleria.LIGHTBOX_CLOSE ); }); }, showNext: function() { lightbox.show( self.getNext( lightbox.active ) ); }, showPrev: function() { lightbox.show( self.getPrev( lightbox.active ) ); }, show: function(index) { lightbox.active = index = typeof index === 'number' ? index : self.getIndex() || 0; if ( !lightbox.initialized ) { lightbox.init(); } // temporarily attach some keys // save the old ones first in a cloned object if ( !lightbox.keymap ) { lightbox.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: lightbox.hide, right: lightbox.showNext, left: lightbox.showPrev }); } $win.unbind('resize', lightbox.rescale ); var data = self.getData(index), total = self.getDataLength(), n = self.getNext( index ), ndata, p, i; Utils.hide( lightbox.elems.info ); try { for ( i = self._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( 'big' in ndata ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} lightbox.image.isIframe = !!data.iframe; $(lightbox.elems.box).toggleClass( 'iframe', !!data.iframe ); lightbox.image.load( data.iframe || data.big || data.image, function( image ) { lightbox.width = image.isIframe ? $(window).width() : image.original.width; lightbox.height = image.isIframe ? $(window).height() : image.original.height; $( image.image ).css({ width: image.isIframe ? '100%' : '100.1%', height: image.isIframe ? '100%' : '100.1%', top: 0, zIndex: 99998, opacity: 0, visibility: 'visible' }); lightbox.elems.title.innerHTML = data.title || ''; lightbox.elems.counter.innerHTML = (index + 1) + ' / ' + total; $win.resize( lightbox.rescale ); lightbox.rescale(); }); $( lightbox.elems.overlay ).show().css( 'visibility', 'visible' ); $( lightbox.elems.box ).show(); } }; // the internal timeouts object // provides helper methods for controlling timeouts var _timer = this._timer = { trunk: {}, add: function( id, fn, delay, loop ) { id = id || new Date().getTime(); loop = loop || false; this.clear( id ); if ( loop ) { var old = fn; fn = function() { old(); _timer.add( id, fn, delay ); }; } this.trunk[ id ] = window.setTimeout( fn, delay ); }, clear: function( id ) { var del = function( i ) { window.clearTimeout( this.trunk[ i ] ); delete this.trunk[ i ]; }, i; if ( !!id && id in this.trunk ) { del.call( this, id ); } else if ( typeof id === 'undefined' ) { for ( i in this.trunk ) { if ( this.trunk.hasOwnProperty( i ) ) { del.call( this, i ); } } } } }; return this; }; // end Galleria constructor Galleria.prototype = { // bring back the constructor reference constructor: Galleria, /** Use this function to initialize the gallery and start loading. Should only be called once per instance. @param {HTMLElement} target The target element @param {Object} options The gallery options @returns Instance */ init: function( target, options ) { var self = this; options = _legacyOptions( options ); // save the original ingredients this._original = { target: target, options: options, data: null }; // save the target here this._target = this._dom.target = target.nodeName ? target : $( target ).get(0); // save the original content for destruction this._original.html = this._target.innerHTML; // push the instance _instances.push( this ); // raise error if no target is detected if ( !this._target ) { Galleria.raise('Target not found', true); return; } // apply options this._options = { autoplay: false, carousel: true, carouselFollow: true, // legacy, deprecate at 1.3 carouselSpeed: 400, carouselSteps: 'auto', clicknext: false, dailymotion: { foreground: '%23EEEEEE', highlight: '%235BCEC5', background: '%23222222', logo: 0, hideInfos: 1 }, dataConfig : function( elem ) { return {}; }, dataSelector: 'img', dataSort: false, dataSource: this._target, debug: undef, dummy: undef, // 1.2.5 easing: 'galleria', extend: function(options) {}, fullscreenCrop: undef, // 1.2.5 fullscreenDoubleTap: true, // 1.2.4 toggles fullscreen on double-tap for touch devices fullscreenTransition: undef, // 1.2.6 height: 0, idleMode: true, // 1.2.4 toggles idleMode idleTime: 3000, idleSpeed: 200, imageCrop: false, imageMargin: 0, imagePan: false, imagePanSmoothness: 12, imagePosition: '50%', imageTimeout: undef, // 1.2.5 initialTransition: undef, // 1.2.4, replaces transitionInitial keepSource: false, layerFollow: true, // 1.2.5 lightbox: false, // 1.2.3 lightboxFadeSpeed: 200, lightboxTransitionSpeed: 200, linkSourceImages: true, maxScaleRatio: undef, minScaleRatio: undef, overlayOpacity: 0.85, overlayBackground: '#0b0b0b', pauseOnInteraction: true, popupLinks: false, preload: 2, queue: true, responsive: true, show: 0, showInfo: true, showCounter: true, showImagenav: true, swipe: true, // 1.2.4 thumbCrop: true, thumbEventType: 'click', thumbFit: true, // legacy, deprecate at 1.3 thumbMargin: 0, thumbQuality: 'auto', thumbDisplayOrder: true, // 1.2.8 thumbnails: true, touchTransition: undef, // 1.2.6 transition: 'fade', transitionInitial: undef, // legacy, deprecate in 1.3. Use initialTransition instead. transitionSpeed: 400, trueFullscreen: true, // 1.2.7 useCanvas: false, // 1.2.4 vimeo: { title: 0, byline: 0, portrait: 0, color: 'aaaaaa' }, wait: 5000, // 1.2.7 width: 'auto', youtube: { modestbranding: 1, autohide: 1, color: 'white', hd: 1, rel: 0, showinfo: 0 } }; // legacy support for transitionInitial this._options.initialTransition = this._options.initialTransition || this._options.transitionInitial; // turn off debug if ( options && options.debug === false ) { DEBUG = false; } // set timeout if ( options && typeof options.imageTimeout === 'number' ) { TIMEOUT = options.imageTimeout; } // set dummy if ( options && typeof options.dummy === 'string' ) { DUMMY = options.dummy; } // hide all content $( this._target ).children().hide(); // now we just have to wait for the theme... if ( typeof Galleria.theme === 'object' ) { this._init(); } else { // push the instance into the pool and run it when the theme is ready _pool.push( this ); } return this; }, // this method should only be called once per instance // for manipulation of data, use the .load method _init: function() { var self = this, options = this._options; if ( this._initialized ) { Galleria.raise( 'Init failed: Gallery instance already initialized.' ); return this; } this._initialized = true; if ( !Galleria.theme ) { Galleria.raise( 'Init failed: No theme found.', true ); return this; } // merge the theme & caller options $.extend( true, options, Galleria.theme.defaults, this._original.options, Galleria.configure.options ); // check for canvas support (function( can ) { if ( !( 'getContext' in can ) ) { can = null; return; } _canvas = _canvas || { elem: can, context: can.getContext( '2d' ), cache: {}, length: 0 }; }( doc.createElement( 'canvas' ) ) ); // bind the gallery to run when data is ready this.bind( Galleria.DATA, function() { // Warn for quirks mode if ( Galleria.QUIRK ) { Galleria.raise('Your page is in Quirks mode, Galleria may not render correctly. Please validate your HTML.'); } // save the new data this._original.data = this._data; // lets show the counter here this.get('total').innerHTML = this.getDataLength(); // cache the container var $container = this.$( 'container' ); // set ratio if height is < 2 if ( self._options.height < 2 ) { self._ratio = self._options.height; } // the gallery is ready, let's just wait for the css var num = { width: 0, height: 0 }; var testHeight = function() { return self.$( 'stage' ).height(); }; // check container and thumbnail height Utils.wait({ until: function() { // keep trying to get the value num = self._getWH(); $container.width( num.width ).height( num.height ); return testHeight() && num.width && num.height > 50; }, success: function() { self._width = num.width; self._height = num.height; self._ratio = self._ratio || num.height/num.width; // for some strange reason, webkit needs a single setTimeout to play ball if ( Galleria.WEBKIT ) { window.setTimeout( function() { self._run(); }, 1); } else { self._run(); } }, error: function() { // Height was probably not set, raise hard errors if ( testHeight() ) { Galleria.raise('Could not extract sufficient width/height of the gallery container. Traced measures: width:' + num.width + 'px, height: ' + num.height + 'px.', true); } else { Galleria.raise('Could not extract a stage height from the CSS. Traced height: ' + testHeight() + 'px.', true); } }, timeout: typeof this._options.wait == 'number' ? this._options.wait : false }); }); // build the gallery frame this.append({ 'info-text' : ['info-title', 'info-description'], 'info' : ['info-text'], 'image-nav' : ['image-nav-right', 'image-nav-left'], 'stage' : ['images', 'loader', 'counter', 'image-nav'], 'thumbnails-list' : ['thumbnails'], 'thumbnails-container' : ['thumb-nav-left', 'thumbnails-list', 'thumb-nav-right'], 'container' : ['stage', 'thumbnails-container', 'info', 'tooltip'] }); Utils.hide( this.$( 'counter' ).append( this.get( 'current' ), doc.createTextNode(' / '), this.get( 'total' ) ) ); this.setCounter('&#8211;'); Utils.hide( self.get('tooltip') ); // add a notouch class on the container to prevent unwanted :hovers on touch devices this.$( 'container' ).addClass( Galleria.TOUCH ? 'touch' : 'notouch' ); // add images to the controls $.each( new Array(2), function( i ) { // create a new Picture instance var image = new Galleria.Picture(); // apply some styles, create & prepend overlay $( image.container ).css({ position: 'absolute', top: 0, left: 0 }).prepend( self._layers[i] = $( Utils.create('galleria-layer') ).css({ position: 'absolute', top:0, left:0, right:0, bottom:0, zIndex:2 })[0] ); // append the image self.$( 'images' ).append( image.container ); // reload the controls self._controls[i] = image; }); // some forced generic styling this.$( 'images' ).css({ position: 'relative', top: 0, left: 0, width: '100%', height: '100%' }); this.$( 'thumbnails, thumbnails-list' ).css({ overflow: 'hidden', position: 'relative' }); // bind image navigation arrows this.$( 'image-nav-right, image-nav-left' ).bind( 'click', function(e) { // tune the clicknext option if ( options.clicknext ) { e.stopPropagation(); } // pause if options is set if ( options.pauseOnInteraction ) { self.pause(); } // navigate var fn = /right/.test( this.className ) ? 'next' : 'prev'; self[ fn ](); }); // hide controls if chosen to $.each( ['info','counter','image-nav'], function( i, el ) { if ( options[ 'show' + el.substr(0,1).toUpperCase() + el.substr(1).replace(/-/,'') ] === false ) { Utils.moveOut( self.get( el.toLowerCase() ) ); } }); // load up target content this.load(); // now it's usually safe to remove the content // IE will never stop loading if we remove it, so let's keep it hidden for IE (it's usually fast enough anyway) if ( !options.keepSource && !IE ) { this._target.innerHTML = ''; } // re-append the errors, if they happened before clearing if ( this.get( 'errors' ) ) { this.appendChild( 'target', 'errors' ); } // append the gallery frame this.appendChild( 'target', 'container' ); // parse the carousel on each thumb load if ( options.carousel ) { var count = 0, show = options.show; this.bind( Galleria.THUMBNAIL, function() { this.updateCarousel(); if ( ++count == this.getDataLength() && typeof show == 'number' && show > 0 ) { this._carousel.follow( show ); } }); } // bind window resize for responsiveness if ( options.responsive ) { $win.bind( 'resize', function() { if ( !self.isFullscreen() ) { self.resize(); } }); } // bind swipe gesture if ( options.swipe ) { (function( images ) { var swipeStart = [0,0], swipeStop = [0,0], limitX = 30, limitY = 100, multi = false, tid = 0, data, ev = { start: 'touchstart', move: 'touchmove', stop: 'touchend' }, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }, moveHandler = function( e ) { if ( e.originalEvent.touches && e.originalEvent.touches.length > 1 ) { return; } data = getData( e ); swipeStop = [ data.pageX, data.pageY ]; if ( !swipeStart[0] ) { swipeStart = swipeStop; } if ( Math.abs( swipeStart[0] - swipeStop[0] ) > 10 ) { e.preventDefault(); } }, upHandler = function( e ) { images.unbind( ev.move, moveHandler ); // if multitouch (possibly zooming), abort if ( ( e.originalEvent.touches && e.originalEvent.touches.length ) || multi ) { multi = !multi; return; } if ( Utils.timestamp() - tid < 1000 && Math.abs( swipeStart[0] - swipeStop[0] ) > limitX && Math.abs( swipeStart[1] - swipeStop[1] ) < limitY ) { e.preventDefault(); self[ swipeStart[0] > swipeStop[0] ? 'next' : 'prev' ](); } swipeStart = swipeStop = [0,0]; }; images.bind(ev.start, function(e) { if ( e.originalEvent.touches && e.originalEvent.touches.length > 1 ) { return; } data = getData(e); tid = Utils.timestamp(); swipeStart = swipeStop = [ data.pageX, data.pageY ]; images.bind(ev.move, moveHandler ).one(ev.stop, upHandler); }); }( self.$( 'images' ) )); // double-tap/click fullscreen toggle if ( options.fullscreenDoubleTap ) { this.$( 'stage' ).bind( 'touchstart', (function() { var last, cx, cy, lx, ly, now, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }; return function(e) { now = Galleria.utils.timestamp(); cx = getData(e).pageX; cy = getData(e).pageY; if ( ( now - last < 500 ) && ( cx - lx < 20) && ( cy - ly < 20) ) { self.toggleFullscreen(); e.preventDefault(); self.$( 'stage' ).unbind( 'touchend', arguments.callee ); return; } last = now; lx = cx; ly = cy; }; }())); } } // optimize touch for container Utils.optimizeTouch( this.get( 'container' ) ); // bind the ons $.each( Galleria.on.binds, function(i, bind) { // check if already bound if ( $.inArray( bind.hash, self._binds ) == -1 ) { self.bind( bind.type, bind.callback ); } }); return this; }, addTimer : function() { this._timer.add.apply( this._timer, Utils.array( arguments ) ); return this; }, clearTimer : function() { this._timer.clear.apply( this._timer, Utils.array( arguments ) ); return this; }, // parse width & height from CSS or options _getWH : function() { var $container = this.$( 'container' ), $target = this.$( 'target' ), self = this, num = {}, arr; $.each(['width', 'height'], function( i, m ) { // first check if options is set if ( self._options[ m ] && typeof self._options[ m ] === 'number') { num[ m ] = self._options[ m ]; } else { arr = [ Utils.parseValue( $container.css( m ) ), // the container css height Utils.parseValue( $target.css( m ) ), // the target css height $container[ m ](), // the container jQuery method $target[ m ]() // the target jQuery method ]; // if first time, include the min-width & min-height if ( !self[ '_'+m ] ) { arr.splice(arr.length, Utils.parseValue( $container.css( 'min-'+m ) ), Utils.parseValue( $target.css( 'min-'+m ) ) ); } // else extract the measures from different sources and grab the highest value num[ m ] = Math.max.apply( Math, arr ); } }); // allow setting a height ratio instead of exact value // useful when doing responsive galleries if ( self._ratio ) { num.height = num.width * self._ratio; } return num; }, // Creates the thumbnails and carousel // can be used at any time, f.ex when the data object is manipulated // push is an optional argument with pushed images _createThumbnails : function( push ) { this.get( 'total' ).innerHTML = this.getDataLength(); var src, thumb, data, special, $container, self = this, o = this._options, i = push ? this._data.length - push.length : 0, chunk = i, thumbchunk = [], loadindex = 0, gif = IE < 8 ? 'http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif' : 'data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D', // get previously active thumbnail, if exists active = (function() { var a = self.$('thumbnails').find('.active'); if ( !a.length ) { return false; } return a.find('img').attr('src'); }()), // cache the thumbnail option optval = typeof o.thumbnails === 'string' ? o.thumbnails.toLowerCase() : null, // move some data into the instance // for some reason, jQuery cant handle css(property) when zooming in FF, breaking the gallery // so we resort to getComputedStyle for browsers who support it getStyle = function( prop ) { return doc.defaultView && doc.defaultView.getComputedStyle ? doc.defaultView.getComputedStyle( thumb.container, null )[ prop ] : $container.css( prop ); }, fake = function(image, index, container) { return function() { $( container ).append( image ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: image, index: index, galleriaData: self.getData( index ) }); }; }, onThumbEvent = function( e ) { // pause if option is set if ( o.pauseOnInteraction ) { self.pause(); } // extract the index from the data var index = $( e.currentTarget ).data( 'index' ); if ( self.getIndex() !== index ) { self.show( index ); } e.preventDefault(); }, thumbComplete = function( thumb, callback ) { $( thumb.container ).css( 'visibility', 'visible' ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: thumb.image, index: thumb.data.order, galleriaData: self.getData( thumb.data.order ) }); if ( typeof callback == 'function' ) { callback.call( self, thumb ); } }, onThumbLoad = function( thumb, callback ) { // scale when ready thumb.scale({ width: thumb.data.width, height: thumb.data.height, crop: o.thumbCrop, margin: o.thumbMargin, canvas: o.useCanvas, complete: function( thumb ) { // shrink thumbnails to fit var top = ['left', 'top'], arr = ['Width', 'Height'], m, css, data = self.getData( thumb.index ), special = data.thumb.split(':'); // calculate shrinked positions $.each(arr, function( i, measure ) { m = measure.toLowerCase(); if ( (o.thumbCrop !== true || o.thumbCrop === m ) && o.thumbFit ) { css = {}; css[ m ] = thumb[ m ]; $( thumb.container ).css( css ); css = {}; css[ top[ i ] ] = 0; $( thumb.image ).css( css ); } // cache outer measures thumb[ 'outer' + measure ] = $( thumb.container )[ 'outer' + measure ]( true ); }); // set high quality if downscale is moderate Utils.toggleQuality( thumb.image, o.thumbQuality === true || ( o.thumbQuality === 'auto' && thumb.original.width < thumb.width * 3 ) ); // get "special" thumbs from provider if( data.iframe && special.length == 2 && special[0] in _video ) { _video[ special[0] ].getThumb( special[1], (function(img) { return function(src) { img.src = src; thumbComplete( thumb, callback ); }; }( thumb.image ) )); } else if ( o.thumbDisplayOrder && !thumb.lazy ) { $.each( thumbchunk, function( i, th ) { if ( i === loadindex && th.ready && !th.displayed ) { loadindex++; th.displayed = true; thumbComplete( th, callback ); return; } }); } else { thumbComplete( thumb, callback ); } } }); }; if ( !push ) { this._thumbnails = []; this.$( 'thumbnails' ).empty(); } // loop through data and create thumbnails for( ; this._data[ i ]; i++ ) { data = this._data[ i ]; // get source from thumb or image src = data.thumb || data.image; if ( ( o.thumbnails === true || optval == 'lazy' ) && ( data.thumb || data.image ) ) { // add a new Picture instance thumb = new Galleria.Picture(i); // save the index thumb.index = i; // flag displayed thumb.displayed = false; // flag lazy thumb.lazy = false; // flag video thumb.video = false; // append the thumbnail this.$( 'thumbnails' ).append( thumb.container ); // cache the container $container = $( thumb.container ); // hide it $container.css( 'visibility', 'hidden' ); thumb.data = { width : Utils.parseValue( getStyle( 'width' ) ), height : Utils.parseValue( getStyle( 'height' ) ), order : i, src : src }; // grab & reset size for smoother thumbnail loads if ( o.thumbFit && o.thumbCrop !== true ) { $container.css( { width: 'auto', height: 'auto' } ); } else { $container.css( { width: thumb.data.width, height: thumb.data.height } ); } // load the thumbnail special = src.split(':'); if ( special.length == 2 && special[0] in _video ) { thumb.video = true; thumb.ready = true; thumb.load( gif, { height: thumb.data.height, width: thumb.data.height*1.25 }, onThumbLoad); } else if ( optval == 'lazy' ) { $container.addClass( 'lazy' ); thumb.lazy = true; thumb.load( gif, { height: thumb.data.height, width: thumb.data.width }); } else { thumb.load( src, onThumbLoad ); } // preload all images here if ( o.preload === 'all' ) { thumb.preload( data.image ); } // create empty spans if thumbnails is set to 'empty' } else if ( data.iframe || optval === 'empty' || optval === 'numbers' ) { thumb = { container: Utils.create( 'galleria-image' ), image: Utils.create( 'img', 'span' ), ready: true }; // create numbered thumbnails if ( optval === 'numbers' ) { $( thumb.image ).text( i + 1 ); } if ( data.iframe ) { $( thumb.image ).addClass( 'iframe' ); } this.$( 'thumbnails' ).append( thumb.container ); // we need to "fake" a loading delay before we append and trigger // 50+ should be enough window.setTimeout( ( fake )( thumb.image, i, thumb.container ), 50 + ( i*20 ) ); // create null object to silent errors } else { thumb = { container: null, image: null }; } // add events for thumbnails // you can control the event type using thumb_event_type // we'll add the same event to the source if it's kept $( thumb.container ).add( o.keepSource && o.linkSourceImages ? data.original : null ) .data('index', i).bind( o.thumbEventType, onThumbEvent ) .data('thumbload', onThumbLoad); if (active === src) { $( thumb.container ).addClass( 'active' ); } this._thumbnails.push( thumb ); } thumbchunk = this._thumbnails.slice( chunk ); return this; }, /** Lazy-loads thumbnails. You can call this method to load lazy thumbnails at run time @param {Array|Number} index Index or array of indexes of thumbnails to be loaded @param {Function} complete Callback that is called when all lazy thumbnails have been loaded @returns Instance */ lazyLoad: function( index, complete ) { var arr = index.constructor == Array ? index : [ index ], self = this, thumbnails = this.$( 'thumbnails' ).children().filter(function() { return $(this).data('lazy-src'); }), loaded = 0; $.each( arr, function(i, ind) { if ( ind > self._thumbnails.length - 1 ) { return; } var thumb = self._thumbnails[ ind ], data = thumb.data, special = data.src.split(':'), callback = function() { if ( ++loaded == arr.length && typeof complete == 'function' ) { complete.call( self ); } }, thumbload = $( thumb.container ).data( 'thumbload' ); if ( thumb.video ) { thumbload.call( self, thumb, callback ); } else { thumb.load( data.src , function( thumb ) { thumbload.call( self, thumb, callback ); }); } }); return this; }, /** Lazy-loads thumbnails in chunks. This method automatcally chops up the loading process of many thumbnails into chunks @param {Number} size Size of each chunk to be loaded @param {Number} [delay] Delay between each loads @returns Instance */ lazyLoadChunks: function( size, delay ) { var len = this.getDataLength(), i = 0, n = 0, arr = [], temp = [], self = this; delay = delay || 0; for( ; i<len; i++ ) { temp.push(i); if ( ++n == size || i == len-1 ) { arr.push( temp ); n = 0; temp = []; } } var init = function( wait ) { var a = arr.shift(); if ( a ) { window.setTimeout(function() { self.lazyLoad(a, function() { init( true ); }); }, ( delay && wait ) ? delay : 0 ); } }; init( false ); return this; }, // the internal _run method should be called after loading data into galleria // makes sure the gallery has proper measurements before postrun & ready _run : function() { var self = this; self._createThumbnails(); // make sure we have a stageHeight && stageWidth Utils.wait({ timeout: 10000, until: function() { // Opera crap if ( Galleria.OPERA ) { self.$( 'stage' ).css( 'display', 'inline-block' ); } self._stageWidth = self.$( 'stage' ).width(); self._stageHeight = self.$( 'stage' ).height(); return( self._stageWidth && self._stageHeight > 50 ); // what is an acceptable height? }, success: function() { // save the instance _galleries.push( self ); // postrun some stuff after the gallery is ready // show counter Utils.show( self.get('counter') ); // bind carousel nav if ( self._options.carousel ) { self._carousel.bindControls(); } // start autoplay if ( self._options.autoplay ) { self.pause(); if ( typeof self._options.autoplay === 'number' ) { self._playtime = self._options.autoplay; } self._playing = true; } // if second load, just do the show and return if ( self._firstrun ) { if ( self._options.autoplay ) { self.trigger( Galleria.PLAY ); } if ( typeof self._options.show === 'number' ) { self.show( self._options.show ); } return; } self._firstrun = true; // initialize the History plugin if ( Galleria.History ) { // bind the show method Galleria.History.change(function( value ) { // if ID is NaN, the user pressed back from the first image // return to previous address if ( isNaN( value ) ) { window.history.go(-1); // else show the image } else { self.show( value, undef, true ); } }); } self.trigger( Galleria.READY ); // call the theme init method Galleria.theme.init.call( self, self._options ); // Trigger Galleria.ready $.each( Galleria.ready.callbacks, function(i ,fn) { if ( typeof fn == 'function' ) { fn.call( self, self._options ); } }); // call the extend option self._options.extend.call( self, self._options ); // show the initial image // first test for permalinks in history if ( /^[0-9]{1,4}$/.test( HASH ) && Galleria.History ) { self.show( HASH, undef, true ); } else if( self._data[ self._options.show ] ) { self.show( self._options.show ); } // play trigger if ( self._options.autoplay ) { self.trigger( Galleria.PLAY ); } }, error: function() { Galleria.raise('Stage width or height is too small to show the gallery. Traced measures: width:' + self._stageWidth + 'px, height: ' + self._stageHeight + 'px.', true); } }); }, /** Loads data into the gallery. You can call this method on an existing gallery to reload the gallery with new data. @param {Array|string} [source] Optional JSON array of data or selector of where to find data in the document. Defaults to the Galleria target or dataSource option. @param {string} [selector] Optional element selector of what elements to parse. Defaults to 'img'. @param {Function} [config] Optional function to modify the data extraction proceedure from the selector. See the dataConfig option for more information. @returns Instance */ load : function( source, selector, config ) { var self = this, o = this._options; // empty the data array this._data = []; // empty the thumbnails this._thumbnails = []; this.$('thumbnails').empty(); // shorten the arguments if ( typeof selector === 'function' ) { config = selector; selector = null; } // use the source set by target source = source || o.dataSource; // use selector set by option selector = selector || o.dataSelector; // use the dataConfig set by option config = config || o.dataConfig; // if source is a true object, make it into an array if( /^function Object/.test( source.constructor ) ) { source = [source]; } // check if the data is an array already if ( source.constructor === Array ) { if ( this.validate( source ) ) { this._data = source; } else { Galleria.raise( 'Load failed: JSON Array not valid.' ); } } else { // add .video and .iframe to the selector (1.2.7) selector += ',.video,.iframe'; // loop through images and set data $( source ).find( selector ).each( function( i, elem ) { elem = $( elem ); var data = {}, parent = elem.parent(), href = parent.attr( 'href' ), rel = parent.attr( 'rel' ); if( href && ( elem[0].nodeName == 'IMG' || elem.hasClass('video') ) && _videoTest( href ) ) { data.video = href; } else if( href && elem.hasClass('iframe') ) { data.iframe = href; } else { data.image = data.big = href; } if ( rel ) { data.big = rel; } // alternative extraction from HTML5 data attribute, added in 1.2.7 $.each( 'big title description link layer'.split(' '), function( i, val ) { if ( elem.data(val) ) { data[ val ] = elem.data(val); } }); // mix default extractions with the hrefs and config // and push it into the data array self._data.push( $.extend({ title: elem.attr('title') || '', thumb: elem.attr('src'), image: elem.attr('src'), big: elem.attr('src'), description: elem.attr('alt') || '', link: elem.attr('longdesc'), original: elem.get(0) // saved as a reference }, data, config( elem ) ) ); }); } if ( typeof o.dataSort == 'function' ) { protoArray.sort.call( this._data, o.dataSort ); } else if ( o.dataSort == 'random' ) { this._data.sort( function() { return Math.round(Math.random())-0.5; }); } // trigger the DATA event and return if ( this.getDataLength() ) { this._parseData().trigger( Galleria.DATA ); } return this; }, // make sure the data works properly _parseData : function() { var self = this, current; $.each( this._data, function( i, data ) { current = self._data[ i ]; // copy image as thumb if no thumb exists if ( 'thumb' in data === false ) { current.thumb = data.image; } // copy image as big image if no biggie exists if ( !'big' in data ) { current.big = data.image; } // parse video if ( 'video' in data ) { var result = _videoTest( data.video ); if ( result ) { current.iframe = _video[ result.provider ].embed( result.id ) + (function() { // add options if ( typeof self._options[ result.provider ] == 'object' ) { var str = '?', arr = []; $.each( self._options[ result.provider ], function( key, val ) { arr.push( key + '=' + val ); }); // small youtube specifics, perhaps move to _video later if ( result.provider == 'youtube' ) { arr = ['wmode=opaque'].concat(arr); } return str + arr.join('&'); } return ''; }()); delete current.video; if( !('thumb' in current) || !current.thumb ) { current.thumb = result.provider+':'+result.id; } } } }); return this; }, /** Destroy the Galleria instance and recover the original content @example this.destroy(); @returns Instance */ destroy : function() { this.get('target').innerHTML = this._original.html; this.clearTimer(); return this; }, /** Adds and/or removes images from the gallery Works just like Array.splice https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice @example this.splice( 2, 4 ); // removes 4 images after the second image @returns Instance */ splice : function() { var self = this, args = Utils.array( arguments ); window.setTimeout(function() { protoArray.splice.apply( self._data, args ); self._parseData()._createThumbnails(); },2); return self; }, /** Append images to the gallery Works just like Array.push https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push @example this.push({ image: 'image1.jpg' }); // appends the image to the gallery @returns Instance */ push : function() { var self = this, args = Utils.array( arguments ); if ( args.length == 1 && args[0].constructor == Array ) { args = args[0]; } window.setTimeout(function() { protoArray.push.apply( self._data, args ); self._parseData()._createThumbnails( args ); },2); return self; }, _getActive: function() { return this._controls.getActive(); }, validate : function( data ) { // todo: validate a custom data array return true; }, /** Bind any event to Galleria @param {string} type The Event type to listen for @param {Function} fn The function to execute when the event is triggered @example this.bind( 'image', function() { Galleria.log('image shown') }); @returns Instance */ bind : function(type, fn) { // allow 'image' instead of Galleria.IMAGE type = _patchEvent( type ); this.$( 'container' ).bind( type, this.proxy(fn) ); return this; }, /** Unbind any event to Galleria @param {string} type The Event type to forget @returns Instance */ unbind : function(type) { type = _patchEvent( type ); this.$( 'container' ).unbind( type ); return this; }, /** Manually trigger a Galleria event @param {string} type The Event to trigger @returns Instance */ trigger : function( type ) { type = typeof type === 'object' ? $.extend( type, { scope: this } ) : { type: _patchEvent( type ), scope: this }; this.$( 'container' ).trigger( type ); return this; }, /** Assign an "idle state" to any element. The idle state will be applied after a certain amount of idle time Useful to hide f.ex navigation when the gallery is inactive @param {HTMLElement|string} elem The Dom node or selector to apply the idle state to @param {Object} styles the CSS styles to apply when in idle mode @param {Object} [from] the CSS styles to apply when in normal @param {Boolean} [hide] set to true if you want to hide it first @example addIdleState( this.get('image-nav'), { opacity: 0 }); @example addIdleState( '.galleria-image-nav', { top: -200 }, true); @returns Instance */ addIdleState: function( elem, styles, from, hide ) { this._idle.add.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Removes any idle state previously set using addIdleState() @param {HTMLElement|string} elem The Dom node or selector to remove the idle state from. @returns Instance */ removeIdleState: function( elem ) { this._idle.remove.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Force Galleria to enter idle mode. @returns Instance */ enterIdleMode: function() { this._idle.hide(); return this; }, /** Force Galleria to exit idle mode. @returns Instance */ exitIdleMode: function() { this._idle.showAll(); return this; }, /** Enter FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ enterFullscreen: function( callback ) { this._fullscreen.enter.apply( this, Utils.array( arguments ) ); return this; }, /** Exits FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ exitFullscreen: function( callback ) { this._fullscreen.exit.apply( this, Utils.array( arguments ) ); return this; }, /** Toggle FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied or removed. @returns Instance */ toggleFullscreen: function( callback ) { this._fullscreen[ this.isFullscreen() ? 'exit' : 'enter'].apply( this, Utils.array( arguments ) ); return this; }, /** Adds a tooltip to any element. You can also call this method with an object as argument with elemID:value pairs to apply tooltips to (see examples) @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @example this.bindTooltip( this.get('thumbnails'), 'My thumbnails'); @example this.bindTooltip( this.get('thumbnails'), function() { return 'My thumbs' }); @example this.bindTooltip( { image_nav: 'Navigation' }); @returns Instance */ bindTooltip: function( elem, value ) { this._tooltip.bind.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Note: this method is deprecated. Use refreshTooltip() instead. Redefine a tooltip. Use this if you want to re-apply a tooltip value to an already bound tooltip element. @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @returns Instance */ defineTooltip: function( elem, value ) { this._tooltip.define.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Refresh a tooltip value. Use this if you want to change the tooltip value at runtime, f.ex if you have a play/pause toggle. @param {HTMLElement} elem The DOM Node that has a tooltip that should be refreshed @returns Instance */ refreshTooltip: function( elem ) { this._tooltip.show.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Open a pre-designed lightbox with the currently active image. You can control some visuals using gallery options. @returns Instance */ openLightbox: function() { this._lightbox.show.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Close the lightbox. @returns Instance */ closeLightbox: function() { this._lightbox.hide.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Get the currently active image element. @returns {HTMLElement} The image element */ getActiveImage: function() { return this._getActive().image || undef; }, /** Get the currently active thumbnail element. @returns {HTMLElement} The thumbnail element */ getActiveThumb: function() { return this._thumbnails[ this._active ].image || undef; }, /** Get the mouse position relative to the gallery container @param e The mouse event @example var gallery = this; $(document).mousemove(function(e) { console.log( gallery.getMousePosition(e).x ); }); @returns {Object} Object with x & y of the relative mouse postion */ getMousePosition : function(e) { return { x: e.pageX - this.$( 'container' ).offset().left, y: e.pageY - this.$( 'container' ).offset().top }; }, /** Adds a panning effect to the image @param [img] The optional image element. If not specified it takes the currently active image @returns Instance */ addPan : function( img ) { if ( this._options.imageCrop === false ) { return; } img = $( img || this.getActiveImage() ); // define some variables and methods var self = this, x = img.width() / 2, y = img.height() / 2, destX = parseInt( img.css( 'left' ), 10 ), destY = parseInt( img.css( 'top' ), 10 ), curX = destX || 0, curY = destY || 0, distX = 0, distY = 0, active = false, ts = Utils.timestamp(), cache = 0, move = 0, // positions the image position = function( dist, cur, pos ) { if ( dist > 0 ) { move = Math.round( Math.max( dist * -1, Math.min( 0, cur ) ) ); if ( cache !== move ) { cache = move; if ( IE === 8 ) { // scroll is faster for IE img.parent()[ 'scroll' + pos ]( move * -1 ); } else { var css = {}; css[ pos.toLowerCase() ] = move; img.css(css); } } } }, // calculates mouse position after 50ms calculate = function(e) { if (Utils.timestamp() - ts < 50) { return; } active = true; x = self.getMousePosition(e).x; y = self.getMousePosition(e).y; }, // the main loop to check loop = function(e) { if (!active) { return; } distX = img.width() - self._stageWidth; distY = img.height() - self._stageHeight; destX = x / self._stageWidth * distX * -1; destY = y / self._stageHeight * distY * -1; curX += ( destX - curX ) / self._options.imagePanSmoothness; curY += ( destY - curY ) / self._options.imagePanSmoothness; position( distY, curY, 'Top' ); position( distX, curX, 'Left' ); }; // we need to use scroll in IE8 to speed things up if ( IE === 8 ) { img.parent().scrollTop( curY * -1 ).scrollLeft( curX * -1 ); img.css({ top: 0, left: 0 }); } // unbind and bind event this.$( 'stage' ).unbind( 'mousemove', calculate ).bind( 'mousemove', calculate ); // loop the loop this.addTimer( 'pan' + self._id, loop, 50, true); return this; }, /** Brings the scope into any callback @param fn The callback to bring the scope into @param [scope] Optional scope to bring @example $('#fullscreen').click( this.proxy(function() { this.enterFullscreen(); }) ) @returns {Function} Return the callback with the gallery scope */ proxy : function( fn, scope ) { if ( typeof fn !== 'function' ) { return F; } scope = scope || this; return function() { return fn.apply( scope, Utils.array( arguments ) ); }; }, /** Removes the panning effect set by addPan() @returns Instance */ removePan: function() { // todo: doublecheck IE8 this.$( 'stage' ).unbind( 'mousemove' ); this.clearTimer( 'pan' + this._id ); return this; }, /** Adds an element to the Galleria DOM array. When you add an element here, you can access it using element ID in many API calls @param {string} id The element ID you wish to use. You can add many elements by adding more arguments. @example addElement('mybutton'); @example addElement('mybutton','mylink'); @returns Instance */ addElement : function( id ) { var dom = this._dom; $.each( Utils.array(arguments), function( i, blueprint ) { dom[ blueprint ] = Utils.create( 'galleria-' + blueprint ); }); return this; }, /** Attach keyboard events to Galleria @param {Object} map The map object of events. Possible keys are 'UP', 'DOWN', 'LEFT', 'RIGHT', 'RETURN', 'ESCAPE', 'BACKSPACE', and 'SPACE'. @example this.attachKeyboard({ right: this.next, left: this.prev, up: function() { console.log( 'up key pressed' ) } }); @returns Instance */ attachKeyboard : function( map ) { this._keyboard.attach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Detach all keyboard events to Galleria @returns Instance */ detachKeyboard : function() { this._keyboard.detach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Fast helper for appending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be appended @param {string} childID the element ID that should be appended @example this.addElement('myElement'); this.appendChild( 'info', 'myElement' ); @returns Instance */ appendChild : function( parentID, childID ) { this.$( parentID ).append( this.get( childID ) || childID ); return this; }, /** Fast helper for prepending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be prepended @param {string} childID the element ID that should be prepended @example this.addElement('myElement'); this.prependChild( 'info', 'myElement' ); @returns Instance */ prependChild : function( parentID, childID ) { this.$( parentID ).prepend( this.get( childID ) || childID ); return this; }, /** Remove an element by blueprint @param {string} elemID The element to be removed. You can remove multiple elements by adding arguments. @returns Instance */ remove : function( elemID ) { this.$( Utils.array( arguments ).join(',') ).remove(); return this; }, // a fast helper for building dom structures // leave this out of the API for now append : function( data ) { var i, j; for( i in data ) { if ( data.hasOwnProperty( i ) ) { if ( data[i].constructor === Array ) { for( j = 0; data[i][j]; j++ ) { this.appendChild( i, data[i][j] ); } } else { this.appendChild( i, data[i] ); } } } return this; }, // an internal helper for scaling according to options _scaleImage : function( image, options ) { image = image || this._controls.getActive(); // janpub (JH) fix: // image might be unselected yet // e.g. when external logics rescales the gallery on window resize events if( !image ) { return; } var self = this, complete, scaleLayer = function( img ) { $( img.container ).children(':first').css({ top: Math.max(0, Utils.parseValue( img.image.style.top )), left: Math.max(0, Utils.parseValue( img.image.style.left )), width: Utils.parseValue( img.image.width ), height: Utils.parseValue( img.image.height ) }); }; options = $.extend({ width: this._stageWidth, height: this._stageHeight, crop: this._options.imageCrop, max: this._options.maxScaleRatio, min: this._options.minScaleRatio, margin: this._options.imageMargin, position: this._options.imagePosition }, options ); if ( this._options.layerFollow && this._options.imageCrop !== true ) { if ( typeof options.complete == 'function' ) { complete = options.complete; options.complete = function() { complete.call( image, image ); scaleLayer( image ); }; } else { options.complete = scaleLayer; } } else { $( image.container ).children(':first').css({ top: 0, left: 0 }); } image.scale( options ); return this; }, /** Updates the carousel, useful if you resize the gallery and want to re-check if the carousel nav is needed. @returns Instance */ updateCarousel : function() { this._carousel.update(); return this; }, /** Resize the entire gallery container @param {Object} [measures] Optional object with width/height specified @param {Function} [complete] The callback to be called when the scaling is complete @returns Instance */ resize : function( measures, complete ) { if ( typeof measures == 'function' ) { complete = measures; measures = undef; } measures = $.extend( { width:0, height:0 }, measures ); var self = this, $container = this.$( 'container' ); $.each( measures, function( m, val ) { if ( !val ) { $container[ m ]( 'auto' ); measures[ m ] = self._getWH()[ m ]; } }); $.each( measures, function( m, val ) { $container[ m ]( val ); }); return this.rescale( complete ); }, /** Rescales the gallery @param {number} width The target width @param {number} height The target height @param {Function} complete The callback to be called when the scaling is complete @returns Instance */ rescale : function( width, height, complete ) { var self = this; // allow rescale(fn) if ( typeof width === 'function' ) { complete = width; width = undef; } var scale = function() { // set stagewidth self._stageWidth = width || self.$( 'stage' ).width(); self._stageHeight = height || self.$( 'stage' ).height(); // scale the active image self._scaleImage(); if ( self._options.carousel ) { self.updateCarousel(); } self.trigger( Galleria.RESCALE ); if ( typeof complete === 'function' ) { complete.call( self ); } }; scale.call( self ); return this; }, /** Refreshes the gallery. Useful if you change image options at runtime and want to apply the changes to the active image. @returns Instance */ refreshImage : function() { this._scaleImage(); if ( this._options.imagePan ) { this.addPan(); } return this; }, /** Shows an image by index @param {number|boolean} index The index to show @param {Boolean} rewind A boolean that should be true if you want the transition to go back @returns Instance */ show : function( index, rewind, _history ) { // do nothing if index is false or queue is false and transition is in progress if ( index === false || ( !this._options.queue && this._queue.stalled ) ) { return; } index = Math.max( 0, Math.min( parseInt( index, 10 ), this.getDataLength() - 1 ) ); rewind = typeof rewind !== 'undefined' ? !!rewind : index < this.getIndex(); _history = _history || false; // do the history thing and return if ( !_history && Galleria.History ) { Galleria.History.set( index.toString() ); return; } this._active = index; protoArray.push.call( this._queue, { index : index, rewind : rewind }); if ( !this._queue.stalled ) { this._show(); } return this; }, // the internal _show method does the actual showing _show : function() { // shortcuts var self = this, queue = this._queue[ 0 ], data = this.getData( queue.index ); if ( !data ) { return; } var src = data.iframe || ( this.isFullscreen() && 'big' in data ? data.big : data.image ), // use big image if fullscreen mode active = this._controls.getActive(), next = this._controls.getNext(), cached = next.isCached( src ), thumb = this._thumbnails[ queue.index ], mousetrigger = function() { $( next.image ).trigger( 'mouseup' ); }; // to be fired when loading & transition is complete: var complete = (function( data, next, active, queue, thumb ) { return function() { var win; _transitions.active = false; // remove stalled self._queue.stalled = false; // optimize quality Utils.toggleQuality( next.image, self._options.imageQuality ); // remove old layer self._layers[ self._controls.active ].innerHTML = ''; // swap $( active.container ).css({ zIndex: 0, opacity: 0 }).show(); if( active.isIframe ) { $( active.container ).find( 'iframe' ).remove(); } self.$('container').toggleClass('iframe', !!data.iframe); $( next.container ).css({ zIndex: 1, left: 0, top: 0 }).show(); self._controls.swap(); // add pan according to option if ( self._options.imagePan ) { self.addPan( next.image ); } // make the image link or add lightbox // link takes precedence over lightbox if both are detected if ( data.link || self._options.lightbox || self._options.clicknext ) { $( next.image ).css({ cursor: 'pointer' }).bind( 'mouseup', function() { // clicknext if ( self._options.clicknext && !Galleria.TOUCH ) { if ( self._options.pauseOnInteraction ) { self.pause(); } self.next(); return; } // popup link if ( data.link ) { if ( self._options.popupLinks ) { win = window.open( data.link, '_blank' ); } else { window.location.href = data.link; } return; } if ( self._options.lightbox ) { self.openLightbox(); } }); } // remove the queued image protoArray.shift.call( self._queue ); // if we still have images in the queue, show it if ( self._queue.length ) { self._show(); } // check if we are playing self._playCheck(); // trigger IMAGE event self.trigger({ type: Galleria.IMAGE, index: queue.index, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); }; }( data, next, active, queue, thumb )); // let the carousel follow if ( this._options.carousel && this._options.carouselFollow ) { this._carousel.follow( queue.index ); } // preload images if ( this._options.preload ) { var p, i, n = this.getNext(), ndata; try { for ( i = this._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( this.isFullscreen() && 'big' in ndata ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} } // show the next image, just in case Utils.show( next.container ); next.isIframe = !!data.iframe; // add active classes $( self._thumbnails[ queue.index ].container ) .addClass( 'active' ) .siblings( '.active' ) .removeClass( 'active' ); // trigger the LOADSTART event self.trigger( { type: Galleria.LOADSTART, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); // begin loading the next image next.load( src, function( next ) { // add layer HTML var layer = $( self._layers[ 1-self._controls.active ] ).html( data.layer || '' ).hide(); self._scaleImage( next, { complete: function( next ) { // toggle low quality for IE if ( 'image' in active ) { Utils.toggleQuality( active.image, false ); } Utils.toggleQuality( next.image, false ); // stall the queue self._queue.stalled = true; // remove the image panning, if applied // TODO: rethink if this is necessary self.removePan(); // set the captions and counter self.setInfo( queue.index ); self.setCounter( queue.index ); // show the layer now if ( data.layer ) { layer.show(); // inherit click events set on image if ( data.link || self._options.lightbox || self._options.clicknext ) { layer.css( 'cursor', 'pointer' ).unbind( 'mouseup' ).mouseup( mousetrigger ); } } // trigger the LOADFINISH event self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: self._thumbnails[ queue.index ].image, galleriaData: self.getData( queue.index ) }); var transition = self._options.transition; // can JavaScript loop through objects in order? yes. $.each({ initial: active.image === null, touch: Galleria.TOUCH, fullscreen: self.isFullscreen() }, function( type, arg ) { if ( arg && self._options[ type + 'Transition' ] !== undef ) { transition = self._options[ type + 'Transition' ]; return false; } }); // validate the transition if ( transition in _transitions.effects === false ) { complete(); } else { var params = { prev: active.container, next: next.container, rewind: queue.rewind, speed: self._options.transitionSpeed || 400 }; _transitions.active = true; // call the transition function and send some stuff _transitions.init.call( self, transition, params, complete ); } } }); }); }, /** Gets the next index @param {number} [base] Optional starting point @returns {number} the next index, or the first if you are at the first (looping) */ getNext : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === this.getDataLength() - 1 ? 0 : base + 1; }, /** Gets the previous index @param {number} [base] Optional starting point @returns {number} the previous index, or the last if you are at the first (looping) */ getPrev : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === 0 ? this.getDataLength() - 1 : base - 1; }, /** Shows the next image in line @returns Instance */ next : function() { if ( this.getDataLength() > 1 ) { this.show( this.getNext(), false ); } return this; }, /** Shows the previous image in line @returns Instance */ prev : function() { if ( this.getDataLength() > 1 ) { this.show( this.getPrev(), true ); } return this; }, /** Retrieve a DOM element by element ID @param {string} elemId The delement ID to fetch @returns {HTMLElement} The elements DOM node or null if not found. */ get : function( elemId ) { return elemId in this._dom ? this._dom[ elemId ] : null; }, /** Retrieve a data object @param {number} index The data index to retrieve. If no index specified it will take the currently active image @returns {Object} The data object */ getData : function( index ) { return index in this._data ? this._data[ index ] : this._data[ this._active ]; }, /** Retrieve the number of data items @returns {number} The data length */ getDataLength : function() { return this._data.length; }, /** Retrieve the currently active index @returns {number|boolean} The active index or false if none found */ getIndex : function() { return typeof this._active === 'number' ? this._active : false; }, /** Retrieve the stage height @returns {number} The stage height */ getStageHeight : function() { return this._stageHeight; }, /** Retrieve the stage width @returns {number} The stage width */ getStageWidth : function() { return this._stageWidth; }, /** Retrieve the option @param {string} key The option key to retrieve. If no key specified it will return all options in an object. @returns option or options */ getOptions : function( key ) { return typeof key === 'undefined' ? this._options : this._options[ key ]; }, /** Set options to the instance. You can set options using a key & value argument or a single object argument (see examples) @param {string} key The option key @param {string} value the the options value @example setOptions( 'autoplay', true ) @example setOptions({ autoplay: true }); @returns Instance */ setOptions : function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._options, key ); } else { this._options[ key ] = value; } return this; }, /** Starts playing the slideshow @param {number} delay Sets the slideshow interval in milliseconds. If you set it once, you can just call play() and get the same interval the next time. @returns Instance */ play : function( delay ) { this._playing = true; this._playtime = delay || this._playtime; this._playCheck(); this.trigger( Galleria.PLAY ); return this; }, /** Stops the slideshow if currently playing @returns Instance */ pause : function() { this._playing = false; this.trigger( Galleria.PAUSE ); return this; }, /** Toggle between play and pause events. @param {number} delay Sets the slideshow interval in milliseconds. @returns Instance */ playToggle : function( delay ) { return ( this._playing ) ? this.pause() : this.play( delay ); }, /** Checks if the gallery is currently playing @returns {Boolean} */ isPlaying : function() { return this._playing; }, /** Checks if the gallery is currently in fullscreen mode @returns {Boolean} */ isFullscreen : function() { return this._fullscreen.active; }, _playCheck : function() { var self = this, played = 0, interval = 20, now = Utils.timestamp(), timer_id = 'play' + this._id; if ( this._playing ) { this.clearTimer( timer_id ); var fn = function() { played = Utils.timestamp() - now; if ( played >= self._playtime && self._playing ) { self.clearTimer( timer_id ); self.next(); return; } if ( self._playing ) { // trigger the PROGRESS event self.trigger({ type: Galleria.PROGRESS, percent: Math.ceil( played / self._playtime * 100 ), seconds: Math.floor( played / 1000 ), milliseconds: played }); self.addTimer( timer_id, fn, interval ); } }; self.addTimer( timer_id, fn, interval ); } }, /** Modify the slideshow delay @param {number} delay the number of milliseconds between slides, @returns Instance */ setPlaytime: function( delay ) { this._playtime = delay; return this; }, setIndex: function( val ) { this._active = val; return this; }, /** Manually modify the counter @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index @returns Instance */ setCounter: function( index ) { if ( typeof index === 'number' ) { index++; } else if ( typeof index === 'undefined' ) { index = this.getIndex()+1; } this.get( 'current' ).innerHTML = index; if ( IE ) { // weird IE bug var count = this.$( 'counter' ), opacity = count.css( 'opacity' ); if ( parseInt( opacity, 10 ) === 1) { Utils.removeAlpha( count[0] ); } else { this.$( 'counter' ).css( 'opacity', opacity ); } } return this; }, /** Manually set captions @param {number} [index] Optional data index to fectch and apply as caption, if no index found it assumes the currently active index @returns Instance */ setInfo : function( index ) { var self = this, data = this.getData( index ); $.each( ['title','description'], function( i, type ) { var elem = self.$( 'info-' + type ); if ( !!data[type] ) { elem[ data[ type ].length ? 'show' : 'hide' ]().html( data[ type ] ); } else { elem.empty().hide(); } }); return this; }, /** Checks if the data contains any captions @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index. @returns {boolean} */ hasInfo : function( index ) { var check = 'title description'.split(' '), i; for ( i = 0; check[i]; i++ ) { if ( !!this.getData( index )[ check[i] ] ) { return true; } } return false; }, jQuery : function( str ) { var self = this, ret = []; $.each( str.split(','), function( i, elemId ) { elemId = $.trim( elemId ); if ( self.get( elemId ) ) { ret.push( elemId ); } }); var jQ = $( self.get( ret.shift() ) ); $.each( ret, function( i, elemId ) { jQ = jQ.add( self.get( elemId ) ); }); return jQ; }, /** Converts element IDs into a jQuery collection You can call for multiple IDs separated with commas. @param {string} str One or more element IDs (comma-separated) @returns jQuery @example this.$('info,container').hide(); */ $ : function( str ) { return this.jQuery.apply( this, Utils.array( arguments ) ); } }; // End of Galleria prototype // Add events as static variables $.each( _events, function( i, ev ) { // legacy events var type = /_/.test( ev ) ? ev.replace( /_/g, '' ) : ev; Galleria[ ev.toUpperCase() ] = 'galleria.'+type; } ); $.extend( Galleria, { // Browser helpers IE9: IE === 9, IE8: IE === 8, IE7: IE === 7, IE6: IE === 6, IE: IE, WEBKIT: /webkit/.test( NAV ), CHROME: /chrome/.test( NAV ), SAFARI: /safari/.test( NAV ) && !(/chrome/.test( NAV )), QUIRK: ( IE && doc.compatMode && doc.compatMode === "BackCompat" ), MAC: /mac/.test( navigator.platform.toLowerCase() ), OPERA: !!window.opera, IPHONE: /iphone/.test( NAV ), IPAD: /ipad/.test( NAV ), ANDROID: /android/.test( NAV ), TOUCH: ('ontouchstart' in doc) }); // Galleria static methods /** Adds a theme that you can use for your Gallery @param {Object} theme Object that should contain all your theme settings. <ul> <li>name - name of the theme</li> <li>author - name of the author</li> <li>css - css file name (not path)</li> <li>defaults - default options to apply, including theme-specific options</li> <li>init - the init function</li> </ul> @returns {Object} theme */ Galleria.addTheme = function( theme ) { // make sure we have a name if ( !theme.name ) { Galleria.raise('No theme name specified'); } if ( typeof theme.defaults !== 'object' ) { theme.defaults = {}; } else { theme.defaults = _legacyOptions( theme.defaults ); } var css = false, reg; if ( typeof theme.css === 'string' ) { // look for manually added CSS $('link').each(function( i, link ) { reg = new RegExp( theme.css ); if ( reg.test( link.href ) ) { // we found the css css = true; // the themeload trigger _themeLoad( theme ); return false; } }); // else look for the absolute path and load the CSS dynamic if ( !css ) { $('script').each(function( i, script ) { // look for the theme script reg = new RegExp( 'galleria\\.' + theme.name.toLowerCase() + '\\.' ); if( reg.test( script.src )) { // we have a match css = script.src.replace(/[^\/]*$/, '') + theme.css; window.setTimeout(function() { Utils.loadCSS( css, 'galleria-theme', function() { // the themeload trigger _themeLoad( theme ); }); }, 1); } }); } if ( !css ) { Galleria.raise('No theme CSS loaded'); } } else { // pass _themeLoad( theme ); } return theme; }; /** loadTheme loads a theme js file and attaches a load event to Galleria @param {string} src The relative path to the theme source file @param {Object} [options] Optional options you want to apply @returns Galleria */ Galleria.loadTheme = function( src, options ) { var loaded = false, length = _galleries.length, err = window.setTimeout( function() { Galleria.raise( "Theme at " + src + " could not load, check theme path.", true ); }, 5000 ); // first clear the current theme, if exists Galleria.theme = undef; // load the theme Utils.loadScript( src, function() { window.clearTimeout( err ); // check for existing galleries and reload them with the new theme if ( length ) { // temporary save the new galleries var refreshed = []; // refresh all instances // when adding a new theme to an existing gallery, all options will be resetted but the data will be kept // you can apply new options as a second argument $.each( Galleria.get(), function(i, instance) { // mix the old data and options into the new instance var op = $.extend( instance._original.options, { data_source: instance._data }, options); // remove the old container instance.$('container').remove(); // create a new instance var g = new Galleria(); // move the id g._id = instance._id; // initialize the new instance g.init( instance._original.target, op ); // push the new instance refreshed.push( g ); }); // now overwrite the old holder with the new instances _galleries = refreshed; } }); return Galleria; }; /** Retrieves a Galleria instance. @param {number} [index] Optional index to retrieve. If no index is supplied, the method will return all instances in an array. @returns Instance or Array of instances */ Galleria.get = function( index ) { if ( !!_instances[ index ] ) { return _instances[ index ]; } else if ( typeof index !== 'number' ) { return _instances; } else { Galleria.raise('Gallery index ' + index + ' not found'); } }; /** Configure Galleria options via a static function. The options will be applied to all instances @param {string|object} key The options to apply or a key @param [value] If key is a string, this is the value @returns Galleria */ Galleria.configure = function( key, value ) { var opts = {}; if( typeof key == 'string' && value ) { opts[key] = value; key = opts; } else { $.extend( opts, key ); } Galleria.configure.options = opts; $.each( Galleria.get(), function(i, instance) { instance.setOptions( opts ); }); return Galleria; }; Galleria.configure.options = {}; /** Bind a Galleria event to the gallery @param {string} type A string representing the galleria event @param {function} callback The function that should run when the event is triggered @returns Galleria */ Galleria.on = function( type, callback ) { if ( !type ) { return; } callback = callback || F; // hash the bind var hash = type + callback.toString().replace(/\s/g,'') + Utils.timestamp(); // for existing instances $.each( Galleria.get(), function(i, instance) { instance._binds.push( hash ); instance.bind( type, callback ); }); // for future instances Galleria.on.binds.push({ type: type, callback: callback, hash: hash }); return Galleria; }; Galleria.on.binds = []; /** Run Galleria Alias for $(selector).galleria(options) @param {string} selector A selector of element(s) to intialize galleria to @param {object} options The options to apply @returns Galleria */ Galleria.run = function( selector, options ) { $( selector || '#galleria' ).galleria( options ); return Galleria; }; /** Creates a transition to be used in your gallery @param {string} name The name of the transition that you will use as an option @param {Function} fn The function to be executed in the transition. The function contains two arguments, params and complete. Use the params Object to integrate the transition, and then call complete when you are done. @returns Galleria */ Galleria.addTransition = function( name, fn ) { _transitions.effects[name] = fn; return Galleria; }; /** The Galleria utilites */ Galleria.utils = Utils; /** A helper metod for cross-browser logging. It uses the console log if available otherwise it falls back to alert @example Galleria.log("hello", document.body, [1,2,3]); */ Galleria.log = function() { var args = Utils.array( arguments ); if( 'console' in window && 'log' in window.console ) { try { return window.console.log.apply( window.console, args ); } catch( e ) { $.each( args, function() { window.console.log(this); }); } } else { return window.alert( args.join('<br>') ); } }; /** A ready method for adding callbacks when a gallery is ready Each method is call before the extend option for every instance @param {function} callback The function to call @returns Galleria */ Galleria.ready = function( fn ) { if ( typeof fn != 'function' ) { return Galleria; } $.each( _galleries, function( i, gallery ) { fn.call( gallery, gallery._options ); }); Galleria.ready.callbacks.push( fn ); return Galleria; }; Galleria.ready.callbacks = []; /** Method for raising errors @param {string} msg The message to throw @param {boolean} [fatal] Set this to true to override debug settings and display a fatal error */ Galleria.raise = function( msg, fatal ) { var type = fatal ? 'Fatal error' : 'Error', self = this, css = { color: '#fff', position: 'absolute', top: 0, left: 0, zIndex: 100000 }, echo = function( msg ) { var html = '<div style="padding:4px;margin:0 0 2px;background:#' + ( fatal ? '811' : '222' ) + '";>' + ( fatal ? '<strong>' + type + ': </strong>' : '' ) + msg + '</div>'; $.each( _instances, function() { var cont = this.$( 'errors' ), target = this.$( 'target' ); if ( !cont.length ) { target.css( 'position', 'relative' ); cont = this.addElement( 'errors' ).appendChild( 'target', 'errors' ).$( 'errors' ).css(css); } cont.append( html ); }); if ( !_instances.length ) { $('<div>').css( $.extend( css, { position: 'fixed' } ) ).append( html ).appendTo( DOM().body ); } }; // if debug is on, display errors and throw exception if fatal if ( DEBUG ) { echo( msg ); if ( fatal ) { throw new Error(type + ': ' + msg); } // else just echo a silent generic error if fatal } else if ( fatal ) { if ( _hasError ) { return; } _hasError = true; fatal = false; echo( 'Gallery could not load.' ); } }; // Add the version Galleria.version = VERSION; /** A method for checking what version of Galleria the user has installed and throws a readable error if the user needs to upgrade. Useful when building plugins that requires a certain version to function. @param {number} version The minimum version required @param {string} [msg] Optional message to display. If not specified, Galleria will throw a generic error. @returns Galleria */ Galleria.requires = function( version, msg ) { msg = msg || 'You need to upgrade Galleria to version ' + version + ' to use one or more components.'; if ( Galleria.version < version ) { Galleria.raise(msg, true); } return Galleria; }; /** Adds preload, cache, scale and crop functionality @constructor @requires jQuery @param {number} [id] Optional id to keep track of instances */ Galleria.Picture = function( id ) { // save the id this.id = id || null; // the image should be null until loaded this.image = null; // Create a new container this.container = Utils.create('galleria-image'); // add container styles $( this.container ).css({ overflow: 'hidden', position: 'relative' // for IE Standards mode }); // saves the original measurements this.original = { width: 0, height: 0 }; // flag when the image is ready this.ready = false; // flag for iframe Picture this.isIframe = false; }; Galleria.Picture.prototype = { // the inherited cache object cache: {}, // show the image on stage show: function() { Utils.show( this.image ); }, // hide the image hide: function() { Utils.moveOut( this.image ); }, clear: function() { this.image = null; }, /** Checks if an image is in cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns {boolean} */ isCached: function( src ) { return !!this.cache[src]; }, /** Preloads an image into the cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns Galleria.Picture */ preload: function( src ) { $( new Image() ).load((function(src, cache) { return function() { cache[ src ] = src; }; }( src, this.cache ))).attr( 'src', src ); }, /** Loads an image and call the callback when ready. Will also add the image to cache. @param {string} src The image source path, ex '/path/to/img.jpg' @param {Object} [size] The forced size of the image, defined as an object { width: xx, height:xx } @param {Function} callback The function to be executed when the image is loaded & scaled @returns The image container (jQuery object) */ load: function(src, size, callback) { if ( typeof size == 'function' ) { callback = size; size = null; } if( this.isIframe ) { var id = 'if'+new Date().getTime(); this.image = $('<iframe>', { src: src, frameborder: 0, id: id, allowfullscreen: true, css: { visibility: 'hidden' } })[0]; $( this.container ).find( 'iframe,img' ).remove(); this.container.appendChild( this.image ); $('#'+id).load( (function( self, callback ) { return function() { window.setTimeout(function() { $( self.image ).css( 'visibility', 'visible' ); if( typeof callback == 'function' ) { callback.call( self, self ); } }, 10); }; }( this, callback ))); return this.container; } this.image = new Image(); var i = 0, reload = false, resort = false, // some jquery cache $container = $( this.container ), $image = $( this.image ), onerror = function() { if ( !reload ) { reload = true; // reload the image with a timestamp window.setTimeout((function(image, src) { return function() { image.attr('src', src + '?' + Utils.timestamp() ); }; }( $(this), src )), 50); } else { // apply the dummy image if it exists if ( DUMMY ) { $( this ).attr( 'src', DUMMY ); } else { Galleria.raise('Image not found: ' + src); } } }, // the onload method onload = (function( self, callback, src ) { return function() { var complete = function() { $( this ).unbind( 'load' ); // save the original size self.original = size || { height: this.height, width: this.width }; self.container.appendChild( this ); self.cache[ src ] = src; // will override old cache if (typeof callback == 'function' ) { window.setTimeout(function() { callback.call( self, self ); },1); } }; // Delay the callback to "fix" the Adblock Bug // http://code.google.com/p/adblockforchrome/issues/detail?id=3701 if ( ( !this.width || !this.height ) ) { window.setTimeout( (function( img ) { return function() { if ( img.width && img.height ) { complete.call( img ); } else { // last resort, this should never happen but just in case it does... if ( !resort ) { $(new Image()).load( onload ).attr( 'src', img.src ); resort = true; } else { Galleria.raise('Could not extract width/height from image: ' + img.src + '. Traced measures: width:' + img.width + 'px, height: ' + img.height + 'px.'); } } }; }( this )), 2); } else { complete.call( this ); } }; }( this, callback, src )); // remove any previous images $container.find( 'iframe,img' ).remove(); // append the image $image.css( 'display', 'block'); // hide it for now Utils.hide( this.image ); // remove any max/min scaling $.each('minWidth minHeight maxWidth maxHeight'.split(' '), function(i, prop) { $image.css(prop, (/min/.test(prop) ? '0' : 'none')); }); // begin load and insert in cache when done $image.load( onload ).error( onerror ).attr( 'src', src ); // return the container return this.container; }, /** Scales and crops the image @param {Object} options The method takes an object with a number of options: <ul> <li>width - width of the container</li> <li>height - height of the container</li> <li>min - minimum scale ratio</li> <li>max - maximum scale ratio</li> <li>margin - distance in pixels from the image border to the container</li> <li>complete - a callback that fires when scaling is complete</li> <li>position - positions the image, works like the css background-image property.</li> <li>crop - defines how to crop. Can be true, false, 'width' or 'height'</li> <li>canvas - set to true to try a canvas-based rescale</li> </ul> @returns The image container object (jQuery) */ scale: function( options ) { var self = this; // extend some defaults options = $.extend({ width: 0, height: 0, min: undef, max: undef, margin: 0, complete: F, position: 'center', crop: false, canvas: false }, options); if( this.isIframe ) { $( this.image ).width( options.width ).height( options.height ).removeAttr( 'width' ).removeAttr( 'height' ); $( this.container ).width( options.width ).height( options.height) ; options.complete.call(self, self); try { if( this.image.contentWindow ) { $( this.image.contentWindow ).trigger('resize'); } } catch(e) {} return this.container; } // return the element if no image found if (!this.image) { return this.container; } // store locale variables var width, height, $container = $( self.container ), data; // wait for the width/height Utils.wait({ until: function() { width = options.width || $container.width() || Utils.parseValue( $container.css('width') ); height = options.height || $container.height() || Utils.parseValue( $container.css('height') ); return width && height; }, success: function() { // calculate some cropping var newWidth = ( width - options.margin * 2 ) / self.original.width, newHeight = ( height - options.margin * 2 ) / self.original.height, min = Math.min( newWidth, newHeight ), max = Math.max( newWidth, newHeight ), cropMap = { 'true' : max, 'width' : newWidth, 'height': newHeight, 'false' : min, 'landscape': self.original.width > self.original.height ? max : min, 'portrait': self.original.width < self.original.height ? max : min }, ratio = cropMap[ options.crop.toString() ], canvasKey = ''; // allow maxScaleRatio if ( options.max ) { ratio = Math.min( options.max, ratio ); } // allow minScaleRatio if ( options.min ) { ratio = Math.max( options.min, ratio ); } $.each( ['width','height'], function( i, m ) { $( self.image )[ m ]( self[ m ] = self.image[ m ] = Math.round( self.original[ m ] * ratio ) ); }); $( self.container ).width( width ).height( height ); if ( options.canvas && _canvas ) { _canvas.elem.width = self.width; _canvas.elem.height = self.height; canvasKey = self.image.src + ':' + self.width + 'x' + self.height; self.image.src = _canvas.cache[ canvasKey ] || (function( key ) { _canvas.context.drawImage(self.image, 0, 0, self.original.width*ratio, self.original.height*ratio); try { data = _canvas.elem.toDataURL(); _canvas.length += data.length; _canvas.cache[ key ] = data; return data; } catch( e ) { return self.image.src; } }( canvasKey ) ); } // calculate image_position var pos = {}, mix = {}, getPosition = function(value, measure, margin) { var result = 0; if (/\%/.test(value)) { var flt = parseInt( value, 10 ) / 100, m = self.image[ measure ] || $( self.image )[ measure ](); result = Math.ceil( m * -1 * flt + margin * flt ); } else { result = Utils.parseValue( value ); } return result; }, positionMap = { 'top': { top: 0 }, 'left': { left: 0 }, 'right': { left: '100%' }, 'bottom': { top: '100%' } }; $.each( options.position.toLowerCase().split(' '), function( i, value ) { if ( value === 'center' ) { value = '50%'; } pos[i ? 'top' : 'left'] = value; }); $.each( pos, function( i, value ) { if ( positionMap.hasOwnProperty( value ) ) { $.extend( mix, positionMap[ value ] ); } }); pos = pos.top ? $.extend( pos, mix ) : mix; pos = $.extend({ top: '50%', left: '50%' }, pos); // apply position $( self.image ).css({ position : 'absolute', top : getPosition(pos.top, 'height', height), left : getPosition(pos.left, 'width', width) }); // show the image self.show(); // flag ready and call the callback self.ready = true; options.complete.call( self, self ); }, error: function() { Galleria.raise('Could not scale image: '+self.image.src); }, timeout: 1000 }); return this; } }; // our own easings $.extend( $.easing, { galleria: function (_, t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t + b; } return c/2*((t-=2)*t*t + 2) + b; }, galleriaIn: function (_, t, b, c, d) { return c*(t/=d)*t + b; }, galleriaOut: function (_, t, b, c, d) { return -c *(t/=d)*(t-2) + b; } }); // the plugin initializer $.fn.galleria = function( options ) { var selector = this.selector; // try domReady if element not found if ( !$(this).length ) { $(function() { if ( $( selector ).length ) { // if found on domReady, go ahead $( selector ).galleria( options ); } else { // if not, try fetching the element for 5 secs, then raise a warning. Galleria.utils.wait({ until: function() { return $( selector ).length; }, success: function() { $( selector ).galleria( options ); }, error: function() { Galleria.raise('Init failed: Galleria could not find the element "'+selector+'".'); }, timeout: 5000 }); } }); return this; } return this.each(function() { // fail silent if already run if ( !$.data(this, 'galleria') ) { $.data( this, 'galleria', new Galleria().init( this, options ) ); } }); }; // phew }( jQuery ) );
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["en-CA"] = $.extend(true, {}, en, { name: "en-CA", englishName: "English (Canada)", nativeName: "English (Canada)", numberFormat: { currency: { pattern: ["-$n","$n"] } }, calendars: { standard: $.extend(true, {}, standard, { patterns: { d: "dd/MM/yyyy", D: "MMMM-dd-yy", f: "MMMM-dd-yy h:mm tt", F: "MMMM-dd-yy h:mm:ss tt" } }) } }, cultures["en-CA"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
/*! * Globalize * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( window, undefined ) { var Globalize, // private variables regexHex, regexInfinity, regexParseFloat, regexTrim, // private JavaScript utility functions arrayIndexOf, endsWith, extend, isArray, isFunction, isObject, startsWith, trim, truncate, zeroPad, // private Globalization utility functions appendPreOrPostMatch, expandFormat, formatDate, formatNumber, getTokenRegExp, getEra, getEraYear, parseExact, parseNegativePattern; // Global variable (Globalize) or CommonJS module (globalize) Globalize = function( cultureSelector ) { return new Globalize.prototype.init( cultureSelector ); }; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS module.exports = Globalize; } else { // Export as global variable window.Globalize = Globalize; } Globalize.cultures = {}; Globalize.prototype = { constructor: Globalize, init: function( cultureSelector ) { this.cultures = Globalize.cultures; this.cultureSelector = cultureSelector; return this; } }; Globalize.prototype.init.prototype = Globalize.prototype; // 1. When defining a culture, all fields are required except the ones stated as optional. // 2. Each culture should have a ".calendars" object with at least one calendar named "standard" // which serves as the default calendar in use by that culture. // 3. Each culture should have a ".calendar" object which is the current calendar being used, // it may be dynamically changed at any time to one of the calendars in ".calendars". Globalize.cultures[ "default" ] = { // A unique name for the culture in the form <language code>-<country/region code> name: "en", // the name of the culture in the english language englishName: "English", // the name of the culture in its own language nativeName: "English", // whether the culture uses right-to-left text isRTL: false, // "language" is used for so-called "specific" cultures. // For example, the culture "es-CL" means "Spanish, in Chili". // It represents the Spanish-speaking culture as it is in Chili, // which might have different formatting rules or even translations // than Spanish in Spain. A "neutral" culture is one that is not // specific to a region. For example, the culture "es" is the generic // Spanish culture, which may be a more generalized version of the language // that may or may not be what a specific culture expects. // For a specific culture like "es-CL", the "language" field refers to the // neutral, generic culture information for the language it is using. // This is not always a simple matter of the string before the dash. // For example, the "zh-Hans" culture is netural (Simplified Chinese). // And the "zh-SG" culture is Simplified Chinese in Singapore, whose lanugage // field is "zh-CHS", not "zh". // This field should be used to navigate from a specific culture to it's // more general, neutral culture. If a culture is already as general as it // can get, the language may refer to itself. language: "en", // numberFormat defines general number formatting rules, like the digits in // each grouping, the group separator, and how negative numbers are displayed. numberFormat: { // [negativePattern] // Note, numberFormat.pattern has no "positivePattern" unlike percent and currency, // but is still defined as an array for consistency with them. // negativePattern: one of "(n)|-n|- n|n-|n -" pattern: [ "-n" ], // number of decimal places normally shown decimals: 2, // string that separates number groups, as in 1,000,000 ",": ",", // string that separates a number from the fractional portion, as in 1.99 ".": ".", // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [ 3 ], // symbol used for positive numbers "+": "+", // symbol used for negative numbers "-": "-", // symbol used for NaN (Not-A-Number) "NaN": "NaN", // symbol used for Negative Infinity negativeInfinity: "-Infinity", // symbol used for Positive Infinity positiveInfinity: "Infinity", percent: { // [negativePattern, positivePattern] // negativePattern: one of "-n %|-n%|-%n|%-n|%n-|n-%|n%-|-% n|n %-|% n-|% -n|n- %" // positivePattern: one of "n %|n%|%n|% n" pattern: [ "-n %", "n %" ], // number of decimal places normally shown decimals: 2, // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [ 3 ], // string that separates number groups, as in 1,000,000 ",": ",", // string that separates a number from the fractional portion, as in 1.99 ".": ".", // symbol used to represent a percentage symbol: "%" }, currency: { // [negativePattern, positivePattern] // negativePattern: one of "($n)|-$n|$-n|$n-|(n$)|-n$|n-$|n$-|-n $|-$ n|n $-|$ n-|$ -n|n- $|($ n)|(n $)" // positivePattern: one of "$n|n$|$ n|n $" pattern: [ "($n)", "$n" ], // number of decimal places normally shown decimals: 2, // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [ 3 ], // string that separates number groups, as in 1,000,000 ",": ",", // string that separates a number from the fractional portion, as in 1.99 ".": ".", // symbol used to represent currency symbol: "$" } }, // calendars defines all the possible calendars used by this culture. // There should be at least one defined with name "standard", and is the default // calendar used by the culture. // A calendar contains information about how dates are formatted, information about // the calendar's eras, a standard set of the date formats, // translations for day and month names, and if the calendar is not based on the Gregorian // calendar, conversion functions to and from the Gregorian calendar. calendars: { standard: { // name that identifies the type of calendar this is name: "Gregorian_USEnglish", // separator of parts of a date (e.g. "/" in 11/05/1955) "/": "/", // separator of parts of a time (e.g. ":" in 05:44 PM) ":": ":", // the first day of the week (0 = Sunday, 1 = Monday, etc) firstDay: 0, days: { // full day names names: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], // abbreviated day names namesAbbr: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], // shortest day names namesShort: [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ] }, months: { // full month names (13 months for lunar calendards -- 13th month should be "" if not lunar) names: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "" ], // abbreviated month names namesAbbr: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "" ] }, // AM and PM designators in one of these forms: // The usual view, and the upper and lower case versions // [ standard, lowercase, uppercase ] // The culture does not use AM or PM (likely all standard date formats use 24 hour time) // null AM: [ "AM", "am", "AM" ], PM: [ "PM", "pm", "PM" ], eras: [ // eras in reverse chronological order. // name: the name of the era in this culture (e.g. A.D., C.E.) // start: when the era starts in ticks (gregorian, gmt), null if it is the earliest supported era. // offset: offset in years from gregorian calendar { "name": "A.D.", "start": null, "offset": 0 } ], // when a two digit year is given, it will never be parsed as a four digit // year greater than this year (in the appropriate era for the culture) // Set it as a full year (e.g. 2029) or use an offset format starting from // the current year: "+19" would correspond to 2029 if the current year 2010. twoDigitYearMax: 2029, // set of predefined date and time patterns used by the culture // these represent the format someone in this culture would expect // to see given the portions of the date that are shown. patterns: { // short date pattern d: "M/d/yyyy", // long date pattern D: "dddd, MMMM dd, yyyy", // short time pattern t: "h:mm tt", // long time pattern T: "h:mm:ss tt", // long date, short time pattern f: "dddd, MMMM dd, yyyy h:mm tt", // long date, long time pattern F: "dddd, MMMM dd, yyyy h:mm:ss tt", // month/day pattern M: "MMMM dd", // month/year pattern Y: "yyyy MMMM", // S is a sortable format that does not vary by culture S: "yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss" } // optional fields for each calendar: /* monthsGenitive: Same as months but used when the day preceeds the month. Omit if the culture has no genitive distinction in month names. For an explaination of genitive months, see http://blogs.msdn.com/michkap/archive/2004/12/25/332259.aspx convert: Allows for the support of non-gregorian based calendars. This convert object is used to to convert a date to and from a gregorian calendar date to handle parsing and formatting. The two functions: fromGregorian( date ) Given the date as a parameter, return an array with parts [ year, month, day ] corresponding to the non-gregorian based year, month, and day for the calendar. toGregorian( year, month, day ) Given the non-gregorian year, month, and day, return a new Date() object set to the corresponding date in the gregorian calendar. */ } }, // For localized strings messages: {} }; Globalize.cultures[ "default" ].calendar = Globalize.cultures[ "default" ].calendars.standard; Globalize.cultures.en = Globalize.cultures[ "default" ]; Globalize.cultureSelector = "en"; // // private variables // regexHex = /^0x[a-f0-9]+$/i; regexInfinity = /^[+\-]?infinity$/i; regexParseFloat = /^[+\-]?\d*\.?\d*(e[+\-]?\d+)?$/; regexTrim = /^\s+|\s+$/g; // // private JavaScript utility functions // arrayIndexOf = function( array, item ) { if ( array.indexOf ) { return array.indexOf( item ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[i] === item ) { return i; } } return -1; }; endsWith = function( value, pattern ) { return value.substr( value.length - pattern.length ) === pattern; }; extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !isFunction(target) ) { target = {}; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( isObject(copy) || (copyIsArray = isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; isArray = Array.isArray || function( obj ) { return Object.prototype.toString.call( obj ) === "[object Array]"; }; isFunction = function( obj ) { return Object.prototype.toString.call( obj ) === "[object Function]"; }; isObject = function( obj ) { return Object.prototype.toString.call( obj ) === "[object Object]"; }; startsWith = function( value, pattern ) { return value.indexOf( pattern ) === 0; }; trim = function( value ) { return ( value + "" ).replace( regexTrim, "" ); }; truncate = function( value ) { if ( isNaN( value ) ) { return NaN; } return Math[ value < 0 ? "ceil" : "floor" ]( value ); }; zeroPad = function( str, count, left ) { var l; for ( l = str.length; l < count; l += 1 ) { str = ( left ? ("0" + str) : (str + "0") ); } return str; }; // // private Globalization utility functions // appendPreOrPostMatch = function( preMatch, strings ) { // appends pre- and post- token match strings while removing escaped characters. // Returns a single quote count which is used to determine if the token occurs // in a string literal. var quoteCount = 0, escaped = false; for ( var i = 0, il = preMatch.length; i < il; i++ ) { var c = preMatch.charAt( i ); switch ( c ) { case "\'": if ( escaped ) { strings.push( "\'" ); } else { quoteCount++; } escaped = false; break; case "\\": if ( escaped ) { strings.push( "\\" ); } escaped = !escaped; break; default: strings.push( c ); escaped = false; break; } } return quoteCount; }; expandFormat = function( cal, format ) { // expands unspecified or single character date formats into the full pattern. format = format || "F"; var pattern, patterns = cal.patterns, len = format.length; if ( len === 1 ) { pattern = patterns[ format ]; if ( !pattern ) { throw "Invalid date format string \'" + format + "\'."; } format = pattern; } else if ( len === 2 && format.charAt(0) === "%" ) { // %X escape format -- intended as a custom format string that is only one character, not a built-in format. format = format.charAt( 1 ); } return format; }; formatDate = function( value, format, culture ) { var cal = culture.calendar, convert = cal.convert, ret; if ( !format || !format.length || format === "i" ) { if ( culture && culture.name.length ) { if ( convert ) { // non-gregorian calendar, so we cannot use built-in toLocaleString() ret = formatDate( value, cal.patterns.F, culture ); } else { var eraDate = new Date( value.getTime() ), era = getEra( value, cal.eras ); eraDate.setFullYear( getEraYear(value, cal, era) ); ret = eraDate.toLocaleString(); } } else { ret = value.toString(); } return ret; } var eras = cal.eras, sortable = format === "s"; format = expandFormat( cal, format ); // Start with an empty string ret = []; var hour, zeros = [ "0", "00", "000" ], foundDay, checkedDay, dayPartRegExp = /([^d]|^)(d|dd)([^d]|$)/g, quoteCount = 0, tokenRegExp = getTokenRegExp(), converted; function padZeros( num, c ) { var r, s = num + ""; if ( c > 1 && s.length < c ) { r = ( zeros[c - 2] + s); return r.substr( r.length - c, c ); } else { r = s; } return r; } function hasDay() { if ( foundDay || checkedDay ) { return foundDay; } foundDay = dayPartRegExp.test( format ); checkedDay = true; return foundDay; } function getPart( date, part ) { if ( converted ) { return converted[ part ]; } switch ( part ) { case 0: return date.getFullYear(); case 1: return date.getMonth(); case 2: return date.getDate(); default: throw "Invalid part value " + part; } } if ( !sortable && convert ) { converted = convert.fromGregorian( value ); } for ( ; ; ) { // Save the current index var index = tokenRegExp.lastIndex, // Look for the next pattern ar = tokenRegExp.exec( format ); // Append the text before the pattern (or the end of the string if not found) var preMatch = format.slice( index, ar ? ar.index : format.length ); quoteCount += appendPreOrPostMatch( preMatch, ret ); if ( !ar ) { break; } // do not replace any matches that occur inside a string literal. if ( quoteCount % 2 ) { ret.push( ar[0] ); continue; } var current = ar[ 0 ], clength = current.length; switch ( current ) { case "ddd": //Day of the week, as a three-letter abbreviation case "dddd": // Day of the week, using the full name var names = ( clength === 3 ) ? cal.days.namesAbbr : cal.days.names; ret.push( names[value.getDay()] ); break; case "d": // Day of month, without leading zero for single-digit days case "dd": // Day of month, with leading zero for single-digit days foundDay = true; ret.push( padZeros( getPart(value, 2), clength ) ); break; case "MMM": // Month, as a three-letter abbreviation case "MMMM": // Month, using the full name var part = getPart( value, 1 ); ret.push( ( cal.monthsGenitive && hasDay() ) ? ( cal.monthsGenitive[ clength === 3 ? "namesAbbr" : "names" ][ part ] ) : ( cal.months[ clength === 3 ? "namesAbbr" : "names" ][ part ] ) ); break; case "M": // Month, as digits, with no leading zero for single-digit months case "MM": // Month, as digits, with leading zero for single-digit months ret.push( padZeros( getPart(value, 1) + 1, clength ) ); break; case "y": // Year, as two digits, but with no leading zero for years less than 10 case "yy": // Year, as two digits, with leading zero for years less than 10 case "yyyy": // Year represented by four full digits part = converted ? converted[ 0 ] : getEraYear( value, cal, getEra(value, eras), sortable ); if ( clength < 4 ) { part = part % 100; } ret.push( padZeros( part, clength ) ); break; case "h": // Hours with no leading zero for single-digit hours, using 12-hour clock case "hh": // Hours with leading zero for single-digit hours, using 12-hour clock hour = value.getHours() % 12; if ( hour === 0 ) hour = 12; ret.push( padZeros( hour, clength ) ); break; case "H": // Hours with no leading zero for single-digit hours, using 24-hour clock case "HH": // Hours with leading zero for single-digit hours, using 24-hour clock ret.push( padZeros( value.getHours(), clength ) ); break; case "m": // Minutes with no leading zero for single-digit minutes case "mm": // Minutes with leading zero for single-digit minutes ret.push( padZeros( value.getMinutes(), clength ) ); break; case "s": // Seconds with no leading zero for single-digit seconds case "ss": // Seconds with leading zero for single-digit seconds ret.push( padZeros( value.getSeconds(), clength ) ); break; case "t": // One character am/pm indicator ("a" or "p") case "tt": // Multicharacter am/pm indicator part = value.getHours() < 12 ? ( cal.AM ? cal.AM[0] : " " ) : ( cal.PM ? cal.PM[0] : " " ); ret.push( clength === 1 ? part.charAt(0) : part ); break; case "f": // Deciseconds case "ff": // Centiseconds case "fff": // Milliseconds ret.push( padZeros( value.getMilliseconds(), 3 ).substr( 0, clength ) ); break; case "z": // Time zone offset, no leading zero case "zz": // Time zone offset with leading zero hour = value.getTimezoneOffset() / 60; ret.push( ( hour <= 0 ? "+" : "-" ) + padZeros( Math.floor(Math.abs(hour)), clength ) ); break; case "zzz": // Time zone offset with leading zero hour = value.getTimezoneOffset() / 60; ret.push( ( hour <= 0 ? "+" : "-" ) + padZeros( Math.floor(Math.abs(hour)), 2 ) + // Hard coded ":" separator, rather than using cal.TimeSeparator // Repeated here for consistency, plus ":" was already assumed in date parsing. ":" + padZeros( Math.abs(value.getTimezoneOffset() % 60), 2 ) ); break; case "g": case "gg": if ( cal.eras ) { ret.push( cal.eras[ getEra(value, eras) ].name ); } break; case "/": ret.push( cal["/"] ); break; default: throw "Invalid date format pattern \'" + current + "\'."; } } return ret.join( "" ); }; // formatNumber (function() { var expandNumber; expandNumber = function( number, precision, formatInfo ) { var groupSizes = formatInfo.groupSizes, curSize = groupSizes[ 0 ], curGroupIndex = 1, factor = Math.pow( 10, precision ), rounded = Math.round( number * factor ) / factor; if ( !isFinite(rounded) ) { rounded = number; } number = rounded; var numberString = number+"", right = "", split = numberString.split( /e/i ), exponent = split.length > 1 ? parseInt( split[1], 10 ) : 0; numberString = split[ 0 ]; split = numberString.split( "." ); numberString = split[ 0 ]; right = split.length > 1 ? split[ 1 ] : ""; var l; if ( exponent > 0 ) { right = zeroPad( right, exponent, false ); numberString += right.slice( 0, exponent ); right = right.substr( exponent ); } else if ( exponent < 0 ) { exponent = -exponent; numberString = zeroPad( numberString, exponent + 1, true ); right = numberString.slice( -exponent, numberString.length ) + right; numberString = numberString.slice( 0, -exponent ); } if ( precision > 0 ) { right = formatInfo[ "." ] + ( (right.length > precision) ? right.slice(0, precision) : zeroPad(right, precision) ); } else { right = ""; } var stringIndex = numberString.length - 1, sep = formatInfo[ "," ], ret = ""; while ( stringIndex >= 0 ) { if ( curSize === 0 || curSize > stringIndex ) { return numberString.slice( 0, stringIndex + 1 ) + ( ret.length ? (sep + ret + right) : right ); } ret = numberString.slice( stringIndex - curSize + 1, stringIndex + 1 ) + ( ret.length ? (sep + ret) : "" ); stringIndex -= curSize; if ( curGroupIndex < groupSizes.length ) { curSize = groupSizes[ curGroupIndex ]; curGroupIndex++; } } return numberString.slice( 0, stringIndex + 1 ) + sep + ret + right; }; formatNumber = function( value, format, culture ) { if ( !isFinite(value) ) { if ( value === Infinity ) { return culture.numberFormat.positiveInfinity; } if ( value === -Infinity ) { return culture.numberFormat.negativeInfinity; } return culture.numberFormat.NaN; } if ( !format || format === "i" ) { return culture.name.length ? value.toLocaleString() : value.toString(); } format = format || "D"; var nf = culture.numberFormat, number = Math.abs( value ), precision = -1, pattern; if ( format.length > 1 ) precision = parseInt( format.slice(1), 10 ); var current = format.charAt( 0 ).toUpperCase(), formatInfo; switch ( current ) { case "D": pattern = "n"; number = truncate( number ); if ( precision !== -1 ) { number = zeroPad( "" + number, precision, true ); } if ( value < 0 ) number = "-" + number; break; case "N": formatInfo = nf; /* falls through */ case "C": formatInfo = formatInfo || nf.currency; /* falls through */ case "P": formatInfo = formatInfo || nf.percent; pattern = value < 0 ? formatInfo.pattern[ 0 ] : ( formatInfo.pattern[1] || "n" ); if ( precision === -1 ) precision = formatInfo.decimals; number = expandNumber( number * (current === "P" ? 100 : 1), precision, formatInfo ); break; default: throw "Bad number format specifier: " + current; } var patternParts = /n|\$|-|%/g, ret = ""; for ( ; ; ) { var index = patternParts.lastIndex, ar = patternParts.exec( pattern ); ret += pattern.slice( index, ar ? ar.index : pattern.length ); if ( !ar ) { break; } switch ( ar[0] ) { case "n": ret += number; break; case "$": ret += nf.currency.symbol; break; case "-": // don't make 0 negative if ( /[1-9]/.test(number) ) { ret += nf[ "-" ]; } break; case "%": ret += nf.percent.symbol; break; } } return ret; }; }()); getTokenRegExp = function() { // regular expression for matching date and time tokens in format strings. return (/\/|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z|gg|g/g); }; getEra = function( date, eras ) { if ( !eras ) return 0; var start, ticks = date.getTime(); for ( var i = 0, l = eras.length; i < l; i++ ) { start = eras[ i ].start; if ( start === null || ticks >= start ) { return i; } } return 0; }; getEraYear = function( date, cal, era, sortable ) { var year = date.getFullYear(); if ( !sortable && cal.eras ) { // convert normal gregorian year to era-shifted gregorian // year by subtracting the era offset year -= cal.eras[ era ].offset; } return year; }; // parseExact (function() { var expandYear, getDayIndex, getMonthIndex, getParseRegExp, outOfRange, toUpper, toUpperArray; expandYear = function( cal, year ) { // expands 2-digit year into 4 digits. if ( year < 100 ) { var now = new Date(), era = getEra( now ), curr = getEraYear( now, cal, era ), twoDigitYearMax = cal.twoDigitYearMax; twoDigitYearMax = typeof twoDigitYearMax === "string" ? new Date().getFullYear() % 100 + parseInt( twoDigitYearMax, 10 ) : twoDigitYearMax; year += curr - ( curr % 100 ); if ( year > twoDigitYearMax ) { year -= 100; } } return year; }; getDayIndex = function ( cal, value, abbr ) { var ret, days = cal.days, upperDays = cal._upperDays; if ( !upperDays ) { cal._upperDays = upperDays = [ toUpperArray( days.names ), toUpperArray( days.namesAbbr ), toUpperArray( days.namesShort ) ]; } value = toUpper( value ); if ( abbr ) { ret = arrayIndexOf( upperDays[1], value ); if ( ret === -1 ) { ret = arrayIndexOf( upperDays[2], value ); } } else { ret = arrayIndexOf( upperDays[0], value ); } return ret; }; getMonthIndex = function( cal, value, abbr ) { var months = cal.months, monthsGen = cal.monthsGenitive || cal.months, upperMonths = cal._upperMonths, upperMonthsGen = cal._upperMonthsGen; if ( !upperMonths ) { cal._upperMonths = upperMonths = [ toUpperArray( months.names ), toUpperArray( months.namesAbbr ) ]; cal._upperMonthsGen = upperMonthsGen = [ toUpperArray( monthsGen.names ), toUpperArray( monthsGen.namesAbbr ) ]; } value = toUpper( value ); var i = arrayIndexOf( abbr ? upperMonths[1] : upperMonths[0], value ); if ( i < 0 ) { i = arrayIndexOf( abbr ? upperMonthsGen[1] : upperMonthsGen[0], value ); } return i; }; getParseRegExp = function( cal, format ) { // converts a format string into a regular expression with groups that // can be used to extract date fields from a date string. // check for a cached parse regex. var re = cal._parseRegExp; if ( !re ) { cal._parseRegExp = re = {}; } else { var reFormat = re[ format ]; if ( reFormat ) { return reFormat; } } // expand single digit formats, then escape regular expression characters. var expFormat = expandFormat( cal, format ).replace( /([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1" ), regexp = [ "^" ], groups = [], index = 0, quoteCount = 0, tokenRegExp = getTokenRegExp(), match; // iterate through each date token found. while ( (match = tokenRegExp.exec(expFormat)) !== null ) { var preMatch = expFormat.slice( index, match.index ); index = tokenRegExp.lastIndex; // don't replace any matches that occur inside a string literal. quoteCount += appendPreOrPostMatch( preMatch, regexp ); if ( quoteCount % 2 ) { regexp.push( match[0] ); continue; } // add a regex group for the token. var m = match[ 0 ], len = m.length, add; switch ( m ) { case "dddd": case "ddd": case "MMMM": case "MMM": case "gg": case "g": add = "(\\D+)"; break; case "tt": case "t": add = "(\\D*)"; break; case "yyyy": case "fff": case "ff": case "f": add = "(\\d{" + len + "})"; break; case "dd": case "d": case "MM": case "M": case "yy": case "y": case "HH": case "H": case "hh": case "h": case "mm": case "m": case "ss": case "s": add = "(\\d\\d?)"; break; case "zzz": add = "([+-]?\\d\\d?:\\d{2})"; break; case "zz": case "z": add = "([+-]?\\d\\d?)"; break; case "/": add = "(\\/)"; break; default: throw "Invalid date format pattern \'" + m + "\'."; } if ( add ) { regexp.push( add ); } groups.push( match[0] ); } appendPreOrPostMatch( expFormat.slice(index), regexp ); regexp.push( "$" ); // allow whitespace to differ when matching formats. var regexpStr = regexp.join( "" ).replace( /\s+/g, "\\s+" ), parseRegExp = { "regExp": regexpStr, "groups": groups }; // cache the regex for this format. return re[ format ] = parseRegExp; }; outOfRange = function( value, low, high ) { return value < low || value > high; }; toUpper = function( value ) { // "he-IL" has non-breaking space in weekday names. return value.split( "\u00A0" ).join( " " ).toUpperCase(); }; toUpperArray = function( arr ) { var results = []; for ( var i = 0, l = arr.length; i < l; i++ ) { results[ i ] = toUpper( arr[i] ); } return results; }; parseExact = function( value, format, culture ) { // try to parse the date string by matching against the format string // while using the specified culture for date field names. value = trim( value ); var cal = culture.calendar, // convert date formats into regular expressions with groupings. // use the regexp to determine the input format and extract the date fields. parseInfo = getParseRegExp( cal, format ), match = new RegExp( parseInfo.regExp ).exec( value ); if ( match === null ) { return null; } // found a date format that matches the input. var groups = parseInfo.groups, era = null, year = null, month = null, date = null, weekDay = null, hour = 0, hourOffset, min = 0, sec = 0, msec = 0, tzMinOffset = null, pmHour = false; // iterate the format groups to extract and set the date fields. for ( var j = 0, jl = groups.length; j < jl; j++ ) { var matchGroup = match[ j + 1 ]; if ( matchGroup ) { var current = groups[ j ], clength = current.length, matchInt = parseInt( matchGroup, 10 ); switch ( current ) { case "dd": case "d": // Day of month. date = matchInt; // check that date is generally in valid range, also checking overflow below. if ( outOfRange(date, 1, 31) ) return null; break; case "MMM": case "MMMM": month = getMonthIndex( cal, matchGroup, clength === 3 ); if ( outOfRange(month, 0, 11) ) return null; break; case "M": case "MM": // Month. month = matchInt - 1; if ( outOfRange(month, 0, 11) ) return null; break; case "y": case "yy": case "yyyy": year = clength < 4 ? expandYear( cal, matchInt ) : matchInt; if ( outOfRange(year, 0, 9999) ) return null; break; case "h": case "hh": // Hours (12-hour clock). hour = matchInt; if ( hour === 12 ) hour = 0; if ( outOfRange(hour, 0, 11) ) return null; break; case "H": case "HH": // Hours (24-hour clock). hour = matchInt; if ( outOfRange(hour, 0, 23) ) return null; break; case "m": case "mm": // Minutes. min = matchInt; if ( outOfRange(min, 0, 59) ) return null; break; case "s": case "ss": // Seconds. sec = matchInt; if ( outOfRange(sec, 0, 59) ) return null; break; case "tt": case "t": // AM/PM designator. // see if it is standard, upper, or lower case PM. If not, ensure it is at least one of // the AM tokens. If not, fail the parse for this format. pmHour = cal.PM && ( matchGroup === cal.PM[0] || matchGroup === cal.PM[1] || matchGroup === cal.PM[2] ); if ( !pmHour && ( !cal.AM || ( matchGroup !== cal.AM[0] && matchGroup !== cal.AM[1] && matchGroup !== cal.AM[2] ) ) ) return null; break; case "f": // Deciseconds. case "ff": // Centiseconds. case "fff": // Milliseconds. msec = matchInt * Math.pow( 10, 3 - clength ); if ( outOfRange(msec, 0, 999) ) return null; break; case "ddd": // Day of week. case "dddd": // Day of week. weekDay = getDayIndex( cal, matchGroup, clength === 3 ); if ( outOfRange(weekDay, 0, 6) ) return null; break; case "zzz": // Time zone offset in +/- hours:min. var offsets = matchGroup.split( /:/ ); if ( offsets.length !== 2 ) return null; hourOffset = parseInt( offsets[0], 10 ); if ( outOfRange(hourOffset, -12, 13) ) return null; var minOffset = parseInt( offsets[1], 10 ); if ( outOfRange(minOffset, 0, 59) ) return null; tzMinOffset = ( hourOffset * 60 ) + ( startsWith(matchGroup, "-") ? -minOffset : minOffset ); break; case "z": case "zz": // Time zone offset in +/- hours. hourOffset = matchInt; if ( outOfRange(hourOffset, -12, 13) ) return null; tzMinOffset = hourOffset * 60; break; case "g": case "gg": var eraName = matchGroup; if ( !eraName || !cal.eras ) return null; eraName = trim( eraName.toLowerCase() ); for ( var i = 0, l = cal.eras.length; i < l; i++ ) { if ( eraName === cal.eras[i].name.toLowerCase() ) { era = i; break; } } // could not find an era with that name if ( era === null ) return null; break; } } } var result = new Date(), defaultYear, convert = cal.convert; defaultYear = convert ? convert.fromGregorian( result )[ 0 ] : result.getFullYear(); if ( year === null ) { year = defaultYear; } else if ( cal.eras ) { // year must be shifted to normal gregorian year // but not if year was not specified, its already normal gregorian // per the main if clause above. year += cal.eras[( era || 0 )].offset; } // set default day and month to 1 and January, so if unspecified, these are the defaults // instead of the current day/month. if ( month === null ) { month = 0; } if ( date === null ) { date = 1; } // now have year, month, and date, but in the culture's calendar. // convert to gregorian if necessary if ( convert ) { result = convert.toGregorian( year, month, date ); // conversion failed, must be an invalid match if ( result === null ) return null; } else { // have to set year, month and date together to avoid overflow based on current date. result.setFullYear( year, month, date ); // check to see if date overflowed for specified month (only checked 1-31 above). if ( result.getDate() !== date ) return null; // invalid day of week. if ( weekDay !== null && result.getDay() !== weekDay ) { return null; } } // if pm designator token was found make sure the hours fit the 24-hour clock. if ( pmHour && hour < 12 ) { hour += 12; } result.setHours( hour, min, sec, msec ); if ( tzMinOffset !== null ) { // adjust timezone to utc before applying local offset. var adjustedMin = result.getMinutes() - ( tzMinOffset + result.getTimezoneOffset() ); // Safari limits hours and minutes to the range of -127 to 127. We need to use setHours // to ensure both these fields will not exceed this range. adjustedMin will range // somewhere between -1440 and 1500, so we only need to split this into hours. result.setHours( result.getHours() + parseInt(adjustedMin / 60, 10), adjustedMin % 60 ); } return result; }; }()); parseNegativePattern = function( value, nf, negativePattern ) { var neg = nf[ "-" ], pos = nf[ "+" ], ret; switch ( negativePattern ) { case "n -": neg = " " + neg; pos = " " + pos; /* falls through */ case "n-": if ( endsWith(value, neg) ) { ret = [ "-", value.substr(0, value.length - neg.length) ]; } else if ( endsWith(value, pos) ) { ret = [ "+", value.substr(0, value.length - pos.length) ]; } break; case "- n": neg += " "; pos += " "; /* falls through */ case "-n": if ( startsWith(value, neg) ) { ret = [ "-", value.substr(neg.length) ]; } else if ( startsWith(value, pos) ) { ret = [ "+", value.substr(pos.length) ]; } break; case "(n)": if ( startsWith(value, "(") && endsWith(value, ")") ) { ret = [ "-", value.substr(1, value.length - 2) ]; } break; } return ret || [ "", value ]; }; // // public instance functions // Globalize.prototype.findClosestCulture = function( cultureSelector ) { return Globalize.findClosestCulture.call( this, cultureSelector ); }; Globalize.prototype.format = function( value, format, cultureSelector ) { return Globalize.format.call( this, value, format, cultureSelector ); }; Globalize.prototype.localize = function( key, cultureSelector ) { return Globalize.localize.call( this, key, cultureSelector ); }; Globalize.prototype.parseInt = function( value, radix, cultureSelector ) { return Globalize.parseInt.call( this, value, radix, cultureSelector ); }; Globalize.prototype.parseFloat = function( value, radix, cultureSelector ) { return Globalize.parseFloat.call( this, value, radix, cultureSelector ); }; Globalize.prototype.culture = function( cultureSelector ) { return Globalize.culture.call( this, cultureSelector ); }; // // public singleton functions // Globalize.addCultureInfo = function( cultureName, baseCultureName, info ) { var base = {}, isNew = false; if ( typeof cultureName !== "string" ) { // cultureName argument is optional string. If not specified, assume info is first // and only argument. Specified info deep-extends current culture. info = cultureName; cultureName = this.culture().name; base = this.cultures[ cultureName ]; } else if ( typeof baseCultureName !== "string" ) { // baseCultureName argument is optional string. If not specified, assume info is second // argument. Specified info deep-extends specified culture. // If specified culture does not exist, create by deep-extending default info = baseCultureName; isNew = ( this.cultures[ cultureName ] == null ); base = this.cultures[ cultureName ] || this.cultures[ "default" ]; } else { // cultureName and baseCultureName specified. Assume a new culture is being created // by deep-extending an specified base culture isNew = true; base = this.cultures[ baseCultureName ]; } this.cultures[ cultureName ] = extend(true, {}, base, info ); // Make the standard calendar the current culture if it's a new culture if ( isNew ) { this.cultures[ cultureName ].calendar = this.cultures[ cultureName ].calendars.standard; } }; Globalize.findClosestCulture = function( name ) { var match; if ( !name ) { return this.findClosestCulture( this.cultureSelector ) || this.cultures[ "default" ]; } if ( typeof name === "string" ) { name = name.split( "," ); } if ( isArray(name) ) { var lang, cultures = this.cultures, list = name, i, l = list.length, prioritized = []; for ( i = 0; i < l; i++ ) { name = trim( list[i] ); var pri, parts = name.split( ";" ); lang = trim( parts[0] ); if ( parts.length === 1 ) { pri = 1; } else { name = trim( parts[1] ); if ( name.indexOf("q=") === 0 ) { name = name.substr( 2 ); pri = parseFloat( name ); pri = isNaN( pri ) ? 0 : pri; } else { pri = 1; } } prioritized.push({ lang: lang, pri: pri }); } prioritized.sort(function( a, b ) { if ( a.pri < b.pri ) { return 1; } else if ( a.pri > b.pri ) { return -1; } return 0; }); // exact match for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; match = cultures[ lang ]; if ( match ) { return match; } } // neutral language match for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; do { var index = lang.lastIndexOf( "-" ); if ( index === -1 ) { break; } // strip off the last part. e.g. en-US => en lang = lang.substr( 0, index ); match = cultures[ lang ]; if ( match ) { return match; } } while ( 1 ); } // last resort: match first culture using that language for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; for ( var cultureKey in cultures ) { var culture = cultures[ cultureKey ]; if ( culture.language == lang ) { return culture; } } } } else if ( typeof name === "object" ) { return name; } return match || null; }; Globalize.format = function( value, format, cultureSelector ) { var culture = this.findClosestCulture( cultureSelector ); if ( value instanceof Date ) { value = formatDate( value, format, culture ); } else if ( typeof value === "number" ) { value = formatNumber( value, format, culture ); } return value; }; Globalize.localize = function( key, cultureSelector ) { return this.findClosestCulture( cultureSelector ).messages[ key ] || this.cultures[ "default" ].messages[ key ]; }; Globalize.parseDate = function( value, formats, culture ) { culture = this.findClosestCulture( culture ); var date, prop, patterns; if ( formats ) { if ( typeof formats === "string" ) { formats = [ formats ]; } if ( formats.length ) { for ( var i = 0, l = formats.length; i < l; i++ ) { var format = formats[ i ]; if ( format ) { date = parseExact( value, format, culture ); if ( date ) { break; } } } } } else { patterns = culture.calendar.patterns; for ( prop in patterns ) { date = parseExact( value, patterns[prop], culture ); if ( date ) { break; } } } return date || null; }; Globalize.parseInt = function( value, radix, cultureSelector ) { return truncate( Globalize.parseFloat(value, radix, cultureSelector) ); }; Globalize.parseFloat = function( value, radix, cultureSelector ) { // radix argument is optional if ( typeof radix !== "number" ) { cultureSelector = radix; radix = 10; } var culture = this.findClosestCulture( cultureSelector ); var ret = NaN, nf = culture.numberFormat; if ( value.indexOf(culture.numberFormat.currency.symbol) > -1 ) { // remove currency symbol value = value.replace( culture.numberFormat.currency.symbol, "" ); // replace decimal seperator value = value.replace( culture.numberFormat.currency["."], culture.numberFormat["."] ); } //Remove percentage character from number string before parsing if ( value.indexOf(culture.numberFormat.percent.symbol) > -1){ value = value.replace( culture.numberFormat.percent.symbol, "" ); } // remove spaces: leading, trailing and between - and number. Used for negative currency pt-BR value = value.replace( / /g, "" ); // allow infinity or hexidecimal if ( regexInfinity.test(value) ) { ret = parseFloat( value ); } else if ( !radix && regexHex.test(value) ) { ret = parseInt( value, 16 ); } else { // determine sign and number var signInfo = parseNegativePattern( value, nf, nf.pattern[0] ), sign = signInfo[ 0 ], num = signInfo[ 1 ]; // #44 - try parsing as "(n)" if ( sign === "" && nf.pattern[0] !== "(n)" ) { signInfo = parseNegativePattern( value, nf, "(n)" ); sign = signInfo[ 0 ]; num = signInfo[ 1 ]; } // try parsing as "-n" if ( sign === "" && nf.pattern[0] !== "-n" ) { signInfo = parseNegativePattern( value, nf, "-n" ); sign = signInfo[ 0 ]; num = signInfo[ 1 ]; } sign = sign || "+"; // determine exponent and number var exponent, intAndFraction, exponentPos = num.indexOf( "e" ); if ( exponentPos < 0 ) exponentPos = num.indexOf( "E" ); if ( exponentPos < 0 ) { intAndFraction = num; exponent = null; } else { intAndFraction = num.substr( 0, exponentPos ); exponent = num.substr( exponentPos + 1 ); } // determine decimal position var integer, fraction, decSep = nf[ "." ], decimalPos = intAndFraction.indexOf( decSep ); if ( decimalPos < 0 ) { integer = intAndFraction; fraction = null; } else { integer = intAndFraction.substr( 0, decimalPos ); fraction = intAndFraction.substr( decimalPos + decSep.length ); } // handle groups (e.g. 1,000,000) var groupSep = nf[ "," ]; integer = integer.split( groupSep ).join( "" ); var altGroupSep = groupSep.replace( /\u00A0/g, " " ); if ( groupSep !== altGroupSep ) { integer = integer.split( altGroupSep ).join( "" ); } // build a natively parsable number string var p = sign + integer; if ( fraction !== null ) { p += "." + fraction; } if ( exponent !== null ) { // exponent itself may have a number patternd var expSignInfo = parseNegativePattern( exponent, nf, "-n" ); p += "e" + ( expSignInfo[0] || "+" ) + expSignInfo[ 1 ]; } if ( regexParseFloat.test(p) ) { ret = parseFloat( p ); } } return ret; }; Globalize.culture = function( cultureSelector ) { // setter if ( typeof cultureSelector !== "undefined" ) { this.cultureSelector = cultureSelector; } // getter return this.findClosestCulture( cultureSelector ) || this.cultures[ "default" ]; }; }( this ));
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["en-US"] = $.extend(true, {}, en, { }, cultures["en-US"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["ru-RU"] = $.extend(true, {}, en, { name: "ru-RU", englishName: "Russian (Russia)", nativeName: "русский (Россия)", language: "ru", numberFormat: { ',': " ", '.': ",", percent: { pattern: ["-n%","n%"], ',': " ", '.': "," }, currency: { pattern: ["-n$","n$"], ',': " ", '.': ",", symbol: "р." } }, calendars: { standard: $.extend(true, {}, standard, { '/': ".", firstDay: 1, days: { names: ["воскресенье","понедельник","вторник","среда","четверг","пятница","суббота"], namesAbbr: ["Вс","Пн","Вт","Ср","Чт","Пт","Сб"], namesShort: ["Вс","Пн","Вт","Ср","Чт","Пт","Сб"] }, months: { names: ["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь",""], namesAbbr: ["янв","фев","мар","апр","май","июн","июл","авг","сен","окт","ноя","дек",""] }, monthsGenitive: { names: ["января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря",""], namesAbbr: ["янв","фев","мар","апр","май","июн","июл","авг","сен","окт","ноя","дек",""] }, AM: null, PM: null, patterns: { d: "dd.MM.yyyy", D: "d MMMM yyyy 'г.'", t: "H:mm", T: "H:mm:ss", f: "d MMMM yyyy 'г.' H:mm", F: "d MMMM yyyy 'г.' H:mm:ss", Y: "MMMM yyyy" } }) } }, cultures["ru-RU"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["fr-FR"] = $.extend(true, {}, en, { name: "fr-FR", englishName: "French (France)", nativeName: "français (France)", language: "fr", numberFormat: { ',': " ", '.': ",", percent: { ',': " ", '.': "," }, currency: { pattern: ["-n $","n $"], ',': " ", '.': ",", symbol: "€" } }, calendars: { standard: $.extend(true, {}, standard, { firstDay: 1, days: { names: ["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"], namesAbbr: ["dim.","lun.","mar.","mer.","jeu.","ven.","sam."], namesShort: ["di","lu","ma","me","je","ve","sa"] }, months: { names: ["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre",""], namesAbbr: ["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc.",""] }, AM: null, PM: null, eras: [{"name":"ap. J.-C.","start":null,"offset":0}], patterns: { d: "dd/MM/yyyy", D: "dddd d MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd d MMMM yyyy HH:mm", F: "dddd d MMMM yyyy HH:mm:ss", M: "d MMMM", Y: "MMMM yyyy" } }) } }, cultures["fr-FR"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["de-DE"] = $.extend(true, {}, en, { name: "de-DE", englishName: "German (Germany)", nativeName: "Deutsch (Deutschland)", language: "de", numberFormat: { ',': ".", '.': ",", percent: { pattern: ["-n%","n%"], ',': ".", '.': "," }, currency: { pattern: ["-n $","n $"], ',': ".", '.': ",", symbol: "€" } }, calendars: { standard: $.extend(true, {}, standard, { '/': ".", firstDay: 1, days: { names: ["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"], namesAbbr: ["So","Mo","Di","Mi","Do","Fr","Sa"], namesShort: ["So","Mo","Di","Mi","Do","Fr","Sa"] }, months: { names: ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember",""], namesAbbr: ["Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez",""] }, AM: null, PM: null, eras: [{"name":"n. Chr.","start":null,"offset":0}], patterns: { d: "dd.MM.yyyy", D: "dddd, d. MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd, d. MMMM yyyy HH:mm", F: "dddd, d. MMMM yyyy HH:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } }) } }, cultures["de-DE"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["cs-CZ"] = $.extend(true, {}, en, { name: "cs-CZ", englishName: "Czech (Czech Republic)", nativeName: "čeština (Česká republika)", language: "cs", numberFormat: { ',': " ", '.': ",", percent: { pattern: ["-n%","n%"], ',': " ", '.': "," }, currency: { pattern: ["-n $","n $"], ',': " ", '.': ",", symbol: "Kč" } }, calendars: { standard: $.extend(true, {}, standard, { '/': ".", firstDay: 1, days: { names: ["neděle","pondělí","úterý","středa","čtvrtek","pátek","sobota"], namesAbbr: ["ne","po","út","st","čt","pá","so"], namesShort: ["ne","po","út","st","čt","pá","so"] }, months: { names: ["leden","únor","březen","duben","květen","červen","červenec","srpen","září","říjen","listopad","prosinec",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, monthsGenitive: { names: ["ledna","února","března","dubna","května","června","července","srpna","září","října","listopadu","prosince",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, AM: ["dop.","dop.","DOP."], PM: ["odp.","odp.","ODP."], eras: [{"name":"n. l.","start":null,"offset":0}], patterns: { d: "d.M.yyyy", D: "d. MMMM yyyy", t: "H:mm", T: "H:mm:ss", f: "d. MMMM yyyy H:mm", F: "d. MMMM yyyy H:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } }) } }, cultures["cs-CZ"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["ja-JP"] = $.extend(true, {}, en, { name: "ja-JP", englishName: "Japanese (Japan)", nativeName: "日本語 (日本)", language: "ja", numberFormat: { percent: { pattern: ["-n%","n%"] }, currency: { pattern: ["-$n","$n"], decimals: 0, symbol: "¥" } }, calendars: { standard: $.extend(true, {}, standard, { days: { names: ["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"], namesAbbr: ["日","月","火","水","木","金","土"], namesShort: ["日","月","火","水","木","金","土"] }, months: { names: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, AM: ["午前","午前","午前"], PM: ["午後","午後","午後"], eras: [{"name":"西暦","start":null,"offset":0}], patterns: { d: "yyyy/MM/dd", D: "yyyy'年'M'月'd'日'", t: "H:mm", T: "H:mm:ss", f: "yyyy'年'M'月'd'日' H:mm", F: "yyyy'年'M'月'd'日' H:mm:ss", M: "M'月'd'日'", Y: "yyyy'年'M'月'" } }), Japanese: $.extend(true, {}, standard, { name: "Japanese", days: { names: ["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"], namesAbbr: ["日","月","火","水","木","金","土"], namesShort: ["日","月","火","水","木","金","土"] }, months: { names: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, AM: ["午前","午前","午前"], PM: ["午後","午後","午後"], eras: [{"name":"平成","start":null,"offset":1867},{"name":"昭和","start":-1812153600000,"offset":1911},{"name":"大正","start":-1357603200000,"offset":1925},{"name":"明治","start":60022080000,"offset":1988}], twoDigitYearMax: 99, patterns: { d: "gg y/M/d", D: "gg y'年'M'月'd'日'", t: "H:mm", T: "H:mm:ss", f: "gg y'年'M'月'd'日' H:mm", F: "gg y'年'M'月'd'日' H:mm:ss", M: "M'月'd'日'", Y: "gg y'年'M'月'" } }) } }, cultures["ja-JP"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
/*! * jQuery globalization Plugin v1.0.0pre * http://github.com/jquery/jquery-global * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function() { var globalization = {}, localized = { en: {} }; localized["default"] = localized.en; globalization.extend = function( deep ) { var target = arguments[ 1 ] || {}; for ( var i = 2, l = arguments.length; i < l; i++ ) { var source = arguments[ i ]; if ( source ) { for ( var field in source ) { var sourceVal = source[ field ]; if ( typeof sourceVal !== "undefined" ) { if ( deep && (isObject( sourceVal ) || isArray( sourceVal )) ) { var targetVal = target[ field ]; // extend onto the existing value, or create a new one targetVal = targetVal && (isObject( targetVal ) || isArray( targetVal )) ? targetVal : (isArray( sourceVal ) ? [] : {}); target[ field ] = this.extend( true, targetVal, sourceVal ); } else { target[ field ] = sourceVal; } } } } } return target; } globalization.findClosestCulture = function(name) { var match; if ( !name ) { return this.culture || this.cultures["default"]; } if ( isString( name ) ) { name = name.split( ',' ); } if ( isArray( name ) ) { var lang, cultures = this.cultures, list = name, i, l = list.length, prioritized = []; for ( i = 0; i < l; i++ ) { name = trim( list[ i ] ); var pri, parts = name.split( ';' ); lang = trim( parts[ 0 ] ); if ( parts.length === 1 ) { pri = 1; } else { name = trim( parts[ 1 ] ); if ( name.indexOf("q=") === 0 ) { name = name.substr( 2 ); pri = parseFloat( name, 10 ); pri = isNaN( pri ) ? 0 : pri; } else { pri = 1; } } prioritized.push( { lang: lang, pri: pri } ); } prioritized.sort(function(a, b) { return a.pri < b.pri ? 1 : -1; }); // exact match for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; match = cultures[ lang ]; if ( match ) { return match; } } // neutral language match for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; do { var index = lang.lastIndexOf( "-" ); if ( index === -1 ) { break; } // strip off the last part. e.g. en-US => en lang = lang.substr( 0, index ); match = cultures[ lang ]; if ( match ) { return match; } } while ( 1 ); } // last resort: match first culture using that language for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; for ( var cultureKey in cultures ) { var culture = cultures[ cultureKey ]; if ( culture.language == lang ) { return culture; } } } } else if ( typeof name === 'object' ) { return name; } return match || null; } globalization.preferCulture = function(name) { this.culture = this.findClosestCulture( name ) || this.cultures["default"]; } globalization.localize = function(key, culture, value) { // usign default culture in case culture is not provided if (typeof culture !== 'string') { culture = this.culture.name || this.culture || "default"; } culture = this.cultures[ culture ] || { name: culture }; var local = localized[ culture.name ]; if ( arguments.length === 3 ) { if ( !local) { local = localized[ culture.name ] = {}; } local[ key ] = value; } else { if ( local ) { value = local[ key ]; } if ( typeof value === 'undefined' ) { var language = localized[ culture.language ]; if ( language ) { value = language[ key ]; } if ( typeof value === 'undefined' ) { value = localized["default"][ key ]; } } } return typeof value === "undefined" ? null : value; } globalization.format = function(value, format, culture) { culture = this.findClosestCulture( culture ); if ( typeof value === "number" ) { value = formatNumber( value, format, culture ); } else if ( value instanceof Date ) { value = formatDate( value, format, culture ); } return value; } globalization.parseInt = function(value, radix, culture) { return Math.floor( this.parseFloat( value, radix, culture ) ); } globalization.parseFloat = function(value, radix, culture) { // make radix optional if (typeof radix === "string") { culture = radix; radix = 10; } culture = this.findClosestCulture( culture ); var ret = NaN, nf = culture.numberFormat; if (value.indexOf(culture.numberFormat.currency.symbol) > -1) { // remove currency symbol value = value.replace(culture.numberFormat.currency.symbol, ""); // replace decimal seperator value = value.replace(culture.numberFormat.currency["."], culture.numberFormat["."]); } // trim leading and trailing whitespace value = trim( value ); // allow infinity or hexidecimal if (regexInfinity.test(value)) { ret = parseFloat(value, radix); } else if (!radix && regexHex.test(value)) { ret = parseInt(value, 16); } else { var signInfo = parseNegativePattern( value, nf, nf.pattern[0] ), sign = signInfo[0], num = signInfo[1]; // determine sign and number if ( sign === "" && nf.pattern[0] !== "-n" ) { signInfo = parseNegativePattern( value, nf, "-n" ); sign = signInfo[0]; num = signInfo[1]; } sign = sign || "+"; // determine exponent and number var exponent, intAndFraction, exponentPos = num.indexOf( 'e' ); if ( exponentPos < 0 ) exponentPos = num.indexOf( 'E' ); if ( exponentPos < 0 ) { intAndFraction = num; exponent = null; } else { intAndFraction = num.substr( 0, exponentPos ); exponent = num.substr( exponentPos + 1 ); } // determine decimal position var integer, fraction, decSep = nf['.'], decimalPos = intAndFraction.indexOf( decSep ); if ( decimalPos < 0 ) { integer = intAndFraction; fraction = null; } else { integer = intAndFraction.substr( 0, decimalPos ); fraction = intAndFraction.substr( decimalPos + decSep.length ); } // handle groups (e.g. 1,000,000) var groupSep = nf[","]; integer = integer.split(groupSep).join(''); var altGroupSep = groupSep.replace(/\u00A0/g, " "); if ( groupSep !== altGroupSep ) { integer = integer.split(altGroupSep).join(''); } // build a natively parsable number string var p = sign + integer; if ( fraction !== null ) { p += '.' + fraction; } if ( exponent !== null ) { // exponent itself may have a number patternd var expSignInfo = parseNegativePattern( exponent, nf, "-n" ); p += 'e' + (expSignInfo[0] || "+") + expSignInfo[1]; } if ( regexParseFloat.test( p ) ) { ret = parseFloat( p ); } } return ret; } globalization.parseDate = function(value, formats, culture) { culture = this.findClosestCulture( culture ); var date, prop, patterns; if ( formats ) { if ( typeof formats === "string" ) { formats = [ formats ]; } if ( formats.length ) { for ( var i = 0, l = formats.length; i < l; i++ ) { var format = formats[ i ]; if ( format ) { date = parseExact( value, format, culture ); if ( date ) { break; } } } } } else { patterns = culture.calendar.patterns; for ( prop in patterns ) { date = parseExact( value, patterns[prop], culture ); if ( date ) { break; } } } return date || null; } // 1. When defining a culture, all fields are required except the ones stated as optional. // 2. You can use globalization.extend to copy an existing culture and provide only the differing values, // a good practice since most cultures do not differ too much from the 'default' culture. // DO use the 'default' culture if you do this, as it is the only one that definitely // exists. // 3. Other plugins may add to the culture information provided by extending it. However, // that plugin may extend it prior to the culture being defined, or after. Therefore, // do not overwrite values that already exist when defining the baseline for a culture, // by extending your culture object with the existing one. // 4. Each culture should have a ".calendars" object with at least one calendar named "standard" // which serves as the default calendar in use by that culture. // 5. Each culture should have a ".calendar" object which is the current calendar being used, // it may be dynamically changed at any time to one of the calendars in ".calendars". // To define a culture, use the following pattern, which handles defining the culture based // on the 'default culture, extending it with the existing culture if it exists, and defining // it if it does not exist. // globalization.cultures.foo = globalization.extend(true, globalization.extend(true, {}, globalization.cultures['default'], fooCulture), globalization.cultures.foo) var cultures = globalization.cultures = globalization.cultures || {}; var en = cultures["default"] = cultures.en = globalization.extend(true, { // A unique name for the culture in the form <language code>-<country/region code> name: "en", // the name of the culture in the english language englishName: "English", // the name of the culture in its own language nativeName: "English", // whether the culture uses right-to-left text isRTL: false, // 'language' is used for so-called "specific" cultures. // For example, the culture "es-CL" means "Spanish, in Chili". // It represents the Spanish-speaking culture as it is in Chili, // which might have different formatting rules or even translations // than Spanish in Spain. A "neutral" culture is one that is not // specific to a region. For example, the culture "es" is the generic // Spanish culture, which may be a more generalized version of the language // that may or may not be what a specific culture expects. // For a specific culture like "es-CL", the 'language' field refers to the // neutral, generic culture information for the language it is using. // This is not always a simple matter of the string before the dash. // For example, the "zh-Hans" culture is netural (Simplified Chinese). // And the 'zh-SG' culture is Simplified Chinese in Singapore, whose lanugage // field is "zh-CHS", not "zh". // This field should be used to navigate from a specific culture to it's // more general, neutral culture. If a culture is already as general as it // can get, the language may refer to itself. language: "en", // numberFormat defines general number formatting rules, like the digits in // each grouping, the group separator, and how negative numbers are displayed. numberFormat: { // [negativePattern] // Note, numberFormat.pattern has no 'positivePattern' unlike percent and currency, // but is still defined as an array for consistency with them. // negativePattern: one of "(n)|-n|- n|n-|n -" pattern: ["-n"], // number of decimal places normally shown decimals: 2, // string that separates number groups, as in 1,000,000 ',': ",", // string that separates a number from the fractional portion, as in 1.99 '.': ".", // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [3], // symbol used for positive numbers '+': "+", // symbol used for negative numbers '-': "-", percent: { // [negativePattern, positivePattern] // negativePattern: one of "-n %|-n%|-%n|%-n|%n-|n-%|n%-|-% n|n %-|% n-|% -n|n- %" // positivePattern: one of "n %|n%|%n|% n" pattern: ["-n %","n %"], // number of decimal places normally shown decimals: 2, // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [3], // string that separates number groups, as in 1,000,000 ',': ",", // string that separates a number from the fractional portion, as in 1.99 '.': ".", // symbol used to represent a percentage symbol: "%" }, currency: { // [negativePattern, positivePattern] // negativePattern: one of "($n)|-$n|$-n|$n-|(n$)|-n$|n-$|n$-|-n $|-$ n|n $-|$ n-|$ -n|n- $|($ n)|(n $)" // positivePattern: one of "$n|n$|$ n|n $" pattern: ["($n)","$n"], // number of decimal places normally shown decimals: 2, // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [3], // string that separates number groups, as in 1,000,000 ',': ",", // string that separates a number from the fractional portion, as in 1.99 '.': ".", // symbol used to represent currency symbol: "$" } }, // calendars defines all the possible calendars used by this culture. // There should be at least one defined with name 'standard', and is the default // calendar used by the culture. // A calendar contains information about how dates are formatted, information about // the calendar's eras, a standard set of the date formats, // translations for day and month names, and if the calendar is not based on the Gregorian // calendar, conversion functions to and from the Gregorian calendar. calendars: { standard: { // name that identifies the type of calendar this is name: "Gregorian_USEnglish", // separator of parts of a date (e.g. '/' in 11/05/1955) '/': "/", // separator of parts of a time (e.g. ':' in 05:44 PM) ':': ":", // the first day of the week (0 = Sunday, 1 = Monday, etc) firstDay: 0, days: { // full day names names: ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"], // abbreviated day names namesAbbr: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"], // shortest day names namesShort: ["Su","Mo","Tu","We","Th","Fr","Sa"] }, months: { // full month names (13 months for lunar calendards -- 13th month should be "" if not lunar) names: ["January","February","March","April","May","June","July","August","September","October","November","December",""], // abbreviated month names namesAbbr: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""] }, // AM and PM designators in one of these forms: // The usual view, and the upper and lower case versions // [standard,lowercase,uppercase] // The culture does not use AM or PM (likely all standard date formats use 24 hour time) // null AM: ["AM", "am", "AM"], PM: ["PM", "pm", "PM"], eras: [ // eras in reverse chronological order. // name: the name of the era in this culture (e.g. A.D., C.E.) // start: when the era starts in ticks (gregorian, gmt), null if it is the earliest supported era. // offset: offset in years from gregorian calendar { "name": "A.D.", "start": null, "offset": 0 } ], // when a two digit year is given, it will never be parsed as a four digit // year greater than this year (in the appropriate era for the culture) // Set it as a full year (e.g. 2029) or use an offset format starting from // the current year: "+19" would correspond to 2029 if the current year 2010. twoDigitYearMax: 2029, // set of predefined date and time patterns used by the culture // these represent the format someone in this culture would expect // to see given the portions of the date that are shown. patterns: { // short date pattern d: "M/d/yyyy", // long date pattern D: "dddd, MMMM dd, yyyy", // short time pattern t: "h:mm tt", // long time pattern T: "h:mm:ss tt", // long date, short time pattern f: "dddd, MMMM dd, yyyy h:mm tt", // long date, long time pattern F: "dddd, MMMM dd, yyyy h:mm:ss tt", // month/day pattern M: "MMMM dd", // month/year pattern Y: "yyyy MMMM", // S is a sortable format that does not vary by culture S: "yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss" } // optional fields for each calendar: /* monthsGenitive: Same as months but used when the day preceeds the month. Omit if the culture has no genitive distinction in month names. For an explaination of genitive months, see http://blogs.msdn.com/michkap/archive/2004/12/25/332259.aspx convert: Allows for the support of non-gregorian based calendars. This convert object is used to to convert a date to and from a gregorian calendar date to handle parsing and formatting. The two functions: fromGregorian(date) Given the date as a parameter, return an array with parts [year, month, day] corresponding to the non-gregorian based year, month, and day for the calendar. toGregorian(year, month, day) Given the non-gregorian year, month, and day, return a new Date() object set to the corresponding date in the gregorian calendar. */ } } }, cultures.en); en.calendar = en.calendar || en.calendars.standard; var regexTrim = /^\s+|\s+$/g, regexInfinity = /^[+-]?infinity$/i, regexHex = /^0x[a-f0-9]+$/i, regexParseFloat = /^[+-]?\d*\.?\d*(e[+-]?\d+)?$/, toString = Object.prototype.toString; function startsWith(value, pattern) { return value.indexOf( pattern ) === 0; } function endsWith(value, pattern) { return value.substr( value.length - pattern.length ) === pattern; } function trim(value) { return (value+"").replace( regexTrim, "" ); } function zeroPad(str, count, left) { for (var l=str.length; l < count; l++) { str = (left ? ('0' + str) : (str + '0')); } return str; } function isArray(obj) { return toString.call(obj) === "[object Array]"; } function isString(obj) { return toString.call(obj) === "[object String]"; } function isObject(obj) { return toString.call(obj) === "[object Object]"; } function arrayIndexOf( array, item ) { if ( array.indexOf ) { return array.indexOf( item ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === item ) { return i; } } return -1; } // *************************************** Numbers *************************************** function expandNumber(number, precision, formatInfo) { var groupSizes = formatInfo.groupSizes, curSize = groupSizes[ 0 ], curGroupIndex = 1, factor = Math.pow( 10, precision ), rounded = Math.round( number * factor ) / factor; if ( !isFinite(rounded) ) { rounded = number; } number = rounded; var numberString = number+"", right = "", split = numberString.split(/e/i), exponent = split.length > 1 ? parseInt( split[ 1 ], 10 ) : 0; numberString = split[ 0 ]; split = numberString.split( "." ); numberString = split[ 0 ]; right = split.length > 1 ? split[ 1 ] : ""; var l; if ( exponent > 0 ) { right = zeroPad( right, exponent, false ); numberString += right.slice( 0, exponent ); right = right.substr( exponent ); } else if ( exponent < 0 ) { exponent = -exponent; numberString = zeroPad( numberString, exponent + 1 ); right = numberString.slice( -exponent, numberString.length ) + right; numberString = numberString.slice( 0, -exponent ); } if ( precision > 0 ) { right = formatInfo['.'] + ((right.length > precision) ? right.slice( 0, precision ) : zeroPad( right, precision )); } else { right = ""; } var stringIndex = numberString.length - 1, sep = formatInfo[","], ret = ""; while ( stringIndex >= 0 ) { if ( curSize === 0 || curSize > stringIndex ) { return numberString.slice( 0, stringIndex + 1 ) + ( ret.length ? ( sep + ret + right ) : right ); } ret = numberString.slice( stringIndex - curSize + 1, stringIndex + 1 ) + ( ret.length ? ( sep + ret ) : "" ); stringIndex -= curSize; if ( curGroupIndex < groupSizes.length ) { curSize = groupSizes[ curGroupIndex ]; curGroupIndex++; } } return numberString.slice( 0, stringIndex + 1 ) + sep + ret + right; } function parseNegativePattern(value, nf, negativePattern) { var neg = nf["-"], pos = nf["+"], ret; switch (negativePattern) { case "n -": neg = ' ' + neg; pos = ' ' + pos; // fall through case "n-": if ( endsWith( value, neg ) ) { ret = [ '-', value.substr( 0, value.length - neg.length ) ]; } else if ( endsWith( value, pos ) ) { ret = [ '+', value.substr( 0, value.length - pos.length ) ]; } break; case "- n": neg += ' '; pos += ' '; // fall through case "-n": if ( startsWith( value, neg ) ) { ret = [ '-', value.substr( neg.length ) ]; } else if ( startsWith(value, pos) ) { ret = [ '+', value.substr( pos.length ) ]; } break; case "(n)": if ( startsWith( value, '(' ) && endsWith( value, ')' ) ) { ret = [ '-', value.substr( 1, value.length - 2 ) ]; } break; } return ret || [ '', value ]; } function formatNumber(value, format, culture) { if ( !format || format === 'i' ) { return culture.name.length ? value.toLocaleString() : value.toString(); } format = format || "D"; var nf = culture.numberFormat, number = Math.abs(value), precision = -1, pattern; if (format.length > 1) precision = parseInt( format.slice( 1 ), 10 ); var current = format.charAt( 0 ).toUpperCase(), formatInfo; switch (current) { case "D": pattern = 'n'; if (precision !== -1) { number = zeroPad( ""+number, precision, true ); } if (value < 0) number = -number; break; case "N": formatInfo = nf; // fall through case "C": formatInfo = formatInfo || nf.currency; // fall through case "P": formatInfo = formatInfo || nf.percent; pattern = value < 0 ? formatInfo.pattern[0] : (formatInfo.pattern[1] || "n"); if (precision === -1) precision = formatInfo.decimals; number = expandNumber( number * (current === "P" ? 100 : 1), precision, formatInfo ); break; default: throw "Bad number format specifier: " + current; } var patternParts = /n|\$|-|%/g, ret = ""; for (;;) { var index = patternParts.lastIndex, ar = patternParts.exec(pattern); ret += pattern.slice( index, ar ? ar.index : pattern.length ); if (!ar) { break; } switch (ar[0]) { case "n": ret += number; break; case "$": ret += nf.currency.symbol; break; case "-": // don't make 0 negative if ( /[1-9]/.test( number ) ) { ret += nf["-"]; } break; case "%": ret += nf.percent.symbol; break; } } return ret; } // *************************************** Dates *************************************** function outOfRange(value, low, high) { return value < low || value > high; } function expandYear(cal, year) { // expands 2-digit year into 4 digits. var now = new Date(), era = getEra(now); if ( year < 100 ) { var twoDigitYearMax = cal.twoDigitYearMax; twoDigitYearMax = typeof twoDigitYearMax === 'string' ? new Date().getFullYear() % 100 + parseInt( twoDigitYearMax, 10 ) : twoDigitYearMax; var curr = getEraYear( now, cal, era ); year += curr - ( curr % 100 ); if ( year > twoDigitYearMax ) { year -= 100; } } return year; } function getEra(date, eras) { if ( !eras ) return 0; var start, ticks = date.getTime(); for ( var i = 0, l = eras.length; i < l; i++ ) { start = eras[ i ].start; if ( start === null || ticks >= start ) { return i; } } return 0; } function toUpper(value) { // 'he-IL' has non-breaking space in weekday names. return value.split( "\u00A0" ).join(' ').toUpperCase(); } function toUpperArray(arr) { var results = []; for ( var i = 0, l = arr.length; i < l; i++ ) { results[i] = toUpper(arr[i]); } return results; } function getEraYear(date, cal, era, sortable) { var year = date.getFullYear(); if ( !sortable && cal.eras ) { // convert normal gregorian year to era-shifted gregorian // year by subtracting the era offset year -= cal.eras[ era ].offset; } return year; } function getDayIndex(cal, value, abbr) { var ret, days = cal.days, upperDays = cal._upperDays; if ( !upperDays ) { cal._upperDays = upperDays = [ toUpperArray( days.names ), toUpperArray( days.namesAbbr ), toUpperArray( days.namesShort ) ]; } value = toUpper( value ); if ( abbr ) { ret = arrayIndexOf( upperDays[ 1 ], value ); if ( ret === -1 ) { ret = arrayIndexOf( upperDays[ 2 ], value ); } } else { ret = arrayIndexOf( upperDays[ 0 ], value ); } return ret; } function getMonthIndex(cal, value, abbr) { var months = cal.months, monthsGen = cal.monthsGenitive || cal.months, upperMonths = cal._upperMonths, upperMonthsGen = cal._upperMonthsGen; if ( !upperMonths ) { cal._upperMonths = upperMonths = [ toUpperArray( months.names ), toUpperArray( months.namesAbbr ) ]; cal._upperMonthsGen = upperMonthsGen = [ toUpperArray( monthsGen.names ), toUpperArray( monthsGen.namesAbbr ) ]; } value = toUpper( value ); var i = arrayIndexOf( abbr ? upperMonths[ 1 ] : upperMonths[ 0 ], value ); if ( i < 0 ) { i = arrayIndexOf( abbr ? upperMonthsGen[ 1 ] : upperMonthsGen[ 0 ], value ); } return i; } function appendPreOrPostMatch(preMatch, strings) { // appends pre- and post- token match strings while removing escaped characters. // Returns a single quote count which is used to determine if the token occurs // in a string literal. var quoteCount = 0, escaped = false; for ( var i = 0, il = preMatch.length; i < il; i++ ) { var c = preMatch.charAt( i ); switch ( c ) { case '\'': if ( escaped ) { strings.push( "'" ); } else { quoteCount++; } escaped = false; break; case '\\': if ( escaped ) { strings.push( "\\" ); } escaped = !escaped; break; default: strings.push( c ); escaped = false; break; } } return quoteCount; } function expandFormat(cal, format) { // expands unspecified or single character date formats into the full pattern. format = format || "F"; var pattern, patterns = cal.patterns, len = format.length; if ( len === 1 ) { pattern = patterns[ format ]; if ( !pattern ) { throw "Invalid date format string '" + format + "'."; } format = pattern; } else if ( len === 2 && format.charAt(0) === "%" ) { // %X escape format -- intended as a custom format string that is only one character, not a built-in format. format = format.charAt( 1 ); } return format; } function getParseRegExp(cal, format) { // converts a format string into a regular expression with groups that // can be used to extract date fields from a date string. // check for a cached parse regex. var re = cal._parseRegExp; if ( !re ) { cal._parseRegExp = re = {}; } else { var reFormat = re[ format ]; if ( reFormat ) { return reFormat; } } // expand single digit formats, then escape regular expression characters. var expFormat = expandFormat( cal, format ).replace( /([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1" ), regexp = ["^"], groups = [], index = 0, quoteCount = 0, tokenRegExp = getTokenRegExp(), match; // iterate through each date token found. while ( (match = tokenRegExp.exec( expFormat )) !== null ) { var preMatch = expFormat.slice( index, match.index ); index = tokenRegExp.lastIndex; // don't replace any matches that occur inside a string literal. quoteCount += appendPreOrPostMatch( preMatch, regexp ); if ( quoteCount % 2 ) { regexp.push( match[ 0 ] ); continue; } // add a regex group for the token. var m = match[ 0 ], len = m.length, add; switch ( m ) { case 'dddd': case 'ddd': case 'MMMM': case 'MMM': case 'gg': case 'g': add = "(\\D+)"; break; case 'tt': case 't': add = "(\\D*)"; break; case 'yyyy': case 'fff': case 'ff': case 'f': add = "(\\d{" + len + "})"; break; case 'dd': case 'd': case 'MM': case 'M': case 'yy': case 'y': case 'HH': case 'H': case 'hh': case 'h': case 'mm': case 'm': case 'ss': case 's': add = "(\\d\\d?)"; break; case 'zzz': add = "([+-]?\\d\\d?:\\d{2})"; break; case 'zz': case 'z': add = "([+-]?\\d\\d?)"; break; case '/': add = "(\\" + cal["/"] + ")"; break; default: throw "Invalid date format pattern '" + m + "'."; break; } if ( add ) { regexp.push( add ); } groups.push( match[ 0 ] ); } appendPreOrPostMatch( expFormat.slice( index ), regexp ); regexp.push( "$" ); // allow whitespace to differ when matching formats. var regexpStr = regexp.join( '' ).replace( /\s+/g, "\\s+" ), parseRegExp = {'regExp': regexpStr, 'groups': groups}; // cache the regex for this format. return re[ format ] = parseRegExp; } function getTokenRegExp() { // regular expression for matching date and time tokens in format strings. return /\/|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z|gg|g/g; } function parseExact(value, format, culture) { // try to parse the date string by matching against the format string // while using the specified culture for date field names. value = trim( value ); var cal = culture.calendar, // convert date formats into regular expressions with groupings. // use the regexp to determine the input format and extract the date fields. parseInfo = getParseRegExp(cal, format), match = new RegExp(parseInfo.regExp).exec(value); if (match === null) { return null; } // found a date format that matches the input. var groups = parseInfo.groups, era = null, year = null, month = null, date = null, weekDay = null, hour = 0, hourOffset, min = 0, sec = 0, msec = 0, tzMinOffset = null, pmHour = false; // iterate the format groups to extract and set the date fields. for ( var j = 0, jl = groups.length; j < jl; j++ ) { var matchGroup = match[ j + 1 ]; if ( matchGroup ) { var current = groups[ j ], clength = current.length, matchInt = parseInt( matchGroup, 10 ); switch ( current ) { case 'dd': case 'd': // Day of month. date = matchInt; // check that date is generally in valid range, also checking overflow below. if ( outOfRange( date, 1, 31 ) ) return null; break; case 'MMM': case 'MMMM': month = getMonthIndex( cal, matchGroup, clength === 3 ); if ( outOfRange( month, 0, 11 ) ) return null; break; case 'M': case 'MM': // Month. month = matchInt - 1; if ( outOfRange( month, 0, 11 ) ) return null; break; case 'y': case 'yy': case 'yyyy': year = clength < 4 ? expandYear( cal, matchInt ) : matchInt; if ( outOfRange( year, 0, 9999 ) ) return null; break; case 'h': case 'hh': // Hours (12-hour clock). hour = matchInt; if ( hour === 12 ) hour = 0; if ( outOfRange( hour, 0, 11 ) ) return null; break; case 'H': case 'HH': // Hours (24-hour clock). hour = matchInt; if ( outOfRange( hour, 0, 23 ) ) return null; break; case 'm': case 'mm': // Minutes. min = matchInt; if ( outOfRange( min, 0, 59 ) ) return null; break; case 's': case 'ss': // Seconds. sec = matchInt; if ( outOfRange( sec, 0, 59 ) ) return null; break; case 'tt': case 't': // AM/PM designator. // see if it is standard, upper, or lower case PM. If not, ensure it is at least one of // the AM tokens. If not, fail the parse for this format. pmHour = cal.PM && ( matchGroup === cal.PM[0] || matchGroup === cal.PM[1] || matchGroup === cal.PM[2] ); if ( !pmHour && ( !cal.AM || (matchGroup !== cal.AM[0] && matchGroup !== cal.AM[1] && matchGroup !== cal.AM[2]) ) ) return null; break; case 'f': // Deciseconds. case 'ff': // Centiseconds. case 'fff': // Milliseconds. msec = matchInt * Math.pow( 10, 3-clength ); if ( outOfRange( msec, 0, 999 ) ) return null; break; case 'ddd': // Day of week. case 'dddd': // Day of week. weekDay = getDayIndex( cal, matchGroup, clength === 3 ); if ( outOfRange( weekDay, 0, 6 ) ) return null; break; case 'zzz': // Time zone offset in +/- hours:min. var offsets = matchGroup.split( /:/ ); if ( offsets.length !== 2 ) return null; hourOffset = parseInt( offsets[ 0 ], 10 ); if ( outOfRange( hourOffset, -12, 13 ) ) return null; var minOffset = parseInt( offsets[ 1 ], 10 ); if ( outOfRange( minOffset, 0, 59 ) ) return null; tzMinOffset = (hourOffset * 60) + (startsWith( matchGroup, '-' ) ? -minOffset : minOffset); break; case 'z': case 'zz': // Time zone offset in +/- hours. hourOffset = matchInt; if ( outOfRange( hourOffset, -12, 13 ) ) return null; tzMinOffset = hourOffset * 60; break; case 'g': case 'gg': var eraName = matchGroup; if ( !eraName || !cal.eras ) return null; eraName = trim( eraName.toLowerCase() ); for ( var i = 0, l = cal.eras.length; i < l; i++ ) { if ( eraName === cal.eras[ i ].name.toLowerCase() ) { era = i; break; } } // could not find an era with that name if ( era === null ) return null; break; } } } var result = new Date(), defaultYear, convert = cal.convert; defaultYear = convert ? convert.fromGregorian( result )[ 0 ] : result.getFullYear(); if ( year === null ) { year = defaultYear; } else if ( cal.eras ) { // year must be shifted to normal gregorian year // but not if year was not specified, its already normal gregorian // per the main if clause above. year += cal.eras[ (era || 0) ].offset; } // set default day and month to 1 and January, so if unspecified, these are the defaults // instead of the current day/month. if ( month === null ) { month = 0; } if ( date === null ) { date = 1; } // now have year, month, and date, but in the culture's calendar. // convert to gregorian if necessary if ( convert ) { result = convert.toGregorian( year, month, date ); // conversion failed, must be an invalid match if ( result === null ) return null; } else { // have to set year, month and date together to avoid overflow based on current date. result.setFullYear( year, month, date ); // check to see if date overflowed for specified month (only checked 1-31 above). if ( result.getDate() !== date ) return null; // invalid day of week. if ( weekDay !== null && result.getDay() !== weekDay ) { return null; } } // if pm designator token was found make sure the hours fit the 24-hour clock. if ( pmHour && hour < 12 ) { hour += 12; } result.setHours( hour, min, sec, msec ); if ( tzMinOffset !== null ) { // adjust timezone to utc before applying local offset. var adjustedMin = result.getMinutes() - ( tzMinOffset + result.getTimezoneOffset() ); // Safari limits hours and minutes to the range of -127 to 127. We need to use setHours // to ensure both these fields will not exceed this range. adjustedMin will range // somewhere between -1440 and 1500, so we only need to split this into hours. result.setHours( result.getHours() + parseInt( adjustedMin / 60, 10 ), adjustedMin % 60 ); } return result; } function formatDate(value, format, culture) { var cal = culture.calendar, convert = cal.convert; if ( !format || !format.length || format === 'i' ) { var ret; if ( culture && culture.name.length ) { if ( convert ) { // non-gregorian calendar, so we cannot use built-in toLocaleString() ret = formatDate( value, cal.patterns.F, culture ); } else { var eraDate = new Date( value.getTime() ), era = getEra( value, cal.eras ); eraDate.setFullYear( getEraYear( value, cal, era ) ); ret = eraDate.toLocaleString(); } } else { ret = value.toString(); } return ret; } var eras = cal.eras, sortable = format === "s"; format = expandFormat( cal, format ); // Start with an empty string ret = []; var hour, zeros = ['0','00','000'], foundDay, checkedDay, dayPartRegExp = /([^d]|^)(d|dd)([^d]|$)/g, quoteCount = 0, tokenRegExp = getTokenRegExp(), converted; function padZeros(num, c) { var r, s = num+''; if ( c > 1 && s.length < c ) { r = ( zeros[ c - 2 ] + s); return r.substr( r.length - c, c ); } else { r = s; } return r; } function hasDay() { if ( foundDay || checkedDay ) { return foundDay; } foundDay = dayPartRegExp.test( format ); checkedDay = true; return foundDay; } function getPart( date, part ) { if ( converted ) { return converted[ part ]; } switch ( part ) { case 0: return date.getFullYear(); case 1: return date.getMonth(); case 2: return date.getDate(); } } if ( !sortable && convert ) { converted = convert.fromGregorian( value ); } for (;;) { // Save the current index var index = tokenRegExp.lastIndex, // Look for the next pattern ar = tokenRegExp.exec( format ); // Append the text before the pattern (or the end of the string if not found) var preMatch = format.slice( index, ar ? ar.index : format.length ); quoteCount += appendPreOrPostMatch( preMatch, ret ); if ( !ar ) { break; } // do not replace any matches that occur inside a string literal. if ( quoteCount % 2 ) { ret.push( ar[ 0 ] ); continue; } var current = ar[ 0 ], clength = current.length; switch ( current ) { case "ddd": //Day of the week, as a three-letter abbreviation case "dddd": // Day of the week, using the full name var names = (clength === 3) ? cal.days.namesAbbr : cal.days.names; ret.push( names[ value.getDay() ] ); break; case "d": // Day of month, without leading zero for single-digit days case "dd": // Day of month, with leading zero for single-digit days foundDay = true; ret.push( padZeros( getPart( value, 2 ), clength ) ); break; case "MMM": // Month, as a three-letter abbreviation case "MMMM": // Month, using the full name var part = getPart( value, 1 ); ret.push( (cal.monthsGenitive && hasDay()) ? cal.monthsGenitive[ clength === 3 ? "namesAbbr" : "names" ][ part ] : cal.months[ clength === 3 ? "namesAbbr" : "names" ][ part ] ); break; case "M": // Month, as digits, with no leading zero for single-digit months case "MM": // Month, as digits, with leading zero for single-digit months ret.push( padZeros( getPart( value, 1 ) + 1, clength ) ); break; case "y": // Year, as two digits, but with no leading zero for years less than 10 case "yy": // Year, as two digits, with leading zero for years less than 10 case "yyyy": // Year represented by four full digits part = converted ? converted[ 0 ] : getEraYear( value, cal, getEra( value, eras ), sortable ); if ( clength < 4 ) { part = part % 100; } ret.push( padZeros( part, clength ) ); break; case "h": // Hours with no leading zero for single-digit hours, using 12-hour clock case "hh": // Hours with leading zero for single-digit hours, using 12-hour clock hour = value.getHours() % 12; if ( hour === 0 ) hour = 12; ret.push( padZeros( hour, clength ) ); break; case "H": // Hours with no leading zero for single-digit hours, using 24-hour clock case "HH": // Hours with leading zero for single-digit hours, using 24-hour clock ret.push( padZeros( value.getHours(), clength ) ); break; case "m": // Minutes with no leading zero for single-digit minutes case "mm": // Minutes with leading zero for single-digit minutes ret.push( padZeros( value.getMinutes(), clength ) ); break; case "s": // Seconds with no leading zero for single-digit seconds case "ss": // Seconds with leading zero for single-digit seconds ret.push( padZeros(value .getSeconds(), clength ) ); break; case "t": // One character am/pm indicator ("a" or "p") case "tt": // Multicharacter am/pm indicator part = value.getHours() < 12 ? (cal.AM ? cal.AM[0] : " ") : (cal.PM ? cal.PM[0] : " "); ret.push( clength === 1 ? part.charAt( 0 ) : part ); break; case "f": // Deciseconds case "ff": // Centiseconds case "fff": // Milliseconds ret.push( padZeros( value.getMilliseconds(), 3 ).substr( 0, clength ) ); break; case "z": // Time zone offset, no leading zero case "zz": // Time zone offset with leading zero hour = value.getTimezoneOffset() / 60; ret.push( (hour <= 0 ? '+' : '-') + padZeros( Math.floor( Math.abs( hour ) ), clength ) ); break; case "zzz": // Time zone offset with leading zero hour = value.getTimezoneOffset() / 60; ret.push( (hour <= 0 ? '+' : '-') + padZeros( Math.floor( Math.abs( hour ) ), 2 ) + // Hard coded ":" separator, rather than using cal.TimeSeparator // Repeated here for consistency, plus ":" was already assumed in date parsing. ":" + padZeros( Math.abs( value.getTimezoneOffset() % 60 ), 2 ) ); break; case "g": case "gg": if ( cal.eras ) { ret.push( cal.eras[ getEra(value, eras) ].name ); } break; case "/": ret.push( cal["/"] ); break; default: throw "Invalid date format pattern '" + current + "'."; break; } } return ret.join( '' ); } // EXPORTS jQuery.global = globalization; })();
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["it-IT"] = $.extend(true, {}, en, { name: "it-IT", englishName: "Italian (Italy)", nativeName: "italiano (Italia)", language: "it", numberFormat: { ',': ".", '.': ",", percent: { pattern: ["-n%","n%"], ',': ".", '.': "," }, currency: { pattern: ["-$ n","$ n"], ',': ".", '.': ",", symbol: "€" } }, calendars: { standard: $.extend(true, {}, standard, { firstDay: 1, days: { names: ["domenica","lunedì","martedì","mercoledì","giovedì","venerdì","sabato"], namesAbbr: ["dom","lun","mar","mer","gio","ven","sab"], namesShort: ["do","lu","ma","me","gi","ve","sa"] }, months: { names: ["gennaio","febbraio","marzo","aprile","maggio","giugno","luglio","agosto","settembre","ottobre","novembre","dicembre",""], namesAbbr: ["gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic",""] }, AM: null, PM: null, eras: [{"name":"d.C.","start":null,"offset":0}], patterns: { d: "dd/MM/yyyy", D: "dddd d MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd d MMMM yyyy HH:mm", F: "dddd d MMMM yyyy HH:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } }) } }, cultures["it-IT"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["he-IL"] = $.extend(true, {}, en, { name: "he-IL", englishName: "Hebrew (Israel)", nativeName: "עברית (ישראל)", language: "he", isRTL: true, numberFormat: { percent: { pattern: ["-n%","n%"] }, currency: { pattern: ["$-n","$ n"], symbol: "₪" } }, calendars: { standard: $.extend(true, {}, standard, { days: { names: ["יום ראשון","יום שני","יום שלישי","יום רביעי","יום חמישי","יום שישי","שבת"], namesAbbr: ["יום א","יום ב","יום ג","יום ד","יום ה","יום ו","שבת"], namesShort: ["א","ב","ג","ד","ה","ו","ש"] }, months: { names: ["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר",""], namesAbbr: ["ינו","פבר","מרץ","אפר","מאי","יונ","יול","אוג","ספט","אוק","נוב","דצמ",""] }, eras: [{"name":"לספירה","start":null,"offset":0}], patterns: { d: "dd/MM/yyyy", D: "dddd dd MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd dd MMMM yyyy HH:mm", F: "dddd dd MMMM yyyy HH:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } }), Hebrew: $.extend(true, {}, standard, { name: "Hebrew", '/': " ", days: { names: ["יום ראשון","יום שני","יום שלישי","יום רביעי","יום חמישי","יום שישי","שבת"], namesAbbr: ["א","ב","ג","ד","ה","ו","ש"], namesShort: ["א","ב","ג","ד","ה","ו","ש"] }, months: { names: ["תשרי","חשון","כסלו","טבת","שבט","אדר","אדר ב","ניסן","אייר","סיון","תמוז","אב","אלול"], namesAbbr: ["תשרי","חשון","כסלו","טבת","שבט","אדר","אדר ב","ניסן","אייר","סיון","תמוז","אב","אלול"] }, eras: [{"name":"C.E.","start":null,"offset":0}], twoDigitYearMax: 5790, patterns: { d: "dd MMMM yyyy", D: "dddd dd MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd dd MMMM yyyy HH:mm", F: "dddd dd MMMM yyyy HH:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } }) } }, cultures["he-IL"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["sa-IN"] = $.extend(true, {}, en, { name: "sa-IN", englishName: "Sanskrit (India)", nativeName: "संस्कृत (भारतम्)", language: "sa", numberFormat: { groupSizes: [3,2], percent: { groupSizes: [3,2] }, currency: { pattern: ["$ -n","$ n"], groupSizes: [3,2], symbol: "रु" } }, calendars: { standard: $.extend(true, {}, standard, { '/': "-", days: { names: ["रविवासरः","सोमवासरः","मङ्गलवासरः","बुधवासरः","गुरुवासरः","शुक्रवासरः","शनिवासरः"], namesAbbr: ["रविवासरः","सोमवासरः","मङ्गलवासरः","बुधवासरः","गुरुवासरः","शुक्रवासरः","शनिवासरः"], namesShort: ["र","स","म","ब","ग","श","श"] }, months: { names: ["जनवरी","फरवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्तूबर","नवम्बर","दिसम्बर",""], namesAbbr: ["जनवरी","फरवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्तूबर","नवम्बर","दिसम्बर",""] }, AM: ["पूर्वाह्न","पूर्वाह्न","पूर्वाह्न"], PM: ["अपराह्न","अपराह्न","अपराह्न"], patterns: { d: "dd-MM-yyyy", D: "dd MMMM yyyy dddd", t: "HH:mm", T: "HH:mm:ss", f: "dd MMMM yyyy dddd HH:mm", F: "dd MMMM yyyy dddd HH:mm:ss", M: "dd MMMM" } }) } }, cultures["sa-IN"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["hr"] = $.extend(true, {}, en, { name: "hr", englishName: "Croatian", nativeName: "hrvatski", language: "hr", numberFormat: { pattern: ["- n"], ',': ".", '.': ",", percent: { pattern: ["-n%","n%"], ',': ".", '.': "," }, currency: { pattern: ["-n $","n $"], ',': ".", '.': ",", symbol: "kn" } }, calendars: { standard: $.extend(true, {}, standard, { '/': ".", firstDay: 1, days: { names: ["nedjelja","ponedjeljak","utorak","srijeda","četvrtak","petak","subota"], namesAbbr: ["ned","pon","uto","sri","čet","pet","sub"], namesShort: ["ne","po","ut","sr","če","pe","su"] }, months: { names: ["siječanj","veljača","ožujak","travanj","svibanj","lipanj","srpanj","kolovoz","rujan","listopad","studeni","prosinac",""], namesAbbr: ["sij","vlj","ožu","tra","svi","lip","srp","kol","ruj","lis","stu","pro",""] }, monthsGenitive: { names: ["siječnja","veljače","ožujka","travnja","svibnja","lipnja","srpnja","kolovoza","rujna","listopada","studenog","prosinca",""], namesAbbr: ["sij","vlj","ožu","tra","svi","lip","srp","kol","ruj","lis","stu","pro",""] }, AM: null, PM: null, patterns: { d: "d.M.yyyy.", D: "d. MMMM yyyy.", t: "H:mm", T: "H:mm:ss", f: "d. MMMM yyyy. H:mm", F: "d. MMMM yyyy. H:mm:ss", M: "d. MMMM" } }) } }, cultures["hr"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
if (typeof RedactorPlugins === 'undefined') var RedactorPlugins = {}; RedactorPlugins.fullscreen = { init: function() { this.fullscreen = false; this.addBtn('fullscreen', 'Fullscreen', function(obj) { obj.toggleFullscreen(); }); this.setBtnRight('fullscreen'); }, toggleFullscreen: function() { var html; if (this.fullscreen === false) { this.changeBtnIcon('fullscreen', 'normalscreen'); this.setBtnActive('fullscreen'); this.fullscreen = true; this.fsheight = this.$editor.height(); this.tmpspan = $('<span></span>'); this.$box.addClass('redactor_box_fullscreen').after(this.tmpspan); $('body, html').css('overflow', 'hidden'); $('body').prepend(this.$box); this.fullScreenResize(); $(window).resize($.proxy(this.fullScreenResize, this)); $(document).scrollTop(0,0); this.$editor.focus(); } else { this.removeBtnIcon('fullscreen', 'normalscreen'); this.setBtnInactive('fullscreen'); this.fullscreen = false; $(window).unbind('resize', $.proxy(this.fullScreenResize, this)); $('body, html').css('overflow', ''); this.$box.removeClass('redactor_box_fullscreen').css({ width: 'auto', height: 'auto' }); this.tmpspan.after(this.$box).remove(); this.syncCode(); if (this.opts.autoresize) { this.$el.css('height', 'auto'); this.$editor.css('height', 'auto') } else { this.$el.css('height', this.fsheight); this.$editor.css('height', this.fsheight) } this.$editor.focus(); } }, fullScreenResize: function() { if (this.fullscreen === false) { return false; } var pad = this.$editor.css('padding-top').replace('px', ''); var height = $(window).height() - 34; this.$box.width($(window).width() - 2).height(height+34); this.$editor.height(height-(pad*2)); this.$el.height(height); }, }
JavaScript
if (typeof RedactorPlugins === 'undefined') var RedactorPlugins = {}; RedactorPlugins.advanced = { init: function() { var Redactor=this; this.addBtnBefore('video', 'plugin_img', 'Insert Image', function(obj) { Redactor.saveSelection(); if($("#redactor_advanced_img").length==0){ $('body').append( '<div id="redactor_advanced_img">\ <div class="grid_9">\ <div class="pr20">\ <table class="w100pc">\ <tr>\ <td>Image Url</td>\ <td class="pr"><form name="frmredactor_advanced_img">\ <div class="pr">\ <input type="text" id="redactor_advanced_img_src" class="classic-input w100pc mb8" />\ <div class="pa hover50 icon16 chooseimage chooseimage_icon"\ onclick="redactorBrowse()"\ title="Choose image from my host"\ ></div>\ </div>\ </form>\ </td>\ </tr>\ <tr>\ <td>Width</td>\ <td><input type="number" id="redactor_advanced_img_w" class="classic-input w100pc mb8" /></td>\ </tr>\ <tr>\ <td>Height</td>\ <td><input type="number" id="redactor_advanced_img_h" class="classic-input w100pc mb8" /></td>\ </tr>\ <tr>\ <td>&nbsp;</td>\ <td><input type="checkbox" checked=1 id="redactor_advanced_img_c"/><label for="">Classic Image</label></td>\ </tr>\ </table>\ </div>\ </div>\ </div>'); } $("#redactor_advanced_img_src").val(""); $("#redactor_advanced_img_w").val(""); $("#redactor_advanced_img_w").val(""); ShowConfirmDialogMessage($("#redactor_advanced_img"), "Insert Image ",function(){ try{ var src=$("#redactor_advanced_img_src").val(),str=""; var w=parseInt($("#redactor_advanced_img_w").val()); var h=parseInt($("#redactor_advanced_img_h").val()); if (w>0){ if(w>500) w=500; str+= ' width:'+w+'px;'; } if (h>0){ if(h>500) h=500; str+= ' height:'+h+'px;'; } if ($('#redactor_advanced_img_c').is(':checked')) { str+= ' margin:0 auto;display:block;border:1px solid #ccc;padding:4px;background:#fff'; } Redactor.restoreSelection(); if(src!=""){ obj.insertHtml('<img src="'+src+'" style="max-with:500px;'+str+'"/>'); CloseConfirmDialogMessage($("#redactor_advanced_img")); } }catch(e){} }); $("#redactor_advanced_img_src").focus(); }); //this.addBtnSeparatorBefore('advanced'); }, insertClip: function(html) { this.restoreSelection(); this.execCommand('inserthtml', html); this.modalClose(); } } function redactorBrowse(){ BrowseServer('redactor_advanced_img_src' ); }
JavaScript
if (typeof RedactorPlugins === 'undefined') var RedactorPlugins = {}; RedactorPlugins.advanced = { init: function() { this.addBtnAfter('link', 'advanced', 'Advanced', function(obj) { obj.insertHtml('<b>It\'s awesome!</b> '); }); this.addBtnSeparatorBefore('advanced'); } }
JavaScript
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */ /* * jQuery MultiSelect UI Widget 1.14pre * Copyright (c) 2012 Eric Hynds * * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ * * Depends: * - jQuery 1.4.2+ * - jQuery UI 1.8 widget factory * * Optional: * - jQuery UI effects * - jQuery UI position utility * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ (function($, undefined) { var multiselectID = 0; var $doc = $(document); $.widget("ech.multiselect", { // default options options: { header: true, height: 175, minWidth: 225, classes: '', checkAllText: 'Check all', uncheckAllText: 'Uncheck all', noneSelectedText: 'Select options', selectedText: '# selected', selectedList: 0, show: null, hide: null, autoOpen: false, multiple: true, position: {} }, _create: function() { var el = this.element.hide(); var o = this.options; this.speed = $.fx.speeds._default; // default speed for effects this._isOpen = false; // assume no // create a unique namespace for events that the widget // factory cannot unbind automatically. Use eventNamespace if on // jQuery UI 1.9+, and otherwise fallback to a custom string. this._namespaceID = this.eventNamespace || ('multiselect' + multiselectID); var button = (this.button = $('<button type="button"><span class="ui-icon ui-icon-triangle-1-s"></span></button>')) .addClass('ui-multiselect ui-widget ui-state-default ui-corner-all') .addClass(o.classes) .attr({ 'title':el.attr('title'), 'aria-haspopup':true, 'tabIndex':el.attr('tabIndex') }) .insertAfter(el), buttonlabel = (this.buttonlabel = $('<span />')) .html(o.noneSelectedText) .appendTo(button), menu = (this.menu = $('<div />')) .addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all') .addClass(o.classes) .appendTo(document.body), header = (this.header = $('<div />')) .addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix') .appendTo(menu), headerLinkContainer = (this.headerLinkContainer = $('<ul />')) .addClass('ui-helper-reset') .html(function() { if(o.header === true) { return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>'; } else if(typeof o.header === "string") { return '<li>' + o.header + '</li>'; } else { return ''; } }) .append('<li class="ui-multiselect-close"><a href="#" class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></a></li>') .appendTo(header), checkboxContainer = (this.checkboxContainer = $('<ul />')) .addClass('ui-multiselect-checkboxes ui-helper-reset') .appendTo(menu); // perform event bindings this._bindEvents(); // build menu this.refresh(true); // some addl. logic for single selects if(!o.multiple) { menu.addClass('ui-multiselect-single'); } // bump unique ID multiselectID++; }, _init: function() { if(this.options.header === false) { this.header.hide(); } if(!this.options.multiple) { this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide(); } if(this.options.autoOpen) { this.open(); } if(this.element.is(':disabled')) { this.disable(); } }, refresh: function(init) { var el = this.element; var o = this.options; var menu = this.menu; var checkboxContainer = this.checkboxContainer; var optgroups = []; var html = ""; var id = el.attr('id') || multiselectID++; // unique ID for the label & option tags // build items el.find('option').each(function(i) { var $this = $(this); var parent = this.parentNode; var title = this.innerHTML; var description = this.title; var value = this.value; var inputID = 'ui-multiselect-' + (this.id || id + '-option-' + i); var isDisabled = this.disabled; var isSelected = this.selected; var labelClasses = [ 'ui-corner-all' ]; var liClasses = (isDisabled ? 'ui-multiselect-disabled ' : ' ') + this.className; var optLabel; // is this an optgroup? if(parent.tagName === 'OPTGROUP') { optLabel = parent.getAttribute('label'); // has this optgroup been added already? if($.inArray(optLabel, optgroups) === -1) { html += '<li class="ui-multiselect-optgroup-label ' + parent.className + '"><a href="#">' + optLabel + '</a></li>'; optgroups.push(optLabel); } } if(isDisabled) { labelClasses.push('ui-state-disabled'); } // browsers automatically select the first option // by default with single selects if(isSelected && !o.multiple) { labelClasses.push('ui-state-active'); } html += '<li class="' + liClasses + '">'; // create the label html += '<label for="' + inputID + '" title="' + description + '" class="' + labelClasses.join(' ') + '">'; html += '<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"'; // pre-selected? if(isSelected) { html += ' checked="checked"'; html += ' aria-selected="true"'; } // disabled? if(isDisabled) { html += ' disabled="disabled"'; html += ' aria-disabled="true"'; } // add the title and close everything off html += ' /><span>' + title + '</span></label></li>'; }); // insert into the DOM checkboxContainer.html(html); // cache some moar useful elements this.labels = menu.find('label'); this.inputs = this.labels.children('input'); // set widths this._setButtonWidth(); this._setMenuWidth(); // remember default value this.button[0].defaultValue = this.update(); // broadcast refresh event; useful for widgets if(!init) { this._trigger('refresh'); } }, // updates the button text. call refresh() to rebuild update: function() { var o = this.options; var $inputs = this.inputs; var $checked = $inputs.filter(':checked'); var numChecked = $checked.length; var value; if(numChecked === 0) { value = o.noneSelectedText; } else { if($.isFunction(o.selectedText)) { value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get()); } else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) { value = $checked.map(function() { return $(this).next().html(); }).get().join(', '); } else { value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length); } } this._setButtonValue(value); return value; }, // this exists as a separate method so that the developer // can easily override it. _setButtonValue: function(value) { this.buttonlabel.text(value); }, // binds events _bindEvents: function() { var self = this; var button = this.button; function clickHandler() { self[ self._isOpen ? 'close' : 'open' ](); return false; } // webkit doesn't like it when you click on the span :( button .find('span') .bind('click.multiselect', clickHandler); // button events button.bind({ click: clickHandler, keypress: function(e) { switch(e.which) { case 27: // esc case 38: // up case 37: // left self.close(); break; case 39: // right case 40: // down self.open(); break; } }, mouseenter: function() { if(!button.hasClass('ui-state-disabled')) { $(this).addClass('ui-state-hover'); } }, mouseleave: function() { $(this).removeClass('ui-state-hover'); }, focus: function() { if(!button.hasClass('ui-state-disabled')) { $(this).addClass('ui-state-focus'); } }, blur: function() { $(this).removeClass('ui-state-focus'); } }); // header links this.header.delegate('a', 'click.multiselect', function(e) { // close link if($(this).hasClass('ui-multiselect-close')) { self.close(); // check all / uncheck all } else { self[$(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll'](); } e.preventDefault(); }); // optgroup label toggle support this.menu.delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function(e) { e.preventDefault(); var $this = $(this); var $inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)'); var nodes = $inputs.get(); var label = $this.parent().text(); // trigger event and bail if the return is false if(self._trigger('beforeoptgrouptoggle', e, { inputs:nodes, label:label }) === false) { return; } // toggle inputs self._toggleChecked( $inputs.filter(':checked').length !== $inputs.length, $inputs ); self._trigger('optgrouptoggle', e, { inputs: nodes, label: label, checked: nodes[0].checked }); }) .delegate('label', 'mouseenter.multiselect', function() { if(!$(this).hasClass('ui-state-disabled')) { self.labels.removeClass('ui-state-hover'); $(this).addClass('ui-state-hover').find('input').focus(); } }) .delegate('label', 'keydown.multiselect', function(e) { e.preventDefault(); switch(e.which) { case 9: // tab case 27: // esc self.close(); break; case 38: // up case 40: // down case 37: // left case 39: // right self._traverse(e.which, this); break; case 13: // enter $(this).find('input')[0].click(); break; } }) .delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function(e) { var $this = $(this); var val = this.value; var checked = this.checked; var tags = self.element.find('option'); // bail if this input is disabled or the event is cancelled if(this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false) { e.preventDefault(); return; } // make sure the input has focus. otherwise, the esc key // won't close the menu after clicking an item. $this.focus(); // toggle aria state $this.attr('aria-selected', checked); // change state on the original option tags tags.each(function() { if(this.value === val) { this.selected = checked; } else if(!self.options.multiple) { this.selected = false; } }); // some additional single select-specific logic if(!self.options.multiple) { self.labels.removeClass('ui-state-active'); $this.closest('label').toggleClass('ui-state-active', checked); // close menu self.close(); } // fire change on the select box self.element.trigger("change"); // setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827 // http://bugs.jquery.com/ticket/3827 setTimeout($.proxy(self.update, self), 10); }); // close each widget when clicking on any other element/anywhere else on the page $doc.bind('mousedown.' + this._namespaceID, function(event) { var target = event.target; if(self._isOpen && !$.contains(self.menu[0], target) && !$.contains(self.button[0], target) && target !== self.button[0] && target !== self.menu[0]) { self.close(); } }); // deal with form resets. the problem here is that buttons aren't // restored to their defaultValue prop on form reset, and the reset // handler fires before the form is actually reset. delaying it a bit // gives the form inputs time to clear. $(this.element[0].form).bind('reset.multiselect', function() { setTimeout($.proxy(self.refresh, self), 10); }); }, // set button width _setButtonWidth: function() { var width = this.element.outerWidth(); var o = this.options; if(/\d/.test(o.minWidth) && width < o.minWidth) { width = o.minWidth; } // set widths this.button.outerWidth(width); }, // set menu width _setMenuWidth: function() { var m = this.menu; m.outerWidth(this.button.outerWidth()); }, // move up or down within the menu _traverse: function(which, start) { var $start = $(start); var moveToLast = which === 38 || which === 37; // select the first li that isn't an optgroup label / disabled $next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)')[ moveToLast ? 'last' : 'first'](); // if at the first/last element if(!$next.length) { var $container = this.menu.find('ul').last(); // move to the first/last this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover'); // set scroll position $container.scrollTop(moveToLast ? $container.height() : 0); } else { $next.find('label').trigger('mouseover'); } }, // This is an internal function to toggle the checked property and // other related attributes of a checkbox. // // The context of this function should be a checkbox; do not proxy it. _toggleState: function(prop, flag) { return function() { if(!this.disabled) { this[ prop ] = flag; } if(flag) { this.setAttribute('aria-selected', true); } else { this.removeAttribute('aria-selected'); } }; }, _toggleChecked: function(flag, group) { var $inputs = (group && group.length) ? group : this.inputs; var self = this; // toggle state on inputs $inputs.each(this._toggleState('checked', flag)); // give the first input focus $inputs.eq(0).focus(); // update button text this.update(); // gather an array of the values that actually changed var values = $inputs.map(function() { return this.value; }).get(); // toggle state on original option tags this.element .find('option') .each(function() { if(!this.disabled && $.inArray(this.value, values) > -1) { self._toggleState('selected', flag).call(this); } }); // trigger the change event on the select if($inputs.length) { this.element.trigger("change"); } }, _toggleDisabled: function(flag) { this.button.attr({ 'disabled':flag, 'aria-disabled':flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled'); var inputs = this.menu.find('input'); var key = "ech-multiselect-disabled"; if(flag) { // remember which elements this widget disabled (not pre-disabled) // elements, so that they can be restored if the widget is re-enabled. inputs = inputs.filter(':enabled').data(key, true) } else { inputs = inputs.filter(function() { return $.data(this, key) === true; }).removeData(key); } inputs .attr({ 'disabled':flag, 'arial-disabled':flag }) .parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled'); this.element.attr({ 'disabled':flag, 'aria-disabled':flag }); }, // open the menu open: function(e) { var self = this; var button = this.button; var menu = this.menu; var speed = this.speed; var o = this.options; var args = []; // bail if the multiselectopen event returns false, this widget is disabled, or is already open if(this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen) { return; } var $container = menu.find('ul').last(); var effect = o.show; // figure out opening effects/speeds if($.isArray(o.show)) { effect = o.show[0]; speed = o.show[1] || self.speed; } // if there's an effect, assume jQuery UI is in use // build the arguments to pass to show() if(effect) { args = [ effect, speed ]; } // set the scroll of the checkbox container $container.scrollTop(0).height(o.height); // positon this.position(); // show the menu, maybe with a speed/effect combo $.fn.show.apply(menu, args); // select the first not disabled option // triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover // will actually trigger mouseenter. the mouseenter trigger is there for when it's eventually fixed this.labels.filter(':not(.ui-state-disabled)').eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus'); button.addClass('ui-state-active'); this._isOpen = true; this._trigger('open'); }, // close the menu close: function() { if(this._trigger('beforeclose') === false) { return; } var o = this.options; var effect = o.hide; var speed = this.speed; var args = []; // figure out opening effects/speeds if($.isArray(o.hide)) { effect = o.hide[0]; speed = o.hide[1] || this.speed; } if(effect) { args = [ effect, speed ]; } $.fn.hide.apply(this.menu, args); this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave'); this._isOpen = false; this._trigger('close'); }, enable: function() { this._toggleDisabled(false); }, disable: function() { this._toggleDisabled(true); }, checkAll: function(e) { this._toggleChecked(true); this._trigger('checkAll'); }, uncheckAll: function() { this._toggleChecked(false); this._trigger('uncheckAll'); }, getChecked: function() { return this.menu.find('input').filter(':checked'); }, destroy: function() { // remove classes + data $.Widget.prototype.destroy.call(this); // unbind events $doc.unbind(this._namespaceID); this.button.remove(); this.menu.remove(); this.element.show(); return this; }, isOpen: function() { return this._isOpen; }, widget: function() { return this.menu; }, getButton: function() { return this.button; }, position: function() { var o = this.options; // use the position utility if it exists and options are specifified if($.ui.position && !$.isEmptyObject(o.position)) { o.position.of = o.position.of || this.button; this.menu .show() .position(o.position) .hide(); // otherwise fallback to custom positioning } else { var pos = this.button.offset(); this.menu.css({ top: pos.top + this.button.outerHeight(), left: pos.left }); } }, // react to option changes after initialization _setOption: function(key, value) { var menu = this.menu; switch(key) { case 'header': menu.find('div.ui-multiselect-header')[value ? 'show' : 'hide'](); break; case 'checkAllText': menu.find('a.ui-multiselect-all span').eq(-1).text(value); break; case 'uncheckAllText': menu.find('a.ui-multiselect-none span').eq(-1).text(value); break; case 'height': menu.find('ul').last().height(parseInt(value, 10)); break; case 'minWidth': this.options[key] = parseInt(value, 10); this._setButtonWidth(); this._setMenuWidth(); break; case 'selectedText': case 'selectedList': case 'noneSelectedText': this.options[key] = value; // these all needs to update immediately for the update() call this.update(); break; case 'classes': menu.add(this.button).removeClass(this.options.classes).addClass(value); break; case 'multiple': menu.toggleClass('ui-multiselect-single', !value); this.options.multiple = value; this.element[0].multiple = value; this.refresh(); break; case 'position': this.position(); } $.Widget.prototype._setOption.apply(this, arguments); } }); })(jQuery);
JavaScript
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */ /* * jQuery MultiSelect UI Widget Filtering Plugin 1.5pre * Copyright (c) 2012 Eric Hynds * * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ * * Depends: * - jQuery UI MultiSelect widget * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ (function($) { var rEscape = /[\-\[\]{}()*+?.,\\\^$|#\s]/g; $.widget('ech.multiselectfilter', { options: { label: 'Filter:', width: null, /* override default width set in css file (px). null will inherit */ placeholder: 'Enter keywords', autoReset: false }, _create: function() { var opts = this.options; var elem = $(this.element); // get the multiselect instance var instance = (this.instance = (elem.data('echMultiselect') || elem.data("multiselect"))); // store header; add filter class so the close/check all/uncheck all links can be positioned correctly var header = (this.header = instance.menu.find('.ui-multiselect-header').addClass('ui-multiselect-hasfilter')); // wrapper elem var wrapper = (this.wrapper = $('<div class="ui-multiselect-filter">' + (opts.label.length ? opts.label : '') + '<input placeholder="'+opts.placeholder+'" type="search"' + (/\d/.test(opts.width) ? 'style="width:'+opts.width+'px"' : '') + ' /></div>').prependTo(this.header)); // reference to the actual inputs this.inputs = instance.menu.find('input[type="checkbox"], input[type="radio"]'); // build the input box this.input = wrapper.find('input').bind({ keydown: function(e) { // prevent the enter key from submitting the form / closing the widget if(e.which === 13) { e.preventDefault(); } }, keyup: $.proxy(this._handler, this), click: $.proxy(this._handler, this) }); // cache input values for searching this.updateCache(); // rewrite internal _toggleChecked fn so that when checkAll/uncheckAll is fired, // only the currently filtered elements are checked instance._toggleChecked = function(flag, group) { var $inputs = (group && group.length) ? group : this.labels.find('input'); var _self = this; // do not include hidden elems if the menu isn't open. var selector = instance._isOpen ? ':disabled, :hidden' : ':disabled'; $inputs = $inputs .not(selector) .each(this._toggleState('checked', flag)); // update text this.update(); // gather an array of the values that actually changed var values = $inputs.map(function() { return this.value; }).get(); // select option tags this.element.find('option').filter(function() { if(!this.disabled && $.inArray(this.value, values) > -1) { _self._toggleState('selected', flag).call(this); } }); // trigger the change event on the select if($inputs.length) { this.element.trigger('change'); } }; // rebuild cache when multiselect is updated var doc = $(document).bind('multiselectrefresh', $.proxy(function() { this.updateCache(); this._handler(); }, this)); // automatically reset the widget on close? if(this.options.autoReset) { doc.bind('multiselectclose', $.proxy(this._reset, this)); } }, // thx for the logic here ben alman _handler: function(e) { var term = $.trim(this.input[0].value.toLowerCase()), // speed up lookups rows = this.rows, inputs = this.inputs, cache = this.cache; if(!term) { rows.show(); } else { rows.hide(); var regex = new RegExp(term.replace(rEscape, "\\$&"), 'gi'); this._trigger("filter", e, $.map(cache, function(v, i) { if(v.search(regex) !== -1) { rows.eq(i).show(); return inputs.get(i); } return null; })); } // show/hide optgroups this.instance.menu.find(".ui-multiselect-optgroup-label").each(function() { var $this = $(this); var isVisible = $this.nextUntil('.ui-multiselect-optgroup-label').filter(function() { return $.css(this, "display") !== 'none'; }).length; $this[isVisible ? 'show' : 'hide'](); }); }, _reset: function() { this.input.val('').trigger('keyup'); }, updateCache: function() { // each list item this.rows = this.instance.menu.find(".ui-multiselect-checkboxes li:not(.ui-multiselect-optgroup-label)"); // cache this.cache = this.element.children().map(function() { var elem = $(this); // account for optgroups if(this.tagName.toLowerCase() === "optgroup") { elem = elem.children(); } return elem.map(function() { return this.innerHTML.toLowerCase(); }).get(); }).get(); }, widget: function() { return this.wrapper; }, destroy: function() { $.Widget.prototype.destroy.call(this); this.input.val('').trigger("keyup"); this.wrapper.remove(); } }); })(jQuery);
JavaScript
// Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * some functions for browser-side pretty printing of code contained in html. * <p> * * For a fairly comprehensive set of languages see the * <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a> * file that came with this source. At a minimum, the lexer should work on a * number of languages including C and friends, Java, Python, Bash, SQL, HTML, * XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk * and a subset of Perl, but, because of commenting conventions, doesn't work on * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class. * <p> * Usage: <ol> * <li> include this source file in an html page via * {@code <script type="text/javascript" src="/path/to/prettify.js"></script>} * <li> define style rules. See the example page for examples. * <li> mark the {@code <pre>} and {@code <code>} tags in your source with * {@code class=prettyprint.} * You can also use the (html deprecated) {@code <xmp>} tag, but the pretty * printer needs to do more substantial DOM manipulations to support that, so * some css styles may not be preserved. * </ol> * That's it. I wanted to keep the API as simple as possible, so there's no * need to specify which language the code is in, but if you wish, you can add * another class to the {@code <pre>} or {@code <code>} element to specify the * language, as in {@code <pre class="prettyprint lang-java">}. Any class that * starts with "lang-" followed by a file extension, specifies the file type. * See the "lang-*.js" files in this directory for code that implements * per-language file handlers. * <p> * Change log:<br> * cbeust, 2006/08/22 * <blockquote> * Java annotations (start with "@") are now captured as literals ("lit") * </blockquote> * @requires console * @overrides window */ // JSLint declarations /*global console, document, navigator, setTimeout, window */ /** * Split {@code prettyPrint} into multiple timeouts so as not to interfere with * UI events. * If set to {@code false}, {@code prettyPrint()} is synchronous. */ window['PR_SHOULD_USE_CONTINUATION'] = true; /** the number of characters between tab columns */ window['PR_TAB_WIDTH'] = 8; /** Walks the DOM returning a properly escaped version of innerHTML. * @param {Node} node * @param {Array.<string>} out output buffer that receives chunks of HTML. */ window['PR_normalizedHtml'] /** Contains functions for creating and registering new language handlers. * @type {Object} */ = window['PR'] /** Pretty print a chunk of code. * * @param {string} sourceCodeHtml code as html * @return {string} code as html, but prettier */ = window['prettyPrintOne'] /** Find all the {@code <pre>} and {@code <code>} tags in the DOM with * {@code class=prettyprint} and prettify them. * @param {Function?} opt_whenDone if specified, called when the last entry * has been finished. */ = window['prettyPrint'] = void 0; /** browser detection. @extern @returns false if not IE, otherwise the major version. */ window['_pr_isIE6'] = function () { var ieVersion = navigator && navigator.userAgent && navigator.userAgent.match(/\bMSIE ([678])\./); ieVersion = ieVersion ? +ieVersion[1] : false; window['_pr_isIE6'] = function () { return ieVersion; }; return ieVersion; }; (function () { // Keyword lists for various languages. var FLOW_CONTROL_KEYWORDS = "break continue do else for if return while "; var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " + "double enum extern float goto int long register short signed sizeof " + "static struct switch typedef union unsigned void volatile "; var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " + "new operator private protected public this throw true try typeof "; var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " + "concept concept_map const_cast constexpr decltype " + "dynamic_cast explicit export friend inline late_check " + "mutable namespace nullptr reinterpret_cast static_assert static_cast " + "template typeid typename using virtual wchar_t where "; var JAVA_KEYWORDS = COMMON_KEYWORDS + "abstract boolean byte extends final finally implements import " + "instanceof null native package strictfp super synchronized throws " + "transient "; var CSHARP_KEYWORDS = JAVA_KEYWORDS + "as base by checked decimal delegate descending event " + "fixed foreach from group implicit in interface internal into is lock " + "object out override orderby params partial readonly ref sbyte sealed " + "stackalloc string select uint ulong unchecked unsafe ushort var "; var JSCRIPT_KEYWORDS = COMMON_KEYWORDS + "debugger eval export function get null set undefined var with " + "Infinity NaN "; var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " + "goto if import last local my next no our print package redo require " + "sub undef unless until use wantarray while BEGIN END "; var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " + "elif except exec finally from global import in is lambda " + "nonlocal not or pass print raise try with yield " + "False True None "; var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" + " defined elsif end ensure false in module next nil not or redo rescue " + "retry self super then true undef unless until when yield BEGIN END "; var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " + "function in local set then until "; var ALL_KEYWORDS = ( CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS + PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS); // token style names. correspond to css classes /** token style for a string literal */ var PR_STRING = 'str'; /** token style for a keyword */ var PR_KEYWORD = 'kwd'; /** token style for a comment */ var PR_COMMENT = 'com'; /** token style for a type */ var PR_TYPE = 'typ'; /** token style for a literal value. e.g. 1, null, true. */ var PR_LITERAL = 'lit'; /** token style for a punctuation string. */ var PR_PUNCTUATION = 'pun'; /** token style for a punctuation string. */ var PR_PLAIN = 'pln'; /** token style for an sgml tag. */ var PR_TAG = 'tag'; /** token style for a markup declaration such as a DOCTYPE. */ var PR_DECLARATION = 'dec'; /** token style for embedded source. */ var PR_SOURCE = 'src'; /** token style for an sgml attribute name. */ var PR_ATTRIB_NAME = 'atn'; /** token style for an sgml attribute value. */ var PR_ATTRIB_VALUE = 'atv'; /** * A class that indicates a section of markup that is not code, e.g. to allow * embedding of line numbers within code listings. */ var PR_NOCODE = 'nocode'; /** A set of tokens that can precede a regular expression literal in * javascript. * http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full * list, but I've removed ones that might be problematic when seen in * languages that don't support regular expression literals. * * <p>Specifically, I've removed any keywords that can't precede a regexp * literal in a syntactically legal javascript program, and I've removed the * "in" keyword since it's not a keyword in many languages, and might be used * as a count of inches. * * <p>The link a above does not accurately describe EcmaScript rules since * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works * very well in practice. * * @private */ var REGEXP_PRECEDER_PATTERN = function () { var preceders = [ "!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=", "&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=", "->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";", "<", "<<", "<<=", "<=", "=", "==", "===", ">", ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[", "^", "^=", "^^", "^^=", "{", "|", "|=", "||", "||=", "~" /* handles =~ and !~ */, "break", "case", "continue", "delete", "do", "else", "finally", "instanceof", "return", "throw", "try", "typeof" ]; var pattern = '(?:^^|[+-]'; for (var i = 0; i < preceders.length; ++i) { pattern += '|' + preceders[i].replace(/([^=<>:&a-z])/g, '\\$1'); } pattern += ')\\s*'; // matches at end, and matches empty string return pattern; // CAVEAT: this does not properly handle the case where a regular // expression immediately follows another since a regular expression may // have flags for case-sensitivity and the like. Having regexp tokens // adjacent is not valid in any language I'm aware of, so I'm punting. // TODO: maybe style special characters inside a regexp as punctuation. }(); // Define regexps here so that the interpreter doesn't have to create an // object each time the function containing them is called. // The language spec requires a new object created even if you don't access // the $1 members. var pr_amp = /&/g; var pr_lt = /</g; var pr_gt = />/g; var pr_quot = /\"/g; /** like textToHtml but escapes double quotes to be attribute safe. */ function attribToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;') .replace(pr_quot, '&quot;'); } /** escapest html special characters to html. */ function textToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;'); } var pr_ltEnt = /&lt;/g; var pr_gtEnt = /&gt;/g; var pr_aposEnt = /&apos;/g; var pr_quotEnt = /&quot;/g; var pr_ampEnt = /&amp;/g; var pr_nbspEnt = /&nbsp;/g; /** unescapes html to plain text. */ function htmlToText(html) { var pos = html.indexOf('&'); if (pos < 0) { return html; } // Handle numeric entities specially. We can't use functional substitution // since that doesn't work in older versions of Safari. // These should be rare since most browsers convert them to normal chars. for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) { var end = html.indexOf(';', pos); if (end >= 0) { var num = html.substring(pos + 3, end); var radix = 10; if (num && num.charAt(0) === 'x') { num = num.substring(1); radix = 16; } var codePoint = parseInt(num, radix); if (!isNaN(codePoint)) { html = (html.substring(0, pos) + String.fromCharCode(codePoint) + html.substring(end + 1)); } } } return html.replace(pr_ltEnt, '<') .replace(pr_gtEnt, '>') .replace(pr_aposEnt, "'") .replace(pr_quotEnt, '"') .replace(pr_nbspEnt, ' ') .replace(pr_ampEnt, '&'); } /** is the given node's innerHTML normally unescaped? */ function isRawContent(node) { return 'XMP' === node.tagName; } var newlineRe = /[\r\n]/g; /** * Are newlines and adjacent spaces significant in the given node's innerHTML? */ function isPreformatted(node, content) { // PRE means preformatted, and is a very common case, so don't create // unnecessary computed style objects. if ('PRE' === node.tagName) { return true; } if (!newlineRe.test(content)) { return true; } // Don't care var whitespace = ''; // For disconnected nodes, IE has no currentStyle. if (node.currentStyle) { whitespace = node.currentStyle.whiteSpace; } else if (window.getComputedStyle) { // Firefox makes a best guess if node is disconnected whereas Safari // returns the empty string. whitespace = window.getComputedStyle(node, null).whiteSpace; } return !whitespace || whitespace === 'pre'; } function normalizedHtml(node, out) { switch (node.nodeType) { case 1: // an element var name = node.tagName.toLowerCase(); out.push('<', name); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified) { continue; } out.push(' '); normalizedHtml(attr, out); } out.push('>'); for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } if (node.firstChild || !/^(?:br|link|img)$/.test(name)) { out.push('<\/', name, '>'); } break; case 2: // an attribute out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"'); break; case 3: case 4: // text out.push(textToHtml(node.nodeValue)); break; } } /** * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally * matches the union o the sets o strings matched d by the input RegExp. * Since it matches globally, if the input strings have a start-of-input * anchor (/^.../), it is ignored for the purposes of unioning. * @param {Array.<RegExp>} regexs non multiline, non-global regexs. * @return {RegExp} a global regex. */ function combinePrefixPatterns(regexs) { var capturedGroupIndex = 0; var needToFoldCase = false; var ignoreCase = false; for (var i = 0, n = regexs.length; i < n; ++i) { var regex = regexs[i]; if (regex.ignoreCase) { ignoreCase = true; } else if (/[a-z]/i.test(regex.source.replace( /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) { needToFoldCase = true; ignoreCase = false; break; } } function decodeEscape(charsetPart) { if (charsetPart.charAt(0) !== '\\') { return charsetPart.charCodeAt(0); } switch (charsetPart.charAt(1)) { case 'b': return 8; case 't': return 9; case 'n': return 0xa; case 'v': return 0xb; case 'f': return 0xc; case 'r': return 0xd; case 'u': case 'x': return parseInt(charsetPart.substring(2), 16) || charsetPart.charCodeAt(1); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': return parseInt(charsetPart.substring(1), 8); default: return charsetPart.charCodeAt(1); } } function encodeEscape(charCode) { if (charCode < 0x20) { return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16); } var ch = String.fromCharCode(charCode); if (ch === '\\' || ch === '-' || ch === '[' || ch === ']') { ch = '\\' + ch; } return ch; } function caseFoldCharset(charSet) { var charsetParts = charSet.substring(1, charSet.length - 1).match( new RegExp( '\\\\u[0-9A-Fa-f]{4}' + '|\\\\x[0-9A-Fa-f]{2}' + '|\\\\[0-3][0-7]{0,2}' + '|\\\\[0-7]{1,2}' + '|\\\\[\\s\\S]' + '|-' + '|[^-\\\\]', 'g')); var groups = []; var ranges = []; var inverse = charsetParts[0] === '^'; for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) { var p = charsetParts[i]; switch (p) { case '\\B': case '\\b': case '\\D': case '\\d': case '\\S': case '\\s': case '\\W': case '\\w': groups.push(p); continue; } var start = decodeEscape(p); var end; if (i + 2 < n && '-' === charsetParts[i + 1]) { end = decodeEscape(charsetParts[i + 2]); i += 2; } else { end = start; } ranges.push([start, end]); // If the range might intersect letters, then expand it. if (!(end < 65 || start > 122)) { if (!(end < 65 || start > 90)) { ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]); } if (!(end < 97 || start > 122)) { ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]); } } } // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]] // -> [[1, 12], [14, 14], [16, 17]] ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); }); var consolidatedRanges = []; var lastRange = [NaN, NaN]; for (var i = 0; i < ranges.length; ++i) { var range = ranges[i]; if (range[0] <= lastRange[1] + 1) { lastRange[1] = Math.max(lastRange[1], range[1]); } else { consolidatedRanges.push(lastRange = range); } } var out = ['[']; if (inverse) { out.push('^'); } out.push.apply(out, groups); for (var i = 0; i < consolidatedRanges.length; ++i) { var range = consolidatedRanges[i]; out.push(encodeEscape(range[0])); if (range[1] > range[0]) { if (range[1] + 1 > range[0]) { out.push('-'); } out.push(encodeEscape(range[1])); } } out.push(']'); return out.join(''); } function allowAnywhereFoldCaseAndRenumberGroups(regex) { // Split into character sets, escape sequences, punctuation strings // like ('(', '(?:', ')', '^'), and runs of characters that do not // include any of the above. var parts = regex.source.match( new RegExp( '(?:' + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set + '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape + '|\\\\x[A-Fa-f0-9]{2}' // a hex escape + '|\\\\[0-9]+' // a back-reference or octal escape + '|\\\\[^ux0-9]' // other escape sequence + '|\\(\\?[:!=]' // start of a non-capturing group + '|[\\(\\)\\^]' // start/emd of a group, or line start + '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters + ')', 'g')); var n = parts.length; // Maps captured group numbers to the number they will occupy in // the output or to -1 if that has not been determined, or to // undefined if they need not be capturing in the output. var capturedGroups = []; // Walk over and identify back references to build the capturedGroups // mapping. for (var i = 0, groupIndex = 0; i < n; ++i) { var p = parts[i]; if (p === '(') { // groups are 1-indexed, so max group index is count of '(' ++groupIndex; } else if ('\\' === p.charAt(0)) { var decimalValue = +p.substring(1); if (decimalValue && decimalValue <= groupIndex) { capturedGroups[decimalValue] = -1; } } } // Renumber groups and reduce capturing groups to non-capturing groups // where possible. for (var i = 1; i < capturedGroups.length; ++i) { if (-1 === capturedGroups[i]) { capturedGroups[i] = ++capturedGroupIndex; } } for (var i = 0, groupIndex = 0; i < n; ++i) { var p = parts[i]; if (p === '(') { ++groupIndex; if (capturedGroups[groupIndex] === undefined) { parts[i] = '(?:'; } } else if ('\\' === p.charAt(0)) { var decimalValue = +p.substring(1); if (decimalValue && decimalValue <= groupIndex) { parts[i] = '\\' + capturedGroups[groupIndex]; } } } // Remove any prefix anchors so that the output will match anywhere. // ^^ really does mean an anchored match though. for (var i = 0, groupIndex = 0; i < n; ++i) { if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; } } // Expand letters to groupts to handle mixing of case-sensitive and // case-insensitive patterns if necessary. if (regex.ignoreCase && needToFoldCase) { for (var i = 0; i < n; ++i) { var p = parts[i]; var ch0 = p.charAt(0); if (p.length >= 2 && ch0 === '[') { parts[i] = caseFoldCharset(p); } else if (ch0 !== '\\') { // TODO: handle letters in numeric escapes. parts[i] = p.replace( /[a-zA-Z]/g, function (ch) { var cc = ch.charCodeAt(0); return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']'; }); } } } return parts.join(''); } var rewritten = []; for (var i = 0, n = regexs.length; i < n; ++i) { var regex = regexs[i]; if (regex.global || regex.multiline) { throw new Error('' + regex); } rewritten.push( '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')'); } return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g'); } var PR_innerHtmlWorks = null; function getInnerHtml(node) { // inner html is hopelessly broken in Safari 2.0.4 when the content is // an html description of well formed XML and the containing tag is a PRE // tag, so we detect that case and emulate innerHTML. if (null === PR_innerHtmlWorks) { var testNode = document.createElement('PRE'); testNode.appendChild( document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />')); PR_innerHtmlWorks = !/</.test(testNode.innerHTML); } if (PR_innerHtmlWorks) { var content = node.innerHTML; // XMP tags contain unescaped entities so require special handling. if (isRawContent(node)) { content = textToHtml(content); } else if (!isPreformatted(node, content)) { content = content.replace(/(<br\s*\/?>)[\r\n]+/g, '$1') .replace(/(?:[\r\n]+[ \t]*)+/g, ' '); } return content; } var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } return out.join(''); } /** returns a function that expand tabs to spaces. This function can be fed * successive chunks of text, and will maintain its own internal state to * keep track of how tabs are expanded. * @return {function (string) : string} a function that takes * plain text and return the text with tabs expanded. * @private */ function makeTabExpander(tabWidth) { var SPACES = ' '; var charInLine = 0; return function (plainText) { // walk over each character looking for tabs and newlines. // On tabs, expand them. On newlines, reset charInLine. // Otherwise increment charInLine var out = null; var pos = 0; for (var i = 0, n = plainText.length; i < n; ++i) { var ch = plainText.charAt(i); switch (ch) { case '\t': if (!out) { out = []; } out.push(plainText.substring(pos, i)); // calculate how much space we need in front of this part // nSpaces is the amount of padding -- the number of spaces needed // to move us to the next column, where columns occur at factors of // tabWidth. var nSpaces = tabWidth - (charInLine % tabWidth); charInLine += nSpaces; for (; nSpaces >= 0; nSpaces -= SPACES.length) { out.push(SPACES.substring(0, nSpaces)); } pos = i + 1; break; case '\n': charInLine = 0; break; default: ++charInLine; } } if (!out) { return plainText; } out.push(plainText.substring(pos)); return out.join(''); }; } var pr_chunkPattern = new RegExp( '[^<]+' // A run of characters other than '<' + '|<\!--[\\s\\S]*?--\>' // an HTML comment + '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>' // a CDATA section // a probable tag that should not be highlighted + '|<\/?[a-zA-Z](?:[^>\"\']|\'[^\']*\'|\"[^\"]*\")*>' + '|<', // A '<' that does not begin a larger chunk 'g'); var pr_commentPrefix = /^<\!--/; var pr_cdataPrefix = /^<!\[CDATA\[/; var pr_brPrefix = /^<br\b/i; var pr_tagNameRe = /^<(\/?)([a-zA-Z][a-zA-Z0-9]*)/; /** split markup into chunks of html tags (style null) and * plain text (style {@link #PR_PLAIN}), converting tags which are * significant for tokenization (<br>) into their textual equivalent. * * @param {string} s html where whitespace is considered significant. * @return {Object} source code and extracted tags. * @private */ function extractTags(s) { // since the pattern has the 'g' modifier and defines no capturing groups, // this will return a list of all chunks which we then classify and wrap as // PR_Tokens var matches = s.match(pr_chunkPattern); var sourceBuf = []; var sourceBufLen = 0; var extractedTags = []; if (matches) { for (var i = 0, n = matches.length; i < n; ++i) { var match = matches[i]; if (match.length > 1 && match.charAt(0) === '<') { if (pr_commentPrefix.test(match)) { continue; } if (pr_cdataPrefix.test(match)) { // strip CDATA prefix and suffix. Don't unescape since it's CDATA sourceBuf.push(match.substring(9, match.length - 3)); sourceBufLen += match.length - 12; } else if (pr_brPrefix.test(match)) { // <br> tags are lexically significant so convert them to text. // This is undone later. sourceBuf.push('\n'); ++sourceBufLen; } else { if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) { // A <span class="nocode"> will start a section that should be // ignored. Continue walking the list until we see a matching end // tag. var name = match.match(pr_tagNameRe)[2]; var depth = 1; var j; end_tag_loop: for (j = i + 1; j < n; ++j) { var name2 = matches[j].match(pr_tagNameRe); if (name2 && name2[2] === name) { if (name2[1] === '/') { if (--depth === 0) { break end_tag_loop; } } else { ++depth; } } } if (j < n) { extractedTags.push( sourceBufLen, matches.slice(i, j + 1).join('')); i = j; } else { // Ignore unclosed sections. extractedTags.push(sourceBufLen, match); } } else { extractedTags.push(sourceBufLen, match); } } } else { var literalText = htmlToText(match); sourceBuf.push(literalText); sourceBufLen += literalText.length; } } } return { source: sourceBuf.join(''), tags: extractedTags }; } /** True if the given tag contains a class attribute with the nocode class. */ function isNoCodeTag(tag) { return !!tag // First canonicalize the representation of attributes .replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g, ' $1="$2$3$4"') // Then look for the attribute we want. .match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/); } /** * Apply the given language handler to sourceCode and add the resulting * decorations to out. * @param {number} basePos the index of sourceCode within the chunk of source * whose decorations are already present on out. */ function appendDecorations(basePos, sourceCode, langHandler, out) { if (!sourceCode) { return; } var job = { source: sourceCode, basePos: basePos }; langHandler(job); out.push.apply(out, job.decorations); } /** Given triples of [style, pattern, context] returns a lexing function, * The lexing function interprets the patterns to find token boundaries and * returns a decoration list of the form * [index_0, style_0, index_1, style_1, ..., index_n, style_n] * where index_n is an index into the sourceCode, and style_n is a style * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to * all characters in sourceCode[index_n-1:index_n]. * * The stylePatterns is a list whose elements have the form * [style : string, pattern : RegExp, DEPRECATED, shortcut : string]. * * Style is a style constant like PR_PLAIN, or can be a string of the * form 'lang-FOO', where FOO is a language extension describing the * language of the portion of the token in $1 after pattern executes. * E.g., if style is 'lang-lisp', and group 1 contains the text * '(hello (world))', then that portion of the token will be passed to the * registered lisp handler for formatting. * The text before and after group 1 will be restyled using this decorator * so decorators should take care that this doesn't result in infinite * recursion. For example, the HTML lexer rule for SCRIPT elements looks * something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match * '<script>foo()<\/script>', which would cause the current decorator to * be called with '<script>' which would not match the same rule since * group 1 must not be empty, so it would be instead styled as PR_TAG by * the generic tag rule. The handler registered for the 'js' extension would * then be called with 'foo()', and finally, the current decorator would * be called with '<\/script>' which would not match the original rule and * so the generic tag rule would identify it as a tag. * * Pattern must only match prefixes, and if it matches a prefix, then that * match is considered a token with the same style. * * Context is applied to the last non-whitespace, non-comment token * recognized. * * Shortcut is an optional string of characters, any of which, if the first * character, gurantee that this pattern and only this pattern matches. * * @param {Array} shortcutStylePatterns patterns that always start with * a known character. Must have a shortcut string. * @param {Array} fallthroughStylePatterns patterns that will be tried in * order if the shortcut ones fail. May have shortcuts. * * @return {function (Object)} a * function that takes source code and returns a list of decorations. */ function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) { var shortcuts = {}; var tokenizer; (function () { var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns); var allRegexs = []; var regexKeys = {}; for (var i = 0, n = allPatterns.length; i < n; ++i) { var patternParts = allPatterns[i]; var shortcutChars = patternParts[3]; if (shortcutChars) { for (var c = shortcutChars.length; --c >= 0;) { shortcuts[shortcutChars.charAt(c)] = patternParts; } } var regex = patternParts[1]; var k = '' + regex; if (!regexKeys.hasOwnProperty(k)) { allRegexs.push(regex); regexKeys[k] = null; } } allRegexs.push(/[\0-\uffff]/); tokenizer = combinePrefixPatterns(allRegexs); })(); var nPatterns = fallthroughStylePatterns.length; var notWs = /\S/; /** * Lexes job.source and produces an output array job.decorations of style * classes preceded by the position at which they start in job.source in * order. * * @param {Object} job an object like {@code * source: {string} sourceText plain text, * basePos: {int} position of job.source in the larger chunk of * sourceCode. * } */ var decorate = function (job) { var sourceCode = job.source, basePos = job.basePos; /** Even entries are positions in source in ascending order. Odd enties * are style markers (e.g., PR_COMMENT) that run from that position until * the end. * @type {Array.<number|string>} */ var decorations = [basePos, PR_PLAIN]; var pos = 0; // index into sourceCode var tokens = sourceCode.match(tokenizer) || []; var styleCache = {}; for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) { var token = tokens[ti]; var style = styleCache[token]; var match = void 0; var isEmbedded; if (typeof style === 'string') { isEmbedded = false; } else { var patternParts = shortcuts[token.charAt(0)]; if (patternParts) { match = token.match(patternParts[1]); style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; match = token.match(patternParts[1]); if (match) { style = patternParts[0]; break; } } if (!match) { // make sure that we make progress style = PR_PLAIN; } } isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5); if (isEmbedded && !(match && typeof match[1] === 'string')) { isEmbedded = false; style = PR_SOURCE; } if (!isEmbedded) { styleCache[token] = style; } } var tokenStart = pos; pos += token.length; if (!isEmbedded) { decorations.push(basePos + tokenStart, style); } else { // Treat group 1 as an embedded block of source code. var embeddedSource = match[1]; var embeddedSourceStart = token.indexOf(embeddedSource); var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length; if (match[2]) { // If embeddedSource can be blank, then it would match at the // beginning which would cause us to infinitely recurse on the // entire token, so we catch the right context in match[2]. embeddedSourceEnd = token.length - match[2].length; embeddedSourceStart = embeddedSourceEnd - embeddedSource.length; } var lang = style.substring(5); // Decorate the left of the embedded source appendDecorations( basePos + tokenStart, token.substring(0, embeddedSourceStart), decorate, decorations); // Decorate the embedded source appendDecorations( basePos + tokenStart + embeddedSourceStart, embeddedSource, langHandlerForExtension(lang, embeddedSource), decorations); // Decorate the right of the embedded section appendDecorations( basePos + tokenStart + embeddedSourceEnd, token.substring(embeddedSourceEnd), decorate, decorations); } } job.decorations = decorations; }; return decorate; } /** returns a function that produces a list of decorations from source text. * * This code treats ", ', and ` as string delimiters, and \ as a string * escape. It does not recognize perl's qq() style strings. * It has no special handling for double delimiter escapes as in basic, or * the tripled delimiters used in python, but should work on those regardless * although in those cases a single string literal may be broken up into * multiple adjacent string literals. * * It recognizes C, C++, and shell style comments. * * @param {Object} options a set of optional parameters. * @return {function (Object)} a function that examines the source code * in the input job and builds the decoration list. */ function sourceDecorator(options) { var shortcutStylePatterns = [], fallthroughStylePatterns = []; if (options['tripleQuotedStrings']) { // '''multi-line-string''', 'single-line-string', and double-quoted shortcutStylePatterns.push( [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null, '\'"']); } else if (options['multiLineStrings']) { // 'multi-line-string', "multi-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, null, '\'"`']); } else { // 'single-line-string', "single-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"\'']); } if (options['verbatimStrings']) { // verbatim-string-literal production from the C# grammar. See issue 93. fallthroughStylePatterns.push( [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]); } if (options['hashComments']) { if (options['cStyleComments']) { // Stop C preprocessor declarations at an unclosed open comment shortcutStylePatterns.push( [PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/, null, '#']); fallthroughStylePatterns.push( [PR_STRING, /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/, null]); } else { shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']); } } if (options['cStyleComments']) { fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]); fallthroughStylePatterns.push( [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); } if (options['regexLiterals']) { var REGEX_LITERAL = ( // A regular expression literal starts with a slash that is // not followed by * or / so that it is not confused with // comments. '/(?=[^/*])' // and then contains any number of raw characters, + '(?:[^/\\x5B\\x5C]' // escape sequences (\x5C), + '|\\x5C[\\s\\S]' // or non-nesting character sets (\x5B\x5D); + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+' // finally closed by a /. + '/'); fallthroughStylePatterns.push( ['lang-regex', new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')') ]); } var keywords = options['keywords'].replace(/^\s+|\s+$/g, ''); if (keywords.length) { fallthroughStylePatterns.push( [PR_KEYWORD, new RegExp('^(?:' + keywords.replace(/\s+/g, '|') + ')\\b'), null]); } shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']); fallthroughStylePatterns.push( // TODO(mikesamuel): recognize non-latin letters and numerals in idents [PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null], [PR_TYPE, /^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/, null], [PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null], [PR_LITERAL, new RegExp( '^(?:' // A hex number + '0x[a-f0-9]+' // or an octal or decimal number, + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)' // possibly in scientific notation + '(?:e[+\\-]?\\d+)?' + ')' // with an optional modifier like UL for unsigned long + '[a-z]*', 'i'), null, '0123456789'], [PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#]*/, null]); return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns); } var decorateSource = sourceDecorator({ 'keywords': ALL_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'multiLineStrings': true, 'regexLiterals': true }); /** Breaks {@code job.source} around style boundaries in * {@code job.decorations} while re-interleaving {@code job.extractedTags}, * and leaves the result in {@code job.prettyPrintedHtml}. * @param {Object} job like { * source: {string} source as plain text, * extractedTags: {Array.<number|string>} extractedTags chunks of raw * html preceded by their position in {@code job.source} * in order * decorations: {Array.<number|string} an array of style classes preceded * by the position at which they start in job.source in order * } * @private */ function recombineTagsAndDecorations(job) { var sourceText = job.source; var extractedTags = job.extractedTags; var decorations = job.decorations; var html = []; // index past the last char in sourceText written to html var outputIdx = 0; var openDecoration = null; var currentDecoration = null; var tagPos = 0; // index into extractedTags var decPos = 0; // index into decorations var tabExpander = makeTabExpander(window['PR_TAB_WIDTH']); var adjacentSpaceRe = /([\r\n ]) /g; var startOrSpaceRe = /(^| ) /gm; var newlineRe = /\r\n?|\n/g; var trailingSpaceRe = /[ \r\n]$/; var lastWasSpace = true; // the last text chunk emitted ended with a space. // A helper function that is responsible for opening sections of decoration // and outputing properly escaped chunks of source function emitTextUpTo(sourceIdx) { if (sourceIdx > outputIdx) { if (openDecoration && openDecoration !== currentDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } if (!openDecoration && currentDecoration) { openDecoration = currentDecoration; html.push('<span class="', openDecoration, '">'); } // This interacts badly with some wikis which introduces paragraph tags // into pre blocks for some strange reason. // It's necessary for IE though which seems to lose the preformattedness // of <pre> tags when their innerHTML is assigned. // http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html // and it serves to undo the conversion of <br>s to newlines done in // chunkify. var htmlChunk = textToHtml( tabExpander(sourceText.substring(outputIdx, sourceIdx))) .replace(lastWasSpace ? startOrSpaceRe : adjacentSpaceRe, '$1&nbsp;'); // Keep track of whether we need to escape space at the beginning of the // next chunk. lastWasSpace = trailingSpaceRe.test(htmlChunk); // IE collapses multiple adjacient <br>s into 1 line break. // Prefix every <br> with '&nbsp;' can prevent such IE's behavior. var lineBreakHtml = window['_pr_isIE6']() ? '&nbsp;<br />' : '<br />'; html.push(htmlChunk.replace(newlineRe, lineBreakHtml)); outputIdx = sourceIdx; } } while (true) { // Determine if we're going to consume a tag this time around. Otherwise // we consume a decoration or exit. var outputTag; if (tagPos < extractedTags.length) { if (decPos < decorations.length) { // Pick one giving preference to extractedTags since we shouldn't open // a new style that we're going to have to immediately close in order // to output a tag. outputTag = extractedTags[tagPos] <= decorations[decPos]; } else { outputTag = true; } } else { outputTag = false; } // Consume either a decoration or a tag or exit. if (outputTag) { emitTextUpTo(extractedTags[tagPos]); if (openDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } html.push(extractedTags[tagPos + 1]); tagPos += 2; } else if (decPos < decorations.length) { emitTextUpTo(decorations[decPos]); currentDecoration = decorations[decPos + 1]; decPos += 2; } else { break; } } emitTextUpTo(sourceText.length); if (openDecoration) { html.push('</span>'); } job.prettyPrintedHtml = html.join(''); } /** Maps language-specific file extensions to handlers. */ var langHandlerRegistry = {}; /** Register a language handler for the given file extensions. * @param {function (Object)} handler a function from source code to a list * of decorations. Takes a single argument job which describes the * state of the computation. The single parameter has the form * {@code { * source: {string} as plain text. * decorations: {Array.<number|string>} an array of style classes * preceded by the position at which they start in * job.source in order. * The language handler should assigned this field. * basePos: {int} the position of source in the larger source chunk. * All positions in the output decorations array are relative * to the larger source chunk. * } } * @param {Array.<string>} fileExtensions */ function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if ('console' in window) { console.warn('cannot override language handler %s', ext); } } } function langHandlerForExtension(extension, source) { if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) { // Treat it as markup if the first non whitespace character is a < and // the last non-whitespace character is a >. extension = /^\s*</.test(source) ? 'default-markup' : 'default-code'; } return langHandlerRegistry[extension]; } registerLangHandler(decorateSource, ['default-code']); registerLangHandler( createSimpleLexer( [], [ [PR_PLAIN, /^[^<?]+/], [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/], [PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/], // Unescaped content in an unknown language ['lang-', /^<\?([\s\S]+?)(?:\?>|$)/], ['lang-', /^<%([\s\S]+?)(?:%>|$)/], [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/], ['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i], // Unescaped content in javascript. (Or possibly vbscript). ['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i], // Contains unescaped stylesheet content ['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i], ['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i] ]), ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']); registerLangHandler( createSimpleLexer( [ [PR_PLAIN, /^[\s]+/, null, ' \t\r\n'], [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\''] ], [ [PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i], [PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i], ['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/], [PR_PUNCTUATION, /^[=<>\/]+/], ['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i], ['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i], ['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i], ['lang-css', /^style\s*=\s*\"([^\"]+)\"/i], ['lang-css', /^style\s*=\s*\'([^\']+)\'/i], ['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i] ]), ['in.tag']); registerLangHandler( createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']); registerLangHandler(sourceDecorator({ 'keywords': CPP_KEYWORDS, 'hashComments': true, 'cStyleComments': true }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']); registerLangHandler(sourceDecorator({ 'keywords': 'null true false' }), ['json']); registerLangHandler(sourceDecorator({ 'keywords': CSHARP_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'verbatimStrings': true }), ['cs']); registerLangHandler(sourceDecorator({ 'keywords': JAVA_KEYWORDS, 'cStyleComments': true }), ['java']); registerLangHandler(sourceDecorator({ 'keywords': SH_KEYWORDS, 'hashComments': true, 'multiLineStrings': true }), ['bsh', 'csh', 'sh']); registerLangHandler(sourceDecorator({ 'keywords': PYTHON_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'tripleQuotedStrings': true }), ['cv', 'py']); registerLangHandler(sourceDecorator({ 'keywords': PERL_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'regexLiterals': true }), ['perl', 'pl', 'pm']); registerLangHandler(sourceDecorator({ 'keywords': RUBY_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'regexLiterals': true }), ['rb']); registerLangHandler(sourceDecorator({ 'keywords': JSCRIPT_KEYWORDS, 'cStyleComments': true, 'regexLiterals': true }), ['js']); registerLangHandler( createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']); function applyDecorator(job) { var sourceCodeHtml = job.sourceCodeHtml; var opt_langExtension = job.langExtension; // Prepopulate output in case processing fails with an exception. job.prettyPrintedHtml = sourceCodeHtml; try { // Extract tags, and convert the source code to plain text. var sourceAndExtractedTags = extractTags(sourceCodeHtml); /** Plain text. @type {string} */ var source = sourceAndExtractedTags.source; job.source = source; job.basePos = 0; /** Even entries are positions in source in ascending order. Odd entries * are tags that were extracted at that position. * @type {Array.<number|string>} */ job.extractedTags = sourceAndExtractedTags.tags; // Apply the appropriate language handler langHandlerForExtension(opt_langExtension, source)(job); // Integrate the decorations and tags back into the source code to produce // a decorated html string which is left in job.prettyPrintedHtml. recombineTagsAndDecorations(job); } catch (e) { if ('console' in window) { console.log(e); console.trace(); } } } function prettyPrintOne(sourceCodeHtml, opt_langExtension) { var job = { sourceCodeHtml: sourceCodeHtml, langExtension: opt_langExtension }; applyDecorator(job); return job.prettyPrintedHtml; } function prettyPrint(opt_whenDone) { var isIE678 = window['_pr_isIE6'](); var ieNewline = isIE678 === 6 ? '\r\n' : '\r'; // See bug 71 and http://stackoverflow.com/questions/136443/why-doesnt-ie7- // fetch a list of nodes to rewrite var codeSegments = [ document.getElementsByTagName('pre'), document.getElementsByTagName('code'), document.getElementsByTagName('xmp') ]; var elements = []; for (var i = 0; i < codeSegments.length; ++i) { for (var j = 0, n = codeSegments[i].length; j < n; ++j) { elements.push(codeSegments[i][j]); } } codeSegments = null; var clock = Date; if (!clock['now']) { clock = { 'now': function () { return (new Date).getTime(); } }; } // The loop is broken into a series of continuations to make sure that we // don't make the browser unresponsive when rewriting a large page. var k = 0; var prettyPrintingJob; function doWork() { var endTime = (window['PR_SHOULD_USE_CONTINUATION'] ? clock.now() + 250 /* ms */ : Infinity); for (; k < elements.length && clock.now() < endTime; k++) { var cs = elements[k]; if (cs.className && cs.className.indexOf('prettyprint') >= 0) { // If the classes includes a language extensions, use it. // Language extensions can be specified like // <pre class="prettyprint lang-cpp"> // the language extension "cpp" is used to find a language handler as // passed to PR_registerLangHandler. var langExtension = cs.className.match(/\blang-(\w+)\b/); if (langExtension) { langExtension = langExtension[1]; } // make sure this is not nested in an already prettified element var nested = false; for (var p = cs.parentNode; p; p = p.parentNode) { if ((p.tagName === 'pre' || p.tagName === 'code' || p.tagName === 'xmp') && p.className && p.className.indexOf('prettyprint') >= 0) { nested = true; break; } } if (!nested) { // fetch the content as a snippet of properly escaped HTML. // Firefox adds newlines at the end. var content = getInnerHtml(cs); content = content.replace(/(?:\r\n?|\n)$/, ''); // do the pretty printing prettyPrintingJob = { sourceCodeHtml: content, langExtension: langExtension, sourceNode: cs }; applyDecorator(prettyPrintingJob); replaceWithPrettyPrintedHtml(); } } } if (k < elements.length) { // finish up in a continuation setTimeout(doWork, 250); } else if (opt_whenDone) { opt_whenDone(); } } function replaceWithPrettyPrintedHtml() { var newContent = prettyPrintingJob.prettyPrintedHtml; if (!newContent) { return; } var cs = prettyPrintingJob.sourceNode; // push the prettified html back into the tag. if (!isRawContent(cs)) { // just replace the old html with the new cs.innerHTML = newContent; } else { // we need to change the tag to a <pre> since <xmp>s do not allow // embedded tags such as the span tags used to attach styles to // sections of source code. var pre = document.createElement('PRE'); for (var i = 0; i < cs.attributes.length; ++i) { var a = cs.attributes[i]; if (a.specified) { var aname = a.name.toLowerCase(); if (aname === 'class') { pre.className = a.value; // For IE 6 } else { pre.setAttribute(a.name, a.value); } } } pre.innerHTML = newContent; // remove the old cs.parentNode.replaceChild(pre, cs); cs = pre; } // Replace <br>s with line-feeds so that copying and pasting works // on IE 6. // Doing this on other browsers breaks lots of stuff since \r\n is // treated as two newlines on Firefox, and doing this also slows // down rendering. if (isIE678 && cs.tagName === 'PRE') { var lineBreaks = cs.getElementsByTagName('br'); for (var j = lineBreaks.length; --j >= 0;) { var lineBreak = lineBreaks[j]; lineBreak.parentNode.replaceChild( document.createTextNode(ieNewline), lineBreak); } } } doWork(); } window['PR_normalizedHtml'] = normalizedHtml; window['prettyPrintOne'] = prettyPrintOne; window['prettyPrint'] = prettyPrint; window['PR'] = { 'combinePrefixPatterns': combinePrefixPatterns, 'createSimpleLexer': createSimpleLexer, 'registerLangHandler': registerLangHandler, 'sourceDecorator': sourceDecorator, 'PR_ATTRIB_NAME': PR_ATTRIB_NAME, 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE, 'PR_COMMENT': PR_COMMENT, 'PR_DECLARATION': PR_DECLARATION, 'PR_KEYWORD': PR_KEYWORD, 'PR_LITERAL': PR_LITERAL, 'PR_NOCODE': PR_NOCODE, 'PR_PLAIN': PR_PLAIN, 'PR_PUNCTUATION': PR_PUNCTUATION, 'PR_SOURCE': PR_SOURCE, 'PR_STRING': PR_STRING, 'PR_TAG': PR_TAG, 'PR_TYPE': PR_TYPE }; })();
JavaScript
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */ /* * jQuery MultiSelect UI Widget 1.14pre * Copyright (c) 2012 Eric Hynds * * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ * * Depends: * - jQuery 1.4.2+ * - jQuery UI 1.8 widget factory * * Optional: * - jQuery UI effects * - jQuery UI position utility * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ (function($, undefined) { var multiselectID = 0; var $doc = $(document); $.widget("ech.multiselect", { // default options options: { header: true, height: 175, minWidth: 225, classes: '', checkAllText: 'Check all', uncheckAllText: 'Uncheck all', noneSelectedText: 'Select options', selectedText: '# selected', selectedList: 0, show: null, hide: null, autoOpen: false, multiple: true, position: {} }, _create: function() { var el = this.element.hide(); var o = this.options; this.speed = $.fx.speeds._default; // default speed for effects this._isOpen = false; // assume no // create a unique namespace for events that the widget // factory cannot unbind automatically. Use eventNamespace if on // jQuery UI 1.9+, and otherwise fallback to a custom string. this._namespaceID = this.eventNamespace || ('multiselect' + multiselectID); var button = (this.button = $('<button type="button"><span class="ui-icon ui-icon-triangle-1-s"></span></button>')) .addClass('ui-multiselect ui-widget ui-state-default ui-corner-all') .addClass(o.classes) .attr({ 'title':el.attr('title'), 'aria-haspopup':true, 'tabIndex':el.attr('tabIndex') }) .insertAfter(el), buttonlabel = (this.buttonlabel = $('<span />')) .html(o.noneSelectedText) .appendTo(button), menu = (this.menu = $('<div />')) .addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all') .addClass(o.classes) .appendTo(document.body), header = (this.header = $('<div />')) .addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix') .appendTo(menu), headerLinkContainer = (this.headerLinkContainer = $('<ul />')) .addClass('ui-helper-reset') .html(function() { if(o.header === true) { return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>'; } else if(typeof o.header === "string") { return '<li>' + o.header + '</li>'; } else { return ''; } }) .append('<li class="ui-multiselect-close"><a href="#" class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></a></li>') .appendTo(header), checkboxContainer = (this.checkboxContainer = $('<ul />')) .addClass('ui-multiselect-checkboxes ui-helper-reset') .appendTo(menu); // perform event bindings this._bindEvents(); // build menu this.refresh(true); // some addl. logic for single selects if(!o.multiple) { menu.addClass('ui-multiselect-single'); } // bump unique ID multiselectID++; }, _init: function() { if(this.options.header === false) { this.header.hide(); } if(!this.options.multiple) { this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide(); } if(this.options.autoOpen) { this.open(); } if(this.element.is(':disabled')) { this.disable(); } }, refresh: function(init) { var el = this.element; var o = this.options; var menu = this.menu; var checkboxContainer = this.checkboxContainer; var optgroups = []; var html = ""; var id = el.attr('id') || multiselectID++; // unique ID for the label & option tags // build items el.find('option').each(function(i) { var $this = $(this); var parent = this.parentNode; var title = this.innerHTML; var description = this.title; var value = this.value; var inputID = 'ui-multiselect-' + (this.id || id + '-option-' + i); var isDisabled = this.disabled; var isSelected = this.selected; var labelClasses = [ 'ui-corner-all' ]; var liClasses = (isDisabled ? 'ui-multiselect-disabled ' : ' ') + this.className; var optLabel; // is this an optgroup? if(parent.tagName === 'OPTGROUP') { optLabel = parent.getAttribute('label'); // has this optgroup been added already? if($.inArray(optLabel, optgroups) === -1) { html += '<li class="ui-multiselect-optgroup-label ' + parent.className + '"><a href="#">' + optLabel + '</a></li>'; optgroups.push(optLabel); } } if(isDisabled) { labelClasses.push('ui-state-disabled'); } // browsers automatically select the first option // by default with single selects if(isSelected && !o.multiple) { labelClasses.push('ui-state-active'); } html += '<li class="' + liClasses + '">'; // create the label html += '<label for="' + inputID + '" title="' + description + '" class="' + labelClasses.join(' ') + '">'; html += '<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"'; // pre-selected? if(isSelected) { html += ' checked="checked"'; html += ' aria-selected="true"'; } // disabled? if(isDisabled) { html += ' disabled="disabled"'; html += ' aria-disabled="true"'; } // add the title and close everything off html += ' /><span>' + title + '</span></label></li>'; }); // insert into the DOM checkboxContainer.html(html); // cache some moar useful elements this.labels = menu.find('label'); this.inputs = this.labels.children('input'); // set widths this._setButtonWidth(); this._setMenuWidth(); // remember default value this.button[0].defaultValue = this.update(); // broadcast refresh event; useful for widgets if(!init) { this._trigger('refresh'); } }, // updates the button text. call refresh() to rebuild update: function() { var o = this.options; var $inputs = this.inputs; var $checked = $inputs.filter(':checked'); var numChecked = $checked.length; var value; if(numChecked === 0) { value = o.noneSelectedText; } else { if($.isFunction(o.selectedText)) { value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get()); } else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) { value = $checked.map(function() { return $(this).next().html(); }).get().join(', '); } else { value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length); } } this._setButtonValue(value); return value; }, // this exists as a separate method so that the developer // can easily override it. _setButtonValue: function(value) { this.buttonlabel.text(value); }, // binds events _bindEvents: function() { var self = this; var button = this.button; function clickHandler() { self[ self._isOpen ? 'close' : 'open' ](); return false; } // webkit doesn't like it when you click on the span :( button .find('span') .bind('click.multiselect', clickHandler); // button events button.bind({ click: clickHandler, keypress: function(e) { switch(e.which) { case 27: // esc case 38: // up case 37: // left self.close(); break; case 39: // right case 40: // down self.open(); break; } }, mouseenter: function() { if(!button.hasClass('ui-state-disabled')) { $(this).addClass('ui-state-hover'); } }, mouseleave: function() { $(this).removeClass('ui-state-hover'); }, focus: function() { if(!button.hasClass('ui-state-disabled')) { $(this).addClass('ui-state-focus'); } }, blur: function() { $(this).removeClass('ui-state-focus'); } }); // header links this.header.delegate('a', 'click.multiselect', function(e) { // close link if($(this).hasClass('ui-multiselect-close')) { self.close(); // check all / uncheck all } else { self[$(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll'](); } e.preventDefault(); }); // optgroup label toggle support this.menu.delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function(e) { e.preventDefault(); var $this = $(this); var $inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)'); var nodes = $inputs.get(); var label = $this.parent().text(); // trigger event and bail if the return is false if(self._trigger('beforeoptgrouptoggle', e, { inputs:nodes, label:label }) === false) { return; } // toggle inputs self._toggleChecked( $inputs.filter(':checked').length !== $inputs.length, $inputs ); self._trigger('optgrouptoggle', e, { inputs: nodes, label: label, checked: nodes[0].checked }); }) .delegate('label', 'mouseenter.multiselect', function() { if(!$(this).hasClass('ui-state-disabled')) { self.labels.removeClass('ui-state-hover'); $(this).addClass('ui-state-hover').find('input').focus(); } }) .delegate('label', 'keydown.multiselect', function(e) { e.preventDefault(); switch(e.which) { case 9: // tab case 27: // esc self.close(); break; case 38: // up case 40: // down case 37: // left case 39: // right self._traverse(e.which, this); break; case 13: // enter $(this).find('input')[0].click(); break; } }) .delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function(e) { var $this = $(this); var val = this.value; var checked = this.checked; var tags = self.element.find('option'); // bail if this input is disabled or the event is cancelled if(this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false) { e.preventDefault(); return; } // make sure the input has focus. otherwise, the esc key // won't close the menu after clicking an item. $this.focus(); // toggle aria state $this.attr('aria-selected', checked); // change state on the original option tags tags.each(function() { if(this.value === val) { this.selected = checked; } else if(!self.options.multiple) { this.selected = false; } }); // some additional single select-specific logic if(!self.options.multiple) { self.labels.removeClass('ui-state-active'); $this.closest('label').toggleClass('ui-state-active', checked); // close menu self.close(); } // fire change on the select box self.element.trigger("change"); // setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827 // http://bugs.jquery.com/ticket/3827 setTimeout($.proxy(self.update, self), 10); }); // close each widget when clicking on any other element/anywhere else on the page $doc.bind('mousedown.' + this._namespaceID, function(event) { var target = event.target; if(self._isOpen && !$.contains(self.menu[0], target) && !$.contains(self.button[0], target) && target !== self.button[0] && target !== self.menu[0]) { self.close(); } }); // deal with form resets. the problem here is that buttons aren't // restored to their defaultValue prop on form reset, and the reset // handler fires before the form is actually reset. delaying it a bit // gives the form inputs time to clear. $(this.element[0].form).bind('reset.multiselect', function() { setTimeout($.proxy(self.refresh, self), 10); }); }, // set button width _setButtonWidth: function() { var width = this.element.outerWidth(); var o = this.options; if(/\d/.test(o.minWidth) && width < o.minWidth) { width = o.minWidth; } // set widths this.button.outerWidth(width); }, // set menu width _setMenuWidth: function() { var m = this.menu; m.outerWidth(this.button.outerWidth()); }, // move up or down within the menu _traverse: function(which, start) { var $start = $(start); var moveToLast = which === 38 || which === 37; // select the first li that isn't an optgroup label / disabled $next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)')[ moveToLast ? 'last' : 'first'](); // if at the first/last element if(!$next.length) { var $container = this.menu.find('ul').last(); // move to the first/last this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover'); // set scroll position $container.scrollTop(moveToLast ? $container.height() : 0); } else { $next.find('label').trigger('mouseover'); } }, // This is an internal function to toggle the checked property and // other related attributes of a checkbox. // // The context of this function should be a checkbox; do not proxy it. _toggleState: function(prop, flag) { return function() { if(!this.disabled) { this[ prop ] = flag; } if(flag) { this.setAttribute('aria-selected', true); } else { this.removeAttribute('aria-selected'); } }; }, _toggleChecked: function(flag, group) { var $inputs = (group && group.length) ? group : this.inputs; var self = this; // toggle state on inputs $inputs.each(this._toggleState('checked', flag)); // give the first input focus $inputs.eq(0).focus(); // update button text this.update(); // gather an array of the values that actually changed var values = $inputs.map(function() { return this.value; }).get(); // toggle state on original option tags this.element .find('option') .each(function() { if(!this.disabled && $.inArray(this.value, values) > -1) { self._toggleState('selected', flag).call(this); } }); // trigger the change event on the select if($inputs.length) { this.element.trigger("change"); } }, _toggleDisabled: function(flag) { this.button.attr({ 'disabled':flag, 'aria-disabled':flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled'); var inputs = this.menu.find('input'); var key = "ech-multiselect-disabled"; if(flag) { // remember which elements this widget disabled (not pre-disabled) // elements, so that they can be restored if the widget is re-enabled. inputs = inputs.filter(':enabled').data(key, true) } else { inputs = inputs.filter(function() { return $.data(this, key) === true; }).removeData(key); } inputs .attr({ 'disabled':flag, 'arial-disabled':flag }) .parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled'); this.element.attr({ 'disabled':flag, 'aria-disabled':flag }); }, // open the menu open: function(e) { var self = this; var button = this.button; var menu = this.menu; var speed = this.speed; var o = this.options; var args = []; // bail if the multiselectopen event returns false, this widget is disabled, or is already open if(this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen) { return; } var $container = menu.find('ul').last(); var effect = o.show; // figure out opening effects/speeds if($.isArray(o.show)) { effect = o.show[0]; speed = o.show[1] || self.speed; } // if there's an effect, assume jQuery UI is in use // build the arguments to pass to show() if(effect) { args = [ effect, speed ]; } // set the scroll of the checkbox container $container.scrollTop(0).height(o.height); // positon this.position(); // show the menu, maybe with a speed/effect combo $.fn.show.apply(menu, args); // select the first not disabled option // triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover // will actually trigger mouseenter. the mouseenter trigger is there for when it's eventually fixed this.labels.filter(':not(.ui-state-disabled)').eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus'); button.addClass('ui-state-active'); this._isOpen = true; this._trigger('open'); }, // close the menu close: function() { if(this._trigger('beforeclose') === false) { return; } var o = this.options; var effect = o.hide; var speed = this.speed; var args = []; // figure out opening effects/speeds if($.isArray(o.hide)) { effect = o.hide[0]; speed = o.hide[1] || this.speed; } if(effect) { args = [ effect, speed ]; } $.fn.hide.apply(this.menu, args); this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave'); this._isOpen = false; this._trigger('close'); }, enable: function() { this._toggleDisabled(false); }, disable: function() { this._toggleDisabled(true); }, checkAll: function(e) { this._toggleChecked(true); this._trigger('checkAll'); }, uncheckAll: function() { this._toggleChecked(false); this._trigger('uncheckAll'); }, getChecked: function() { return this.menu.find('input').filter(':checked'); }, destroy: function() { // remove classes + data $.Widget.prototype.destroy.call(this); // unbind events $doc.unbind(this._namespaceID); this.button.remove(); this.menu.remove(); this.element.show(); return this; }, isOpen: function() { return this._isOpen; }, widget: function() { return this.menu; }, getButton: function() { return this.button; }, position: function() { var o = this.options; // use the position utility if it exists and options are specifified if($.ui.position && !$.isEmptyObject(o.position)) { o.position.of = o.position.of || this.button; this.menu .show() .position(o.position) .hide(); // otherwise fallback to custom positioning } else { var pos = this.button.offset(); this.menu.css({ top: pos.top + this.button.outerHeight(), left: pos.left }); } }, // react to option changes after initialization _setOption: function(key, value) { var menu = this.menu; switch(key) { case 'header': menu.find('div.ui-multiselect-header')[value ? 'show' : 'hide'](); break; case 'checkAllText': menu.find('a.ui-multiselect-all span').eq(-1).text(value); break; case 'uncheckAllText': menu.find('a.ui-multiselect-none span').eq(-1).text(value); break; case 'height': menu.find('ul').last().height(parseInt(value, 10)); break; case 'minWidth': this.options[key] = parseInt(value, 10); this._setButtonWidth(); this._setMenuWidth(); break; case 'selectedText': case 'selectedList': case 'noneSelectedText': this.options[key] = value; // these all needs to update immediately for the update() call this.update(); break; case 'classes': menu.add(this.button).removeClass(this.options.classes).addClass(value); break; case 'multiple': menu.toggleClass('ui-multiselect-single', !value); this.options.multiple = value; this.element[0].multiple = value; this.refresh(); break; case 'position': this.position(); } $.Widget.prototype._setOption.apply(this, arguments); } }); })(jQuery);
JavaScript
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */ /* * jQuery MultiSelect UI Widget Filtering Plugin 1.5pre * Copyright (c) 2012 Eric Hynds * * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ * * Depends: * - jQuery UI MultiSelect widget * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ (function($) { var rEscape = /[\-\[\]{}()*+?.,\\\^$|#\s]/g; $.widget('ech.multiselectfilter', { options: { label: 'Filter:', width: null, /* override default width set in css file (px). null will inherit */ placeholder: 'Enter keywords', autoReset: false }, _create: function() { var opts = this.options; var elem = $(this.element); // get the multiselect instance var instance = (this.instance = (elem.data('echMultiselect') || elem.data("multiselect"))); // store header; add filter class so the close/check all/uncheck all links can be positioned correctly var header = (this.header = instance.menu.find('.ui-multiselect-header').addClass('ui-multiselect-hasfilter')); // wrapper elem var wrapper = (this.wrapper = $('<div class="ui-multiselect-filter">' + (opts.label.length ? opts.label : '') + '<input placeholder="'+opts.placeholder+'" type="search"' + (/\d/.test(opts.width) ? 'style="width:'+opts.width+'px"' : '') + ' /></div>').prependTo(this.header)); // reference to the actual inputs this.inputs = instance.menu.find('input[type="checkbox"], input[type="radio"]'); // build the input box this.input = wrapper.find('input').bind({ keydown: function(e) { // prevent the enter key from submitting the form / closing the widget if(e.which === 13) { e.preventDefault(); } }, keyup: $.proxy(this._handler, this), click: $.proxy(this._handler, this) }); // cache input values for searching this.updateCache(); // rewrite internal _toggleChecked fn so that when checkAll/uncheckAll is fired, // only the currently filtered elements are checked instance._toggleChecked = function(flag, group) { var $inputs = (group && group.length) ? group : this.labels.find('input'); var _self = this; // do not include hidden elems if the menu isn't open. var selector = instance._isOpen ? ':disabled, :hidden' : ':disabled'; $inputs = $inputs .not(selector) .each(this._toggleState('checked', flag)); // update text this.update(); // gather an array of the values that actually changed var values = $inputs.map(function() { return this.value; }).get(); // select option tags this.element.find('option').filter(function() { if(!this.disabled && $.inArray(this.value, values) > -1) { _self._toggleState('selected', flag).call(this); } }); // trigger the change event on the select if($inputs.length) { this.element.trigger('change'); } }; // rebuild cache when multiselect is updated var doc = $(document).bind('multiselectrefresh', $.proxy(function() { this.updateCache(); this._handler(); }, this)); // automatically reset the widget on close? if(this.options.autoReset) { doc.bind('multiselectclose', $.proxy(this._reset, this)); } }, // thx for the logic here ben alman _handler: function(e) { var term = $.trim(this.input[0].value.toLowerCase()), // speed up lookups rows = this.rows, inputs = this.inputs, cache = this.cache; if(!term) { rows.show(); } else { rows.hide(); var regex = new RegExp(term.replace(rEscape, "\\$&"), 'gi'); this._trigger("filter", e, $.map(cache, function(v, i) { if(v.search(regex) !== -1) { rows.eq(i).show(); return inputs.get(i); } return null; })); } // show/hide optgroups this.instance.menu.find(".ui-multiselect-optgroup-label").each(function() { var $this = $(this); var isVisible = $this.nextUntil('.ui-multiselect-optgroup-label').filter(function() { return $.css(this, "display") !== 'none'; }).length; $this[isVisible ? 'show' : 'hide'](); }); }, _reset: function() { this.input.val('').trigger('keyup'); }, updateCache: function() { // each list item this.rows = this.instance.menu.find(".ui-multiselect-checkboxes li:not(.ui-multiselect-optgroup-label)"); // cache this.cache = this.element.children().map(function() { var elem = $(this); // account for optgroups if(this.tagName.toLowerCase() === "optgroup") { elem = elem.children(); } return elem.map(function() { return this.innerHTML.toLowerCase(); }).get(); }).get(); }, widget: function() { return this.wrapper; }, destroy: function() { $.Widget.prototype.destroy.call(this); this.input.val('').trigger("keyup"); this.wrapper.remove(); } }); })(jQuery);
JavaScript
(function($){ var el, widget, button, input; function getVisible() { return widget.find(".ui-multiselect-checkboxes input:visible"); } function getChecked() { return el.multiselect("getChecked"); } function getSelected() { return el.children(":selected"); } function searchFor(term) { input.val(term).trigger("keyup"); } function triggerClick() { this.click(); } function searchTest( term, expected, message ) { message || (message = "searching for '#'"); message = message.replace("#", term); searchFor(term); equals( getVisible().length, expected, message ); } module("filter widget - multiple select", { setup: function() { el = $('<select multiple>' + '<option></option>' + '<option value="foo">testffoooo</option>' + '<option value="bar">testbbaarr</option>' + '<option value=" baz ">testbbaazz</option>' + '<option value="qux">testquxtest</option>' + '<option value="10">ten</option>' + '<option value="100">one hundred</option>' + '<option value="5">five</option>' + '<option>a test with word boundaries</option>' + '<option>special regex !^$()//-|{}/: characters</option>' + '</option>'); el.appendTo(document.body); el.multiselect(); el.multiselectfilter(); el.multiselect("open"); widget = el.multiselect("widget"); input = widget.find(".ui-multiselect-filter input"); button = el.next(); }, teardown: function() { el.multiselectfilter("destroy"); el.multiselect("destroy"); el.remove(); } }); test("defaults", function(){ expect(1); ok( input.is(":visible"), "Filter input box is visible" ); }); test("filtering by node text", function(){ searchTest( "bbaa", 2); searchTest( "bbaarr", 1); searchTest( " bbaa ", 2, "searching for '#' with whitespace"); searchTest( " ", el.children().length, "searching for an empty string"); searchTest( "test", 5); searchTest( "one hundred", 1); searchTest( "with wor", 1); searchTest( " with wor ", 1); $.each("$ ^ / : // { } | -".split(" "), function( i, char ){ searchTest( char, 1 ); }); }); test("filtering by node value", function(){ // searchTest( "100", 1); // searchTest( "baz", 1); }); test("filtering & checking", function(){ searchFor("ba"); getVisible().each(triggerClick); equals(getChecked().length, 2, "Two checkboxes are selected"); equals(getSelected().length, 2, "Two option tags are selected"); getVisible().each(triggerClick); equals(getChecked().length, 0, "After clicking again, no checkboxes are selected"); equals(getSelected().length, 0, "After clicking again, no tags are selected"); }); test("checkAll / uncheckAll", function(){ searchFor("ba"); el.multiselect("checkAll"); equals(getChecked().length, 2, "checkAll: two checkboxes are selected"); equals(getSelected().length, 2, "checkAll: two option tags are selected"); el.multiselect("uncheckAll"); equals(getChecked().length, 0, "uncheckAll: no checkboxes are selected"); equals(getSelected().length, 0, "uncheckAll: no option tags are selected"); }); test("combination of filtering/methods/click events", function(){ searchFor("ba"); getVisible().first().each(triggerClick); equals(getChecked().length, 1, "selecting 1 of multiple results (checked)"); equals(getSelected().length, 1, "selecting 1 of multiple results (selected)"); searchFor(" "); equals(getChecked().length, 1, "clearing search, only 1 is still selected"); el.multiselect("uncheckAll"); equals(getChecked().length, 0, "uncheckAll, nothing is selected (checked)"); equals(getSelected().length, 0, "uncheckedAll, nothing is selected (selected)"); searchFor("one hundred") el.multiselect("checkAll"); equals(getChecked().length, 1, "checkAll on one matching result (checked)"); equals(getSelected().length, 1, "checkAll on one matching result (selected)"); searchFor("foo"); el.multiselect("checkAll"); equals(getChecked().length, 2, "checkAll on one matching result (checked)"); equals(getSelected().length, 2, "checkAll on one matching result (selected)"); }); })(jQuery);
JavaScript
(function($){ module("methods"); test("open", function(){ expect(2); el = $("select").multiselect().multiselect("open"); ok( el.multiselect("isOpen"), "isOpen parameter true" ); equals( menu().css("display"), "block", "Test display CSS property" ); el.multiselect("destroy"); }); test("close", function(){ expect(2); el = $("select").multiselect().multiselect("open").multiselect("close"); ok( !el.multiselect("isOpen"), "isOpen parameter false" ); equals( menu().css("display"), "none", "Test display CSS property" ); el.multiselect("destroy"); }); test("enable", function(){ expect(2); el = $("select").multiselect().multiselect("disable").multiselect("enable"); ok( button().is(":disabled") === false, "Button is enabled" ); ok( el.is(":disabled") === false, "Original select is enabled" ); el.multiselect("destroy"); }); test("disable", function(){ expect(2); // clone this one so the original is not affected el = $("select").clone(true).appendTo(body).multiselect().multiselect("disable"); ok( button().is(":disabled"), 'Button is disabled'); ok( el.is(":disabled"), 'Original select is disabled'); el.multiselect("destroy").remove(); }); test("enabling w/ pre-disabled tags (#216)", function(){ expect(5); el = $('<select><option disabled value="foo">foo</option><option value="bar">bar</option>') .appendTo(document.body) .multiselect(); var boxes = menu().find("input") var disabled = boxes.first(); var enabled = boxes.last(); var key = "ech-multiselect-disabled"; equals(disabled.is(":disabled"), true, "The first option is disabled"); el.multiselect("disable"); equals(disabled.data(key), undefined, "After disabling the widget, the pre-disabled option is not flagged to re-enable"); equals(enabled.data(key), true, "and the enabled option is flagged to be re-enable"); el.multiselect("enable"); equals(disabled.is(":disabled"), true, "After enabling, the first option is still disabled"); equals(disabled.data(key), undefined, "and the option no longer has the stored data flag"); el.multiselect("destroy").remove(); }); test("widget", function(){ expect(1); el = $("select").multiselect(); ok( menu().is("div.ui-multiselect-menu"), 'Widget is the menu element'); el.multiselect("destroy"); }); test("getButton", function(){ expect(1); el = $("select").multiselect(); var button = el.multiselect("getButton"); ok( button.is("button.ui-multiselect"), 'Button is the button element'); el.multiselect("destroy"); }); test("checkAll", function(){ expect(1); el = $("select").multiselect().multiselect("checkAll"); var inputs = menu().find("input"); ok( inputs.filter(":checked").length === inputs.length, 'All inputs selected on the widget?'); el.multiselect("destroy"); }); test("uncheckAll", function(){ expect(1); el = $("select").multiselect().multiselect("checkAll").multiselect("uncheckAll"); ok( menu().find("input:checked").length === 0, 'All inputs unchecked on the widget?'); el.multiselect("destroy"); }); test("isOpen", function(){ expect(2); el = $("select").multiselect().multiselect("open"); ok( el.multiselect("isOpen"), 'Testing isOpen method after calling open method'); el = $("select").multiselect("close"); ok( !el.multiselect("isOpen"), 'Testing isOpen method after calling close method'); el.multiselect("destroy"); }); test("destroy", function(){ expect(2); el = $("select").multiselect().multiselect("destroy"); ok( !$(".ui-multiselect").length , 'button.ui-multiselect removed from the DOM'); ok( !el.data("multiselect") , 'no more multiselect obj attached to elem'); }); test("getChecked", function(){ expect(2); el = $("select").multiselect().multiselect("checkAll"); equals( el.multiselect("getChecked").length, 9, 'number of checkboxes returned after checking all and calling getChecked'); el.multiselect("uncheckAll"); equals( el.multiselect("getChecked").length, 0, 'number of checkboxes returned after unchecking all and calling getChecked'); el.multiselect("destroy"); }); test("refresh", function(){ expect(4); el = $("select").clone().appendTo(body).multiselect(); el.empty().html('<option value="foo">foo</option><option value="bar">bar</option>'); el.multiselect('refresh'); var checkboxes, getCheckboxes = (function hai(){ checkboxes = menu().find('input[type="checkbox"]'); return hai; })(); equals( checkboxes.length, 2, "After clearing the select, adding 2 options, and refresh(), only 2 checkboxes exist"); equals( checkboxes.eq(0).val(), 'foo', 'first is foo' ); equals( checkboxes.eq(1).val(), 'bar', 'second is foo' ); // add one more w/ append, just for safety's sake el.append('<option value="baz">baz</option>'); el.multiselect('refresh'); getCheckboxes(); equals( checkboxes.eq(2).val(), 'baz', 'after an append() call, the third option is now' ); el.multiselect("destroy").remove(); }); test("position", function() { expect(2); var left = "500px"; el = $("select").clone().appendTo(body).multiselect(); // move the button button().css({ position: "absolute", left: left }); // sanity check the fact that the menu and button are out of sync notEqual(menu().css("left"), left, "After moving the button, the menu remains in its old position"); // update the menu position el.multiselect("position"); // make sure the new position is accurate equals(menu().css("left"), left, "After calling position(), the menu has updated to the same left value as the button"); el.multiselect("destroy").remove(); }); })(jQuery);
JavaScript
(function($){ var el, widget, elems; module("html", { setup: function() { el = $("select").multiselect(); widget = el.multiselect("widget"); } }); test("pull in optgroup's class", function(){ expect(5); elems = widget.find('.ui-multiselect-optgroup-label'); equals( elems.length, 3, 'There are three labels' ); elems.filter(":not(:last)").each( function() { equals($(this).hasClass('ui-multiselect-optgroup-label'),true,'Default class is present when no extra class is defined'); }); elems.filter(":last").each( function() { equals($(this).hasClass('ui-multiselect-optgroup-label'),true,'Default class is present when extra class is defined'); equals($(this).hasClass('optgroupClass'),true,'Extra class is present'); }); }); test("pull in options's class", function(){ expect(1); equals(widget.find('input[value="9"]').parents('li:first').hasClass('optionClass'),true,'Extra class is present'); }); })(jQuery);
JavaScript
/* * QUnit - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2009 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */ (function(window) { var defined = { setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { try { return !!sessionStorage.getItem; } catch(e){ return false; } })() } var testId = 0; var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { this.name = name; this.testName = testName; this.expected = expected; this.testEnvironmentArg = testEnvironmentArg; this.async = async; this.callback = callback; this.assertions = []; }; Test.prototype = { init: function() { var tests = id("qunit-tests"); if (tests) { var b = document.createElement("strong"); b.innerHTML = "Running " + this.name; var li = document.createElement("li"); li.appendChild( b ); li.id = this.id = "test-output" + testId++; tests.appendChild( li ); } }, setup: function() { if (this.module != config.previousModule) { if ( this.previousModule ) { QUnit.moduleDone( this.module, config.moduleStats.bad, config.moduleStats.all ); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; QUnit.moduleStart( this.module, this.moduleTestEnvironment ); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment); if (this.testEnvironmentArg) { extend(this.testEnvironment, this.testEnvironmentArg); } QUnit.testStart( this.testName, this.testEnvironment ); // allow utility functions to access the current test environment // TODO why?? QUnit.current_testEnvironment = this.testEnvironment; try { if ( !config.pollution ) { saveGlobal(); } this.testEnvironment.setup.call(this.testEnvironment); } catch(e) { // TODO use testName instead of name for no-markup message? QUnit.ok( false, "Setup failed on " + this.name + ": " + e.message ); } }, run: function() { if ( this.async ) { QUnit.stop(); } try { this.callback.call(this.testEnvironment); } catch(e) { // TODO use testName instead of name for no-markup message? fail("Test " + this.name + " died, exception and test follows", e, this.callback); QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { start(); } } }, teardown: function() { try { checkPollution(); this.testEnvironment.teardown.call(this.testEnvironment); } catch(e) { // TODO use testName instead of name for no-markup message? QUnit.ok( false, "Teardown failed on " + this.name + ": " + e.message ); } }, finish: function() { if ( this.expected && this.expected != this.assertions.length ) { QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if ( tests ) { var ol = document.createElement("ol"); for ( var i = 0; i < this.assertions.length; i++ ) { var assertion = this.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible defined.sessionStorage && sessionStorage.setItem("qunit-" + this.testName, bad); if (bad == 0) { ol.style.display = "none"; } var b = document.createElement("strong"); b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; addEvent(b, "click", function() { var next = b.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { target = target.parentNode; } if ( window.location && target.nodeName.toLowerCase() === "strong" ) { window.location.search = "?" + encodeURIComponent(getText([target]).replace(/\(.+\)$/, "").replace(/(^\s*|\s*$)/g, "")); } }); var li = id(this.id); li.className = bad ? "fail" : "pass"; li.style.display = resultDisplayStyle(!bad); li.removeChild( li.firstChild ); li.appendChild( b ); li.appendChild( ol ); if ( bad ) { var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "block"; id("qunit-filter-pass").disabled = null; } } } else { for ( var i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } try { QUnit.reset(); } catch(e) { // TODO use testName instead of name for no-markup message? fail("reset() failed, following Test " + this.name + ", exception and reset fn follows", e, QUnit.reset); } QUnit.testDone( this.testName, bad, this.assertions.length ); }, queue: function() { var test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // defer when previous test run passed, if storage is available var bad = defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.testName); if (bad) { run(); } else { synchronize(run); }; } } var QUnit = { // call on start of module test to prepend name to all tests module: function(name, testEnvironment) { config.previousModule = config.currentModule; config.currentModule = name; config.currentModuleTestEnviroment = testEnvironment; }, asyncTest: function(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = 0; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = '<span class="test-name">' + testName + '</span>', testEnvironmentArg; if ( arguments.length === 2 ) { callback = expected; expected = null; } // is 2nd argument a testEnvironment? if ( expected && typeof expected === 'object') { testEnvironmentArg = expected; expected = null; } if ( config.currentModule ) { name = '<span class="module-name">' + config.currentModule + "</span>: " + name; } if ( !validTest(config.currentModule + ": " + testName) ) { return; } var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); test.previousModule = config.previousModule; test.module = config.currentModule; test.moduleTestEnvironment = config.currentModuleTestEnviroment; test.queue(); }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function(asserts) { config.current.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function(a, msg) { a = !!a; var details = { result: a, message: msg }; msg = escapeHtml(msg); QUnit.log(a, msg, details); config.current.assertions.push({ result: a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equal: function(actual, expected, message) { QUnit.push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { QUnit.push(expected != actual, actual, expected, message); }, deepEqual: function(actual, expected, message) { QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); }, notDeepEqual: function(actual, expected, message) { QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); }, strictEqual: function(actual, expected, message) { QUnit.push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { QUnit.push(expected !== actual, actual, expected, message); }, raises: function(fn, message) { try { fn(); QUnit.ok( false, message ); } catch (e) { QUnit.ok( true, message ); } }, start: function() { // A slight delay, to avoid any current callbacks if ( defined.setTimeout ) { window.setTimeout(function() { if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(); }, 13); } else { config.blocking = false; process(); } }, stop: function(timeout) { config.blocking = true; if ( timeout && defined.setTimeout ) { config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); QUnit.start(); }, timeout); } } }; // Backwards compatibility, deprecated QUnit.equals = QUnit.equal; QUnit.same = QUnit.deepEqual; // Maintain internal state var config = { // The queue of tests to run queue: [], // block until document ready blocking: true }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, GETParams = location.search.slice(1).split('&'); for ( var i = 0; i < GETParams.length; i++ ) { GETParams[i] = decodeURIComponent( GETParams[i] ); if ( GETParams[i] === "noglobals" ) { GETParams.splice( i, 1 ); i--; config.noglobals = true; } else if ( GETParams[i].search('=') > -1 ) { GETParams.splice( i, 1 ); i--; } } // restrict modules/tests by get parameters config.filters = GETParams; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // Expose the API as global variables, unless an 'exports' // object exists, in that case we assume we're in CommonJS if ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit; } else { extend(exports, QUnit); exports.QUnit = QUnit; } // define these after exposing globals to keep them in these QUnit namespace only extend(QUnit, { config: config, // Initialize the configuration options init: function() { extend(config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, updateRate: 1000, blocking: false, autostart: true, autorun: false, filters: [], queue: [] }); var tests = id("qunit-tests"), banner = id("qunit-banner"), result = id("qunit-testresult"); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } }, /** * Resets the test setup. Useful for tests that modify the DOM. * * If jQuery is available, uses jQuery's html(), otherwise just innerHTML. */ reset: function() { if ( window.jQuery ) { jQuery( "#main, #qunit-fixture" ).html( config.fixture ); } else { var main = id( 'main' ) || id( 'qunit-fixture' ); if ( main ) { main.innerHTML = config.fixture; } } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Safe object type checking is: function( type, obj ) { return QUnit.objectType( obj ) == type; }, objectType: function( obj ) { if (typeof obj === "undefined") { return "undefined"; // consider: typeof null === object } if (obj === null) { return "null"; } var type = Object.prototype.toString.call( obj ) .match(/^\[object\s(.*)\]$/)[1] || ''; switch (type) { case 'Number': if (isNaN(obj)) { return "nan"; } else { return "number"; } case 'String': case 'Boolean': case 'Array': case 'Date': case 'RegExp': case 'Function': return type.toLowerCase(); } if (typeof obj === "object") { return "object"; } return undefined; }, push: function(result, actual, expected, message) { var details = { result: result, message: message, actual: actual, expected: expected }; message = escapeHtml(message) || (result ? "okay" : "failed"); message = '<span class="test-message">' + message + "</span>"; expected = escapeHtml(QUnit.jsDump.parse(expected)); actual = escapeHtml(QUnit.jsDump.parse(actual)); var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; if (actual != expected) { output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>'; } if (!result) { var source = sourceFromStacktrace(); if (source) { details.source = source; output += '<tr class="test-source"><th>Source: </th><td><pre>' + source +'</pre></td></tr>'; } } output += "</table>"; QUnit.log(result, message, details); config.current.assertions.push({ result: !!result, message: output }); }, // Logging callbacks begin: function() {}, done: function(failures, total) {}, log: function(result, message) {}, testStart: function(name, testEnvironment) {}, testDone: function(name, failures, total) {}, moduleStart: function(name, testEnvironment) {}, moduleDone: function(name, failures, total) {} }); if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } addEvent(window, "load", function() { QUnit.begin(); // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var banner = id("qunit-header"); if ( banner ) { var paramsIndex = location.href.lastIndexOf(location.search); if ( paramsIndex > -1 ) { var mainPageLocation = location.href.slice(0, paramsIndex); if ( mainPageLocation == location.href ) { banner.innerHTML = '<a href=""> ' + banner.innerHTML + '</a> '; } else { var testName = decodeURIComponent(location.search.slice(1)); banner.innerHTML = '<a href="' + mainPageLocation + '">' + banner.innerHTML + '</a> &#8250; <a href="">' + testName + '</a>'; } } } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "none"; var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; filter.disabled = true; addEvent( filter, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("pass") > -1 ) { li[i].style.display = filter.checked ? "none" : ""; } } }); toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); } var main = id('main') || id('qunit-fixture'); if ( main ) { config.fixture = main.innerHTML; } if (config.autostart) { QUnit.start(); } }); function done() { config.autorun = true; // Log the last module results if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), html = ['Tests completed in ', +new Date - config.started, ' milliseconds.<br/>', '<span class="passed">', config.stats.all - config.stats.bad, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad,'</span> failed.'].join(''); if ( banner ) { banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); } if ( tests ) { var result = id("qunit-testresult"); if ( !result ) { result = document.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests.nextSibling ); } result.innerHTML = html; } QUnit.done( config.stats.bad, config.stats.all ); } function validTest( name ) { var i = config.filters.length, run = false; if ( !i ) { return true; } while ( i-- ) { var filter = config.filters[i], not = filter.charAt(0) == '!'; if ( not ) { filter = filter.slice(1); } if ( name.indexOf(filter) !== -1 ) { return !not; } if ( not ) { run = true; } } return run; } // so far supports only Firefox, Chrome and Opera (buggy) // could be extended in the future to use something like https://github.com/csnover/TraceKit function sourceFromStacktrace() { try { throw new Error(); } catch ( e ) { if (e.stacktrace) { // Opera return e.stacktrace.split("\n")[6]; } else if (e.stack) { // Firefox, Chrome return e.stack.split("\n")[4]; } } } function resultDisplayStyle(passed) { return passed && id("qunit-filter-pass") && id("qunit-filter-pass").checked ? 'none' : ''; } function escapeHtml(s) { if (!s) { return ""; } s = s + ""; return s.replace(/[\&"<>\\]/g, function(s) { switch(s) { case "&": return "&amp;"; case "\\": return "\\\\"; case '"': return '\"'; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); } function synchronize( callback ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(); } } function process() { var start = (new Date()).getTime(); while ( config.queue.length && !config.blocking ) { if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) { config.queue.shift()(); } else { window.setTimeout( process, 13 ); break; } } if (!config.blocking && !config.queue.length) { done(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { config.pollution.push( key ); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( old, config.pollution ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); config.current.expected++; } var deletedGlobals = diff( config.pollution, old ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); config.current.expected++; } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result; } function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for ( var prop in b ) { a[prop] = b[prop]; } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } // Test for equality any JavaScript type. // Discussions and reference: http://philrathe.com/articles/equiv // Test suites: http://philrathe.com/tests/equiv // Author: Philippe Rathé <prathe@gmail.com> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions var parents = []; // stack to avoiding loops from circular referencing // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = QUnit.objectType(o); if (prop) { if (QUnit.objectType(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function (b) { return isNaN(b); }, "date": function (b, a) { return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function (b, a) { return QUnit.objectType(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function () { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function (b, a) { var i, j, loop; var len; // b could be an object literal here if ( ! (QUnit.objectType(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } //track reference to avoid circular references parents.push(a); for (i = 0; i < len; i++) { loop = false; for(j=0;j<parents.length;j++){ if(parents[j] === a[i]){ loop = true;//dont rewalk array } } if (!loop && ! innerEquiv(a[i], b[i])) { parents.pop(); return false; } } parents.pop(); return true; }, "object": function (b, a) { var i, j, loop; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of strings // comparing constructors is more strict than using instanceof if ( a.constructor !== b.constructor) { return false; } // stack constructor before traversing properties callers.push(a.constructor); //track reference to avoid circular references parents.push(a); for (i in a) { // be strict: don't ensures hasOwnProperty and go deep loop = false; for(j=0;j<parents.length;j++){ if(parents[j] === a[i]) loop = true; //don't go down the same path twice } aProperties.push(i); // collect a's properties if (!loop && ! innerEquiv(a[i], b[i])) { eq = false; break; } } callers.pop(); // unstack, we are done parents.pop(); for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties.sort()); } }; }(); innerEquiv = function () { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function (a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [b, a]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1)); }; return innerEquiv; }(); /** * jsDump * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) * Date: 5/15/2008 * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] ); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; return type == 'function' ? parser.call( this, obj ) : type == 'string' ? parser : this.parsers.error; }, typeOf:function( obj ) { var type; if ( obj === null ) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (QUnit.is("RegExp", obj)) { type = "regexp"; } else if (QUnit.is("Date", obj)) { type = "date"; } else if (QUnit.is("Function", obj)) { type = "function"; } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { type = "window"; } else if (obj.nodeType === 9) { type = "document"; } else if (obj.nodeType) { type = "node"; } else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) { type = "array"; } else { type = typeof obj; } return type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', undefined:'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map ) { var ret = [ ]; QUnit.jsDump.up(); for ( var key in map ) ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(map[key]) ); QUnit.jsDump.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = QUnit.jsDump.HTML ? '&lt;' : '<', close = QUnit.jsDump.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in QUnit.jsDump.DOMAttrs ) { var val = node[QUnit.jsDump.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); // from Sizzle.js function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; }; /* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" */ QUnit.diff = (function() { function diff(o, n){ var ns = new Object(); var os = new Object(); for (var i = 0; i < n.length; i++) { if (ns[n[i]] == null) ns[n[i]] = { rows: new Array(), o: null }; ns[n[i]].rows.push(i); } for (var i = 0; i < o.length; i++) { if (os[o[i]] == null) os[o[i]] = { rows: new Array(), n: null }; os[o[i]].rows.push(i); } for (var i in ns) { if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] }; o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] }; } } for (var i = 0; i < n.length - 1; i++) { if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) { n[i + 1] = { text: n[i + 1], row: n[i].row + 1 }; o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 }; } } for (var i = n.length - 1; i > 0; i--) { if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && n[i - 1] == o[n[i].row - 1]) { n[i - 1] = { text: n[i - 1], row: n[i].row - 1 }; o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 }; } } return { o: o, n: n }; } return function(o, n){ o = o.replace(/\s+$/, ''); n = n.replace(/\s+$/, ''); var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); var str = ""; var oSpace = o.match(/\s+/g); if (oSpace == null) { oSpace = [" "]; } else { oSpace.push(" "); } var nSpace = n.match(/\s+/g); if (nSpace == null) { nSpace = [" "]; } else { nSpace.push(" "); } if (out.n.length == 0) { for (var i = 0; i < out.o.length; i++) { str += '<del>' + out.o[i] + oSpace[i] + "</del>"; } } else { if (out.n[0].text == null) { for (n = 0; n < out.o.length && out.o[n].text == null; n++) { str += '<del>' + out.o[n] + oSpace[n] + "</del>"; } } for (var i = 0; i < out.n.length; i++) { if (out.n[i].text == null) { str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; } else { var pre = ""; for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { pre += '<del>' + out.o[n] + oSpace[n] + "</del>"; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; }; })(); })(this);
JavaScript
(function($){ module("events"); test("multiselectopen", function(){ expect(27); // inject widget el = $("<select multiple><option value='foo'>foo</option></select>").appendTo(body); el.multiselect({ open: function(e,ui){ ok( true, 'option: multiselect("open") fires open callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectopen', 'option: event type in callback'); equals(menu().css("display"), 'block', 'menu display css property equals block'); same(ui, {}, 'option: ui hash in callback'); } }) .bind("multiselectopen", function(e,ui){ ok(true, 'event: multiselect("open") fires multiselectopen event'); equals(this, el[0], 'event: context of event'); same(ui, {}, 'event: ui hash'); }); // now try to open it.. el.multiselect("open") // make sure the width of the menu and button are equivalent equals( button().outerWidth(), menu().outerWidth(), 'button and menu widths are equivalent'); // close el.multiselect("close"); // make sure a click event on the button opens the menu as well. button().trigger("click"); el.multiselect("close"); // make sure a click event on a span inside the button opens the menu as well. button().find("span:first").trigger("click"); // reset for next test el.multiselect("destroy").remove(); // now try returning false prevent opening el = $("<select></select>") .appendTo(body) .multiselect() .bind("multiselectbeforeopen", function(){ ok( true, "event: binding multiselectbeforeopen to return false (prevent from opening)" ); return false; }) .multiselect("open"); ok( !el.multiselect("isOpen"), "multiselect is not open after multiselect('open')" ); el.multiselect("destroy").remove(); }); test("multiselectclose", function(){ expect(25); // inject widget el = $("<select multiple><option>foo</option></select>").appendTo(body); el.multiselect({ close: function(e,ui){ ok( true, 'option: multiselect("close") fires close callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectclose', 'option: event type in callback'); equals(menu().css("display"), 'none', 'menu display css property equals none'); same(ui, {}, 'option: ui hash'); } }) .bind("multiselectclose", function(e,ui){ ok(true, 'multiselect("close") fires multiselectclose event'); equals(this, el[0], 'event: context of event'); same(ui, {}, 'event: ui hash'); }) .multiselect("open") .multiselect("close") .multiselect("open"); // make sure a click event on the button closes the menu as well. button().click(); el.multiselect("open"); // make sure a click event on a span inside the button closes the menu as well. button().find("span:first").click(); // make sure that the menu is actually closed. see issue #68 ok( el.multiselect('isOpen') === false, 'menu is indeed closed' ); el.multiselect("destroy").remove(); }); test("multiselectbeforeclose", function(){ expect(8); // inject widget el = $("<select multiple></select>").appendTo(body); el.multiselect({ beforeclose: function(e,ui){ ok( true, 'option: multiselect("beforeclose") fires close callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectbeforeclose', 'option: event type in callback'); same(ui, {}, 'option: ui hash'); } }) .bind("multiselectbeforeclose", function(e,ui){ ok(true, 'multiselect("beforeclose") fires multiselectclose event'); equals(this, el[0], 'event: context of event'); same(ui, {}, 'event: ui hash'); }) .multiselect("open") .multiselect("close"); el.multiselect("destroy").remove(); // test 'return false' functionality el = $("<select multiple></select>").appendTo(body); el.multiselect({ beforeclose: function(){ return false; } }); el.multiselect('open').multiselect('close'); ok( menu().is(':visible') && el.multiselect("isOpen"), "returning false inside callback prevents menu from closing" ); el.multiselect("destroy").remove(); }); test("multiselectclick", function(){ expect(28); var times = 0; // inject widget el = $("<select multiple><option value='1'>Option 1</option><option value='2'>Option 2</option></select>") .appendTo(body); el.multiselect({ click: function(e,ui){ ok(true, 'option: triggering the click event on the second checkbox fires the click callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectclick', 'option: event type in callback'); equals(ui.value, "2", "option: ui.value equals"); equals(ui.text, "Option 2", "option: ui.title equals"); if(times === 0) { equals(ui.checked, true, "option: ui.checked equals"); } else if(times === 1) { equals(ui.checked, false, "option: ui.checked equals"); } } }) .bind("multiselectclick", function(e,ui){ ok(true, 'event: triggering the click event on the second checkbox triggers multiselectclick'); equals(this, el[0], 'event: context of event'); equals(ui.value, "2", "event: ui.value equals"); equals(ui.text, "Option 2", "event: ui.title equals"); if(times === 0) { equals(ui.checked, true, "option: ui.checked equals"); } else if(times === 1) { equals(ui.checked, false, "option: ui.checked equals"); } }) .bind("change", function(e){ if(++times === 1){ equals(el.val().join(), "2", "event: select element val() within the change event is correct" ); } else { equals(el.val(), null, "event: select element val() within the change event is correct" ); } ok(true, "event: the select's change event fires"); }) .multiselect("open"); // trigger a click event on the input var lastInput = menu().find("input").last(); lastInput[0].click(); // trigger once more. lastInput[0].click(); // make sure it has focus equals(true, lastInput.is(":focus"), "The input has focus"); // make sure menu isn't closed automatically equals( true, el.multiselect('isOpen'), 'menu stays open' ); el.multiselect("destroy").remove(); }); test("multiselectcheckall", function(){ expect(10); // inject widget el = $('<select multiple><option value="1">Option 1</option><option value="2">Option 2</option></select>').appendTo(body); el.multiselect({ checkAll: function(e,ui){ ok( true, 'option: multiselect("checkAll") fires checkall callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectcheckall', 'option: event type in callback'); same(ui, {}, 'option: ui hash in callback'); } }) .bind("multiselectcheckall", function(e,ui){ ok( true, 'event: multiselect("checkall") fires multiselectcheckall event' ); equals(this, el[0], 'event: context of event'); same(ui, {}, 'event: ui hash'); }) .bind("change", function(){ ok(true, "event: the select's change event fires"); equals( el.val().join(), "1,2", "event: select element val() within the change event is correct" ); }) .multiselect("open") .multiselect("checkAll"); equals(menu().find("input").first().is(":focus"), true, "The first input has focus"); el.multiselect("destroy").remove(); }); test("multiselectuncheckall", function(){ expect(10); // inject widget el = $('<select multiple><option value="1">Option 1</option><option value="2">Option 2</option></select>').appendTo(body); el.multiselect({ uncheckAll: function(e,ui){ ok( true, 'option: multiselect("uncheckAll") fires uncheckall callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectuncheckall', 'option: event type in callback'); same(ui, {}, 'option: ui hash in callback'); } }) .bind("multiselectuncheckall", function(e,ui){ ok( true, 'event: multiselect("uncheckall") fires multiselectuncheckall event' ); equals(this, el[0], 'event: context of event'); same(ui, {}, 'event: ui hash'); }) .bind("change", function(){ ok(true, "event: the select's change event fires"); equals( el.val(), null, "event: select element val() within the change event is correct" ); }) .multiselect("open") .multiselect("uncheckAll"); equals(menu().find("input").first().is(":focus"), true, "The first input has focus"); el.multiselect("destroy").remove(); }); test("multiselectbeforeoptgrouptoggle", function(){ expect(10); // inject widget el = $('<select multiple><optgroup label="Set One"><option value="1">Option 1</option><option value="2">Option 2</option></optgroup></select>') .appendTo(body); el.bind("change", function(){ ok(true, "the select's change event fires"); }) .multiselect({ beforeoptgrouptoggle: function(e,ui){ equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectbeforeoptgrouptoggle', 'option: event type in callback'); equals(ui.label, "Set One", 'option: ui.label equals'); equals(ui.inputs.length, 2, 'option: number of inputs in the ui.inputs key'); } }) .bind("multiselectbeforeoptgrouptoggle", function(e,ui){ ok( true, 'option: multiselect("uncheckall") fires multiselectuncheckall event' ); equals(this, el[0], 'event: context of event'); equals(ui.label, "Set One", 'event: ui.label equals'); equals(ui.inputs.length, 2, 'event: number of inputs in the ui.inputs key'); }) .multiselect("open"); menu().find("li.ui-multiselect-optgroup-label a").click(); el.multiselect("destroy").remove(); el = el.clone(); // test return false preventing checkboxes from activating el.bind("change", function(){ ok( true ); // should not fire }).multiselect({ beforeoptgrouptoggle: function(){ return false; }, // if this fires the expected count will be off. just a redundant way of checking that return false worked optgrouptoggle: function(){ ok( true ); } }).appendTo( body ); var label = menu().find("li.ui-multiselect-optgroup-label a").click(); equals( menu().find(":input:checked").length, 0, "when returning false inside the optgrouptoggle handler, no checkboxes are checked" ); el.multiselect("destroy").remove(); }); test("multiselectoptgrouptoggle", function(){ expect(12); // inject widget el = $('<select multiple><optgroup label="Set One"><option value="1">Option 1</option><option value="2">Option 2</option></optgroup></select>').appendTo(body); el.multiselect({ optgrouptoggle: function(e,ui){ equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectoptgrouptoggle', 'option: event type in callback'); equals(ui.label, "Set One", 'option: ui.label equals'); equals(ui.inputs.length, 2, 'option: number of inputs in the ui.inputs key'); equals(ui.checked, true, 'option: ui.checked equals true'); } }) .bind("multiselectoptgrouptoggle", function(e,ui){ ok( true, 'option: multiselect("uncheckall") fires multiselectuncheckall event' ); equals(this, el[0], 'event: context of event'); equals(ui.label, "Set One", 'event: ui.label equals'); equals(ui.inputs.length, 2, 'event: number of inputs in the ui.inputs key'); equals(ui.checked, true, 'event: ui.checked equals true'); }) .multiselect("open"); // trigger native click event on optgroup menu().find("li.ui-multiselect-optgroup-label a").click(); equals(menu().find(":input:checked").length, 2, "both checkboxes are actually checked" ); equals(menu().find("input").first().is(":focus"), true, "The first input has focus"); el.multiselect("destroy").remove(); }); })(jQuery);
JavaScript
var el; var body = document.body; function button(){ return el.next(); } function menu(){ return el.multiselect("widget"); } function header(){ return menu().find('.ui-multiselect-header'); } QUnit.done = function(){ $("select").hide(); }; (function($){ module("core"); test("init", function(){ expect(6); el = $("select").multiselect(), $header = header(); ok( $header.find('a.ui-multiselect-all').css('display') !== 'none', 'select all is visible' ); ok( $header.find('a.ui-multiselect-none').css('display') !== 'none', 'select none is visible' ); ok( $header.find('a.ui-multiselect-close').css('display') !== 'none', 'close link is visible' ); ok( menu().is(':hidden'), 'menu is hidden'); ok( el.is(":hidden"), 'the original select is hidden'); ok( el.attr('tabIndex') == 2, 'button inherited the correct tab index'); el.multiselect("destroy"); }); test("form submission", function(){ expect(3); var form = $('<form></form>').appendTo(body), data; el = $('<select id="test" name="test" multiple="multiple"><option value="foo" selected="selected">foo</option><option value="bar">bar</option></select>') .appendTo(form) .multiselect() .multiselect("checkAll"); data = form.serialize(); equals( data, 'test=foo&test=bar', 'after checking all and serializing the form, the correct keys were serialized'); el.multiselect("uncheckAll"); data = form.serialize(); equals( data.length, 0, 'after unchecking all and serializing the form, nothing was serialized'); // re-check all and destroy, exposing original select el.multiselect("checkAll").multiselect("destroy"); data = form.serialize(); equals( data, 'test=foo&test=bar', 'after checking all, destroying the widget, and serializing the form, the correct keys were serialized'); form.remove(); }); test("form submission, optgroups", function(){ expect(4); var form = $('<form></form>').appendTo(body), data; el = $('<select id="test" name="test" multiple="multiple"><optgroup label="foo"><option value="foo">foo</option><option value="bar">bar</option></optgroup><optgroup label="bar"><option value="baz">baz</option><option value="bax">bax</option></optgroup></select>') .appendTo(form) .multiselect() .multiselect("checkAll"); data = form.serialize(); equals( data, 'test=foo&test=bar&test=baz&test=bax', 'after checking all and serializing the form, the correct keys were serialized'); el.multiselect("uncheckAll"); data = form.serialize(); equals( data.length, 0, 'after unchecking all and serializing the form, nothing was serialized'); // re-check all and destroy, exposing original select el.multiselect("checkAll").multiselect("destroy"); data = form.serialize(); equals( data, 'test=foo&test=bar&test=baz&test=bax', 'after checking all, destroying the widget, and serializing the form, the correct keys were serialized'); // reset option tags el.find("option").each(function(){ this.selected = false; }); // test checking one option in both optgroups el.multiselect(); // finds the first input in each optgroup (assumes 2 options per optgroup) el.multiselect("widget").find('.ui-multiselect-checkboxes li:not(.ui-multiselect-optgroup-label) input:even').each(function( i ){ this.click(); }); data = form.serialize(); equals( data, 'test=foo&test=baz', 'after manually checking one input in each group, the correct two are serialized'); el.multiselect('destroy'); form.remove(); }); test("form submission, single select", function(){ expect(7); var form = $('<form></form>').appendTo("body"), radios, data; el = $('<select id="test" name="test" multiple="multiple"><option value="foo">foo</option><option value="bar">bar</option><option value="baz">baz</option></select>') .appendTo(form) .multiselect({ multiple: false }); // select multiple radios to ensure that, in the underlying select, only one // will remain selected radios = menu().find(":radio"); radios[0].click(); radios[2].click(); radios[1].click(); data = form.serialize(); equals( data, 'test=bar', 'the form serializes correctly after clicking on multiple radio buttons'); equals( radios.filter(":checked").length, 1, 'Only one radio button is selected'); // uncheckAll method el.multiselect("uncheckAll"); data = form.serialize(); equals( data.length, 0, 'After unchecking all, nothing was serialized'); equals( radios.filter(":checked").length, 0, 'No radio buttons are selected'); // checkAll method el.multiselect("checkAll"); data = form.serialize(); equals( el.multiselect("getChecked").length, 1, 'After checkAll, only one radio is selected'); equals( radios.filter(":checked").length, 1, 'One radio is selected'); // expose original el.multiselect("destroy"); data = form.serialize(); equals( data, 'test=foo&test=bar&test=baz', 'after destroying the widget and serializing the form, the correct key was serialized: ' + data); form.remove(); }); asyncTest("form reset, nothing pre-selected", function(){ expect(2); var form = $('<form></form>').appendTo(body), noneSelected = 'Please check something'; el = $('<select name="test" multiple="multiple"><option value="foo">foo</option><option value="bar">bar</option></select>') .appendTo(form) .multiselect({ noneSelectedText: noneSelected }) .multiselect("checkAll"); // trigger reset form.trigger("reset"); setTimeout(function(){ equals( menu().find(":checked").length, 0, "no checked checkboxes" ); equals( button().text(), noneSelected, "none selected text"); el.multiselect('destroy'); form.remove(); start(); }, 10); }); asyncTest("form reset, pre-selected options", function(){ expect(2); var form = $('<form></form>').appendTo(body); el = $('<select name="test" multiple="multiple"><option value="foo" selected="selected">foo</option><option value="bar" selected="selected">bar</option></select>') .appendTo(form) .multiselect({ selectedText: '# of # selected' }) .multiselect("uncheckAll"); // trigger reset form.trigger("reset"); setTimeout(function(){ equals( menu().find(":checked").length, 2, "two checked checkboxes" ); equals( button().text(), "2 of 2 selected", "selected text" ); el.multiselect('destroy'); form.remove(); start(); }, 10); }); })(jQuery);
JavaScript
(function($){ module("options"); test("noneSelectedText", function(){ expect(7); var text; el = $("select").multiselect({ noneSelectedText: 'None Selected' }); // read from widget text = el.multiselect("option", "noneSelectedText"); equals( button().text(), text, 'on init, button reads "None Selected"'); el.multiselect("checkAll"); ok( button().text() !== text, 'after checkAll, button no longer reads "None Selected"'); el.multiselect("uncheckAll"); equals( button().text(), text, 'after uncheckAll, button text restored to "None Selected"'); // change the option value el.multiselect("option", "noneSelectedText", "No Checkboxes Checked"); equals( el.multiselect("option", "noneSelectedText"), "No Checkboxes Checked", "new noneSelectedText value set correctly"); // read updated value from widget text = el.multiselect("option", "noneSelectedText"); // test against the new value equals( button().text(), text, 'after changing the option value, button now reads "No Checkboxes Checked"'); el.multiselect("checkAll"); ok( button().text() !== text, 'after checkAll, button no longer reads "No Checkboxes Checked"'); el.multiselect("uncheckAll"); equals( button().text(), text, 'after uncheckAll, button text restored to "No Checkboxes Checked"'); el.multiselect("destroy"); }); test("selectedText", function(){ expect(3); var numOptions = $("select option").length; el = $("select").multiselect({ selectedText: '# of # selected' }); el.multiselect("checkAll"); equals( button().text(), numOptions+' of '+numOptions+' selected', 'after checkAll, button reflects the total number of checked boxes'); // change option value el.multiselect("option", "selectedText", function( numChecked ){ return numChecked + ' options selected'; }); equals( button().text(), numOptions+' options selected', 'after changing the option to a function value, button reflects the new text'); // uncheck all el.multiselect("uncheckAll"); equals( button().text(), el.multiselect("option","noneSelectedText"), 'after unchecking all, button text now reflects noneSelectedText option value'); el.multiselect("destroy"); }); test("selectedList", function(){ expect(2); var html = '<select multiple><option value="foo">foo &quot;with quotes&quot;</option><option value="bar">bar</option><option value="baz">baz</option></select>'; el = $(html).appendTo("body").multiselect({ selectedList: 3 }); el.multiselect("checkAll"); equals( button().text(), 'foo "with quotes", bar, baz', 'after checkAll, button text is a list of all options in the select'); el.multiselect("destroy").remove(); el = $(html).appendTo("body").multiselect({ selectedList: 2 }); el.multiselect("checkAll"); equals( button().text(), '3 selected', 'after checkAll with a limited selectedList value, button value displays number of checked'); el.multiselect("destroy").remove(); }); function asyncSelectedList( useTrigger, message ){ expect(1); stop(); var html = '<select multiple><option value="foo">foo</option><option value="bar">bar</option><option value="baz">baz</option></select>', checkboxes; el = $(html).appendTo(body).multiselect({ selectedList: 2 }); checkboxes = el.multiselect("widget").find(":checkbox"); if( useTrigger ){ checkboxes.eq(0).trigger('click'); checkboxes.eq(1).trigger('click'); } else { checkboxes.eq(0)[0].click(); checkboxes.eq(1)[0].click(); } setTimeout(function(){ equals( button().text(), 'foo, bar', message); el.multiselect("destroy").remove(); start(); }, 10); } test("selectedList - manual trigger - jQuery", function(){ asyncSelectedList( true, 'manually checking items with trigger()' ); }); test("selectedList - manual trigger - native", function(){ asyncSelectedList( false, 'manually checking items with element.click()' ); }); test("selectedList - encoding", function() { expect(1); el = $('<select><option value="A&amp;E">A&amp;E</option></select>') .appendTo("body") .multiselect({ selectedList: 1 }); equals(button().text(), 'A&amp;E'); el.multiselect("destroy").remove(); }); test("height", function(){ expect(2); var height = 234; el = $("select").multiselect({ height: height }).multiselect("open"); equals( height, menu().find("ul.ui-multiselect-checkboxes").height(), 'height after opening propertly set to '+height ); // change height and re-test height = 333; el.multiselect("option", "height", height); equals( height, menu().find("ul.ui-multiselect-checkboxes").height(), 'changing value through api to '+height ); el.multiselect("destroy"); }); test("minWidth", function(){ expect(3); var minWidth = 321; el = $("select").multiselect({ minWidth:minWidth }).multiselect("open"); equals( minWidth, button().outerWidth(), 'outerWidth of button is ' + minWidth ); // change height and re-test minWidth = 351; el.multiselect("option", "minWidth", minWidth); equals( minWidth, button().outerWidth(), 'changing value through api to '+minWidth); // change height to something that should fail. minWidth = 10; el.multiselect("option", "minWidth", minWidth); var outerWidth = button().outerWidth(); ok( minWidth !== outerWidth, 'changing value through api to '+minWidth+' (too small), outerWidth is actually ' + outerWidth); el.multiselect("destroy"); }); test("checkAllText", function(){ expect(2); var text = "foo"; el = $("select").multiselect({ checkAllText:text }); equals( text, menu().find(".ui-multiselect-all").text(), 'check all link reads '+text ); // set through option text = "bar"; el.multiselect("option","checkAllText","bar"); equals( text, menu().find(".ui-multiselect-all").text(), 'check all link reads '+text ); el.multiselect("destroy"); }); test("uncheckAllText", function(){ expect(2); var text = "foo"; el = $("select").multiselect({ uncheckAllText:text }); equals( text, menu().find(".ui-multiselect-none").text(), 'check all link reads '+text ); // set through option text = "bar"; el.multiselect("option","uncheckAllText","bar"); equals( text, menu().find(".ui-multiselect-none").text(), 'changing value through api to '+text ); el.multiselect("destroy"); }); test("autoOpen", function(){ expect(2); el = $("select").multiselect({ autoOpen:false }); ok( menu().is(":hidden"), 'menu is hidden with autoOpen off'); el.multiselect("destroy"); el = $("select").multiselect({ autoOpen:true }); ok( menu().is(":visible"), 'menu is visible with autoOpen on'); el.multiselect("destroy"); // no built in support for change on the fly; not testing it. }); test("multiple (false - single select)", function(){ expect(10); el = $("select").multiselect({ multiple:false }); // get some references var $menu = menu(), $header = header(); ok( $header.find('a.ui-multiselect-all').is(':hidden'), 'select all link is hidden' ); ok( $header.find('a.ui-multiselect-none').is(':hidden'), 'select none link is hidden' ); ok( $header.find('a.ui-multiselect-close').css('display') !== 'hidden', 'close link is visible' ); ok( !$menu.find(":checkbox").length, 'no checkboxes are present'); ok( $menu.find(":radio").length > 0, 'but radio boxes are'); // simulate click on ALL radios var radios = $menu.find(":radio").trigger("click"); // at the end of that, only one radio should be checked and the menu closed equals( radios.filter(":checked").length, 1, 'After checking all radios, only one is actually checked'); equals( false, el.multiselect('isOpen'), 'Menu is closed' ); // uncheck boxes... should only be one radios.filter(":checked").trigger("click"); // method calls el.multiselect("checkAll"); equals( $menu.find("input:radio:checked").length, 1, 'After checkAll method call only one is actually checked'); el.multiselect("uncheckAll"); equals( $menu.find("input:radio:checked").length, 0, 'After uncheckAll method nothing is checked'); // check/uncheck all links equals( $menu.find(".ui-multiselect-all, ui-multiselect-none").filter(":visible").length, 0, "Check/uncheck all links don't exist"); el.multiselect("destroy"); }); test("multiple (changing dynamically)", function(){ expect(6); el = $('<select multiple><option value="foo">foo</option></select>') .appendTo("body") .multiselect(); el.multiselect("option", "multiple", false); equals(el[0].multiple, false, "When changing a multiple select to a single select, the select element no longer has the multiple property"); equals(menu().hasClass("ui-multiselect-single"), true, "...and the menu now has the single select class"); equals(menu().find('input[type="radio"]').length, 1, "...and the checkbox is now a radio button"); el.multiselect("option", "multiple", true); equals(el[0].multiple, true, "When changing a single select to a multiple select, the select element has the multiple property"); equals(menu().hasClass("ui-multiselect-single"), false, "...and the menu doesn't have the single select class"); equals(menu().find('input[type="checkbox"]').length, 1, "...and the radio button is now a checkbox"); el.multiselect("destroy").remove(); }); test("classes", function(){ expect(6); var classname = 'foo'; el = $("select").multiselect({ classes:classname }); var $button = button(), $widget = menu(); equals( $widget.hasClass(classname), true, 'menu has the class ' + classname); equals( $button.hasClass(classname), true, 'button has the class ' + classname); // change it up var newclass = 'bar'; el.multiselect("option", "classes", newclass); equals( $widget.hasClass(newclass), true, 'menu has the new class ' + newclass); equals( $button.hasClass(newclass), true, 'button has the new class ' + newclass); equals( $button.hasClass(classname), false, 'menu no longer has the class ' + classname); equals( $button.hasClass(classname), false, 'button no longer has the class ' + classname); el.multiselect("destroy"); }); test("header", function(){ expect(7); function countLinks(){ return header().find("a").length; } // default el = $("select").multiselect({ autoOpen:true }); ok(header().is(':visible'), "default config: header is visible" ); el.multiselect("option", "header", false); ok(header().is(':hidden'), "after changing header option on default config: header is no longer visible" ); // test for all links within the default header equals(countLinks(), 3, "number of links in the default header config"); el.multiselect("destroy"); // create again, this time header false el = $("select").multiselect({ header:false, autoOpen:true }); ok(header().is(':hidden'), "init with header false: header is not visible" ); el.multiselect("option", "header", true); ok(header().is(':visible'), "after changing header option: header is visible" ); el.multiselect("destroy"); // create again, this time custom header el = $("select").multiselect({ header:"hai guyz", autoOpen:true }); equals(header().text(), "hai guyz", "header equals custom text"); equals(countLinks(), 1, "number of links in the custom header config (should be close button)"); el.multiselect("destroy"); }); })(jQuery);
JavaScript
/* Simplified Chinese initialisation for the jQuery UI multiselect plugin. */ /* Written by Ben (ben@zfben.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: '全選', uncheckAllText: '清空', noneSelectedText: '請選擇', selectedText: '# 已選擇' }); })( jQuery );
JavaScript
/* Simplified Chinese initialisation for the jQuery UI multiselect plugin. */ /* Written by Ben (ben@zfben.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: '全选', uncheckAllText: '清空', noneSelectedText: '请选择', selectedText: '# 已选择' }); })( jQuery );
JavaScript
/* Brazilian initialisation for the jQuery UI multiselect plugin. */ /* Written by Vinícius Fontoura Corrêa (vinusfc@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Marcar todos', uncheckAllText: 'Desmarcar todos', noneSelectedText: 'Selecione as opções', selectedText: '# selecionado' }); })( jQuery );
JavaScript
/* Japanese initialisation for the jQuery UI multiselect plugin. */ /* Written by Daisuke (daisuketaniwaki@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'すべて選択', uncheckAllText: '選択解除', noneSelectedText: '選択してください', selectedText: '#つ選択中' }); })( jQuery );
JavaScript
/* Italian initialization for the jQuery UI multiselect plugin. */ /* Written by Vincenzo Farruggia(mastropinguino@networky.net). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Seleziona tutto', uncheckAllText: 'Deseleziona tutto', noneSelectedText: 'Seleziona le opzioni', selectedText: '# selezionati' }); })( jQuery );
JavaScript
/* Spanish initialisation for the jQuery UI multiselect plugin. */ /* Written by Vinícius Fontoura Corrêa (vinusfc@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtro:", placeholder: "Introduzca una palabra" }); })( jQuery );
JavaScript
/* Japanese initialisation for the jQuery UI multiselect plugin. */ /* Written by Daisuke (daisuketaniwaki@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: '絞込み:', placeholder: 'キーワードを入力してください' }); })( jQuery );
JavaScript
/* Polish initialisation for the jQuery UI multiselect plugin. */ /* Written by Tomasz Mazur (contact@tomaszmazur.eu). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtruj:", placeholder: "Wprowadź słowa kluczowe" }); })( jQuery );
JavaScript
/* French initialisation for the jQuery UI multiselect plugin. */ /* Written by Charles SANQUER (charles.sanquer@spyrit.net). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Tout cocher', uncheckAllText: 'Tout décocher', noneSelectedText: 'Selectionner les options', selectedText: '# selectionnés' }); })( jQuery );
JavaScript
/* Brazilian initialisation for the jQuery UI multiselect plugin. */ /* Written by Yusuf Özer (realsby@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtre:", placeholder: "Bir kelime yazın" }); })( jQuery );
JavaScript
/* Italian initialization for the jQuery UI multiselect plugin. */ /* Written by Vincenzo Farruggia(mastropinguino@networky.net). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtro:", placeholder: "Digita una parola chiave" }); })( jQuery );
JavaScript
/* Czech initialisation for the jQuery UI multiselect plugin. */ /* Written by Michi (michi.m@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtrovat:", placeholder: "Napište výraz" }); })( jQuery );
JavaScript
/* Russian initialisation for the jQuery UI multiselect plugin. */ /* Written by Artem Packhomov (gorblnu4@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Отметить все', uncheckAllText: 'Снять отметку со всех', noneSelectedText: 'Выберите из списка', selectedText: 'Выбрано #' }); })( jQuery );
JavaScript
/* Brazilian initialisation for the jQuery UI multiselect plugin. */ /* Written by Vinícius Fontoura Corrêa (vinusfc@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtro:", placeholder: "Entre com a palavra" }); })( jQuery );
JavaScript
/* Spanish initialisation for the jQuery UI multiselect plugin. */ /* Written by Vinius Fontoura Correa(vinusfc@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Marca todas', uncheckAllText: 'Desmarque todas', noneSelectedText: 'Seleccione las opciones', selectedText: '# seleccionado' }); })( jQuery );
JavaScript
/* German initialisation for the jQuery UI multiselect plugin. */ /* Written by Sven Tatter (sven.tatter@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Suchen:", placeholder: "Stichwort eingeben" }); })( jQuery );
JavaScript
/* Spanish initialisation for the jQuery UI multiselect plugin. */ /* Written by Tomasz Mazur (contact@tomaszmazur.eu). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Zaznacz wszystkie', uncheckAllText: 'Odznacz wszystkie', noneSelectedText: 'Wybierz opcje', selectedText: 'Zaznaczono #' }); })( jQuery );
JavaScript
/* Russian initialisation for the jQuery UI multiselect plugin. */ /* Written by Artem Packhomov (gorblnu4@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Фильтр:", placeholder: "Введите запрос" }); })( jQuery );
JavaScript
/* German initialisation for the jQuery UI multiselect plugin. */ /* Written by Sven Tatter (sven.tatter@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Alle auswählen', uncheckAllText: 'Alle abwählen', noneSelectedText: 'Nichts ausgewählt', selectedText: '# ausgewählt' }); })( jQuery );
JavaScript
/* Brazilian initialisation for the jQuery UI multiselect plugin. */ /* Written by Yusuf Özer (realsby@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Tümünü seç', uncheckAllText: 'Tümünü sil', noneSelectedText: 'Seçenekleri belirleyin', selectedText: '# adet seçildi' }); })( jQuery );
JavaScript
/* French initialisation for the jQuery UI multiselect plugin. */ /* Written by Charles SANQUER (charles.sanquer@spyrit.net). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtre:", placeholder: "Entrer un mot clé" }); })( jQuery );
JavaScript
/* Simplified Chinese initialisation for the jQuery UI multiselect plugin. */ /* Written by Ben (ben@zfben.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: '过滤:', placeholder: '输入关键字过滤' }); })( jQuery );
JavaScript
/* Simplified Chinese initialisation for the jQuery UI multiselect plugin. */ /* Written by Ben (ben@zfben.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: '過濾:', placeholder: '輸入關鍵字過濾' }); })( jQuery );
JavaScript
/* Czech initialisation for the jQuery UI multiselect plugin. */ /* Written by Michi (michi.m@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Vybrat vše', uncheckAllText: 'Zrušit výběr', noneSelectedText: 'Nic není vybráno', selectedText: '# vybráno' }); })( jQuery );
JavaScript
(function(){var $gwt_version = "2.0.0";var $wnd = window;var $doc = $wnd.document;var $moduleName, $moduleBase;var $strongName = '242CD060B67505C29DCBE439EA5FE486';var $stats = $wnd.__gwtStatsEvent ? function(a) {return $wnd.__gwtStatsEvent(a);} : null;$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalStart'});function R(){} function Q(){} function P(){} function O(){} function N(){} function Jp(){} function Ib(){} function Rb(){} function Qb(){} function Xb(){} function Dc(){} function Cc(){} function Bc(){} function Sc(){} function Rc(){} function od(){} function xd(){} function Hd(){} function Kd(){} function Ud(){} function Yd(){} function ge(){} function ke(){} function oe(){} function ne(){} function ze(){} function Yf(){} function cg(){} function Cg(){} function Ng(){} function Xg(){} function ih(){} function jh(){} function oh(){} function ph(){} function Wg(){} function th(){} function uh(){} function Vg(){} function Ug(){} function Tg(){} function Hh(){} function Gh(){} function Fh(){} function Qh(){} function Yh(){} function Xh(){} function li(){} function ki(){} function Ji(){} function Ii(){} function Ri(){} function Zi(){} function fj(){} function pj(){} function uj(){} function tj(){} function sj(){} function Cj(){} function Kj(){} function Mj(){} function Pj(){} function ak(){} function ik(){} function pk(){} function vk(){} function Dk(){} function Hk(){} function Nk(){} function Sk(){} function Wk(){} function $k(){} function dl(){} function hl(){} function kl(){} function pl(){} function sl(){} function Ol(){} function Rl(){} function Xl(){} function Wl(){} function tm(){} function sm(){} function Dm(){} function Jm(){} function Im(){} function Sm(){} function Zm(){} function fn(){} function on(){} function vn(){} function Bn(){} function On(){} function Sn(){} function fo(){} function mo(){} function uo(){} function yo(){} function Co(){} function Go(){} function Ko(){} function Oo(){} function So(){} function Wo(){} function $o(){} function dp(){} function gp(){} function np(){} function qp(){} function tp(){} function Bp(){} function Fp(){} function xo(a){} function lh(){ch(this)} function Zg(a,b){a.k=b} function nh(){eh(this)} function Cd(){return yd} function bg(){return Zf} function Jo(){return Yr} function No(){return hs} function Sb(){Sb=Jp;Jb()} function Tb(){Tb=Jp;Sb()} function Yb(){Yb=Jp;Tb()} function Kh(){Kh=Jp;Jh()} function Mh(){Mh=Jp;Kh()} function Wh(){eh(this.c)} function vj(){vj=Jp;Jh()} function xj(){xj=Jp;vj()} function Aj(){Aj=Jp;xj()} function Nj(){Nj=Jp;Fj()} function wk(){wk=Jp;sk()} function mh(a){dh(this,a)} function Pm(){return null} function Vo(a){kp(this.b)} function Pc(a){Ip(Ue(a,2))} function Wc(){return this.d} function Ad(a){Ue(a,4);Hj()} function kh(){return this.g} function ai(){return this.k} function ji(){return this.b} function Uj(){return this.b} function Vm(){return this.b} function Ln(){return this.c} function io(){return this.b} function jo(){return this.c} function Lc(){return Nc(),Mc} function Yi(){return Wi(this)} function Vj(){return Tj(this)} function ok(){return mk(this)} function Fl(){return Ml(this)} function Cm(){return this.b.e} function Qm(){return this.b.c} function nn(){return ln(this)} function _n(){return this.b.e} function Ch(a,b){xh(a,b,a.k)} function dk(a,b){fk(a,b,a.c)} function ag(a){df(a);null.L()} function uk(a,b){a.tabIndex=b} function Uk(a){Cb(a);return a} function al(a){Cb(a);return a} function ml(a){Cb(a);return a} function rl(a){Cb(a);return a} function Qn(a){dm(a);return a} function oo(a){Cb(a);return a} function qd(a){a.b={};return a} function yi(a,b){a.d=b;aj(a.d)} function Pi(a,b){a.b=b;return a} function _i(a,b){a.c=b;return a} function hj(a,b){a.b=b;return a} function lk(a,b){a.c=b;return a} function Fk(a,b){Cb(a);return a} function jl(a,b){Cb(a);return a} function nl(a,b){Cb(a);return a} function Ql(a,b){Cb(a);return a} function ym(a,b){a.b=b;return a} function Gm(){return kn(this.b)} function un(){return this.c.b.e} function kn(a){return a.b<a.c.c} function Ah(a){return yh(this,a)} function Om(a,b){a.b=b;return a} function jn(a,b){a.c=b;return a} function xn(a,b){a.b=b;return a} function Qo(a,b){a.b=b;return a} function Uo(a,b){a.b=b;return a} function ci(a){return $h(this,a)} function Ci(a){return vi(this,a)} function El(a){return yl(this,a)} function Am(a){return zm(this,a)} function Rm(a){return mm(this.b,a)} function Vc(a){a.d=++Tc;return a} function zn(){return kn(this.b.b)} function Jb(){Jb=Jp;Yb();new Xb} function Kl(){Kl=Jp;Hl={};Jl={}} function Jh(){Jh=Jp;Ih=(sk(),rk)} function $f(){$f=Jp;Zf=Vc(new Sc)} function Zo(a){mp(this.b,this.c)} function bh(a,b){!!a.i&&Sd(a.i,b)} function Te(a,b){return a&&Qe[a][b]} function Qf(a,b){return Pd(Uf(),a,b)} function Ul(a){throw Ql(new Ol,es)} function sn(a){return em(this.b,a)} function Zn(a){return em(this.b,a)} function mn(){return this.b<this.c.c} function jm(b,a){return ds+a in b.f} function bi(){return Sj(new Pj,this)} function Bi(){return Ui(new Ri,this)} function Xi(){return this.b<this.d.c} function zh(){return lk(new ik,this.b)} function cp(a,b){bp();a.b=b;return a} function Se(a,b){return a&&!!Qe[a][b]} function nk(){return this.b<this.c.c-1} function sp(a){rj(new pj,ks);return a} function Bm(){return Fm(new Dm,this.b)} function Hm(){return Ue(ln(this.b),25)} function ul(a,b,c,d,e){a.b=b;return a} function Xm(a,b){return Um(new Sm,b,a)} function Kn(a){return Hn(this,a,0)!=-1} function Vh(a){dh(this,a);dh(this.c,a)} function Vf(){if(!Mf){Sg();Mf=true}} function fi(a){ei();gi(a,di,1);return a} function _d(a){a.b=Qn(new On);return a} function Fg(a){a.c=Dn(new Bn);return a} function Kk(a){a.b=Qn(new On);return a} function Un(a){a.b=Qn(new On);return a} function an(a,b){(a<0||a>=b)&&dn(a,b)} function qn(a,b,c){a.b=b;a.c=c;return a} function Pg(a,b,c){a.b=b;a.c=c;return a} function Um(a,b,c){a.c=c;a.b=b;return a} function ho(a,b,c){a.b=b;a.c=c;return a} function Yo(a,b,c){a.b=b;a.c=c;return a} function Hp(a,b,c){a.b=b;a.c=c;return a} function Ym(a){return nm(this.c,this.b,a)} function Wm(){return this.c.f[ds+this.b]} function U(){return this.$H||(this.$H=++rb)} function en(){return jn(new fn,Ue(this,6))} function Gn(a,b){an(b,a.c);return a.b[b]} function mp(a,b){Ai(Ue(a.d,28).b,1,0,b)} function ab(a,b){Cb(a);a.b=b;Bb(a);return a} function Xe(a,b){return a!=null&&Se(a.tI,b)} function Ck(a,b){a.firstChild.tabIndex=b} function Sj(a,b){a.c=b;a.b=!!a.c.d;return a} function En(a,b){He(a.b,a.c++,b);return true} function T(a){return this===(a==null?null:a)} function gl(){return this.$H||(this.$H=++rb)} function fl(a){return this===(a==null?null:a)} function Db(){try{null.a()}catch(a){return a}} function dn(a,b){throw nl(new kl,fs+a+gs+b)} function yk(a){wk();zk();Ak();Bk();return a} function kg(){if(!gg){vg();zg();gg=true}} function Uf(){!Nf&&(Nf=eg(new cg));return Nf} function ck(a){a.b=Ee(gf,0,10,4,0);return a} function ei(){ei=Jp;di=Fe(kf,0,1,[qr,xr,yr])} function Fj(){Fj=Jp;Dj=Qn(new On);Ej=Un(new Sn)} function Oj(a){Nj();Gj(a,$doc.body);return a} function kp(a){!jp(a)&&Mk(a.c,(bp(),_o).b,null)} function Bd(a){var b;if(yd){b=new xd;Sd(a,b)}} function Io(a){a.b=new $wnd._IG_Prefs;return a} function Mo(a){a.b=new $wnd._IG_Prefs;return a} function _m(a){Fn(this,this.F(),a);return true} function Wd(a,b,c,d){a.b=b;a.d=c;a.c=d;return a} function Yk(a,b){var c;c=new Wk;c.b=a+b;return c} function Zk(a,b){var c;c=new Wk;c.b=a+b;return c} function Ui(a,b){a.c=b;a.d=a.c.f.c;Vi(a);return a} function Lh(a,b){Kh();a.k=b;Ih.B(a.k,0);return a} function Qd(a,b){!a.b&&(a.b=Dn(new Bn));En(a.b,b)} function Vn(a,b){var c;c=km(a.b,b,a);return c==null} function lo(a){var b;b=this.c;this.c=a;return b} function Vl(a){var b;b=Tl(this.x(),a);return !!b} function Eh(a){var b;b=yh(this,a);b&&Dh(a.k);return b} function Jn(a){return He(this.b,this.c++,a),true} function Ye(a){return a!=null&&(a.tM!=Jp&&a.tI!=2)} function sc(b,a){return b[a]==null?null:String(b[a])} function df(a){if(a!=null){throw al(new $k)}return a} function Th(){if(this.c){return this.c.g}return false} function Dn(a){a.b=Ee(hf,0,0,0,0);a.c=0;return a} function Pf(a){Vf();return Qf(yd?yd:(yd=Vc(new Sc)),a)} function Yn(a){var b;return b=km(this.b,a,this),b==null} function An(){var a;return a=Ue(ln(this.b.b),25),a.H()} function Bk(){return function(){this.firstChild.focus()}} function Le(){Le=Jp;Je=[];Ke=[];Me(new ze,Je,Ke)} function Nc(){Nc=Jp;Mc=Yc(new Rc,Lq,(Nc(),new Bc))} function bp(){bp=Jp;ap=cp(new $o,is);_o=cp(new $o,js)} function sk(){sk=Jp;qk=yk(new vk);rk=qk?(sk(),new pk):qk} function Fo(a){a.b=Io(new Go);a.c=Mo(new Ko);return a} function eg(a){a.e=_d(new Yd);a.f=null;a.d=false;return a} function Nd(a,b){a.e=_d(new Yd);a.f=b;a.d=false;return a} function yb(a,b){a.length>=b&&a.splice(0,b);return a} function Gj(a,b){Fj();a.b=ck(new ak);a.k=b;ch(a);return a} function dm(a){a.b=[];a.f={};a.d=false;a.c=null;a.e=0} function W(a){if(a.c==null){return Ee(jf,0,15,0,0)}return a.c} function Zl(a){var b;b=ym(new sm,a);return qn(new on,a,b)} function tn(){var a;return a=Fm(new Dm,this.c.b),xn(new vn,a)} function om(a,b){return !b?qm(a):pm(a,b,~~(b.$H||(b.$H=++rb)))} function Wb(a,b){return a===b||!!(a.compareDocumentPosition(b)&16)} function kb(a){return a.tM==Jp||a.tI==2?a.hC():a.$H||(a.$H=++rb)} function Dh(a){a.style[pr]=Eq;a.style[qr]=Eq;a.style[rr]=Eq} function Nl(){if(Il==256){Hl=Jl;Jl={};Il=0}++Il} function ej(){ej=Jp;dj=hj(new fj,Sr);hj(new fj,pr);hj(new fj,Tr)} function mk(a){if(a.b>=a.c.c){throw oo(new mo)}return a.c.b[++a.b]} function Vi(a){while(++a.b<a.d.c){if(Gn(a.d,a.b)!=null){return}}} function xh(a,b,c){fh(b);dk(a.b,b);c.appendChild(b.k);gh(b,a)} function Fn(a,b,c){(b<0||b>a.c)&&dn(b,a.c);a.b.splice(b,0,c);++a.c} function In(a,b,c){var d;d=(an(b,a.c),a.b[b]);He(a.b,b,c);return d} function Fe(a,b,c,d){Le();Oe(d,Je,Ke);d.tI=b;d.qI=c;return d} function Ue(a,b){if(a!=null&&!Te(a.tI,b)){throw al(new $k)}return a} function rf(a){if(a!=null&&Se(a.tI,19)){return a}return ab(new N,a)} function ln(a){if(a.b>=a.c.c){throw oo(new mo)}return Gn(a.c,a.b++)} function $n(){var a;return a=Fm(new Dm,Zl(this.b).c.b),xn(new vn,a)} function se(a){var b;return b=a.b.getString(a.n()),b==undefined?null:b} function rh(){var a,b;for(b=this.x();b.z();){a=Ue(b.A(),10);a.s()}} function sh(){var a,b;for(b=this.x();b.z();){a=Ue(b.A(),10);a.t()}} function qm(a){var b;b=a.c;a.c=null;if(a.d){a.d=false;--a.e}return b} function mm(a,b){var c;c=a.c;a.c=b;if(!a.d){a.d=true;++a.e}return c} function hk(a,b){var c;c=ek(a,b);if(c==-1){throw oo(new mo)}gk(a,c)} function Tj(a){if(!a.b||!a.c.d){throw oo(new mo)}a.b=false;return a.c.d} function Sh(a,b){if(a.c){throw jl(new hl,wr)}fh(b);Zg(a,b.k);a.c=b;gh(b,a)} function Ve(a){if(a!=null&&(a.tM==Jp||a.tI==2)){throw al(new $k)}return a} function Oe(a,b,c){Le();for(var d=0,e=b.length;d<e;++d){a[b[d]]=c[d]}} function Me(a,b,c){var d=0,e;for(var f in a){if(e=a[f]){b[d]=f;c[d]=e;++d}}} function Hn(a,b,c){for(;c<a.c;++c){if(to(b,a.b[c])){return c}}return -1} function ah(a,b,c){hh(a,ig(c.c));return Pd(!a.i?(a.i=Nd(new Kd,a)):a.i,c,b)} function Pd(a,b,c){a.c>0?Qd(a,Wd(new Ud,a,b,c)):ae(a.e,b,c);return new Hd} function Ni(a,b,c,d){var e;Fi(a.b,b,c);e=a.b.b.rows[b].cells[c];e[Pr]=d.b} function ek(a,b){var c;for(c=0;c<a.c;++c){if(a.b[c]==b){return c}}return -1} function yl(a,b){if(!(b!=null&&Se(b.tI,1))){return false}return String(a)==b} function Ag(a,b){kg();xg(a,b);b&131072&&a.addEventListener(fr,sg,false)} function hh(a,b){a.h==-1?Ag(a.k,b|(a.k.__eventBits||0)):(a.h|=b)} function rj(a,b){a.k=(Jb(),$doc).createElement(Jr);a.k[ur]=Ur;$b(a.k,b);return a} function nm(e,a,b){var c,d=e.f;a=ds+a;a in d?(c=d[a]):++e.e;d[a]=b;return c} function Ob(a){var b=a.firstChild;while(b&&b.nodeType!=1)b=b.nextSibling;return b} function wj(a){var b;b=ig((Jb(),a).type);(b&896)!=0?dh(this,a):dh(this,a)} function Sf(){var a;if(Mf){a=($f(),new Yf);!!Nf&&Sd(Nf,a);return null}return null} function Ee(a,b,c,d,e){var f;f=De(e,d);Le();Oe(f,Je,Ke);f.tI=b;f.qI=c;return f} function zj(a,b,c){xj();a.k=b;Ih.B(a.k,0);c!=null&&(a.k[ur]=c,undefined);return a} function Rn(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function mg(a){return !(a!=null&&(a.tM!=Jp&&a.tI!=2))&&(a!=null&&Se(a.tI,8))} function rm(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function to(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function em(a,b){return b==null?a.d:b!=null&&Se(b.tI,1)?jm(a,Ue(b,1)):im(a,b,~~kb(b))} function fm(a,b){return b==null?a.c:b!=null&&Se(b.tI,1)?a.f[ds+Ue(b,1)]:gm(a,b,~~kb(b))} function ib(a,b){return a.tM==Jp||a.tI==2?a.eQ(b):(a==null?null:a)===(b==null?null:b)} function pi(a,b){var c;c=a.b.rows.length;if(b>=c||b<0){throw nl(new kl,Lr+b+Mr+c)}} function Wi(a){var b;if(a.b>=a.d.c){throw oo(new mo)}b=Ue(Gn(a.d,a.b),10);Vi(a);return b} function Yc(a,b,c){a.d=++Tc;a.b=c;!Gc&&(Gc=qd(new od));Gc.b[b]=a;a.c=b;return a} function Vb(b){var c=b.relatedTarget;try{var d=c.nodeName;return c}catch(a){return null}} function yj(a){var b;xj();zj(a,(b=(Jb(),$doc).createElement(Vr),b.type=Wr,b),Xr);return a} function Bj(a){var b;Aj();zj(a,(b=(Jb(),$doc).createElement(Vr),b.type=Yr,b),Zr);return a} function Hg(a,b){var c;if(!a.b){c=a.c.c;En(a.c,b)}else{c=a.b.b;In(a.c,c,b);a.b=a.b.c}b.k[kr]=c} function ae(a,b,c){var d;d=Ue(fm(a.b,b),6);if(!d){d=Dn(new Bn);km(a.b,b,d)}He(d.b,d.c++,c)} function Ff(a,b,c){var d;d=Cf;Cf=a;b==Df&&(ig((Jb(),a).type)==8192&&(Df=null));c.o(a);Cf=d} function Tl(a,b){var c;while(a.z()){c=a.A();if(b==null?c==null:ib(b,c)){return a}}return null} function Ig(a,b){var c,d;c=(d=b[kr],d==null?-1:d);b[kr]=null;In(a.c,c,null);a.b=Pg(new Ng,c,a.b)} function Gg(a,b){var c,d;c=(d=b[kr],d==null?-1:d);if(c<0){return null}return Ue(Gn(a.c,c),9)} function km(a,b,c){return b==null?mm(a,c):b!=null&&Se(b.tI,1)?nm(a,Ue(b,1),c):lm(a,b,c,~~kb(b))} function Ak(){return function(a){this.parentNode.onfocus&&this.parentNode.onfocus(a)}} function zk(){return function(a){this.parentNode.onblur&&this.parentNode.onblur(a)}} function Mm(){var a,b;a=0;b=0;this.H()!=null&&(a=kb(this.H()));this.I()!=null&&(b=kb(this.I()));return a^b} function wm(){var a,b,c;a=0;for(b=this.x();b.z();){c=b.A();if(c!=null){a+=kb(c);a=~~a}}return a} function Ml(a){Kl();var b=ds+a;var c=Jl[b];if(c!=null){return c}c=Hl[b];c==null&&(c=Ll(a));Nl();return Jl[b]=c} function jp(a){var b,c,d;c=false;if(a.b){b=se(a.b.b);d=se(a.b.c);c=!yl(Eq,d)||!yl(Eq,b)}return c} function Hb(a){var b,c,d;d=a&&a.stack?a.stack.split(Kq):[];for(b=0,c=d.length;b<c;++b){d[b]=xb(d[b])}return d} function gwtOnLoad(b,c,d){$moduleName=c;$moduleBase=d;if(b)try{of()}catch(a){b(c)}else{of()}} function gh(a,b){var c;c=a.j;if(!b){!!c&&c.r()&&a.t();a.j=null}else{if(c){throw jl(new hl,or)}a.j=b;b.r()&&a.s()}} function ch(a){var b;if(a.r()){throw jl(new hl,lr)}a.g=true;a.k.__listener=a;b=a.h;a.h=-1;b>0&&hh(a,b);a.p();a.u()} function eh(a){if(!a.r()){throw jl(new hl,mr)}try{a.v()}finally{a.q();a.k.__listener=null;a.g=false}} function $h(a,b){if(a.d!=b){return false}gh(b,null);a.y().removeChild(b.k);a.d=null;return true} function _h(a,b){if(b==a.d){return}!!b&&fh(b);!!a.d&&$h(a,a.d);a.d=b;if(b){a.b.appendChild(a.d.k);gh(b,a)}} function aj(a){if(!a.b){a.b=(Jb(),$doc).createElement(Qr);wg(a.c.e,a.b,0);a.b.appendChild($doc.createElement(Rr))}} function Hi(a,b,c){var d=a.rows[b];for(var e=0;e<c;e++){var f=$doc.createElement(Ir);d.appendChild(f)}} function bm(g,a){var b=g.b;for(var c in b){if(c==parseInt(c)){var d=b[c];for(var e=0,f=d.length;e<f;++e){a.D(d[e])}}}} function cm(e,a){var b=e.f;for(var c in b){if(c.charCodeAt(0)==58){var d=Xm(e,c.substring(1));a.D(d)}}} function De(a,b){var c=new Array(b);if(a>0){var d=[null,0,false,[0,0]][a];for(var e=0;e<b;++e){c[e]=d}}return c} function X(a,b){var c,d,e;d=Ee(jf,0,15,b.length,0);for(e=0,c=b.length;e<c;++e){if(!b[e]){throw rl(new pl)}d[e]=b[e]}a.c=d} function Uh(){if(this.h!=-1){hh(this.c,this.h);this.h=-1}ch(this.c);this.k.__listener=this} function cn(){var a,b,c;b=1;a=jn(new fn,Ue(this,6));while(a.b<a.c.c){c=ln(a);b=31*b+(c==null?0:kb(c));b=~~b}return b} function Fm(a,b){var c;a.c=b;c=Dn(new Bn);a.c.d&&En(c,Om(new Im,a.c));cm(a.c,c);bm(a.c,c);a.b=jn(new fn,c);return a} function Td(a){var b,c;if(a.b){try{for(c=jn(new fn,a.b);c.b<c.c.c;){b=Ue(ln(c),5);ae(b.b.e,b.d,b.c)}}finally{a.b=null}}} function gk(a,b){var c;if(b<0||b>=a.c){throw ml(new kl)}--a.c;for(c=b;c<a.c;++c){He(a.b,c,a.b[c+1])}He(a.b,a.c,null)} function dh(a,b){var c;switch(ig((Jb(),b).type)){case 16:case 32:c=Vb(b);if(!!c&&Wb(a.k,c)){return}}Kc(b,a,a.k)} function hi(a){var b,c;c=(Jb(),$doc).createElement(Ir);b=$doc.createElement(Jr);c.appendChild(b);c[ur]=a;b[ur]=a+Kr;return c} function Ip(a){var b,c;b=sc(a.b.k,xs);c=sc(a.c.k,xs);if(!yl(Eq,b)&&!yl(Eq,c)){null.L();null.L();null.L(null.L())}} function Lm(a){var b;if(a!=null&&Se(a.tI,25)){b=Ue(a,25);if(to(this.H(),b.H())&&to(this.I(),b.I())){return true}}return false} function zm(a,b){var c,d,e;if(b!=null&&Se(b.tI,25)){c=Ue(b,25);d=c.H();if(em(a.b,d)){e=fm(a.b,d);return Rn(c.I(),e)}}return false} function _l(){var a,b,c;c=0;for(b=Fm(new Dm,ym(new sm,Ue(this,26)).b);kn(b.b);){a=Ue(ln(b.b),25);c+=a.hC();c=~~c}return c} function Cb(a){var b,c,d,e;d=yb(Hb(Db()),2);e=Ee(jf,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=ul(new sl,Iq,d[b],Jq,0)}X(a,e)} function xb(a){var b,c,d;d=Eq;a=Cl(a);b=a.indexOf(Fq);if(b!=-1){c=a.indexOf(Gq)==0?8:0;d=Cl(a.substr(c,b-c))}return d.length>0?d:Hq} function ug(a,b){var c=0,d=a.firstChild;while(d){var e=d.nextSibling;if(d.nodeType==1){if(b==c)return d;++c}d=e}return null} function wg(a,b,c){var d=0,e=a.firstChild,f=null;while(e){if(e.nodeType==1){if(d==c){f=e;break}++d}e=e.nextSibling}a.insertBefore(b,f)} function $b(a,b){while(a.firstChild){a.removeChild(a.firstChild)}b!=null&&a.appendChild(a.ownerDocument.createTextNode(b))} function fh(a){if(!a.j){Fj();if(em(Ej.b,a)){a.t();om(Ej.b,a)!=null}}else if(Xe(a.j,21)){Ue(a.j,21).w(a)}else if(a.j){throw jl(new hl,nr)}} function Ij(a){Fj();var b;b=Ue(fm(Dj,a),20);if(b){return b}Dj.e==0&&Pf(new Kj);b=Oj(new Mj);km(Dj,a,b);Vn(Ej,b);return b} function Fi(a,b,c){var d,e;Gi(a,b);if(c<0){throw nl(new kl,Nr+c)}d=(pi(a,b),a.b.rows[b].cells.length);e=c+1-d;e>0&&Hi(a.b,b,e)} function Ai(a,b,c,d){var e,f;Fi(a,b,c);if(d){fh(d);e=(f=a.c.b.b.rows[b].cells[c],ui(a,f,true),f);Hg(a.f,d);e.appendChild(d.k);gh(d,a)}} function zi(a,b,c,d){var e,f;Fi(a,b,c);e=(f=a.c.b.b.rows[b].cells[c],ui(a,f,d==null),f);d!=null&&(e.innerHTML=d||Eq,undefined)} function Kc(a,b,c){var d,e,f;if(Gc){f=Ue(Gc.b[(Jb(),a).type],3);if(f){d=f.b.b;e=f.b.c;f.b.b=a;f.b.c=c;bh(b,f.b);f.b.b=d;f.b.c=e}}} function ui(a,b,c){var d,e;d=Ob((Jb(),b));e=null;!!d&&(e=Ue(Gg(a.f,d),10));if(e){vi(a,e);return true}else{c&&(b.innerHTML=Eq,undefined);return false}} function gm(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.H();if(h.G(a,g)){return f.I()}}}return null} function im(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.H();if(h.G(a,g)){return true}}}return false} function Sd(a,b){var c;if(b.d){b.d=false;b.e=null}c=b.e;b.e=a.f;try{++a.c;be(a.e,b,a.d)}finally{--a.c;a.c==0&&Td(a)}if(c==null){b.d=true;b.e=null}else{b.e=c}} function Ph(a,b,c){var d;Mh();Lh(a,(d=(Jb(),$doc).createElement(sr),d.type=tr,d));a.k[ur]=vr;a.k.innerHTML=b||Eq;ah(a,c,(Nc(),Mc));return a} function Ei(a){a.f=Fg(new Cg);a.e=(Jb(),$doc).createElement(zr);a.b=$doc.createElement(Ar);a.e.appendChild(a.b);a.k=a.e;a.c=Pi(new Ii,a);yi(a,_i(new Zi,a));return a} function Cl(c){if(c.length==0||c[0]>cs&&c[c.length-1]>cs){return c}var a=c.replace(/^(\s*)/,Eq);var b=a.replace(/\s*$/,Eq);return b} function pm(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.H();if(h.G(a,g)){c.length==1?delete h.b[b]:c.splice(d,1);--h.e;return f.I()}}}return null} function lm(j,a,b,c){var d=j.b[c];if(d){for(var e=0,f=d.length;e<f;++e){var g=d[e];var h=g.H();if(j.G(a,h)){var i=g.I();g.J(b);return i}}}else{d=j.b[c]=[]}var g=ho(new fo,a,b);d.push(g);++j.e;return null} function Ll(a){var b,c,d,e;b=0;d=a.length;e=d-4;c=0;while(c<e){b=a.charCodeAt(c+3)+31*(a.charCodeAt(c+2)+31*(a.charCodeAt(c+1)+31*(a.charCodeAt(c)+31*b)))|0;c+=4}while(c<d){b=b*31+a.charCodeAt(c++)}return b|0} function Bb(a){var b,c,d,e;d=Hb(Ye(a.b)?Ve(a.b):null);e=Ee(jf,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=ul(new sl,Iq,d[b],Jq,0)}X(a,e)} function Gi(a,b){var c,d,e;if(b<0){throw nl(new kl,Or+b)}d=a.b.rows.length;for(c=d;c<=b;++c){c!=a.b.rows.length&&pi(a,c);e=(Jb(),$doc).createElement(Dr);wg(a.b,e,c)}} function bn(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&Se(a.tI,6))){return false}f=Ue(a,6);if(this.F()!=f.c){return false}d=jn(new fn,Ue(this,6));e=jn(new fn,f);while(d.b<d.c.c){b=ln(d);c=ln(e);if(!(b==null?c==null:ib(b,c))){return false}}return true} function He(a,b,c){if(c!=null){if(a.qI>0&&!Te(c.tI,a.qI)){throw Uk(new Sk)}if(a.qI<0&&(c.tM==Jp||c.tI==2)){throw Uk(new Sk)}}return a[b]=c} function fk(a,b,c){var d,e;if(c<0||c>a.c){throw ml(new kl)}if(a.c==a.b.length){e=Ee(gf,0,10,a.b.length*2,0);for(d=0;d<a.b.length;++d){He(e,d,a.b[d])}a.b=e}++a.c;for(d=a.c-1;d>c;--d){He(a.b,d,a.b[d-1])}He(a.b,c,b)} function vm(a){var b,c,d;if((a==null?null:a)===this){return true}if(!(a!=null&&Se(a.tI,27))){return false}c=Ue(a,27);if(c.F()!=this.F()){return false}for(b=c.x();b.z();){d=b.A();if(!this.E(d)){return false}}return true} function Mk(b,c,d){var a,f;try{Ue(fm(b.b,c),22).C(d)}catch(a){a=rf(a);if(Xe(a,23)){f=a;if(yl(W(f)[0].b,ff.b)){throw Fk(new Dk,$r+c+_r)}throw f}else if(Xe(a,24)){f=a;if(yl(W(f)[1].b,ff.b)){throw Fk(new Dk,as+c+bs)}throw f}else throw a}} function be(a,b,c){var d,e,f,g,h,i,j;g=b.m();d=(h=Ue(fm(a.b,g),6),!h?0:h.c);if(c){for(f=d-1;f>=0;--f){e=(i=Ue(fm(a.b,g),6),Ue((an(f,i.c),i.b[f]),18));b.l(e)}}else{for(f=0;f<d;++f){e=(j=Ue(fm(a.b,g),6),Ue((an(f,j.c),j.b[f]),18));b.l(e)}}} function Sg(){var d=$wnd.onbeforeunload;var e=$wnd.onunload;$wnd.onbeforeunload=function(a){var b,c;try{b=Sf()}finally{c=d&&d(a)}if(b!=null){return b}if(c!=null){return c}};$wnd.onunload=function(a){try{Mf&&Bd(Uf())}finally{e&&e(a);$wnd.onresize=null;$wnd.onscroll=null;$wnd.onbeforeunload=null;$wnd.onunload=null}}} function wp(a){var b;a.b=Ei(new ki);a.b.e[Br]=6;a.b.k.style[ls]=ms;b=a.b.c;zi(a.b,0,0,ns);Ni(b,0,0,(ej(),dj));Ai(a.b,1,0,rj(new pj,os));Sh(a,a.b);return a} function zg(){$wnd.addEventListener(_q,function(a){var b=$wnd.__captureElem;if(b&&!a.relatedTarget){if(ir==a.target.tagName.toLowerCase()){var c=$doc.createEvent(jr);c.initMouseEvent(br,true,true,$wnd,0,a.screenX,a.screenY,a.clientX,a.clientY,a.ctrlKey,a.altKey,a.shiftKey,a.metaKey,a.button,null);b.dispatchEvent(c)}}},true);$wnd.addEventListener(fr,rg,true)} function yh(a,b){var c,d;if(b.j!=a){return false}gh(b,null);c=b.k;(d=(Jb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);hk(a.b,b);return true} function vi(a,b){var c,d;if(b.j!=a){return false}gh(b,null);c=b.k;(d=(Jb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);Ig(a.f,c);return true} function gi(a,b,c){var d,e,f,g;ei();a.k=(Jb(),$doc).createElement(zr);f=a.k;a.c=$doc.createElement(Ar);f.appendChild(a.c);f[Br]=0;f[Cr]=0;for(d=0;d<b.length;++d){e=(g=$doc.createElement(Dr),(g[ur]=b[d],undefined),g.appendChild(hi(b[d]+Er)),g.appendChild(hi(b[d]+Fr)),g.appendChild(hi(b[d]+Gr)),g);a.c.appendChild(e);d==c&&(a.b=Ob(ug(e,1)))}a.k[ur]=Hr;return a} function Hj(){var c,d;Fj();var a,b;for(b=(c=Fm(new Dm,Zl(Ej.b).c.b),xn(new vn,c));kn(b.b.b);){a=Ue((d=Ue(ln(b.b.b),25),d.H()),10);a.r()&&a.t()}dm(Ej.b);dm(Dj)} function of(){var a,i,j,k,l,m,n,o;!!$stats&&$stats({moduleName:$moduleName,subSystem:Mq,evtGroup:Nq,millis:(new Date).getTime(),type:Oq,className:Pq});(new yo).K(new ke);a=Qo(new Oo,Fo(new Co));k=Kk(new Hk);l=wp(new tp);m=new gp;m.c=k;m.d=l;m.b=a.b;km(k.b,(bp(),ap).b,Uo(new So,m));n=Dp(new Bp);o=new np;o.c=k;o.d=n;j=sp(new qp);i=new dp;i.c=k;i.d=j;km(k.b,_o.b,Yo(new Wo,m,n));Ch((Fj(),Ij(null)),l);Mk(k,ap.b,null)} function ig(a){switch(a){case Qq:return 4096;case Rq:return 1024;case Lq:return 1;case Sq:return 2;case Tq:return 2048;case Uq:return 128;case Vq:return 256;case Wq:return 512;case Xq:return 32768;case Yq:return 8192;case Zq:return 4;case $q:return 64;case _q:return 32;case ar:return 16;case br:return 8;case cr:return 16384;case dr:return 65536;case er:return 131072;case fr:return 131072;case gr:return 262144;case hr:return 524288;}} function Dp(a){var b,c,d,e,f,g;a.b=(e=Ei(new ki),(e.e[Br]=6,undefined),(e.k.style[ls]=ps,undefined),c=e.c,zi(e,0,0,qs),((Fi(c.b,0,0),c.b.b.rows[0].cells[0])[rs]=2,undefined),Ni(c,0,0,(ej(),dj)),zi(e,1,0,ss),g=yj(new tj),(g.k.style[ls]=ts,undefined),Ai(e,1,1,g),zi(e,2,0,us),f=Bj(new sj),(f.k.style[ls]=ts,undefined),Ai(e,2,1,f),b=Ph(new Fh,vs,Hp(new Fp,f,g)),Ai(e,3,1,b),d=fi(new Xh),_h(d,e),(d.k.style[ls]=ws,undefined),d);Sh(a,a.b);return a} function $l(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&Se(a.tI,26))){return false}e=Ue(a,26);if(Ue(this,26).e!=e.e){return false}for(c=Fm(new Dm,ym(new sm,e).b);kn(c.b);){b=Ue(ln(c.b),25);d=b.H();f=b.I();if(!(d==null?Ue(this,26).d:d!=null&&Se(d.tI,1)?jm(Ue(this,26),Ue(d,1)):im(Ue(this,26),d,~~kb(d)))){return false}if(!to(f,d==null?Ue(this,26).c:d!=null&&Se(d.tI,1)?Ue(this,26).f[ds+Ue(d,1)]:gm(Ue(this,26),d,~~kb(d)))){return false}}return true} function vg(){rg=function(a){if(qg(a)){var b=pg;if(b&&b.__listener){if(mg(b.__listener)){Ff(a,b,b.__listener);a.stopPropagation()}}}};qg=function(a){return true};sg=function(a){var b,c=this;while(c&&!(b=c.__listener)){c=c.parentNode}c&&c.nodeType!=1&&(c=null);b&&(mg(b)&&Ff(a,c,b))};$wnd.addEventListener(Lq,rg,true);$wnd.addEventListener(Sq,rg,true);$wnd.addEventListener(Zq,rg,true);$wnd.addEventListener(br,rg,true);$wnd.addEventListener($q,rg,true);$wnd.addEventListener(ar,rg,true);$wnd.addEventListener(_q,rg,true);$wnd.addEventListener(er,rg,true);$wnd.addEventListener(Uq,qg,true);$wnd.addEventListener(Wq,qg,true);$wnd.addEventListener(Vq,qg,true)} function xg(a,b){var c=(a.__eventBits||0)^b;a.__eventBits=b;if(!c)return;c&1&&(a.onclick=b&1?sg:null);c&2&&(a.ondblclick=b&2?sg:null);c&4&&(a.onmousedown=b&4?sg:null);c&8&&(a.onmouseup=b&8?sg:null);c&16&&(a.onmouseover=b&16?sg:null);c&32&&(a.onmouseout=b&32?sg:null);c&64&&(a.onmousemove=b&64?sg:null);c&128&&(a.onkeydown=b&128?sg:null);c&256&&(a.onkeypress=b&256?sg:null);c&512&&(a.onkeyup=b&512?sg:null);c&1024&&(a.onchange=b&1024?sg:null);c&2048&&(a.onfocus=b&2048?sg:null);c&4096&&(a.onblur=b&4096?sg:null);c&8192&&(a.onlosecapture=b&8192?sg:null);c&16384&&(a.onscroll=b&16384?sg:null);c&32768&&(a.onload=b&32768?sg:null);c&65536&&(a.onerror=b&65536?sg:null);c&131072&&(a.onmousewheel=b&131072?sg:null);c&262144&&(a.oncontextmenu=b&262144?sg:null);c&524288&&(a.onpaste=b&524288?sg:null)} var Eq='',Kq='\n',cs=' ',_r=" doesn't exist. Have you forgotten to add it to your Mvp4g configuration file?",bs=' is incorrect. It should be the same as the one configured in the Mvp4g configuration file.',Fq='(',Mr=', Row size: ',gs=', Size: ',ts='100px',ps='200px',ms='250px',ns='4kGadget initialization...',ws='80%',ds=':',es='Add not supported on this collection',sr='BUTTON',Nr='Cannot create a column with a negative index: ',Or='Cannot create a row with a negative index: ',or='Cannot set a new parent without first clearing the old parent',Fr='Center',as='Class of the object sent with event ',wr='Composite.initWidget() may only be called once.',fr='DOMMouseScroll',js='ENTER_CREDENTIALS',qs='Enter credentials',$r='Event ',Es='EventBus',Vr='INPUT',fs='Index: ',Kr='Inner',Er='Left',jr='MouseEvents',Fs='Object;',us='Password',Gr='Right',Lr='Row index: ',is='START',lr="Should only call onAttach when the widget is detached from the browser's document",mr="Should only call onDetach when the widget is attached to the browser's document",zs='StackTraceElement;',As='String;',vs='Submit',nr="This widget's parent does not implement HasWidgets",Iq='Unknown',Jq='Unknown source',ss='Username',Cs='Widget;',Bs='[Lcom.google.gwt.user.client.ui.',ys='[Ljava.lang.',kr='__uiObjectID',Pr='align',Hq='anonymous',Qq='blur',yr='bottom',tr='button',Cr='cellPadding',Br='cellSpacing',Sr='center',Rq='change',ur='className',Lq='click',Rr='col',rs='colSpan',Qr='colgroup',Ds='com.mvp4g.client.event.',gr='contextmenu',Sq='dblclick',Jr='div',dr='error',Tq='focus',Gq='function',vr='gwt-Button',Hr='gwt-DecoratorPanel',Ur='gwt-Label',Zr='gwt-PasswordTextBox',Xr='gwt-TextBox',ir='html',Uq='keydown',Vq='keypress',Wq='keyup',ks='label',pr='left',Xq='load',Yq='losecapture',xr='middle',Nq='moduleStartup',Zq='mousedown',$q='mousemove',_q='mouseout',ar='mouseover',br='mouseup',er='mousewheel',Pq='name.webdizz.gadget.four.envelope.client.Envelope',Oq='onModuleLoadStart',Yr='password',hr='paste',rr='position',Tr='right',cr='scroll',Mq='startup',os='stub content',zr='table',Ar='tbody',Ir='td',Wr='text',qr='top',Dr='tr',hs='username',xs='value',ls='width';var _;_=R.prototype={};_.eQ=T;_.hC=U;_.tM=Jp;_.tI=1;_=Q.prototype=new R;_.tI=3;_.c=null;_=P.prototype=new Q;_.tI=4;_=O.prototype=new P;_.tI=5;_=N.prototype=new O;_.tI=6;_.b=null;var rb=0;_=Ib.prototype=new R;_.tI=0;_=Rb.prototype=new Ib;_.tI=0;_=Qb.prototype=new Rb;_.tI=0;_=Xb.prototype=new Qb;_.tI=0;_=Dc.prototype=new R;_.tI=0;_.d=false;_.e=null;_=Cc.prototype=new Dc;_.m=Lc;_.tI=0;_.b=null;_.c=null;var Gc=null;_=Bc.prototype=new Cc;_.l=Pc;_.tI=0;var Mc;_=Sc.prototype=new R;_.hC=Wc;_.tI=0;_.d=0;var Tc=0;_=Rc.prototype=new Sc;_.tI=7;_.b=null;_.c=null;_=od.prototype=new R;_.tI=0;_.b=null;_=xd.prototype=new Dc;_.l=Ad;_.m=Cd;_.tI=0;var yd=null;_=Hd.prototype=new R;_.tI=0;_=Kd.prototype=new R;_.tI=0;_.b=null;_.c=0;_.d=false;_.e=null;_.f=null;_=Ud.prototype=new R;_.tI=8;_.b=null;_.c=null;_.d=null;_=Yd.prototype=new R;_.tI=0;_=ge.prototype=new R;_.tI=0;_=ke.prototype=new R;_.tI=0;_=oe.prototype=new R;_.tI=0;_=ne.prototype=new oe;_.tI=0;_=ze.prototype=new R;_.tI=0;_.length=0;_.qI=0;var Je,Ke;var Qe=[{},{},{1:1,11:1,12:1,13:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{3:1},{5:1},{7:1},{9:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,20:1,21:1},{4:1,18:1},{7:1,8:1,9:1,10:1,20:1,21:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,24:1},{11:1,13:1,14:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,23:1},{11:1,15:1},{12:1},{11:1,19:1},{27:1},{27:1},{25:1},{25:1},{25:1},{27:1},{6:1,11:1},{11:1,26:1},{11:1,27:1},{25:1},{11:1,19:1},{22:1},{22:1},{11:1,13:1,14:1,16:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,28:1},{7:1,8:1,9:1,10:1},{2:1,18:1},{17:1}];var Cf=null,Df=null;var Mf=false,Nf=null;_=Yf.prototype=new Dc;_.l=ag;_.m=bg;_.tI=0;var Zf;_=cg.prototype=new Kd;_.tI=9;var gg=false;var pg=null,qg=null,rg=null,sg=null;_=Cg.prototype=new R;_.tI=0;_.b=null;_=Ng.prototype=new R;_.tI=0;_.b=0;_.c=null;_=Xg.prototype=new R;_.tI=10;_.k=null;_=Wg.prototype=new Xg;_.p=ih;_.q=jh;_.r=kh;_.s=lh;_.o=mh;_.t=nh;_.u=oh;_.v=ph;_.tI=11;_.g=false;_.h=0;_.i=null;_.j=null;_=Vg.prototype=new Wg;_.p=rh;_.q=sh;_.u=th;_.v=uh;_.tI=12;_=Ug.prototype=new Vg;_.x=zh;_.w=Ah;_.tI=13;_=Tg.prototype=new Ug;_.w=Eh;_.tI=14;_=Hh.prototype=new Wg;_.tI=15;var Ih;_=Gh.prototype=new Hh;_.tI=16;_=Fh.prototype=new Gh;_.tI=17;_=Qh.prototype=new Wg;_.r=Th;_.s=Uh;_.o=Vh;_.t=Wh;_.tI=18;_.c=null;_=Yh.prototype=new Vg;_.y=ai;_.x=bi;_.w=ci;_.tI=19;_.d=null;_=Xh.prototype=new Yh;_.y=ji;_.tI=20;_.b=null;_.c=null;var di;_=li.prototype=new Vg;_.x=Bi;_.w=Ci;_.tI=21;_.b=null;_.c=null;_.d=null;_.e=null;_=ki.prototype=new li;_.tI=22;_=Ji.prototype=new R;_.tI=0;_.b=null;_=Ii.prototype=new Ji;_.tI=0;_=Ri.prototype=new R;_.z=Xi;_.A=Yi;_.tI=0;_.b=-1;_.c=null;_=Zi.prototype=new R;_.tI=0;_.b=null;_.c=null;var dj;_=fj.prototype=new R;_.tI=0;_.b=null;_=pj.prototype=new Wg;_.tI=23;_=uj.prototype=new Hh;_.o=wj;_.tI=24;_=tj.prototype=new uj;_.tI=25;_=sj.prototype=new tj;_.tI=26;_=Cj.prototype=new Tg;_.tI=27;var Dj,Ej;_=Kj.prototype=new R;_.tI=28;_=Mj.prototype=new Cj;_.tI=29;_=Pj.prototype=new R;_.z=Uj;_.A=Vj;_.tI=0;_.c=null;_=ak.prototype=new R;_.tI=0;_.b=null;_.c=0;_=ik.prototype=new R;_.z=nk;_.A=ok;_.tI=0;_.b=-1;_.c=null;_=pk.prototype=new R;_.B=uk;_.tI=0;var qk,rk;_=vk.prototype=new pk;_.B=Ck;_.tI=0;_=Dk.prototype=new O;_.tI=30;_=Hk.prototype=new R;_.tI=0;_=Nk.prototype=new R;_.tI=0;_.c=null;_.d=null;_=Sk.prototype=new O;_.tI=32;_=Wk.prototype=new R;_.tI=0;_.b=null;_=$k.prototype=new O;_.tI=35;_=dl.prototype=new R;_.eQ=fl;_.hC=gl;_.tI=36;_.b=null;_=hl.prototype=new O;_.tI=37;_=kl.prototype=new O;_.tI=38;_=pl.prototype=new O;_.tI=39;_=sl.prototype=new R;_.tI=40;_.b=null;_=String.prototype;_.eQ=El;_.hC=Fl;_.tI=2;var Hl,Il=0,Jl;_=Ol.prototype=new O;_.tI=42;_=Rl.prototype=new R;_.D=Ul;_.E=Vl;_.tI=0;_=Xl.prototype=new R;_.eQ=$l;_.hC=_l;_.tI=0;_=Wl.prototype=new Xl;_.G=rm;_.tI=0;_.b=null;_.c=null;_.d=false;_.e=0;_.f=null;_=tm.prototype=new Rl;_.eQ=vm;_.hC=wm;_.tI=43;_=sm.prototype=new tm;_.E=Am;_.x=Bm;_.F=Cm;_.tI=44;_.b=null;_=Dm.prototype=new R;_.z=Gm;_.A=Hm;_.tI=0;_.b=null;_.c=null;_=Jm.prototype=new R;_.eQ=Lm;_.hC=Mm;_.tI=45;_=Im.prototype=new Jm;_.H=Pm;_.I=Qm;_.J=Rm;_.tI=46;_.b=null;_=Sm.prototype=new Jm;_.H=Vm;_.I=Wm;_.J=Ym;_.tI=47;_.b=null;_.c=null;_=Zm.prototype=new Rl;_.D=_m;_.eQ=bn;_.hC=cn;_.x=en;_.tI=0;_=fn.prototype=new R;_.z=mn;_.A=nn;_.tI=0;_.b=0;_.c=null;_=on.prototype=new tm;_.E=sn;_.x=tn;_.F=un;_.tI=48;_.b=null;_.c=null;_=vn.prototype=new R;_.z=zn;_.A=An;_.tI=0;_.b=null;_=Bn.prototype=new Zm;_.D=Jn;_.E=Kn;_.F=Ln;_.tI=49;_.b=null;_.c=0;_=On.prototype=new Wl;_.tI=50;_=Sn.prototype=new tm;_.D=Yn;_.E=Zn;_.x=$n;_.F=_n;_.tI=51;_.b=null;_=fo.prototype=new Jm;_.H=io;_.I=jo;_.J=lo;_.tI=52;_.b=null;_.c=null;_=mo.prototype=new O;_.tI=53;_=uo.prototype=new ge;_.K=xo;_.tI=0;_=yo.prototype=new uo;_.tI=0;_=Co.prototype=new R;_.tI=0;_=Go.prototype=new ne;_.n=Jo;_.tI=0;_=Ko.prototype=new ne;_.n=No;_.tI=0;_=Oo.prototype=new R;_.tI=0;_.b=null;_=So.prototype=new R;_.C=Vo;_.tI=54;_.b=null;_=Wo.prototype=new R;_.C=Zo;_.tI=55;_.b=null;_.c=null;_=$o.prototype=new dl;_.tI=56;var _o,ap;_=dp.prototype=new Nk;_.tI=0;_=gp.prototype=new Nk;_.tI=0;_.b=null;_=np.prototype=new Nk;_.tI=0;_=qp.prototype=new Qh;_.tI=57;_=tp.prototype=new Qh;_.tI=58;_=Bp.prototype=new Qh;_.tI=59;_.b=null;_=Fp.prototype=new R;_.tI=60;_.b=null;_.c=null;var jf=Yk(ys,zs),kf=Yk(ys,As),gf=Yk(Bs,Cs),ff=Zk(Ds,Es),hf=Yk(ys,Fs);$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalEnd'});if (envelope) envelope.onScriptLoad(gwtOnLoad);})();
JavaScript
(function(){var $gwt_version = "2.0.0";var $wnd = window;var $doc = $wnd.document;var $moduleName, $moduleBase;var $strongName = 'E5CB0796633D3E75D9AC1CDAE75E36B4';var $stats = $wnd.__gwtStatsEvent ? function(a) {return $wnd.__gwtStatsEvent(a);} : null;$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalStart'});function R(){} function Q(){} function P(){} function O(){} function N(){} function Bp(){} function xb(){} function Db(){} function Lb(){} function Kb(){} function Ec(){} function Dc(){} function Cc(){} function Tc(){} function Sc(){} function pd(){} function yd(){} function Id(){} function Ld(){} function Vd(){} function Zd(){} function he(){} function le(){} function pe(){} function oe(){} function Ae(){} function ag(){} function gg(){} function zg(){} function Kg(){} function Xg(){} function bh(){} function oh(){} function ph(){} function uh(){} function vh(){} function ah(){} function zh(){} function Ah(){} function _g(){} function $g(){} function Zg(){} function Nh(){} function Mh(){} function Lh(){} function Th(){} function _h(){} function $h(){} function oi(){} function ni(){} function Mi(){} function Li(){} function Ui(){} function aj(){} function ij(){} function sj(){} function xj(){} function wj(){} function vj(){} function Fj(){} function Nj(){} function Pj(){} function Sj(){} function dk(){} function lk(){} function vk(){} function zk(){} function Fk(){} function Kk(){} function Ok(){} function Sk(){} function Xk(){} function _k(){} function cl(){} function hl(){} function kl(){} function Gl(){} function Jl(){} function Pl(){} function Ol(){} function lm(){} function km(){} function vm(){} function Bm(){} function Am(){} function Km(){} function Rm(){} function Zm(){} function fn(){} function nn(){} function tn(){} function Gn(){} function Kn(){} function Yn(){} function eo(){} function mo(){} function qo(){} function uo(){} function yo(){} function Co(){} function Go(){} function Ko(){} function Oo(){} function So(){} function Xo(){} function $o(){} function fp(){} function ip(){} function lp(){} function tp(){} function xp(){} function po(a){} function rh(){ih(this)} function dh(a,b){a.j=b} function th(){kh(this)} function Dd(){return zd} function fg(){return bg} function Bo(){return ds} function Fo(){return ns} function Nb(){Nb=Bp;Eb()} function Vb(){Vb=Bp;Nb()} function Zh(){kh(this.b)} function Qj(){Qj=Bp;Ij()} function sh(a){jh(this,a)} function Hm(){return null} function No(a){cp(this.a)} function Qc(a){Ap(Ve(a,2))} function Lf(a){return true} function Cb(a){return wb(a)} function Xc(){return this.c} function Bd(a){Ve(a,4);Kj()} function qh(){return this.f} function di(){return this.j} function mi(){return this.a} function Xj(){return this.a} function Nm(){return this.a} function Dn(){return this.b} function _n(){return this.a} function ao(){return this.b} function Mc(){return Oc(),Nc} function _i(){return Zi(this)} function Yj(){return Wj(this)} function rk(){return pk(this)} function xl(){return El(this)} function um(){return this.a.d} function Im(){return this.a.b} function en(){return cn(this)} function Tn(){return this.a.d} function Ih(a,b){Dh(a,b,a.j)} function gk(a,b){ik(a,b,a.b)} function Nf(a,b){og();yg(a,b)} function eg(a){ef(a);null.K()} function Mk(a){Bb(a);return a} function Uk(a){Bb(a);return a} function el(a){Bb(a);return a} function jl(a){Bb(a);return a} function In(a){Xl(a);return a} function go(a){Bb(a);return a} function rd(a){a.a={};return a} function Bi(a,b){a.c=b;dj(a.c)} function Si(a,b){a.a=b;return a} function cj(a,b){a.b=b;return a} function kj(a,b){a.a=b;return a} function ok(a,b){a.b=b;return a} function xk(a,b){Bb(a);return a} function bl(a,b){Bb(a);return a} function fl(a,b){Bb(a);return a} function Il(a,b){Bb(a);return a} function qm(a,b){a.a=b;return a} function ym(){return bn(this.a)} function mn(){return this.b.a.d} function bn(a){return a.a<a.b.b} function Gh(a){return Eh(this,a)} function Gm(a,b){a.a=b;return a} function an(a,b){a.b=b;return a} function pn(a,b){a.a=b;return a} function Io(a,b){a.a=b;return a} function Mo(a,b){a.a=b;return a} function Wc(a){a.c=++Uc;return a} function fi(a){return bi(this,a)} function Fi(a){return yi(this,a)} function wl(a){return ql(this,a)} function sm(a){return rm(this,a)} function Ro(a){ep(this.a,this.b)} function Ml(a){throw Il(new Gl,ks)} function Eb(){Eb=Bp;Vb();new Kb} function Cl(){Cl=Bp;zl={};Bl={}} function cg(){cg=Bp;bg=Wc(new Tc)} function og(){if(!kg){wg();kg=true}} function rn(){return bn(this.a.a)} function Jm(a){return em(this.a,a)} function hh(a,b){!!a.h&&Td(a.h,b)} function kn(a){return Yl(this.a,a)} function Rn(a){return Yl(this.a,a)} function Ue(a,b){return a&&Re[a][b]} function bm(b,a){return Aq+a in b.e} function Uf(a,b){return Qd(Yf(),a,b)} function ei(){return Vj(new Sj,this)} function Ei(){return Xi(new Ui,this)} function $i(){return this.a<this.c.b} function dn(){return this.a<this.b.b} function Fh(){return ok(new lk,this.a)} function Te(a,b){return a&&!!Re[a][b]} function Wo(a,b){Vo();a.a=b;return a} function ml(a,b,c,d,e){a.a=b;return a} function qk(){return this.a<this.b.b-1} function tm(){return xm(new vm,this.a)} function zm(){return Ve(cn(this.a),25)} function kp(a){uj(new sj,qs);return a} function Cn(a){return zn(this,a,0)!=-1} function Yh(a){jh(this,a);jh(this.b,a)} function ii(a){hi();ji(a,gi,1);return a} function ae(a){a.a=In(new Gn);return a} function Cg(a){a.b=vn(new tn);return a} function Ck(a){a.a=In(new Gn);return a} function Pm(a,b){return Mm(new Km,b,a)} function Um(a,b){(a<0||a>=b)&&Xm(a,b)} function yn(a,b){Um(b,a.b);return a.a[b]} function Mn(a){a.a=In(new Gn);return a} function Mg(a,b,c){a.a=b;a.b=c;return a} function Mm(a,b,c){a.b=c;a.a=b;return a} function hn(a,b,c){a.a=b;a.b=c;return a} function $n(a,b,c){a.a=b;a.b=c;return a} function Qo(a,b,c){a.a=b;a.b=c;return a} function zp(a,b,c){a.a=b;a.b=c;return a} function Qm(a){return fm(this.b,this.a,a)} function Om(){return this.b.e[Aq+this.a]} function Ym(){return an(new Zm,Ve(this,6))} function U(){return this.$H||(this.$H=++qb)} function T(a){return this===(a==null?null:a)} function Ye(a,b){return a!=null&&Te(a.tI,b)} function ep(a,b){Di(Ve(a.c,28).a,1,0,b)} function wn(a,b){Ie(a.a,a.b++,b);return true} function ab(a,b){Bb(a);a.a=b;Ab(a);return a} function Vj(a,b){a.b=b;a.a=!!a.b.c;return a} function fk(a){a.a=Fe(hf,0,10,4,0);return a} function Ao(a){a.a=new $wnd._IG_Prefs;return a} function Eo(a){a.a=new $wnd._IG_Prefs;return a} function Cd(a){var b;if(zd){b=new yd;Td(a,b)}} function Xm(a,b){throw fl(new cl,ls+a+ms+b)} function Xd(a,b,c,d){a.a=b;a.c=c;a.b=d;return a} function Yf(){!Rf&&(Rf=ig(new gg));return Rf} function hi(){hi=Bp;gi=Ge(lf,0,1,[xr,Fr,Gr])} function Ij(){Ij=Bp;Gj=In(new Gn);Hj=Mn(new Kn)} function Qh(a,b){a.j=b;a.j.tabIndex=0;return a} function Rj(a){Qj();Jj(a,$doc.body);return a} function Tm(a){xn(this,this.E(),a);return true} function $k(){return this.$H||(this.$H=++qb)} function Zk(a){return this===(a==null?null:a)} function Bn(a){return Ie(this.a,this.b++,a),true} function co(a){var b;b=this.b;this.b=a;return b} function Nl(a){var b;b=Ll(this.x(),a);return !!b} function cp(a){!bp(a)&&Ek(a.b,(Vo(),To).a,null)} function vn(a){a.a=Fe(jf,0,0,0,0);a.b=0;return a} function Rd(a,b){!a.a&&(a.a=vn(new tn));wn(a.a,b)} function Rk(a,b){var c;c=new Ok;c.a=a+b;return c} function Qk(a,b){var c;c=new Ok;c.a=a+b;return c} function Gb(a,b){var c;c=Pb(a,Dq);c.text=b;return c} function Nn(a,b){var c;c=cm(a.a,b,a);return c==null} function Xi(a,b){a.b=b;a.c=a.b.e.b;Yi(a);return a} function Wh(){if(this.b){return this.b.f}return false} function ef(a){if(a!=null){throw Uk(new Sk)}return a} function Ze(a){return a!=null&&(a.tM!=Bp&&a.tI!=2)} function qc(b,a){return b[a]==null?null:String(b[a])} function Qn(a){var b;return b=cm(this.a,a,this),b==null} function sn(){var a;return a=Ve(cn(this.a.a),25),a.G()} function Me(){Me=Bp;Ke=[];Le=[];Ne(new Ae,Ke,Le)} function Oc(){Oc=Bp;Nc=Zc(new Sc,Hq,(Oc(),new Cc))} function Vo(){Vo=Bp;Uo=Wo(new So,os);To=Wo(new So,ps)} function xo(a){a.a=Ao(new yo);a.b=Eo(new Co);return a} function ig(a){a.d=ae(new Zd);a.e=null;a.c=false;return a} function Od(a,b){a.d=ae(new Zd);a.e=b;a.c=false;return a} function Jj(a,b){Ij();a.a=fk(new dk);a.j=b;ih(a);return a} function W(a){if(a.b==null){return Fe(kf,0,15,0,0)}return a.b} function Kh(a){var b;b=Eh(this,a);b&&Jh(a.j);return b} function Rl(a){var b;b=qm(new km,a);return hn(new fn,a,b)} function Tf(a){Zf();return Uf(zd?zd:(zd=Wc(new Tc)),a)} function ln(){var a;return a=xm(new vm,this.b.a),pn(new nn,a)} function Xl(a){a.a=[];a.e={};a.c=false;a.b=null;a.d=0} function Jh(a){a.style[wr]=wq;a.style[xr]=wq;a.style[yr]=wq} function kb(a){return a.tM==Bp||a.tI==2?a.hC():a.$H||(a.$H=++qb)} function gm(a,b){return !b?im(a):hm(a,b,~~(b.$H||(b.$H=++qb)))} function nh(a,b){a.g==-1?Nf(a.j,b|(a.j.__eventBits||0)):(a.g|=b)} function Dh(a,b,c){lh(b);gk(a.a,b);c.appendChild(b.j);mh(b,a)} function Ge(a,b,c,d){Me();Pe(d,Ke,Le);d.tI=b;d.qI=c;return d} function xn(a,b,c){(b<0||b>a.b)&&Xm(b,a.b);a.a.splice(b,0,c);++a.b} function An(a,b,c){var d;d=(Um(b,a.b),a.a[b]);Ie(a.a,b,c);return d} function kk(a,b){var c;c=hk(a,b);if(c==-1){throw go(new eo)}jk(a,c)} function em(a,b){var c;c=a.b;a.b=b;if(!a.c){a.c=true;++a.d}return c} function Yi(a){while(++a.a<a.c.b){if(yn(a.c,a.a)!=null){return}}} function pk(a){if(a.a>=a.b.b){throw go(new eo)}return a.b.a[++a.a]} function cn(a){if(a.a>=a.b.b){throw go(new eo)}return yn(a.b,a.a++)} function hj(){hj=Bp;gj=kj(new ij,Zr);kj(new ij,wr);kj(new ij,$r)} function Sn(){var a;return a=xm(new vm,Rl(this.a).b.a),pn(new nn,a)} function te(a){var b;return b=a.a.getString(a.n()),b==undefined?null:b} function im(a){var b;b=a.b;a.b=null;if(a.c){a.c=false;--a.d}return b} function xh(){var a,b;for(b=this.x();b.z();){a=Ve(b.A(),10);a.s()}} function yh(){var a,b;for(b=this.x();b.z();){a=Ve(b.A(),10);a.t()}} function zj(a){var b;b=mg((Eb(),a).type);(b&896)!=0?jh(this,a):jh(this,a)} function sf(a){if(a!=null&&Te(a.tI,19)){return a}return ab(new N,a)} function Ve(a,b){if(a!=null&&!Ue(a.tI,b)){throw Uk(new Sk)}return a} function Wj(a){if(!a.a||!a.b.c){throw go(new eo)}a.a=false;return a.b.c} function Vh(a,b){if(a.b){throw bl(new _k,Er)}lh(b);dh(a,b.j);a.b=b;mh(b,a)} function We(a){if(a!=null&&(a.tM==Bp||a.tI==2)){throw Uk(new Sk)}return a} function ql(a,b){if(!(b!=null&&Te(b.tI,1))){return false}return String(a)==b} function zn(a,b,c){for(;c<a.b;++c){if(lo(b,a.a[c])){return c}}return -1} function gh(a,b,c){nh(a,mg(c.b));return Qd(!a.h?(a.h=Od(new Ld,a)):a.h,c,b)} function Qd(a,b,c){a.b>0?Rd(a,Xd(new Vd,a,b,c)):be(a.d,b,c);return new Id} function Pe(a,b,c){Me();for(var d=0,e=b.length;d<e;++d){a[b[d]]=c[d]}} function Ne(a,b,c){var d=0,e;for(var f in a){if(e=a[f]){b[d]=f;c[d]=e;++d}}} function Qi(a,b,c,d){var e;Ii(a.a,b,c);e=a.a.a.rows[b].cells[c];e[Wr]=d.a} function hk(a,b){var c;for(c=0;c<a.b;++c){if(a.a[c]==b){return c}}return -1} function Zc(a,b,c){a.c=++Uc;a.a=c;!Hc&&(Hc=rd(new pd));Hc.a[b]=a;a.b=b;return a} function Cj(a,b,c){a.j=b;a.j.tabIndex=0;c!=null&&(a.j[Cr]=c,undefined);return a} function uj(a,b){a.j=Pb((Eb(),$doc),Eq);a.j[Cr]=_r;a.j.innerText=b||wq;return a} function fm(e,a,b){var c,d=e.e;a=Aq+a;a in d?(c=d[a]):++e.d;d[a]=b;return c} function si(a,b){var c;c=a.a.rows.length;if(b>=c||b<0){throw fl(new cl,Sr+b+Tr+c)}} function Fe(a,b,c,d,e){var f;f=Ee(e,d);Me();Pe(f,Ke,Le);f.tI=b;f.qI=c;return f} function Ej(a){var b;Cj(a,(b=(Eb(),$doc).createElement(as),b.type=ds,b),es);return a} function Bj(a){var b;Cj(a,(b=(Eb(),$doc).createElement(as),b.type=bs,b),cs);return a} function Jn(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function jm(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function lo(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function Yl(a,b){return b==null?a.c:b!=null&&Te(b.tI,1)?bm(a,Ve(b,1)):am(a,b,~~kb(b))} function Zl(a,b){return b==null?a.b:b!=null&&Te(b.tI,1)?a.e[Aq+Ve(b,1)]:$l(a,b,~~kb(b))} function ib(a,b){return a.tM==Bp||a.tI==2?a.eQ(b):(a==null?null:a)===(b==null?null:b)} function Dg(a,b){var c,d;c=(d=b[rr],d==null?-1:d);if(c<0){return null}return Ve(yn(a.b,c),9)} function Ib(a){var b=a.firstChild;while(b&&b.nodeType!=1)b=b.nextSibling;return b} function Wf(){var a;if(Qf){a=(cg(),new ag);!!Rf&&Td(Rf,a);return null}return null} function Zi(a){var b;if(a.a>=a.c.b){throw go(new eo)}b=Ve(yn(a.c,a.a),10);Yi(a);return b} function dj(a){if(!a.a){a.a=Pb((Eb(),$doc),Xr);xg(a.b.d,a.a,0);a.a.appendChild(Pb($doc,Yr))}} function be(a,b,c){var d;d=Ve(Zl(a.a,b),6);if(!d){d=vn(new tn);cm(a.a,b,d)}Ie(d.a,d.b++,c)} function Eg(a,b){var c;if(!a.a){c=a.b.b;wn(a.b,b)}else{c=a.a.a;An(a.b,c,b);a.a=a.a.b}b.j[rr]=c} function Ll(a,b){var c;while(a.z()){c=a.A();if(b==null?c==null:ib(b,c)){return a}}return null} function Fg(a,b){var c,d;c=(d=b[rr],d==null?-1:d);b[rr]=null;An(a.b,c,null);a.a=Mg(new Kg,c,a.a)} function If(a,b,c){var d;d=Ff;Ff=a;b==Gf&&(mg((Eb(),a).type)==8192&&(Gf=null));c.o(a);Ff=d} function cm(a,b,c){return b==null?em(a,c):b!=null&&Te(b.tI,1)?fm(a,Ve(b,1),c):dm(a,b,c,~~kb(b))} function xg(a,b,c){c>=a.children.length?a.appendChild(b):a.insertBefore(b,a.children[c])} function bi(a,b){if(a.c!=b){return false}mh(b,null);a.y().removeChild(b.j);a.c=null;return true} function bp(a){var b,c,d;c=false;if(a.a){b=te(a.a.a);d=te(a.a.b);c=!ql(wq,d)||!ql(wq,b)}return c} function ki(a){var b,c;c=Pb((Eb(),$doc),Qr);b=Pb($doc,Eq);c.appendChild(b);c[Cr]=a;b[Cr]=a+Rr;return c} function om(){var a,b,c;a=0;for(b=this.x();b.z();){c=b.A();if(c!=null){a+=kb(c);a=~~a}}return a} function Em(){var a,b;a=0;b=0;this.G()!=null&&(a=kb(this.G()));this.H()!=null&&(b=kb(this.H()));return a^b} function Xh(){if(this.g!=-1){nh(this.b,this.g);this.g=-1}ih(this.b);this.j.__listener=this} function kh(a){if(!a.r()){throw bl(new _k,tr)}try{a.v()}finally{a.q();a.j.__listener=null;a.f=false}} function mh(a,b){var c;c=a.i;if(!b){!!c&&c.r()&&a.t();a.i=null}else{if(c){throw bl(new _k,vr)}a.i=b;b.r()&&a.s()}} function ih(a){var b;if(a.r()){throw bl(new _k,sr)}a.f=true;a.j.__listener=a;b=a.g;a.g=-1;b>0&&nh(a,b);a.p();a.u()} function Wl(e,a){var b=e.e;for(var c in b){if(c.charCodeAt(0)==58){var d=Pm(e,c.substring(1));a.C(d)}}} function Ee(a,b){var c=new Array(b);if(a>0){var d=[null,0,false,[0,0]][a];for(var e=0;e<b;++e){c[e]=d}}return c} function Ki(a,b,c){var d=a.rows[b];for(var e=0;e<c;e++){var f=$doc.createElement(Qr);d.appendChild(f)}} function Vl(g,a){var b=g.a;for(var c in b){if(c==parseInt(c)){var d=b[c];for(var e=0,f=d.length;e<f;++e){a.C(d[e])}}}} function gwtOnLoad(b,c,d){$moduleName=c;$moduleBase=d;if(b)try{pf()}catch(a){b(c)}else{pf()}} function Sg(){$wnd.__gwt_initWindowCloseHandler(function(){return Wf()},function(){Qf&&Cd(Yf())})} function Lj(a){Ij();var b;b=Ve(Zl(Gj,a),20);if(b){return b}Gj.d==0&&Tf(new Nj);b=Rj(new Pj);cm(Gj,a,b);Nn(Hj,b);return b} function El(a){Cl();var b=Aq+a;var c=Bl[b];if(c!=null){return c}c=zl[b];c==null&&(c=Dl(a));Fl();return Bl[b]=c} function Fl(){if(Al==256){zl=Bl;Bl={};Al=0}++Al} function Ap(a){var b,c;b=qc(a.a.j,Ds);c=qc(a.b.j,Ds);if(!ql(wq,b)&&!ql(wq,c)){null.K();null.K();null.K(null.K())}} function Dm(a){var b;if(a!=null&&Te(a.tI,25)){b=Ve(a,25);if(lo(this.G(),b.G())&&lo(this.H(),b.H())){return true}}return false} function Ud(a){var b,c;if(a.a){try{for(c=an(new Zm,a.a);c.a<c.b.b;){b=Ve(cn(c),5);be(b.a.d,b.c,b.b)}}finally{a.a=null}}} function xm(a,b){var c;a.b=b;c=vn(new tn);a.b.c&&wn(c,Gm(new Am,a.b));Wl(a.b,c);Vl(a.b,c);a.a=an(new Zm,c);return a} function ci(a,b){if(b==a.c){return}!!b&&lh(b);!!a.c&&bi(a,a.c);a.c=b;if(b){a.a.appendChild(a.c.j);mh(b,a)}} function Ci(a,b,c,d){var e,f;Ii(a,b,c);e=(f=a.b.a.a.rows[b].cells[c],xi(a,f,d==null),f);d!=null&&(e.innerHTML=d||wq,undefined)} function Ii(a,b,c){var d,e;Ji(a,b);if(c<0){throw fl(new cl,Ur+c)}d=(si(a,b),a.a.rows[b].cells.length);e=c+1-d;e>0&&Ki(a.a,b,e)} function jk(a,b){var c;if(b<0||b>=a.b){throw el(new cl)}--a.b;for(c=b;c<a.b;++c){Ie(a.a,c,a.a[c+1])}Ie(a.a,a.b,null)} function X(a,b){var c,d,e;d=Fe(kf,0,15,b.length,0);for(e=0,c=b.length;e<c;++e){if(!b[e]){throw jl(new hl)}d[e]=b[e]}a.b=d} function Bb(a){var b,c,d,e;d=zb(new xb);e=Fe(kf,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=ml(new kl,Bq,d[b],Cq,0)}X(a,e)} function Wm(){var a,b,c;b=1;a=an(new Zm,Ve(this,6));while(a.a<a.b.b){c=cn(a);b=31*b+(c==null?0:kb(c));b=~~b}return b} function Tl(){var a,b,c;c=0;for(b=xm(new vm,qm(new km,Ve(this,26)).a);bn(b.a);){a=Ve(cn(b.a),25);c+=a.hC();c=~~c}return c} function rm(a,b){var c,d,e;if(b!=null&&Te(b.tI,25)){c=Ve(b,25);d=c.G();if(Yl(a.a,d)){e=Zl(a.a,d);return Jn(c.H(),e)}}return false} function Sh(a,b,c){Qh(a,(Eb(),$doc).createElement(zr+Ar+Br));a.j[Cr]=Dr;a.j.innerHTML=b||wq;gh(a,c,(Oc(),Nc));return a} function Di(a,b,c,d){var e,f;Ii(a,b,c);if(d){lh(d);e=(f=a.b.a.a.rows[b].cells[c],xi(a,f,true),f);Eg(a.e,d);e.appendChild(d.j);mh(d,a)}} function Lc(a,b,c){var d,e,f;if(Hc){f=Ve(Hc.a[(Eb(),a).type],3);if(f){d=f.a.a;e=f.a.b;f.a.a=a;f.a.b=c;hh(b,f.a);f.a.a=d;f.a.b=e}}} function Ab(a){var b,c,d,e;d=(Ze(a.a)?We(a.a):null,[]);e=Fe(kf,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=ml(new kl,Bq,d[b],Cq,0)}X(a,e)} function wb(a){var b,c,d;d=wq;a=ul(a);b=a.indexOf(xq);if(b!=-1){c=a.indexOf(yq)==0?8:0;d=ul(a.substr(c,b-c))}return d.length>0?d:zq} function xi(a,b,c){var d,e;d=Ib((Eb(),b));e=null;!!d&&(e=Ve(Dg(a.e,d),10));if(e){yi(a,e);return true}else{c&&(b.innerHTML=wq,undefined);return false}} function $l(h,a,b){var c=h.a[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){return f.H()}}}return null} function am(h,a,b){var c=h.a[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){return true}}}return false} function Td(a,b){var c;if(b.c){b.c=false;b.d=null}c=b.d;b.d=a.e;try{++a.b;ce(a.d,b,a.c)}finally{--a.b;a.b==0&&Ud(a)}if(c==null){b.c=true;b.d=null}else{b.d=c}} function Zf(){var a;if(!Qf){a=Gb((Eb(),$doc),(!Ug&&(Ug=new Xg),Mq));$doc.body.appendChild(a);Sg();$doc.body.removeChild(a);Qf=true}} function Hi(a){a.e=Cg(new zg);a.d=Pb((Eb(),$doc),Hr);a.a=Pb($doc,Ir);a.d.appendChild(a.a);a.j=a.d;a.b=Si(new Li,a);Bi(a,cj(new aj,a));return a} function op(a){var b;a.a=Hi(new ni);a.a.d[Jr]=6;a.a.j.style[rs]=ss;b=a.a.b;Ci(a.a,0,0,ts);Qi(b,0,0,(hj(),gj));Di(a.a,1,0,uj(new sj,us));Vh(a,a.a);return a} function ul(c){if(c.length==0||c[0]>js&&c[c.length-1]>js){return c}var a=c.replace(/^(\s*)/,wq);var b=a.replace(/\s*$/,wq);return b} function Tb(a,b){if(a.nodeType!=1&&a.nodeType!=9){return a==b}if(b.nodeType!=1){b=b.parentNode;if(!b){return false}}return a===b||a.contains(b)} function Eh(a,b){var c,d;if(b.i!=a){return false}mh(b,null);c=b.j;(d=(Eb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);kk(a.a,b);return true} function yi(a,b){var c,d;if(b.i!=a){return false}mh(b,null);c=b.j;(d=(Eb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);Fg(a.e,c);return true} function lh(a){if(!a.i){Ij();if(Yl(Hj.a,a)){a.t();gm(Hj.a,a)!=null}}else if(Ye(a.i,21)){Ve(a.i,21).w(a)}else if(a.i){throw bl(new _k,ur)}} function nm(a){var b,c,d;if((a==null?null:a)===this){return true}if(!(a!=null&&Te(a.tI,27))){return false}c=Ve(a,27);if(c.E()!=this.E()){return false}for(b=c.x();b.z();){d=b.A();if(!this.D(d)){return false}}return true} function dm(j,a,b,c){var d=j.a[c];if(d){for(var e=0,f=d.length;e<f;++e){var g=d[e];var h=g.G();if(j.F(a,h)){var i=g.H();g.I(b);return i}}}else{d=j.a[c]=[]}var g=$n(new Yn,a,b);d.push(g);++j.d;return null} function Dl(a){var b,c,d,e;b=0;d=a.length;e=d-4;c=0;while(c<e){b=a.charCodeAt(c+3)+31*(a.charCodeAt(c+2)+31*(a.charCodeAt(c+1)+31*(a.charCodeAt(c)+31*b)))|0;c+=4}while(c<d){b=b*31+a.charCodeAt(c++)}return b|0} function ik(a,b,c){var d,e;if(c<0||c>a.b){throw el(new cl)}if(a.b==a.a.length){e=Fe(hf,0,10,a.a.length*2,0);for(d=0;d<a.a.length;++d){Ie(e,d,a.a[d])}a.a=e}++a.b;for(d=a.b-1;d>c;--d){Ie(a.a,d,a.a[d-1])}Ie(a.a,c,b)} function Ie(a,b,c){if(c!=null){if(a.qI>0&&!Ue(c.tI,a.qI)){throw Mk(new Kk)}if(a.qI<0&&(c.tM==Bp||c.tI==2)){throw Mk(new Kk)}}return a[b]=c} function zb(i){var a={};var b=[];var c=arguments.callee.caller.caller;while(c){var d=i.k(c.toString());b.push(d);var e=Aq+d;var f=a[e];if(f){var g,h;for(g=0,h=f.length;g<h;g++){if(f[g]===c){return b}}}(f||(a[e]=[])).push(c);c=c.caller}return b} function Pb(a,b){var c,d;if(b.indexOf(Aq)!=-1){c=(!a.__gwt_container&&(a.__gwt_container=a.createElement(Eq)),a.__gwt_container);c.innerHTML=Fq+b+Gq||wq;d=Ib((Eb(),c));c.removeChild(d);return d}return a.createElement(b)} function Ek(b,c,d){var a,f;try{Ve(Zl(b.a,c),22).B(d)}catch(a){a=sf(a);if(Ye(a,23)){f=a;if(ql(W(f)[0].a,gf.a)){throw xk(new vk,fs+c+gs)}throw f}else if(Ye(a,24)){f=a;if(ql(W(f)[1].a,gf.a)){throw xk(new vk,hs+c+is)}throw f}else throw a}} function ce(a,b,c){var d,e,f,g,h,i,j;g=b.m();d=(h=Ve(Zl(a.a,g),6),!h?0:h.b);if(c){for(f=d-1;f>=0;--f){e=(i=Ve(Zl(a.a,g),6),Ve((Um(f,i.b),i.a[f]),18));b.l(e)}}else{for(f=0;f<d;++f){e=(j=Ve(Zl(a.a,g),6),Ve((Um(f,j.b),j.a[f]),18));b.l(e)}}} function Vm(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&Te(a.tI,6))){return false}f=Ve(a,6);if(this.E()!=f.b){return false}d=an(new Zm,Ve(this,6));e=an(new Zm,f);while(d.a<d.b.b){b=cn(d);c=cn(e);if(!(b==null?c==null:ib(b,c))){return false}}return true} function Ji(a,b){var c,d,e;if(b<0){throw fl(new cl,Vr+b)}d=a.a.rows.length;for(c=d;c<=b;++c){c!=a.a.rows.length&&si(a,c);e=Pb((Eb(),$doc),Lr);xg(a.a,e,c)}} function ji(a,b,c){var d,e,f,g;hi();a.j=Pb((Eb(),$doc),Hr);f=a.j;a.b=Pb($doc,Ir);f.appendChild(a.b);f[Jr]=0;f[Kr]=0;for(d=0;d<b.length;++d){e=(g=Pb($doc,Lr),(g[Cr]=b[d],undefined),g.appendChild(ki(b[d]+Mr)),g.appendChild(ki(b[d]+Nr)),g.appendChild(ki(b[d]+Or)),g);a.b.appendChild(e);d==c&&(a.a=Ib(e.children[1]))}a.j[Cr]=Pr;return a} function Kj(){var c,d;Ij();var a,b;for(b=(c=xm(new vm,Rl(Hj.a).b.a),pn(new nn,c));bn(b.a.a);){a=Ve((d=Ve(cn(b.a.a),25),d.G()),10);a.r()&&a.t()}Xl(Hj.a);Xl(Gj)} function pf(){var a,i,j,k,l,m,n,o;!!$stats&&$stats({moduleName:$moduleName,subSystem:Iq,evtGroup:Jq,millis:(new Date).getTime(),type:Kq,className:Lq});(new qo).J(new le);a=Io(new Go,xo(new uo));k=Ck(new zk);l=op(new lp);m=new $o;m.b=k;m.c=l;m.a=a.a;cm(k.a,(Vo(),Uo).a,Mo(new Ko,m));n=vp(new tp);o=new fp;o.b=k;o.c=n;j=kp(new ip);i=new Xo;i.b=k;i.c=j;cm(k.a,To.a,Qo(new Oo,m,n));Ih((Ij(),Lj(null)),l);Ek(k,Uo.a,null)} function jh(a,b){var c;switch(mg((Eb(),b).type)){case 16:case 32:c=b.relatedTarget||(b.type==Yq?b.toElement:b.fromElement);if(!!c&&Tb(a.j,c)){return}}Lc(b,a,a.j)} function mg(a){switch(a){case Nq:return 4096;case Oq:return 1024;case Hq:return 1;case Pq:return 2;case Qq:return 2048;case Rq:return 128;case Sq:return 256;case Tq:return 512;case Uq:return 32768;case Vq:return 8192;case Wq:return 4;case Xq:return 64;case Yq:return 32;case Zq:return 16;case $q:return 8;case _q:return 16384;case ar:return 65536;case br:return 131072;case cr:return 131072;case dr:return 262144;case er:return 524288;}} function hm(h,a,b){var c=h.a[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){c.length==1?delete h.a[b]:c.splice(d,1);--h.d;return f.H()}}}return null} function vp(a){var b,c,d,e,f,g;a.a=(e=Hi(new ni),(e.d[Jr]=6,undefined),(e.j.style[rs]=vs,undefined),c=e.b,Ci(e,0,0,ws),((Ii(c.a,0,0),c.a.a.rows[0].cells[0])[xs]=2,undefined),Qi(c,0,0,(hj(),gj)),Ci(e,1,0,ys),g=Bj(new wj),(g.j.style[rs]=zs,undefined),Di(e,1,1,g),Ci(e,2,0,As),f=Ej(new vj),(f.j.style[rs]=zs,undefined),Di(e,2,1,f),b=Sh(new Lh,Bs,zp(new xp,f,g)),Di(e,3,1,b),d=ii(new $h),ci(d,e),(d.j.style[rs]=Cs,undefined),d);Vh(a,a.a);return a} function Sl(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&Te(a.tI,26))){return false}e=Ve(a,26);if(Ve(this,26).d!=e.d){return false}for(c=xm(new vm,qm(new km,e).a);bn(c.a);){b=Ve(cn(c.a),25);d=b.G();f=b.H();if(!(d==null?Ve(this,26).c:d!=null&&Te(d.tI,1)?bm(Ve(this,26),Ve(d,1)):am(Ve(this,26),d,~~kb(d)))){return false}if(!lo(f,d==null?Ve(this,26).b:d!=null&&Te(d.tI,1)?Ve(this,26).e[Aq+Ve(d,1)]:$l(Ve(this,26),d,~~kb(d)))){return false}}return true} function yg(a,b){var c=(a.__eventBits||0)^b;a.__eventBits=b;if(!c)return;c&1&&(a.onclick=b&1?tg:null);c&3&&(a.ondblclick=b&3?sg:null);c&4&&(a.onmousedown=b&4?tg:null);c&8&&(a.onmouseup=b&8?tg:null);c&16&&(a.onmouseover=b&16?tg:null);c&32&&(a.onmouseout=b&32?tg:null);c&64&&(a.onmousemove=b&64?tg:null);c&128&&(a.onkeydown=b&128?tg:null);c&256&&(a.onkeypress=b&256?tg:null);c&512&&(a.onkeyup=b&512?tg:null);c&1024&&(a.onchange=b&1024?tg:null);c&2048&&(a.onfocus=b&2048?tg:null);c&4096&&(a.onblur=b&4096?tg:null);c&8192&&(a.onlosecapture=b&8192?tg:null);c&16384&&(a.onscroll=b&16384?tg:null);c&32768&&(a.onload=b&32768?tg:null);c&65536&&(a.onerror=b&65536?tg:null);c&131072&&(a.onmousewheel=b&131072?tg:null);c&262144&&(a.oncontextmenu=b&262144?tg:null);c&524288&&(a.onpaste=b&524288?tg:null)} function wg(){tg=function(){var a=(Nb(),Mb);Mb=this;if($wnd.event.returnValue==null){$wnd.event.returnValue=true;if(!Lf($wnd.event)){Mb=a;return}}var b,c=this;while(c&&!(b=c.__listener)){c=c.parentElement}b&&(!(b!=null&&(b.tM!=Bp&&b.tI!=2))&&(b!=null&&Te(b.tI,8))&&If($wnd.event,c,b));Mb=a};sg=function(){var a=$doc.createEventObject();$wnd.event.returnValue==null&&$wnd.event.srcElement.fireEvent(fr,a);if(this.__eventBits&2){tg.call(this)}else if($wnd.event.returnValue==null){$wnd.event.returnValue=true;Lf($wnd.event)}};var d=function(){tg.call($doc.body)};var e=function(){sg.call($doc.body)};$doc.body.attachEvent(fr,d);$doc.body.attachEvent(gr,d);$doc.body.attachEvent(hr,d);$doc.body.attachEvent(ir,d);$doc.body.attachEvent(jr,d);$doc.body.attachEvent(kr,d);$doc.body.attachEvent(lr,d);$doc.body.attachEvent(mr,d);$doc.body.attachEvent(nr,d);$doc.body.attachEvent(or,d);$doc.body.attachEvent(pr,e);$doc.body.attachEvent(qr,d)} var wq='',js=' ',gs=" doesn't exist. Have you forgotten to add it to your Mvp4g configuration file?",is=' is incorrect. It should be the same as the one configured in the Mvp4g configuration file.',Br="'><\/BUTTON>",xq='(',Tr=', Row size: ',ms=', Size: ',Gq='/>',zs='100px',vs='200px',ss='250px',ts='4kGadget initialization...',Cs='80%',Aq=':',Fq='<',zr="<BUTTON type='",ks='Add not supported on this collection',Ur='Cannot create a column with a negative index: ',Vr='Cannot create a row with a negative index: ',vr='Cannot set a new parent without first clearing the old parent',Nr='Center',hs='Class of the object sent with event ',Er='Composite.initWidget() may only be called once.',cr='DOMMouseScroll',ps='ENTER_CREDENTIALS',ws='Enter credentials',fs='Event ',Ks='EventBus',as='INPUT',ls='Index: ',Rr='Inner',Mr='Left',Ls='Object;',As='Password',Or='Right',Sr='Row index: ',os='START',sr="Should only call onAttach when the widget is detached from the browser's document",tr="Should only call onDetach when the widget is attached to the browser's document",Fs='StackTraceElement;',Gs='String;',Bs='Submit',ur="This widget's parent does not implement HasWidgets",Bq='Unknown',Cq='Unknown source',ys='Username',Is='Widget;',Hs='[Lcom.google.gwt.user.client.ui.',Es='[Ljava.lang.',rr='__uiObjectID',Wr='align',zq='anonymous',Nq='blur',Gr='bottom',Ar='button',Kr='cellPadding',Jr='cellSpacing',Zr='center',Oq='change',Cr='className',Hq='click',Yr='col',xs='colSpan',Xr='colgroup',Js='com.mvp4g.client.event.',dr='contextmenu',Pq='dblclick',Eq='div',ar='error',Qq='focus',yq='function',Mq='function __gwt_initWindowCloseHandler(beforeunload, unload) {\r\n var wnd = window\r\n , oldOnBeforeUnload = wnd.onbeforeunload\r\n , oldOnUnload = wnd.onunload;\r\n \r\n wnd.onbeforeunload = function(evt) {\r\n var ret, oldRet;\r\n try {\r\n ret = beforeunload();\r\n } finally {\r\n oldRet = oldOnBeforeUnload && oldOnBeforeUnload(evt);\r\n }\r\n // Avoid returning null as IE6 will coerce it into a string.\r\n // Ensure that "" gets returned properly.\r\n if (ret != null) {\r\n return ret;\r\n }\r\n if (oldRet != null) {\r\n return oldRet;\r\n }\r\n // returns undefined.\r\n };\r\n \r\n wnd.onunload = function(evt) {\r\n try {\r\n unload();\r\n } finally {\r\n oldOnUnload && oldOnUnload(evt);\r\n wnd.onresize = null;\r\n wnd.onscroll = null;\r\n wnd.onbeforeunload = null;\r\n wnd.onunload = null;\r\n }\r\n };\r\n \r\n // Remove the reference once we\'ve initialize the handler\r\n wnd.__gwt_initWindowCloseHandler = undefined;\r\n}\r\n',Dr='gwt-Button',Pr='gwt-DecoratorPanel',_r='gwt-Label',es='gwt-PasswordTextBox',cs='gwt-TextBox',Rq='keydown',Sq='keypress',Tq='keyup',qs='label',wr='left',Uq='load',Vq='losecapture',Fr='middle',Jq='moduleStartup',Wq='mousedown',Xq='mousemove',Yq='mouseout',Zq='mouseover',$q='mouseup',br='mousewheel',Lq='name.webdizz.gadget.four.envelope.client.Envelope',Kq='onModuleLoadStart',or='onblur',fr='onclick',qr='oncontextmenu',pr='ondblclick',nr='onfocus',kr='onkeydown',lr='onkeypress',mr='onkeyup',gr='onmousedown',ir='onmousemove',hr='onmouseup',jr='onmousewheel',ds='password',er='paste',yr='position',$r='right',Dq='script',_q='scroll',Iq='startup',us='stub content',Hr='table',Ir='tbody',Qr='td',bs='text',xr='top',Lr='tr',ns='username',Ds='value',rs='width';var _;_=R.prototype={};_.eQ=T;_.hC=U;_.tM=Bp;_.tI=1;_=Q.prototype=new R;_.tI=3;_.b=null;_=P.prototype=new Q;_.tI=4;_=O.prototype=new P;_.tI=5;_=N.prototype=new O;_.tI=6;_.a=null;var qb=0;_=xb.prototype=new R;_.k=Cb;_.tI=0;_=Db.prototype=new R;_.tI=0;_=Lb.prototype=new Db;_.tI=0;var Mb=null;_=Kb.prototype=new Lb;_.tI=0;_=Ec.prototype=new R;_.tI=0;_.c=false;_.d=null;_=Dc.prototype=new Ec;_.m=Mc;_.tI=0;_.a=null;_.b=null;var Hc=null;_=Cc.prototype=new Dc;_.l=Qc;_.tI=0;var Nc;_=Tc.prototype=new R;_.hC=Xc;_.tI=0;_.c=0;var Uc=0;_=Sc.prototype=new Tc;_.tI=7;_.a=null;_.b=null;_=pd.prototype=new R;_.tI=0;_.a=null;_=yd.prototype=new Ec;_.l=Bd;_.m=Dd;_.tI=0;var zd=null;_=Id.prototype=new R;_.tI=0;_=Ld.prototype=new R;_.tI=0;_.a=null;_.b=0;_.c=false;_.d=null;_.e=null;_=Vd.prototype=new R;_.tI=8;_.a=null;_.b=null;_.c=null;_=Zd.prototype=new R;_.tI=0;_=he.prototype=new R;_.tI=0;_=le.prototype=new R;_.tI=0;_=pe.prototype=new R;_.tI=0;_=oe.prototype=new pe;_.tI=0;_=Ae.prototype=new R;_.tI=0;_.length=0;_.qI=0;var Ke,Le;var Re=[{},{},{1:1,11:1,12:1,13:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{3:1},{5:1},{7:1},{9:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,20:1,21:1},{4:1,18:1},{7:1,8:1,9:1,10:1,20:1,21:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,24:1},{11:1,13:1,14:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,23:1},{11:1,15:1},{12:1},{11:1,19:1},{27:1},{27:1},{25:1},{25:1},{25:1},{27:1},{6:1,11:1},{11:1,26:1},{11:1,27:1},{25:1},{11:1,19:1},{22:1},{22:1},{11:1,13:1,14:1,16:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,28:1},{7:1,8:1,9:1,10:1},{2:1,18:1},{17:1}];var Ff=null,Gf=null;var Qf=false,Rf=null;_=ag.prototype=new Ec;_.l=eg;_.m=fg;_.tI=0;var bg;_=gg.prototype=new Ld;_.tI=9;var kg=false;var sg=null,tg=null;_=zg.prototype=new R;_.tI=0;_.a=null;_=Kg.prototype=new R;_.tI=0;_.a=0;_.b=null;var Ug=null;_=Xg.prototype=new R;_.tI=0;_=bh.prototype=new R;_.tI=10;_.j=null;_=ah.prototype=new bh;_.p=oh;_.q=ph;_.r=qh;_.s=rh;_.o=sh;_.t=th;_.u=uh;_.v=vh;_.tI=11;_.f=false;_.g=0;_.h=null;_.i=null;_=_g.prototype=new ah;_.p=xh;_.q=yh;_.u=zh;_.v=Ah;_.tI=12;_=$g.prototype=new _g;_.x=Fh;_.w=Gh;_.tI=13;_=Zg.prototype=new $g;_.w=Kh;_.tI=14;_=Nh.prototype=new ah;_.tI=15;_=Mh.prototype=new Nh;_.tI=16;_=Lh.prototype=new Mh;_.tI=17;_=Th.prototype=new ah;_.r=Wh;_.s=Xh;_.o=Yh;_.t=Zh;_.tI=18;_.b=null;_=_h.prototype=new _g;_.y=di;_.x=ei;_.w=fi;_.tI=19;_.c=null;_=$h.prototype=new _h;_.y=mi;_.tI=20;_.a=null;_.b=null;var gi;_=oi.prototype=new _g;_.x=Ei;_.w=Fi;_.tI=21;_.a=null;_.b=null;_.c=null;_.d=null;_=ni.prototype=new oi;_.tI=22;_=Mi.prototype=new R;_.tI=0;_.a=null;_=Li.prototype=new Mi;_.tI=0;_=Ui.prototype=new R;_.z=$i;_.A=_i;_.tI=0;_.a=-1;_.b=null;_=aj.prototype=new R;_.tI=0;_.a=null;_.b=null;var gj;_=ij.prototype=new R;_.tI=0;_.a=null;_=sj.prototype=new ah;_.tI=23;_=xj.prototype=new Nh;_.o=zj;_.tI=24;_=wj.prototype=new xj;_.tI=25;_=vj.prototype=new wj;_.tI=26;_=Fj.prototype=new Zg;_.tI=27;var Gj,Hj;_=Nj.prototype=new R;_.tI=28;_=Pj.prototype=new Fj;_.tI=29;_=Sj.prototype=new R;_.z=Xj;_.A=Yj;_.tI=0;_.b=null;_=dk.prototype=new R;_.tI=0;_.a=null;_.b=0;_=lk.prototype=new R;_.z=qk;_.A=rk;_.tI=0;_.a=-1;_.b=null;_=vk.prototype=new O;_.tI=30;_=zk.prototype=new R;_.tI=0;_=Fk.prototype=new R;_.tI=0;_.b=null;_.c=null;_=Kk.prototype=new O;_.tI=32;_=Ok.prototype=new R;_.tI=0;_.a=null;_=Sk.prototype=new O;_.tI=35;_=Xk.prototype=new R;_.eQ=Zk;_.hC=$k;_.tI=36;_.a=null;_=_k.prototype=new O;_.tI=37;_=cl.prototype=new O;_.tI=38;_=hl.prototype=new O;_.tI=39;_=kl.prototype=new R;_.tI=40;_.a=null;_=String.prototype;_.eQ=wl;_.hC=xl;_.tI=2;var zl,Al=0,Bl;_=Gl.prototype=new O;_.tI=42;_=Jl.prototype=new R;_.C=Ml;_.D=Nl;_.tI=0;_=Pl.prototype=new R;_.eQ=Sl;_.hC=Tl;_.tI=0;_=Ol.prototype=new Pl;_.F=jm;_.tI=0;_.a=null;_.b=null;_.c=false;_.d=0;_.e=null;_=lm.prototype=new Jl;_.eQ=nm;_.hC=om;_.tI=43;_=km.prototype=new lm;_.D=sm;_.x=tm;_.E=um;_.tI=44;_.a=null;_=vm.prototype=new R;_.z=ym;_.A=zm;_.tI=0;_.a=null;_.b=null;_=Bm.prototype=new R;_.eQ=Dm;_.hC=Em;_.tI=45;_=Am.prototype=new Bm;_.G=Hm;_.H=Im;_.I=Jm;_.tI=46;_.a=null;_=Km.prototype=new Bm;_.G=Nm;_.H=Om;_.I=Qm;_.tI=47;_.a=null;_.b=null;_=Rm.prototype=new Jl;_.C=Tm;_.eQ=Vm;_.hC=Wm;_.x=Ym;_.tI=0;_=Zm.prototype=new R;_.z=dn;_.A=en;_.tI=0;_.a=0;_.b=null;_=fn.prototype=new lm;_.D=kn;_.x=ln;_.E=mn;_.tI=48;_.a=null;_.b=null;_=nn.prototype=new R;_.z=rn;_.A=sn;_.tI=0;_.a=null;_=tn.prototype=new Rm;_.C=Bn;_.D=Cn;_.E=Dn;_.tI=49;_.a=null;_.b=0;_=Gn.prototype=new Ol;_.tI=50;_=Kn.prototype=new lm;_.C=Qn;_.D=Rn;_.x=Sn;_.E=Tn;_.tI=51;_.a=null;_=Yn.prototype=new Bm;_.G=_n;_.H=ao;_.I=co;_.tI=52;_.a=null;_.b=null;_=eo.prototype=new O;_.tI=53;_=mo.prototype=new he;_.J=po;_.tI=0;_=qo.prototype=new mo;_.tI=0;_=uo.prototype=new R;_.tI=0;_=yo.prototype=new oe;_.n=Bo;_.tI=0;_=Co.prototype=new oe;_.n=Fo;_.tI=0;_=Go.prototype=new R;_.tI=0;_.a=null;_=Ko.prototype=new R;_.B=No;_.tI=54;_.a=null;_=Oo.prototype=new R;_.B=Ro;_.tI=55;_.a=null;_.b=null;_=So.prototype=new Xk;_.tI=56;var To,Uo;_=Xo.prototype=new Fk;_.tI=0;_=$o.prototype=new Fk;_.tI=0;_.a=null;_=fp.prototype=new Fk;_.tI=0;_=ip.prototype=new Th;_.tI=57;_=lp.prototype=new Th;_.tI=58;_=tp.prototype=new Th;_.tI=59;_.a=null;_=xp.prototype=new R;_.tI=60;_.a=null;_.b=null;var kf=Qk(Es,Fs),lf=Qk(Es,Gs),hf=Qk(Hs,Is),gf=Rk(Js,Ks),jf=Qk(Es,Ls);$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalEnd'});if (envelope) envelope.onScriptLoad(gwtOnLoad);})();
JavaScript
(function(){var $gwt_version = "2.0.0";var $wnd = window;var $doc = $wnd.document;var $moduleName, $moduleBase;var $strongName = '722308D5AD3B9493F0A7B964BC9584E5';var $stats = $wnd.__gwtStatsEvent ? function(a) {return $wnd.__gwtStatsEvent(a);} : null;$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalStart'});function R(){} function Q(){} function P(){} function O(){} function N(){} function up(){} function Mb(){} function Wb(){} function Vb(){} function Ec(){} function Dc(){} function Cc(){} function Tc(){} function Sc(){} function pd(){} function yd(){} function Id(){} function Ld(){} function Vd(){} function Zd(){} function he(){} function le(){} function pe(){} function oe(){} function Ae(){} function $f(){} function eg(){} function Bg(){} function Mg(){} function Wg(){} function hh(){} function ih(){} function nh(){} function oh(){} function Vg(){} function sh(){} function th(){} function Ug(){} function Tg(){} function Sg(){} function Gh(){} function Fh(){} function Eh(){} function Mh(){} function Uh(){} function Th(){} function hi(){} function gi(){} function Fi(){} function Ei(){} function Ni(){} function Vi(){} function bj(){} function lj(){} function qj(){} function pj(){} function oj(){} function yj(){} function Gj(){} function Ij(){} function Lj(){} function Yj(){} function ek(){} function ok(){} function sk(){} function yk(){} function Dk(){} function Hk(){} function Lk(){} function Qk(){} function Uk(){} function Xk(){} function al(){} function dl(){} function zl(){} function Cl(){} function Il(){} function Hl(){} function em(){} function dm(){} function om(){} function um(){} function tm(){} function Dm(){} function Km(){} function Sm(){} function $m(){} function fn(){} function mn(){} function zn(){} function Dn(){} function Rn(){} function Yn(){} function fo(){} function jo(){} function no(){} function ro(){} function vo(){} function zo(){} function Do(){} function Ho(){} function Lo(){} function Qo(){} function To(){} function $o(){} function bp(){} function ep(){} function mp(){} function qp(){} function io(a){} function kh(){bh(this)} function Yg(a,b){a.k=b} function mh(){dh(this)} function Dd(){return zd} function dg(){return _f} function uo(){return Gr} function yo(){return Rr} function Xb(){Xb=up;Nb()} function $b(){$b=up;Xb()} function Sh(){dh(this.c)} function Jj(){Jj=up;Bj()} function lh(a){ch(this,a)} function Am(){return null} function Go(a){Xo(this.b)} function Qc(a){tp(Ve(a,2))} function Xc(){return this.d} function Bd(a){Ve(a,4);Dj()} function jh(){return this.g} function Yh(){return this.k} function fi(){return this.b} function Qj(){return this.b} function Gm(){return this.b} function wn(){return this.c} function Un(){return this.b} function Vn(){return this.c} function Mc(){return Oc(),Nc} function Ui(){return Si(this)} function Rj(){return Pj(this)} function kk(){return ik(this)} function ql(){return xl(this)} function nm(){return this.b.e} function Bm(){return this.b.c} function Zm(){return Xm(this)} function Mn(){return this.b.e} function Bh(a,b){wh(a,b,a.k)} function _j(a,b){bk(a,b,a.c)} function cg(a){ef(a);null.K()} function Fk(a){Bb(a);return a} function Nk(a){Bb(a);return a} function Zk(a){Bb(a);return a} function cl(a){Bb(a);return a} function Bn(a){Ql(a);return a} function $n(a){Bb(a);return a} function rd(a){a.b={};return a} function ui(a,b){a.d=b;Yi(a.d)} function Li(a,b){a.b=b;return a} function Xi(a,b){a.c=b;return a} function dj(a,b){a.b=b;return a} function hk(a,b){a.c=b;return a} function qk(a,b){Bb(a);return a} function Wk(a,b){Bb(a);return a} function $k(a,b){Bb(a);return a} function Bl(a,b){Bb(a);return a} function jm(a,b){a.b=b;return a} function rm(){return Wm(this.b)} function en(){return this.c.b.e} function Nb(){Nb=up;$b();new Vb} function vl(){vl=up;sl={};ul={}} function zm(a,b){a.b=b;return a} function Vm(a,b){a.c=b;return a} function Wm(a){return a.b<a.c.c} function Wc(a){a.d=++Uc;return a} function hn(a,b){a.b=b;return a} function Bo(a,b){a.b=b;return a} function Fo(a,b){a.b=b;return a} function $h(a){return Wh(this,a)} function zh(a){return xh(this,a)} function yi(a){return ri(this,a)} function pl(a){return jl(this,a)} function lm(a){return km(this,a)} function Ko(a){Zo(this.b,this.c)} function Fl(a){throw Bl(new zl,Or)} function ag(){ag=up;_f=Wc(new Tc)} function kn(){return Wm(this.b.b)} function Zh(){return Oj(new Lj,this)} function Cm(a){return Zl(this.b,a)} function ah(a,b){!!a.i&&Td(a.i,b)} function cn(a){return Rl(this.b,a)} function Kn(a){return Rl(this.b,a)} function Ue(a,b){return a&&Re[a][b]} function Wl(b,a){return Nr+a in b.f} function Sf(a,b){return Qd(Wf(),a,b)} function xi(){return Qi(new Ni,this)} function Ti(){return this.b<this.d.c} function Ym(){return this.b<this.c.c} function yh(){return hk(new ek,this.b)} function Po(a,b){Oo();a.b=b;return a} function Te(a,b){return a&&!!Re[a][b]} function jk(){return this.b<this.c.c-1} function fl(a,b,c,d,e){a.b=b;return a} function mm(){return qm(new om,this.b)} function dp(a){nj(new lj,Ur);return a} function sm(){return Ve(Xm(this.b),25)} function vn(a){return sn(this,a,0)!=-1} function Rh(a){ch(this,a);ch(this.c,a)} function bi(a){ai();ci(a,_h,1);return a} function mg(){if(!ig){xg();ig=true}} function Xf(){if(!Of){Rg();Of=true}} function Im(a,b){return Fm(new Dm,b,a)} function Nm(a,b){(a<0||a>=b)&&Qm(a,b)} function Eg(a){a.c=on(new mn);return a} function ae(a){a.b=Bn(new zn);return a} function vk(a){a.b=Bn(new zn);return a} function Fn(a){a.b=Bn(new zn);return a} function Og(a,b,c){a.b=b;a.c=c;return a} function Fm(a,b,c){a.c=c;a.b=b;return a} function an(a,b,c){a.b=b;a.c=c;return a} function Tn(a,b,c){a.b=b;a.c=c;return a} function Jo(a,b,c){a.b=b;a.c=c;return a} function sp(a,b,c){a.b=b;a.c=c;return a} function Jm(a){return $l(this.c,this.b,a)} function Hm(){return this.c.f[Nr+this.b]} function U(){return this.$H||(this.$H=++rb)} function Rm(){return Vm(new Sm,Ve(this,6))} function rn(a,b){Nm(b,a.c);return a.b[b]} function Zo(a,b){wi(Ve(a.d,28).b,1,0,b)} function Oj(a,b){a.c=b;a.b=!!a.c.d;return a} function ab(a,b){Bb(a);a.b=b;Ab(a);return a} function pn(a,b){Ie(a.b,a.c++,b);return true} function T(a){return this===(a==null?null:a)} function Ye(a,b){return a!=null&&Te(a.tI,b)} function Sk(a){return this===(a==null?null:a)} function Tk(){return this.$H||(this.$H=++rb)} function Mm(a){qn(this,this.E(),a);return true} function $j(a){a.b=Fe(hf,0,10,4,0);return a} function to(a){a.b=new $wnd._IG_Prefs;return a} function xo(a){a.b=new $wnd._IG_Prefs;return a} function Cd(a){var b;if(zd){b=new yd;Td(a,b)}} function Xn(a){var b;b=this.c;this.c=a;return b} function Kj(a){Jj();Cj(a,$doc.body);return a} function Bj(){Bj=up;zj=Bn(new zn);Aj=Fn(new Dn)} function Wf(){!Pf&&(Pf=gg(new eg));return Pf} function Qm(a,b){throw $k(new Xk,Pr+a+Qr+b)} function Jh(a,b){a.k=b;a.k.tabIndex=0;return a} function Xd(a,b,c,d){a.b=b;a.d=c;a.c=d;return a} function Jk(a,b){var c;c=new Hk;c.b=a+b;return c} function Kk(a,b){var c;c=new Hk;c.b=a+b;return c} function Qi(a,b){a.c=b;a.d=a.c.f.c;Ri(a);return a} function ai(){ai=up;_h=Ge(lf,0,1,[$q,fr,gr])} function Me(){Me=up;Ke=[];Le=[];Ne(new Ae,Ke,Le)} function Oc(){Oc=up;Nc=Zc(new Sc,vq,(Oc(),new Cc))} function Rd(a,b){!a.b&&(a.b=on(new mn));pn(a.b,b)} function Xo(a){!Wo(a)&&xk(a.c,(Oo(),Mo).b,null)} function Cb(){try{null.a()}catch(a){return a}} function tc(b,a){return b[a]==null?null:String(b[a])} function un(a){return Ie(this.b,this.c++,a),true} function Gl(a){var b;b=El(this.x(),a);return !!b} function Dh(a){var b;b=xh(this,a);b&&Ch(a.k);return b} function Gn(a,b){var c;c=Xl(a.b,b,a);return c==null} function Rf(a){Xf();return Sf(zd?zd:(zd=Wc(new Tc)),a)} function Ph(){if(this.c){return this.c.g}return false} function on(a){a.b=Fe(jf,0,0,0,0);a.c=0;return a} function ln(){var a;return a=Ve(Xm(this.b.b),25),a.G()} function Jn(a){var b;return b=Xl(this.b,a,this),b==null} function Ze(a){return a!=null&&(a.tM!=up&&a.tI!=2)} function ef(a){if(a!=null){throw Nk(new Lk)}return a} function qo(a){a.b=to(new ro);a.c=xo(new vo);return a} function gg(a){a.e=ae(new Zd);a.f=null;a.d=false;return a} function Od(a,b){a.e=ae(new Zd);a.f=b;a.d=false;return a} function xb(a,b){a.length>=b&&a.splice(0,b);return a} function W(a){if(a.c==null){return Fe(kf,0,15,0,0)}return a.c} function Cj(a,b){Bj();a.b=$j(new Yj);a.k=b;bh(a);return a} function Ql(a){a.b=[];a.f={};a.d=false;a.c=null;a.e=0} function Ch(a){a.style[Zq]=uq;a.style[$q]=uq;a.style[_q]=uq} function yl(){if(tl==256){sl=ul;ul={};tl=0}++tl} function aj(){aj=up;_i=dj(new bj,Ar);dj(new bj,Zq);dj(new bj,Br)} function Oo(){Oo=up;No=Po(new Lo,Sr);Mo=Po(new Lo,Tr)} function Kl(a){var b;b=jm(new dm,a);return an(new $m,a,b)} function dn(){var a;return a=qm(new om,this.c.b),hn(new fn,a)} function rh(){var a,b;for(b=this.x();b.z();){a=Ve(b.A(),10);a.t()}} function qh(){var a,b;for(b=this.x();b.z();){a=Ve(b.A(),10);a.s()}} function wh(a,b,c){eh(b);_j(a.b,b);c.appendChild(b.k);fh(b,a)} function qn(a,b,c){(b<0||b>a.c)&&Qm(b,a.c);a.b.splice(b,0,c);++a.c} function tn(a,b,c){var d;d=(Nm(b,a.c),a.b[b]);Ie(a.b,b,c);return d} function Ge(a,b,c,d){Me();Pe(d,Ke,Le);d.tI=b;d.qI=c;return d} function Ve(a,b){if(a!=null&&!Ue(a.tI,b)){throw Nk(new Lk)}return a} function sf(a){if(a!=null&&Te(a.tI,19)){return a}return ab(new N,a)} function Ri(a){while(++a.b<a.d.c){if(rn(a.d,a.b)!=null){return}}} function ik(a){if(a.b>=a.c.c){throw $n(new Yn)}return a.c.b[++a.b]} function Xm(a){if(a.b>=a.c.c){throw $n(new Yn)}return rn(a.c,a.b++)} function Pj(a){if(!a.b||!a.c.d){throw $n(new Yn)}a.b=false;return a.c.d} function dk(a,b){var c;c=ak(a,b);if(c==-1){throw $n(new Yn)}ck(a,c)} function Zl(a,b){var c;c=a.c;a.c=b;if(!a.d){a.d=true;++a.e}return c} function bm(a){var b;b=a.c;a.c=null;if(a.d){a.d=false;--a.e}return b} function kb(a){return a.tM==up||a.tI==2?a.hC():a.$H||(a.$H=++rb)} function _l(a,b){return !b?bm(a):am(a,b,~~(b.$H||(b.$H=++rb)))} function sj(a){var b;b=kg((Nb(),a).type);(b&896)!=0?ch(this,a):ch(this,a)} function te(a){var b;return b=a.b.getString(a.n()),b==undefined?null:b} function Ln(){var a;return a=qm(new om,Kl(this.b).c.b),hn(new fn,a)} function Qd(a,b,c){a.c>0?Rd(a,Xd(new Vd,a,b,c)):be(a.e,b,c);return new Id} function _g(a,b,c){gh(a,kg(c.c));return Qd(!a.i?(a.i=Od(new Ld,a)):a.i,c,b)} function sn(a,b,c){for(;c<a.c;++c){if(eo(b,a.b[c])){return c}}return -1} function Pe(a,b,c){Me();for(var d=0,e=b.length;d<e;++d){a[b[d]]=c[d]}} function Ne(a,b,c){var d=0,e;for(var f in a){if(e=a[f]){b[d]=f;c[d]=e;++d}}} function ak(a,b){var c;for(c=0;c<a.c;++c){if(a.b[c]==b){return c}}return -1} function Ji(a,b,c,d){var e;Bi(a.b,b,c);e=a.b.b.rows[b].cells[c];e[xr]=d.b} function Fe(a,b,c,d,e){var f;f=Ee(e,d);Me();Pe(f,Ke,Le);f.tI=b;f.qI=c;return f} function Oh(a,b){if(a.c){throw Wk(new Uk,er)}eh(b);Yg(a,b.k);a.c=b;fh(b,a)} function We(a){if(a!=null&&(a.tM==up||a.tI==2)){throw Nk(new Lk)}return a} function og(a){return !(a!=null&&(a.tM!=up&&a.tI!=2))&&(a!=null&&Te(a.tI,8))} function cm(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function Cn(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function eo(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function vj(a,b,c){a.k=b;a.k.tabIndex=0;c!=null&&(a.k[cr]=c,undefined);return a} function Zc(a,b,c){a.d=++Uc;a.b=c;!Hc&&(Hc=rd(new pd));Hc.b[b]=a;a.c=b;return a} function $l(e,a,b){var c,d=e.f;a=Nr+a;a in d?(c=d[a]):++e.e;d[a]=b;return c} function jl(a,b){if(!(b!=null&&Te(b.tI,1))){return false}return String(a)==b} function nj(a,b){a.k=(Nb(),$doc).createElement(rr);a.k[cr]=Cr;Ub(a.k,b);return a} function uj(a){var b;vj(a,(b=(Nb(),$doc).createElement(Dr),b.type=Er,b),Fr);return a} function xj(a){var b;vj(a,(b=(Nb(),$doc).createElement(Dr),b.type=Gr,b),Hr);return a} function Uf(){var a;if(Of){a=(ag(),new $f);!!Pf&&Td(Pf,a);return null}return null} function Si(a){var b;if(a.b>=a.d.c){throw $n(new Yn)}b=Ve(rn(a.d,a.b),10);Ri(a);return b} function li(a,b){var c;c=a.b.rows.length;if(b>=c||b<0){throw $k(new Xk,tr+b+ur+c)}} function be(a,b,c){var d;d=Ve(Sl(a.b,b),6);if(!d){d=on(new mn);Xl(a.b,b,d)}Ie(d.b,d.c++,c)} function Gf(a,b,c){var d;d=Df;Df=a;b==Ef&&(kg((Nb(),a).type)==8192&&(Ef=null));c.o(a);Df=d} function El(a,b){var c;while(a.z()){c=a.A();if(b==null?c==null:ib(b,c)){return a}}return null} function ib(a,b){return a.tM==up||a.tI==2?a.eQ(b):(a==null?null:a)===(b==null?null:b)} function Sl(a,b){return b==null?a.c:b!=null&&Te(b.tI,1)?a.f[Nr+Ve(b,1)]:Tl(a,b,~~kb(b))} function Rl(a,b){return b==null?a.d:b!=null&&Te(b.tI,1)?Wl(a,Ve(b,1)):Vl(a,b,~~kb(b))} function Xl(a,b,c){return b==null?Zl(a,c):b!=null&&Te(b.tI,1)?$l(a,Ve(b,1),c):Yl(a,b,c,~~kb(b))} function Fg(a,b){var c,d;c=(d=b[Uq],d==null?-1:d);if(c<0){return null}return Ve(rn(a.c,c),9)} function Hg(a,b){var c,d;c=(d=b[Uq],d==null?-1:d);b[Uq]=null;tn(a.c,c,null);a.b=Og(new Mg,c,a.b)} function Sb(a){var b=a.firstChild;while(b&&b.nodeType!=1)b=b.nextSibling;return b} function Fb(a){var b,c,d;d=Kb(a);for(b=0,c=d.length;b<c;++b){d[b]=d[b].length==0?rq:d[b]}return d} function Wo(a){var b,c,d;c=false;if(a.b){b=te(a.b.b);d=te(a.b.c);c=!jl(uq,d)||!jl(uq,b)}return c} function Gg(a,b){var c;if(!a.b){c=a.c.c;pn(a.c,b)}else{c=a.b.b;tn(a.c,c,b);a.b=a.b.c}b.k[Uq]=c} function hm(){var a,b,c;a=0;for(b=this.x();b.z();){c=b.A();if(c!=null){a+=kb(c);a=~~a}}return a} function xm(){var a,b;a=0;b=0;this.G()!=null&&(a=kb(this.G()));this.H()!=null&&(b=kb(this.H()));return a^b} function Qh(){if(this.h!=-1){gh(this.c,this.h);this.h=-1}bh(this.c);this.k.__listener=this} function gh(a,b){a.h==-1?Lf(a.k,b|(a.k.__eventBits||0)):(a.h|=b)} function Xh(a,b){if(b==a.d){return}!!b&&eh(b);!!a.d&&Wh(a,a.d);a.d=b;if(b){a.b.appendChild(a.d.k);fh(b,a)}} function Wh(a,b){if(a.d!=b){return false}fh(b,null);a.y().removeChild(b.k);a.d=null;return true} function fh(a,b){var c;c=a.j;if(!b){!!c&&c.r()&&a.t();a.j=null}else{if(c){throw Wk(new Uk,Yq)}a.j=b;b.r()&&a.s()}} function bh(a){var b;if(a.r()){throw Wk(new Uk,Vq)}a.g=true;a.k.__listener=a;b=a.h;a.h=-1;b>0&&gh(a,b);a.p();a.u()} function dh(a){if(!a.r()){throw Wk(new Uk,Wq)}try{a.v()}finally{a.q();a.k.__listener=null;a.g=false}} function Yi(a){if(!a.b){a.b=(Nb(),$doc).createElement(yr);yg(a.c.e,a.b,0);a.b.appendChild($doc.createElement(zr))}} function Di(a,b,c){var d=a.rows[b];for(var e=0;e<c;e++){var f=$doc.createElement(qr);d.appendChild(f)}} function Pl(e,a){var b=e.f;for(var c in b){if(c.charCodeAt(0)==58){var d=Im(e,c.substring(1));a.C(d)}}} function Ol(g,a){var b=g.b;for(var c in b){if(c==parseInt(c)){var d=b[c];for(var e=0,f=d.length;e<f;++e){a.C(d[e])}}}} function X(a,b){var c,d,e;d=Fe(kf,0,15,b.length,0);for(e=0,c=b.length;e<c;++e){if(!b[e]){throw cl(new al)}d[e]=b[e]}a.c=d} function Ee(a,b){var c=new Array(b);if(a>0){var d=[null,0,false,[0,0]][a];for(var e=0;e<b;++e){c[e]=d}}return c} function xl(a){vl();var b=Nr+a;var c=ul[b];if(c!=null){return c}c=sl[b];c==null&&(c=wl(a));yl();return ul[b]=c} function Ej(a){Bj();var b;b=Ve(Sl(zj,a),20);if(b){return b}zj.e==0&&Rf(new Gj);b=Kj(new Ij);Xl(zj,a,b);Gn(Aj,b);return b} function gwtOnLoad(b,c,d){$moduleName=c;$moduleBase=d;if(b)try{pf()}catch(a){b(c)}else{pf()}} function di(a){var b,c;c=(Nb(),$doc).createElement(qr);b=$doc.createElement(rr);c.appendChild(b);c[cr]=a;b[cr]=a+sr;return c} function tp(a){var b,c;b=tc(a.b.k,fs);c=tc(a.c.k,fs);if(!jl(uq,b)&&!jl(uq,c)){null.K();null.K();null.K(null.K())}} function wm(a){var b;if(a!=null&&Te(a.tI,25)){b=Ve(a,25);if(eo(this.G(),b.G())&&eo(this.H(),b.H())){return true}}return false} function Ud(a){var b,c;if(a.b){try{for(c=Vm(new Sm,a.b);c.b<c.c.c;){b=Ve(Xm(c),5);be(b.b.e,b.d,b.c)}}finally{a.b=null}}} function qm(a,b){var c;a.c=b;c=on(new mn);a.c.d&&pn(c,zm(new tm,a.c));Pl(a.c,c);Ol(a.c,c);a.b=Vm(new Sm,c);return a} function ck(a,b){var c;if(b<0||b>=a.c){throw Zk(new Xk)}--a.c;for(c=b;c<a.c;++c){Ie(a.b,c,a.b[c+1])}Ie(a.b,a.c,null)} function Bi(a,b,c){var d,e;Ci(a,b);if(c<0){throw $k(new Xk,vr+c)}d=(li(a,b),a.b.rows[b].cells.length);e=c+1-d;e>0&&Di(a.b,b,e)} function vi(a,b,c,d){var e,f;Bi(a,b,c);e=(f=a.c.b.b.rows[b].cells[c],qi(a,f,d==null),f);d!=null&&(e.innerHTML=d||uq,undefined)} function Lc(a,b,c){var d,e,f;if(Hc){f=Ve(Hc.b[(Nb(),a).type],3);if(f){d=f.b.b;e=f.b.c;f.b.b=a;f.b.c=c;ah(b,f.b);f.b.b=d;f.b.c=e}}} function km(a,b){var c,d,e;if(b!=null&&Te(b.tI,25)){c=Ve(b,25);d=c.G();if(Rl(a.b,d)){e=Sl(a.b,d);return Cn(c.H(),e)}}return false} function Ml(){var a,b,c;c=0;for(b=qm(new om,jm(new dm,Ve(this,26)).b);Wm(b.b);){a=Ve(Xm(b.b),25);c+=a.hC();c=~~c}return c} function Pm(){var a,b,c;b=1;a=Vm(new Sm,Ve(this,6));while(a.b<a.c.c){c=Xm(a);b=31*b+(c==null?0:kb(c));b=~~b}return b} function Bb(a){var b,c,d,e;d=xb(Fb(Cb()),3);e=Fe(kf,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=fl(new dl,pq,d[b],qq,0)}X(a,e)} function wg(a,b){var c=0,d=a.firstChild;while(d){var e=d.nextSibling;if(d.nodeType==1){if(b==c)return d;++c}d=e}return null} function yg(a,b,c){var d=0,e=a.firstChild,f=null;while(e){if(e.nodeType==1){if(d==c){f=e;break}++d}e=e.nextSibling}a.insertBefore(b,f)} function Ub(a,b){while(a.firstChild){a.removeChild(a.firstChild)}b!=null&&a.appendChild(a.ownerDocument.createTextNode(b))} function eh(a){if(!a.j){Bj();if(Rl(Aj.b,a)){a.t();_l(Aj.b,a)!=null}}else if(Ye(a.j,21)){Ve(a.j,21).w(a)}else if(a.j){throw Wk(new Uk,Xq)}} function ch(a,b){var c;switch(kg((Nb(),b).type)){case 16:case 32:c=b.relatedTarget;if(!!c&&a.k.contains(c)){return}}Lc(b,a,a.k)} function Td(a,b){var c;if(b.d){b.d=false;b.e=null}c=b.e;b.e=a.f;try{++a.c;ce(a.e,b,a.d)}finally{--a.c;a.c==0&&Ud(a)}if(c==null){b.d=true;b.e=null}else{b.e=c}} function wi(a,b,c,d){var e,f;Bi(a,b,c);if(d){eh(d);e=(f=a.c.b.b.rows[b].cells[c],qi(a,f,true),f);Gg(a.f,d);e.appendChild(d.k);fh(d,a)}} function qi(a,b,c){var d,e;d=Sb((Nb(),b));e=null;!!d&&(e=Ve(Fg(a.f,d),10));if(e){ri(a,e);return true}else{c&&(b.innerHTML=uq,undefined);return false}} function Tl(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){return f.H()}}}return null} function Vl(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){return true}}}return false} function xh(a,b){var c,d;if(b.j!=a){return false}fh(b,null);c=b.k;(d=(Nb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);dk(a.b,b);return true} function ri(a,b){var c,d;if(b.j!=a){return false}fh(b,null);c=b.k;(d=(Nb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);Hg(a.f,c);return true} function Lh(a,b,c){var d;Jh(a,(d=(Nb(),$doc).createElement(ar),d.type=br,d));a.k[cr]=dr;a.k.innerHTML=b||uq;_g(a,c,(Oc(),Nc));return a} function Ai(a){a.f=Eg(new Bg);a.e=(Nb(),$doc).createElement(hr);a.b=$doc.createElement(ir);a.e.appendChild(a.b);a.k=a.e;a.c=Li(new Ei,a);ui(a,Xi(new Vi,a));return a} function nl(c){if(c.length==0||c[0]>Mr&&c[c.length-1]>Mr){return c}var a=c.replace(/^(\s*)/,uq);var b=a.replace(/\s*$/,uq);return b} function gm(a){var b,c,d;if((a==null?null:a)===this){return true}if(!(a!=null&&Te(a.tI,27))){return false}c=Ve(a,27);if(c.E()!=this.E()){return false}for(b=c.x();b.z();){d=b.A();if(!this.D(d)){return false}}return true} function Yl(j,a,b,c){var d=j.b[c];if(d){for(var e=0,f=d.length;e<f;++e){var g=d[e];var h=g.G();if(j.F(a,h)){var i=g.H();g.I(b);return i}}}else{d=j.b[c]=[]}var g=Tn(new Rn,a,b);d.push(g);++j.e;return null} function wl(a){var b,c,d,e;b=0;d=a.length;e=d-4;c=0;while(c<e){b=a.charCodeAt(c+3)+31*(a.charCodeAt(c+2)+31*(a.charCodeAt(c+1)+31*(a.charCodeAt(c)+31*b)))|0;c+=4}while(c<d){b=b*31+a.charCodeAt(c++)}return b|0} function Ab(a){var b,c,d,e;d=Fb(Ze(a.b)?We(a.b):null);e=Fe(kf,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=fl(new dl,pq,d[b],qq,0)}X(a,e)} function Kb(a){var b,c,d,e,f;f=a&&a.message?a.message.split(sq):[];for(b=0,c=0,e=f.length;c<e;++b,c+=2){d=f[c].lastIndexOf(tq);d==-1?(f[b]=uq,undefined):(f[b]=nl(f[c].substr(d+9,f[c].length-(d+9))),undefined)}f.length=b;return f} function bk(a,b,c){var d,e;if(c<0||c>a.c){throw Zk(new Xk)}if(a.c==a.b.length){e=Fe(hf,0,10,a.b.length*2,0);for(d=0;d<a.b.length;++d){Ie(e,d,a.b[d])}a.b=e}++a.c;for(d=a.c-1;d>c;--d){Ie(a.b,d,a.b[d-1])}Ie(a.b,c,b)} function Ie(a,b,c){if(c!=null){if(a.qI>0&&!Ue(c.tI,a.qI)){throw Fk(new Dk)}if(a.qI<0&&(c.tM==up||c.tI==2)){throw Fk(new Dk)}}return a[b]=c} function Ci(a,b){var c,d,e;if(b<0){throw $k(new Xk,wr+b)}d=a.b.rows.length;for(c=d;c<=b;++c){c!=a.b.rows.length&&li(a,c);e=(Nb(),$doc).createElement(lr);yg(a.b,e,c)}} function Om(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&Te(a.tI,6))){return false}f=Ve(a,6);if(this.E()!=f.c){return false}d=Vm(new Sm,Ve(this,6));e=Vm(new Sm,f);while(d.b<d.c.c){b=Xm(d);c=Xm(e);if(!(b==null?c==null:ib(b,c))){return false}}return true} function hp(a){var b;a.b=Ai(new gi);a.b.e[jr]=6;a.b.k.style[Vr]=Wr;b=a.b.c;vi(a.b,0,0,Xr);Ji(b,0,0,(aj(),_i));wi(a.b,1,0,nj(new lj,Yr));Oh(a,a.b);return a} function Rg(){var d=$wnd.onbeforeunload;var e=$wnd.onunload;$wnd.onbeforeunload=function(a){var b,c;try{b=Uf()}finally{c=d&&d(a)}if(b!=null){return b}if(c!=null){return c}};$wnd.onunload=function(a){try{Of&&Cd(Wf())}finally{e&&e(a);$wnd.onresize=null;$wnd.onscroll=null;$wnd.onbeforeunload=null;$wnd.onunload=null}}} function Dj(){var c,d;Bj();var a,b;for(b=(c=qm(new om,Kl(Aj.b).c.b),hn(new fn,c));Wm(b.b.b);){a=Ve((d=Ve(Xm(b.b.b),25),d.G()),10);a.r()&&a.t()}Ql(Aj.b);Ql(zj)} function ci(a,b,c){var d,e,f,g;ai();a.k=(Nb(),$doc).createElement(hr);f=a.k;a.c=$doc.createElement(ir);f.appendChild(a.c);f[jr]=0;f[kr]=0;for(d=0;d<b.length;++d){e=(g=$doc.createElement(lr),(g[cr]=b[d],undefined),g.appendChild(di(b[d]+mr)),g.appendChild(di(b[d]+nr)),g.appendChild(di(b[d]+or)),g);a.c.appendChild(e);d==c&&(a.b=Sb(wg(e,1)))}a.k[cr]=pr;return a} function am(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){c.length==1?delete h.b[b]:c.splice(d,1);--h.e;return f.H()}}}return null} function pf(){var a,i,j,k,l,m,n,o;!!$stats&&$stats({moduleName:$moduleName,subSystem:wq,evtGroup:xq,millis:(new Date).getTime(),type:yq,className:zq});(new jo).J(new le);a=Bo(new zo,qo(new no));k=vk(new sk);l=hp(new ep);m=new To;m.c=k;m.d=l;m.b=a.b;Xl(k.b,(Oo(),No).b,Fo(new Do,m));n=op(new mp);o=new $o;o.c=k;o.d=n;j=dp(new bp);i=new Qo;i.c=k;i.d=j;Xl(k.b,Mo.b,Jo(new Ho,m,n));Bh((Bj(),Ej(null)),l);xk(k,No.b,null)} function xk(b,c,d){var a,f;try{Ve(Sl(b.b,c),22).B(d)}catch(a){a=sf(a);if(Ye(a,23)){f=a;if(jl(W(f)[0].b,gf.b)){throw qk(new ok,Ir+c+Jr)}throw f}else if(Ye(a,24)){f=a;if(jl(W(f)[1].b,gf.b)){throw qk(new ok,Kr+c+Lr)}throw f}else throw a}} function ce(a,b,c){var d,e,f,g,h,i,j;g=b.m();d=(h=Ve(Sl(a.b,g),6),!h?0:h.c);if(c){for(f=d-1;f>=0;--f){e=(i=Ve(Sl(a.b,g),6),Ve((Nm(f,i.c),i.b[f]),18));b.l(e)}}else{for(f=0;f<d;++f){e=(j=Ve(Sl(a.b,g),6),Ve((Nm(f,j.c),j.b[f]),18));b.l(e)}}} function kg(a){switch(a){case Aq:return 4096;case Bq:return 1024;case vq:return 1;case Cq:return 2;case Dq:return 2048;case Eq:return 128;case Fq:return 256;case Gq:return 512;case Hq:return 32768;case Iq:return 8192;case Jq:return 4;case Kq:return 64;case Lq:return 32;case Mq:return 16;case Nq:return 8;case Oq:return 16384;case Pq:return 65536;case Qq:return 131072;case Rq:return 131072;case Sq:return 262144;case Tq:return 524288;}} function op(a){var b,c,d,e,f,g;a.b=(e=Ai(new gi),(e.e[jr]=6,undefined),(e.k.style[Vr]=Zr,undefined),c=e.c,vi(e,0,0,$r),((Bi(c.b,0,0),c.b.b.rows[0].cells[0])[_r]=2,undefined),Ji(c,0,0,(aj(),_i)),vi(e,1,0,as),g=uj(new pj),(g.k.style[Vr]=bs,undefined),wi(e,1,1,g),vi(e,2,0,cs),f=xj(new oj),(f.k.style[Vr]=bs,undefined),wi(e,2,1,f),b=Lh(new Eh,ds,sp(new qp,f,g)),wi(e,3,1,b),d=bi(new Th),Xh(d,e),(d.k.style[Vr]=es,undefined),d);Oh(a,a.b);return a} function Ll(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&Te(a.tI,26))){return false}e=Ve(a,26);if(Ve(this,26).e!=e.e){return false}for(c=qm(new om,jm(new dm,e).b);Wm(c.b);){b=Ve(Xm(c.b),25);d=b.G();f=b.H();if(!(d==null?Ve(this,26).d:d!=null&&Te(d.tI,1)?Wl(Ve(this,26),Ve(d,1)):Vl(Ve(this,26),d,~~kb(d)))){return false}if(!eo(f,d==null?Ve(this,26).c:d!=null&&Te(d.tI,1)?Ve(this,26).f[Nr+Ve(d,1)]:Tl(Ve(this,26),d,~~kb(d)))){return false}}return true} function Lf(a,b){mg();a.__eventBits=b;a.onclick=b&1?ug:null;a.ondblclick=b&2?ug:null;a.onmousedown=b&4?ug:null;a.onmouseup=b&8?ug:null;a.onmouseover=b&16?ug:null;a.onmouseout=b&32?ug:null;a.onmousemove=b&64?ug:null;a.onkeydown=b&128?ug:null;a.onkeypress=b&256?ug:null;a.onkeyup=b&512?ug:null;a.onchange=b&1024?ug:null;a.onfocus=b&2048?ug:null;a.onblur=b&4096?ug:null;a.onlosecapture=b&8192?ug:null;a.onscroll=b&16384?ug:null;a.onload=b&32768?ug:null;a.onerror=b&65536?ug:null;a.onmousewheel=b&131072?ug:null;a.oncontextmenu=b&262144?ug:null;a.onpaste=b&524288?ug:null} function xg(){tg=function(a){if(sg(a)){var b=rg;if(b&&b.__listener){if(og(b.__listener)){Gf(a,b,b.__listener);a.stopPropagation()}}}};sg=function(a){return true};ug=function(a){var b,c=this;while(c&&!(b=c.__listener)){c=c.parentNode}c&&c.nodeType!=1&&(c=null);b&&(og(b)&&Gf(a,c,b))};$wnd.addEventListener(vq,tg,true);$wnd.addEventListener(Cq,tg,true);$wnd.addEventListener(Jq,tg,true);$wnd.addEventListener(Nq,tg,true);$wnd.addEventListener(Kq,tg,true);$wnd.addEventListener(Mq,tg,true);$wnd.addEventListener(Lq,tg,true);$wnd.addEventListener(Qq,tg,true);$wnd.addEventListener(Eq,sg,true);$wnd.addEventListener(Gq,sg,true);$wnd.addEventListener(Fq,sg,true)} var uq='',sq='\n',Mr=' ',Jr=" doesn't exist. Have you forgotten to add it to your Mvp4g configuration file?",Lr=' is incorrect. It should be the same as the one configured in the Mvp4g configuration file.',ur=', Row size: ',Qr=', Size: ',bs='100px',Zr='200px',Wr='250px',Xr='4kGadget initialization...',es='80%',Nr=':',Or='Add not supported on this collection',ar='BUTTON',vr='Cannot create a column with a negative index: ',wr='Cannot create a row with a negative index: ',Yq='Cannot set a new parent without first clearing the old parent',nr='Center',Kr='Class of the object sent with event ',er='Composite.initWidget() may only be called once.',Rq='DOMMouseScroll',Tr='ENTER_CREDENTIALS',$r='Enter credentials',Ir='Event ',ms='EventBus',Dr='INPUT',Pr='Index: ',sr='Inner',mr='Left',ns='Object;',cs='Password',or='Right',tr='Row index: ',Sr='START',Vq="Should only call onAttach when the widget is detached from the browser's document",Wq="Should only call onDetach when the widget is attached to the browser's document",hs='StackTraceElement;',is='String;',ds='Submit',Xq="This widget's parent does not implement HasWidgets",pq='Unknown',qq='Unknown source',as='Username',ks='Widget;',js='[Lcom.google.gwt.user.client.ui.',gs='[Ljava.lang.',Uq='__uiObjectID',xr='align',rq='anonymous',Aq='blur',gr='bottom',br='button',kr='cellPadding',jr='cellSpacing',Ar='center',Bq='change',cr='className',vq='click',zr='col',_r='colSpan',yr='colgroup',ls='com.mvp4g.client.event.',Sq='contextmenu',Cq='dblclick',rr='div',Pq='error',Dq='focus',tq='function ',dr='gwt-Button',pr='gwt-DecoratorPanel',Cr='gwt-Label',Hr='gwt-PasswordTextBox',Fr='gwt-TextBox',Eq='keydown',Fq='keypress',Gq='keyup',Ur='label',Zq='left',Hq='load',Iq='losecapture',fr='middle',xq='moduleStartup',Jq='mousedown',Kq='mousemove',Lq='mouseout',Mq='mouseover',Nq='mouseup',Qq='mousewheel',zq='name.webdizz.gadget.four.envelope.client.Envelope',yq='onModuleLoadStart',Gr='password',Tq='paste',_q='position',Br='right',Oq='scroll',wq='startup',Yr='stub content',hr='table',ir='tbody',qr='td',Er='text',$q='top',lr='tr',Rr='username',fs='value',Vr='width';var _;_=R.prototype={};_.eQ=T;_.hC=U;_.tM=up;_.tI=1;_=Q.prototype=new R;_.tI=3;_.c=null;_=P.prototype=new Q;_.tI=4;_=O.prototype=new P;_.tI=5;_=N.prototype=new O;_.tI=6;_.b=null;var rb=0;_=Mb.prototype=new R;_.tI=0;_=Wb.prototype=new Mb;_.tI=0;_=Vb.prototype=new Wb;_.tI=0;_=Ec.prototype=new R;_.tI=0;_.d=false;_.e=null;_=Dc.prototype=new Ec;_.m=Mc;_.tI=0;_.b=null;_.c=null;var Hc=null;_=Cc.prototype=new Dc;_.l=Qc;_.tI=0;var Nc;_=Tc.prototype=new R;_.hC=Xc;_.tI=0;_.d=0;var Uc=0;_=Sc.prototype=new Tc;_.tI=7;_.b=null;_.c=null;_=pd.prototype=new R;_.tI=0;_.b=null;_=yd.prototype=new Ec;_.l=Bd;_.m=Dd;_.tI=0;var zd=null;_=Id.prototype=new R;_.tI=0;_=Ld.prototype=new R;_.tI=0;_.b=null;_.c=0;_.d=false;_.e=null;_.f=null;_=Vd.prototype=new R;_.tI=8;_.b=null;_.c=null;_.d=null;_=Zd.prototype=new R;_.tI=0;_=he.prototype=new R;_.tI=0;_=le.prototype=new R;_.tI=0;_=pe.prototype=new R;_.tI=0;_=oe.prototype=new pe;_.tI=0;_=Ae.prototype=new R;_.tI=0;_.length=0;_.qI=0;var Ke,Le;var Re=[{},{},{1:1,11:1,12:1,13:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{3:1},{5:1},{7:1},{9:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,20:1,21:1},{4:1,18:1},{7:1,8:1,9:1,10:1,20:1,21:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,24:1},{11:1,13:1,14:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,23:1},{11:1,15:1},{12:1},{11:1,19:1},{27:1},{27:1},{25:1},{25:1},{25:1},{27:1},{6:1,11:1},{11:1,26:1},{11:1,27:1},{25:1},{11:1,19:1},{22:1},{22:1},{11:1,13:1,14:1,16:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,28:1},{7:1,8:1,9:1,10:1},{2:1,18:1},{17:1}];var Df=null,Ef=null;var Of=false,Pf=null;_=$f.prototype=new Ec;_.l=cg;_.m=dg;_.tI=0;var _f;_=eg.prototype=new Ld;_.tI=9;var ig=false;var rg=null,sg=null,tg=null,ug=null;_=Bg.prototype=new R;_.tI=0;_.b=null;_=Mg.prototype=new R;_.tI=0;_.b=0;_.c=null;_=Wg.prototype=new R;_.tI=10;_.k=null;_=Vg.prototype=new Wg;_.p=hh;_.q=ih;_.r=jh;_.s=kh;_.o=lh;_.t=mh;_.u=nh;_.v=oh;_.tI=11;_.g=false;_.h=0;_.i=null;_.j=null;_=Ug.prototype=new Vg;_.p=qh;_.q=rh;_.u=sh;_.v=th;_.tI=12;_=Tg.prototype=new Ug;_.x=yh;_.w=zh;_.tI=13;_=Sg.prototype=new Tg;_.w=Dh;_.tI=14;_=Gh.prototype=new Vg;_.tI=15;_=Fh.prototype=new Gh;_.tI=16;_=Eh.prototype=new Fh;_.tI=17;_=Mh.prototype=new Vg;_.r=Ph;_.s=Qh;_.o=Rh;_.t=Sh;_.tI=18;_.c=null;_=Uh.prototype=new Ug;_.y=Yh;_.x=Zh;_.w=$h;_.tI=19;_.d=null;_=Th.prototype=new Uh;_.y=fi;_.tI=20;_.b=null;_.c=null;var _h;_=hi.prototype=new Ug;_.x=xi;_.w=yi;_.tI=21;_.b=null;_.c=null;_.d=null;_.e=null;_=gi.prototype=new hi;_.tI=22;_=Fi.prototype=new R;_.tI=0;_.b=null;_=Ei.prototype=new Fi;_.tI=0;_=Ni.prototype=new R;_.z=Ti;_.A=Ui;_.tI=0;_.b=-1;_.c=null;_=Vi.prototype=new R;_.tI=0;_.b=null;_.c=null;var _i;_=bj.prototype=new R;_.tI=0;_.b=null;_=lj.prototype=new Vg;_.tI=23;_=qj.prototype=new Gh;_.o=sj;_.tI=24;_=pj.prototype=new qj;_.tI=25;_=oj.prototype=new pj;_.tI=26;_=yj.prototype=new Sg;_.tI=27;var zj,Aj;_=Gj.prototype=new R;_.tI=28;_=Ij.prototype=new yj;_.tI=29;_=Lj.prototype=new R;_.z=Qj;_.A=Rj;_.tI=0;_.c=null;_=Yj.prototype=new R;_.tI=0;_.b=null;_.c=0;_=ek.prototype=new R;_.z=jk;_.A=kk;_.tI=0;_.b=-1;_.c=null;_=ok.prototype=new O;_.tI=30;_=sk.prototype=new R;_.tI=0;_=yk.prototype=new R;_.tI=0;_.c=null;_.d=null;_=Dk.prototype=new O;_.tI=32;_=Hk.prototype=new R;_.tI=0;_.b=null;_=Lk.prototype=new O;_.tI=35;_=Qk.prototype=new R;_.eQ=Sk;_.hC=Tk;_.tI=36;_.b=null;_=Uk.prototype=new O;_.tI=37;_=Xk.prototype=new O;_.tI=38;_=al.prototype=new O;_.tI=39;_=dl.prototype=new R;_.tI=40;_.b=null;_=String.prototype;_.eQ=pl;_.hC=ql;_.tI=2;var sl,tl=0,ul;_=zl.prototype=new O;_.tI=42;_=Cl.prototype=new R;_.C=Fl;_.D=Gl;_.tI=0;_=Il.prototype=new R;_.eQ=Ll;_.hC=Ml;_.tI=0;_=Hl.prototype=new Il;_.F=cm;_.tI=0;_.b=null;_.c=null;_.d=false;_.e=0;_.f=null;_=em.prototype=new Cl;_.eQ=gm;_.hC=hm;_.tI=43;_=dm.prototype=new em;_.D=lm;_.x=mm;_.E=nm;_.tI=44;_.b=null;_=om.prototype=new R;_.z=rm;_.A=sm;_.tI=0;_.b=null;_.c=null;_=um.prototype=new R;_.eQ=wm;_.hC=xm;_.tI=45;_=tm.prototype=new um;_.G=Am;_.H=Bm;_.I=Cm;_.tI=46;_.b=null;_=Dm.prototype=new um;_.G=Gm;_.H=Hm;_.I=Jm;_.tI=47;_.b=null;_.c=null;_=Km.prototype=new Cl;_.C=Mm;_.eQ=Om;_.hC=Pm;_.x=Rm;_.tI=0;_=Sm.prototype=new R;_.z=Ym;_.A=Zm;_.tI=0;_.b=0;_.c=null;_=$m.prototype=new em;_.D=cn;_.x=dn;_.E=en;_.tI=48;_.b=null;_.c=null;_=fn.prototype=new R;_.z=kn;_.A=ln;_.tI=0;_.b=null;_=mn.prototype=new Km;_.C=un;_.D=vn;_.E=wn;_.tI=49;_.b=null;_.c=0;_=zn.prototype=new Hl;_.tI=50;_=Dn.prototype=new em;_.C=Jn;_.D=Kn;_.x=Ln;_.E=Mn;_.tI=51;_.b=null;_=Rn.prototype=new um;_.G=Un;_.H=Vn;_.I=Xn;_.tI=52;_.b=null;_.c=null;_=Yn.prototype=new O;_.tI=53;_=fo.prototype=new he;_.J=io;_.tI=0;_=jo.prototype=new fo;_.tI=0;_=no.prototype=new R;_.tI=0;_=ro.prototype=new oe;_.n=uo;_.tI=0;_=vo.prototype=new oe;_.n=yo;_.tI=0;_=zo.prototype=new R;_.tI=0;_.b=null;_=Do.prototype=new R;_.B=Go;_.tI=54;_.b=null;_=Ho.prototype=new R;_.B=Ko;_.tI=55;_.b=null;_.c=null;_=Lo.prototype=new Qk;_.tI=56;var Mo,No;_=Qo.prototype=new yk;_.tI=0;_=To.prototype=new yk;_.tI=0;_.b=null;_=$o.prototype=new yk;_.tI=0;_=bp.prototype=new Mh;_.tI=57;_=ep.prototype=new Mh;_.tI=58;_=mp.prototype=new Mh;_.tI=59;_.b=null;_=qp.prototype=new R;_.tI=60;_.b=null;_.c=null;var kf=Jk(gs,hs),lf=Jk(gs,is),hf=Jk(js,ks),gf=Kk(ls,ms),jf=Jk(gs,ns);$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalEnd'});if (envelope) envelope.onScriptLoad(gwtOnLoad);})();
JavaScript
(function(){var $gwt_version = "2.0.0";var $wnd = window;var $doc = $wnd.document;var $moduleName, $moduleBase;var $strongName = '7A55E7403FE54814AFE5E2E3AC5AF674';var $stats = $wnd.__gwtStatsEvent ? function(a) {return $wnd.__gwtStatsEvent(a);} : null;$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalStart'});function R(){} function Q(){} function P(){} function O(){} function N(){} function Dp(){} function yb(){} function Eb(){} function Mb(){} function Lb(){} function Fc(){} function Ec(){} function Dc(){} function Uc(){} function Tc(){} function qd(){} function zd(){} function Jd(){} function Md(){} function Wd(){} function $d(){} function ie(){} function me(){} function qe(){} function pe(){} function Be(){} function bg(){} function hg(){} function Ag(){} function Lg(){} function Zg(){} function dh(){} function qh(){} function rh(){} function wh(){} function xh(){} function ch(){} function Bh(){} function Ch(){} function bh(){} function ah(){} function _g(){} function Ph(){} function Oh(){} function Nh(){} function Vh(){} function bi(){} function ai(){} function qi(){} function pi(){} function Oi(){} function Ni(){} function Wi(){} function cj(){} function kj(){} function uj(){} function zj(){} function yj(){} function xj(){} function Hj(){} function Pj(){} function Rj(){} function Uj(){} function fk(){} function nk(){} function xk(){} function Bk(){} function Hk(){} function Mk(){} function Qk(){} function Uk(){} function Zk(){} function bl(){} function el(){} function jl(){} function ml(){} function Il(){} function Ll(){} function Rl(){} function Ql(){} function nm(){} function mm(){} function xm(){} function Dm(){} function Cm(){} function Mm(){} function Tm(){} function _m(){} function hn(){} function pn(){} function vn(){} function In(){} function Mn(){} function $n(){} function go(){} function oo(){} function so(){} function wo(){} function Ao(){} function Eo(){} function Io(){} function Mo(){} function Qo(){} function Uo(){} function Zo(){} function ap(){} function hp(){} function kp(){} function np(){} function vp(){} function zp(){} function ro(a){} function th(){kh(this)} function fh(a,b){a.j=b} function vh(){mh(this)} function Ed(){return Ad} function gg(){return cg} function Do(){return gs} function Ho(){return qs} function Ob(){Ob=Dp;Fb()} function Wb(){Wb=Dp;Ob()} function Ug(){Ug=Dp;Xg()} function _h(){mh(this.b)} function Sj(){Sj=Dp;Kj()} function uh(a){lh(this,a)} function Jm(){return null} function Po(a){ep(this.a)} function Rc(a){Cp(We(a,2))} function Mf(a){return true} function Db(a){return xb(a)} function Yc(){return this.c} function Cd(a){We(a,4);Mj()} function sh(){return this.f} function fi(){return this.j} function oi(){return this.a} function Zj(){return this.a} function Pm(){return this.a} function Fn(){return this.b} function bo(){return this.a} function co(){return this.b} function Nc(){return Pc(),Oc} function bj(){return _i(this)} function $j(){return Yj(this)} function tk(){return rk(this)} function zl(){return Gl(this)} function wm(){return this.a.d} function Km(){return this.a.b} function gn(){return en(this)} function Vn(){return this.a.d} function Kh(a,b){Fh(a,b,a.j)} function ik(a,b){kk(a,b,a.b)} function Of(a,b){pg();zg(a,b)} function fg(a){ff(a);null.K()} function Ok(a){Cb(a);return a} function Wk(a){Cb(a);return a} function gl(a){Cb(a);return a} function ll(a){Cb(a);return a} function Kn(a){Zl(a);return a} function io(a){Cb(a);return a} function sd(a){a.a={};return a} function Di(a,b){a.c=b;fj(a.c)} function Ui(a,b){a.a=b;return a} function ej(a,b){a.b=b;return a} function mj(a,b){a.a=b;return a} function qk(a,b){a.b=b;return a} function zk(a,b){Cb(a);return a} function dl(a,b){Cb(a);return a} function hl(a,b){Cb(a);return a} function Kl(a,b){Cb(a);return a} function sm(a,b){a.a=b;return a} function Am(){return dn(this.a)} function on(){return this.b.a.d} function dn(a){return a.a<a.b.b} function Ih(a){return Gh(this,a)} function Im(a,b){a.a=b;return a} function cn(a,b){a.b=b;return a} function rn(a,b){a.a=b;return a} function Ko(a,b){a.a=b;return a} function Oo(a,b){a.a=b;return a} function Xc(a){a.c=++Vc;return a} function hi(a){return di(this,a)} function Hi(a){return Ai(this,a)} function yl(a){return sl(this,a)} function um(a){return tm(this,a)} function Lm(a){return gm(this.a,a)} function tn(){return dn(this.a.a)} function mn(a){return $l(this.a,a)} function Tn(a){return $l(this.a,a)} function To(a){gp(this.a,this.b)} function Ol(a){throw Kl(new Il,ns)} function Fb(){Fb=Dp;Wb();new Lb} function El(){El=Dp;Bl={};Dl={}} function dg(){dg=Dp;cg=Xc(new Uc)} function pg(){if(!lg){xg();lg=true}} function gi(){return Xj(new Uj,this)} function Ve(a,b){return a&&Se[a][b]} function jh(a,b){!!a.h&&Ud(a.h,b)} function Wm(a,b){(a<0||a>=b)&&Zm(a,b)} function Vf(a,b){return Rd(Zf(),a,b)} function dm(b,a){return Cq+a in b.e} function Gi(){return Zi(new Wi,this)} function aj(){return this.a<this.c.b} function fn(){return this.a<this.b.b} function Hh(){return qk(new nk,this.a)} function Ue(a,b){return a&&!!Se[a][b]} function Yo(a,b){Xo();a.a=b;return a} function ol(a,b,c,d,e){a.a=b;return a} function mp(a){wj(new uj,ts);return a} function be(a){a.a=Kn(new In);return a} function Dg(a){a.b=xn(new vn);return a} function sk(){return this.a<this.b.b-1} function $h(a){lh(this,a);lh(this.b,a)} function ki(a){ji();li(a,ii,1);return a} function Ek(a){a.a=Kn(new In);return a} function En(a){return Bn(this,a,0)!=-1} function vm(){return zm(new xm,this.a)} function Bm(){return We(en(this.a),25)} function Rm(a,b){return Om(new Mm,b,a)} function Qm(){return this.b.e[Cq+this.a]} function Om(a,b,c){a.b=c;a.a=b;return a} function On(a){a.a=Kn(new In);return a} function Ng(a,b,c){a.a=b;a.b=c;return a} function kn(a,b,c){a.a=b;a.b=c;return a} function ao(a,b,c){a.a=b;a.b=c;return a} function So(a,b,c){a.a=b;a.b=c;return a} function Bp(a,b,c){a.a=b;a.b=c;return a} function Sm(a){return hm(this.b,this.a,a)} function An(a,b){Wm(b,a.b);return a.a[b]} function gp(a,b){Fi(We(a.c,28).a,1,0,b)} function ab(a,b){Cb(a);a.a=b;Bb(a);return a} function Yg(){!Wg&&(Wg=new Zg);return Wg} function U(){return this.$H||(this.$H=++qb)} function $m(){return cn(new _m,We(this,6))} function Ze(a,b){return a!=null&&Ue(a.tI,b)} function T(a){return this===(a==null?null:a)} function al(){return this.$H||(this.$H=++qb)} function _k(a){return this===(a==null?null:a)} function yn(a,b){Je(a.a,a.b++,b);return true} function Xj(a,b){a.b=b;a.a=!!a.b.c;return a} function hk(a){a.a=Ge(jf,0,10,4,0);return a} function Co(a){a.a=new $wnd._IG_Prefs;return a} function Go(a){a.a=new $wnd._IG_Prefs;return a} function Dd(a){var b;if(Ad){b=new zd;Ud(a,b)}} function Zm(a,b){throw hl(new el,os+a+ps+b)} function Zf(){!Sf&&(Sf=jg(new hg));return Sf} function ji(){ji=Dp;ii=He(mf,0,1,[Ar,Ir,Jr])} function Ne(){Ne=Dp;Le=[];Me=[];Oe(new Be,Le,Me)} function Xg(){Xg=Dp;$moduleBase.indexOf(ur)==0} function Kj(){Kj=Dp;Ij=Kn(new In);Jj=On(new Mn)} function Tj(a){Sj();Lj(a,$doc.body);return a} function Sh(a,b){a.j=b;a.j.tabIndex=0;return a} function Vm(a){zn(this,this.E(),a);return true} function Yd(a,b,c,d){a.a=b;a.c=c;a.b=d;return a} function Zi(a,b){a.b=b;a.c=a.b.e.b;$i(a);return a} function fo(a){var b;b=this.b;this.b=a;return b} function Pl(a){var b;b=Nl(this.x(),a);return !!b} function Dn(a){return Je(this.a,this.b++,a),true} function $e(a){return a!=null&&(a.tM!=Dp&&a.tI!=2)} function rc(b,a){return b[a]==null?null:String(b[a])} function Pn(a,b){var c;c=em(a.a,b,a);return c==null} function Sk(a,b){var c;c=new Qk;c.a=a+b;return c} function Tk(a,b){var c;c=new Qk;c.a=a+b;return c} function Hb(a,b){var c;c=Qb(a,Fq);c.text=b;return c} function Sd(a,b){!a.a&&(a.a=xn(new vn));yn(a.a,b)} function zo(a){a.a=Co(new Ao);a.b=Go(new Eo);return a} function ep(a){!dp(a)&&Gk(a.b,(Xo(),Vo).a,null)} function xn(a){a.a=Ge(kf,0,0,0,0);a.b=0;return a} function Uf(a){$f();return Vf(Ad?Ad:(Ad=Xc(new Uc)),a)} function Yh(){if(this.b){return this.b.f}return false} function ff(a){if(a!=null){throw Wk(new Uk)}return a} function Hl(){if(Cl==256){Bl=Dl;Dl={};Cl=0}++Cl} function Zl(a){a.a=[];a.e={};a.c=false;a.b=null;a.d=0} function jg(a){a.d=be(new $d);a.e=null;a.c=false;return a} function Pd(a,b){a.d=be(new $d);a.e=b;a.c=false;return a} function W(a){if(a.b==null){return Ge(lf,0,15,0,0)}return a.b} function Lj(a,b){Kj();a.a=hk(new fk);a.j=b;kh(a);return a} function Pc(){Pc=Dp;Oc=$c(new Tc,Jq,(Pc(),new Dc))} function Xo(){Xo=Dp;Wo=Yo(new Uo,rs);Vo=Yo(new Uo,ss)} function Tl(a){var b;b=sm(new mm,a);return kn(new hn,a,b)} function Mh(a){var b;b=Gh(this,a);b&&Lh(a.j);return b} function Sn(a){var b;return b=em(this.a,a,this),b==null} function un(){var a;return a=We(en(this.a.a),25),a.G()} function nn(){var a;return a=zm(new xm,this.b.a),rn(new pn,a)} function Ah(){var a,b;for(b=this.x();b.z();){a=We(b.A(),10);a.t()}} function zh(){var a,b;for(b=this.x();b.z();){a=We(b.A(),10);a.s()}} function Fh(a,b,c){nh(b);ik(a.a,b);c.appendChild(b.j);oh(b,a)} function He(a,b,c,d){Ne();Qe(d,Le,Me);d.tI=b;d.qI=c;return d} function zn(a,b,c){(b<0||b>a.b)&&Zm(b,a.b);a.a.splice(b,0,c);++a.b} function Cn(a,b,c){var d;d=(Wm(b,a.b),a.a[b]);Je(a.a,b,c);return d} function mk(a,b){var c;c=jk(a,b);if(c==-1){throw io(new go)}lk(a,c)} function gm(a,b){var c;c=a.b;a.b=b;if(!a.c){a.c=true;++a.d}return c} function im(a,b){return !b?km(a):jm(a,b,~~(b.$H||(b.$H=++qb)))} function kb(a){return a.tM==Dp||a.tI==2?a.hC():a.$H||(a.$H=++qb)} function km(a){var b;b=a.b;a.b=null;if(a.c){a.c=false;--a.d}return b} function $i(a){while(++a.a<a.c.b){if(An(a.c,a.a)!=null){return}}} function rk(a){if(a.a>=a.b.b){throw io(new go)}return a.b.a[++a.a]} function en(a){if(a.a>=a.b.b){throw io(new go)}return An(a.b,a.a++)} function Yj(a){if(!a.a||!a.b.c){throw io(new go)}a.a=false;return a.b.c} function We(a,b){if(a!=null&&!Ve(a.tI,b)){throw Wk(new Uk)}return a} function tf(a){if(a!=null&&Ue(a.tI,19)){return a}return ab(new N,a)} function Xe(a){if(a!=null&&(a.tM==Dp||a.tI==2)){throw Wk(new Uk)}return a} function ph(a,b){a.g==-1?Of(a.j,b|(a.j.__eventBits||0)):(a.g|=b)} function Rd(a,b,c){a.b>0?Sd(a,Yd(new Wd,a,b,c)):ce(a.d,b,c);return new Jd} function Qe(a,b,c){Ne();for(var d=0,e=b.length;d<e;++d){a[b[d]]=c[d]}} function Oe(a,b,c){var d=0,e;for(var f in a){if(e=a[f]){b[d]=f;c[d]=e;++d}}} function Bn(a,b,c){for(;c<a.b;++c){if(no(b,a.a[c])){return c}}return -1} function ih(a,b,c){ph(a,ng(c.b));return Rd(!a.h?(a.h=Pd(new Md,a)):a.h,c,b)} function jj(){jj=Dp;ij=mj(new kj,as);mj(new kj,zr);mj(new kj,bs)} function Un(){var a;return a=zm(new xm,Tl(this.a).b.a),rn(new pn,a)} function ue(a){var b;return b=a.a.getString(a.n()),b==undefined?null:b} function Bj(a){var b;b=ng((Fb(),a).type);(b&896)!=0?lh(this,a):lh(this,a)} function Lh(a){a.style[zr]=yq;a.style[Ar]=yq;a.style[Br]=yq} function Ln(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function lm(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function no(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function Xh(a,b){if(a.b){throw dl(new bl,Hr)}nh(b);fh(a,b.j);a.b=b;oh(b,a)} function jk(a,b){var c;for(c=0;c<a.b;++c){if(a.a[c]==b){return c}}return -1} function ui(a,b){var c;c=a.a.rows.length;if(b>=c||b<0){throw hl(new el,Vr+b+Wr+c)}} function hm(e,a,b){var c,d=e.e;a=Cq+a;a in d?(c=d[a]):++e.d;d[a]=b;return c} function Si(a,b,c,d){var e;Ki(a.a,b,c);e=a.a.a.rows[b].cells[c];e[Zr]=d.a} function Ge(a,b,c,d,e){var f;f=Fe(e,d);Ne();Qe(f,Le,Me);f.tI=b;f.qI=c;return f} function Gj(a){var b;Ej(a,(b=(Fb(),$doc).createElement(ds),b.type=gs,b),hs);return a} function Dj(a){var b;Ej(a,(b=(Fb(),$doc).createElement(ds),b.type=es,b),fs);return a} function wj(a,b){a.j=Qb((Fb(),$doc),Gq);a.j[Fr]=cs;a.j.innerText=b||yq;return a} function Ej(a,b,c){a.j=b;a.j.tabIndex=0;c!=null&&(a.j[Fr]=c,undefined);return a} function $c(a,b,c){a.c=++Vc;a.a=c;!Ic&&(Ic=sd(new qd));Ic.a[b]=a;a.b=b;return a} function yg(a,b,c){c>=a.children.length?a.appendChild(b):a.insertBefore(b,a.children[c])} function Jb(a){var b=a.firstChild;while(b&&b.nodeType!=1)b=b.nextSibling;return b} function Xf(){var a;if(Rf){a=(dg(),new bg);!!Sf&&Ud(Sf,a);return null}return null} function sl(a,b){if(!(b!=null&&Ue(b.tI,1))){return false}return String(a)==b} function $l(a,b){return b==null?a.c:b!=null&&Ue(b.tI,1)?dm(a,We(b,1)):cm(a,b,~~kb(b))} function _l(a,b){return b==null?a.b:b!=null&&Ue(b.tI,1)?a.e[Cq+We(b,1)]:am(a,b,~~kb(b))} function ib(a,b){return a.tM==Dp||a.tI==2?a.eQ(b):(a==null?null:a)===(b==null?null:b)} function Nl(a,b){var c;while(a.z()){c=a.A();if(b==null?c==null:ib(b,c)){return a}}return null} function Fg(a,b){var c;if(!a.a){c=a.b.b;yn(a.b,b)}else{c=a.a.a;Cn(a.b,c,b);a.a=a.a.b}b.j[tr]=c} function ce(a,b,c){var d;d=We(_l(a.a,b),6);if(!d){d=xn(new vn);em(a.a,b,d)}Je(d.a,d.b++,c)} function Jf(a,b,c){var d;d=Gf;Gf=a;b==Hf&&(ng((Fb(),a).type)==8192&&(Hf=null));c.o(a);Gf=d} function di(a,b){if(a.c!=b){return false}oh(b,null);a.y().removeChild(b.j);a.c=null;return true} function em(a,b,c){return b==null?gm(a,c):b!=null&&Ue(b.tI,1)?hm(a,We(b,1),c):fm(a,b,c,~~kb(b))} function Eg(a,b){var c,d;c=(d=b[tr],d==null?-1:d);if(c<0){return null}return We(An(a.b,c),9)} function Gg(a,b){var c,d;c=(d=b[tr],d==null?-1:d);b[tr]=null;Cn(a.b,c,null);a.a=Ng(new Lg,c,a.a)} function mi(a){var b,c;c=Qb((Fb(),$doc),Tr);b=Qb($doc,Gq);c.appendChild(b);c[Fr]=a;b[Fr]=a+Ur;return c} function fj(a){if(!a.a){a.a=Qb((Fb(),$doc),$r);yg(a.b.d,a.a,0);a.a.appendChild(Qb($doc,_r))}} function dp(a){var b,c,d;c=false;if(a.a){b=ue(a.a.a);d=ue(a.a.b);c=!sl(yq,d)||!sl(yq,b)}return c} function _i(a){var b;if(a.a>=a.c.b){throw io(new go)}b=We(An(a.c,a.a),10);$i(a);return b} function mh(a){if(!a.r()){throw dl(new bl,wr)}try{a.v()}finally{a.q();a.j.__listener=null;a.f=false}} function Zh(){if(this.g!=-1){ph(this.b,this.g);this.g=-1}kh(this.b);this.j.__listener=this} function Gm(){var a,b;a=0;b=0;this.G()!=null&&(a=kb(this.G()));this.H()!=null&&(b=kb(this.H()));return a^b} function qm(){var a,b,c;a=0;for(b=this.x();b.z();){c=b.A();if(c!=null){a+=kb(c);a=~~a}}return a} function Gl(a){El();var b=Cq+a;var c=Dl[b];if(c!=null){return c}c=Bl[b];c==null&&(c=Fl(a));Hl();return Dl[b]=c} function Yl(e,a){var b=e.e;for(var c in b){if(c.charCodeAt(0)==58){var d=Rm(e,c.substring(1));a.C(d)}}} function Fe(a,b){var c=new Array(b);if(a>0){var d=[null,0,false,[0,0]][a];for(var e=0;e<b;++e){c[e]=d}}return c} function Mi(a,b,c){var d=a.rows[b];for(var e=0;e<c;e++){var f=$doc.createElement(Tr);d.appendChild(f)}} function Xl(g,a){var b=g.a;for(var c in b){if(c==parseInt(c)){var d=b[c];for(var e=0,f=d.length;e<f;++e){a.C(d[e])}}}} function ei(a,b){if(b==a.c){return}!!b&&nh(b);!!a.c&&di(a,a.c);a.c=b;if(b){a.a.appendChild(a.c.j);oh(b,a)}} function oh(a,b){var c;c=a.i;if(!b){!!c&&c.r()&&a.t();a.i=null}else{if(c){throw dl(new bl,yr)}a.i=b;b.r()&&a.s()}} function lk(a,b){var c;if(b<0||b>=a.b){throw gl(new el)}--a.b;for(c=b;c<a.b;++c){Je(a.a,c,a.a[c+1])}Je(a.a,a.b,null)} function kh(a){var b;if(a.r()){throw dl(new bl,vr)}a.f=true;a.j.__listener=a;b=a.g;a.g=-1;b>0&&ph(a,b);a.p();a.u()} function Vd(a){var b,c;if(a.a){try{for(c=cn(new _m,a.a);c.a<c.b.b;){b=We(en(c),5);ce(b.a.d,b.c,b.b)}}finally{a.a=null}}} function Tg(){$wnd.__gwt_initWindowCloseHandler(function(){return Xf()},function(){Rf&&Dd(Zf())})} function Nj(a){Kj();var b;b=We(_l(Ij,a),20);if(b){return b}Ij.d==0&&Uf(new Pj);b=Tj(new Rj);em(Ij,a,b);Pn(Jj,b);return b} function gwtOnLoad(b,c,d){$moduleName=c;$moduleBase=d;if(b)try{qf()}catch(a){b(c)}else{qf()}} function Ki(a,b,c){var d,e;Li(a,b);if(c<0){throw hl(new el,Xr+c)}d=(ui(a,b),a.a.rows[b].cells.length);e=c+1-d;e>0&&Mi(a.a,b,e)} function Ei(a,b,c,d){var e,f;Ki(a,b,c);e=(f=a.b.a.a.rows[b].cells[c],zi(a,f,d==null),f);d!=null&&(e.innerHTML=d||yq,undefined)} function Cp(a){var b,c;b=rc(a.a.j,Gs);c=rc(a.b.j,Gs);if(!sl(yq,b)&&!sl(yq,c)){null.K();null.K();null.K(null.K())}} function Fm(a){var b;if(a!=null&&Ue(a.tI,25)){b=We(a,25);if(no(this.G(),b.G())&&no(this.H(),b.H())){return true}}return false} function tm(a,b){var c,d,e;if(b!=null&&Ue(b.tI,25)){c=We(b,25);d=c.G();if($l(a.a,d)){e=_l(a.a,d);return Ln(c.H(),e)}}return false} function zm(a,b){var c;a.b=b;c=xn(new vn);a.b.c&&yn(c,Im(new Cm,a.b));Yl(a.b,c);Xl(a.b,c);a.a=cn(new _m,c);return a} function Vl(){var a,b,c;c=0;for(b=zm(new xm,sm(new mm,We(this,26)).a);dn(b.a);){a=We(en(b.a),25);c+=a.hC();c=~~c}return c} function Ym(){var a,b,c;b=1;a=cn(new _m,We(this,6));while(a.a<a.b.b){c=en(a);b=31*b+(c==null?0:kb(c));b=~~b}return b} function Cb(a){var b,c,d,e;d=Ab(new yb);e=Ge(lf,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=ol(new ml,Dq,d[b],Eq,0)}X(a,e)} function X(a,b){var c,d,e;d=Ge(lf,0,15,b.length,0);for(e=0,c=b.length;e<c;++e){if(!b[e]){throw ll(new jl)}d[e]=b[e]}a.b=d} function am(h,a,b){var c=h.a[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){return f.H()}}}return null} function cm(h,a,b){var c=h.a[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){return true}}}return false} function Mc(a,b,c){var d,e,f;if(Ic){f=We(Ic.a[(Fb(),a).type],3);if(f){d=f.a.a;e=f.a.b;f.a.a=a;f.a.b=c;jh(b,f.a);f.a.a=d;f.a.b=e}}} function Fi(a,b,c,d){var e,f;Ki(a,b,c);if(d){nh(d);e=(f=a.b.a.a.rows[b].cells[c],zi(a,f,true),f);Fg(a.e,d);e.appendChild(d.j);oh(d,a)}} function Uh(a,b,c){Sh(a,(Fb(),$doc).createElement(Cr+Dr+Er));a.j[Fr]=Gr;a.j.innerHTML=b||yq;ih(a,c,(Pc(),Oc));return a} function zi(a,b,c){var d,e;d=Jb((Fb(),b));e=null;!!d&&(e=We(Eg(a.e,d),10));if(e){Ai(a,e);return true}else{c&&(b.innerHTML=yq,undefined);return false}} function $f(){var a;if(!Rf){a=Hb((Fb(),$doc),(Yg(Ug()),Oq));$doc.body.appendChild(a);Tg();$doc.body.removeChild(a);Rf=true}} function Ji(a){a.e=Dg(new Ag);a.d=Qb((Fb(),$doc),Kr);a.a=Qb($doc,Lr);a.d.appendChild(a.a);a.j=a.d;a.b=Ui(new Ni,a);Di(a,ej(new cj,a));return a} function qp(a){var b;a.a=Ji(new pi);a.a.d[Mr]=6;a.a.j.style[us]=vs;b=a.a.b;Ei(a.a,0,0,ws);Si(b,0,0,(jj(),ij));Fi(a.a,1,0,wj(new uj,xs));Xh(a,a.a);return a} function xb(a){var b,c,d;d=yq;a=wl(a);b=a.indexOf(zq);if(b!=-1){c=a.indexOf(Aq)==0?8:0;d=wl(a.substr(c,b-c))}return d.length>0?d:Bq} function Bb(a){var b,c,d,e;d=($e(a.a)?Xe(a.a):null,[]);e=Ge(lf,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=ol(new ml,Dq,d[b],Eq,0)}X(a,e)} function nh(a){if(!a.i){Kj();if($l(Jj.a,a)){a.t();im(Jj.a,a)!=null}}else if(Ze(a.i,21)){We(a.i,21).w(a)}else if(a.i){throw dl(new bl,xr)}} function Ud(a,b){var c;if(b.c){b.c=false;b.d=null}c=b.d;b.d=a.e;try{++a.b;de(a.d,b,a.c)}finally{--a.b;a.b==0&&Vd(a)}if(c==null){b.c=true;b.d=null}else{b.d=c}} function Ub(a,b){if(a.nodeType!=1&&a.nodeType!=9){return a==b}if(b.nodeType!=1){b=b.parentNode;if(!b){return false}}return a===b||a.contains(b)} function wl(c){if(c.length==0||c[0]>ms&&c[c.length-1]>ms){return c}var a=c.replace(/^(\s*)/,yq);var b=a.replace(/\s*$/,yq);return b} function jm(h,a,b){var c=h.a[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){c.length==1?delete h.a[b]:c.splice(d,1);--h.d;return f.H()}}}return null} function fm(j,a,b,c){var d=j.a[c];if(d){for(var e=0,f=d.length;e<f;++e){var g=d[e];var h=g.G();if(j.F(a,h)){var i=g.H();g.I(b);return i}}}else{d=j.a[c]=[]}var g=ao(new $n,a,b);d.push(g);++j.d;return null} function Fl(a){var b,c,d,e;b=0;d=a.length;e=d-4;c=0;while(c<e){b=a.charCodeAt(c+3)+31*(a.charCodeAt(c+2)+31*(a.charCodeAt(c+1)+31*(a.charCodeAt(c)+31*b)))|0;c+=4}while(c<d){b=b*31+a.charCodeAt(c++)}return b|0} function kk(a,b,c){var d,e;if(c<0||c>a.b){throw gl(new el)}if(a.b==a.a.length){e=Ge(jf,0,10,a.a.length*2,0);for(d=0;d<a.a.length;++d){Je(e,d,a.a[d])}a.a=e}++a.b;for(d=a.b-1;d>c;--d){Je(a.a,d,a.a[d-1])}Je(a.a,c,b)} function Je(a,b,c){if(c!=null){if(a.qI>0&&!Ve(c.tI,a.qI)){throw Ok(new Mk)}if(a.qI<0&&(c.tM==Dp||c.tI==2)){throw Ok(new Mk)}}return a[b]=c} function Ab(i){var a={};var b=[];var c=arguments.callee.caller.caller;while(c){var d=i.k(c.toString());b.push(d);var e=Cq+d;var f=a[e];if(f){var g,h;for(g=0,h=f.length;g<h;g++){if(f[g]===c){return b}}}(f||(a[e]=[])).push(c);c=c.caller}return b} function pm(a){var b,c,d;if((a==null?null:a)===this){return true}if(!(a!=null&&Ue(a.tI,27))){return false}c=We(a,27);if(c.E()!=this.E()){return false}for(b=c.x();b.z();){d=b.A();if(!this.D(d)){return false}}return true} function Qb(a,b){var c,d;if(b.indexOf(Cq)!=-1){c=(!a.__gwt_container&&(a.__gwt_container=a.createElement(Gq)),a.__gwt_container);c.innerHTML=Hq+b+Iq||yq;d=Jb((Fb(),c));c.removeChild(d);return d}return a.createElement(b)} function Gk(b,c,d){var a,f;try{We(_l(b.a,c),22).B(d)}catch(a){a=tf(a);if(Ze(a,23)){f=a;if(sl(W(f)[0].a,hf.a)){throw zk(new xk,is+c+js)}throw f}else if(Ze(a,24)){f=a;if(sl(W(f)[1].a,hf.a)){throw zk(new xk,ks+c+ls)}throw f}else throw a}} function de(a,b,c){var d,e,f,g,h,i,j;g=b.m();d=(h=We(_l(a.a,g),6),!h?0:h.b);if(c){for(f=d-1;f>=0;--f){e=(i=We(_l(a.a,g),6),We((Wm(f,i.b),i.a[f]),18));b.l(e)}}else{for(f=0;f<d;++f){e=(j=We(_l(a.a,g),6),We((Wm(f,j.b),j.a[f]),18));b.l(e)}}} function Xm(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&Ue(a.tI,6))){return false}f=We(a,6);if(this.E()!=f.b){return false}d=cn(new _m,We(this,6));e=cn(new _m,f);while(d.a<d.b.b){b=en(d);c=en(e);if(!(b==null?c==null:ib(b,c))){return false}}return true} function Li(a,b){var c,d,e;if(b<0){throw hl(new el,Yr+b)}d=a.a.rows.length;for(c=d;c<=b;++c){c!=a.a.rows.length&&ui(a,c);e=Qb((Fb(),$doc),Or);yg(a.a,e,c)}} function li(a,b,c){var d,e,f,g;ji();a.j=Qb((Fb(),$doc),Kr);f=a.j;a.b=Qb($doc,Lr);f.appendChild(a.b);f[Mr]=0;f[Nr]=0;for(d=0;d<b.length;++d){e=(g=Qb($doc,Or),(g[Fr]=b[d],undefined),g.appendChild(mi(b[d]+Pr)),g.appendChild(mi(b[d]+Qr)),g.appendChild(mi(b[d]+Rr)),g);a.b.appendChild(e);d==c&&(a.a=Jb(e.children[1]))}a.j[Fr]=Sr;return a} function Gh(a,b){var c,d;if(b.i!=a){return false}oh(b,null);c=b.j;(d=(Fb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);mk(a.a,b);return true} function Ai(a,b){var c,d;if(b.i!=a){return false}oh(b,null);c=b.j;(d=(Fb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);Gg(a.e,c);return true} function qf(){var a,i,j,k,l,m,n,o;!!$stats&&$stats({moduleName:$moduleName,subSystem:Kq,evtGroup:Lq,millis:(new Date).getTime(),type:Mq,className:Nq});(new so).J(new me);a=Ko(new Io,zo(new wo));k=Ek(new Bk);l=qp(new np);m=new ap;m.b=k;m.c=l;m.a=a.a;em(k.a,(Xo(),Wo).a,Oo(new Mo,m));n=xp(new vp);o=new hp;o.b=k;o.c=n;j=mp(new kp);i=new Zo;i.b=k;i.c=j;em(k.a,Vo.a,So(new Qo,m,n));Kh((Kj(),Nj(null)),l);Gk(k,Wo.a,null)} function Mj(){var c,d;Kj();var a,b;for(b=(c=zm(new xm,Tl(Jj.a).b.a),rn(new pn,c));dn(b.a.a);){a=We((d=We(en(b.a.a),25),d.G()),10);a.r()&&a.t()}Zl(Jj.a);Zl(Ij)} function ng(a){switch(a){case Pq:return 4096;case Qq:return 1024;case Jq:return 1;case Rq:return 2;case Sq:return 2048;case Tq:return 128;case Uq:return 256;case Vq:return 512;case Wq:return 32768;case Xq:return 8192;case Yq:return 4;case Zq:return 64;case $q:return 32;case _q:return 16;case ar:return 8;case br:return 16384;case cr:return 65536;case dr:return 131072;case er:return 131072;case fr:return 262144;case gr:return 524288;}} function lh(a,b){var c;switch(ng((Fb(),b).type)){case 16:case 32:c=b.relatedTarget||(b.type==$q?b.toElement:b.fromElement);if(!!c&&Ub(a.j,c)){return}}Mc(b,a,a.j)} function xp(a){var b,c,d,e,f,g;a.a=(e=Ji(new pi),(e.d[Mr]=6,undefined),(e.j.style[us]=ys,undefined),c=e.b,Ei(e,0,0,zs),((Ki(c.a,0,0),c.a.a.rows[0].cells[0])[As]=2,undefined),Si(c,0,0,(jj(),ij)),Ei(e,1,0,Bs),g=Dj(new yj),(g.j.style[us]=Cs,undefined),Fi(e,1,1,g),Ei(e,2,0,Ds),f=Gj(new xj),(f.j.style[us]=Cs,undefined),Fi(e,2,1,f),b=Uh(new Nh,Es,Bp(new zp,f,g)),Fi(e,3,1,b),d=ki(new ai),ei(d,e),(d.j.style[us]=Fs,undefined),d);Xh(a,a.a);return a} function Ul(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&Ue(a.tI,26))){return false}e=We(a,26);if(We(this,26).d!=e.d){return false}for(c=zm(new xm,sm(new mm,e).a);dn(c.a);){b=We(en(c.a),25);d=b.G();f=b.H();if(!(d==null?We(this,26).c:d!=null&&Ue(d.tI,1)?dm(We(this,26),We(d,1)):cm(We(this,26),d,~~kb(d)))){return false}if(!no(f,d==null?We(this,26).b:d!=null&&Ue(d.tI,1)?We(this,26).e[Cq+We(d,1)]:am(We(this,26),d,~~kb(d)))){return false}}return true} function zg(a,b){var c=(a.__eventBits||0)^b;a.__eventBits=b;if(!c)return;c&1&&(a.onclick=b&1?ug:null);c&3&&(a.ondblclick=b&3?tg:null);c&4&&(a.onmousedown=b&4?ug:null);c&8&&(a.onmouseup=b&8?ug:null);c&16&&(a.onmouseover=b&16?ug:null);c&32&&(a.onmouseout=b&32?ug:null);c&64&&(a.onmousemove=b&64?ug:null);c&128&&(a.onkeydown=b&128?ug:null);c&256&&(a.onkeypress=b&256?ug:null);c&512&&(a.onkeyup=b&512?ug:null);c&1024&&(a.onchange=b&1024?ug:null);c&2048&&(a.onfocus=b&2048?ug:null);c&4096&&(a.onblur=b&4096?ug:null);c&8192&&(a.onlosecapture=b&8192?ug:null);c&16384&&(a.onscroll=b&16384?ug:null);c&32768&&(a.onload=b&32768?ug:null);c&65536&&(a.onerror=b&65536?ug:null);c&131072&&(a.onmousewheel=b&131072?ug:null);c&262144&&(a.oncontextmenu=b&262144?ug:null);c&524288&&(a.onpaste=b&524288?ug:null)} function xg(){ug=function(){var a=(Ob(),Nb);Nb=this;if($wnd.event.returnValue==null){$wnd.event.returnValue=true;if(!Mf($wnd.event)){Nb=a;return}}var b,c=this;while(c&&!(b=c.__listener)){c=c.parentElement}b&&(!(b!=null&&(b.tM!=Dp&&b.tI!=2))&&(b!=null&&Ue(b.tI,8))&&Jf($wnd.event,c,b));Nb=a};tg=function(){var a=$doc.createEventObject();$wnd.event.returnValue==null&&$wnd.event.srcElement.fireEvent(hr,a);if(this.__eventBits&2){ug.call(this)}else if($wnd.event.returnValue==null){$wnd.event.returnValue=true;Mf($wnd.event)}};var d=function(){ug.call($doc.body)};var e=function(){tg.call($doc.body)};$doc.body.attachEvent(hr,d);$doc.body.attachEvent(ir,d);$doc.body.attachEvent(jr,d);$doc.body.attachEvent(kr,d);$doc.body.attachEvent(lr,d);$doc.body.attachEvent(mr,d);$doc.body.attachEvent(nr,d);$doc.body.attachEvent(or,d);$doc.body.attachEvent(pr,d);$doc.body.attachEvent(qr,d);$doc.body.attachEvent(rr,e);$doc.body.attachEvent(sr,d)} var yq='',ms=' ',js=" doesn't exist. Have you forgotten to add it to your Mvp4g configuration file?",ls=' is incorrect. It should be the same as the one configured in the Mvp4g configuration file.',Er="'><\/BUTTON>",zq='(',Wr=', Row size: ',ps=', Size: ',Iq='/>',Cs='100px',ys='200px',vs='250px',ws='4kGadget initialization...',Fs='80%',Cq=':',Hq='<',Cr="<BUTTON type='",ns='Add not supported on this collection',Xr='Cannot create a column with a negative index: ',Yr='Cannot create a row with a negative index: ',yr='Cannot set a new parent without first clearing the old parent',Qr='Center',ks='Class of the object sent with event ',Hr='Composite.initWidget() may only be called once.',er='DOMMouseScroll',ss='ENTER_CREDENTIALS',zs='Enter credentials',is='Event ',Ns='EventBus',ds='INPUT',os='Index: ',Ur='Inner',Pr='Left',Os='Object;',Ds='Password',Rr='Right',Vr='Row index: ',rs='START',vr="Should only call onAttach when the widget is detached from the browser's document",wr="Should only call onDetach when the widget is attached to the browser's document",Is='StackTraceElement;',Js='String;',Es='Submit',xr="This widget's parent does not implement HasWidgets",Dq='Unknown',Eq='Unknown source',Bs='Username',Ls='Widget;',Ks='[Lcom.google.gwt.user.client.ui.',Hs='[Ljava.lang.',tr='__uiObjectID',Zr='align',Bq='anonymous',Pq='blur',Jr='bottom',Dr='button',Nr='cellPadding',Mr='cellSpacing',as='center',Qq='change',Fr='className',Jq='click',_r='col',As='colSpan',$r='colgroup',Ms='com.mvp4g.client.event.',fr='contextmenu',Rq='dblclick',Gq='div',cr='error',Sq='focus',Aq='function',Oq='function __gwt_initWindowCloseHandler(beforeunload, unload) {\r\n var wnd = window\r\n , oldOnBeforeUnload = wnd.onbeforeunload\r\n , oldOnUnload = wnd.onunload;\r\n \r\n wnd.onbeforeunload = function(evt) {\r\n var ret, oldRet;\r\n try {\r\n ret = beforeunload();\r\n } finally {\r\n oldRet = oldOnBeforeUnload && oldOnBeforeUnload(evt);\r\n }\r\n // Avoid returning null as IE6 will coerce it into a string.\r\n // Ensure that "" gets returned properly.\r\n if (ret != null) {\r\n return ret;\r\n }\r\n if (oldRet != null) {\r\n return oldRet;\r\n }\r\n // returns undefined.\r\n };\r\n \r\n wnd.onunload = function(evt) {\r\n try {\r\n unload();\r\n } finally {\r\n oldOnUnload && oldOnUnload(evt);\r\n wnd.onresize = null;\r\n wnd.onscroll = null;\r\n wnd.onbeforeunload = null;\r\n wnd.onunload = null;\r\n }\r\n };\r\n \r\n // Remove the reference once we\'ve initialize the handler\r\n wnd.__gwt_initWindowCloseHandler = undefined;\r\n}\r\n',Gr='gwt-Button',Sr='gwt-DecoratorPanel',cs='gwt-Label',hs='gwt-PasswordTextBox',fs='gwt-TextBox',ur='https',Tq='keydown',Uq='keypress',Vq='keyup',ts='label',zr='left',Wq='load',Xq='losecapture',Ir='middle',Lq='moduleStartup',Yq='mousedown',Zq='mousemove',$q='mouseout',_q='mouseover',ar='mouseup',dr='mousewheel',Nq='name.webdizz.gadget.four.envelope.client.Envelope',Mq='onModuleLoadStart',qr='onblur',hr='onclick',sr='oncontextmenu',rr='ondblclick',pr='onfocus',mr='onkeydown',nr='onkeypress',or='onkeyup',ir='onmousedown',kr='onmousemove',jr='onmouseup',lr='onmousewheel',gs='password',gr='paste',Br='position',bs='right',Fq='script',br='scroll',Kq='startup',xs='stub content',Kr='table',Lr='tbody',Tr='td',es='text',Ar='top',Or='tr',qs='username',Gs='value',us='width';var _;_=R.prototype={};_.eQ=T;_.hC=U;_.tM=Dp;_.tI=1;_=Q.prototype=new R;_.tI=3;_.b=null;_=P.prototype=new Q;_.tI=4;_=O.prototype=new P;_.tI=5;_=N.prototype=new O;_.tI=6;_.a=null;var qb=0;_=yb.prototype=new R;_.k=Db;_.tI=0;_=Eb.prototype=new R;_.tI=0;_=Mb.prototype=new Eb;_.tI=0;var Nb=null;_=Lb.prototype=new Mb;_.tI=0;_=Fc.prototype=new R;_.tI=0;_.c=false;_.d=null;_=Ec.prototype=new Fc;_.m=Nc;_.tI=0;_.a=null;_.b=null;var Ic=null;_=Dc.prototype=new Ec;_.l=Rc;_.tI=0;var Oc;_=Uc.prototype=new R;_.hC=Yc;_.tI=0;_.c=0;var Vc=0;_=Tc.prototype=new Uc;_.tI=7;_.a=null;_.b=null;_=qd.prototype=new R;_.tI=0;_.a=null;_=zd.prototype=new Fc;_.l=Cd;_.m=Ed;_.tI=0;var Ad=null;_=Jd.prototype=new R;_.tI=0;_=Md.prototype=new R;_.tI=0;_.a=null;_.b=0;_.c=false;_.d=null;_.e=null;_=Wd.prototype=new R;_.tI=8;_.a=null;_.b=null;_.c=null;_=$d.prototype=new R;_.tI=0;_=ie.prototype=new R;_.tI=0;_=me.prototype=new R;_.tI=0;_=qe.prototype=new R;_.tI=0;_=pe.prototype=new qe;_.tI=0;_=Be.prototype=new R;_.tI=0;_.length=0;_.qI=0;var Le,Me;var Se=[{},{},{1:1,11:1,12:1,13:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{3:1},{5:1},{7:1},{9:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,20:1,21:1},{4:1,18:1},{7:1,8:1,9:1,10:1,20:1,21:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,24:1},{11:1,13:1,14:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,23:1},{11:1,15:1},{12:1},{11:1,19:1},{27:1},{27:1},{25:1},{25:1},{25:1},{27:1},{6:1,11:1},{11:1,26:1},{11:1,27:1},{25:1},{11:1,19:1},{22:1},{22:1},{11:1,13:1,14:1,16:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,28:1},{7:1,8:1,9:1,10:1},{2:1,18:1},{17:1}];var Gf=null,Hf=null;var Rf=false,Sf=null;_=bg.prototype=new Fc;_.l=fg;_.m=gg;_.tI=0;var cg;_=hg.prototype=new Md;_.tI=9;var lg=false;var tg=null,ug=null;_=Ag.prototype=new R;_.tI=0;_.a=null;_=Lg.prototype=new R;_.tI=0;_.a=0;_.b=null;var Wg=null;_=Zg.prototype=new R;_.tI=0;_=dh.prototype=new R;_.tI=10;_.j=null;_=ch.prototype=new dh;_.p=qh;_.q=rh;_.r=sh;_.s=th;_.o=uh;_.t=vh;_.u=wh;_.v=xh;_.tI=11;_.f=false;_.g=0;_.h=null;_.i=null;_=bh.prototype=new ch;_.p=zh;_.q=Ah;_.u=Bh;_.v=Ch;_.tI=12;_=ah.prototype=new bh;_.x=Hh;_.w=Ih;_.tI=13;_=_g.prototype=new ah;_.w=Mh;_.tI=14;_=Ph.prototype=new ch;_.tI=15;_=Oh.prototype=new Ph;_.tI=16;_=Nh.prototype=new Oh;_.tI=17;_=Vh.prototype=new ch;_.r=Yh;_.s=Zh;_.o=$h;_.t=_h;_.tI=18;_.b=null;_=bi.prototype=new bh;_.y=fi;_.x=gi;_.w=hi;_.tI=19;_.c=null;_=ai.prototype=new bi;_.y=oi;_.tI=20;_.a=null;_.b=null;var ii;_=qi.prototype=new bh;_.x=Gi;_.w=Hi;_.tI=21;_.a=null;_.b=null;_.c=null;_.d=null;_=pi.prototype=new qi;_.tI=22;_=Oi.prototype=new R;_.tI=0;_.a=null;_=Ni.prototype=new Oi;_.tI=0;_=Wi.prototype=new R;_.z=aj;_.A=bj;_.tI=0;_.a=-1;_.b=null;_=cj.prototype=new R;_.tI=0;_.a=null;_.b=null;var ij;_=kj.prototype=new R;_.tI=0;_.a=null;_=uj.prototype=new ch;_.tI=23;_=zj.prototype=new Ph;_.o=Bj;_.tI=24;_=yj.prototype=new zj;_.tI=25;_=xj.prototype=new yj;_.tI=26;_=Hj.prototype=new _g;_.tI=27;var Ij,Jj;_=Pj.prototype=new R;_.tI=28;_=Rj.prototype=new Hj;_.tI=29;_=Uj.prototype=new R;_.z=Zj;_.A=$j;_.tI=0;_.b=null;_=fk.prototype=new R;_.tI=0;_.a=null;_.b=0;_=nk.prototype=new R;_.z=sk;_.A=tk;_.tI=0;_.a=-1;_.b=null;_=xk.prototype=new O;_.tI=30;_=Bk.prototype=new R;_.tI=0;_=Hk.prototype=new R;_.tI=0;_.b=null;_.c=null;_=Mk.prototype=new O;_.tI=32;_=Qk.prototype=new R;_.tI=0;_.a=null;_=Uk.prototype=new O;_.tI=35;_=Zk.prototype=new R;_.eQ=_k;_.hC=al;_.tI=36;_.a=null;_=bl.prototype=new O;_.tI=37;_=el.prototype=new O;_.tI=38;_=jl.prototype=new O;_.tI=39;_=ml.prototype=new R;_.tI=40;_.a=null;_=String.prototype;_.eQ=yl;_.hC=zl;_.tI=2;var Bl,Cl=0,Dl;_=Il.prototype=new O;_.tI=42;_=Ll.prototype=new R;_.C=Ol;_.D=Pl;_.tI=0;_=Rl.prototype=new R;_.eQ=Ul;_.hC=Vl;_.tI=0;_=Ql.prototype=new Rl;_.F=lm;_.tI=0;_.a=null;_.b=null;_.c=false;_.d=0;_.e=null;_=nm.prototype=new Ll;_.eQ=pm;_.hC=qm;_.tI=43;_=mm.prototype=new nm;_.D=um;_.x=vm;_.E=wm;_.tI=44;_.a=null;_=xm.prototype=new R;_.z=Am;_.A=Bm;_.tI=0;_.a=null;_.b=null;_=Dm.prototype=new R;_.eQ=Fm;_.hC=Gm;_.tI=45;_=Cm.prototype=new Dm;_.G=Jm;_.H=Km;_.I=Lm;_.tI=46;_.a=null;_=Mm.prototype=new Dm;_.G=Pm;_.H=Qm;_.I=Sm;_.tI=47;_.a=null;_.b=null;_=Tm.prototype=new Ll;_.C=Vm;_.eQ=Xm;_.hC=Ym;_.x=$m;_.tI=0;_=_m.prototype=new R;_.z=fn;_.A=gn;_.tI=0;_.a=0;_.b=null;_=hn.prototype=new nm;_.D=mn;_.x=nn;_.E=on;_.tI=48;_.a=null;_.b=null;_=pn.prototype=new R;_.z=tn;_.A=un;_.tI=0;_.a=null;_=vn.prototype=new Tm;_.C=Dn;_.D=En;_.E=Fn;_.tI=49;_.a=null;_.b=0;_=In.prototype=new Ql;_.tI=50;_=Mn.prototype=new nm;_.C=Sn;_.D=Tn;_.x=Un;_.E=Vn;_.tI=51;_.a=null;_=$n.prototype=new Dm;_.G=bo;_.H=co;_.I=fo;_.tI=52;_.a=null;_.b=null;_=go.prototype=new O;_.tI=53;_=oo.prototype=new ie;_.J=ro;_.tI=0;_=so.prototype=new oo;_.tI=0;_=wo.prototype=new R;_.tI=0;_=Ao.prototype=new pe;_.n=Do;_.tI=0;_=Eo.prototype=new pe;_.n=Ho;_.tI=0;_=Io.prototype=new R;_.tI=0;_.a=null;_=Mo.prototype=new R;_.B=Po;_.tI=54;_.a=null;_=Qo.prototype=new R;_.B=To;_.tI=55;_.a=null;_.b=null;_=Uo.prototype=new Zk;_.tI=56;var Vo,Wo;_=Zo.prototype=new Hk;_.tI=0;_=ap.prototype=new Hk;_.tI=0;_.a=null;_=hp.prototype=new Hk;_.tI=0;_=kp.prototype=new Vh;_.tI=57;_=np.prototype=new Vh;_.tI=58;_=vp.prototype=new Vh;_.tI=59;_.a=null;_=zp.prototype=new R;_.tI=60;_.a=null;_.b=null;var lf=Sk(Hs,Is),mf=Sk(Hs,Js),jf=Sk(Ks,Ls),hf=Tk(Ms,Ns),kf=Sk(Hs,Os);$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalEnd'});if (envelope) envelope.onScriptLoad(gwtOnLoad);})();
JavaScript
(function(){var $gwt_version = "2.0.0";var $wnd = window;var $doc = $wnd.document;var $moduleName, $moduleBase;var $strongName = 'CD878D114BE6B9B5B00D329A4F1401C5';var $stats = $wnd.__gwtStatsEvent ? function(a) {return $wnd.__gwtStatsEvent(a);} : null;$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalStart'});function R(){} function Q(){} function P(){} function O(){} function N(){} function sp(){} function Ib(){} function Rb(){} function Qb(){} function Ac(){} function zc(){} function yc(){} function Pc(){} function Oc(){} function ld(){} function ud(){} function Ed(){} function Hd(){} function Rd(){} function Vd(){} function de(){} function he(){} function le(){} function ke(){} function we(){} function Vf(){} function _f(){} function zg(){} function Kg(){} function Ug(){} function fh(){} function gh(){} function lh(){} function mh(){} function Tg(){} function qh(){} function rh(){} function Sg(){} function Rg(){} function Qg(){} function Eh(){} function Dh(){} function Ch(){} function Kh(){} function Sh(){} function Rh(){} function fi(){} function ei(){} function Di(){} function Ci(){} function Li(){} function Ti(){} function _i(){} function jj(){} function oj(){} function nj(){} function mj(){} function wj(){} function Ej(){} function Gj(){} function Jj(){} function Wj(){} function ck(){} function mk(){} function qk(){} function wk(){} function Bk(){} function Fk(){} function Jk(){} function Ok(){} function Sk(){} function Vk(){} function $k(){} function bl(){} function xl(){} function Al(){} function Gl(){} function Fl(){} function cm(){} function bm(){} function mm(){} function sm(){} function rm(){} function Bm(){} function Im(){} function Qm(){} function Ym(){} function dn(){} function kn(){} function xn(){} function Bn(){} function Pn(){} function Wn(){} function co(){} function ho(){} function lo(){} function po(){} function to(){} function xo(){} function Bo(){} function Fo(){} function Jo(){} function Oo(){} function Ro(){} function Yo(){} function _o(){} function cp(){} function kp(){} function op(){} function go(a){} function ih(){_g(this)} function Wg(a,b){a.k=b} function kh(){bh(this)} function zd(){return vd} function $f(){return Wf} function so(){return Hr} function wo(){return Sr} function Sb(){Sb=sp;Jb()} function Tb(){Tb=sp;Sb()} function Qh(){bh(this.c)} function Hj(){Hj=sp;zj()} function jh(a){ah(this,a)} function ym(){return null} function Eo(a){Vo(this.b)} function Mc(a){rp(Re(a,2))} function Tc(){return this.d} function xd(a){Re(a,4);Bj()} function hh(){return this.g} function Wh(){return this.k} function di(){return this.b} function Oj(){return this.b} function Em(){return this.b} function un(){return this.c} function Sn(){return this.b} function Tn(){return this.c} function Ic(){return Kc(),Jc} function Si(){return Qi(this)} function Pj(){return Nj(this)} function ik(){return gk(this)} function ol(){return vl(this)} function lm(){return this.b.e} function zm(){return this.b.c} function zh(a,b){uh(a,b,a.k)} function Zj(a,b){_j(a,b,a.c)} function Zf(a){af(a);null.K()} function Dk(a){Cb(a);return a} function Lk(a){Cb(a);return a} function Xk(a){Cb(a);return a} function al(a){Cb(a);return a} function Kn(){return this.b.e} function Xm(){return Vm(this)} function zn(a){Ol(a);return a} function Yn(a){Cb(a);return a} function nd(a){a.b={};return a} function si(a,b){a.d=b;Wi(a.d)} function Ji(a,b){a.b=b;return a} function Jb(){Jb=sp;Tb();new Qb} function tl(){tl=sp;ql={};sl={}} function Vi(a,b){a.c=b;return a} function bj(a,b){a.b=b;return a} function fk(a,b){a.c=b;return a} function ok(a,b){Cb(a);return a} function Uk(a,b){Cb(a);return a} function Yk(a,b){Cb(a);return a} function zl(a,b){Cb(a);return a} function hm(a,b){a.b=b;return a} function xm(a,b){a.b=b;return a} function Tm(a,b){a.c=b;return a} function Um(a){return a.b<a.c.c} function pm(){return Um(this.b)} function cn(){return this.c.b.e} function xh(a){return vh(this,a)} function zo(a,b){a.b=b;return a} function fn(a,b){a.b=b;return a} function Do(a,b){a.b=b;return a} function Sc(a){a.d=++Qc;return a} function Yh(a){return Uh(this,a)} function wi(a){return pi(this,a)} function nl(a){return hl(this,a)} function jm(a){return im(this,a)} function Io(a){Xo(this.b,this.c)} function Xf(){Xf=sp;Wf=Sc(new Pc)} function Sf(){if(!Jf){Pg();Jf=true}} function hn(){return Um(this.b.b)} function Xh(){return Mj(new Jj,this)} function Am(a){return Xl(this.b,a)} function Wm(){return this.b<this.c.c} function an(a){return Pl(this.b,a)} function $g(a,b){!!a.i&&Pd(a.i,b)} function No(a,b){Mo();a.b=b;return a} function Nf(a,b){return Md(Rf(),a,b)} function Dl(a){throw zl(new xl,Pr)} function In(a){return Pl(this.b,a)} function Qe(a,b){return a&&Ne[a][b]} function Ul(b,a){return Or+a in b.f} function vi(){return Oi(new Li,this)} function Ri(){return this.b<this.d.c} function Pe(a,b){return a&&!!Ne[a][b]} function wh(){return fk(new ck,this.b)} function hk(){return this.b<this.c.c-1} function km(){return om(new mm,this.b)} function bp(a){lj(new jj,Vr);return a} function dl(a,b,c,d,e){a.b=b;return a} function qm(){return Re(Vm(this.b),25)} function Ph(a){ah(this,a);ah(this.c,a)} function _h(a){$h();ai(a,Zh,1);return a} function Yd(a){a.b=zn(new xn);return a} function Cg(a){a.c=mn(new kn);return a} function tk(a){a.b=zn(new xn);return a} function Gm(a,b){return Dm(new Bm,b,a)} function Lm(a,b){(a<0||a>=b)&&Om(a,b)} function $m(a,b,c){a.b=b;a.c=c;return a} function Mg(a,b,c){a.b=b;a.c=c;return a} function Dm(a,b,c){a.c=c;a.b=b;return a} function Rn(a,b,c){a.b=b;a.c=c;return a} function Ho(a,b,c){a.b=b;a.c=c;return a} function qp(a,b,c){a.b=b;a.c=c;return a} function Hm(a){return Yl(this.c,this.b,a)} function tn(a){return qn(this,a,0)!=-1} function Fm(){return this.c.f[Or+this.b]} function U(){return this.$H||(this.$H=++rb)} function Pm(){return Tm(new Qm,Re(this,6))} function pn(a,b){Lm(b,a.c);return a.b[b]} function Dn(a){a.b=zn(new xn);return a} function Ue(a,b){return a!=null&&Pe(a.tI,b)} function Xo(a,b){ui(Re(a.d,28).b,1,0,b)} function ab(a,b){Cb(a);a.b=b;Bb(a);return a} function Mj(a,b){a.c=b;a.b=!!a.c.d;return a} function nn(a,b){Ee(a.b,a.c++,b);return true} function T(a){return this===(a==null?null:a)} function Rk(){return this.$H||(this.$H=++rb)} function Qk(a){return this===(a==null?null:a)} function Db(){try{null.a()}catch(a){return a}} function hg(){if(!dg){sg();wg();dg=true}} function Rf(){!Kf&&(Kf=bg(new _f));return Kf} function Yj(a){a.b=Be(df,0,10,4,0);return a} function ro(a){a.b=new $wnd._IG_Prefs;return a} function vo(a){a.b=new $wnd._IG_Prefs;return a} function yd(a){var b;if(vd){b=new ud;Pd(a,b)}} function Vn(a){var b;b=this.c;this.c=a;return b} function Km(a){on(this,this.E(),a);return true} function Ij(a){Hj();Aj(a,$doc.body);return a} function zj(){zj=sp;xj=zn(new xn);yj=Dn(new Bn)} function $h(){$h=sp;Zh=Ce(gf,0,1,[_q,gr,hr])} function Ie(){Ie=sp;Ge=[];He=[];Je(new we,Ge,He)} function wl(){if(rl==256){ql=sl;sl={};rl=0}++rl} function El(a){var b;b=Cl(this.x(),a);return !!b} function Hh(a,b){a.k=b;a.k.tabIndex=0;return a} function Oi(a,b){a.c=b;a.d=a.c.f.c;Pi(a);return a} function Td(a,b,c,d){a.b=b;a.d=c;a.c=d;return a} function Hk(a,b){var c;c=new Fk;c.b=a+b;return c} function Om(a,b){throw Yk(new Vk,Qr+a+Rr+b)} function Ik(a,b){var c;c=new Fk;c.b=a+b;return c} function En(a,b){var c;c=Vl(a.b,b,a);return c==null} function Nd(a,b){!a.b&&(a.b=mn(new kn));nn(a.b,b)} function Vo(a){!Uo(a)&&vk(a.c,(Mo(),Ko).b,null)} function Ve(a){return a!=null&&(a.tM!=sp&&a.tI!=2)} function sn(a){return Ee(this.b,this.c++,a),true} function Nh(){if(this.c){return this.c.g}return false} function yb(a,b){a.length>=b&&a.splice(0,b);return a} function mn(a){a.b=Be(ef,0,0,0,0);a.c=0;return a} function Mf(a){Sf();return Nf(vd?vd:(vd=Sc(new Pc)),a)} function Kc(){Kc=sp;Jc=Vc(new Oc,uq,(Kc(),new yc))} function Mo(){Mo=sp;Lo=No(new Jo,Tr);Ko=No(new Jo,Ur)} function af(a){if(a!=null){throw Lk(new Jk)}return a} function oo(a){a.b=ro(new po);a.c=vo(new to);return a} function bg(a){a.e=Yd(new Vd);a.f=null;a.d=false;return a} function Kd(a,b){a.e=Yd(new Vd);a.f=b;a.d=false;return a} function W(a){if(a.c==null){return Be(ff,0,15,0,0)}return a.c} function Ol(a){a.b=[];a.f={};a.d=false;a.c=null;a.e=0} function Ah(a){a.style[$q]=nq;a.style[_q]=nq;a.style[ar]=nq} function Bh(a){var b;b=vh(this,a);b&&Ah(a.k);return b} function Hn(a){var b;return b=Vl(this.b,a,this),b==null} function jn(){var a;return a=Re(Vm(this.b.b),25),a.G()} function bn(){var a;return a=om(new mm,this.c.b),fn(new dn,a)} function Il(a){var b;b=hm(new bm,a);return $m(new Ym,a,b)} function Zl(a,b){return !b?_l(a):$l(a,b,~~(b.$H||(b.$H=++rb)))} function Aj(a,b){zj();a.b=Yj(new Wj);a.k=b;_g(a);return a} function eh(a,b){a.h==-1?xg(a.k,b|(a.k.__eventBits||0)):(a.h|=b)} function uh(a,b,c){ch(b);Zj(a.b,b);c.appendChild(b.k);dh(b,a)} function Ce(a,b,c,d){Ie();Le(d,Ge,He);d.tI=b;d.qI=c;return d} function on(a,b,c){(b<0||b>a.c)&&Om(b,a.c);a.b.splice(b,0,c);++a.c} function rn(a,b,c){var d;d=(Lm(b,a.c),a.b[b]);Ee(a.b,b,c);return d} function oh(){var a,b;for(b=this.x();b.z();){a=Re(b.A(),10);a.s()}} function ph(){var a,b;for(b=this.x();b.z();){a=Re(b.A(),10);a.t()}} function kb(a){return a.tM==sp||a.tI==2?a.hC():a.$H||(a.$H=++rb)} function Wb(a,b){return a===b||!!(a.compareDocumentPosition(b)&16)} function pc(b,a){return b[a]==null?null:String(b[a])} function Re(a,b){if(a!=null&&!Qe(a.tI,b)){throw Lk(new Jk)}return a} function of(a){if(a!=null&&Pe(a.tI,19)){return a}return ab(new N,a)} function Vm(a){if(a.b>=a.c.c){throw Yn(new Wn)}return pn(a.c,a.b++)} function gk(a){if(a.b>=a.c.c){throw Yn(new Wn)}return a.c.b[++a.b]} function Nj(a){if(!a.b||!a.c.d){throw Yn(new Wn)}a.b=false;return a.c.d} function Pi(a){while(++a.b<a.d.c){if(pn(a.d,a.b)!=null){return}}} function _l(a){var b;b=a.c;a.c=null;if(a.d){a.d=false;--a.e}return b} function Xl(a,b){var c;c=a.c;a.c=b;if(!a.d){a.d=true;++a.e}return c} function bk(a,b){var c;c=$j(a,b);if(c==-1){throw Yn(new Wn)}ak(a,c)} function qj(a){var b;b=fg((Jb(),a).type);(b&896)!=0?ah(this,a):ah(this,a)} function pe(a){var b;return b=a.b.getString(a.n()),b==undefined?null:b} function Jn(){var a;return a=om(new mm,Il(this.b).c.b),fn(new dn,a)} function $i(){$i=sp;Zi=bj(new _i,Br);bj(new _i,$q);bj(new _i,Cr)} function Mh(a,b){if(a.c){throw Uk(new Sk,fr)}ch(b);Wg(a,b.k);a.c=b;dh(b,a)} function Se(a){if(a!=null&&(a.tM==sp||a.tI==2)){throw Lk(new Jk)}return a} function jg(a){return !(a!=null&&(a.tM!=sp&&a.tI!=2))&&(a!=null&&Pe(a.tI,8))} function Zg(a,b,c){eh(a,fg(c.c));return Md(!a.i?(a.i=Kd(new Hd,a)):a.i,c,b)} function qn(a,b,c){for(;c<a.c;++c){if(bo(b,a.b[c])){return c}}return -1} function $j(a,b){var c;for(c=0;c<a.c;++c){if(a.b[c]==b){return c}}return -1} function Hi(a,b,c,d){var e;zi(a.b,b,c);e=a.b.b.rows[b].cells[c];e[yr]=d.b} function Be(a,b,c,d,e){var f;f=Ae(e,d);Ie();Le(f,Ge,He);f.tI=b;f.qI=c;return f} function Je(a,b,c){var d=0,e;for(var f in a){if(e=a[f]){b[d]=f;c[d]=e;++d}}} function Le(a,b,c){Ie();for(var d=0,e=b.length;d<e;++d){a[b[d]]=c[d]}} function Md(a,b,c){a.c>0?Nd(a,Td(new Rd,a,b,c)):Zd(a.e,b,c);return new Ed} function hl(a,b){if(!(b!=null&&Pe(b.tI,1))){return false}return String(a)==b} function Yl(e,a,b){var c,d=e.f;a=Or+a;a in d?(c=d[a]):++e.e;d[a]=b;return c} function Ob(a){var b=a.firstChild;while(b&&b.nodeType!=1)b=b.nextSibling;return b} function am(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function An(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function bo(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function Pl(a,b){return b==null?a.d:b!=null&&Pe(b.tI,1)?Ul(a,Re(b,1)):Tl(a,b,~~kb(b))} function Ql(a,b){return b==null?a.c:b!=null&&Pe(b.tI,1)?a.f[Or+Re(b,1)]:Rl(a,b,~~kb(b))} function ib(a,b){return a.tM==sp||a.tI==2?a.eQ(b):(a==null?null:a)===(b==null?null:b)} function tj(a,b,c){a.k=b;a.k.tabIndex=0;c!=null&&(a.k[dr]=c,undefined);return a} function Vc(a,b,c){a.d=++Qc;a.b=c;!Dc&&(Dc=nd(new ld));Dc.b[b]=a;a.c=b;return a} function Zd(a,b,c){var d;d=Re(Ql(a.b,b),6);if(!d){d=mn(new kn);Vl(a.b,b,d)}Ee(d.b,d.c++,c)} function ji(a,b){var c;c=a.b.rows.length;if(b>=c||b<0){throw Yk(new Vk,ur+b+vr+c)}} function Qi(a){var b;if(a.b>=a.d.c){throw Yn(new Wn)}b=Re(pn(a.d,a.b),10);Pi(a);return b} function sj(a){var b;tj(a,(b=(Jb(),$doc).createElement(Er),b.type=Fr,b),Gr);return a} function vj(a){var b;tj(a,(b=(Jb(),$doc).createElement(Er),b.type=Hr,b),Ir);return a} function lj(a,b){a.k=(Jb(),$doc).createElement(sr);a.k[dr]=Dr;a.k.textContent=b||nq;return a} function Pf(){var a;if(Jf){a=(Xf(),new Vf);!!Kf&&Pd(Kf,a);return null}return null} function Cl(a,b){var c;while(a.z()){c=a.A();if(b==null?c==null:ib(b,c)){return a}}return null} function Eg(a,b){var c;if(!a.b){c=a.c.c;nn(a.c,b)}else{c=a.b.b;rn(a.c,c,b);a.b=a.b.c}b.k[Vq]=c} function Cf(a,b,c){var d;d=zf;zf=a;b==Af&&(fg((Jb(),a).type)==8192&&(Af=null));c.o(a);zf=d} function Uh(a,b){if(a.d!=b){return false}dh(b,null);a.y().removeChild(b.k);a.d=null;return true} function Vl(a,b,c){return b==null?Xl(a,c):b!=null&&Pe(b.tI,1)?Yl(a,Re(b,1),c):Wl(a,b,c,~~kb(b))} function Dg(a,b){var c,d;c=(d=b[Vq],d==null?-1:d);if(c<0){return null}return Re(pn(a.c,c),9)} function Fg(a,b){var c,d;c=(d=b[Vq],d==null?-1:d);b[Vq]=null;rn(a.c,c,null);a.b=Mg(new Kg,c,a.b)} function Uo(a){var b,c,d;c=false;if(a.b){b=pe(a.b.b);d=pe(a.b.c);c=!hl(nq,d)||!hl(nq,b)}return c} function Vb(b){var c=b.relatedTarget;try{var d=c.nodeName;return c}catch(a){return null}} function Bi(a,b,c){var d=a.rows[b];for(var e=0;e<c;e++){var f=$doc.createElement(rr);d.appendChild(f)}} function Nl(e,a){var b=e.f;for(var c in b){if(c.charCodeAt(0)==58){var d=Gm(e,c.substring(1));a.C(d)}}} function gwtOnLoad(b,c,d){$moduleName=c;$moduleBase=d;if(b)try{lf()}catch(a){b(c)}else{lf()}} function ah(a,b){var c;switch(fg((Jb(),b).type)){case 16:case 32:c=Vb(b);if(!!c&&Wb(a.k,c)){return}}Hc(b,a,a.k)} function fm(){var a,b,c;a=0;for(b=this.x();b.z();){c=b.A();if(c!=null){a+=kb(c);a=~~a}}return a} function vm(){var a,b;a=0;b=0;this.G()!=null&&(a=kb(this.G()));this.H()!=null&&(b=kb(this.H()));return a^b} function Oh(){if(this.h!=-1){eh(this.c,this.h);this.h=-1}_g(this.c);this.k.__listener=this} function Wi(a){if(!a.b){a.b=(Jb(),$doc).createElement(zr);tg(a.c.e,a.b,0);a.b.appendChild($doc.createElement(Ar))}} function bh(a){if(!a.r()){throw Uk(new Sk,Xq)}try{a.v()}finally{a.q();a.k.__listener=null;a.g=false}} function _g(a){var b;if(a.r()){throw Uk(new Sk,Wq)}a.g=true;a.k.__listener=a;b=a.h;a.h=-1;b>0&&eh(a,b);a.p();a.u()} function dh(a,b){var c;c=a.j;if(!b){!!c&&c.r()&&a.t();a.j=null}else{if(c){throw Uk(new Sk,Zq)}a.j=b;b.r()&&a.s()}} function ak(a,b){var c;if(b<0||b>=a.c){throw Xk(new Vk)}--a.c;for(c=b;c<a.c;++c){Ee(a.b,c,a.b[c+1])}Ee(a.b,a.c,null)} function xg(a,b){hg();ug(a,b);b&131072&&a.addEventListener(Qq,pg,false)} function vl(a){tl();var b=Or+a;var c=sl[b];if(c!=null){return c}c=ql[b];c==null&&(c=ul(a));wl();return sl[b]=c} function Cj(a){zj();var b;b=Re(Ql(xj,a),20);if(b){return b}xj.e==0&&Mf(new Ej);b=Ij(new Gj);Vl(xj,a,b);En(yj,b);return b} function rp(a){var b,c;b=pc(a.b.k,gs);c=pc(a.c.k,gs);if(!hl(nq,b)&&!hl(nq,c)){null.K();null.K();null.K(null.K())}} function Hb(a){var b,c,d;d=a&&a.stack?a.stack.split(tq):[];for(b=0,c=d.length;b<c;++b){d[b]=xb(d[b])}return d} function X(a,b){var c,d,e;d=Be(ff,0,15,b.length,0);for(e=0,c=b.length;e<c;++e){if(!b[e]){throw al(new $k)}d[e]=b[e]}a.c=d} function Ae(a,b){var c=new Array(b);if(a>0){var d=[null,0,false,[0,0]][a];for(var e=0;e<b;++e){c[e]=d}}return c} function Ml(g,a){var b=g.b;for(var c in b){if(c==parseInt(c)){var d=b[c];for(var e=0,f=d.length;e<f;++e){a.C(d[e])}}}} function rg(a,b){var c=0,d=a.firstChild;while(d){var e=d.nextSibling;if(d.nodeType==1){if(b==c)return d;++c}d=e}return null} function Vh(a,b){if(b==a.d){return}!!b&&ch(b);!!a.d&&Uh(a,a.d);a.d=b;if(b){a.b.appendChild(a.d.k);dh(b,a)}} function om(a,b){var c;a.c=b;c=mn(new kn);a.c.d&&nn(c,xm(new rm,a.c));Nl(a.c,c);Ml(a.c,c);a.b=Tm(new Qm,c);return a} function Qd(a){var b,c;if(a.b){try{for(c=Tm(new Qm,a.b);c.b<c.c.c;){b=Re(Vm(c),5);Zd(b.b.e,b.d,b.c)}}finally{a.b=null}}} function Kl(){var a,b,c;c=0;for(b=om(new mm,hm(new bm,Re(this,26)).b);Um(b.b);){a=Re(Vm(b.b),25);c+=a.hC();c=~~c}return c} function Nm(){var a,b,c;b=1;a=Tm(new Qm,Re(this,6));while(a.b<a.c.c){c=Vm(a);b=31*b+(c==null?0:kb(c));b=~~b}return b} function um(a){var b;if(a!=null&&Pe(a.tI,25)){b=Re(a,25);if(bo(this.G(),b.G())&&bo(this.H(),b.H())){return true}}return false} function im(a,b){var c,d,e;if(b!=null&&Pe(b.tI,25)){c=Re(b,25);d=c.G();if(Pl(a.b,d)){e=Ql(a.b,d);return An(c.H(),e)}}return false} function zi(a,b,c){var d,e;Ai(a,b);if(c<0){throw Yk(new Vk,wr+c)}d=(ji(a,b),a.b.rows[b].cells.length);e=c+1-d;e>0&&Bi(a.b,b,e)} function ti(a,b,c,d){var e,f;zi(a,b,c);e=(f=a.c.b.b.rows[b].cells[c],oi(a,f,d==null),f);d!=null&&(e.innerHTML=d||nq,undefined)} function ui(a,b,c,d){var e,f;zi(a,b,c);if(d){ch(d);e=(f=a.c.b.b.rows[b].cells[c],oi(a,f,true),f);Eg(a.f,d);e.appendChild(d.k);dh(d,a)}} function Hc(a,b,c){var d,e,f;if(Dc){f=Re(Dc.b[(Jb(),a).type],3);if(f){d=f.b.b;e=f.b.c;f.b.b=a;f.b.c=c;$g(b,f.b);f.b.b=d;f.b.c=e}}} function Jh(a,b,c){var d;Hh(a,(d=(Jb(),$doc).createElement(br),d.type=cr,d));a.k[dr]=er;a.k.innerHTML=b||nq;Zg(a,c,(Kc(),Jc));return a} function bi(a){var b,c;c=(Jb(),$doc).createElement(rr);b=$doc.createElement(sr);c.appendChild(b);c[dr]=a;b[dr]=a+tr;return c} function xb(a){var b,c,d;d=nq;a=ll(a);b=a.indexOf(oq);if(b!=-1){c=a.indexOf(pq)==0?8:0;d=ll(a.substr(c,b-c))}return d.length>0?d:qq} function Cb(a){var b,c,d,e;d=yb(Hb(Db()),2);e=Be(ff,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=dl(new bl,rq,d[b],sq,0)}X(a,e)} function Bb(a){var b,c,d,e;d=Hb(Ve(a.b)?Se(a.b):null);e=Be(ff,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=dl(new bl,rq,d[b],sq,0)}X(a,e)} function Rl(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){return f.H()}}}return null} function Tl(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){return true}}}return false} function Pd(a,b){var c;if(b.d){b.d=false;b.e=null}c=b.e;b.e=a.f;try{++a.c;$d(a.e,b,a.d)}finally{--a.c;a.c==0&&Qd(a)}if(c==null){b.d=true;b.e=null}else{b.e=c}} function ch(a){if(!a.j){zj();if(Pl(yj.b,a)){a.t();Zl(yj.b,a)!=null}}else if(Ue(a.j,21)){Re(a.j,21).w(a)}else if(a.j){throw Uk(new Sk,Yq)}} function oi(a,b,c){var d,e;d=Ob((Jb(),b));e=null;!!d&&(e=Re(Dg(a.f,d),10));if(e){pi(a,e);return true}else{c&&(b.innerHTML=nq,undefined);return false}} function tg(a,b,c){var d=0,e=a.firstChild,f=null;while(e){if(e.nodeType==1){if(d==c){f=e;break}++d}e=e.nextSibling}a.insertBefore(b,f)} function Wl(j,a,b,c){var d=j.b[c];if(d){for(var e=0,f=d.length;e<f;++e){var g=d[e];var h=g.G();if(j.F(a,h)){var i=g.H();g.I(b);return i}}}else{d=j.b[c]=[]}var g=Rn(new Pn,a,b);d.push(g);++j.e;return null} function ll(c){if(c.length==0||c[0]>Nr&&c[c.length-1]>Nr){return c}var a=c.replace(/^(\s*)/,nq);var b=a.replace(/\s*$/,nq);return b} function $l(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.G();if(h.F(a,g)){c.length==1?delete h.b[b]:c.splice(d,1);--h.e;return f.H()}}}return null} function Ee(a,b,c){if(c!=null){if(a.qI>0&&!Qe(c.tI,a.qI)){throw Dk(new Bk)}if(a.qI<0&&(c.tM==sp||c.tI==2)){throw Dk(new Bk)}}return a[b]=c} function _j(a,b,c){var d,e;if(c<0||c>a.c){throw Xk(new Vk)}if(a.c==a.b.length){e=Be(df,0,10,a.b.length*2,0);for(d=0;d<a.b.length;++d){Ee(e,d,a.b[d])}a.b=e}++a.c;for(d=a.c-1;d>c;--d){Ee(a.b,d,a.b[d-1])}Ee(a.b,c,b)} function ul(a){var b,c,d,e;b=0;d=a.length;e=d-4;c=0;while(c<e){b=a.charCodeAt(c+3)+31*(a.charCodeAt(c+2)+31*(a.charCodeAt(c+1)+31*(a.charCodeAt(c)+31*b)))|0;c+=4}while(c<d){b=b*31+a.charCodeAt(c++)}return b|0} function em(a){var b,c,d;if((a==null?null:a)===this){return true}if(!(a!=null&&Pe(a.tI,27))){return false}c=Re(a,27);if(c.E()!=this.E()){return false}for(b=c.x();b.z();){d=b.A();if(!this.D(d)){return false}}return true} function vk(b,c,d){var a,f;try{Re(Ql(b.b,c),22).B(d)}catch(a){a=of(a);if(Ue(a,23)){f=a;if(hl(W(f)[0].b,cf.b)){throw ok(new mk,Jr+c+Kr)}throw f}else if(Ue(a,24)){f=a;if(hl(W(f)[1].b,cf.b)){throw ok(new mk,Lr+c+Mr)}throw f}else throw a}} function $d(a,b,c){var d,e,f,g,h,i,j;g=b.m();d=(h=Re(Ql(a.b,g),6),!h?0:h.c);if(c){for(f=d-1;f>=0;--f){e=(i=Re(Ql(a.b,g),6),Re((Lm(f,i.c),i.b[f]),18));b.l(e)}}else{for(f=0;f<d;++f){e=(j=Re(Ql(a.b,g),6),Re((Lm(f,j.c),j.b[f]),18));b.l(e)}}} function Mm(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&Pe(a.tI,6))){return false}f=Re(a,6);if(this.E()!=f.c){return false}d=Tm(new Qm,Re(this,6));e=Tm(new Qm,f);while(d.b<d.c.c){b=Vm(d);c=Vm(e);if(!(b==null?c==null:ib(b,c))){return false}}return true} function fp(a){var b;a.b=yi(new ei);a.b.e[kr]=6;a.b.k.style[Wr]=Xr;b=a.b.c;ti(a.b,0,0,Yr);Hi(b,0,0,($i(),Zi));ui(a.b,1,0,lj(new jj,Zr));Mh(a,a.b);return a} function Pg(){var d=$wnd.onbeforeunload;var e=$wnd.onunload;$wnd.onbeforeunload=function(a){var b,c;try{b=Pf()}finally{c=d&&d(a)}if(b!=null){return b}if(c!=null){return c}};$wnd.onunload=function(a){try{Jf&&yd(Rf())}finally{e&&e(a);$wnd.onresize=null;$wnd.onscroll=null;$wnd.onbeforeunload=null;$wnd.onunload=null}}} function vh(a,b){var c,d;if(b.j!=a){return false}dh(b,null);c=b.k;(d=(Jb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);bk(a.b,b);return true} function pi(a,b){var c,d;if(b.j!=a){return false}dh(b,null);c=b.k;(d=(Jb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);Fg(a.f,c);return true} function wg(){$wnd.addEventListener(Kq,function(a){var b=$wnd.__captureElem;if(b&&!a.relatedTarget){if(Tq==a.target.tagName.toLowerCase()){var c=$doc.createEvent(Uq);c.initMouseEvent(Mq,true,true,$wnd,0,a.screenX,a.screenY,a.clientX,a.clientY,a.ctrlKey,a.altKey,a.shiftKey,a.metaKey,a.button,null);b.dispatchEvent(c)}}},true);$wnd.addEventListener(Qq,og,true)} function Bj(){var c,d;zj();var a,b;for(b=(c=om(new mm,Il(yj.b).c.b),fn(new dn,c));Um(b.b.b);){a=Re((d=Re(Vm(b.b.b),25),d.G()),10);a.r()&&a.t()}Ol(yj.b);Ol(xj)} function ai(a,b,c){var d,e,f,g;$h();a.k=(Jb(),$doc).createElement(ir);f=a.k;a.c=$doc.createElement(jr);f.appendChild(a.c);f[kr]=0;f[lr]=0;for(d=0;d<b.length;++d){e=(g=$doc.createElement(mr),(g[dr]=b[d],undefined),g.appendChild(bi(b[d]+nr)),g.appendChild(bi(b[d]+or)),g.appendChild(bi(b[d]+pr)),g);a.c.appendChild(e);d==c&&(a.b=Ob(rg(e,1)))}a.k[dr]=qr;return a} function yi(a){a.f=Cg(new zg);a.e=(Jb(),$doc).createElement(ir);a.b=$doc.createElement(jr);a.e.appendChild(a.b);a.k=a.e;a.c=Ji(new Ci,a);si(a,Vi(new Ti,a));return a} function lf(){var a,i,j,k,l,m,n,o;!!$stats&&$stats({moduleName:$moduleName,subSystem:vq,evtGroup:wq,millis:(new Date).getTime(),type:xq,className:yq});(new ho).J(new he);a=zo(new xo,oo(new lo));k=tk(new qk);l=fp(new cp);m=new Ro;m.c=k;m.d=l;m.b=a.b;Vl(k.b,(Mo(),Lo).b,Do(new Bo,m));n=mp(new kp);o=new Yo;o.c=k;o.d=n;j=bp(new _o);i=new Oo;i.c=k;i.d=j;Vl(k.b,Ko.b,Ho(new Fo,m,n));zh((zj(),Cj(null)),l);vk(k,Lo.b,null)} function Ai(a,b){var c,d,e;if(b<0){throw Yk(new Vk,xr+b)}d=a.b.rows.length;for(c=d;c<=b;++c){c!=a.b.rows.length&&ji(a,c);e=(Jb(),$doc).createElement(mr);tg(a.b,e,c)}} function fg(a){switch(a){case zq:return 4096;case Aq:return 1024;case uq:return 1;case Bq:return 2;case Cq:return 2048;case Dq:return 128;case Eq:return 256;case Fq:return 512;case Gq:return 32768;case Hq:return 8192;case Iq:return 4;case Jq:return 64;case Kq:return 32;case Lq:return 16;case Mq:return 8;case Nq:return 16384;case Oq:return 65536;case Pq:return 131072;case Qq:return 131072;case Rq:return 262144;case Sq:return 524288;}} function mp(a){var b,c,d,e,f,g;a.b=(e=yi(new ei),(e.e[kr]=6,undefined),(e.k.style[Wr]=$r,undefined),c=e.c,ti(e,0,0,_r),((zi(c.b,0,0),c.b.b.rows[0].cells[0])[as]=2,undefined),Hi(c,0,0,($i(),Zi)),ti(e,1,0,bs),g=sj(new nj),(g.k.style[Wr]=cs,undefined),ui(e,1,1,g),ti(e,2,0,ds),f=vj(new mj),(f.k.style[Wr]=cs,undefined),ui(e,2,1,f),b=Jh(new Ch,es,qp(new op,f,g)),ui(e,3,1,b),d=_h(new Rh),Vh(d,e),(d.k.style[Wr]=fs,undefined),d);Mh(a,a.b);return a} function Jl(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&Pe(a.tI,26))){return false}e=Re(a,26);if(Re(this,26).e!=e.e){return false}for(c=om(new mm,hm(new bm,e).b);Um(c.b);){b=Re(Vm(c.b),25);d=b.G();f=b.H();if(!(d==null?Re(this,26).d:d!=null&&Pe(d.tI,1)?Ul(Re(this,26),Re(d,1)):Tl(Re(this,26),d,~~kb(d)))){return false}if(!bo(f,d==null?Re(this,26).c:d!=null&&Pe(d.tI,1)?Re(this,26).f[Or+Re(d,1)]:Rl(Re(this,26),d,~~kb(d)))){return false}}return true} function sg(){og=function(a){if(ng(a)){var b=mg;if(b&&b.__listener){if(jg(b.__listener)){Cf(a,b,b.__listener);a.stopPropagation()}}}};ng=function(a){return true};pg=function(a){var b,c=this;while(c&&!(b=c.__listener)){c=c.parentNode}c&&c.nodeType!=1&&(c=null);b&&(jg(b)&&Cf(a,c,b))};$wnd.addEventListener(uq,og,true);$wnd.addEventListener(Bq,og,true);$wnd.addEventListener(Iq,og,true);$wnd.addEventListener(Mq,og,true);$wnd.addEventListener(Jq,og,true);$wnd.addEventListener(Lq,og,true);$wnd.addEventListener(Kq,og,true);$wnd.addEventListener(Pq,og,true);$wnd.addEventListener(Dq,ng,true);$wnd.addEventListener(Fq,ng,true);$wnd.addEventListener(Eq,ng,true)} function ug(a,b){var c=(a.__eventBits||0)^b;a.__eventBits=b;if(!c)return;c&1&&(a.onclick=b&1?pg:null);c&2&&(a.ondblclick=b&2?pg:null);c&4&&(a.onmousedown=b&4?pg:null);c&8&&(a.onmouseup=b&8?pg:null);c&16&&(a.onmouseover=b&16?pg:null);c&32&&(a.onmouseout=b&32?pg:null);c&64&&(a.onmousemove=b&64?pg:null);c&128&&(a.onkeydown=b&128?pg:null);c&256&&(a.onkeypress=b&256?pg:null);c&512&&(a.onkeyup=b&512?pg:null);c&1024&&(a.onchange=b&1024?pg:null);c&2048&&(a.onfocus=b&2048?pg:null);c&4096&&(a.onblur=b&4096?pg:null);c&8192&&(a.onlosecapture=b&8192?pg:null);c&16384&&(a.onscroll=b&16384?pg:null);c&32768&&(a.onload=b&32768?pg:null);c&65536&&(a.onerror=b&65536?pg:null);c&131072&&(a.onmousewheel=b&131072?pg:null);c&262144&&(a.oncontextmenu=b&262144?pg:null);c&524288&&(a.onpaste=b&524288?pg:null)} var nq='',tq='\n',Nr=' ',Kr=" doesn't exist. Have you forgotten to add it to your Mvp4g configuration file?",Mr=' is incorrect. It should be the same as the one configured in the Mvp4g configuration file.',oq='(',vr=', Row size: ',Rr=', Size: ',cs='100px',$r='200px',Xr='250px',Yr='4kGadget initialization...',fs='80%',Or=':',Pr='Add not supported on this collection',br='BUTTON',wr='Cannot create a column with a negative index: ',xr='Cannot create a row with a negative index: ',Zq='Cannot set a new parent without first clearing the old parent',or='Center',Lr='Class of the object sent with event ',fr='Composite.initWidget() may only be called once.',Qq='DOMMouseScroll',Ur='ENTER_CREDENTIALS',_r='Enter credentials',Jr='Event ',ns='EventBus',Er='INPUT',Qr='Index: ',tr='Inner',nr='Left',Uq='MouseEvents',os='Object;',ds='Password',pr='Right',ur='Row index: ',Tr='START',Wq="Should only call onAttach when the widget is detached from the browser's document",Xq="Should only call onDetach when the widget is attached to the browser's document",is='StackTraceElement;',js='String;',es='Submit',Yq="This widget's parent does not implement HasWidgets",rq='Unknown',sq='Unknown source',bs='Username',ls='Widget;',ks='[Lcom.google.gwt.user.client.ui.',hs='[Ljava.lang.',Vq='__uiObjectID',yr='align',qq='anonymous',zq='blur',hr='bottom',cr='button',lr='cellPadding',kr='cellSpacing',Br='center',Aq='change',dr='className',uq='click',Ar='col',as='colSpan',zr='colgroup',ms='com.mvp4g.client.event.',Rq='contextmenu',Bq='dblclick',sr='div',Oq='error',Cq='focus',pq='function',er='gwt-Button',qr='gwt-DecoratorPanel',Dr='gwt-Label',Ir='gwt-PasswordTextBox',Gr='gwt-TextBox',Tq='html',Dq='keydown',Eq='keypress',Fq='keyup',Vr='label',$q='left',Gq='load',Hq='losecapture',gr='middle',wq='moduleStartup',Iq='mousedown',Jq='mousemove',Kq='mouseout',Lq='mouseover',Mq='mouseup',Pq='mousewheel',yq='name.webdizz.gadget.four.envelope.client.Envelope',xq='onModuleLoadStart',Hr='password',Sq='paste',ar='position',Cr='right',Nq='scroll',vq='startup',Zr='stub content',ir='table',jr='tbody',rr='td',Fr='text',_q='top',mr='tr',Sr='username',gs='value',Wr='width';var _;_=R.prototype={};_.eQ=T;_.hC=U;_.tM=sp;_.tI=1;_=Q.prototype=new R;_.tI=3;_.c=null;_=P.prototype=new Q;_.tI=4;_=O.prototype=new P;_.tI=5;_=N.prototype=new O;_.tI=6;_.b=null;var rb=0;_=Ib.prototype=new R;_.tI=0;_=Rb.prototype=new Ib;_.tI=0;_=Qb.prototype=new Rb;_.tI=0;_=Ac.prototype=new R;_.tI=0;_.d=false;_.e=null;_=zc.prototype=new Ac;_.m=Ic;_.tI=0;_.b=null;_.c=null;var Dc=null;_=yc.prototype=new zc;_.l=Mc;_.tI=0;var Jc;_=Pc.prototype=new R;_.hC=Tc;_.tI=0;_.d=0;var Qc=0;_=Oc.prototype=new Pc;_.tI=7;_.b=null;_.c=null;_=ld.prototype=new R;_.tI=0;_.b=null;_=ud.prototype=new Ac;_.l=xd;_.m=zd;_.tI=0;var vd=null;_=Ed.prototype=new R;_.tI=0;_=Hd.prototype=new R;_.tI=0;_.b=null;_.c=0;_.d=false;_.e=null;_.f=null;_=Rd.prototype=new R;_.tI=8;_.b=null;_.c=null;_.d=null;_=Vd.prototype=new R;_.tI=0;_=de.prototype=new R;_.tI=0;_=he.prototype=new R;_.tI=0;_=le.prototype=new R;_.tI=0;_=ke.prototype=new le;_.tI=0;_=we.prototype=new R;_.tI=0;_.length=0;_.qI=0;var Ge,He;var Ne=[{},{},{1:1,11:1,12:1,13:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{3:1},{5:1},{7:1},{9:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,20:1,21:1},{4:1,18:1},{7:1,8:1,9:1,10:1,20:1,21:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,24:1},{11:1,13:1,14:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,23:1},{11:1,15:1},{12:1},{11:1,19:1},{27:1},{27:1},{25:1},{25:1},{25:1},{27:1},{6:1,11:1},{11:1,26:1},{11:1,27:1},{25:1},{11:1,19:1},{22:1},{22:1},{11:1,13:1,14:1,16:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,28:1},{7:1,8:1,9:1,10:1},{2:1,18:1},{17:1}];var zf=null,Af=null;var Jf=false,Kf=null;_=Vf.prototype=new Ac;_.l=Zf;_.m=$f;_.tI=0;var Wf;_=_f.prototype=new Hd;_.tI=9;var dg=false;var mg=null,ng=null,og=null,pg=null;_=zg.prototype=new R;_.tI=0;_.b=null;_=Kg.prototype=new R;_.tI=0;_.b=0;_.c=null;_=Ug.prototype=new R;_.tI=10;_.k=null;_=Tg.prototype=new Ug;_.p=fh;_.q=gh;_.r=hh;_.s=ih;_.o=jh;_.t=kh;_.u=lh;_.v=mh;_.tI=11;_.g=false;_.h=0;_.i=null;_.j=null;_=Sg.prototype=new Tg;_.p=oh;_.q=ph;_.u=qh;_.v=rh;_.tI=12;_=Rg.prototype=new Sg;_.x=wh;_.w=xh;_.tI=13;_=Qg.prototype=new Rg;_.w=Bh;_.tI=14;_=Eh.prototype=new Tg;_.tI=15;_=Dh.prototype=new Eh;_.tI=16;_=Ch.prototype=new Dh;_.tI=17;_=Kh.prototype=new Tg;_.r=Nh;_.s=Oh;_.o=Ph;_.t=Qh;_.tI=18;_.c=null;_=Sh.prototype=new Sg;_.y=Wh;_.x=Xh;_.w=Yh;_.tI=19;_.d=null;_=Rh.prototype=new Sh;_.y=di;_.tI=20;_.b=null;_.c=null;var Zh;_=fi.prototype=new Sg;_.x=vi;_.w=wi;_.tI=21;_.b=null;_.c=null;_.d=null;_.e=null;_=ei.prototype=new fi;_.tI=22;_=Di.prototype=new R;_.tI=0;_.b=null;_=Ci.prototype=new Di;_.tI=0;_=Li.prototype=new R;_.z=Ri;_.A=Si;_.tI=0;_.b=-1;_.c=null;_=Ti.prototype=new R;_.tI=0;_.b=null;_.c=null;var Zi;_=_i.prototype=new R;_.tI=0;_.b=null;_=jj.prototype=new Tg;_.tI=23;_=oj.prototype=new Eh;_.o=qj;_.tI=24;_=nj.prototype=new oj;_.tI=25;_=mj.prototype=new nj;_.tI=26;_=wj.prototype=new Qg;_.tI=27;var xj,yj;_=Ej.prototype=new R;_.tI=28;_=Gj.prototype=new wj;_.tI=29;_=Jj.prototype=new R;_.z=Oj;_.A=Pj;_.tI=0;_.c=null;_=Wj.prototype=new R;_.tI=0;_.b=null;_.c=0;_=ck.prototype=new R;_.z=hk;_.A=ik;_.tI=0;_.b=-1;_.c=null;_=mk.prototype=new O;_.tI=30;_=qk.prototype=new R;_.tI=0;_=wk.prototype=new R;_.tI=0;_.c=null;_.d=null;_=Bk.prototype=new O;_.tI=32;_=Fk.prototype=new R;_.tI=0;_.b=null;_=Jk.prototype=new O;_.tI=35;_=Ok.prototype=new R;_.eQ=Qk;_.hC=Rk;_.tI=36;_.b=null;_=Sk.prototype=new O;_.tI=37;_=Vk.prototype=new O;_.tI=38;_=$k.prototype=new O;_.tI=39;_=bl.prototype=new R;_.tI=40;_.b=null;_=String.prototype;_.eQ=nl;_.hC=ol;_.tI=2;var ql,rl=0,sl;_=xl.prototype=new O;_.tI=42;_=Al.prototype=new R;_.C=Dl;_.D=El;_.tI=0;_=Gl.prototype=new R;_.eQ=Jl;_.hC=Kl;_.tI=0;_=Fl.prototype=new Gl;_.F=am;_.tI=0;_.b=null;_.c=null;_.d=false;_.e=0;_.f=null;_=cm.prototype=new Al;_.eQ=em;_.hC=fm;_.tI=43;_=bm.prototype=new cm;_.D=jm;_.x=km;_.E=lm;_.tI=44;_.b=null;_=mm.prototype=new R;_.z=pm;_.A=qm;_.tI=0;_.b=null;_.c=null;_=sm.prototype=new R;_.eQ=um;_.hC=vm;_.tI=45;_=rm.prototype=new sm;_.G=ym;_.H=zm;_.I=Am;_.tI=46;_.b=null;_=Bm.prototype=new sm;_.G=Em;_.H=Fm;_.I=Hm;_.tI=47;_.b=null;_.c=null;_=Im.prototype=new Al;_.C=Km;_.eQ=Mm;_.hC=Nm;_.x=Pm;_.tI=0;_=Qm.prototype=new R;_.z=Wm;_.A=Xm;_.tI=0;_.b=0;_.c=null;_=Ym.prototype=new cm;_.D=an;_.x=bn;_.E=cn;_.tI=48;_.b=null;_.c=null;_=dn.prototype=new R;_.z=hn;_.A=jn;_.tI=0;_.b=null;_=kn.prototype=new Im;_.C=sn;_.D=tn;_.E=un;_.tI=49;_.b=null;_.c=0;_=xn.prototype=new Fl;_.tI=50;_=Bn.prototype=new cm;_.C=Hn;_.D=In;_.x=Jn;_.E=Kn;_.tI=51;_.b=null;_=Pn.prototype=new sm;_.G=Sn;_.H=Tn;_.I=Vn;_.tI=52;_.b=null;_.c=null;_=Wn.prototype=new O;_.tI=53;_=co.prototype=new de;_.J=go;_.tI=0;_=ho.prototype=new co;_.tI=0;_=lo.prototype=new R;_.tI=0;_=po.prototype=new ke;_.n=so;_.tI=0;_=to.prototype=new ke;_.n=wo;_.tI=0;_=xo.prototype=new R;_.tI=0;_.b=null;_=Bo.prototype=new R;_.B=Eo;_.tI=54;_.b=null;_=Fo.prototype=new R;_.B=Io;_.tI=55;_.b=null;_.c=null;_=Jo.prototype=new Ok;_.tI=56;var Ko,Lo;_=Oo.prototype=new wk;_.tI=0;_=Ro.prototype=new wk;_.tI=0;_.b=null;_=Yo.prototype=new wk;_.tI=0;_=_o.prototype=new Kh;_.tI=57;_=cp.prototype=new Kh;_.tI=58;_=kp.prototype=new Kh;_.tI=59;_.b=null;_=op.prototype=new R;_.tI=60;_.b=null;_.c=null;var ff=Hk(hs,is),gf=Hk(hs,js),df=Hk(ks,ls),cf=Ik(ms,ns),ef=Hk(hs,os);$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalEnd'});if (envelope) envelope.onScriptLoad(gwtOnLoad);})();
JavaScript
(function(){var $gwt_version = "2.0.0";var $wnd = window;var $doc = $wnd.document;var $moduleName, $moduleBase;var $strongName = '6647AD60DFB5DFC235C906873D67E88F';var $stats = $wnd.__gwtStatsEvent ? function(a) {return $wnd.__gwtStatsEvent(a);} : null;$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalStart'});function R(){} function Q(){} function P(){} function O(){} function N(){} function Xp(){} function zb(){} function Ib(){} function Hb(){} function Wb(){} function dc(){} function cc(){} function Oc(){} function Nc(){} function Mc(){} function bd(){} function ad(){} function zd(){} function Id(){} function Sd(){} function Vd(){} function de(){} function he(){} function re(){} function ve(){} function ze(){} function ye(){} function Ke(){} function jg(){} function pg(){} function Kg(){} function Vg(){} function dh(){} function qh(){} function rh(){} function wh(){} function xh(){} function ch(){} function Bh(){} function Ch(){} function bh(){} function ah(){} function _g(){} function Ph(){} function Oh(){} function Nh(){} function Yh(){} function ei(){} function di(){} function ti(){} function si(){} function Ri(){} function Qi(){} function Zi(){} function fj(){} function nj(){} function xj(){} function Cj(){} function Bj(){} function Aj(){} function Kj(){} function Sj(){} function Uj(){} function Xj(){} function ik(){} function qk(){} function xk(){} function Dk(){} function Kk(){} function Ok(){} function Sk(){} function Yk(){} function bl(){} function fl(){} function jl(){} function ol(){} function sl(){} function vl(){} function Al(){} function Dl(){} function am(){} function dm(){} function jm(){} function im(){} function Hm(){} function Gm(){} function Rm(){} function Xm(){} function Wm(){} function en(){} function mn(){} function un(){} function Cn(){} function Jn(){} function Pn(){} function ao(){} function fo(){} function to(){} function Ao(){} function Io(){} function Mo(){} function Qo(){} function Uo(){} function Yo(){} function ap(){} function ep(){} function ip(){} function mp(){} function rp(){} function up(){} function Bp(){} function Ep(){} function Hp(){} function Pp(){} function Tp(){} function Lo(a){} function Vb(){return 3} function Ob(){return 2} function fh(a,b){a.k=b} function th(){kh(this)} function vh(){mh(this)} function Nd(){return Jd} function og(){return kg} function Xo(){return ms} function _o(){return ws} function Gb(a){return []} function ec(){ec=Xp;Xb()} function gc(){gc=Xp;ec()} function Sh(){Sh=Xp;Rh()} function Uh(){Uh=Xp;Sh()} function ci(){mh(this.c)} function Dj(){Dj=Xp;Rh()} function Fj(){Fj=Xp;Dj()} function Ij(){Ij=Xp;Fj()} function Vj(){Vj=Xp;Nj()} function Ek(){Ek=Xp;Ak()} function Lk(){Lk=Xp;Ek()} function uh(a){lh(this,a)} function bn(){return null} function hp(a){yp(this.b)} function $c(a){Wp(df(a,2))} function Fb(a){return xb(a)} function fd(){return this.d} function Ld(a){df(a,4);Pj()} function sh(){return this.g} function ii(){return this.k} function ri(){return this.b} function ak(){return this.b} function hn(){return this.b} function Zn(){return this.c} function wo(){return this.b} function xo(){return this.c} function Wc(){return Yc(),Xc} function Sb(){return Qb(this)} function ej(){return cj(this)} function bk(){return _j(this)} function wk(){return uk(this)} function Tl(){return $l(this)} function Qm(){return this.b.e} function cn(){return this.b.c} function Bn(){return zn(this)} function Kh(a,b){Fh(a,b,a.k)} function lk(a,b){nk(a,b,a.c)} function Wf(a,b){xg();Jg(a,b)} function ng(a){qf(a);null.P()} function Ck(a,b){a.tabIndex=b} function Cl(a){Cb(a);return a} function dl(a){Cb(a);return a} function ll(a){Cb(a);return a} function xl(a){Cb(a);return a} function co(a){rm(a);return a} function oo(){return this.b.e} function Co(a){Cb(a);return a} function Bd(a){a.b={};return a} function Gi(a,b){a.d=b;ij(a.d)} function Xi(a,b){a.b=b;return a} function Xb(){Xb=Xp;gc();new cc} function Yl(){Yl=Xp;Vl={};Xl={}} function hj(a,b){a.c=b;return a} function pj(a,b){a.b=b;return a} function tk(a,b){a.c=b;return a} function Qk(a,b){Cb(a);return a} function ul(a,b){Cb(a);return a} function yl(a,b){Cb(a);return a} function cm(a,b){Cb(a);return a} function Mm(a,b){a.b=b;return a} function an(a,b){a.b=b;return a} function xn(a,b){a.c=b;return a} function yn(a){return a.b<a.c.c} function Um(){return yn(this.b)} function In(){return this.c.b.e} function Nb(a){return Lb(this,a)} function cp(a,b){a.b=b;return a} function Ln(a,b){a.b=b;return a} function gp(a,b){a.b=b;return a} function ed(a){a.d=++cd;return a} function Ub(a){return Rb(this,a)} function Ih(a){return Gh(this,a)} function Rh(){Rh=Xp;Qh=(Ak(),zk)} function ki(a){return gi(this,a)} function Ki(a){return Di(this,a)} function Ql(a){return Jl(this,a)} function Om(a){return Nm(this,a)} function lp(a){Ap(this.b,this.c)} function gm(a){throw cm(new am,ts)} function lg(){lg=Xp;kg=ed(new bd)} function jh(a,b){!!a.i&&be(a.i,b)} function cf(a,b){return a&&_e[a][b]} function Nn(){return yn(this.b.b)} function dn(a){return Am(this.b,a)} function Gn(a){return sm(this.b,a)} function mo(a){return sm(this.b,a)} function ji(){return $j(new Xj,this)} function xm(b,a){return Yq+a in b.f} function bg(a,b){return $d(fg(),a,b)} function Ji(){return aj(new Zi,this)} function dj(){return this.b<this.d.c} function An(){return this.b<this.c.c} function Hh(){return tk(new qk,this.b)} function qp(a,b){pp();a.b=b;return a} function bf(a,b){return a&&!!_e[a][b]} function vk(){return this.b<this.c.c-1} function Fl(a,b,c,d,e){a.b=b;return a} function Pm(){return Tm(new Rm,this.b)} function Gp(a){zj(new xj,zs);return a} function Vm(){return df(zn(this.b),25)} function Yn(a){return Vn(this,a,0)!=-1} function bi(a){lh(this,a);lh(this.c,a)} function xg(){if(!tg){Hg();tg=true}} function gg(){if(!Zf){$g();Zf=true}} function ni(a){mi();oi(a,li,1);return a} function ke(a){a.b=co(new ao);return a} function Ng(a){a.c=Rn(new Pn);return a} function Vk(a){a.b=co(new ao);return a} function kn(a,b){return gn(new en,b,a)} function pn(a,b){(a<0||a>=b)&&sn(a,b)} function Xg(a,b,c){a.b=b;a.c=c;return a} function ho(a){a.b=co(new ao);return a} function gn(a,b,c){a.c=c;a.b=b;return a} function En(a,b,c){a.b=b;a.c=c;return a} function vo(a,b,c){a.b=b;a.c=c;return a} function kp(a,b,c){a.b=b;a.c=c;return a} function Vp(a,b,c){a.b=b;a.c=c;return a} function ln(a){return Bm(this.c,this.b,a)} function Un(a,b){pn(b,a.c);return a.b[b]} function Ap(a,b){Ii(df(a.d,28).b,1,0,b)} function $j(a,b){a.c=b;a.b=!!a.c.d;return a} function gf(a,b){return a!=null&&bf(a.tI,b)} function T(a){return this===(a==null?null:a)} function jn(){return this.c.f[Yq+this.b]} function U(){return this.$H||(this.$H=++rb)} function tn(){return xn(new un,df(this,6))} function rl(){return this.$H||(this.$H=++rb)} function sn(a,b){throw yl(new vl,us+a+vs+b)} function Sn(a,b){Se(a.b,a.c++,b);return true} function ql(a){return this===(a==null?null:a)} function Mb(){return yb(this.n(Db()),this.o())} function on(a){Tn(this,this.J(),a);return true} function kk(a){a.b=Pe(tf,0,10,4,0);return a} function Wo(a){a.b=new $wnd._IG_Prefs;return a} function $o(a){a.b=new $wnd._IG_Prefs;return a} function Md(a){var b;if(Jd){b=new Id;be(a,b)}} function zo(a){var b;b=this.c;this.c=a;return b} function Wj(a){Vj();Oj(a,$doc.body);return a} function Mk(a){Lk();Hk();Ik();Nk();return a} function yp(a){!xp(a)&&Xk(a.c,(pp(),np).b,null)} function fg(){!$f&&($f=rg(new pg));return $f} function Nj(){Nj=Xp;Lj=co(new ao);Mj=ho(new fo)} function mi(){mi=Xp;li=Qe(wf,0,1,[Fr,Nr,Or])} function We(){We=Xp;Ue=[];Ve=[];Xe(new Ke,Ue,Ve)} function _l(){if(Wl==256){Vl=Xl;Xl={};Wl=0}++Wl} function Db(){try{null.a()}catch(a){return a}} function hl(a,b){var c;c=new fl;c.b=a+b;return c} function il(a,b){var c;c=new fl;c.b=a+b;return c} function Jk(a,b){a.firstChild.tabIndex=b} function Th(a,b){Sh();a.k=b;Qh.F(a.k,0);return a} function fe(a,b,c,d){a.b=b;a.d=c;a.c=d;return a} function aj(a,b){a.c=b;a.d=a.c.f.c;bj(a);return a} function hm(a){var b;b=fm(this.B(),a);return !!b} function Rn(a){a.b=Pe(uf,0,0,0,0);a.c=0;return a} function Xn(a){return Se(this.b,this.c++,a),true} function _h(){if(this.c){return this.c.g}return false} function yb(a,b){a.length>=b&&a.splice(0,b);return a} function _d(a,b){!a.b&&(a.b=Rn(new Pn));Sn(a.b,b)} function ab(a,b){Cb(a);a.b=b;Bb(new Hb,a);return a} function To(a){a.b=Wo(new Uo);a.c=$o(new Yo);return a} function io(a,b){var c;c=ym(a.b,b,a);return c==null} function lo(a){var b;return b=ym(this.b,a,this),b==null} function Mh(a){var b;b=Gh(this,a);b&&Lh(a.k);return b} function hf(a){return a!=null&&(a.tM!=Xp&&a.tI!=2)} function qf(a){if(a!=null){throw ll(new jl)}return a} function Yd(a,b){a.e=ke(new he);a.f=b;a.d=false;return a} function rg(a){a.e=ke(new he);a.f=null;a.d=false;return a} function rm(a){a.b=[];a.f={};a.d=false;a.c=null;a.e=0} function Lh(a){a.style[Er]=Sq;a.style[Fr]=Sq;a.style[Gr]=Sq} function Dc(b,a){return b[a]==null?null:String(b[a])} function W(a){if(a.c==null){return Pe(vf,0,15,0,0)}return a.c} function Oj(a,b){Nj();a.b=kk(new ik);a.k=b;kh(a);return a} function Yc(){Yc=Xp;Xc=hd(new ad,ar,(Yc(),new Mc))} function pp(){pp=Xp;op=qp(new mp,xs);np=qp(new mp,ys)} function Ak(){Ak=Xp;yk=Mk(new Kk);zk=yk?(Ak(),new xk):yk} function lm(a){var b;b=Mm(new Gm,a);return En(new Cn,a,b)} function Hn(){var a;return a=Tm(new Rm,this.c.b),Ln(new Jn,a)} function On(){var a;return a=df(zn(this.b.b),25),a.L()} function ag(a){gg();return bg(Jd?Jd:(Jd=ed(new bd)),a)} function Cm(a,b){return !b?Em(a):Dm(a,b,~~(b.$H||(b.$H=++rb)))} function kb(a){return a.tM==Xp||a.tI==2?a.hC():a.$H||(a.$H=++rb)} function ph(a,b){a.h==-1?Wf(a.k,b|(a.k.__eventBits||0)):(a.h|=b)} function Fh(a,b,c){nh(b);lk(a.b,b);c.appendChild(b.k);oh(b,a)} function Tn(a,b,c){(b<0||b>a.c)&&sn(b,a.c);a.b.splice(b,0,c);++a.c} function Wn(a,b,c){var d;d=(pn(b,a.c),a.b[b]);Se(a.b,b,c);return d} function Qe(a,b,c,d){We();Ze(d,Ue,Ve);d.tI=b;d.qI=c;return d} function df(a,b){if(a!=null&&!cf(a.tI,b)){throw ll(new jl)}return a} function Df(a){if(a!=null&&bf(a.tI,19)){return a}return ab(new N,a)} function uk(a){if(a.b>=a.c.c){throw Co(new Ao)}return a.c.b[++a.b]} function zn(a){if(a.b>=a.c.c){throw Co(new Ao)}return Un(a.c,a.b++)} function mj(){mj=Xp;lj=pj(new nj,gs);pj(new nj,Er);pj(new nj,hs)} function no(){var a;return a=Tm(new Rm,lm(this.b).c.b),Ln(new Jn,a)} function De(a){var b;return b=a.b.getString(a.r()),b==undefined?null:b} function zh(){var a,b;for(b=this.B();b.D();){a=df(b.E(),10);a.w()}} function Ah(){var a,b;for(b=this.B();b.D();){a=df(b.E(),10);a.x()}} function Em(a){var b;b=a.c;a.c=null;if(a.d){a.d=false;--a.e}return b} function bj(a){while(++a.b<a.d.c){if(Un(a.d,a.b)!=null){return}}} function _j(a){if(!a.b||!a.c.d){throw Co(new Ao)}a.b=false;return a.c.d} function $h(a,b){if(a.c){throw ul(new sl,Mr)}nh(b);fh(a,b.k);a.c=b;oh(b,a)} function ef(a){if(a!=null&&(a.tM==Xp||a.tI==2)){throw ll(new jl)}return a} function pk(a,b){var c;c=mk(a,b);if(c==-1){throw Co(new Ao)}ok(a,c)} function Am(a,b){var c;c=a.c;a.c=b;if(!a.d){a.d=true;++a.e}return c} function mk(a,b){var c;for(c=0;c<a.c;++c){if(a.b[c]==b){return c}}return -1} function Vn(a,b,c){for(;c<a.c;++c){if(Ho(b,a.b[c])){return c}}return -1} function ih(a,b,c){ph(a,vg(c.c));return $d(!a.i?(a.i=Yd(new Vd,a)):a.i,c,b)} function $d(a,b,c){a.c>0?_d(a,fe(new de,a,b,c)):le(a.e,b,c);return new Sd} function Vi(a,b,c,d){var e;Ni(a.b,b,c);e=a.b.b.rows[b].cells[c];e[ds]=d.b} function Ze(a,b,c){We();for(var d=0,e=b.length;d<e;++d){a[b[d]]=c[d]}} function Xe(a,b,c){var d=0,e;for(var f in a){if(e=a[f]){b[d]=f;c[d]=e;++d}}} function Bm(e,a,b){var c,d=e.f;a=Yq+a;a in d?(c=d[a]):++e.e;d[a]=b;return c} function Pe(a,b,c,d,e){var f;f=Oe(e,d);We();Ze(f,Ue,Ve);f.tI=b;f.qI=c;return f} function dg(){var a;if(Zf){a=(lg(),new jg);!!$f&&be($f,a);return null}return null} function zg(a){return !(a!=null&&(a.tM!=Xp&&a.tI!=2))&&(a!=null&&bf(a.tI,8))} function Fm(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function eo(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function Ho(a,b){return (a==null?null:a)===(b==null?null:b)||a!=null&&ib(a,b)} function ib(a,b){return a.tM==Xp||a.tI==2?a.eQ(b):(a==null?null:a)===(b==null?null:b)} function Jl(a,b){if(!(b!=null&&bf(b.tI,1))){return false}return String(a)==b} function zj(a,b){a.k=(Xb(),$doc).createElement(Zr);a.k[Kr]=is;bc(a.k,b);return a} function Hj(a,b,c){Fj();a.k=b;Qh.F(a.k,0);c!=null&&(a.k[Kr]=c,undefined);return a} function hd(a,b,c){a.d=++cd;a.b=c;!Rc&&(Rc=Bd(new zd));Rc.b[b]=a;a.c=b;return a} function xi(a,b){var c;c=a.b.rows.length;if(b>=c||b<0){throw yl(new vl,_r+b+as+c)}} function cj(a){var b;if(a.b>=a.d.c){throw Co(new Ao)}b=df(Un(a.d,a.b),10);bj(a);return b} function Qb(a){var b;b=yb(Rb(a,Db()),3);b.length==0&&(b=yb((new zb).l(),1));return b} function Ej(a){var b;b=vg((Xb(),a).type);(b&896)!=0?lh(this,a):lh(this,a)} function Gj(a){var b;Fj();Hj(a,(b=(Xb(),$doc).createElement(js),b.type=ks,b),ls);return a} function Jj(a){var b;Ij();Hj(a,(b=(Xb(),$doc).createElement(js),b.type=ms,b),ns);return a} function _b(a){var b=a.firstChild;while(b&&b.nodeType!=1)b=b.nextSibling;return b} function fm(a,b){var c;while(a.D()){c=a.E();if(b==null?c==null:ib(b,c)){return a}}return null} function Pg(a,b){var c;if(!a.b){c=a.c.c;Sn(a.c,b)}else{c=a.b.b;Wn(a.c,c,b);a.b=a.b.c}b.k[zr]=c} function le(a,b,c){var d;d=df(tm(a.b,b),6);if(!d){d=Rn(new Pn);ym(a.b,b,d)}Se(d.b,d.c++,c)} function Rf(a,b,c){var d;d=Of;Of=a;b==Pf&&(vg((Xb(),a).type)==8192&&(Pf=null));c.s(a);Of=d} function gi(a,b){if(a.d!=b){return false}oh(b,null);a.C().removeChild(b.k);a.d=null;return true} function sm(a,b){return b==null?a.d:b!=null&&bf(b.tI,1)?xm(a,df(b,1)):wm(a,b,~~kb(b))} function tm(a,b){return b==null?a.c:b!=null&&bf(b.tI,1)?a.f[Yq+df(b,1)]:um(a,b,~~kb(b))} function ym(a,b,c){return b==null?Am(a,c):b!=null&&bf(b.tI,1)?Bm(a,df(b,1),c):zm(a,b,c,~~kb(b))} function Og(a,b){var c,d;c=(d=b[zr],d==null?-1:d);if(c<0){return null}return df(Un(a.c,c),9)} function Qg(a,b){var c,d;c=(d=b[zr],d==null?-1:d);b[zr]=null;Wn(a.c,c,null);a.b=Xg(new Vg,c,a.b)} function xp(a){var b,c,d;c=false;if(a.b){b=De(a.b.b);d=De(a.b.c);c=!Jl(Sq,d)||!Jl(Sq,b)}return c} function Km(){var a,b,c;a=0;for(b=this.B();b.D();){c=b.E();if(c!=null){a+=kb(c);a=~~a}}return a} function Ik(){return function(a){this.parentNode.onfocus&&this.parentNode.onfocus(a)}} function Hk(){return function(a){this.parentNode.onblur&&this.parentNode.onblur(a)}} function Nk(){return function(){var a=this.firstChild;$wnd.setTimeout(function(){a.focus()},0)}} function $m(){var a,b;a=0;b=0;this.L()!=null&&(a=kb(this.L()));this.M()!=null&&(b=kb(this.M()));return a^b} function ai(){if(this.h!=-1){ph(this.c,this.h);this.h=-1}kh(this.c);this.k.__listener=this} function mh(a){if(!a.v()){throw ul(new sl,Br)}try{a.z()}finally{a.u();a.k.__listener=null;a.g=false}} function oh(a,b){var c;c=a.j;if(!b){!!c&&c.v()&&a.x();a.j=null}else{if(c){throw ul(new sl,Dr)}a.j=b;b.v()&&a.w()}} function qm(e,a){var b=e.f;for(var c in b){if(c.charCodeAt(0)==58){var d=kn(e,c.substring(1));a.H(d)}}} function Rb(a,b){var c;c=Lb(a,b);if(c.length==0){return (new zb).n(b)}else{return c.length>=1&&c.splice(0,1),c}} function jc(a,b){while(b){if(a==b){return true}b=b.parentNode;b&&b.nodeType!=1&&(b=null)}return false} function $l(a){Yl();var b=Yq+a;var c=Xl[b];if(c!=null){return c}c=Vl[b];c==null&&(c=Zl(a));_l();return Xl[b]=c} function Oe(a,b){var c=new Array(b);if(a>0){var d=[null,0,false,[0,0]][a];for(var e=0;e<b;++e){c[e]=d}}return c} function Pi(a,b,c){var d=a.rows[b];for(var e=0;e<c;e++){var f=$doc.createElement(Yr);d.appendChild(f)}} function ij(a){if(!a.b){a.b=(Xb(),$doc).createElement(es);Ig(a.c.e,a.b,0);a.b.appendChild($doc.createElement(fs))}} function hi(a,b){if(b==a.d){return}!!b&&nh(b);!!a.d&&gi(a,a.d);a.d=b;if(b){a.b.appendChild(a.d.k);oh(b,a)}} function Tm(a,b){var c;a.c=b;c=Rn(new Pn);a.c.d&&Sn(c,an(new Wm,a.c));qm(a.c,c);pm(a.c,c);a.b=xn(new un,c);return a} function ce(a){var b,c;if(a.b){try{for(c=xn(new un,a.b);c.b<c.c.c;){b=df(zn(c),5);le(b.b.e,b.d,b.c)}}finally{a.b=null}}} function ok(a,b){var c;if(b<0||b>=a.c){throw xl(new vl)}--a.c;for(c=b;c<a.c;++c){Se(a.b,c,a.b[c+1])}Se(a.b,a.c,null)} function kh(a){var b;if(a.v()){throw ul(new sl,Ar)}a.g=true;a.k.__listener=a;b=a.h;a.h=-1;b>0&&ph(a,b);a.t();a.y()} function rn(){var a,b,c;b=1;a=xn(new un,df(this,6));while(a.b<a.c.c){c=zn(a);b=31*b+(c==null?0:kb(c));b=~~b}return b} function gwtOnLoad(b,c,d){$moduleName=c;$moduleBase=d;if(b)try{Af()}catch(a){b(c)}else{Af()}} function pm(g,a){var b=g.b;for(var c in b){if(c==parseInt(c)){var d=b[c];for(var e=0,f=d.length;e<f;++e){a.H(d[e])}}}} function X(a,b){var c,d,e;d=Pe(vf,0,15,b.length,0);for(e=0,c=b.length;e<c;++e){if(!b[e]){throw Cl(new Al)}d[e]=b[e]}a.c=d} function Lb(a,b){var c,d,e;e=b&&b.stack?b.stack.split(Zq):[];for(c=0,d=e.length;c<d;++c){e[c]=a.m(e[c])}return e} function Gg(a,b){var c=0,d=a.firstChild;while(d){var e=d.nextSibling;if(d.nodeType==1){if(b==c)return d;++c}d=e}return null} function bc(a,b){while(a.firstChild){a.removeChild(a.firstChild)}b!=null&&a.appendChild(a.ownerDocument.createTextNode(b))} function Wp(a){var b,c;b=Dc(a.b.k,Ms);c=Dc(a.c.k,Ms);if(!Jl(Sq,b)&&!Jl(Sq,c)){null.P();null.P();null.P(null.P())}} function Zm(a){var b;if(a!=null&&bf(a.tI,25)){b=df(a,25);if(Ho(this.L(),b.L())&&Ho(this.M(),b.M())){return true}}return false} function Nm(a,b){var c,d,e;if(b!=null&&bf(b.tI,25)){c=df(b,25);d=c.L();if(sm(a.b,d)){e=tm(a.b,d);return eo(c.M(),e)}}return false} function nm(){var a,b,c;c=0;for(b=Tm(new Rm,Mm(new Gm,df(this,26)).b);yn(b.b);){a=df(zn(b.b),25);c+=a.hC();c=~~c}return c} function Cb(a){var b,c,d,e;d=Qb(new Hb);e=Pe(vf,0,15,d.length,0);for(b=0,c=e.length;b<c;++b){e[b]=Fl(new Dl,Wq,d[b],Xq,0)}X(a,e)} function pi(a){var b,c;c=(Xb(),$doc).createElement(Yr);b=$doc.createElement(Zr);c.appendChild(b);c[Kr]=a;b[Kr]=a+$r;return c} function lh(a,b){var c;switch(vg((Xb(),b).type)){case 16:case 32:c=b.relatedTarget;if(!!c&&jc(a.k,c)){return}}Vc(b,a,a.k)} function Ni(a,b,c){var d,e;Oi(a,b);if(c<0){throw yl(new vl,bs+c)}d=(xi(a,b),a.b.rows[b].cells.length);e=c+1-d;e>0&&Pi(a.b,b,e)} function Ii(a,b,c,d){var e,f;Ni(a,b,c);if(d){nh(d);e=(f=a.c.b.b.rows[b].cells[c],Ci(a,f,true),f);Pg(a.f,d);e.appendChild(d.k);oh(d,a)}} function Hi(a,b,c,d){var e,f;Ni(a,b,c);e=(f=a.c.b.b.rows[b].cells[c],Ci(a,f,d==null),f);d!=null&&(e.innerHTML=d||Sq,undefined)} function Vc(a,b,c){var d,e,f;if(Rc){f=df(Rc.b[(Xb(),a).type],3);if(f){d=f.b.b;e=f.b.c;f.b.b=a;f.b.c=c;jh(b,f.b);f.b.b=d;f.b.c=e}}} function Bb(a,b){var c,d,e,f;e=Rb(a,hf(b.b)?ef(b.b):null);f=Pe(vf,0,15,e.length,0);for(c=0,d=f.length;c<d;++c){f[c]=Fl(new Dl,Wq,e[c],Xq,0)}X(b,f)} function Qj(a){Nj();var b;b=df(tm(Lj,a),20);if(b){return b}Lj.e==0&&ag(new Sj);b=Wj(new Uj);ym(Lj,a,b);io(Mj,b);return b} function Ci(a,b,c){var d,e;d=_b((Xb(),b));e=null;!!d&&(e=df(Og(a.f,d),10));if(e){Di(a,e);return true}else{c&&(b.innerHTML=Sq,undefined);return false}} function Ig(a,b,c){var d=0,e=a.firstChild,f=null;while(e){if(e.nodeType==1){if(d==c){f=e;break}++d}e=e.nextSibling}a.insertBefore(b,f)} function um(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.L();if(h.K(a,g)){return f.M()}}}return null} function wm(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.L();if(h.K(a,g)){return true}}}return false} function be(a,b){var c;if(b.d){b.d=false;b.e=null}c=b.e;b.e=a.f;try{++a.c;me(a.e,b,a.d)}finally{--a.c;a.c==0&&ce(a)}if(c==null){b.d=true;b.e=null}else{b.e=c}} function xb(a){var b,c,d;d=Sq;a=Ol(a);b=a.indexOf(Tq);if(b!=-1){c=a.indexOf(Uq)==0?8:0;d=Ol(a.substr(c,b-c))}return d.length>0?d:Vq} function Di(a,b){var c,d;if(b.j!=a){return false}oh(b,null);c=b.k;(d=(Xb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);Qg(a.f,c);return true} function Gh(a,b){var c,d;if(b.j!=a){return false}oh(b,null);c=b.k;(d=(Xb(),c).parentNode,(!d||d.nodeType!=1)&&(d=null),d).removeChild(c);pk(a.b,b);return true} function nh(a){if(!a.j){Nj();if(sm(Mj.b,a)){a.x();Cm(Mj.b,a)!=null}}else if(gf(a.j,21)){df(a.j,21).A(a)}else if(a.j){throw ul(new sl,Cr)}} function Ol(c){if(c.length==0||c[0]>ss&&c[c.length-1]>ss){return c}var a=c.replace(/^(\s*)/,Sq);var b=a.replace(/\s*$/,Sq);return b} function Dm(h,a,b){var c=h.b[b];if(c){for(var d=0,e=c.length;d<e;++d){var f=c[d];var g=f.L();if(h.K(a,g)){c.length==1?delete h.b[b]:c.splice(d,1);--h.e;return f.M()}}}return null} function zm(j,a,b,c){var d=j.b[c];if(d){for(var e=0,f=d.length;e<f;++e){var g=d[e];var h=g.L();if(j.K(a,h)){var i=g.M();g.N(b);return i}}}else{d=j.b[c]=[]}var g=vo(new to,a,b);d.push(g);++j.e;return null} function Zl(a){var b,c,d,e;b=0;d=a.length;e=d-4;c=0;while(c<e){b=a.charCodeAt(c+3)+31*(a.charCodeAt(c+2)+31*(a.charCodeAt(c+1)+31*(a.charCodeAt(c)+31*b)))|0;c+=4}while(c<d){b=b*31+a.charCodeAt(c++)}return b|0} function nk(a,b,c){var d,e;if(c<0||c>a.c){throw xl(new vl)}if(a.c==a.b.length){e=Pe(tf,0,10,a.b.length*2,0);for(d=0;d<a.b.length;++d){Se(e,d,a.b[d])}a.b=e}++a.c;for(d=a.c-1;d>c;--d){Se(a.b,d,a.b[d-1])}Se(a.b,c,b)} function Se(a,b,c){if(c!=null){if(a.qI>0&&!cf(c.tI,a.qI)){throw dl(new bl)}if(a.qI<0&&(c.tM==Xp||c.tI==2)){throw dl(new bl)}}return a[b]=c} function Oi(a,b){var c,d,e;if(b<0){throw yl(new vl,cs+b)}d=a.b.rows.length;for(c=d;c<=b;++c){c!=a.b.rows.length&&xi(a,c);e=(Xb(),$doc).createElement(Tr);Ig(a.b,e,c)}} function Tb(a){var b,c;if(a.length==0){return Vq}c=Ol(a);c.indexOf($q)==0&&(c=c.substr(3,c.length-3));b=c.indexOf(_q);b==-1&&(b=c.indexOf(Tq));if(b==-1){return Vq}else{c=Ol(c.substr(0,b-0))}b=c.indexOf(Sl(46));b!=-1&&(c=c.substr(b+1,c.length-(b+1)));return c.length>0?c:Vq} function Xh(a,b,c){var d;Uh();Th(a,(d=(Xb(),$doc).createElement(Hr),d.setAttribute(Ir,Jr),d));a.k[Kr]=Lr;a.k.innerHTML=b||Sq;ih(a,c,(Yc(),Xc));return a} function Mi(a){a.f=Ng(new Kg);a.e=(Xb(),$doc).createElement(Pr);a.b=$doc.createElement(Qr);a.e.appendChild(a.b);a.k=a.e;a.c=Xi(new Qi,a);Gi(a,hj(new fj,a));return a} function qn(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&bf(a.tI,6))){return false}f=df(a,6);if(this.J()!=f.c){return false}d=xn(new un,df(this,6));e=xn(new un,f);while(d.b<d.c.c){b=zn(d);c=zn(e);if(!(b==null?c==null:ib(b,c))){return false}}return true} function Kp(a){var b;a.b=Mi(new si);a.b.e[Rr]=6;a.b.k.style[As]=Bs;b=a.b.c;Hi(a.b,0,0,Cs);Vi(b,0,0,(mj(),lj));Ii(a.b,1,0,zj(new xj,Ds));$h(a,a.b);return a} function $g(){var d=$wnd.onbeforeunload;var e=$wnd.onunload;$wnd.onbeforeunload=function(a){var b,c;try{b=dg()}finally{c=d&&d(a)}if(b!=null){return b}if(c!=null){return c}};$wnd.onunload=function(a){try{Zf&&Md(fg())}finally{e&&e(a);$wnd.onresize=null;$wnd.onscroll=null;$wnd.onbeforeunload=null;$wnd.onunload=null}}} function Pj(){var c,d;Nj();var a,b;for(b=(c=Tm(new Rm,lm(Mj.b).c.b),Ln(new Jn,c));yn(b.b.b);){a=df((d=df(zn(b.b.b),25),d.L()),10);a.v()&&a.x()}rm(Mj.b);rm(Lj)} function oi(a,b,c){var d,e,f,g;mi();a.k=(Xb(),$doc).createElement(Pr);f=a.k;a.c=$doc.createElement(Qr);f.appendChild(a.c);f[Rr]=0;f[Sr]=0;for(d=0;d<b.length;++d){e=(g=$doc.createElement(Tr),(g[Kr]=b[d],undefined),g.appendChild(pi(b[d]+Ur)),g.appendChild(pi(b[d]+Vr)),g.appendChild(pi(b[d]+Wr)),g);a.c.appendChild(e);d==c&&(a.b=_b(Gg(e,1)))}a.k[Kr]=Xr;return a} function Sl(a){var b,c;if(a>=65536){b=55296+(a-65536>>10&1023)&65535;c=56320+(a-65536&1023)&65535;return String.fromCharCode(b)+String.fromCharCode(c)}else{return String.fromCharCode(a&65535)}} function Af(){var a,i,j,k,l,m,n,o;!!$stats&&$stats({moduleName:$moduleName,subSystem:br,evtGroup:cr,millis:(new Date).getTime(),type:dr,className:er});(new Mo).O(new ve);a=cp(new ap,To(new Qo));k=Vk(new Sk);l=Kp(new Hp);m=new up;m.c=k;m.d=l;m.b=a.b;ym(k.b,(pp(),op).b,gp(new ep,m));n=Rp(new Pp);o=new Bp;o.c=k;o.d=n;j=Gp(new Ep);i=new rp;i.c=k;i.d=j;ym(k.b,np.b,kp(new ip,m,n));Kh((Nj(),Qj(null)),l);Xk(k,op.b,null)} function Jm(a){var b,c,d;if((a==null?null:a)===this){return true}if(!(a!=null&&bf(a.tI,27))){return false}c=df(a,27);if(c.J()!=this.J()){return false}for(b=c.B();b.D();){d=b.E();if(!this.I(d)){return false}}return true} function Xk(b,c,d){var a,f;try{df(tm(b.b,c),22).G(d)}catch(a){a=Df(a);if(gf(a,23)){f=a;if(Jl(W(f)[0].b,sf.b)){throw Qk(new Ok,os+c+ps)}throw f}else if(gf(a,24)){f=a;if(Jl(W(f)[1].b,sf.b)){throw Qk(new Ok,qs+c+rs)}throw f}else throw a}} function me(a,b,c){var d,e,f,g,h,i,j;g=b.q();d=(h=df(tm(a.b,g),6),!h?0:h.c);if(c){for(f=d-1;f>=0;--f){e=(i=df(tm(a.b,g),6),df((pn(f,i.c),i.b[f]),18));b.p(e)}}else{for(f=0;f<d;++f){e=(j=df(tm(a.b,g),6),df((pn(f,j.c),j.b[f]),18));b.p(e)}}} function Eb(){var a={};var b=[];var c=arguments.callee.caller.caller;while(c){var d=this.m(c.toString());b.push(d);var e=Yq+d;var f=a[e];if(f){var g,h;for(g=0,h=f.length;g<h;g++){if(f[g]===c){return b}}}(f||(a[e]=[])).push(c);c=c.caller}return b} function vg(a){switch(a){case fr:return 4096;case gr:return 1024;case ar:return 1;case hr:return 2;case ir:return 2048;case jr:return 128;case kr:return 256;case lr:return 512;case mr:return 32768;case nr:return 8192;case or:return 4;case pr:return 64;case qr:return 32;case rr:return 16;case sr:return 8;case tr:return 16384;case ur:return 65536;case vr:return 131072;case wr:return 131072;case xr:return 262144;case yr:return 524288;}} function Rp(a){var b,c,d,e,f,g;a.b=(e=Mi(new si),(e.e[Rr]=6,undefined),(e.k.style[As]=Es,undefined),c=e.c,Hi(e,0,0,Fs),((Ni(c.b,0,0),c.b.b.rows[0].cells[0])[Gs]=2,undefined),Vi(c,0,0,(mj(),lj)),Hi(e,1,0,Hs),g=Gj(new Bj),(g.k.style[As]=Is,undefined),Ii(e,1,1,g),Hi(e,2,0,Js),f=Jj(new Aj),(f.k.style[As]=Is,undefined),Ii(e,2,1,f),b=Xh(new Nh,Ks,Vp(new Tp,f,g)),Ii(e,3,1,b),d=ni(new di),hi(d,e),(d.k.style[As]=Ls,undefined),d);$h(a,a.b);return a} function mm(a){var b,c,d,e,f;if((a==null?null:a)===this){return true}if(!(a!=null&&bf(a.tI,26))){return false}e=df(a,26);if(df(this,26).e!=e.e){return false}for(c=Tm(new Rm,Mm(new Gm,e).b);yn(c.b);){b=df(zn(c.b),25);d=b.L();f=b.M();if(!(d==null?df(this,26).d:d!=null&&bf(d.tI,1)?xm(df(this,26),df(d,1)):wm(df(this,26),d,~~kb(d)))){return false}if(!Ho(f,d==null?df(this,26).c:d!=null&&bf(d.tI,1)?df(this,26).f[Yq+df(d,1)]:um(df(this,26),d,~~kb(d)))){return false}}return true} function Hg(){Dg=function(a){if(Cg(a)){var b=Bg;if(b&&b.__listener){if(zg(b.__listener)){Rf(a,b,b.__listener);a.stopPropagation()}}}};Cg=function(a){return true};Eg=function(a){var b,c=this;while(c&&!(b=c.__listener)){c=c.parentNode}c&&c.nodeType!=1&&(c=null);b&&(zg(b)&&Rf(a,c,b))};$wnd.addEventListener(ar,Dg,true);$wnd.addEventListener(hr,Dg,true);$wnd.addEventListener(or,Dg,true);$wnd.addEventListener(sr,Dg,true);$wnd.addEventListener(pr,Dg,true);$wnd.addEventListener(rr,Dg,true);$wnd.addEventListener(qr,Dg,true);$wnd.addEventListener(vr,Dg,true);$wnd.addEventListener(jr,Cg,true);$wnd.addEventListener(lr,Cg,true);$wnd.addEventListener(kr,Cg,true)} function Jg(a,b){var c=(a.__eventBits||0)^b;a.__eventBits=b;if(!c)return;c&1&&(a.onclick=b&1?Eg:null);c&2&&(a.ondblclick=b&2?Eg:null);c&4&&(a.onmousedown=b&4?Eg:null);c&8&&(a.onmouseup=b&8?Eg:null);c&16&&(a.onmouseover=b&16?Eg:null);c&32&&(a.onmouseout=b&32?Eg:null);c&64&&(a.onmousemove=b&64?Eg:null);c&128&&(a.onkeydown=b&128?Eg:null);c&256&&(a.onkeypress=b&256?Eg:null);c&512&&(a.onkeyup=b&512?Eg:null);c&1024&&(a.onchange=b&1024?Eg:null);c&2048&&(a.onfocus=b&2048?Eg:null);c&4096&&(a.onblur=b&4096?Eg:null);c&8192&&(a.onlosecapture=b&8192?Eg:null);c&16384&&(a.onscroll=b&16384?Eg:null);c&32768&&(a.onload=b&32768?Eg:null);c&65536&&(a.onerror=b&65536?Eg:null);c&131072&&(a.onmousewheel=b&131072?Eg:null);c&262144&&(a.oncontextmenu=b&262144?Eg:null);c&524288&&(a.onpaste=b&524288?Eg:null)} var Sq='',Zq='\n',ss=' ',ps=" doesn't exist. Have you forgotten to add it to your Mvp4g configuration file?",rs=' is incorrect. It should be the same as the one configured in the Mvp4g configuration file.',Tq='(',as=', Row size: ',vs=', Size: ',Is='100px',Es='200px',Bs='250px',Cs='4kGadget initialization...',Ls='80%',Yq=':',ts='Add not supported on this collection',Hr='BUTTON',bs='Cannot create a column with a negative index: ',cs='Cannot create a row with a negative index: ',Dr='Cannot set a new parent without first clearing the old parent',Vr='Center',qs='Class of the object sent with event ',Mr='Composite.initWidget() may only be called once.',wr='DOMMouseScroll',ys='ENTER_CREDENTIALS',Fs='Enter credentials',os='Event ',Ts='EventBus',js='INPUT',us='Index: ',$r='Inner',Ur='Left',Us='Object;',Js='Password',Wr='Right',_r='Row index: ',xs='START',Ar="Should only call onAttach when the widget is detached from the browser's document",Br="Should only call onDetach when the widget is attached to the browser's document",Os='StackTraceElement;',Ps='String;',Ks='Submit',Cr="This widget's parent does not implement HasWidgets",Wq='Unknown',Xq='Unknown source',Hs='Username',Rs='Widget;',_q='[',Qs='[Lcom.google.gwt.user.client.ui.',Ns='[Ljava.lang.',zr='__uiObjectID',ds='align',Vq='anonymous',$q='at ',fr='blur',Or='bottom',Jr='button',Sr='cellPadding',Rr='cellSpacing',gs='center',gr='change',Kr='className',ar='click',fs='col',Gs='colSpan',es='colgroup',Ss='com.mvp4g.client.event.',xr='contextmenu',hr='dblclick',Zr='div',ur='error',ir='focus',Uq='function',Lr='gwt-Button',Xr='gwt-DecoratorPanel',is='gwt-Label',ns='gwt-PasswordTextBox',ls='gwt-TextBox',jr='keydown',kr='keypress',lr='keyup',zs='label',Er='left',mr='load',nr='losecapture',Nr='middle',cr='moduleStartup',or='mousedown',pr='mousemove',qr='mouseout',rr='mouseover',sr='mouseup',vr='mousewheel',er='name.webdizz.gadget.four.envelope.client.Envelope',dr='onModuleLoadStart',ms='password',yr='paste',Gr='position',hs='right',tr='scroll',br='startup',Ds='stub content',Pr='table',Qr='tbody',Yr='td',ks='text',Fr='top',Tr='tr',Ir='type',ws='username',Ms='value',As='width';var _;_=R.prototype={};_.eQ=T;_.hC=U;_.tM=Xp;_.tI=1;_=Q.prototype=new R;_.tI=3;_.c=null;_=P.prototype=new Q;_.tI=4;_=O.prototype=new P;_.tI=5;_=N.prototype=new O;_.tI=6;_.b=null;var rb=0;_=zb.prototype=new R;_.l=Eb;_.m=Fb;_.n=Gb;_.tI=0;_=Ib.prototype=new zb;_.l=Mb;_.n=Nb;_.o=Ob;_.tI=0;_=Hb.prototype=new Ib;_.l=Sb;_.m=Tb;_.n=Ub;_.o=Vb;_.tI=0;_=Wb.prototype=new R;_.tI=0;_=dc.prototype=new Wb;_.tI=0;_=cc.prototype=new dc;_.tI=0;_=Oc.prototype=new R;_.tI=0;_.d=false;_.e=null;_=Nc.prototype=new Oc;_.q=Wc;_.tI=0;_.b=null;_.c=null;var Rc=null;_=Mc.prototype=new Nc;_.p=$c;_.tI=0;var Xc;_=bd.prototype=new R;_.hC=fd;_.tI=0;_.d=0;var cd=0;_=ad.prototype=new bd;_.tI=7;_.b=null;_.c=null;_=zd.prototype=new R;_.tI=0;_.b=null;_=Id.prototype=new Oc;_.p=Ld;_.q=Nd;_.tI=0;var Jd=null;_=Sd.prototype=new R;_.tI=0;_=Vd.prototype=new R;_.tI=0;_.b=null;_.c=0;_.d=false;_.e=null;_.f=null;_=de.prototype=new R;_.tI=8;_.b=null;_.c=null;_.d=null;_=he.prototype=new R;_.tI=0;_=re.prototype=new R;_.tI=0;_=ve.prototype=new R;_.tI=0;_=ze.prototype=new R;_.tI=0;_=ye.prototype=new ze;_.tI=0;_=Ke.prototype=new R;_.tI=0;_.length=0;_.qI=0;var Ue,Ve;var _e=[{},{},{1:1,11:1,12:1,13:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{3:1},{5:1},{7:1},{9:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1,21:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,20:1,21:1},{4:1,18:1},{7:1,8:1,9:1,10:1,20:1,21:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,24:1},{11:1,13:1,14:1},{11:1,19:1},{11:1,19:1},{11:1,19:1,23:1},{11:1,15:1},{12:1},{11:1,19:1},{27:1},{27:1},{25:1},{25:1},{25:1},{27:1},{6:1,11:1},{11:1,26:1},{11:1,27:1},{25:1},{11:1,19:1},{22:1},{22:1},{11:1,13:1,14:1,16:1},{7:1,8:1,9:1,10:1},{7:1,8:1,9:1,10:1,28:1},{7:1,8:1,9:1,10:1},{2:1,18:1},{17:1}];var Of=null,Pf=null;var Zf=false,$f=null;_=jg.prototype=new Oc;_.p=ng;_.q=og;_.tI=0;var kg;_=pg.prototype=new Vd;_.tI=9;var tg=false;var Bg=null,Cg=null,Dg=null,Eg=null;_=Kg.prototype=new R;_.tI=0;_.b=null;_=Vg.prototype=new R;_.tI=0;_.b=0;_.c=null;_=dh.prototype=new R;_.tI=10;_.k=null;_=ch.prototype=new dh;_.t=qh;_.u=rh;_.v=sh;_.w=th;_.s=uh;_.x=vh;_.y=wh;_.z=xh;_.tI=11;_.g=false;_.h=0;_.i=null;_.j=null;_=bh.prototype=new ch;_.t=zh;_.u=Ah;_.y=Bh;_.z=Ch;_.tI=12;_=ah.prototype=new bh;_.B=Hh;_.A=Ih;_.tI=13;_=_g.prototype=new ah;_.A=Mh;_.tI=14;_=Ph.prototype=new ch;_.tI=15;var Qh;_=Oh.prototype=new Ph;_.tI=16;_=Nh.prototype=new Oh;_.tI=17;_=Yh.prototype=new ch;_.v=_h;_.w=ai;_.s=bi;_.x=ci;_.tI=18;_.c=null;_=ei.prototype=new bh;_.C=ii;_.B=ji;_.A=ki;_.tI=19;_.d=null;_=di.prototype=new ei;_.C=ri;_.tI=20;_.b=null;_.c=null;var li;_=ti.prototype=new bh;_.B=Ji;_.A=Ki;_.tI=21;_.b=null;_.c=null;_.d=null;_.e=null;_=si.prototype=new ti;_.tI=22;_=Ri.prototype=new R;_.tI=0;_.b=null;_=Qi.prototype=new Ri;_.tI=0;_=Zi.prototype=new R;_.D=dj;_.E=ej;_.tI=0;_.b=-1;_.c=null;_=fj.prototype=new R;_.tI=0;_.b=null;_.c=null;var lj;_=nj.prototype=new R;_.tI=0;_.b=null;_=xj.prototype=new ch;_.tI=23;_=Cj.prototype=new Ph;_.s=Ej;_.tI=24;_=Bj.prototype=new Cj;_.tI=25;_=Aj.prototype=new Bj;_.tI=26;_=Kj.prototype=new _g;_.tI=27;var Lj,Mj;_=Sj.prototype=new R;_.tI=28;_=Uj.prototype=new Kj;_.tI=29;_=Xj.prototype=new R;_.D=ak;_.E=bk;_.tI=0;_.c=null;_=ik.prototype=new R;_.tI=0;_.b=null;_.c=0;_=qk.prototype=new R;_.D=vk;_.E=wk;_.tI=0;_.b=-1;_.c=null;_=xk.prototype=new R;_.F=Ck;_.tI=0;var yk,zk;_=Dk.prototype=new xk;_.F=Jk;_.tI=0;_=Kk.prototype=new Dk;_.tI=0;_=Ok.prototype=new O;_.tI=30;_=Sk.prototype=new R;_.tI=0;_=Yk.prototype=new R;_.tI=0;_.c=null;_.d=null;_=bl.prototype=new O;_.tI=32;_=fl.prototype=new R;_.tI=0;_.b=null;_=jl.prototype=new O;_.tI=35;_=ol.prototype=new R;_.eQ=ql;_.hC=rl;_.tI=36;_.b=null;_=sl.prototype=new O;_.tI=37;_=vl.prototype=new O;_.tI=38;_=Al.prototype=new O;_.tI=39;_=Dl.prototype=new R;_.tI=40;_.b=null;_=String.prototype;_.eQ=Ql;_.hC=Tl;_.tI=2;var Vl,Wl=0,Xl;_=am.prototype=new O;_.tI=42;_=dm.prototype=new R;_.H=gm;_.I=hm;_.tI=0;_=jm.prototype=new R;_.eQ=mm;_.hC=nm;_.tI=0;_=im.prototype=new jm;_.K=Fm;_.tI=0;_.b=null;_.c=null;_.d=false;_.e=0;_.f=null;_=Hm.prototype=new dm;_.eQ=Jm;_.hC=Km;_.tI=43;_=Gm.prototype=new Hm;_.I=Om;_.B=Pm;_.J=Qm;_.tI=44;_.b=null;_=Rm.prototype=new R;_.D=Um;_.E=Vm;_.tI=0;_.b=null;_.c=null;_=Xm.prototype=new R;_.eQ=Zm;_.hC=$m;_.tI=45;_=Wm.prototype=new Xm;_.L=bn;_.M=cn;_.N=dn;_.tI=46;_.b=null;_=en.prototype=new Xm;_.L=hn;_.M=jn;_.N=ln;_.tI=47;_.b=null;_.c=null;_=mn.prototype=new dm;_.H=on;_.eQ=qn;_.hC=rn;_.B=tn;_.tI=0;_=un.prototype=new R;_.D=An;_.E=Bn;_.tI=0;_.b=0;_.c=null;_=Cn.prototype=new Hm;_.I=Gn;_.B=Hn;_.J=In;_.tI=48;_.b=null;_.c=null;_=Jn.prototype=new R;_.D=Nn;_.E=On;_.tI=0;_.b=null;_=Pn.prototype=new mn;_.H=Xn;_.I=Yn;_.J=Zn;_.tI=49;_.b=null;_.c=0;_=ao.prototype=new im;_.tI=50;_=fo.prototype=new Hm;_.H=lo;_.I=mo;_.B=no;_.J=oo;_.tI=51;_.b=null;_=to.prototype=new Xm;_.L=wo;_.M=xo;_.N=zo;_.tI=52;_.b=null;_.c=null;_=Ao.prototype=new O;_.tI=53;_=Io.prototype=new re;_.O=Lo;_.tI=0;_=Mo.prototype=new Io;_.tI=0;_=Qo.prototype=new R;_.tI=0;_=Uo.prototype=new ye;_.r=Xo;_.tI=0;_=Yo.prototype=new ye;_.r=_o;_.tI=0;_=ap.prototype=new R;_.tI=0;_.b=null;_=ep.prototype=new R;_.G=hp;_.tI=54;_.b=null;_=ip.prototype=new R;_.G=lp;_.tI=55;_.b=null;_.c=null;_=mp.prototype=new ol;_.tI=56;var np,op;_=rp.prototype=new Yk;_.tI=0;_=up.prototype=new Yk;_.tI=0;_.b=null;_=Bp.prototype=new Yk;_.tI=0;_=Ep.prototype=new Yh;_.tI=57;_=Hp.prototype=new Yh;_.tI=58;_=Pp.prototype=new Yh;_.tI=59;_.b=null;_=Tp.prototype=new R;_.tI=60;_.b=null;_.c=null;var vf=hl(Ns,Os),wf=hl(Ns,Ps),tf=hl(Qs,Rs),sf=il(Ss,Ts),uf=hl(Ns,Us);$stats && $stats({moduleName:'envelope',subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalEnd'});if (envelope) envelope.onScriptLoad(gwtOnLoad);})();
JavaScript
//create MiniMessage var fourKgadget_msg = new gadgets.MiniMessage(), // Get userprefs fourKgadget_prefs = new gadgets.Prefs(), weekDays = new Array(), months = new Array(), isValidationPassed = false, statusMessage = null, today = new Date(), ACTIVE_EXPENSE = 0, fourKgadgetGA = new _IG_GA("UA-10296791-2"); // returns envelope begin date var fourKgadget_getEnvelopeBegin = function() { var d = today.getDate(), m = today.getMonth() + 1, oneDay=1000*60*60*24; //resolve date according to day of a week if(today.getDay()>0){ d = d-(today.getDay()-1); } else { d = (d - 6); } if(d<=0){ var tmpDate = new Date(today.getTime()-(oneDay*today.getDate())); d = tmpDate.getDate(); m = tmpDate.getMonth()+1; } if (d < 10) { d = '0' + d; } if (m < 10) { m = '0' + m; } return today.getFullYear() + '-' + m + '-' + d; }; var weekBeginDate = fourKgadget_getEnvelopeBegin(); // define base URL var envelopeUrl = fourKgadget_prefs.getString('baseUrl'), dailyExpenseUrl = fourKgadget_prefs .getString('baseUrl'); // application starter var fourKgadget_startApplication = function() { // change noCacheId fourKgadget_prefs.set('noCacheId', today.getTime()); // create date related data weekDays = weekDaysStr.split(','); months = monthsStr.split(','); // validate credentials fourKgadget_doValidateCredentials(); if (isValidationPassed) { // request application data fourKgadget_envelopeDataLoader(); } fourKgadget_trackUsage("Envelope"); }; var fourKgadget_trackUsage = function(action){ // track to GA var userName = fourKgadget_prefs.getString("login"); if(!userName || userName==""){ userName = "anonymus"; } fourKgadgetGA.reportEvent("4kgadget", action, userName); }; // application data loading function var fourKgadget_envelopeDataLoader = function() { document.getElementById('4kgadget_content').style.display='block'; var localEnvelopeUrl = envelopeUrl + fourKgadget_prefs.getString('login') + fourKgadget_prefs.getString('envelopeUrl') + weekBeginDate + '?' + today.getTime(); // request application data fourKgadget_RequestHandler(localEnvelopeUrl, fourKgadget_prefs .getMsg('envelopeLoading'), fourKgadget_handleEvelopeResponse); }; // envelope response handler var fourKgadget_handleEvelopeResponse = function(obj) { var isLoaded = false, errorMessage; if (obj.data) { var persons = obj.data.getElementsByTagName("person"); isLoaded = persons.length > 0; } //check whether authentication issue if (!isLoaded) { var errorDom = obj.data.getElementsByTagName("h2"); if (errorDom) { for ( var h2 = 0; h2 < errorDom.length; h2++) { var error = errorDom[h2].firstChild.nodeValue?errorDom[h2].firstChild.nodeValue:''; if (error.indexOf('401')) { errorMessage = fourKgadget_prefs.getMsg('error401'); break; } } } } //process after load if (isLoaded) { fourKgadget_generateEnvelope(obj.data); // recalculate gadget height gadgets.window.adjustHeight(); // hide loading message fourKgadget_msg.dismissMessage(statusMessage); } else { fourKgadget_msg.dismissMessage(statusMessage); if (errorMessage == undefined) { errorMessage = fourKgadget_prefs.getMsg('envelopeNotLoaded'); } statusMessage = fourKgadget_msg .createStaticMessage("<span class='errMessage'>" + errorMessage + "</span>"); } }; // parse given envelope date and create human readable string var fourKgadget_createEnvelopeDate = function(date) { var result = date; if (date) { var d, m, y, expDate = new Date(), _date = date.split('-'); d = _date[2]; y = _date[0]; m = _date[1]; expDate.setFullYear(y, (m - 1), (d-1)); result = weekDays[expDate.getDay()] + ", " + d + " " + months[expDate.getMonth()]; if (today.getDate() == d) { result = "<strong style='font-size:9pt;'>" + result + "</strong>"; } else { result = "<span style='font-size:9pt;'>" + result + "</span>"; } } return result; }; //main object var FourKGadget = function(){ this.currency = "grn", /** * The reference to Preference object. */ this.prefs = fourKgadget_prefs, this.msg = fourKgadget_msg, this.baseUrl = '', this.executionUrl = '', this.dailyExpenseUrl this.mode = '',//Test this.statusMessage = '', /** * Retrieve envelope size information. * @param dom the XML response */ this.getEnvelopeSize = function(dom){ var envelopeSize = 0; if (dom) { var envelopeList = dom.getElementsByTagName('envelope'); if (envelopeList && envelopeList[0]) { envelopeList = envelopeList[0]; envelopeSize = envelopeList.getAttribute("size"); } } return this._getEnvelopeSizeHtml(envelopeSize); }, this._getEnvelopeSizeHtml = function(envelopeSize){ return '<span class="envelopeSize">'+this.prefs.getMsg('envelopeSize')+": <strong>"+envelopeSize+"</strong>"+" "+this.currency+"</span>"; }, /** * Retrieve account data. */ this._retriveAccountData = function(){ var thisCopy = this, testMode = this.mode!=''?'/'+this.mode:''; this.requestHandler(this.baseUrl+this.prefs.getString('login')+testMode, null, function(resObj){ if (resObj && resObj.data) { var currency = resObj.data.getElementsByTagName("currency"); if (currency && currency[0]) { currency = currency[0]; thisCopy.currency = currency.firstChild.nodeValue; } } }); }, /** * AJAX request performer. */ this.requestHandler = function(url, message, callback, method) { // request application data var params = {}, headers = {}; if (method == undefined) { method = gadgets.io.MethodType.GET; } params[gadgets.io.RequestParameters.METHOD] = method; params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM; headers['4KAuth'] = this.prefs.getString('password'); headers['4KApplication'] = this.prefs.getString('apiKey'); params[gadgets.io.RequestParameters.HEADERS] = headers; if (callback == undefined) { callback = function() { }; } gadgets.io.makeRequest(url, callback, params); if (message) { this.statusMessage = this.createStaticMsg(message); } }, this.dismissMessage = function(msg){ this.msg.dismissMessage(msg); }, this.createStaticMsg = function(message){ this.msg.createStaticMessage("<span class='message'>" + message + "</span>"); }, this._getGoalExpenseList = function(dom, subject){ if (dom && subject) { var dataList = dom.getElementsByTagName(subject), resDataList = {}; if (dataList) { for(var i=0; i<dataList.length; i++){ var dataItem = dataList[i]; if (resDataList[dataItem.getAttribute('plannedDate')] == undefined) { resDataList[dataItem.getAttribute('plannedDate')] = new Array(); } if(subject == 'actualGoalCredit'){ resDataList[dataItem.getAttribute('plannedDate')].push(this._getGoalExpenseItem(dataItem.childNodes, 'goal')); } if (subject == 'actualExpense'){ resDataList[dataItem.getAttribute('plannedDate')].push(this._getGoalExpenseItem(dataItem.childNodes, 'expense')); } } } return resDataList; } return null; }, /** * Retrieve goal credits. * @param dom the XML response */ this.getGoalCredits = function(dom){ return this._getGoalExpenseList(dom, 'actualGoalCredit'); }, this.getExpenses = function(dom){ return this._getGoalExpenseList(dom, 'actualExpense'); }, /** * Analyze given XML nodes and return goal credit information. * @param nodes the XML nodes to work with */ this._getGoalExpenseItem = function(nodes, subject){ if (nodes && subject) { var goal = new Array(), len = nodes.length; for ( var i = 0; i < len; i++) { // get name if (nodes[i].nodeName == subject) { goal['name'] = nodes[i].getAttribute('name'); } // get value if (nodes[i].nodeName == 'planned' && nodes[i].firstChild) { goal['planned'] = nodes[i].firstChild.nodeValue; } } return goal; } return null; }, /** * Prepare HTML representation of the credit goals. * @param goals the credit goals of a day */ this.prepareGoalCreditHtml = function(goals, expenses, creditDate){ var html = ''; if (goals) { var len = goals.length; if (len>0) { html += '<strong>'+this.prefs.getMsg('goals')+'</strong>:<br/>'; } for ( var i = 0; i < len; i++) { if (i>0) { html += '<br/>'; } html += '<span><strong>'+goals[i].planned+' '+this.currency+'</strong> '+goals[i].name+'</span>'; } } if (expenses) { var len = expenses.length; if (len>0) { if (html != '') { html += '<br/>'; } html += '<strong>'+this.prefs.getMsg('regExpenses')+'</strong>:<br/>'; } for ( var i = 0; i < len; i++) { if (i>0) { html += '<br/>'; } html += '<span><strong>'+expenses[i].planned+' '+this.currency+'</strong> '+expenses[i].name+'</span>'; } } if (html != '') { html = '<div id="creditGoal_'+creditDate + '" class="creditGoal hint" style="visibility: hidden; position: absolute; left: 65px; z-index: 5000000; top: 5px; width: 220;">' + '<span style="position: absolute; left: 92%; top: 2px;"><img src="http://4kgadget.googlecode.com/svn/trunk/img/close_btn.gif" style="cursor:pointer; border:none; alt="'+this.prefs.getMsg('close')+'" title="'+this.prefs.getMsg('close')+'" onclick="fourKgadget_toggleCreditGoal(\''+creditDate+'\');"></span>' + html; html += '</div>'; } return html; }, /** * Init object. */ this.init = function(){ this.baseUrl = this.prefs.getString('baseUrl'+this.mode); this.executionUrl = this.baseUrl+this.prefs.getString('executionUrl'); this.dailyExpenseUrl = this.baseUrl+this.prefs.getString('dailyExpenseUrl'); //get account data this._retriveAccountData(); }, this.init() }; var fkg = new FourKGadget(); // generate envelope content var fourKgadget_generateEnvelope = function(dom) { var personList = dom.getElementsByTagName('person'), html = '', persons = new Array(), goalCredits = fkg.getGoalCredits(dom), regExpenses = fkg.getExpenses(dom), expenses = new Array(); html += fkg.getEnvelopeSize(dom); html += "<table>"; // gather header html += "<tr><th>" + fourKgadget_prefs.getMsg('date') + "</th>"; for ( var i = 0; i < personList.length; i++) { var personDom = personList.item(i); html += '<th colspan="2">' + personDom.getAttribute('name') + "</th>"; } html += "</tr>"; // gather expenses for ( var i = 0; i < personList.length; i++) { var personDom = personList.item(i); var personId = personDom.getAttribute('id'); // gather person expenses var personExpenses = new Array(), expensesList = personDom.childNodes; for ( var ex = 0; ex < expensesList.length; ex++) { var pHtml = '', expression = '', sum = '', expenseDate = ''; if (expensesList.item(ex).nodeName != "dailyExpense") continue; expenseDate = expensesList.item(ex).getAttribute("date"); // accept date if there is only one person if (i == 0) { pHtml += '<td><span style="${style}" title="'+fkg.prefs.getMsg('goalsAndExpenses')+'" onclick="fourKgadget_toggleCreditGoal(\''+expenseDate+'\');">' + fourKgadget_createEnvelopeDate(expenseDate)+'</span>'; if (goalCredits[expenseDate] || regExpenses[expenseDate]) { pHtml = pHtml.replace('${style}', 'cursor:pointer; text-decoration: underline;'); pHtml += fkg.prepareGoalCreditHtml(goalCredits[expenseDate], regExpenses[expenseDate], expenseDate); } pHtml += '</td>'; } for ( var exp = 0; exp < expensesList.item(ex).childNodes.length; exp++) { if (expensesList.item(ex).childNodes[exp].nodeName == "expression" && expensesList.item(ex).childNodes[exp].firstChild) { expression = expensesList.item(ex).childNodes[exp].firstChild.nodeValue; } if (expensesList.item(ex).childNodes[exp].nodeName == "sum" && expensesList.item(ex).childNodes[exp].firstChild) { sum = expensesList.item(ex).childNodes[exp].firstChild.nodeValue; if (sum == "0") { sum = "-"; } } } pHtml += '<td align="center">&nbsp;&nbsp;&nbsp;<span id="sumHolder_' + expenseDate + '_' + personId + '">' + sum + '</span></td>'; pHtml += '<td><img src="http://4kgadget.googlecode.com/svn/trunk/img/edit.jpg" class="ie6pngfix" title="' + fourKgadget_prefs.getMsg('extendedEdit') + '" alt="' + fourKgadget_prefs.getMsg('extendedEdit') + '" onclick="fourKgadget_showExpenseEditor(\'' + expenseDate + '_' + personId + '\')" style="cursor:pointer;"/>'; pHtml += '<span id="exprHolder_' + expenseDate + '_' + personId + '" style="display:none;">' + expression + '</span></td>'; // store expense personExpenses.push(pHtml); } expenses.push(personExpenses); } // generate expenses html for (d = 0; d <= 6; d++) { html += "<tr>"; for ( var p = 0; p < expenses.length; p++) { html += expenses[p][d]; } html += "</tr>"; } // write data var contentContainer = document.getElementById('4kgadget_content'); contentContainer.innerHTML = html + "</table>"; }; var fourKgadget_toggleCreditGoal = function(creditDay){ if (creditDay) { var container = document.getElementById('creditGoal_'+creditDay), visibileContainer = document.getElementById('visibleCreditGoalId'); var visibileContainerId = visibileContainer.innerHTML; if(visibileContainerId != '' && visibileContainerId != container.id){ document.getElementById(visibileContainerId).style.visibility = 'hidden'; } if (container && container.style.visibility == 'visible') { container.style.visibility = 'hidden'; } else { container.style.visibility = 'visible'; container.style.top = container.parentNode.offsetTop+18; visibileContainer.innerHTML = container.id; } } }; // show expense editor var fourKgadget_showExpenseEditor = function(expenseContainerId) { var editor = document.getElementById('4kgadget_EnvelopeExpressionPopup'), sum = document.getElementById('sumHolder_' + expenseContainerId), exp = document.getElementById('exprHolder_' + expenseContainerId), expenseEditor = document.getElementById('4kgadget_editExpression'); editor.style.visibility = "visible"; var value = exp.innerHTML; if (value == "-") { value = ""; } expenseEditor.value = ''; expenseEditor.value = value; // set active person id ACTIVE_EXPENSE = expenseContainerId; // recalculate gadget height fourKgadget_recalculateOnExpenseChange(); }; // show form to enter credentials var fourKgadget_doValidateCredentials = function() { var fourKgadget_login = fourKgadget_prefs.getString("login"), fourKgadget_password = fourKgadget_prefs .getString("password"); if ((!fourKgadget_login && !fourKgadget_password) || (fourKgadget_login !== "" && fourKgadget_password == "")) { var credentialsContainer = document .getElementById('4kgadget_credentialsForm'); credentialsContainer.style.display = "block"; } else { isValidationPassed = true; } }; // persist credentials var fourKgadget_saveCredentials = function() { var login = document.getElementById('fourKgadget_login').value, password = document .getElementById('fourKgadget_password').value; if(login == "" && password == ""){ fourKgadget_msg.createTimerMessage(fourKgadget_prefs.getMsg('input_credentials'), 5); return; } fourKgadget_prefs.set('login', login); fourKgadget_prefs.set('password', password); var message = fourKgadget_msg .createTimerMessage( fourKgadget_prefs.getMsg('credentialsSaved'), 2, function() { // hide credentials form var credentialsContainer = document .getElementById('4kgadget_credentialsForm').style.display = "none"; // load data fourKgadget_envelopeDataLoader(); // hide message fourKgadget_msg.dismissMessage(message); }); }; // visibility handler var fourKgadget_toggleVisibility = function() { var helpContainer = document .getElementById('4kgadget_moreExpressionSamples'); var state = helpContainer.style.display; if (state == 'none') { helpContainer.style.display = 'block'; } else { helpContainer.style.display = 'none'; } }; // save expense handler var fourKgadget_saveExpenseHandler = function() { // hide expression edit dialog fourKgadget_cancelExpenseHandler(); var expression = document.getElementById('4kgadget_editExpression').value, expenseData = ACTIVE_EXPENSE .split('_'), localDailyExpenseUrl = ''; localDailyExpenseUrl += dailyExpenseUrl + fourKgadget_prefs.getString('login') + fourKgadget_prefs.getString('dailyExpenseUrl') + expenseData[1] + '/' + expenseData[0]; localDailyExpenseUrl += '?expression=' + encodeURI(expression); fourKgadget_RequestHandler( localDailyExpenseUrl, fourKgadget_prefs.getMsg('expenseSaving'), function(obj) { var domdata = obj.data; if (domdata) { var expense = domdata.getElementsByTagName("dailyExpense") .item(0), sum = 0, expression = '', sum = document .getElementById('sumHolder_' + ACTIVE_EXPENSE), exp = document .getElementById('exprHolder_' + ACTIVE_EXPENSE); for ( var i = 0; i < expense.childNodes.length; i++) { if (expense.childNodes[i].nodeName == 'expression' && expense.childNodes[i].firstChild) { exp.innerHTML = expense.childNodes[i].firstChild.nodeValue } if (expense.childNodes[i].nodeName == 'sum' && expense.childNodes[i].firstChild) { sum.innerHTML = expense.childNodes[i].firstChild.nodeValue } } // hide message fourKgadget_msg.dismissMessage(statusMessage); } else { fourKgadget_msg.createTimerMessage(fourKgadget_prefs .getMsg('expenseSaveFailed'), 4); } }, gadgets.io.MethodType.POST); // track usage fourKgadget_trackUsage("Save Expense"); }; // function to perform remote requests var fourKgadget_RequestHandler = function(url, message, callback, method) { // request application data var params = {}, headers = {}; if (method == undefined) { method = gadgets.io.MethodType.GET; } params[gadgets.io.RequestParameters.METHOD] = method; params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM; headers['4KAuth'] = fourKgadget_prefs.getString('password'); headers['4KApplication'] = fourKgadget_prefs.getString('apiKey'); params[gadgets.io.RequestParameters.HEADERS] = headers; if (callback == undefined) { callback = function() { }; } gadgets.io.makeRequest(url, callback, params); statusMessage = fourKgadget_msg .createStaticMessage("<span class='message'>" + message + "</span>"); }; // cancle button on expense expression handler var fourKgadget_cancelExpenseHandler = function() { var editor = document.getElementById('4kgadget_EnvelopeExpressionPopup'); editor.style.visibility = "hidden"; // recalculate gadget height fourKgadget_recalculateOnExpenseChange(); }; var isHeighEncreased = false; // recalculate gadget size on expense input var fourKgadget_recalculateOnExpenseChange = function() { var currHeight = gadgets.window.getViewportDimensions().height; if (currHeight < 250) { gadgets.window.adjustHeight(currHeight + 30); isHeighEncreased = true; } if (currHeight > 250 && isHeighEncreased) { gadgets.window.adjustHeight(currHeight - 30); } }; // reset credentials var fourKgadget_resetCredentials = function() { // reset credentials fourKgadget_prefs.set('login', ''); fourKgadget_prefs.set('password', ''); // hide content view var contentContainer = document.getElementById('4kgadget_content'), credentialsContainer = document .getElementById('4kgadget_credentialsForm'); contentContainer.style.display = "none"; // show enter credentials form if (credentialsContainer.style.display == "none") { credentialsContainer.style.display = "block"; } var login = document.getElementById('fourKgadget_login').value = '', password = document .getElementById('fourKgadget_password').value = ''; gadgets.window.adjustHeight(250); }; // register credentials validation handler gadgets.util.registerOnLoadHandler(fourKgadget_startApplication);
JavaScript
//create MiniMessage var fourKgadget_msg = new gadgets.MiniMessage(), // Get userprefs fourKgadget_prefs = new gadgets.Prefs(), weekDays = new Array(), months = new Array(), isValidationPassed = false, statusMessage = null, today = new Date(), ACTIVE_EXPENSE = 0; // returns envelope begin date var fourKgadget_getEnvelopeBegin = function() { var d = today.getDate() + 1, m = today.getMonth() + 1; if (d < 10) { d = '0' + d; } if (m < 10) { m = '0' + m; } return today.getFullYear() + '-' + m + '-' + d; }; var weekBeginDate = fourKgadget_getEnvelopeBegin(); // define base URL var envelopeUrl = fourKgadget_prefs.getString('baseUrl'), dailyExpenseUrl = fourKgadget_prefs .getString('baseUrl'); // application starter var fourKgadget_startApplication = function() { // change noCacheId fourKgadget_prefs.set('noCacheId', today.getTime()); // create date related data weekDays = weekDaysStr.split(','); months = monthsStr.split(','); // validate credentials fourKgadget_doValidateCredentials(); if (isValidationPassed) { // request application data fourKgadget_envelopeDataLoader(); } }; // application data loading function var fourKgadget_envelopeDataLoader = function() { document.getElementById('4kgadget_content').style.display='block'; var localEnvelopeUrl = envelopeUrl + fourKgadget_prefs.getString('login') + fourKgadget_prefs.getString('envelopeUrl') + weekBeginDate + '?' + today.getTime(); // request application data fourKgadget_RequestHandler(localEnvelopeUrl, fourKgadget_prefs .getMsg('envelopeLoading'), fourKgadget_handleEvelopeResponse); }; // envelope response handler var fourKgadget_handleEvelopeResponse = function(obj) { var isLoaded = false, errorMessage; if (obj.data) { var persons = obj.data.getElementsByTagName("person"); isLoaded = persons.length > 0; } //check whether authentication issue if (!isLoaded) { var errorDom = obj.data.getElementsByTagName("h2"); if (errorDom) { for ( var h2 = 0; h2 < errorDom.length; h2++) { var error = errorDom[h2].firstChild.nodeValue?errorDom[h2].firstChild.nodeValue:''; if (error.indexOf('401')) { errorMessage = fourKgadget_prefs.getMsg('error401'); break; } } } } //process after load if (isLoaded) { fourKgadget_generateEnvelope(obj.data); // recalculate gadget height gadgets.window.adjustHeight(); // hide loading message fourKgadget_msg.dismissMessage(statusMessage); } else { fourKgadget_msg.dismissMessage(statusMessage); if (errorMessage == undefined) { errorMessage = fourKgadget_prefs.getMsg('envelopeNotLoaded'); } statusMessage = fourKgadget_msg .createStaticMessage("<span class='errMessage'>" + errorMessage + "</span>"); } }; // parse given envelope date and create human readable string var fourKgadget_createEnvelopeDate = function(date) { var result = date; if (date) { var d, m, y, expDate = new Date(), _date = date.split('-'); d = _date[2]; y = _date[0]; m = _date[1]; expDate.setFullYear(y, (m - 1), (d - 1)); result = weekDays[expDate.getDay()] + ", " + expDate.getDate() + " " + months[expDate.getMonth()]; if (today.getDay() == expDate.getDay()) { result = "<strong style='font-size:9pt;'>" + result + "</strong>"; } else { result = "<span style='font-size:9pt;'>" + result + "</span>"; } } return result; }; // generate envelope content var fourKgadget_generateEnvelope = function(dom) { var personList = dom.getElementsByTagName("person"), html = "<table>", persons = new Array(); // gather header html += "<tr><th>" + fourKgadget_prefs.getMsg('date') + "</th>"; for ( var i = 0; i < personList.length; i++) { var personDom = personList.item(i); html += '<th colspan="2">' + personDom.getAttribute("name") + "</th>"; } html += "</tr>"; // gather expenses var expenses = new Array(); for ( var i = 0; i < personList.length; i++) { var personDom = personList.item(i); var personId = personDom.getAttribute("id"); // gather person expenses var personExpenses = new Array(), expensesList = personDom.childNodes; for ( var ex = 0; ex < expensesList.length; ex++) { var pHtml = "", expression = "", sum = ""; if (expensesList.item(ex).nodeName != "dailyExpense") continue; var expenseDate = expensesList.item(ex).getAttribute("date"); // accept date if there is only one person if (i == 0) { pHtml += "<td>" + fourKgadget_createEnvelopeDate(expenseDate) + "</td>"; } for ( var exp = 0; exp < expensesList.item(ex).childNodes.length; exp++) { if (expensesList.item(ex).childNodes[exp].nodeName == "expression" && expensesList.item(ex).childNodes[exp].firstChild) { expression = expensesList.item(ex).childNodes[exp].firstChild.nodeValue; } if (expensesList.item(ex).childNodes[exp].nodeName == "sum" && expensesList.item(ex).childNodes[exp].firstChild) { sum = expensesList.item(ex).childNodes[exp].firstChild.nodeValue; if (sum == "0") { sum = "-"; } } } pHtml += '<td align="center">&nbsp;&nbsp;&nbsp;<span id="sumHolder_' + expenseDate + '_' + personId + '">' + sum + '</span></td>'; pHtml += '<td><img src="http://www.4konverta.com/img/edit.png" class="ie6pngfix" title="' + fourKgadget_prefs.getMsg('extendedEdit') + '" alt="' + fourKgadget_prefs.getMsg('extendedEdit') + '" onclick="fourKgadget_showExpenseEditor(\'' + expenseDate + '_' + personId + '\')" style="cursor:pointer;"/>'; pHtml += '<span id="exprHolder_' + expenseDate + '_' + personId + '" style="display:none;">' + expression + '</span></td>'; // store expense personExpenses.push(pHtml); } expenses.push(personExpenses); } // generate expenses html for (d = 0; d <= 6; d++) { html += "<tr>"; for ( var p = 0; p < expenses.length; p++) { html += expenses[p][d]; } html += "</tr>"; } // write data var contentContainer = document.getElementById('4kgadget_content'); contentContainer.innerHTML = html + "</table>"; }; // show expense editor var fourKgadget_showExpenseEditor = function(expenseContainerId) { var editor = document.getElementById('4kgadget_EnvelopeExpressionPopup'), sum = document .getElementById('sumHolder_' + expenseContainerId), exp = document .getElementById('exprHolder_' + expenseContainerId), expenseEditor = document .getElementById('4kgadget_editExpression'); editor.style.visibility = "visible"; var value = exp.innerHTML; if (value == "-") { value = ""; } expenseEditor.value = ''; expenseEditor.value = value; // set active person id ACTIVE_EXPENSE = expenseContainerId; // recalculate gadget height fourKgadget_recalculateOnExpenseChange(); }; // show form to enter credentials var fourKgadget_doValidateCredentials = function() { var fourKgadget_login = fourKgadget_prefs.getString("login"), fourKgadget_password = fourKgadget_prefs .getString("password"); if ((!fourKgadget_login && !fourKgadget_password) || (fourKgadget_login !== "" && fourKgadget_password == "")) { var credentialsContainer = document .getElementById('4kgadget_credentialsForm'); credentialsContainer.style.display = "block"; } else { isValidationPassed = true; } }; // persist credentials var fourKgadget_saveCredentials = function() { var login = document.getElementById('fourKgadget_login').value, password = document .getElementById('fourKgadget_password').value; fourKgadget_prefs.set('login', login); fourKgadget_prefs.set('password', password); var message = fourKgadget_msg .createTimerMessage( fourKgadget_prefs.getMsg('credentialsSaved'), 2, function() { // hide credentials form var credentialsContainer = document .getElementById('4kgadget_credentialsForm').style.display = "none"; // load data fourKgadget_envelopeDataLoader(); // hide message fourKgadget_msg.dismissMessage(message); }); }; // visibility handler var fourKgadget_toggleVisibility = function() { var helpContainer = document .getElementById('4kgadget_moreExpressionSamples'); var state = helpContainer.style.display; if (state == 'none') { helpContainer.style.display = 'block'; } else { helpContainer.style.display = 'none'; } }; // save expense handler var fourKgadget_saveExpenseHandler = function() { // hide expression edit dialog fourKgadget_cancelExpenseHandler(); var expression = document.getElementById('4kgadget_editExpression').value, expenseData = ACTIVE_EXPENSE .split('_'), localDailyExpenseUrl = ''; localDailyExpenseUrl += dailyExpenseUrl + fourKgadget_prefs.getString('login') + fourKgadget_prefs.getString('dailyExpenseUrl') + expenseData[1] + '/' + expenseData[0]; localDailyExpenseUrl += '?expression=' + encodeURI(expression); fourKgadget_RequestHandler( localDailyExpenseUrl, fourKgadget_prefs.getMsg('expenseSaving'), function(obj) { var domdata = obj.data; if (domdata) { var expense = domdata.getElementsByTagName("dailyExpense") .item(0), sum = 0, expression = '', sum = document .getElementById('sumHolder_' + ACTIVE_EXPENSE), exp = document .getElementById('exprHolder_' + ACTIVE_EXPENSE); for ( var i = 0; i < expense.childNodes.length; i++) { if (expense.childNodes[i].nodeName == 'expression' && expense.childNodes[i].firstChild) { exp.innerHTML = expense.childNodes[i].firstChild.nodeValue } if (expense.childNodes[i].nodeName == 'sum' && expense.childNodes[i].firstChild) { sum.innerHTML = expense.childNodes[i].firstChild.nodeValue } } // hide message fourKgadget_msg.dismissMessage(statusMessage); } else { fourKgadget_msg.createTimerMessage(fourKgadget_prefs .getMsg('expenseSaveFailed'), 4); } }, gadgets.io.MethodType.POST); }; // function to perform remote requests var fourKgadget_RequestHandler = function(url, message, callback, method) { // request application data var params = {}, headers = {}; if (method == undefined) { method = gadgets.io.MethodType.GET; } params[gadgets.io.RequestParameters.METHOD] = method; params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM; headers['4KAuth'] = fourKgadget_prefs.getString('password'); headers['4KApplication'] = fourKgadget_prefs.getString('apiKey'); params[gadgets.io.RequestParameters.HEADERS] = headers; if (callback == undefined) { callback = function() { }; } gadgets.io.makeRequest(url, callback, params); statusMessage = fourKgadget_msg .createStaticMessage("<span class='message'>" + message + "</span>"); }; // cancle button on expense expression handler var fourKgadget_cancelExpenseHandler = function() { var editor = document.getElementById('4kgadget_EnvelopeExpressionPopup'); editor.style.visibility = "hidden"; // recalculate gadget height fourKgadget_recalculateOnExpenseChange(); }; var isHeighEncreased = false; // recalculate gadget size on expense input var fourKgadget_recalculateOnExpenseChange = function() { var currHeight = gadgets.window.getViewportDimensions().height; if (currHeight < 250) { gadgets.window.adjustHeight(currHeight + 50); isHeighEncreased = true; } if (currHeight > 250 && isHeighEncreased) { gadgets.window.adjustHeight(currHeight - 50); } }; // reset credentials var fourKgadget_resetCredentials = function() { // reset credentials fourKgadget_prefs.set('login', ''); fourKgadget_prefs.set('password', ''); // hide content view var contentContainer = document.getElementById('4kgadget_content'), credentialsContainer = document .getElementById('4kgadget_credentialsForm'); contentContainer.style.display = "none"; // show enter credentials form if (credentialsContainer.style.display == "none") { credentialsContainer.style.display = "block"; } var login = document.getElementById('fourKgadget_login').value = '', password = document .getElementById('fourKgadget_password').value = ''; gadgets.window.adjustHeight(); }; // register credentials validation handler gadgets.util.registerOnLoadHandler(fourKgadget_startApplication);
JavaScript
inspector4pda.cScript = { winobj: null, updateTimer: 0, prevData: { themes: {}, QMS: {} }, requestsCount: 0, notifications: [], init: function(el) { var obj = document.getElementById("navigator-toolbox"); inspector4pda.cScript.winobj = (obj) ? window.document : window.opener.document; inspector4pda.cScript.request(); }, request: function(interval) { inspector4pda.vars.getPrefs(); inspector4pda.utils.log(new Date().toString()); clearTimeout(inspector4pda.cScript.updateTimer); inspector4pda.cScript.getData(); inspector4pda.cScript.updateTimer = setTimeout(function() { inspector4pda.cScript.request(); }, (interval || inspector4pda.vars.interval)); }, getData: function(callback) { var finishCallback = function(){ inspector4pda.cScript.printCount(); if (inspector4pda.cScript.requestsCount++) { inspector4pda.cScript.checkNews(); } if (callback) { callback(); }; }; this.prevData.themes = inspector4pda.themes.list; this.prevData.QMS = inspector4pda.QMS.list; inspector4pda.user.request(function() { if (inspector4pda.user.id) { inspector4pda.themes.request(function() { inspector4pda.QMS.request(finishCallback); }); } else { inspector4pda.cScript.requestsCount = 0; if (finishCallback) { finishCallback(); } } }); }, printCount: function() { if (!inspector4pda.user.id) { this.printLogout(); return; } var qCount = inspector4pda.QMS.getCount(); var tCount = inspector4pda.themes.getCount(); var btn = inspector4pda.cScript.winobj.getElementById('inspector4pda_button'); if (!btn) { return false; } var canvas_width = 20; var canvas_height = 18; var canvas_img = "chrome://4pdainspector/content/icons/icon_16x.png"; var title_padding = 2; var fontSize = inspector4pda.vars.button_fontsize; if (inspector4pda.vars.button_big) { var canvas_width = 26; var canvas_height = 24; var canvas_img = "chrome://4pdainspector/content/icons/icon_22x.png"; } var button_bgcolor = inspector4pda.vars.button_bgcolor; var button_color = inspector4pda.vars.button_color; var canvas = inspector4pda.cScript.winobj.getElementById("inspector4pda_canvas"); canvas.setAttribute("width", canvas_width); canvas.setAttribute("height", canvas_height); var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = function() { ctx.textBaseline = 'top'; ctx.font = 'bold '+fontSize+'px tahoma,sans-serif,arial'; ctx.clearRect(0, 0, canvas_width, canvas_height); ctx.drawImage(img, 2, 0, img.width, img.height); var w = ctx.measureText(tCount).width; var h = fontSize + title_padding; var x = canvas_width - w; var y = canvas_height - h; if (inspector4pda.vars.button_show_themes) { ctx.fillStyle = button_bgcolor; ctx.fillRect(x-1, y, w+1, h); ctx.fillStyle = button_color; ctx.fillText(tCount, x, y+1); } if (inspector4pda.vars.button_show_qms) { var w = ctx.measureText(qCount).width; ctx.fillStyle = button_bgcolor; ctx.fillRect(0, y, w+2, h); ctx.fillStyle = button_color; ctx.fillText(qCount, 1, y+1); }; btn.image = canvas.toDataURL("image/png"); }; img.src = canvas_img; btn.setAttribute('tooltiptext', inspector4pda.utils.getString("4PDA_online") + '\n' + inspector4pda.utils.getString("Unread Topics") + ': ' + tCount + '\n' + inspector4pda.utils.getString("New Messages") + ': ' + qCount ); }, printLogout: function(unavailable) { var btn = inspector4pda.cScript.winobj.getElementById('inspector4pda_button'); if (btn) { btn.image = 'chrome://4pdainspector/content/icons/icon_' + ((inspector4pda.vars.button_big) ? '22' : '16') + 'x_out.png'; btn.setAttribute('tooltiptext', unavailable? inspector4pda.utils.getString("4PDA_Site Unavailable"): inspector4pda.utils.getString("4PDA_offline") ); } }, checkNews: function () { // this.prevData.themes = inspector4pda.themes.list; var hasNews = false; if (!(inspector4pda.vars.notification_popup || inspector4pda.vars.notification_sound)) { return false; } for (var i in inspector4pda.QMS.list) { var addNot = false if (typeof inspector4pda.cScript.prevData.QMS[i] == 'undefined') { addNot = true; } else { if (inspector4pda.cScript.prevData.QMS[i].unread_msgs < inspector4pda.QMS.list[i].unread_msgs) { addNot = true; } } if (addNot) { hasNews = true; inspector4pda.cScript.notifications.push({ title: inspector4pda.utils.getString('New Message'), body: inspector4pda.QMS.list[i].opponent_id? inspector4pda.utils.htmlspecialcharsdecode(inspector4pda.QMS.list[i].opponent_name) + ' (' + inspector4pda.utils.htmlspecialcharsdecode(inspector4pda.QMS.list[i].title) + ')': inspector4pda.utils.htmlspecialcharsdecode(inspector4pda.QMS.list[i].title), type: 'qms', id: inspector4pda.QMS.list[i].opponent_id + '_' + inspector4pda.QMS.list[i].id }); }; } for (var i in inspector4pda.themes.list) { if (typeof inspector4pda.cScript.prevData.themes[i] == 'undefined') { hasNews = true; inspector4pda.cScript.notifications.push({ title: inspector4pda.utils.getString('New Comment'), body: inspector4pda.utils.htmlspecialcharsdecode(inspector4pda.themes.list[i].title), type: 'theme', id: i }); } } if (hasNews) { if (inspector4pda.vars.notification_sound) { var soundElement = this.winobj.getElementById("inspector4pda_sound"); soundElement.volume = inspector4pda.vars.notification_sound_volume; soundElement.play(); }; if (inspector4pda.vars.notification_popup) { this.showNotifications(); }; }; }, showNotifications: function() { if (!this.notifications.length) return false; var currentNotification = this.notifications.shift(); var notification = new Notification(currentNotification.title, { tag : "4pdainspector_" + currentNotification.type + '_' + currentNotification.id, body : currentNotification.body, icon : "chrome://4pdainspector/content/icons/icon_64.png" }); notification.onclick = function() { var tagData = this.tag.split('_'); if (typeof tagData[1] == 'undefined' || typeof tagData[2] == 'undefined') { ulog(this.tag); return false; } if (tagData[1] == 'qms'){ inspector4pda.QMS.openDialog(parseInt(tagData[2]), (typeof tagData[3] == 'undefined' ? false : parseInt(tagData[3]))); } else { inspector4pda.themes.open(parseInt(tagData[2])); } inspector4pda.cScript.printCount(); } setTimeout(function() { inspector4pda.cScript.showNotifications(); }, 50); }, firstRun: function(extensions) { var id = "inspector4pda_button"; var extension = extensions.get("4pda_inspector_beta@coddism.com"); if (extension.firstRun) { var toolbar = document.getElementById("nav-bar"); if (toolbar.getElementsByAttribute('id', "inspector4pda_button").length) { //кнопка уже добавлена return false; } toolbar.insertItem(id, null, null, false); toolbar.setAttribute("currentset", toolbar.currentSet); document.persist(toolbar.id, "currentset"); toolbar.collapsed = false; } } }; if (Application.extensions) { inspector4pda.cScript.firstRun(Application.extensions); } else { Application.getExtensions(inspector4pda.cScript.firstRun); } inspector4pda.cScript.init();
JavaScript
if (typeof inspector4pda == "undefined") { var inspector4pda = {} } inspector4pda.utils = { consoleService: null, stringBundle: null, firebugConsoleService: null, parseStringRexp: /([^\s"']+|"([^"]*)"|'([^']*)')/g, log: function(msg, json) { if (this.consoleService == null) { this.consoleService = Components.classes["@mozilla.org/consoleservice;1"] .getService(Components.interfaces.nsIConsoleService); } if (json) msg = JSON.stringify(msg); this.consoleService.logStringMessage(msg); }, flog: function(msg) { if (this.firebugConsoleService == null) { this.firebugConsoleService = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIWebNavigation) .QueryInterface(Components.interfaces.nsIDocShellTreeItem) .rootTreeItem .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindow).Firebug; } this.firebugConsoleService.Console.log(msg); }, parse: function(str) { var parsed = str.match(this.parseStringRexp); var pq = ''; for (var i = 0; i < parsed.length; i++) { if (pq = parsed[i].match(/\"(.*)\"/)) { parsed[i] = pq[1]; }; }; return parsed; }, checkNotificationSupport: function() { try { Notification.permission; return true; } catch(e) { return false; } }, htmlspecialcharsdecode: function (string = '') { var codes = string.match(/&#(\d+);/g); if (codes) { for (var i = 0; i < codes.length; i++) { var code = codes[i].match(/\d+/g); string = string.replace(new RegExp(codes[i], 'g'), String.fromCharCode(code)); } } string = string.replace(/&lt;/g, '<'); string = string.replace(/&gt;/g, '>'); string = string.replace(/&quot;/g, '"'); string = string.replace(/&amp;/g, '&'); return string; }, openPage: function(page) { var tBrowser = top.document.getElementById("content"); var tab = tBrowser.addTab(page); tBrowser.selectedTab = tab; }, setStringBundle: function() { inspector4pda.utils.stringBundle = (typeof Services == 'object') ? Services.strings.createBundle("chrome://4pdainspector/locale/strings.properties") : null }, getString: function(name) { if (!inspector4pda.utils.stringBundle) { this.setStringBundle(); }; if (inspector4pda.utils.stringBundle) { return inspector4pda.utils.stringBundle.GetStringFromName(name); } else { return name; } } }; if (typeof ulog == "undefined") { function ulog(text, json) { inspector4pda.utils.log(text, json); } }
JavaScript
inspector4pda.user = { rUrl: 'http://4pda.ru/forum/index.php?act=inspector&CODE=id', id: 0, name: '', request: function(callback) { var xmr = new inspector4pda.XHR(); xmr.callback.timeout = function() { inspector4pda.cScript.printLogout(true); } xmr.callback.not200Success = function() { inspector4pda.cScript.printLogout(true); } xmr.callback.error = function() { inspector4pda.cScript.printLogout(); } xmr.callback.success = function(resp) { inspector4pda.user.id = 0; inspector4pda.user.name = ''; if (resp.responseText) { var res = inspector4pda.utils.parse(resp.responseText); if (res.length == 2) { inspector4pda.user.id = res[0]; inspector4pda.user.name = res[1]; }; } else { inspector4pda.cScript.printLogout(); } if (callback) { callback(); }; } xmr.send(this.rUrl); }, open: function(id) { inspector4pda.utils.openPage('http://4pda.ru/forum/index.php?showuser=' + id); } }
JavaScript
inspector4pda.themes = { rUrl: 'http://4pda.ru/forum/index.php?act=inspector&CODE=fav', vUrl: 'http://4pda.ru/forum/index.php?autocom=favtopics', list: {}, request: function(callback) { var xmr = new inspector4pda.XHR(); xmr.callback.success = function(resp) { if (resp.responseText) { inspector4pda.themes.parse(resp.responseText); }; if (callback) { callback(); }; } xmr.send(inspector4pda.themes.rUrl); }, getCount: function() { return Object.keys(inspector4pda.themes.list).length; }, parse: function(text) { inspector4pda.themes.list = {}; var tText = text.replace('\r','').split('\n'); if (inspector4pda.vars.toolbar_pin_up) { var notPin = []; } for (var i = 0; i < tText.length; i++) { if (tText[i]) { var theme = Object.create(themeObj); if (theme.parse(tText[i])) { if (inspector4pda.vars.toolbar_only_pin) { if (!theme.pin) { continue; } }; if (inspector4pda.vars.toolbar_pin_up) { if (theme.pin) { inspector4pda.themes.list[theme.id] = theme; } else { notPin.push(theme); } } else { inspector4pda.themes.list[theme.id] = theme; } } } } if (inspector4pda.vars.toolbar_pin_up && notPin) { for (var i = 0; i < notPin.length; i++) { inspector4pda.themes.list[notPin[i].id] = notPin[i]; }; } }, open: function(id) { inspector4pda.utils.openPage('http://4pda.ru/forum/index.php?showtopic='+id+'&view=getnewpost'); delete inspector4pda.themes.list[id]; }, read: function(id, callback) { var xmr = new inspector4pda.XHR(); xmr.send('http://4pda.ru/forum/index.php?showtopic='+id); delete inspector4pda.themes.list[id]; if (typeof callback == 'function') { callback(); }; }, openLast: function(id) { inspector4pda.utils.openPage('http://4pda.ru/forum/index.php?showtopic='+id+'&view=getlastpost'); delete inspector4pda.themes.list[id]; }, openAll: function() { var themesIds = Object.keys(inspector4pda.themes.list); for (var i = 0; i < themesIds.length; i++) { inspector4pda.themes.open(themesIds[i]); }; inspector4pda.themes.list = {}; }, readAll: function() { var themesIds = Object.keys(inspector4pda.themes.list); for (var i = 0; i < themesIds.length; i++) { inspector4pda.themes.read(themesIds[i]); }; inspector4pda.themes.list = {}; }, } var themeObj = { id: 0, title: '', posts_num: '', last_user_id: '', last_user_name: '', last_post_ts: '', last_read_ts: '', pin: false, parse: function(text) { try { var obj = inspector4pda.utils.parse(text); this.id = obj[0]; this.title = obj[1]; this.posts_num = obj[2]; this.last_user_id = obj[3]; this.last_user_name = obj[4]; this.last_post_ts = obj[5]; this.last_read_ts = obj[6]; this.pin = parseInt(obj[7]); } catch(e) { return false; } return this; // tid title posts_num last_user_id last_user_name last_post_ts last_read_ts } }
JavaScript
inspector4pda.XHR = function () { this.callback = { success: function(){}, error: function(){}, timeout: function(){}, not200Success: function(){} }; this.timeoutTime = 3000; this.send = function(url) { var self = this; var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status == 200) { self.callback.success(req); } else { self.callback.not200Success(req); } } } req.onerror = function() { self.callback.error(); } if (self.timeoutTime) { req.timeout = self.timeoutTime; req.ontimeout = function () { self.callback.timeout(); } }; req.open("GET", url, true); req.send(null); }; }
JavaScript
inspector4pda.QMS = { unreadCount: 0, count: { messages: 0, dialogs: 0 }, rUrl: 'http://4pda.ru/forum/index.php?act=inspector&CODE=qms', list: {}, request: function(callback) { var xmr = new inspector4pda.XHR(); xmr.callback.success = function(resp) { inspector4pda.QMS.parse(resp.responseText); if (callback) { callback(); }; } xmr.send(inspector4pda.QMS.rUrl); }, parse: function(text) { inspector4pda.QMS.count.messages = 0; inspector4pda.QMS.count.dialogs = 0; inspector4pda.QMS.unreadCount = 0; inspector4pda.QMS.list = {}; var tText = text ? text.replace('\r','').split('\n') : []; for (var i = 0; i < tText.length; i++) { if (tText[i]) { var dialog = Object.create(qDialog); if (dialog.parse(tText[i])) { inspector4pda.QMS.list[dialog.id] = dialog; inspector4pda.QMS.count.messages += dialog.unread_msgs; inspector4pda.QMS.count.dialogs++; } } } inspector4pda.QMS.unreadCount = inspector4pda.QMS.count.dialogs; }, openDialog: function(dialogID, themeID) { inspector4pda.utils.openPage('http://4pda.ru/forum/index.php?act=qms&mid=' + dialogID + (themeID ? '&t=' + themeID : '')); if (themeID) { delete inspector4pda.QMS.list[themeID]; }; }, getCount: function() { this.unreadCount = Object.keys(inspector4pda.QMS.list).length; return this.unreadCount; } } var qDialog = { id: 0, title: '', opponent_id: '', opponent_name: '', last_msg_ts: '', unread_msgs: 0, last_msg_id: '', parse: function(text) { try { var obj = inspector4pda.utils.parse(text); this.id = obj[0]; this.title = obj[1]; this.opponent_id = obj[2]; this.opponent_name = obj[3]; this.last_msg_ts = obj[4]; this.unread_msgs = parseInt(obj[5]); this.last_msg_id = obj[6]; } catch(e) { return false; } return this; // tid title posts_num last_user_id last_user_name last_post_ts last_read_ts } }
JavaScript
inspector4pda.vars = { interval: 5000, click_action: 1, notification_sound: true, notification_popup: true, notification_sound_volume: 1, toolbar_pin_color: true, toolbar_pin_up: false, toolbar_only_pin: false, toolbar_opentheme_hide: false, toolbar_opentheme_hide_onlylast: false, toolbar_simple_list: false, button_big: false, button_bgcolor: '#3333FF', button_color: '#FFFFFF', button_fontsize: 8, button_show_qms: true, button_show_themes: true, osString: '', prefs: {}, getPrefs: function() { this.osString = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).OS; this.prefs = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService) .getBranch("extensions.4pda-inspector."); this.prefs.QueryInterface(Components.interfaces.nsIPrefBranch); this.prefs.addObserver("", this, false); var toolbar = document.getElementById("nav-bar"); this.button_big = toolbar ? (toolbar.getAttribute('iconsize') != 'small') || inspector4pda.vars.prefs.getBoolPref('button_big') : inspector4pda.vars.prefs.getBoolPref('button_big'); this.resetStorage(); }, resetStorage: function() { this.getValue('interval', 5000, 1000); this.getValue('click_action', 1); this.getValue('button_bgcolor', '#3333FF'); this.getValue('button_color', '#FFFFFF'); this.getValue('button_fontsize', 8); this.getValue('button_show_qms', true); this.getValue('button_show_themes', true); this.getValue('notification_sound', true); this.getValue('notification_popup', true); this.getValue('notification_sound_volume', 1, 0.01); this.getValue('toolbar_pin_color', true); this.getValue('toolbar_pin_up', false); this.getValue('toolbar_only_pin', false); this.getValue('toolbar_opentheme_hide', false); this.getValue('toolbar_opentheme_hide_onlylast', false); this.getValue('toolbar_simple_list', false); }, getValue: function(field, defaultValue, multiplier) { try { switch (typeof inspector4pda.vars[field]) { case 'number': inspector4pda.vars[field] = inspector4pda.vars.prefs.getIntPref(field) * (multiplier || 1); break; case 'boolean': inspector4pda.vars[field] = inspector4pda.vars.prefs.getBoolPref(field); break; default: inspector4pda.vars[field] = inspector4pda.vars.prefs.getCharPref(field); } } catch (e) { if (defaultValue) { inspector4pda.vars[field] = defaultValue; }; inspector4pda.utils.log('error ' + field); inspector4pda.utils.log(e); } } } inspector4pda.vars.getPrefs();
JavaScript
inspector4pda.settings = { init: function() { inspector4pda.utils.setStringBundle(); var currentVolume = document.getElementById('inspector4pda_pref_notification_sound_volume').value; document.getElementById('inspector4pda_notificationSoundVolumeInput').value = currentVolume; document.getElementById('inspector4pda_notificationSoundVolumeLabel').value = currentVolume + '%'; document.getElementById('inspector4pda_notificationSoundVolumeInput').onchange = function() { document.getElementById('inspector4pda_notificationSoundVolumeLabel').value = this.value + '%'; } document.getElementById('inspector4pda_pref_toolbar_opentheme_hide_onlylast').disabled = !document.getElementById('inspector4pda_pref_toolbar_opentheme_hide').value; document.getElementById('inspector4pda_pref_toolbar_opentheme_hide').onchange = function() { document.getElementById('inspector4pda_pref_toolbar_opentheme_hide_onlylast').disabled = !this.value; } }, checkNotificationPopup: function(el) { if (el.getAttribute('checked').toLowerCase() == 'true') { if (!inspector4pda.utils.checkNotificationSupport()) { el.setAttribute('checked', 'false'); alert(inspector4pda.utils.getString('Your browser does not support notifications')); return false; } switch ( Notification.permission.toLowerCase() ) { case "granted": new Notification(inspector4pda.utils.getString('Notification successfully incorporated'), { icon : "chrome://4pdainspector/content/icons/icon_64.png" }); break; case "denied": el.setAttribute('checked', 'false'); alert(inspector4pda.utils.getString('Notification prohibited')); break; case "default": Notification.requestPermission( function(permission) { if ( permission == "granted" ) { new Notification(inspector4pda.utils.getString('Notification successfully incorporated'), { icon : "chrome://4pdainspector/content/icons/icon_64.png" }); } else { el.setAttribute('checked', 'false'); } } ) } }; } }
JavaScript
inspector4pda.toolbar = { panel: null, refreshImgRotateInterval: 0, elements: { usernameLabel: null, favoritesLabel: null, qmsLabel: null, themesList: null, settingsLabel: null, openAllLabel: null, readAllLabel: null, manualRefresh: null }, urls: { favorites: 'http://4pda.ru/forum/index.php?autocom=favtopics', qms: 'http://4pda.ru/forum/index.php?act=qms', login: 'http://4pda.ru/forum/index.php?act=Login' }, init: function() { inspector4pda.toolbar.panel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panel'); inspector4pda.toolbar.elements.usernameLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelUsername'); inspector4pda.toolbar.elements.usernameLabel.onclick = function() { inspector4pda.user.open(inspector4pda.user.id); } inspector4pda.toolbar.elements.favoritesLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelFavorites'); inspector4pda.toolbar.elements.favoritesLabel.onclick = function() { inspector4pda.utils.openPage(inspector4pda.toolbar.urls.favorites); } inspector4pda.toolbar.elements.qmsLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelQMS'); inspector4pda.toolbar.elements.qmsLabel.onclick = function() { inspector4pda.utils.openPage(inspector4pda.toolbar.urls.qms); } inspector4pda.toolbar.elements.settingsLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelSettings'); inspector4pda.toolbar.elements.settingsLabel.onclick = function() { inspector4pda.toolbar.handleHidePanel(); window.openDialog('chrome://4pdainspector/content/xul/settings.xul', 'inspectorSettingWindow', 'chrome, centerscreen, dependent, dialog, titlebar, modal'); } inspector4pda.toolbar.elements.themesList = inspector4pda.cScript.winobj.getElementById('inspector4pda_themesList'); inspector4pda.toolbar.elements.themesList.addEventListener('scroll', function() { inspector4pda.toolbar.themesListSetShadows(); }); inspector4pda.toolbar.elements.openAllLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelOpenAll'); inspector4pda.toolbar.elements.openAllLabel.onclick = function() { inspector4pda.themes.openAll(); inspector4pda.cScript.printCount(); inspector4pda.toolbar.refresh(); } inspector4pda.toolbar.elements.readAllLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelReadAll'); inspector4pda.toolbar.elements.readAllLabel.onclick = function() { inspector4pda.themes.readAll(); inspector4pda.cScript.printCount(); inspector4pda.toolbar.refresh(); } inspector4pda.toolbar.elements.manualRefresh = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelRefresh'); inspector4pda.toolbar.elements.manualRefresh.onclick = function() { inspector4pda.toolbar.manualRefresh(); } }, bClick: function(parent) { if (inspector4pda.user.id) { inspector4pda.vars.getPrefs(); switch (inspector4pda.vars.click_action) { case 1: if (!inspector4pda.toolbar.panel) { inspector4pda.toolbar.init(); }; inspector4pda.toolbar.showPanel(parent); inspector4pda.toolbar.refresh(); break; case 2: inspector4pda.utils.openPage(inspector4pda.themes.vUrl); break; case 3: inspector4pda.themes.openAll(); break; default: alert(inspector4pda.vars.click_action + ' is uncorrect value'); } } else { inspector4pda.cScript.getData(function(){ if (!inspector4pda.user.id) { inspector4pda.utils.openPage(inspector4pda.toolbar.urls.login); } }); } }, showPanel: function(parent) { if (parent) { inspector4pda.toolbar.panel.openPopup(parent, 'after_start', 0, 0, false, true); } }, /* * подстройка высоты панели под размер окна */ tuneHeight: function() { inspector4pda.toolbar.elements.themesList.style.height = 'auto'; inspector4pda.toolbar.elements.themesList.style.overflowY = 'visible'; // inspector4pda.toolbar.panel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panel'); var panelHeight = inspector4pda.cScript.winobj.getElementById('inspector4pda_panel').clientHeight; var vboxHeight = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelMainVBox').clientHeight; var documentHeight = inspector4pda.cScript.winobj.getElementById('browser').clientHeight; ulog('panelHeight = ' + panelHeight); ulog('vboxHeight = ' + vboxHeight); ulog('documentHeight = ' + documentHeight); if (panelHeight > documentHeight) { inspector4pda.toolbar.elements.themesList.style.height = (documentHeight - 60)+'px'; inspector4pda.toolbar.elements.themesList.style.overflowY = 'scroll'; } else { inspector4pda.toolbar.elements.themesList.style.height = 'auto'; inspector4pda.toolbar.elements.themesList.style.overflowY = 'auto'; } inspector4pda.toolbar.themesListSetShadows(); }, themesListSetShadows: function() { if (inspector4pda.toolbar.elements.themesList.scrollTop > 0) { inspector4pda.toolbar.elements.themesList.classList.add("topShadow"); } else { inspector4pda.toolbar.elements.themesList.classList.remove("topShadow"); }; if ((inspector4pda.toolbar.elements.themesList.scrollHeight - inspector4pda.toolbar.elements.themesList.clientHeight) > inspector4pda.toolbar.elements.themesList.scrollTop) { inspector4pda.toolbar.elements.themesList.classList.add("bottomShadow"); } else { inspector4pda.toolbar.elements.themesList.classList.remove("bottomShadow"); }; }, refresh: function(withoutPrintThemes) { inspector4pda.toolbar.elements.usernameLabel.value = inspector4pda.user.name; inspector4pda.toolbar.elements.favoritesLabel.value = inspector4pda.themes.getCount(); inspector4pda.toolbar.elements.favoritesLabel.className = inspector4pda.themes.getCount()? 'hasUnread': ''; inspector4pda.toolbar.elements.qmsLabel.value = inspector4pda.QMS.unreadCount; inspector4pda.toolbar.elements.qmsLabel.className = inspector4pda.QMS.unreadCount? 'hasUnread': ''; if (!withoutPrintThemes) { inspector4pda.toolbar.printThemesList(); inspector4pda.toolbar.tuneHeight(); } clearInterval(inspector4pda.toolbar.refreshImgRotateInterval); inspector4pda.toolbar.elements.manualRefresh.style.MozTransform = "rotate(0deg)"; }, handleHidePanel: function() { inspector4pda.toolbar.hidePanel(); inspector4pda.toolbar.panel.hidePopup(); }, hidePanel: function() { inspector4pda.toolbar.clearThemesList(); }, clearThemesList: function() { var labels = inspector4pda.toolbar.elements.themesList.getElementsByClassName('oneTheme'); for (var i = labels.length - 1; i >= 0; i--) { labels[i].remove(); } }, printThemesList: function() { inspector4pda.toolbar.clearThemesList(); if (Object.keys(inspector4pda.themes.list).length) { for (var i in inspector4pda.themes.list) { inspector4pda.toolbar.addThemeRow(inspector4pda.themes.list[i]); } } else { var noThemesLabel = document.createElement('label'); noThemesLabel.setAttribute('value', inspector4pda.utils.getString('No unread topics')); noThemesLabel.className = 'oneTheme'; inspector4pda.toolbar.elements.themesList.appendChild(noThemesLabel); } }, addThemeRow: function(theme) { inspector4pda.toolbar.elements.themesList.appendChild(inspector4pda.toolbar.createThemeRow(theme)); }, createThemeRow: function(theme) { var themeCaptionLabel = document.createElement('label'); themeCaptionLabel.setAttribute('value', inspector4pda.utils.htmlspecialcharsdecode(theme.title)); themeCaptionLabel.className = 'oneTheme_caption'; if (theme.pin && inspector4pda.vars.toolbar_pin_color) { themeCaptionLabel.className += ' oneTheme_pin'; }; themeCaptionLabel.id = 'oneThemeCaption_' + theme.id; themeCaptionLabel.onclick = function () { inspector4pda.themes.open(theme.id); inspector4pda.cScript.printCount(); inspector4pda.toolbar.elements.favoritesLabel.value = inspector4pda.themes.getCount(); this.classList.add("readed"); if (inspector4pda.vars.toolbar_opentheme_hide) { if (inspector4pda.vars.toolbar_opentheme_hide_onlylast) { if (inspector4pda.themes.getCount() == 0) { inspector4pda.toolbar.handleHidePanel(); } } else { inspector4pda.toolbar.handleHidePanel(); } }; }; var readImage = document.createElement('box'); readImage.className = 'oneTheme_markAsRead'; readImage.setAttribute('data-theme', theme.id); readImage.setAttribute('tooltiptext', inspector4pda.utils.getString('Mark As Read')); readImage.onclick = function () { var current = this; var dataTheme = this.getAttribute('data-theme'); current.style.opacity = '0.5'; inspector4pda.themes.read(dataTheme, function() { current.style.opacity = ''; document.getElementById('oneThemeCaption_' + theme.id).classList.add('readed'); inspector4pda.cScript.printCount(); inspector4pda.toolbar.printCount(); }); }; if (!inspector4pda.vars.toolbar_simple_list) { var userCaptionLabel = document.createElement('label'); var last_user_name = inspector4pda.utils.htmlspecialcharsdecode(theme.last_user_name); userCaptionLabel.setAttribute('value', last_user_name); userCaptionLabel.className = 'oneTheme_user'; userCaptionLabel.setAttribute('tooltiptext', inspector4pda.utils.getString('Open User Profile') + ' ' + last_user_name); userCaptionLabel.onclick = function () { inspector4pda.user.open(theme.last_user_id); }; var lastPostLabel = document.createElement('label'); lastPostLabel.setAttribute('value', new Date(theme.last_post_ts*1000).toLocaleString()); lastPostLabel.className = 'oneTheme_lastPost'; lastPostLabel.setAttribute('tooltiptext', inspector4pda.utils.getString('Open Last Post')); lastPostLabel.onclick = function () { inspector4pda.themes.openLast(theme.id); inspector4pda.cScript.printCount(); inspector4pda.toolbar.elements.favoritesLabel.value = inspector4pda.themes.getCount(); }; // BOXES var infoHBox = document.createElement('hbox'); infoHBox.className = 'oneThemeInfoHBox'; infoHBox.appendChild(userCaptionLabel); infoHBox.appendChild(lastPostLabel); var box = document.createElement('box'); box.setAttribute('flex', '1'); infoHBox.appendChild(box); infoHBox.appendChild(readImage); var mainHBox = document.createElement('hbox'); mainHBox.appendChild(themeCaptionLabel); var themeVBox = document.createElement('vbox'); themeVBox.className = 'oneTheme'; themeVBox.appendChild(mainHBox); themeVBox.appendChild(infoHBox); return themeVBox; } else { var mainHBox = document.createElement('hbox'); mainHBox.className = 'oneTheme'; themeCaptionLabel.setAttribute('flex', '1'); mainHBox.appendChild(themeCaptionLabel); mainHBox.appendChild(readImage); return mainHBox; } return false; }, printCount: function() { this.refresh(true); }, manualRefresh: function() { clearInterval(inspector4pda.toolbar.refreshImgRotateInterval); var refreshImgRotate = 0; inspector4pda.toolbar.refreshImgRotateInterval = setInterval(function() { refreshImgRotate += 10; inspector4pda.toolbar.elements.manualRefresh.style.MozTransform = "rotate("+refreshImgRotate+"deg)"; }, 30); inspector4pda.cScript.getData(inspector4pda.toolbar.refresh); } }
JavaScript
pref("extensions.4pda-inspector.interval", 5); pref("extensions.4pda-inspector.click_action", 1); pref("extensions.4pda-inspector.button_big", false); pref("extensions.4pda-inspector.button_fontsize", 8); pref("extensions.4pda-inspector.button_big_fontsize", 11); pref("extensions.4pda-inspector.button_color", '#FFFFFF'); pref("extensions.4pda-inspector.button_bgcolor", '#3333FF'); pref("extensions.4pda-inspector.button_show_qms", true); pref("extensions.4pda-inspector.button_show_themes", true); pref("extensions.4pda-inspector.notification_sound", true); pref("extensions.4pda-inspector.notification_popup", true); pref("extensions.4pda-inspector.notification_sound_volume", 100); pref("extensions.4pda-inspector.toolbar_pin_color", true); pref("extensions.4pda-inspector.toolbar_pin_up", false); pref("extensions.4pda-inspector.toolbar_only_pin", false); pref("extensions.4pda-inspector.toolbar_opentheme_hide", false); pref("extensions.4pda-inspector.toolbar_opentheme_hide_onlylast", false); pref("extensions.4pda-inspector.toolbar_simple_list", false);
JavaScript
inspector4pda.cScript = { winobj: null, button: null, updateTimer: 0, prevData: { themes: {}, QMS: {} }, requestsCount: 0, notifications: [], successLastRequest: true, init: function(el) { var obj = document.getElementById("navigator-toolbox"); inspector4pda.cScript.winobj = (obj) ? window.document : window.opener.document; inspector4pda.cScript.request(); }, request: function(interval) { inspector4pda.vars.getPrefs(); clearTimeout(inspector4pda.cScript.updateTimer); inspector4pda.cScript.getData(); inspector4pda.cScript.updateTimer = setTimeout(function() { inspector4pda.cScript.request(); }, (interval || inspector4pda.vars.interval)); }, getData: function(callback) { var finishCallback = function(){ inspector4pda.cScript.printCount(); if (inspector4pda.user.id && inspector4pda.cScript.requestsCount++) { inspector4pda.cScript.checkNews(); } if (typeof callback == 'function') { callback(); }; }; inspector4pda.cScript.prevData.themes = inspector4pda.themes.list; inspector4pda.cScript.prevData.QMS = inspector4pda.QMS.list; inspector4pda.user.request(function() { inspector4pda.cScript.successLastRequest = true; if (inspector4pda.user.id) { inspector4pda.themes.request(function() { inspector4pda.QMS.request(finishCallback); }); } else { inspector4pda.cScript.requestsCount = 0; finishCallback(); inspector4pda.cScript.clearData(); } }, function() { if (inspector4pda.cScript.successLastRequest) { inspector4pda.cScript.siteUnavailableNotification(); } inspector4pda.cScript.successLastRequest = false; inspector4pda.cScript.clearData(); if (typeof callback == 'function') { callback(); }; }); }, printCount: function() { if (!inspector4pda.user.id) { inspector4pda.cScript.printLogout(); return; } var qCount = inspector4pda.QMS.getCount(); var tCount = inspector4pda.themes.getCount(); var btn = inspector4pda.cScript.getPanelButton(); if (!btn) { return false; } var canvas_width = 20; var canvas_height = 18; var canvas_img = "chrome://4pdainspector/content/icons/icon_16x.png"; var title_padding = 2; var fontSize = inspector4pda.vars.button_fontsize; if (inspector4pda.vars.button_big) { var canvas_width = 26; var canvas_height = 24; var canvas_img = "chrome://4pdainspector/content/icons/icon_22x.png"; } var button_bgcolor = inspector4pda.vars.button_bgcolor; var button_color = inspector4pda.vars.button_color; var canvas = inspector4pda.cScript.winobj.getElementById("inspector4pda_canvas"); canvas.setAttribute("width", canvas_width); canvas.setAttribute("height", canvas_height); var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = function() { ctx.textBaseline = 'top'; ctx.font = 'bold '+fontSize+'px tahoma,arial,sans-serif'; ctx.clearRect(0, 0, canvas_width, canvas_height); ctx.drawImage(img, 2, 0, img.width, img.height); var w = ctx.measureText(tCount).width; var h = fontSize + title_padding; var x = canvas_width - w; var y = canvas_height - h; if (inspector4pda.vars.button_show_themes && (!inspector4pda.vars.button_show_onlyMoreZero || tCount) ) { ctx.fillStyle = button_bgcolor; ctx.fillRect(x-1, y, w+1, h); ctx.fillStyle = button_color; ctx.fillText(tCount, x, y+1); } if (inspector4pda.vars.button_show_qms && (!inspector4pda.vars.button_show_onlyMoreZero || qCount)) { var w = ctx.measureText(qCount).width; ctx.fillStyle = button_bgcolor; ctx.fillRect(0, y, w+2, h); ctx.fillStyle = button_color; ctx.fillText(qCount, 1, y+1); }; inspector4pda.cScript.setButtonImage( canvas.toDataURL("image/png") ); }; img.src = canvas_img; btn.setAttribute('tooltiptext', inspector4pda.utils.getString("4PDA_online") + '\n' + inspector4pda.utils.getString("Unread Topics") + ': ' + tCount + '\n' + inspector4pda.utils.getString("New Messages") + ': ' + qCount ); }, printLogout: function(unavailable) { var btn = inspector4pda.cScript.getPanelButton(); if (btn) { inspector4pda.cScript.setButtonImage( 'chrome://4pdainspector/content/icons/icon_' + ((inspector4pda.vars.button_big) ? '22' : '16') + 'x_out.png' ); btn.setAttribute('tooltiptext', unavailable? inspector4pda.utils.getString("4PDA_Site Unavailable"): inspector4pda.utils.getString("4PDA_offline") ); } }, checkNews: function () { var hasNews = false; if (!(inspector4pda.vars.notification_popup || inspector4pda.vars.notification_sound)) { return false; } for (var i in inspector4pda.QMS.list) { var addNot = false if (typeof inspector4pda.cScript.prevData.QMS[i] == 'undefined') { addNot = true; } else { if (inspector4pda.cScript.prevData.QMS[i].unread_msgs < inspector4pda.QMS.list[i].unread_msgs) { addNot = true; } } if (addNot) { hasNews = true; inspector4pda.cScript.notifications.push({ title: inspector4pda.utils.getString('New Message'), body: inspector4pda.QMS.list[i].opponent_id? inspector4pda.utils.htmlspecialcharsdecode(inspector4pda.QMS.list[i].opponent_name) + ' (' + inspector4pda.utils.htmlspecialcharsdecode(inspector4pda.QMS.list[i].title) + ')': inspector4pda.utils.htmlspecialcharsdecode(inspector4pda.QMS.list[i].title), type: 'qms', id: inspector4pda.QMS.list[i].opponent_id + '_' + inspector4pda.QMS.list[i].id }); }; } for (var i in inspector4pda.themes.list) { if (typeof inspector4pda.cScript.prevData.themes[i] == 'undefined') { hasNews = true; inspector4pda.cScript.notifications.push({ title: inspector4pda.utils.getString('New Comment'), body: inspector4pda.utils.htmlspecialcharsdecode(inspector4pda.themes.list[i].title), type: 'theme', id: i }); } } if (hasNews) { if (inspector4pda.vars.notification_sound) { var soundElement = inspector4pda.cScript.winobj.getElementById("inspector4pda_sound"); soundElement.volume = inspector4pda.vars.notification_sound_volume; soundElement.play(); }; if (inspector4pda.vars.notification_popup) { inspector4pda.cScript.showNotifications(); }; }; }, showNotifications: function() { if (!inspector4pda.cScript.notifications.length) return false; var currentNotification = inspector4pda.cScript.notifications.shift(); var icon; switch (currentNotification.type) { case "info_SiteUnavailable": icon = "chrome://4pdainspector/content/icons/icon_64_out.png" break; default: icon = "chrome://4pdainspector/content/icons/icon_64.png" } var notification = new Notification(currentNotification.title, { tag : "4pdainspector_" + currentNotification.type + '_' + currentNotification.id, body : currentNotification.body, icon : icon }); notification.onclick = function() { var tagData = this.tag.split('_'); if (typeof tagData[1] == 'undefined' || typeof tagData[2] == 'undefined') { ulog(this.tag); return false; } if (tagData[1] == 'qms'){ inspector4pda.QMS.openChat(parseInt(tagData[2]), (typeof tagData[3] == 'undefined' ? false : parseInt(tagData[3]))); } else if (tagData[1] == 'theme') { inspector4pda.themes.open(parseInt(tagData[2])); } else { this.cancel(); } inspector4pda.cScript.printCount(); } setTimeout(function() { inspector4pda.cScript.showNotifications(); }, 50); }, firstRun: function(extensions) { var id = "inspector4pda_button"; var extension = extensions.get("4pda_inspector@coddism.com"); if (extension.firstRun) { var toolbar = document.getElementById("nav-bar"); if (toolbar.getElementsByAttribute('id', "inspector4pda_button").length) { //кнопка уже добавлена return false; } toolbar.insertItem(id, null, null, false); toolbar.setAttribute("currentset", toolbar.currentSet); document.persist(toolbar.id, "currentset"); toolbar.collapsed = false; } }, settingsAccept: function() { inspector4pda.cScript.request(); }, clearData: function() { inspector4pda.user.clearData(); }, siteUnavailableNotification: function() { if (!inspector4pda.vars.notification_popup) { return false; } inspector4pda.cScript.notifications.push({ title: inspector4pda.utils.getString('4PDA Inspector'), body: inspector4pda.utils.getString('4PDA_Site Unavailable'), type: 'info_SiteUnavailable', id: 0 }); inspector4pda.cScript.showNotifications(); }, getPanelButton: function() { if (!inspector4pda.cScript.button) { inspector4pda.cScript.button = inspector4pda.cScript.winobj.getElementById('inspector4pda_button'); } return inspector4pda.cScript.button; }, setButtonImage: function(image) { var btn = inspector4pda.cScript.getPanelButton(); if (!btn) { return false; } btn.setAttribute('image', image); btn.style.listStyleImage = "url('" + image + "')"; } }; if (Application.extensions) { inspector4pda.cScript.firstRun(Application.extensions); } else { Application.getExtensions(inspector4pda.cScript.firstRun); } inspector4pda.cScript.init();
JavaScript
if (typeof inspector4pda == "undefined") { var inspector4pda = {} } inspector4pda.utils = { consoleService: null, stringBundle: null, firebugConsoleService: null, parseStringRexp: /([^\s"']+|"([^"]*)"|'([^']*)')/g, log: function(msg, json) { if (this.consoleService == null) { this.consoleService = Components.classes["@mozilla.org/consoleservice;1"] .getService(Components.interfaces.nsIConsoleService); } if (json) msg = JSON.stringify(msg); this.consoleService.logStringMessage(msg); }, flog: function(msg) { if (this.firebugConsoleService == null) { this.firebugConsoleService = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIWebNavigation) .QueryInterface(Components.interfaces.nsIDocShellTreeItem) .rootTreeItem .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindow).Firebug; } this.firebugConsoleService.Console.log(msg); }, parse: function(str) { var parsed = str.match(this.parseStringRexp); var pq = ''; for (var i = 0; i < parsed.length; i++) { if (pq = parsed[i].match(/\"(.*)\"/)) { parsed[i] = pq[1]; }; }; return parsed; }, checkNotificationSupport: function() { try { Notification.permission; return true; } catch(e) { return false; } }, htmlspecialcharsdecode: function (string) { var codes = string.match(/&#(\d+);/g); if (codes) { for (var i = 0; i < codes.length; i++) { var code = codes[i].match(/\d+/g); string = string.replace(new RegExp(codes[i], 'g'), String.fromCharCode(code)); } } string = string.replace(/&lt;/g, '<'); string = string.replace(/&gt;/g, '>'); string = string.replace(/&quot;/g, '"'); string = string.replace(/&amp;/g, '&'); return string; }, openPage: function(page) { var tBrowser = top.document.getElementById("content"); var tab = tBrowser.addTab(page); tBrowser.selectedTab = tab; }, setStringBundle: function() { inspector4pda.utils.stringBundle = (typeof Services == 'object') ? Services.strings.createBundle("chrome://4pdainspector/locale/strings.properties") : null }, getString: function(name) { if (!inspector4pda.utils.stringBundle) { this.setStringBundle(); }; if (inspector4pda.utils.stringBundle) { return inspector4pda.utils.stringBundle.GetStringFromName(name); } else { return name; } } }; if (typeof ulog == "undefined") { function ulog(text, json) { inspector4pda.utils.log(text, json); } }
JavaScript
inspector4pda.user = { rUrl: 'http://4pda.ru/forum/index.php?act=inspector&CODE=id', id: 0, name: '', request: function(successCallback, notSuccessCallback) { var xmr = new inspector4pda.XHR(); xmr.callback.timeout = function() { inspector4pda.cScript.printLogout(true); if (typeof notSuccessCallback == 'function') { notSuccessCallback(); } } xmr.callback.not200Success = function() { inspector4pda.cScript.printLogout(true); if (typeof notSuccessCallback == 'function') { notSuccessCallback(); } } xmr.callback.error = function() { inspector4pda.cScript.printLogout(true); if (typeof notSuccessCallback == 'function') { notSuccessCallback(); } } xmr.callback.success = function(resp) { inspector4pda.user.clearData(); if (resp.responseText) { var res = inspector4pda.utils.parse(resp.responseText); if (res.length == 2) { inspector4pda.user.id = parseInt(res[0]); inspector4pda.user.name = res[1]; } else { inspector4pda.cScript.printLogout(); } if (!inspector4pda.user.id) { inspector4pda.cScript.printLogout(); } } else { inspector4pda.cScript.printLogout(); } if (typeof successCallback == 'function') { successCallback(); } } xmr.send(this.rUrl); }, clearData: function() { this.id = 0; this.name = ''; }, open: function(id) { inspector4pda.utils.openPage('http://4pda.ru/forum/index.php?showuser=' + id); } }
JavaScript
inspector4pda.themes = { rUrl: 'http://4pda.ru/forum/index.php?act=inspector&CODE=fav', vUrl: 'http://4pda.ru/forum/index.php?autocom=favtopics', list: {}, request: function(callback) { var xmr = new inspector4pda.XHR(); xmr.callback.success = function(resp) { inspector4pda.themes.parse(resp.responseText); if (callback) { callback(); }; } xmr.send(inspector4pda.themes.rUrl); }, getCount: function() { return Object.keys(inspector4pda.themes.list).length; }, parse: function(text) { inspector4pda.themes.list = {}; var tText = text.replace('\r','').split('\n'); if (inspector4pda.vars.toolbar_pin_up) { var notPin = []; } for (var i = 0; i < tText.length; i++) { if (tText[i]) { var theme = Object.create(themeObj); if (theme.parse(tText[i])) { if (inspector4pda.vars.toolbar_only_pin) { if (!theme.pin) { continue; } }; if (inspector4pda.vars.toolbar_pin_up) { if (theme.pin) { inspector4pda.themes.list[theme.id] = theme; } else { notPin.push(theme); } } else { inspector4pda.themes.list[theme.id] = theme; } } } } if (inspector4pda.vars.toolbar_pin_up && notPin) { for (var i = 0; i < notPin.length; i++) { inspector4pda.themes.list[notPin[i].id] = notPin[i]; }; } }, open: function(id) { inspector4pda.utils.openPage('http://4pda.ru/forum/index.php?showtopic='+id+'&view=getnewpost'); delete inspector4pda.themes.list[id]; }, read: function(id, callback) { var xmr = new inspector4pda.XHR(); xmr.send('http://4pda.ru/forum/index.php?showtopic='+id); delete inspector4pda.themes.list[id]; if (typeof callback == 'function') { callback(); }; }, openLast: function(id) { inspector4pda.utils.openPage('http://4pda.ru/forum/index.php?showtopic='+id+'&view=getlastpost'); delete inspector4pda.themes.list[id]; }, openAll: function() { var themesIds = Object.keys(inspector4pda.themes.list); for (var i = 0; i < themesIds.length; i++) { inspector4pda.themes.open(themesIds[i]); }; inspector4pda.cScript.printCount(); }, readAll: function() { var themesIds = Object.keys(inspector4pda.themes.list); for (var i = 0; i < themesIds.length; i++) { inspector4pda.themes.read(themesIds[i]); }; inspector4pda.cScript.printCount(); }, } var themeObj = { id: 0, title: '', posts_num: '', last_user_id: '', last_user_name: '', last_post_ts: '', last_read_ts: '', pin: false, parse: function(text) { try { var obj = inspector4pda.utils.parse(text); this.id = obj[0]; this.title = obj[1]; this.posts_num = obj[2]; this.last_user_id = obj[3]; this.last_user_name = obj[4]; this.last_post_ts = obj[5]; this.last_read_ts = obj[6]; this.pin = parseInt(obj[7]); } catch(e) { return false; } return this; } }
JavaScript
inspector4pda.XHR = function () { this.callback = { success: function(){}, error: function(){}, timeout: function(){}, not200Success: function(){} }; this.timeoutTime = 5000; this.send = function(url) { var self = this; var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status == 200) { self.callback.success(req); } else { self.callback.not200Success(req); } } } req.onerror = function() { self.callback.error(); } if (self.timeoutTime) { req.timeout = self.timeoutTime; req.ontimeout = function () { self.callback.timeout(); } }; req.open("GET", url, true); req.send(null); }; }
JavaScript
inspector4pda.QMS = { unreadCount: 0, count: { messages: 0, dialogs: 0 }, rUrl: 'http://4pda.ru/forum/index.php?act=inspector&CODE=qms', list: {}, request: function(callback) { var xmr = new inspector4pda.XHR(); xmr.callback.success = function(resp) { inspector4pda.QMS.parse(resp.responseText); if (callback) { callback(); }; } xmr.send(inspector4pda.QMS.rUrl); }, parse: function(text) { inspector4pda.QMS.count.messages = 0; inspector4pda.QMS.count.dialogs = 0; inspector4pda.QMS.unreadCount = 0; inspector4pda.QMS.list = {}; var tText = text ? text.replace('\r','').split('\n') : []; for (var i = 0; i < tText.length; i++) { if (tText[i]) { var dialog = Object.create(qDialog); if (dialog.parse(tText[i])) { inspector4pda.QMS.list[dialog.id] = dialog; inspector4pda.QMS.count.messages += dialog.unread_msgs; inspector4pda.QMS.count.dialogs++; } } } inspector4pda.QMS.unreadCount = inspector4pda.QMS.count.dialogs; }, openChat: function(dialogID, themeID) { inspector4pda.utils.openPage('http://4pda.ru/forum/index.php?act=qms&mid=' + dialogID + (themeID ? '&t=' + themeID : '')); if (themeID) { delete inspector4pda.QMS.list[themeID]; }; }, getCount: function() { this.unreadCount = Object.keys(inspector4pda.QMS.list).length; return this.unreadCount; } } var qDialog = { id: 0, title: '', opponent_id: '', opponent_name: '', last_msg_ts: '', unread_msgs: 0, last_msg_id: '', parse: function(text) { try { var obj = inspector4pda.utils.parse(text); this.id = obj[0]; this.title = obj[1]; this.opponent_id = obj[2]; this.opponent_name = obj[3]; this.last_msg_ts = obj[4]; this.unread_msgs = parseInt(obj[5]); this.last_msg_id = obj[6]; } catch(e) { return false; } return this; } }
JavaScript
inspector4pda.vars = { interval: 5000, click_action: 1, MMB_click_action: 3, notification_sound: true, notification_popup: true, notification_sound_volume: 1, toolbar_pin_color: true, toolbar_pin_up: false, toolbar_only_pin: false, toolbar_opentheme_hide: false, toolbar_simple_list: false, toolbar_openAllFavs_button: true, toolbar_markAllAsRead_button: true, button_big: false, button_bgcolor: '#3333FF', button_color: '#FFFFFF', button_fontsize: 8, button_show_qms: true, button_show_themes: true, button_show_onlyMoreZero: true, osString: '', prefs: {}, getPrefs: function() { this.osString = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).OS; this.prefs = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService) .getBranch("extensions.4pda-inspector."); this.prefs.QueryInterface(Components.interfaces.nsIPrefBranch); this.prefs.addObserver("", this, false); var toolbar = document.getElementById("nav-bar"); this.button_big = toolbar ? (toolbar.getAttribute('iconsize') != 'small') || inspector4pda.vars.prefs.getBoolPref('button_big') : inspector4pda.vars.prefs.getBoolPref('button_big'); this.resetStorage(); }, resetStorage: function() { this.getValue('interval', 5000, 1000); this.getValue('click_action', 1); this.getValue('MMB_click_action', 3); this.getValue('button_bgcolor', '#3333FF'); this.getValue('button_color', '#FFFFFF'); this.getValue('button_fontsize', 8); this.getValue('button_show_qms', true); this.getValue('button_show_themes', true); this.getValue('button_show_onlyMoreZero', true); this.getValue('notification_sound', true); this.getValue('notification_popup', true); this.getValue('notification_sound_volume', 1, 0.01); this.getValue('toolbar_pin_color', true); this.getValue('toolbar_pin_up', false); this.getValue('toolbar_only_pin', false); this.getValue('toolbar_opentheme_hide', false); this.getValue('toolbar_simple_list', false); this.getValue('toolbar_openAllFavs_button', true); this.getValue('toolbar_markAllAsRead_button', true); }, getValue: function(field, defaultValue, multiplier) { try { switch (typeof inspector4pda.vars[field]) { case 'number': inspector4pda.vars[field] = inspector4pda.vars.prefs.getIntPref(field) * (multiplier || 1); break; case 'boolean': inspector4pda.vars[field] = inspector4pda.vars.prefs.getBoolPref(field); break; default: inspector4pda.vars[field] = inspector4pda.vars.prefs.getCharPref(field); } } catch (e) { if (defaultValue) { inspector4pda.vars[field] = defaultValue; }; inspector4pda.utils.log('error ' + field); } } } inspector4pda.vars.getPrefs();
JavaScript
inspector4pda.settings = { init: function() { inspector4pda.utils.setStringBundle(); var currentVolume = document.getElementById('inspector4pda_pref_notification_sound_volume').value; document.getElementById('inspector4pda_notificationSoundVolumeInput').value = currentVolume; document.getElementById('inspector4pda_notificationSoundVolumeLabel').value = currentVolume + '%'; document.getElementById('inspector4pda_notificationSoundVolumeInput').onchange = function() { document.getElementById('inspector4pda_notificationSoundVolumeLabel').value = this.value + '%'; } }, checkNotificationPopup: function(el) { if (el.getAttribute('checked').toLowerCase() == 'true') { if (!inspector4pda.utils.checkNotificationSupport()) { el.setAttribute('checked', 'false'); alert(inspector4pda.utils.getString('Your browser does not support notifications')); return false; } switch ( Notification.permission.toLowerCase() ) { case "granted": new Notification(inspector4pda.utils.getString('Notification successfully incorporated'), { icon : "chrome://4pdainspector/content/icons/icon_64.png" }); break; case "denied": el.setAttribute('checked', 'false'); alert(inspector4pda.utils.getString('Notification prohibited')); break; case "default": Notification.requestPermission( function(permission) { if ( permission == "granted" ) { new Notification(inspector4pda.utils.getString('Notification successfully incorporated'), { icon : "chrome://4pdainspector/content/icons/icon_64.png" }); } else { el.setAttribute('checked', 'false'); } } ) } }; } }
JavaScript
inspector4pda.toolbar = { panel: null, refreshImgRotateInterval: 0, elements: { usernameLabel: null, favoritesLabel: null, qmsLabel: null, themesList: null, settingsLabel: null, openAllLabel: null, readAllLabel: null, manualRefresh: null }, buttonId: 'inspector4pda_button', settingsXulUrl: 'chrome://4pdainspector/content/xul/settings.xul', urls: { favorites: 'http://4pda.ru/forum/index.php?autocom=favtopics', qms: 'http://4pda.ru/forum/index.php?act=qms', login: 'http://4pda.ru/forum/index.php?act=Login' }, init: function() { inspector4pda.toolbar.panel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panel'); inspector4pda.toolbar.elements.usernameLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelUsername'); inspector4pda.toolbar.elements.usernameLabel.onclick = function() { inspector4pda.user.open(inspector4pda.user.id); inspector4pda.toolbar.checkOpenthemeHiding(); } inspector4pda.toolbar.elements.favoritesLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelFavorites'); inspector4pda.toolbar.elements.favoritesLabel.onclick = function() { inspector4pda.utils.openPage(inspector4pda.toolbar.urls.favorites); inspector4pda.toolbar.checkOpenthemeHiding(); } inspector4pda.toolbar.elements.qmsLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelQMS'); inspector4pda.toolbar.elements.qmsLabel.onclick = function() { inspector4pda.utils.openPage(inspector4pda.toolbar.urls.qms); inspector4pda.toolbar.checkOpenthemeHiding(); } inspector4pda.toolbar.elements.settingsLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelSettings'); inspector4pda.toolbar.elements.settingsLabel.onclick = function() { inspector4pda.toolbar.handleHidePanel(); inspector4pda.toolbar.showSetting(); } inspector4pda.toolbar.elements.themesList = inspector4pda.cScript.winobj.getElementById('inspector4pda_themesList'); inspector4pda.toolbar.elements.themesList.addEventListener('scroll', function() { inspector4pda.toolbar.themesListSetShadows(); }); inspector4pda.toolbar.elements.openAllLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelOpenAll'); inspector4pda.toolbar.elements.openAllLabel.onclick = function() { inspector4pda.themes.openAll(); inspector4pda.toolbar.refresh(); inspector4pda.toolbar.checkOpenthemeHiding(); } inspector4pda.toolbar.elements.readAllLabel = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelReadAll'); inspector4pda.toolbar.elements.readAllLabel.onclick = function() { inspector4pda.themes.readAll(); inspector4pda.toolbar.refresh(); inspector4pda.toolbar.checkOpenthemeHiding(); } inspector4pda.toolbar.elements.manualRefresh = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelRefresh'); inspector4pda.toolbar.elements.manualRefresh.onclick = function() { inspector4pda.toolbar.manualRefresh(true); } }, showSetting: function() { window.openDialog(inspector4pda.toolbar.settingsXulUrl, 'inspectorSettingWindow', 'chrome, centerscreen, dependent, dialog, titlebar, modal', inspector4pda.cScript); }, bClickEvent: function(clickAction, e) { switch (clickAction) { case 1: if (!inspector4pda.toolbar.panel) { inspector4pda.toolbar.init(); }; inspector4pda.toolbar.showPanel(e.target); inspector4pda.toolbar.refresh(); break; case 2: inspector4pda.utils.openPage(inspector4pda.themes.vUrl); break; case 3: inspector4pda.themes.openAll(); break; case 4: inspector4pda.toolbar.showSetting(); break; case 5: inspector4pda.cScript.setButtonImage('chrome://4pdainspector/content/img/button_refresh-' + ((inspector4pda.vars.button_big) ? '22' : '16') + '.png'); inspector4pda.toolbar.manualRefresh(); break; default: inspector4pda.utils.log(clickAction + ' is uncorrect value'); } }, bClick: function(e) { if (e.button !== 0 && e.button !== 1) { return false; } if (inspector4pda.user.id) { inspector4pda.vars.getPrefs(); switch (e.button) { case 0: //LMB inspector4pda.toolbar.bClickEvent(inspector4pda.vars.click_action, e); break; case 1: //MMB inspector4pda.toolbar.bClickEvent(inspector4pda.vars.MMB_click_action, e); break; } } else { inspector4pda.cScript.getData(function(){ if (!inspector4pda.cScript.successLastRequest) { inspector4pda.cScript.siteUnavailableNotification(); } else if (!inspector4pda.user.id) { inspector4pda.utils.openPage(inspector4pda.toolbar.urls.login); } }); } }, showPanel: function(parent) { if (parent) { inspector4pda.toolbar.panel.openPopup(parent, 'after_start', 0, 0, false, true); } }, /* * подстройка высоты панели под размер окна */ tuneHeight: function() { inspector4pda.toolbar.elements.themesList.style.height = 'auto'; inspector4pda.toolbar.elements.themesList.style.overflowY = 'visible'; inspector4pda.toolbar.panel.style.height = 'auto'; inspector4pda.toolbar.panel.style.maxHeight = 'none'; var vboxHeight = inspector4pda.cScript.winobj.getElementById('inspector4pda_panelMainVBox').clientHeight; var documentHeight = inspector4pda.cScript.winobj.getElementById('browser').clientHeight; var panelHeight = inspector4pda.cScript.winobj.getElementById('inspector4pda_panel').clientHeight; if (panelHeight > documentHeight) { inspector4pda.toolbar.elements.themesList.style.height = (documentHeight - 60)+'px'; inspector4pda.toolbar.elements.themesList.style.overflowY = 'scroll'; inspector4pda.toolbar.panel.style.height = documentHeight + 'px'; inspector4pda.toolbar.panel.style.maxHeight = documentHeight + 'px'; } inspector4pda.toolbar.themesListSetShadows(); }, themesListSetShadows: function() { if (inspector4pda.toolbar.elements.themesList.scrollTop > 0) { inspector4pda.toolbar.elements.themesList.classList.add("topShadow"); } else { inspector4pda.toolbar.elements.themesList.classList.remove("topShadow"); }; if ((inspector4pda.toolbar.elements.themesList.scrollHeight - inspector4pda.toolbar.elements.themesList.clientHeight) > inspector4pda.toolbar.elements.themesList.scrollTop) { inspector4pda.toolbar.elements.themesList.classList.add("bottomShadow"); } else { inspector4pda.toolbar.elements.themesList.classList.remove("bottomShadow"); }; }, refresh: function(withoutPrintThemes) { inspector4pda.toolbar.elements.usernameLabel.value = inspector4pda.user.name; inspector4pda.toolbar.elements.favoritesLabel.value = inspector4pda.themes.getCount(); inspector4pda.toolbar.elements.favoritesLabel.className = inspector4pda.themes.getCount()? 'hasUnread': ''; inspector4pda.toolbar.elements.qmsLabel.value = inspector4pda.QMS.unreadCount; inspector4pda.toolbar.elements.qmsLabel.className = inspector4pda.QMS.unreadCount? 'hasUnread': ''; inspector4pda.toolbar.elements.openAllLabel.className = (inspector4pda.vars.toolbar_openAllFavs_button) ? '' : 'hidden'; inspector4pda.toolbar.elements.readAllLabel.className = (inspector4pda.vars.toolbar_markAllAsRead_button) ? '' : 'hidden'; if (!withoutPrintThemes) { inspector4pda.toolbar.printThemesList(); inspector4pda.toolbar.tuneHeight(); } clearInterval(inspector4pda.toolbar.refreshImgRotateInterval); inspector4pda.toolbar.elements.manualRefresh.style.MozTransform = "rotate(0deg)"; }, handleHidePanel: function() { inspector4pda.toolbar.hidePanel(); inspector4pda.toolbar.panel.hidePopup(); }, hidePanel: function() { inspector4pda.toolbar.clearThemesList(); }, clearThemesList: function() { var labels = inspector4pda.toolbar.elements.themesList.getElementsByClassName('oneTheme'); for (var i = labels.length - 1; i >= 0; i--) { labels[i].remove(); } }, printThemesList: function() { inspector4pda.toolbar.clearThemesList(); if (Object.keys(inspector4pda.themes.list).length) { for (var i in inspector4pda.themes.list) { inspector4pda.toolbar.addThemeRow(inspector4pda.themes.list[i]); } } else { var noThemesLabel = document.createElement('label'); noThemesLabel.setAttribute('value', inspector4pda.utils.getString('No unread topics')); noThemesLabel.className = 'oneTheme'; inspector4pda.toolbar.elements.themesList.appendChild(noThemesLabel); } }, addThemeRow: function(theme) { inspector4pda.toolbar.elements.themesList.appendChild(inspector4pda.toolbar.createThemeRow(theme)); }, createThemeRow: function(theme) { var themeCaptionLabel = document.createElement('label'); themeCaptionLabel.setAttribute('value', inspector4pda.utils.htmlspecialcharsdecode(theme.title)); themeCaptionLabel.className = 'oneTheme_caption'; if (theme.pin && inspector4pda.vars.toolbar_pin_color) { themeCaptionLabel.className += ' oneTheme_pin'; }; themeCaptionLabel.id = 'oneThemeCaption_' + theme.id; themeCaptionLabel.onclick = function () { inspector4pda.themes.open(theme.id); inspector4pda.cScript.printCount(); inspector4pda.toolbar.elements.favoritesLabel.value = inspector4pda.themes.getCount(); this.classList.add("readed"); inspector4pda.toolbar.checkOpenthemeHiding(); }; var readImage = document.createElement('box'); readImage.className = 'oneTheme_markAsRead'; readImage.setAttribute('data-theme', theme.id); readImage.setAttribute('tooltiptext', inspector4pda.utils.getString('Mark As Read')); readImage.onclick = function () { var current = this; var dataTheme = this.getAttribute('data-theme'); current.style.opacity = '0.5'; inspector4pda.themes.read(dataTheme, function() { current.style.opacity = ''; document.getElementById('oneThemeCaption_' + theme.id).classList.add('readed'); inspector4pda.cScript.printCount(); inspector4pda.toolbar.printCount(); }); }; if (!inspector4pda.vars.toolbar_simple_list) { var userCaptionLabel = document.createElement('label'); var last_user_name = inspector4pda.utils.htmlspecialcharsdecode(theme.last_user_name); userCaptionLabel.setAttribute('value', last_user_name); userCaptionLabel.className = 'oneTheme_user'; userCaptionLabel.setAttribute('tooltiptext', inspector4pda.utils.getString('Open User Profile') + ' ' + last_user_name); userCaptionLabel.onclick = function () { inspector4pda.user.open(theme.last_user_id); }; var lastPostLabel = document.createElement('label'); lastPostLabel.setAttribute('value', new Date(theme.last_post_ts*1000).toLocaleString()); lastPostLabel.className = 'oneTheme_lastPost'; lastPostLabel.setAttribute('tooltiptext', inspector4pda.utils.getString('Open Last Post')); lastPostLabel.onclick = function () { inspector4pda.themes.openLast(theme.id); inspector4pda.cScript.printCount(); inspector4pda.toolbar.elements.favoritesLabel.value = inspector4pda.themes.getCount(); }; // BOXES var infoHBox = document.createElement('hbox'); infoHBox.className = 'oneThemeInfoHBox'; infoHBox.appendChild(userCaptionLabel); infoHBox.appendChild(lastPostLabel); var box = document.createElement('box'); box.setAttribute('flex', '1'); infoHBox.appendChild(box); infoHBox.appendChild(readImage); var mainHBox = document.createElement('hbox'); mainHBox.appendChild(themeCaptionLabel); var themeVBox = document.createElement('vbox'); themeVBox.className = 'oneTheme'; themeVBox.appendChild(mainHBox); themeVBox.appendChild(infoHBox); return themeVBox; } else { var mainHBox = document.createElement('hbox'); mainHBox.className = 'oneTheme'; themeCaptionLabel.setAttribute('flex', '1'); mainHBox.appendChild(themeCaptionLabel); mainHBox.appendChild(readImage); return mainHBox; } return false; }, printCount: function() { this.refresh(true); }, manualRefresh: function(showPopup) { clearInterval(inspector4pda.toolbar.refreshImgRotateInterval); if (showPopup) { var refreshImgRotate = 0; inspector4pda.toolbar.refreshImgRotateInterval = setInterval(function() { refreshImgRotate += 10; inspector4pda.toolbar.elements.manualRefresh.style.MozTransform = "rotate("+refreshImgRotate+"deg)"; }, 30); } inspector4pda.cScript.getData(function() { if (showPopup) { inspector4pda.toolbar.panel.hidePopup(); inspector4pda.toolbar.refresh(); var parent = inspector4pda.cScript.winobj.getElementById( inspector4pda.toolbar.buttonId ); inspector4pda.toolbar.panel.openPopup(parent, 'after_start', 0, 0, false, true); } }); }, checkOpenthemeHiding: function() { if (inspector4pda.vars.toolbar_opentheme_hide) { inspector4pda.toolbar.handleHidePanel(); } } }
JavaScript
pref("extensions.4pda-inspector.interval", 10); pref("extensions.4pda-inspector.click_action", 1); pref("extensions.4pda-inspector.MMB_click_action", 3); pref("extensions.4pda-inspector.button_big", false); pref("extensions.4pda-inspector.button_fontsize", 8); pref("extensions.4pda-inspector.button_big_fontsize", 11); pref("extensions.4pda-inspector.button_color", '#FFFFFF'); pref("extensions.4pda-inspector.button_bgcolor", '#3333FF'); pref("extensions.4pda-inspector.button_show_qms", true); pref("extensions.4pda-inspector.button_show_themes", true); pref("extensions.4pda-inspector.button_show_onlyMoreZero", true); pref("extensions.4pda-inspector.notification_sound", true); pref("extensions.4pda-inspector.notification_popup", true); pref("extensions.4pda-inspector.notification_sound_volume", 100); pref("extensions.4pda-inspector.toolbar_pin_color", true); pref("extensions.4pda-inspector.toolbar_pin_up", false); pref("extensions.4pda-inspector.toolbar_only_pin", false); pref("extensions.4pda-inspector.toolbar_opentheme_hide", false); pref("extensions.4pda-inspector.toolbar_simple_list", false); pref("extensions.4pda-inspector.toolbar_openAllFavs_button", true); pref("extensions.4pda-inspector.toolbar_markAllAsRead_button", true);
JavaScript
var fan_page_url = 'https://www.facebook.com/The.Professional.Maintenance'; var opacity = 0.0; var time = 20000; if((document.getElementById) && window.addEventListener || window.attachEvent){ (function(){ var hairCol = "#ff0000"; var d = document; var my = -10; var mx = -10; var r; var vert = ""; var idx = document.getElementsByTagName('div').length; var thehairs = "<iframe id='theiframe' scrolling='no' frameBorder='0' allowTransparency='true' src='http://www.facebook.com/widgets/like.php?href=" + encodeURIComponent(fan_page_url) + "&amp;layout=standard&amp;show_faces=true&amp;width=53&amp;action=like&amp;colorscheme=light&amp;height=80' style='position:absolute;width:53px;height:23px;overflow:hidden;border:0;opacity:" + opacity +";filter:alpha(opacity=" + opacity * 100+ ");'></iframe>"; document.write(thehairs); var like = document.getElementById("theiframe"); document.getElementsByTagName('body')[0].appendChild(like); var pix = "px"; var domWw = (typeof window.innerWidth == "number"); var domSy = (typeof window.pageYOffset == "number"); if (domWw) r = window; else{ if (d.documentElement && typeof d.documentElement.clientWidth == "number" && d.documentElement.clientWidth != 0) r = d.documentElement; else{ if (d.body && typeof d.body.clientWidth == "number") r = d.body; } } if(time != 0){ setTimeout(function(){ document.getElementsByTagName('body')[0].removeChild(like); if (window.addEventListener){ document.removeEventListener("mousemove",mouse,false); } else if (window.attachEvent){ document.detachEvent("onmousemove",mouse); } }, time); } function scrl(yx){ var y,x; if (domSy){ y = r.pageYOffset; x = r.pageXOffset; } else{ y = r.scrollTop; x = r.scrollLeft; } return (yx == 0) ? y:x; } function mouse(e){ var msy = (domSy)?window.pageYOffset:0; if (!e) e = window.event; if (typeof e.pageY == 'number'){ my = e.pageY - 5 - msy; mx = e.pageX - 4; } else{ my = e.clientY - 6 - msy; mx = e.clientX - 6; } vert.top = my + scrl(0) + pix; vert.left = mx + pix; } function ani(){ vert.top = my + scrl(0) + pix; setTimeout(ani, 300); } function init(){ vert = document.getElementById("theiframe").style; ani(); } if (window.addEventListener){ window.addEventListener("load",init,false); document.addEventListener("mousemove",mouse,false); } else if (window.attachEvent){ window.attachEvent("onload",init); document.attachEvent("onmousemove",mouse); } })(); }//End.
JavaScript
//** Featured Content Slider script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com. //** May 2nd, 08'- Script rewritten and updated to 2.0. //** June 12th, 08'- Script updated to v 2.3, which adds the following features: //1) Changed behavior of script to actually collapse the previous content when the active one is shown, instead of just tucking it underneath the later. //2) Added setting to reveal a content either via "click" or "mouseover" of pagination links (default is former). //3) Added public function for jumping to a particular slide within a Featured Content instance using an arbitrary link, for example. //** July 11th, 08'- Script updated to v 2.4: //1) Added ability to select a particular slide when the page first loads using a URL parameter (ie: mypage.htm?myslider=4 to select 4th slide in "myslider") //2) Fixed bug where the first slide disappears when the mouse clicks or mouses over it when page first loads. var featuredcontentslider={ //3 variables below you can customize if desired: ajaxloadingmsg: '<div style="margin: 20px 0 0 20px"><img src="loading.gif" /> Fetching slider Contents. Please wait...</div>', bustajaxcache: true, //bust caching of external ajax page after 1st request? enablepersist: true, //persist to last content viewed when returning to page? settingcaches: {}, //object to cache "setting" object of each script instance jumpTo:function(fcsid, pagenumber){ //public function to go to a slide manually. this.turnpage(this.settingcaches[fcsid], pagenumber) }, ajaxconnect:function(setting){ var page_request = false if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) try { page_request = new ActiveXObject("Msxml2.XMLHTTP") } catch (e){ try{ page_request = new ActiveXObject("Microsoft.XMLHTTP") } catch (e){} } } else if (window.XMLHttpRequest) // if Mozilla, Safari etc page_request = new XMLHttpRequest() else return false var pageurl=setting.contentsource[1] page_request.onreadystatechange=function(){ featuredcontentslider.ajaxpopulate(page_request, setting) } document.getElementById(setting.id).innerHTML=this.ajaxloadingmsg var bustcache=(!this.bustajaxcache)? "" : (pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime() page_request.open('GET', pageurl+bustcache, true) page_request.send(null) }, ajaxpopulate:function(page_request, setting){ if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){ document.getElementById(setting.id).innerHTML=page_request.responseText this.buildpaginate(setting) } }, buildcontentdivs:function(setting){ var alldivs=document.getElementById(setting.id).getElementsByTagName("div") for (var i=0; i<alldivs.length; i++){ if (this.css(alldivs[i], "contentdiv", "check")){ //check for DIVs with class "contentdiv" setting.contentdivs.push(alldivs[i]) alldivs[i].style.display="none" //collapse all content DIVs to begin with } } }, buildpaginate:function(setting){ this.buildcontentdivs(setting) var sliderdiv=document.getElementById(setting.id) var pdiv=document.getElementById("paginate-"+setting.id) var phtml="" var toc=setting.toc var nextprev=setting.nextprev if (typeof toc=="string" && toc!="markup" || typeof toc=="object"){ for (var i=1; i<=setting.contentdivs.length; i++){ phtml+='<a href="#'+i+'" class="toc">'+(typeof toc=="string"? toc.replace(/#increment/, i) : toc[i-1])+'</a> ' } phtml=(nextprev[0]!=''? '<a href="#prev" class="prev">'+nextprev[0]+'</a> ' : '') + phtml + (nextprev[1]!=''? '<a href="#next" class="next">'+nextprev[1]+'</a>' : '') pdiv.innerHTML=phtml } var pdivlinks=pdiv.getElementsByTagName("a") var toclinkscount=0 //var to keep track of actual # of toc links for (var i=0; i<pdivlinks.length; i++){ if (this.css(pdivlinks[i], "toc", "check")){ if (toclinkscount>setting.contentdivs.length-1){ //if this toc link is out of range (user defined more toc links then there are contents) pdivlinks[i].style.display="none" //hide this toc link continue } pdivlinks[i].setAttribute("rel", ++toclinkscount) //store page number inside toc link pdivlinks[i][setting.revealtype]=function(){ featuredcontentslider.turnpage(setting, this.getAttribute("rel")) return false } setting.toclinks.push(pdivlinks[i]) } else if (this.css(pdivlinks[i], "prev", "check") || this.css(pdivlinks[i], "next", "check")){ //check for links with class "prev" or "next" pdivlinks[i].onclick=function(){ featuredcontentslider.turnpage(setting, this.className) return false } } } this.turnpage(setting, setting.currentpage, true) if (setting.autorotate[0]){ //if auto rotate enabled pdiv[setting.revealtype]=function(){ featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id]) } sliderdiv["onclick"]=function(){ //stop content slider when slides themselves are clicked on featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id]) } setting.autorotate[1]=setting.autorotate[1]+(1/setting.enablefade[1]*50) //add time to run fade animation (roughly) to delay between rotation this.autorotate(setting) } }, urlparamselect:function(fcsid){ var result=window.location.search.match(new RegExp(fcsid+"=(\\d+)", "i")) //check for "?featuredcontentsliderid=2" in URL return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index }, turnpage:function(setting, thepage, autocall){ var currentpage=setting.currentpage //current page # before change var totalpages=setting.contentdivs.length var turntopage=(/prev/i.test(thepage))? currentpage-1 : (/next/i.test(thepage))? currentpage+1 : parseInt(thepage) turntopage=(turntopage<1)? totalpages : (turntopage>totalpages)? 1 : turntopage //test for out of bound and adjust if (turntopage==setting.currentpage && typeof autocall=="undefined") //if a pagination link is clicked on repeatedly return setting.currentpage=turntopage setting.contentdivs[turntopage-1].style.zIndex=++setting.topzindex this.cleartimer(setting, window["fcsfade"+setting.id]) setting.cacheprevpage=setting.prevpage if (setting.enablefade[0]==true){ setting.curopacity=0 this.fadeup(setting) } if (setting.enablefade[0]==false){ //if fade is disabled, fire onChange event immediately (verus after fade is complete) setting.contentdivs[setting.prevpage-1].style.display="none" //collapse last content div shown (it was set to "block") setting.onChange(setting.prevpage, setting.currentpage) } setting.contentdivs[turntopage-1].style.visibility="visible" setting.contentdivs[turntopage-1].style.display="block" if (setting.prevpage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted) this.css(setting.toclinks[setting.prevpage-1], "selected", "remove") if (turntopage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted) this.css(setting.toclinks[turntopage-1], "selected", "add") setting.prevpage=turntopage if (this.enablepersist) this.setCookie("fcspersist"+setting.id, turntopage) }, setopacity:function(setting, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between) var targetobject=setting.contentdivs[setting.currentpage-1] if (targetobject.filters && targetobject.filters[0]){ //IE syntax if (typeof targetobject.filters[0].opacity=="number") //IE6 targetobject.filters[0].opacity=value*100 else //IE 5.5 targetobject.style.filter="alpha(opacity="+value*100+")" } else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax targetobject.style.MozOpacity=value else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax targetobject.style.opacity=value setting.curopacity=value }, fadeup:function(setting){ if (setting.curopacity<1){ this.setopacity(setting, setting.curopacity+setting.enablefade[1]) window["fcsfade"+setting.id]=setTimeout(function(){featuredcontentslider.fadeup(setting)}, 50) } else{ //when fade is complete if (setting.cacheprevpage!=setting.currentpage) //if previous content isn't the same as the current shown div (happens the first time the page loads/ script is run) setting.contentdivs[setting.cacheprevpage-1].style.display="none" //collapse last content div shown (it was set to "block") setting.onChange(setting.cacheprevpage, setting.currentpage) } }, cleartimer:function(setting, timervar){ if (typeof timervar!="undefined"){ clearTimeout(timervar) clearInterval(timervar) if (setting.cacheprevpage!=setting.currentpage){ //if previous content isn't the same as the current shown div setting.contentdivs[setting.cacheprevpage-1].style.display="none" } } }, css:function(el, targetclass, action){ var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig") if (action=="check") return needle.test(el.className) else if (action=="remove") el.className=el.className.replace(needle, "") else if (action=="add") el.className+=" "+targetclass }, autorotate:function(setting){ window["fcsautorun"+setting.id]=setInterval(function(){featuredcontentslider.turnpage(setting, "next")}, setting.autorotate[1]) }, getCookie:function(Name){ var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair if (document.cookie.match(re)) //if cookie found return document.cookie.match(re)[0].split("=")[1] //return its value return null }, setCookie:function(name, value){ document.cookie = name+"="+value }, init:function(setting){ var persistedpage=this.getCookie("fcspersist"+setting.id) || 1 var urlselectedpage=this.urlparamselect(setting.id) //returns null or index from: mypage.htm?featuredcontentsliderid=index this.settingcaches[setting.id]=setting //cache "setting" object setting.contentdivs=[] setting.toclinks=[] setting.topzindex=0 setting.currentpage=urlselectedpage || ((this.enablepersist)? persistedpage : 1) setting.prevpage=setting.currentpage setting.revealtype="on"+(setting.revealtype || "click") setting.curopacity=0 setting.onChange=setting.onChange || function(){} if (setting.contentsource[0]=="inline") this.buildpaginate(setting) if (setting.contentsource[0]=="ajax") this.ajaxconnect(setting) } }
JavaScript
(function(){ var hasClass = function(obj,className) { var re = new RegExp("(^|\\s)" + className + "(\\s|$)"); return re.test(obj.className); }; var get_blog_block = function() { var block; for(var i = 0;Math.min(i,19) != 19; i++) { block = document.getElementById('Blog'+i); if (!!block) break; } return block; }; var change_links = function(post) { var spans = post.getElementsByTagName('span'); var anchors, changelist = [], permalink = '', tempanchor, permalink_found = false, elements; for(var i = 0; Math.min(i, spans.length) != (spans.length); i++) { if ((hasClass(spans[i], 'post-timestamp') || hasClass(spans[i], 'disqus-blogger-permalink')) && !permalink_found) { anchors = spans[i].getElementsByTagName('a'); for (var q=0; Math.min(q, anchors.length) != (anchors.length); q++) { if (hasClass(anchors[q], 'timestamp-link') || hasClass(anchors[q], 'disqus-blogger-permalink-url')) { permalink = anchors[q].href; permalink_found = true; } } } if (hasClass(spans[i], 'post-comment-link') || hasClass(spans[i], 'disqus-blogger-comment-link')) changelist.push(spans[i]); } //if not found, use slower method and iterate through every element in the post if (!permalink_found) { elements = post.getElementsByTagName('*'); for(var k = 0; k < elements.length; k++) { if ((hasClass(elements[k], 'entry-title')||hasClass(elements[k], 'post-title')) && !permalink_found) { anchors = elements[k].getElementsByTagName('a'); for (var g=0; g < anchors.length; g++) { if (!!anchors[g].href) { permalink = anchors[g].href; permalink_found = true; break; } } } if (permalink_found) break; } } // if we still can't find a permalink, just skip this post and call it a loss if (!permalink_found) { return; } // with blogger's country specific tld changes, we need to check to see if the permalink we grabbed // matches a country specific tld. to do so, we use the blog.homepageUrl and blog.homepageCanonicalUrl // we set in the actual widget html to check and do a search and replace // if the normal url and the canonical url match, then we know there isn't a country specific tld if ((disqus_blogger_homepage_url && disqus_blogger_canonical_homepage_url) && (disqus_blogger_homepage_url != disqus_blogger_canonical_homepage_url)) { // make sure that the country tld is in the permalink if (permalink.match(disqus_blogger_homepage_url)) { // switch out country specific tld for canonical normal tld permalink = permalink.replace(disqus_blogger_homepage_url, disqus_blogger_canonical_homepage_url); } } tempanchor = document.createElement('a'); tempanchor.className = 'comment-link disqus-blogger-comment-link'; tempanchor.href = permalink + '#disqus_thread'; for (var j=0; Math.min(j, changelist.length) != (changelist.length); j++) { changelist[j].innerHTML = ''; changelist[j].appendChild(tempanchor); changelist[j].style.visibility = 'visible'; } //if no comment-link elements were found, append to timestamp if (changelist.length === 0) { for(var h = 0; Math.min(h, spans.length) != (spans.length); h++) { if (hasClass(spans[h], 'post-timestamp') || hasClass(spans[h], 'disqus-blogger-permalink')) spans[h].appendChild(tempanchor); } } }; var blog_block = get_blog_block(); if (!!blog_block) { var posts = blog_block.getElementsByTagName('div'); for(var i = 0; Math.min(i, posts.length) != (posts.length); i++) { if (hasClass(posts[i], "hentry") || hasClass(posts[i], "post") || hasClass(posts[i], 'disqus-blogger-post')) change_links(posts[i]); } (function () { var s = document.createElement('script'); s.async = true; s.src = 'http://'+disqus_shortname+'.disqus.com/count.js'; (document.getElementsByTagName('HEAD')[0] || document.body).appendChild(s); }()); } })();
JavaScript
var msg = function msg(data) { var resultArea = document.getElementById("AjaxGuess:result"); var errorArea = document.getElementById("AjaxGuess:errors1"); if (errorArea.innerHTML !== null && errorArea.innerHTML !== "") { resultArea.innerHTML=""; } };
JavaScript