vendor/assets/javascripts/jquery.qtip.js in qtip2-jquery-rails-2.0.0 vs vendor/assets/javascripts/jquery.qtip.js in qtip2-jquery-rails-2.1.1.pre
- old
+ new
@@ -1,1407 +1,1557 @@
-/*! qTip2 - Pretty powerful tooltips - v2.0.0 - 2012-10-25
-* http://craigsworks.com/projects/qtip2/
-* Copyright (c) 2012 Craig Michael Thompson; Licensed MIT, GPL */
-
-/*jslint browser: true, onevar: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true */
+/*
+ * qTip2 - Pretty powerful tooltips - v2.1.1
+ * http://qtip2.com
+ *
+ * Copyright (c) 2013 Craig Michael Thompson
+ * Released under the MIT, GPL licenses
+ * http://jquery.org/license
+ *
+ * Date: Thu Jul 11 2013 02:03 GMT+0100+0100
+ * Plugins: tips modal viewport svg imagemap ie6
+ * Styles: basic css3
+ */
/*global window: false, jQuery: false, console: false, define: false */
/* Cache window, document, undefined */
(function( window, document, undefined ) {
// Uses AMD or browser globals to create a jQuery plugin.
(function( factory ) {
"use strict";
if(typeof define === 'function' && define.amd) {
- define(['jquery'], factory);
+ define(['jquery', 'imagesloaded'], factory);
}
else if(jQuery && !jQuery.fn.qtip) {
factory(jQuery);
}
}
(function($) {
/* This currently causes issues with Safari 6, so for it's disabled */
//"use strict"; // (Dis)able ECMAScript "strict" operation for this function. See more: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
- // Munge the primitives - Paul Irish tip
- var TRUE = true,
- FALSE = false,
- NULL = null,
+;// Munge the primitives - Paul Irish tip
+var TRUE = true,
+FALSE = false,
+NULL = null,
- // Side names and other stuff
- X = 'x', Y = 'y',
- WIDTH = 'width',
- HEIGHT = 'height',
- TOP = 'top',
- LEFT = 'left',
- BOTTOM = 'bottom',
- RIGHT = 'right',
- CENTER = 'center',
- FLIP = 'flip',
- FLIPINVERT = 'flipinvert',
- SHIFT = 'shift',
+// Common variables
+X = 'x', Y = 'y',
+WIDTH = 'width',
+HEIGHT = 'height',
- // Shortcut vars
- QTIP, PLUGINS, MOUSE,
- usedIDs = {},
- uitooltip = 'ui-tooltip',
- widget = 'ui-widget',
- disabled = 'ui-state-disabled',
- selector = 'div.qtip.'+uitooltip,
- defaultClass = uitooltip + '-default',
- focusClass = uitooltip + '-focus',
- hoverClass = uitooltip + '-hover',
- replaceSuffix = '_replacedByqTip',
- oldtitle = 'oldtitle',
- trackingBound,
- redrawContainer;
+// Positioning sides
+TOP = 'top',
+LEFT = 'left',
+BOTTOM = 'bottom',
+RIGHT = 'right',
+CENTER = 'center',
+// Position adjustment types
+FLIP = 'flip',
+FLIPINVERT = 'flipinvert',
+SHIFT = 'shift',
+
+// Shortcut vars
+QTIP, PROTOTYPE, CORNER, CHECKS,
+PLUGINS = {},
+NAMESPACE = 'qtip',
+ATTR_HAS = 'data-hasqtip',
+ATTR_ID = 'data-qtip-id',
+WIDGET = ['ui-widget', 'ui-tooltip'],
+SELECTOR = '.'+NAMESPACE,
+INACTIVE_EVENTS = 'click dblclick mousedown mouseup mousemove mouseleave mouseenter'.split(' '),
+
+CLASS_FIXED = NAMESPACE+'-fixed',
+CLASS_DEFAULT = NAMESPACE + '-default',
+CLASS_FOCUS = NAMESPACE + '-focus',
+CLASS_HOVER = NAMESPACE + '-hover',
+CLASS_DISABLED = NAMESPACE+'-disabled',
+
+replaceSuffix = '_replacedByqTip',
+oldtitle = 'oldtitle',
+trackingBound;
+
+// Browser detection
+BROWSER = {
/*
- * redraw() container for width/height calculations
- */
- redrawContainer = $('<div/>', { id: 'qtip-rcontainer' });
- $(function() { redrawContainer.appendTo(document.body); });
+ * IE version detection
+ *
+ * Adapted from: http://ajaxian.com/archives/attack-of-the-ie-conditional-comment
+ * Credit to James Padolsey for the original implemntation!
+ */
+ ie: (function(){
+ var v = 3, div = document.createElement('div');
+ while ((div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->')) {
+ if(!div.getElementsByTagName('i')[0]) { break; }
+ }
+ return v > 4 ? v : NaN;
+ }()),
+
+ /*
+ * iOS version detection
+ */
+ iOS: parseFloat(
+ ('' + (/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0,''])[1])
+ .replace('undefined', '3_2').replace('_', '.').replace('_', '')
+ ) || FALSE
+};
+;function QTip(target, options, id, attr) {
+ // Elements and ID
+ this.id = id;
+ this.target = target;
+ this.tooltip = NULL;
+ this.elements = elements = { target: target };
+
+ // Internal constructs
+ this._id = NAMESPACE + '-' + id;
+ this.timers = { img: {} };
+ this.options = options;
+ this.plugins = {};
+
+ // Cache object
+ this.cache = cache = {
+ event: {},
+ target: $(),
+ disabled: FALSE,
+ attr: attr,
+ onTooltip: FALSE,
+ lastClass: ''
+ };
+
+ // Set the initial flags
+ this.rendered = this.destroyed = this.disabled = this.waiting =
+ this.hiddenDuringWait = this.positioning = this.triggering = FALSE;
+}
+PROTOTYPE = QTip.prototype;
+
+PROTOTYPE.render = function(show) {
+ if(this.rendered || this.destroyed) { return this; } // If tooltip has already been rendered, exit
+
+ var self = this,
+ options = this.options,
+ cache = this.cache,
+ elements = this.elements,
+ text = options.content.text,
+ title = options.content.title,
+ button = options.content.button,
+ posOptions = options.position,
+ namespace = '.'+this._id+' ',
+ deferreds = [];
+
+ // Add ARIA attributes to target
+ $.attr(this.target[0], 'aria-describedby', this._id);
+
+ // Create tooltip element
+ this.tooltip = elements.tooltip = tooltip = $('<div/>', {
+ 'id': this._id,
+ 'class': [ NAMESPACE, CLASS_DEFAULT, options.style.classes, NAMESPACE + '-pos-' + options.position.my.abbrev() ].join(' '),
+ 'width': options.style.width || '',
+ 'height': options.style.height || '',
+ 'tracking': posOptions.target === 'mouse' && posOptions.adjust.mouse,
+
+ /* ARIA specific attributes */
+ 'role': 'alert',
+ 'aria-live': 'polite',
+ 'aria-atomic': FALSE,
+ 'aria-describedby': this._id + '-content',
+ 'aria-hidden': TRUE
+ })
+ .toggleClass(CLASS_DISABLED, this.disabled)
+ .attr(ATTR_ID, this.id)
+ .data(NAMESPACE, this)
+ .appendTo(posOptions.container)
+ .append(
+ // Create content element
+ elements.content = $('<div />', {
+ 'class': NAMESPACE + '-content',
+ 'id': this._id + '-content',
+ 'aria-atomic': TRUE
+ })
+ );
+
+ // Set rendered flag and prevent redundant reposition calls for now
+ this.rendered = -1;
+ this.positioning = TRUE;
+
+ // Create title...
+ if(title) {
+ this._createTitle();
+
+ // Update title only if its not a callback (called in toggle if so)
+ if(!$.isFunction(title)) {
+ deferreds.push( this._updateTitle(title, FALSE) );
+ }
+ }
+
+ // Create button
+ if(button) { this._createButton(); }
+
+ // Set proper rendered flag and update content if not a callback function (called in toggle)
+ if(!$.isFunction(text)) {
+ deferreds.push( this._updateContent(text, FALSE) );
+ }
+ this.rendered = TRUE;
+
+ // Setup widget classes
+ this._setWidget();
+
+ // Assign passed event callbacks (before plugins!)
+ $.each(options.events, function(name, callback) {
+ $.isFunction(callback) && tooltip.bind(
+ (name === 'toggle' ? ['tooltipshow','tooltiphide'] : ['tooltip'+name])
+ .join(namespace)+namespace, callback
+ );
+ });
+
+ // Initialize 'render' plugins
+ $.each(PLUGINS, function(name) {
+ var instance;
+ if(this.initialize === 'render' && (instance = this(self))) {
+ self.plugins[name] = instance;
+ }
+ });
+
+ // Assign events
+ this._assignEvents();
+
+ // When deferreds have completed
+ $.when.apply($, deferreds).then(function() {
+ // tooltiprender event
+ self._trigger('render');
+
+ // Reset flags
+ self.positioning = FALSE;
+
+ // Show tooltip if not hidden during wait period
+ if(!self.hiddenDuringWait && (options.show.ready || show)) {
+ self.toggle(TRUE, cache.event, FALSE);
+ }
+ self.hiddenDuringWait = FALSE;
+ });
+
+ // Expose API
+ QTIP.api[this.id] = this;
+
+ return this;
+};
+
+PROTOTYPE.destroy = function(immediate) {
+ // Set flag the signify destroy is taking place to plugins
+ // and ensure it only gets destroyed once!
+ if(this.destroyed) { return this.target; }
+
+ function process() {
+ if(this.destroyed) { return; }
+ this.destroyed = TRUE;
+
+ var target = this.target,
+ title = target.attr(oldtitle);
+
+ // Destroy tooltip if rendered
+ if(this.rendered) {
+ this.tooltip.stop(1,0).find('*').remove().end().remove();
+ }
+
+ // Destroy all plugins
+ $.each(this.plugins, function(name) {
+ this.destroy && this.destroy();
+ });
+
+ // Clear timers and remove bound events
+ clearTimeout(this.timers.show);
+ clearTimeout(this.timers.hide);
+ this._unassignEvents();
+
+ // Remove api object and ARIA attributes
+ target.removeData(NAMESPACE).removeAttr(ATTR_ID)
+ .removeAttr('aria-describedby');
+
+ // Reset old title attribute if removed
+ if(this.options.suppress && title) {
+ target.attr('title', title).removeAttr(oldtitle);
+ }
+
+ // Remove qTip events associated with this API
+ this._unbind(target);
+
+ // Remove ID from used id objects, and delete object references
+ // for better garbage collection and leak protection
+ this.options = this.elements = this.cache = this.timers =
+ this.plugins = this.mouse = NULL;
+
+ // Delete epoxsed API object
+ delete QTIP.api[this.id];
+ }
+
+ // If an immediate destory is needed
+ if(immediate !== TRUE && this.rendered) {
+ tooltip.one('tooltiphidden', $.proxy(process, this));
+ !this.triggering && this.hide();
+ }
+
+ // If we're not in the process of hiding... process
+ else { process.call(this); }
+
+ return this.target;
+};
+
+;function invalidOpt(a) {
+ return a === NULL || $.type(a) !== 'object';
+}
+function invalidContent(c) {
+ return !( $.isFunction(c) || (c && c.attr) || c.length || ($.type(c) === 'object' && (c.jquery || c.then) ));
+}
// Option object sanitizer
-function sanitizeOptions(opts)
-{
- var invalid = function(a) { return a === NULL || 'object' !== typeof a; },
- invalidContent = function(c) { return !$.isFunction(c) && ((!c && !c.attr) || c.length < 1 || ('object' === typeof c && !c.jquery)); };
+function sanitizeOptions(opts) {
+ var content, text, ajax, once;
- if(!opts || 'object' !== typeof opts) { return FALSE; }
+ if(invalidOpt(opts)) { return FALSE; }
- if(invalid(opts.metadata)) {
+ if(invalidOpt(opts.metadata)) {
opts.metadata = { type: opts.metadata };
}
if('content' in opts) {
- if(invalid(opts.content) || opts.content.jquery) {
- opts.content = { text: opts.content };
+ content = opts.content;
+
+ if(invalidOpt(content) || content.jquery || content.done) {
+ content = opts.content = {
+ text: (text = invalidContent(content) ? FALSE : content)
+ };
}
+ else { text = content.text; }
- if(invalidContent(opts.content.text || FALSE)) {
- opts.content.text = FALSE;
+ // DEPRECATED - Old content.ajax plugin functionality
+ // Converts it into the proper Deferred syntax
+ if('ajax' in content) {
+ ajax = content.ajax;
+ once = ajax && ajax.once !== FALSE;
+ delete content.ajax;
+
+ content.text = function(event, api) {
+ var loading = text || $(this).attr(api.options.content.attr) || 'Loading...',
+
+ deferred = $.ajax(
+ $.extend({}, ajax, { context: api })
+ )
+ .then(ajax.success, NULL, ajax.error)
+ .then(function(content) {
+ if(content && once) { api.set('content.text', content); }
+ return content;
+ },
+ function(xhr, status, error) {
+ if(api.destroyed || xhr.status === 0) { return; }
+ api.set('content.text', status + ': ' + error);
+ });
+
+ return !once ? (api.set('content.text', loading), deferred) : loading;
+ };
}
- if('title' in opts.content) {
- if(invalid(opts.content.title)) {
- opts.content.title = { text: opts.content.title };
+ if('title' in content) {
+ if(!invalidOpt(content.title)) {
+ content.button = content.title.button;
+ content.title = content.title.text;
}
- if(invalidContent(opts.content.title.text || FALSE)) {
- opts.content.title.text = FALSE;
+ if(invalidContent(content.title || FALSE)) {
+ content.title = FALSE;
}
}
}
- if('position' in opts && invalid(opts.position)) {
+ if('position' in opts && invalidOpt(opts.position)) {
opts.position = { my: opts.position, at: opts.position };
}
- if('show' in opts && invalid(opts.show)) {
- opts.show = opts.show.jquery ? { target: opts.show } : { event: opts.show };
+ if('show' in opts && invalidOpt(opts.show)) {
+ opts.show = opts.show.jquery ? { target: opts.show } :
+ opts.show === TRUE ? { ready: TRUE } : { event: opts.show };
}
- if('hide' in opts && invalid(opts.hide)) {
+ if('hide' in opts && invalidOpt(opts.hide)) {
opts.hide = opts.hide.jquery ? { target: opts.hide } : { event: opts.hide };
}
- if('style' in opts && invalid(opts.style)) {
+ if('style' in opts && invalidOpt(opts.style)) {
opts.style = { classes: opts.style };
}
// Sanitize plugin options
$.each(PLUGINS, function() {
- if(this.sanitize) { this.sanitize(opts); }
+ this.sanitize && this.sanitize(opts);
});
return opts;
}
-/*
-* Core plugin implementation
-*/
-function QTip(target, options, id, attr)
-{
- // Declare this reference
- var self = this,
- docBody = document.body,
- tooltipID = uitooltip + '-' + id,
- isPositioning = 0,
- isDrawing = 0,
- tooltip = $(),
- namespace = '.qtip-' + id,
- elements, cache;
+// Setup builtin .set() option checks
+CHECKS = PROTOTYPE.checks = {
+ builtin: {
+ // Core checks
+ '^id$': function(obj, o, v, prev) {
+ var id = v === TRUE ? QTIP.nextid : v,
+ new_id = NAMESPACE + '-' + id;
- // Setup class attributes
- self.id = id;
- self.rendered = FALSE;
- self.destroyed = FALSE;
- self.elements = elements = { target: target };
- self.timers = { img: {} };
- self.options = options;
- self.checks = {};
- self.plugins = {};
- self.cache = cache = {
- event: {},
- target: $(),
- disabled: FALSE,
- attr: attr,
- onTarget: FALSE,
- lastClass: ''
- };
+ if(id !== FALSE && id.length > 0 && !$('#'+new_id).length) {
+ this._id = new_id;
- /*
- * Private core functions
- */
- function convertNotation(notation)
- {
- var i = 0, obj, option = options,
+ if(this.rendered) {
+ this.tooltip[0].id = this._id;
+ this.elements.content[0].id = this._id + '-content';
+ this.elements.title[0].id = this._id + '-title';
+ }
+ }
+ else { obj[o] = prev; }
+ },
+ '^prerender': function(obj, o, v) {
+ v && !this.rendered && this.render(this.options.show.ready);
+ },
- // Split notation into array
- levels = notation.split('.');
+ // Content checks
+ '^content.text$': function(obj, o, v) {
+ this._updateContent(v);
+ },
+ '^content.attr$': function(obj, o, v, prev) {
+ if(this.options.content.text === this.target.attr(prev)) {
+ this._updateContent( this.target.attr(v) );
+ }
+ },
+ '^content.title$': function(obj, o, v) {
+ // Remove title if content is null
+ if(!v) { return this._removeTitle(); }
- // Loop through
- while( option = option[ levels[i++] ] ) {
- if(i < levels.length) { obj = option; }
- }
+ // If title isn't already created, create it now and update
+ v && !this.elements.title && this._createTitle();
+ this._updateTitle(v);
+ },
+ '^content.button$': function(obj, o, v) {
+ this._updateButton(v);
+ },
+ '^content.title.(text|button)$': function(obj, o, v) {
+ this.set('content.'+o, v); // Backwards title.text/button compat
+ },
- return [obj || options, levels.pop()];
- }
+ // Position checks
+ '^position.(my|at)$': function(obj, o, v){
+ 'string' === typeof v && (obj[o] = new CORNER(v, o === 'at'));
+ },
+ '^position.container$': function(obj, o, v){
+ this.tooltip.appendTo(v);
+ },
- function triggerEvent(type, args, event) {
- var callback = $.Event('tooltip'+type);
- callback.originalEvent = (event ? $.extend({}, event) : NULL) || cache.event || NULL;
- tooltip.trigger(callback, [self].concat(args || []));
+ // Show checks
+ '^show.ready$': function(obj, o, v) {
+ v && (!this.rendered && this.render(TRUE) || this.toggle(TRUE));
+ },
- return !callback.isDefaultPrevented();
- }
+ // Style checks
+ '^style.classes$': function(obj, o, v, p) {
+ this.tooltip.removeClass(p).addClass(v);
+ },
+ '^style.width|height': function(obj, o, v) {
+ this.tooltip.css(o, v);
+ },
+ '^style.widget|content.title': function() {
+ this._setWidget();
+ },
+ '^style.def': function(obj, o, v) {
+ this.tooltip.toggleClass(CLASS_DEFAULT, !!v);
+ },
- function setWidget()
- {
- var on = options.style.widget;
+ // Events check
+ '^events.(render|show|move|hide|focus|blur)$': function(obj, o, v) {
+ tooltip[($.isFunction(v) ? '' : 'un') + 'bind']('tooltip'+o, v);
+ },
- tooltip.toggleClass('ui-helper-reset '+widget, on).toggleClass(defaultClass, options.style.def && !on);
+ // Properties which require event reassignment
+ '^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)': function() {
+ var posOptions = this.options.position;
- if(elements.content) {
- elements.content.toggleClass(widget+'-content', on);
- }
+ // Set tracking flag
+ tooltip.attr('tracking', posOptions.target === 'mouse' && posOptions.adjust.mouse);
- if(elements.titlebar) {
- elements.titlebar.toggleClass(widget+'-header', on);
+ // Reassign events
+ this._unassignEvents();
+ this._assignEvents();
}
- if(elements.button) {
- elements.button.toggleClass(uitooltip+'-icon', !on);
- }
}
+};
- function removeTitle(reposition)
- {
- if(elements.title) {
- elements.titlebar.remove();
- elements.titlebar = elements.title = elements.button = NULL;
+// Dot notation converter
+function convertNotation(options, notation) {
+ var i = 0, obj, option = options,
- // Reposition if enabled
- if(reposition !== FALSE) { self.reposition(); }
- }
+ // Split notation into array
+ levels = notation.split('.');
+
+ // Loop through
+ while( option = option[ levels[i++] ] ) {
+ if(i < levels.length) { obj = option; }
}
- function createButton()
- {
- var button = options.content.title.button,
- isString = typeof button === 'string',
- close = isString ? button : 'Close tooltip';
+ return [obj || options, levels.pop()];
+}
- if(elements.button) { elements.button.remove(); }
+PROTOTYPE.get = function(notation) {
+ if(this.destroyed) { return this; }
- // Use custom button if one was supplied by user, else use default
- if(button.jquery) {
- elements.button = button;
- }
- else {
- elements.button = $('<a />', {
- 'class': 'ui-state-default ui-tooltip-close ' + (options.style.widget ? '' : uitooltip+'-icon'),
- 'title': close,
- 'aria-label': close
- })
- .prepend(
- $('<span />', {
- 'class': 'ui-icon ui-icon-close',
- 'html': '×'
- })
- );
- }
+ var o = convertNotation(this.options, notation.toLowerCase()),
+ result = o[0][ o[1] ];
- // Create button and setup attributes
- elements.button.appendTo(elements.titlebar)
- .attr('role', 'button')
- .click(function(event) {
- if(!tooltip.hasClass(disabled)) { self.hide(event); }
- return FALSE;
- });
+ return result.precedance ? result.string() : result;
+};
- // Redraw the tooltip when we're done
- self.redraw();
- }
+function setCallback(notation, args) {
+ var category, rule, match;
- function createTitle()
- {
- var id = tooltipID+'-title';
+ for(category in this.checks) {
+ for(rule in this.checks[category]) {
+ if(match = (new RegExp(rule, 'i')).exec(notation)) {
+ args.push(match);
- // Destroy previous title element, if present
- if(elements.titlebar) { removeTitle(); }
+ if(category === 'builtin' || this.plugins[category]) {
+ this.checks[category][rule].apply(
+ this.plugins[category] || this, args
+ );
+ }
+ }
+ }
+ }
+}
- // Create title bar and title elements
- elements.titlebar = $('<div />', {
- 'class': uitooltip + '-titlebar ' + (options.style.widget ? 'ui-widget-header' : '')
- })
- .append(
- elements.title = $('<div />', {
- 'id': id,
- 'class': uitooltip + '-title',
- 'aria-atomic': TRUE
- })
- )
- .insertBefore(elements.content)
+var rmove = /^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,
+ rrender = /^prerender|show\.ready/i;
- // Button-specific events
- .delegate('.ui-tooltip-close', 'mousedown keydown mouseup keyup mouseout', function(event) {
- $(this).toggleClass('ui-state-active ui-state-focus', event.type.substr(-4) === 'down');
- })
- .delegate('.ui-tooltip-close', 'mouseover mouseout', function(event){
- $(this).toggleClass('ui-state-hover', event.type === 'mouseover');
- });
+PROTOTYPE.set = function(option, value) {
+ if(this.destroyed) { return this; }
- // Create button if enabled
- if(options.content.title.button) { createButton(); }
+ var rendered = this.rendered,
+ reposition = FALSE,
+ options = this.options,
+ checks = this.checks,
+ name;
- // Redraw the tooltip dimensions if it's rendered
- else if(self.rendered){ self.redraw(); }
+ // Convert singular option/value pair into object form
+ if('string' === typeof option) {
+ name = option; option = {}; option[name] = value;
}
+ else { option = $.extend({}, option); }
- function updateButton(button)
- {
- var elem = elements.button,
- title = elements.title;
-
- // Make sure tooltip is rendered and if not, return
- if(!self.rendered) { return FALSE; }
-
- if(!button) {
- elem.remove();
+ // Set all of the defined options to their new values
+ $.each(option, function(notation, value) {
+ if(!rendered && !rrender.test(notation)) {
+ delete option[notation]; return;
}
- else {
- if(!title) {
- createTitle();
- }
- createButton();
- }
- }
- function updateTitle(content, reposition)
- {
- var elem = elements.title;
+ // Set new obj value
+ var obj = convertNotation(options, notation.toLowerCase()), previous;
+ previous = obj[0][ obj[1] ];
+ obj[0][ obj[1] ] = value && value.nodeType ? $(value) : value;
- // Make sure tooltip is rendered and if not, return
- if(!self.rendered || !content) { return FALSE; }
+ // Also check if we need to reposition
+ reposition = rmove.test(notation) || reposition;
- // Use function to parse content
- if($.isFunction(content)) {
- content = content.call(target, cache.event, self);
- }
+ // Set the new params for the callback
+ option[notation] = [obj[0], obj[1], value, previous];
+ });
- // Remove title if callback returns false or null/undefined (but not '')
- if(content === FALSE || (!content && content !== '')) { return removeTitle(FALSE); }
+ // Re-sanitize options
+ sanitizeOptions(options);
- // Append new content if its a DOM array and show it if hidden
- else if(content.jquery && content.length > 0) {
- elem.empty().append(content.css({ display: 'block' }));
- }
+ /*
+ * Execute any valid callbacks for the set options
+ * Also set positioning flag so we don't get loads of redundant repositioning calls.
+ */
+ this.positioning = TRUE;
+ $.each(option, $.proxy(setCallback, this));
+ this.positioning = FALSE;
- // Content is a regular string, insert the new content
- else { elem.html(content); }
-
- // Redraw and reposition
- self.redraw();
- if(reposition !== FALSE && self.rendered && tooltip[0].offsetWidth > 0) {
- self.reposition(cache.event);
- }
+ // Update position if needed
+ if(this.rendered && this.tooltip[0].offsetWidth > 0 && reposition) {
+ this.reposition( options.position.target === 'mouse' ? NULL : this.cache.event );
}
- function updateContent(content, reposition)
- {
- var elem = elements.content;
+ return this;
+};
- // Make sure tooltip is rendered and content is defined. If not return
- if(!self.rendered || !content) { return FALSE; }
+;PROTOTYPE._update = function(content, element, reposition) {
+ var self = this,
+ cache = this.cache;
- // Use function to parse content
- if($.isFunction(content)) {
- content = content.call(target, cache.event, self) || '';
- }
+ // Make sure tooltip is rendered and content is defined. If not return
+ if(!this.rendered || !content) { return FALSE; }
- // Append new content if its a DOM array and show it if hidden
- if(content.jquery && content.length > 0) {
- elem.empty().append(content.css({ display: 'block' }));
- }
+ // Use function to parse content
+ if($.isFunction(content)) {
+ content = content.call(this.elements.target, cache.event, this) || '';
+ }
- // Content is a regular string, insert the new content
- else { elem.html(content); }
+ // Handle deferred content
+ if($.isFunction(content.then)) {
+ cache.waiting = TRUE;
+ return content.then(function(c) {
+ cache.waiting = FALSE;
+ return self._update(c, element);
+ }, NULL, function(e) {
+ return self._update(e, element);
+ });
+ }
- // Image detection
- function detectImages(next) {
- var images, srcs = {};
+ // If content is null... return false
+ if(content === FALSE || (!content && content !== '')) { return FALSE; }
- function imageLoad(image) {
- // Clear src from object and any timers and events associated with the image
- if(image) {
- delete srcs[image.src];
- clearTimeout(self.timers.img[image.src]);
- $(image).unbind(namespace);
- }
+ // Append new content if its a DOM array and show it if hidden
+ if(content.jquery && content.length > 0) {
+ element.children().detach().end().append( content.css({ display: 'block' }) );
+ }
- // If queue is empty after image removal, update tooltip and continue the queue
- if($.isEmptyObject(srcs)) {
- self.redraw();
- if(reposition !== FALSE) {
- self.reposition(cache.event);
- }
+ // Content is a regular string, insert the new content
+ else { element.html(content); }
- next();
- }
+ // If imagesLoaded is included, ensure images have loaded and return promise
+ cache.waiting = TRUE;
+
+ return ( $.fn.imagesLoaded ? element.imagesLoaded() : $.Deferred().resolve($([])) )
+ .done(function(images) {
+ cache.waiting = FALSE;
+
+ // Reposition if rendered
+ if(images.length && self.rendered && self.tooltip[0].offsetWidth > 0) {
+ self.reposition(cache.event, !images.length);
}
+ })
+ .promise();
+};
- // Find all content images without dimensions, and if no images were found, continue
- if((images = elem.find('img[src]:not([height]):not([width])')).length === 0) { return imageLoad(); }
+PROTOTYPE._updateContent = function(content, reposition) {
+ this._update(content, this.elements.content, reposition);
+};
- // Apply timer to each image to poll for dimensions
- images.each(function(i, elem) {
- // Skip if the src is already present
- if(srcs[elem.src] !== undefined) { return; }
+PROTOTYPE._updateTitle = function(content, reposition) {
+ if(this._update(content, this.elements.title, reposition) === FALSE) {
+ this._removeTitle(FALSE);
+ }
+};
- // Keep track of how many times we poll for image dimensions.
- // If it doesn't return in a reasonable amount of time, it's better
- // to display the tooltip, rather than hold up the queue.
- var iterations = 0, maxIterations = 3;
+PROTOTYPE._createTitle = function()
+{
+ var elements = this.elements,
+ id = this._id+'-title';
- (function timer(){
- // When the dimensions are found, remove the image from the queue
- if(elem.height || elem.width || (iterations > maxIterations)) { return imageLoad(elem); }
+ // Destroy previous title element, if present
+ if(elements.titlebar) { this._removeTitle(); }
- // Increase iterations and restart timer
- iterations += 1;
- self.timers.img[elem.src] = setTimeout(timer, 700);
- }());
+ // Create title bar and title elements
+ elements.titlebar = $('<div />', {
+ 'class': NAMESPACE + '-titlebar ' + (this.options.style.widget ? createWidgetClass('header') : '')
+ })
+ .append(
+ elements.title = $('<div />', {
+ 'id': id,
+ 'class': NAMESPACE + '-title',
+ 'aria-atomic': TRUE
+ })
+ )
+ .insertBefore(elements.content)
- // Also apply regular load/error event handlers
- $(elem).bind('error'+namespace+' load'+namespace, function(){ imageLoad(this); });
+ // Button-specific events
+ .delegate('.qtip-close', 'mousedown keydown mouseup keyup mouseout', function(event) {
+ $(this).toggleClass('ui-state-active ui-state-focus', event.type.substr(-4) === 'down');
+ })
+ .delegate('.qtip-close', 'mouseover mouseout', function(event){
+ $(this).toggleClass('ui-state-hover', event.type === 'mouseover');
+ });
- // Store the src and element in our object
- srcs[elem.src] = elem;
- });
- }
+ // Create button if enabled
+ if(this.options.content.button) { this._createButton(); }
+};
- /*
- * If we're still rendering... insert into 'fx' queue our image dimension
- * checker which will halt the showing of the tooltip until image dimensions
- * can be detected properly.
- */
- if(self.rendered < 0) { tooltip.queue('fx', detectImages); }
+PROTOTYPE._removeTitle = function(reposition)
+{
+ var elements = this.elements;
- // We're fully rendered, so reset isDrawing flag and proceed without queue delay
- else { isDrawing = 0; detectImages($.noop); }
+ if(elements.title) {
+ elements.titlebar.remove();
+ elements.titlebar = elements.title = elements.button = NULL;
- return self;
+ // Reposition if enabled
+ if(reposition !== FALSE) { this.reposition(); }
}
+};
- function assignEvents()
- {
- var posOptions = options.position,
- targets = {
- show: options.show.target,
- hide: options.hide.target,
- viewport: $(posOptions.viewport),
- document: $(document),
- body: $(document.body),
- window: $(window)
- },
- events = {
- show: $.trim('' + options.show.event).split(' '),
- hide: $.trim('' + options.hide.event).split(' ')
- },
- IE6 = $.browser.msie && parseInt($.browser.version, 10) === 6;
+;PROTOTYPE.reposition = function(event, effect) {
+ if(!this.rendered || this.positioning || this.destroyed) { return this; }
- // Define show event method
- function showMethod(event)
- {
- if(tooltip.hasClass(disabled)) { return FALSE; }
+ // Set positioning flag
+ this.positioning = TRUE;
- // Clear hide timers
- clearTimeout(self.timers.show);
- clearTimeout(self.timers.hide);
+ var cache = this.cache,
+ tooltip = this.tooltip,
+ posOptions = this.options.position,
+ target = posOptions.target,
+ my = posOptions.my,
+ at = posOptions.at,
+ viewport = posOptions.viewport,
+ container = posOptions.container,
+ adjust = posOptions.adjust,
+ method = adjust.method.split(' '),
+ elemWidth = tooltip.outerWidth(FALSE),
+ elemHeight = tooltip.outerHeight(FALSE),
+ targetWidth = 0,
+ targetHeight = 0,
+ type = tooltip.css('position'),
+ position = { left: 0, top: 0 },
+ visible = tooltip[0].offsetWidth > 0,
+ isScroll = event && event.type === 'scroll',
+ win = $(window),
+ doc = container[0].ownerDocument,
+ mouse = this.mouse,
+ pluginCalculations, offset;
- // Start show timer
- var callback = function(){ self.toggle(TRUE, event); };
- if(options.show.delay > 0) {
- self.timers.show = setTimeout(callback, options.show.delay);
- }
- else{ callback(); }
- }
+ // Check if absolute position was passed
+ if($.isArray(target) && target.length === 2) {
+ // Force left top and set position
+ at = { x: LEFT, y: TOP };
+ position = { left: target[0], top: target[1] };
+ }
- // Define hide method
- function hideMethod(event)
- {
- if(tooltip.hasClass(disabled) || isPositioning || isDrawing) { return FALSE; }
+ // Check if mouse was the target
+ else if(target === 'mouse' && ((event && event.pageX) || cache.event.pageX)) {
+ // Force left top to allow flipping
+ at = { x: LEFT, y: TOP };
- // Check if new target was actually the tooltip element
- var relatedTarget = $(event.relatedTarget || event.target),
- ontoTooltip = relatedTarget.closest(selector)[0] === tooltip[0],
- ontoTarget = relatedTarget[0] === targets.show[0];
+ // Use cached event if one isn't available for positioning
+ event = mouse && mouse.pageX && (adjust.mouse || !event || !event.pageX) ? mouse :
+ (event && (event.type === 'resize' || event.type === 'scroll') ? cache.event :
+ event && event.pageX && event.type === 'mousemove' ? event :
+ (!adjust.mouse || this.options.show.distance) && cache.origin && cache.origin.pageX ? cache.origin :
+ event) || event || cache.event || mouse || {};
- // Clear timers and stop animation queue
- clearTimeout(self.timers.show);
- clearTimeout(self.timers.hide);
+ // Calculate body and container offset and take them into account below
+ if(type !== 'static') { position = container.offset(); }
+ if(doc.body.offsetWidth !== (window.innerWidth || doc.documentElement.clientWidth)) { offset = $(doc.body).offset(); }
- // Prevent hiding if tooltip is fixed and event target is the tooltip. Or if mouse positioning is enabled and cursor momentarily overlaps
- if((posOptions.target === 'mouse' && ontoTooltip) || (options.hide.fixed && ((/mouse(out|leave|move)/).test(event.type) && (ontoTooltip || ontoTarget)))) {
- try { event.preventDefault(); event.stopImmediatePropagation(); } catch(e) {} return;
- }
+ // Use event coordinates for position
+ position = {
+ left: event.pageX - position.left + (offset && offset.left || 0),
+ top: event.pageY - position.top + (offset && offset.top || 0)
+ };
- // If tooltip has displayed, start hide timer
- if(options.hide.delay > 0) {
- self.timers.hide = setTimeout(function(){ self.hide(event); }, options.hide.delay);
- }
- else{ self.hide(event); }
+ // Scroll events are a pain, some browsers
+ if(adjust.mouse && isScroll) {
+ position.left -= mouse.scrollX - win.scrollLeft();
+ position.top -= mouse.scrollY - win.scrollTop();
}
+ }
- // Define inactive method
- function inactiveMethod(event)
- {
- if(tooltip.hasClass(disabled)) { return FALSE; }
-
- // Clear timer
- clearTimeout(self.timers.inactive);
- self.timers.inactive = setTimeout(function(){ self.hide(event); }, options.hide.inactive);
+ // Target wasn't mouse or absolute...
+ else {
+ // Check if event targetting is being used
+ if(target === 'event' && event && event.target && event.type !== 'scroll' && event.type !== 'resize') {
+ cache.target = $(event.target);
}
-
- function repositionMethod(event) {
- if(self.rendered && tooltip[0].offsetWidth > 0) { self.reposition(event); }
+ else if(target !== 'event'){
+ cache.target = $(target.jquery ? target : elements.target);
}
+ target = cache.target;
- // On mouseenter/mouseleave...
- tooltip.bind('mouseenter'+namespace+' mouseleave'+namespace, function(event) {
- var state = event.type === 'mouseenter';
+ // Parse the target into a jQuery object and make sure there's an element present
+ target = $(target).eq(0);
+ if(target.length === 0) { return this; }
- // Focus the tooltip on mouseenter (z-index stacking)
- if(state) { self.focus(event); }
+ // Check if window or document is the target
+ else if(target[0] === document || target[0] === window) {
+ targetWidth = BROWSER.iOS ? window.innerWidth : target.width();
+ targetHeight = BROWSER.iOS ? window.innerHeight : target.height();
- // Add hover class
- tooltip.toggleClass(hoverClass, state);
- });
-
- // If using mouseout/mouseleave as a hide event...
- if(/mouse(out|leave)/i.test(options.hide.event)) {
- // Hide tooltips when leaving current window/frame (but not select/option elements)
- if(options.hide.leave === 'window') {
- targets.window.bind('mouseout'+namespace+' blur'+namespace, function(event) {
- if(!/select|option/.test(event.target.nodeName) && !event.relatedTarget) { self.hide(event); }
- });
+ if(target[0] === window) {
+ position = {
+ top: (viewport || target).scrollTop(),
+ left: (viewport || target).scrollLeft()
+ };
}
}
- // Enable hide.fixed
- if(options.hide.fixed) {
- // Add tooltip as a hide target
- targets.hide = targets.hide.add(tooltip);
+ // Check if the target is an <AREA> element
+ else if(PLUGINS.imagemap && target.is('area')) {
+ pluginCalculations = PLUGINS.imagemap(this, target, at, PLUGINS.viewport ? method : FALSE);
+ }
- // Clear hide timer on tooltip hover to prevent it from closing
- tooltip.bind('mouseover'+namespace, function() {
- if(!tooltip.hasClass(disabled)) { clearTimeout(self.timers.hide); }
- });
+ // Check if the target is an SVG element
+ else if(PLUGINS.svg && target[0].ownerSVGElement) {
+ pluginCalculations = PLUGINS.svg(this, target, at, PLUGINS.viewport ? method : FALSE);
}
- /*
- * Make sure hoverIntent functions properly by using mouseleave to clear show timer if
- * mouseenter/mouseout is used for show.event, even if it isn't in the users options.
- */
- else if(/mouse(over|enter)/i.test(options.show.event)) {
- targets.hide.bind('mouseleave'+namespace, function(event) {
- clearTimeout(self.timers.show);
- });
+ // Otherwise use regular jQuery methods
+ else {
+ targetWidth = target.outerWidth(FALSE);
+ targetHeight = target.outerHeight(FALSE);
+ position = target.offset();
}
- // Hide tooltip on document mousedown if unfocus events are enabled
- if(('' + options.hide.event).indexOf('unfocus') > -1) {
- posOptions.container.closest('html').bind('mousedown'+namespace+' touchstart'+namespace, function(event) {
- var elem = $(event.target),
- enabled = self.rendered && !tooltip.hasClass(disabled) && tooltip[0].offsetWidth > 0,
- isAncestor = elem.parents(selector).filter(tooltip[0]).length > 0;
-
- if(elem[0] !== target[0] && elem[0] !== tooltip[0] && !isAncestor &&
- !target.has(elem[0]).length && !elem.attr('disabled')
- ) {
- self.hide(event);
- }
- });
+ // Parse returned plugin values into proper variables
+ if(pluginCalculations) {
+ targetWidth = pluginCalculations.width;
+ targetHeight = pluginCalculations.height;
+ offset = pluginCalculations.offset;
+ position = pluginCalculations.position;
}
- // Check if the tooltip hides when inactive
- if('number' === typeof options.hide.inactive) {
- // Bind inactive method to target as a custom event
- targets.show.bind('qtip-'+id+'-inactive', inactiveMethod);
+ // Adjust position to take into account offset parents
+ position = this.reposition.offset(target, position, container);
- // Define events which reset the 'inactive' event handler
- $.each(QTIP.inactiveEvents, function(index, type){
- targets.hide.add(elements.tooltip).bind(type+namespace+'-inactive', inactiveMethod);
- });
+ // Adjust for position.fixed tooltips (and also iOS scroll bug in v3.2-4.0 & v4.3-4.3.2)
+ if((BROWSER.iOS > 3.1 && BROWSER.iOS < 4.1) ||
+ (BROWSER.iOS >= 4.3 && BROWSER.iOS < 4.33) ||
+ (!BROWSER.iOS && type === 'fixed')
+ ){
+ position.left -= win.scrollLeft();
+ position.top -= win.scrollTop();
}
- // Apply hide events
- $.each(events.hide, function(index, type) {
- var showIndex = $.inArray(type, events.show),
- targetHide = $(targets.hide);
-
- // Both events and targets are identical, apply events using a toggle
- if((showIndex > -1 && targetHide.add(targets.show).length === targetHide.length) || type === 'unfocus')
- {
- targets.show.bind(type+namespace, function(event) {
- if(tooltip[0].offsetWidth > 0) { hideMethod(event); }
- else { showMethod(event); }
- });
-
- // Don't bind the event again
- delete events.show[ showIndex ];
- }
-
- // Events are not identical, bind normally
- else { targets.hide.bind(type+namespace, hideMethod); }
- });
-
- // Apply show events
- $.each(events.show, function(index, type) {
- targets.show.bind(type+namespace, showMethod);
- });
-
- // Check if the tooltip hides when mouse is moved a certain distance
- if('number' === typeof options.hide.distance) {
- // Bind mousemove to target to detect distance difference
- targets.show.add(tooltip).bind('mousemove'+namespace, function(event) {
- var origin = cache.origin || {},
- limit = options.hide.distance,
- abs = Math.abs;
-
- // Check if the movement has gone beyond the limit, and hide it if so
- if(abs(event.pageX - origin.pageX) >= limit || abs(event.pageY - origin.pageY) >= limit) {
- self.hide(event);
- }
- });
+ // Adjust position relative to target
+ if(!pluginCalculations || (pluginCalculations && pluginCalculations.adjustable !== FALSE)) {
+ position.left += at.x === RIGHT ? targetWidth : at.x === CENTER ? targetWidth / 2 : 0;
+ position.top += at.y === BOTTOM ? targetHeight : at.y === CENTER ? targetHeight / 2 : 0;
}
+ }
- // Mouse positioning events
- if(posOptions.target === 'mouse') {
- // Cache mousemove coords on show targets
- targets.show.bind('mousemove'+namespace, function(event) {
- MOUSE = { pageX: event.pageX, pageY: event.pageY, type: 'mousemove' };
- });
+ // Adjust position relative to tooltip
+ position.left += adjust.x + (my.x === RIGHT ? -elemWidth : my.x === CENTER ? -elemWidth / 2 : 0);
+ position.top += adjust.y + (my.y === BOTTOM ? -elemHeight : my.y === CENTER ? -elemHeight / 2 : 0);
- // If mouse adjustment is on...
- if(posOptions.adjust.mouse) {
- // Apply a mouseleave event so we don't get problems with overlapping
- if(options.hide.event) {
- // Hide when we leave the tooltip and not onto the show target
- tooltip.bind('mouseleave'+namespace, function(event) {
- if((event.relatedTarget || event.target) !== targets.show[0]) { self.hide(event); }
- });
+ // Use viewport adjustment plugin if enabled
+ if(PLUGINS.viewport) {
+ position.adjusted = PLUGINS.viewport(
+ this, position, posOptions, targetWidth, targetHeight, elemWidth, elemHeight
+ );
- // Track if we're on the target or not
- elements.target.bind('mouseenter'+namespace+' mouseleave'+namespace, function(event) {
- cache.onTarget = event.type === 'mouseenter';
- });
- }
+ // Apply offsets supplied by positioning plugin (if used)
+ if(offset && position.adjusted.left) { position.left += offset.left; }
+ if(offset && position.adjusted.top) { position.top += offset.top; }
+ }
- // Update tooltip position on mousemove
- targets.document.bind('mousemove'+namespace, function(event) {
- // Update the tooltip position only if the tooltip is visible and adjustment is enabled
- if(self.rendered && cache.onTarget && !tooltip.hasClass(disabled) && tooltip[0].offsetWidth > 0) {
- self.reposition(event || MOUSE);
- }
- });
- }
- }
+ // Viewport adjustment is disabled, set values to zero
+ else { position.adjusted = { left: 0, top: 0 }; }
- // Adjust positions of the tooltip on window resize if enabled
- if(posOptions.adjust.resize || targets.viewport.length) {
- ($.event.special.resize ? targets.viewport : targets.window).bind('resize'+namespace, repositionMethod);
- }
+ // tooltipmove event
+ if(!this._trigger('move', [position, viewport.elem || viewport], event)) { return this; }
+ delete position.adjusted;
- // Adjust tooltip position on scroll if screen adjustment is enabled
- if(targets.viewport.length || (IE6 && tooltip.css('position') === 'fixed')) {
- targets.viewport.bind('scroll'+namespace, repositionMethod);
- }
+ // If effect is disabled, target it mouse, no animation is defined or positioning gives NaN out, set CSS directly
+ if(effect === FALSE || !visible || isNaN(position.left) || isNaN(position.top) || target === 'mouse' || !$.isFunction(posOptions.effect)) {
+ tooltip.css(position);
}
- function unassignEvents()
- {
- var targets = [
- options.show.target[0],
- options.hide.target[0],
- self.rendered && elements.tooltip[0],
- options.position.container[0],
- options.position.viewport[0],
- options.position.container.closest('html')[0], // unfocus
- window,
- document
- ];
+ // Use custom function if provided
+ else if($.isFunction(posOptions.effect)) {
+ posOptions.effect.call(tooltip, this, $.extend({}, position));
+ tooltip.queue(function(next) {
+ // Reset attributes to avoid cross-browser rendering bugs
+ $(this).css({ opacity: '', height: '' });
+ if(BROWSER.ie) { this.style.removeAttribute('filter'); }
- // Check if tooltip is rendered
- if(self.rendered) {
- $([]).pushStack( $.grep(targets, function(i){ return typeof i === 'object'; }) ).unbind(namespace);
- }
-
- // Tooltip isn't yet rendered, remove render event
- else { options.show.target.unbind(namespace+'-create'); }
+ next();
+ });
}
- // Setup builtin .set() option checks
- self.checks.builtin = {
- // Core checks
- '^id$': function(obj, o, v) {
- var id = v === TRUE ? QTIP.nextid : v,
- tooltipID = uitooltip + '-' + id;
+ // Set positioning flag
+ this.positioning = FALSE;
- if(id !== FALSE && id.length > 0 && !$('#'+tooltipID).length) {
- tooltip[0].id = tooltipID;
- elements.content[0].id = tooltipID + '-content';
- elements.title[0].id = tooltipID + '-title';
- }
- },
+ return this;
+};
- // Content checks
- '^content.text$': function(obj, o, v){ updateContent(v); },
- '^content.title.text$': function(obj, o, v) {
- // Remove title if content is null
- if(!v) { return removeTitle(); }
+// Custom (more correct for qTip!) offset calculator
+PROTOTYPE.reposition.offset = function(elem, pos, container) {
+ if(!container[0]) { return pos; }
- // If title isn't already created, create it now and update
- if(!elements.title && v) { createTitle(); }
- updateTitle(v);
- },
- '^content.title.button$': function(obj, o, v){ updateButton(v); },
+ var ownerDocument = $(elem[0].ownerDocument),
+ quirks = !!BROWSER.ie && document.compatMode !== 'CSS1Compat',
+ parent = container[0],
+ scrolled, position, parentOffset, overflow;
- // Position checks
- '^position.(my|at)$': function(obj, o, v){
- // Parse new corner value into Corner objecct
- if('string' === typeof v) {
- obj[o] = new PLUGINS.Corner(v);
+ function scroll(e, i) {
+ pos.left += i * e.scrollLeft();
+ pos.top += i * e.scrollTop();
+ }
+
+ // Compensate for non-static containers offset
+ do {
+ if((position = $.css(parent, 'position')) !== 'static') {
+ if(position === 'fixed') {
+ parentOffset = parent.getBoundingClientRect();
+ scroll(ownerDocument, -1);
}
- },
- '^position.container$': function(obj, o, v){
- if(self.rendered) { tooltip.appendTo(v); }
- },
+ else {
+ parentOffset = $(parent).position();
+ parentOffset.left += (parseFloat($.css(parent, 'borderLeftWidth')) || 0);
+ parentOffset.top += (parseFloat($.css(parent, 'borderTopWidth')) || 0);
+ }
- // Show checks
- '^show.ready$': function() {
- if(!self.rendered) { self.render(1); }
- else { self.toggle(TRUE); }
- },
+ pos.left -= parentOffset.left + (parseFloat($.css(parent, 'marginLeft')) || 0);
+ pos.top -= parentOffset.top + (parseFloat($.css(parent, 'marginTop')) || 0);
- // Style checks
- '^style.classes$': function(obj, o, v) {
- tooltip.attr('class', uitooltip + ' qtip ' + v);
- },
- '^style.widget|content.title': setWidget,
+ // If this is the first parent element with an overflow of "scroll" or "auto", store it
+ if(!scrolled && (overflow = $.css(parent, 'overflow')) !== 'hidden' && overflow !== 'visible') { scrolled = $(parent); }
+ }
+ }
+ while((parent = parent.offsetParent));
- // Events check
- '^events.(render|show|move|hide|focus|blur)$': function(obj, o, v) {
- tooltip[($.isFunction(v) ? '' : 'un') + 'bind']('tooltip'+o, v);
- },
+ // Compensate for containers scroll if it also has an offsetParent (or in IE quirks mode)
+ if(scrolled && (scrolled[0] !== ownerDocument[0] || quirks)) {
+ scroll(scrolled, 1);
+ }
- // Properties which require event reassignment
- '^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)': function() {
- var posOptions = options.position;
+ return pos;
+};
- // Set tracking flag
- tooltip.attr('tracking', posOptions.target === 'mouse' && posOptions.adjust.mouse);
+// Corner class
+var C = (CORNER = PROTOTYPE.reposition.Corner = function(corner, forceY) {
+ corner = ('' + corner).replace(/([A-Z])/, ' $1').replace(/middle/gi, CENTER).toLowerCase();
+ this.x = (corner.match(/left|right/i) || corner.match(/center/) || ['inherit'])[0].toLowerCase();
+ this.y = (corner.match(/top|bottom|center/i) || ['inherit'])[0].toLowerCase();
+ this.forceY = !!forceY;
- // Reassign events
- unassignEvents(); assignEvents();
- }
- };
+ var f = corner.charAt(0);
+ this.precedance = (f === 't' || f === 'b' ? Y : X);
+}).prototype;
- /*
- * Public API methods
- */
- $.extend(self, {
- render: function(show)
- {
- if(self.rendered) { return self; } // If tooltip has already been rendered, exit
+C.invert = function(z, center) {
+ this[z] = this[z] === LEFT ? RIGHT : this[z] === RIGHT ? LEFT : center || this[z];
+};
- var text = options.content.text,
- title = options.content.title.text,
- posOptions = options.position;
+C.string = function() {
+ var x = this.x, y = this.y;
+ return x === y ? x : this.precedance === Y || (this.forceY && y !== 'center') ? y+' '+x : x+' '+y;
+};
- // Add ARIA attributes to target
- $.attr(target[0], 'aria-describedby', tooltipID);
+C.abbrev = function() {
+ var result = this.string().split(' ');
+ return result[0].charAt(0) + (result[1] && result[1].charAt(0) || '');
+};
- // Create tooltip element
- tooltip = elements.tooltip = $('<div/>', {
- 'id': tooltipID,
- 'class': uitooltip + ' qtip ' + defaultClass + ' ' + options.style.classes + ' '+ uitooltip + '-pos-' + options.position.my.abbrev(),
- 'width': options.style.width || '',
- 'height': options.style.height || '',
- 'tracking': posOptions.target === 'mouse' && posOptions.adjust.mouse,
+C.clone = function() {
+ return new CORNER( this.string(), this.forceY );
+};;
+PROTOTYPE.toggle = function(state, event) {
+ var cache = this.cache,
+ options = this.options,
+ tooltip = this.tooltip;
- /* ARIA specific attributes */
- 'role': 'alert',
- 'aria-live': 'polite',
- 'aria-atomic': FALSE,
- 'aria-describedby': tooltipID + '-content',
- 'aria-hidden': TRUE
- })
- .toggleClass(disabled, cache.disabled)
- .data('qtip', self)
- .appendTo(options.position.container)
- .append(
- // Create content element
- elements.content = $('<div />', {
- 'class': uitooltip + '-content',
- 'id': tooltipID + '-content',
- 'aria-atomic': TRUE
- })
- );
+ // Try to prevent flickering when tooltip overlaps show element
+ if(event) {
+ if((/over|enter/).test(event.type) && (/out|leave/).test(cache.event.type) &&
+ options.show.target.add(event.target).length === options.show.target.length &&
+ tooltip.has(event.relatedTarget).length) {
+ return this;
+ }
- // Set rendered flag and prevent redundant redraw/reposition calls for now
- self.rendered = -1;
- isDrawing = 1; isPositioning = 1;
+ // Cache event
+ cache.event = $.extend({}, event);
+ }
+
+ // If we're currently waiting and we've just hidden... stop it
+ this.waiting && !state && (this.hiddenDuringWait = TRUE);
- // Create title...
- if(title) {
- createTitle();
+ // Render the tooltip if showing and it isn't already
+ if(!this.rendered) { return state ? this.render(1) : this; }
+ else if(this.destroyed || this.disabled) { return this; }
- // Update title only if its not a callback (called in toggle if so)
- if(!$.isFunction(title)) { updateTitle(title, FALSE); }
- }
+ var type = state ? 'show' : 'hide',
+ opts = this.options[type],
+ otherOpts = this.options[ !state ? 'show' : 'hide' ],
+ posOptions = this.options.position,
+ contentOptions = this.options.content,
+ width = this.tooltip.css('width'),
+ visible = this.tooltip[0].offsetWidth > 0,
+ animate = state || opts.target.length === 1,
+ sameTarget = !event || opts.target.length < 2 || cache.target[0] === event.target,
+ identicalState, allow, showEvent, delay;
- // Set proper rendered flag and update content if not a callback function (called in toggle)
- if(!$.isFunction(text)) { updateContent(text, FALSE); }
- self.rendered = TRUE;
+ // Detect state if valid one isn't provided
+ if((typeof state).search('boolean|number')) { state = !visible; }
- // Setup widget classes
- setWidget();
+ // Check if the tooltip is in an identical state to the new would-be state
+ identicalState = !tooltip.is(':animated') && visible === state && sameTarget;
- // Assign passed event callbacks (before plugins!)
- $.each(options.events, function(name, callback) {
- if($.isFunction(callback)) {
- tooltip.bind(name === 'toggle' ? 'tooltipshow tooltiphide' : 'tooltip'+name, callback);
- }
- });
+ // Fire tooltip(show/hide) event and check if destroyed
+ allow = !identicalState ? !!this._trigger(type, [90]) : NULL;
- // Initialize 'render' plugins
- $.each(PLUGINS, function() {
- if(this.initialize === 'render') { this(self); }
- });
+ // If the user didn't stop the method prematurely and we're showing the tooltip, focus it
+ if(allow !== FALSE && state) { this.focus(event); }
- // Assign events
- assignEvents();
+ // If the state hasn't changed or the user stopped it, return early
+ if(!allow || identicalState) { return this; }
- /* Queue this part of the render process in our fx queue so we can
- * load images before the tooltip renders fully.
- *
- * See: updateContent method
- */
- tooltip.queue('fx', function(next) {
- // tooltiprender event
- triggerEvent('render');
+ // Set ARIA hidden attribute
+ $.attr(tooltip[0], 'aria-hidden', !!!state);
- // Reset flags
- isDrawing = 0; isPositioning = 0;
+ // Execute state specific properties
+ if(state) {
+ // Store show origin coordinates
+ cache.origin = $.extend({}, this.mouse);
- // Redraw the tooltip manually now we're fully rendered
- self.redraw();
+ // Update tooltip content & title if it's a dynamic function
+ if($.isFunction(contentOptions.text)) { this._updateContent(contentOptions.text, FALSE); }
+ if($.isFunction(contentOptions.title)) { this._updateTitle(contentOptions.title, FALSE); }
- // Show tooltip if needed
- if(options.show.ready || show) {
- self.toggle(TRUE, cache.event, FALSE);
- }
+ // Cache mousemove events for positioning purposes (if not already tracking)
+ if(!trackingBound && posOptions.target === 'mouse' && posOptions.adjust.mouse) {
+ $(document).bind('mousemove.'+NAMESPACE, this._storeMouse);
+ trackingBound = TRUE;
+ }
- next(); // Move on to next method in queue
- });
+ // Update the tooltip position (set width first to prevent viewport/max-width issues)
+ if(!width) { tooltip.css('width', tooltip.outerWidth(FALSE)); }
+ this.reposition(event, arguments[2]);
+ if(!width) { tooltip.css('width', ''); }
- return self;
- },
+ // Hide other tooltips if tooltip is solo
+ if(!!opts.solo) {
+ (typeof opts.solo === 'string' ? $(opts.solo) : $(SELECTOR, opts.solo))
+ .not(tooltip).not(opts.target).qtip('hide', $.Event('tooltipsolo'));
+ }
+ }
+ else {
+ // Clear show timer if we're hiding
+ clearTimeout(this.timers.show);
- get: function(notation)
- {
- var result, o;
+ // Remove cached origin on hide
+ delete cache.origin;
- switch(notation.toLowerCase())
- {
- case 'dimensions':
- result = {
- height: tooltip.outerHeight(FALSE), width: tooltip.outerWidth(FALSE)
- };
- break;
+ // Remove mouse tracking event if not needed (all tracking qTips are hidden)
+ if(trackingBound && !$(SELECTOR+'[tracking="true"]:visible', opts.solo).not(tooltip).length) {
+ $(document).unbind('mousemove.'+NAMESPACE);
+ trackingBound = FALSE;
+ }
- case 'offset':
- result = PLUGINS.offset(tooltip, options.position.container);
- break;
+ // Blur the tooltip
+ this.blur(event);
+ }
- default:
- o = convertNotation(notation.toLowerCase());
- result = o[0][ o[1] ];
- result = result.precedance ? result.string() : result;
- break;
- }
+ // Define post-animation, state specific properties
+ after = $.proxy(function() {
+ if(state) {
+ // Prevent antialias from disappearing in IE by removing filter
+ if(BROWSER.ie) { tooltip[0].style.removeAttribute('filter'); }
- return result;
- },
+ // Remove overflow setting to prevent tip bugs
+ tooltip.css('overflow', '');
- set: function(option, value)
- {
- var rmove = /^position\.(my|at|adjust|target|container)|style|content|show\.ready/i,
- rdraw = /^content\.(title|attr)|style/i,
- reposition = FALSE,
- redraw = FALSE,
- checks = self.checks,
- name;
-
- function callback(notation, args) {
- var category, rule, match;
-
- for(category in checks) {
- for(rule in checks[category]) {
- if(match = (new RegExp(rule, 'i')).exec(notation)) {
- args.push(match);
- checks[category][rule].apply(self, args);
- }
- }
- }
+ // Autofocus elements if enabled
+ if('string' === typeof opts.autofocus) {
+ $(this.options.show.autofocus, tooltip).focus();
}
- // Convert singular option/value pair into object form
- if('string' === typeof option) {
- name = option; option = {}; option[name] = value;
- }
- else { option = $.extend(TRUE, {}, option); }
-
- // Set all of the defined options to their new values
- $.each(option, function(notation, value) {
- var obj = convertNotation( notation.toLowerCase() ), previous;
-
- // Set new obj value
- previous = obj[0][ obj[1] ];
- obj[0][ obj[1] ] = 'object' === typeof value && value.nodeType ? $(value) : value;
-
- // Set the new params for the callback
- option[notation] = [obj[0], obj[1], value, previous];
-
- // Also check if we need to reposition / redraw
- reposition = rmove.test(notation) || reposition;
- redraw = rdraw.test(notation) || redraw;
+ // If set, hide tooltip when inactive for delay period
+ this.options.show.target.trigger('qtip-'+this.id+'-inactive');
+ }
+ else {
+ // Reset CSS states
+ tooltip.css({
+ display: '',
+ visibility: '',
+ opacity: '',
+ left: '',
+ top: ''
});
+ }
- // Re-sanitize options
- sanitizeOptions(options);
+ // tooltipvisible/tooltiphidden events
+ this._trigger(state ? 'visible' : 'hidden');
+ }, this);
- /*
- * Execute any valid callbacks for the set options
- * Also set isPositioning/isDrawing so we don't get loads of redundant repositioning
- * and redraw calls.
- */
- isPositioning = isDrawing = 1; $.each(option, callback); isPositioning = isDrawing = 0;
+ // If no effect type is supplied, use a simple toggle
+ if(opts.effect === FALSE || animate === FALSE) {
+ tooltip[ type ]();
+ after();
+ }
- // Update position / redraw if needed
- if(self.rendered && tooltip[0].offsetWidth > 0) {
- if(reposition) {
- self.reposition( options.position.target === 'mouse' ? NULL : cache.event );
- }
- if(redraw) { self.redraw(); }
- }
+ // Use custom function if provided
+ else if($.isFunction(opts.effect)) {
+ tooltip.stop(1, 1);
+ opts.effect.call(tooltip, this);
+ tooltip.queue('fx', function(n) {
+ after(); n();
+ });
+ }
- return self;
- },
+ // Use basic fade function by default
+ else { tooltip.fadeTo(90, state ? 1 : 0, after); }
- toggle: function(state, event)
- {
- // Try to prevent flickering when tooltip overlaps show element
- if(event) {
- if((/over|enter/).test(event.type) && (/out|leave/).test(cache.event.type) &&
- options.show.target.add(event.target).length === options.show.target.length &&
- tooltip.has(event.relatedTarget).length) {
- return self;
- }
+ // If inactive hide method is set, active it
+ if(state) { opts.target.trigger('qtip-'+this.id+'-inactive'); }
- // Cache event
- cache.event = $.extend({}, event);
- }
-
- // Render the tooltip if showing and it isn't already
- if(!self.rendered) { return state ? self.render(1) : self; }
+ return this;
+};
- var type = state ? 'show' : 'hide',
- opts = options[type],
- otherOpts = options[ !state ? 'show' : 'hide' ],
- posOptions = options.position,
- contentOptions = options.content,
- visible = tooltip[0].offsetWidth > 0,
- animate = state || opts.target.length === 1,
- sameTarget = !event || opts.target.length < 2 || cache.target[0] === event.target,
- showEvent, delay;
+PROTOTYPE.show = function(event) { return this.toggle(TRUE, event); };
- // Detect state if valid one isn't provided
- if((typeof state).search('boolean|number')) { state = !visible; }
+PROTOTYPE.hide = function(event) { return this.toggle(FALSE, event); };
- // Return if element is already in correct state
- if(!tooltip.is(':animated') && visible === state && sameTarget) { return self; }
+;PROTOTYPE.focus = function(event) {
+ if(!this.rendered || this.destroyed) { return this; }
- // tooltipshow/tooltiphide events
- if(!triggerEvent(type, [90])) { return self; }
+ var qtips = $(SELECTOR),
+ tooltip = this.tooltip,
+ curIndex = parseInt(tooltip[0].style.zIndex, 10),
+ newIndex = QTIP.zindex + qtips.length,
+ focusedElem;
- // Set ARIA hidden status attribute
- $.attr(tooltip[0], 'aria-hidden', !!!state);
-
- // Execute state specific properties
- if(state) {
- // Store show origin coordinates
- cache.origin = $.extend({}, MOUSE);
-
- // Focus the tooltip
- self.focus(event);
-
- // Update tooltip content & title if it's a dynamic function
- if($.isFunction(contentOptions.text)) { updateContent(contentOptions.text, FALSE); }
- if($.isFunction(contentOptions.title.text)) { updateTitle(contentOptions.title.text, FALSE); }
-
- // Cache mousemove events for positioning purposes (if not already tracking)
- if(!trackingBound && posOptions.target === 'mouse' && posOptions.adjust.mouse) {
- $(document).bind('mousemove.qtip', function(event) {
- MOUSE = { pageX: event.pageX, pageY: event.pageY, type: 'mousemove' };
- });
- trackingBound = TRUE;
- }
-
- // Update the tooltip position
- self.reposition(event, arguments[2]);
-
- // Hide other tooltips if tooltip is solo
- if(!!opts.solo) {
- $(selector, opts.solo).not(tooltip).qtip('hide', $.Event('tooltipsolo'));
- }
- }
- else {
- // Clear show timer if we're hiding
- clearTimeout(self.timers.show);
-
- // Remove cached origin on hide
- delete cache.origin;
-
- // Remove mouse tracking event if not needed (all tracking qTips are hidden)
- if(trackingBound && !$(selector+'[tracking="true"]:visible', opts.solo).not(tooltip).length) {
- $(document).unbind('mousemove.qtip');
- trackingBound = FALSE;
- }
-
- // Blur the tooltip
- self.blur(event);
- }
-
- // Define post-animation, state specific properties
- function after() {
- if(state) {
- // Prevent antialias from disappearing in IE by removing filter
- if($.browser.msie) { tooltip[0].style.removeAttribute('filter'); }
-
- // Remove overflow setting to prevent tip bugs
- tooltip.css('overflow', '');
-
- // Autofocus elements if enabled
- if('string' === typeof opts.autofocus) {
- $(opts.autofocus, tooltip).focus();
+ // Only update the z-index if it has changed and tooltip is not already focused
+ if(!tooltip.hasClass(CLASS_FOCUS)) {
+ // tooltipfocus event
+ if(this._trigger('focus', [newIndex], event)) {
+ // Only update z-index's if they've changed
+ if(curIndex !== newIndex) {
+ // Reduce our z-index's and keep them properly ordered
+ qtips.each(function() {
+ if(this.style.zIndex > curIndex) {
+ this.style.zIndex = this.style.zIndex - 1;
}
+ });
- // If set, hide tooltip when inactive for delay period
- opts.target.trigger('qtip-'+id+'-inactive');
- }
- else {
- // Reset CSS states
- tooltip.css({
- display: '',
- visibility: '',
- opacity: '',
- left: '',
- top: ''
- });
- }
-
- // tooltipvisible/tooltiphidden events
- triggerEvent(state ? 'visible' : 'hidden');
+ // Fire blur event for focused tooltip
+ qtips.filter('.' + CLASS_FOCUS).qtip('blur', event);
}
- // If no effect type is supplied, use a simple toggle
- if(opts.effect === FALSE || animate === FALSE) {
- tooltip[ type ]();
- after.call(tooltip);
- }
+ // Set the new z-index
+ tooltip.addClass(CLASS_FOCUS)[0].style.zIndex = newIndex;
+ }
+ }
- // Use custom function if provided
- else if($.isFunction(opts.effect)) {
- tooltip.stop(1, 1);
- opts.effect.call(tooltip, self);
- tooltip.queue('fx', function(n){ after(); n(); });
- }
+ return this;
+};
- // Use basic fade function by default
- else { tooltip.fadeTo(90, state ? 1 : 0, after); }
+PROTOTYPE.blur = function(event) {
+ if(!this.rendered || this.destroyed) { return this; }
- // If inactive hide method is set, active it
- if(state) { opts.target.trigger('qtip-'+id+'-inactive'); }
+ // Set focused status to FALSE
+ this.tooltip.removeClass(CLASS_FOCUS);
- return self;
- },
+ // tooltipblur event
+ this._trigger('blur', [ this.tooltip.css('zIndex') ], event);
- show: function(event){ return self.toggle(TRUE, event); },
+ return this;
+};
- hide: function(event){ return self.toggle(FALSE, event); },
+;PROTOTYPE.disable = function(state) {
+ if(this.destroyed) { return this; }
- focus: function(event)
- {
- if(!self.rendered) { return self; }
+ if('boolean' !== typeof state) {
+ state = !(this.tooltip.hasClass(CLASS_DISABLED) || this.disabled);
+ }
- var qtips = $(selector),
- curIndex = parseInt(tooltip[0].style.zIndex, 10),
- newIndex = QTIP.zindex + qtips.length,
- cachedEvent = $.extend({}, event),
- focusedElem;
+ if(this.rendered) {
+ this.tooltip.toggleClass(CLASS_DISABLED, state)
+ .attr('aria-disabled', state);
+ }
- // Only update the z-index if it has changed and tooltip is not already focused
- if(!tooltip.hasClass(focusClass))
- {
- // tooltipfocus event
- if(triggerEvent('focus', [newIndex], cachedEvent)) {
- // Only update z-index's if they've changed
- if(curIndex !== newIndex) {
- // Reduce our z-index's and keep them properly ordered
- qtips.each(function() {
- if(this.style.zIndex > curIndex) {
- this.style.zIndex = this.style.zIndex - 1;
- }
- });
+ this.disabled = !!state;
- // Fire blur event for focused tooltip
- qtips.filter('.' + focusClass).qtip('blur', cachedEvent);
- }
+ return this;
+};
- // Set the new z-index
- tooltip.addClass(focusClass)[0].style.zIndex = newIndex;
- }
- }
+PROTOTYPE.enable = function() { return this.disable(FALSE); };
- return self;
- },
+;PROTOTYPE._createButton = function()
+{
+ var self = this,
+ elements = this.elements,
+ tooltip = elements.tooltip,
+ button = this.options.content.button,
+ isString = typeof button === 'string',
+ close = isString ? button : 'Close tooltip';
- blur: function(event) {
- // Set focused status to FALSE
- tooltip.removeClass(focusClass);
+ if(elements.button) { elements.button.remove(); }
- // tooltipblur event
- triggerEvent('blur', [tooltip.css('zIndex')], event);
+ // Use custom button if one was supplied by user, else use default
+ if(button.jquery) {
+ elements.button = button;
+ }
+ else {
+ elements.button = $('<a />', {
+ 'class': 'qtip-close ' + (this.options.style.widget ? '' : NAMESPACE+'-icon'),
+ 'title': close,
+ 'aria-label': close
+ })
+ .prepend(
+ $('<span />', {
+ 'class': 'ui-icon ui-icon-close',
+ 'html': '×'
+ })
+ );
+ }
- return self;
- },
+ // Create button and setup attributes
+ elements.button.appendTo(elements.titlebar || tooltip)
+ .attr('role', 'button')
+ .click(function(event) {
+ if(!tooltip.hasClass(CLASS_DISABLED)) { self.hide(event); }
+ return FALSE;
+ });
+};
- reposition: function(event, effect)
- {
- if(!self.rendered || isPositioning) { return self; }
+PROTOTYPE._updateButton = function(button)
+{
+ // Make sure tooltip is rendered and if not, return
+ if(!this.rendered) { return FALSE; }
- // Set positioning flag
- isPositioning = 1;
+ var elem = this.elements.button;
+ if(button) { this._createButton(); }
+ else { elem.remove(); }
+};
- var target = options.position.target,
- posOptions = options.position,
- my = posOptions.my,
- at = posOptions.at,
- adjust = posOptions.adjust,
- method = adjust.method.split(' '),
- elemWidth = tooltip.outerWidth(FALSE),
- elemHeight = tooltip.outerHeight(FALSE),
- targetWidth = 0,
- targetHeight = 0,
- fixed = tooltip.css('position') === 'fixed',
- viewport = posOptions.viewport,
- position = { left: 0, top: 0 },
- container = posOptions.container,
- visible = tooltip[0].offsetWidth > 0,
- adjusted, offset, win;
+;// Widget class creator
+function createWidgetClass(cls) {
+ return WIDGET.concat('').join(cls ? '-'+cls+' ' : ' ');
+}
- // Check if absolute position was passed
- if($.isArray(target) && target.length === 2) {
- // Force left top and set position
- at = { x: LEFT, y: TOP };
- position = { left: target[0], top: target[1] };
- }
+// Widget class setter method
+PROTOTYPE._setWidget = function()
+{
+ var on = this.options.style.widget,
+ elements = this.elements,
+ tooltip = elements.tooltip,
+ disabled = tooltip.hasClass(CLASS_DISABLED);
- // Check if mouse was the target
- else if(target === 'mouse' && ((event && event.pageX) || cache.event.pageX)) {
- // Force left top to allow flipping
- at = { x: LEFT, y: TOP };
+ tooltip.removeClass(CLASS_DISABLED);
+ CLASS_DISABLED = on ? 'ui-state-disabled' : 'qtip-disabled';
+ tooltip.toggleClass(CLASS_DISABLED, disabled);
- // Use cached event if one isn't available for positioning
- event = MOUSE && MOUSE.pageX && (adjust.mouse || !event || !event.pageX) ? { pageX: MOUSE.pageX, pageY: MOUSE.pageY } :
- (event && (event.type === 'resize' || event.type === 'scroll') ? cache.event :
- event && event.pageX && event.type === 'mousemove' ? event :
- !adjust.mouse && cache.origin && cache.origin.pageX && options.show.distance ? cache.origin :
- event) || event || cache.event || MOUSE || {};
+ tooltip.toggleClass('ui-helper-reset '+createWidgetClass(), on).toggleClass(CLASS_DEFAULT, this.options.style.def && !on);
+
+ if(elements.content) {
+ elements.content.toggleClass( createWidgetClass('content'), on);
+ }
+ if(elements.titlebar) {
+ elements.titlebar.toggleClass( createWidgetClass('header'), on);
+ }
+ if(elements.button) {
+ elements.button.toggleClass(NAMESPACE+'-icon', !on);
+ }
+};;function showMethod(event) {
+ if(this.tooltip.hasClass(CLASS_DISABLED)) { return FALSE; }
- // Use event coordinates for position
- position = { top: event.pageY, left: event.pageX };
- }
+ // Clear hide timers
+ clearTimeout(this.timers.show);
+ clearTimeout(this.timers.hide);
- // Target wasn't mouse or absolute...
- else {
- // Check if event targetting is being used
- if(target === 'event' && event && event.target && event.type !== 'scroll' && event.type !== 'resize') {
- cache.target = $(event.target);
- }
- else if(target !== 'event'){
- cache.target = $(target.jquery ? target : elements.target);
- }
- target = cache.target;
+ // Start show timer
+ var callback = $.proxy(function(){ this.toggle(TRUE, event); }, this);
+ if(this.options.show.delay > 0) {
+ this.timers.show = setTimeout(callback, this.options.show.delay);
+ }
+ else{ callback(); }
+}
- // Parse the target into a jQuery object and make sure there's an element present
- target = $(target).eq(0);
- if(target.length === 0) { return self; }
+function hideMethod(event) {
+ if(this.tooltip.hasClass(CLASS_DISABLED)) { return FALSE; }
- // Check if window or document is the target
- else if(target[0] === document || target[0] === window) {
- targetWidth = PLUGINS.iOS ? window.innerWidth : target.width();
- targetHeight = PLUGINS.iOS ? window.innerHeight : target.height();
+ // Check if new target was actually the tooltip element
+ var relatedTarget = $(event.relatedTarget),
+ ontoTooltip = relatedTarget.closest(SELECTOR)[0] === this.tooltip[0],
+ ontoTarget = relatedTarget[0] === this.options.show.target[0];
- if(target[0] === window) {
- position = {
- top: (viewport || target).scrollTop(),
- left: (viewport || target).scrollLeft()
- };
- }
- }
+ // Clear timers and stop animation queue
+ clearTimeout(this.timers.show);
+ clearTimeout(this.timers.hide);
- // Use Imagemap/SVG plugins if needed
- else if(PLUGINS.imagemap && target.is('area')) {
- adjusted = PLUGINS.imagemap(self, target, at, PLUGINS.viewport ? method : FALSE);
- }
- else if(PLUGINS.svg && typeof target[0].xmlbase === 'string') {
- adjusted = PLUGINS.svg(self, target, at, PLUGINS.viewport ? method : FALSE);
- }
+ // Prevent hiding if tooltip is fixed and event target is the tooltip.
+ // Or if mouse positioning is enabled and cursor momentarily overlaps
+ if(this !== relatedTarget[0] &&
+ (this.options.position.target === 'mouse' && ontoTooltip) ||
+ (this.options.hide.fixed && (
+ (/mouse(out|leave|move)/).test(event.type) && (ontoTooltip || ontoTarget))
+ ))
+ {
+ try {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ } catch(e) {}
- else {
- targetWidth = target.outerWidth(FALSE);
- targetHeight = target.outerHeight(FALSE);
+ return;
+ }
- position = PLUGINS.offset(target, container);
- }
+ // If tooltip has displayed, start hide timer
+ var callback = $.proxy(function(){ this.toggle(FALSE, event); }, this);
+ if(this.options.hide.delay > 0) {
+ this.timers.hide = setTimeout(callback, this.options.hide.delay);
+ }
+ else{ callback(); }
+}
- // Parse returned plugin values into proper variables
- if(adjusted) {
- targetWidth = adjusted.width;
- targetHeight = adjusted.height;
- offset = adjusted.offset;
- position = adjusted.position;
- }
+function inactiveMethod(event) {
+ if(this.tooltip.hasClass(CLASS_DISABLED) || !this.options.hide.inactive) { return FALSE; }
- // Adjust for position.fixed tooltips (and also iOS scroll bug in v3.2-4.0 & v4.3-4.3.2)
- if((PLUGINS.iOS > 3.1 && PLUGINS.iOS < 4.1) ||
- (PLUGINS.iOS >= 4.3 && PLUGINS.iOS < 4.33) ||
- (!PLUGINS.iOS && fixed)
- ){
- win = $(window);
- position.left -= win.scrollLeft();
- position.top -= win.scrollTop();
- }
+ // Clear timer
+ clearTimeout(this.timers.inactive);
+ this.timers.inactive = setTimeout(
+ $.proxy(function(){ this.hide(event); }, this), this.options.hide.inactive
+ );
+}
- // Adjust position relative to target
- position.left += at.x === RIGHT ? targetWidth : at.x === CENTER ? targetWidth / 2 : 0;
- position.top += at.y === BOTTOM ? targetHeight : at.y === CENTER ? targetHeight / 2 : 0;
- }
+function repositionMethod(event) {
+ if(this.rendered && this.tooltip[0].offsetWidth > 0) { this.reposition(event); }
+}
- // Adjust position relative to tooltip
- position.left += adjust.x + (my.x === RIGHT ? -elemWidth : my.x === CENTER ? -elemWidth / 2 : 0);
- position.top += adjust.y + (my.y === BOTTOM ? -elemHeight : my.y === CENTER ? -elemHeight / 2 : 0);
+// Store mouse coordinates
+PROTOTYPE._storeMouse = function(event) {
+ this.mouse = {
+ pageX: event.pageX,
+ pageY: event.pageY,
+ type: 'mousemove',
+ scrollX: window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft,
+ scrollY: window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop
+ };
+};
- // Use viewport adjustment plugin if enabled
- if(PLUGINS.viewport) {
- position.adjusted = PLUGINS.viewport(
- self, position, posOptions, targetWidth, targetHeight, elemWidth, elemHeight
- );
+// Bind events
+PROTOTYPE._bind = function(targets, events, method, suffix, context) {
+ var ns = '.' + this._id + (suffix ? '-'+suffix : '');
+ events.length && $(targets).bind(
+ (events.split ? events : events.join(ns + ' ')) + ns,
+ $.proxy(method, context || this)
+ );
+};
+PROTOTYPE._unbind = function(targets, suffix) {
+ $(targets).unbind('.' + this._id + (suffix ? '-'+suffix : ''));
+};
- // Apply offsets supplied by positioning plugin (if used)
- if(offset && position.adjusted.left) { position.left += offset.left; }
- if(offset && position.adjusted.top) { position.top += offset.top; }
- }
+// Apply common event handlers using delegate (avoids excessive .bind calls!)
+var ns = '.'+NAMESPACE;
+function delegate(selector, events, method) {
+ $(document.body).delegate(selector,
+ (events.split ? events : events.join(ns + ' ')) + ns,
+ function() {
+ var api = QTIP.api[ $.attr(this, ATTR_ID) ];
+ api && !api.disabled && method.apply(api, arguments);
+ }
+ );
+}
- // Viewport adjustment is disabled, set values to zero
- else { position.adjusted = { left: 0, top: 0 }; }
+$(function() {
+ delegate(SELECTOR, ['mouseenter', 'mouseleave'], function(event) {
+ var state = event.type === 'mouseenter',
+ tooltip = $(event.currentTarget),
+ target = $(event.relatedTarget || event.target),
+ options = this.options;
- // tooltipmove event
- if(!triggerEvent('move', [position, viewport.elem || viewport], event)) { return self; }
- delete position.adjusted;
+ // On mouseenter...
+ if(state) {
+ // Focus the tooltip on mouseenter (z-index stacking)
+ this.focus(event);
- // If effect is disabled, target it mouse, no animation is defined or positioning gives NaN out, set CSS directly
- if(effect === FALSE || !visible || isNaN(position.left) || isNaN(position.top) || target === 'mouse' || !$.isFunction(posOptions.effect)) {
- tooltip.css(position);
- }
+ // Clear hide timer on tooltip hover to prevent it from closing
+ tooltip.hasClass(CLASS_FIXED) && !tooltip.hasClass(CLASS_DISABLED) && clearTimeout(this.timers.hide);
+ }
- // Use custom function if provided
- else if($.isFunction(posOptions.effect)) {
- posOptions.effect.call(tooltip, self, $.extend({}, position));
- tooltip.queue(function(next) {
- // Reset attributes to avoid cross-browser rendering bugs
- $(this).css({ opacity: '', height: '' });
- if($.browser.msie) { this.style.removeAttribute('filter'); }
-
- next();
- });
+ // On mouseleave...
+ else {
+ // Hide when we leave the tooltip and not onto the show target (if a hide event is set)
+ if(options.position.target === 'mouse' && options.hide.event &&
+ options.show.target && !target.closest(options.show.target[0]).length) {
+ this.hide(event);
}
+ }
- // Set positioning flag
- isPositioning = 0;
+ // Add hover class
+ tooltip.toggleClass(CLASS_HOVER, state);
+ });
- return self;
- },
+ // Define events which reset the 'inactive' event handler
+ delegate('['+ATTR_ID+']', INACTIVE_EVENTS, inactiveMethod);
+});
- // Max/min width simulator function for all browsers.. yeaaah!
- redraw: function()
- {
- if(self.rendered < 1 || isDrawing) { return self; }
+// Event trigger
+PROTOTYPE._trigger = function(type, args, event) {
+ var callback = $.Event('tooltip'+type);
+ callback.originalEvent = (event && $.extend({}, event)) || this.cache.event || NULL;
- var style = options.style,
- container = options.position.container,
- perc, width, max, min;
+ this.triggering = TRUE;
+ this.tooltip.trigger(callback, [this].concat(args || []));
+ this.triggering = FALSE;
- // Set drawing flag
- isDrawing = 1;
+ return !callback.isDefaultPrevented();
+};
- // tooltipredraw event
- triggerEvent('redraw');
+// Event assignment method
+PROTOTYPE._assignEvents = function() {
+ var options = this.options,
+ posOptions = options.position,
- // If tooltip has a set height/width, just set it... like a boss!
- if(style.height) { tooltip.css(HEIGHT, style.height); }
- if(style.width) { tooltip.css(WIDTH, style.width); }
+ tooltip = this.tooltip,
+ showTarget = options.show.target,
+ hideTarget = options.hide.target,
+ containerTarget = posOptions.container,
+ viewportTarget = posOptions.viewport,
+ documentTarget = $(document),
+ bodyTarget = $(document.body),
+ windowTarget = $(window),
- // Simulate max/min width if not set width present...
- else {
- // Reset width and add fluid class
- tooltip.css(WIDTH, '').appendTo(redrawContainer);
+ showEvents = options.show.event ? $.trim('' + options.show.event).split(' ') : [],
+ hideEvents = options.hide.event ? $.trim('' + options.hide.event).split(' ') : [],
+ toggleEvents = [];
- // Grab our tooltip width (add 1 if odd so we don't get wrapping problems.. huzzah!)
- width = tooltip.width();
- if(width % 2 < 1) { width += 1; }
+ // Hide tooltips when leaving current window/frame (but not select/option elements)
+ if(/mouse(out|leave)/i.test(options.hide.event) && options.hide.leave === 'window') {
+ this._bind(documentTarget, ['mouseout', 'blur'], function(event) {
+ if(!/select|option/.test(event.target.nodeName) && !event.relatedTarget) {
+ this.hide(event);
+ }
+ });
+ }
- // Grab our max/min properties
- max = tooltip.css('max-width') || '';
- min = tooltip.css('min-width') || '';
+ // Enable hide.fixed by adding appropriate class
+ if(options.hide.fixed) {
+ hideTarget = hideTarget.add( tooltip.addClass(CLASS_FIXED) );
+ }
- // Parse into proper pixel values
- perc = (max + min).indexOf('%') > -1 ? container.width() / 100 : 0;
- max = ((max.indexOf('%') > -1 ? perc : 1) * parseInt(max, 10)) || width;
- min = ((min.indexOf('%') > -1 ? perc : 1) * parseInt(min, 10)) || 0;
+ /*
+ * Make sure hoverIntent functions properly by using mouseleave to clear show timer if
+ * mouseenter/mouseout is used for show.event, even if it isn't in the users options.
+ */
+ else if(/mouse(over|enter)/i.test(options.show.event)) {
+ this._bind(hideTarget, 'mouseleave', function() {
+ clearTimeout(this.timers.show);
+ });
+ }
- // Determine new dimension size based on max/min/current values
- width = max + min ? Math.min(Math.max(width, min), max) : width;
+ // Hide tooltip on document mousedown if unfocus events are enabled
+ if(('' + options.hide.event).indexOf('unfocus') > -1) {
+ this._bind(containerTarget.closest('html'), ['mousedown', 'touchstart'], function(event) {
+ var elem = $(event.target),
+ enabled = this.rendered && !this.tooltip.hasClass(CLASS_DISABLED) && this.tooltip[0].offsetWidth > 0,
+ isAncestor = elem.parents(SELECTOR).filter(this.tooltip[0]).length > 0;
- // Set the newly calculated width and remvoe fluid class
- tooltip.css(WIDTH, Math.round(width)).appendTo(container);
+ if(elem[0] !== this.target[0] && elem[0] !== this.tooltip[0] && !isAncestor &&
+ !this.target.has(elem[0]).length && enabled
+ ) {
+ this.hide(event);
}
+ });
+ }
- // tooltipredrawn event
- triggerEvent('redrawn');
+ // Check if the tooltip hides when inactive
+ if('number' === typeof options.hide.inactive) {
+ // Bind inactive method to show target(s) as a custom event
+ this._bind(showTarget, 'qtip-'+this.id+'-inactive', inactiveMethod);
- // Set drawing flag
- isDrawing = 0;
+ // Define events which reset the 'inactive' event handler
+ this._bind(hideTarget.add(tooltip), QTIP.inactiveEvents, inactiveMethod, '-inactive');
+ }
- return self;
- },
+ // Apply hide events (and filter identical show events)
+ hideEvents = $.map(hideEvents, function(type) {
+ var showIndex = $.inArray(type, showEvents);
- disable: function(state)
- {
- if('boolean' !== typeof state) {
- state = !(tooltip.hasClass(disabled) || cache.disabled);
- }
+ // Both events and targets are identical, apply events using a toggle
+ if((showIndex > -1 && hideTarget.add(showTarget).length === hideTarget.length)) {
+ toggleEvents.push( showEvents.splice( showIndex, 1 )[0] ); return;
+ }
- if(self.rendered) {
- tooltip.toggleClass(disabled, state);
- $.attr(tooltip[0], 'aria-disabled', state);
- }
- else {
- cache.disabled = !!state;
- }
+ return type;
+ });
- return self;
- },
+ // Apply show/hide/toggle events
+ this._bind(showTarget, showEvents, showMethod);
+ this._bind(hideTarget, hideEvents, hideMethod);
+ this._bind(showTarget, toggleEvents, function(event) {
+ (this.tooltip[0].offsetWidth > 0 ? hideMethod : showMethod).call(this, event);
+ });
- enable: function() { return self.disable(FALSE); },
- destroy: function()
- {
- var t = target[0],
- title = $.attr(t, oldtitle),
- elemAPI = target.data('qtip');
+ // Mouse movement bindings
+ this._bind(showTarget.add(tooltip), 'mousemove', function(event) {
+ // Check if the tooltip hides when mouse is moved a certain distance
+ if('number' === typeof options.hide.distance) {
+ var origin = this.cache.origin || {},
+ limit = this.options.hide.distance,
+ abs = Math.abs;
- // Set flag the signify destroy is taking place to plugins
- self.destroyed = TRUE;
+ // Check if the movement has gone beyond the limit, and hide it if so
+ if(abs(event.pageX - origin.pageX) >= limit || abs(event.pageY - origin.pageY) >= limit) {
+ this.hide(event);
+ }
+ }
- // Destroy tooltip and any associated plugins if rendered
- if(self.rendered) {
- tooltip.stop(1,0).remove();
+ // Cache mousemove coords on show targets
+ this._storeMouse(event);
+ });
- $.each(self.plugins, function() {
- if(this.destroy) { this.destroy(); }
+ // Mouse positioning events
+ if(posOptions.target === 'mouse') {
+ // If mouse adjustment is on...
+ if(posOptions.adjust.mouse) {
+ // Apply a mouseleave event so we don't get problems with overlapping
+ if(options.hide.event) {
+ // Track if we're on the target or not
+ this._bind(showTarget, ['mouseenter', 'mouseleave'], function(event) {
+ this.cache.onTarget = event.type === 'mouseenter';
});
}
- // Clear timers and remove bound events
- clearTimeout(self.timers.show);
- clearTimeout(self.timers.hide);
- unassignEvents();
-
- // If the API if actually this qTip API...
- if(!elemAPI || self === elemAPI) {
- // Remove api object
- $.removeData(t, 'qtip');
-
- // Reset old title attribute if removed
- if(options.suppress && title) {
- $.attr(t, 'title', title);
- target.removeAttr(oldtitle);
+ // Update tooltip position on mousemove
+ this._bind(documentTarget, 'mousemove', function(event) {
+ // Update the tooltip position only if the tooltip is visible and adjustment is enabled
+ if(this.rendered && this.cache.onTarget && !this.tooltip.hasClass(CLASS_DISABLED) && this.tooltip[0].offsetWidth > 0) {
+ this.reposition(event);
}
+ });
+ }
+ }
- // Remove ARIA attributes
- target.removeAttr('aria-describedby');
- }
+ // Adjust positions of the tooltip on window resize if enabled
+ if(posOptions.adjust.resize || viewportTarget.length) {
+ this._bind( $.event.special.resize ? viewportTarget : windowTarget, 'resize', repositionMethod );
+ }
- // Remove qTip events associated with this API
- target.unbind('.qtip-'+id);
+ // Adjust tooltip position on scroll of the window or viewport element if present
+ if(posOptions.adjust.scroll) {
+ this._bind( windowTarget.add(posOptions.container), 'scroll', repositionMethod );
+ }
+};
- // Remove ID from sued id object
- delete usedIDs[self.id];
+// Un-assignment method
+PROTOTYPE._unassignEvents = function() {
+ var targets = [
+ this.options.show.target[0],
+ this.options.hide.target[0],
+ this.rendered && this.tooltip[0],
+ this.options.position.container[0],
+ this.options.position.viewport[0],
+ this.options.position.container.closest('html')[0], // unfocus
+ window,
+ document
+ ];
- return target;
- }
- });
-}
+ // Check if tooltip is rendered
+ if(this.rendered) {
+ this._unbind($([]).pushStack( $.grep(targets, function(i) {
+ return typeof i === 'object';
+ })));
+ }
-// Initialization method
-function init(id, opts)
+ // Tooltip isn't yet rendered, remove render event
+ else { $(targets[0]).unbind('.'+this._id+'-create'); }
+};
+
+;// Initialization method
+function init(elem, id, opts)
{
var obj, posOptions, attr, config, title,
// Setup element references
- elem = $(this),
docBody = $(document.body),
// Use document body instead of document element if needed
- newTarget = this === document ? docBody : elem,
+ newTarget = elem[0] === document ? docBody : elem,
// Grab metadata from element if plugin is present
metadata = (elem.metadata) ? elem.metadata(opts.metadata) : NULL,
// If metadata type if HTML5, grab 'name' from the object instead, or use the regular data object otherwise
@@ -1443,35 +1593,40 @@
// Ensure we only use a single container
posOptions.container = posOptions.container.eq(0);
// Convert position corner values into x and y strings
- posOptions.at = new PLUGINS.Corner(posOptions.at);
- posOptions.my = new PLUGINS.Corner(posOptions.my);
+ posOptions.at = new CORNER(posOptions.at, TRUE);
+ posOptions.my = new CORNER(posOptions.my);
// Destroy previous tooltip if overwrite is enabled, or skip element if not
- if($.data(this, 'qtip')) {
+ if(elem.data(NAMESPACE)) {
if(config.overwrite) {
elem.qtip('destroy');
}
else if(config.overwrite === FALSE) {
return FALSE;
}
}
+ // Add has-qtip attribute
+ elem.attr(ATTR_HAS, id);
+
// Remove title attribute and store it if present
- if(config.suppress && (title = $.attr(this, 'title'))) {
+ if(config.suppress && (title = elem.attr('title'))) {
// Final attr call fixes event delegatiom and IE default tooltip showing problem
- $(this).removeAttr('title').attr(oldtitle, title).attr('title', '');
+ elem.removeAttr('title').attr(oldtitle, title).attr('title', '');
}
// Initialize the tooltip and add API reference
obj = new QTip(elem, config, id, !!attr);
- $.data(this, 'qtip', obj);
+ elem.data(NAMESPACE, obj);
// Catch remove/removeqtip events on target element to destroy redundant tooltip
- elem.bind('remove.qtip-'+id+' removeqtip.qtip-'+id, function(){ obj.destroy(); });
+ elem.one('remove.qtip-'+id+' removeqtip.qtip-'+id, function() {
+ var api; if((api = $(this).data(NAMESPACE))) { api.destroy(); }
+ });
return obj;
}
// jQuery $.fn extension method
@@ -1479,11 +1634,11 @@
{
var command = ('' + options).toLowerCase(), // Parse command
returned = NULL,
args = $.makeArray(arguments).slice(1),
event = args[args.length - 1],
- opts = this[0] ? $.data(this[0], 'qtip') : NULL;
+ opts = this[0] ? $.data(this[0], NAMESPACE) : NULL;
// Check for API request
if((!arguments.length && opts) || command === 'api') {
return opts;
}
@@ -1491,30 +1646,30 @@
// Execute API command if present
else if('string' === typeof options)
{
this.each(function()
{
- var api = $.data(this, 'qtip');
+ var api = $.data(this, NAMESPACE);
if(!api) { return TRUE; }
// Cache the event if possible
if(event && event.timeStamp) { api.cache.event = event; }
// Check for specific API commands
- if((command === 'option' || command === 'options') && notation) {
- if($.isPlainObject(notation) || newValue !== undefined) {
+ if(notation && (command === 'option' || command === 'options')) {
+ if(newValue !== undefined || $.isPlainObject(notation)) {
api.set(notation, newValue);
}
else {
returned = api.get(notation);
return FALSE;
}
}
// Execute API command
else if(api[command]) {
- api[command].apply(api[command], args);
+ api[command].apply(api, args);
}
});
return returned !== NULL ? returned : this;
}
@@ -1535,18 +1690,19 @@
return this.each(function(i) {
var options, targets, events, namespace, api, id;
// Find next available ID, or use custom ID if provided
id = $.isArray(opts.id) ? opts.id[i] : opts.id;
- id = !id || id === FALSE || id.length < 1 || usedIDs[id] ? QTIP.nextid++ : (usedIDs[id] = id);
+ id = !id || id === FALSE || id.length < 1 || QTIP.api[id] ? QTIP.nextid++ : id;
// Setup events namespace
namespace = '.qtip-'+id+'-create';
// Initialize the qTip and re-grab newly sanitized options
- api = init.call(this, id, opts);
+ api = init($(this), id, opts);
if(api === FALSE) { return TRUE; }
+ else { QTIP.api[id] = api; }
options = api.options;
// Initialize plugins
$.each(PLUGINS, function() {
if(this.initialize === 'initialize') { this(api); }
@@ -1558,25 +1714,25 @@
show: $.trim('' + options.show.event).replace(/ /g, namespace+' ') + namespace,
hide: $.trim('' + options.hide.event).replace(/ /g, namespace+' ') + namespace
};
/*
- * Make sure hoverIntent functions properly by using mouseleave as a hide event if
- * mouseenter/mouseout is used for show.event, even if it isn't in the users options.
- */
+ * Make sure hoverIntent functions properly by using mouseleave as a hide event if
+ * mouseenter/mouseout is used for show.event, even if it isn't in the users options.
+ */
if(/mouse(over|enter)/i.test(events.show) && !/mouse(out|leave)/i.test(events.hide)) {
events.hide += ' mouseleave' + namespace;
}
/*
- * Also make sure initial mouse targetting works correctly by caching mousemove coords
- * on show targets before the tooltip has rendered.
- *
- * Also set onTarget when triggered to keep mouse tracking working
- */
+ * Also make sure initial mouse targetting works correctly by caching mousemove coords
+ * on show targets before the tooltip has rendered.
+ *
+ * Also set onTarget when triggered to keep mouse tracking working
+ */
targets.show.bind('mousemove'+namespace, function(event) {
- MOUSE = { pageX: event.pageX, pageY: event.pageY, type: 'mousemove' };
+ api._storeMouse(event);
api.cache.onTarget = TRUE;
});
// Define hoverIntent function
function hoverIntent(event) {
@@ -1587,11 +1743,11 @@
// Unbind show and hide events
targets.show.add(targets.hide).unbind(namespace);
}
// Only continue if tooltip isn't disabled
- if(api.cache.disabled) { return FALSE; }
+ if(api.disabled) { return FALSE; }
// Cache the event data
api.cache.event = $.extend({}, event);
api.cache.target = event ? $(event.target) : [undefined];
@@ -1612,132 +1768,56 @@
// Prerendering is enabled, create tooltip now
if(options.show.ready || options.prerender) { hoverIntent(event); }
});
};
-// Setup base plugins
-PLUGINS = QTIP.plugins = {
- // Corner object parser
- Corner: function(corner) {
- corner = ('' + corner).replace(/([A-Z])/, ' $1').replace(/middle/gi, CENTER).toLowerCase();
- this.x = (corner.match(/left|right/i) || corner.match(/center/) || ['inherit'])[0].toLowerCase();
- this.y = (corner.match(/top|bottom|center/i) || ['inherit'])[0].toLowerCase();
+// Populated in render method
+QTIP.api = {};
+;$.each({
+ /* Allow other plugins to successfully retrieve the title of an element with a qTip applied */
+ attr: function(attr, val) {
+ if(this.length) {
+ var self = this[0],
+ title = 'title',
+ api = $.data(self, 'qtip');
- var f = corner.charAt(0); this.precedance = (f === 't' || f === 'b' ? Y : X);
+ if(attr === title && api && 'object' === typeof api && api.options.suppress) {
+ if(arguments.length < 2) {
+ return $.attr(self, oldtitle);
+ }
- this.string = function() { return this.precedance === Y ? this.y+this.x : this.x+this.y; };
- this.abbrev = function() {
- var x = this.x.substr(0,1), y = this.y.substr(0,1);
- return x === y ? x : this.precedance === Y ? y + x : x + y;
- };
-
- this.invertx = function(center) { this.x = this.x === LEFT ? RIGHT : this.x === RIGHT ? LEFT : center || this.x; };
- this.inverty = function(center) { this.y = this.y === TOP ? BOTTOM : this.y === BOTTOM ? TOP : center || this.y; };
-
- this.clone = function() {
- return {
- x: this.x, y: this.y, precedance: this.precedance,
- string: this.string, abbrev: this.abbrev, clone: this.clone,
- invertx: this.invertx, inverty: this.inverty
- };
- };
- },
-
- // Custom (more correct for qTip!) offset calculator
- offset: function(elem, container) {
- var pos = elem.offset(),
- docBody = elem.closest('body')[0],
- parent = container, scrolled,
- coffset, overflow;
-
- function scroll(e, i) {
- pos.left += i * e.scrollLeft();
- pos.top += i * e.scrollTop();
- }
-
- if(parent) {
- // Compensate for non-static containers offset
- do {
- if(parent.css('position') !== 'static') {
- coffset = parent.position();
-
- // Account for element positioning, borders and margins
- pos.left -= coffset.left + (parseInt(parent.css('borderLeftWidth'), 10) || 0) + (parseInt(parent.css('marginLeft'), 10) || 0);
- pos.top -= coffset.top + (parseInt(parent.css('borderTopWidth'), 10) || 0) + (parseInt(parent.css('marginTop'), 10) || 0);
-
- // If this is the first parent element with an overflow of "scroll" or "auto", store it
- if(!scrolled && (overflow = parent.css('overflow')) !== 'hidden' && overflow !== 'visible') { scrolled = parent; }
+ // If qTip is rendered and title was originally used as content, update it
+ if(api && api.options.content.attr === title && api.cache.attr) {
+ api.set('content.text', val);
}
- }
- while((parent = $(parent[0].offsetParent)).length);
- // Compensate for containers scroll if it also has an offsetParent
- if(scrolled && scrolled[0] !== docBody) { scroll( scrolled, 1 ); }
+ // Use the regular attr method to set, then cache the result
+ return this.attr(oldtitle, val);
+ }
}
- return pos;
+ return $.fn['attr'+replaceSuffix].apply(this, arguments);
},
- /*
- * iOS version detection
- */
- iOS: parseFloat(
- ('' + (/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0,''])[1])
- .replace('undefined', '3_2').replace('_', '.').replace('_', '')
- ) || FALSE,
+ /* Allow clone to correctly retrieve cached title attributes */
+ clone: function(keepData) {
+ var titles = $([]), title = 'title',
- /*
- * jQuery-specific $.fn overrides
- */
- fn: {
- /* Allow other plugins to successfully retrieve the title of an element with a qTip applied */
- attr: function(attr, val) {
- if(this.length) {
- var self = this[0],
- title = 'title',
- api = $.data(self, 'qtip');
+ // Clone our element using the real clone method
+ elems = $.fn['clone'+replaceSuffix].apply(this, arguments);
- if(attr === title && api && 'object' === typeof api && api.options.suppress) {
- if(arguments.length < 2) {
- return $.attr(self, oldtitle);
- }
-
- // If qTip is rendered and title was originally used as content, update it
- if(api && api.options.content.attr === title && api.cache.attr) {
- api.set('content.text', val);
- }
-
- // Use the regular attr method to set, then cache the result
- return this.attr(oldtitle, val);
- }
- }
-
- return $.fn['attr'+replaceSuffix].apply(this, arguments);
- },
-
- /* Allow clone to correctly retrieve cached title attributes */
- clone: function(keepData) {
- var titles = $([]), title = 'title',
-
- // Clone our element using the real clone method
- elems = $.fn['clone'+replaceSuffix].apply(this, arguments);
-
- // Grab all elements with an oldtitle set, and change it to regular title attribute, if keepData is false
- if(!keepData) {
- elems.filter('['+oldtitle+']').attr('title', function() {
- return $.attr(this, oldtitle);
- })
- .removeAttr(oldtitle);
- }
-
- return elems;
+ // Grab all elements with an oldtitle set, and change it to regular title attribute, if keepData is false
+ if(!keepData) {
+ elems.filter('['+oldtitle+']').attr('title', function() {
+ return $.attr(this, oldtitle);
+ })
+ .removeAttr(oldtitle);
}
- }
-};
-// Apply the fn overrides above
-$.each(PLUGINS.fn, function(name, func) {
+ return elems;
+ }
+}, function(name, func) {
if(!func || $.fn[name+replaceSuffix]) { return TRUE; }
var old = $.fn[name+replaceSuffix] = $.fn[name];
$.fn[name] = function() {
return func.apply(this, arguments) || old.apply(this, arguments);
@@ -1749,22 +1829,30 @@
* http://code.jquery.com/ui/jquery-ui-git.js
*/
if(!$.ui) {
$['cleanData'+replaceSuffix] = $.cleanData;
$.cleanData = function( elems ) {
- for(var i = 0, elem; (elem = elems[i]) !== undefined; i++) {
- try { $( elem ).triggerHandler('removeqtip'); }
- catch( e ) {}
+ for(var i = 0, elem; (elem = $( elems[i] )).length; i++) {
+ if(elem.attr(ATTR_HAS)) {
+ try { elem.triggerHandler('removeqtip'); }
+ catch( e ) {}
+ }
}
- $['cleanData'+replaceSuffix]( elems );
+ $['cleanData'+replaceSuffix].apply(this, arguments);
};
}
-// Set global qTip properties
-QTIP.version = '@VERSION';
+;// qTip version
+QTIP.version = '2.1.1';
+
+// Base ID for all qTips
QTIP.nextid = 0;
-QTIP.inactiveEvents = 'click dblclick mousedown mouseup mousemove mouseleave mouseenter'.split(' ');
+
+// Inactive events array
+QTIP.inactiveEvents = INACTIVE_EVENTS;
+
+// Base z-index for all qTips
QTIP.zindex = 15000;
// Define configuration defaults
QTIP.defaults = {
prerender: FALSE,
@@ -1772,26 +1860,25 @@
overwrite: TRUE,
suppress: TRUE,
content: {
text: TRUE,
attr: 'title',
- title: {
- text: FALSE,
- button: FALSE
- }
+ title: FALSE,
+ button: FALSE
},
position: {
my: 'top left',
at: 'bottom right',
target: FALSE,
container: FALSE,
viewport: FALSE,
adjust: {
x: 0, y: 0,
mouse: TRUE,
+ scroll: TRUE,
resize: TRUE,
- method: 'flip flip'
+ method: 'flipinvert flipinvert'
},
effect: function(api, pos, viewport) {
$(this).animate(pos, {
duration: 200,
queue: FALSE
@@ -1835,334 +1922,479 @@
focus: NULL,
blur: NULL
}
};
+;var TIP,
-PLUGINS.svg = function(api, svg, corner, adjustMethod)
-{
- var doc = $(document),
- elem = svg[0],
- result = {
- width: 0, height: 0,
- position: { top: 1e10, left: 1e10 }
- },
- box, mtx, root, point, tPoint;
+// .bind()/.on() namespace
+TIPNS = '.qtip-tip',
- // Ascend the parentNode chain until we find an element with getBBox()
- while(!elem.getBBox) { elem = elem.parentNode; }
+// Common CSS strings
+MARGIN = 'margin',
+BORDER = 'border',
+COLOR = 'color',
+BG_COLOR = 'background-color',
+TRANSPARENT = 'transparent',
+IMPORTANT = ' !important',
- // Check for a valid bounding box method
- if (elem.getBBox && elem.parentNode) {
- box = elem.getBBox();
- mtx = elem.getScreenCTM();
- root = elem.farthestViewportElement || elem;
+// Check if the browser supports <canvas/> elements
+HASCANVAS = !!document.createElement('canvas').getContext,
- // Return if no method is found
- if(!root.createSVGPoint) { return result; }
+// Invalid colour values used in parseColours()
+INVALID = /rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i;
- // Create our point var
- point = root.createSVGPoint();
+// Camel-case method, taken from jQuery source
+// http://code.jquery.com/jquery-1.8.0.js
+function camel(s) { return s.charAt(0).toUpperCase() + s.slice(1); }
- // Adjust top and left
- point.x = box.x;
- point.y = box.y;
- tPoint = point.matrixTransform(mtx);
- result.position.left = tPoint.x;
- result.position.top = tPoint.y;
+/*
+ * Modified from Modernizr's testPropsAll()
+ * http://modernizr.com/downloads/modernizr-latest.js
+ */
+var cssProps = {}, cssPrefixes = ["Webkit", "O", "Moz", "ms"];
+function vendorCss(elem, prop) {
+ var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1),
+ props = (prop + ' ' + cssPrefixes.join(ucProp + ' ') + ucProp).split(' '),
+ cur, val, i = 0;
- // Adjust width and height
- point.x += box.width;
- point.y += box.height;
- tPoint = point.matrixTransform(mtx);
- result.width = tPoint.x - result.position.left;
- result.height = tPoint.y - result.position.top;
+ // If the property has already been mapped...
+ if(cssProps[prop]) { return elem.css(cssProps[prop]); }
- // Adjust by scroll offset
- result.position.left += doc.scrollLeft();
- result.position.top += doc.scrollTop();
+ while((cur = props[i++])) {
+ if((val = elem.css(cur)) !== undefined) {
+ return cssProps[prop] = cur, val;
+ }
}
+}
- return result;
-};
+// Parse a given elements CSS property into an int
+function intCss(elem, prop) {
+ return parseInt(vendorCss(elem, prop), 10);
+}
-function Ajax(api)
-{
- var self = this,
- tooltip = api.elements.tooltip,
- opts = api.options.content.ajax,
- defaults = QTIP.defaults.content.ajax,
- namespace = '.qtip-ajax',
- rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
- first = TRUE,
- stop = FALSE,
- xhr;
+// VML creation (for IE only)
+if(!HASCANVAS) {
+ createVML = function(tag, props, style) {
+ return '<qtipvml:'+tag+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(props||'')+
+ ' style="behavior: url(#default#VML); '+(style||'')+ '" />';
+ };
+}
- api.checks.ajax = {
- '^content.ajax': function(obj, name, v) {
- // If content.ajax object was reset, set our local var
- if(name === 'ajax') { opts = v; }
- if(name === 'once') {
- self.init();
- }
- else if(opts && opts.url) {
- self.load();
- }
- else {
- tooltip.unbind(namespace);
- }
+
+function Tip(qtip, options) {
+ this._ns = 'tip';
+ this.options = options;
+ this.offset = options.offset;
+ this.size = [ options.width, options.height ];
+
+ // Initialize
+ this.init( (this.qtip = qtip) );
+}
+
+$.extend(Tip.prototype, {
+ init: function(qtip) {
+ var context, tip;
+
+ // Create tip element and prepend to the tooltip
+ tip = this.element = qtip.elements.tip = $('<div />', { 'class': NAMESPACE+'-tip' }).prependTo(qtip.tooltip);
+
+ // Create tip drawing element(s)
+ if(HASCANVAS) {
+ // save() as soon as we create the canvas element so FF2 doesn't bork on our first restore()!
+ context = $('<canvas />').appendTo(this.element)[0].getContext('2d');
+
+ // Setup constant parameters
+ context.lineJoin = 'miter';
+ context.miterLimit = 100;
+ context.save();
}
- };
+ else {
+ context = createVML('shape', 'coordorigin="0,0"', 'position:absolute;');
+ this.element.html(context + context);
- $.extend(self, {
- init: function() {
- // Make sure ajax options are enabled and bind event
- if(opts && opts.url) {
- tooltip.unbind(namespace)[ opts.once ? 'one' : 'bind' ]('tooltipshow'+namespace, self.load);
- }
+ // Prevent mousing down on the tip since it causes problems with .live() handling in IE due to VML
+ qtip._bind( $('*', tip).add(tip), ['click', 'mousedown'], function(event) { event.stopPropagation(); }, this._ns);
+ }
- return self;
- },
+ // Bind update events
+ qtip._bind(qtip.tooltip, 'tooltipmove', this.reposition, this._ns, this);
- load: function(event) {
- if(stop) {stop = FALSE; return; }
+ // Create it
+ this.create();
+ },
- var hasSelector = opts.url.lastIndexOf(' '),
- url = opts.url,
- selector,
- hideFirst = !opts.loading && first;
+ _swapDimensions: function() {
+ this.size[0] = this.options.height;
+ this.size[1] = this.options.width;
+ },
+ _resetDimensions: function() {
+ this.size[0] = this.options.width;
+ this.size[1] = this.options.height;
+ },
- // If loading option is disabled, prevent the tooltip showing until we've completed the request
- if(hideFirst) { try{ event.preventDefault(); } catch(e) {} }
+ _useTitle: function(corner) {
+ var titlebar = this.qtip.elements.titlebar;
+ return titlebar && (
+ corner.y === TOP || (corner.y === CENTER && this.element.position().top + (this.size[1] / 2) + this.options.offset < titlebar.outerHeight(TRUE))
+ );
+ },
- // Make sure default event hasn't been prevented
- else if(event && event.isDefaultPrevented()) { return self; }
+ _parseCorner: function(corner) {
+ var my = this.qtip.options.position.my;
- // Cancel old request
- if(xhr && xhr.abort) { xhr.abort(); }
-
- // Check if user delcared a content selector like in .load()
- if(hasSelector > -1) {
- selector = url.substr(hasSelector);
- url = url.substr(0, hasSelector);
- }
+ // Detect corner and mimic properties
+ if(corner === FALSE || my === FALSE) {
+ corner = FALSE;
+ }
+ else if(corner === TRUE) {
+ corner = new CORNER( my.string() );
+ }
+ else if(!corner.string) {
+ corner = new CORNER(corner);
+ corner.fixed = TRUE;
+ }
- // Define common after callback for both success/error handlers
- function after() {
- var complete;
+ return corner;
+ },
- // Don't proceed if tooltip is destroyed
- if(api.destroyed) { return; }
+ _parseWidth: function(corner, side, use) {
+ var elements = this.qtip.elements,
+ prop = BORDER + camel(side) + 'Width';
- // Set first flag to false
- first = FALSE;
+ return (use ? intCss(use, prop) : (
+ intCss(elements.content, prop) ||
+ intCss(this._useTitle(corner) && elements.titlebar || elements.content, prop) ||
+ intCss(tooltip, prop)
+ )) || 0;
+ },
- // Re-display tip if loading and first time, and reset first flag
- if(hideFirst) { stop = TRUE; api.show(event.originalEvent); }
+ _parseRadius: function(corner) {
+ var elements = this.qtip.elements,
+ prop = BORDER + camel(corner.y) + camel(corner.x) + 'Radius';
- // Call users complete method if it was defined
- if((complete = defaults.complete || opts.complete) && $.isFunction(complete)) {
- complete.apply(opts.context || api, arguments);
- }
- }
+ return BROWSER.ie < 9 ? 0 :
+ intCss(this._useTitle(corner) && elements.titlebar || elements.content, prop) ||
+ intCss(elements.tooltip, prop) || 0;
+ },
- // Define success handler
- function successHandler(content, status, jqXHR) {
- var success;
+ _invalidColour: function(elem, prop, compare) {
+ var val = elem.css(prop);
+ return !val || (compare && val === elem.css(compare)) || INVALID.test(val) ? FALSE : val;
+ },
- // Don't proceed if tooltip is destroyed
- if(api.destroyed) { return; }
+ _parseColours: function(corner) {
+ var elements = this.qtip.elements,
+ tip = this.element.css('cssText', ''),
+ borderSide = BORDER + camel(corner[ corner.precedance ]) + camel(COLOR),
+ colorElem = this._useTitle(corner) && elements.titlebar || elements.content,
+ css = this._invalidColour, color = [];
- // If URL contains a selector
- if(selector && 'string' === typeof content) {
- // Create a dummy div to hold the results and grab the selector element
- content = $('<div/>')
- // inject the contents of the document in, removing the scripts
- // to avoid any 'Permission Denied' errors in IE
- .append(content.replace(rscript, ""))
-
- // Locate the specified elements
- .find(selector);
- }
+ // Attempt to detect the background colour from various elements, left-to-right precedance
+ color[0] = css(tip, BG_COLOR) || css(colorElem, BG_COLOR) || css(elements.content, BG_COLOR) ||
+ css(tooltip, BG_COLOR) || tip.css(BG_COLOR);
- // Call the success function if one is defined
- if((success = defaults.success || opts.success) && $.isFunction(success)) {
- success.call(opts.context || api, content, status, jqXHR);
- }
+ // Attempt to detect the correct border side colour from various elements, left-to-right precedance
+ color[1] = css(tip, borderSide, COLOR) || css(colorElem, borderSide, COLOR) ||
+ css(elements.content, borderSide, COLOR) || css(tooltip, borderSide, COLOR) || tooltip.css(borderSide);
- // Otherwise set the content
- else { api.set('content.text', content); }
- }
+ // Reset background and border colours
+ $('*', tip).add(tip).css('cssText', BG_COLOR+':'+TRANSPARENT+IMPORTANT+';'+BORDER+':0'+IMPORTANT+';');
- // Error handler
- function errorHandler(xhr, status, error) {
- if(api.destroyed || xhr.status === 0) { return; }
- api.set('content.text', status + ': ' + error);
- }
+ return color;
+ },
- // Setup $.ajax option object and process the request
- xhr = $.ajax(
- $.extend({
- error: defaults.error || errorHandler,
- context: api
- },
- opts, { url: url, success: successHandler, complete: after })
- );
- },
+ _calculateSize: function(corner) {
+ var y = corner.precedance === Y,
+ width = this.options[ y ? 'height' : 'width' ],
+ height = this.options[ y ? 'width' : 'height' ],
+ isCenter = corner.abbrev() === 'c',
+ base = width * (isCenter ? 0.5 : 1),
+ pow = Math.pow,
+ round = Math.round,
+ bigHyp, ratio, result,
- destroy: function() {
- // Cancel ajax request if possible
- if(xhr && xhr.abort) { xhr.abort(); }
+ smallHyp = Math.sqrt( pow(base, 2) + pow(height, 2) ),
+ hyp = [ (this.border / base) * smallHyp, (this.border / height) * smallHyp ];
- // Set api.destroyed flag
- api.destroyed = TRUE;
+ hyp[2] = Math.sqrt( pow(hyp[0], 2) - pow(this.border, 2) );
+ hyp[3] = Math.sqrt( pow(hyp[1], 2) - pow(this.border, 2) );
+
+ bigHyp = smallHyp + hyp[2] + hyp[3] + (isCenter ? 0 : hyp[0]);
+ ratio = bigHyp / smallHyp;
+
+ result = [ round(ratio * width), round(ratio * height) ];
+
+ return y ? result : result.reverse();
+ },
+
+ // Tip coordinates calculator
+ _calculateTip: function(corner) {
+ var width = this.size[0], height = this.size[1],
+ width2 = Math.ceil(width / 2), height2 = Math.ceil(height / 2),
+
+ // Define tip coordinates in terms of height and width values
+ tips = {
+ br: [0,0, width,height, width,0],
+ bl: [0,0, width,0, 0,height],
+ tr: [0,height, width,0, width,height],
+ tl: [0,0, 0,height, width,height],
+ tc: [0,height, width2,0, width,height],
+ bc: [0,0, width,0, width2,height],
+ rc: [0,0, width,height2, 0,height],
+ lc: [width,0, width,height, 0,height2]
+ };
+
+ // Set common side shapes
+ tips.lt = tips.br; tips.rt = tips.bl;
+ tips.lb = tips.tr; tips.rb = tips.tl;
+
+ return tips[ corner.abbrev() ];
+ },
+
+ create: function() {
+ // Determine tip corner
+ var c = this.corner = (HASCANVAS || BROWSER.ie) && this._parseCorner(this.options.corner);
+
+ // If we have a tip corner...
+ if( (this.enabled = !!this.corner && this.corner.abbrev() !== 'c') ) {
+ // Cache it
+ this.qtip.cache.corner = c.clone();
+
+ // Create it
+ this.update();
}
- });
- self.init();
-}
+ // Toggle tip element
+ this.element.toggle(this.enabled);
+ return this.corner;
+ },
-PLUGINS.ajax = function(api)
-{
- var self = api.plugins.ajax;
-
- return 'object' === typeof self ? self : (api.plugins.ajax = new Ajax(api));
-};
+ update: function(corner, position) {
+ if(!this.enabled) { return this; }
-PLUGINS.ajax.initialize = 'render';
+ var elements = this.qtip.elements,
+ tip = this.element,
+ inner = tip.children(),
+ options = this.options,
+ size = this.size,
+ mimic = options.mimic,
+ round = Math.round,
+ color, precedance, context,
+ coords, translate, newSize, border;
-// Setup plugin sanitization
-PLUGINS.ajax.sanitize = function(options)
-{
- var content = options.content, opts;
- if(content && 'ajax' in content) {
- opts = content.ajax;
- if(typeof opts !== 'object') { opts = options.content.ajax = { url: opts }; }
- if('boolean' !== typeof opts.once && opts.once) { opts.once = !!opts.once; }
- }
-};
+ // Re-determine tip if not already set
+ if(!corner) { corner = this.qtip.cache.corner || this.corner; }
-// Extend original api defaults
-$.extend(TRUE, QTIP.defaults, {
- content: {
- ajax: {
- loading: TRUE,
- once: TRUE
+ // Use corner property if we detect an invalid mimic value
+ if(mimic === FALSE) { mimic = corner; }
+
+ // Otherwise inherit mimic properties from the corner object as necessary
+ else {
+ mimic = new CORNER(mimic);
+ mimic.precedance = corner.precedance;
+
+ if(mimic.x === 'inherit') { mimic.x = corner.x; }
+ else if(mimic.y === 'inherit') { mimic.y = corner.y; }
+ else if(mimic.x === mimic.y) {
+ mimic[ corner.precedance ] = corner[ corner.precedance ];
+ }
}
- }
-});
+ precedance = mimic.precedance;
+ // Ensure the tip width.height are relative to the tip position
+ if(corner.precedance === X) { this._swapDimensions(); }
+ else { this._resetDimensions(); }
-// Tip coordinates calculator
-function calculateTip(corner, width, height)
-{
- var width2 = Math.ceil(width / 2), height2 = Math.ceil(height / 2),
+ // Update our colours
+ color = this.color = this._parseColours(corner);
- // Define tip coordinates in terms of height and width values
- tips = {
- bottomright: [[0,0], [width,height], [width,0]],
- bottomleft: [[0,0], [width,0], [0,height]],
- topright: [[0,height], [width,0], [width,height]],
- topleft: [[0,0], [0,height], [width,height]],
- topcenter: [[0,height], [width2,0], [width,height]],
- bottomcenter: [[0,0], [width,0], [width2,height]],
- rightcenter: [[0,0], [width,height2], [0,height]],
- leftcenter: [[width,0], [width,height], [0,height2]]
- };
+ // Detect border width, taking into account colours
+ if(color[1] !== TRANSPARENT) {
+ // Grab border width
+ border = this.border = this._parseWidth(corner, corner[corner.precedance]);
- // Set common side shapes
- tips.lefttop = tips.bottomright; tips.righttop = tips.bottomleft;
- tips.leftbottom = tips.topright; tips.rightbottom = tips.topleft;
+ // If border width isn't zero, use border color as fill (1.0 style tips)
+ if(options.border && border < 1) { color[0] = color[1]; }
- return tips[ corner.string() ];
-}
+ // Set border width (use detected border width if options.border is true)
+ this.border = border = options.border !== TRUE ? options.border : border;
+ }
+ // Border colour was invalid, set border to zero
+ else { this.border = border = 0; }
-function Tip(qTip, command)
-{
- var self = this,
- opts = qTip.options.style.tip,
- elems = qTip.elements,
- tooltip = elems.tooltip,
- cache = { top: 0, left: 0 },
- size = {
- width: opts.width,
- height: opts.height
- },
- color = { },
- border = opts.border || 0,
- namespace = '.qtip-tip',
- hasCanvas = !!($('<canvas />')[0] || {}).getContext,
- tiphtml;
+ // Calculate coordinates
+ coords = this._calculateTip(mimic);
- self.corner = NULL;
- self.mimic = NULL;
- self.border = border;
- self.offset = opts.offset;
- self.size = size;
+ // Determine tip size
+ newSize = this.size = this._calculateSize(corner);
+ tip.css({
+ width: newSize[0],
+ height: newSize[1],
+ lineHeight: newSize[1]+'px'
+ });
- // Add new option checks for the plugin
- qTip.checks.tip = {
- '^position.my|style.tip.(corner|mimic|border)$': function() {
- // Make sure a tip can be drawn
- if(!self.init()) {
- self.destroy();
- }
+ // Calculate tip translation
+ if(corner.precedance === Y) {
+ translate = [
+ round(mimic.x === LEFT ? border : mimic.x === RIGHT ? newSize[0] - size[0] - border : (newSize[0] - size[0]) / 2),
+ round(mimic.y === TOP ? newSize[1] - size[1] : 0)
+ ];
+ }
+ else {
+ translate = [
+ round(mimic.x === LEFT ? newSize[0] - size[0] : 0),
+ round(mimic.y === TOP ? border : mimic.y === BOTTOM ? newSize[1] - size[1] - border : (newSize[1] - size[1]) / 2)
+ ];
+ }
- // Reposition the tooltip
- qTip.reposition();
- },
- '^style.tip.(height|width)$': function() {
- // Re-set dimensions and redraw the tip
- size = {
- width: opts.width,
- height: opts.height
- };
- self.create();
- self.update();
+ // Canvas drawing implementation
+ if(HASCANVAS) {
+ // Set the canvas size using calculated size
+ inner.attr(WIDTH, newSize[0]).attr(HEIGHT, newSize[1]);
- // Reposition the tooltip
- qTip.reposition();
- },
- '^content.title.text|style.(classes|widget)$': function() {
- if(elems.tip && elems.tip.length) {
- self.update();
+ // Grab canvas context and clear/save it
+ context = inner[0].getContext('2d');
+ context.restore(); context.save();
+ context.clearRect(0,0,3000,3000);
+
+ // Set properties
+ context.fillStyle = color[0];
+ context.strokeStyle = color[1];
+ context.lineWidth = border * 2;
+
+ // Draw the tip
+ context.translate(translate[0], translate[1]);
+ context.beginPath();
+ context.moveTo(coords[0], coords[1]);
+ context.lineTo(coords[2], coords[3]);
+ context.lineTo(coords[4], coords[5]);
+ context.closePath();
+
+ // Apply fill and border
+ if(border) {
+ // Make sure transparent borders are supported by doing a stroke
+ // of the background colour before the stroke colour
+ if(tooltip.css('background-clip') === 'border-box') {
+ context.strokeStyle = color[0];
+ context.stroke();
+ }
+ context.strokeStyle = color[1];
+ context.stroke();
}
+ context.fill();
}
- };
- function whileVisible(callback) {
- var visible = tooltip.is(':visible');
- tooltip.show(); callback(); tooltip.toggle(visible);
- }
+ // VML (IE Proprietary implementation)
+ else {
+ // Setup coordinates string
+ coords = 'm' + coords[0] + ',' + coords[1] + ' l' + coords[2] +
+ ',' + coords[3] + ' ' + coords[4] + ',' + coords[5] + ' xe';
- function swapDimensions() {
- size.width = opts.height;
- size.height = opts.width;
- }
+ // Setup VML-specific offset for pixel-perfection
+ translate[2] = border && /^(r|b)/i.test(corner.string()) ?
+ BROWSER.ie === 8 ? 2 : 1 : 0;
- function resetDimensions() {
- size.width = opts.width;
- size.height = opts.height;
- }
+ // Set initial CSS
+ inner.css({
+ coordsize: (size[0]+border) + ' ' + (size[1]+border),
+ antialias: ''+(mimic.string().indexOf(CENTER) > -1),
+ left: translate[0] - (translate[2] * Number(precedance === X)),
+ top: translate[1] - (translate[2] * Number(precedance === Y)),
+ width: size[0] + border,
+ height: size[1] + border
+ })
+ .each(function(i) {
+ var $this = $(this);
- function reposition(event, api, pos, viewport) {
- if(!elems.tip) { return; }
+ // Set shape specific attributes
+ $this[ $this.prop ? 'prop' : 'attr' ]({
+ coordsize: (size[0]+border) + ' ' + (size[1]+border),
+ path: coords,
+ fillcolor: color[0],
+ filled: !!i,
+ stroked: !i
+ })
+ .toggle(!!(border || i));
- var newCorner = self.corner.clone(),
+ // Check if border is enabled and add stroke element
+ !i && $this.html( createVML(
+ 'stroke', 'weight="'+(border*2)+'px" color="'+color[1]+'" miterlimit="1000" joinstyle="miter"'
+ ) );
+ });
+ }
+
+ // Position if needed
+ if(position !== FALSE) { this.calculate(corner); }
+ },
+
+ calculate: function(corner) {
+ if(!this.enabled) { return FALSE; }
+
+ var self = this,
+ elements = this.qtip.elements,
+ tip = this.element,
+ userOffset = this.options.offset,
+ isWidget = this.qtip.tooltip.hasClass('ui-widget'),
+ position = { },
+ precedance, size, corners;
+
+ // Inherit corner if not provided
+ corner = corner || this.corner;
+ precedance = corner.precedance;
+
+ // Determine which tip dimension to use for adjustment
+ size = this._calculateSize(corner);
+
+ // Setup corners and offset array
+ corners = [ corner.x, corner.y ];
+ if(precedance === X) { corners.reverse(); }
+
+ // Calculate tip position
+ $.each(corners, function(i, side) {
+ var b, bc, br;
+
+ if(side === CENTER) {
+ b = precedance === Y ? LEFT : TOP;
+ position[ b ] = '50%';
+ position[MARGIN+'-' + b] = -Math.round(size[ precedance === Y ? 0 : 1 ] / 2) + userOffset;
+ }
+ else {
+ b = self._parseWidth(corner, side, elements.tooltip);
+ bc = self._parseWidth(corner, side, elements.content);
+ br = self._parseRadius(corner);
+
+ position[ side ] = Math.max(-self.border, i ? bc : (userOffset + (br > b ? br : -b)));
+ }
+ });
+
+ // Adjust for tip size
+ position[ corner[precedance] ] -= size[ precedance === X ? 0 : 1 ];
+
+ // Set and return new position
+ tip.css({ margin: '', top: '', bottom: '', left: '', right: '' }).css(position);
+ return position;
+ },
+
+ reposition: function(event, api, pos, viewport) {
+ if(!this.enabled) { return; }
+
+ var cache = api.cache,
+ newCorner = this.corner.clone(),
adjust = pos.adjusted,
- method = qTip.options.position.adjust.method.split(' '),
+ method = api.options.position.adjust.method.split(' '),
horizontal = method[0],
vertical = method[1] || method[0],
shift = { left: FALSE, top: FALSE, x: 0, y: 0 },
offset, css = {}, props;
// If our tip position isn't fixed e.g. doesn't adjust with viewport...
- if(self.corner.fixed !== TRUE) {
+ if(this.corner.fixed !== TRUE) {
// Horizontal - Shift or flip method
if(horizontal === SHIFT && newCorner.precedance === X && adjust.left && newCorner.y !== CENTER) {
newCorner.precedance = newCorner.precedance === X ? Y : X;
}
else if(horizontal !== SHIFT && adjust.left){
@@ -2176,29 +2408,27 @@
else if(vertical !== SHIFT && adjust.top) {
newCorner.y = newCorner.y === CENTER ? (adjust.top > 0 ? TOP : BOTTOM) : (newCorner.y === TOP ? BOTTOM : TOP);
}
// Update and redraw the tip if needed (check cached details of last drawn tip)
- if(newCorner.string() !== cache.corner.string() && (cache.top !== adjust.top || cache.left !== adjust.left)) {
- self.update(newCorner, FALSE);
+ if(newCorner.string() !== cache.corner.string() && (cache.cornerTop !== adjust.top || cache.cornerLeft !== adjust.left)) {
+ this.update(newCorner, FALSE);
}
}
// Setup tip offset properties
- offset = self.position(newCorner, adjust);
- offset[ newCorner.x ] += parseWidth(newCorner, newCorner.x);
- offset[ newCorner.y ] += parseWidth(newCorner, newCorner.y);
+ offset = this.calculate(newCorner, adjust);
// Readjust offset object to make it left/top
if(offset.right !== undefined) { offset.left = -offset.right; }
if(offset.bottom !== undefined) { offset.top = -offset.bottom; }
- offset.user = Math.max(0, opts.offset);
+ offset.user = this.offset;
// Viewport "shift" specific adjustments
if(shift.left = (horizontal === SHIFT && !!adjust.left)) {
if(newCorner.x === CENTER) {
- css['margin-left'] = shift.x = offset['margin-left'] - adjust.left;
+ css[MARGIN+'-left'] = shift.x = offset[MARGIN+'-left'] - adjust.left;
}
else {
props = offset.right !== undefined ?
[ adjust.left, -offset.left ] : [ -adjust.left, offset.left ];
@@ -2210,11 +2440,11 @@
css[ offset.right !== undefined ? RIGHT : LEFT ] = shift.x;
}
}
if(shift.top = (vertical === SHIFT && !!adjust.top)) {
if(newCorner.y === CENTER) {
- css['margin-top'] = shift.y = offset['margin-top'] - adjust.top;
+ css[MARGIN+'-top'] = shift.y = offset[MARGIN+'-top'] - adjust.top;
}
else {
props = offset.bottom !== undefined ?
[ adjust.top, -offset.top ] : [ -adjust.top, offset.top ];
@@ -2230,453 +2460,73 @@
/*
* If the tip is adjusted in both dimensions, or in a
* direction that would cause it to be anywhere but the
* outer border, hide it!
*/
- elems.tip.css(css).toggle(
+ this.element.css(css).toggle(
!((shift.x && shift.y) || (newCorner.x === CENTER && shift.y) || (newCorner.y === CENTER && shift.x))
);
// Adjust position to accomodate tip dimensions
pos.left -= offset.left.charAt ? offset.user : horizontal !== SHIFT || shift.top || !shift.left && !shift.top ? offset.left : 0;
pos.top -= offset.top.charAt ? offset.user : vertical !== SHIFT || shift.left || !shift.left && !shift.top ? offset.top : 0;
// Cache details
- cache.left = adjust.left; cache.top = adjust.top;
+ cache.cornerLeft = adjust.left; cache.cornerTop = adjust.top;
cache.corner = newCorner.clone();
- }
+ },
- function parseCorner() {
- var corner = opts.corner,
- posOptions = qTip.options.position,
- at = posOptions.at,
- my = posOptions.my.string ? posOptions.my.string() : posOptions.my;
+ destroy: function() {
+ // Unbind events
+ this.qtip._unbind(this.qtip.tooltip, this._ns);
- // Detect corner and mimic properties
- if(corner === FALSE || (my === FALSE && at === FALSE)) {
- return FALSE;
+ // Remove the tip element(s)
+ if(this.qtip.elements.tip) {
+ this.qtip.elements.tip.find('*')
+ .remove().end().remove();
}
- else {
- if(corner === TRUE) {
- self.corner = new PLUGINS.Corner(my);
- }
- else if(!corner.string) {
- self.corner = new PLUGINS.Corner(corner);
- self.corner.fixed = TRUE;
- }
- }
-
- // Cache it
- cache.corner = new PLUGINS.Corner( self.corner.string() );
-
- return self.corner.string() !== 'centercenter';
}
+});
- /* border width calculator */
- function parseWidth(corner, side, use) {
- side = !side ? corner[corner.precedance] : side;
-
- var isTitleTop = elems.titlebar && corner.y === TOP,
- elem = isTitleTop ? elems.titlebar : tooltip,
- borderSide = 'border-' + side + '-width',
- css = function(elem) { return parseInt(elem.css(borderSide), 10); },
- val;
-
- // Grab the border-width value (make tooltip visible first)
- whileVisible(function() {
- val = (use ? css(use) : (css(elems.content) || css(elem) || css(tooltip))) || 0;
- });
- return val;
- }
-
- function parseRadius(corner) {
- var isTitleTop = elems.titlebar && corner.y === TOP,
- elem = isTitleTop ? elems.titlebar : elems.content,
- moz = $.browser.mozilla,
- prefix = moz ? '-moz-' : $.browser.webkit ? '-webkit-' : '',
- nonStandard = 'border-radius-' + corner.y + corner.x,
- standard = 'border-' + corner.y + '-' + corner.x + '-radius',
- css = function(c) { return parseInt(elem.css(c), 10) || parseInt(tooltip.css(c), 10); },
- val;
-
- whileVisible(function() {
- val = css(standard) || css(prefix + standard) || css(prefix + nonStandard) || css(nonStandard) || 0;
- });
- return val;
- }
-
- function parseColours(actual) {
- var i, fill, border,
- tip = elems.tip.css('cssText', ''),
- corner = actual || self.corner,
- invalid = /rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i,
- borderSide = 'border-' + corner[ corner.precedance ] + '-color',
- bgColor = 'background-color',
- transparent = 'transparent',
- important = ' !important',
-
- titlebar = elems.titlebar,
- useTitle = titlebar && (corner.y === TOP || (corner.y === CENTER && tip.position().top + (size.height / 2) + opts.offset < titlebar.outerHeight(TRUE))),
- colorElem = useTitle ? titlebar : elems.content;
-
- function css(elem, prop, compare) {
- var val = elem.css(prop) || transparent;
- if(compare && val === elem.css(compare)) { return FALSE; }
- else { return invalid.test(val) ? FALSE : val; }
- }
-
- // Ensure tooltip is visible then...
- whileVisible(function() {
- // Attempt to detect the background colour from various elements, left-to-right precedance
- color.fill = css(tip, bgColor) || css(colorElem, bgColor) || css(elems.content, bgColor) ||
- css(tooltip, bgColor) || tip.css(bgColor);
-
- // Attempt to detect the correct border side colour from various elements, left-to-right precedance
- color.border = css(tip, borderSide, 'color') || css(colorElem, borderSide, 'color') ||
- css(elems.content, borderSide, 'color') || css(tooltip, borderSide, 'color') || tooltip.css(borderSide);
-
- // Reset background and border colours
- $('*', tip).add(tip).css('cssText', bgColor+':'+transparent+important+';border:0'+important+';');
- });
- }
-
- function calculateSize(corner) {
- var y = corner.precedance === Y,
- width = size [ y ? WIDTH : HEIGHT ],
- height = size [ y ? HEIGHT : WIDTH ],
- isCenter = corner.string().indexOf(CENTER) > -1,
- base = width * (isCenter ? 0.5 : 1),
- pow = Math.pow,
- round = Math.round,
- bigHyp, ratio, result,
-
- smallHyp = Math.sqrt( pow(base, 2) + pow(height, 2) ),
-
- hyp = [
- (border / base) * smallHyp, (border / height) * smallHyp
- ];
- hyp[2] = Math.sqrt( pow(hyp[0], 2) - pow(border, 2) );
- hyp[3] = Math.sqrt( pow(hyp[1], 2) - pow(border, 2) );
-
- bigHyp = smallHyp + hyp[2] + hyp[3] + (isCenter ? 0 : hyp[0]);
- ratio = bigHyp / smallHyp;
-
- result = [ round(ratio * height), round(ratio * width) ];
- return { height: result[ y ? 0 : 1 ], width: result[ y ? 1 : 0 ] };
- }
-
- function createVML(tag, props, style) {
- return '<qvml:'+tag+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(props||'')+
- ' style="behavior: url(#default#VML); '+(style||'')+ '" />';
- }
-
- $.extend(self, {
- init: function()
- {
- var enabled = parseCorner() && (hasCanvas || $.browser.msie);
-
- // Determine tip corner and type
- if(enabled) {
- // Create a new tip and draw it
- self.create();
- self.update();
-
- // Bind update events
- tooltip.unbind(namespace).bind('tooltipmove'+namespace, reposition);
-
- // Fix for issue of tips not showing after redraw in IE (VML...)
- if(!hasCanvas) {
- tooltip.bind('tooltipredraw tooltipredrawn', function(event) {
- if(event.type === 'tooltipredraw') {
- tiphtml = elems.tip.html();
- elems.tip.html('');
- }
- else { elems.tip.html(tiphtml); }
- });
- }
- }
-
- return enabled;
- },
-
- create: function()
- {
- var width = size.width,
- height = size.height,
- vml;
-
- // Remove previous tip element if present
- if(elems.tip) { elems.tip.remove(); }
-
- // Create tip element and prepend to the tooltip
- elems.tip = $('<div />', { 'class': 'ui-tooltip-tip' }).css({ width: width, height: height }).prependTo(tooltip);
-
- // Create tip drawing element(s)
- if(hasCanvas) {
- // save() as soon as we create the canvas element so FF2 doesn't bork on our first restore()!
- $('<canvas />').appendTo(elems.tip)[0].getContext('2d').save();
- }
- else {
- vml = createVML('shape', 'coordorigin="0,0"', 'position:absolute;');
- elems.tip.html(vml + vml);
-
- // Prevent mousing down on the tip since it causes problems with .live() handling in IE due to VML
- $('*', elems.tip).bind('click mousedown', function(event) { event.stopPropagation(); });
- }
- },
-
- update: function(corner, position)
- {
- var tip = elems.tip,
- inner = tip.children(),
- width = size.width,
- height = size.height,
- mimic = opts.mimic,
- round = Math.round,
- precedance, context, coords, translate, newSize;
-
- // Re-determine tip if not already set
- if(!corner) { corner = cache.corner || self.corner; }
-
- // Use corner property if we detect an invalid mimic value
- if(mimic === FALSE) { mimic = corner; }
-
- // Otherwise inherit mimic properties from the corner object as necessary
- else {
- mimic = new PLUGINS.Corner(mimic);
- mimic.precedance = corner.precedance;
-
- if(mimic.x === 'inherit') { mimic.x = corner.x; }
- else if(mimic.y === 'inherit') { mimic.y = corner.y; }
- else if(mimic.x === mimic.y) {
- mimic[ corner.precedance ] = corner[ corner.precedance ];
- }
- }
- precedance = mimic.precedance;
-
- // Ensure the tip width.height are relative to the tip position
- if(corner.precedance === X) { swapDimensions(); }
- else { resetDimensions(); }
-
- // Set the tip dimensions
- elems.tip.css({
- width: (width = size.width),
- height: (height = size.height)
- });
-
- // Update our colours
- parseColours(corner);
-
- // Detect border width, taking into account colours
- if(color.border !== 'transparent') {
- // Grab border width
- border = parseWidth(corner, NULL);
-
- // If border width isn't zero, use border color as fill (1.0 style tips)
- if(opts.border === 0 && border > 0) { color.fill = color.border; }
-
- // Set border width (use detected border width if opts.border is true)
- self.border = border = opts.border !== TRUE ? opts.border : border;
- }
-
- // Border colour was invalid, set border to zero
- else { self.border = border = 0; }
-
- // Calculate coordinates
- coords = calculateTip(mimic, width , height);
-
- // Determine tip size
- self.size = newSize = calculateSize(corner);
- tip.css(newSize);
-
- // Calculate tip translation
- if(corner.precedance === Y) {
- translate = [
- round(mimic.x === LEFT ? border : mimic.x === RIGHT ? newSize.width - width - border : (newSize.width - width) / 2),
- round(mimic.y === TOP ? newSize.height - height : 0)
- ];
- }
- else {
- translate = [
- round(mimic.x === LEFT ? newSize.width - width : 0),
- round(mimic.y === TOP ? border : mimic.y === BOTTOM ? newSize.height - height - border : (newSize.height - height) / 2)
- ];
- }
-
- // Canvas drawing implementation
- if(hasCanvas) {
- // Set the canvas size using calculated size
- inner.attr(newSize);
-
- // Grab canvas context and clear/save it
- context = inner[0].getContext('2d');
- context.restore(); context.save();
- context.clearRect(0,0,3000,3000);
-
- // Set properties
- context.fillStyle = color.fill;
- context.strokeStyle = color.border;
- context.lineWidth = border * 2;
- context.lineJoin = 'miter';
- context.miterLimit = 100;
-
- // Translate origin
- context.translate(translate[0], translate[1]);
-
- // Draw the tip
- context.beginPath();
- context.moveTo(coords[0][0], coords[0][1]);
- context.lineTo(coords[1][0], coords[1][1]);
- context.lineTo(coords[2][0], coords[2][1]);
- context.closePath();
-
- // Apply fill and border
- if(border) {
- // Make sure transparent borders are supported by doing a stroke
- // of the background colour before the stroke colour
- if(tooltip.css('background-clip') === 'border-box') {
- context.strokeStyle = color.fill;
- context.stroke();
- }
- context.strokeStyle = color.border;
- context.stroke();
- }
- context.fill();
- }
-
- // VML (IE Proprietary implementation)
- else {
- // Setup coordinates string
- coords = 'm' + coords[0][0] + ',' + coords[0][1] + ' l' + coords[1][0] +
- ',' + coords[1][1] + ' ' + coords[2][0] + ',' + coords[2][1] + ' xe';
-
- // Setup VML-specific offset for pixel-perfection
- translate[2] = border && /^(r|b)/i.test(corner.string()) ?
- parseFloat($.browser.version, 10) === 8 ? 2 : 1 : 0;
-
- // Set initial CSS
- inner.css({
- coordsize: (width+border) + ' ' + (height+border),
- antialias: ''+(mimic.string().indexOf(CENTER) > -1),
- left: translate[0],
- top: translate[1],
- width: width + border,
- height: height + border
- })
- .each(function(i) {
- var $this = $(this);
-
- // Set shape specific attributes
- $this[ $this.prop ? 'prop' : 'attr' ]({
- coordsize: (width+border) + ' ' + (height+border),
- path: coords,
- fillcolor: color.fill,
- filled: !!i,
- stroked: !i
- })
- .toggle(!!(border || i));
-
- // Check if border is enabled and add stroke element
- if(!i && $this.html() === '') {
- $this.html(
- createVML('stroke', 'weight="'+(border*2)+'px" color="'+color.border+'" miterlimit="1000" joinstyle="miter"')
- );
- }
- });
- }
-
- // Position if needed
- if(position !== FALSE) { self.position(corner); }
- },
-
- // Tip positioning method
- position: function(corner)
- {
- var tip = elems.tip,
- position = {},
- userOffset = Math.max(0, opts.offset),
- precedance, dimensions, corners;
-
- // Return if tips are disabled or tip is not yet rendered
- if(opts.corner === FALSE || !tip) { return FALSE; }
-
- // Inherit corner if not provided
- corner = corner || self.corner;
- precedance = corner.precedance;
-
- // Determine which tip dimension to use for adjustment
- dimensions = calculateSize(corner);
-
- // Setup corners and offset array
- corners = [ corner.x, corner.y ];
- if(precedance === X) { corners.reverse(); }
-
- // Calculate tip position
- $.each(corners, function(i, side) {
- var b, bc, br;
-
- if(side === CENTER) {
- b = precedance === Y ? LEFT : TOP;
- position[ b ] = '50%';
- position['margin-' + b] = -Math.round(dimensions[ precedance === Y ? WIDTH : HEIGHT ] / 2) + userOffset;
- }
- else {
- b = parseWidth(corner, side);
- bc = parseWidth(corner, side, elems.content);
- br = parseRadius(corner);
-
- position[ side ] = i ? bc : (userOffset + (br > b ? br : -b));
- }
- });
-
- // Adjust for tip dimensions
- position[ corner[precedance] ] -= dimensions[ precedance === X ? WIDTH : HEIGHT ];
-
- // Set and return new position
- tip.css({ top: '', bottom: '', left: '', right: '', margin: '' }).css(position);
- return position;
- },
-
- destroy: function()
- {
- // Remove the tip element
- if(elems.tip) { elems.tip.remove(); }
- elems.tip = false;
-
- // Unbind events
- tooltip.unbind(namespace);
- }
- });
-
- self.init();
-}
-
-PLUGINS.tip = function(api)
-{
- var self = api.plugins.tip;
-
- return 'object' === typeof self ? self : (api.plugins.tip = new Tip(api));
+TIP = PLUGINS.tip = function(api) {
+ return new Tip(api, api.options.style.tip);
};
// Initialize tip on render
-PLUGINS.tip.initialize = 'render';
+TIP.initialize = 'render';
// Setup plugin sanitization options
-PLUGINS.tip.sanitize = function(options)
-{
- var style = options.style, opts;
- if(style && 'tip' in style) {
+TIP.sanitize = function(options) {
+ if(options.style && 'tip' in options.style) {
opts = options.style.tip;
- if(typeof opts !== 'object'){ options.style.tip = { corner: opts }; }
- if(!(/string|boolean/i).test(typeof opts['corner'])) { opts['corner'] = TRUE; }
- if(typeof opts.width !== 'number'){ delete opts.width; }
- if(typeof opts.height !== 'number'){ delete opts.height; }
- if(typeof opts.border !== 'number' && opts.border !== TRUE){ delete opts.border; }
- if(typeof opts.offset !== 'number'){ delete opts.offset; }
+ if(typeof opts !== 'object') { opts = options.style.tip = { corner: opts }; }
+ if(!(/string|boolean/i).test(typeof opts.corner)) { opts.corner = TRUE; }
}
};
+// Add new option checks for the plugin
+CHECKS.tip = {
+ '^position.my|style.tip.(corner|mimic|border)$': function() {
+ // Make sure a tip can be drawn
+ this.create();
+
+ // Reposition the tooltip
+ this.qtip.reposition();
+ },
+ '^style.tip.(height|width)$': function(obj) {
+ // Re-set dimensions and redraw the tip
+ this.size = size = [ obj.width, obj.height ];
+ this.update();
+
+ // Reposition the tooltip
+ this.qtip.reposition();
+ },
+ '^content.title|style.(classes|widget)$': function() {
+ this.update();
+ }
+};
+
// Extend original qTip defaults
$.extend(TRUE, QTIP.defaults, {
style: {
tip: {
corner: TRUE,
@@ -2687,321 +2537,342 @@
offset: 0
}
}
});
+;var MODAL, OVERLAY,
+ MODALCLASS = 'qtip-modal',
+ MODALSELECTOR = '.'+MODALCLASS;
-function Modal(api)
+OVERLAY = function()
{
var self = this,
- options = api.options.show.modal,
- elems = api.elements,
- tooltip = elems.tooltip,
- overlaySelector = '#qtip-overlay',
- globalNamespace = '.qtipmodal',
- namespace = globalNamespace + api.id,
- attr = 'is-modal-qtip',
- docBody = $(document.body),
- focusableSelector = PLUGINS.modal.focusable.join(','),
- focusableElems = {}, overlay;
+ focusableElems = {},
+ current, onLast,
+ prevState, elem;
- // Setup option set checks
- api.checks.modal = {
- '^show.modal.(on|blur)$': function() {
- // Initialise
- self.init();
-
- // Show the modal if not visible already and tooltip is visible
- elems.overlay.toggle( tooltip.is(':visible') );
- },
- '^content.text$': function() {
- updateFocusable();
- }
- };
+ // Modified code from jQuery UI 1.10.0 source
+ // http://code.jquery.com/ui/1.10.0/jquery-ui.js
+ function focusable(element) {
+ // Use the defined focusable checker when possible
+ if($.expr[':'].focusable) { return $.expr[':'].focusable; }
- function updateFocusable() {
- focusableElems = $(focusableSelector, tooltip).not('[disabled]').map(function() {
- return typeof this.focus === 'function' ? this : null;
- });
+ var isTabIndexNotNaN = !isNaN($.attr(element, 'tabindex')),
+ nodeName = element.nodeName && element.nodeName.toLowerCase(),
+ map, mapName, img;
+
+ if('area' === nodeName) {
+ map = element.parentNode;
+ mapName = map.name;
+ if(!element.href || !mapName || map.nodeName.toLowerCase() !== 'map') {
+ return false;
+ }
+ img = $('img[usemap=#' + mapName + ']')[0];
+ return !!img && img.is(':visible');
+ }
+ return (/input|select|textarea|button|object/.test( nodeName ) ?
+ !element.disabled :
+ 'a' === nodeName ?
+ element.href || isTabIndexNotNaN :
+ isTabIndexNotNaN
+ );
}
+ // Focus inputs using cached focusable elements (see update())
function focusInputs(blurElems) {
// Blurring body element in IE causes window.open windows to unfocus!
if(focusableElems.length < 1 && blurElems.length) { blurElems.not('body').blur(); }
// Focus the inputs
else { focusableElems.first().focus(); }
}
+ // Steal focus from elements outside tooltip
function stealFocus(event) {
+ if(!elem.is(':visible')) { return; }
+
var target = $(event.target),
- container = target.closest('.qtip'),
+ tooltip = current.tooltip,
+ container = target.closest(SELECTOR),
targetOnTop;
// Determine if input container target is above this
targetOnTop = container.length < 1 ? FALSE :
(parseInt(container[0].style.zIndex, 10) > parseInt(tooltip[0].style.zIndex, 10));
// If we're showing a modal, but focus has landed on an input below
// this modal, divert focus to the first visible input in this modal
// or if we can't find one... the tooltip itself
- if(!targetOnTop && ($(event.target).closest(selector)[0] !== tooltip[0])) {
+ if(!targetOnTop && target.closest(SELECTOR)[0] !== tooltip[0]) {
focusInputs(target);
}
+
+ // Detect when we leave the last focusable element...
+ onLast = event.target === focusableElems[focusableElems.length - 1];
}
$.extend(self, {
- init: function()
- {
- // If modal is disabled... return
- if(!options.on) { return self; }
-
- // Create the overlay if needed
- overlay = self.create();
-
- // Add unique attribute so we can grab modal tooltips easily via a selector
- tooltip.attr(attr, TRUE)
-
- // Set z-index
- .css('z-index', PLUGINS.modal.zindex + $(selector+'['+attr+']').length)
-
- // Remove previous bound events in globalNamespace
- .unbind(globalNamespace).unbind(namespace)
-
- // Apply our show/hide/focus modal events
- .bind('tooltipshow'+globalNamespace+' tooltiphide'+globalNamespace, function(event, api, duration) {
- var oEvent = event.originalEvent;
-
- // Make sure mouseout doesn't trigger a hide when showing the modal and mousing onto backdrop
- if(event.target === tooltip[0]) {
- if(oEvent && event.type === 'tooltiphide' && /mouse(leave|enter)/.test(oEvent.type) && $(oEvent.relatedTarget).closest(overlay[0]).length) {
- try { event.preventDefault(); } catch(e) {}
- }
- else if(!oEvent || (oEvent && !oEvent.solo)) {
- self[ event.type.replace('tooltip', '') ](event, duration);
- }
- }
+ init: function() {
+ // Create document overlay
+ elem = self.elem = $('<div />', {
+ id: 'qtip-overlay',
+ html: '<div></div>',
+ mousedown: function() { return FALSE; }
})
+ .hide();
- // Adjust modal z-index on tooltip focus
- .bind('tooltipfocus'+globalNamespace, function(event) {
- // If focus was cancelled before it reearch us, don't do anything
- if(event.isDefaultPrevented() || event.target !== tooltip[0]) { return; }
-
- var qtips = $(selector).filter('['+attr+']'),
-
- // Keep the modal's lower than other, regular qtips
- newIndex = PLUGINS.modal.zindex + qtips.length,
- curIndex = parseInt(tooltip[0].style.zIndex, 10);
-
- // Set overlay z-index
- overlay[0].style.zIndex = newIndex - 2;
-
- // Reduce modal z-index's and keep them properly ordered
- qtips.each(function() {
- if(this.style.zIndex > curIndex) {
- this.style.zIndex -= 1;
- }
+ // Update position on window resize or scroll
+ function resize() {
+ var win = $(this);
+ elem.css({
+ height: win.height(),
+ width: win.width()
});
+ }
+ $(window).bind('resize'+MODALSELECTOR, resize);
+ resize(); // Fire it initially too
- // Fire blur event for focused tooltip
- qtips.end().filter('.' + focusClass).qtip('blur', event.originalEvent);
+ // Make sure we can't focus anything outside the tooltip
+ $(document.body).bind('focusin'+MODALSELECTOR, stealFocus);
- // Set the new z-index
- tooltip.addClass(focusClass)[0].style.zIndex = newIndex;
-
- // Prevent default handling
- try { event.preventDefault(); } catch(e) {}
- })
-
- // Focus any other visible modals when this one hides
- .bind('tooltiphide'+globalNamespace, function(event) {
- if(event.target === tooltip[0]) {
- $('[' + attr + ']').filter(':visible').not(tooltip).last().qtip('focus', event);
+ // Apply keyboard "Escape key" close handler
+ $(document).bind('keydown'+MODALSELECTOR, function(event) {
+ if(current && current.options.show.modal.escape && event.keyCode === 27) {
+ current.hide(event);
}
});
- // Apply keyboard "Escape key" close handler
- if(options.escape) {
- $(document).unbind(namespace).bind('keydown'+namespace, function(event) {
- if(event.keyCode === 27 && tooltip.hasClass(focusClass)) {
- api.hide(event);
- }
- });
- }
-
// Apply click handler for blur option
- if(options.blur) {
- elems.overlay.unbind(namespace).bind('click'+namespace, function(event) {
- if(tooltip.hasClass(focusClass)) { api.hide(event); }
- });
- }
+ elem.bind('click'+MODALSELECTOR, function(event) {
+ if(current && current.options.show.modal.blur) {
+ current.hide(event);
+ }
+ });
- // Update focusable elements
- updateFocusable();
-
return self;
},
- create: function()
- {
- var elem = $(overlaySelector);
+ update: function(api) {
+ // Update current API reference
+ current = api;
- // Return if overlay is already rendered
- if(elem.length) {
- // Modal overlay should always be below all tooltips if possible
- return (elems.overlay = elem.insertAfter( $(selector).last() ));
- }
-
- // Create document overlay
- overlay = elems.overlay = $('<div />', {
- id: overlaySelector.substr(1),
- html: '<div></div>',
- mousedown: function() { return FALSE; }
- })
- .hide()
- .insertAfter( $(selector).last() );
-
- // Update position on window resize or scroll
- function resize() {
- overlay.css({
- height: $(window).height(),
- width: $(window).width()
+ // Update focusable elements if enabled
+ if(api.options.show.modal.stealfocus !== FALSE) {
+ focusableElems = api.tooltip.find('*').filter(function() {
+ return focusable(this);
});
}
- $(window).unbind(globalNamespace).bind('resize'+globalNamespace, resize);
- resize(); // Fire it initially too
-
- return overlay;
+ else { focusableElems = []; }
},
- toggle: function(event, state, duration)
- {
- // Make sure default event hasn't been prevented
- if(event && event.isDefaultPrevented()) { return self; }
-
- var effect = options.effect,
+ toggle: function(api, state, duration) {
+ var docBody = $(document.body),
+ tooltip = api.tooltip,
+ options = api.options.show.modal,
+ effect = options.effect,
type = state ? 'show': 'hide',
- visible = overlay.is(':visible'),
- modals = $('[' + attr + ']').filter(':visible').not(tooltip),
+ visible = elem.is(':visible'),
+ visibleModals = $(MODALSELECTOR).filter(':visible:not(:animated)').not(tooltip),
zindex;
- // Create our overlay if it isn't present already
- if(!overlay) { overlay = self.create(); }
+ // Set active tooltip API reference
+ self.update(api);
- // Prevent modal from conflicting with show.solo, and don't hide backdrop is other modals are visible
- if((overlay.is(':animated') && visible === state) || (!state && modals.length)) { return self; }
+ // If the modal can steal the focus...
+ // Blur the current item and focus anything in the modal we an
+ if(state && options.stealfocus !== FALSE) {
+ focusInputs( $(':focus') );
+ }
- // State specific...
+ // Toggle backdrop cursor style on show
+ elem.toggleClass('blurs', options.blur);
+
+ // Set position and append to body on show
if(state) {
- // Set position
- overlay.css({ left: 0, top: 0 });
+ elem.css({ left: 0, top: 0 })
+ .appendTo(document.body);
+ }
- // Toggle backdrop cursor style on show
- overlay.toggleClass('blurs', options.blur);
-
- // IF the modal can steal the focus
- if(options.stealfocus !== FALSE) {
- // Make sure we can't focus anything outside the tooltip
- docBody.bind('focusin'+namespace, stealFocus);
-
- // Blur the current item and focus anything in the modal we an
- focusInputs( $('body :focus') );
- }
+ // Prevent modal from conflicting with show.solo, and don't hide backdrop is other modals are visible
+ if((elem.is(':animated') && visible === state && prevState !== FALSE) || (!state && visibleModals.length)) {
+ return self;
}
- else {
- // Undelegate focus handler
- docBody.unbind('focusin'+namespace);
- }
// Stop all animations
- overlay.stop(TRUE, FALSE);
+ elem.stop(TRUE, FALSE);
// Use custom function if provided
if($.isFunction(effect)) {
- effect.call(overlay, state);
+ effect.call(elem, state);
}
// If no effect type is supplied, use a simple toggle
else if(effect === FALSE) {
- overlay[ type ]();
+ elem[ type ]();
}
// Use basic fade function
else {
- overlay.fadeTo( parseInt(duration, 10) || 90, state ? 1 : 0, function() {
- if(!state) { $(this).hide(); }
+ elem.fadeTo( parseInt(duration, 10) || 90, state ? 1 : 0, function() {
+ if(!state) { elem.hide(); }
});
}
- // Reset position on hide
+ // Reset position and detach from body on hide
if(!state) {
- overlay.queue(function(next) {
- overlay.css({ left: '', top: '' });
+ elem.queue(function(next) {
+ elem.css({ left: '', top: '' });
+ if(!$(MODALSELECTOR).length) { elem.detach(); }
next();
});
}
+ // Cache the state
+ prevState = state;
+
+ // If the tooltip is destroyed, set reference to null
+ if(current.destroyed) { current = NULL; }
+
return self;
- },
+ }
+ });
- show: function(event, duration) { return self.toggle(event, TRUE, duration); },
- hide: function(event, duration) { return self.toggle(event, FALSE, duration); },
+ self.init();
+};
+OVERLAY = new OVERLAY();
- destroy: function()
- {
- var delBlanket = overlay;
+function Modal(api, options) {
+ this.options = options;
+ this._ns = '-modal';
- if(delBlanket) {
- // Check if any other modal tooltips are present
- delBlanket = $('[' + attr + ']').not(tooltip).length < 1;
+ this.init( (this.qtip = api) );
+}
- // Remove overlay if needed
- if(delBlanket) {
- elems.overlay.remove();
- $(document).unbind(globalNamespace);
+$.extend(Modal.prototype, {
+ init: function(qtip) {
+ var tooltip = qtip.tooltip;
+
+ // If modal is disabled... return
+ if(!this.options.on) { return this; }
+
+ // Set overlay reference
+ qtip.elements.overlay = OVERLAY.elem;
+
+ // Add unique attribute so we can grab modal tooltips easily via a SELECTOR, and set z-index
+ tooltip.addClass(MODALCLASS).css('z-index', PLUGINS.modal.zindex + $(MODALSELECTOR).length);
+
+ // Apply our show/hide/focus modal events
+ qtip._bind(tooltip, ['tooltipshow', 'tooltiphide'], function(event, api, duration) {
+ var oEvent = event.originalEvent;
+
+ // Make sure mouseout doesn't trigger a hide when showing the modal and mousing onto backdrop
+ if(event.target === tooltip[0]) {
+ if(oEvent && event.type === 'tooltiphide' && /mouse(leave|enter)/.test(oEvent.type) && $(oEvent.relatedTarget).closest(overlay[0]).length) {
+ try { event.preventDefault(); } catch(e) {}
}
- else {
- elems.overlay.unbind(globalNamespace+api.id);
+ else if(!oEvent || (oEvent && !oEvent.solo)) {
+ this.toggle(event, event.type === 'tooltipshow', duration);
}
+ }
+ }, this._ns, this);
- // Undelegate focus handler
- docBody.undelegate('*', 'focusin'+namespace);
+ // Adjust modal z-index on tooltip focus
+ qtip._bind(tooltip, 'tooltipfocus', function(event, api) {
+ // If focus was cancelled before it reached us, don't do anything
+ if(event.isDefaultPrevented() || event.target !== tooltip[0]) { return; }
+
+ var qtips = $(MODALSELECTOR),
+
+ // Keep the modal's lower than other, regular qtips
+ newIndex = PLUGINS.modal.zindex + qtips.length,
+ curIndex = parseInt(tooltip[0].style.zIndex, 10);
+
+ // Set overlay z-index
+ OVERLAY.elem[0].style.zIndex = newIndex - 1;
+
+ // Reduce modal z-index's and keep them properly ordered
+ qtips.each(function() {
+ if(this.style.zIndex > curIndex) {
+ this.style.zIndex -= 1;
+ }
+ });
+
+ // Fire blur event for focused tooltip
+ qtips.filter('.' + CLASS_FOCUS).qtip('blur', event.originalEvent);
+
+ // Set the new z-index
+ tooltip.addClass(CLASS_FOCUS)[0].style.zIndex = newIndex;
+
+ // Set current
+ OVERLAY.update(api);
+
+ // Prevent default handling
+ try { event.preventDefault(); } catch(e) {}
+ }, this._ns, this);
+
+ // Focus any other visible modals when this one hides
+ qtip._bind(tooltip, 'tooltiphide', function(event) {
+ if(event.target === tooltip[0]) {
+ $(MODALSELECTOR).filter(':visible').not(tooltip).last().qtip('focus', event);
}
+ }, this._ns, this);
+ },
- // Remove bound events
- return tooltip.removeAttr(attr).unbind(globalNamespace);
- }
- });
+ toggle: function(event, state, duration) {
+ // Make sure default event hasn't been prevented
+ if(event && event.isDefaultPrevented()) { return this; }
- self.init();
-}
+ // Toggle it
+ OVERLAY.toggle(this.qtip, !!state, duration);
+ },
-PLUGINS.modal = function(api) {
- var self = api.plugins.modal;
+ destroy: function() {
+ // Remove modal class
+ this.qtip.tooltip.removeClass(MODALCLASS);
- return 'object' === typeof self ? self : (api.plugins.modal = new Modal(api));
-};
+ // Remove bound events
+ this.qtip._unbind(this.qtip.tooltip, this._ns);
-// Plugin needs to be initialized on render
-PLUGINS.modal.initialize = 'render';
+ // Delete element reference
+ OVERLAY.toggle(this.qtip, FALSE);
+ delete this.qtip.elements.overlay;
+ }
+});
+
+MODAL = PLUGINS.modal = function(api) {
+ return new Modal(api, api.options.show.modal);
+};
+
// Setup sanitiztion rules
-PLUGINS.modal.sanitize = function(opts) {
+MODAL.sanitize = function(opts) {
if(opts.show) {
if(typeof opts.show.modal !== 'object') { opts.show.modal = { on: !!opts.show.modal }; }
else if(typeof opts.show.modal.on === 'undefined') { opts.show.modal.on = TRUE; }
}
};
// Base z-index for all modal tooltips (use qTip core z-index as a base)
-PLUGINS.modal.zindex = QTIP.zindex - 200;
+MODAL.zindex = QTIP.zindex - 200;
-// Defines the selector used to select all 'focusable' elements within the modal when using the show.modal.stealfocus option.
-// Selectors initially taken from http://stackoverflow.com/questions/7668525/is-there-a-jquery-selector-to-get-all-elements-that-can-get-focus
-PLUGINS.modal.focusable = ['a[href]', 'area[href]', 'input', 'select', 'textarea', 'button', 'iframe', 'object', 'embed', '[tabindex]', '[contenteditable]'];
+// Plugin needs to be initialized on render
+MODAL.initialize = 'render';
+// Setup option set checks
+CHECKS.modal = {
+ '^show.modal.(on|blur)$': function() {
+ // Initialise
+ this.destroy();
+ this.init();
+
+ // Show the modal if not visible already and tooltip is visible
+ this.qtip.elems.overlay.toggle(
+ this.qtip.tooltip[0].offsetWidth > 0
+ );
+ }
+};
+
// Extend original api defaults
$.extend(TRUE, QTIP.defaults, {
show: {
modal: {
on: FALSE,
@@ -3010,13 +2881,11 @@
stealfocus: TRUE,
escape: TRUE
}
}
});
-
-
-PLUGINS.viewport = function(api, position, posOptions, targetWidth, targetHeight, elemWidth, elemHeight)
+;PLUGINS.viewport = function(api, position, posOptions, targetWidth, targetHeight, elemWidth, elemHeight)
{
var target = posOptions.target,
tooltip = api.elements.tooltip,
my = posOptions.my,
at = posOptions.at,
@@ -3038,12 +2907,12 @@
// Cache our viewport details
fixed = tooltip.css('position') === 'fixed';
viewport = {
elem: viewport,
- height: viewport[ (viewport[0] === window ? 'h' : 'outerH') + 'eight' ](),
- width: viewport[ (viewport[0] === window ? 'w' : 'outerW') + 'idth' ](),
+ width: viewport[0] === window ? viewport.width() : viewport.outerWidth(FALSE),
+ height: viewport[0] === window ? viewport.height() : viewport.outerHeight(FALSE),
scrollleft: fixed ? 0 : viewport.scrollLeft(),
scrolltop: fixed ? 0 : viewport.scrollTop(),
offset: viewport.offset() || { left: 0, top: 0 }
};
container = {
@@ -3090,17 +2959,17 @@
adjust *= (type === FLIPINVERT ? 2 : 0);
// Check for overflow on the left/top
if(overflow1 > 0 && (mySide !== side1 || overflow2 > 0)) {
position[side1] -= offset + adjust;
- newMy['invert'+side](side1);
+ newMy.invert(side, side1);
}
// Check for overflow on the bottom/right
else if(overflow2 > 0 && (mySide !== side2 || overflow1 > 0) ) {
position[side1] -= (mySide === CENTER ? -offset : offset) + adjust;
- newMy['invert'+side](side2);
+ newMy.invert(side, side2);
}
// Make sure we haven't made things worse with the adjustment and reset if so
if(position[side1] < viewportScroll && -position[side1] > overflow2) {
position[side1] = initialPos; newMy = my.clone();
@@ -3118,248 +2987,414 @@
left: methodX !== 'none' ? calculate( X, Y, methodX, adjust.x, LEFT, RIGHT, WIDTH, targetWidth, elemWidth ) : 0,
top: methodY !== 'none' ? calculate( Y, X, methodY, adjust.y, TOP, BOTTOM, HEIGHT, targetHeight, elemHeight ) : 0
};
// Set tooltip position class if it's changed
- if(newMy && cache.lastClass !== (newClass = uitooltip + '-pos-' + newMy.abbrev())) {
+ if(newMy && cache.lastClass !== (newClass = NAMESPACE + '-pos-' + newMy.abbrev())) {
tooltip.removeClass(api.cache.lastClass).addClass( (api.cache.lastClass = newClass) );
}
return adjusted;
-};
-PLUGINS.imagemap = function(api, area, corner, adjustMethod)
-{
- if(!area.jquery) { area = $(area); }
-
- var cache = (api.cache.areas = {}),
- shape = (area[0].shape || area.attr('shape')).toLowerCase(),
- coordsString = area[0].coords || area.attr('coords'),
- baseCoords = coordsString.split(','),
- coords = [],
- image = $('img[usemap="#'+area.parent('map').attr('name')+'"]'),
- imageOffset = image.offset(),
- result = {
+};;PLUGINS.polys = {
+ // POLY area coordinate calculator
+ // Special thanks to Ed Cradock for helping out with this.
+ // Uses a binary search algorithm to find suitable coordinates.
+ polygon: function(baseCoords, corner) {
+ var result = {
width: 0, height: 0,
position: {
top: 1e10, right: 0,
bottom: 0, left: 1e10
- }
+ },
+ adjustable: FALSE
},
- i = 0, next = 0, dimensions;
+ i = 0, next,
+ coords = [],
+ compareX = 1, compareY = 1,
+ realX = 0, realY = 0,
+ newWidth, newHeight;
- // POLY area coordinate calculator
- // Special thanks to Ed Cradock for helping out with this.
- // Uses a binary search algorithm to find suitable coordinates.
- function polyCoordinates(result, coords, corner)
- {
- var i = 0,
- compareX = 1, compareY = 1,
- realX = 0, realY = 0,
- newWidth = result.width,
- newHeight = result.height;
+ // First pass, sanitize coords and determine outer edges
+ i = baseCoords.length; while(i--) {
+ next = [ parseInt(baseCoords[--i], 10), parseInt(baseCoords[i+1], 10) ];
- // Use a binary search algorithm to locate most suitable coordinate (hopefully)
- while(newWidth > 0 && newHeight > 0 && compareX > 0 && compareY > 0)
- {
- newWidth = Math.floor(newWidth / 2);
- newHeight = Math.floor(newHeight / 2);
+ if(next[0] > result.position.right){ result.position.right = next[0]; }
+ if(next[0] < result.position.left){ result.position.left = next[0]; }
+ if(next[1] > result.position.bottom){ result.position.bottom = next[1]; }
+ if(next[1] < result.position.top){ result.position.top = next[1]; }
- if(corner.x === LEFT){ compareX = newWidth; }
- else if(corner.x === RIGHT){ compareX = result.width - newWidth; }
- else{ compareX += Math.floor(newWidth / 2); }
+ coords.push(next);
+ }
- if(corner.y === TOP){ compareY = newHeight; }
- else if(corner.y === BOTTOM){ compareY = result.height - newHeight; }
- else{ compareY += Math.floor(newHeight / 2); }
+ // Calculate height and width from outer edges
+ newWidth = result.width = Math.abs(result.position.right - result.position.left);
+ newHeight = result.height = Math.abs(result.position.bottom - result.position.top);
- i = coords.length; while(i--)
+ // If it's the center corner...
+ if(corner.abbrev() === 'c') {
+ result.position = {
+ left: result.position.left + (result.width / 2),
+ top: result.position.top + (result.height / 2)
+ };
+ }
+ else {
+ // Second pass, use a binary search algorithm to locate most suitable coordinate
+ while(newWidth > 0 && newHeight > 0 && compareX > 0 && compareY > 0)
{
- if(coords.length < 2){ break; }
+ newWidth = Math.floor(newWidth / 2);
+ newHeight = Math.floor(newHeight / 2);
- realX = coords[i][0] - result.position.left;
- realY = coords[i][1] - result.position.top;
+ if(corner.x === LEFT){ compareX = newWidth; }
+ else if(corner.x === RIGHT){ compareX = result.width - newWidth; }
+ else{ compareX += Math.floor(newWidth / 2); }
- if((corner.x === LEFT && realX >= compareX) ||
- (corner.x === RIGHT && realX <= compareX) ||
- (corner.x === CENTER && (realX < compareX || realX > (result.width - compareX))) ||
- (corner.y === TOP && realY >= compareY) ||
- (corner.y === BOTTOM && realY <= compareY) ||
- (corner.y === CENTER && (realY < compareY || realY > (result.height - compareY)))) {
- coords.splice(i, 1);
+ if(corner.y === TOP){ compareY = newHeight; }
+ else if(corner.y === BOTTOM){ compareY = result.height - newHeight; }
+ else{ compareY += Math.floor(newHeight / 2); }
+
+ i = coords.length; while(i--)
+ {
+ if(coords.length < 2){ break; }
+
+ realX = coords[i][0] - result.position.left;
+ realY = coords[i][1] - result.position.top;
+
+ if((corner.x === LEFT && realX >= compareX) ||
+ (corner.x === RIGHT && realX <= compareX) ||
+ (corner.x === CENTER && (realX < compareX || realX > (result.width - compareX))) ||
+ (corner.y === TOP && realY >= compareY) ||
+ (corner.y === BOTTOM && realY <= compareY) ||
+ (corner.y === CENTER && (realY < compareY || realY > (result.height - compareY)))) {
+ coords.splice(i, 1);
+ }
}
}
+ result.position = { left: coords[0][0], top: coords[0][1] };
}
- return { left: coords[0][0], top: coords[0][1] };
- }
+ return result;
+ },
- // Make sure we account for padding and borders on the image
- imageOffset.left += Math.ceil((image.outerWidth() - image.width()) / 2);
- imageOffset.top += Math.ceil((image.outerHeight() - image.height()) / 2);
+ rect: function(ax, ay, bx, by, corner) {
+ return {
+ width: Math.abs(bx - ax),
+ height: Math.abs(by - ay),
+ position: {
+ left: Math.min(ax, bx),
+ top: Math.min(ay, by)
+ }
+ };
+ },
- // Parse coordinates into proper array
- if(shape === 'poly') {
- i = baseCoords.length; while(i--)
- {
- next = [ parseInt(baseCoords[--i], 10), parseInt(baseCoords[i+1], 10) ];
+ _angles: {
+ tc: 3 / 2, tr: 7 / 4, tl: 5 / 4,
+ bc: 1 / 2, br: 1 / 4, bl: 3 / 4,
+ rc: 2, lc: 1, c: 0
+ },
+ ellipse: function(cx, cy, rx, ry, corner) {
+ var c = PLUGINS.polys._angles[ corner.abbrev() ],
+ rxc = rx * Math.cos( c * Math.PI ),
+ rys = ry * Math.sin( c * Math.PI );
- if(next[0] > result.position.right){ result.position.right = next[0]; }
- if(next[0] < result.position.left){ result.position.left = next[0]; }
- if(next[1] > result.position.bottom){ result.position.bottom = next[1]; }
- if(next[1] < result.position.top){ result.position.top = next[1]; }
-
- coords.push(next);
- }
+ return {
+ width: (rx * 2) - Math.abs(rxc),
+ height: (ry * 2) - Math.abs(rys),
+ position: {
+ left: cx + rxc,
+ top: cy + rys
+ },
+ adjustable: FALSE
+ };
+ },
+ circle: function(cx, cy, r, corner) {
+ return PLUGINS.polys.ellipse(cx, cy, r, r, corner);
}
- else {
- i = -1; while(i++ < baseCoords.length) {
- coords.push( parseInt(baseCoords[i], 10) );
- }
- }
+};;PLUGINS.svg = function(api, svg, corner, adjustMethod)
+{
+ var doc = $(document),
+ elem = svg[0],
+ result = {},
+ name, box, position, dimensions;
- // Calculate details
- switch(shape)
- {
+ // Ascend the parentNode chain until we find an element with getBBox()
+ while(!elem.getBBox) { elem = elem.parentNode; }
+ if(!elem.getBBox || !elem.parentNode) { return FALSE; }
+
+ // Determine which shape calculation to use
+ switch(elem.nodeName) {
case 'rect':
- result = {
- width: Math.abs(coords[2] - coords[0]),
- height: Math.abs(coords[3] - coords[1]),
- position: {
- left: Math.min(coords[0], coords[2]),
- top: Math.min(coords[1], coords[3])
- }
- };
+ position = PLUGINS.svg.toPixel(elem, elem.x.baseVal.value, elem.y.baseVal.value);
+ dimensions = PLUGINS.svg.toPixel(elem,
+ elem.x.baseVal.value + elem.width.baseVal.value,
+ elem.y.baseVal.value + elem.height.baseVal.value
+ );
+
+ result = PLUGINS.polys.rect(
+ position[0], position[1],
+ dimensions[0], dimensions[1],
+ corner
+ );
break;
+ case 'ellipse':
case 'circle':
- result = {
- width: coords[2] + 2,
- height: coords[2] + 2,
- position: { left: coords[0], top: coords[1] }
- };
+ position = PLUGINS.svg.toPixel(elem,
+ elem.cx.baseVal.value,
+ elem.cy.baseVal.value
+ );
+
+ result = PLUGINS.polys.ellipse(
+ position[0], position[1],
+ (elem.rx || elem.r).baseVal.value,
+ (elem.ry || elem.r).baseVal.value,
+ corner
+ );
break;
- case 'poly':
- result.width = Math.abs(result.position.right - result.position.left);
- result.height = Math.abs(result.position.bottom - result.position.top);
+ case 'line':
+ case 'polygon':
+ case 'polyline':
+ points = elem.points || [
+ { x: elem.x1.baseVal.value, y: elem.y1.baseVal.value },
+ { x: elem.x2.baseVal.value, y: elem.y2.baseVal.value }
+ ];
- if(corner.abbrev() === 'c') {
- result.position = {
- left: result.position.left + (result.width / 2),
- top: result.position.top + (result.height / 2)
- };
+ for(result = [], i = -1, len = points.numberOfItems || points.length; ++i < len;) {
+ next = points.getItem ? points.getItem(i) : points[i];
+ result.push.apply(result, PLUGINS.svg.toPixel(elem, next.x, next.y));
}
- else {
- // Calculate if we can't find a cached value
- if(!cache[corner+coordsString]) {
- result.position = polyCoordinates(result, coords.slice(), corner);
- // If flip adjustment is enabled, also calculate the closest opposite point
- if(adjustMethod && (adjustMethod[0] === 'flip' || adjustMethod[1] === 'flip')) {
- result.offset = polyCoordinates(result, coords.slice(), {
- x: corner.x === LEFT ? RIGHT : corner.x === RIGHT ? LEFT : CENTER,
- y: corner.y === TOP ? BOTTOM : corner.y === BOTTOM ? TOP : CENTER
- });
+ result = PLUGINS.polys.polygon(result, corner);
+ break;
- result.offset.left -= result.position.left;
- result.offset.top -= result.position.top;
- }
+ // Unknown shape... use bounding box as fallback
+ default:
+ box = elem.getBBox();
+ mtx = elem.getScreenCTM();
+ root = elem.farthestViewportElement || elem;
- // Store the result
- cache[corner+coordsString] = result;
- }
+ // Return if no createSVGPoint method is found
+ if(!root.createSVGPoint) { return FALSE; }
- // Grab the cached result
- result = cache[corner+coordsString];
- }
+ // Create our point var
+ point = root.createSVGPoint();
- result.width = result.height = 0;
+ // Adjust top and left
+ point.x = box.x;
+ point.y = box.y;
+ tPoint = point.matrixTransform(mtx);
+ result.position = {
+ left: tPoint.x, top: tPoint.y
+ };
+
+ // Adjust width and height
+ point.x += box.width;
+ point.y += box.height;
+ tPoint = point.matrixTransform(mtx);
+ result.width = tPoint.x - result.position.left;
+ result.height = tPoint.y - result.position.top;
break;
}
+ // Adjust by scroll offset
+ result.position.left += doc.scrollLeft();
+ result.position.top += doc.scrollTop();
+
+ return result;
+};
+
+PLUGINS.svg.toPixel = function(elem, x, y) {
+ var mtx = elem.getScreenCTM(),
+ root = elem.farthestViewportElement || elem,
+ result, point;
+
+ // Create SVG point
+ if(!root.createSVGPoint) { return FALSE; }
+ point = root.createSVGPoint();
+
+ point.x = x; point.y = y;
+ result = point.matrixTransform(mtx);
+ return [ result.x, result.y ];
+};;PLUGINS.imagemap = function(api, area, corner, adjustMethod)
+{
+ if(!area.jquery) { area = $(area); }
+
+ var shape = area.attr('shape').toLowerCase().replace('poly', 'polygon'),
+ image = $('img[usemap="#'+area.parent('map').attr('name')+'"]'),
+ coordsString = area.attr('coords'),
+ coordsArray = coordsString.split(','),
+ imageOffset, coords, i, next;
+
+ // If we can't find the image using the map...
+ if(!image.length) { return FALSE; }
+
+ // Pass coordinates string if polygon
+ if(shape === 'polygon') {
+ result = PLUGINS.polys.polygon(coordsArray, corner);
+ }
+
+ // Otherwise parse the coordinates and pass them as arguments
+ else if(PLUGINS.polys[shape]) {
+ for(i = -1, len = coordsArray.length, coords = []; ++i < len;) {
+ coords.push( parseInt(coordsArray[i], 10) );
+ }
+
+ result = PLUGINS.polys[shape].apply(
+ this, coords.concat(corner)
+ );
+ }
+
+ // If no shapre calculation method was found, return false
+ else { return FALSE; }
+
+ // Make sure we account for padding and borders on the image
+ imageOffset = image.offset();
+ imageOffset.left += Math.ceil((image.outerWidth(FALSE) - image.width()) / 2);
+ imageOffset.top += Math.ceil((image.outerHeight(FALSE) - image.height()) / 2);
+
// Add image position to offset coordinates
result.position.left += imageOffset.left;
result.position.top += imageOffset.top;
return result;
-};
+};;var IE6,
-
/*
* BGIFrame adaption (http://plugins.jquery.com/project/bgiframe)
* Special thanks to Brandon Aaron
*/
-function BGIFrame(api)
-{
- var self = this,
- elems = api.elements,
- tooltip = elems.tooltip,
- namespace = '.bgiframe-' + api.id;
+BGIFRAME = '<iframe class="qtip-bgiframe" frameborder="0" tabindex="-1" src="javascript:\'\';" ' +
+ ' style="display:block; position:absolute; z-index:-1; filter:alpha(opacity=0); ' +
+ '-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";"></iframe>';
- $.extend(self, {
- init: function()
- {
- // Create the BGIFrame element
- elems.bgiframe = $('<iframe class="ui-tooltip-bgiframe" frameborder="0" tabindex="-1" src="javascript:\'\';" ' +
- ' style="display:block; position:absolute; z-index:-1; filter:alpha(opacity=0); ' +
- '-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";"></iframe>');
+function Ie6(api, qtip) {
+ this._ns = 'ie6';
+ this.init( (this.qtip = api) );
+}
- // Append the new element to the tooltip
- elems.bgiframe.appendTo(tooltip);
+$.extend(Ie6.prototype, {
+ _scroll : function() {
+ var overlay = this.qtip.elements.overlay;
+ overlay && (overlay[0].style.top = $(window).scrollTop() + 'px');
+ },
+ init: function(qtip) {
+ var tooltip = qtip.tooltip,
+ scroll;
+
+ // Create the BGIFrame element if needed
+ if($('select, object').length < 1) {
+ this.bgiframe = qtip.elements.bgiframe = $(BGIFRAME).appendTo(tooltip);
+
// Update BGIFrame on tooltip move
- tooltip.bind('tooltipmove'+namespace, self.adjust);
- },
+ qtip._bind(tooltip, 'tooltipmove', this.adjustBGIFrame, this._ns, this);
+ }
- adjust: function()
- {
- var dimensions = api.get('dimensions'), // Determine current tooltip dimensions
- plugin = api.plugins.tip,
- tip = elems.tip,
- tipAdjust, offset;
+ // redraw() container for width/height calculations
+ this.redrawContainer = $('<div/>', { id: NAMESPACE+'-rcontainer' })
+ .appendTo(document.body);
- // Adjust border offset
- offset = parseInt(tooltip.css('border-left-width'), 10) || 0;
- offset = { left: -offset, top: -offset };
+ // Fixup modal plugin if present too
+ if( qtip.elements.overlay && qtip.elements.overlay.addClass('qtipmodal-ie6fix') ) {
+ qtip._bind(window, ['scroll', 'resize'], this._scroll, this._ns, this);
+ qtip._bind(tooltip, ['tooltipshow'], this._scroll, this._ns, this);
+ }
- // Adjust for tips plugin
- if(plugin && tip) {
- tipAdjust = (plugin.corner.precedance === 'x') ? ['width', 'left'] : ['height', 'top'];
- offset[ tipAdjust[1] ] -= tip[ tipAdjust[0] ]();
- }
+ // Set dimensions
+ this.redraw();
+ },
- // Update bgiframe
- elems.bgiframe.css(offset).css(dimensions);
- },
+ adjustBGIFrame: function() {
+ var tooltip = this.qtip.tooltip,
+ dimensions = {
+ height: tooltip.outerHeight(FALSE),
+ width: tooltip.outerWidth(FALSE)
+ },
+ plugin = this.qtip.plugins.tip,
+ tip = this.qtip.elements.tip,
+ tipAdjust, offset;
- destroy: function()
- {
- // Remove iframe
- elems.bgiframe.remove();
+ // Adjust border offset
+ offset = parseInt(tooltip.css('borderLeftWidth'), 10) || 0;
+ offset = { left: -offset, top: -offset };
- // Remove bound events
- tooltip.unbind(namespace);
+ // Adjust for tips plugin
+ if(plugin && tip) {
+ tipAdjust = (plugin.corner.precedance === 'x') ? [WIDTH, LEFT] : [HEIGHT, TOP];
+ offset[ tipAdjust[1] ] -= tip[ tipAdjust[0] ]();
}
- });
- self.init();
-}
+ // Update bgiframe
+ this.bgiframe.css(offset).css(dimensions);
+ },
-PLUGINS.bgiframe = function(api)
-{
- var browser = $.browser,
- self = api.plugins.bgiframe;
-
- // Proceed only if the browser is IE6 and offending elements are present
- if($('select, object').length < 1 || !(browser.msie && (''+browser.version).charAt(0) === '6')) {
- return FALSE;
+ // Max/min width simulator function
+ redraw: function() {
+ if(this.qtip.rendered < 1 || this.drawing) { return self; }
+
+ var tooltip = this.qtip.tooltip,
+ style = this.qtip.options.style,
+ container = this.qtip.options.position.container,
+ perc, width, max, min;
+
+ // Set drawing flag
+ this.qtip.drawing = 1;
+
+ // If tooltip has a set height/width, just set it... like a boss!
+ if(style.height) { tooltip.css(HEIGHT, style.height); }
+ if(style.width) { tooltip.css(WIDTH, style.width); }
+
+ // Simulate max/min width if not set width present...
+ else {
+ // Reset width and add fluid class
+ tooltip.css(WIDTH, '').appendTo(this.redrawContainer);
+
+ // Grab our tooltip width (add 1 if odd so we don't get wrapping problems.. huzzah!)
+ width = tooltip.width();
+ if(width % 2 < 1) { width += 1; }
+
+ // Grab our max/min properties
+ max = tooltip.css('maxWidth') || '';
+ min = tooltip.css('minWidth') || '';
+
+ // Parse into proper pixel values
+ perc = (max + min).indexOf('%') > -1 ? container.width() / 100 : 0;
+ max = ((max.indexOf('%') > -1 ? perc : 1) * parseInt(max, 10)) || width;
+ min = ((min.indexOf('%') > -1 ? perc : 1) * parseInt(min, 10)) || 0;
+
+ // Determine new dimension size based on max/min/current values
+ width = max + min ? Math.min(Math.max(width, min), max) : width;
+
+ // Set the newly calculated width and remvoe fluid class
+ tooltip.css(WIDTH, Math.round(width)).appendTo(container);
+ }
+
+ // Set drawing flag
+ this.drawing = 0;
+
+ return self;
+ },
+
+ destroy: function() {
+ // Remove iframe
+ this.bgiframe && this.bgiframe.remove();
+
+ // Remove bound events
+ this.qtip._unbind([window, this.qtip.tooltip], this._ns);
}
+});
- return 'object' === typeof self ? self : (api.plugins.bgiframe = new BGIFrame(api));
+IE6 = PLUGINS.ie6 = function(api) {
+ // Proceed only if the browser is IE6
+ return BROWSER.ie === 6 ? new Ie6(api) : FALSE;
};
-// Plugin needs to be initialized on render
-PLUGINS.bgiframe.initialize = 'render';
+IE6.initialize = 'render';
+CHECKS.ie6 = {
+ '^content|style$': function() {
+ this.redraw();
+ }
+};;}));
+}( window, document ));
-}));
-}( window, document ));
\ No newline at end of file
+