o: ActiveSupport::Cache::Entry :@compressedF:@expires_in0:@created_atf1374498082.1404521: @value"G5{I" class:EFI"ProcessedAsset;FI"logical_path;F"vendor/numeral.jsI" pathname;F"\/Users/patricknegri/Desenvolvimento/iugu-ux/vendor/assets/javascripts/vendor/numeral.jsI"content_type;FI"application/javascript;FI" mtime;FI"2013-07-08T11:28:54-03:00;FI" length;Fi*2I" digest;F"%aa69b877beea6593c1114d76cb2fe21eI" source;FI"*2// numeral.js // version : 1.4.7 // author : Adam Draper // license : MIT // http://adamwdraper.github.com/Numeral-js/ (function () { /************************************ Constants ************************************/ var numeral, VERSION = '1.4.7', // internal storage for language config files languages = {}, currentLanguage = 'en', zeroFormat = null, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports); /************************************ Constructors ************************************/ // Numeral prototype object function Numeral (number) { this._n = number; } /** * Implementation of toFixed() that treats floats more like decimals * * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present * problems for accounting- and finance-related software. */ function toFixed (value, precision, optionals) { var power = Math.pow(10, precision), output; // Multiply up by precision, round accurately, then divide and use native toFixed(): output = (Math.round(value * power) / power).toFixed(precision); if (optionals) { var optionalsRegExp = new RegExp('0{1,' + optionals + '}$'); output = output.replace(optionalsRegExp, ''); } return output; } /************************************ Formatting ************************************/ // determine what type of formatting we need to do function formatNumeral (n, format) { var output; // figure out what kind of format we are dealing with if (format.indexOf('$') > -1) { // currency!!!!! output = formatCurrency(n, format); } else if (format.indexOf('%') > -1) { // percentage output = formatPercentage(n, format); } else if (format.indexOf(':') > -1) { // time output = formatTime(n, format); } else { // plain ol' numbers or bytes output = formatNumber(n, format); } // return string return output; } // revert to number function unformatNumeral (n, string) { if (string.indexOf(':') > -1) { n._n = unformatTime(string); } else { if (string === zeroFormat) { n._n = 0; } else { var stringOriginal = string; if (languages[currentLanguage].delimiters.decimal !== '.') { string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.'); } // see if abbreviations are there so that we can multiply to the correct number var thousandRegExp = new RegExp(languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), millionRegExp = new RegExp(languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), billionRegExp = new RegExp(languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), trillionRegExp = new RegExp(languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); // see if bytes are there so that we can multiply to the correct number var prefixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], bytesMultiplier = false; for (var power = 0; power <= prefixes.length; power++) { bytesMultiplier = (string.indexOf(prefixes[power]) > -1) ? Math.pow(1024, power + 1) : false; if (bytesMultiplier) { break; } } // do some math to create our number n._n = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * Number(((string.indexOf('(') > -1) ? '-' : '') + string.replace(/[^0-9\.-]+/g, '')); // round if we are talking about bytes n._n = (bytesMultiplier) ? Math.ceil(n._n) : n._n; } } return n._n; } function formatCurrency (n, format) { var prependSymbol = (format.indexOf('$') <= 1) ? true : false; // remove $ for the moment var space = ''; // check for space before or after currency if (format.indexOf(' $') > -1) { space = ' '; format = format.replace(' $', ''); } else if (format.indexOf('$ ') > -1) { space = ' '; format = format.replace('$ ', ''); } else { format = format.replace('$', ''); } // format the number var output = formatNumeral(n, format); // position the symbol if (prependSymbol) { if (output.indexOf('(') > -1 || output.indexOf('-') > -1) { output = output.split(''); output.splice(1, 0, languages[currentLanguage].currency.symbol + space); output = output.join(''); } else { output = languages[currentLanguage].currency.symbol + space + output; } } else { if (output.indexOf(')') > -1) { output = output.split(''); output.splice(-1, 0, space + languages[currentLanguage].currency.symbol); output = output.join(''); } else { output = output + space + languages[currentLanguage].currency.symbol; } } return output; } function formatPercentage (n, format) { var space = ''; // check for space before % if (format.indexOf(' %') > -1) { space = ' '; format = format.replace(' %', ''); } else { format = format.replace('%', ''); } n._n = n._n * 100; var output = formatNumeral(n, format); if (output.indexOf(')') > -1 ) { output = output.split(''); output.splice(-1, 0, space + '%'); output = output.join(''); } else { output = output + space + '%'; } return output; } function formatTime (n, format) { var hours = Math.floor(n._n/60/60), minutes = Math.floor((n._n - (hours * 60 * 60))/60), seconds = Math.round(n._n - (hours * 60 * 60) - (minutes * 60)); return hours + ':' + ((minutes < 10) ? '0' + minutes : minutes) + ':' + ((seconds < 10) ? '0' + seconds : seconds); } function unformatTime (string) { var timeArray = string.split(':'), seconds = 0; // turn hours and minutes into seconds and add them all up if (timeArray.length === 3) { // hours seconds = seconds + (Number(timeArray[0]) * 60 * 60); // minutes seconds = seconds + (Number(timeArray[1]) * 60); // seconds seconds = seconds + Number(timeArray[2]); } else if (timeArray.lenght === 2) { // minutes seconds = seconds + (Number(timeArray[0]) * 60); // seconds seconds = seconds + Number(timeArray[1]); } return Number(seconds); } function formatNumber (n, format) { var negP = false, optDec = false, abbr = '', bytes = '', ord = '', abs = Math.abs(n._n); // check if number is zero and a custom zero format has been set if (n._n === 0 && zeroFormat !== null) { return zeroFormat; } else { // see if we should use parentheses for negative number if (format.indexOf('(') > -1) { negP = true; format = format.slice(1, -1); } // see if abbreviation is wanted if (format.indexOf('a') > -1) { // check for space before abbreviation if (format.indexOf(' a') > -1) { abbr = ' '; format = format.replace(' a', ''); } else { format = format.replace('a', ''); } if (abs >= Math.pow(10, 12)) { // trillion abbr = abbr + languages[currentLanguage].abbreviations.trillion; n._n = n._n / Math.pow(10, 12); } else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9)) { // billion abbr = abbr + languages[currentLanguage].abbreviations.billion; n._n = n._n / Math.pow(10, 9); } else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6)) { // million abbr = abbr + languages[currentLanguage].abbreviations.million; n._n = n._n / Math.pow(10, 6); } else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3)) { // thousand abbr = abbr + languages[currentLanguage].abbreviations.thousand; n._n = n._n / Math.pow(10, 3); } } // see if we are formatting bytes if (format.indexOf('b') > -1) { // check for space before if (format.indexOf(' b') > -1) { bytes = ' '; format = format.replace(' b', ''); } else { format = format.replace('b', ''); } var prefixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], min, max; for (var power = 0; power <= prefixes.length; power++) { min = Math.pow(1024, power); max = Math.pow(1024, power+1); if (n._n >= min && n._n < max) { bytes = bytes + prefixes[power]; if (min > 0) { n._n = n._n / min; } break; } } } // see if ordinal is wanted if (format.indexOf('o') > -1) { // check for space before if (format.indexOf(' o') > -1) { ord = ' '; format = format.replace(' o', ''); } else { format = format.replace('o', ''); } ord = ord + languages[currentLanguage].ordinal(n._n); } if (format.indexOf('[.]') > -1) { optDec = true; format = format.replace('[.]', '.'); } var w = n._n.toString().split('.')[0], precision = format.split('.')[1], thousands = format.indexOf(','), d = '', neg = false; if (precision) { if (precision.indexOf('[') > -1) { precision = precision.replace(']', ''); precision = precision.split('['); d = toFixed(n._n, (precision[0].length + precision[1].length), precision[1].length); } else { d = toFixed(n._n, precision.length); } w = d.split('.')[0]; if (d.split('.')[1].length) { d = languages[currentLanguage].delimiters.decimal + d.split('.')[1]; } else { d = ''; } if (optDec && Number(d) === 0) { d = ''; } } else { w = toFixed(n._n, null); } // format number if (w.indexOf('-') > -1) { w = w.slice(1); neg = true; } if (thousands > -1) { w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + languages[currentLanguage].delimiters.thousands); } if (format.indexOf('.') === 0) { w = ''; } return ((negP && neg) ? '(' : '') + ((!negP && neg) ? '-' : '') + w + d + ((ord) ? ord : '') + ((abbr) ? abbr : '') + ((bytes) ? bytes : '') + ((negP && neg) ? ')' : ''); } } /************************************ Top Level Functions ************************************/ numeral = function (input) { if (numeral.isNumeral(input)) { input = input.value(); } else if (!Number(input)) { input = 0; } return new Numeral(Number(input)); }; // version number numeral.version = VERSION; // compare numeral object numeral.isNumeral = function (obj) { return obj instanceof Numeral; }; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. numeral.language = function (key, values) { if (!key) { return currentLanguage; } if (key && !values) { currentLanguage = key; } if (values || !languages[key]) { loadLanguage(key, values); } return numeral; }; numeral.language('en', { delimiters: { thousands: ',', decimal: '.' }, abbreviations: { thousand: 'k', million: 'm', billion: 'b', trillion: 't' }, ordinal: function (number) { var b = number % 10; return (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; }, currency: { symbol: '$' } }); numeral.zeroFormat = function (format) { if (typeof(format) === 'string') { zeroFormat = format; } else { zeroFormat = null; } }; /************************************ Helpers ************************************/ function loadLanguage(key, values) { languages[key] = values; } /************************************ Numeral Prototype ************************************/ numeral.fn = Numeral.prototype = { clone : function () { return numeral(this); }, format : function (inputString) { return formatNumeral(this, inputString ? inputString : numeral.defaultFormat); }, unformat : function (inputString) { return unformatNumeral(this, inputString ? inputString : numeral.defaultFormat); }, value : function () { return this._n; }, valueOf : function () { return this._n; }, set : function (value) { this._n = Number(value); return this; }, add : function (value) { this._n = this._n + Number(value); return this; }, subtract : function (value) { this._n = this._n - Number(value); return this; }, multiply : function (value) { this._n = this._n * Number(value); return this; }, divide : function (value) { this._n = this._n / Number(value); return this; }, difference : function (value) { var difference = this._n - Number(value); if (difference < 0) { difference = -difference; } return difference; } }; /************************************ Exposing Numeral ************************************/ // CommonJS module is defined if (hasModule) { module.exports = numeral; } /*global ender:false */ if (typeof ender === 'undefined') { // here, `this` means `window` in the browser, or `global` on the server // add `numeral` as a global object via a string identifier, // for Closure Compiler 'advanced' mode this['numeral'] = numeral; } /*global define:false */ if (typeof define === 'function' && define.amd) { define([], function () { return numeral; }); } }).call(this); /*! * jQuery contextMenu - Plugin for simple contextMenu handling * * Version: 1.5.25 * * Authors: Rodney Rehm, Addy Osmani (patches for FF) * Web: http://medialize.github.com/jQuery-contextMenu/ * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license * GPL v3 http://opensource.org/licenses/GPL-3.0 * */ (function($, undefined){ // TODO: - // ARIA stuff: menuitem, menuitemcheckbox und menuitemradio // create structure if $.support[htmlCommand || htmlMenuitem] and !opt.disableNative // determine html5 compatibility $.support.htmlMenuitem = ('HTMLMenuItemElement' in window); $.support.htmlCommand = ('HTMLCommandElement' in window); $.support.eventSelectstart = ("onselectstart" in document.documentElement); /* // should the need arise, test for css user-select $.support.cssUserSelect = (function(){ var t = false, e = document.createElement('div'); $.each('Moz|Webkit|Khtml|O|ms|Icab|'.split('|'), function(i, prefix) { var propCC = prefix + (prefix ? 'U' : 'u') + 'serSelect', prop = (prefix ? ('-' + prefix.toLowerCase() + '-') : '') + 'user-select'; e.style.cssText = prop + ': text;'; if (e.style[propCC] == 'text') { t = true; return false; } return true; }); return t; })(); */ var // currently active contextMenu trigger $currentTrigger = null, // is contextMenu initialized with at least one menu? initialized = false, // window handle $win = $(window), // number of registered menus counter = 0, // mapping selector to namespace namespaces = {}, // mapping namespace to options menus = {}, // custom command type handlers types = {}, // default values defaults = { // selector of contextMenu trigger selector: null, // where to append the menu to appendTo: null, // method to trigger context menu ["right", "left", "hover"] trigger: "right", // hide menu when mouse leaves trigger / menu elements autoHide: false, // ms to wait before showing a hover-triggered context menu delay: 200, // determine position to show menu at determinePosition: function($menu) { // position to the lower middle of the trigger element if ($.ui && $.ui.position) { // .position() is provided as a jQuery UI utility // (...and it won't work on hidden elements) $menu.css('display', 'block').position({ my: "center top", at: "center bottom", of: this, offset: "0 5", collision: "fit" }).css('display', 'none'); } else { // determine contextMenu position var offset = this.offset(); offset.top += this.outerHeight(); offset.left += this.outerWidth() / 2 - $menu.outerWidth() / 2; $menu.css(offset); } }, // position menu position: function(opt, x, y) { var $this = this, offset; // determine contextMenu position if (!x && !y) { opt.determinePosition.call(this, opt.$menu); return; } else if (x === "maintain" && y === "maintain") { // x and y must not be changed (after re-show on command click) offset = opt.$menu.position(); } else { // x and y are given (by mouse event) var triggerIsFixed = opt.$trigger.parents().andSelf() .filter(function() { return $(this).css('position') == "fixed"; }).length; if (triggerIsFixed) { y -= $win.scrollTop(); x -= $win.scrollLeft(); } offset = {top: y, left: x}; } // correct offset if viewport demands it var bottom = $win.scrollTop() + $win.height(), right = $win.scrollLeft() + $win.width(), height = opt.$menu.height(), width = opt.$menu.width(); if (offset.top + height > bottom) { offset.top -= height; } if (offset.left + width > right) { offset.left -= width; } opt.$menu.css(offset); }, // position the sub-menu positionSubmenu: function($menu) { if ($.ui && $.ui.position) { // .position() is provided as a jQuery UI utility // (...and it won't work on hidden elements) $menu.css('display', 'block').position({ my: "left top", at: "right top", of: this, collision: "fit" }).css('display', ''); } else { // determine contextMenu position var offset = { top: 0, left: this.outerWidth() }; $menu.css(offset); } }, // offset to add to zIndex zIndex: 1, // show hide animation settings animation: { duration: 50, show: 'slideDown', hide: 'slideUp' }, // events events: { show: $.noop, hide: $.noop }, // default callback callback: null, // list of contextMenu items items: {} }, // mouse position for hover activation hoveract = { timer: null, pageX: null, pageY: null }, // determine zIndex zindex = function($t) { var zin = 0, $tt = $t; while (true) { zin = Math.max(zin, parseInt($tt.css('z-index'), 10) || 0); $tt = $tt.parent(); if (!$tt || !$tt.length || "html body".indexOf($tt.prop('nodeName').toLowerCase()) > -1 ) { break; } } return zin; }, // event handlers handle = { // abort anything abortevent: function(e){ e.preventDefault(); e.stopImmediatePropagation(); }, // contextmenu show dispatcher contextmenu: function(e) { var $this = $(this); // disable actual context-menu e.preventDefault(); e.stopImmediatePropagation(); // abort native-triggered events unless we're triggering on right click if (e.data.trigger != 'right' && e.originalEvent) { return; } if (!$this.hasClass('context-menu-disabled')) { // theoretically need to fire a show event at // http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus // var evt = jQuery.Event("show", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this }); // e.data.$menu.trigger(evt); $currentTrigger = $this; if (e.data.build) { var built = e.data.build($currentTrigger, e); // abort if build() returned false if (built === false) { return; } // dynamically build menu on invocation e.data = $.extend(true, {}, defaults, e.data, built || {}); // abort if there are no items to display if (!e.data.items || $.isEmptyObject(e.data.items)) { // Note: jQuery captures and ignores errors from event handlers if (window.console) { (console.error || console.log)("No items specified to show in contextMenu"); } throw new Error('No Items sepcified'); } // backreference for custom command type creation e.data.$trigger = $currentTrigger; op.create(e.data); } // show menu op.show.call($this, e.data, e.pageX, e.pageY); } }, // contextMenu left-click trigger click: function(e) { e.preventDefault(); e.stopImmediatePropagation(); $(this).trigger($.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY })); }, // contextMenu right-click trigger mousedown: function(e) { // register mouse down var $this = $(this); // hide any previous menus if ($currentTrigger && $currentTrigger.length && !$currentTrigger.is($this)) { $currentTrigger.data('contextMenu').$menu.trigger('contextmenu:hide'); } // activate on right click if (e.button == 2) { $currentTrigger = $this.data('contextMenuActive', true); } }, // contextMenu right-click trigger mouseup: function(e) { // show menu var $this = $(this); if ($this.data('contextMenuActive') && $currentTrigger && $currentTrigger.length && $currentTrigger.is($this) && !$this.hasClass('context-menu-disabled')) { e.preventDefault(); e.stopImmediatePropagation(); $currentTrigger = $this; $this.trigger($.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY })); } $this.removeData('contextMenuActive'); }, // contextMenu hover trigger mouseenter: function(e) { var $this = $(this), $related = $(e.relatedTarget), $document = $(document); // abort if we're coming from a menu if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) { return; } // abort if a menu is shown if ($currentTrigger && $currentTrigger.length) { return; } hoveract.pageX = e.pageX; hoveract.pageY = e.pageY; hoveract.data = e.data; $document.on('mousemove.contextMenuShow', handle.mousemove); hoveract.timer = setTimeout(function() { hoveract.timer = null; $document.off('mousemove.contextMenuShow'); $currentTrigger = $this; $this.trigger($.Event("contextmenu", { data: hoveract.data, pageX: hoveract.pageX, pageY: hoveract.pageY })); }, e.data.delay ); }, // contextMenu hover trigger mousemove: function(e) { hoveract.pageX = e.pageX; hoveract.pageY = e.pageY; }, // contextMenu hover trigger mouseleave: function(e) { // abort if we're leaving for a menu var $related = $(e.relatedTarget); if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) { return; } try { clearTimeout(hoveract.timer); } catch(e) {} hoveract.timer = null; }, // click on layer to hide contextMenu layerClick: function(e) { var $this = $(this), root = $this.data('contextMenuRoot'), mouseup = false, button = e.button, x = e.pageX, y = e.pageY, target, offset, selectors; e.preventDefault(); e.stopImmediatePropagation(); // This hack looks about as ugly as it is // Firefox 12 (at least) fires the contextmenu event directly "after" mousedown // for some reason `root.$layer.hide(); document.elementFromPoint()` causes this // contextmenu event to be triggered on the uncovered element instead of on the // layer (where every other sane browser, including Firefox nightly at the time) // triggers the event. This workaround might be obsolete by September 2012. $this.on('mouseup', function() { mouseup = true; }); setTimeout(function() { var $window, hideshow; // test if we need to reposition the menu if ((root.trigger == 'left' && button == 0) || (root.trigger == 'right' && button == 2)) { if (document.elementFromPoint) { root.$layer.hide(); target = document.elementFromPoint(x - $win.scrollLeft(), y - $win.scrollTop()); root.$layer.show(); selectors = []; for (var s in namespaces) { selectors.push(s); } target = $(target).closest(selectors.join(', ')); if (target.length) { if (target.is(root.$trigger[0])) { root.position.call(root.$trigger, root, x, y); return; } } } else { offset = root.$trigger.offset(); $window = $(window); // while this looks kinda awful, it's the best way to avoid // unnecessarily calculating any positions offset.top += $window.scrollTop(); if (offset.top <= e.pageY) { offset.left += $window.scrollLeft(); if (offset.left <= e.pageX) { offset.bottom = offset.top + root.$trigger.outerHeight(); if (offset.bottom >= e.pageY) { offset.right = offset.left + root.$trigger.outerWidth(); if (offset.right >= e.pageX) { // reposition root.position.call(root.$trigger, root, x, y); return; } } } } } } hideshow = function(e) { if (e) { e.preventDefault(); e.stopImmediatePropagation(); } root.$menu.trigger('contextmenu:hide'); if (target && target.length) { setTimeout(function() { target.contextMenu({x: x, y: y}); }, 50); } }; if (mouseup) { // mouseup has already happened hideshow(); } else { // remove only after mouseup has completed $this.on('mouseup', hideshow); } }, 50); }, // key handled :hover keyStop: function(e, opt) { if (!opt.isInput) { e.preventDefault(); } e.stopPropagation(); }, key: function(e) { var opt = $currentTrigger.data('contextMenu') || {}, $children = opt.$menu.children(), $round; switch (e.keyCode) { case 9: case 38: // up handle.keyStop(e, opt); // if keyCode is [38 (up)] or [9 (tab) with shift] if (opt.isInput) { if (e.keyCode == 9 && e.shiftKey) { e.preventDefault(); opt.$selected && opt.$selected.find('input, textarea, select').blur(); opt.$menu.trigger('prevcommand'); return; } else if (e.keyCode == 38 && opt.$selected.find('input, textarea, select').prop('type') == 'checkbox') { // checkboxes don't capture this key e.preventDefault(); return; } } else if (e.keyCode != 9 || e.shiftKey) { opt.$menu.trigger('prevcommand'); return; } // omitting break; // case 9: // tab - reached through omitted break; case 40: // down handle.keyStop(e, opt); if (opt.isInput) { if (e.keyCode == 9) { e.preventDefault(); opt.$selected && opt.$selected.find('input, textarea, select').blur(); opt.$menu.trigger('nextcommand'); return; } else if (e.keyCode == 40 && opt.$selected.find('input, textarea, select').prop('type') == 'checkbox') { // checkboxes don't capture this key e.preventDefault(); return; } } else { opt.$menu.trigger('nextcommand'); return; } break; case 37: // left handle.keyStop(e, opt); if (opt.isInput || !opt.$selected || !opt.$selected.length) { break; } if (!opt.$selected.parent().hasClass('context-menu-root')) { var $parent = opt.$selected.parent().parent(); opt.$selected.trigger('contextmenu:blur'); opt.$selected = $parent; return; } break; case 39: // right handle.keyStop(e, opt); if (opt.isInput || !opt.$selected || !opt.$selected.length) { break; } var itemdata = opt.$selected.data('contextMenu') || {}; if (itemdata.$menu && opt.$selected.hasClass('context-menu-submenu')) { opt.$selected = null; itemdata.$selected = null; itemdata.$menu.trigger('nextcommand'); return; } break; case 35: // end case 36: // home if (opt.$selected && opt.$selected.find('input, textarea, select').length) { return; } else { (opt.$selected && opt.$selected.parent() || opt.$menu) .children(':not(.disabled, .not-selectable)')[e.keyCode == 36 ? 'first' : 'last']() .trigger('contextmenu:focus'); e.preventDefault(); return; } break; case 13: // enter handle.keyStop(e, opt); if (opt.isInput) { if (opt.$selected && !opt.$selected.is('textarea, select')) { e.preventDefault(); return; } break; } opt.$selected && opt.$selected.trigger('mouseup'); return; case 32: // space case 33: // page up case 34: // page down // prevent browser from scrolling down while menu is visible handle.keyStop(e, opt); return; case 27: // esc handle.keyStop(e, opt); opt.$menu.trigger('contextmenu:hide'); return; default: // 0-9, a-z var k = (String.fromCharCode(e.keyCode)).toUpperCase(); if (opt.accesskeys[k]) { // according to the specs accesskeys must be invoked immediately opt.accesskeys[k].$node.trigger(opt.accesskeys[k].$menu ? 'contextmenu:focus' : 'mouseup' ); return; } break; } // pass event to selected item, // stop propagation to avoid endless recursion e.stopPropagation(); opt.$selected && opt.$selected.trigger(e); }, // select previous possible command in menu prevItem: function(e) { e.stopPropagation(); var opt = $(this).data('contextMenu') || {}; // obtain currently selected menu if (opt.$selected) { var $s = opt.$selected; opt = opt.$selected.parent().data('contextMenu') || {}; opt.$selected = $s; } var $children = opt.$menu.children(), $prev = !opt.$selected || !opt.$selected.prev().length ? $children.last() : opt.$selected.prev(), $round = $prev; // skip disabled while ($prev.hasClass('disabled') || $prev.hasClass('not-selectable')) { if ($prev.prev().length) { $prev = $prev.prev(); } else { $prev = $children.last(); } if ($prev.is($round)) { // break endless loop return; } } // leave current if (opt.$selected) { handle.itemMouseleave.call(opt.$selected.get(0), e); } // activate next handle.itemMouseenter.call($prev.get(0), e); // focus input var $input = $prev.find('input, textarea, select'); if ($input.length) { $input.focus(); } }, // select next possible command in menu nextItem: function(e) { e.stopPropagation(); var opt = $(this).data('contextMenu') || {}; // obtain currently selected menu if (opt.$selected) { var $s = opt.$selected; opt = opt.$selected.parent().data('contextMenu') || {}; opt.$selected = $s; } var $children = opt.$menu.children(), $next = !opt.$selected || !opt.$selected.next().length ? $children.first() : opt.$selected.next(), $round = $next; // skip disabled while ($next.hasClass('disabled') || $next.hasClass('not-selectable')) { if ($next.next().length) { $next = $next.next(); } else { $next = $children.first(); } if ($next.is($round)) { // break endless loop return; } } // leave current if (opt.$selected) { handle.itemMouseleave.call(opt.$selected.get(0), e); } // activate next handle.itemMouseenter.call($next.get(0), e); // focus input var $input = $next.find('input, textarea, select'); if ($input.length) { $input.focus(); } }, // flag that we're inside an input so the key handler can act accordingly focusInput: function(e) { var $this = $(this).closest('.context-menu-item'), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; root.$selected = opt.$selected = $this; root.isInput = opt.isInput = true; }, // flag that we're inside an input so the key handler can act accordingly blurInput: function(e) { var $this = $(this).closest('.context-menu-item'), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; root.isInput = opt.isInput = false; }, // :hover on menu menuMouseenter: function(e) { var root = $(this).data().contextMenuRoot; root.hovering = true; }, // :hover on menu menuMouseleave: function(e) { var root = $(this).data().contextMenuRoot; if (root.$layer && root.$layer.is(e.relatedTarget)) { root.hovering = false; } }, // :hover done manually so key handling is possible itemMouseenter: function(e) { var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; root.hovering = true; // abort if we're re-entering if (e && root.$layer && root.$layer.is(e.relatedTarget)) { e.preventDefault(); e.stopImmediatePropagation(); } // make sure only one item is selected (opt.$menu ? opt : root).$menu .children('.hover').trigger('contextmenu:blur'); if ($this.hasClass('disabled') || $this.hasClass('not-selectable')) { opt.$selected = null; return; } $this.trigger('contextmenu:focus'); }, // :hover done manually so key handling is possible itemMouseleave: function(e) { var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; if (root !== opt && root.$layer && root.$layer.is(e.relatedTarget)) { root.$selected && root.$selected.trigger('contextmenu:blur'); e.preventDefault(); e.stopImmediatePropagation(); root.$selected = opt.$selected = opt.$node; return; } $this.trigger('contextmenu:blur'); }, // contextMenu item click itemClick: function(e) { var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot, key = data.contextMenuKey, callback; // abort if the key is unknown or disabled or is a menu if (!opt.items[key] || $this.hasClass('disabled') || $this.hasClass('context-menu-submenu')) { return; } e.preventDefault(); e.stopImmediatePropagation(); if ($.isFunction(root.callbacks[key])) { // item-specific callback callback = root.callbacks[key]; } else if ($.isFunction(root.callback)) { // default callback callback = root.callback; } else { // no callback, no action return; } // hide menu if callback doesn't stop that if (callback.call(root.$trigger, key, root) !== false) { root.$menu.trigger('contextmenu:hide'); } else if (root.$menu.parent().length) { op.update.call(root.$trigger, root); } }, // ignore click events on input elements inputClick: function(e) { e.stopImmediatePropagation(); }, // hide hideMenu: function(e, data) { var root = $(this).data('contextMenuRoot'); op.hide.call(root.$trigger, root, data && data.force); }, // focus focusItem: function(e) { e.stopPropagation(); var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; $this.addClass('hover') .siblings('.hover').trigger('contextmenu:blur'); // remember selected opt.$selected = root.$selected = $this; // position sub-menu - do after show so dumb $.ui.position can keep up if (opt.$node) { root.positionSubmenu.call(opt.$node, opt.$menu); } }, // blur blurItem: function(e) { e.stopPropagation(); var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; $this.removeClass('hover'); opt.$selected = null; } }, // operations op = { show: function(opt, x, y) { var $this = $(this), offset, css = {}; // hide any open menus $('#context-menu-layer').trigger('mousedown'); // backreference for callbacks opt.$trigger = $this; // show event if (opt.events.show.call($this, opt) === false) { $currentTrigger = null; return; } // create or update context menu op.update.call($this, opt); // position menu opt.position.call($this, opt, x, y); // make sure we're in front if (opt.zIndex) { css.zIndex = zindex($this) + opt.zIndex; } // add layer op.layer.call(opt.$menu, opt, css.zIndex); // adjust sub-menu zIndexes opt.$menu.find('ul').css('zIndex', css.zIndex + 1); // position and show context menu opt.$menu.css( css )[opt.animation.show](opt.animation.duration); // make options available $this.data('contextMenu', opt); // register key handler $(document).off('keydown.contextMenu').on('keydown.contextMenu', handle.key); // register autoHide handler if (opt.autoHide) { // trigger element coordinates var pos = $this.position(); pos.right = pos.left + $this.outerWidth(); pos.bottom = pos.top + this.outerHeight(); // mouse position handler $(document).on('mousemove.contextMenuAutoHide', function(e) { if (opt.$layer && !opt.hovering && (!(e.pageX >= pos.left && e.pageX <= pos.right) || !(e.pageY >= pos.top && e.pageY <= pos.bottom))) { // if mouse in menu... opt.$menu.trigger('contextmenu:hide'); } }); } }, hide: function(opt, force) { var $this = $(this); if (!opt) { opt = $this.data('contextMenu') || {}; } // hide event if (!force && opt.events && opt.events.hide.call($this, opt) === false) { return; } if (opt.$layer) { // keep layer for a bit so the contextmenu event can be aborted properly by opera setTimeout((function($layer){ return function(){ $layer.remove(); }; })(opt.$layer), 10); try { delete opt.$layer; } catch(e) { opt.$layer = null; } } // remove handle $currentTrigger = null; // remove selected opt.$menu.find('.hover').trigger('contextmenu:blur'); opt.$selected = null; // unregister key and mouse handlers //$(document).off('.contextMenuAutoHide keydown.contextMenu'); // http://bugs.jquery.com/ticket/10705 $(document).off('.contextMenuAutoHide').off('keydown.contextMenu'); // hide menu opt.$menu && opt.$menu[opt.animation.hide](opt.animation.duration, function (){ // tear down dynamically built menu after animation is completed. if (opt.build) { opt.$menu.remove(); $.each(opt, function(key, value) { switch (key) { case 'ns': case 'selector': case 'build': case 'trigger': return true; default: opt[key] = undefined; try { delete opt[key]; } catch (e) {} return true; } }); } }); }, create: function(opt, root) { if (root === undefined) { root = opt; } // create contextMenu opt.$menu = $('
    ').data({ 'contextMenu': opt, 'contextMenuRoot': root }); $.each(['callbacks', 'commands', 'inputs'], function(i,k){ opt[k] = {}; if (!root[k]) { root[k] = {}; } }); root.accesskeys || (root.accesskeys = {}); // create contextMenu items $.each(opt.items, function(key, item){ var $t = $('
  • '), $label = null, $input = null; item.$node = $t.data({ 'contextMenu': opt, 'contextMenuRoot': root, 'contextMenuKey': key }); // register accesskey // NOTE: the accesskey attribute should be applicable to any element, but Safari5 and Chrome13 still can't do that if (item.accesskey) { var aks = splitAccesskey(item.accesskey); for (var i=0, ak; ak = aks[i]; i++) { if (!root.accesskeys[ak]) { root.accesskeys[ak] = item; item._name = item.name.replace(new RegExp('(' + ak + ')', 'i'), '$1'); break; } } } if (typeof item == "string") { $t.addClass('context-menu-separator not-selectable'); } else if (item.type && types[item.type]) { // run custom type handler types[item.type].call($t, item, opt, root); // register commands $.each([opt, root], function(i,k){ k.commands[key] = item; if ($.isFunction(item.callback)) { k.callbacks[key] = item.callback; } }); } else { // add label for input if (item.type == 'html') { $t.addClass('context-menu-html not-selectable'); } else if (item.type) { $label = $('').appendTo($t); $('').html(item._name || item.name).appendTo($label); $t.addClass('context-menu-input'); opt.hasTypes = true; $.each([opt, root], function(i,k){ k.commands[key] = item; k.inputs[key] = item; }); } else if (item.items) { item.type = 'sub'; } switch (item.type) { case 'text': $input = $('') .val(item.value || "").appendTo($label); break; case 'textarea': $input = $('') .val(item.value || "").appendTo($label); if (item.height) { $input.height(item.height); } break; case 'checkbox': $input = $('') .val(item.value || "").prop("checked", !!item.selected).prependTo($label); break; case 'radio': $input = $('') .val(item.value || "").prop("checked", !!item.selected).prependTo($label); break; case 'select': $input = $(' if (item.type && item.type != 'sub' && item.type != 'html') { $input .on('focus', handle.focusInput) .on('blur', handle.blurInput); if (item.events) { $input.on(item.events, opt); } } // add icons if (item.icon) { $t.addClass("icon icon-" + item.icon); } } // cache contained elements item.$input = $input; item.$label = $label; // attach item to menu $t.appendTo(opt.$menu); // Disable text selection if (!opt.hasTypes && $.support.eventSelectstart) { // browsers support user-select: none, // IE has a special event for text-selection // browsers supporting neither will not be preventing text-selection $t.on('selectstart.disableTextSelect', handle.abortevent); } }); // attach contextMenu to (to bypass any possible overflow:hidden issues on parents of the trigger element) if (!opt.$node) { opt.$menu.css('display', 'none').addClass('context-menu-root'); } opt.$menu.appendTo(opt.appendTo || document.body); }, update: function(opt, root) { var $this = this; if (root === undefined) { root = opt; // determine widths of submenus, as CSS won't grow them automatically // position:absolute > position:absolute; min-width:100; max-width:200; results in width: 100; // kinda sucks hard... opt.$menu.find('ul').andSelf().css({position: 'static', display: 'block'}).each(function(){ var $this = $(this); $this.width($this.css('position', 'absolute').width()) .css('position', 'static'); }).css({position: '', display: ''}); } // re-check disabled for each item opt.$menu.children().each(function(){ var $item = $(this), key = $item.data('contextMenuKey'), item = opt.items[key], disabled = ($.isFunction(item.disabled) && item.disabled.call($this, key, root)) || item.disabled === true; // dis- / enable item $item[disabled ? 'addClass' : 'removeClass']('disabled'); if (item.type) { // dis- / enable input elements $item.find('input, select, textarea').prop('disabled', disabled); // update input states switch (item.type) { case 'text': case 'textarea': item.$input.val(item.value || ""); break; case 'checkbox': case 'radio': item.$input.val(item.value || "").prop('checked', !!item.selected); break; case 'select': item.$input.val(item.selected || ""); break; } } if (item.$menu) { // update sub-menu op.update.call($this, item, root); } }); }, layer: function(opt, zIndex) { // add transparent layer for click area // filter and background for Internet Explorer, Issue #23 var $layer = opt.$layer = $('
    ') .css({height: $win.height(), width: $win.width(), display: 'block'}) .data('contextMenuRoot', opt) .insertBefore(this) .on('contextmenu', handle.abortevent) .on('mousedown', handle.layerClick); // IE6 doesn't know position:fixed; if (!$.support.fixedPosition) { $layer.css({ 'position' : 'absolute', 'height' : $(document).height() }); } return $layer; } }; // split accesskey according to http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#assigned-access-key function splitAccesskey(val) { var t = val.split(/\s+/), keys = []; for (var i=0, k; k = t[i]; i++) { k = k[0].toUpperCase(); // first character only // theoretically non-accessible characters should be ignored, but different systems, different keyboard layouts, ... screw it. // a map to look up already used access keys would be nice keys.push(k); } return keys; } // handle contextMenu triggers $.fn.contextMenu = function(operation) { if (operation === undefined) { this.first().trigger('contextmenu'); } else if (operation.x && operation.y) { this.first().trigger($.Event("contextmenu", {pageX: operation.x, pageY: operation.y})); } else if (operation === "hide") { var $menu = this.data('contextMenu').$menu; $menu && $menu.trigger('contextmenu:hide'); } else if (operation) { this.removeClass('context-menu-disabled'); } else if (!operation) { this.addClass('context-menu-disabled'); } return this; }; // manage contextMenu instances $.contextMenu = function(operation, options) { if (typeof operation != 'string') { options = operation; operation = 'create'; } if (typeof options == 'string') { options = {selector: options}; } else if (options === undefined) { options = {}; } // merge with default options var o = $.extend(true, {}, defaults, options || {}), $document = $(document); switch (operation) { case 'create': // no selector no joy if (!o.selector) { throw new Error('No selector specified'); } // make sure internal classes are not bound to if (o.selector.match(/.context-menu-(list|item|input)($|\s)/)) { throw new Error('Cannot bind to selector "' + o.selector + '" as it contains a reserved className'); } if (!o.build && (!o.items || $.isEmptyObject(o.items))) { throw new Error('No Items sepcified'); } counter ++; o.ns = '.contextMenu' + counter; namespaces[o.selector] = o.ns; menus[o.ns] = o; // default to right click if (!o.trigger) { o.trigger = 'right'; } if (!initialized) { // make sure item click is registered first $document .on({ 'contextmenu:hide.contextMenu': handle.hideMenu, 'prevcommand.contextMenu': handle.prevItem, 'nextcommand.contextMenu': handle.nextItem, 'contextmenu.contextMenu': handle.abortevent, 'mouseenter.contextMenu': handle.menuMouseenter, 'mouseleave.contextMenu': handle.menuMouseleave }, '.context-menu-list') .on('mouseup.contextMenu', '.context-menu-input', handle.inputClick) .on({ 'mouseup.contextMenu': handle.itemClick, 'contextmenu:focus.contextMenu': handle.focusItem, 'contextmenu:blur.contextMenu': handle.blurItem, 'contextmenu.contextMenu': handle.abortevent, 'mouseenter.contextMenu': handle.itemMouseenter, 'mouseleave.contextMenu': handle.itemMouseleave }, '.context-menu-item'); initialized = true; } // engage native contextmenu event $document .on('contextmenu' + o.ns, o.selector, o, handle.contextmenu); switch (o.trigger) { case 'hover': $document .on('mouseenter' + o.ns, o.selector, o, handle.mouseenter) .on('mouseleave' + o.ns, o.selector, o, handle.mouseleave); break; case 'left': $document.on('click' + o.ns, o.selector, o, handle.click); break; /* default: // http://www.quirksmode.org/dom/events/contextmenu.html $document .on('mousedown' + o.ns, o.selector, o, handle.mousedown) .on('mouseup' + o.ns, o.selector, o, handle.mouseup); break; */ } // create menu if (!o.build) { op.create(o); } break; case 'destroy': if (!o.selector) { $document.off('.contextMenu .contextMenuAutoHide'); $.each(namespaces, function(key, value) { $document.off(value); }); namespaces = {}; menus = {}; counter = 0; initialized = false; $('#context-menu-layer, .context-menu-list').remove(); } else if (namespaces[o.selector]) { var $visibleMenu = $('.context-menu-list').filter(':visible'); if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is(o.selector)) { $visibleMenu.trigger('contextmenu:hide', {force: true}); } try { if (menus[namespaces[o.selector]].$menu) { menus[namespaces[o.selector]].$menu.remove(); } delete menus[namespaces[o.selector]]; } catch(e) { menus[namespaces[o.selector]] = null; } $document.off(namespaces[o.selector]); } break; case 'html5': // if or are not handled by the browser, // or options was a bool true, // initialize $.contextMenu for them if ((!$.support.htmlCommand && !$.support.htmlMenuitem) || (typeof options == "boolean" && options)) { $('menu[type="context"]').each(function() { if (this.id) { $.contextMenu({ selector: '[contextmenu=' + this.id +']', items: $.contextMenu.fromMenu(this) }); } }).css('display', 'none'); } break; default: throw new Error('Unknown operation "' + operation + '"'); } return this; }; // import values into commands $.contextMenu.setInputValues = function(opt, data) { if (data === undefined) { data = {}; } $.each(opt.inputs, function(key, item) { switch (item.type) { case 'text': case 'textarea': item.value = data[key] || ""; break; case 'checkbox': item.selected = data[key] ? true : false; break; case 'radio': item.selected = (data[item.radio] || "") == item.value ? true : false; break; case 'select': item.selected = data[key] || ""; break; } }); }; // export values from commands $.contextMenu.getInputValues = function(opt, data) { if (data === undefined) { data = {}; } $.each(opt.inputs, function(key, item) { switch (item.type) { case 'text': case 'textarea': case 'select': data[key] = item.$input.val(); break; case 'checkbox': data[key] = item.$input.prop('checked'); break; case 'radio': if (item.$input.prop('checked')) { data[item.radio] = item.value; } break; } }); return data; }; // find