From 01d48661816c7336041f2018e4cbf660476ad19e Mon Sep 17 00:00:00 2001 From: vyshane Date: Thu, 8 Feb 2007 05:19:36 +0000 Subject: [PATCH] Updated YUI library to 0.12.2 --- lib/yui/README.txt | 1 + lib/yui/animation/README | 78 +- lib/yui/animation/animation-debug.js | 2621 ++--- lib/yui/animation/animation-min.js | 123 +- lib/yui/animation/animation.js | 2613 ++--- lib/yui/autocomplete/README | 136 +- lib/yui/autocomplete/autocomplete-debug.js | 2191 ++-- lib/yui/autocomplete/autocomplete-min.js | 359 +- lib/yui/autocomplete/autocomplete.js | 2149 ++-- lib/yui/calendar/README | 150 +- lib/yui/calendar/assets/calendar.css | 382 +- lib/yui/calendar/calendar-debug.js | 8565 ++++++++------- lib/yui/calendar/calendar-min.js | 218 +- lib/yui/calendar/calendar.js | 8487 ++++++++------- lib/yui/connection/README | 320 +- lib/yui/connection/connection-debug.js | 1958 ++-- lib/yui/connection/connection-min.js | 201 +- lib/yui/connection/connection.js | 1923 ++-- lib/yui/container/README | 217 +- lib/yui/container/assets/container.css | 422 +- lib/yui/container/container-debug.js | 9343 +++++++++-------- lib/yui/container/container-min.js | 302 +- lib/yui/container/container.js | 9262 ++++++++-------- lib/yui/container/container_core-debug.js | 5883 ++++++----- lib/yui/container/container_core-min.js | 205 +- lib/yui/container/container_core.js | 5830 +++++----- lib/yui/dom/README | 147 +- lib/yui/dom/dom-debug.js | 1855 ++-- lib/yui/dom/dom-min.js | 110 +- lib/yui/dom/dom.js | 1785 ++-- lib/yui/dragdrop/README | 216 +- lib/yui/dragdrop/dragdrop-debug.js | 6111 +++++------ lib/yui/dragdrop/dragdrop-min.js | 179 +- lib/yui/dragdrop/dragdrop.js | 5896 +++++------ lib/yui/event/README | 265 +- lib/yui/event/event-debug.js | 3592 +++---- lib/yui/event/event-min.js | 129 +- lib/yui/event/event.js | 3542 +++---- lib/yui/fonts/README | 26 +- lib/yui/fonts/fonts-min.css | 2 +- lib/yui/fonts/fonts.css | 54 +- lib/yui/grids/README | 86 +- lib/yui/grids/grids-min.css | 1 - lib/yui/grids/grids.css | 250 +- lib/yui/logger/README | 82 +- lib/yui/logger/assets/logger.css | 46 +- lib/yui/logger/logger-debug.js | 3127 +++--- lib/yui/logger/logger-min.js | 118 +- lib/yui/logger/logger.js | 3127 +++--- lib/yui/menu/README | 498 +- lib/yui/menu/assets/menu.css | 592 +- lib/yui/menu/menu-debug.js | 8551 ++++++++------- lib/yui/menu/menu-min.js | 432 +- lib/yui/menu/menu.js | 8463 ++++++++------- lib/yui/reset-fonts-grids/README | 32 +- .../reset-fonts-grids/reset-fonts-grids.css | 5 +- lib/yui/reset/README | 40 +- lib/yui/reset/reset-min.css | 2 +- lib/yui/reset/reset.css | 22 +- lib/yui/slider/README | 122 +- lib/yui/slider/slider-debug.js | 2505 ++--- lib/yui/slider/slider-min.js | 63 +- lib/yui/slider/slider.js | 2416 ++--- lib/yui/tabview/README | 27 +- lib/yui/tabview/assets/border_tabs.css | 94 +- lib/yui/tabview/assets/tabs.css | 66 - lib/yui/tabview/tabview-debug.js | 3917 +++---- lib/yui/tabview/tabview-min.js | 113 +- lib/yui/tabview/tabview.js | 3879 +++---- lib/yui/treeview/README | 254 +- lib/yui/treeview/assets/tree.css | 201 +- lib/yui/treeview/treeview-debug.js | 4556 ++++---- lib/yui/treeview/treeview-min.js | 135 +- lib/yui/treeview/treeview.js | 4463 ++++---- lib/yui/utilities/README | 59 +- lib/yui/utilities/utilities.js | 734 +- lib/yui/yahoo-dom-event/README | 62 +- lib/yui/yahoo-dom-event/yahoo-dom-event.js | 242 +- lib/yui/yahoo/README | 85 +- lib/yui/yahoo/yahoo-debug.js | 288 +- lib/yui/yahoo/yahoo-min.js | 15 +- lib/yui/yahoo/yahoo.js | 287 +- 82 files changed, 69138 insertions(+), 68767 deletions(-) delete mode 100755 lib/yui/tabview/assets/tabs.css diff --git a/lib/yui/README.txt b/lib/yui/README.txt index 10db7aa9d0..cf4952ba59 100644 --- a/lib/yui/README.txt +++ b/lib/yui/README.txt @@ -8,3 +8,4 @@ from: Added to Moodle 13 July 2006 Updated to YUI 0.12.0, 23 November 2006 Updated to YUI 0.12.1, 8 January 2007 +Updated to YUI 0.12.2, 8 Febuary 2007 \ No newline at end of file diff --git a/lib/yui/animation/README b/lib/yui/animation/README index f79c1c30c6..d6ea69a4be 100755 --- a/lib/yui/animation/README +++ b/lib/yui/animation/README @@ -1,37 +1,41 @@ -Animation Release Notes - -*** version 0.12.1 *** -* minified version no longer strips line breaks - -*** version 0.12.0 *** - -* added boolean finish argument to Anim.stop() - -*** version 0.11.3 *** - -* no changes - -*** version 0.11.1 *** - -* changed "prototype" shorthand to "proto" (workaround firefox < 1.5 scoping -bug) - -*** version 0.11.0 *** - -* ColorAnim subclass added -* Motion and Scroll now inherit from ColorAnim -* getDefaultUnit method added -* defaultUnit and defaultUnits deprecated -* getDefault and setDefault methods deprecated - -*** version 0.10.0 *** - -* Scroll now handles relative ("by") animation correctly - -* Now converts "auto" values of "from" to appropriate initial values - -*** version 0.9.0 *** - -* Initial release - - +Animation Release Notes + +*** version 0.12.2 *** + +* raised AnimMgr.fps to 1000 + +*** version 0.12.1 *** +* minified version no longer strips line breaks + +*** version 0.12.0 *** + +* added boolean finish argument to Anim.stop() + +*** version 0.11.3 *** + +* no changes + +*** version 0.11.1 *** + +* changed "prototype" shorthand to "proto" (workaround firefox < 1.5 scoping +bug) + +*** version 0.11.0 *** + +* ColorAnim subclass added +* Motion and Scroll now inherit from ColorAnim +* getDefaultUnit method added +* defaultUnit and defaultUnits deprecated +* getDefault and setDefault methods deprecated + +*** version 0.10.0 *** + +* Scroll now handles relative ("by") animation correctly + +* Now converts "auto" values of "from" to appropriate initial values + +*** version 0.9.0 *** + +* Initial release + + diff --git a/lib/yui/animation/animation-debug.js b/lib/yui/animation/animation-debug.js index 915941f403..7745b235b7 100755 --- a/lib/yui/animation/animation-debug.js +++ b/lib/yui/animation/animation-debug.js @@ -1,1276 +1,1345 @@ -/* -Copyright (c) 2006, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version: 0.12.1 -*/ - -/** - * The animation module provides allows effects to be added to HTMLElements. - * @module animation - */ - -/** - * - * Base animation class that provides the interface for building animated effects. - *

Usage: var myAnim = new YAHOO.util.Anim(el, { width: { from: 10, to: 100 } }, 1, YAHOO.util.Easing.easeOut);

- * @class Anim - * @namespace YAHOO.util - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @constructor - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - -YAHOO.util.Anim = function(el, attributes, duration, method) { - if (el) { - this.init(el, attributes, duration, method); - } -}; - -YAHOO.util.Anim.prototype = { - /** - * Provides a readable name for the Anim instance. - * @method toString - * @return {String} - */ - toString: function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Anim " + id); - }, - - patterns: { // cached for performance - noNegatives: /width|height|opacity|padding/i, // keep at zero or above - offsetAttribute: /^((width|height)|(top|left))$/, // use offsetValue as default - defaultUnit: /width|height|top$|bottom$|left$|right$/i, // use 'px' by default - offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i // IE may return these, so convert these to offset - }, - - /** - * Returns the value computed by the animation's "method". - * @method doMethod - * @param {String} attr The name of the attribute. - * @param {Number} start The value this attribute should start from for this animation. - * @param {Number} end The value this attribute should end at for this animation. - * @return {Number} The Value to be applied to the attribute. - */ - doMethod: function(attr, start, end) { - return this.method(this.currentFrame, start, end - start, this.totalFrames); - }, - - /** - * Applies a value to an attribute. - * @method setAttribute - * @param {String} attr The name of the attribute. - * @param {Number} val The value to be applied to the attribute. - * @param {String} unit The unit ('px', '%', etc.) of the value. - */ - setAttribute: function(attr, val, unit) { - if ( this.patterns.noNegatives.test(attr) ) { - val = (val > 0) ? val : 0; - } - - YAHOO.util.Dom.setStyle(this.getEl(), attr, val + unit); - }, - - /** - * Returns current value of the attribute. - * @method getAttribute - * @param {String} attr The name of the attribute. - * @return {Number} val The current value of the attribute. - */ - getAttribute: function(attr) { - var el = this.getEl(); - var val = YAHOO.util.Dom.getStyle(el, attr); - - if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) { - return parseFloat(val); - } - - var a = this.patterns.offsetAttribute.exec(attr) || []; - var pos = !!( a[3] ); // top or left - var box = !!( a[2] ); // width or height - - // use offsets for width/height and abs pos top/left - if ( box || (YAHOO.util.Dom.getStyle(el, 'position') == 'absolute' && pos) ) { - val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)]; - } else { // default to zero for other 'auto' - val = 0; - } - - return val; - }, - - /** - * Returns the unit to use when none is supplied. - * @method getDefaultUnit - * @param {attr} attr The name of the attribute. - * @return {String} The default unit to be used. - */ - getDefaultUnit: function(attr) { - if ( this.patterns.defaultUnit.test(attr) ) { - return 'px'; - } - - return ''; - }, - - /** - * Sets the actual values to be used during the animation. - * @method setRuntimeAttribute - * Should only be needed for subclass use. - * @param {Object} attr The attribute object - * @private - */ - setRuntimeAttribute: function(attr) { - var start; - var end; - var attributes = this.attributes; - - this.runtimeAttributes[attr] = {}; - - var isset = function(prop) { - return (typeof prop !== 'undefined'); - }; - - if ( !isset(attributes[attr]['to']) && !isset(attributes[attr]['by']) ) { - return false; // note return; nothing to animate to - } - - start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr); - - // To beats by, per SMIL 2.1 spec - if ( isset(attributes[attr]['to']) ) { - end = attributes[attr]['to']; - } else if ( isset(attributes[attr]['by']) ) { - if (start.constructor == Array) { - end = []; - for (var i = 0, len = start.length; i < len; ++i) { - end[i] = start[i] + attributes[attr]['by'][i]; - } - } else { - end = start + attributes[attr]['by']; - } - } - - this.runtimeAttributes[attr].start = start; - this.runtimeAttributes[attr].end = end; - - // set units if needed - this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr); - }, - - /** - * Constructor for Anim instance. - * @method init - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - init: function(el, attributes, duration, method) { - /** - * Whether or not the animation is running. - * @property isAnimated - * @private - * @type Boolean - */ - var isAnimated = false; - - /** - * A Date object that is created when the animation begins. - * @property startTime - * @private - * @type Date - */ - var startTime = null; - - /** - * The number of frames this animation was able to execute. - * @property actualFrames - * @private - * @type Int - */ - var actualFrames = 0; - - /** - * The element to be animated. - * @property el - * @private - * @type HTMLElement - */ - el = YAHOO.util.Dom.get(el); - - /** - * The collection of attributes to be animated. - * Each attribute must have at least a "to" or "by" defined in order to animate. - * If "to" is supplied, the animation will end with the attribute at that value. - * If "by" is supplied, the animation will end at that value plus its starting value. - * If both are supplied, "to" is used, and "by" is ignored. - * Optional additional member include "from" (the value the attribute should start animating from, defaults to current value), and "unit" (the units to apply to the values). - * @property attributes - * @type Object - */ - this.attributes = attributes || {}; - - /** - * The length of the animation. Defaults to "1" (second). - * @property duration - * @type Number - */ - this.duration = duration || 1; - - /** - * The method that will provide values to the attribute(s) during the animation. - * Defaults to "YAHOO.util.Easing.easeNone". - * @property method - * @type Function - */ - this.method = method || YAHOO.util.Easing.easeNone; - - /** - * Whether or not the duration should be treated as seconds. - * Defaults to true. - * @property useSeconds - * @type Boolean - */ - this.useSeconds = true; // default to seconds - - /** - * The location of the current animation on the timeline. - * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. - * @property currentFrame - * @type Int - */ - this.currentFrame = 0; - - /** - * The total number of frames to be executed. - * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. - * @property totalFrames - * @type Int - */ - this.totalFrames = YAHOO.util.AnimMgr.fps; - - - /** - * Returns a reference to the animated element. - * @method getEl - * @return {HTMLElement} - */ - this.getEl = function() { return el; }; - - /** - * Checks whether the element is currently animated. - * @method isAnimated - * @return {Boolean} current value of isAnimated. - */ - this.isAnimated = function() { - return isAnimated; - }; - - /** - * Returns the animation start time. - * @method getStartTime - * @return {Date} current value of startTime. - */ - this.getStartTime = function() { - return startTime; - }; - - this.runtimeAttributes = {}; - - var logger = {}; - logger.log = function() {YAHOO.log.apply(window, arguments)}; - - logger.log('creating new instance of ' + this); - - /** - * Starts the animation by registering it with the animation manager. - * @method animate - */ - this.animate = function() { - if ( this.isAnimated() ) { return false; } - - this.currentFrame = 0; - - this.totalFrames = ( this.useSeconds ) ? Math.ceil(YAHOO.util.AnimMgr.fps * this.duration) : this.duration; - - YAHOO.util.AnimMgr.registerElement(this); - }; - - /** - * Stops the animation. Normally called by AnimMgr when animation completes. - * @method stop - * @param {Boolean} finish (optional) If true, animation will jump to final frame. - */ - this.stop = function(finish) { - if (finish) { - this.currentFrame = this.totalFrames; - this._onTween.fire(); - } - YAHOO.util.AnimMgr.stop(this); - }; - - var onStart = function() { - this.onStart.fire(); - - this.runtimeAttributes = {}; - for (var attr in this.attributes) { - this.setRuntimeAttribute(attr); - } - - isAnimated = true; - actualFrames = 0; - startTime = new Date(); - }; - - /** - * Feeds the starting and ending values for each animated attribute to doMethod once per frame, then applies the resulting value to the attribute(s). - * @private - */ - - var onTween = function() { - var data = { - duration: new Date() - this.getStartTime(), - currentFrame: this.currentFrame - }; - - data.toString = function() { - return ( - 'duration: ' + data.duration + - ', currentFrame: ' + data.currentFrame - ); - }; - - this.onTween.fire(data); - - var runtimeAttributes = this.runtimeAttributes; - - for (var attr in runtimeAttributes) { - this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); - } - - actualFrames += 1; - }; - - var onComplete = function() { - var actual_duration = (new Date() - startTime) / 1000 ; - - var data = { - duration: actual_duration, - frames: actualFrames, - fps: actualFrames / actual_duration - }; - - data.toString = function() { - return ( - 'duration: ' + data.duration + - ', frames: ' + data.frames + - ', fps: ' + data.fps - ); - }; - - isAnimated = false; - actualFrames = 0; - this.onComplete.fire(data); - }; - - /** - * Custom event that fires after onStart, useful in subclassing - * @private - */ - this._onStart = new YAHOO.util.CustomEvent('_start', this, true); - - /** - * Custom event that fires when animation begins - * Listen via subscribe method (e.g. myAnim.onStart.subscribe(someFunction) - * @event onStart - */ - this.onStart = new YAHOO.util.CustomEvent('start', this); - - /** - * Custom event that fires between each frame - * Listen via subscribe method (e.g. myAnim.onTween.subscribe(someFunction) - * @event onTween - */ - this.onTween = new YAHOO.util.CustomEvent('tween', this); - - /** - * Custom event that fires after onTween - * @private - */ - this._onTween = new YAHOO.util.CustomEvent('_tween', this, true); - - /** - * Custom event that fires when animation ends - * Listen via subscribe method (e.g. myAnim.onComplete.subscribe(someFunction) - * @event onComplete - */ - this.onComplete = new YAHOO.util.CustomEvent('complete', this); - /** - * Custom event that fires after onComplete - * @private - */ - this._onComplete = new YAHOO.util.CustomEvent('_complete', this, true); - - this._onStart.subscribe(onStart); - this._onTween.subscribe(onTween); - this._onComplete.subscribe(onComplete); - } -}; - -/** - * Handles animation queueing and threading. - * Used by Anim and subclasses. - * @class AnimMgr - * @namespace YAHOO.util - */ -YAHOO.util.AnimMgr = new function() { - /** - * Reference to the animation Interval. - * @property thread - * @private - * @type Int - */ - var thread = null; - - /** - * The current queue of registered animation objects. - * @property queue - * @private - * @type Array - */ - var queue = []; - - /** - * The number of active animations. - * @property tweenCount - * @private - * @type Int - */ - var tweenCount = 0; - - /** - * Base frame rate (frames per second). - * Arbitrarily high for better x-browser calibration (slower browsers drop more frames). - * @property fps - * @type Int - * - */ - this.fps = 200; - - /** - * Interval delay in milliseconds, defaults to fastest possible. - * @property delay - * @type Int - * - */ - this.delay = 1; - - /** - * Adds an animation instance to the animation queue. - * All animation instances must be registered in order to animate. - * @method registerElement - * @param {object} tween The Anim instance to be be registered - */ - this.registerElement = function(tween) { - queue[queue.length] = tween; - tweenCount += 1; - tween._onStart.fire(); - this.start(); - }; - - /** - * removes an animation instance from the animation queue. - * All animation instances must be registered in order to animate. - * @method unRegister - * @param {object} tween The Anim instance to be be registered - * @param {Int} index The index of the Anim instance - * @private - */ - this.unRegister = function(tween, index) { - tween._onComplete.fire(); - index = index || getIndex(tween); - if (index != -1) { queue.splice(index, 1); } - - tweenCount -= 1; - if (tweenCount <= 0) { this.stop(); } - }; - - /** - * Starts the animation thread. - * Only one thread can run at a time. - * @method start - */ - this.start = function() { - if (thread === null) { thread = setInterval(this.run, this.delay); } - }; - - /** - * Stops the animation thread or a specific animation instance. - * @method stop - * @param {object} tween A specific Anim instance to stop (optional) - * If no instance given, Manager stops thread and all animations. - */ - this.stop = function(tween) { - if (!tween) { - clearInterval(thread); - for (var i = 0, len = queue.length; i < len; ++i) { - if (queue[i].isAnimated()) { - this.unRegister(tween, i); - } - } - queue = []; - thread = null; - tweenCount = 0; - } - else { - this.unRegister(tween); - } - }; - - /** - * Called per Interval to handle each animation frame. - * @method run - */ - this.run = function() { - for (var i = 0, len = queue.length; i < len; ++i) { - var tween = queue[i]; - if ( !tween || !tween.isAnimated() ) { continue; } - - if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null) - { - tween.currentFrame += 1; - - if (tween.useSeconds) { - correctFrame(tween); - } - tween._onTween.fire(); - } - else { YAHOO.util.AnimMgr.stop(tween, i); } - } - }; - - var getIndex = function(anim) { - for (var i = 0, len = queue.length; i < len; ++i) { - if (queue[i] == anim) { - return i; // note return; - } - } - return -1; - }; - - /** - * On the fly frame correction to keep animation on time. - * @method correctFrame - * @private - * @param {Object} tween The Anim instance being corrected. - */ - var correctFrame = function(tween) { - var frames = tween.totalFrames; - var frame = tween.currentFrame; - var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); - var elapsed = (new Date() - tween.getStartTime()); - var tweak = 0; - - if (elapsed < tween.duration * 1000) { // check if falling behind - tweak = Math.round((elapsed / expected - 1) * tween.currentFrame); - } else { // went over duration, so jump to end - tweak = frames - (frame + 1); - } - if (tweak > 0 && isFinite(tweak)) { // adjust if needed - if (tween.currentFrame + tweak >= frames) {// dont go past last frame - tweak = frames - (frame + 1); - } - - tween.currentFrame += tweak; - } - }; -}; -/** - * Used to calculate Bezier splines for any number of control points. - * @class Bezier - * @namespace YAHOO.util - * - */ -YAHOO.util.Bezier = new function() -{ - /** - * Get the current position of the animated element based on t. - * Each point is an array of "x" and "y" values (0 = x, 1 = y) - * At least 2 points are required (start and end). - * First point is start. Last point is end. - * Additional control points are optional. - * @method getPosition - * @param {Array} points An array containing Bezier points - * @param {Number} t A number between 0 and 1 which is the basis for determining current position - * @return {Array} An array containing int x and y member data - */ - this.getPosition = function(points, t) - { - var n = points.length; - var tmp = []; - - for (var i = 0; i < n; ++i){ - tmp[i] = [points[i][0], points[i][1]]; // save input - } - - for (var j = 1; j < n; ++j) { - for (i = 0; i < n - j; ++i) { - tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; - tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; - } - } - - return [ tmp[0][0], tmp[0][1] ]; - - }; -}; -(function() { -/** - * Anim subclass for color transitions. - *

Usage: var myAnim = new Y.ColorAnim(el, { backgroundColor: { from: '#FF0000', to: '#FFFFFF' } }, 1, Y.Easing.easeOut); Color values can be specified with either 112233, #112233, - * [255,255,255], or rgb(255,255,255)

- * @class ColorAnim - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @constructor - * @extends YAHOO.util.Anim - * @param {HTMLElement | String} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - YAHOO.util.ColorAnim = function(el, attributes, duration, method) { - YAHOO.util.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); - }; - - YAHOO.extend(YAHOO.util.ColorAnim, YAHOO.util.Anim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.ColorAnim.superclass; - var proto = Y.ColorAnim.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("ColorAnim " + id); - }; - - proto.patterns.color = /color$/i; - proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i; - proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i; - proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i; - proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/; // need rgba for safari - - /** - * Attempts to parse the given string and return a 3-tuple. - * @method parseColor - * @param {String} s The string to parse. - * @return {Array} The 3-tuple of rgb values. - */ - proto.parseColor = function(s) { - if (s.length == 3) { return s; } - - var c = this.patterns.hex.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ]; - } - - c = this.patterns.rgb.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ]; - } - - c = this.patterns.hex3.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ]; - } - - return null; - }; - - proto.getAttribute = function(attr) { - var el = this.getEl(); - if ( this.patterns.color.test(attr) ) { - var val = YAHOO.util.Dom.getStyle(el, attr); - - if (this.patterns.transparent.test(val)) { // bgcolor default - var parent = el.parentNode; // try and get from an ancestor - val = Y.Dom.getStyle(parent, attr); - - while (parent && this.patterns.transparent.test(val)) { - parent = parent.parentNode; - val = Y.Dom.getStyle(parent, attr); - if (parent.tagName.toUpperCase() == 'HTML') { - val = '#fff'; - } - } - } - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.doMethod = function(attr, start, end) { - var val; - - if ( this.patterns.color.test(attr) ) { - val = []; - for (var i = 0, len = start.length; i < len; ++i) { - val[i] = superclass.doMethod.call(this, attr, start[i], end[i]); - } - - val = 'rgb('+Math.floor(val[0])+','+Math.floor(val[1])+','+Math.floor(val[2])+')'; - } - else { - val = superclass.doMethod.call(this, attr, start, end); - } - - return val; - }; - - proto.setRuntimeAttribute = function(attr) { - superclass.setRuntimeAttribute.call(this, attr); - - if ( this.patterns.color.test(attr) ) { - var attributes = this.attributes; - var start = this.parseColor(this.runtimeAttributes[attr].start); - var end = this.parseColor(this.runtimeAttributes[attr].end); - // fix colors if going "by" - if ( typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined' ) { - end = this.parseColor(attributes[attr].by); - - for (var i = 0, len = start.length; i < len; ++i) { - end[i] = start[i] + end[i]; - } - } - - this.runtimeAttributes[attr].start = start; - this.runtimeAttributes[attr].end = end; - } - }; -})();/* -TERMS OF USE - EASING EQUATIONS -Open source under the BSD License. -Copyright 2001 Robert Penner All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * Singleton that determines how an animation proceeds from start to end. - * @class Easing - * @namespace YAHOO.util -*/ - -YAHOO.util.Easing = { - - /** - * Uniform speed between points. - * @method easeNone - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeNone: function (t, b, c, d) { - return c*t/d + b; - }, - - /** - * Begins slowly and accelerates towards end. (quadratic) - * @method easeIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeIn: function (t, b, c, d) { - return c*(t/=d)*t + b; - }, - - /** - * Begins quickly and decelerates towards end. (quadratic) - * @method easeOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeOut: function (t, b, c, d) { - return -c *(t/=d)*(t-2) + b; - }, - - /** - * Begins slowly and decelerates towards end. (quadratic) - * @method easeBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeBoth: function (t, b, c, d) { - if ((t/=d/2) < 1) return c/2*t*t + b; - return -c/2 * ((--t)*(t-2) - 1) + b; - }, - - /** - * Begins slowly and accelerates towards end. (quartic) - * @method easeInStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeInStrong: function (t, b, c, d) { - return c*(t/=d)*t*t*t + b; - }, - - /** - * Begins quickly and decelerates towards end. (quartic) - * @method easeOutStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeOutStrong: function (t, b, c, d) { - return -c * ((t=t/d-1)*t*t*t - 1) + b; - }, - - /** - * Begins slowly and decelerates towards end. (quartic) - * @method easeBothStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeBothStrong: function (t, b, c, d) { - if ((t/=d/2) < 1) return c/2*t*t*t*t + b; - return -c/2 * ((t-=2)*t*t*t - 2) + b; - }, - - /** - * Snap in elastic effect. - * @method elasticIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - - elasticIn: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; - }, - - /** - * Snap out elastic effect. - * @method elasticOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - elasticOut: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; - }, - - /** - * Snap both elastic effect. - * @method elasticBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - elasticBoth: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; - return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; - }, - - - /** - * Backtracks slightly, then reverses direction and moves to end. - * @method backIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backIn: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - return c*(t/=d)*t*((s+1)*t - s) + b; - }, - - /** - * Overshoots end, then reverses and comes back to end. - * @method backOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backOut: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; - }, - - /** - * Backtracks slightly, then reverses direction, overshoots end, - * then reverses and comes back to end. - * @method backBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backBoth: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; - return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; - }, - - /** - * Bounce off of start. - * @method bounceIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceIn: function (t, b, c, d) { - return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; - }, - - /** - * Bounces off end. - * @method bounceOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceOut: function (t, b, c, d) { - if ((t/=d) < (1/2.75)) { - return c*(7.5625*t*t) + b; - } else if (t < (2/2.75)) { - return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; - } else if (t < (2.5/2.75)) { - return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; - } else { - return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; - } - }, - - /** - * Bounces off start and end. - * @method bounceBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceBoth: function (t, b, c, d) { - if (t < d/2) return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b; - return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; - } -}; - -(function() { -/** - * Anim subclass for moving elements along a path defined by the "points" - * member of "attributes". All "points" are arrays with x, y coordinates. - *

Usage: var myAnim = new YAHOO.util.Motion(el, { points: { to: [800, 800] } }, 1, YAHOO.util.Easing.easeOut);

- * @class Motion - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @constructor - * @extends YAHOO.util.Anim - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - YAHOO.util.Motion = function(el, attributes, duration, method) { - if (el) { // dont break existing subclasses not using YAHOO.extend - YAHOO.util.Motion.superclass.constructor.call(this, el, attributes, duration, method); - } - }; - - YAHOO.extend(YAHOO.util.Motion, YAHOO.util.ColorAnim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.Motion.superclass; - var proto = Y.Motion.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Motion " + id); - }; - - proto.patterns.points = /^points$/i; - - proto.setAttribute = function(attr, val, unit) { - if ( this.patterns.points.test(attr) ) { - unit = unit || 'px'; - superclass.setAttribute.call(this, 'left', val[0], unit); - superclass.setAttribute.call(this, 'top', val[1], unit); - } else { - superclass.setAttribute.call(this, attr, val, unit); - } - }; - - proto.getAttribute = function(attr) { - if ( this.patterns.points.test(attr) ) { - var val = [ - superclass.getAttribute.call(this, 'left'), - superclass.getAttribute.call(this, 'top') - ]; - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.doMethod = function(attr, start, end) { - var val = null; - - if ( this.patterns.points.test(attr) ) { - var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100; - val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t); - } else { - val = superclass.doMethod.call(this, attr, start, end); - } - return val; - }; - - proto.setRuntimeAttribute = function(attr) { - if ( this.patterns.points.test(attr) ) { - var el = this.getEl(); - var attributes = this.attributes; - var start; - var control = attributes['points']['control'] || []; - var end; - var i, len; - - if (control.length > 0 && !(control[0] instanceof Array) ) { // could be single point or array of points - control = [control]; - } else { // break reference to attributes.points.control - var tmp = []; - for (i = 0, len = control.length; i< len; ++i) { - tmp[i] = control[i]; - } - control = tmp; - } - - if (Y.Dom.getStyle(el, 'position') == 'static') { // default to relative - Y.Dom.setStyle(el, 'position', 'relative'); - } - - if ( isset(attributes['points']['from']) ) { - Y.Dom.setXY(el, attributes['points']['from']); // set position to from point - } - else { Y.Dom.setXY( el, Y.Dom.getXY(el) ); } // set it to current position - - start = this.getAttribute('points'); // get actual top & left - - // TO beats BY, per SMIL 2.1 spec - if ( isset(attributes['points']['to']) ) { - end = translateValues.call(this, attributes['points']['to'], start); - - var pageXY = Y.Dom.getXY(this.getEl()); - for (i = 0, len = control.length; i < len; ++i) { - control[i] = translateValues.call(this, control[i], start); - } - - - } else if ( isset(attributes['points']['by']) ) { - end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ]; - - for (i = 0, len = control.length; i < len; ++i) { - control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ]; - } - } - - this.runtimeAttributes[attr] = [start]; - - if (control.length > 0) { - this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control); - } - - this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end; - } - else { - superclass.setRuntimeAttribute.call(this, attr); - } - }; - - var translateValues = function(val, start) { - var pageXY = Y.Dom.getXY(this.getEl()); - val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ]; - - return val; - }; - - var isset = function(prop) { - return (typeof prop !== 'undefined'); - }; -})(); -(function() { -/** - * Anim subclass for scrolling elements to a position defined by the "scroll" - * member of "attributes". All "scroll" members are arrays with x, y scroll positions. - *

Usage: var myAnim = new YAHOO.util.Scroll(el, { scroll: { to: [0, 800] } }, 1, YAHOO.util.Easing.easeOut);

- * @class Scroll - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @extends YAHOO.util.Anim - * @constructor - * @param {String or HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - YAHOO.util.Scroll = function(el, attributes, duration, method) { - if (el) { // dont break existing subclasses not using YAHOO.extend - YAHOO.util.Scroll.superclass.constructor.call(this, el, attributes, duration, method); - } - }; - - YAHOO.extend(YAHOO.util.Scroll, YAHOO.util.ColorAnim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.Scroll.superclass; - var proto = Y.Scroll.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Scroll " + id); - }; - - proto.doMethod = function(attr, start, end) { - var val = null; - - if (attr == 'scroll') { - val = [ - this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames), - this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames) - ]; - - } else { - val = superclass.doMethod.call(this, attr, start, end); - } - return val; - }; - - proto.getAttribute = function(attr) { - var val = null; - var el = this.getEl(); - - if (attr == 'scroll') { - val = [ el.scrollLeft, el.scrollTop ]; - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.setAttribute = function(attr, val, unit) { - var el = this.getEl(); - - if (attr == 'scroll') { - el.scrollLeft = val[0]; - el.scrollTop = val[1]; - } else { - superclass.setAttribute.call(this, attr, val, unit); - } - }; -})(); +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 0.12.2 +*/ +/** + * The animation module provides allows effects to be added to HTMLElements. + * @module animation + * @requires yahoo, event, dom + */ + +/** + * + * Base animation class that provides the interface for building animated effects. + *

Usage: var myAnim = new YAHOO.util.Anim(el, { width: { from: 10, to: 100 } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Anim + * @namespace YAHOO.util + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @constructor + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + +YAHOO.util.Anim = function(el, attributes, duration, method) { + if (el) { + this.init(el, attributes, duration, method); + } +}; + +YAHOO.util.Anim.prototype = { + /** + * Provides a readable name for the Anim instance. + * @method toString + * @return {String} + */ + toString: function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Anim " + id); + }, + + patterns: { // cached for performance + noNegatives: /width|height|opacity|padding/i, // keep at zero or above + offsetAttribute: /^((width|height)|(top|left))$/, // use offsetValue as default + defaultUnit: /width|height|top$|bottom$|left$|right$/i, // use 'px' by default + offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i // IE may return these, so convert these to offset + }, + + /** + * Returns the value computed by the animation's "method". + * @method doMethod + * @param {String} attr The name of the attribute. + * @param {Number} start The value this attribute should start from for this animation. + * @param {Number} end The value this attribute should end at for this animation. + * @return {Number} The Value to be applied to the attribute. + */ + doMethod: function(attr, start, end) { + return this.method(this.currentFrame, start, end - start, this.totalFrames); + }, + + /** + * Applies a value to an attribute. + * @method setAttribute + * @param {String} attr The name of the attribute. + * @param {Number} val The value to be applied to the attribute. + * @param {String} unit The unit ('px', '%', etc.) of the value. + */ + setAttribute: function(attr, val, unit) { + if ( this.patterns.noNegatives.test(attr) ) { + val = (val > 0) ? val : 0; + } + + YAHOO.util.Dom.setStyle(this.getEl(), attr, val + unit); + }, + + /** + * Returns current value of the attribute. + * @method getAttribute + * @param {String} attr The name of the attribute. + * @return {Number} val The current value of the attribute. + */ + getAttribute: function(attr) { + var el = this.getEl(); + var val = YAHOO.util.Dom.getStyle(el, attr); + + if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) { + return parseFloat(val); + } + + var a = this.patterns.offsetAttribute.exec(attr) || []; + var pos = !!( a[3] ); // top or left + var box = !!( a[2] ); // width or height + + // use offsets for width/height and abs pos top/left + if ( box || (YAHOO.util.Dom.getStyle(el, 'position') == 'absolute' && pos) ) { + val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)]; + } else { // default to zero for other 'auto' + val = 0; + } + + return val; + }, + + /** + * Returns the unit to use when none is supplied. + * @method getDefaultUnit + * @param {attr} attr The name of the attribute. + * @return {String} The default unit to be used. + */ + getDefaultUnit: function(attr) { + if ( this.patterns.defaultUnit.test(attr) ) { + return 'px'; + } + + return ''; + }, + + /** + * Sets the actual values to be used during the animation. Should only be needed for subclass use. + * @method setRuntimeAttribute + * @param {Object} attr The attribute object + * @private + */ + setRuntimeAttribute: function(attr) { + var start; + var end; + var attributes = this.attributes; + + this.runtimeAttributes[attr] = {}; + + var isset = function(prop) { + return (typeof prop !== 'undefined'); + }; + + if ( !isset(attributes[attr]['to']) && !isset(attributes[attr]['by']) ) { + return false; // note return; nothing to animate to + } + + start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr); + + // To beats by, per SMIL 2.1 spec + if ( isset(attributes[attr]['to']) ) { + end = attributes[attr]['to']; + } else if ( isset(attributes[attr]['by']) ) { + if (start.constructor == Array) { + end = []; + for (var i = 0, len = start.length; i < len; ++i) { + end[i] = start[i] + attributes[attr]['by'][i]; + } + } else { + end = start + attributes[attr]['by']; + } + } + + this.runtimeAttributes[attr].start = start; + this.runtimeAttributes[attr].end = end; + + // set units if needed + this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr); + }, + + /** + * Constructor for Anim instance. + * @method init + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + init: function(el, attributes, duration, method) { + /** + * Whether or not the animation is running. + * @property isAnimated + * @private + * @type Boolean + */ + var isAnimated = false; + + /** + * A Date object that is created when the animation begins. + * @property startTime + * @private + * @type Date + */ + var startTime = null; + + /** + * The number of frames this animation was able to execute. + * @property actualFrames + * @private + * @type Int + */ + var actualFrames = 0; + + /** + * The element to be animated. + * @property el + * @private + * @type HTMLElement + */ + el = YAHOO.util.Dom.get(el); + + /** + * The collection of attributes to be animated. + * Each attribute must have at least a "to" or "by" defined in order to animate. + * If "to" is supplied, the animation will end with the attribute at that value. + * If "by" is supplied, the animation will end at that value plus its starting value. + * If both are supplied, "to" is used, and "by" is ignored. + * Optional additional member include "from" (the value the attribute should start animating from, defaults to current value), and "unit" (the units to apply to the values). + * @property attributes + * @type Object + */ + this.attributes = attributes || {}; + + /** + * The length of the animation. Defaults to "1" (second). + * @property duration + * @type Number + */ + this.duration = duration || 1; + + /** + * The method that will provide values to the attribute(s) during the animation. + * Defaults to "YAHOO.util.Easing.easeNone". + * @property method + * @type Function + */ + this.method = method || YAHOO.util.Easing.easeNone; + + /** + * Whether or not the duration should be treated as seconds. + * Defaults to true. + * @property useSeconds + * @type Boolean + */ + this.useSeconds = true; // default to seconds + + /** + * The location of the current animation on the timeline. + * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. + * @property currentFrame + * @type Int + */ + this.currentFrame = 0; + + /** + * The total number of frames to be executed. + * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. + * @property totalFrames + * @type Int + */ + this.totalFrames = YAHOO.util.AnimMgr.fps; + + + /** + * Returns a reference to the animated element. + * @method getEl + * @return {HTMLElement} + */ + this.getEl = function() { return el; }; + + /** + * Checks whether the element is currently animated. + * @method isAnimated + * @return {Boolean} current value of isAnimated. + */ + this.isAnimated = function() { + return isAnimated; + }; + + /** + * Returns the animation start time. + * @method getStartTime + * @return {Date} current value of startTime. + */ + this.getStartTime = function() { + return startTime; + }; + + this.runtimeAttributes = {}; + + var logger = {}; + logger.log = function() {YAHOO.log.apply(window, arguments)}; + + logger.log('creating new instance of ' + this); + + /** + * Starts the animation by registering it with the animation manager. + * @method animate + */ + this.animate = function() { + if ( this.isAnimated() ) { + return false; + } + + this.currentFrame = 0; + + this.totalFrames = ( this.useSeconds ) ? Math.ceil(YAHOO.util.AnimMgr.fps * this.duration) : this.duration; + + YAHOO.util.AnimMgr.registerElement(this); + }; + + /** + * Stops the animation. Normally called by AnimMgr when animation completes. + * @method stop + * @param {Boolean} finish (optional) If true, animation will jump to final frame. + */ + this.stop = function(finish) { + if (finish) { + this.currentFrame = this.totalFrames; + this._onTween.fire(); + } + YAHOO.util.AnimMgr.stop(this); + }; + + var onStart = function() { + this.onStart.fire(); + + this.runtimeAttributes = {}; + for (var attr in this.attributes) { + this.setRuntimeAttribute(attr); + } + + isAnimated = true; + actualFrames = 0; + startTime = new Date(); + }; + + /** + * Feeds the starting and ending values for each animated attribute to doMethod once per frame, then applies the resulting value to the attribute(s). + * @private + */ + + var onTween = function() { + var data = { + duration: new Date() - this.getStartTime(), + currentFrame: this.currentFrame + }; + + data.toString = function() { + return ( + 'duration: ' + data.duration + + ', currentFrame: ' + data.currentFrame + ); + }; + + this.onTween.fire(data); + + var runtimeAttributes = this.runtimeAttributes; + + for (var attr in runtimeAttributes) { + this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); + } + + actualFrames += 1; + }; + + var onComplete = function() { + var actual_duration = (new Date() - startTime) / 1000 ; + + var data = { + duration: actual_duration, + frames: actualFrames, + fps: actualFrames / actual_duration + }; + + data.toString = function() { + return ( + 'duration: ' + data.duration + + ', frames: ' + data.frames + + ', fps: ' + data.fps + ); + }; + + isAnimated = false; + actualFrames = 0; + this.onComplete.fire(data); + }; + + /** + * Custom event that fires after onStart, useful in subclassing + * @private + */ + this._onStart = new YAHOO.util.CustomEvent('_start', this, true); + + /** + * Custom event that fires when animation begins + * Listen via subscribe method (e.g. myAnim.onStart.subscribe(someFunction) + * @event onStart + */ + this.onStart = new YAHOO.util.CustomEvent('start', this); + + /** + * Custom event that fires between each frame + * Listen via subscribe method (e.g. myAnim.onTween.subscribe(someFunction) + * @event onTween + */ + this.onTween = new YAHOO.util.CustomEvent('tween', this); + + /** + * Custom event that fires after onTween + * @private + */ + this._onTween = new YAHOO.util.CustomEvent('_tween', this, true); + + /** + * Custom event that fires when animation ends + * Listen via subscribe method (e.g. myAnim.onComplete.subscribe(someFunction) + * @event onComplete + */ + this.onComplete = new YAHOO.util.CustomEvent('complete', this); + /** + * Custom event that fires after onComplete + * @private + */ + this._onComplete = new YAHOO.util.CustomEvent('_complete', this, true); + + this._onStart.subscribe(onStart); + this._onTween.subscribe(onTween); + this._onComplete.subscribe(onComplete); + } +}; + +/** + * Handles animation queueing and threading. + * Used by Anim and subclasses. + * @class AnimMgr + * @namespace YAHOO.util + */ +YAHOO.util.AnimMgr = new function() { + /** + * Reference to the animation Interval. + * @property thread + * @private + * @type Int + */ + var thread = null; + + /** + * The current queue of registered animation objects. + * @property queue + * @private + * @type Array + */ + var queue = []; + + /** + * The number of active animations. + * @property tweenCount + * @private + * @type Int + */ + var tweenCount = 0; + + /** + * Base frame rate (frames per second). + * Arbitrarily high for better x-browser calibration (slower browsers drop more frames). + * @property fps + * @type Int + * + */ + this.fps = 1000; + + /** + * Interval delay in milliseconds, defaults to fastest possible. + * @property delay + * @type Int + * + */ + this.delay = 1; + + /** + * Adds an animation instance to the animation queue. + * All animation instances must be registered in order to animate. + * @method registerElement + * @param {object} tween The Anim instance to be be registered + */ + this.registerElement = function(tween) { + queue[queue.length] = tween; + tweenCount += 1; + tween._onStart.fire(); + this.start(); + }; + + /** + * removes an animation instance from the animation queue. + * All animation instances must be registered in order to animate. + * @method unRegister + * @param {object} tween The Anim instance to be be registered + * @param {Int} index The index of the Anim instance + * @private + */ + this.unRegister = function(tween, index) { + tween._onComplete.fire(); + index = index || getIndex(tween); + if (index != -1) { queue.splice(index, 1); } + + tweenCount -= 1; + if (tweenCount <= 0) { this.stop(); } + }; + + /** + * Starts the animation thread. + * Only one thread can run at a time. + * @method start + */ + this.start = function() { + if (thread === null) { thread = setInterval(this.run, this.delay); } + }; + + /** + * Stops the animation thread or a specific animation instance. + * @method stop + * @param {object} tween A specific Anim instance to stop (optional) + * If no instance given, Manager stops thread and all animations. + */ + this.stop = function(tween) { + if (!tween) { + clearInterval(thread); + for (var i = 0, len = queue.length; i < len; ++i) { + if (queue[i].isAnimated()) { + this.unRegister(tween, i); + } + } + queue = []; + thread = null; + tweenCount = 0; + } + else { + this.unRegister(tween); + } + }; + + /** + * Called per Interval to handle each animation frame. + * @method run + */ + this.run = function() { + for (var i = 0, len = queue.length; i < len; ++i) { + var tween = queue[i]; + if ( !tween || !tween.isAnimated() ) { continue; } + + if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null) + { + tween.currentFrame += 1; + + if (tween.useSeconds) { + correctFrame(tween); + } + tween._onTween.fire(); + } + else { YAHOO.util.AnimMgr.stop(tween, i); } + } + }; + + var getIndex = function(anim) { + for (var i = 0, len = queue.length; i < len; ++i) { + if (queue[i] == anim) { + return i; // note return; + } + } + return -1; + }; + + /** + * On the fly frame correction to keep animation on time. + * @method correctFrame + * @private + * @param {Object} tween The Anim instance being corrected. + */ + var correctFrame = function(tween) { + var frames = tween.totalFrames; + var frame = tween.currentFrame; + var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); + var elapsed = (new Date() - tween.getStartTime()); + var tweak = 0; + + if (elapsed < tween.duration * 1000) { // check if falling behind + tweak = Math.round((elapsed / expected - 1) * tween.currentFrame); + } else { // went over duration, so jump to end + tweak = frames - (frame + 1); + } + if (tweak > 0 && isFinite(tweak)) { // adjust if needed + if (tween.currentFrame + tweak >= frames) {// dont go past last frame + tweak = frames - (frame + 1); + } + + tween.currentFrame += tweak; + } + }; +}; +/** + * Used to calculate Bezier splines for any number of control points. + * @class Bezier + * @namespace YAHOO.util + * + */ +YAHOO.util.Bezier = new function() { + /** + * Get the current position of the animated element based on t. + * Each point is an array of "x" and "y" values (0 = x, 1 = y) + * At least 2 points are required (start and end). + * First point is start. Last point is end. + * Additional control points are optional. + * @method getPosition + * @param {Array} points An array containing Bezier points + * @param {Number} t A number between 0 and 1 which is the basis for determining current position + * @return {Array} An array containing int x and y member data + */ + this.getPosition = function(points, t) { + var n = points.length; + var tmp = []; + + for (var i = 0; i < n; ++i){ + tmp[i] = [points[i][0], points[i][1]]; // save input + } + + for (var j = 1; j < n; ++j) { + for (i = 0; i < n - j; ++i) { + tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; + tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; + } + } + + return [ tmp[0][0], tmp[0][1] ]; + + }; +}; +(function() { +/** + * Anim subclass for color transitions. + *

Usage: var myAnim = new Y.ColorAnim(el, { backgroundColor: { from: '#FF0000', to: '#FFFFFF' } }, 1, Y.Easing.easeOut); Color values can be specified with either 112233, #112233, + * [255,255,255], or rgb(255,255,255)

+ * @class ColorAnim + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @constructor + * @extends YAHOO.util.Anim + * @param {HTMLElement | String} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + YAHOO.util.ColorAnim = function(el, attributes, duration, method) { + YAHOO.util.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); + }; + + YAHOO.extend(YAHOO.util.ColorAnim, YAHOO.util.Anim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.ColorAnim.superclass; + var proto = Y.ColorAnim.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("ColorAnim " + id); + }; + + proto.patterns.color = /color$/i; + proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i; + proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i; + proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i; + proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/; // need rgba for safari + + /** + * Attempts to parse the given string and return a 3-tuple. + * @method parseColor + * @param {String} s The string to parse. + * @return {Array} The 3-tuple of rgb values. + */ + proto.parseColor = function(s) { + if (s.length == 3) { return s; } + + var c = this.patterns.hex.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ]; + } + + c = this.patterns.rgb.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ]; + } + + c = this.patterns.hex3.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ]; + } + + return null; + }; + + proto.getAttribute = function(attr) { + var el = this.getEl(); + if ( this.patterns.color.test(attr) ) { + var val = YAHOO.util.Dom.getStyle(el, attr); + + if (this.patterns.transparent.test(val)) { // bgcolor default + var parent = el.parentNode; // try and get from an ancestor + val = Y.Dom.getStyle(parent, attr); + + while (parent && this.patterns.transparent.test(val)) { + parent = parent.parentNode; + val = Y.Dom.getStyle(parent, attr); + if (parent.tagName.toUpperCase() == 'HTML') { + val = '#fff'; + } + } + } + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.doMethod = function(attr, start, end) { + var val; + + if ( this.patterns.color.test(attr) ) { + val = []; + for (var i = 0, len = start.length; i < len; ++i) { + val[i] = superclass.doMethod.call(this, attr, start[i], end[i]); + } + + val = 'rgb('+Math.floor(val[0])+','+Math.floor(val[1])+','+Math.floor(val[2])+')'; + } + else { + val = superclass.doMethod.call(this, attr, start, end); + } + + return val; + }; + + proto.setRuntimeAttribute = function(attr) { + superclass.setRuntimeAttribute.call(this, attr); + + if ( this.patterns.color.test(attr) ) { + var attributes = this.attributes; + var start = this.parseColor(this.runtimeAttributes[attr].start); + var end = this.parseColor(this.runtimeAttributes[attr].end); + // fix colors if going "by" + if ( typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined' ) { + end = this.parseColor(attributes[attr].by); + + for (var i = 0, len = start.length; i < len; ++i) { + end[i] = start[i] + end[i]; + } + } + + this.runtimeAttributes[attr].start = start; + this.runtimeAttributes[attr].end = end; + } + }; +})();/* +TERMS OF USE - EASING EQUATIONS +Open source under the BSD License. +Copyright 2001 Robert Penner All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * Singleton that determines how an animation proceeds from start to end. + * @class Easing + * @namespace YAHOO.util +*/ + +YAHOO.util.Easing = { + + /** + * Uniform speed between points. + * @method easeNone + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeNone: function (t, b, c, d) { + return c*t/d + b; + }, + + /** + * Begins slowly and accelerates towards end. (quadratic) + * @method easeIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeIn: function (t, b, c, d) { + return c*(t/=d)*t + b; + }, + + /** + * Begins quickly and decelerates towards end. (quadratic) + * @method easeOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeOut: function (t, b, c, d) { + return -c *(t/=d)*(t-2) + b; + }, + + /** + * Begins slowly and decelerates towards end. (quadratic) + * @method easeBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeBoth: function (t, b, c, d) { + if ((t/=d/2) < 1) { + return c/2*t*t + b; + } + + return -c/2 * ((--t)*(t-2) - 1) + b; + }, + + /** + * Begins slowly and accelerates towards end. (quartic) + * @method easeInStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeInStrong: function (t, b, c, d) { + return c*(t/=d)*t*t*t + b; + }, + + /** + * Begins quickly and decelerates towards end. (quartic) + * @method easeOutStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeOutStrong: function (t, b, c, d) { + return -c * ((t=t/d-1)*t*t*t - 1) + b; + }, + + /** + * Begins slowly and decelerates towards end. (quartic) + * @method easeBothStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeBothStrong: function (t, b, c, d) { + if ((t/=d/2) < 1) { + return c/2*t*t*t*t + b; + } + + return -c/2 * ((t-=2)*t*t*t - 2) + b; + }, + + /** + * Snap in elastic effect. + * @method elasticIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} a Amplitude (optional) + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + + elasticIn: function (t, b, c, d, a, p) { + if (t == 0) { + return b; + } + if ( (t /= d) == 1 ) { + return b+c; + } + if (!p) { + p=d*.3; + } + + if (!a || a < Math.abs(c)) { + a = c; + var s = p/4; + } + else { + var s = p/(2*Math.PI) * Math.asin (c/a); + } + + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + }, + + /** + * Snap out elastic effect. + * @method elasticOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} a Amplitude (optional) + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + elasticOut: function (t, b, c, d, a, p) { + if (t == 0) { + return b; + } + if ( (t /= d) == 1 ) { + return b+c; + } + if (!p) { + p=d*.3; + } + + if (!a || a < Math.abs(c)) { + a = c; + var s = p / 4; + } + else { + var s = p/(2*Math.PI) * Math.asin (c/a); + } + + return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; + }, + + /** + * Snap both elastic effect. + * @method elasticBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} a Amplitude (optional) + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + elasticBoth: function (t, b, c, d, a, p) { + if (t == 0) { + return b; + } + + if ( (t /= d/2) == 2 ) { + return b+c; + } + + if (!p) { + p = d*(.3*1.5); + } + + if ( !a || a < Math.abs(c) ) { + a = c; + var s = p/4; + } + else { + var s = p/(2*Math.PI) * Math.asin (c/a); + } + + if (t < 1) { + return -.5*(a*Math.pow(2,10*(t-=1)) * + Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + } + return a*Math.pow(2,-10*(t-=1)) * + Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; + }, + + + /** + * Backtracks slightly, then reverses direction and moves to end. + * @method backIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backIn: function (t, b, c, d, s) { + if (typeof s == 'undefined') { + s = 1.70158; + } + return c*(t/=d)*t*((s+1)*t - s) + b; + }, + + /** + * Overshoots end, then reverses and comes back to end. + * @method backOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backOut: function (t, b, c, d, s) { + if (typeof s == 'undefined') { + s = 1.70158; + } + return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; + }, + + /** + * Backtracks slightly, then reverses direction, overshoots end, + * then reverses and comes back to end. + * @method backBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backBoth: function (t, b, c, d, s) { + if (typeof s == 'undefined') { + s = 1.70158; + } + + if ((t /= d/2 ) < 1) { + return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; + } + return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; + }, + + /** + * Bounce off of start. + * @method bounceIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceIn: function (t, b, c, d) { + return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; + }, + + /** + * Bounces off end. + * @method bounceOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceOut: function (t, b, c, d) { + if ((t/=d) < (1/2.75)) { + return c*(7.5625*t*t) + b; + } else if (t < (2/2.75)) { + return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; + } + return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; + }, + + /** + * Bounces off start and end. + * @method bounceBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceBoth: function (t, b, c, d) { + if (t < d/2) { + return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b; + } + return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; + } +}; + +(function() { +/** + * Anim subclass for moving elements along a path defined by the "points" + * member of "attributes". All "points" are arrays with x, y coordinates. + *

Usage: var myAnim = new YAHOO.util.Motion(el, { points: { to: [800, 800] } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Motion + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @constructor + * @extends YAHOO.util.Anim + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + YAHOO.util.Motion = function(el, attributes, duration, method) { + if (el) { // dont break existing subclasses not using YAHOO.extend + YAHOO.util.Motion.superclass.constructor.call(this, el, attributes, duration, method); + } + }; + + YAHOO.extend(YAHOO.util.Motion, YAHOO.util.ColorAnim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.Motion.superclass; + var proto = Y.Motion.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Motion " + id); + }; + + proto.patterns.points = /^points$/i; + + proto.setAttribute = function(attr, val, unit) { + if ( this.patterns.points.test(attr) ) { + unit = unit || 'px'; + superclass.setAttribute.call(this, 'left', val[0], unit); + superclass.setAttribute.call(this, 'top', val[1], unit); + } else { + superclass.setAttribute.call(this, attr, val, unit); + } + }; + + proto.getAttribute = function(attr) { + if ( this.patterns.points.test(attr) ) { + var val = [ + superclass.getAttribute.call(this, 'left'), + superclass.getAttribute.call(this, 'top') + ]; + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.doMethod = function(attr, start, end) { + var val = null; + + if ( this.patterns.points.test(attr) ) { + var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100; + val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t); + } else { + val = superclass.doMethod.call(this, attr, start, end); + } + return val; + }; + + proto.setRuntimeAttribute = function(attr) { + if ( this.patterns.points.test(attr) ) { + var el = this.getEl(); + var attributes = this.attributes; + var start; + var control = attributes['points']['control'] || []; + var end; + var i, len; + + if (control.length > 0 && !(control[0] instanceof Array) ) { // could be single point or array of points + control = [control]; + } else { // break reference to attributes.points.control + var tmp = []; + for (i = 0, len = control.length; i< len; ++i) { + tmp[i] = control[i]; + } + control = tmp; + } + + if (Y.Dom.getStyle(el, 'position') == 'static') { // default to relative + Y.Dom.setStyle(el, 'position', 'relative'); + } + + if ( isset(attributes['points']['from']) ) { + Y.Dom.setXY(el, attributes['points']['from']); // set position to from point + } + else { Y.Dom.setXY( el, Y.Dom.getXY(el) ); } // set it to current position + + start = this.getAttribute('points'); // get actual top & left + + // TO beats BY, per SMIL 2.1 spec + if ( isset(attributes['points']['to']) ) { + end = translateValues.call(this, attributes['points']['to'], start); + + var pageXY = Y.Dom.getXY(this.getEl()); + for (i = 0, len = control.length; i < len; ++i) { + control[i] = translateValues.call(this, control[i], start); + } + + + } else if ( isset(attributes['points']['by']) ) { + end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ]; + + for (i = 0, len = control.length; i < len; ++i) { + control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ]; + } + } + + this.runtimeAttributes[attr] = [start]; + + if (control.length > 0) { + this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control); + } + + this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end; + } + else { + superclass.setRuntimeAttribute.call(this, attr); + } + }; + + var translateValues = function(val, start) { + var pageXY = Y.Dom.getXY(this.getEl()); + val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ]; + + return val; + }; + + var isset = function(prop) { + return (typeof prop !== 'undefined'); + }; +})(); +(function() { +/** + * Anim subclass for scrolling elements to a position defined by the "scroll" + * member of "attributes". All "scroll" members are arrays with x, y scroll positions. + *

Usage: var myAnim = new YAHOO.util.Scroll(el, { scroll: { to: [0, 800] } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Scroll + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @extends YAHOO.util.Anim + * @constructor + * @param {String or HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + YAHOO.util.Scroll = function(el, attributes, duration, method) { + if (el) { // dont break existing subclasses not using YAHOO.extend + YAHOO.util.Scroll.superclass.constructor.call(this, el, attributes, duration, method); + } + }; + + YAHOO.extend(YAHOO.util.Scroll, YAHOO.util.ColorAnim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.Scroll.superclass; + var proto = Y.Scroll.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Scroll " + id); + }; + + proto.doMethod = function(attr, start, end) { + var val = null; + + if (attr == 'scroll') { + val = [ + this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames), + this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames) + ]; + + } else { + val = superclass.doMethod.call(this, attr, start, end); + } + return val; + }; + + proto.getAttribute = function(attr) { + var val = null; + var el = this.getEl(); + + if (attr == 'scroll') { + val = [ el.scrollLeft, el.scrollTop ]; + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.setAttribute = function(attr, val, unit) { + var el = this.getEl(); + + if (attr == 'scroll') { + el.scrollLeft = val[0]; + el.scrollTop = val[1]; + } else { + superclass.setAttribute.call(this, attr, val, unit); + } + }; +})(); diff --git a/lib/yui/animation/animation-min.js b/lib/yui/animation/animation-min.js index 87a42cf079..9e1291f510 100755 --- a/lib/yui/animation/animation-min.js +++ b/lib/yui/animation/animation-min.js @@ -1,50 +1,75 @@ -/* Copyright (c) 2006, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 0.12.1 */ -YAHOO.util.Anim=function(el,attributes,duration,method){if(el){this.init(el,attributes,duration,method);}};YAHOO.util.Anim.prototype={toString:function(){var el=this.getEl();var id=el.id||el.tagName;return("Anim "+id);},patterns:{noNegatives:/width|height|opacity|padding/i,offsetAttribute:/^((width|height)|(top|left))$/,defaultUnit:/width|height|top$|bottom$|left$|right$/i,offsetUnit:/\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i},doMethod:function(attr,start,end){return this.method(this.currentFrame,start,end-start,this.totalFrames);},setAttribute:function(attr,val,unit){if(this.patterns.noNegatives.test(attr)){val=(val>0)?val:0;} -YAHOO.util.Dom.setStyle(this.getEl(),attr,val+unit);},getAttribute:function(attr){var el=this.getEl();var val=YAHOO.util.Dom.getStyle(el,attr);if(val!=='auto'&&!this.patterns.offsetUnit.test(val)){return parseFloat(val);} -var a=this.patterns.offsetAttribute.exec(attr)||[];var pos=!!(a[3]);var box=!!(a[2]);if(box||(YAHOO.util.Dom.getStyle(el,'position')=='absolute'&&pos)){val=el['offset'+a[0].charAt(0).toUpperCase()+a[0].substr(1)];}else{val=0;} -return val;},getDefaultUnit:function(attr){if(this.patterns.defaultUnit.test(attr)){return'px';} -return'';},setRuntimeAttribute:function(attr){var start;var end;var attributes=this.attributes;this.runtimeAttributes[attr]={};var isset=function(prop){return(typeof prop!=='undefined');};if(!isset(attributes[attr]['to'])&&!isset(attributes[attr]['by'])){return false;} -start=(isset(attributes[attr]['from']))?attributes[attr]['from']:this.getAttribute(attr);if(isset(attributes[attr]['to'])){end=attributes[attr]['to'];}else if(isset(attributes[attr]['by'])){if(start.constructor==Array){end=[];for(var i=0,len=start.length;i0&&isFinite(tweak)){if(tween.currentFrame+tweak>=frames){tweak=frames-(frame+1);} -tween.currentFrame+=tweak;}};};YAHOO.util.Bezier=new function() -{this.getPosition=function(points,t) -{var n=points.length;var tmp=[];for(var i=0;i0&&!(control[0]instanceof Array)){control=[control];}else{var tmp=[];for(i=0,len=control.length;i0){this.runtimeAttributes[attr]=this.runtimeAttributes[attr].concat(control);} -this.runtimeAttributes[attr][this.runtimeAttributes[attr].length]=end;} -else{superclass.setRuntimeAttribute.call(this,attr);}};var translateValues=function(val,start){var pageXY=Y.Dom.getXY(this.getEl());val=[val[0]-pageXY[0]+start[0],val[1]-pageXY[1]+start[1]];return val;};var isset=function(prop){return(typeof prop!=='undefined');};})();(function(){YAHOO.util.Scroll=function(el,attributes,duration,method){if(el){YAHOO.util.Scroll.superclass.constructor.call(this,el,attributes,duration,method);}};YAHOO.extend(YAHOO.util.Scroll,YAHOO.util.ColorAnim);var Y=YAHOO.util;var superclass=Y.Scroll.superclass;var proto=Y.Scroll.prototype;proto.toString=function(){var el=this.getEl();var id=el.id||el.tagName;return("Scroll "+id);};proto.doMethod=function(attr,start,end){var val=null;if(attr=='scroll'){val=[this.method(this.currentFrame,start[0],end[0]-start[0],this.totalFrames),this.method(this.currentFrame,start[1],end[1]-start[1],this.totalFrames)];}else{val=superclass.doMethod.call(this,attr,start,end);} -return val;};proto.getAttribute=function(attr){var val=null;var el=this.getEl();if(attr=='scroll'){val=[el.scrollLeft,el.scrollTop];}else{val=superclass.getAttribute.call(this,attr);} +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 0.12.2 +*/ + +YAHOO.util.Anim=function(el,attributes,duration,method){if(el){this.init(el,attributes,duration,method);}};YAHOO.util.Anim.prototype={toString:function(){var el=this.getEl();var id=el.id||el.tagName;return("Anim "+id);},patterns:{noNegatives:/width|height|opacity|padding/i,offsetAttribute:/^((width|height)|(top|left))$/,defaultUnit:/width|height|top$|bottom$|left$|right$/i,offsetUnit:/\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i},doMethod:function(attr,start,end){return this.method(this.currentFrame,start,end-start,this.totalFrames);},setAttribute:function(attr,val,unit){if(this.patterns.noNegatives.test(attr)){val=(val>0)?val:0;} +YAHOO.util.Dom.setStyle(this.getEl(),attr,val+unit);},getAttribute:function(attr){var el=this.getEl();var val=YAHOO.util.Dom.getStyle(el,attr);if(val!=='auto'&&!this.patterns.offsetUnit.test(val)){return parseFloat(val);} +var a=this.patterns.offsetAttribute.exec(attr)||[];var pos=!!(a[3]);var box=!!(a[2]);if(box||(YAHOO.util.Dom.getStyle(el,'position')=='absolute'&&pos)){val=el['offset'+a[0].charAt(0).toUpperCase()+a[0].substr(1)];}else{val=0;} +return val;},getDefaultUnit:function(attr){if(this.patterns.defaultUnit.test(attr)){return'px';} +return'';},setRuntimeAttribute:function(attr){var start;var end;var attributes=this.attributes;this.runtimeAttributes[attr]={};var isset=function(prop){return(typeof prop!=='undefined');};if(!isset(attributes[attr]['to'])&&!isset(attributes[attr]['by'])){return false;} +start=(isset(attributes[attr]['from']))?attributes[attr]['from']:this.getAttribute(attr);if(isset(attributes[attr]['to'])){end=attributes[attr]['to'];}else if(isset(attributes[attr]['by'])){if(start.constructor==Array){end=[];for(var i=0,len=start.length;i0&&isFinite(tweak)){if(tween.currentFrame+tweak>=frames){tweak=frames-(frame+1);} +tween.currentFrame+=tweak;}};};YAHOO.util.Bezier=new function(){this.getPosition=function(points,t){var n=points.length;var tmp=[];for(var i=0;i0&&!(control[0]instanceof Array)){control=[control];}else{var tmp=[];for(i=0,len=control.length;i0){this.runtimeAttributes[attr]=this.runtimeAttributes[attr].concat(control);} +this.runtimeAttributes[attr][this.runtimeAttributes[attr].length]=end;} +else{superclass.setRuntimeAttribute.call(this,attr);}};var translateValues=function(val,start){var pageXY=Y.Dom.getXY(this.getEl());val=[val[0]-pageXY[0]+start[0],val[1]-pageXY[1]+start[1]];return val;};var isset=function(prop){return(typeof prop!=='undefined');};})();(function(){YAHOO.util.Scroll=function(el,attributes,duration,method){if(el){YAHOO.util.Scroll.superclass.constructor.call(this,el,attributes,duration,method);}};YAHOO.extend(YAHOO.util.Scroll,YAHOO.util.ColorAnim);var Y=YAHOO.util;var superclass=Y.Scroll.superclass;var proto=Y.Scroll.prototype;proto.toString=function(){var el=this.getEl();var id=el.id||el.tagName;return("Scroll "+id);};proto.doMethod=function(attr,start,end){var val=null;if(attr=='scroll'){val=[this.method(this.currentFrame,start[0],end[0]-start[0],this.totalFrames),this.method(this.currentFrame,start[1],end[1]-start[1],this.totalFrames)];}else{val=superclass.doMethod.call(this,attr,start,end);} +return val;};proto.getAttribute=function(attr){var val=null;var el=this.getEl();if(attr=='scroll'){val=[el.scrollLeft,el.scrollTop];}else{val=superclass.getAttribute.call(this,attr);} return val;};proto.setAttribute=function(attr,val,unit){var el=this.getEl();if(attr=='scroll'){el.scrollLeft=val[0];el.scrollTop=val[1];}else{superclass.setAttribute.call(this,attr,val,unit);}};})(); \ No newline at end of file diff --git a/lib/yui/animation/animation.js b/lib/yui/animation/animation.js index 79443906a1..3b34cf4af3 100755 --- a/lib/yui/animation/animation.js +++ b/lib/yui/animation/animation.js @@ -1,1272 +1,1341 @@ -/* -Copyright (c) 2006, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version: 0.12.1 -*/ - -/** - * The animation module provides allows effects to be added to HTMLElements. - * @module animation - */ - -/** - * - * Base animation class that provides the interface for building animated effects. - *

Usage: var myAnim = new YAHOO.util.Anim(el, { width: { from: 10, to: 100 } }, 1, YAHOO.util.Easing.easeOut);

- * @class Anim - * @namespace YAHOO.util - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @constructor - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - -YAHOO.util.Anim = function(el, attributes, duration, method) { - if (el) { - this.init(el, attributes, duration, method); - } -}; - -YAHOO.util.Anim.prototype = { - /** - * Provides a readable name for the Anim instance. - * @method toString - * @return {String} - */ - toString: function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Anim " + id); - }, - - patterns: { // cached for performance - noNegatives: /width|height|opacity|padding/i, // keep at zero or above - offsetAttribute: /^((width|height)|(top|left))$/, // use offsetValue as default - defaultUnit: /width|height|top$|bottom$|left$|right$/i, // use 'px' by default - offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i // IE may return these, so convert these to offset - }, - - /** - * Returns the value computed by the animation's "method". - * @method doMethod - * @param {String} attr The name of the attribute. - * @param {Number} start The value this attribute should start from for this animation. - * @param {Number} end The value this attribute should end at for this animation. - * @return {Number} The Value to be applied to the attribute. - */ - doMethod: function(attr, start, end) { - return this.method(this.currentFrame, start, end - start, this.totalFrames); - }, - - /** - * Applies a value to an attribute. - * @method setAttribute - * @param {String} attr The name of the attribute. - * @param {Number} val The value to be applied to the attribute. - * @param {String} unit The unit ('px', '%', etc.) of the value. - */ - setAttribute: function(attr, val, unit) { - if ( this.patterns.noNegatives.test(attr) ) { - val = (val > 0) ? val : 0; - } - - YAHOO.util.Dom.setStyle(this.getEl(), attr, val + unit); - }, - - /** - * Returns current value of the attribute. - * @method getAttribute - * @param {String} attr The name of the attribute. - * @return {Number} val The current value of the attribute. - */ - getAttribute: function(attr) { - var el = this.getEl(); - var val = YAHOO.util.Dom.getStyle(el, attr); - - if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) { - return parseFloat(val); - } - - var a = this.patterns.offsetAttribute.exec(attr) || []; - var pos = !!( a[3] ); // top or left - var box = !!( a[2] ); // width or height - - // use offsets for width/height and abs pos top/left - if ( box || (YAHOO.util.Dom.getStyle(el, 'position') == 'absolute' && pos) ) { - val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)]; - } else { // default to zero for other 'auto' - val = 0; - } - - return val; - }, - - /** - * Returns the unit to use when none is supplied. - * @method getDefaultUnit - * @param {attr} attr The name of the attribute. - * @return {String} The default unit to be used. - */ - getDefaultUnit: function(attr) { - if ( this.patterns.defaultUnit.test(attr) ) { - return 'px'; - } - - return ''; - }, - - /** - * Sets the actual values to be used during the animation. - * @method setRuntimeAttribute - * Should only be needed for subclass use. - * @param {Object} attr The attribute object - * @private - */ - setRuntimeAttribute: function(attr) { - var start; - var end; - var attributes = this.attributes; - - this.runtimeAttributes[attr] = {}; - - var isset = function(prop) { - return (typeof prop !== 'undefined'); - }; - - if ( !isset(attributes[attr]['to']) && !isset(attributes[attr]['by']) ) { - return false; // note return; nothing to animate to - } - - start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr); - - // To beats by, per SMIL 2.1 spec - if ( isset(attributes[attr]['to']) ) { - end = attributes[attr]['to']; - } else if ( isset(attributes[attr]['by']) ) { - if (start.constructor == Array) { - end = []; - for (var i = 0, len = start.length; i < len; ++i) { - end[i] = start[i] + attributes[attr]['by'][i]; - } - } else { - end = start + attributes[attr]['by']; - } - } - - this.runtimeAttributes[attr].start = start; - this.runtimeAttributes[attr].end = end; - - // set units if needed - this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr); - }, - - /** - * Constructor for Anim instance. - * @method init - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - init: function(el, attributes, duration, method) { - /** - * Whether or not the animation is running. - * @property isAnimated - * @private - * @type Boolean - */ - var isAnimated = false; - - /** - * A Date object that is created when the animation begins. - * @property startTime - * @private - * @type Date - */ - var startTime = null; - - /** - * The number of frames this animation was able to execute. - * @property actualFrames - * @private - * @type Int - */ - var actualFrames = 0; - - /** - * The element to be animated. - * @property el - * @private - * @type HTMLElement - */ - el = YAHOO.util.Dom.get(el); - - /** - * The collection of attributes to be animated. - * Each attribute must have at least a "to" or "by" defined in order to animate. - * If "to" is supplied, the animation will end with the attribute at that value. - * If "by" is supplied, the animation will end at that value plus its starting value. - * If both are supplied, "to" is used, and "by" is ignored. - * Optional additional member include "from" (the value the attribute should start animating from, defaults to current value), and "unit" (the units to apply to the values). - * @property attributes - * @type Object - */ - this.attributes = attributes || {}; - - /** - * The length of the animation. Defaults to "1" (second). - * @property duration - * @type Number - */ - this.duration = duration || 1; - - /** - * The method that will provide values to the attribute(s) during the animation. - * Defaults to "YAHOO.util.Easing.easeNone". - * @property method - * @type Function - */ - this.method = method || YAHOO.util.Easing.easeNone; - - /** - * Whether or not the duration should be treated as seconds. - * Defaults to true. - * @property useSeconds - * @type Boolean - */ - this.useSeconds = true; // default to seconds - - /** - * The location of the current animation on the timeline. - * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. - * @property currentFrame - * @type Int - */ - this.currentFrame = 0; - - /** - * The total number of frames to be executed. - * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. - * @property totalFrames - * @type Int - */ - this.totalFrames = YAHOO.util.AnimMgr.fps; - - - /** - * Returns a reference to the animated element. - * @method getEl - * @return {HTMLElement} - */ - this.getEl = function() { return el; }; - - /** - * Checks whether the element is currently animated. - * @method isAnimated - * @return {Boolean} current value of isAnimated. - */ - this.isAnimated = function() { - return isAnimated; - }; - - /** - * Returns the animation start time. - * @method getStartTime - * @return {Date} current value of startTime. - */ - this.getStartTime = function() { - return startTime; - }; - - this.runtimeAttributes = {}; - - - - /** - * Starts the animation by registering it with the animation manager. - * @method animate - */ - this.animate = function() { - if ( this.isAnimated() ) { return false; } - - this.currentFrame = 0; - - this.totalFrames = ( this.useSeconds ) ? Math.ceil(YAHOO.util.AnimMgr.fps * this.duration) : this.duration; - - YAHOO.util.AnimMgr.registerElement(this); - }; - - /** - * Stops the animation. Normally called by AnimMgr when animation completes. - * @method stop - * @param {Boolean} finish (optional) If true, animation will jump to final frame. - */ - this.stop = function(finish) { - if (finish) { - this.currentFrame = this.totalFrames; - this._onTween.fire(); - } - YAHOO.util.AnimMgr.stop(this); - }; - - var onStart = function() { - this.onStart.fire(); - - this.runtimeAttributes = {}; - for (var attr in this.attributes) { - this.setRuntimeAttribute(attr); - } - - isAnimated = true; - actualFrames = 0; - startTime = new Date(); - }; - - /** - * Feeds the starting and ending values for each animated attribute to doMethod once per frame, then applies the resulting value to the attribute(s). - * @private - */ - - var onTween = function() { - var data = { - duration: new Date() - this.getStartTime(), - currentFrame: this.currentFrame - }; - - data.toString = function() { - return ( - 'duration: ' + data.duration + - ', currentFrame: ' + data.currentFrame - ); - }; - - this.onTween.fire(data); - - var runtimeAttributes = this.runtimeAttributes; - - for (var attr in runtimeAttributes) { - this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); - } - - actualFrames += 1; - }; - - var onComplete = function() { - var actual_duration = (new Date() - startTime) / 1000 ; - - var data = { - duration: actual_duration, - frames: actualFrames, - fps: actualFrames / actual_duration - }; - - data.toString = function() { - return ( - 'duration: ' + data.duration + - ', frames: ' + data.frames + - ', fps: ' + data.fps - ); - }; - - isAnimated = false; - actualFrames = 0; - this.onComplete.fire(data); - }; - - /** - * Custom event that fires after onStart, useful in subclassing - * @private - */ - this._onStart = new YAHOO.util.CustomEvent('_start', this, true); - - /** - * Custom event that fires when animation begins - * Listen via subscribe method (e.g. myAnim.onStart.subscribe(someFunction) - * @event onStart - */ - this.onStart = new YAHOO.util.CustomEvent('start', this); - - /** - * Custom event that fires between each frame - * Listen via subscribe method (e.g. myAnim.onTween.subscribe(someFunction) - * @event onTween - */ - this.onTween = new YAHOO.util.CustomEvent('tween', this); - - /** - * Custom event that fires after onTween - * @private - */ - this._onTween = new YAHOO.util.CustomEvent('_tween', this, true); - - /** - * Custom event that fires when animation ends - * Listen via subscribe method (e.g. myAnim.onComplete.subscribe(someFunction) - * @event onComplete - */ - this.onComplete = new YAHOO.util.CustomEvent('complete', this); - /** - * Custom event that fires after onComplete - * @private - */ - this._onComplete = new YAHOO.util.CustomEvent('_complete', this, true); - - this._onStart.subscribe(onStart); - this._onTween.subscribe(onTween); - this._onComplete.subscribe(onComplete); - } -}; - -/** - * Handles animation queueing and threading. - * Used by Anim and subclasses. - * @class AnimMgr - * @namespace YAHOO.util - */ -YAHOO.util.AnimMgr = new function() { - /** - * Reference to the animation Interval. - * @property thread - * @private - * @type Int - */ - var thread = null; - - /** - * The current queue of registered animation objects. - * @property queue - * @private - * @type Array - */ - var queue = []; - - /** - * The number of active animations. - * @property tweenCount - * @private - * @type Int - */ - var tweenCount = 0; - - /** - * Base frame rate (frames per second). - * Arbitrarily high for better x-browser calibration (slower browsers drop more frames). - * @property fps - * @type Int - * - */ - this.fps = 200; - - /** - * Interval delay in milliseconds, defaults to fastest possible. - * @property delay - * @type Int - * - */ - this.delay = 1; - - /** - * Adds an animation instance to the animation queue. - * All animation instances must be registered in order to animate. - * @method registerElement - * @param {object} tween The Anim instance to be be registered - */ - this.registerElement = function(tween) { - queue[queue.length] = tween; - tweenCount += 1; - tween._onStart.fire(); - this.start(); - }; - - /** - * removes an animation instance from the animation queue. - * All animation instances must be registered in order to animate. - * @method unRegister - * @param {object} tween The Anim instance to be be registered - * @param {Int} index The index of the Anim instance - * @private - */ - this.unRegister = function(tween, index) { - tween._onComplete.fire(); - index = index || getIndex(tween); - if (index != -1) { queue.splice(index, 1); } - - tweenCount -= 1; - if (tweenCount <= 0) { this.stop(); } - }; - - /** - * Starts the animation thread. - * Only one thread can run at a time. - * @method start - */ - this.start = function() { - if (thread === null) { thread = setInterval(this.run, this.delay); } - }; - - /** - * Stops the animation thread or a specific animation instance. - * @method stop - * @param {object} tween A specific Anim instance to stop (optional) - * If no instance given, Manager stops thread and all animations. - */ - this.stop = function(tween) { - if (!tween) { - clearInterval(thread); - for (var i = 0, len = queue.length; i < len; ++i) { - if (queue[i].isAnimated()) { - this.unRegister(tween, i); - } - } - queue = []; - thread = null; - tweenCount = 0; - } - else { - this.unRegister(tween); - } - }; - - /** - * Called per Interval to handle each animation frame. - * @method run - */ - this.run = function() { - for (var i = 0, len = queue.length; i < len; ++i) { - var tween = queue[i]; - if ( !tween || !tween.isAnimated() ) { continue; } - - if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null) - { - tween.currentFrame += 1; - - if (tween.useSeconds) { - correctFrame(tween); - } - tween._onTween.fire(); - } - else { YAHOO.util.AnimMgr.stop(tween, i); } - } - }; - - var getIndex = function(anim) { - for (var i = 0, len = queue.length; i < len; ++i) { - if (queue[i] == anim) { - return i; // note return; - } - } - return -1; - }; - - /** - * On the fly frame correction to keep animation on time. - * @method correctFrame - * @private - * @param {Object} tween The Anim instance being corrected. - */ - var correctFrame = function(tween) { - var frames = tween.totalFrames; - var frame = tween.currentFrame; - var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); - var elapsed = (new Date() - tween.getStartTime()); - var tweak = 0; - - if (elapsed < tween.duration * 1000) { // check if falling behind - tweak = Math.round((elapsed / expected - 1) * tween.currentFrame); - } else { // went over duration, so jump to end - tweak = frames - (frame + 1); - } - if (tweak > 0 && isFinite(tweak)) { // adjust if needed - if (tween.currentFrame + tweak >= frames) {// dont go past last frame - tweak = frames - (frame + 1); - } - - tween.currentFrame += tweak; - } - }; -}; -/** - * Used to calculate Bezier splines for any number of control points. - * @class Bezier - * @namespace YAHOO.util - * - */ -YAHOO.util.Bezier = new function() -{ - /** - * Get the current position of the animated element based on t. - * Each point is an array of "x" and "y" values (0 = x, 1 = y) - * At least 2 points are required (start and end). - * First point is start. Last point is end. - * Additional control points are optional. - * @method getPosition - * @param {Array} points An array containing Bezier points - * @param {Number} t A number between 0 and 1 which is the basis for determining current position - * @return {Array} An array containing int x and y member data - */ - this.getPosition = function(points, t) - { - var n = points.length; - var tmp = []; - - for (var i = 0; i < n; ++i){ - tmp[i] = [points[i][0], points[i][1]]; // save input - } - - for (var j = 1; j < n; ++j) { - for (i = 0; i < n - j; ++i) { - tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; - tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; - } - } - - return [ tmp[0][0], tmp[0][1] ]; - - }; -}; -(function() { -/** - * Anim subclass for color transitions. - *

Usage: var myAnim = new Y.ColorAnim(el, { backgroundColor: { from: '#FF0000', to: '#FFFFFF' } }, 1, Y.Easing.easeOut); Color values can be specified with either 112233, #112233, - * [255,255,255], or rgb(255,255,255)

- * @class ColorAnim - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @constructor - * @extends YAHOO.util.Anim - * @param {HTMLElement | String} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - YAHOO.util.ColorAnim = function(el, attributes, duration, method) { - YAHOO.util.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); - }; - - YAHOO.extend(YAHOO.util.ColorAnim, YAHOO.util.Anim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.ColorAnim.superclass; - var proto = Y.ColorAnim.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("ColorAnim " + id); - }; - - proto.patterns.color = /color$/i; - proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i; - proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i; - proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i; - proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/; // need rgba for safari - - /** - * Attempts to parse the given string and return a 3-tuple. - * @method parseColor - * @param {String} s The string to parse. - * @return {Array} The 3-tuple of rgb values. - */ - proto.parseColor = function(s) { - if (s.length == 3) { return s; } - - var c = this.patterns.hex.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ]; - } - - c = this.patterns.rgb.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ]; - } - - c = this.patterns.hex3.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ]; - } - - return null; - }; - - proto.getAttribute = function(attr) { - var el = this.getEl(); - if ( this.patterns.color.test(attr) ) { - var val = YAHOO.util.Dom.getStyle(el, attr); - - if (this.patterns.transparent.test(val)) { // bgcolor default - var parent = el.parentNode; // try and get from an ancestor - val = Y.Dom.getStyle(parent, attr); - - while (parent && this.patterns.transparent.test(val)) { - parent = parent.parentNode; - val = Y.Dom.getStyle(parent, attr); - if (parent.tagName.toUpperCase() == 'HTML') { - val = '#fff'; - } - } - } - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.doMethod = function(attr, start, end) { - var val; - - if ( this.patterns.color.test(attr) ) { - val = []; - for (var i = 0, len = start.length; i < len; ++i) { - val[i] = superclass.doMethod.call(this, attr, start[i], end[i]); - } - - val = 'rgb('+Math.floor(val[0])+','+Math.floor(val[1])+','+Math.floor(val[2])+')'; - } - else { - val = superclass.doMethod.call(this, attr, start, end); - } - - return val; - }; - - proto.setRuntimeAttribute = function(attr) { - superclass.setRuntimeAttribute.call(this, attr); - - if ( this.patterns.color.test(attr) ) { - var attributes = this.attributes; - var start = this.parseColor(this.runtimeAttributes[attr].start); - var end = this.parseColor(this.runtimeAttributes[attr].end); - // fix colors if going "by" - if ( typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined' ) { - end = this.parseColor(attributes[attr].by); - - for (var i = 0, len = start.length; i < len; ++i) { - end[i] = start[i] + end[i]; - } - } - - this.runtimeAttributes[attr].start = start; - this.runtimeAttributes[attr].end = end; - } - }; -})();/* -TERMS OF USE - EASING EQUATIONS -Open source under the BSD License. -Copyright 2001 Robert Penner All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * Singleton that determines how an animation proceeds from start to end. - * @class Easing - * @namespace YAHOO.util -*/ - -YAHOO.util.Easing = { - - /** - * Uniform speed between points. - * @method easeNone - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeNone: function (t, b, c, d) { - return c*t/d + b; - }, - - /** - * Begins slowly and accelerates towards end. (quadratic) - * @method easeIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeIn: function (t, b, c, d) { - return c*(t/=d)*t + b; - }, - - /** - * Begins quickly and decelerates towards end. (quadratic) - * @method easeOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeOut: function (t, b, c, d) { - return -c *(t/=d)*(t-2) + b; - }, - - /** - * Begins slowly and decelerates towards end. (quadratic) - * @method easeBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeBoth: function (t, b, c, d) { - if ((t/=d/2) < 1) return c/2*t*t + b; - return -c/2 * ((--t)*(t-2) - 1) + b; - }, - - /** - * Begins slowly and accelerates towards end. (quartic) - * @method easeInStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeInStrong: function (t, b, c, d) { - return c*(t/=d)*t*t*t + b; - }, - - /** - * Begins quickly and decelerates towards end. (quartic) - * @method easeOutStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeOutStrong: function (t, b, c, d) { - return -c * ((t=t/d-1)*t*t*t - 1) + b; - }, - - /** - * Begins slowly and decelerates towards end. (quartic) - * @method easeBothStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeBothStrong: function (t, b, c, d) { - if ((t/=d/2) < 1) return c/2*t*t*t*t + b; - return -c/2 * ((t-=2)*t*t*t - 2) + b; - }, - - /** - * Snap in elastic effect. - * @method elasticIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - - elasticIn: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; - }, - - /** - * Snap out elastic effect. - * @method elasticOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - elasticOut: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; - }, - - /** - * Snap both elastic effect. - * @method elasticBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - elasticBoth: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; - return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; - }, - - /** - * Backtracks slightly, then reverses direction and moves to end. - * @method backIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backIn: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - return c*(t/=d)*t*((s+1)*t - s) + b; - }, - - /** - * Overshoots end, then reverses and comes back to end. - * @method backOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backOut: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; - }, - - /** - * Backtracks slightly, then reverses direction, overshoots end, - * then reverses and comes back to end. - * @method backBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backBoth: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; - return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; - }, - - /** - * Bounce off of start. - * @method bounceIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceIn: function (t, b, c, d) { - return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; - }, - - /** - * Bounces off end. - * @method bounceOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceOut: function (t, b, c, d) { - if ((t/=d) < (1/2.75)) { - return c*(7.5625*t*t) + b; - } else if (t < (2/2.75)) { - return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; - } else if (t < (2.5/2.75)) { - return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; - } else { - return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; - } - }, - - /** - * Bounces off start and end. - * @method bounceBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceBoth: function (t, b, c, d) { - if (t < d/2) return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b; - return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; - } -}; - -(function() { -/** - * Anim subclass for moving elements along a path defined by the "points" - * member of "attributes". All "points" are arrays with x, y coordinates. - *

Usage: var myAnim = new YAHOO.util.Motion(el, { points: { to: [800, 800] } }, 1, YAHOO.util.Easing.easeOut);

- * @class Motion - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @constructor - * @extends YAHOO.util.Anim - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - YAHOO.util.Motion = function(el, attributes, duration, method) { - if (el) { // dont break existing subclasses not using YAHOO.extend - YAHOO.util.Motion.superclass.constructor.call(this, el, attributes, duration, method); - } - }; - - YAHOO.extend(YAHOO.util.Motion, YAHOO.util.ColorAnim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.Motion.superclass; - var proto = Y.Motion.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Motion " + id); - }; - - proto.patterns.points = /^points$/i; - - proto.setAttribute = function(attr, val, unit) { - if ( this.patterns.points.test(attr) ) { - unit = unit || 'px'; - superclass.setAttribute.call(this, 'left', val[0], unit); - superclass.setAttribute.call(this, 'top', val[1], unit); - } else { - superclass.setAttribute.call(this, attr, val, unit); - } - }; - - proto.getAttribute = function(attr) { - if ( this.patterns.points.test(attr) ) { - var val = [ - superclass.getAttribute.call(this, 'left'), - superclass.getAttribute.call(this, 'top') - ]; - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.doMethod = function(attr, start, end) { - var val = null; - - if ( this.patterns.points.test(attr) ) { - var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100; - val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t); - } else { - val = superclass.doMethod.call(this, attr, start, end); - } - return val; - }; - - proto.setRuntimeAttribute = function(attr) { - if ( this.patterns.points.test(attr) ) { - var el = this.getEl(); - var attributes = this.attributes; - var start; - var control = attributes['points']['control'] || []; - var end; - var i, len; - - if (control.length > 0 && !(control[0] instanceof Array) ) { // could be single point or array of points - control = [control]; - } else { // break reference to attributes.points.control - var tmp = []; - for (i = 0, len = control.length; i< len; ++i) { - tmp[i] = control[i]; - } - control = tmp; - } - - if (Y.Dom.getStyle(el, 'position') == 'static') { // default to relative - Y.Dom.setStyle(el, 'position', 'relative'); - } - - if ( isset(attributes['points']['from']) ) { - Y.Dom.setXY(el, attributes['points']['from']); // set position to from point - } - else { Y.Dom.setXY( el, Y.Dom.getXY(el) ); } // set it to current position - - start = this.getAttribute('points'); // get actual top & left - - // TO beats BY, per SMIL 2.1 spec - if ( isset(attributes['points']['to']) ) { - end = translateValues.call(this, attributes['points']['to'], start); - - var pageXY = Y.Dom.getXY(this.getEl()); - for (i = 0, len = control.length; i < len; ++i) { - control[i] = translateValues.call(this, control[i], start); - } - - - } else if ( isset(attributes['points']['by']) ) { - end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ]; - - for (i = 0, len = control.length; i < len; ++i) { - control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ]; - } - } - - this.runtimeAttributes[attr] = [start]; - - if (control.length > 0) { - this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control); - } - - this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end; - } - else { - superclass.setRuntimeAttribute.call(this, attr); - } - }; - - var translateValues = function(val, start) { - var pageXY = Y.Dom.getXY(this.getEl()); - val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ]; - - return val; - }; - - var isset = function(prop) { - return (typeof prop !== 'undefined'); - }; -})(); -(function() { -/** - * Anim subclass for scrolling elements to a position defined by the "scroll" - * member of "attributes". All "scroll" members are arrays with x, y scroll positions. - *

Usage: var myAnim = new YAHOO.util.Scroll(el, { scroll: { to: [0, 800] } }, 1, YAHOO.util.Easing.easeOut);

- * @class Scroll - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @extends YAHOO.util.Anim - * @constructor - * @param {String or HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - YAHOO.util.Scroll = function(el, attributes, duration, method) { - if (el) { // dont break existing subclasses not using YAHOO.extend - YAHOO.util.Scroll.superclass.constructor.call(this, el, attributes, duration, method); - } - }; - - YAHOO.extend(YAHOO.util.Scroll, YAHOO.util.ColorAnim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.Scroll.superclass; - var proto = Y.Scroll.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Scroll " + id); - }; - - proto.doMethod = function(attr, start, end) { - var val = null; - - if (attr == 'scroll') { - val = [ - this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames), - this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames) - ]; - - } else { - val = superclass.doMethod.call(this, attr, start, end); - } - return val; - }; - - proto.getAttribute = function(attr) { - var val = null; - var el = this.getEl(); - - if (attr == 'scroll') { - val = [ el.scrollLeft, el.scrollTop ]; - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.setAttribute = function(attr, val, unit) { - var el = this.getEl(); - - if (attr == 'scroll') { - el.scrollLeft = val[0]; - el.scrollTop = val[1]; - } else { - superclass.setAttribute.call(this, attr, val, unit); - } - }; -})(); +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 0.12.2 +*/ +/** + * The animation module provides allows effects to be added to HTMLElements. + * @module animation + * @requires yahoo, event, dom + */ + +/** + * + * Base animation class that provides the interface for building animated effects. + *

Usage: var myAnim = new YAHOO.util.Anim(el, { width: { from: 10, to: 100 } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Anim + * @namespace YAHOO.util + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @constructor + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + +YAHOO.util.Anim = function(el, attributes, duration, method) { + if (el) { + this.init(el, attributes, duration, method); + } +}; + +YAHOO.util.Anim.prototype = { + /** + * Provides a readable name for the Anim instance. + * @method toString + * @return {String} + */ + toString: function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Anim " + id); + }, + + patterns: { // cached for performance + noNegatives: /width|height|opacity|padding/i, // keep at zero or above + offsetAttribute: /^((width|height)|(top|left))$/, // use offsetValue as default + defaultUnit: /width|height|top$|bottom$|left$|right$/i, // use 'px' by default + offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i // IE may return these, so convert these to offset + }, + + /** + * Returns the value computed by the animation's "method". + * @method doMethod + * @param {String} attr The name of the attribute. + * @param {Number} start The value this attribute should start from for this animation. + * @param {Number} end The value this attribute should end at for this animation. + * @return {Number} The Value to be applied to the attribute. + */ + doMethod: function(attr, start, end) { + return this.method(this.currentFrame, start, end - start, this.totalFrames); + }, + + /** + * Applies a value to an attribute. + * @method setAttribute + * @param {String} attr The name of the attribute. + * @param {Number} val The value to be applied to the attribute. + * @param {String} unit The unit ('px', '%', etc.) of the value. + */ + setAttribute: function(attr, val, unit) { + if ( this.patterns.noNegatives.test(attr) ) { + val = (val > 0) ? val : 0; + } + + YAHOO.util.Dom.setStyle(this.getEl(), attr, val + unit); + }, + + /** + * Returns current value of the attribute. + * @method getAttribute + * @param {String} attr The name of the attribute. + * @return {Number} val The current value of the attribute. + */ + getAttribute: function(attr) { + var el = this.getEl(); + var val = YAHOO.util.Dom.getStyle(el, attr); + + if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) { + return parseFloat(val); + } + + var a = this.patterns.offsetAttribute.exec(attr) || []; + var pos = !!( a[3] ); // top or left + var box = !!( a[2] ); // width or height + + // use offsets for width/height and abs pos top/left + if ( box || (YAHOO.util.Dom.getStyle(el, 'position') == 'absolute' && pos) ) { + val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)]; + } else { // default to zero for other 'auto' + val = 0; + } + + return val; + }, + + /** + * Returns the unit to use when none is supplied. + * @method getDefaultUnit + * @param {attr} attr The name of the attribute. + * @return {String} The default unit to be used. + */ + getDefaultUnit: function(attr) { + if ( this.patterns.defaultUnit.test(attr) ) { + return 'px'; + } + + return ''; + }, + + /** + * Sets the actual values to be used during the animation. Should only be needed for subclass use. + * @method setRuntimeAttribute + * @param {Object} attr The attribute object + * @private + */ + setRuntimeAttribute: function(attr) { + var start; + var end; + var attributes = this.attributes; + + this.runtimeAttributes[attr] = {}; + + var isset = function(prop) { + return (typeof prop !== 'undefined'); + }; + + if ( !isset(attributes[attr]['to']) && !isset(attributes[attr]['by']) ) { + return false; // note return; nothing to animate to + } + + start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr); + + // To beats by, per SMIL 2.1 spec + if ( isset(attributes[attr]['to']) ) { + end = attributes[attr]['to']; + } else if ( isset(attributes[attr]['by']) ) { + if (start.constructor == Array) { + end = []; + for (var i = 0, len = start.length; i < len; ++i) { + end[i] = start[i] + attributes[attr]['by'][i]; + } + } else { + end = start + attributes[attr]['by']; + } + } + + this.runtimeAttributes[attr].start = start; + this.runtimeAttributes[attr].end = end; + + // set units if needed + this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr); + }, + + /** + * Constructor for Anim instance. + * @method init + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + init: function(el, attributes, duration, method) { + /** + * Whether or not the animation is running. + * @property isAnimated + * @private + * @type Boolean + */ + var isAnimated = false; + + /** + * A Date object that is created when the animation begins. + * @property startTime + * @private + * @type Date + */ + var startTime = null; + + /** + * The number of frames this animation was able to execute. + * @property actualFrames + * @private + * @type Int + */ + var actualFrames = 0; + + /** + * The element to be animated. + * @property el + * @private + * @type HTMLElement + */ + el = YAHOO.util.Dom.get(el); + + /** + * The collection of attributes to be animated. + * Each attribute must have at least a "to" or "by" defined in order to animate. + * If "to" is supplied, the animation will end with the attribute at that value. + * If "by" is supplied, the animation will end at that value plus its starting value. + * If both are supplied, "to" is used, and "by" is ignored. + * Optional additional member include "from" (the value the attribute should start animating from, defaults to current value), and "unit" (the units to apply to the values). + * @property attributes + * @type Object + */ + this.attributes = attributes || {}; + + /** + * The length of the animation. Defaults to "1" (second). + * @property duration + * @type Number + */ + this.duration = duration || 1; + + /** + * The method that will provide values to the attribute(s) during the animation. + * Defaults to "YAHOO.util.Easing.easeNone". + * @property method + * @type Function + */ + this.method = method || YAHOO.util.Easing.easeNone; + + /** + * Whether or not the duration should be treated as seconds. + * Defaults to true. + * @property useSeconds + * @type Boolean + */ + this.useSeconds = true; // default to seconds + + /** + * The location of the current animation on the timeline. + * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. + * @property currentFrame + * @type Int + */ + this.currentFrame = 0; + + /** + * The total number of frames to be executed. + * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. + * @property totalFrames + * @type Int + */ + this.totalFrames = YAHOO.util.AnimMgr.fps; + + + /** + * Returns a reference to the animated element. + * @method getEl + * @return {HTMLElement} + */ + this.getEl = function() { return el; }; + + /** + * Checks whether the element is currently animated. + * @method isAnimated + * @return {Boolean} current value of isAnimated. + */ + this.isAnimated = function() { + return isAnimated; + }; + + /** + * Returns the animation start time. + * @method getStartTime + * @return {Date} current value of startTime. + */ + this.getStartTime = function() { + return startTime; + }; + + this.runtimeAttributes = {}; + + + + /** + * Starts the animation by registering it with the animation manager. + * @method animate + */ + this.animate = function() { + if ( this.isAnimated() ) { + return false; + } + + this.currentFrame = 0; + + this.totalFrames = ( this.useSeconds ) ? Math.ceil(YAHOO.util.AnimMgr.fps * this.duration) : this.duration; + + YAHOO.util.AnimMgr.registerElement(this); + }; + + /** + * Stops the animation. Normally called by AnimMgr when animation completes. + * @method stop + * @param {Boolean} finish (optional) If true, animation will jump to final frame. + */ + this.stop = function(finish) { + if (finish) { + this.currentFrame = this.totalFrames; + this._onTween.fire(); + } + YAHOO.util.AnimMgr.stop(this); + }; + + var onStart = function() { + this.onStart.fire(); + + this.runtimeAttributes = {}; + for (var attr in this.attributes) { + this.setRuntimeAttribute(attr); + } + + isAnimated = true; + actualFrames = 0; + startTime = new Date(); + }; + + /** + * Feeds the starting and ending values for each animated attribute to doMethod once per frame, then applies the resulting value to the attribute(s). + * @private + */ + + var onTween = function() { + var data = { + duration: new Date() - this.getStartTime(), + currentFrame: this.currentFrame + }; + + data.toString = function() { + return ( + 'duration: ' + data.duration + + ', currentFrame: ' + data.currentFrame + ); + }; + + this.onTween.fire(data); + + var runtimeAttributes = this.runtimeAttributes; + + for (var attr in runtimeAttributes) { + this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); + } + + actualFrames += 1; + }; + + var onComplete = function() { + var actual_duration = (new Date() - startTime) / 1000 ; + + var data = { + duration: actual_duration, + frames: actualFrames, + fps: actualFrames / actual_duration + }; + + data.toString = function() { + return ( + 'duration: ' + data.duration + + ', frames: ' + data.frames + + ', fps: ' + data.fps + ); + }; + + isAnimated = false; + actualFrames = 0; + this.onComplete.fire(data); + }; + + /** + * Custom event that fires after onStart, useful in subclassing + * @private + */ + this._onStart = new YAHOO.util.CustomEvent('_start', this, true); + + /** + * Custom event that fires when animation begins + * Listen via subscribe method (e.g. myAnim.onStart.subscribe(someFunction) + * @event onStart + */ + this.onStart = new YAHOO.util.CustomEvent('start', this); + + /** + * Custom event that fires between each frame + * Listen via subscribe method (e.g. myAnim.onTween.subscribe(someFunction) + * @event onTween + */ + this.onTween = new YAHOO.util.CustomEvent('tween', this); + + /** + * Custom event that fires after onTween + * @private + */ + this._onTween = new YAHOO.util.CustomEvent('_tween', this, true); + + /** + * Custom event that fires when animation ends + * Listen via subscribe method (e.g. myAnim.onComplete.subscribe(someFunction) + * @event onComplete + */ + this.onComplete = new YAHOO.util.CustomEvent('complete', this); + /** + * Custom event that fires after onComplete + * @private + */ + this._onComplete = new YAHOO.util.CustomEvent('_complete', this, true); + + this._onStart.subscribe(onStart); + this._onTween.subscribe(onTween); + this._onComplete.subscribe(onComplete); + } +}; + +/** + * Handles animation queueing and threading. + * Used by Anim and subclasses. + * @class AnimMgr + * @namespace YAHOO.util + */ +YAHOO.util.AnimMgr = new function() { + /** + * Reference to the animation Interval. + * @property thread + * @private + * @type Int + */ + var thread = null; + + /** + * The current queue of registered animation objects. + * @property queue + * @private + * @type Array + */ + var queue = []; + + /** + * The number of active animations. + * @property tweenCount + * @private + * @type Int + */ + var tweenCount = 0; + + /** + * Base frame rate (frames per second). + * Arbitrarily high for better x-browser calibration (slower browsers drop more frames). + * @property fps + * @type Int + * + */ + this.fps = 1000; + + /** + * Interval delay in milliseconds, defaults to fastest possible. + * @property delay + * @type Int + * + */ + this.delay = 1; + + /** + * Adds an animation instance to the animation queue. + * All animation instances must be registered in order to animate. + * @method registerElement + * @param {object} tween The Anim instance to be be registered + */ + this.registerElement = function(tween) { + queue[queue.length] = tween; + tweenCount += 1; + tween._onStart.fire(); + this.start(); + }; + + /** + * removes an animation instance from the animation queue. + * All animation instances must be registered in order to animate. + * @method unRegister + * @param {object} tween The Anim instance to be be registered + * @param {Int} index The index of the Anim instance + * @private + */ + this.unRegister = function(tween, index) { + tween._onComplete.fire(); + index = index || getIndex(tween); + if (index != -1) { queue.splice(index, 1); } + + tweenCount -= 1; + if (tweenCount <= 0) { this.stop(); } + }; + + /** + * Starts the animation thread. + * Only one thread can run at a time. + * @method start + */ + this.start = function() { + if (thread === null) { thread = setInterval(this.run, this.delay); } + }; + + /** + * Stops the animation thread or a specific animation instance. + * @method stop + * @param {object} tween A specific Anim instance to stop (optional) + * If no instance given, Manager stops thread and all animations. + */ + this.stop = function(tween) { + if (!tween) { + clearInterval(thread); + for (var i = 0, len = queue.length; i < len; ++i) { + if (queue[i].isAnimated()) { + this.unRegister(tween, i); + } + } + queue = []; + thread = null; + tweenCount = 0; + } + else { + this.unRegister(tween); + } + }; + + /** + * Called per Interval to handle each animation frame. + * @method run + */ + this.run = function() { + for (var i = 0, len = queue.length; i < len; ++i) { + var tween = queue[i]; + if ( !tween || !tween.isAnimated() ) { continue; } + + if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null) + { + tween.currentFrame += 1; + + if (tween.useSeconds) { + correctFrame(tween); + } + tween._onTween.fire(); + } + else { YAHOO.util.AnimMgr.stop(tween, i); } + } + }; + + var getIndex = function(anim) { + for (var i = 0, len = queue.length; i < len; ++i) { + if (queue[i] == anim) { + return i; // note return; + } + } + return -1; + }; + + /** + * On the fly frame correction to keep animation on time. + * @method correctFrame + * @private + * @param {Object} tween The Anim instance being corrected. + */ + var correctFrame = function(tween) { + var frames = tween.totalFrames; + var frame = tween.currentFrame; + var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); + var elapsed = (new Date() - tween.getStartTime()); + var tweak = 0; + + if (elapsed < tween.duration * 1000) { // check if falling behind + tweak = Math.round((elapsed / expected - 1) * tween.currentFrame); + } else { // went over duration, so jump to end + tweak = frames - (frame + 1); + } + if (tweak > 0 && isFinite(tweak)) { // adjust if needed + if (tween.currentFrame + tweak >= frames) {// dont go past last frame + tweak = frames - (frame + 1); + } + + tween.currentFrame += tweak; + } + }; +}; +/** + * Used to calculate Bezier splines for any number of control points. + * @class Bezier + * @namespace YAHOO.util + * + */ +YAHOO.util.Bezier = new function() { + /** + * Get the current position of the animated element based on t. + * Each point is an array of "x" and "y" values (0 = x, 1 = y) + * At least 2 points are required (start and end). + * First point is start. Last point is end. + * Additional control points are optional. + * @method getPosition + * @param {Array} points An array containing Bezier points + * @param {Number} t A number between 0 and 1 which is the basis for determining current position + * @return {Array} An array containing int x and y member data + */ + this.getPosition = function(points, t) { + var n = points.length; + var tmp = []; + + for (var i = 0; i < n; ++i){ + tmp[i] = [points[i][0], points[i][1]]; // save input + } + + for (var j = 1; j < n; ++j) { + for (i = 0; i < n - j; ++i) { + tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; + tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; + } + } + + return [ tmp[0][0], tmp[0][1] ]; + + }; +}; +(function() { +/** + * Anim subclass for color transitions. + *

Usage: var myAnim = new Y.ColorAnim(el, { backgroundColor: { from: '#FF0000', to: '#FFFFFF' } }, 1, Y.Easing.easeOut); Color values can be specified with either 112233, #112233, + * [255,255,255], or rgb(255,255,255)

+ * @class ColorAnim + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @constructor + * @extends YAHOO.util.Anim + * @param {HTMLElement | String} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + YAHOO.util.ColorAnim = function(el, attributes, duration, method) { + YAHOO.util.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); + }; + + YAHOO.extend(YAHOO.util.ColorAnim, YAHOO.util.Anim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.ColorAnim.superclass; + var proto = Y.ColorAnim.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("ColorAnim " + id); + }; + + proto.patterns.color = /color$/i; + proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i; + proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i; + proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i; + proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/; // need rgba for safari + + /** + * Attempts to parse the given string and return a 3-tuple. + * @method parseColor + * @param {String} s The string to parse. + * @return {Array} The 3-tuple of rgb values. + */ + proto.parseColor = function(s) { + if (s.length == 3) { return s; } + + var c = this.patterns.hex.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ]; + } + + c = this.patterns.rgb.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ]; + } + + c = this.patterns.hex3.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ]; + } + + return null; + }; + + proto.getAttribute = function(attr) { + var el = this.getEl(); + if ( this.patterns.color.test(attr) ) { + var val = YAHOO.util.Dom.getStyle(el, attr); + + if (this.patterns.transparent.test(val)) { // bgcolor default + var parent = el.parentNode; // try and get from an ancestor + val = Y.Dom.getStyle(parent, attr); + + while (parent && this.patterns.transparent.test(val)) { + parent = parent.parentNode; + val = Y.Dom.getStyle(parent, attr); + if (parent.tagName.toUpperCase() == 'HTML') { + val = '#fff'; + } + } + } + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.doMethod = function(attr, start, end) { + var val; + + if ( this.patterns.color.test(attr) ) { + val = []; + for (var i = 0, len = start.length; i < len; ++i) { + val[i] = superclass.doMethod.call(this, attr, start[i], end[i]); + } + + val = 'rgb('+Math.floor(val[0])+','+Math.floor(val[1])+','+Math.floor(val[2])+')'; + } + else { + val = superclass.doMethod.call(this, attr, start, end); + } + + return val; + }; + + proto.setRuntimeAttribute = function(attr) { + superclass.setRuntimeAttribute.call(this, attr); + + if ( this.patterns.color.test(attr) ) { + var attributes = this.attributes; + var start = this.parseColor(this.runtimeAttributes[attr].start); + var end = this.parseColor(this.runtimeAttributes[attr].end); + // fix colors if going "by" + if ( typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined' ) { + end = this.parseColor(attributes[attr].by); + + for (var i = 0, len = start.length; i < len; ++i) { + end[i] = start[i] + end[i]; + } + } + + this.runtimeAttributes[attr].start = start; + this.runtimeAttributes[attr].end = end; + } + }; +})();/* +TERMS OF USE - EASING EQUATIONS +Open source under the BSD License. +Copyright 2001 Robert Penner All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * Singleton that determines how an animation proceeds from start to end. + * @class Easing + * @namespace YAHOO.util +*/ + +YAHOO.util.Easing = { + + /** + * Uniform speed between points. + * @method easeNone + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeNone: function (t, b, c, d) { + return c*t/d + b; + }, + + /** + * Begins slowly and accelerates towards end. (quadratic) + * @method easeIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeIn: function (t, b, c, d) { + return c*(t/=d)*t + b; + }, + + /** + * Begins quickly and decelerates towards end. (quadratic) + * @method easeOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeOut: function (t, b, c, d) { + return -c *(t/=d)*(t-2) + b; + }, + + /** + * Begins slowly and decelerates towards end. (quadratic) + * @method easeBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeBoth: function (t, b, c, d) { + if ((t/=d/2) < 1) { + return c/2*t*t + b; + } + + return -c/2 * ((--t)*(t-2) - 1) + b; + }, + + /** + * Begins slowly and accelerates towards end. (quartic) + * @method easeInStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeInStrong: function (t, b, c, d) { + return c*(t/=d)*t*t*t + b; + }, + + /** + * Begins quickly and decelerates towards end. (quartic) + * @method easeOutStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeOutStrong: function (t, b, c, d) { + return -c * ((t=t/d-1)*t*t*t - 1) + b; + }, + + /** + * Begins slowly and decelerates towards end. (quartic) + * @method easeBothStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeBothStrong: function (t, b, c, d) { + if ((t/=d/2) < 1) { + return c/2*t*t*t*t + b; + } + + return -c/2 * ((t-=2)*t*t*t - 2) + b; + }, + + /** + * Snap in elastic effect. + * @method elasticIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} a Amplitude (optional) + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + + elasticIn: function (t, b, c, d, a, p) { + if (t == 0) { + return b; + } + if ( (t /= d) == 1 ) { + return b+c; + } + if (!p) { + p=d*.3; + } + + if (!a || a < Math.abs(c)) { + a = c; + var s = p/4; + } + else { + var s = p/(2*Math.PI) * Math.asin (c/a); + } + + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + }, + + /** + * Snap out elastic effect. + * @method elasticOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} a Amplitude (optional) + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + elasticOut: function (t, b, c, d, a, p) { + if (t == 0) { + return b; + } + if ( (t /= d) == 1 ) { + return b+c; + } + if (!p) { + p=d*.3; + } + + if (!a || a < Math.abs(c)) { + a = c; + var s = p / 4; + } + else { + var s = p/(2*Math.PI) * Math.asin (c/a); + } + + return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; + }, + + /** + * Snap both elastic effect. + * @method elasticBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} a Amplitude (optional) + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + elasticBoth: function (t, b, c, d, a, p) { + if (t == 0) { + return b; + } + + if ( (t /= d/2) == 2 ) { + return b+c; + } + + if (!p) { + p = d*(.3*1.5); + } + + if ( !a || a < Math.abs(c) ) { + a = c; + var s = p/4; + } + else { + var s = p/(2*Math.PI) * Math.asin (c/a); + } + + if (t < 1) { + return -.5*(a*Math.pow(2,10*(t-=1)) * + Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + } + return a*Math.pow(2,-10*(t-=1)) * + Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; + }, + + /** + * Backtracks slightly, then reverses direction and moves to end. + * @method backIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backIn: function (t, b, c, d, s) { + if (typeof s == 'undefined') { + s = 1.70158; + } + return c*(t/=d)*t*((s+1)*t - s) + b; + }, + + /** + * Overshoots end, then reverses and comes back to end. + * @method backOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backOut: function (t, b, c, d, s) { + if (typeof s == 'undefined') { + s = 1.70158; + } + return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; + }, + + /** + * Backtracks slightly, then reverses direction, overshoots end, + * then reverses and comes back to end. + * @method backBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backBoth: function (t, b, c, d, s) { + if (typeof s == 'undefined') { + s = 1.70158; + } + + if ((t /= d/2 ) < 1) { + return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; + } + return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; + }, + + /** + * Bounce off of start. + * @method bounceIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceIn: function (t, b, c, d) { + return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; + }, + + /** + * Bounces off end. + * @method bounceOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceOut: function (t, b, c, d) { + if ((t/=d) < (1/2.75)) { + return c*(7.5625*t*t) + b; + } else if (t < (2/2.75)) { + return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; + } + return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; + }, + + /** + * Bounces off start and end. + * @method bounceBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceBoth: function (t, b, c, d) { + if (t < d/2) { + return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b; + } + return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; + } +}; + +(function() { +/** + * Anim subclass for moving elements along a path defined by the "points" + * member of "attributes". All "points" are arrays with x, y coordinates. + *

Usage: var myAnim = new YAHOO.util.Motion(el, { points: { to: [800, 800] } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Motion + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @constructor + * @extends YAHOO.util.Anim + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + YAHOO.util.Motion = function(el, attributes, duration, method) { + if (el) { // dont break existing subclasses not using YAHOO.extend + YAHOO.util.Motion.superclass.constructor.call(this, el, attributes, duration, method); + } + }; + + YAHOO.extend(YAHOO.util.Motion, YAHOO.util.ColorAnim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.Motion.superclass; + var proto = Y.Motion.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Motion " + id); + }; + + proto.patterns.points = /^points$/i; + + proto.setAttribute = function(attr, val, unit) { + if ( this.patterns.points.test(attr) ) { + unit = unit || 'px'; + superclass.setAttribute.call(this, 'left', val[0], unit); + superclass.setAttribute.call(this, 'top', val[1], unit); + } else { + superclass.setAttribute.call(this, attr, val, unit); + } + }; + + proto.getAttribute = function(attr) { + if ( this.patterns.points.test(attr) ) { + var val = [ + superclass.getAttribute.call(this, 'left'), + superclass.getAttribute.call(this, 'top') + ]; + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.doMethod = function(attr, start, end) { + var val = null; + + if ( this.patterns.points.test(attr) ) { + var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100; + val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t); + } else { + val = superclass.doMethod.call(this, attr, start, end); + } + return val; + }; + + proto.setRuntimeAttribute = function(attr) { + if ( this.patterns.points.test(attr) ) { + var el = this.getEl(); + var attributes = this.attributes; + var start; + var control = attributes['points']['control'] || []; + var end; + var i, len; + + if (control.length > 0 && !(control[0] instanceof Array) ) { // could be single point or array of points + control = [control]; + } else { // break reference to attributes.points.control + var tmp = []; + for (i = 0, len = control.length; i< len; ++i) { + tmp[i] = control[i]; + } + control = tmp; + } + + if (Y.Dom.getStyle(el, 'position') == 'static') { // default to relative + Y.Dom.setStyle(el, 'position', 'relative'); + } + + if ( isset(attributes['points']['from']) ) { + Y.Dom.setXY(el, attributes['points']['from']); // set position to from point + } + else { Y.Dom.setXY( el, Y.Dom.getXY(el) ); } // set it to current position + + start = this.getAttribute('points'); // get actual top & left + + // TO beats BY, per SMIL 2.1 spec + if ( isset(attributes['points']['to']) ) { + end = translateValues.call(this, attributes['points']['to'], start); + + var pageXY = Y.Dom.getXY(this.getEl()); + for (i = 0, len = control.length; i < len; ++i) { + control[i] = translateValues.call(this, control[i], start); + } + + + } else if ( isset(attributes['points']['by']) ) { + end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ]; + + for (i = 0, len = control.length; i < len; ++i) { + control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ]; + } + } + + this.runtimeAttributes[attr] = [start]; + + if (control.length > 0) { + this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control); + } + + this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end; + } + else { + superclass.setRuntimeAttribute.call(this, attr); + } + }; + + var translateValues = function(val, start) { + var pageXY = Y.Dom.getXY(this.getEl()); + val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ]; + + return val; + }; + + var isset = function(prop) { + return (typeof prop !== 'undefined'); + }; +})(); +(function() { +/** + * Anim subclass for scrolling elements to a position defined by the "scroll" + * member of "attributes". All "scroll" members are arrays with x, y scroll positions. + *

Usage: var myAnim = new YAHOO.util.Scroll(el, { scroll: { to: [0, 800] } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Scroll + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @extends YAHOO.util.Anim + * @constructor + * @param {String or HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + YAHOO.util.Scroll = function(el, attributes, duration, method) { + if (el) { // dont break existing subclasses not using YAHOO.extend + YAHOO.util.Scroll.superclass.constructor.call(this, el, attributes, duration, method); + } + }; + + YAHOO.extend(YAHOO.util.Scroll, YAHOO.util.ColorAnim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.Scroll.superclass; + var proto = Y.Scroll.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Scroll " + id); + }; + + proto.doMethod = function(attr, start, end) { + var val = null; + + if (attr == 'scroll') { + val = [ + this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames), + this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames) + ]; + + } else { + val = superclass.doMethod.call(this, attr, start, end); + } + return val; + }; + + proto.getAttribute = function(attr) { + var val = null; + var el = this.getEl(); + + if (attr == 'scroll') { + val = [ el.scrollLeft, el.scrollTop ]; + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.setAttribute = function(attr, val, unit) { + var el = this.getEl(); + + if (attr == 'scroll') { + el.scrollLeft = val[0]; + el.scrollTop = val[1]; + } else { + superclass.setAttribute.call(this, attr, val, unit); + } + }; +})(); diff --git a/lib/yui/autocomplete/README b/lib/yui/autocomplete/README index 01cad9d227..39c1cd89cf 100755 --- a/lib/yui/autocomplete/README +++ b/lib/yui/autocomplete/README @@ -1,65 +1,71 @@ -AutoComplete Release Notes - -*** version 0.12.1 *** - -* No longer trigger typeAhead feature when user is backspacing on input text. - - - -*** version 0.12.0 *** - -* The following constants must be defined as static class properties and are no longer -available as instance properties: - -YAHOO.widget.DataSource.ERROR_DATANULL -YAHOO.widget.DataSource.ERROR_DATAPARSE -YAHOO.widget.DS_XHR.TYPE_JSON -YAHOO.widget.DS_XHR.TYPE_XML -YAHOO.widget.DS_XHR.TYPE_FLAT -YAHOO.widget.DS_XHR.ERROR_DATAXHR - -* The property minQueryLength now supports zero and negative number values for -DS_JSFunction and DS_XHR objects, to enable null or empty string queries and to disable -AutoComplete functionality altogether, respectively. - -* Enabling the alwaysShowContainer feature will no longer send containerExpandEvent or -containerCollapseEvent. - - - -**** version 0.11.3 *** - -* The iFrameSrc property has been deprecated. Implementers no longer need to -specify an https URL to avoid IE security warnings when working with sites over -SSL. - - - -*** version 0.11.0 *** - -* The method getListIds() has been deprecated for getListItems(), which returns -an array of DOM references. - -* All classnames have been prefixed with "yui-ac-". - -* Container elements should no longer have CSS property "display" set to "none". - -* The useIFrame property can now be set after instantiation. - -* On some browsers, the unmatchedItemSelectEvent may not be fired properly when -delimiter characters are defined. - -* On some browsers, defining delimiter characters while enabling forceSelection -may result in unexpected behavior. - - - -*** version 0.10.0 *** - -* Initial release - -* In order to enable the useIFrame property, it should be set in the -constructor. - -* On some browsers, defining delimiter characters while enabling forceSelection -may result in unexpected behavior. +AutoComplete Release Notes + +*** version 0.12.2 *** + +* No changes. + + + +*** version 0.12.1 *** + +* No longer trigger typeAhead feature when user is backspacing on input text. + + + +*** version 0.12.0 *** + +* The following constants must be defined as static class properties and are no longer +available as instance properties: + +YAHOO.widget.DataSource.ERROR_DATANULL +YAHOO.widget.DataSource.ERROR_DATAPARSE +YAHOO.widget.DS_XHR.TYPE_JSON +YAHOO.widget.DS_XHR.TYPE_XML +YAHOO.widget.DS_XHR.TYPE_FLAT +YAHOO.widget.DS_XHR.ERROR_DATAXHR + +* The property minQueryLength now supports zero and negative number values for +DS_JSFunction and DS_XHR objects, to enable null or empty string queries and to disable +AutoComplete functionality altogether, respectively. + +* Enabling the alwaysShowContainer feature will no longer send containerExpandEvent or +containerCollapseEvent. + + + +**** version 0.11.3 *** + +* The iFrameSrc property has been deprecated. Implementers no longer need to +specify an https URL to avoid IE security warnings when working with sites over +SSL. + + + +*** version 0.11.0 *** + +* The method getListIds() has been deprecated for getListItems(), which returns +an array of DOM references. + +* All classnames have been prefixed with "yui-ac-". + +* Container elements should no longer have CSS property "display" set to "none". + +* The useIFrame property can now be set after instantiation. + +* On some browsers, the unmatchedItemSelectEvent may not be fired properly when +delimiter characters are defined. + +* On some browsers, defining delimiter characters while enabling forceSelection +may result in unexpected behavior. + + + +*** version 0.10.0 *** + +* Initial release + +* In order to enable the useIFrame property, it should be set in the +constructor. + +* On some browsers, defining delimiter characters while enabling forceSelection +may result in unexpected behavior. diff --git a/lib/yui/autocomplete/autocomplete-debug.js b/lib/yui/autocomplete/autocomplete-debug.js index d6c3ac3616..45dc20894d 100755 --- a/lib/yui/autocomplete/autocomplete-debug.js +++ b/lib/yui/autocomplete/autocomplete-debug.js @@ -1,10 +1,9 @@ -/* -Copyright (c) 2006, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.com/yui/license.txt -version: 0.12.1 -*/ - +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 0.12.2 +*/ /** * The AutoComplete control provides the front-end logic for text-entry suggestion and * completion functionality. @@ -138,7 +137,7 @@ YAHOO.widget.AutoComplete = function(elInput,elContainer,oDataSource,oConfigs) { this.selectionEnforceEvent = new YAHOO.util.CustomEvent("selectionEnforce", this); this.containerCollapseEvent = new YAHOO.util.CustomEvent("containerCollapse", this); this.textboxBlurEvent = new YAHOO.util.CustomEvent("textboxBlur", this); - + // Finish up oTextbox.setAttribute("autocomplete","off"); YAHOO.widget.AutoComplete._nIndex++; @@ -516,7 +515,7 @@ YAHOO.widget.AutoComplete.prototype.textboxKeyEvent = null; /** * Fired when the AutoComplete instance makes a query to the DataSource. - * + * * @event dataRequestEvent * @param oSelf {Object} The AutoComplete instance. * @param sQuery {String} The query string. @@ -554,7 +553,7 @@ YAHOO.widget.AutoComplete.prototype.containerExpandEvent = null; /** * Fired when the input field has been prefilled by the type-ahead - * feature. + * feature. * * @event typeAheadEvent * @param oSelf {Object} The AutoComplete instance. @@ -582,7 +581,7 @@ YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent = null; YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent = null; /** - * Fired when result item has been arrowed to. + * Fired when result item has been arrowed to. * * @event itemArrowToEvent * @param oSelf {Object} The AutoComplete instance. @@ -613,7 +612,7 @@ YAHOO.widget.AutoComplete.prototype.itemSelectEvent = null; /** * Fired when a user selection does not match any of the displayed result items. * Note that this event may not behave as expected when delimiter characters - * have been defined. + * have been defined. * * @event unmatchedItemSelectEvent * @param oSelf {Object} The AutoComplete instance. @@ -1370,7 +1369,7 @@ YAHOO.widget.AutoComplete.prototype._toggleContainer = function(bShow) { if(this.alwaysShowContainer && this._bContainerOpen) { return; } - + // Clear contents of container if(!bShow) { this._oContainer._oContent.scrollTop = 0; @@ -2013,1086 +2012,1086 @@ YAHOO.widget.AutoComplete.prototype._onFormSubmit = function(v,oSelf) { oSelf._oTextbox.setAttribute("autocomplete","off"); } }; -/****************************************************************************/ -/****************************************************************************/ -/****************************************************************************/ - -/** - * The DataSource classes manages sending a request and returning response from a live - * database. Supported data include local JavaScript arrays and objects and databases - * accessible via XHR connections. Supported response formats include JavaScript arrays, - * JSON, XML, and flat-file textual data. - * - * @class DataSource - * @constructor - */ -YAHOO.widget.DataSource = function() { - /* abstract class */ -}; - - -///////////////////////////////////////////////////////////////////////////// -// -// Public constants -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Error message for null data responses. - * - * @property ERROR_DATANULL - * @type String - * @static - * @final - */ -YAHOO.widget.DataSource.ERROR_DATANULL = "Response data was null"; - -/** - * Error message for data responses with parsing errors. - * - * @property ERROR_DATAPARSE - * @type String - * @static - * @final - */ -YAHOO.widget.DataSource.ERROR_DATAPARSE = "Response data could not be parsed"; - - -///////////////////////////////////////////////////////////////////////////// -// -// Public member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Max size of the local cache. Set to 0 to turn off caching. Caching is - * useful to reduce the number of server connections. Recommended only for data - * sources that return comprehensive results for queries or when stale data is - * not an issue. - * - * @property maxCacheEntries - * @type Number - * @default 15 - */ -YAHOO.widget.DataSource.prototype.maxCacheEntries = 15; - -/** - * Use this to equate cache matching with the type of matching done by your live - * data source. If caching is on and queryMatchContains is true, the cache - * returns results that "contain" the query string. By default, - * queryMatchContains is set to false, meaning the cache only returns results - * that "start with" the query string. - * - * @property queryMatchContains - * @type Boolean - * @default false - */ -YAHOO.widget.DataSource.prototype.queryMatchContains = false; - -/** - * Enables query subset matching. If caching is on and queryMatchSubset is - * true, substrings of queries will return matching cached results. For - * instance, if the first query is for "abc" susequent queries that start with - * "abc", like "abcd", will be queried against the cache, and not the live data - * source. Recommended only for DataSources that return comprehensive results - * for queries with very few characters. - * - * @property queryMatchSubset - * @type Boolean - * @default false - * - */ -YAHOO.widget.DataSource.prototype.queryMatchSubset = false; - -/** - * Enables query case-sensitivity matching. If caching is on and - * queryMatchCase is true, queries will only return results for case-sensitive - * matches. - * - * @property queryMatchCase - * @type Boolean - * @default false - */ -YAHOO.widget.DataSource.prototype.queryMatchCase = false; - - -///////////////////////////////////////////////////////////////////////////// -// -// Public methods -// -///////////////////////////////////////////////////////////////////////////// - - /** - * Public accessor to the unique name of the DataSource instance. - * - * @method toString - * @return {String} Unique name of the DataSource instance - */ -YAHOO.widget.DataSource.prototype.toString = function() { - return "DataSource " + this._sName; -}; - -/** - * Retrieves query results, first checking the local cache, then making the - * query request to the live data source as defined by the function doQuery. - * - * @method getResults - * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. - * @param sQuery {String} Query string. - * @param oParent {Object} The object instance that has requested data. - */ -YAHOO.widget.DataSource.prototype.getResults = function(oCallbackFn, sQuery, oParent) { - - // First look in cache - var aResults = this._doQueryCache(oCallbackFn,sQuery,oParent); - - // Not in cache, so get results from server - if(aResults.length === 0) { - this.queryEvent.fire(this, oParent, sQuery); - this.doQuery(oCallbackFn, sQuery, oParent); - } -}; - -/** - * Abstract method implemented by subclasses to make a query to the live data - * source. Must call the callback function with the response returned from the - * query. Populates cache (if enabled). - * - * @method doQuery - * @param oCallbackFn {HTMLFunction} Callback function implemented by oParent to which to return results. - * @param sQuery {String} Query string. - * @param oParent {Object} The object instance that has requested data. - */ -YAHOO.widget.DataSource.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { - /* override this */ -}; - -/** - * Flushes cache. - * - * @method flushCache - */ -YAHOO.widget.DataSource.prototype.flushCache = function() { - if(this._aCache) { - this._aCache = []; - } - if(this._aCacheHelper) { - this._aCacheHelper = []; - } - this.cacheFlushEvent.fire(this); -}; - -///////////////////////////////////////////////////////////////////////////// -// -// Public events -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Fired when a query is made to the live data source. - * - * @event queryEvent - * @param oSelf {Object} The DataSource instance. - * @param oParent {Object} The requesting object. - * @param sQuery {String} The query string. - */ -YAHOO.widget.DataSource.prototype.queryEvent = null; - -/** - * Fired when a query is made to the local cache. - * - * @event cacheQueryEvent - * @param oSelf {Object} The DataSource instance. - * @param oParent {Object} The requesting object. - * @param sQuery {String} The query string. - */ -YAHOO.widget.DataSource.prototype.cacheQueryEvent = null; - -/** - * Fired when data is retrieved from the live data source. - * - * @event getResultsEvent - * @param oSelf {Object} The DataSource instance. - * @param oParent {Object} The requesting object. - * @param sQuery {String} The query string. - * @param aResults {Object[]} Array of result objects. - */ -YAHOO.widget.DataSource.prototype.getResultsEvent = null; - -/** - * Fired when data is retrieved from the local cache. - * - * @event getCachedResultsEvent - * @param oSelf {Object} The DataSource instance. - * @param oParent {Object} The requesting object. - * @param sQuery {String} The query string. - * @param aResults {Object[]} Array of result objects. - */ -YAHOO.widget.DataSource.prototype.getCachedResultsEvent = null; - -/** - * Fired when an error is encountered with the live data source. - * - * @event dataErrorEvent - * @param oSelf {Object} The DataSource instance. - * @param oParent {Object} The requesting object. - * @param sQuery {String} The query string. - * @param sMsg {String} Error message string - */ -YAHOO.widget.DataSource.prototype.dataErrorEvent = null; - -/** - * Fired when the local cache is flushed. - * - * @event cacheFlushEvent - * @param oSelf {Object} The DataSource instance - */ -YAHOO.widget.DataSource.prototype.cacheFlushEvent = null; - -///////////////////////////////////////////////////////////////////////////// -// -// Private member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Internal class variable to index multiple DataSource instances. - * - * @property _nIndex - * @type Number - * @private - * @static - */ -YAHOO.widget.DataSource._nIndex = 0; - -/** - * Name of DataSource instance. - * - * @property _sName - * @type String - * @private - */ -YAHOO.widget.DataSource.prototype._sName = null; - -/** - * Local cache of data result objects indexed chronologically. - * - * @property _aCache - * @type Object[] - * @private - */ -YAHOO.widget.DataSource.prototype._aCache = null; - - -///////////////////////////////////////////////////////////////////////////// -// -// Private methods -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Initializes DataSource instance. - * - * @method _init - * @private - */ -YAHOO.widget.DataSource.prototype._init = function() { - // Validate and initialize public configs - var maxCacheEntries = this.maxCacheEntries; - if(isNaN(maxCacheEntries) || (maxCacheEntries < 0)) { - maxCacheEntries = 0; - } - // Initialize local cache - if(maxCacheEntries > 0 && !this._aCache) { - this._aCache = []; - } - - this._sName = "instance" + YAHOO.widget.DataSource._nIndex; - YAHOO.widget.DataSource._nIndex++; - - this.queryEvent = new YAHOO.util.CustomEvent("query", this); - this.cacheQueryEvent = new YAHOO.util.CustomEvent("cacheQuery", this); - this.getResultsEvent = new YAHOO.util.CustomEvent("getResults", this); - this.getCachedResultsEvent = new YAHOO.util.CustomEvent("getCachedResults", this); - this.dataErrorEvent = new YAHOO.util.CustomEvent("dataError", this); - this.cacheFlushEvent = new YAHOO.util.CustomEvent("cacheFlush", this); -}; - -/** - * Adds a result object to the local cache, evicting the oldest element if the - * cache is full. Newer items will have higher indexes, the oldest item will have - * index of 0. - * - * @method _addCacheElem - * @param oResult {Object} Data result object, including array of results. - * @private - */ -YAHOO.widget.DataSource.prototype._addCacheElem = function(oResult) { - var aCache = this._aCache; - // Don't add if anything important is missing. - if(!aCache || !oResult || !oResult.query || !oResult.results) { - return; - } - - // If the cache is full, make room by removing from index=0 - if(aCache.length >= this.maxCacheEntries) { - aCache.shift(); - } - - // Add to cache, at the end of the array - aCache.push(oResult); -}; - -/** - * Queries the local cache for results. If query has been cached, the callback - * function is called with the results, and the cached is refreshed so that it - * is now the newest element. - * - * @method _doQueryCache - * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. - * @param sQuery {String} Query string. - * @param oParent {Object} The object instance that has requested data. - * @return aResults {Object[]} Array of results from local cache if found, otherwise null. - * @private - */ -YAHOO.widget.DataSource.prototype._doQueryCache = function(oCallbackFn, sQuery, oParent) { - var aResults = []; - var bMatchFound = false; - var aCache = this._aCache; - var nCacheLength = (aCache) ? aCache.length : 0; - var bMatchContains = this.queryMatchContains; - - // If cache is enabled... - if((this.maxCacheEntries > 0) && aCache && (nCacheLength > 0)) { - this.cacheQueryEvent.fire(this, oParent, sQuery); - // If case is unimportant, normalize query now instead of in loops - if(!this.queryMatchCase) { - var sOrigQuery = sQuery; - sQuery = sQuery.toLowerCase(); - } - - // Loop through each cached element's query property... - for(var i = nCacheLength-1; i >= 0; i--) { - var resultObj = aCache[i]; - var aAllResultItems = resultObj.results; - // If case is unimportant, normalize match key for comparison - var matchKey = (!this.queryMatchCase) ? - encodeURIComponent(resultObj.query).toLowerCase(): - encodeURIComponent(resultObj.query); - - // If a cached match key exactly matches the query... - if(matchKey == sQuery) { - // Stash all result objects into aResult[] and stop looping through the cache. - bMatchFound = true; - aResults = aAllResultItems; - - // The matching cache element was not the most recent, - // so now we need to refresh the cache. - if(i != nCacheLength-1) { - // Remove element from its original location - aCache.splice(i,1); - // Add element as newest - this._addCacheElem(resultObj); - } - break; - } - // Else if this query is not an exact match and subset matching is enabled... - else if(this.queryMatchSubset) { - // Loop through substrings of each cached element's query property... - for(var j = sQuery.length-1; j >= 0 ; j--) { - var subQuery = sQuery.substr(0,j); - - // If a substring of a cached sQuery exactly matches the query... - if(matchKey == subQuery) { - bMatchFound = true; - - // Go through each cached result object to match against the query... - for(var k = aAllResultItems.length-1; k >= 0; k--) { - var aRecord = aAllResultItems[k]; - var sKeyIndex = (this.queryMatchCase) ? - encodeURIComponent(aRecord[0]).indexOf(sQuery): - encodeURIComponent(aRecord[0]).toLowerCase().indexOf(sQuery); - - // A STARTSWITH match is when the query is found at the beginning of the key string... - if((!bMatchContains && (sKeyIndex === 0)) || - // A CONTAINS match is when the query is found anywhere within the key string... - (bMatchContains && (sKeyIndex > -1))) { - // Stash a match into aResults[]. - aResults.unshift(aRecord); - } - } - - // Add the subset match result set object as the newest element to cache, - // and stop looping through the cache. - resultObj = {}; - resultObj.query = sQuery; - resultObj.results = aResults; - this._addCacheElem(resultObj); - break; - } - } - if(bMatchFound) { - break; - } - } - } - - // If there was a match, send along the results. - if(bMatchFound) { - this.getCachedResultsEvent.fire(this, oParent, sOrigQuery, aResults); - oCallbackFn(sOrigQuery, aResults, oParent); - } - } - return aResults; -}; - - -/****************************************************************************/ -/****************************************************************************/ -/****************************************************************************/ - -/** - * Implementation of YAHOO.widget.DataSource using XML HTTP requests that return - * query results. - * - * @class DS_XHR - * @extends YAHOO.widget.DataSource - * @requires connection - * @constructor - * @param sScriptURI {String} Absolute or relative URI to script that returns query - * results as JSON, XML, or delimited flat-file data. - * @param aSchema {String[]} Data schema definition of results. - * @param oConfigs {Object} (optional) Object literal of config params. - */ -YAHOO.widget.DS_XHR = function(sScriptURI, aSchema, oConfigs) { - // Set any config params passed in to override defaults - if(typeof oConfigs == "object") { - for(var sConfig in oConfigs) { - this[sConfig] = oConfigs[sConfig]; - } - } - - // Initialization sequence - if(!aSchema || (aSchema.constructor != Array)) { - YAHOO.log("Could not instantiate XHR DataSource due to invalid arguments", "error", this.toString()); - return; - } - else { - this.schema = aSchema; - } - this.scriptURI = sScriptURI; - this._init(); - YAHOO.log("XHR DataSource initialized","info",this.toString()); -}; - -YAHOO.widget.DS_XHR.prototype = new YAHOO.widget.DataSource(); - -///////////////////////////////////////////////////////////////////////////// -// -// Public constants -// -///////////////////////////////////////////////////////////////////////////// - -/** - * JSON data type. - * - * @property TYPE_JSON - * @type Number - * @static - * @final - */ -YAHOO.widget.DS_XHR.TYPE_JSON = 0; - -/** - * XML data type. - * - * @property TYPE_XML - * @type Number - * @static - * @final - */ -YAHOO.widget.DS_XHR.TYPE_XML = 1; - -/** - * Flat-file data type. - * - * @property TYPE_FLAT - * @type Number - * @static - * @final - */ -YAHOO.widget.DS_XHR.TYPE_FLAT = 2; - -/** - * Error message for XHR failure. - * - * @property ERROR_DATAXHR - * @type String - * @static - * @final - */ -YAHOO.widget.DS_XHR.ERROR_DATAXHR = "XHR response failed"; - -///////////////////////////////////////////////////////////////////////////// -// -// Public member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Alias to YUI Connection Manager. Allows implementers to specify their own - * subclasses of the YUI Connection Manager utility. - * - * @property connMgr - * @type Object - * @default YAHOO.util.Connect - */ -YAHOO.widget.DS_XHR.prototype.connMgr = YAHOO.util.Connect; - -/** - * Number of milliseconds the XHR connection will wait for a server response. A - * a value of zero indicates the XHR connection will wait forever. Any value - * greater than zero will use the Connection utility's Auto-Abort feature. - * - * @property connTimeout - * @type Number - * @default 0 - */ -YAHOO.widget.DS_XHR.prototype.connTimeout = 0; - -/** - * Absolute or relative URI to script that returns query results. For instance, - * queries will be sent to <scriptURI>?<scriptQueryParam>=userinput - * - * @property scriptURI - * @type String - */ -YAHOO.widget.DS_XHR.prototype.scriptURI = null; - -/** - * Query string parameter name sent to scriptURI. For instance, queries will be - * sent to <scriptURI>?<scriptQueryParam>=userinput - * - * @property scriptQueryParam - * @type String - * @default "query" - */ -YAHOO.widget.DS_XHR.prototype.scriptQueryParam = "query"; - -/** - * String of key/value pairs to append to requests made to scriptURI. Define - * this string when you want to send additional query parameters to your script. - * When defined, queries will be sent to - * <scriptURI>?<scriptQueryParam>=userinput&<scriptQueryAppend> - * - * @property scriptQueryAppend - * @type String - * @default "" - */ -YAHOO.widget.DS_XHR.prototype.scriptQueryAppend = ""; - -/** - * XHR response data type. Other types that may be defined are YAHOO.widget.DS_XHR.TYPE_XML - * and YAHOO.widget.DS_XHR.TYPE_FLAT. - * - * @property responseType - * @type String - * @default YAHOO.widget.DS_XHR.TYPE_JSON - */ -YAHOO.widget.DS_XHR.prototype.responseType = YAHOO.widget.DS_XHR.TYPE_JSON; - -/** - * String after which to strip results. If the results from the XHR are sent - * back as HTML, the gzip HTML comment appears at the end of the data and should - * be ignored. - * - * @property responseStripAfter - * @type String - * @default "\n<!-" - */ -YAHOO.widget.DS_XHR.prototype.responseStripAfter = "\n 0) { - sUri += "&" + this.scriptQueryAppend; - } - YAHOO.log("DataSource is querying URL " + sUri, "info", this.toString()); - var oResponse = null; - - var oSelf = this; - /* - * Sets up ajax request callback - * - * @param {object} oReq HTTPXMLRequest object - * @private - */ - var responseSuccess = function(oResp) { - // Response ID does not match last made request ID. - if(!oSelf._oConn || (oResp.tId != oSelf._oConn.tId)) { - oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); - YAHOO.log(YAHOO.widget.DataSource.ERROR_DATANULL, "error", this.toString()); - return; - } -//DEBUG -/*YAHOO.log(oResp.responseXML.getElementsByTagName("Result"),'warn'); -for(var foo in oResp) { - YAHOO.log(foo + ": "+oResp[foo],'warn'); -} -YAHOO.log('responseXML.xml: '+oResp.responseXML.xml,'warn');*/ - if(!isXML) { - oResp = oResp.responseText; - } - else { - oResp = oResp.responseXML; - } - if(oResp === null) { - oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); - YAHOO.log(YAHOO.widget.DataSource.ERROR_DATANULL, "error", oSelf.toString()); - return; - } - - var aResults = oSelf.parseResponse(sQuery, oResp, oParent); - var resultObj = {}; - resultObj.query = decodeURIComponent(sQuery); - resultObj.results = aResults; - if(aResults === null) { - oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATAPARSE); - YAHOO.log(YAHOO.widget.DataSource.ERROR_DATAPARSE, "error", oSelf.toString()); - aResults = []; - } - else { - oSelf.getResultsEvent.fire(oSelf, oParent, sQuery, aResults); - oSelf._addCacheElem(resultObj); - } - oCallbackFn(sQuery, aResults, oParent); - }; - - var responseFailure = function(oResp) { - oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DS_XHR.ERROR_DATAXHR); - YAHOO.log(YAHOO.widget.DS_XHR.ERROR_DATAXHR + ": " + oResp.statusText, "error", oSelf.toString()); - return; - }; - - var oCallback = { - success:responseSuccess, - failure:responseFailure - }; - - if(!isNaN(this.connTimeout) && this.connTimeout > 0) { - oCallback.timeout = this.connTimeout; - } - - if(this._oConn) { - this.connMgr.abort(this._oConn); - } - - oSelf._oConn = this.connMgr.asyncRequest("GET", sUri, oCallback, null); -}; - -/** - * Parses raw response data into an array of result objects. The result data key - * is always stashed in the [0] element of each result object. - * - * @method parseResponse - * @param sQuery {String} Query string. - * @param oResponse {Object} The raw response data to parse. - * @param oParent {Object} The object instance that has requested data. - * @returns {Object[]} Array of result objects. - */ -YAHOO.widget.DS_XHR.prototype.parseResponse = function(sQuery, oResponse, oParent) { - var aSchema = this.schema; - var aResults = []; - var bError = false; - - // Strip out comment at the end of results - var nEnd = ((this.responseStripAfter !== "") && (oResponse.indexOf)) ? - oResponse.indexOf(this.responseStripAfter) : -1; - if(nEnd != -1) { - oResponse = oResponse.substring(0,nEnd); - } - - switch (this.responseType) { - case YAHOO.widget.DS_XHR.TYPE_JSON: - var jsonList; - // Divert KHTML clients from JSON lib - if(window.JSON && (navigator.userAgent.toLowerCase().indexOf('khtml')== -1)) { - // Use the JSON utility if available - var jsonObjParsed = JSON.parse(oResponse); - if(!jsonObjParsed) { - bError = true; - break; - } - else { - try { - // eval is necessary here since aSchema[0] is of unknown depth - jsonList = eval("jsonObjParsed." + aSchema[0]); - } - catch(e) { - bError = true; - break; - } - } - } - else { - // Parse the JSON response as a string - try { - // Trim leading spaces - while (oResponse.substring(0,1) == " ") { - oResponse = oResponse.substring(1, oResponse.length); - } - - // Invalid JSON response - if(oResponse.indexOf("{") < 0) { - bError = true; - break; - } - - // Empty (but not invalid) JSON response - if(oResponse.indexOf("{}") === 0) { - break; - } - - // Turn the string into an object literal... - // ...eval is necessary here - var jsonObjRaw = eval("(" + oResponse + ")"); - if(!jsonObjRaw) { - bError = true; - break; - } - - // Grab the object member that contains an array of all reponses... - // ...eval is necessary here since aSchema[0] is of unknown depth - jsonList = eval("(jsonObjRaw." + aSchema[0]+")"); - } - catch(e) { - bError = true; - break; - } - } - - if(!jsonList) { - bError = true; - break; - } - - if(jsonList.constructor != Array) { - jsonList = [jsonList]; - } - - // Loop through the array of all responses... - for(var i = jsonList.length-1; i >= 0 ; i--) { - var aResultItem = []; - var jsonResult = jsonList[i]; - // ...and loop through each data field value of each response - for(var j = aSchema.length-1; j >= 1 ; j--) { - // ...and capture data into an array mapped according to the schema... - var dataFieldValue = jsonResult[aSchema[j]]; - if(!dataFieldValue) { - dataFieldValue = ""; - } - //YAHOO.log("data: " + i + " value:" +j+" = "+dataFieldValue,"debug",this.toString()); - aResultItem.unshift(dataFieldValue); - } - // If schema isn't well defined, pass along the entire result object - if(aResultItem.length == 1) { - aResultItem.push(jsonResult); - } - // Capture the array of data field values in an array of results - aResults.unshift(aResultItem); - } - break; - case YAHOO.widget.DS_XHR.TYPE_XML: - // Get the collection of results - var xmlList = oResponse.getElementsByTagName(aSchema[0]); - if(!xmlList) { - bError = true; - break; - } - // Loop through each result - for(var k = xmlList.length-1; k >= 0 ; k--) { - var result = xmlList.item(k); - //YAHOO.log("Result"+k+" is "+result.attributes.item(0).firstChild.nodeValue,"debug",this.toString()); - var aFieldSet = []; - // Loop through each data field in each result using the schema - for(var m = aSchema.length-1; m >= 1 ; m--) { - //YAHOO.log(aSchema[m]+" is "+result.attributes.getNamedItem(aSchema[m]).firstChild.nodeValue); - var sValue = null; - // Values may be held in an attribute... - var xmlAttr = result.attributes.getNamedItem(aSchema[m]); - if(xmlAttr) { - sValue = xmlAttr.value; - //YAHOO.log("Attr value is "+sValue,"debug",this.toString()); - } - // ...or in a node - else{ - var xmlNode = result.getElementsByTagName(aSchema[m]); - if(xmlNode && xmlNode.item(0) && xmlNode.item(0).firstChild) { - sValue = xmlNode.item(0).firstChild.nodeValue; - //YAHOO.log("Node value is "+sValue,"debug",this.toString()); - } - else { - sValue = ""; - //YAHOO.log("Value not found","debug",this.toString()); - } - } - // Capture the schema-mapped data field values into an array - aFieldSet.unshift(sValue); - } - // Capture each array of values into an array of results - aResults.unshift(aFieldSet); - } - break; - case YAHOO.widget.DS_XHR.TYPE_FLAT: - if(oResponse.length > 0) { - // Delete the last line delimiter at the end of the data if it exists - var newLength = oResponse.length-aSchema[0].length; - if(oResponse.substr(newLength) == aSchema[0]) { - oResponse = oResponse.substr(0, newLength); - } - var aRecords = oResponse.split(aSchema[0]); - for(var n = aRecords.length-1; n >= 0; n--) { - aResults[n] = aRecords[n].split(aSchema[1]); - } - } - break; - default: - break; - } - sQuery = null; - oResponse = null; - oParent = null; - if(bError) { - return null; - } - else { - return aResults; - } -}; - -///////////////////////////////////////////////////////////////////////////// -// -// Private member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * XHR connection object. - * - * @property _oConn - * @type Object - * @private - */ -YAHOO.widget.DS_XHR.prototype._oConn = null; - - -/****************************************************************************/ -/****************************************************************************/ -/****************************************************************************/ - -/** - * Implementation of YAHOO.widget.DataSource using a native Javascript function as - * its live data source. - * - * @class DS_JSFunction - * @constructor - * @extends YAHOO.widget.DataSource - * @param oFunction {HTMLFunction} In-memory Javascript function that returns query results as an array of objects. - * @param oConfigs {Object} (optional) Object literal of config params. - */ -YAHOO.widget.DS_JSFunction = function(oFunction, oConfigs) { - // Set any config params passed in to override defaults - if(typeof oConfigs == "object") { - for(var sConfig in oConfigs) { - this[sConfig] = oConfigs[sConfig]; - } - } - - // Initialization sequence - if(!oFunction || (oFunction.constructor != Function)) { - YAHOO.log("Could not instantiate JSFunction DataSource due to invalid arguments", "error", this.toString()); - return; - } - else { - this.dataFunction = oFunction; - this._init(); - YAHOO.log("JS Function DataSource initialized","info",this.toString()); - } -}; - -YAHOO.widget.DS_JSFunction.prototype = new YAHOO.widget.DataSource(); - -///////////////////////////////////////////////////////////////////////////// -// -// Public member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * In-memory Javascript function that returns query results. - * - * @property dataFunction - * @type HTMLFunction - */ -YAHOO.widget.DS_JSFunction.prototype.dataFunction = null; - -///////////////////////////////////////////////////////////////////////////// -// -// Public methods -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Queries the live data source defined by function for results. Results are - * passed back to a callback function. - * - * @method doQuery - * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. - * @param sQuery {String} Query string. - * @param oParent {Object} The object instance that has requested data. - */ -YAHOO.widget.DS_JSFunction.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { - var oFunction = this.dataFunction; - var aResults = []; - - aResults = oFunction(sQuery); - if(aResults === null) { - this.dataErrorEvent.fire(this, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); - YAHOO.log(YAHOO.widget.DataSource.ERROR_DATANULL, "error", this.toString()); - return; - } - - var resultObj = {}; - resultObj.query = decodeURIComponent(sQuery); - resultObj.results = aResults; - this._addCacheElem(resultObj); - - this.getResultsEvent.fire(this, oParent, sQuery, aResults); - oCallbackFn(sQuery, aResults, oParent); - return; -}; - -/****************************************************************************/ -/****************************************************************************/ -/****************************************************************************/ - -/** - * Implementation of YAHOO.widget.DataSource using a native Javascript array as - * its live data source. - * - * @class DS_JSArray - * @constructor - * @extends YAHOO.widget.DataSource - * @param aData {String[]} In-memory Javascript array of simple string data. - * @param oConfigs {Object} (optional) Object literal of config params. - */ -YAHOO.widget.DS_JSArray = function(aData, oConfigs) { - // Set any config params passed in to override defaults - if(typeof oConfigs == "object") { - for(var sConfig in oConfigs) { - this[sConfig] = oConfigs[sConfig]; - } - } - - // Initialization sequence - if(!aData || (aData.constructor != Array)) { - YAHOO.log("Could not instantiate JSArray DataSource due to invalid arguments", "error", this.toString()); - return; - } - else { - this.data = aData; - this._init(); - YAHOO.log("JS Array DataSource initialized","info",this.toString()); - } -}; - -YAHOO.widget.DS_JSArray.prototype = new YAHOO.widget.DataSource(); - -///////////////////////////////////////////////////////////////////////////// -// -// Public member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * In-memory Javascript array of strings. - * - * @property data - * @type Array - */ -YAHOO.widget.DS_JSArray.prototype.data = null; - -///////////////////////////////////////////////////////////////////////////// -// -// Public methods -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Queries the live data source defined by data for results. Results are passed - * back to a callback function. - * - * @method doQuery - * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. - * @param sQuery {String} Query string. - * @param oParent {Object} The object instance that has requested data. - */ -YAHOO.widget.DS_JSArray.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { - var aData = this.data; // the array - var aResults = []; // container for results - var bMatchFound = false; - var bMatchContains = this.queryMatchContains; - if(sQuery) { - if(!this.queryMatchCase) { - sQuery = sQuery.toLowerCase(); - } - - // Loop through each element of the array... - // which can be a string or an array of strings - for(var i = aData.length-1; i >= 0; i--) { - var aDataset = []; - - if(aData[i]) { - if(aData[i].constructor == String) { - aDataset[0] = aData[i]; - } - else if(aData[i].constructor == Array) { - aDataset = aData[i]; - } - } - - if(aDataset[0] && (aDataset[0].constructor == String)) { - var sKeyIndex = (this.queryMatchCase) ? - encodeURIComponent(aDataset[0]).indexOf(sQuery): - encodeURIComponent(aDataset[0]).toLowerCase().indexOf(sQuery); - - // A STARTSWITH match is when the query is found at the beginning of the key string... - if((!bMatchContains && (sKeyIndex === 0)) || - // A CONTAINS match is when the query is found anywhere within the key string... - (bMatchContains && (sKeyIndex > -1))) { - // Stash a match into aResults[]. - aResults.unshift(aDataset); - } - } - } - } - - this.getResultsEvent.fire(this, oParent, sQuery, aResults); - oCallbackFn(sQuery, aResults, oParent); -}; +/****************************************************************************/ +/****************************************************************************/ +/****************************************************************************/ + +/** + * The DataSource classes manages sending a request and returning response from a live + * database. Supported data include local JavaScript arrays and objects and databases + * accessible via XHR connections. Supported response formats include JavaScript arrays, + * JSON, XML, and flat-file textual data. + * + * @class DataSource + * @constructor + */ +YAHOO.widget.DataSource = function() { + /* abstract class */ +}; + + +///////////////////////////////////////////////////////////////////////////// +// +// Public constants +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Error message for null data responses. + * + * @property ERROR_DATANULL + * @type String + * @static + * @final + */ +YAHOO.widget.DataSource.ERROR_DATANULL = "Response data was null"; + +/** + * Error message for data responses with parsing errors. + * + * @property ERROR_DATAPARSE + * @type String + * @static + * @final + */ +YAHOO.widget.DataSource.ERROR_DATAPARSE = "Response data could not be parsed"; + + +///////////////////////////////////////////////////////////////////////////// +// +// Public member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Max size of the local cache. Set to 0 to turn off caching. Caching is + * useful to reduce the number of server connections. Recommended only for data + * sources that return comprehensive results for queries or when stale data is + * not an issue. + * + * @property maxCacheEntries + * @type Number + * @default 15 + */ +YAHOO.widget.DataSource.prototype.maxCacheEntries = 15; + +/** + * Use this to equate cache matching with the type of matching done by your live + * data source. If caching is on and queryMatchContains is true, the cache + * returns results that "contain" the query string. By default, + * queryMatchContains is set to false, meaning the cache only returns results + * that "start with" the query string. + * + * @property queryMatchContains + * @type Boolean + * @default false + */ +YAHOO.widget.DataSource.prototype.queryMatchContains = false; + +/** + * Enables query subset matching. If caching is on and queryMatchSubset is + * true, substrings of queries will return matching cached results. For + * instance, if the first query is for "abc" susequent queries that start with + * "abc", like "abcd", will be queried against the cache, and not the live data + * source. Recommended only for DataSources that return comprehensive results + * for queries with very few characters. + * + * @property queryMatchSubset + * @type Boolean + * @default false + * + */ +YAHOO.widget.DataSource.prototype.queryMatchSubset = false; + +/** + * Enables query case-sensitivity matching. If caching is on and + * queryMatchCase is true, queries will only return results for case-sensitive + * matches. + * + * @property queryMatchCase + * @type Boolean + * @default false + */ +YAHOO.widget.DataSource.prototype.queryMatchCase = false; + + +///////////////////////////////////////////////////////////////////////////// +// +// Public methods +// +///////////////////////////////////////////////////////////////////////////// + + /** + * Public accessor to the unique name of the DataSource instance. + * + * @method toString + * @return {String} Unique name of the DataSource instance + */ +YAHOO.widget.DataSource.prototype.toString = function() { + return "DataSource " + this._sName; +}; + +/** + * Retrieves query results, first checking the local cache, then making the + * query request to the live data source as defined by the function doQuery. + * + * @method getResults + * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. + * @param sQuery {String} Query string. + * @param oParent {Object} The object instance that has requested data. + */ +YAHOO.widget.DataSource.prototype.getResults = function(oCallbackFn, sQuery, oParent) { + + // First look in cache + var aResults = this._doQueryCache(oCallbackFn,sQuery,oParent); + + // Not in cache, so get results from server + if(aResults.length === 0) { + this.queryEvent.fire(this, oParent, sQuery); + this.doQuery(oCallbackFn, sQuery, oParent); + } +}; + +/** + * Abstract method implemented by subclasses to make a query to the live data + * source. Must call the callback function with the response returned from the + * query. Populates cache (if enabled). + * + * @method doQuery + * @param oCallbackFn {HTMLFunction} Callback function implemented by oParent to which to return results. + * @param sQuery {String} Query string. + * @param oParent {Object} The object instance that has requested data. + */ +YAHOO.widget.DataSource.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { + /* override this */ +}; + +/** + * Flushes cache. + * + * @method flushCache + */ +YAHOO.widget.DataSource.prototype.flushCache = function() { + if(this._aCache) { + this._aCache = []; + } + if(this._aCacheHelper) { + this._aCacheHelper = []; + } + this.cacheFlushEvent.fire(this); +}; + +///////////////////////////////////////////////////////////////////////////// +// +// Public events +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Fired when a query is made to the live data source. + * + * @event queryEvent + * @param oSelf {Object} The DataSource instance. + * @param oParent {Object} The requesting object. + * @param sQuery {String} The query string. + */ +YAHOO.widget.DataSource.prototype.queryEvent = null; + +/** + * Fired when a query is made to the local cache. + * + * @event cacheQueryEvent + * @param oSelf {Object} The DataSource instance. + * @param oParent {Object} The requesting object. + * @param sQuery {String} The query string. + */ +YAHOO.widget.DataSource.prototype.cacheQueryEvent = null; + +/** + * Fired when data is retrieved from the live data source. + * + * @event getResultsEvent + * @param oSelf {Object} The DataSource instance. + * @param oParent {Object} The requesting object. + * @param sQuery {String} The query string. + * @param aResults {Object[]} Array of result objects. + */ +YAHOO.widget.DataSource.prototype.getResultsEvent = null; + +/** + * Fired when data is retrieved from the local cache. + * + * @event getCachedResultsEvent + * @param oSelf {Object} The DataSource instance. + * @param oParent {Object} The requesting object. + * @param sQuery {String} The query string. + * @param aResults {Object[]} Array of result objects. + */ +YAHOO.widget.DataSource.prototype.getCachedResultsEvent = null; + +/** + * Fired when an error is encountered with the live data source. + * + * @event dataErrorEvent + * @param oSelf {Object} The DataSource instance. + * @param oParent {Object} The requesting object. + * @param sQuery {String} The query string. + * @param sMsg {String} Error message string + */ +YAHOO.widget.DataSource.prototype.dataErrorEvent = null; + +/** + * Fired when the local cache is flushed. + * + * @event cacheFlushEvent + * @param oSelf {Object} The DataSource instance + */ +YAHOO.widget.DataSource.prototype.cacheFlushEvent = null; + +///////////////////////////////////////////////////////////////////////////// +// +// Private member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Internal class variable to index multiple DataSource instances. + * + * @property _nIndex + * @type Number + * @private + * @static + */ +YAHOO.widget.DataSource._nIndex = 0; + +/** + * Name of DataSource instance. + * + * @property _sName + * @type String + * @private + */ +YAHOO.widget.DataSource.prototype._sName = null; + +/** + * Local cache of data result objects indexed chronologically. + * + * @property _aCache + * @type Object[] + * @private + */ +YAHOO.widget.DataSource.prototype._aCache = null; + + +///////////////////////////////////////////////////////////////////////////// +// +// Private methods +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Initializes DataSource instance. + * + * @method _init + * @private + */ +YAHOO.widget.DataSource.prototype._init = function() { + // Validate and initialize public configs + var maxCacheEntries = this.maxCacheEntries; + if(isNaN(maxCacheEntries) || (maxCacheEntries < 0)) { + maxCacheEntries = 0; + } + // Initialize local cache + if(maxCacheEntries > 0 && !this._aCache) { + this._aCache = []; + } + + this._sName = "instance" + YAHOO.widget.DataSource._nIndex; + YAHOO.widget.DataSource._nIndex++; + + this.queryEvent = new YAHOO.util.CustomEvent("query", this); + this.cacheQueryEvent = new YAHOO.util.CustomEvent("cacheQuery", this); + this.getResultsEvent = new YAHOO.util.CustomEvent("getResults", this); + this.getCachedResultsEvent = new YAHOO.util.CustomEvent("getCachedResults", this); + this.dataErrorEvent = new YAHOO.util.CustomEvent("dataError", this); + this.cacheFlushEvent = new YAHOO.util.CustomEvent("cacheFlush", this); +}; + +/** + * Adds a result object to the local cache, evicting the oldest element if the + * cache is full. Newer items will have higher indexes, the oldest item will have + * index of 0. + * + * @method _addCacheElem + * @param oResult {Object} Data result object, including array of results. + * @private + */ +YAHOO.widget.DataSource.prototype._addCacheElem = function(oResult) { + var aCache = this._aCache; + // Don't add if anything important is missing. + if(!aCache || !oResult || !oResult.query || !oResult.results) { + return; + } + + // If the cache is full, make room by removing from index=0 + if(aCache.length >= this.maxCacheEntries) { + aCache.shift(); + } + + // Add to cache, at the end of the array + aCache.push(oResult); +}; + +/** + * Queries the local cache for results. If query has been cached, the callback + * function is called with the results, and the cached is refreshed so that it + * is now the newest element. + * + * @method _doQueryCache + * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. + * @param sQuery {String} Query string. + * @param oParent {Object} The object instance that has requested data. + * @return aResults {Object[]} Array of results from local cache if found, otherwise null. + * @private + */ +YAHOO.widget.DataSource.prototype._doQueryCache = function(oCallbackFn, sQuery, oParent) { + var aResults = []; + var bMatchFound = false; + var aCache = this._aCache; + var nCacheLength = (aCache) ? aCache.length : 0; + var bMatchContains = this.queryMatchContains; + + // If cache is enabled... + if((this.maxCacheEntries > 0) && aCache && (nCacheLength > 0)) { + this.cacheQueryEvent.fire(this, oParent, sQuery); + // If case is unimportant, normalize query now instead of in loops + if(!this.queryMatchCase) { + var sOrigQuery = sQuery; + sQuery = sQuery.toLowerCase(); + } + + // Loop through each cached element's query property... + for(var i = nCacheLength-1; i >= 0; i--) { + var resultObj = aCache[i]; + var aAllResultItems = resultObj.results; + // If case is unimportant, normalize match key for comparison + var matchKey = (!this.queryMatchCase) ? + encodeURIComponent(resultObj.query).toLowerCase(): + encodeURIComponent(resultObj.query); + + // If a cached match key exactly matches the query... + if(matchKey == sQuery) { + // Stash all result objects into aResult[] and stop looping through the cache. + bMatchFound = true; + aResults = aAllResultItems; + + // The matching cache element was not the most recent, + // so now we need to refresh the cache. + if(i != nCacheLength-1) { + // Remove element from its original location + aCache.splice(i,1); + // Add element as newest + this._addCacheElem(resultObj); + } + break; + } + // Else if this query is not an exact match and subset matching is enabled... + else if(this.queryMatchSubset) { + // Loop through substrings of each cached element's query property... + for(var j = sQuery.length-1; j >= 0 ; j--) { + var subQuery = sQuery.substr(0,j); + + // If a substring of a cached sQuery exactly matches the query... + if(matchKey == subQuery) { + bMatchFound = true; + + // Go through each cached result object to match against the query... + for(var k = aAllResultItems.length-1; k >= 0; k--) { + var aRecord = aAllResultItems[k]; + var sKeyIndex = (this.queryMatchCase) ? + encodeURIComponent(aRecord[0]).indexOf(sQuery): + encodeURIComponent(aRecord[0]).toLowerCase().indexOf(sQuery); + + // A STARTSWITH match is when the query is found at the beginning of the key string... + if((!bMatchContains && (sKeyIndex === 0)) || + // A CONTAINS match is when the query is found anywhere within the key string... + (bMatchContains && (sKeyIndex > -1))) { + // Stash a match into aResults[]. + aResults.unshift(aRecord); + } + } + + // Add the subset match result set object as the newest element to cache, + // and stop looping through the cache. + resultObj = {}; + resultObj.query = sQuery; + resultObj.results = aResults; + this._addCacheElem(resultObj); + break; + } + } + if(bMatchFound) { + break; + } + } + } + + // If there was a match, send along the results. + if(bMatchFound) { + this.getCachedResultsEvent.fire(this, oParent, sOrigQuery, aResults); + oCallbackFn(sOrigQuery, aResults, oParent); + } + } + return aResults; +}; + + +/****************************************************************************/ +/****************************************************************************/ +/****************************************************************************/ + +/** + * Implementation of YAHOO.widget.DataSource using XML HTTP requests that return + * query results. + * + * @class DS_XHR + * @extends YAHOO.widget.DataSource + * @requires connection + * @constructor + * @param sScriptURI {String} Absolute or relative URI to script that returns query + * results as JSON, XML, or delimited flat-file data. + * @param aSchema {String[]} Data schema definition of results. + * @param oConfigs {Object} (optional) Object literal of config params. + */ +YAHOO.widget.DS_XHR = function(sScriptURI, aSchema, oConfigs) { + // Set any config params passed in to override defaults + if(typeof oConfigs == "object") { + for(var sConfig in oConfigs) { + this[sConfig] = oConfigs[sConfig]; + } + } + + // Initialization sequence + if(!aSchema || (aSchema.constructor != Array)) { + YAHOO.log("Could not instantiate XHR DataSource due to invalid arguments", "error", this.toString()); + return; + } + else { + this.schema = aSchema; + } + this.scriptURI = sScriptURI; + this._init(); + YAHOO.log("XHR DataSource initialized","info",this.toString()); +}; + +YAHOO.widget.DS_XHR.prototype = new YAHOO.widget.DataSource(); + +///////////////////////////////////////////////////////////////////////////// +// +// Public constants +// +///////////////////////////////////////////////////////////////////////////// + +/** + * JSON data type. + * + * @property TYPE_JSON + * @type Number + * @static + * @final + */ +YAHOO.widget.DS_XHR.TYPE_JSON = 0; + +/** + * XML data type. + * + * @property TYPE_XML + * @type Number + * @static + * @final + */ +YAHOO.widget.DS_XHR.TYPE_XML = 1; + +/** + * Flat-file data type. + * + * @property TYPE_FLAT + * @type Number + * @static + * @final + */ +YAHOO.widget.DS_XHR.TYPE_FLAT = 2; + +/** + * Error message for XHR failure. + * + * @property ERROR_DATAXHR + * @type String + * @static + * @final + */ +YAHOO.widget.DS_XHR.ERROR_DATAXHR = "XHR response failed"; + +///////////////////////////////////////////////////////////////////////////// +// +// Public member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Alias to YUI Connection Manager. Allows implementers to specify their own + * subclasses of the YUI Connection Manager utility. + * + * @property connMgr + * @type Object + * @default YAHOO.util.Connect + */ +YAHOO.widget.DS_XHR.prototype.connMgr = YAHOO.util.Connect; + +/** + * Number of milliseconds the XHR connection will wait for a server response. A + * a value of zero indicates the XHR connection will wait forever. Any value + * greater than zero will use the Connection utility's Auto-Abort feature. + * + * @property connTimeout + * @type Number + * @default 0 + */ +YAHOO.widget.DS_XHR.prototype.connTimeout = 0; + +/** + * Absolute or relative URI to script that returns query results. For instance, + * queries will be sent to <scriptURI>?<scriptQueryParam>=userinput + * + * @property scriptURI + * @type String + */ +YAHOO.widget.DS_XHR.prototype.scriptURI = null; + +/** + * Query string parameter name sent to scriptURI. For instance, queries will be + * sent to <scriptURI>?<scriptQueryParam>=userinput + * + * @property scriptQueryParam + * @type String + * @default "query" + */ +YAHOO.widget.DS_XHR.prototype.scriptQueryParam = "query"; + +/** + * String of key/value pairs to append to requests made to scriptURI. Define + * this string when you want to send additional query parameters to your script. + * When defined, queries will be sent to + * <scriptURI>?<scriptQueryParam>=userinput&<scriptQueryAppend> + * + * @property scriptQueryAppend + * @type String + * @default "" + */ +YAHOO.widget.DS_XHR.prototype.scriptQueryAppend = ""; + +/** + * XHR response data type. Other types that may be defined are YAHOO.widget.DS_XHR.TYPE_XML + * and YAHOO.widget.DS_XHR.TYPE_FLAT. + * + * @property responseType + * @type String + * @default YAHOO.widget.DS_XHR.TYPE_JSON + */ +YAHOO.widget.DS_XHR.prototype.responseType = YAHOO.widget.DS_XHR.TYPE_JSON; + +/** + * String after which to strip results. If the results from the XHR are sent + * back as HTML, the gzip HTML comment appears at the end of the data and should + * be ignored. + * + * @property responseStripAfter + * @type String + * @default "\n<!-" + */ +YAHOO.widget.DS_XHR.prototype.responseStripAfter = "\n 0) { + sUri += "&" + this.scriptQueryAppend; + } + YAHOO.log("DataSource is querying URL " + sUri, "info", this.toString()); + var oResponse = null; + + var oSelf = this; + /* + * Sets up ajax request callback + * + * @param {object} oReq HTTPXMLRequest object + * @private + */ + var responseSuccess = function(oResp) { + // Response ID does not match last made request ID. + if(!oSelf._oConn || (oResp.tId != oSelf._oConn.tId)) { + oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); + YAHOO.log(YAHOO.widget.DataSource.ERROR_DATANULL, "error", this.toString()); + return; + } +//DEBUG +/*YAHOO.log(oResp.responseXML.getElementsByTagName("Result"),'warn'); +for(var foo in oResp) { + YAHOO.log(foo + ": "+oResp[foo],'warn'); +} +YAHOO.log('responseXML.xml: '+oResp.responseXML.xml,'warn');*/ + if(!isXML) { + oResp = oResp.responseText; + } + else { + oResp = oResp.responseXML; + } + if(oResp === null) { + oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); + YAHOO.log(YAHOO.widget.DataSource.ERROR_DATANULL, "error", oSelf.toString()); + return; + } + + var aResults = oSelf.parseResponse(sQuery, oResp, oParent); + var resultObj = {}; + resultObj.query = decodeURIComponent(sQuery); + resultObj.results = aResults; + if(aResults === null) { + oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATAPARSE); + YAHOO.log(YAHOO.widget.DataSource.ERROR_DATAPARSE, "error", oSelf.toString()); + aResults = []; + } + else { + oSelf.getResultsEvent.fire(oSelf, oParent, sQuery, aResults); + oSelf._addCacheElem(resultObj); + } + oCallbackFn(sQuery, aResults, oParent); + }; + + var responseFailure = function(oResp) { + oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DS_XHR.ERROR_DATAXHR); + YAHOO.log(YAHOO.widget.DS_XHR.ERROR_DATAXHR + ": " + oResp.statusText, "error", oSelf.toString()); + return; + }; + + var oCallback = { + success:responseSuccess, + failure:responseFailure + }; + + if(!isNaN(this.connTimeout) && this.connTimeout > 0) { + oCallback.timeout = this.connTimeout; + } + + if(this._oConn) { + this.connMgr.abort(this._oConn); + } + + oSelf._oConn = this.connMgr.asyncRequest("GET", sUri, oCallback, null); +}; + +/** + * Parses raw response data into an array of result objects. The result data key + * is always stashed in the [0] element of each result object. + * + * @method parseResponse + * @param sQuery {String} Query string. + * @param oResponse {Object} The raw response data to parse. + * @param oParent {Object} The object instance that has requested data. + * @returns {Object[]} Array of result objects. + */ +YAHOO.widget.DS_XHR.prototype.parseResponse = function(sQuery, oResponse, oParent) { + var aSchema = this.schema; + var aResults = []; + var bError = false; + + // Strip out comment at the end of results + var nEnd = ((this.responseStripAfter !== "") && (oResponse.indexOf)) ? + oResponse.indexOf(this.responseStripAfter) : -1; + if(nEnd != -1) { + oResponse = oResponse.substring(0,nEnd); + } + + switch (this.responseType) { + case YAHOO.widget.DS_XHR.TYPE_JSON: + var jsonList; + // Divert KHTML clients from JSON lib + if(window.JSON && (navigator.userAgent.toLowerCase().indexOf('khtml')== -1)) { + // Use the JSON utility if available + var jsonObjParsed = JSON.parse(oResponse); + if(!jsonObjParsed) { + bError = true; + break; + } + else { + try { + // eval is necessary here since aSchema[0] is of unknown depth + jsonList = eval("jsonObjParsed." + aSchema[0]); + } + catch(e) { + bError = true; + break; + } + } + } + else { + // Parse the JSON response as a string + try { + // Trim leading spaces + while (oResponse.substring(0,1) == " ") { + oResponse = oResponse.substring(1, oResponse.length); + } + + // Invalid JSON response + if(oResponse.indexOf("{") < 0) { + bError = true; + break; + } + + // Empty (but not invalid) JSON response + if(oResponse.indexOf("{}") === 0) { + break; + } + + // Turn the string into an object literal... + // ...eval is necessary here + var jsonObjRaw = eval("(" + oResponse + ")"); + if(!jsonObjRaw) { + bError = true; + break; + } + + // Grab the object member that contains an array of all reponses... + // ...eval is necessary here since aSchema[0] is of unknown depth + jsonList = eval("(jsonObjRaw." + aSchema[0]+")"); + } + catch(e) { + bError = true; + break; + } + } + + if(!jsonList) { + bError = true; + break; + } + + if(jsonList.constructor != Array) { + jsonList = [jsonList]; + } + + // Loop through the array of all responses... + for(var i = jsonList.length-1; i >= 0 ; i--) { + var aResultItem = []; + var jsonResult = jsonList[i]; + // ...and loop through each data field value of each response + for(var j = aSchema.length-1; j >= 1 ; j--) { + // ...and capture data into an array mapped according to the schema... + var dataFieldValue = jsonResult[aSchema[j]]; + if(!dataFieldValue) { + dataFieldValue = ""; + } + //YAHOO.log("data: " + i + " value:" +j+" = "+dataFieldValue,"debug",this.toString()); + aResultItem.unshift(dataFieldValue); + } + // If schema isn't well defined, pass along the entire result object + if(aResultItem.length == 1) { + aResultItem.push(jsonResult); + } + // Capture the array of data field values in an array of results + aResults.unshift(aResultItem); + } + break; + case YAHOO.widget.DS_XHR.TYPE_XML: + // Get the collection of results + var xmlList = oResponse.getElementsByTagName(aSchema[0]); + if(!xmlList) { + bError = true; + break; + } + // Loop through each result + for(var k = xmlList.length-1; k >= 0 ; k--) { + var result = xmlList.item(k); + //YAHOO.log("Result"+k+" is "+result.attributes.item(0).firstChild.nodeValue,"debug",this.toString()); + var aFieldSet = []; + // Loop through each data field in each result using the schema + for(var m = aSchema.length-1; m >= 1 ; m--) { + //YAHOO.log(aSchema[m]+" is "+result.attributes.getNamedItem(aSchema[m]).firstChild.nodeValue); + var sValue = null; + // Values may be held in an attribute... + var xmlAttr = result.attributes.getNamedItem(aSchema[m]); + if(xmlAttr) { + sValue = xmlAttr.value; + //YAHOO.log("Attr value is "+sValue,"debug",this.toString()); + } + // ...or in a node + else{ + var xmlNode = result.getElementsByTagName(aSchema[m]); + if(xmlNode && xmlNode.item(0) && xmlNode.item(0).firstChild) { + sValue = xmlNode.item(0).firstChild.nodeValue; + //YAHOO.log("Node value is "+sValue,"debug",this.toString()); + } + else { + sValue = ""; + //YAHOO.log("Value not found","debug",this.toString()); + } + } + // Capture the schema-mapped data field values into an array + aFieldSet.unshift(sValue); + } + // Capture each array of values into an array of results + aResults.unshift(aFieldSet); + } + break; + case YAHOO.widget.DS_XHR.TYPE_FLAT: + if(oResponse.length > 0) { + // Delete the last line delimiter at the end of the data if it exists + var newLength = oResponse.length-aSchema[0].length; + if(oResponse.substr(newLength) == aSchema[0]) { + oResponse = oResponse.substr(0, newLength); + } + var aRecords = oResponse.split(aSchema[0]); + for(var n = aRecords.length-1; n >= 0; n--) { + aResults[n] = aRecords[n].split(aSchema[1]); + } + } + break; + default: + break; + } + sQuery = null; + oResponse = null; + oParent = null; + if(bError) { + return null; + } + else { + return aResults; + } +}; + +///////////////////////////////////////////////////////////////////////////// +// +// Private member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * XHR connection object. + * + * @property _oConn + * @type Object + * @private + */ +YAHOO.widget.DS_XHR.prototype._oConn = null; + + +/****************************************************************************/ +/****************************************************************************/ +/****************************************************************************/ + +/** + * Implementation of YAHOO.widget.DataSource using a native Javascript function as + * its live data source. + * + * @class DS_JSFunction + * @constructor + * @extends YAHOO.widget.DataSource + * @param oFunction {HTMLFunction} In-memory Javascript function that returns query results as an array of objects. + * @param oConfigs {Object} (optional) Object literal of config params. + */ +YAHOO.widget.DS_JSFunction = function(oFunction, oConfigs) { + // Set any config params passed in to override defaults + if(typeof oConfigs == "object") { + for(var sConfig in oConfigs) { + this[sConfig] = oConfigs[sConfig]; + } + } + + // Initialization sequence + if(!oFunction || (oFunction.constructor != Function)) { + YAHOO.log("Could not instantiate JSFunction DataSource due to invalid arguments", "error", this.toString()); + return; + } + else { + this.dataFunction = oFunction; + this._init(); + YAHOO.log("JS Function DataSource initialized","info",this.toString()); + } +}; + +YAHOO.widget.DS_JSFunction.prototype = new YAHOO.widget.DataSource(); + +///////////////////////////////////////////////////////////////////////////// +// +// Public member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * In-memory Javascript function that returns query results. + * + * @property dataFunction + * @type HTMLFunction + */ +YAHOO.widget.DS_JSFunction.prototype.dataFunction = null; + +///////////////////////////////////////////////////////////////////////////// +// +// Public methods +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Queries the live data source defined by function for results. Results are + * passed back to a callback function. + * + * @method doQuery + * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. + * @param sQuery {String} Query string. + * @param oParent {Object} The object instance that has requested data. + */ +YAHOO.widget.DS_JSFunction.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { + var oFunction = this.dataFunction; + var aResults = []; + + aResults = oFunction(sQuery); + if(aResults === null) { + this.dataErrorEvent.fire(this, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); + YAHOO.log(YAHOO.widget.DataSource.ERROR_DATANULL, "error", this.toString()); + return; + } + + var resultObj = {}; + resultObj.query = decodeURIComponent(sQuery); + resultObj.results = aResults; + this._addCacheElem(resultObj); + + this.getResultsEvent.fire(this, oParent, sQuery, aResults); + oCallbackFn(sQuery, aResults, oParent); + return; +}; + +/****************************************************************************/ +/****************************************************************************/ +/****************************************************************************/ + +/** + * Implementation of YAHOO.widget.DataSource using a native Javascript array as + * its live data source. + * + * @class DS_JSArray + * @constructor + * @extends YAHOO.widget.DataSource + * @param aData {String[]} In-memory Javascript array of simple string data. + * @param oConfigs {Object} (optional) Object literal of config params. + */ +YAHOO.widget.DS_JSArray = function(aData, oConfigs) { + // Set any config params passed in to override defaults + if(typeof oConfigs == "object") { + for(var sConfig in oConfigs) { + this[sConfig] = oConfigs[sConfig]; + } + } + + // Initialization sequence + if(!aData || (aData.constructor != Array)) { + YAHOO.log("Could not instantiate JSArray DataSource due to invalid arguments", "error", this.toString()); + return; + } + else { + this.data = aData; + this._init(); + YAHOO.log("JS Array DataSource initialized","info",this.toString()); + } +}; + +YAHOO.widget.DS_JSArray.prototype = new YAHOO.widget.DataSource(); + +///////////////////////////////////////////////////////////////////////////// +// +// Public member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * In-memory Javascript array of strings. + * + * @property data + * @type Array + */ +YAHOO.widget.DS_JSArray.prototype.data = null; + +///////////////////////////////////////////////////////////////////////////// +// +// Public methods +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Queries the live data source defined by data for results. Results are passed + * back to a callback function. + * + * @method doQuery + * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. + * @param sQuery {String} Query string. + * @param oParent {Object} The object instance that has requested data. + */ +YAHOO.widget.DS_JSArray.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { + var aData = this.data; // the array + var aResults = []; // container for results + var bMatchFound = false; + var bMatchContains = this.queryMatchContains; + if(sQuery) { + if(!this.queryMatchCase) { + sQuery = sQuery.toLowerCase(); + } + + // Loop through each element of the array... + // which can be a string or an array of strings + for(var i = aData.length-1; i >= 0; i--) { + var aDataset = []; + + if(aData[i]) { + if(aData[i].constructor == String) { + aDataset[0] = aData[i]; + } + else if(aData[i].constructor == Array) { + aDataset = aData[i]; + } + } + + if(aDataset[0] && (aDataset[0].constructor == String)) { + var sKeyIndex = (this.queryMatchCase) ? + encodeURIComponent(aDataset[0]).indexOf(sQuery): + encodeURIComponent(aDataset[0]).toLowerCase().indexOf(sQuery); + + // A STARTSWITH match is when the query is found at the beginning of the key string... + if((!bMatchContains && (sKeyIndex === 0)) || + // A CONTAINS match is when the query is found anywhere within the key string... + (bMatchContains && (sKeyIndex > -1))) { + // Stash a match into aResults[]. + aResults.unshift(aDataset); + } + } + } + } + + this.getResultsEvent.fire(this, oParent, sQuery, aResults); + oCallbackFn(sQuery, aResults, oParent); +}; diff --git a/lib/yui/autocomplete/autocomplete-min.js b/lib/yui/autocomplete/autocomplete-min.js index 4d03d7dc74..91bba0312c 100755 --- a/lib/yui/autocomplete/autocomplete-min.js +++ b/lib/yui/autocomplete/autocomplete-min.js @@ -1,178 +1,183 @@ -/* Copyright (c) 2006, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.txt version: 0.12.1 */ - -YAHOO.widget.AutoComplete=function(elInput,elContainer,oDataSource,oConfigs){if(elInput&&elContainer&&oDataSource){if(oDataSource&&(oDataSource instanceof YAHOO.widget.DataSource)){this.dataSource=oDataSource;} -else{return;} -if(YAHOO.util.Dom.inDocument(elInput)){if(typeof elInput=="string"){this._sName="instance"+YAHOO.widget.AutoComplete._nIndex+" "+elInput;this._oTextbox=document.getElementById(elInput);} -else{this._sName=(elInput.id)?"instance"+YAHOO.widget.AutoComplete._nIndex+" "+elInput.id:"instance"+YAHOO.widget.AutoComplete._nIndex;this._oTextbox=elInput;}} -else{return;} -if(YAHOO.util.Dom.inDocument(elContainer)){if(typeof elContainer=="string"){this._oContainer=document.getElementById(elContainer);} -else{this._oContainer=elContainer;} -if(this._oContainer.style.display=="none"){}} -else{return;} -if(typeof oConfigs=="object"){for(var sConfig in oConfigs){if(sConfig){this[sConfig]=oConfigs[sConfig];}}} -this._initContainer();this._initProps();this._initList();this._initContainerHelpers();var oSelf=this;var oTextbox=this._oTextbox;var oContent=this._oContainer._oContent;YAHOO.util.Event.addListener(oTextbox,"keyup",oSelf._onTextboxKeyUp,oSelf);YAHOO.util.Event.addListener(oTextbox,"keydown",oSelf._onTextboxKeyDown,oSelf);YAHOO.util.Event.addListener(oTextbox,"focus",oSelf._onTextboxFocus,oSelf);YAHOO.util.Event.addListener(oTextbox,"blur",oSelf._onTextboxBlur,oSelf);YAHOO.util.Event.addListener(oContent,"mouseover",oSelf._onContainerMouseover,oSelf);YAHOO.util.Event.addListener(oContent,"mouseout",oSelf._onContainerMouseout,oSelf);YAHOO.util.Event.addListener(oContent,"scroll",oSelf._onContainerScroll,oSelf);YAHOO.util.Event.addListener(oContent,"resize",oSelf._onContainerResize,oSelf);if(oTextbox.form){YAHOO.util.Event.addListener(oTextbox.form,"submit",oSelf._onFormSubmit,oSelf);} -YAHOO.util.Event.addListener(oTextbox,"keypress",oSelf._onTextboxKeyPress,oSelf);this.textboxFocusEvent=new YAHOO.util.CustomEvent("textboxFocus",this);this.textboxKeyEvent=new YAHOO.util.CustomEvent("textboxKey",this);this.dataRequestEvent=new YAHOO.util.CustomEvent("dataRequest",this);this.dataReturnEvent=new YAHOO.util.CustomEvent("dataReturn",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.containerExpandEvent=new YAHOO.util.CustomEvent("containerExpand",this);this.typeAheadEvent=new YAHOO.util.CustomEvent("typeAhead",this);this.itemMouseOverEvent=new YAHOO.util.CustomEvent("itemMouseOver",this);this.itemMouseOutEvent=new YAHOO.util.CustomEvent("itemMouseOut",this);this.itemArrowToEvent=new YAHOO.util.CustomEvent("itemArrowTo",this);this.itemArrowFromEvent=new YAHOO.util.CustomEvent("itemArrowFrom",this);this.itemSelectEvent=new YAHOO.util.CustomEvent("itemSelect",this);this.unmatchedItemSelectEvent=new YAHOO.util.CustomEvent("unmatchedItemSelect",this);this.selectionEnforceEvent=new YAHOO.util.CustomEvent("selectionEnforce",this);this.containerCollapseEvent=new YAHOO.util.CustomEvent("containerCollapse",this);this.textboxBlurEvent=new YAHOO.util.CustomEvent("textboxBlur",this);oTextbox.setAttribute("autocomplete","off");YAHOO.widget.AutoComplete._nIndex++;} -else{}};YAHOO.widget.AutoComplete.prototype.dataSource=null;YAHOO.widget.AutoComplete.prototype.minQueryLength=1;YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed=10;YAHOO.widget.AutoComplete.prototype.queryDelay=0.5;YAHOO.widget.AutoComplete.prototype.highlightClassName="yui-ac-highlight";YAHOO.widget.AutoComplete.prototype.prehighlightClassName=null;YAHOO.widget.AutoComplete.prototype.delimChar=null;YAHOO.widget.AutoComplete.prototype.autoHighlight=true;YAHOO.widget.AutoComplete.prototype.typeAhead=false;YAHOO.widget.AutoComplete.prototype.animHoriz=false;YAHOO.widget.AutoComplete.prototype.animVert=true;YAHOO.widget.AutoComplete.prototype.animSpeed=0.3;YAHOO.widget.AutoComplete.prototype.forceSelection=false;YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete=true;YAHOO.widget.AutoComplete.prototype.alwaysShowContainer=false;YAHOO.widget.AutoComplete.prototype.useIFrame=false;YAHOO.widget.AutoComplete.prototype.useShadow=false;YAHOO.widget.AutoComplete.prototype.toString=function(){return"AutoComplete "+this._sName;};YAHOO.widget.AutoComplete.prototype.isContainerOpen=function(){return this._bContainerOpen;};YAHOO.widget.AutoComplete.prototype.getListItems=function(){return this._aListItems;};YAHOO.widget.AutoComplete.prototype.getListItemData=function(oListItem){if(oListItem._oResultData){return oListItem._oResultData;} -else{return false;}};YAHOO.widget.AutoComplete.prototype.setHeader=function(sHeader){if(sHeader){if(this._oContainer._oContent._oHeader){this._oContainer._oContent._oHeader.innerHTML=sHeader;this._oContainer._oContent._oHeader.style.display="block";}} -else{this._oContainer._oContent._oHeader.innerHTML="";this._oContainer._oContent._oHeader.style.display="none";}};YAHOO.widget.AutoComplete.prototype.setFooter=function(sFooter){if(sFooter){if(this._oContainer._oContent._oFooter){this._oContainer._oContent._oFooter.innerHTML=sFooter;this._oContainer._oContent._oFooter.style.display="block";}} -else{this._oContainer._oContent._oFooter.innerHTML="";this._oContainer._oContent._oFooter.style.display="none";}};YAHOO.widget.AutoComplete.prototype.setBody=function(sBody){if(sBody){if(this._oContainer._oContent._oBody){this._oContainer._oContent._oBody.innerHTML=sBody;this._oContainer._oContent._oBody.style.display="block";this._oContainer._oContent.style.display="block";}} -else{this._oContainer._oContent._oBody.innerHTML="";this._oContainer._oContent.style.display="none";} -this._maxResultsDisplayed=0;};YAHOO.widget.AutoComplete.prototype.formatResult=function(oResultItem,sQuery){var sResult=oResultItem[0];if(sResult){return sResult;} -else{return"";}};YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer=function(oResultItem,sQuery){return true;};YAHOO.widget.AutoComplete.prototype.sendQuery=function(sQuery){this._sendQuery(sQuery);};YAHOO.widget.AutoComplete.prototype.textboxFocusEvent=null;YAHOO.widget.AutoComplete.prototype.textboxKeyEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestEvent=null;YAHOO.widget.AutoComplete.prototype.dataReturnEvent=null;YAHOO.widget.AutoComplete.prototype.dataErrorEvent=null;YAHOO.widget.AutoComplete.prototype.containerExpandEvent=null;YAHOO.widget.AutoComplete.prototype.typeAheadEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowToEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent=null;YAHOO.widget.AutoComplete.prototype.itemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent=null;YAHOO.widget.AutoComplete.prototype.containerCollapseEvent=null;YAHOO.widget.AutoComplete.prototype.textboxBlurEvent=null;YAHOO.widget.AutoComplete._nIndex=0;YAHOO.widget.AutoComplete.prototype._sName=null;YAHOO.widget.AutoComplete.prototype._oTextbox=null;YAHOO.widget.AutoComplete.prototype._bFocused=true;YAHOO.widget.AutoComplete.prototype._oAnim=null;YAHOO.widget.AutoComplete.prototype._oContainer=null;YAHOO.widget.AutoComplete.prototype._bContainerOpen=false;YAHOO.widget.AutoComplete.prototype._bOverContainer=false;YAHOO.widget.AutoComplete.prototype._aListItems=null;YAHOO.widget.AutoComplete.prototype._nDisplayedItems=0;YAHOO.widget.AutoComplete.prototype._maxResultsDisplayed=0;YAHOO.widget.AutoComplete.prototype._sCurQuery=null;YAHOO.widget.AutoComplete.prototype._sSavedQuery=null;YAHOO.widget.AutoComplete.prototype._oCurItem=null;YAHOO.widget.AutoComplete.prototype._bItemSelected=false;YAHOO.widget.AutoComplete.prototype._nKeyCode=null;YAHOO.widget.AutoComplete.prototype._nDelayID=-1;YAHOO.widget.AutoComplete.prototype._iFrameSrc="javascript:false;";YAHOO.widget.AutoComplete.prototype._queryInterval=null;YAHOO.widget.AutoComplete.prototype._sLastTextboxValue=null;YAHOO.widget.AutoComplete.prototype._initProps=function(){var minQueryLength=this.minQueryLength;if(isNaN(minQueryLength)||(minQueryLength<1)){minQueryLength=1;} -var maxResultsDisplayed=this.maxResultsDisplayed;if(isNaN(this.maxResultsDisplayed)||(this.maxResultsDisplayed<1)){this.maxResultsDisplayed=10;} -var queryDelay=this.queryDelay;if(isNaN(this.queryDelay)||(this.queryDelay<0)){this.queryDelay=0.5;} -var aDelimChar=(this.delimChar)?this.delimChar:null;if(aDelimChar){if(typeof aDelimChar=="string"){this.delimChar=[aDelimChar];} -else if(aDelimChar.constructor!=Array){this.delimChar=null;}} -var animSpeed=this.animSpeed;if((this.animHoriz||this.animVert)&&YAHOO.util.Anim){if(isNaN(animSpeed)||(animSpeed<0)){animSpeed=0.3;} -if(!this._oAnim){oAnim=new YAHOO.util.Anim(this._oContainer._oContent,{},this.animSpeed);this._oAnim=oAnim;} -else{this._oAnim.duration=animSpeed;}} -if(this.forceSelection&&this.delimChar){}};YAHOO.widget.AutoComplete.prototype._initContainerHelpers=function(){if(this.useShadow&&!this._oContainer._oShadow){var oShadow=document.createElement("div");oShadow.className="yui-ac-shadow";this._oContainer._oShadow=this._oContainer.appendChild(oShadow);} -if(this.useIFrame&&!this._oContainer._oIFrame){var oIFrame=document.createElement("iframe");oIFrame.src=this._iFrameSrc;oIFrame.frameBorder=0;oIFrame.scrolling="no";oIFrame.style.position="absolute";oIFrame.style.width="100%";oIFrame.style.height="100%";oIFrame.tabIndex=-1;this._oContainer._oIFrame=this._oContainer.appendChild(oIFrame);}};YAHOO.widget.AutoComplete.prototype._initContainer=function(){if(!this._oContainer._oContent){var oContent=document.createElement("div");oContent.className="yui-ac-content";oContent.style.display="none";this._oContainer._oContent=this._oContainer.appendChild(oContent);var oHeader=document.createElement("div");oHeader.className="yui-ac-hd";oHeader.style.display="none";this._oContainer._oContent._oHeader=this._oContainer._oContent.appendChild(oHeader);var oBody=document.createElement("div");oBody.className="yui-ac-bd";this._oContainer._oContent._oBody=this._oContainer._oContent.appendChild(oBody);var oFooter=document.createElement("div");oFooter.className="yui-ac-ft";oFooter.style.display="none";this._oContainer._oContent._oFooter=this._oContainer._oContent.appendChild(oFooter);} -else{}};YAHOO.widget.AutoComplete.prototype._initList=function(){this._aListItems=[];while(this._oContainer._oContent._oBody.hasChildNodes()){var oldListItems=this.getListItems();if(oldListItems){for(var oldi=oldListItems.length-1;oldi>=0;i--){oldListItems[oldi]=null;}} -this._oContainer._oContent._oBody.innerHTML="";} -var oList=document.createElement("ul");oList=this._oContainer._oContent._oBody.appendChild(oList);for(var i=0;i=18&&nKeyCode<=20)||(nKeyCode==27)||(nKeyCode>=33&&nKeyCode<=35)||(nKeyCode>=36&&nKeyCode<=38)||(nKeyCode==40)||(nKeyCode>=44&&nKeyCode<=45)){return true;} -return false;};YAHOO.widget.AutoComplete.prototype._sendQuery=function(sQuery){if(this.minQueryLength==-1){this._toggleContainer(false);return;} -var aDelimChar=(this.delimChar)?this.delimChar:null;if(aDelimChar){var nDelimIndex=-1;for(var i=aDelimChar.length-1;i>=0;i--){var nNewIndex=sQuery.lastIndexOf(aDelimChar[i]);if(nNewIndex>nDelimIndex){nDelimIndex=nNewIndex;}} -if(aDelimChar[i]==" "){for(var j=aDelimChar.length-1;j>=0;j--){if(sQuery[nDelimIndex-1]==aDelimChar[j]){nDelimIndex--;break;}}} -if(nDelimIndex>-1){var nQueryStart=nDelimIndex+1;while(sQuery.charAt(nQueryStart)==" "){nQueryStart+=1;} -this._sSavedQuery=sQuery.substring(0,nQueryStart);sQuery=sQuery.substr(nQueryStart);} -else if(sQuery.indexOf(this._sSavedQuery)<0){this._sSavedQuery=null;}} -if(sQuery&&(sQuery.length0)){if(this._nDelayID!=-1){clearTimeout(this._nDelayID);} -this._toggleContainer(false);return;} -sQuery=encodeURIComponent(sQuery);this._nDelayID=-1;this.dataRequestEvent.fire(this,sQuery);this.dataSource.getResults(this._populateList,sQuery,this);};YAHOO.widget.AutoComplete.prototype._populateList=function(sQuery,aResults,oSelf){if(aResults===null){oSelf.dataErrorEvent.fire(oSelf,sQuery);} -if(!oSelf._bFocused||!aResults){return;} -var isOpera=(navigator.userAgent.toLowerCase().indexOf("opera")!=-1);var contentStyle=oSelf._oContainer._oContent.style;contentStyle.width=(!isOpera)?null:"";contentStyle.height=(!isOpera)?null:"";var sCurQuery=decodeURIComponent(sQuery);oSelf._sCurQuery=sCurQuery;oSelf._bItemSelected=false;if(oSelf._maxResultsDisplayed!=oSelf.maxResultsDisplayed){oSelf._initList();} -var nItems=Math.min(aResults.length,oSelf.maxResultsDisplayed);oSelf._nDisplayedItems=nItems;if(nItems>0){oSelf._initContainerHelpers();var aItems=oSelf._aListItems;for(var i=nItems-1;i>=0;i--){var oItemi=aItems[i];var oResultItemi=aResults[i];oItemi.innerHTML=oSelf.formatResult(oResultItemi,sCurQuery);oItemi.style.display="list-item";oItemi._sResultKey=oResultItemi[0];oItemi._oResultData=oResultItemi;} -for(var j=aItems.length-1;j>=nItems;j--){var oItemj=aItems[j];oItemj.innerHTML=null;oItemj.style.display="none";oItemj._sResultKey=null;oItemj._oResultData=null;} -if(oSelf.autoHighlight){var oFirstItem=aItems[0];oSelf._toggleHighlight(oFirstItem,"to");oSelf.itemArrowToEvent.fire(oSelf,oFirstItem);oSelf._typeAhead(oFirstItem,sQuery);} -else{oSelf._oCurItem=null;} -var ok=oSelf.doBeforeExpandContainer(oSelf._oTextbox,oSelf._oContainer,sQuery,aResults);oSelf._toggleContainer(ok);} -else{oSelf._toggleContainer(false);} -oSelf.dataReturnEvent.fire(oSelf,sQuery,aResults);};YAHOO.widget.AutoComplete.prototype._clearSelection=function(){var sValue=this._oTextbox.value;var sChar=(this.delimChar)?this.delimChar[0]:null;var nIndex=(sChar)?sValue.lastIndexOf(sChar,sValue.length-2):-1;if(nIndex>-1){this._oTextbox.value=sValue.substring(0,nIndex);} -else{this._oTextbox.value="";} -this._sSavedQuery=this._oTextbox.value;this.selectionEnforceEvent.fire(this);};YAHOO.widget.AutoComplete.prototype._textMatchesOption=function(){var foundMatch=false;for(var i=this._nDisplayedItems-1;i>=0;i--){var oItem=this._aListItems[i];var sMatch=oItem._sResultKey.toLowerCase();if(sMatch==this._sCurQuery.toLowerCase()){foundMatch=true;break;}} -return(foundMatch);};YAHOO.widget.AutoComplete.prototype._typeAhead=function(oItem,sQuery){if(!this.typeAhead||(this._nKeyCode==8)){return;} -var oTextbox=this._oTextbox;var sValue=this._oTextbox.value;if(!oTextbox.setSelectionRange&&!oTextbox.createTextRange){return;} -var nStart=sValue.length;this._updateValue(oItem);var nEnd=oTextbox.value.length;this._selectText(oTextbox,nStart,nEnd);var sPrefill=oTextbox.value.substr(nStart,nEnd);this.typeAheadEvent.fire(this,sQuery,sPrefill);};YAHOO.widget.AutoComplete.prototype._selectText=function(oTextbox,nStart,nEnd){if(oTextbox.setSelectionRange){oTextbox.setSelectionRange(nStart,nEnd);} -else if(oTextbox.createTextRange){var oTextRange=oTextbox.createTextRange();oTextRange.moveStart("character",nStart);oTextRange.moveEnd("character",nEnd-oTextbox.value.length);oTextRange.select();} -else{oTextbox.select();}};YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers=function(bShow){var bFireEvent=false;var width=this._oContainer._oContent.offsetWidth+"px";var height=this._oContainer._oContent.offsetHeight+"px";if(this.useIFrame&&this._oContainer._oIFrame){bFireEvent=true;if(bShow){this._oContainer._oIFrame.style.width=width;this._oContainer._oIFrame.style.height=height;} -else{this._oContainer._oIFrame.style.width=0;this._oContainer._oIFrame.style.height=0;}} -if(this.useShadow&&this._oContainer._oShadow){bFireEvent=true;if(bShow){this._oContainer._oShadow.style.width=width;this._oContainer._oShadow.style.height=height;} -else{this._oContainer._oShadow.style.width=0;this._oContainer._oShadow.style.height=0;}}};YAHOO.widget.AutoComplete.prototype._toggleContainer=function(bShow){var oContainer=this._oContainer;if(this.alwaysShowContainer&&this._bContainerOpen){return;} -if(!bShow){this._oContainer._oContent.scrollTop=0;var aItems=this._aListItems;if(aItems&&(aItems.length>0)){for(var i=aItems.length-1;i>=0;i--){aItems[i].style.display="none";}} -if(this._oCurItem){this._toggleHighlight(this._oCurItem,"from");} -this._oCurItem=null;this._nDisplayedItems=0;this._sCurQuery=null;} -if(!bShow&&!this._bContainerOpen){oContainer._oContent.style.display="none";return;} -var oAnim=this._oAnim;if(oAnim&&oAnim.getEl()&&(this.animHoriz||this.animVert)){if(!bShow){this._toggleContainerHelpers(bShow);} -if(oAnim.isAnimated()){oAnim.stop();} -var oClone=oContainer._oContent.cloneNode(true);oContainer.appendChild(oClone);oClone.style.top="-9000px";oClone.style.display="block";var wExp=oClone.offsetWidth;var hExp=oClone.offsetHeight;var wColl=(this.animHoriz)?0:wExp;var hColl=(this.animVert)?0:hExp;oAnim.attributes=(bShow)?{width:{to:wExp},height:{to:hExp}}:{width:{to:wColl},height:{to:hColl}};if(bShow&&!this._bContainerOpen){oContainer._oContent.style.width=wColl+"px";oContainer._oContent.style.height=hColl+"px";} -else{oContainer._oContent.style.width=wExp+"px";oContainer._oContent.style.height=hExp+"px";} -oContainer.removeChild(oClone);oClone=null;var oSelf=this;var onAnimComplete=function(){oAnim.onComplete.unsubscribeAll();if(bShow){oSelf.containerExpandEvent.fire(oSelf);} -else{oContainer._oContent.style.display="none";oSelf.containerCollapseEvent.fire(oSelf);} -oSelf._toggleContainerHelpers(bShow);};oContainer._oContent.style.display="block";oAnim.onComplete.subscribe(onAnimComplete);oAnim.animate();this._bContainerOpen=bShow;} -else{if(bShow){oContainer._oContent.style.display="block";this.containerExpandEvent.fire(this);} -else{oContainer._oContent.style.display="none";this.containerCollapseEvent.fire(this);} -this._toggleContainerHelpers(bShow);this._bContainerOpen=bShow;}};YAHOO.widget.AutoComplete.prototype._toggleHighlight=function(oNewItem,sType){var sHighlight=this.highlightClassName;if(this._oCurItem){YAHOO.util.Dom.removeClass(this._oCurItem,sHighlight);} -if((sType=="to")&&sHighlight){YAHOO.util.Dom.addClass(oNewItem,sHighlight);this._oCurItem=oNewItem;}};YAHOO.widget.AutoComplete.prototype._togglePrehighlight=function(oNewItem,sType){if(oNewItem==this._oCurItem){return;} -var sPrehighlight=this.prehighlightClassName;if((sType=="mouseover")&&sPrehighlight){YAHOO.util.Dom.addClass(oNewItem,sPrehighlight);} -else{YAHOO.util.Dom.removeClass(oNewItem,sPrehighlight);}};YAHOO.widget.AutoComplete.prototype._updateValue=function(oItem){var oTextbox=this._oTextbox;var sDelimChar=(this.delimChar)?(this.delimChar[0]||this.delimChar):null;var sSavedQuery=this._sSavedQuery;var sResultKey=oItem._sResultKey;oTextbox.focus();oTextbox.value="";if(sDelimChar){if(sSavedQuery){oTextbox.value=sSavedQuery;} -oTextbox.value+=sResultKey+sDelimChar;if(sDelimChar!=" "){oTextbox.value+=" ";}} -else{oTextbox.value=sResultKey;} -if(oTextbox.type=="textarea"){oTextbox.scrollTop=oTextbox.scrollHeight;} -var end=oTextbox.value.length;this._selectText(oTextbox,end,end);this._oCurItem=oItem;};YAHOO.widget.AutoComplete.prototype._selectItem=function(oItem){this._bItemSelected=true;this._updateValue(oItem);this._cancelIntervalDetection(this);this.itemSelectEvent.fire(this,oItem,oItem._oResultData);this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype._jumpSelection=function(){if(!this.typeAhead){return;} -else{this._toggleContainer(false);}};YAHOO.widget.AutoComplete.prototype._moveSelection=function(nKeyCode){if(this._bContainerOpen){var oCurItem=this._oCurItem;var nCurItemIndex=-1;if(oCurItem){nCurItemIndex=oCurItem._nItemIndex;} -var nNewItemIndex=(nKeyCode==40)?(nCurItemIndex+1):(nCurItemIndex-1);if(nNewItemIndex<-2||nNewItemIndex>=this._nDisplayedItems){return;} -if(oCurItem){this._toggleHighlight(oCurItem,"from");this.itemArrowFromEvent.fire(this,oCurItem);} -if(nNewItemIndex==-1){if(this.delimChar&&this._sSavedQuery){if(!this._textMatchesOption()){this._oTextbox.value=this._sSavedQuery;} -else{this._oTextbox.value=this._sSavedQuery+this._sCurQuery;}} -else{this._oTextbox.value=this._sCurQuery;} -this._oCurItem=null;return;} -if(nNewItemIndex==-2){this._toggleContainer(false);return;} -var oNewItem=this._aListItems[nNewItemIndex];var oContent=this._oContainer._oContent;var scrollOn=((YAHOO.util.Dom.getStyle(oContent,"overflow")=="auto")||(YAHOO.util.Dom.getStyle(oContent,"overflowY")=="auto"));if(scrollOn&&(nNewItemIndex>-1)&&(nNewItemIndex(oContent.scrollTop+oContent.offsetHeight)){oContent.scrollTop=(oNewItem.offsetTop+oNewItem.offsetHeight)-oContent.offsetHeight;} -else if((oNewItem.offsetTop+oNewItem.offsetHeight)(oContent.scrollTop+oContent.offsetHeight)){this._oContainer._oContent.scrollTop=(oNewItem.offsetTop+oNewItem.offsetHeight)-oContent.offsetHeight;}}} -this._toggleHighlight(oNewItem,"to");this.itemArrowToEvent.fire(this,oNewItem);if(this.typeAhead){this._updateValue(oNewItem);}}};YAHOO.widget.AutoComplete.prototype._onItemMouseover=function(v,oSelf){if(oSelf.prehighlightClassName){oSelf._togglePrehighlight(this,"mouseover");} -else{oSelf._toggleHighlight(this,"to");} -oSelf.itemMouseOverEvent.fire(oSelf,this);};YAHOO.widget.AutoComplete.prototype._onItemMouseout=function(v,oSelf){if(oSelf.prehighlightClassName){oSelf._togglePrehighlight(this,"mouseout");} -else{oSelf._toggleHighlight(this,"from");} -oSelf.itemMouseOutEvent.fire(oSelf,this);};YAHOO.widget.AutoComplete.prototype._onItemMouseclick=function(v,oSelf){oSelf._toggleHighlight(this,"to");oSelf._selectItem(this);};YAHOO.widget.AutoComplete.prototype._onContainerMouseover=function(v,oSelf){oSelf._bOverContainer=true;};YAHOO.widget.AutoComplete.prototype._onContainerMouseout=function(v,oSelf){oSelf._bOverContainer=false;if(oSelf._oCurItem){oSelf._toggleHighlight(oSelf._oCurItem,"to");}};YAHOO.widget.AutoComplete.prototype._onContainerScroll=function(v,oSelf){oSelf._oTextbox.focus();};YAHOO.widget.AutoComplete.prototype._onContainerResize=function(v,oSelf){oSelf._toggleContainerHelpers(oSelf._bContainerOpen);};YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown=function(v,oSelf){var nKeyCode=v.keyCode;switch(nKeyCode){case 9:if(oSelf.delimChar&&(oSelf._nKeyCode!=nKeyCode)){if(oSelf._bContainerOpen){YAHOO.util.Event.stopEvent(v);}} -if(oSelf._oCurItem){oSelf._selectItem(oSelf._oCurItem);} -else{oSelf._toggleContainer(false);} -break;case 13:if(oSelf._nKeyCode!=nKeyCode){if(oSelf._bContainerOpen){YAHOO.util.Event.stopEvent(v);}} -if(oSelf._oCurItem){oSelf._selectItem(oSelf._oCurItem);} -else{oSelf._toggleContainer(false);} -break;case 27:oSelf._toggleContainer(false);return;case 39:oSelf._jumpSelection();break;case 38:YAHOO.util.Event.stopEvent(v);oSelf._moveSelection(nKeyCode);break;case 40:YAHOO.util.Event.stopEvent(v);oSelf._moveSelection(nKeyCode);break;default:break;}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress=function(v,oSelf){var nKeyCode=v.keyCode;var isMac=(navigator.userAgent.toLowerCase().indexOf("mac")!=-1);if(isMac){switch(nKeyCode){case 9:if(oSelf.delimChar&&(oSelf._nKeyCode!=nKeyCode)){if(oSelf._bContainerOpen){YAHOO.util.Event.stopEvent(v);}} -break;case 13:if(oSelf._nKeyCode!=nKeyCode){if(oSelf._bContainerOpen){YAHOO.util.Event.stopEvent(v);}} -break;case 38:case 40:YAHOO.util.Event.stopEvent(v);break;default:break;}} -else if(nKeyCode==229){oSelf._queryInterval=setInterval(function(){oSelf._onIMEDetected(oSelf);},500);}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp=function(v,oSelf){oSelf._initProps();var nKeyCode=v.keyCode;oSelf._nKeyCode=nKeyCode;var sText=this.value;if(oSelf._isIgnoreKey(nKeyCode)||(sText.toLowerCase()==oSelf._sCurQuery)){return;} -else{oSelf.textboxKeyEvent.fire(oSelf,nKeyCode);} -if(oSelf.queryDelay>0){var nDelayID=setTimeout(function(){oSelf._sendQuery(sText);},(oSelf.queryDelay*1000));if(oSelf._nDelayID!=-1){clearTimeout(oSelf._nDelayID);} -oSelf._nDelayID=nDelayID;} -else{oSelf._sendQuery(sText);}};YAHOO.widget.AutoComplete.prototype._onTextboxFocus=function(v,oSelf){oSelf._oTextbox.setAttribute("autocomplete","off");oSelf._bFocused=true;oSelf.textboxFocusEvent.fire(oSelf);};YAHOO.widget.AutoComplete.prototype._onTextboxBlur=function(v,oSelf){if(!oSelf._bOverContainer||(oSelf._nKeyCode==9)){if(!oSelf._bItemSelected){if(!oSelf._bContainerOpen||(oSelf._bContainerOpen&&!oSelf._textMatchesOption())){if(oSelf.forceSelection){oSelf._clearSelection();} -else{oSelf.unmatchedItemSelectEvent.fire(oSelf,oSelf._sCurQuery);}}} -if(oSelf._bContainerOpen){oSelf._toggleContainer(false);} -oSelf._cancelIntervalDetection(oSelf);oSelf._bFocused=false;oSelf.textboxBlurEvent.fire(oSelf);}};YAHOO.widget.AutoComplete.prototype._onFormSubmit=function(v,oSelf){if(oSelf.allowBrowserAutocomplete){oSelf._oTextbox.setAttribute("autocomplete","on");} -else{oSelf._oTextbox.setAttribute("autocomplete","off");}};YAHOO.widget.DataSource=function(){};YAHOO.widget.DataSource.ERROR_DATANULL="Response data was null";YAHOO.widget.DataSource.ERROR_DATAPARSE="Response data could not be parsed";YAHOO.widget.DataSource.prototype.maxCacheEntries=15;YAHOO.widget.DataSource.prototype.queryMatchContains=false;YAHOO.widget.DataSource.prototype.queryMatchSubset=false;YAHOO.widget.DataSource.prototype.queryMatchCase=false;YAHOO.widget.DataSource.prototype.toString=function(){return"DataSource "+this._sName;};YAHOO.widget.DataSource.prototype.getResults=function(oCallbackFn,sQuery,oParent){var aResults=this._doQueryCache(oCallbackFn,sQuery,oParent);if(aResults.length===0){this.queryEvent.fire(this,oParent,sQuery);this.doQuery(oCallbackFn,sQuery,oParent);}};YAHOO.widget.DataSource.prototype.doQuery=function(oCallbackFn,sQuery,oParent){};YAHOO.widget.DataSource.prototype.flushCache=function(){if(this._aCache){this._aCache=[];} -if(this._aCacheHelper){this._aCacheHelper=[];} -this.cacheFlushEvent.fire(this);};YAHOO.widget.DataSource.prototype.queryEvent=null;YAHOO.widget.DataSource.prototype.cacheQueryEvent=null;YAHOO.widget.DataSource.prototype.getResultsEvent=null;YAHOO.widget.DataSource.prototype.getCachedResultsEvent=null;YAHOO.widget.DataSource.prototype.dataErrorEvent=null;YAHOO.widget.DataSource.prototype.cacheFlushEvent=null;YAHOO.widget.DataSource._nIndex=0;YAHOO.widget.DataSource.prototype._sName=null;YAHOO.widget.DataSource.prototype._aCache=null;YAHOO.widget.DataSource.prototype._init=function(){var maxCacheEntries=this.maxCacheEntries;if(isNaN(maxCacheEntries)||(maxCacheEntries<0)){maxCacheEntries=0;} -if(maxCacheEntries>0&&!this._aCache){this._aCache=[];} -this._sName="instance"+YAHOO.widget.DataSource._nIndex;YAHOO.widget.DataSource._nIndex++;this.queryEvent=new YAHOO.util.CustomEvent("query",this);this.cacheQueryEvent=new YAHOO.util.CustomEvent("cacheQuery",this);this.getResultsEvent=new YAHOO.util.CustomEvent("getResults",this);this.getCachedResultsEvent=new YAHOO.util.CustomEvent("getCachedResults",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.cacheFlushEvent=new YAHOO.util.CustomEvent("cacheFlush",this);};YAHOO.widget.DataSource.prototype._addCacheElem=function(oResult){var aCache=this._aCache;if(!aCache||!oResult||!oResult.query||!oResult.results){return;} -if(aCache.length>=this.maxCacheEntries){aCache.shift();} -aCache.push(oResult);};YAHOO.widget.DataSource.prototype._doQueryCache=function(oCallbackFn,sQuery,oParent){var aResults=[];var bMatchFound=false;var aCache=this._aCache;var nCacheLength=(aCache)?aCache.length:0;var bMatchContains=this.queryMatchContains;if((this.maxCacheEntries>0)&&aCache&&(nCacheLength>0)){this.cacheQueryEvent.fire(this,oParent,sQuery);if(!this.queryMatchCase){var sOrigQuery=sQuery;sQuery=sQuery.toLowerCase();} -for(var i=nCacheLength-1;i>=0;i--){var resultObj=aCache[i];var aAllResultItems=resultObj.results;var matchKey=(!this.queryMatchCase)?encodeURIComponent(resultObj.query).toLowerCase():encodeURIComponent(resultObj.query);if(matchKey==sQuery){bMatchFound=true;aResults=aAllResultItems;if(i!=nCacheLength-1){aCache.splice(i,1);this._addCacheElem(resultObj);} -break;} -else if(this.queryMatchSubset){for(var j=sQuery.length-1;j>=0;j--){var subQuery=sQuery.substr(0,j);if(matchKey==subQuery){bMatchFound=true;for(var k=aAllResultItems.length-1;k>=0;k--){var aRecord=aAllResultItems[k];var sKeyIndex=(this.queryMatchCase)?encodeURIComponent(aRecord[0]).indexOf(sQuery):encodeURIComponent(aRecord[0]).toLowerCase().indexOf(sQuery);if((!bMatchContains&&(sKeyIndex===0))||(bMatchContains&&(sKeyIndex>-1))){aResults.unshift(aRecord);}} -resultObj={};resultObj.query=sQuery;resultObj.results=aResults;this._addCacheElem(resultObj);break;}} -if(bMatchFound){break;}}} -if(bMatchFound){this.getCachedResultsEvent.fire(this,oParent,sOrigQuery,aResults);oCallbackFn(sOrigQuery,aResults,oParent);}} -return aResults;};YAHOO.widget.DS_XHR=function(sScriptURI,aSchema,oConfigs){if(typeof oConfigs=="object"){for(var sConfig in oConfigs){this[sConfig]=oConfigs[sConfig];}} -if(!aSchema||(aSchema.constructor!=Array)){return;} -else{this.schema=aSchema;} -this.scriptURI=sScriptURI;this._init();};YAHOO.widget.DS_XHR.prototype=new YAHOO.widget.DataSource();YAHOO.widget.DS_XHR.TYPE_JSON=0;YAHOO.widget.DS_XHR.TYPE_XML=1;YAHOO.widget.DS_XHR.TYPE_FLAT=2;YAHOO.widget.DS_XHR.ERROR_DATAXHR="XHR response failed";YAHOO.widget.DS_XHR.prototype.connMgr=YAHOO.util.Connect;YAHOO.widget.DS_XHR.prototype.connTimeout=0;YAHOO.widget.DS_XHR.prototype.scriptURI=null;YAHOO.widget.DS_XHR.prototype.scriptQueryParam="query";YAHOO.widget.DS_XHR.prototype.scriptQueryAppend="";YAHOO.widget.DS_XHR.prototype.responseType=YAHOO.widget.DS_XHR.TYPE_JSON;YAHOO.widget.DS_XHR.prototype.responseStripAfter="\n0){sUri+="&"+this.scriptQueryAppend;} -var oResponse=null;var oSelf=this;var responseSuccess=function(oResp){if(!oSelf._oConn||(oResp.tId!=oSelf._oConn.tId)){oSelf.dataErrorEvent.fire(oSelf,oParent,sQuery,YAHOO.widget.DataSource.ERROR_DATANULL);return;} -for(var foo in oResp){} -if(!isXML){oResp=oResp.responseText;} -else{oResp=oResp.responseXML;} -if(oResp===null){oSelf.dataErrorEvent.fire(oSelf,oParent,sQuery,YAHOO.widget.DataSource.ERROR_DATANULL);return;} -var aResults=oSelf.parseResponse(sQuery,oResp,oParent);var resultObj={};resultObj.query=decodeURIComponent(sQuery);resultObj.results=aResults;if(aResults===null){oSelf.dataErrorEvent.fire(oSelf,oParent,sQuery,YAHOO.widget.DataSource.ERROR_DATAPARSE);aResults=[];} -else{oSelf.getResultsEvent.fire(oSelf,oParent,sQuery,aResults);oSelf._addCacheElem(resultObj);} -oCallbackFn(sQuery,aResults,oParent);};var responseFailure=function(oResp){oSelf.dataErrorEvent.fire(oSelf,oParent,sQuery,YAHOO.widget.DS_XHR.ERROR_DATAXHR);return;};var oCallback={success:responseSuccess,failure:responseFailure};if(!isNaN(this.connTimeout)&&this.connTimeout>0){oCallback.timeout=this.connTimeout;} -if(this._oConn){this.connMgr.abort(this._oConn);} -oSelf._oConn=this.connMgr.asyncRequest("GET",sUri,oCallback,null);};YAHOO.widget.DS_XHR.prototype.parseResponse=function(sQuery,oResponse,oParent){var aSchema=this.schema;var aResults=[];var bError=false;var nEnd=((this.responseStripAfter!=="")&&(oResponse.indexOf))?oResponse.indexOf(this.responseStripAfter):-1;if(nEnd!=-1){oResponse=oResponse.substring(0,nEnd);} -switch(this.responseType){case YAHOO.widget.DS_XHR.TYPE_JSON:var jsonList;if(window.JSON&&(navigator.userAgent.toLowerCase().indexOf('khtml')==-1)){var jsonObjParsed=JSON.parse(oResponse);if(!jsonObjParsed){bError=true;break;} -else{try{jsonList=eval("jsonObjParsed."+aSchema[0]);} -catch(e){bError=true;break;}}} -else{try{while(oResponse.substring(0,1)==" "){oResponse=oResponse.substring(1,oResponse.length);} -if(oResponse.indexOf("{")<0){bError=true;break;} -if(oResponse.indexOf("{}")===0){break;} -var jsonObjRaw=eval("("+oResponse+")");if(!jsonObjRaw){bError=true;break;} -jsonList=eval("(jsonObjRaw."+aSchema[0]+")");} -catch(e){bError=true;break;}} -if(!jsonList){bError=true;break;} -if(jsonList.constructor!=Array){jsonList=[jsonList];} -for(var i=jsonList.length-1;i>=0;i--){var aResultItem=[];var jsonResult=jsonList[i];for(var j=aSchema.length-1;j>=1;j--){var dataFieldValue=jsonResult[aSchema[j]];if(!dataFieldValue){dataFieldValue="";} -aResultItem.unshift(dataFieldValue);} -if(aResultItem.length==1){aResultItem.push(jsonResult);} -aResults.unshift(aResultItem);} -break;case YAHOO.widget.DS_XHR.TYPE_XML:var xmlList=oResponse.getElementsByTagName(aSchema[0]);if(!xmlList){bError=true;break;} -for(var k=xmlList.length-1;k>=0;k--){var result=xmlList.item(k);var aFieldSet=[];for(var m=aSchema.length-1;m>=1;m--){var sValue=null;var xmlAttr=result.attributes.getNamedItem(aSchema[m]);if(xmlAttr){sValue=xmlAttr.value;} -else{var xmlNode=result.getElementsByTagName(aSchema[m]);if(xmlNode&&xmlNode.item(0)&&xmlNode.item(0).firstChild){sValue=xmlNode.item(0).firstChild.nodeValue;} -else{sValue="";}} -aFieldSet.unshift(sValue);} -aResults.unshift(aFieldSet);} -break;case YAHOO.widget.DS_XHR.TYPE_FLAT:if(oResponse.length>0){var newLength=oResponse.length-aSchema[0].length;if(oResponse.substr(newLength)==aSchema[0]){oResponse=oResponse.substr(0,newLength);} -var aRecords=oResponse.split(aSchema[0]);for(var n=aRecords.length-1;n>=0;n--){aResults[n]=aRecords[n].split(aSchema[1]);}} -break;default:break;} -sQuery=null;oResponse=null;oParent=null;if(bError){return null;} -else{return aResults;}};YAHOO.widget.DS_XHR.prototype._oConn=null;YAHOO.widget.DS_JSFunction=function(oFunction,oConfigs){if(typeof oConfigs=="object"){for(var sConfig in oConfigs){this[sConfig]=oConfigs[sConfig];}} -if(!oFunction||(oFunction.constructor!=Function)){return;} -else{this.dataFunction=oFunction;this._init();}};YAHOO.widget.DS_JSFunction.prototype=new YAHOO.widget.DataSource();YAHOO.widget.DS_JSFunction.prototype.dataFunction=null;YAHOO.widget.DS_JSFunction.prototype.doQuery=function(oCallbackFn,sQuery,oParent){var oFunction=this.dataFunction;var aResults=[];aResults=oFunction(sQuery);if(aResults===null){this.dataErrorEvent.fire(this,oParent,sQuery,YAHOO.widget.DataSource.ERROR_DATANULL);return;} -var resultObj={};resultObj.query=decodeURIComponent(sQuery);resultObj.results=aResults;this._addCacheElem(resultObj);this.getResultsEvent.fire(this,oParent,sQuery,aResults);oCallbackFn(sQuery,aResults,oParent);return;};YAHOO.widget.DS_JSArray=function(aData,oConfigs){if(typeof oConfigs=="object"){for(var sConfig in oConfigs){this[sConfig]=oConfigs[sConfig];}} -if(!aData||(aData.constructor!=Array)){return;} -else{this.data=aData;this._init();}};YAHOO.widget.DS_JSArray.prototype=new YAHOO.widget.DataSource();YAHOO.widget.DS_JSArray.prototype.data=null;YAHOO.widget.DS_JSArray.prototype.doQuery=function(oCallbackFn,sQuery,oParent){var aData=this.data;var aResults=[];var bMatchFound=false;var bMatchContains=this.queryMatchContains;if(sQuery){if(!this.queryMatchCase){sQuery=sQuery.toLowerCase();} -for(var i=aData.length-1;i>=0;i--){var aDataset=[];if(aData[i]){if(aData[i].constructor==String){aDataset[0]=aData[i];} -else if(aData[i].constructor==Array){aDataset=aData[i];}} -if(aDataset[0]&&(aDataset[0].constructor==String)){var sKeyIndex=(this.queryMatchCase)?encodeURIComponent(aDataset[0]).indexOf(sQuery):encodeURIComponent(aDataset[0]).toLowerCase().indexOf(sQuery);if((!bMatchContains&&(sKeyIndex===0))||(bMatchContains&&(sKeyIndex>-1))){aResults.unshift(aDataset);}}}} +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 0.12.2 +*/ + +YAHOO.widget.AutoComplete=function(elInput,elContainer,oDataSource,oConfigs){if(elInput&&elContainer&&oDataSource){if(oDataSource&&(oDataSource instanceof YAHOO.widget.DataSource)){this.dataSource=oDataSource;} +else{return;} +if(YAHOO.util.Dom.inDocument(elInput)){if(typeof elInput=="string"){this._sName="instance"+YAHOO.widget.AutoComplete._nIndex+" "+elInput;this._oTextbox=document.getElementById(elInput);} +else{this._sName=(elInput.id)?"instance"+YAHOO.widget.AutoComplete._nIndex+" "+elInput.id:"instance"+YAHOO.widget.AutoComplete._nIndex;this._oTextbox=elInput;}} +else{return;} +if(YAHOO.util.Dom.inDocument(elContainer)){if(typeof elContainer=="string"){this._oContainer=document.getElementById(elContainer);} +else{this._oContainer=elContainer;} +if(this._oContainer.style.display=="none"){}} +else{return;} +if(typeof oConfigs=="object"){for(var sConfig in oConfigs){if(sConfig){this[sConfig]=oConfigs[sConfig];}}} +this._initContainer();this._initProps();this._initList();this._initContainerHelpers();var oSelf=this;var oTextbox=this._oTextbox;var oContent=this._oContainer._oContent;YAHOO.util.Event.addListener(oTextbox,"keyup",oSelf._onTextboxKeyUp,oSelf);YAHOO.util.Event.addListener(oTextbox,"keydown",oSelf._onTextboxKeyDown,oSelf);YAHOO.util.Event.addListener(oTextbox,"focus",oSelf._onTextboxFocus,oSelf);YAHOO.util.Event.addListener(oTextbox,"blur",oSelf._onTextboxBlur,oSelf);YAHOO.util.Event.addListener(oContent,"mouseover",oSelf._onContainerMouseover,oSelf);YAHOO.util.Event.addListener(oContent,"mouseout",oSelf._onContainerMouseout,oSelf);YAHOO.util.Event.addListener(oContent,"scroll",oSelf._onContainerScroll,oSelf);YAHOO.util.Event.addListener(oContent,"resize",oSelf._onContainerResize,oSelf);if(oTextbox.form){YAHOO.util.Event.addListener(oTextbox.form,"submit",oSelf._onFormSubmit,oSelf);} +YAHOO.util.Event.addListener(oTextbox,"keypress",oSelf._onTextboxKeyPress,oSelf);this.textboxFocusEvent=new YAHOO.util.CustomEvent("textboxFocus",this);this.textboxKeyEvent=new YAHOO.util.CustomEvent("textboxKey",this);this.dataRequestEvent=new YAHOO.util.CustomEvent("dataRequest",this);this.dataReturnEvent=new YAHOO.util.CustomEvent("dataReturn",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.containerExpandEvent=new YAHOO.util.CustomEvent("containerExpand",this);this.typeAheadEvent=new YAHOO.util.CustomEvent("typeAhead",this);this.itemMouseOverEvent=new YAHOO.util.CustomEvent("itemMouseOver",this);this.itemMouseOutEvent=new YAHOO.util.CustomEvent("itemMouseOut",this);this.itemArrowToEvent=new YAHOO.util.CustomEvent("itemArrowTo",this);this.itemArrowFromEvent=new YAHOO.util.CustomEvent("itemArrowFrom",this);this.itemSelectEvent=new YAHOO.util.CustomEvent("itemSelect",this);this.unmatchedItemSelectEvent=new YAHOO.util.CustomEvent("unmatchedItemSelect",this);this.selectionEnforceEvent=new YAHOO.util.CustomEvent("selectionEnforce",this);this.containerCollapseEvent=new YAHOO.util.CustomEvent("containerCollapse",this);this.textboxBlurEvent=new YAHOO.util.CustomEvent("textboxBlur",this);oTextbox.setAttribute("autocomplete","off");YAHOO.widget.AutoComplete._nIndex++;} +else{}};YAHOO.widget.AutoComplete.prototype.dataSource=null;YAHOO.widget.AutoComplete.prototype.minQueryLength=1;YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed=10;YAHOO.widget.AutoComplete.prototype.queryDelay=0.5;YAHOO.widget.AutoComplete.prototype.highlightClassName="yui-ac-highlight";YAHOO.widget.AutoComplete.prototype.prehighlightClassName=null;YAHOO.widget.AutoComplete.prototype.delimChar=null;YAHOO.widget.AutoComplete.prototype.autoHighlight=true;YAHOO.widget.AutoComplete.prototype.typeAhead=false;YAHOO.widget.AutoComplete.prototype.animHoriz=false;YAHOO.widget.AutoComplete.prototype.animVert=true;YAHOO.widget.AutoComplete.prototype.animSpeed=0.3;YAHOO.widget.AutoComplete.prototype.forceSelection=false;YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete=true;YAHOO.widget.AutoComplete.prototype.alwaysShowContainer=false;YAHOO.widget.AutoComplete.prototype.useIFrame=false;YAHOO.widget.AutoComplete.prototype.useShadow=false;YAHOO.widget.AutoComplete.prototype.toString=function(){return"AutoComplete "+this._sName;};YAHOO.widget.AutoComplete.prototype.isContainerOpen=function(){return this._bContainerOpen;};YAHOO.widget.AutoComplete.prototype.getListItems=function(){return this._aListItems;};YAHOO.widget.AutoComplete.prototype.getListItemData=function(oListItem){if(oListItem._oResultData){return oListItem._oResultData;} +else{return false;}};YAHOO.widget.AutoComplete.prototype.setHeader=function(sHeader){if(sHeader){if(this._oContainer._oContent._oHeader){this._oContainer._oContent._oHeader.innerHTML=sHeader;this._oContainer._oContent._oHeader.style.display="block";}} +else{this._oContainer._oContent._oHeader.innerHTML="";this._oContainer._oContent._oHeader.style.display="none";}};YAHOO.widget.AutoComplete.prototype.setFooter=function(sFooter){if(sFooter){if(this._oContainer._oContent._oFooter){this._oContainer._oContent._oFooter.innerHTML=sFooter;this._oContainer._oContent._oFooter.style.display="block";}} +else{this._oContainer._oContent._oFooter.innerHTML="";this._oContainer._oContent._oFooter.style.display="none";}};YAHOO.widget.AutoComplete.prototype.setBody=function(sBody){if(sBody){if(this._oContainer._oContent._oBody){this._oContainer._oContent._oBody.innerHTML=sBody;this._oContainer._oContent._oBody.style.display="block";this._oContainer._oContent.style.display="block";}} +else{this._oContainer._oContent._oBody.innerHTML="";this._oContainer._oContent.style.display="none";} +this._maxResultsDisplayed=0;};YAHOO.widget.AutoComplete.prototype.formatResult=function(oResultItem,sQuery){var sResult=oResultItem[0];if(sResult){return sResult;} +else{return"";}};YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer=function(oResultItem,sQuery){return true;};YAHOO.widget.AutoComplete.prototype.sendQuery=function(sQuery){this._sendQuery(sQuery);};YAHOO.widget.AutoComplete.prototype.textboxFocusEvent=null;YAHOO.widget.AutoComplete.prototype.textboxKeyEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestEvent=null;YAHOO.widget.AutoComplete.prototype.dataReturnEvent=null;YAHOO.widget.AutoComplete.prototype.dataErrorEvent=null;YAHOO.widget.AutoComplete.prototype.containerExpandEvent=null;YAHOO.widget.AutoComplete.prototype.typeAheadEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowToEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent=null;YAHOO.widget.AutoComplete.prototype.itemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent=null;YAHOO.widget.AutoComplete.prototype.containerCollapseEvent=null;YAHOO.widget.AutoComplete.prototype.textboxBlurEvent=null;YAHOO.widget.AutoComplete._nIndex=0;YAHOO.widget.AutoComplete.prototype._sName=null;YAHOO.widget.AutoComplete.prototype._oTextbox=null;YAHOO.widget.AutoComplete.prototype._bFocused=true;YAHOO.widget.AutoComplete.prototype._oAnim=null;YAHOO.widget.AutoComplete.prototype._oContainer=null;YAHOO.widget.AutoComplete.prototype._bContainerOpen=false;YAHOO.widget.AutoComplete.prototype._bOverContainer=false;YAHOO.widget.AutoComplete.prototype._aListItems=null;YAHOO.widget.AutoComplete.prototype._nDisplayedItems=0;YAHOO.widget.AutoComplete.prototype._maxResultsDisplayed=0;YAHOO.widget.AutoComplete.prototype._sCurQuery=null;YAHOO.widget.AutoComplete.prototype._sSavedQuery=null;YAHOO.widget.AutoComplete.prototype._oCurItem=null;YAHOO.widget.AutoComplete.prototype._bItemSelected=false;YAHOO.widget.AutoComplete.prototype._nKeyCode=null;YAHOO.widget.AutoComplete.prototype._nDelayID=-1;YAHOO.widget.AutoComplete.prototype._iFrameSrc="javascript:false;";YAHOO.widget.AutoComplete.prototype._queryInterval=null;YAHOO.widget.AutoComplete.prototype._sLastTextboxValue=null;YAHOO.widget.AutoComplete.prototype._initProps=function(){var minQueryLength=this.minQueryLength;if(isNaN(minQueryLength)||(minQueryLength<1)){minQueryLength=1;} +var maxResultsDisplayed=this.maxResultsDisplayed;if(isNaN(this.maxResultsDisplayed)||(this.maxResultsDisplayed<1)){this.maxResultsDisplayed=10;} +var queryDelay=this.queryDelay;if(isNaN(this.queryDelay)||(this.queryDelay<0)){this.queryDelay=0.5;} +var aDelimChar=(this.delimChar)?this.delimChar:null;if(aDelimChar){if(typeof aDelimChar=="string"){this.delimChar=[aDelimChar];} +else if(aDelimChar.constructor!=Array){this.delimChar=null;}} +var animSpeed=this.animSpeed;if((this.animHoriz||this.animVert)&&YAHOO.util.Anim){if(isNaN(animSpeed)||(animSpeed<0)){animSpeed=0.3;} +if(!this._oAnim){oAnim=new YAHOO.util.Anim(this._oContainer._oContent,{},this.animSpeed);this._oAnim=oAnim;} +else{this._oAnim.duration=animSpeed;}} +if(this.forceSelection&&this.delimChar){}};YAHOO.widget.AutoComplete.prototype._initContainerHelpers=function(){if(this.useShadow&&!this._oContainer._oShadow){var oShadow=document.createElement("div");oShadow.className="yui-ac-shadow";this._oContainer._oShadow=this._oContainer.appendChild(oShadow);} +if(this.useIFrame&&!this._oContainer._oIFrame){var oIFrame=document.createElement("iframe");oIFrame.src=this._iFrameSrc;oIFrame.frameBorder=0;oIFrame.scrolling="no";oIFrame.style.position="absolute";oIFrame.style.width="100%";oIFrame.style.height="100%";oIFrame.tabIndex=-1;this._oContainer._oIFrame=this._oContainer.appendChild(oIFrame);}};YAHOO.widget.AutoComplete.prototype._initContainer=function(){if(!this._oContainer._oContent){var oContent=document.createElement("div");oContent.className="yui-ac-content";oContent.style.display="none";this._oContainer._oContent=this._oContainer.appendChild(oContent);var oHeader=document.createElement("div");oHeader.className="yui-ac-hd";oHeader.style.display="none";this._oContainer._oContent._oHeader=this._oContainer._oContent.appendChild(oHeader);var oBody=document.createElement("div");oBody.className="yui-ac-bd";this._oContainer._oContent._oBody=this._oContainer._oContent.appendChild(oBody);var oFooter=document.createElement("div");oFooter.className="yui-ac-ft";oFooter.style.display="none";this._oContainer._oContent._oFooter=this._oContainer._oContent.appendChild(oFooter);} +else{}};YAHOO.widget.AutoComplete.prototype._initList=function(){this._aListItems=[];while(this._oContainer._oContent._oBody.hasChildNodes()){var oldListItems=this.getListItems();if(oldListItems){for(var oldi=oldListItems.length-1;oldi>=0;i--){oldListItems[oldi]=null;}} +this._oContainer._oContent._oBody.innerHTML="";} +var oList=document.createElement("ul");oList=this._oContainer._oContent._oBody.appendChild(oList);for(var i=0;i=18&&nKeyCode<=20)||(nKeyCode==27)||(nKeyCode>=33&&nKeyCode<=35)||(nKeyCode>=36&&nKeyCode<=38)||(nKeyCode==40)||(nKeyCode>=44&&nKeyCode<=45)){return true;} +return false;};YAHOO.widget.AutoComplete.prototype._sendQuery=function(sQuery){if(this.minQueryLength==-1){this._toggleContainer(false);return;} +var aDelimChar=(this.delimChar)?this.delimChar:null;if(aDelimChar){var nDelimIndex=-1;for(var i=aDelimChar.length-1;i>=0;i--){var nNewIndex=sQuery.lastIndexOf(aDelimChar[i]);if(nNewIndex>nDelimIndex){nDelimIndex=nNewIndex;}} +if(aDelimChar[i]==" "){for(var j=aDelimChar.length-1;j>=0;j--){if(sQuery[nDelimIndex-1]==aDelimChar[j]){nDelimIndex--;break;}}} +if(nDelimIndex>-1){var nQueryStart=nDelimIndex+1;while(sQuery.charAt(nQueryStart)==" "){nQueryStart+=1;} +this._sSavedQuery=sQuery.substring(0,nQueryStart);sQuery=sQuery.substr(nQueryStart);} +else if(sQuery.indexOf(this._sSavedQuery)<0){this._sSavedQuery=null;}} +if(sQuery&&(sQuery.length0)){if(this._nDelayID!=-1){clearTimeout(this._nDelayID);} +this._toggleContainer(false);return;} +sQuery=encodeURIComponent(sQuery);this._nDelayID=-1;this.dataRequestEvent.fire(this,sQuery);this.dataSource.getResults(this._populateList,sQuery,this);};YAHOO.widget.AutoComplete.prototype._populateList=function(sQuery,aResults,oSelf){if(aResults===null){oSelf.dataErrorEvent.fire(oSelf,sQuery);} +if(!oSelf._bFocused||!aResults){return;} +var isOpera=(navigator.userAgent.toLowerCase().indexOf("opera")!=-1);var contentStyle=oSelf._oContainer._oContent.style;contentStyle.width=(!isOpera)?null:"";contentStyle.height=(!isOpera)?null:"";var sCurQuery=decodeURIComponent(sQuery);oSelf._sCurQuery=sCurQuery;oSelf._bItemSelected=false;if(oSelf._maxResultsDisplayed!=oSelf.maxResultsDisplayed){oSelf._initList();} +var nItems=Math.min(aResults.length,oSelf.maxResultsDisplayed);oSelf._nDisplayedItems=nItems;if(nItems>0){oSelf._initContainerHelpers();var aItems=oSelf._aListItems;for(var i=nItems-1;i>=0;i--){var oItemi=aItems[i];var oResultItemi=aResults[i];oItemi.innerHTML=oSelf.formatResult(oResultItemi,sCurQuery);oItemi.style.display="list-item";oItemi._sResultKey=oResultItemi[0];oItemi._oResultData=oResultItemi;} +for(var j=aItems.length-1;j>=nItems;j--){var oItemj=aItems[j];oItemj.innerHTML=null;oItemj.style.display="none";oItemj._sResultKey=null;oItemj._oResultData=null;} +if(oSelf.autoHighlight){var oFirstItem=aItems[0];oSelf._toggleHighlight(oFirstItem,"to");oSelf.itemArrowToEvent.fire(oSelf,oFirstItem);oSelf._typeAhead(oFirstItem,sQuery);} +else{oSelf._oCurItem=null;} +var ok=oSelf.doBeforeExpandContainer(oSelf._oTextbox,oSelf._oContainer,sQuery,aResults);oSelf._toggleContainer(ok);} +else{oSelf._toggleContainer(false);} +oSelf.dataReturnEvent.fire(oSelf,sQuery,aResults);};YAHOO.widget.AutoComplete.prototype._clearSelection=function(){var sValue=this._oTextbox.value;var sChar=(this.delimChar)?this.delimChar[0]:null;var nIndex=(sChar)?sValue.lastIndexOf(sChar,sValue.length-2):-1;if(nIndex>-1){this._oTextbox.value=sValue.substring(0,nIndex);} +else{this._oTextbox.value="";} +this._sSavedQuery=this._oTextbox.value;this.selectionEnforceEvent.fire(this);};YAHOO.widget.AutoComplete.prototype._textMatchesOption=function(){var foundMatch=false;for(var i=this._nDisplayedItems-1;i>=0;i--){var oItem=this._aListItems[i];var sMatch=oItem._sResultKey.toLowerCase();if(sMatch==this._sCurQuery.toLowerCase()){foundMatch=true;break;}} +return(foundMatch);};YAHOO.widget.AutoComplete.prototype._typeAhead=function(oItem,sQuery){if(!this.typeAhead||(this._nKeyCode==8)){return;} +var oTextbox=this._oTextbox;var sValue=this._oTextbox.value;if(!oTextbox.setSelectionRange&&!oTextbox.createTextRange){return;} +var nStart=sValue.length;this._updateValue(oItem);var nEnd=oTextbox.value.length;this._selectText(oTextbox,nStart,nEnd);var sPrefill=oTextbox.value.substr(nStart,nEnd);this.typeAheadEvent.fire(this,sQuery,sPrefill);};YAHOO.widget.AutoComplete.prototype._selectText=function(oTextbox,nStart,nEnd){if(oTextbox.setSelectionRange){oTextbox.setSelectionRange(nStart,nEnd);} +else if(oTextbox.createTextRange){var oTextRange=oTextbox.createTextRange();oTextRange.moveStart("character",nStart);oTextRange.moveEnd("character",nEnd-oTextbox.value.length);oTextRange.select();} +else{oTextbox.select();}};YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers=function(bShow){var bFireEvent=false;var width=this._oContainer._oContent.offsetWidth+"px";var height=this._oContainer._oContent.offsetHeight+"px";if(this.useIFrame&&this._oContainer._oIFrame){bFireEvent=true;if(bShow){this._oContainer._oIFrame.style.width=width;this._oContainer._oIFrame.style.height=height;} +else{this._oContainer._oIFrame.style.width=0;this._oContainer._oIFrame.style.height=0;}} +if(this.useShadow&&this._oContainer._oShadow){bFireEvent=true;if(bShow){this._oContainer._oShadow.style.width=width;this._oContainer._oShadow.style.height=height;} +else{this._oContainer._oShadow.style.width=0;this._oContainer._oShadow.style.height=0;}}};YAHOO.widget.AutoComplete.prototype._toggleContainer=function(bShow){var oContainer=this._oContainer;if(this.alwaysShowContainer&&this._bContainerOpen){return;} +if(!bShow){this._oContainer._oContent.scrollTop=0;var aItems=this._aListItems;if(aItems&&(aItems.length>0)){for(var i=aItems.length-1;i>=0;i--){aItems[i].style.display="none";}} +if(this._oCurItem){this._toggleHighlight(this._oCurItem,"from");} +this._oCurItem=null;this._nDisplayedItems=0;this._sCurQuery=null;} +if(!bShow&&!this._bContainerOpen){oContainer._oContent.style.display="none";return;} +var oAnim=this._oAnim;if(oAnim&&oAnim.getEl()&&(this.animHoriz||this.animVert)){if(!bShow){this._toggleContainerHelpers(bShow);} +if(oAnim.isAnimated()){oAnim.stop();} +var oClone=oContainer._oContent.cloneNode(true);oContainer.appendChild(oClone);oClone.style.top="-9000px";oClone.style.display="block";var wExp=oClone.offsetWidth;var hExp=oClone.offsetHeight;var wColl=(this.animHoriz)?0:wExp;var hColl=(this.animVert)?0:hExp;oAnim.attributes=(bShow)?{width:{to:wExp},height:{to:hExp}}:{width:{to:wColl},height:{to:hColl}};if(bShow&&!this._bContainerOpen){oContainer._oContent.style.width=wColl+"px";oContainer._oContent.style.height=hColl+"px";} +else{oContainer._oContent.style.width=wExp+"px";oContainer._oContent.style.height=hExp+"px";} +oContainer.removeChild(oClone);oClone=null;var oSelf=this;var onAnimComplete=function(){oAnim.onComplete.unsubscribeAll();if(bShow){oSelf.containerExpandEvent.fire(oSelf);} +else{oContainer._oContent.style.display="none";oSelf.containerCollapseEvent.fire(oSelf);} +oSelf._toggleContainerHelpers(bShow);};oContainer._oContent.style.display="block";oAnim.onComplete.subscribe(onAnimComplete);oAnim.animate();this._bContainerOpen=bShow;} +else{if(bShow){oContainer._oContent.style.display="block";this.containerExpandEvent.fire(this);} +else{oContainer._oContent.style.display="none";this.containerCollapseEvent.fire(this);} +this._toggleContainerHelpers(bShow);this._bContainerOpen=bShow;}};YAHOO.widget.AutoComplete.prototype._toggleHighlight=function(oNewItem,sType){var sHighlight=this.highlightClassName;if(this._oCurItem){YAHOO.util.Dom.removeClass(this._oCurItem,sHighlight);} +if((sType=="to")&&sHighlight){YAHOO.util.Dom.addClass(oNewItem,sHighlight);this._oCurItem=oNewItem;}};YAHOO.widget.AutoComplete.prototype._togglePrehighlight=function(oNewItem,sType){if(oNewItem==this._oCurItem){return;} +var sPrehighlight=this.prehighlightClassName;if((sType=="mouseover")&&sPrehighlight){YAHOO.util.Dom.addClass(oNewItem,sPrehighlight);} +else{YAHOO.util.Dom.removeClass(oNewItem,sPrehighlight);}};YAHOO.widget.AutoComplete.prototype._updateValue=function(oItem){var oTextbox=this._oTextbox;var sDelimChar=(this.delimChar)?(this.delimChar[0]||this.delimChar):null;var sSavedQuery=this._sSavedQuery;var sResultKey=oItem._sResultKey;oTextbox.focus();oTextbox.value="";if(sDelimChar){if(sSavedQuery){oTextbox.value=sSavedQuery;} +oTextbox.value+=sResultKey+sDelimChar;if(sDelimChar!=" "){oTextbox.value+=" ";}} +else{oTextbox.value=sResultKey;} +if(oTextbox.type=="textarea"){oTextbox.scrollTop=oTextbox.scrollHeight;} +var end=oTextbox.value.length;this._selectText(oTextbox,end,end);this._oCurItem=oItem;};YAHOO.widget.AutoComplete.prototype._selectItem=function(oItem){this._bItemSelected=true;this._updateValue(oItem);this._cancelIntervalDetection(this);this.itemSelectEvent.fire(this,oItem,oItem._oResultData);this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype._jumpSelection=function(){if(!this.typeAhead){return;} +else{this._toggleContainer(false);}};YAHOO.widget.AutoComplete.prototype._moveSelection=function(nKeyCode){if(this._bContainerOpen){var oCurItem=this._oCurItem;var nCurItemIndex=-1;if(oCurItem){nCurItemIndex=oCurItem._nItemIndex;} +var nNewItemIndex=(nKeyCode==40)?(nCurItemIndex+1):(nCurItemIndex-1);if(nNewItemIndex<-2||nNewItemIndex>=this._nDisplayedItems){return;} +if(oCurItem){this._toggleHighlight(oCurItem,"from");this.itemArrowFromEvent.fire(this,oCurItem);} +if(nNewItemIndex==-1){if(this.delimChar&&this._sSavedQuery){if(!this._textMatchesOption()){this._oTextbox.value=this._sSavedQuery;} +else{this._oTextbox.value=this._sSavedQuery+this._sCurQuery;}} +else{this._oTextbox.value=this._sCurQuery;} +this._oCurItem=null;return;} +if(nNewItemIndex==-2){this._toggleContainer(false);return;} +var oNewItem=this._aListItems[nNewItemIndex];var oContent=this._oContainer._oContent;var scrollOn=((YAHOO.util.Dom.getStyle(oContent,"overflow")=="auto")||(YAHOO.util.Dom.getStyle(oContent,"overflowY")=="auto"));if(scrollOn&&(nNewItemIndex>-1)&&(nNewItemIndex(oContent.scrollTop+oContent.offsetHeight)){oContent.scrollTop=(oNewItem.offsetTop+oNewItem.offsetHeight)-oContent.offsetHeight;} +else if((oNewItem.offsetTop+oNewItem.offsetHeight)(oContent.scrollTop+oContent.offsetHeight)){this._oContainer._oContent.scrollTop=(oNewItem.offsetTop+oNewItem.offsetHeight)-oContent.offsetHeight;}}} +this._toggleHighlight(oNewItem,"to");this.itemArrowToEvent.fire(this,oNewItem);if(this.typeAhead){this._updateValue(oNewItem);}}};YAHOO.widget.AutoComplete.prototype._onItemMouseover=function(v,oSelf){if(oSelf.prehighlightClassName){oSelf._togglePrehighlight(this,"mouseover");} +else{oSelf._toggleHighlight(this,"to");} +oSelf.itemMouseOverEvent.fire(oSelf,this);};YAHOO.widget.AutoComplete.prototype._onItemMouseout=function(v,oSelf){if(oSelf.prehighlightClassName){oSelf._togglePrehighlight(this,"mouseout");} +else{oSelf._toggleHighlight(this,"from");} +oSelf.itemMouseOutEvent.fire(oSelf,this);};YAHOO.widget.AutoComplete.prototype._onItemMouseclick=function(v,oSelf){oSelf._toggleHighlight(this,"to");oSelf._selectItem(this);};YAHOO.widget.AutoComplete.prototype._onContainerMouseover=function(v,oSelf){oSelf._bOverContainer=true;};YAHOO.widget.AutoComplete.prototype._onContainerMouseout=function(v,oSelf){oSelf._bOverContainer=false;if(oSelf._oCurItem){oSelf._toggleHighlight(oSelf._oCurItem,"to");}};YAHOO.widget.AutoComplete.prototype._onContainerScroll=function(v,oSelf){oSelf._oTextbox.focus();};YAHOO.widget.AutoComplete.prototype._onContainerResize=function(v,oSelf){oSelf._toggleContainerHelpers(oSelf._bContainerOpen);};YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown=function(v,oSelf){var nKeyCode=v.keyCode;switch(nKeyCode){case 9:if(oSelf.delimChar&&(oSelf._nKeyCode!=nKeyCode)){if(oSelf._bContainerOpen){YAHOO.util.Event.stopEvent(v);}} +if(oSelf._oCurItem){oSelf._selectItem(oSelf._oCurItem);} +else{oSelf._toggleContainer(false);} +break;case 13:if(oSelf._nKeyCode!=nKeyCode){if(oSelf._bContainerOpen){YAHOO.util.Event.stopEvent(v);}} +if(oSelf._oCurItem){oSelf._selectItem(oSelf._oCurItem);} +else{oSelf._toggleContainer(false);} +break;case 27:oSelf._toggleContainer(false);return;case 39:oSelf._jumpSelection();break;case 38:YAHOO.util.Event.stopEvent(v);oSelf._moveSelection(nKeyCode);break;case 40:YAHOO.util.Event.stopEvent(v);oSelf._moveSelection(nKeyCode);break;default:break;}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress=function(v,oSelf){var nKeyCode=v.keyCode;var isMac=(navigator.userAgent.toLowerCase().indexOf("mac")!=-1);if(isMac){switch(nKeyCode){case 9:if(oSelf.delimChar&&(oSelf._nKeyCode!=nKeyCode)){if(oSelf._bContainerOpen){YAHOO.util.Event.stopEvent(v);}} +break;case 13:if(oSelf._nKeyCode!=nKeyCode){if(oSelf._bContainerOpen){YAHOO.util.Event.stopEvent(v);}} +break;case 38:case 40:YAHOO.util.Event.stopEvent(v);break;default:break;}} +else if(nKeyCode==229){oSelf._queryInterval=setInterval(function(){oSelf._onIMEDetected(oSelf);},500);}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp=function(v,oSelf){oSelf._initProps();var nKeyCode=v.keyCode;oSelf._nKeyCode=nKeyCode;var sText=this.value;if(oSelf._isIgnoreKey(nKeyCode)||(sText.toLowerCase()==oSelf._sCurQuery)){return;} +else{oSelf.textboxKeyEvent.fire(oSelf,nKeyCode);} +if(oSelf.queryDelay>0){var nDelayID=setTimeout(function(){oSelf._sendQuery(sText);},(oSelf.queryDelay*1000));if(oSelf._nDelayID!=-1){clearTimeout(oSelf._nDelayID);} +oSelf._nDelayID=nDelayID;} +else{oSelf._sendQuery(sText);}};YAHOO.widget.AutoComplete.prototype._onTextboxFocus=function(v,oSelf){oSelf._oTextbox.setAttribute("autocomplete","off");oSelf._bFocused=true;oSelf.textboxFocusEvent.fire(oSelf);};YAHOO.widget.AutoComplete.prototype._onTextboxBlur=function(v,oSelf){if(!oSelf._bOverContainer||(oSelf._nKeyCode==9)){if(!oSelf._bItemSelected){if(!oSelf._bContainerOpen||(oSelf._bContainerOpen&&!oSelf._textMatchesOption())){if(oSelf.forceSelection){oSelf._clearSelection();} +else{oSelf.unmatchedItemSelectEvent.fire(oSelf,oSelf._sCurQuery);}}} +if(oSelf._bContainerOpen){oSelf._toggleContainer(false);} +oSelf._cancelIntervalDetection(oSelf);oSelf._bFocused=false;oSelf.textboxBlurEvent.fire(oSelf);}};YAHOO.widget.AutoComplete.prototype._onFormSubmit=function(v,oSelf){if(oSelf.allowBrowserAutocomplete){oSelf._oTextbox.setAttribute("autocomplete","on");} +else{oSelf._oTextbox.setAttribute("autocomplete","off");}};YAHOO.widget.DataSource=function(){};YAHOO.widget.DataSource.ERROR_DATANULL="Response data was null";YAHOO.widget.DataSource.ERROR_DATAPARSE="Response data could not be parsed";YAHOO.widget.DataSource.prototype.maxCacheEntries=15;YAHOO.widget.DataSource.prototype.queryMatchContains=false;YAHOO.widget.DataSource.prototype.queryMatchSubset=false;YAHOO.widget.DataSource.prototype.queryMatchCase=false;YAHOO.widget.DataSource.prototype.toString=function(){return"DataSource "+this._sName;};YAHOO.widget.DataSource.prototype.getResults=function(oCallbackFn,sQuery,oParent){var aResults=this._doQueryCache(oCallbackFn,sQuery,oParent);if(aResults.length===0){this.queryEvent.fire(this,oParent,sQuery);this.doQuery(oCallbackFn,sQuery,oParent);}};YAHOO.widget.DataSource.prototype.doQuery=function(oCallbackFn,sQuery,oParent){};YAHOO.widget.DataSource.prototype.flushCache=function(){if(this._aCache){this._aCache=[];} +if(this._aCacheHelper){this._aCacheHelper=[];} +this.cacheFlushEvent.fire(this);};YAHOO.widget.DataSource.prototype.queryEvent=null;YAHOO.widget.DataSource.prototype.cacheQueryEvent=null;YAHOO.widget.DataSource.prototype.getResultsEvent=null;YAHOO.widget.DataSource.prototype.getCachedResultsEvent=null;YAHOO.widget.DataSource.prototype.dataErrorEvent=null;YAHOO.widget.DataSource.prototype.cacheFlushEvent=null;YAHOO.widget.DataSource._nIndex=0;YAHOO.widget.DataSource.prototype._sName=null;YAHOO.widget.DataSource.prototype._aCache=null;YAHOO.widget.DataSource.prototype._init=function(){var maxCacheEntries=this.maxCacheEntries;if(isNaN(maxCacheEntries)||(maxCacheEntries<0)){maxCacheEntries=0;} +if(maxCacheEntries>0&&!this._aCache){this._aCache=[];} +this._sName="instance"+YAHOO.widget.DataSource._nIndex;YAHOO.widget.DataSource._nIndex++;this.queryEvent=new YAHOO.util.CustomEvent("query",this);this.cacheQueryEvent=new YAHOO.util.CustomEvent("cacheQuery",this);this.getResultsEvent=new YAHOO.util.CustomEvent("getResults",this);this.getCachedResultsEvent=new YAHOO.util.CustomEvent("getCachedResults",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.cacheFlushEvent=new YAHOO.util.CustomEvent("cacheFlush",this);};YAHOO.widget.DataSource.prototype._addCacheElem=function(oResult){var aCache=this._aCache;if(!aCache||!oResult||!oResult.query||!oResult.results){return;} +if(aCache.length>=this.maxCacheEntries){aCache.shift();} +aCache.push(oResult);};YAHOO.widget.DataSource.prototype._doQueryCache=function(oCallbackFn,sQuery,oParent){var aResults=[];var bMatchFound=false;var aCache=this._aCache;var nCacheLength=(aCache)?aCache.length:0;var bMatchContains=this.queryMatchContains;if((this.maxCacheEntries>0)&&aCache&&(nCacheLength>0)){this.cacheQueryEvent.fire(this,oParent,sQuery);if(!this.queryMatchCase){var sOrigQuery=sQuery;sQuery=sQuery.toLowerCase();} +for(var i=nCacheLength-1;i>=0;i--){var resultObj=aCache[i];var aAllResultItems=resultObj.results;var matchKey=(!this.queryMatchCase)?encodeURIComponent(resultObj.query).toLowerCase():encodeURIComponent(resultObj.query);if(matchKey==sQuery){bMatchFound=true;aResults=aAllResultItems;if(i!=nCacheLength-1){aCache.splice(i,1);this._addCacheElem(resultObj);} +break;} +else if(this.queryMatchSubset){for(var j=sQuery.length-1;j>=0;j--){var subQuery=sQuery.substr(0,j);if(matchKey==subQuery){bMatchFound=true;for(var k=aAllResultItems.length-1;k>=0;k--){var aRecord=aAllResultItems[k];var sKeyIndex=(this.queryMatchCase)?encodeURIComponent(aRecord[0]).indexOf(sQuery):encodeURIComponent(aRecord[0]).toLowerCase().indexOf(sQuery);if((!bMatchContains&&(sKeyIndex===0))||(bMatchContains&&(sKeyIndex>-1))){aResults.unshift(aRecord);}} +resultObj={};resultObj.query=sQuery;resultObj.results=aResults;this._addCacheElem(resultObj);break;}} +if(bMatchFound){break;}}} +if(bMatchFound){this.getCachedResultsEvent.fire(this,oParent,sOrigQuery,aResults);oCallbackFn(sOrigQuery,aResults,oParent);}} +return aResults;};YAHOO.widget.DS_XHR=function(sScriptURI,aSchema,oConfigs){if(typeof oConfigs=="object"){for(var sConfig in oConfigs){this[sConfig]=oConfigs[sConfig];}} +if(!aSchema||(aSchema.constructor!=Array)){return;} +else{this.schema=aSchema;} +this.scriptURI=sScriptURI;this._init();};YAHOO.widget.DS_XHR.prototype=new YAHOO.widget.DataSource();YAHOO.widget.DS_XHR.TYPE_JSON=0;YAHOO.widget.DS_XHR.TYPE_XML=1;YAHOO.widget.DS_XHR.TYPE_FLAT=2;YAHOO.widget.DS_XHR.ERROR_DATAXHR="XHR response failed";YAHOO.widget.DS_XHR.prototype.connMgr=YAHOO.util.Connect;YAHOO.widget.DS_XHR.prototype.connTimeout=0;YAHOO.widget.DS_XHR.prototype.scriptURI=null;YAHOO.widget.DS_XHR.prototype.scriptQueryParam="query";YAHOO.widget.DS_XHR.prototype.scriptQueryAppend="";YAHOO.widget.DS_XHR.prototype.responseType=YAHOO.widget.DS_XHR.TYPE_JSON;YAHOO.widget.DS_XHR.prototype.responseStripAfter="\n0){sUri+="&"+this.scriptQueryAppend;} +var oResponse=null;var oSelf=this;var responseSuccess=function(oResp){if(!oSelf._oConn||(oResp.tId!=oSelf._oConn.tId)){oSelf.dataErrorEvent.fire(oSelf,oParent,sQuery,YAHOO.widget.DataSource.ERROR_DATANULL);return;} +for(var foo in oResp){} +if(!isXML){oResp=oResp.responseText;} +else{oResp=oResp.responseXML;} +if(oResp===null){oSelf.dataErrorEvent.fire(oSelf,oParent,sQuery,YAHOO.widget.DataSource.ERROR_DATANULL);return;} +var aResults=oSelf.parseResponse(sQuery,oResp,oParent);var resultObj={};resultObj.query=decodeURIComponent(sQuery);resultObj.results=aResults;if(aResults===null){oSelf.dataErrorEvent.fire(oSelf,oParent,sQuery,YAHOO.widget.DataSource.ERROR_DATAPARSE);aResults=[];} +else{oSelf.getResultsEvent.fire(oSelf,oParent,sQuery,aResults);oSelf._addCacheElem(resultObj);} +oCallbackFn(sQuery,aResults,oParent);};var responseFailure=function(oResp){oSelf.dataErrorEvent.fire(oSelf,oParent,sQuery,YAHOO.widget.DS_XHR.ERROR_DATAXHR);return;};var oCallback={success:responseSuccess,failure:responseFailure};if(!isNaN(this.connTimeout)&&this.connTimeout>0){oCallback.timeout=this.connTimeout;} +if(this._oConn){this.connMgr.abort(this._oConn);} +oSelf._oConn=this.connMgr.asyncRequest("GET",sUri,oCallback,null);};YAHOO.widget.DS_XHR.prototype.parseResponse=function(sQuery,oResponse,oParent){var aSchema=this.schema;var aResults=[];var bError=false;var nEnd=((this.responseStripAfter!=="")&&(oResponse.indexOf))?oResponse.indexOf(this.responseStripAfter):-1;if(nEnd!=-1){oResponse=oResponse.substring(0,nEnd);} +switch(this.responseType){case YAHOO.widget.DS_XHR.TYPE_JSON:var jsonList;if(window.JSON&&(navigator.userAgent.toLowerCase().indexOf('khtml')==-1)){var jsonObjParsed=JSON.parse(oResponse);if(!jsonObjParsed){bError=true;break;} +else{try{jsonList=eval("jsonObjParsed."+aSchema[0]);} +catch(e){bError=true;break;}}} +else{try{while(oResponse.substring(0,1)==" "){oResponse=oResponse.substring(1,oResponse.length);} +if(oResponse.indexOf("{")<0){bError=true;break;} +if(oResponse.indexOf("{}")===0){break;} +var jsonObjRaw=eval("("+oResponse+")");if(!jsonObjRaw){bError=true;break;} +jsonList=eval("(jsonObjRaw."+aSchema[0]+")");} +catch(e){bError=true;break;}} +if(!jsonList){bError=true;break;} +if(jsonList.constructor!=Array){jsonList=[jsonList];} +for(var i=jsonList.length-1;i>=0;i--){var aResultItem=[];var jsonResult=jsonList[i];for(var j=aSchema.length-1;j>=1;j--){var dataFieldValue=jsonResult[aSchema[j]];if(!dataFieldValue){dataFieldValue="";} +aResultItem.unshift(dataFieldValue);} +if(aResultItem.length==1){aResultItem.push(jsonResult);} +aResults.unshift(aResultItem);} +break;case YAHOO.widget.DS_XHR.TYPE_XML:var xmlList=oResponse.getElementsByTagName(aSchema[0]);if(!xmlList){bError=true;break;} +for(var k=xmlList.length-1;k>=0;k--){var result=xmlList.item(k);var aFieldSet=[];for(var m=aSchema.length-1;m>=1;m--){var sValue=null;var xmlAttr=result.attributes.getNamedItem(aSchema[m]);if(xmlAttr){sValue=xmlAttr.value;} +else{var xmlNode=result.getElementsByTagName(aSchema[m]);if(xmlNode&&xmlNode.item(0)&&xmlNode.item(0).firstChild){sValue=xmlNode.item(0).firstChild.nodeValue;} +else{sValue="";}} +aFieldSet.unshift(sValue);} +aResults.unshift(aFieldSet);} +break;case YAHOO.widget.DS_XHR.TYPE_FLAT:if(oResponse.length>0){var newLength=oResponse.length-aSchema[0].length;if(oResponse.substr(newLength)==aSchema[0]){oResponse=oResponse.substr(0,newLength);} +var aRecords=oResponse.split(aSchema[0]);for(var n=aRecords.length-1;n>=0;n--){aResults[n]=aRecords[n].split(aSchema[1]);}} +break;default:break;} +sQuery=null;oResponse=null;oParent=null;if(bError){return null;} +else{return aResults;}};YAHOO.widget.DS_XHR.prototype._oConn=null;YAHOO.widget.DS_JSFunction=function(oFunction,oConfigs){if(typeof oConfigs=="object"){for(var sConfig in oConfigs){this[sConfig]=oConfigs[sConfig];}} +if(!oFunction||(oFunction.constructor!=Function)){return;} +else{this.dataFunction=oFunction;this._init();}};YAHOO.widget.DS_JSFunction.prototype=new YAHOO.widget.DataSource();YAHOO.widget.DS_JSFunction.prototype.dataFunction=null;YAHOO.widget.DS_JSFunction.prototype.doQuery=function(oCallbackFn,sQuery,oParent){var oFunction=this.dataFunction;var aResults=[];aResults=oFunction(sQuery);if(aResults===null){this.dataErrorEvent.fire(this,oParent,sQuery,YAHOO.widget.DataSource.ERROR_DATANULL);return;} +var resultObj={};resultObj.query=decodeURIComponent(sQuery);resultObj.results=aResults;this._addCacheElem(resultObj);this.getResultsEvent.fire(this,oParent,sQuery,aResults);oCallbackFn(sQuery,aResults,oParent);return;};YAHOO.widget.DS_JSArray=function(aData,oConfigs){if(typeof oConfigs=="object"){for(var sConfig in oConfigs){this[sConfig]=oConfigs[sConfig];}} +if(!aData||(aData.constructor!=Array)){return;} +else{this.data=aData;this._init();}};YAHOO.widget.DS_JSArray.prototype=new YAHOO.widget.DataSource();YAHOO.widget.DS_JSArray.prototype.data=null;YAHOO.widget.DS_JSArray.prototype.doQuery=function(oCallbackFn,sQuery,oParent){var aData=this.data;var aResults=[];var bMatchFound=false;var bMatchContains=this.queryMatchContains;if(sQuery){if(!this.queryMatchCase){sQuery=sQuery.toLowerCase();} +for(var i=aData.length-1;i>=0;i--){var aDataset=[];if(aData[i]){if(aData[i].constructor==String){aDataset[0]=aData[i];} +else if(aData[i].constructor==Array){aDataset=aData[i];}} +if(aDataset[0]&&(aDataset[0].constructor==String)){var sKeyIndex=(this.queryMatchCase)?encodeURIComponent(aDataset[0]).indexOf(sQuery):encodeURIComponent(aDataset[0]).toLowerCase().indexOf(sQuery);if((!bMatchContains&&(sKeyIndex===0))||(bMatchContains&&(sKeyIndex>-1))){aResults.unshift(aDataset);}}}} this.getResultsEvent.fire(this,oParent,sQuery,aResults);oCallbackFn(sQuery,aResults,oParent);}; \ No newline at end of file diff --git a/lib/yui/autocomplete/autocomplete.js b/lib/yui/autocomplete/autocomplete.js index 548fff1201..a39a98780b 100755 --- a/lib/yui/autocomplete/autocomplete.js +++ b/lib/yui/autocomplete/autocomplete.js @@ -1,10 +1,9 @@ -/* -Copyright (c) 2006, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.com/yui/license.txt -version: 0.12.1 -*/ - +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 0.12.2 +*/ /** * The AutoComplete control provides the front-end logic for text-entry suggestion and * completion functionality. @@ -134,7 +133,7 @@ YAHOO.widget.AutoComplete = function(elInput,elContainer,oDataSource,oConfigs) { this.selectionEnforceEvent = new YAHOO.util.CustomEvent("selectionEnforce", this); this.containerCollapseEvent = new YAHOO.util.CustomEvent("containerCollapse", this); this.textboxBlurEvent = new YAHOO.util.CustomEvent("textboxBlur", this); - + // Finish up oTextbox.setAttribute("autocomplete","off"); YAHOO.widget.AutoComplete._nIndex++; @@ -510,7 +509,7 @@ YAHOO.widget.AutoComplete.prototype.textboxKeyEvent = null; /** * Fired when the AutoComplete instance makes a query to the DataSource. - * + * * @event dataRequestEvent * @param oSelf {Object} The AutoComplete instance. * @param sQuery {String} The query string. @@ -548,7 +547,7 @@ YAHOO.widget.AutoComplete.prototype.containerExpandEvent = null; /** * Fired when the input field has been prefilled by the type-ahead - * feature. + * feature. * * @event typeAheadEvent * @param oSelf {Object} The AutoComplete instance. @@ -576,7 +575,7 @@ YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent = null; YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent = null; /** - * Fired when result item has been arrowed to. + * Fired when result item has been arrowed to. * * @event itemArrowToEvent * @param oSelf {Object} The AutoComplete instance. @@ -607,7 +606,7 @@ YAHOO.widget.AutoComplete.prototype.itemSelectEvent = null; /** * Fired when a user selection does not match any of the displayed result items. * Note that this event may not behave as expected when delimiter characters - * have been defined. + * have been defined. * * @event unmatchedItemSelectEvent * @param oSelf {Object} The AutoComplete instance. @@ -1360,7 +1359,7 @@ YAHOO.widget.AutoComplete.prototype._toggleContainer = function(bShow) { if(this.alwaysShowContainer && this._bContainerOpen) { return; } - + // Clear contents of container if(!bShow) { this._oContainer._oContent.scrollTop = 0; @@ -2002,1065 +2001,1065 @@ YAHOO.widget.AutoComplete.prototype._onFormSubmit = function(v,oSelf) { oSelf._oTextbox.setAttribute("autocomplete","off"); } }; -/****************************************************************************/ -/****************************************************************************/ -/****************************************************************************/ - -/** - * The DataSource classes manages sending a request and returning response from a live - * database. Supported data include local JavaScript arrays and objects and databases - * accessible via XHR connections. Supported response formats include JavaScript arrays, - * JSON, XML, and flat-file textual data. - * - * @class DataSource - * @constructor - */ -YAHOO.widget.DataSource = function() { - /* abstract class */ -}; - - -///////////////////////////////////////////////////////////////////////////// -// -// Public constants -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Error message for null data responses. - * - * @property ERROR_DATANULL - * @type String - * @static - * @final - */ -YAHOO.widget.DataSource.ERROR_DATANULL = "Response data was null"; - -/** - * Error message for data responses with parsing errors. - * - * @property ERROR_DATAPARSE - * @type String - * @static - * @final - */ -YAHOO.widget.DataSource.ERROR_DATAPARSE = "Response data could not be parsed"; - - -///////////////////////////////////////////////////////////////////////////// -// -// Public member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Max size of the local cache. Set to 0 to turn off caching. Caching is - * useful to reduce the number of server connections. Recommended only for data - * sources that return comprehensive results for queries or when stale data is - * not an issue. - * - * @property maxCacheEntries - * @type Number - * @default 15 - */ -YAHOO.widget.DataSource.prototype.maxCacheEntries = 15; - -/** - * Use this to equate cache matching with the type of matching done by your live - * data source. If caching is on and queryMatchContains is true, the cache - * returns results that "contain" the query string. By default, - * queryMatchContains is set to false, meaning the cache only returns results - * that "start with" the query string. - * - * @property queryMatchContains - * @type Boolean - * @default false - */ -YAHOO.widget.DataSource.prototype.queryMatchContains = false; - -/** - * Enables query subset matching. If caching is on and queryMatchSubset is - * true, substrings of queries will return matching cached results. For - * instance, if the first query is for "abc" susequent queries that start with - * "abc", like "abcd", will be queried against the cache, and not the live data - * source. Recommended only for DataSources that return comprehensive results - * for queries with very few characters. - * - * @property queryMatchSubset - * @type Boolean - * @default false - * - */ -YAHOO.widget.DataSource.prototype.queryMatchSubset = false; - -/** - * Enables query case-sensitivity matching. If caching is on and - * queryMatchCase is true, queries will only return results for case-sensitive - * matches. - * - * @property queryMatchCase - * @type Boolean - * @default false - */ -YAHOO.widget.DataSource.prototype.queryMatchCase = false; - - -///////////////////////////////////////////////////////////////////////////// -// -// Public methods -// -///////////////////////////////////////////////////////////////////////////// - - /** - * Public accessor to the unique name of the DataSource instance. - * - * @method toString - * @return {String} Unique name of the DataSource instance - */ -YAHOO.widget.DataSource.prototype.toString = function() { - return "DataSource " + this._sName; -}; - -/** - * Retrieves query results, first checking the local cache, then making the - * query request to the live data source as defined by the function doQuery. - * - * @method getResults - * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. - * @param sQuery {String} Query string. - * @param oParent {Object} The object instance that has requested data. - */ -YAHOO.widget.DataSource.prototype.getResults = function(oCallbackFn, sQuery, oParent) { - - // First look in cache - var aResults = this._doQueryCache(oCallbackFn,sQuery,oParent); - - // Not in cache, so get results from server - if(aResults.length === 0) { - this.queryEvent.fire(this, oParent, sQuery); - this.doQuery(oCallbackFn, sQuery, oParent); - } -}; - -/** - * Abstract method implemented by subclasses to make a query to the live data - * source. Must call the callback function with the response returned from the - * query. Populates cache (if enabled). - * - * @method doQuery - * @param oCallbackFn {HTMLFunction} Callback function implemented by oParent to which to return results. - * @param sQuery {String} Query string. - * @param oParent {Object} The object instance that has requested data. - */ -YAHOO.widget.DataSource.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { - /* override this */ -}; - -/** - * Flushes cache. - * - * @method flushCache - */ -YAHOO.widget.DataSource.prototype.flushCache = function() { - if(this._aCache) { - this._aCache = []; - } - if(this._aCacheHelper) { - this._aCacheHelper = []; - } - this.cacheFlushEvent.fire(this); -}; - -///////////////////////////////////////////////////////////////////////////// -// -// Public events -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Fired when a query is made to the live data source. - * - * @event queryEvent - * @param oSelf {Object} The DataSource instance. - * @param oParent {Object} The requesting object. - * @param sQuery {String} The query string. - */ -YAHOO.widget.DataSource.prototype.queryEvent = null; - -/** - * Fired when a query is made to the local cache. - * - * @event cacheQueryEvent - * @param oSelf {Object} The DataSource instance. - * @param oParent {Object} The requesting object. - * @param sQuery {String} The query string. - */ -YAHOO.widget.DataSource.prototype.cacheQueryEvent = null; - -/** - * Fired when data is retrieved from the live data source. - * - * @event getResultsEvent - * @param oSelf {Object} The DataSource instance. - * @param oParent {Object} The requesting object. - * @param sQuery {String} The query string. - * @param aResults {Object[]} Array of result objects. - */ -YAHOO.widget.DataSource.prototype.getResultsEvent = null; - -/** - * Fired when data is retrieved from the local cache. - * - * @event getCachedResultsEvent - * @param oSelf {Object} The DataSource instance. - * @param oParent {Object} The requesting object. - * @param sQuery {String} The query string. - * @param aResults {Object[]} Array of result objects. - */ -YAHOO.widget.DataSource.prototype.getCachedResultsEvent = null; - -/** - * Fired when an error is encountered with the live data source. - * - * @event dataErrorEvent - * @param oSelf {Object} The DataSource instance. - * @param oParent {Object} The requesting object. - * @param sQuery {String} The query string. - * @param sMsg {String} Error message string - */ -YAHOO.widget.DataSource.prototype.dataErrorEvent = null; - -/** - * Fired when the local cache is flushed. - * - * @event cacheFlushEvent - * @param oSelf {Object} The DataSource instance - */ -YAHOO.widget.DataSource.prototype.cacheFlushEvent = null; - -///////////////////////////////////////////////////////////////////////////// -// -// Private member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Internal class variable to index multiple DataSource instances. - * - * @property _nIndex - * @type Number - * @private - * @static - */ -YAHOO.widget.DataSource._nIndex = 0; - -/** - * Name of DataSource instance. - * - * @property _sName - * @type String - * @private - */ -YAHOO.widget.DataSource.prototype._sName = null; - -/** - * Local cache of data result objects indexed chronologically. - * - * @property _aCache - * @type Object[] - * @private - */ -YAHOO.widget.DataSource.prototype._aCache = null; - - -///////////////////////////////////////////////////////////////////////////// -// -// Private methods -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Initializes DataSource instance. - * - * @method _init - * @private - */ -YAHOO.widget.DataSource.prototype._init = function() { - // Validate and initialize public configs - var maxCacheEntries = this.maxCacheEntries; - if(isNaN(maxCacheEntries) || (maxCacheEntries < 0)) { - maxCacheEntries = 0; - } - // Initialize local cache - if(maxCacheEntries > 0 && !this._aCache) { - this._aCache = []; - } - - this._sName = "instance" + YAHOO.widget.DataSource._nIndex; - YAHOO.widget.DataSource._nIndex++; - - this.queryEvent = new YAHOO.util.CustomEvent("query", this); - this.cacheQueryEvent = new YAHOO.util.CustomEvent("cacheQuery", this); - this.getResultsEvent = new YAHOO.util.CustomEvent("getResults", this); - this.getCachedResultsEvent = new YAHOO.util.CustomEvent("getCachedResults", this); - this.dataErrorEvent = new YAHOO.util.CustomEvent("dataError", this); - this.cacheFlushEvent = new YAHOO.util.CustomEvent("cacheFlush", this); -}; - -/** - * Adds a result object to the local cache, evicting the oldest element if the - * cache is full. Newer items will have higher indexes, the oldest item will have - * index of 0. - * - * @method _addCacheElem - * @param oResult {Object} Data result object, including array of results. - * @private - */ -YAHOO.widget.DataSource.prototype._addCacheElem = function(oResult) { - var aCache = this._aCache; - // Don't add if anything important is missing. - if(!aCache || !oResult || !oResult.query || !oResult.results) { - return; - } - - // If the cache is full, make room by removing from index=0 - if(aCache.length >= this.maxCacheEntries) { - aCache.shift(); - } - - // Add to cache, at the end of the array - aCache.push(oResult); -}; - -/** - * Queries the local cache for results. If query has been cached, the callback - * function is called with the results, and the cached is refreshed so that it - * is now the newest element. - * - * @method _doQueryCache - * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. - * @param sQuery {String} Query string. - * @param oParent {Object} The object instance that has requested data. - * @return aResults {Object[]} Array of results from local cache if found, otherwise null. - * @private - */ -YAHOO.widget.DataSource.prototype._doQueryCache = function(oCallbackFn, sQuery, oParent) { - var aResults = []; - var bMatchFound = false; - var aCache = this._aCache; - var nCacheLength = (aCache) ? aCache.length : 0; - var bMatchContains = this.queryMatchContains; - - // If cache is enabled... - if((this.maxCacheEntries > 0) && aCache && (nCacheLength > 0)) { - this.cacheQueryEvent.fire(this, oParent, sQuery); - // If case is unimportant, normalize query now instead of in loops - if(!this.queryMatchCase) { - var sOrigQuery = sQuery; - sQuery = sQuery.toLowerCase(); - } - - // Loop through each cached element's query property... - for(var i = nCacheLength-1; i >= 0; i--) { - var resultObj = aCache[i]; - var aAllResultItems = resultObj.results; - // If case is unimportant, normalize match key for comparison - var matchKey = (!this.queryMatchCase) ? - encodeURIComponent(resultObj.query).toLowerCase(): - encodeURIComponent(resultObj.query); - - // If a cached match key exactly matches the query... - if(matchKey == sQuery) { - // Stash all result objects into aResult[] and stop looping through the cache. - bMatchFound = true; - aResults = aAllResultItems; - - // The matching cache element was not the most recent, - // so now we need to refresh the cache. - if(i != nCacheLength-1) { - // Remove element from its original location - aCache.splice(i,1); - // Add element as newest - this._addCacheElem(resultObj); - } - break; - } - // Else if this query is not an exact match and subset matching is enabled... - else if(this.queryMatchSubset) { - // Loop through substrings of each cached element's query property... - for(var j = sQuery.length-1; j >= 0 ; j--) { - var subQuery = sQuery.substr(0,j); - - // If a substring of a cached sQuery exactly matches the query... - if(matchKey == subQuery) { - bMatchFound = true; - - // Go through each cached result object to match against the query... - for(var k = aAllResultItems.length-1; k >= 0; k--) { - var aRecord = aAllResultItems[k]; - var sKeyIndex = (this.queryMatchCase) ? - encodeURIComponent(aRecord[0]).indexOf(sQuery): - encodeURIComponent(aRecord[0]).toLowerCase().indexOf(sQuery); - - // A STARTSWITH match is when the query is found at the beginning of the key string... - if((!bMatchContains && (sKeyIndex === 0)) || - // A CONTAINS match is when the query is found anywhere within the key string... - (bMatchContains && (sKeyIndex > -1))) { - // Stash a match into aResults[]. - aResults.unshift(aRecord); - } - } - - // Add the subset match result set object as the newest element to cache, - // and stop looping through the cache. - resultObj = {}; - resultObj.query = sQuery; - resultObj.results = aResults; - this._addCacheElem(resultObj); - break; - } - } - if(bMatchFound) { - break; - } - } - } - - // If there was a match, send along the results. - if(bMatchFound) { - this.getCachedResultsEvent.fire(this, oParent, sOrigQuery, aResults); - oCallbackFn(sOrigQuery, aResults, oParent); - } - } - return aResults; -}; - - -/****************************************************************************/ -/****************************************************************************/ -/****************************************************************************/ - -/** - * Implementation of YAHOO.widget.DataSource using XML HTTP requests that return - * query results. - * - * @class DS_XHR - * @extends YAHOO.widget.DataSource - * @requires connection - * @constructor - * @param sScriptURI {String} Absolute or relative URI to script that returns query - * results as JSON, XML, or delimited flat-file data. - * @param aSchema {String[]} Data schema definition of results. - * @param oConfigs {Object} (optional) Object literal of config params. - */ -YAHOO.widget.DS_XHR = function(sScriptURI, aSchema, oConfigs) { - // Set any config params passed in to override defaults - if(typeof oConfigs == "object") { - for(var sConfig in oConfigs) { - this[sConfig] = oConfigs[sConfig]; - } - } - - // Initialization sequence - if(!aSchema || (aSchema.constructor != Array)) { - return; - } - else { - this.schema = aSchema; - } - this.scriptURI = sScriptURI; - this._init(); -}; - -YAHOO.widget.DS_XHR.prototype = new YAHOO.widget.DataSource(); - -///////////////////////////////////////////////////////////////////////////// -// -// Public constants -// -///////////////////////////////////////////////////////////////////////////// - -/** - * JSON data type. - * - * @property TYPE_JSON - * @type Number - * @static - * @final - */ -YAHOO.widget.DS_XHR.TYPE_JSON = 0; - -/** - * XML data type. - * - * @property TYPE_XML - * @type Number - * @static - * @final - */ -YAHOO.widget.DS_XHR.TYPE_XML = 1; - -/** - * Flat-file data type. - * - * @property TYPE_FLAT - * @type Number - * @static - * @final - */ -YAHOO.widget.DS_XHR.TYPE_FLAT = 2; - -/** - * Error message for XHR failure. - * - * @property ERROR_DATAXHR - * @type String - * @static - * @final - */ -YAHOO.widget.DS_XHR.ERROR_DATAXHR = "XHR response failed"; - -///////////////////////////////////////////////////////////////////////////// -// -// Public member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Alias to YUI Connection Manager. Allows implementers to specify their own - * subclasses of the YUI Connection Manager utility. - * - * @property connMgr - * @type Object - * @default YAHOO.util.Connect - */ -YAHOO.widget.DS_XHR.prototype.connMgr = YAHOO.util.Connect; - -/** - * Number of milliseconds the XHR connection will wait for a server response. A - * a value of zero indicates the XHR connection will wait forever. Any value - * greater than zero will use the Connection utility's Auto-Abort feature. - * - * @property connTimeout - * @type Number - * @default 0 - */ -YAHOO.widget.DS_XHR.prototype.connTimeout = 0; - -/** - * Absolute or relative URI to script that returns query results. For instance, - * queries will be sent to <scriptURI>?<scriptQueryParam>=userinput - * - * @property scriptURI - * @type String - */ -YAHOO.widget.DS_XHR.prototype.scriptURI = null; - -/** - * Query string parameter name sent to scriptURI. For instance, queries will be - * sent to <scriptURI>?<scriptQueryParam>=userinput - * - * @property scriptQueryParam - * @type String - * @default "query" - */ -YAHOO.widget.DS_XHR.prototype.scriptQueryParam = "query"; - -/** - * String of key/value pairs to append to requests made to scriptURI. Define - * this string when you want to send additional query parameters to your script. - * When defined, queries will be sent to - * <scriptURI>?<scriptQueryParam>=userinput&<scriptQueryAppend> - * - * @property scriptQueryAppend - * @type String - * @default "" - */ -YAHOO.widget.DS_XHR.prototype.scriptQueryAppend = ""; - -/** - * XHR response data type. Other types that may be defined are YAHOO.widget.DS_XHR.TYPE_XML - * and YAHOO.widget.DS_XHR.TYPE_FLAT. - * - * @property responseType - * @type String - * @default YAHOO.widget.DS_XHR.TYPE_JSON - */ -YAHOO.widget.DS_XHR.prototype.responseType = YAHOO.widget.DS_XHR.TYPE_JSON; - -/** - * String after which to strip results. If the results from the XHR are sent - * back as HTML, the gzip HTML comment appears at the end of the data and should - * be ignored. - * - * @property responseStripAfter - * @type String - * @default "\n<!-" - */ -YAHOO.widget.DS_XHR.prototype.responseStripAfter = "\n 0) { - sUri += "&" + this.scriptQueryAppend; - } - var oResponse = null; - - var oSelf = this; - /* - * Sets up ajax request callback - * - * @param {object} oReq HTTPXMLRequest object - * @private - */ - var responseSuccess = function(oResp) { - // Response ID does not match last made request ID. - if(!oSelf._oConn || (oResp.tId != oSelf._oConn.tId)) { - oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); - return; - } -//DEBUG -for(var foo in oResp) { -} - if(!isXML) { - oResp = oResp.responseText; - } - else { - oResp = oResp.responseXML; - } - if(oResp === null) { - oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); - return; - } - - var aResults = oSelf.parseResponse(sQuery, oResp, oParent); - var resultObj = {}; - resultObj.query = decodeURIComponent(sQuery); - resultObj.results = aResults; - if(aResults === null) { - oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATAPARSE); - aResults = []; - } - else { - oSelf.getResultsEvent.fire(oSelf, oParent, sQuery, aResults); - oSelf._addCacheElem(resultObj); - } - oCallbackFn(sQuery, aResults, oParent); - }; - - var responseFailure = function(oResp) { - oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DS_XHR.ERROR_DATAXHR); - return; - }; - - var oCallback = { - success:responseSuccess, - failure:responseFailure - }; - - if(!isNaN(this.connTimeout) && this.connTimeout > 0) { - oCallback.timeout = this.connTimeout; - } - - if(this._oConn) { - this.connMgr.abort(this._oConn); - } - - oSelf._oConn = this.connMgr.asyncRequest("GET", sUri, oCallback, null); -}; - -/** - * Parses raw response data into an array of result objects. The result data key - * is always stashed in the [0] element of each result object. - * - * @method parseResponse - * @param sQuery {String} Query string. - * @param oResponse {Object} The raw response data to parse. - * @param oParent {Object} The object instance that has requested data. - * @returns {Object[]} Array of result objects. - */ -YAHOO.widget.DS_XHR.prototype.parseResponse = function(sQuery, oResponse, oParent) { - var aSchema = this.schema; - var aResults = []; - var bError = false; - - // Strip out comment at the end of results - var nEnd = ((this.responseStripAfter !== "") && (oResponse.indexOf)) ? - oResponse.indexOf(this.responseStripAfter) : -1; - if(nEnd != -1) { - oResponse = oResponse.substring(0,nEnd); - } - - switch (this.responseType) { - case YAHOO.widget.DS_XHR.TYPE_JSON: - var jsonList; - // Divert KHTML clients from JSON lib - if(window.JSON && (navigator.userAgent.toLowerCase().indexOf('khtml')== -1)) { - // Use the JSON utility if available - var jsonObjParsed = JSON.parse(oResponse); - if(!jsonObjParsed) { - bError = true; - break; - } - else { - try { - // eval is necessary here since aSchema[0] is of unknown depth - jsonList = eval("jsonObjParsed." + aSchema[0]); - } - catch(e) { - bError = true; - break; - } - } - } - else { - // Parse the JSON response as a string - try { - // Trim leading spaces - while (oResponse.substring(0,1) == " ") { - oResponse = oResponse.substring(1, oResponse.length); - } - - // Invalid JSON response - if(oResponse.indexOf("{") < 0) { - bError = true; - break; - } - - // Empty (but not invalid) JSON response - if(oResponse.indexOf("{}") === 0) { - break; - } - - // Turn the string into an object literal... - // ...eval is necessary here - var jsonObjRaw = eval("(" + oResponse + ")"); - if(!jsonObjRaw) { - bError = true; - break; - } - - // Grab the object member that contains an array of all reponses... - // ...eval is necessary here since aSchema[0] is of unknown depth - jsonList = eval("(jsonObjRaw." + aSchema[0]+")"); - } - catch(e) { - bError = true; - break; - } - } - - if(!jsonList) { - bError = true; - break; - } - - if(jsonList.constructor != Array) { - jsonList = [jsonList]; - } - - // Loop through the array of all responses... - for(var i = jsonList.length-1; i >= 0 ; i--) { - var aResultItem = []; - var jsonResult = jsonList[i]; - // ...and loop through each data field value of each response - for(var j = aSchema.length-1; j >= 1 ; j--) { - // ...and capture data into an array mapped according to the schema... - var dataFieldValue = jsonResult[aSchema[j]]; - if(!dataFieldValue) { - dataFieldValue = ""; - } - aResultItem.unshift(dataFieldValue); - } - // If schema isn't well defined, pass along the entire result object - if(aResultItem.length == 1) { - aResultItem.push(jsonResult); - } - // Capture the array of data field values in an array of results - aResults.unshift(aResultItem); - } - break; - case YAHOO.widget.DS_XHR.TYPE_XML: - // Get the collection of results - var xmlList = oResponse.getElementsByTagName(aSchema[0]); - if(!xmlList) { - bError = true; - break; - } - // Loop through each result - for(var k = xmlList.length-1; k >= 0 ; k--) { - var result = xmlList.item(k); - var aFieldSet = []; - // Loop through each data field in each result using the schema - for(var m = aSchema.length-1; m >= 1 ; m--) { - var sValue = null; - // Values may be held in an attribute... - var xmlAttr = result.attributes.getNamedItem(aSchema[m]); - if(xmlAttr) { - sValue = xmlAttr.value; - } - // ...or in a node - else{ - var xmlNode = result.getElementsByTagName(aSchema[m]); - if(xmlNode && xmlNode.item(0) && xmlNode.item(0).firstChild) { - sValue = xmlNode.item(0).firstChild.nodeValue; - } - else { - sValue = ""; - } - } - // Capture the schema-mapped data field values into an array - aFieldSet.unshift(sValue); - } - // Capture each array of values into an array of results - aResults.unshift(aFieldSet); - } - break; - case YAHOO.widget.DS_XHR.TYPE_FLAT: - if(oResponse.length > 0) { - // Delete the last line delimiter at the end of the data if it exists - var newLength = oResponse.length-aSchema[0].length; - if(oResponse.substr(newLength) == aSchema[0]) { - oResponse = oResponse.substr(0, newLength); - } - var aRecords = oResponse.split(aSchema[0]); - for(var n = aRecords.length-1; n >= 0; n--) { - aResults[n] = aRecords[n].split(aSchema[1]); - } - } - break; - default: - break; - } - sQuery = null; - oResponse = null; - oParent = null; - if(bError) { - return null; - } - else { - return aResults; - } -}; - -///////////////////////////////////////////////////////////////////////////// -// -// Private member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * XHR connection object. - * - * @property _oConn - * @type Object - * @private - */ -YAHOO.widget.DS_XHR.prototype._oConn = null; - - -/****************************************************************************/ -/****************************************************************************/ -/****************************************************************************/ - -/** - * Implementation of YAHOO.widget.DataSource using a native Javascript function as - * its live data source. - * - * @class DS_JSFunction - * @constructor - * @extends YAHOO.widget.DataSource - * @param oFunction {HTMLFunction} In-memory Javascript function that returns query results as an array of objects. - * @param oConfigs {Object} (optional) Object literal of config params. - */ -YAHOO.widget.DS_JSFunction = function(oFunction, oConfigs) { - // Set any config params passed in to override defaults - if(typeof oConfigs == "object") { - for(var sConfig in oConfigs) { - this[sConfig] = oConfigs[sConfig]; - } - } - - // Initialization sequence - if(!oFunction || (oFunction.constructor != Function)) { - return; - } - else { - this.dataFunction = oFunction; - this._init(); - } -}; - -YAHOO.widget.DS_JSFunction.prototype = new YAHOO.widget.DataSource(); - -///////////////////////////////////////////////////////////////////////////// -// -// Public member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * In-memory Javascript function that returns query results. - * - * @property dataFunction - * @type HTMLFunction - */ -YAHOO.widget.DS_JSFunction.prototype.dataFunction = null; - -///////////////////////////////////////////////////////////////////////////// -// -// Public methods -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Queries the live data source defined by function for results. Results are - * passed back to a callback function. - * - * @method doQuery - * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. - * @param sQuery {String} Query string. - * @param oParent {Object} The object instance that has requested data. - */ -YAHOO.widget.DS_JSFunction.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { - var oFunction = this.dataFunction; - var aResults = []; - - aResults = oFunction(sQuery); - if(aResults === null) { - this.dataErrorEvent.fire(this, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); - return; - } - - var resultObj = {}; - resultObj.query = decodeURIComponent(sQuery); - resultObj.results = aResults; - this._addCacheElem(resultObj); - - this.getResultsEvent.fire(this, oParent, sQuery, aResults); - oCallbackFn(sQuery, aResults, oParent); - return; -}; - -/****************************************************************************/ -/****************************************************************************/ -/****************************************************************************/ - -/** - * Implementation of YAHOO.widget.DataSource using a native Javascript array as - * its live data source. - * - * @class DS_JSArray - * @constructor - * @extends YAHOO.widget.DataSource - * @param aData {String[]} In-memory Javascript array of simple string data. - * @param oConfigs {Object} (optional) Object literal of config params. - */ -YAHOO.widget.DS_JSArray = function(aData, oConfigs) { - // Set any config params passed in to override defaults - if(typeof oConfigs == "object") { - for(var sConfig in oConfigs) { - this[sConfig] = oConfigs[sConfig]; - } - } - - // Initialization sequence - if(!aData || (aData.constructor != Array)) { - return; - } - else { - this.data = aData; - this._init(); - } -}; - -YAHOO.widget.DS_JSArray.prototype = new YAHOO.widget.DataSource(); - -///////////////////////////////////////////////////////////////////////////// -// -// Public member variables -// -///////////////////////////////////////////////////////////////////////////// - -/** - * In-memory Javascript array of strings. - * - * @property data - * @type Array - */ -YAHOO.widget.DS_JSArray.prototype.data = null; - -///////////////////////////////////////////////////////////////////////////// -// -// Public methods -// -///////////////////////////////////////////////////////////////////////////// - -/** - * Queries the live data source defined by data for results. Results are passed - * back to a callback function. - * - * @method doQuery - * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. - * @param sQuery {String} Query string. - * @param oParent {Object} The object instance that has requested data. - */ -YAHOO.widget.DS_JSArray.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { - var aData = this.data; // the array - var aResults = []; // container for results - var bMatchFound = false; - var bMatchContains = this.queryMatchContains; - if(sQuery) { - if(!this.queryMatchCase) { - sQuery = sQuery.toLowerCase(); - } - - // Loop through each element of the array... - // which can be a string or an array of strings - for(var i = aData.length-1; i >= 0; i--) { - var aDataset = []; - - if(aData[i]) { - if(aData[i].constructor == String) { - aDataset[0] = aData[i]; - } - else if(aData[i].constructor == Array) { - aDataset = aData[i]; - } - } - - if(aDataset[0] && (aDataset[0].constructor == String)) { - var sKeyIndex = (this.queryMatchCase) ? - encodeURIComponent(aDataset[0]).indexOf(sQuery): - encodeURIComponent(aDataset[0]).toLowerCase().indexOf(sQuery); - - // A STARTSWITH match is when the query is found at the beginning of the key string... - if((!bMatchContains && (sKeyIndex === 0)) || - // A CONTAINS match is when the query is found anywhere within the key string... - (bMatchContains && (sKeyIndex > -1))) { - // Stash a match into aResults[]. - aResults.unshift(aDataset); - } - } - } - } - - this.getResultsEvent.fire(this, oParent, sQuery, aResults); - oCallbackFn(sQuery, aResults, oParent); -}; +/****************************************************************************/ +/****************************************************************************/ +/****************************************************************************/ + +/** + * The DataSource classes manages sending a request and returning response from a live + * database. Supported data include local JavaScript arrays and objects and databases + * accessible via XHR connections. Supported response formats include JavaScript arrays, + * JSON, XML, and flat-file textual data. + * + * @class DataSource + * @constructor + */ +YAHOO.widget.DataSource = function() { + /* abstract class */ +}; + + +///////////////////////////////////////////////////////////////////////////// +// +// Public constants +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Error message for null data responses. + * + * @property ERROR_DATANULL + * @type String + * @static + * @final + */ +YAHOO.widget.DataSource.ERROR_DATANULL = "Response data was null"; + +/** + * Error message for data responses with parsing errors. + * + * @property ERROR_DATAPARSE + * @type String + * @static + * @final + */ +YAHOO.widget.DataSource.ERROR_DATAPARSE = "Response data could not be parsed"; + + +///////////////////////////////////////////////////////////////////////////// +// +// Public member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Max size of the local cache. Set to 0 to turn off caching. Caching is + * useful to reduce the number of server connections. Recommended only for data + * sources that return comprehensive results for queries or when stale data is + * not an issue. + * + * @property maxCacheEntries + * @type Number + * @default 15 + */ +YAHOO.widget.DataSource.prototype.maxCacheEntries = 15; + +/** + * Use this to equate cache matching with the type of matching done by your live + * data source. If caching is on and queryMatchContains is true, the cache + * returns results that "contain" the query string. By default, + * queryMatchContains is set to false, meaning the cache only returns results + * that "start with" the query string. + * + * @property queryMatchContains + * @type Boolean + * @default false + */ +YAHOO.widget.DataSource.prototype.queryMatchContains = false; + +/** + * Enables query subset matching. If caching is on and queryMatchSubset is + * true, substrings of queries will return matching cached results. For + * instance, if the first query is for "abc" susequent queries that start with + * "abc", like "abcd", will be queried against the cache, and not the live data + * source. Recommended only for DataSources that return comprehensive results + * for queries with very few characters. + * + * @property queryMatchSubset + * @type Boolean + * @default false + * + */ +YAHOO.widget.DataSource.prototype.queryMatchSubset = false; + +/** + * Enables query case-sensitivity matching. If caching is on and + * queryMatchCase is true, queries will only return results for case-sensitive + * matches. + * + * @property queryMatchCase + * @type Boolean + * @default false + */ +YAHOO.widget.DataSource.prototype.queryMatchCase = false; + + +///////////////////////////////////////////////////////////////////////////// +// +// Public methods +// +///////////////////////////////////////////////////////////////////////////// + + /** + * Public accessor to the unique name of the DataSource instance. + * + * @method toString + * @return {String} Unique name of the DataSource instance + */ +YAHOO.widget.DataSource.prototype.toString = function() { + return "DataSource " + this._sName; +}; + +/** + * Retrieves query results, first checking the local cache, then making the + * query request to the live data source as defined by the function doQuery. + * + * @method getResults + * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. + * @param sQuery {String} Query string. + * @param oParent {Object} The object instance that has requested data. + */ +YAHOO.widget.DataSource.prototype.getResults = function(oCallbackFn, sQuery, oParent) { + + // First look in cache + var aResults = this._doQueryCache(oCallbackFn,sQuery,oParent); + + // Not in cache, so get results from server + if(aResults.length === 0) { + this.queryEvent.fire(this, oParent, sQuery); + this.doQuery(oCallbackFn, sQuery, oParent); + } +}; + +/** + * Abstract method implemented by subclasses to make a query to the live data + * source. Must call the callback function with the response returned from the + * query. Populates cache (if enabled). + * + * @method doQuery + * @param oCallbackFn {HTMLFunction} Callback function implemented by oParent to which to return results. + * @param sQuery {String} Query string. + * @param oParent {Object} The object instance that has requested data. + */ +YAHOO.widget.DataSource.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { + /* override this */ +}; + +/** + * Flushes cache. + * + * @method flushCache + */ +YAHOO.widget.DataSource.prototype.flushCache = function() { + if(this._aCache) { + this._aCache = []; + } + if(this._aCacheHelper) { + this._aCacheHelper = []; + } + this.cacheFlushEvent.fire(this); +}; + +///////////////////////////////////////////////////////////////////////////// +// +// Public events +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Fired when a query is made to the live data source. + * + * @event queryEvent + * @param oSelf {Object} The DataSource instance. + * @param oParent {Object} The requesting object. + * @param sQuery {String} The query string. + */ +YAHOO.widget.DataSource.prototype.queryEvent = null; + +/** + * Fired when a query is made to the local cache. + * + * @event cacheQueryEvent + * @param oSelf {Object} The DataSource instance. + * @param oParent {Object} The requesting object. + * @param sQuery {String} The query string. + */ +YAHOO.widget.DataSource.prototype.cacheQueryEvent = null; + +/** + * Fired when data is retrieved from the live data source. + * + * @event getResultsEvent + * @param oSelf {Object} The DataSource instance. + * @param oParent {Object} The requesting object. + * @param sQuery {String} The query string. + * @param aResults {Object[]} Array of result objects. + */ +YAHOO.widget.DataSource.prototype.getResultsEvent = null; + +/** + * Fired when data is retrieved from the local cache. + * + * @event getCachedResultsEvent + * @param oSelf {Object} The DataSource instance. + * @param oParent {Object} The requesting object. + * @param sQuery {String} The query string. + * @param aResults {Object[]} Array of result objects. + */ +YAHOO.widget.DataSource.prototype.getCachedResultsEvent = null; + +/** + * Fired when an error is encountered with the live data source. + * + * @event dataErrorEvent + * @param oSelf {Object} The DataSource instance. + * @param oParent {Object} The requesting object. + * @param sQuery {String} The query string. + * @param sMsg {String} Error message string + */ +YAHOO.widget.DataSource.prototype.dataErrorEvent = null; + +/** + * Fired when the local cache is flushed. + * + * @event cacheFlushEvent + * @param oSelf {Object} The DataSource instance + */ +YAHOO.widget.DataSource.prototype.cacheFlushEvent = null; + +///////////////////////////////////////////////////////////////////////////// +// +// Private member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Internal class variable to index multiple DataSource instances. + * + * @property _nIndex + * @type Number + * @private + * @static + */ +YAHOO.widget.DataSource._nIndex = 0; + +/** + * Name of DataSource instance. + * + * @property _sName + * @type String + * @private + */ +YAHOO.widget.DataSource.prototype._sName = null; + +/** + * Local cache of data result objects indexed chronologically. + * + * @property _aCache + * @type Object[] + * @private + */ +YAHOO.widget.DataSource.prototype._aCache = null; + + +///////////////////////////////////////////////////////////////////////////// +// +// Private methods +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Initializes DataSource instance. + * + * @method _init + * @private + */ +YAHOO.widget.DataSource.prototype._init = function() { + // Validate and initialize public configs + var maxCacheEntries = this.maxCacheEntries; + if(isNaN(maxCacheEntries) || (maxCacheEntries < 0)) { + maxCacheEntries = 0; + } + // Initialize local cache + if(maxCacheEntries > 0 && !this._aCache) { + this._aCache = []; + } + + this._sName = "instance" + YAHOO.widget.DataSource._nIndex; + YAHOO.widget.DataSource._nIndex++; + + this.queryEvent = new YAHOO.util.CustomEvent("query", this); + this.cacheQueryEvent = new YAHOO.util.CustomEvent("cacheQuery", this); + this.getResultsEvent = new YAHOO.util.CustomEvent("getResults", this); + this.getCachedResultsEvent = new YAHOO.util.CustomEvent("getCachedResults", this); + this.dataErrorEvent = new YAHOO.util.CustomEvent("dataError", this); + this.cacheFlushEvent = new YAHOO.util.CustomEvent("cacheFlush", this); +}; + +/** + * Adds a result object to the local cache, evicting the oldest element if the + * cache is full. Newer items will have higher indexes, the oldest item will have + * index of 0. + * + * @method _addCacheElem + * @param oResult {Object} Data result object, including array of results. + * @private + */ +YAHOO.widget.DataSource.prototype._addCacheElem = function(oResult) { + var aCache = this._aCache; + // Don't add if anything important is missing. + if(!aCache || !oResult || !oResult.query || !oResult.results) { + return; + } + + // If the cache is full, make room by removing from index=0 + if(aCache.length >= this.maxCacheEntries) { + aCache.shift(); + } + + // Add to cache, at the end of the array + aCache.push(oResult); +}; + +/** + * Queries the local cache for results. If query has been cached, the callback + * function is called with the results, and the cached is refreshed so that it + * is now the newest element. + * + * @method _doQueryCache + * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. + * @param sQuery {String} Query string. + * @param oParent {Object} The object instance that has requested data. + * @return aResults {Object[]} Array of results from local cache if found, otherwise null. + * @private + */ +YAHOO.widget.DataSource.prototype._doQueryCache = function(oCallbackFn, sQuery, oParent) { + var aResults = []; + var bMatchFound = false; + var aCache = this._aCache; + var nCacheLength = (aCache) ? aCache.length : 0; + var bMatchContains = this.queryMatchContains; + + // If cache is enabled... + if((this.maxCacheEntries > 0) && aCache && (nCacheLength > 0)) { + this.cacheQueryEvent.fire(this, oParent, sQuery); + // If case is unimportant, normalize query now instead of in loops + if(!this.queryMatchCase) { + var sOrigQuery = sQuery; + sQuery = sQuery.toLowerCase(); + } + + // Loop through each cached element's query property... + for(var i = nCacheLength-1; i >= 0; i--) { + var resultObj = aCache[i]; + var aAllResultItems = resultObj.results; + // If case is unimportant, normalize match key for comparison + var matchKey = (!this.queryMatchCase) ? + encodeURIComponent(resultObj.query).toLowerCase(): + encodeURIComponent(resultObj.query); + + // If a cached match key exactly matches the query... + if(matchKey == sQuery) { + // Stash all result objects into aResult[] and stop looping through the cache. + bMatchFound = true; + aResults = aAllResultItems; + + // The matching cache element was not the most recent, + // so now we need to refresh the cache. + if(i != nCacheLength-1) { + // Remove element from its original location + aCache.splice(i,1); + // Add element as newest + this._addCacheElem(resultObj); + } + break; + } + // Else if this query is not an exact match and subset matching is enabled... + else if(this.queryMatchSubset) { + // Loop through substrings of each cached element's query property... + for(var j = sQuery.length-1; j >= 0 ; j--) { + var subQuery = sQuery.substr(0,j); + + // If a substring of a cached sQuery exactly matches the query... + if(matchKey == subQuery) { + bMatchFound = true; + + // Go through each cached result object to match against the query... + for(var k = aAllResultItems.length-1; k >= 0; k--) { + var aRecord = aAllResultItems[k]; + var sKeyIndex = (this.queryMatchCase) ? + encodeURIComponent(aRecord[0]).indexOf(sQuery): + encodeURIComponent(aRecord[0]).toLowerCase().indexOf(sQuery); + + // A STARTSWITH match is when the query is found at the beginning of the key string... + if((!bMatchContains && (sKeyIndex === 0)) || + // A CONTAINS match is when the query is found anywhere within the key string... + (bMatchContains && (sKeyIndex > -1))) { + // Stash a match into aResults[]. + aResults.unshift(aRecord); + } + } + + // Add the subset match result set object as the newest element to cache, + // and stop looping through the cache. + resultObj = {}; + resultObj.query = sQuery; + resultObj.results = aResults; + this._addCacheElem(resultObj); + break; + } + } + if(bMatchFound) { + break; + } + } + } + + // If there was a match, send along the results. + if(bMatchFound) { + this.getCachedResultsEvent.fire(this, oParent, sOrigQuery, aResults); + oCallbackFn(sOrigQuery, aResults, oParent); + } + } + return aResults; +}; + + +/****************************************************************************/ +/****************************************************************************/ +/****************************************************************************/ + +/** + * Implementation of YAHOO.widget.DataSource using XML HTTP requests that return + * query results. + * + * @class DS_XHR + * @extends YAHOO.widget.DataSource + * @requires connection + * @constructor + * @param sScriptURI {String} Absolute or relative URI to script that returns query + * results as JSON, XML, or delimited flat-file data. + * @param aSchema {String[]} Data schema definition of results. + * @param oConfigs {Object} (optional) Object literal of config params. + */ +YAHOO.widget.DS_XHR = function(sScriptURI, aSchema, oConfigs) { + // Set any config params passed in to override defaults + if(typeof oConfigs == "object") { + for(var sConfig in oConfigs) { + this[sConfig] = oConfigs[sConfig]; + } + } + + // Initialization sequence + if(!aSchema || (aSchema.constructor != Array)) { + return; + } + else { + this.schema = aSchema; + } + this.scriptURI = sScriptURI; + this._init(); +}; + +YAHOO.widget.DS_XHR.prototype = new YAHOO.widget.DataSource(); + +///////////////////////////////////////////////////////////////////////////// +// +// Public constants +// +///////////////////////////////////////////////////////////////////////////// + +/** + * JSON data type. + * + * @property TYPE_JSON + * @type Number + * @static + * @final + */ +YAHOO.widget.DS_XHR.TYPE_JSON = 0; + +/** + * XML data type. + * + * @property TYPE_XML + * @type Number + * @static + * @final + */ +YAHOO.widget.DS_XHR.TYPE_XML = 1; + +/** + * Flat-file data type. + * + * @property TYPE_FLAT + * @type Number + * @static + * @final + */ +YAHOO.widget.DS_XHR.TYPE_FLAT = 2; + +/** + * Error message for XHR failure. + * + * @property ERROR_DATAXHR + * @type String + * @static + * @final + */ +YAHOO.widget.DS_XHR.ERROR_DATAXHR = "XHR response failed"; + +///////////////////////////////////////////////////////////////////////////// +// +// Public member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Alias to YUI Connection Manager. Allows implementers to specify their own + * subclasses of the YUI Connection Manager utility. + * + * @property connMgr + * @type Object + * @default YAHOO.util.Connect + */ +YAHOO.widget.DS_XHR.prototype.connMgr = YAHOO.util.Connect; + +/** + * Number of milliseconds the XHR connection will wait for a server response. A + * a value of zero indicates the XHR connection will wait forever. Any value + * greater than zero will use the Connection utility's Auto-Abort feature. + * + * @property connTimeout + * @type Number + * @default 0 + */ +YAHOO.widget.DS_XHR.prototype.connTimeout = 0; + +/** + * Absolute or relative URI to script that returns query results. For instance, + * queries will be sent to <scriptURI>?<scriptQueryParam>=userinput + * + * @property scriptURI + * @type String + */ +YAHOO.widget.DS_XHR.prototype.scriptURI = null; + +/** + * Query string parameter name sent to scriptURI. For instance, queries will be + * sent to <scriptURI>?<scriptQueryParam>=userinput + * + * @property scriptQueryParam + * @type String + * @default "query" + */ +YAHOO.widget.DS_XHR.prototype.scriptQueryParam = "query"; + +/** + * String of key/value pairs to append to requests made to scriptURI. Define + * this string when you want to send additional query parameters to your script. + * When defined, queries will be sent to + * <scriptURI>?<scriptQueryParam>=userinput&<scriptQueryAppend> + * + * @property scriptQueryAppend + * @type String + * @default "" + */ +YAHOO.widget.DS_XHR.prototype.scriptQueryAppend = ""; + +/** + * XHR response data type. Other types that may be defined are YAHOO.widget.DS_XHR.TYPE_XML + * and YAHOO.widget.DS_XHR.TYPE_FLAT. + * + * @property responseType + * @type String + * @default YAHOO.widget.DS_XHR.TYPE_JSON + */ +YAHOO.widget.DS_XHR.prototype.responseType = YAHOO.widget.DS_XHR.TYPE_JSON; + +/** + * String after which to strip results. If the results from the XHR are sent + * back as HTML, the gzip HTML comment appears at the end of the data and should + * be ignored. + * + * @property responseStripAfter + * @type String + * @default "\n<!-" + */ +YAHOO.widget.DS_XHR.prototype.responseStripAfter = "\n 0) { + sUri += "&" + this.scriptQueryAppend; + } + var oResponse = null; + + var oSelf = this; + /* + * Sets up ajax request callback + * + * @param {object} oReq HTTPXMLRequest object + * @private + */ + var responseSuccess = function(oResp) { + // Response ID does not match last made request ID. + if(!oSelf._oConn || (oResp.tId != oSelf._oConn.tId)) { + oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); + return; + } +//DEBUG +for(var foo in oResp) { +} + if(!isXML) { + oResp = oResp.responseText; + } + else { + oResp = oResp.responseXML; + } + if(oResp === null) { + oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); + return; + } + + var aResults = oSelf.parseResponse(sQuery, oResp, oParent); + var resultObj = {}; + resultObj.query = decodeURIComponent(sQuery); + resultObj.results = aResults; + if(aResults === null) { + oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATAPARSE); + aResults = []; + } + else { + oSelf.getResultsEvent.fire(oSelf, oParent, sQuery, aResults); + oSelf._addCacheElem(resultObj); + } + oCallbackFn(sQuery, aResults, oParent); + }; + + var responseFailure = function(oResp) { + oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DS_XHR.ERROR_DATAXHR); + return; + }; + + var oCallback = { + success:responseSuccess, + failure:responseFailure + }; + + if(!isNaN(this.connTimeout) && this.connTimeout > 0) { + oCallback.timeout = this.connTimeout; + } + + if(this._oConn) { + this.connMgr.abort(this._oConn); + } + + oSelf._oConn = this.connMgr.asyncRequest("GET", sUri, oCallback, null); +}; + +/** + * Parses raw response data into an array of result objects. The result data key + * is always stashed in the [0] element of each result object. + * + * @method parseResponse + * @param sQuery {String} Query string. + * @param oResponse {Object} The raw response data to parse. + * @param oParent {Object} The object instance that has requested data. + * @returns {Object[]} Array of result objects. + */ +YAHOO.widget.DS_XHR.prototype.parseResponse = function(sQuery, oResponse, oParent) { + var aSchema = this.schema; + var aResults = []; + var bError = false; + + // Strip out comment at the end of results + var nEnd = ((this.responseStripAfter !== "") && (oResponse.indexOf)) ? + oResponse.indexOf(this.responseStripAfter) : -1; + if(nEnd != -1) { + oResponse = oResponse.substring(0,nEnd); + } + + switch (this.responseType) { + case YAHOO.widget.DS_XHR.TYPE_JSON: + var jsonList; + // Divert KHTML clients from JSON lib + if(window.JSON && (navigator.userAgent.toLowerCase().indexOf('khtml')== -1)) { + // Use the JSON utility if available + var jsonObjParsed = JSON.parse(oResponse); + if(!jsonObjParsed) { + bError = true; + break; + } + else { + try { + // eval is necessary here since aSchema[0] is of unknown depth + jsonList = eval("jsonObjParsed." + aSchema[0]); + } + catch(e) { + bError = true; + break; + } + } + } + else { + // Parse the JSON response as a string + try { + // Trim leading spaces + while (oResponse.substring(0,1) == " ") { + oResponse = oResponse.substring(1, oResponse.length); + } + + // Invalid JSON response + if(oResponse.indexOf("{") < 0) { + bError = true; + break; + } + + // Empty (but not invalid) JSON response + if(oResponse.indexOf("{}") === 0) { + break; + } + + // Turn the string into an object literal... + // ...eval is necessary here + var jsonObjRaw = eval("(" + oResponse + ")"); + if(!jsonObjRaw) { + bError = true; + break; + } + + // Grab the object member that contains an array of all reponses... + // ...eval is necessary here since aSchema[0] is of unknown depth + jsonList = eval("(jsonObjRaw." + aSchema[0]+")"); + } + catch(e) { + bError = true; + break; + } + } + + if(!jsonList) { + bError = true; + break; + } + + if(jsonList.constructor != Array) { + jsonList = [jsonList]; + } + + // Loop through the array of all responses... + for(var i = jsonList.length-1; i >= 0 ; i--) { + var aResultItem = []; + var jsonResult = jsonList[i]; + // ...and loop through each data field value of each response + for(var j = aSchema.length-1; j >= 1 ; j--) { + // ...and capture data into an array mapped according to the schema... + var dataFieldValue = jsonResult[aSchema[j]]; + if(!dataFieldValue) { + dataFieldValue = ""; + } + aResultItem.unshift(dataFieldValue); + } + // If schema isn't well defined, pass along the entire result object + if(aResultItem.length == 1) { + aResultItem.push(jsonResult); + } + // Capture the array of data field values in an array of results + aResults.unshift(aResultItem); + } + break; + case YAHOO.widget.DS_XHR.TYPE_XML: + // Get the collection of results + var xmlList = oResponse.getElementsByTagName(aSchema[0]); + if(!xmlList) { + bError = true; + break; + } + // Loop through each result + for(var k = xmlList.length-1; k >= 0 ; k--) { + var result = xmlList.item(k); + var aFieldSet = []; + // Loop through each data field in each result using the schema + for(var m = aSchema.length-1; m >= 1 ; m--) { + var sValue = null; + // Values may be held in an attribute... + var xmlAttr = result.attributes.getNamedItem(aSchema[m]); + if(xmlAttr) { + sValue = xmlAttr.value; + } + // ...or in a node + else{ + var xmlNode = result.getElementsByTagName(aSchema[m]); + if(xmlNode && xmlNode.item(0) && xmlNode.item(0).firstChild) { + sValue = xmlNode.item(0).firstChild.nodeValue; + } + else { + sValue = ""; + } + } + // Capture the schema-mapped data field values into an array + aFieldSet.unshift(sValue); + } + // Capture each array of values into an array of results + aResults.unshift(aFieldSet); + } + break; + case YAHOO.widget.DS_XHR.TYPE_FLAT: + if(oResponse.length > 0) { + // Delete the last line delimiter at the end of the data if it exists + var newLength = oResponse.length-aSchema[0].length; + if(oResponse.substr(newLength) == aSchema[0]) { + oResponse = oResponse.substr(0, newLength); + } + var aRecords = oResponse.split(aSchema[0]); + for(var n = aRecords.length-1; n >= 0; n--) { + aResults[n] = aRecords[n].split(aSchema[1]); + } + } + break; + default: + break; + } + sQuery = null; + oResponse = null; + oParent = null; + if(bError) { + return null; + } + else { + return aResults; + } +}; + +///////////////////////////////////////////////////////////////////////////// +// +// Private member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * XHR connection object. + * + * @property _oConn + * @type Object + * @private + */ +YAHOO.widget.DS_XHR.prototype._oConn = null; + + +/****************************************************************************/ +/****************************************************************************/ +/****************************************************************************/ + +/** + * Implementation of YAHOO.widget.DataSource using a native Javascript function as + * its live data source. + * + * @class DS_JSFunction + * @constructor + * @extends YAHOO.widget.DataSource + * @param oFunction {HTMLFunction} In-memory Javascript function that returns query results as an array of objects. + * @param oConfigs {Object} (optional) Object literal of config params. + */ +YAHOO.widget.DS_JSFunction = function(oFunction, oConfigs) { + // Set any config params passed in to override defaults + if(typeof oConfigs == "object") { + for(var sConfig in oConfigs) { + this[sConfig] = oConfigs[sConfig]; + } + } + + // Initialization sequence + if(!oFunction || (oFunction.constructor != Function)) { + return; + } + else { + this.dataFunction = oFunction; + this._init(); + } +}; + +YAHOO.widget.DS_JSFunction.prototype = new YAHOO.widget.DataSource(); + +///////////////////////////////////////////////////////////////////////////// +// +// Public member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * In-memory Javascript function that returns query results. + * + * @property dataFunction + * @type HTMLFunction + */ +YAHOO.widget.DS_JSFunction.prototype.dataFunction = null; + +///////////////////////////////////////////////////////////////////////////// +// +// Public methods +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Queries the live data source defined by function for results. Results are + * passed back to a callback function. + * + * @method doQuery + * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. + * @param sQuery {String} Query string. + * @param oParent {Object} The object instance that has requested data. + */ +YAHOO.widget.DS_JSFunction.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { + var oFunction = this.dataFunction; + var aResults = []; + + aResults = oFunction(sQuery); + if(aResults === null) { + this.dataErrorEvent.fire(this, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL); + return; + } + + var resultObj = {}; + resultObj.query = decodeURIComponent(sQuery); + resultObj.results = aResults; + this._addCacheElem(resultObj); + + this.getResultsEvent.fire(this, oParent, sQuery, aResults); + oCallbackFn(sQuery, aResults, oParent); + return; +}; + +/****************************************************************************/ +/****************************************************************************/ +/****************************************************************************/ + +/** + * Implementation of YAHOO.widget.DataSource using a native Javascript array as + * its live data source. + * + * @class DS_JSArray + * @constructor + * @extends YAHOO.widget.DataSource + * @param aData {String[]} In-memory Javascript array of simple string data. + * @param oConfigs {Object} (optional) Object literal of config params. + */ +YAHOO.widget.DS_JSArray = function(aData, oConfigs) { + // Set any config params passed in to override defaults + if(typeof oConfigs == "object") { + for(var sConfig in oConfigs) { + this[sConfig] = oConfigs[sConfig]; + } + } + + // Initialization sequence + if(!aData || (aData.constructor != Array)) { + return; + } + else { + this.data = aData; + this._init(); + } +}; + +YAHOO.widget.DS_JSArray.prototype = new YAHOO.widget.DataSource(); + +///////////////////////////////////////////////////////////////////////////// +// +// Public member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * In-memory Javascript array of strings. + * + * @property data + * @type Array + */ +YAHOO.widget.DS_JSArray.prototype.data = null; + +///////////////////////////////////////////////////////////////////////////// +// +// Public methods +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Queries the live data source defined by data for results. Results are passed + * back to a callback function. + * + * @method doQuery + * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results. + * @param sQuery {String} Query string. + * @param oParent {Object} The object instance that has requested data. + */ +YAHOO.widget.DS_JSArray.prototype.doQuery = function(oCallbackFn, sQuery, oParent) { + var aData = this.data; // the array + var aResults = []; // container for results + var bMatchFound = false; + var bMatchContains = this.queryMatchContains; + if(sQuery) { + if(!this.queryMatchCase) { + sQuery = sQuery.toLowerCase(); + } + + // Loop through each element of the array... + // which can be a string or an array of strings + for(var i = aData.length-1; i >= 0; i--) { + var aDataset = []; + + if(aData[i]) { + if(aData[i].constructor == String) { + aDataset[0] = aData[i]; + } + else if(aData[i].constructor == Array) { + aDataset = aData[i]; + } + } + + if(aDataset[0] && (aDataset[0].constructor == String)) { + var sKeyIndex = (this.queryMatchCase) ? + encodeURIComponent(aDataset[0]).indexOf(sQuery): + encodeURIComponent(aDataset[0]).toLowerCase().indexOf(sQuery); + + // A STARTSWITH match is when the query is found at the beginning of the key string... + if((!bMatchContains && (sKeyIndex === 0)) || + // A CONTAINS match is when the query is found anywhere within the key string... + (bMatchContains && (sKeyIndex > -1))) { + // Stash a match into aResults[]. + aResults.unshift(aDataset); + } + } + } + } + + this.getResultsEvent.fire(this, oParent, sQuery, aResults); + oCallbackFn(sQuery, aResults, oParent); +}; diff --git a/lib/yui/calendar/README b/lib/yui/calendar/README index eaeb49202c..d4fc65d143 100755 --- a/lib/yui/calendar/README +++ b/lib/yui/calendar/README @@ -1,73 +1,77 @@ -Calendar Release Notes - -*** version 0.12.1 *** - - - Calendar and CalendarGroup now automatically parse the argument passed to setMonth and setYear into an integer, eliminating potential concatenation bugs. - -*** version 0.12 *** - - - New documentation format implemented - - Calendar2up and Calendar_Core are now deprecated. Now, Calendar alone represents the single Calendar instance, and CalendarGroup represents an n-up instance, defaulting to 2up - - Added semantic style classes to Calendar elements to allow for custom styling solely using CSS. - - Remapped all configuration properties to use the Config object (familiar to those who use the Container collection of controls). Property names are the same as their previous counterparts, but wrapped into Calendar.cfg, allowing for runtime reconfiguration of most properties - - Added "title" property for setting the Calendar title - - Added "close" property for enabling and disabling the close icon - - Added "iframe" property for enabling an iframe shim in Internet Explorer 6 and below to fix the select bleed-through bug - - pageDate moved to property: "pagedate" - - selectedDates moved to property: "selected" - - minDate moved to property : "mindate", which accepts a JavaScript Date object like its predecessor, but also supports string dates - - maxDate moved to property : "maxdate", which accepts a JavaScript Date object like its predecessor, but also supports string dates - - Moved style declarations to initStyles function - - Optimized event handling in doSelectCell/doCellMouseOver/doCellMouseOut by only attaching the listener to the outer Calendar container, and only reacting to events on cells with the "selectable" CSS class. - - Added domEventMap field for applying DOM event listeners to cells containing specific class and tag combinations. - - Moved all cell DOM event attachment to applyListeners function - - Added getDateByCellId / getDateFieldsByCellId helper functions - - Corrected DateMath.getWeekNumber to comply with ISO week number handling - - Separated renderCellDefault style portions into styleCellDefault function for easy extension - - Deprecated onBeforeSelect. Created beforeSelectEvent which automatically subscribes to its deprecated predecessor. - - Deprecated onSelect. Created selectEvent, which automatically subscribes to its deprecated predecessor. - - Deprecated onBeforeDeselect. Created beforeSelectEvent which automatically subscribes to its deprecated predecessor. - - Deprecated onDeselect. Created beforeDeselectEvent, which automatically subscribes to its deprecated predecessor. - - Deprecated onChangePage. Created changePageEvent, which automatically subscribes to its deprecated predecessor. - - Deprecated onRender. Created renderEvent, which automatically subscribes to its deprecated predecessor. - - Deprecated onReset. Created resetEvent, which automatically subscribes to its deprecated predecessor. - - Deprecated onClear. Created clearEvent, which automatically subscribes to its deprecated predecessor. - - Corrected setMonth documentation to refer to 0-11 indexed months. - - Added show and hide methods to Calendar for setting the Calendar's display property. - - Optimized internal render classes to use innerHTML and string buffers - - Removed wireCustomEvents function - - Removed wireDefaultEvents function - - Removed doNextMonth / doPreviousMonth - - Removed all buildShell (header, body, footer) functions, since the Calendar shell is now built dynamically on each render - - Wired all CalendarGroup events and configuration properties to be properly delegated to Calendar - - Augmented CalendarGroup with all built-in renderers, label functions, hide, show, and initStyles, creating API transparency between Calendar and CalendarGroup. - - Made all tagName, createElement, and entity references XHTML compliant - - Fixed Daylight Saving Time bug for Brazilian time zone - -*** version 0.11.3 *** - - - Calendar_Core: Added arguments for selected/deselected dates to onSelect/onDeselect - - CalendarGroup: Fixed bug where selected dates passed to constructor were not represented in selectedDates - - Calendar2up: Now displays correctly in Opera 9 - -*** version 0.11.0 *** - - - DateMath: DateMath.add now properly adds weeks - - DateMath: between() function added - - DateMath: getWeekNumber() fixed to take starting day of week into account - - All references to Calendar's built in CSS class handlers are removed, replaced with calls to Dom utility (addClass, removeClass) - - Several CSS class constants now have clearer names - - All CSS classes are now properly namespaced to avoid CSS conflicts - - Fixed table:hover bug in CSS - - Calendar no longer requires the container ID and variable name to match in order for month navigation to function properly - - Calendar month navigation arrows are now represented as background images - -*** version 0.10.0 *** - - - Major performance improvements from attaching DOM events to associated table cells only once, when the Calendar shell is built - - DOM events for mouseover/mouseout are now fired for all browsers (not just Internet Explorer) - - Reset functionality bug fixed for 2-up Calendar view - -*** version 0.9.0 *** - -* Initial release +Calendar Release Notes + +*** version 0.12.2 *** + + - Corrected documentation for clearTime function to reflect the change from midnight to noon + +*** version 0.12.1 *** + + - Calendar and CalendarGroup now automatically parse the argument passed to setMonth and setYear into an integer, eliminating potential concatenation bugs. + +*** version 0.12 *** + + - New documentation format implemented + - Calendar2up and Calendar_Core are now deprecated. Now, Calendar alone represents the single Calendar instance, and CalendarGroup represents an n-up instance, defaulting to 2up + - Added semantic style classes to Calendar elements to allow for custom styling solely using CSS. + - Remapped all configuration properties to use the Config object (familiar to those who use the Container collection of controls). Property names are the same as their previous counterparts, but wrapped into Calendar.cfg, allowing for runtime reconfiguration of most properties + - Added "title" property for setting the Calendar title + - Added "close" property for enabling and disabling the close icon + - Added "iframe" property for enabling an iframe shim in Internet Explorer 6 and below to fix the select bleed-through bug + - pageDate moved to property: "pagedate" + - selectedDates moved to property: "selected" + - minDate moved to property : "mindate", which accepts a JavaScript Date object like its predecessor, but also supports string dates + - maxDate moved to property : "maxdate", which accepts a JavaScript Date object like its predecessor, but also supports string dates + - Moved style declarations to initStyles function + - Optimized event handling in doSelectCell/doCellMouseOver/doCellMouseOut by only attaching the listener to the outer Calendar container, and only reacting to events on cells with the "selectable" CSS class. + - Added domEventMap field for applying DOM event listeners to cells containing specific class and tag combinations. + - Moved all cell DOM event attachment to applyListeners function + - Added getDateByCellId / getDateFieldsByCellId helper functions + - Corrected DateMath.getWeekNumber to comply with ISO week number handling + - Separated renderCellDefault style portions into styleCellDefault function for easy extension + - Deprecated onBeforeSelect. Created beforeSelectEvent which automatically subscribes to its deprecated predecessor. + - Deprecated onSelect. Created selectEvent, which automatically subscribes to its deprecated predecessor. + - Deprecated onBeforeDeselect. Created beforeSelectEvent which automatically subscribes to its deprecated predecessor. + - Deprecated onDeselect. Created beforeDeselectEvent, which automatically subscribes to its deprecated predecessor. + - Deprecated onChangePage. Created changePageEvent, which automatically subscribes to its deprecated predecessor. + - Deprecated onRender. Created renderEvent, which automatically subscribes to its deprecated predecessor. + - Deprecated onReset. Created resetEvent, which automatically subscribes to its deprecated predecessor. + - Deprecated onClear. Created clearEvent, which automatically subscribes to its deprecated predecessor. + - Corrected setMonth documentation to refer to 0-11 indexed months. + - Added show and hide methods to Calendar for setting the Calendar's display property. + - Optimized internal render classes to use innerHTML and string buffers + - Removed wireCustomEvents function + - Removed wireDefaultEvents function + - Removed doNextMonth / doPreviousMonth + - Removed all buildShell (header, body, footer) functions, since the Calendar shell is now built dynamically on each render + - Wired all CalendarGroup events and configuration properties to be properly delegated to Calendar + - Augmented CalendarGroup with all built-in renderers, label functions, hide, show, and initStyles, creating API transparency between Calendar and CalendarGroup. + - Made all tagName, createElement, and entity references XHTML compliant + - Fixed Daylight Saving Time bug for Brazilian time zone + +*** version 0.11.3 *** + + - Calendar_Core: Added arguments for selected/deselected dates to onSelect/onDeselect + - CalendarGroup: Fixed bug where selected dates passed to constructor were not represented in selectedDates + - Calendar2up: Now displays correctly in Opera 9 + +*** version 0.11.0 *** + + - DateMath: DateMath.add now properly adds weeks + - DateMath: between() function added + - DateMath: getWeekNumber() fixed to take starting day of week into account + - All references to Calendar's built in CSS class handlers are removed, replaced with calls to Dom utility (addClass, removeClass) + - Several CSS class constants now have clearer names + - All CSS classes are now properly namespaced to avoid CSS conflicts + - Fixed table:hover bug in CSS + - Calendar no longer requires the container ID and variable name to match in order for month navigation to function properly + - Calendar month navigation arrows are now represented as background images + +*** version 0.10.0 *** + + - Major performance improvements from attaching DOM events to associated table cells only once, when the Calendar shell is built + - DOM events for mouseover/mouseout are now fired for all browsers (not just Internet Explorer) + - Reset functionality bug fixed for 2-up Calendar view + +*** version 0.9.0 *** + +* Initial release diff --git a/lib/yui/calendar/assets/calendar.css b/lib/yui/calendar/assets/calendar.css index 79f0a3282e..b97a705362 100755 --- a/lib/yui/calendar/assets/calendar.css +++ b/lib/yui/calendar/assets/calendar.css @@ -1,191 +1,191 @@ -/* -Copyright (c) 2006, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version 0.12.1 -*/ - -.yui-calcontainer { - position:relative; - padding:5px; - background-color:#F7F9FB; - border:1px solid #7B9EBD; - float:left; - overflow:hidden; -} - -.yui-calcontainer iframe { - position:absolute; - border:none; - margin:0;padding:0; - left:-1px; - top:-1px; - z-index:0; - width:50em; - height:50em; -} - -.yui-calcontainer.multi { - padding:0; -} - -.yui-calcontainer.multi .groupcal { - padding:5px; - background-color:transparent; - z-index:1; - float:left; - position:relative; - border:none; -} - -.yui-calcontainer .title { - font:100% sans-serif; - color:#000; - font-weight:bold; - margin-bottom:5px; - height:25px; - position:absolute; - top:3px;left:5px; - z-index:1; -} - -.yui-calcontainer .close-icon { - position:absolute; - right:3px; - top:3px; - border:none; - z-index:1; -} - -/* Calendar element styles */ - -.yui-calendar { - font:100% sans-serif; - text-align:center; - border-spacing:0; - border-collapse:separate; - position:relative; -} - -.yui-calcontainer.withtitle { - padding-top:1.5em; -} - -.yui-calendar .calnavleft { - position:absolute; - background-repeat:no-repeat; - cursor:pointer; - top:2px; - bottom:0; - width:9px; - height:12px; - left:2px; - z-index:1; -} - -.yui-calendar .calnavright { - position:absolute; - background-repeat:no-repeat; - cursor:pointer; - top:2px; - bottom:0; - width:9px; - height:12px; - right:2px; - z-index:1; -} - -.yui-calendar td.calcell { - padding:.1em .2em; - border:1px solid #E0E0E0; - text-align:center; -} - -.yui-calendar td.calcell a { - color:#003DB8; - text-decoration:none; -} - -.yui-calendar td.calcell.today { - border:1px solid #000; -} - -.yui-calendar td.calcell.oom { - cursor:default; - color:#999; - background-color:#EEE; - border:1px solid #E0E0E0; -} - -.yui-calendar td.calcell.selected { - color:#003DB8; - background-color:#FFF19F; - border:1px solid #FF9900; -} - -.yui-calendar td.calcell.calcellhover { - cursor:pointer; - color:#FFF; - background-color:#FF9900; - border:1px solid #FF9900; -} - -.yui-calendar td.calcell.calcellhover a { - color:#FFF; -} - -.yui-calendar td.calcell.restricted { - text-decoration:line-through; -} - -.yui-calendar td.calcell.previous { - color:#CCC; -} - -.yui-calendar td.calcell.highlight1 { background-color:#CCFF99; } -.yui-calendar td.calcell.highlight2 { background-color:#99CCFF; } -.yui-calendar td.calcell.highlight3 { background-color:#FFCCCC; } -.yui-calendar td.calcell.highlight4 { background-color:#CCFF99; } - -.yui-calendar .calhead { - border:1px solid #E0E0E0; - vertical-align:middle; - background-color:#FFF; -} - -.yui-calendar .calheader { - position:relative; - width:100%; - text-align:center; -} - -.yui-calendar .calheader img { - border:none; -} - -.yui-calendar .calweekdaycell { - color:#666; - font-weight:normal; - text-align:center; - width:1.5em; -} - -.yui-calendar .calfoot { - background-color:#EEE; -} - -.yui-calendar .calrowhead, .yui-calendar .calrowfoot { - color:#666; - font-size:9px; - font-style:italic; - font-weight:normal; - width:15px; -} - -.yui-calendar .calrowhead { - border-right-width:2px; -} - -/*Specific changes for calendar running under fonts/reset */ -.yui-calendar a:hover {background:inherit;} -p#clear {clear:left; padding-top:10px;} +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +Version 0.12 +*/ + +.yui-calcontainer { + position:relative; + padding:5px; + background-color:#F7F9FB; + border:1px solid #7B9EBD; + float:left; + overflow:hidden; +} + +.yui-calcontainer iframe { + position:absolute; + border:none; + margin:0;padding:0; + left:-1px; + top:-1px; + z-index:0; + width:50em; + height:50em; +} + +.yui-calcontainer.multi { + padding:0; +} + +.yui-calcontainer.multi .groupcal { + padding:5px; + background-color:transparent; + z-index:1; + float:left; + position:relative; + border:none; +} + +.yui-calcontainer .title { + font:100% sans-serif; + color:#000; + font-weight:bold; + margin-bottom:5px; + height:25px; + position:absolute; + top:3px;left:5px; + z-index:1; +} + +.yui-calcontainer .close-icon { + position:absolute; + right:3px; + top:3px; + border:none; + z-index:1; +} + +/* Calendar element styles */ + +.yui-calendar { + font:100% sans-serif; + text-align:center; + border-spacing:0; + border-collapse:separate; + position:relative; +} + +.yui-calcontainer.withtitle { + padding-top:1.5em; +} + +.yui-calendar .calnavleft { + position:absolute; + background-repeat:no-repeat; + cursor:pointer; + top:2px; + bottom:0; + width:9px; + height:12px; + left:2px; + z-index:1; +} + +.yui-calendar .calnavright { + position:absolute; + background-repeat:no-repeat; + cursor:pointer; + top:2px; + bottom:0; + width:9px; + height:12px; + right:2px; + z-index:1; +} + +.yui-calendar td.calcell { + padding:.1em .2em; + border:1px solid #E0E0E0; + text-align:center; +} + +.yui-calendar td.calcell a { + color:#003DB8; + text-decoration:none; +} + +.yui-calendar td.calcell.today { + border:1px solid #000; +} + +.yui-calendar td.calcell.oom { + cursor:default; + color:#999; + background-color:#EEE; + border:1px solid #E0E0E0; +} + +.yui-calendar td.calcell.selected { + color:#003DB8; + background-color:#FFF19F; + border:1px solid #FF9900; +} + +.yui-calendar td.calcell.calcellhover { + cursor:pointer; + color:#FFF; + background-color:#FF9900; + border:1px solid #FF9900; +} + +.yui-calendar td.calcell.calcellhover a { + color:#FFF; +} + +.yui-calendar td.calcell.restricted { + text-decoration:line-through; +} + +.yui-calendar td.calcell.previous { + color:#CCC; +} + +.yui-calendar td.calcell.highlight1 { background-color:#CCFF99; } +.yui-calendar td.calcell.highlight2 { background-color:#99CCFF; } +.yui-calendar td.calcell.highlight3 { background-color:#FFCCCC; } +.yui-calendar td.calcell.highlight4 { background-color:#CCFF99; } + +.yui-calendar .calhead { + border:1px solid #E0E0E0; + vertical-align:middle; + background-color:#FFF; +} + +.yui-calendar .calheader { + position:relative; + width:100%; + text-align:center; +} + +.yui-calendar .calheader img { + border:none; +} + +.yui-calendar .calweekdaycell { + color:#666; + font-weight:normal; + text-align:center; + width:1.5em; +} + +.yui-calendar .calfoot { + background-color:#EEE; +} + +.yui-calendar .calrowhead, .yui-calendar .calrowfoot { + color:#666; + font-size:9px; + font-style:italic; + font-weight:normal; + width:15px; +} + +.yui-calendar .calrowhead { + border-right-width:2px; +} + +/*Specific changes for calendar running under fonts/reset */ +.yui-calendar a:hover {background:inherit;} +p#clear {clear:left; padding-top:10px;} diff --git a/lib/yui/calendar/calendar-debug.js b/lib/yui/calendar/calendar-debug.js index 5fec1653cd..622feef52e 100755 --- a/lib/yui/calendar/calendar-debug.js +++ b/lib/yui/calendar/calendar-debug.js @@ -1,4284 +1,4283 @@ -/* -Copyright (c) 2006, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version 0.12.1 -*/ - -/** -* Config is a utility used within an Object to allow the implementer to maintain a list of local configuration properties and listen for changes to those properties dynamically using CustomEvent. The initial values are also maintained so that the configuration can be reset at any given point to its initial state. -* @namespace YAHOO.util -* @class Config -* @constructor -* @param {Object} owner The owner Object to which this Config Object belongs -*/ -YAHOO.util.Config = function(owner) { - if (owner) { - this.init(owner); - } else { - YAHOO.log("No owner specified for Config object", "error"); - } -}; - -YAHOO.util.Config.prototype = { - - /** - * Object reference to the owner of this Config Object - * @property owner - * @type Object - */ - owner : null, - - /** - * Boolean flag that specifies whether a queue is currently being executed - * @property queueInProgress - * @type Boolean - */ - queueInProgress : false, - - - /** - * Validates that the value passed in is a Boolean. - * @method checkBoolean - * @param {Object} val The value to validate - * @return {Boolean} true, if the value is valid - */ - checkBoolean: function(val) { - if (typeof val == 'boolean') { - return true; - } else { - return false; - } - }, - - /** - * Validates that the value passed in is a number. - * @method checkNumber - * @param {Object} val The value to validate - * @return {Boolean} true, if the value is valid - */ - checkNumber: function(val) { - if (isNaN(val)) { - return false; - } else { - return true; - } - } -}; - - -/** -* Initializes the configuration Object and all of its local members. -* @method init -* @param {Object} owner The owner Object to which this Config Object belongs -*/ -YAHOO.util.Config.prototype.init = function(owner) { - - this.owner = owner; - - /** - * Object reference to the owner of this Config Object - * @event configChangedEvent - */ - this.configChangedEvent = new YAHOO.util.CustomEvent("configChanged"); - this.queueInProgress = false; - - /* Private Members */ - - /** - * Maintains the local collection of configuration property objects and their specified values - * @property config - * @private - * @type Object - */ - var config = {}; - - /** - * Maintains the local collection of configuration property objects as they were initially applied. - * This object is used when resetting a property. - * @property initialConfig - * @private - * @type Object - */ - var initialConfig = {}; - - /** - * Maintains the local, normalized CustomEvent queue - * @property eventQueue - * @private - * @type Object - */ - var eventQueue = []; - - /** - * Fires a configuration property event using the specified value. - * @method fireEvent - * @private - * @param {String} key The configuration property's name - * @param {value} Object The value of the correct type for the property - */ - var fireEvent = function( key, value ) { - YAHOO.log("Firing Config event: " + key + "=" + value, "info"); - - key = key.toLowerCase(); - - var property = config[key]; - - if (typeof property != 'undefined' && property.event) { - property.event.fire(value); - } - }; - /* End Private Members */ - - /** - * Adds a property to the Config Object's private config hash. - * @method addProperty - * @param {String} key The configuration property's name - * @param {Object} propertyObject The Object containing all of this property's arguments - */ - this.addProperty = function( key, propertyObject ) { - key = key.toLowerCase(); - - YAHOO.log("Added property: " + key, "info"); - - config[key] = propertyObject; - - propertyObject.event = new YAHOO.util.CustomEvent(key); - propertyObject.key = key; - - if (propertyObject.handler) { - propertyObject.event.subscribe(propertyObject.handler, this.owner, true); - } - - this.setProperty(key, propertyObject.value, true); - - if (! propertyObject.suppressEvent) { - this.queueProperty(key, propertyObject.value); - } - }; - - /** - * Returns a key-value configuration map of the values currently set in the Config Object. - * @method getConfig - * @return {Object} The current config, represented in a key-value map - */ - this.getConfig = function() { - var cfg = {}; - - for (var prop in config) { - var property = config[prop]; - if (typeof property != 'undefined' && property.event) { - cfg[prop] = property.value; - } - } - - return cfg; - }; - - /** - * Returns the value of specified property. - * @method getProperty - * @param {String} key The name of the property - * @return {Object} The value of the specified property - */ - this.getProperty = function(key) { - key = key.toLowerCase(); - - var property = config[key]; - if (typeof property != 'undefined' && property.event) { - return property.value; - } else { - return undefined; - } - }; - - /** - * Resets the specified property's value to its initial value. - * @method resetProperty - * @param {String} key The name of the property - * @return {Boolean} True is the property was reset, false if not - */ - this.resetProperty = function(key) { - key = key.toLowerCase(); - - var property = config[key]; - if (typeof property != 'undefined' && property.event) { - if (initialConfig[key] && initialConfig[key] != 'undefined') { - this.setProperty(key, initialConfig[key]); - } - return true; - } else { - return false; - } - }; - - /** - * Sets the value of a property. If the silent property is passed as true, the property's event will not be fired. - * @method setProperty - * @param {String} key The name of the property - * @param {String} value The value to set the property to - * @param {Boolean} silent Whether the value should be set silently, without firing the property event. - * @return {Boolean} True, if the set was successful, false if it failed. - */ - this.setProperty = function(key, value, silent) { - key = key.toLowerCase(); - - YAHOO.log("setProperty: " + key + "=" + value, "info"); - - if (this.queueInProgress && ! silent) { - this.queueProperty(key,value); // Currently running through a queue... - return true; - } else { - var property = config[key]; - if (typeof property != 'undefined' && property.event) { - if (property.validator && ! property.validator(value)) { // validator - return false; - } else { - property.value = value; - if (! silent) { - fireEvent(key, value); - this.configChangedEvent.fire([key, value]); - } - return true; - } - } else { - return false; - } - } - }; - - /** - * Sets the value of a property and queues its event to execute. If the event is already scheduled to execute, it is - * moved from its current position to the end of the queue. - * @method queueProperty - * @param {String} key The name of the property - * @param {String} value The value to set the property to - * @return {Boolean} true, if the set was successful, false if it failed. - */ - this.queueProperty = function(key, value) { - key = key.toLowerCase(); - - YAHOO.log("queueProperty: " + key + "=" + value, "info"); - - var property = config[key]; - - if (typeof property != 'undefined' && property.event) { - if (typeof value != 'undefined' && property.validator && ! property.validator(value)) { // validator - return false; - } else { - - if (typeof value != 'undefined') { - property.value = value; - } else { - value = property.value; - } - - var foundDuplicate = false; - - for (var i=0;i 11) { - while (newMonth > 11) { - newMonth -= 12; - years += 1; - } - } - - d.setMonth(newMonth); - d.setFullYear(date.getFullYear() + years); - break; - case this.DAY: - d.setDate(date.getDate() + amount); - break; - case this.YEAR: - d.setFullYear(date.getFullYear() + amount); - break; - case this.WEEK: - d.setDate(date.getDate() + (amount * 7)); - break; - } - return d; - }, - - /** - * Subtracts the specified amount of time from the this instance. - * @method subtract - * @param {Date} date The JavaScript Date object to perform subtraction on - * @param {Number} field The this field constant to be used for performing subtraction. - * @param {Number} amount The number of units (measured in the field constant) to subtract from the date. - * @return {Date} The resulting Date object - */ - subtract : function(date, field, amount) { - return this.add(date, field, (amount*-1)); - }, - - /** - * Determines whether a given date is before another date on the calendar. - * @method before - * @param {Date} date The Date object to compare with the compare argument - * @param {Date} compareTo The Date object to use for the comparison - * @return {Boolean} true if the date occurs before the compared date; false if not. - */ - before : function(date, compareTo) { - var ms = compareTo.getTime(); - if (date.getTime() < ms) { - return true; - } else { - return false; - } - }, - - /** - * Determines whether a given date is after another date on the calendar. - * @method after - * @param {Date} date The Date object to compare with the compare argument - * @param {Date} compareTo The Date object to use for the comparison - * @return {Boolean} true if the date occurs after the compared date; false if not. - */ - after : function(date, compareTo) { - var ms = compareTo.getTime(); - if (date.getTime() > ms) { - return true; - } else { - return false; - } - }, - - /** - * Determines whether a given date is between two other dates on the calendar. - * @method between - * @param {Date} date The date to check for - * @param {Date} dateBegin The start of the range - * @param {Date} dateEnd The end of the range - * @return {Boolean} true if the date occurs between the compared dates; false if not. - */ - between : function(date, dateBegin, dateEnd) { - if (this.after(date, dateBegin) && this.before(date, dateEnd)) { - return true; - } else { - return false; - } - }, - - /** - * Retrieves a JavaScript Date object representing January 1 of any given year. - * @method getJan1 - * @param {Number} calendarYear The calendar year for which to retrieve January 1 - * @return {Date} January 1 of the calendar year specified. - */ - getJan1 : function(calendarYear) { - return new Date(calendarYear,0,1); - }, - - /** - * Calculates the number of days the specified date is from January 1 of the specified calendar year. - * Passing January 1 to this function would return an offset value of zero. - * @method getDayOffset - * @param {Date} date The JavaScript date for which to find the offset - * @param {Number} calendarYear The calendar year to use for determining the offset - * @return {Number} The number of days since January 1 of the given year - */ - getDayOffset : function(date, calendarYear) { - var beginYear = this.getJan1(calendarYear); // Find the start of the year. This will be in week 1. - - // Find the number of days the passed in date is away from the calendar year start - var dayOffset = Math.ceil((date.getTime()-beginYear.getTime()) / this.ONE_DAY_MS); - return dayOffset; - }, - - /** - * Calculates the week number for the given date. This function assumes that week 1 is the - * week in which January 1 appears, regardless of whether the week consists of a full 7 days. - * The calendar year can be specified to help find what a the week number would be for a given - * date if the date overlaps years. For instance, a week may be considered week 1 of 2005, or - * week 53 of 2004. Specifying the optional calendarYear allows one to make this distinction - * easily. - * @method getWeekNumber - * @param {Date} date The JavaScript date for which to find the week number - * @param {Number} calendarYear OPTIONAL - The calendar year to use for determining the week number. Default is - * the calendar year of parameter "date". - * @param {Number} weekStartsOn OPTIONAL - The integer (0-6) representing which day a week begins on. Default is 0 (for Sunday). - * @return {Number} The week number of the given date. - */ - getWeekNumber : function(date, calendarYear) { - date = this.clearTime(date); - var nearestThurs = new Date(date.getTime() + (4 * this.ONE_DAY_MS) - ((date.getDay()) * this.ONE_DAY_MS)); - - var jan1 = new Date(nearestThurs.getFullYear(),0,1); - var dayOfYear = ((nearestThurs.getTime() - jan1.getTime()) / this.ONE_DAY_MS) - 1; - - var weekNum = Math.ceil((dayOfYear)/ 7); - return weekNum; - }, - - /** - * Determines if a given week overlaps two different years. - * @method isYearOverlapWeek - * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. - * @return {Boolean} true if the date overlaps two different years. - */ - isYearOverlapWeek : function(weekBeginDate) { - var overlaps = false; - var nextWeek = this.add(weekBeginDate, this.DAY, 6); - if (nextWeek.getFullYear() != weekBeginDate.getFullYear()) { - overlaps = true; - } - return overlaps; - }, - - /** - * Determines if a given week overlaps two different months. - * @method isMonthOverlapWeek - * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. - * @return {Boolean} true if the date overlaps two different months. - */ - isMonthOverlapWeek : function(weekBeginDate) { - var overlaps = false; - var nextWeek = this.add(weekBeginDate, this.DAY, 6); - if (nextWeek.getMonth() != weekBeginDate.getMonth()) { - overlaps = true; - } - return overlaps; - }, - - /** - * Gets the first day of a month containing a given date. - * @method findMonthStart - * @param {Date} date The JavaScript Date used to calculate the month start - * @return {Date} The JavaScript Date representing the first day of the month - */ - findMonthStart : function(date) { - var start = new Date(date.getFullYear(), date.getMonth(), 1); - return start; - }, - - /** - * Gets the last day of a month containing a given date. - * @method findMonthEnd - * @param {Date} date The JavaScript Date used to calculate the month end - * @return {Date} The JavaScript Date representing the last day of the month - */ - findMonthEnd : function(date) { - var start = this.findMonthStart(date); - var nextMonth = this.add(start, this.MONTH, 1); - var end = this.subtract(nextMonth, this.DAY, 1); - return end; - }, - - /** - * Clears the time fields from a given date, effectively setting the time to midnight. - * @method clearTime - * @param {Date} date The JavaScript Date for which the time fields will be cleared - * @return {Date} The JavaScript Date cleared of all time fields - */ - clearTime : function(date) { - date.setHours(12,0,0,0); - return date; - } -}; - -/** -* The Calendar component is a UI control that enables users to choose one or more dates from a graphical calendar presented in a one-month ("one-up") or two-month ("two-up") interface. Calendars are generated entirely via script and can be navigated without any page refreshes. -* @module calendar -* @title Calendar -* @namespace YAHOO.widget -* @requires yahoo,dom,event -*/ - -/** -* Calendar is the base class for the Calendar widget. In its most basic -* implementation, it has the ability to render a calendar widget on the page -* that can be manipulated to select a single date, move back and forth between -* months and years. -*

To construct the placeholder for the calendar widget, the code is as -* follows: -*

-* <div id="cal1Container"></div> -* -* Note that the table can be replaced with any kind of element. -*

-* @namespace YAHOO.widget -* @class Calendar -* @constructor -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.Calendar = function(id, containerId, config) { - this.init(id, containerId, config); -}; - -/** -* The path to be used for images loaded for the Calendar -* @property YAHOO.widget.Calendar.IMG_ROOT -* @static -* @type String -*/ -YAHOO.widget.Calendar.IMG_ROOT = (window.location.href.toLowerCase().indexOf("https") === 0 ? "https://a248.e.akamai.net/sec.yimg.com/i/" : "http://us.i1.yimg.com/us.yimg.com/i/"); - -/** -* Type constant used for renderers to represent an individual date (M/D/Y) -* @property YAHOO.widget.Calendar.DATE -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.DATE = "D"; - -/** -* Type constant used for renderers to represent an individual date across any year (M/D) -* @property YAHOO.widget.Calendar.MONTH_DAY -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.MONTH_DAY = "MD"; - -/** -* Type constant used for renderers to represent a weekday -* @property YAHOO.widget.Calendar.WEEKDAY -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.WEEKDAY = "WD"; - -/** -* Type constant used for renderers to represent a range of individual dates (M/D/Y-M/D/Y) -* @property YAHOO.widget.Calendar.RANGE -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.RANGE = "R"; - -/** -* Type constant used for renderers to represent a month across any year -* @property YAHOO.widget.Calendar.MONTH -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.MONTH = "M"; - -/** -* Constant that represents the total number of date cells that are displayed in a given month -* @property YAHOO.widget.Calendar.DISPLAY_DAYS -* @static -* @final -* @type Number -*/ -YAHOO.widget.Calendar.DISPLAY_DAYS = 42; - -/** -* Constant used for halting the execution of the remainder of the render stack -* @property YAHOO.widget.Calendar.STOP_RENDER -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.STOP_RENDER = "S"; - -YAHOO.widget.Calendar.prototype = { - - /** - * The configuration object used to set up the calendars various locale and style options. - * @property Config - * @private - * @deprecated Configuration properties should be set by calling Calendar.cfg.setProperty. - * @type Object - */ - Config : null, - - /** - * The parent CalendarGroup, only to be set explicitly by the parent group - * @property parent - * @type CalendarGroup - */ - parent : null, - - /** - * The index of this item in the parent group - * @property index - * @type Number - */ - index : -1, - - /** - * The collection of calendar table cells - * @property cells - * @type HTMLTableCellElement[] - */ - cells : null, - - /** - * The collection of calendar cell dates that is parallel to the cells collection. The array contains dates field arrays in the format of [YYYY, M, D]. - * @property cellDates - * @type Array[](Number[]) - */ - cellDates : null, - - /** - * The id that uniquely identifies this calendar. This id should match the id of the placeholder element on the page. - * @property id - * @type String - */ - id : null, - - /** - * The DOM element reference that points to this calendar's container element. The calendar will be inserted into this element when the shell is rendered. - * @property oDomContainer - * @type HTMLElement - */ - oDomContainer : null, - - /** - * A Date object representing today's date. - * @property today - * @type Date - */ - today : null, - - /** - * The list of render functions, along with required parameters, used to render cells. - * @property renderStack - * @type Array[] - */ - renderStack : null, - - /** - * A copy of the initial render functions created before rendering. - * @property _renderStack - * @private - * @type Array - */ - _renderStack : null, - - /** - * A Date object representing the month/year that the calendar is initially set to - * @property _pageDate - * @private - * @type Date - */ - _pageDate : null, - - /** - * The private list of initially selected dates. - * @property _selectedDates - * @private - * @type Array - */ - _selectedDates : null, - - /** - * A map of DOM event handlers to attach to cells associated with specific CSS class names - * @property domEventMap - * @type Object - */ - domEventMap : null -}; - - - -/** -* Initializes the Calendar widget. -* @method init -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.Calendar.prototype.init = function(id, containerId, config) { - this.logger = new YAHOO.widget.LogWriter("Calendar_Core " + id); - - this.initEvents(); - this.today = new Date(); - YAHOO.widget.DateMath.clearTime(this.today); - - this.id = id; - this.oDomContainer = document.getElementById(containerId); - if (! this.oDomContainer) { - this.logger.log("No valid container present.", "error"); - } - - /** - * The Config object used to hold the configuration variables for the Calendar - * @property cfg - * @type YAHOO.util.Config - */ - this.cfg = new YAHOO.util.Config(this); - - /** - * The local object which contains the Calendar's options - * @property Options - * @type Object - */ - this.Options = {}; - - /** - * The local object which contains the Calendar's locale settings - * @property Locale - * @type Object - */ - this.Locale = {}; - - this.initStyles(); - - YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_CONTAINER); - YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_SINGLE); - - this.cellDates = []; - this.cells = []; - this.renderStack = []; - this._renderStack = []; - - this.setupConfig(); - - if (config) { - this.cfg.applyConfig(config, true); - } - - this.cfg.fireQueue(); -}; - -/** -* Renders the built-in IFRAME shim for the IE6 and below -* @method configIframe -*/ -YAHOO.widget.Calendar.prototype.configIframe = function(type, args, obj) { - var useIframe = args[0]; - - if (YAHOO.util.Dom.inDocument(this.oDomContainer)) { - if (useIframe) { - var pos = YAHOO.util.Dom.getStyle(this.oDomContainer, "position"); - - if (this.browser == "ie" && (pos == "absolute" || pos == "relative")) { - if (! YAHOO.util.Dom.inDocument(this.iframe)) { - this.iframe = document.createElement("iframe"); - this.iframe.src = "javascript:false;"; - YAHOO.util.Dom.setStyle(this.iframe, "opacity", "0"); - this.oDomContainer.insertBefore(this.iframe, this.oDomContainer.firstChild); - } - } - } else { - if (this.iframe) { - if (this.iframe.parentNode) { - this.iframe.parentNode.removeChild(this.iframe); - } - this.iframe = null; - } - } - } -}; - -/** -* Default handler for the "title" property -* @method configTitle -*/ -YAHOO.widget.Calendar.prototype.configTitle = function(type, args, obj) { - var title = args[0]; - var close = this.cfg.getProperty("close"); - - var titleDiv; - - if (title && title !== "") { - titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || document.createElement("div"); - titleDiv.className = YAHOO.widget.CalendarGroup.CSS_2UPTITLE; - titleDiv.innerHTML = title; - this.oDomContainer.insertBefore(titleDiv, this.oDomContainer.firstChild); - YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); - } else { - titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || null; - - if (titleDiv) { - YAHOO.util.Event.purgeElement(titleDiv); - this.oDomContainer.removeChild(titleDiv); - } - if (! close) { - YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); - } - } -}; - -/** -* Default handler for the "close" property -* @method configClose -*/ -YAHOO.widget.Calendar.prototype.configClose = function(type, args, obj) { - var close = args[0]; - var title = this.cfg.getProperty("title"); - - var linkClose; - - if (close === true) { - linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || document.createElement("a"); - linkClose.href = "javascript:void(null);"; - linkClose.className = "link-close"; - YAHOO.util.Event.addListener(linkClose, "click", this.hide, this, true); - var imgClose = document.createElement("img"); - imgClose.src = YAHOO.widget.Calendar.IMG_ROOT + "us/my/bn/x_d.gif"; - imgClose.className = YAHOO.widget.CalendarGroup.CSS_2UPCLOSE; - linkClose.appendChild(imgClose); - this.oDomContainer.appendChild(linkClose); - YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); - } else { - linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || null; - - if (linkClose) { - YAHOO.util.Event.purgeElement(linkClose); - this.oDomContainer.removeChild(linkClose); - } - if (! title || title === "") { - YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); - } - } -}; - -/** -* Initializes Calendar's built-in CustomEvents -* @method initEvents -*/ -YAHOO.widget.Calendar.prototype.initEvents = function() { - - /** - * Fired before a selection is made - * @event beforeSelectEvent - */ - this.beforeSelectEvent = new YAHOO.util.CustomEvent("beforeSelect"); - - /** - * Fired when a selection is made - * @event selectEvent - * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. - */ - this.selectEvent = new YAHOO.util.CustomEvent("select"); - - /** - * Fired before a selection is made - * @event beforeDeselectEvent - */ - this.beforeDeselectEvent = new YAHOO.util.CustomEvent("beforeDeselect"); - - /** - * Fired when a selection is made - * @event deselectEvent - * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. - */ - this.deselectEvent = new YAHOO.util.CustomEvent("deselect"); - - /** - * Fired when the Calendar page is changed - * @event changePageEvent - */ - this.changePageEvent = new YAHOO.util.CustomEvent("changePage"); - - /** - * Fired before the Calendar is rendered - * @event beforeRenderEvent - */ - this.beforeRenderEvent = new YAHOO.util.CustomEvent("beforeRender"); - - /** - * Fired when the Calendar is rendered - * @event renderEvent - */ - this.renderEvent = new YAHOO.util.CustomEvent("render"); - - /** - * Fired when the Calendar is reset - * @event resetEvent - */ - this.resetEvent = new YAHOO.util.CustomEvent("reset"); - - /** - * Fired when the Calendar is cleared - * @event clearEvent - */ - this.clearEvent = new YAHOO.util.CustomEvent("clear"); - - this.beforeSelectEvent.subscribe(this.onBeforeSelect, this, true); - this.selectEvent.subscribe(this.onSelect, this, true); - this.beforeDeselectEvent.subscribe(this.onBeforeDeselect, this, true); - this.deselectEvent.subscribe(this.onDeselect, this, true); - this.changePageEvent.subscribe(this.onChangePage, this, true); - this.renderEvent.subscribe(this.onRender, this, true); - this.resetEvent.subscribe(this.onReset, this, true); - this.clearEvent.subscribe(this.onClear, this, true); -}; - - -/** -* The default event function that is attached to a date link within a calendar cell -* when the calendar is rendered. -* @method doSelectCell -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doSelectCell = function(e, cal) { - var target = YAHOO.util.Event.getTarget(e); - - var cell,index,d,date; - - while (target.tagName.toLowerCase() != "td" && ! YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - cell = target; - - if (YAHOO.util.Dom.hasClass(cell, cal.Style.CSS_CELL_SELECTABLE)) { - index = cell.id.split("cell")[1]; - d = cal.cellDates[index]; - date = new Date(d[0],d[1]-1,d[2]); - - var link; - - cal.logger.log("Selecting cell " + index + " via click", "info"); - - if (cal.Options.MULTI_SELECT) { - link = cell.getElementsByTagName("a")[0]; - if (link) { - link.blur(); - } - - var cellDate = cal.cellDates[index]; - var cellDateIndex = cal._indexOfSelectedFieldArray(cellDate); - - if (cellDateIndex > -1) { - cal.deselectCell(index); - } else { - cal.selectCell(index); - } - - } else { - link = cell.getElementsByTagName("a")[0]; - if (link) { - link.blur(); - } - cal.selectCell(index); - } - } -}; - -/** -* The event that is executed when the user hovers over a cell -* @method doCellMouseOver -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doCellMouseOver = function(e, cal) { - var target; - if (e) { - target = YAHOO.util.Event.getTarget(e); - } else { - target = this; - } - - while (target.tagName.toLowerCase() != "td") { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - YAHOO.util.Dom.addClass(target, cal.Style.CSS_CELL_HOVER); - } -}; - -/** -* The event that is executed when the user moves the mouse out of a cell -* @method doCellMouseOut -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doCellMouseOut = function(e, cal) { - var target; - if (e) { - target = YAHOO.util.Event.getTarget(e); - } else { - target = this; - } - - while (target.tagName.toLowerCase() != "td") { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - YAHOO.util.Dom.removeClass(target, cal.Style.CSS_CELL_HOVER); - } -}; - -YAHOO.widget.Calendar.prototype.setupConfig = function() { - - /** - * The month/year representing the current visible Calendar date (mm/yyyy) - * @config pagedate - * @type String - * @default today's date - */ - this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); - - /** - * The date or range of dates representing the current Calendar selection - * @config selected - * @type String - * @default [] - */ - this.cfg.addProperty("selected", { value:[], handler:this.configSelected } ); - - /** - * The title to display above the Calendar's month header - * @config title - * @type String - * @default "" - */ - this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); - - /** - * Whether or not a close button should be displayed for this Calendar - * @config close - * @type Boolean - * @default false - */ - this.cfg.addProperty("close", { value:false, handler:this.configClose } ); - - /** - * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. - * @config iframe - * @type Boolean - * @default true - */ - this.cfg.addProperty("iframe", { value:true, handler:this.configIframe, validator:this.cfg.checkBoolean } ); - - /** - * The minimum selectable date in the current Calendar (mm/dd/yyyy) - * @config mindate - * @type String - * @default null - */ - this.cfg.addProperty("mindate", { value:null, handler:this.configMinDate } ); - - /** - * The maximum selectable date in the current Calendar (mm/dd/yyyy) - * @config maxdate - * @type String - * @default null - */ - this.cfg.addProperty("maxdate", { value:null, handler:this.configMaxDate } ); - - - // Options properties - - /** - * True if the Calendar should allow multiple selections. False by default. - * @config MULTI_SELECT - * @type Boolean - * @default false - */ - this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * The weekday the week begins on. Default is 0 (Sunday). - * @config START_WEEKDAY - * @type number - * @default 0 - */ - this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.configOptions, validator:this.cfg.checkNumber } ); - - /** - * True if the Calendar should show weekday labels. True by default. - * @config SHOW_WEEKDAYS - * @type Boolean - * @default true - */ - this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row headers. False by default. - * @config SHOW_WEEK_HEADER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row footers. False by default. - * @config SHOW_WEEK_FOOTER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should suppress weeks that are not a part of the current month. False by default. - * @config HIDE_BLANK_WEEKS - * @type Boolean - * @default false - */ - this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_LEFT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" - */ - this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.configOptions } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_RIGHT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" - */ - this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.configOptions } ); - - // Locale properties - - /** - * The short month labels for the current locale. - * @config MONTHS_SHORT - * @type String[] - * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - */ - this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.configLocale } ); - - /** - * The long month labels for the current locale. - * @config MONTHS_LONG - * @type String[] - * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" - */ - this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.configLocale } ); - - /** - * The 1-character weekday labels for the current locale. - * @config WEEKDAYS_1CHAR - * @type String[] - * @default ["S", "M", "T", "W", "T", "F", "S"] - */ - this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.configLocale } ); - - /** - * The short weekday labels for the current locale. - * @config WEEKDAYS_SHORT - * @type String[] - * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] - */ - this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.configLocale } ); - - /** - * The medium weekday labels for the current locale. - * @config WEEKDAYS_MEDIUM - * @type String[] - * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] - */ - this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.configLocale } ); - - /** - * The long weekday labels for the current locale. - * @config WEEKDAYS_LONG - * @type String[] - * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] - */ - this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.configLocale } ); - - /** - * Refreshes the locale values used to build the Calendar. - * @method refreshLocale - * @private - */ - var refreshLocale = function() { - this.cfg.refireEvent("LOCALE_MONTHS"); - this.cfg.refireEvent("LOCALE_WEEKDAYS"); - }; - - this.cfg.subscribeToConfigEvent("START_WEEKDAY", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("MONTHS_SHORT", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("MONTHS_LONG", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG", refreshLocale, this, true); - - /** - * The setting that determines which length of month labels should be used. Possible values are "short" and "long". - * @config LOCALE_MONTHS - * @type String - * @default "long" - */ - this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.configLocaleValues } ); - - /** - * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". - * @config LOCALE_WEEKDAYS - * @type String - * @default "short" - */ - this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.configLocaleValues } ); - - /** - * The value used to delimit individual dates in a date string passed to various Calendar functions. - * @config DATE_DELIMITER - * @type String - * @default "," - */ - this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.configLocale } ); - - /** - * The value used to delimit date fields in a date string passed to various Calendar functions. - * @config DATE_FIELD_DELIMITER - * @type String - * @default "/" - */ - this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.configLocale } ); - - /** - * The value used to delimit date ranges in a date string passed to various Calendar functions. - * @config DATE_RANGE_DELIMITER - * @type String - * @default "-" - */ - this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.configLocale } ); - - /** - * The position of the month in a month/year date string - * @config MY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/year date string - * @config MY_YEAR_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day date string - * @config MD_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/year date string - * @config MD_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day/year date string - * @config MDY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/day/year date string - * @config MDY_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/day/year date string - * @config MDY_YEAR_POSITION - * @type Number - * @default 3 - */ - this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.configLocale, validator:this.cfg.checkNumber } ); -}; - -/** -* The default handler for the "pagedate" property -* @method configPageDate -*/ -YAHOO.widget.Calendar.prototype.configPageDate = function(type, args, obj) { - var val = args[0]; - var month, year, aMonthYear; - - if (val) { - if (val instanceof Date) { - val = YAHOO.widget.DateMath.findMonthStart(val); - this.cfg.setProperty("pagedate", val, true); - if (! this._pageDate) { - this._pageDate = this.cfg.getProperty("pagedate"); - } - return; - } else { - aMonthYear = val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER")); - month = parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1], 10)-1; - year = parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1], 10); - } - } else { - month = this.today.getMonth(); - year = this.today.getFullYear(); - } - - this.cfg.setProperty("pagedate", new Date(year, month, 1), true); - - this.logger.log("Set month/year to " + month + "/" + year, "info"); - - if (! this._pageDate) { - this._pageDate = this.cfg.getProperty("pagedate"); - } -}; - -/** -* The default handler for the "mindate" property -* @method configMinDate -*/ -YAHOO.widget.Calendar.prototype.configMinDate = function(type, args, obj) { - var val = args[0]; - if (typeof val == 'string') { - val = this._parseDate(val); - this.cfg.setProperty("mindate", new Date(val[0],(val[1]-1),val[2])); - } -}; - -/** -* The default handler for the "maxdate" property -* @method configMaxDate -*/ -YAHOO.widget.Calendar.prototype.configMaxDate = function(type, args, obj) { - var val = args[0]; - if (typeof val == 'string') { - val = this._parseDate(val); - this.cfg.setProperty("maxdate", new Date(val[0],(val[1]-1),val[2])); - } -}; - -/** -* The default handler for the "selected" property -* @method configSelected -*/ -YAHOO.widget.Calendar.prototype.configSelected = function(type, args, obj) { - var selected = args[0]; - - if (selected) { - if (typeof selected == 'string') { - this.cfg.setProperty("selected", this._parseDates(selected), true); - } - } - if (! this._selectedDates) { - this._selectedDates = this.cfg.getProperty("selected"); - } -}; - -/** -* The default handler for all configuration options properties -* @method configOptions -*/ -YAHOO.widget.Calendar.prototype.configOptions = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - this.Options[type] = val; -}; - -/** -* The default handler for all configuration locale properties -* @method configLocale -*/ -YAHOO.widget.Calendar.prototype.configLocale = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - this.Locale[type] = val; - - this.cfg.refireEvent("LOCALE_MONTHS"); - this.cfg.refireEvent("LOCALE_WEEKDAYS"); - -}; - -/** -* The default handler for all configuration locale field length properties -* @method configLocaleValues -*/ -YAHOO.widget.Calendar.prototype.configLocaleValues = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - - switch (type) { - case "LOCALE_MONTHS": - switch (val) { - case "short": - this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_SHORT").concat(); - break; - case "long": - this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_LONG").concat(); - break; - } - break; - case "LOCALE_WEEKDAYS": - switch (val) { - case "1char": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_1CHAR").concat(); - break; - case "short": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_SHORT").concat(); - break; - case "medium": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_MEDIUM").concat(); - break; - case "long": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_LONG").concat(); - break; - } - - var START_WEEKDAY = this.cfg.getProperty("START_WEEKDAY"); - - if (START_WEEKDAY > 0) { - for (var w=0;w'; - html[html.length] = '
'; - - var renderLeft, renderRight = false; - - if (this.parent) { - if (this.index === 0) { - renderLeft = true; - } - if (this.index == (this.parent.cfg.getProperty("pages") -1)) { - renderRight = true; - } - } else { - renderLeft = true; - renderRight = true; - } - - var cal = this.parent || this; - - if (renderLeft) { - html[html.length] = ' '; - } - - html[html.length] = this.buildMonthLabel(); - - if (renderRight) { - html[html.length] = ' '; - } - - - html[html.length] = '
'; - html[html.length] = ''; - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEKDAYS")) { - html = this.buildWeekdays(html); - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the Calendar's weekday headers. -* @method buildWeekdays -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.buildWeekdays = function(html) { - - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { - html[html.length] = ' '; - } - - for(var i=0;i'; - } - - if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { - html[html.length] = ' '; - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the calendar body. -* @method renderBody -* @param {Date} workingDate The current working Date being used for the render process -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderBody = function(workingDate, html) { - this.logger.log("Rendering body", "info"); - - var startDay = this.cfg.getProperty("START_WEEKDAY"); - - this.preMonthDays = workingDate.getDay(); - if (startDay > 0) { - this.preMonthDays -= startDay; - } - if (this.preMonthDays < 0) { - this.preMonthDays += 7; - } - - this.monthDays = YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate(); - this.postMonthDays = YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays; - - this.logger.log(this.preMonthDays + " preciding out-of-month days", "info"); - this.logger.log(this.monthDays + " month days", "info"); - this.logger.log(this.postMonthDays + " post-month days", "info"); - - workingDate = YAHOO.widget.DateMath.subtract(workingDate, YAHOO.widget.DateMath.DAY, this.preMonthDays); - this.logger.log("Calendar page starts on " + workingDate, "info"); - - var useDate,weekNum,weekClass; - useDate = this.cfg.getProperty("pagedate"); - - html[html.length] = ''; - - var i = 0; - - var tempDiv = document.createElement("div"); - var cell = document.createElement("td"); - tempDiv.appendChild(cell); - - var jan1 = new Date(useDate.getFullYear(),0,1); - - var cal = this.parent || this; - - for (var r=0;r<6;r++) { - - weekNum = YAHOO.widget.DateMath.getWeekNumber(workingDate, useDate.getFullYear(), startDay); - - weekClass = "w" + weekNum; - - if (r !== 0 && this.isDateOOM(workingDate) && this.cfg.getProperty("HIDE_BLANK_WEEKS") === true) { - break; - } else { - - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { html = this.renderRowHeader(weekNum, html); } - - for (var d=0;d<7;d++){ // Render actual days - - var cellRenderers = []; - - this.clearElement(cell); - - YAHOO.util.Dom.addClass(cell, "calcell"); - - cell.id = this.id + "_cell" + i; - this.logger.log("Rendering cell " + cell.id + " (" + workingDate.getFullYear() + "-" + (workingDate.getMonth()+1) + "-" + workingDate.getDate() + ")", "cellrender"); - - cell.innerHTML = i; - - var renderer = null; - - if (workingDate.getFullYear() == this.today.getFullYear() && - workingDate.getMonth() == this.today.getMonth() && - workingDate.getDate() == this.today.getDate()) { - cellRenderers[cellRenderers.length]=cal.renderCellStyleToday; - } - - this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]; // Add this date to cellDates - - if (this.isDateOOM(workingDate)) { - cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth; - } else { - - YAHOO.util.Dom.addClass(cell, "wd" + workingDate.getDay()); - YAHOO.util.Dom.addClass(cell, "d" + workingDate.getDate()); - - for (var s=0;s= d1.getTime() && workingDate.getTime() <= d2.getTime()) { - renderer = rArray[2]; - - if (workingDate.getTime()==d2.getTime()) { - this.renderStack.splice(s,1); - } - } - break; - case YAHOO.widget.Calendar.WEEKDAY: - - var weekday = rArray[1][0]; - if (workingDate.getDay()+1 == weekday) { - renderer = rArray[2]; - } - break; - case YAHOO.widget.Calendar.MONTH: - - month = rArray[1][0]; - if (workingDate.getMonth()+1 == month) { - renderer = rArray[2]; - } - break; - } - - if (renderer) { - cellRenderers[cellRenderers.length]=renderer; - } - } - - } - - if (this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]) > -1) { - cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected; - } - - var mindate = this.cfg.getProperty("mindate"); - var maxdate = this.cfg.getProperty("maxdate"); - - if (mindate) { - mindate = YAHOO.widget.DateMath.clearTime(mindate); - } - if (maxdate) { - maxdate = YAHOO.widget.DateMath.clearTime(maxdate); - } - - if ( - (mindate && (workingDate.getTime() < mindate.getTime())) || - (maxdate && (workingDate.getTime() > maxdate.getTime())) - ) { - cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate; - } else { - cellRenderers[cellRenderers.length]=cal.styleCellDefault; - cellRenderers[cellRenderers.length]=cal.renderCellDefault; - } - - - - for (var x=0;x= 0 && i <= 6) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TOP); - } - if ((i % 7) === 0) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_LEFT); - } - if (((i+1) % 7) === 0) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RIGHT); - } - - var postDays = this.postMonthDays; - if (postDays >= 7 && this.cfg.getProperty("HIDE_BLANK_WEEKS")) { - var blankWeeks = Math.floor(postDays/7); - for (var p=0;p= ((this.preMonthDays+postDays+this.monthDays)-7)) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_BOTTOM); - } - - html[html.length] = tempDiv.innerHTML; - - i++; - } - - if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { html = this.renderRowFooter(weekNum, html); } - - html[html.length] = ''; - } - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the calendar footer. In the default implementation, there is -* no footer. -* @method renderFooter -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderFooter = function(html) { return html; }; - -/** -* Renders the calendar after it has been configured. The render() method has a specific call chain that will execute -* when the method is called: renderHeader, renderBody, renderFooter. -* Refer to the documentation for those methods for information on -* individual render tasks. -* @method render -*/ -YAHOO.widget.Calendar.prototype.render = function() { - this.beforeRenderEvent.fire(); - - // Find starting day of the current month - var workingDate = YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate")); - - this.resetRenderers(); - this.cellDates.length = 0; - - YAHOO.util.Event.purgeElement(this.oDomContainer, true); - - var html = []; - - html[html.length] = ''; - html = this.renderHeader(html); - html = this.renderBody(workingDate, html); - html = this.renderFooter(html); - html[html.length] = '
'; - - this.oDomContainer.innerHTML = html.join("\n"); - - this.applyListeners(); - this.cells = this.oDomContainer.getElementsByTagName("td"); - - this.cfg.refireEvent("title"); - this.cfg.refireEvent("close"); - this.cfg.refireEvent("iframe"); - - this.renderEvent.fire(); -}; - -/** -* Applies the Calendar's DOM listeners to applicable elements. -* @method applyListeners -*/ -YAHOO.widget.Calendar.prototype.applyListeners = function() { - - var root = this.oDomContainer; - var cal = this.parent || this; - - var linkLeft, linkRight; - - linkLeft = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT, "a", root); - linkRight = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT, "a", root); - - if (linkLeft) { - this.linkLeft = linkLeft[0]; - YAHOO.util.Event.addListener(this.linkLeft, "mousedown", cal.previousMonth, cal, true); - } - - if (linkRight) { - this.linkRight = linkRight[0]; - YAHOO.util.Event.addListener(this.linkRight, "mousedown", cal.nextMonth, cal, true); - } - - if (this.domEventMap) { - var el,elements; - for (var cls in this.domEventMap) { - if (this.domEventMap.hasOwnProperty(cls)) { - var items = this.domEventMap[cls]; - - if (! (items instanceof Array)) { - items = [items]; - } - - for (var i=0;i'; - return html; -}; - -/** -* Renders the row footer for a week. -* @method renderRowFooter -* @param {Number} weekNum The week number of the current row -* @param {Array} cell The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderRowFooter = function(weekNum, html) { - html[html.length] = '' + weekNum + ''; - return html; -}; - -/** -* Renders a single standard calendar cell in the calendar widget table. -* All logic for determining how a standard default cell will be rendered is -* encapsulated in this method, and must be accounted for when extending the -* widget class. -* @method renderCellDefault -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellDefault = function(workingDate, cell) { - cell.innerHTML = '' + this.buildDayLabel(workingDate) + ""; -}; - -/** -* Styles a selectable cell. -* @method styleCellDefault -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.styleCellDefault = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTABLE); -}; - - -/** -* Renders a single standard calendar cell using the CSS hightlight1 style -* @method renderCellStyleHighlight1 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT1); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight2 style -* @method renderCellStyleHighlight2 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT2); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight3 style -* @method renderCellStyleHighlight3 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT3); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight4 style -* @method renderCellStyleHighlight4 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT4); -}; - -/** -* Applies the default style used for rendering today's date to the current calendar cell -* @method renderCellStyleToday -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleToday = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TODAY); -}; - -/** -* Applies the default style used for rendering selected dates to the current calendar cell -* @method renderCellStyleSelected -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleSelected = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTED); -}; - -/** -* Applies the default style used for rendering dates that are not a part of the current -* month (preceding or trailing the cells for the current month) -* @method renderCellNotThisMonth -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderCellNotThisMonth = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_OOM); - cell.innerHTML=workingDate.getDate(); - return YAHOO.widget.Calendar.STOP_RENDER; -}; - -/** -* Renders the current calendar cell as a non-selectable "black-out" date using the default -* restricted style. -* @method renderBodyCellRestricted -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderBodyCellRestricted = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL); - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RESTRICTED); - cell.innerHTML=workingDate.getDate(); - return YAHOO.widget.Calendar.STOP_RENDER; -}; - -// END BUILT-IN TABLE CELL RENDERERS - -// BEGIN MONTH NAVIGATION METHODS - -/** -* Adds the designated number of months to the current calendar month, and sets the current -* calendar page date to the new month. -* @method addMonths -* @param {Number} count The number of months to add to the current calendar -*/ -YAHOO.widget.Calendar.prototype.addMonths = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Subtracts the designated number of months from the current calendar month, and sets the current -* calendar page date to the new month. -* @method subtractMonths -* @param {Number} count The number of months to subtract from the current calendar -*/ -YAHOO.widget.Calendar.prototype.subtractMonths = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Adds the designated number of years to the current calendar, and sets the current -* calendar page date to the new month. -* @method addYears -* @param {Number} count The number of years to add to the current calendar -*/ -YAHOO.widget.Calendar.prototype.addYears = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Subtcats the designated number of years from the current calendar, and sets the current -* calendar page date to the new month. -* @method subtractYears -* @param {Number} count The number of years to subtract from the current calendar -*/ -YAHOO.widget.Calendar.prototype.subtractYears = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Navigates to the next month page in the calendar widget. -* @method nextMonth -*/ -YAHOO.widget.Calendar.prototype.nextMonth = function() { - this.addMonths(1); -}; - -/** -* Navigates to the previous month page in the calendar widget. -* @method previousMonth -*/ -YAHOO.widget.Calendar.prototype.previousMonth = function() { - this.subtractMonths(1); -}; - -/** -* Navigates to the next year in the currently selected month in the calendar widget. -* @method nextYear -*/ -YAHOO.widget.Calendar.prototype.nextYear = function() { - this.addYears(1); -}; - -/** -* Navigates to the previous year in the currently selected month in the calendar widget. -* @method previousYear -*/ -YAHOO.widget.Calendar.prototype.previousYear = function() { - this.subtractYears(1); -}; - -// END MONTH NAVIGATION METHODS - -// BEGIN SELECTION METHODS - -/** -* Resets the calendar widget to the originally selected month and year, and -* sets the calendar to the initial selection(s). -* @method reset -*/ -YAHOO.widget.Calendar.prototype.reset = function() { - this.cfg.resetProperty("selected"); - this.cfg.resetProperty("pagedate"); - this.resetEvent.fire(); -}; - -/** -* Clears the selected dates in the current calendar widget and sets the calendar -* to the current month and year. -* @method clear -*/ -YAHOO.widget.Calendar.prototype.clear = function() { - this.cfg.setProperty("selected", []); - this.cfg.setProperty("pagedate", new Date(this.today.getTime())); - this.clearEvent.fire(); -}; - -/** -* Selects a date or a collection of dates on the current calendar. This method, by default, -* does not call the render method explicitly. Once selection has completed, render must be -* called for the changes to be reflected visually. -* @method select -* @param {String/Date/Date[]} date The date string of dates to select in the current calendar. Valid formats are -* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). -* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). -* This method can also take a JavaScript Date object or an array of Date objects. -* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. -*/ -YAHOO.widget.Calendar.prototype.select = function(date) { - this.logger.log("Select: " + date, "info"); - - this.beforeSelectEvent.fire(); - - var selected = this.cfg.getProperty("selected"); - var aToBeSelected = this._toFieldArray(date); - this.logger.log("Selection field array: " + aToBeSelected, "info"); - - for (var a=0;a -1) { - if (this.cfg.getProperty("pagedate").getMonth() == dCellDate.getMonth() && - this.cfg.getProperty("pagedate").getFullYear() == dCellDate.getFullYear()) { - YAHOO.util.Dom.removeClass(cell, this.Style.CSS_CELL_SELECTED); - } - - selected.splice(cellDateIndex, 1); - } - - - if (this.parent) { - this.parent.cfg.setProperty("selected", selected); - } else { - this.cfg.setProperty("selected", selected); - } - - this.deselectEvent.fire(selectDate); - return this.getSelectedDates(); -}; - -/** -* Deselects all dates on the current calendar. -* @method deselectAll -* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. -* Assuming that this function executes properly, the return value should be an empty array. -* However, the empty array is returned for the sake of being able to check the selection status -* of the calendar. -*/ -YAHOO.widget.Calendar.prototype.deselectAll = function() { - this.beforeDeselectEvent.fire(); - - var selected = this.cfg.getProperty("selected"); - var count = selected.length; - var sel = selected.concat(); - - if (this.parent) { - this.parent.cfg.setProperty("selected", []); - } else { - this.cfg.setProperty("selected", []); - } - - if (count > 0) { - this.deselectEvent.fire(sel); - } - - return this.getSelectedDates(); -}; - -// END SELECTION METHODS - -// BEGIN TYPE CONVERSION METHODS - -/** -* Converts a date (either a JavaScript Date object, or a date string) to the internal data structure -* used to represent dates: [[yyyy,mm,dd],[yyyy,mm,dd]]. -* @method _toFieldArray -* @private -* @param {String/Date/Date[]} date The date string of dates to deselect in the current calendar. Valid formats are -* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). -* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). -* This method can also take a JavaScript Date object or an array of Date objects. -* @return {Array[](Number[])} Array of date field arrays -*/ -YAHOO.widget.Calendar.prototype._toFieldArray = function(date) { - var returnDate = []; - - if (date instanceof Date) { - returnDate = [[date.getFullYear(), date.getMonth()+1, date.getDate()]]; - } else if (typeof date == 'string') { - returnDate = this._parseDates(date); - } else if (date instanceof Array) { - for (var i=0;i -*
-*
-* -* The tables for the calendars ("cal1_0" and "cal1_1") will be inserted into those containers. -* @namespace YAHOO.widget -* @class CalendarGroup -* @constructor -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.CalendarGroup = function(id, containerId, config) { - if (arguments.length > 0) { - this.init(id, containerId, config); - } -}; - -/** -* Initializes the calendar group. All subclasses must call this method in order for the -* group to be initialized properly. -* @method init -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.CalendarGroup.prototype.init = function(id, containerId, config) { - this.logger = new YAHOO.widget.LogWriter("CalendarGroup " + id); - - this.initEvents(); - this.initStyles(); - - /** - * The collection of Calendar pages contained within the CalendarGroup - * @property pages - * @type YAHOO.widget.Calendar[] - */ - this.pages = []; - - /** - * The unique id associated with the CalendarGroup - * @property id - * @type String - */ - this.id = id; - - /** - * The unique id associated with the CalendarGroup container - * @property containerId - * @type String - */ - this.containerId = containerId; - - /** - * The outer containing element for the CalendarGroup - * @property oDomContainer - * @type HTMLElement - */ - this.oDomContainer = document.getElementById(containerId); - - YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_CONTAINER); - YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_MULTI_UP); - - /** - * The Config object used to hold the configuration variables for the CalendarGroup - * @property cfg - * @type YAHOO.util.Config - */ - this.cfg = new YAHOO.util.Config(this); - - /** - * The local object which contains the CalendarGroup's options - * @property Options - * @type Object - */ - this.Options = {}; - - /** - * The local object which contains the CalendarGroup's locale settings - * @property Locale - * @type Object - */ - this.Locale = {}; - - this.setupConfig(); - - if (config) { - this.cfg.applyConfig(config, true); - } - - this.cfg.fireQueue(); - - // OPERA HACK FOR MISWRAPPED FLOATS - if (this.browser == "opera"){ - var fixWidth = function() { - var startW = this.oDomContainer.offsetWidth; - var w = 0; - for (var p=0;p 0) { - this.oDomContainer.style.width = w + "px"; - } - }; - this.renderEvent.subscribe(fixWidth,this,true); - } - - this.logger.log("Initialized " + pageCount + "-page CalendarGroup", "info"); -}; - - -YAHOO.widget.CalendarGroup.prototype.setupConfig = function() { - /** - * The number of pages to include in the CalendarGroup. This value can only be set once, in the CalendarGroup's constructor arguments. - * @config pages - * @type Number - * @default 2 - */ - this.cfg.addProperty("pages", { value:2, validator:this.cfg.checkNumber, handler:this.configPages } ); - - /** - * The month/year representing the current visible Calendar date (mm/yyyy) - * @config pagedate - * @type String - * @default today's date - */ - this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); - - /** - * The date or range of dates representing the current Calendar selection - * @config selected - * @type String - * @default [] - */ - this.cfg.addProperty("selected", { value:[], handler:this.delegateConfig } ); - - /** - * The title to display above the CalendarGroup's month header - * @config title - * @type String - * @default "" - */ - this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); - - /** - * Whether or not a close button should be displayed for this CalendarGroup - * @config close - * @type Boolean - * @default false - */ - this.cfg.addProperty("close", { value:false, handler:this.configClose } ); - - /** - * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. - * @config iframe - * @type Boolean - * @default true - */ - this.cfg.addProperty("iframe", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The minimum selectable date in the current Calendar (mm/dd/yyyy) - * @config mindate - * @type String - * @default null - */ - this.cfg.addProperty("mindate", { value:null, handler:this.delegateConfig } ); - - /** - * The maximum selectable date in the current Calendar (mm/dd/yyyy) - * @config maxdate - * @type String - * @default null - */ - this.cfg.addProperty("maxdate", { value:null, handler:this.delegateConfig } ); - - // Options properties - - /** - * True if the Calendar should allow multiple selections. False by default. - * @config MULTI_SELECT - * @type Boolean - * @default false - */ - this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The weekday the week begins on. Default is 0 (Sunday). - * @config START_WEEKDAY - * @type number - * @default 0 - */ - this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * True if the Calendar should show weekday labels. True by default. - * @config SHOW_WEEKDAYS - * @type Boolean - * @default true - */ - this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row headers. False by default. - * @config SHOW_WEEK_HEADER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row footers. False by default. - * @config SHOW_WEEK_FOOTER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should suppress weeks that are not a part of the current month. False by default. - * @config HIDE_BLANK_WEEKS - * @type Boolean - * @default false - */ - this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_LEFT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" - */ - this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.delegateConfig } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_RIGHT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" - */ - this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.delegateConfig } ); - - // Locale properties - - /** - * The short month labels for the current locale. - * @config MONTHS_SHORT - * @type String[] - * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - */ - this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.delegateConfig } ); - - /** - * The long month labels for the current locale. - * @config MONTHS_LONG - * @type String[] - * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" - */ - this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.delegateConfig } ); - - /** - * The 1-character weekday labels for the current locale. - * @config WEEKDAYS_1CHAR - * @type String[] - * @default ["S", "M", "T", "W", "T", "F", "S"] - */ - this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.delegateConfig } ); - - /** - * The short weekday labels for the current locale. - * @config WEEKDAYS_SHORT - * @type String[] - * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] - */ - this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.delegateConfig } ); - - /** - * The medium weekday labels for the current locale. - * @config WEEKDAYS_MEDIUM - * @type String[] - * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] - */ - this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.delegateConfig } ); - - /** - * The long weekday labels for the current locale. - * @config WEEKDAYS_LONG - * @type String[] - * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] - */ - this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.delegateConfig } ); - - /** - * The setting that determines which length of month labels should be used. Possible values are "short" and "long". - * @config LOCALE_MONTHS - * @type String - * @default "long" - */ - this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.delegateConfig } ); - - /** - * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". - * @config LOCALE_WEEKDAYS - * @type String - * @default "short" - */ - this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.delegateConfig } ); - - /** - * The value used to delimit individual dates in a date string passed to various Calendar functions. - * @config DATE_DELIMITER - * @type String - * @default "," - */ - this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.delegateConfig } ); - - /** - * The value used to delimit date fields in a date string passed to various Calendar functions. - * @config DATE_FIELD_DELIMITER - * @type String - * @default "/" - */ - this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.delegateConfig } ); - - /** - * The value used to delimit date ranges in a date string passed to various Calendar functions. - * @config DATE_RANGE_DELIMITER - * @type String - * @default "-" - */ - this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.delegateConfig } ); - - /** - * The position of the month in a month/year date string - * @config MY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/year date string - * @config MY_YEAR_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day date string - * @config MD_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/year date string - * @config MD_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day/year date string - * @config MDY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/day/year date string - * @config MDY_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/day/year date string - * @config MDY_YEAR_POSITION - * @type Number - * @default 3 - */ - this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - -}; - -/** -* Initializes CalendarGroup's built-in CustomEvents -* @method initEvents -*/ -YAHOO.widget.CalendarGroup.prototype.initEvents = function() { - var me = this; - - /** - * Proxy subscriber to subscribe to the CalendarGroup's child Calendars' CustomEvents - * @method sub - * @private - * @param {Function} fn The function to subscribe to this CustomEvent - * @param {Object} obj The CustomEvent's scope object - * @param {Boolean} bOverride Whether or not to apply scope correction - */ - var sub = function(fn, obj, bOverride) { - for (var p=0;p0) { - year+=1; - } - cal.setYear(year); - } -}; -/** -* Calls the render function of all child calendars within the group. -* @method render -*/ -YAHOO.widget.CalendarGroup.prototype.render = function() { - this.renderHeader(); - for (var p=0;p=0;--p) { - var cal = this.pages[p]; - cal.previousMonth(); - } -}; - -/** -* Navigates to the next year in the currently selected month in the calendar widget. -* @method nextYear -*/ -YAHOO.widget.CalendarGroup.prototype.nextYear = function() { - for (var p=0;p 11) { + while (newMonth > 11) { + newMonth -= 12; + years += 1; + } + } + + d.setMonth(newMonth); + d.setFullYear(date.getFullYear() + years); + break; + case this.DAY: + d.setDate(date.getDate() + amount); + break; + case this.YEAR: + d.setFullYear(date.getFullYear() + amount); + break; + case this.WEEK: + d.setDate(date.getDate() + (amount * 7)); + break; + } + return d; + }, + + /** + * Subtracts the specified amount of time from the this instance. + * @method subtract + * @param {Date} date The JavaScript Date object to perform subtraction on + * @param {Number} field The this field constant to be used for performing subtraction. + * @param {Number} amount The number of units (measured in the field constant) to subtract from the date. + * @return {Date} The resulting Date object + */ + subtract : function(date, field, amount) { + return this.add(date, field, (amount*-1)); + }, + + /** + * Determines whether a given date is before another date on the calendar. + * @method before + * @param {Date} date The Date object to compare with the compare argument + * @param {Date} compareTo The Date object to use for the comparison + * @return {Boolean} true if the date occurs before the compared date; false if not. + */ + before : function(date, compareTo) { + var ms = compareTo.getTime(); + if (date.getTime() < ms) { + return true; + } else { + return false; + } + }, + + /** + * Determines whether a given date is after another date on the calendar. + * @method after + * @param {Date} date The Date object to compare with the compare argument + * @param {Date} compareTo The Date object to use for the comparison + * @return {Boolean} true if the date occurs after the compared date; false if not. + */ + after : function(date, compareTo) { + var ms = compareTo.getTime(); + if (date.getTime() > ms) { + return true; + } else { + return false; + } + }, + + /** + * Determines whether a given date is between two other dates on the calendar. + * @method between + * @param {Date} date The date to check for + * @param {Date} dateBegin The start of the range + * @param {Date} dateEnd The end of the range + * @return {Boolean} true if the date occurs between the compared dates; false if not. + */ + between : function(date, dateBegin, dateEnd) { + if (this.after(date, dateBegin) && this.before(date, dateEnd)) { + return true; + } else { + return false; + } + }, + + /** + * Retrieves a JavaScript Date object representing January 1 of any given year. + * @method getJan1 + * @param {Number} calendarYear The calendar year for which to retrieve January 1 + * @return {Date} January 1 of the calendar year specified. + */ + getJan1 : function(calendarYear) { + return new Date(calendarYear,0,1); + }, + + /** + * Calculates the number of days the specified date is from January 1 of the specified calendar year. + * Passing January 1 to this function would return an offset value of zero. + * @method getDayOffset + * @param {Date} date The JavaScript date for which to find the offset + * @param {Number} calendarYear The calendar year to use for determining the offset + * @return {Number} The number of days since January 1 of the given year + */ + getDayOffset : function(date, calendarYear) { + var beginYear = this.getJan1(calendarYear); // Find the start of the year. This will be in week 1. + + // Find the number of days the passed in date is away from the calendar year start + var dayOffset = Math.ceil((date.getTime()-beginYear.getTime()) / this.ONE_DAY_MS); + return dayOffset; + }, + + /** + * Calculates the week number for the given date. This function assumes that week 1 is the + * week in which January 1 appears, regardless of whether the week consists of a full 7 days. + * The calendar year can be specified to help find what a the week number would be for a given + * date if the date overlaps years. For instance, a week may be considered week 1 of 2005, or + * week 53 of 2004. Specifying the optional calendarYear allows one to make this distinction + * easily. + * @method getWeekNumber + * @param {Date} date The JavaScript date for which to find the week number + * @param {Number} calendarYear OPTIONAL - The calendar year to use for determining the week number. Default is + * the calendar year of parameter "date". + * @param {Number} weekStartsOn OPTIONAL - The integer (0-6) representing which day a week begins on. Default is 0 (for Sunday). + * @return {Number} The week number of the given date. + */ + getWeekNumber : function(date, calendarYear) { + date = this.clearTime(date); + var nearestThurs = new Date(date.getTime() + (4 * this.ONE_DAY_MS) - ((date.getDay()) * this.ONE_DAY_MS)); + + var jan1 = new Date(nearestThurs.getFullYear(),0,1); + var dayOfYear = ((nearestThurs.getTime() - jan1.getTime()) / this.ONE_DAY_MS) - 1; + + var weekNum = Math.ceil((dayOfYear)/ 7); + return weekNum; + }, + + /** + * Determines if a given week overlaps two different years. + * @method isYearOverlapWeek + * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. + * @return {Boolean} true if the date overlaps two different years. + */ + isYearOverlapWeek : function(weekBeginDate) { + var overlaps = false; + var nextWeek = this.add(weekBeginDate, this.DAY, 6); + if (nextWeek.getFullYear() != weekBeginDate.getFullYear()) { + overlaps = true; + } + return overlaps; + }, + + /** + * Determines if a given week overlaps two different months. + * @method isMonthOverlapWeek + * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. + * @return {Boolean} true if the date overlaps two different months. + */ + isMonthOverlapWeek : function(weekBeginDate) { + var overlaps = false; + var nextWeek = this.add(weekBeginDate, this.DAY, 6); + if (nextWeek.getMonth() != weekBeginDate.getMonth()) { + overlaps = true; + } + return overlaps; + }, + + /** + * Gets the first day of a month containing a given date. + * @method findMonthStart + * @param {Date} date The JavaScript Date used to calculate the month start + * @return {Date} The JavaScript Date representing the first day of the month + */ + findMonthStart : function(date) { + var start = new Date(date.getFullYear(), date.getMonth(), 1); + return start; + }, + + /** + * Gets the last day of a month containing a given date. + * @method findMonthEnd + * @param {Date} date The JavaScript Date used to calculate the month end + * @return {Date} The JavaScript Date representing the last day of the month + */ + findMonthEnd : function(date) { + var start = this.findMonthStart(date); + var nextMonth = this.add(start, this.MONTH, 1); + var end = this.subtract(nextMonth, this.DAY, 1); + return end; + }, + + /** + * Clears the time fields from a given date, effectively setting the time to 12 noon. + * @method clearTime + * @param {Date} date The JavaScript Date for which the time fields will be cleared + * @return {Date} The JavaScript Date cleared of all time fields + */ + clearTime : function(date) { + date.setHours(12,0,0,0); + return date; + } +}; + +/** +* The Calendar component is a UI control that enables users to choose one or more dates from a graphical calendar presented in a one-month ("one-up") or two-month ("two-up") interface. Calendars are generated entirely via script and can be navigated without any page refreshes. +* @module calendar +* @title Calendar +* @namespace YAHOO.widget +* @requires yahoo,dom,event +*/ + +/** +* Calendar is the base class for the Calendar widget. In its most basic +* implementation, it has the ability to render a calendar widget on the page +* that can be manipulated to select a single date, move back and forth between +* months and years. +*

To construct the placeholder for the calendar widget, the code is as +* follows: +*

+* <div id="cal1Container"></div> +* +* Note that the table can be replaced with any kind of element. +*

+* @namespace YAHOO.widget +* @class Calendar +* @constructor +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.Calendar = function(id, containerId, config) { + this.init(id, containerId, config); +}; + +/** +* The path to be used for images loaded for the Calendar +* @property YAHOO.widget.Calendar.IMG_ROOT +* @static +* @type String +*/ +YAHOO.widget.Calendar.IMG_ROOT = (window.location.href.toLowerCase().indexOf("https") === 0 ? "https://a248.e.akamai.net/sec.yimg.com/i/" : "http://us.i1.yimg.com/us.yimg.com/i/"); + +/** +* Type constant used for renderers to represent an individual date (M/D/Y) +* @property YAHOO.widget.Calendar.DATE +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.DATE = "D"; + +/** +* Type constant used for renderers to represent an individual date across any year (M/D) +* @property YAHOO.widget.Calendar.MONTH_DAY +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.MONTH_DAY = "MD"; + +/** +* Type constant used for renderers to represent a weekday +* @property YAHOO.widget.Calendar.WEEKDAY +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.WEEKDAY = "WD"; + +/** +* Type constant used for renderers to represent a range of individual dates (M/D/Y-M/D/Y) +* @property YAHOO.widget.Calendar.RANGE +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.RANGE = "R"; + +/** +* Type constant used for renderers to represent a month across any year +* @property YAHOO.widget.Calendar.MONTH +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.MONTH = "M"; + +/** +* Constant that represents the total number of date cells that are displayed in a given month +* @property YAHOO.widget.Calendar.DISPLAY_DAYS +* @static +* @final +* @type Number +*/ +YAHOO.widget.Calendar.DISPLAY_DAYS = 42; + +/** +* Constant used for halting the execution of the remainder of the render stack +* @property YAHOO.widget.Calendar.STOP_RENDER +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.STOP_RENDER = "S"; + +YAHOO.widget.Calendar.prototype = { + + /** + * The configuration object used to set up the calendars various locale and style options. + * @property Config + * @private + * @deprecated Configuration properties should be set by calling Calendar.cfg.setProperty. + * @type Object + */ + Config : null, + + /** + * The parent CalendarGroup, only to be set explicitly by the parent group + * @property parent + * @type CalendarGroup + */ + parent : null, + + /** + * The index of this item in the parent group + * @property index + * @type Number + */ + index : -1, + + /** + * The collection of calendar table cells + * @property cells + * @type HTMLTableCellElement[] + */ + cells : null, + + /** + * The collection of calendar cell dates that is parallel to the cells collection. The array contains dates field arrays in the format of [YYYY, M, D]. + * @property cellDates + * @type Array[](Number[]) + */ + cellDates : null, + + /** + * The id that uniquely identifies this calendar. This id should match the id of the placeholder element on the page. + * @property id + * @type String + */ + id : null, + + /** + * The DOM element reference that points to this calendar's container element. The calendar will be inserted into this element when the shell is rendered. + * @property oDomContainer + * @type HTMLElement + */ + oDomContainer : null, + + /** + * A Date object representing today's date. + * @property today + * @type Date + */ + today : null, + + /** + * The list of render functions, along with required parameters, used to render cells. + * @property renderStack + * @type Array[] + */ + renderStack : null, + + /** + * A copy of the initial render functions created before rendering. + * @property _renderStack + * @private + * @type Array + */ + _renderStack : null, + + /** + * A Date object representing the month/year that the calendar is initially set to + * @property _pageDate + * @private + * @type Date + */ + _pageDate : null, + + /** + * The private list of initially selected dates. + * @property _selectedDates + * @private + * @type Array + */ + _selectedDates : null, + + /** + * A map of DOM event handlers to attach to cells associated with specific CSS class names + * @property domEventMap + * @type Object + */ + domEventMap : null +}; + + + +/** +* Initializes the Calendar widget. +* @method init +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.Calendar.prototype.init = function(id, containerId, config) { + this.logger = new YAHOO.widget.LogWriter("Calendar_Core " + id); + + this.initEvents(); + this.today = new Date(); + YAHOO.widget.DateMath.clearTime(this.today); + + this.id = id; + this.oDomContainer = document.getElementById(containerId); + if (! this.oDomContainer) { + this.logger.log("No valid container present.", "error"); + } + + /** + * The Config object used to hold the configuration variables for the Calendar + * @property cfg + * @type YAHOO.util.Config + */ + this.cfg = new YAHOO.util.Config(this); + + /** + * The local object which contains the Calendar's options + * @property Options + * @type Object + */ + this.Options = {}; + + /** + * The local object which contains the Calendar's locale settings + * @property Locale + * @type Object + */ + this.Locale = {}; + + this.initStyles(); + + YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_CONTAINER); + YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_SINGLE); + + this.cellDates = []; + this.cells = []; + this.renderStack = []; + this._renderStack = []; + + this.setupConfig(); + + if (config) { + this.cfg.applyConfig(config, true); + } + + this.cfg.fireQueue(); +}; + +/** +* Renders the built-in IFRAME shim for the IE6 and below +* @method configIframe +*/ +YAHOO.widget.Calendar.prototype.configIframe = function(type, args, obj) { + var useIframe = args[0]; + + if (YAHOO.util.Dom.inDocument(this.oDomContainer)) { + if (useIframe) { + var pos = YAHOO.util.Dom.getStyle(this.oDomContainer, "position"); + + if (this.browser == "ie" && (pos == "absolute" || pos == "relative")) { + if (! YAHOO.util.Dom.inDocument(this.iframe)) { + this.iframe = document.createElement("iframe"); + this.iframe.src = "javascript:false;"; + YAHOO.util.Dom.setStyle(this.iframe, "opacity", "0"); + this.oDomContainer.insertBefore(this.iframe, this.oDomContainer.firstChild); + } + } + } else { + if (this.iframe) { + if (this.iframe.parentNode) { + this.iframe.parentNode.removeChild(this.iframe); + } + this.iframe = null; + } + } + } +}; + +/** +* Default handler for the "title" property +* @method configTitle +*/ +YAHOO.widget.Calendar.prototype.configTitle = function(type, args, obj) { + var title = args[0]; + var close = this.cfg.getProperty("close"); + + var titleDiv; + + if (title && title !== "") { + titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || document.createElement("div"); + titleDiv.className = YAHOO.widget.CalendarGroup.CSS_2UPTITLE; + titleDiv.innerHTML = title; + this.oDomContainer.insertBefore(titleDiv, this.oDomContainer.firstChild); + YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); + } else { + titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || null; + + if (titleDiv) { + YAHOO.util.Event.purgeElement(titleDiv); + this.oDomContainer.removeChild(titleDiv); + } + if (! close) { + YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); + } + } +}; + +/** +* Default handler for the "close" property +* @method configClose +*/ +YAHOO.widget.Calendar.prototype.configClose = function(type, args, obj) { + var close = args[0]; + var title = this.cfg.getProperty("title"); + + var linkClose; + + if (close === true) { + linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || document.createElement("a"); + linkClose.href = "javascript:void(null);"; + linkClose.className = "link-close"; + YAHOO.util.Event.addListener(linkClose, "click", this.hide, this, true); + var imgClose = document.createElement("img"); + imgClose.src = YAHOO.widget.Calendar.IMG_ROOT + "us/my/bn/x_d.gif"; + imgClose.className = YAHOO.widget.CalendarGroup.CSS_2UPCLOSE; + linkClose.appendChild(imgClose); + this.oDomContainer.appendChild(linkClose); + YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); + } else { + linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || null; + + if (linkClose) { + YAHOO.util.Event.purgeElement(linkClose); + this.oDomContainer.removeChild(linkClose); + } + if (! title || title === "") { + YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); + } + } +}; + +/** +* Initializes Calendar's built-in CustomEvents +* @method initEvents +*/ +YAHOO.widget.Calendar.prototype.initEvents = function() { + + /** + * Fired before a selection is made + * @event beforeSelectEvent + */ + this.beforeSelectEvent = new YAHOO.util.CustomEvent("beforeSelect"); + + /** + * Fired when a selection is made + * @event selectEvent + * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. + */ + this.selectEvent = new YAHOO.util.CustomEvent("select"); + + /** + * Fired before a selection is made + * @event beforeDeselectEvent + */ + this.beforeDeselectEvent = new YAHOO.util.CustomEvent("beforeDeselect"); + + /** + * Fired when a selection is made + * @event deselectEvent + * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. + */ + this.deselectEvent = new YAHOO.util.CustomEvent("deselect"); + + /** + * Fired when the Calendar page is changed + * @event changePageEvent + */ + this.changePageEvent = new YAHOO.util.CustomEvent("changePage"); + + /** + * Fired before the Calendar is rendered + * @event beforeRenderEvent + */ + this.beforeRenderEvent = new YAHOO.util.CustomEvent("beforeRender"); + + /** + * Fired when the Calendar is rendered + * @event renderEvent + */ + this.renderEvent = new YAHOO.util.CustomEvent("render"); + + /** + * Fired when the Calendar is reset + * @event resetEvent + */ + this.resetEvent = new YAHOO.util.CustomEvent("reset"); + + /** + * Fired when the Calendar is cleared + * @event clearEvent + */ + this.clearEvent = new YAHOO.util.CustomEvent("clear"); + + this.beforeSelectEvent.subscribe(this.onBeforeSelect, this, true); + this.selectEvent.subscribe(this.onSelect, this, true); + this.beforeDeselectEvent.subscribe(this.onBeforeDeselect, this, true); + this.deselectEvent.subscribe(this.onDeselect, this, true); + this.changePageEvent.subscribe(this.onChangePage, this, true); + this.renderEvent.subscribe(this.onRender, this, true); + this.resetEvent.subscribe(this.onReset, this, true); + this.clearEvent.subscribe(this.onClear, this, true); +}; + + +/** +* The default event function that is attached to a date link within a calendar cell +* when the calendar is rendered. +* @method doSelectCell +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doSelectCell = function(e, cal) { + var target = YAHOO.util.Event.getTarget(e); + + var cell,index,d,date; + + while (target.tagName.toLowerCase() != "td" && ! YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + cell = target; + + if (YAHOO.util.Dom.hasClass(cell, cal.Style.CSS_CELL_SELECTABLE)) { + index = cell.id.split("cell")[1]; + d = cal.cellDates[index]; + date = new Date(d[0],d[1]-1,d[2]); + + var link; + + cal.logger.log("Selecting cell " + index + " via click", "info"); + + if (cal.Options.MULTI_SELECT) { + link = cell.getElementsByTagName("a")[0]; + if (link) { + link.blur(); + } + + var cellDate = cal.cellDates[index]; + var cellDateIndex = cal._indexOfSelectedFieldArray(cellDate); + + if (cellDateIndex > -1) { + cal.deselectCell(index); + } else { + cal.selectCell(index); + } + + } else { + link = cell.getElementsByTagName("a")[0]; + if (link) { + link.blur(); + } + cal.selectCell(index); + } + } +}; + +/** +* The event that is executed when the user hovers over a cell +* @method doCellMouseOver +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doCellMouseOver = function(e, cal) { + var target; + if (e) { + target = YAHOO.util.Event.getTarget(e); + } else { + target = this; + } + + while (target.tagName.toLowerCase() != "td") { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + YAHOO.util.Dom.addClass(target, cal.Style.CSS_CELL_HOVER); + } +}; + +/** +* The event that is executed when the user moves the mouse out of a cell +* @method doCellMouseOut +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doCellMouseOut = function(e, cal) { + var target; + if (e) { + target = YAHOO.util.Event.getTarget(e); + } else { + target = this; + } + + while (target.tagName.toLowerCase() != "td") { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + YAHOO.util.Dom.removeClass(target, cal.Style.CSS_CELL_HOVER); + } +}; + +YAHOO.widget.Calendar.prototype.setupConfig = function() { + + /** + * The month/year representing the current visible Calendar date (mm/yyyy) + * @config pagedate + * @type String + * @default today's date + */ + this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); + + /** + * The date or range of dates representing the current Calendar selection + * @config selected + * @type String + * @default [] + */ + this.cfg.addProperty("selected", { value:[], handler:this.configSelected } ); + + /** + * The title to display above the Calendar's month header + * @config title + * @type String + * @default "" + */ + this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); + + /** + * Whether or not a close button should be displayed for this Calendar + * @config close + * @type Boolean + * @default false + */ + this.cfg.addProperty("close", { value:false, handler:this.configClose } ); + + /** + * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. + * @config iframe + * @type Boolean + * @default true + */ + this.cfg.addProperty("iframe", { value:true, handler:this.configIframe, validator:this.cfg.checkBoolean } ); + + /** + * The minimum selectable date in the current Calendar (mm/dd/yyyy) + * @config mindate + * @type String + * @default null + */ + this.cfg.addProperty("mindate", { value:null, handler:this.configMinDate } ); + + /** + * The maximum selectable date in the current Calendar (mm/dd/yyyy) + * @config maxdate + * @type String + * @default null + */ + this.cfg.addProperty("maxdate", { value:null, handler:this.configMaxDate } ); + + + // Options properties + + /** + * True if the Calendar should allow multiple selections. False by default. + * @config MULTI_SELECT + * @type Boolean + * @default false + */ + this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * The weekday the week begins on. Default is 0 (Sunday). + * @config START_WEEKDAY + * @type number + * @default 0 + */ + this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.configOptions, validator:this.cfg.checkNumber } ); + + /** + * True if the Calendar should show weekday labels. True by default. + * @config SHOW_WEEKDAYS + * @type Boolean + * @default true + */ + this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row headers. False by default. + * @config SHOW_WEEK_HEADER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row footers. False by default. + * @config SHOW_WEEK_FOOTER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should suppress weeks that are not a part of the current month. False by default. + * @config HIDE_BLANK_WEEKS + * @type Boolean + * @default false + */ + this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_LEFT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" + */ + this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.configOptions } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_RIGHT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" + */ + this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.configOptions } ); + + // Locale properties + + /** + * The short month labels for the current locale. + * @config MONTHS_SHORT + * @type String[] + * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + */ + this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.configLocale } ); + + /** + * The long month labels for the current locale. + * @config MONTHS_LONG + * @type String[] + * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" + */ + this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.configLocale } ); + + /** + * The 1-character weekday labels for the current locale. + * @config WEEKDAYS_1CHAR + * @type String[] + * @default ["S", "M", "T", "W", "T", "F", "S"] + */ + this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.configLocale } ); + + /** + * The short weekday labels for the current locale. + * @config WEEKDAYS_SHORT + * @type String[] + * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] + */ + this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.configLocale } ); + + /** + * The medium weekday labels for the current locale. + * @config WEEKDAYS_MEDIUM + * @type String[] + * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] + */ + this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.configLocale } ); + + /** + * The long weekday labels for the current locale. + * @config WEEKDAYS_LONG + * @type String[] + * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + */ + this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.configLocale } ); + + /** + * Refreshes the locale values used to build the Calendar. + * @method refreshLocale + * @private + */ + var refreshLocale = function() { + this.cfg.refireEvent("LOCALE_MONTHS"); + this.cfg.refireEvent("LOCALE_WEEKDAYS"); + }; + + this.cfg.subscribeToConfigEvent("START_WEEKDAY", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("MONTHS_SHORT", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("MONTHS_LONG", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG", refreshLocale, this, true); + + /** + * The setting that determines which length of month labels should be used. Possible values are "short" and "long". + * @config LOCALE_MONTHS + * @type String + * @default "long" + */ + this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.configLocaleValues } ); + + /** + * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". + * @config LOCALE_WEEKDAYS + * @type String + * @default "short" + */ + this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.configLocaleValues } ); + + /** + * The value used to delimit individual dates in a date string passed to various Calendar functions. + * @config DATE_DELIMITER + * @type String + * @default "," + */ + this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.configLocale } ); + + /** + * The value used to delimit date fields in a date string passed to various Calendar functions. + * @config DATE_FIELD_DELIMITER + * @type String + * @default "/" + */ + this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.configLocale } ); + + /** + * The value used to delimit date ranges in a date string passed to various Calendar functions. + * @config DATE_RANGE_DELIMITER + * @type String + * @default "-" + */ + this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.configLocale } ); + + /** + * The position of the month in a month/year date string + * @config MY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/year date string + * @config MY_YEAR_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day date string + * @config MD_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/year date string + * @config MD_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day/year date string + * @config MDY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/day/year date string + * @config MDY_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/day/year date string + * @config MDY_YEAR_POSITION + * @type Number + * @default 3 + */ + this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.configLocale, validator:this.cfg.checkNumber } ); +}; + +/** +* The default handler for the "pagedate" property +* @method configPageDate +*/ +YAHOO.widget.Calendar.prototype.configPageDate = function(type, args, obj) { + var val = args[0]; + var month, year, aMonthYear; + + if (val) { + if (val instanceof Date) { + val = YAHOO.widget.DateMath.findMonthStart(val); + this.cfg.setProperty("pagedate", val, true); + if (! this._pageDate) { + this._pageDate = this.cfg.getProperty("pagedate"); + } + return; + } else { + aMonthYear = val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER")); + month = parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1], 10)-1; + year = parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1], 10); + } + } else { + month = this.today.getMonth(); + year = this.today.getFullYear(); + } + + this.cfg.setProperty("pagedate", new Date(year, month, 1), true); + + this.logger.log("Set month/year to " + month + "/" + year, "info"); + + if (! this._pageDate) { + this._pageDate = this.cfg.getProperty("pagedate"); + } +}; + +/** +* The default handler for the "mindate" property +* @method configMinDate +*/ +YAHOO.widget.Calendar.prototype.configMinDate = function(type, args, obj) { + var val = args[0]; + if (typeof val == 'string') { + val = this._parseDate(val); + this.cfg.setProperty("mindate", new Date(val[0],(val[1]-1),val[2])); + } +}; + +/** +* The default handler for the "maxdate" property +* @method configMaxDate +*/ +YAHOO.widget.Calendar.prototype.configMaxDate = function(type, args, obj) { + var val = args[0]; + if (typeof val == 'string') { + val = this._parseDate(val); + this.cfg.setProperty("maxdate", new Date(val[0],(val[1]-1),val[2])); + } +}; + +/** +* The default handler for the "selected" property +* @method configSelected +*/ +YAHOO.widget.Calendar.prototype.configSelected = function(type, args, obj) { + var selected = args[0]; + + if (selected) { + if (typeof selected == 'string') { + this.cfg.setProperty("selected", this._parseDates(selected), true); + } + } + if (! this._selectedDates) { + this._selectedDates = this.cfg.getProperty("selected"); + } +}; + +/** +* The default handler for all configuration options properties +* @method configOptions +*/ +YAHOO.widget.Calendar.prototype.configOptions = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + this.Options[type] = val; +}; + +/** +* The default handler for all configuration locale properties +* @method configLocale +*/ +YAHOO.widget.Calendar.prototype.configLocale = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + this.Locale[type] = val; + + this.cfg.refireEvent("LOCALE_MONTHS"); + this.cfg.refireEvent("LOCALE_WEEKDAYS"); + +}; + +/** +* The default handler for all configuration locale field length properties +* @method configLocaleValues +*/ +YAHOO.widget.Calendar.prototype.configLocaleValues = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + + switch (type) { + case "LOCALE_MONTHS": + switch (val) { + case "short": + this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_SHORT").concat(); + break; + case "long": + this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_LONG").concat(); + break; + } + break; + case "LOCALE_WEEKDAYS": + switch (val) { + case "1char": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_1CHAR").concat(); + break; + case "short": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_SHORT").concat(); + break; + case "medium": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_MEDIUM").concat(); + break; + case "long": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_LONG").concat(); + break; + } + + var START_WEEKDAY = this.cfg.getProperty("START_WEEKDAY"); + + if (START_WEEKDAY > 0) { + for (var w=0;w'; + html[html.length] = '
'; + + var renderLeft, renderRight = false; + + if (this.parent) { + if (this.index === 0) { + renderLeft = true; + } + if (this.index == (this.parent.cfg.getProperty("pages") -1)) { + renderRight = true; + } + } else { + renderLeft = true; + renderRight = true; + } + + var cal = this.parent || this; + + if (renderLeft) { + html[html.length] = ' '; + } + + html[html.length] = this.buildMonthLabel(); + + if (renderRight) { + html[html.length] = ' '; + } + + + html[html.length] = '
'; + html[html.length] = ''; + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEKDAYS")) { + html = this.buildWeekdays(html); + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the Calendar's weekday headers. +* @method buildWeekdays +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.buildWeekdays = function(html) { + + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { + html[html.length] = ' '; + } + + for(var i=0;i'; + } + + if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { + html[html.length] = ' '; + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the calendar body. +* @method renderBody +* @param {Date} workingDate The current working Date being used for the render process +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderBody = function(workingDate, html) { + this.logger.log("Rendering body", "info"); + + var startDay = this.cfg.getProperty("START_WEEKDAY"); + + this.preMonthDays = workingDate.getDay(); + if (startDay > 0) { + this.preMonthDays -= startDay; + } + if (this.preMonthDays < 0) { + this.preMonthDays += 7; + } + + this.monthDays = YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate(); + this.postMonthDays = YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays; + + this.logger.log(this.preMonthDays + " preciding out-of-month days", "info"); + this.logger.log(this.monthDays + " month days", "info"); + this.logger.log(this.postMonthDays + " post-month days", "info"); + + workingDate = YAHOO.widget.DateMath.subtract(workingDate, YAHOO.widget.DateMath.DAY, this.preMonthDays); + this.logger.log("Calendar page starts on " + workingDate, "info"); + + var useDate,weekNum,weekClass; + useDate = this.cfg.getProperty("pagedate"); + + html[html.length] = ''; + + var i = 0; + + var tempDiv = document.createElement("div"); + var cell = document.createElement("td"); + tempDiv.appendChild(cell); + + var jan1 = new Date(useDate.getFullYear(),0,1); + + var cal = this.parent || this; + + for (var r=0;r<6;r++) { + + weekNum = YAHOO.widget.DateMath.getWeekNumber(workingDate, useDate.getFullYear(), startDay); + + weekClass = "w" + weekNum; + + if (r !== 0 && this.isDateOOM(workingDate) && this.cfg.getProperty("HIDE_BLANK_WEEKS") === true) { + break; + } else { + + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { html = this.renderRowHeader(weekNum, html); } + + for (var d=0;d<7;d++){ // Render actual days + + var cellRenderers = []; + + this.clearElement(cell); + + YAHOO.util.Dom.addClass(cell, "calcell"); + + cell.id = this.id + "_cell" + i; + this.logger.log("Rendering cell " + cell.id + " (" + workingDate.getFullYear() + "-" + (workingDate.getMonth()+1) + "-" + workingDate.getDate() + ")", "cellrender"); + + cell.innerHTML = i; + + var renderer = null; + + if (workingDate.getFullYear() == this.today.getFullYear() && + workingDate.getMonth() == this.today.getMonth() && + workingDate.getDate() == this.today.getDate()) { + cellRenderers[cellRenderers.length]=cal.renderCellStyleToday; + } + + this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]; // Add this date to cellDates + + if (this.isDateOOM(workingDate)) { + cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth; + } else { + + YAHOO.util.Dom.addClass(cell, "wd" + workingDate.getDay()); + YAHOO.util.Dom.addClass(cell, "d" + workingDate.getDate()); + + for (var s=0;s= d1.getTime() && workingDate.getTime() <= d2.getTime()) { + renderer = rArray[2]; + + if (workingDate.getTime()==d2.getTime()) { + this.renderStack.splice(s,1); + } + } + break; + case YAHOO.widget.Calendar.WEEKDAY: + + var weekday = rArray[1][0]; + if (workingDate.getDay()+1 == weekday) { + renderer = rArray[2]; + } + break; + case YAHOO.widget.Calendar.MONTH: + + month = rArray[1][0]; + if (workingDate.getMonth()+1 == month) { + renderer = rArray[2]; + } + break; + } + + if (renderer) { + cellRenderers[cellRenderers.length]=renderer; + } + } + + } + + if (this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]) > -1) { + cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected; + } + + var mindate = this.cfg.getProperty("mindate"); + var maxdate = this.cfg.getProperty("maxdate"); + + if (mindate) { + mindate = YAHOO.widget.DateMath.clearTime(mindate); + } + if (maxdate) { + maxdate = YAHOO.widget.DateMath.clearTime(maxdate); + } + + if ( + (mindate && (workingDate.getTime() < mindate.getTime())) || + (maxdate && (workingDate.getTime() > maxdate.getTime())) + ) { + cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate; + } else { + cellRenderers[cellRenderers.length]=cal.styleCellDefault; + cellRenderers[cellRenderers.length]=cal.renderCellDefault; + } + + + + for (var x=0;x= 0 && i <= 6) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TOP); + } + if ((i % 7) === 0) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_LEFT); + } + if (((i+1) % 7) === 0) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RIGHT); + } + + var postDays = this.postMonthDays; + if (postDays >= 7 && this.cfg.getProperty("HIDE_BLANK_WEEKS")) { + var blankWeeks = Math.floor(postDays/7); + for (var p=0;p= ((this.preMonthDays+postDays+this.monthDays)-7)) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_BOTTOM); + } + + html[html.length] = tempDiv.innerHTML; + + i++; + } + + if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { html = this.renderRowFooter(weekNum, html); } + + html[html.length] = ''; + } + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the calendar footer. In the default implementation, there is +* no footer. +* @method renderFooter +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderFooter = function(html) { return html; }; + +/** +* Renders the calendar after it has been configured. The render() method has a specific call chain that will execute +* when the method is called: renderHeader, renderBody, renderFooter. +* Refer to the documentation for those methods for information on +* individual render tasks. +* @method render +*/ +YAHOO.widget.Calendar.prototype.render = function() { + this.beforeRenderEvent.fire(); + + // Find starting day of the current month + var workingDate = YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate")); + + this.resetRenderers(); + this.cellDates.length = 0; + + YAHOO.util.Event.purgeElement(this.oDomContainer, true); + + var html = []; + + html[html.length] = ''; + html = this.renderHeader(html); + html = this.renderBody(workingDate, html); + html = this.renderFooter(html); + html[html.length] = '
'; + + this.oDomContainer.innerHTML = html.join("\n"); + + this.applyListeners(); + this.cells = this.oDomContainer.getElementsByTagName("td"); + + this.cfg.refireEvent("title"); + this.cfg.refireEvent("close"); + this.cfg.refireEvent("iframe"); + + this.renderEvent.fire(); +}; + +/** +* Applies the Calendar's DOM listeners to applicable elements. +* @method applyListeners +*/ +YAHOO.widget.Calendar.prototype.applyListeners = function() { + + var root = this.oDomContainer; + var cal = this.parent || this; + + var linkLeft, linkRight; + + linkLeft = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT, "a", root); + linkRight = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT, "a", root); + + if (linkLeft) { + this.linkLeft = linkLeft[0]; + YAHOO.util.Event.addListener(this.linkLeft, "mousedown", cal.previousMonth, cal, true); + } + + if (linkRight) { + this.linkRight = linkRight[0]; + YAHOO.util.Event.addListener(this.linkRight, "mousedown", cal.nextMonth, cal, true); + } + + if (this.domEventMap) { + var el,elements; + for (var cls in this.domEventMap) { + if (this.domEventMap.hasOwnProperty(cls)) { + var items = this.domEventMap[cls]; + + if (! (items instanceof Array)) { + items = [items]; + } + + for (var i=0;i'; + return html; +}; + +/** +* Renders the row footer for a week. +* @method renderRowFooter +* @param {Number} weekNum The week number of the current row +* @param {Array} cell The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderRowFooter = function(weekNum, html) { + html[html.length] = '' + weekNum + ''; + return html; +}; + +/** +* Renders a single standard calendar cell in the calendar widget table. +* All logic for determining how a standard default cell will be rendered is +* encapsulated in this method, and must be accounted for when extending the +* widget class. +* @method renderCellDefault +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellDefault = function(workingDate, cell) { + cell.innerHTML = '' + this.buildDayLabel(workingDate) + ""; +}; + +/** +* Styles a selectable cell. +* @method styleCellDefault +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.styleCellDefault = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTABLE); +}; + + +/** +* Renders a single standard calendar cell using the CSS hightlight1 style +* @method renderCellStyleHighlight1 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT1); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight2 style +* @method renderCellStyleHighlight2 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT2); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight3 style +* @method renderCellStyleHighlight3 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT3); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight4 style +* @method renderCellStyleHighlight4 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT4); +}; + +/** +* Applies the default style used for rendering today's date to the current calendar cell +* @method renderCellStyleToday +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleToday = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TODAY); +}; + +/** +* Applies the default style used for rendering selected dates to the current calendar cell +* @method renderCellStyleSelected +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleSelected = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTED); +}; + +/** +* Applies the default style used for rendering dates that are not a part of the current +* month (preceding or trailing the cells for the current month) +* @method renderCellNotThisMonth +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderCellNotThisMonth = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_OOM); + cell.innerHTML=workingDate.getDate(); + return YAHOO.widget.Calendar.STOP_RENDER; +}; + +/** +* Renders the current calendar cell as a non-selectable "black-out" date using the default +* restricted style. +* @method renderBodyCellRestricted +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderBodyCellRestricted = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL); + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RESTRICTED); + cell.innerHTML=workingDate.getDate(); + return YAHOO.widget.Calendar.STOP_RENDER; +}; + +// END BUILT-IN TABLE CELL RENDERERS + +// BEGIN MONTH NAVIGATION METHODS + +/** +* Adds the designated number of months to the current calendar month, and sets the current +* calendar page date to the new month. +* @method addMonths +* @param {Number} count The number of months to add to the current calendar +*/ +YAHOO.widget.Calendar.prototype.addMonths = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Subtracts the designated number of months from the current calendar month, and sets the current +* calendar page date to the new month. +* @method subtractMonths +* @param {Number} count The number of months to subtract from the current calendar +*/ +YAHOO.widget.Calendar.prototype.subtractMonths = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Adds the designated number of years to the current calendar, and sets the current +* calendar page date to the new month. +* @method addYears +* @param {Number} count The number of years to add to the current calendar +*/ +YAHOO.widget.Calendar.prototype.addYears = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Subtcats the designated number of years from the current calendar, and sets the current +* calendar page date to the new month. +* @method subtractYears +* @param {Number} count The number of years to subtract from the current calendar +*/ +YAHOO.widget.Calendar.prototype.subtractYears = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Navigates to the next month page in the calendar widget. +* @method nextMonth +*/ +YAHOO.widget.Calendar.prototype.nextMonth = function() { + this.addMonths(1); +}; + +/** +* Navigates to the previous month page in the calendar widget. +* @method previousMonth +*/ +YAHOO.widget.Calendar.prototype.previousMonth = function() { + this.subtractMonths(1); +}; + +/** +* Navigates to the next year in the currently selected month in the calendar widget. +* @method nextYear +*/ +YAHOO.widget.Calendar.prototype.nextYear = function() { + this.addYears(1); +}; + +/** +* Navigates to the previous year in the currently selected month in the calendar widget. +* @method previousYear +*/ +YAHOO.widget.Calendar.prototype.previousYear = function() { + this.subtractYears(1); +}; + +// END MONTH NAVIGATION METHODS + +// BEGIN SELECTION METHODS + +/** +* Resets the calendar widget to the originally selected month and year, and +* sets the calendar to the initial selection(s). +* @method reset +*/ +YAHOO.widget.Calendar.prototype.reset = function() { + this.cfg.resetProperty("selected"); + this.cfg.resetProperty("pagedate"); + this.resetEvent.fire(); +}; + +/** +* Clears the selected dates in the current calendar widget and sets the calendar +* to the current month and year. +* @method clear +*/ +YAHOO.widget.Calendar.prototype.clear = function() { + this.cfg.setProperty("selected", []); + this.cfg.setProperty("pagedate", new Date(this.today.getTime())); + this.clearEvent.fire(); +}; + +/** +* Selects a date or a collection of dates on the current calendar. This method, by default, +* does not call the render method explicitly. Once selection has completed, render must be +* called for the changes to be reflected visually. +* @method select +* @param {String/Date/Date[]} date The date string of dates to select in the current calendar. Valid formats are +* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). +* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). +* This method can also take a JavaScript Date object or an array of Date objects. +* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. +*/ +YAHOO.widget.Calendar.prototype.select = function(date) { + this.logger.log("Select: " + date, "info"); + + this.beforeSelectEvent.fire(); + + var selected = this.cfg.getProperty("selected"); + var aToBeSelected = this._toFieldArray(date); + this.logger.log("Selection field array: " + aToBeSelected, "info"); + + for (var a=0;a -1) { + if (this.cfg.getProperty("pagedate").getMonth() == dCellDate.getMonth() && + this.cfg.getProperty("pagedate").getFullYear() == dCellDate.getFullYear()) { + YAHOO.util.Dom.removeClass(cell, this.Style.CSS_CELL_SELECTED); + } + + selected.splice(cellDateIndex, 1); + } + + + if (this.parent) { + this.parent.cfg.setProperty("selected", selected); + } else { + this.cfg.setProperty("selected", selected); + } + + this.deselectEvent.fire(selectDate); + return this.getSelectedDates(); +}; + +/** +* Deselects all dates on the current calendar. +* @method deselectAll +* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. +* Assuming that this function executes properly, the return value should be an empty array. +* However, the empty array is returned for the sake of being able to check the selection status +* of the calendar. +*/ +YAHOO.widget.Calendar.prototype.deselectAll = function() { + this.beforeDeselectEvent.fire(); + + var selected = this.cfg.getProperty("selected"); + var count = selected.length; + var sel = selected.concat(); + + if (this.parent) { + this.parent.cfg.setProperty("selected", []); + } else { + this.cfg.setProperty("selected", []); + } + + if (count > 0) { + this.deselectEvent.fire(sel); + } + + return this.getSelectedDates(); +}; + +// END SELECTION METHODS + +// BEGIN TYPE CONVERSION METHODS + +/** +* Converts a date (either a JavaScript Date object, or a date string) to the internal data structure +* used to represent dates: [[yyyy,mm,dd],[yyyy,mm,dd]]. +* @method _toFieldArray +* @private +* @param {String/Date/Date[]} date The date string of dates to deselect in the current calendar. Valid formats are +* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). +* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). +* This method can also take a JavaScript Date object or an array of Date objects. +* @return {Array[](Number[])} Array of date field arrays +*/ +YAHOO.widget.Calendar.prototype._toFieldArray = function(date) { + var returnDate = []; + + if (date instanceof Date) { + returnDate = [[date.getFullYear(), date.getMonth()+1, date.getDate()]]; + } else if (typeof date == 'string') { + returnDate = this._parseDates(date); + } else if (date instanceof Array) { + for (var i=0;i +*
+*
+* +* The tables for the calendars ("cal1_0" and "cal1_1") will be inserted into those containers. +* @namespace YAHOO.widget +* @class CalendarGroup +* @constructor +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.CalendarGroup = function(id, containerId, config) { + if (arguments.length > 0) { + this.init(id, containerId, config); + } +}; + +/** +* Initializes the calendar group. All subclasses must call this method in order for the +* group to be initialized properly. +* @method init +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.CalendarGroup.prototype.init = function(id, containerId, config) { + this.logger = new YAHOO.widget.LogWriter("CalendarGroup " + id); + + this.initEvents(); + this.initStyles(); + + /** + * The collection of Calendar pages contained within the CalendarGroup + * @property pages + * @type YAHOO.widget.Calendar[] + */ + this.pages = []; + + /** + * The unique id associated with the CalendarGroup + * @property id + * @type String + */ + this.id = id; + + /** + * The unique id associated with the CalendarGroup container + * @property containerId + * @type String + */ + this.containerId = containerId; + + /** + * The outer containing element for the CalendarGroup + * @property oDomContainer + * @type HTMLElement + */ + this.oDomContainer = document.getElementById(containerId); + + YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_CONTAINER); + YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_MULTI_UP); + + /** + * The Config object used to hold the configuration variables for the CalendarGroup + * @property cfg + * @type YAHOO.util.Config + */ + this.cfg = new YAHOO.util.Config(this); + + /** + * The local object which contains the CalendarGroup's options + * @property Options + * @type Object + */ + this.Options = {}; + + /** + * The local object which contains the CalendarGroup's locale settings + * @property Locale + * @type Object + */ + this.Locale = {}; + + this.setupConfig(); + + if (config) { + this.cfg.applyConfig(config, true); + } + + this.cfg.fireQueue(); + + // OPERA HACK FOR MISWRAPPED FLOATS + if (this.browser == "opera"){ + var fixWidth = function() { + var startW = this.oDomContainer.offsetWidth; + var w = 0; + for (var p=0;p 0) { + this.oDomContainer.style.width = w + "px"; + } + }; + this.renderEvent.subscribe(fixWidth,this,true); + } + + this.logger.log("Initialized " + pageCount + "-page CalendarGroup", "info"); +}; + + +YAHOO.widget.CalendarGroup.prototype.setupConfig = function() { + /** + * The number of pages to include in the CalendarGroup. This value can only be set once, in the CalendarGroup's constructor arguments. + * @config pages + * @type Number + * @default 2 + */ + this.cfg.addProperty("pages", { value:2, validator:this.cfg.checkNumber, handler:this.configPages } ); + + /** + * The month/year representing the current visible Calendar date (mm/yyyy) + * @config pagedate + * @type String + * @default today's date + */ + this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); + + /** + * The date or range of dates representing the current Calendar selection + * @config selected + * @type String + * @default [] + */ + this.cfg.addProperty("selected", { value:[], handler:this.delegateConfig } ); + + /** + * The title to display above the CalendarGroup's month header + * @config title + * @type String + * @default "" + */ + this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); + + /** + * Whether or not a close button should be displayed for this CalendarGroup + * @config close + * @type Boolean + * @default false + */ + this.cfg.addProperty("close", { value:false, handler:this.configClose } ); + + /** + * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. + * @config iframe + * @type Boolean + * @default true + */ + this.cfg.addProperty("iframe", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The minimum selectable date in the current Calendar (mm/dd/yyyy) + * @config mindate + * @type String + * @default null + */ + this.cfg.addProperty("mindate", { value:null, handler:this.delegateConfig } ); + + /** + * The maximum selectable date in the current Calendar (mm/dd/yyyy) + * @config maxdate + * @type String + * @default null + */ + this.cfg.addProperty("maxdate", { value:null, handler:this.delegateConfig } ); + + // Options properties + + /** + * True if the Calendar should allow multiple selections. False by default. + * @config MULTI_SELECT + * @type Boolean + * @default false + */ + this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The weekday the week begins on. Default is 0 (Sunday). + * @config START_WEEKDAY + * @type number + * @default 0 + */ + this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * True if the Calendar should show weekday labels. True by default. + * @config SHOW_WEEKDAYS + * @type Boolean + * @default true + */ + this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row headers. False by default. + * @config SHOW_WEEK_HEADER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row footers. False by default. + * @config SHOW_WEEK_FOOTER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should suppress weeks that are not a part of the current month. False by default. + * @config HIDE_BLANK_WEEKS + * @type Boolean + * @default false + */ + this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_LEFT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" + */ + this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.delegateConfig } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_RIGHT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" + */ + this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.delegateConfig } ); + + // Locale properties + + /** + * The short month labels for the current locale. + * @config MONTHS_SHORT + * @type String[] + * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + */ + this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.delegateConfig } ); + + /** + * The long month labels for the current locale. + * @config MONTHS_LONG + * @type String[] + * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" + */ + this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.delegateConfig } ); + + /** + * The 1-character weekday labels for the current locale. + * @config WEEKDAYS_1CHAR + * @type String[] + * @default ["S", "M", "T", "W", "T", "F", "S"] + */ + this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.delegateConfig } ); + + /** + * The short weekday labels for the current locale. + * @config WEEKDAYS_SHORT + * @type String[] + * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] + */ + this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.delegateConfig } ); + + /** + * The medium weekday labels for the current locale. + * @config WEEKDAYS_MEDIUM + * @type String[] + * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] + */ + this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.delegateConfig } ); + + /** + * The long weekday labels for the current locale. + * @config WEEKDAYS_LONG + * @type String[] + * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + */ + this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.delegateConfig } ); + + /** + * The setting that determines which length of month labels should be used. Possible values are "short" and "long". + * @config LOCALE_MONTHS + * @type String + * @default "long" + */ + this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.delegateConfig } ); + + /** + * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". + * @config LOCALE_WEEKDAYS + * @type String + * @default "short" + */ + this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.delegateConfig } ); + + /** + * The value used to delimit individual dates in a date string passed to various Calendar functions. + * @config DATE_DELIMITER + * @type String + * @default "," + */ + this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.delegateConfig } ); + + /** + * The value used to delimit date fields in a date string passed to various Calendar functions. + * @config DATE_FIELD_DELIMITER + * @type String + * @default "/" + */ + this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.delegateConfig } ); + + /** + * The value used to delimit date ranges in a date string passed to various Calendar functions. + * @config DATE_RANGE_DELIMITER + * @type String + * @default "-" + */ + this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.delegateConfig } ); + + /** + * The position of the month in a month/year date string + * @config MY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/year date string + * @config MY_YEAR_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day date string + * @config MD_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/year date string + * @config MD_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day/year date string + * @config MDY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/day/year date string + * @config MDY_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/day/year date string + * @config MDY_YEAR_POSITION + * @type Number + * @default 3 + */ + this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + +}; + +/** +* Initializes CalendarGroup's built-in CustomEvents +* @method initEvents +*/ +YAHOO.widget.CalendarGroup.prototype.initEvents = function() { + var me = this; + + /** + * Proxy subscriber to subscribe to the CalendarGroup's child Calendars' CustomEvents + * @method sub + * @private + * @param {Function} fn The function to subscribe to this CustomEvent + * @param {Object} obj The CustomEvent's scope object + * @param {Boolean} bOverride Whether or not to apply scope correction + */ + var sub = function(fn, obj, bOverride) { + for (var p=0;p0) { + year+=1; + } + cal.setYear(year); + } +}; +/** +* Calls the render function of all child calendars within the group. +* @method render +*/ +YAHOO.widget.CalendarGroup.prototype.render = function() { + this.renderHeader(); + for (var p=0;p=0;--p) { + var cal = this.pages[p]; + cal.previousMonth(); + } +}; + +/** +* Navigates to the next year in the currently selected month in the calendar widget. +* @method nextYear +*/ +YAHOO.widget.CalendarGroup.prototype.nextYear = function() { + for (var p=0;p11){while(newMonth>11){newMonth-=12;years+=1;}} -d.setMonth(newMonth);d.setFullYear(date.getFullYear()+years);break;case this.DAY:d.setDate(date.getDate()+amount);break;case this.YEAR:d.setFullYear(date.getFullYear()+amount);break;case this.WEEK:d.setDate(date.getDate()+(amount*7));break;} -return d;},subtract:function(date,field,amount){return this.add(date,field,(amount*-1));},before:function(date,compareTo){var ms=compareTo.getTime();if(date.getTime()ms){return true;}else{return false;}},between:function(date,dateBegin,dateEnd){if(this.after(date,dateBegin)&&this.before(date,dateEnd)){return true;}else{return false;}},getJan1:function(calendarYear){return new Date(calendarYear,0,1);},getDayOffset:function(date,calendarYear){var beginYear=this.getJan1(calendarYear);var dayOffset=Math.ceil((date.getTime()-beginYear.getTime())/this.ONE_DAY_MS);return dayOffset;},getWeekNumber:function(date,calendarYear){date=this.clearTime(date);var nearestThurs=new Date(date.getTime()+(4*this.ONE_DAY_MS)-((date.getDay())*this.ONE_DAY_MS));var jan1=new Date(nearestThurs.getFullYear(),0,1);var dayOfYear=((nearestThurs.getTime()-jan1.getTime())/this.ONE_DAY_MS)-1;var weekNum=Math.ceil((dayOfYear)/7);return weekNum;},isYearOverlapWeek:function(weekBeginDate){var overlaps=false;var nextWeek=this.add(weekBeginDate,this.DAY,6);if(nextWeek.getFullYear()!=weekBeginDate.getFullYear()){overlaps=true;} -return overlaps;},isMonthOverlapWeek:function(weekBeginDate){var overlaps=false;var nextWeek=this.add(weekBeginDate,this.DAY,6);if(nextWeek.getMonth()!=weekBeginDate.getMonth()){overlaps=true;} -return overlaps;},findMonthStart:function(date){var start=new Date(date.getFullYear(),date.getMonth(),1);return start;},findMonthEnd:function(date){var start=this.findMonthStart(date);var nextMonth=this.add(start,this.MONTH,1);var end=this.subtract(nextMonth,this.DAY,1);return end;},clearTime:function(date){date.setHours(12,0,0,0);return date;}};YAHOO.widget.Calendar=function(id,containerId,config){this.init(id,containerId,config);};YAHOO.widget.Calendar.IMG_ROOT=(window.location.href.toLowerCase().indexOf("https")===0?"https://a248.e.akamai.net/sec.yimg.com/i/":"http://us.i1.yimg.com/us.yimg.com/i/");YAHOO.widget.Calendar.DATE="D";YAHOO.widget.Calendar.MONTH_DAY="MD";YAHOO.widget.Calendar.WEEKDAY="WD";YAHOO.widget.Calendar.RANGE="R";YAHOO.widget.Calendar.MONTH="M";YAHOO.widget.Calendar.DISPLAY_DAYS=42;YAHOO.widget.Calendar.STOP_RENDER="S";YAHOO.widget.Calendar.prototype={Config:null,parent:null,index:-1,cells:null,cellDates:null,id:null,oDomContainer:null,today:null,renderStack:null,_renderStack:null,_pageDate:null,_selectedDates:null,domEventMap:null};YAHOO.widget.Calendar.prototype.init=function(id,containerId,config){this.initEvents();this.today=new Date();YAHOO.widget.DateMath.clearTime(this.today);this.id=id;this.oDomContainer=document.getElementById(containerId);this.cfg=new YAHOO.util.Config(this);this.Options={};this.Locale={};this.initStyles();YAHOO.util.Dom.addClass(this.oDomContainer,this.Style.CSS_CONTAINER);YAHOO.util.Dom.addClass(this.oDomContainer,this.Style.CSS_SINGLE);this.cellDates=[];this.cells=[];this.renderStack=[];this._renderStack=[];this.setupConfig();if(config){this.cfg.applyConfig(config,true);} -this.cfg.fireQueue();};YAHOO.widget.Calendar.prototype.configIframe=function(type,args,obj){var useIframe=args[0];if(YAHOO.util.Dom.inDocument(this.oDomContainer)){if(useIframe){var pos=YAHOO.util.Dom.getStyle(this.oDomContainer,"position");if(this.browser=="ie"&&(pos=="absolute"||pos=="relative")){if(!YAHOO.util.Dom.inDocument(this.iframe)){this.iframe=document.createElement("iframe");this.iframe.src="javascript:false;";YAHOO.util.Dom.setStyle(this.iframe,"opacity","0");this.oDomContainer.insertBefore(this.iframe,this.oDomContainer.firstChild);}}}else{if(this.iframe){if(this.iframe.parentNode){this.iframe.parentNode.removeChild(this.iframe);} -this.iframe=null;}}}};YAHOO.widget.Calendar.prototype.configTitle=function(type,args,obj){var title=args[0];var close=this.cfg.getProperty("close");var titleDiv;if(title&&title!==""){titleDiv=YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE,"div",this.oDomContainer)[0]||document.createElement("div");titleDiv.className=YAHOO.widget.CalendarGroup.CSS_2UPTITLE;titleDiv.innerHTML=title;this.oDomContainer.insertBefore(titleDiv,this.oDomContainer.firstChild);YAHOO.util.Dom.addClass(this.oDomContainer,"withtitle");}else{titleDiv=YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE,"div",this.oDomContainer)[0]||null;if(titleDiv){YAHOO.util.Event.purgeElement(titleDiv);this.oDomContainer.removeChild(titleDiv);} -if(!close){YAHOO.util.Dom.removeClass(this.oDomContainer,"withtitle");}}};YAHOO.widget.Calendar.prototype.configClose=function(type,args,obj){var close=args[0];var title=this.cfg.getProperty("title");var linkClose;if(close===true){linkClose=YAHOO.util.Dom.getElementsByClassName("link-close","a",this.oDomContainer)[0]||document.createElement("a");linkClose.href="javascript:void(null);";linkClose.className="link-close";YAHOO.util.Event.addListener(linkClose,"click",this.hide,this,true);var imgClose=document.createElement("img");imgClose.src=YAHOO.widget.Calendar.IMG_ROOT+"us/my/bn/x_d.gif";imgClose.className=YAHOO.widget.CalendarGroup.CSS_2UPCLOSE;linkClose.appendChild(imgClose);this.oDomContainer.appendChild(linkClose);YAHOO.util.Dom.addClass(this.oDomContainer,"withtitle");}else{linkClose=YAHOO.util.Dom.getElementsByClassName("link-close","a",this.oDomContainer)[0]||null;if(linkClose){YAHOO.util.Event.purgeElement(linkClose);this.oDomContainer.removeChild(linkClose);} -if(!title||title===""){YAHOO.util.Dom.removeClass(this.oDomContainer,"withtitle");}}};YAHOO.widget.Calendar.prototype.initEvents=function(){this.beforeSelectEvent=new YAHOO.util.CustomEvent("beforeSelect");this.selectEvent=new YAHOO.util.CustomEvent("select");this.beforeDeselectEvent=new YAHOO.util.CustomEvent("beforeDeselect");this.deselectEvent=new YAHOO.util.CustomEvent("deselect");this.changePageEvent=new YAHOO.util.CustomEvent("changePage");this.beforeRenderEvent=new YAHOO.util.CustomEvent("beforeRender");this.renderEvent=new YAHOO.util.CustomEvent("render");this.resetEvent=new YAHOO.util.CustomEvent("reset");this.clearEvent=new YAHOO.util.CustomEvent("clear");this.beforeSelectEvent.subscribe(this.onBeforeSelect,this,true);this.selectEvent.subscribe(this.onSelect,this,true);this.beforeDeselectEvent.subscribe(this.onBeforeDeselect,this,true);this.deselectEvent.subscribe(this.onDeselect,this,true);this.changePageEvent.subscribe(this.onChangePage,this,true);this.renderEvent.subscribe(this.onRender,this,true);this.resetEvent.subscribe(this.onReset,this,true);this.clearEvent.subscribe(this.onClear,this,true);};YAHOO.widget.Calendar.prototype.doSelectCell=function(e,cal){var target=YAHOO.util.Event.getTarget(e);var cell,index,d,date;while(target.tagName.toLowerCase()!="td"&&!YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} -cell=target;if(YAHOO.util.Dom.hasClass(cell,cal.Style.CSS_CELL_SELECTABLE)){index=cell.id.split("cell")[1];d=cal.cellDates[index];date=new Date(d[0],d[1]-1,d[2]);var link;if(cal.Options.MULTI_SELECT){link=cell.getElementsByTagName("a")[0];if(link){link.blur();} -var cellDate=cal.cellDates[index];var cellDateIndex=cal._indexOfSelectedFieldArray(cellDate);if(cellDateIndex>-1){cal.deselectCell(index);}else{cal.selectCell(index);}}else{link=cell.getElementsByTagName("a")[0];if(link){link.blur();} -cal.selectCell(index);}}};YAHOO.widget.Calendar.prototype.doCellMouseOver=function(e,cal){var target;if(e){target=YAHOO.util.Event.getTarget(e);}else{target=this;} -while(target.tagName.toLowerCase()!="td"){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} -if(YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){YAHOO.util.Dom.addClass(target,cal.Style.CSS_CELL_HOVER);}};YAHOO.widget.Calendar.prototype.doCellMouseOut=function(e,cal){var target;if(e){target=YAHOO.util.Event.getTarget(e);}else{target=this;} -while(target.tagName.toLowerCase()!="td"){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} -if(YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){YAHOO.util.Dom.removeClass(target,cal.Style.CSS_CELL_HOVER);}};YAHOO.widget.Calendar.prototype.setupConfig=function(){this.cfg.addProperty("pagedate",{value:new Date(),handler:this.configPageDate});this.cfg.addProperty("selected",{value:[],handler:this.configSelected});this.cfg.addProperty("title",{value:"",handler:this.configTitle});this.cfg.addProperty("close",{value:false,handler:this.configClose});this.cfg.addProperty("iframe",{value:true,handler:this.configIframe,validator:this.cfg.checkBoolean});this.cfg.addProperty("mindate",{value:null,handler:this.configMinDate});this.cfg.addProperty("maxdate",{value:null,handler:this.configMaxDate});this.cfg.addProperty("MULTI_SELECT",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("START_WEEKDAY",{value:0,handler:this.configOptions,validator:this.cfg.checkNumber});this.cfg.addProperty("SHOW_WEEKDAYS",{value:true,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_HEADER",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_FOOTER",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("HIDE_BLANK_WEEKS",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("NAV_ARROW_LEFT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/callt.gif",handler:this.configOptions});this.cfg.addProperty("NAV_ARROW_RIGHT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/calrt.gif",handler:this.configOptions});this.cfg.addProperty("MONTHS_SHORT",{value:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],handler:this.configLocale});this.cfg.addProperty("MONTHS_LONG",{value:["January","February","March","April","May","June","July","August","September","October","November","December"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_1CHAR",{value:["S","M","T","W","T","F","S"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_SHORT",{value:["Su","Mo","Tu","We","Th","Fr","Sa"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_MEDIUM",{value:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_LONG",{value:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],handler:this.configLocale});var refreshLocale=function(){this.cfg.refireEvent("LOCALE_MONTHS");this.cfg.refireEvent("LOCALE_WEEKDAYS");};this.cfg.subscribeToConfigEvent("START_WEEKDAY",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("MONTHS_SHORT",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("MONTHS_LONG",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG",refreshLocale,this,true);this.cfg.addProperty("LOCALE_MONTHS",{value:"long",handler:this.configLocaleValues});this.cfg.addProperty("LOCALE_WEEKDAYS",{value:"short",handler:this.configLocaleValues});this.cfg.addProperty("DATE_DELIMITER",{value:",",handler:this.configLocale});this.cfg.addProperty("DATE_FIELD_DELIMITER",{value:"/",handler:this.configLocale});this.cfg.addProperty("DATE_RANGE_DELIMITER",{value:"-",handler:this.configLocale});this.cfg.addProperty("MY_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MY_YEAR_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_DAY_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_DAY_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_YEAR_POSITION",{value:3,handler:this.configLocale,validator:this.cfg.checkNumber});};YAHOO.widget.Calendar.prototype.configPageDate=function(type,args,obj){var val=args[0];var month,year,aMonthYear;if(val){if(val instanceof Date){val=YAHOO.widget.DateMath.findMonthStart(val);this.cfg.setProperty("pagedate",val,true);if(!this._pageDate){this._pageDate=this.cfg.getProperty("pagedate");} -return;}else{aMonthYear=val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER"));month=parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1],10)-1;year=parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1],10);}}else{month=this.today.getMonth();year=this.today.getFullYear();} -this.cfg.setProperty("pagedate",new Date(year,month,1),true);if(!this._pageDate){this._pageDate=this.cfg.getProperty("pagedate");}};YAHOO.widget.Calendar.prototype.configMinDate=function(type,args,obj){var val=args[0];if(typeof val=='string'){val=this._parseDate(val);this.cfg.setProperty("mindate",new Date(val[0],(val[1]-1),val[2]));}};YAHOO.widget.Calendar.prototype.configMaxDate=function(type,args,obj){var val=args[0];if(typeof val=='string'){val=this._parseDate(val);this.cfg.setProperty("maxdate",new Date(val[0],(val[1]-1),val[2]));}};YAHOO.widget.Calendar.prototype.configSelected=function(type,args,obj){var selected=args[0];if(selected){if(typeof selected=='string'){this.cfg.setProperty("selected",this._parseDates(selected),true);}} -if(!this._selectedDates){this._selectedDates=this.cfg.getProperty("selected");}};YAHOO.widget.Calendar.prototype.configOptions=function(type,args,obj){type=type.toUpperCase();var val=args[0];this.Options[type]=val;};YAHOO.widget.Calendar.prototype.configLocale=function(type,args,obj){type=type.toUpperCase();var val=args[0];this.Locale[type]=val;this.cfg.refireEvent("LOCALE_MONTHS");this.cfg.refireEvent("LOCALE_WEEKDAYS");};YAHOO.widget.Calendar.prototype.configLocaleValues=function(type,args,obj){type=type.toUpperCase();var val=args[0];switch(type){case"LOCALE_MONTHS":switch(val){case"short":this.Locale.LOCALE_MONTHS=this.cfg.getProperty("MONTHS_SHORT").concat();break;case"long":this.Locale.LOCALE_MONTHS=this.cfg.getProperty("MONTHS_LONG").concat();break;} -break;case"LOCALE_WEEKDAYS":switch(val){case"1char":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_1CHAR").concat();break;case"short":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_SHORT").concat();break;case"medium":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_MEDIUM").concat();break;case"long":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_LONG").concat();break;} -var START_WEEKDAY=this.cfg.getProperty("START_WEEKDAY");if(START_WEEKDAY>0){for(var w=0;w';html[html.length]='
';var renderLeft,renderRight=false;if(this.parent){if(this.index===0){renderLeft=true;} -if(this.index==(this.parent.cfg.getProperty("pages")-1)){renderRight=true;}}else{renderLeft=true;renderRight=true;} -var cal=this.parent||this;if(renderLeft){html[html.length]=' ';} -html[html.length]=this.buildMonthLabel();if(renderRight){html[html.length]=' ';} -html[html.length]='
';html[html.length]='';html[html.length]='';if(this.cfg.getProperty("SHOW_WEEKDAYS")){html=this.buildWeekdays(html);} -html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.buildWeekdays=function(html){html[html.length]='';if(this.cfg.getProperty("SHOW_WEEK_HEADER")){html[html.length]=' ';} -for(var i=0;i'+this.Locale.LOCALE_WEEKDAYS[i]+'';} -if(this.cfg.getProperty("SHOW_WEEK_FOOTER")){html[html.length]=' ';} -html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.renderBody=function(workingDate,html){var startDay=this.cfg.getProperty("START_WEEKDAY");this.preMonthDays=workingDate.getDay();if(startDay>0){this.preMonthDays-=startDay;} -if(this.preMonthDays<0){this.preMonthDays+=7;} -this.monthDays=YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate();this.postMonthDays=YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays;workingDate=YAHOO.widget.DateMath.subtract(workingDate,YAHOO.widget.DateMath.DAY,this.preMonthDays);var useDate,weekNum,weekClass;useDate=this.cfg.getProperty("pagedate");html[html.length]='';var i=0;var tempDiv=document.createElement("div");var cell=document.createElement("td");tempDiv.appendChild(cell);var jan1=new Date(useDate.getFullYear(),0,1);var cal=this.parent||this;for(var r=0;r<6;r++){weekNum=YAHOO.widget.DateMath.getWeekNumber(workingDate,useDate.getFullYear(),startDay);weekClass="w"+weekNum;if(r!==0&&this.isDateOOM(workingDate)&&this.cfg.getProperty("HIDE_BLANK_WEEKS")===true){break;}else{html[html.length]='';if(this.cfg.getProperty("SHOW_WEEK_HEADER")){html=this.renderRowHeader(weekNum,html);} -for(var d=0;d<7;d++){var cellRenderers=[];this.clearElement(cell);YAHOO.util.Dom.addClass(cell,"calcell");cell.id=this.id+"_cell"+i;cell.innerHTML=i;var renderer=null;if(workingDate.getFullYear()==this.today.getFullYear()&&workingDate.getMonth()==this.today.getMonth()&&workingDate.getDate()==this.today.getDate()){cellRenderers[cellRenderers.length]=cal.renderCellStyleToday;} -this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()];if(this.isDateOOM(workingDate)){cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth;}else{YAHOO.util.Dom.addClass(cell,"wd"+workingDate.getDay());YAHOO.util.Dom.addClass(cell,"d"+workingDate.getDate());for(var s=0;s=d1.getTime()&&workingDate.getTime()<=d2.getTime()){renderer=rArray[2];if(workingDate.getTime()==d2.getTime()){this.renderStack.splice(s,1);}} -break;case YAHOO.widget.Calendar.WEEKDAY:var weekday=rArray[1][0];if(workingDate.getDay()+1==weekday){renderer=rArray[2];} -break;case YAHOO.widget.Calendar.MONTH:month=rArray[1][0];if(workingDate.getMonth()+1==month){renderer=rArray[2];} -break;} -if(renderer){cellRenderers[cellRenderers.length]=renderer;}}} -if(this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()])>-1){cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected;} -var mindate=this.cfg.getProperty("mindate");var maxdate=this.cfg.getProperty("maxdate");if(mindate){mindate=YAHOO.widget.DateMath.clearTime(mindate);} -if(maxdate){maxdate=YAHOO.widget.DateMath.clearTime(maxdate);} -if((mindate&&(workingDate.getTime()maxdate.getTime()))){cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate;}else{cellRenderers[cellRenderers.length]=cal.styleCellDefault;cellRenderers[cellRenderers.length]=cal.renderCellDefault;} -for(var x=0;x=0&&i<=6){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_TOP);} -if((i%7)===0){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_LEFT);} -if(((i+1)%7)===0){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_RIGHT);} -var postDays=this.postMonthDays;if(postDays>=7&&this.cfg.getProperty("HIDE_BLANK_WEEKS")){var blankWeeks=Math.floor(postDays/7);for(var p=0;p=((this.preMonthDays+postDays+this.monthDays)-7)){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_BOTTOM);} -html[html.length]=tempDiv.innerHTML;i++;} -if(this.cfg.getProperty("SHOW_WEEK_FOOTER")){html=this.renderRowFooter(weekNum,html);} -html[html.length]='';}} -html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.renderFooter=function(html){return html;};YAHOO.widget.Calendar.prototype.render=function(){this.beforeRenderEvent.fire();var workingDate=YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate"));this.resetRenderers();this.cellDates.length=0;YAHOO.util.Event.purgeElement(this.oDomContainer,true);var html=[];html[html.length]='';html=this.renderHeader(html);html=this.renderBody(workingDate,html);html=this.renderFooter(html);html[html.length]='
';this.oDomContainer.innerHTML=html.join("\n");this.applyListeners();this.cells=this.oDomContainer.getElementsByTagName("td");this.cfg.refireEvent("title");this.cfg.refireEvent("close");this.cfg.refireEvent("iframe");this.renderEvent.fire();};YAHOO.widget.Calendar.prototype.applyListeners=function(){var root=this.oDomContainer;var cal=this.parent||this;var linkLeft,linkRight;linkLeft=YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT,"a",root);linkRight=YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT,"a",root);if(linkLeft){this.linkLeft=linkLeft[0];YAHOO.util.Event.addListener(this.linkLeft,"mousedown",cal.previousMonth,cal,true);} -if(linkRight){this.linkRight=linkRight[0];YAHOO.util.Event.addListener(this.linkRight,"mousedown",cal.nextMonth,cal,true);} -if(this.domEventMap){var el,elements;for(var cls in this.domEventMap){if(this.domEventMap.hasOwnProperty(cls)){var items=this.domEventMap[cls];if(!(items instanceof Array)){items=[items];} -for(var i=0;i'+weekNum+'';return html;};YAHOO.widget.Calendar.prototype.renderRowFooter=function(weekNum,html){html[html.length]=''+weekNum+'';return html;};YAHOO.widget.Calendar.prototype.renderCellDefault=function(workingDate,cell){cell.innerHTML=''+this.buildDayLabel(workingDate)+"";};YAHOO.widget.Calendar.prototype.styleCellDefault=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_SELECTABLE);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT1);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT2);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT3);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT4);};YAHOO.widget.Calendar.prototype.renderCellStyleToday=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_TODAY);};YAHOO.widget.Calendar.prototype.renderCellStyleSelected=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_SELECTED);};YAHOO.widget.Calendar.prototype.renderCellNotThisMonth=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_OOM);cell.innerHTML=workingDate.getDate();return YAHOO.widget.Calendar.STOP_RENDER;};YAHOO.widget.Calendar.prototype.renderBodyCellRestricted=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL);YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_RESTRICTED);cell.innerHTML=workingDate.getDate();return YAHOO.widget.Calendar.STOP_RENDER;};YAHOO.widget.Calendar.prototype.addMonths=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.MONTH,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.subtractMonths=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.MONTH,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.addYears=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.YEAR,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.subtractYears=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.YEAR,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.nextMonth=function(){this.addMonths(1);};YAHOO.widget.Calendar.prototype.previousMonth=function(){this.subtractMonths(1);};YAHOO.widget.Calendar.prototype.nextYear=function(){this.addYears(1);};YAHOO.widget.Calendar.prototype.previousYear=function(){this.subtractYears(1);};YAHOO.widget.Calendar.prototype.reset=function(){this.cfg.resetProperty("selected");this.cfg.resetProperty("pagedate");this.resetEvent.fire();};YAHOO.widget.Calendar.prototype.clear=function(){this.cfg.setProperty("selected",[]);this.cfg.setProperty("pagedate",new Date(this.today.getTime()));this.clearEvent.fire();};YAHOO.widget.Calendar.prototype.select=function(date){this.beforeSelectEvent.fire();var selected=this.cfg.getProperty("selected");var aToBeSelected=this._toFieldArray(date);for(var a=0;a-1){if(this.cfg.getProperty("pagedate").getMonth()==dCellDate.getMonth()&&this.cfg.getProperty("pagedate").getFullYear()==dCellDate.getFullYear()){YAHOO.util.Dom.removeClass(cell,this.Style.CSS_CELL_SELECTED);} -selected.splice(cellDateIndex,1);} -if(this.parent){this.parent.cfg.setProperty("selected",selected);}else{this.cfg.setProperty("selected",selected);} -this.deselectEvent.fire(selectDate);return this.getSelectedDates();};YAHOO.widget.Calendar.prototype.deselectAll=function(){this.beforeDeselectEvent.fire();var selected=this.cfg.getProperty("selected");var count=selected.length;var sel=selected.concat();if(this.parent){this.parent.cfg.setProperty("selected",[]);}else{this.cfg.setProperty("selected",[]);} -if(count>0){this.deselectEvent.fire(sel);} -return this.getSelectedDates();};YAHOO.widget.Calendar.prototype._toFieldArray=function(date){var returnDate=[];if(date instanceof Date){returnDate=[[date.getFullYear(),date.getMonth()+1,date.getDate()]];}else if(typeof date=='string'){returnDate=this._parseDates(date);}else if(date instanceof Array){for(var i=0;i0){this.init(id,containerId,config);}};YAHOO.widget.CalendarGroup.prototype.init=function(id,containerId,config){this.initEvents();this.initStyles();this.pages=[];this.id=id;this.containerId=containerId;this.oDomContainer=document.getElementById(containerId);YAHOO.util.Dom.addClass(this.oDomContainer,YAHOO.widget.CalendarGroup.CSS_CONTAINER);YAHOO.util.Dom.addClass(this.oDomContainer,YAHOO.widget.CalendarGroup.CSS_MULTI_UP);this.cfg=new YAHOO.util.Config(this);this.Options={};this.Locale={};this.setupConfig();if(config){this.cfg.applyConfig(config,true);} -this.cfg.fireQueue();if(this.browser=="opera"){var fixWidth=function(){var startW=this.oDomContainer.offsetWidth;var w=0;for(var p=0;p0){this.oDomContainer.style.width=w+"px";}};this.renderEvent.subscribe(fixWidth,this,true);}};YAHOO.widget.CalendarGroup.prototype.setupConfig=function(){this.cfg.addProperty("pages",{value:2,validator:this.cfg.checkNumber,handler:this.configPages});this.cfg.addProperty("pagedate",{value:new Date(),handler:this.configPageDate});this.cfg.addProperty("selected",{value:[],handler:this.delegateConfig});this.cfg.addProperty("title",{value:"",handler:this.configTitle});this.cfg.addProperty("close",{value:false,handler:this.configClose});this.cfg.addProperty("iframe",{value:true,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("mindate",{value:null,handler:this.delegateConfig});this.cfg.addProperty("maxdate",{value:null,handler:this.delegateConfig});this.cfg.addProperty("MULTI_SELECT",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("START_WEEKDAY",{value:0,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("SHOW_WEEKDAYS",{value:true,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_HEADER",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_FOOTER",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("HIDE_BLANK_WEEKS",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("NAV_ARROW_LEFT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/callt.gif",handler:this.delegateConfig});this.cfg.addProperty("NAV_ARROW_RIGHT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/calrt.gif",handler:this.delegateConfig});this.cfg.addProperty("MONTHS_SHORT",{value:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],handler:this.delegateConfig});this.cfg.addProperty("MONTHS_LONG",{value:["January","February","March","April","May","June","July","August","September","October","November","December"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_1CHAR",{value:["S","M","T","W","T","F","S"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_SHORT",{value:["Su","Mo","Tu","We","Th","Fr","Sa"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_MEDIUM",{value:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_LONG",{value:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],handler:this.delegateConfig});this.cfg.addProperty("LOCALE_MONTHS",{value:"long",handler:this.delegateConfig});this.cfg.addProperty("LOCALE_WEEKDAYS",{value:"short",handler:this.delegateConfig});this.cfg.addProperty("DATE_DELIMITER",{value:",",handler:this.delegateConfig});this.cfg.addProperty("DATE_FIELD_DELIMITER",{value:"/",handler:this.delegateConfig});this.cfg.addProperty("DATE_RANGE_DELIMITER",{value:"-",handler:this.delegateConfig});this.cfg.addProperty("MY_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MY_YEAR_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_DAY_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_DAY_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_YEAR_POSITION",{value:3,handler:this.delegateConfig,validator:this.cfg.checkNumber});};YAHOO.widget.CalendarGroup.prototype.initEvents=function(){var me=this;var sub=function(fn,obj,bOverride){for(var p=0;p0){year+=1;} -cal.setYear(year);}};YAHOO.widget.CalendarGroup.prototype.render=function(){this.renderHeader();for(var p=0;p=0;--p){var cal=this.pages[p];cal.previousMonth();}};YAHOO.widget.CalendarGroup.prototype.nextYear=function(){for(var p=0;p11){while(newMonth>11){newMonth-=12;years+=1;}} +d.setMonth(newMonth);d.setFullYear(date.getFullYear()+years);break;case this.DAY:d.setDate(date.getDate()+amount);break;case this.YEAR:d.setFullYear(date.getFullYear()+amount);break;case this.WEEK:d.setDate(date.getDate()+(amount*7));break;} +return d;},subtract:function(date,field,amount){return this.add(date,field,(amount*-1));},before:function(date,compareTo){var ms=compareTo.getTime();if(date.getTime()ms){return true;}else{return false;}},between:function(date,dateBegin,dateEnd){if(this.after(date,dateBegin)&&this.before(date,dateEnd)){return true;}else{return false;}},getJan1:function(calendarYear){return new Date(calendarYear,0,1);},getDayOffset:function(date,calendarYear){var beginYear=this.getJan1(calendarYear);var dayOffset=Math.ceil((date.getTime()-beginYear.getTime())/this.ONE_DAY_MS);return dayOffset;},getWeekNumber:function(date,calendarYear){date=this.clearTime(date);var nearestThurs=new Date(date.getTime()+(4*this.ONE_DAY_MS)-((date.getDay())*this.ONE_DAY_MS));var jan1=new Date(nearestThurs.getFullYear(),0,1);var dayOfYear=((nearestThurs.getTime()-jan1.getTime())/this.ONE_DAY_MS)-1;var weekNum=Math.ceil((dayOfYear)/7);return weekNum;},isYearOverlapWeek:function(weekBeginDate){var overlaps=false;var nextWeek=this.add(weekBeginDate,this.DAY,6);if(nextWeek.getFullYear()!=weekBeginDate.getFullYear()){overlaps=true;} +return overlaps;},isMonthOverlapWeek:function(weekBeginDate){var overlaps=false;var nextWeek=this.add(weekBeginDate,this.DAY,6);if(nextWeek.getMonth()!=weekBeginDate.getMonth()){overlaps=true;} +return overlaps;},findMonthStart:function(date){var start=new Date(date.getFullYear(),date.getMonth(),1);return start;},findMonthEnd:function(date){var start=this.findMonthStart(date);var nextMonth=this.add(start,this.MONTH,1);var end=this.subtract(nextMonth,this.DAY,1);return end;},clearTime:function(date){date.setHours(12,0,0,0);return date;}};YAHOO.widget.Calendar=function(id,containerId,config){this.init(id,containerId,config);};YAHOO.widget.Calendar.IMG_ROOT=(window.location.href.toLowerCase().indexOf("https")===0?"https://a248.e.akamai.net/sec.yimg.com/i/":"http://us.i1.yimg.com/us.yimg.com/i/");YAHOO.widget.Calendar.DATE="D";YAHOO.widget.Calendar.MONTH_DAY="MD";YAHOO.widget.Calendar.WEEKDAY="WD";YAHOO.widget.Calendar.RANGE="R";YAHOO.widget.Calendar.MONTH="M";YAHOO.widget.Calendar.DISPLAY_DAYS=42;YAHOO.widget.Calendar.STOP_RENDER="S";YAHOO.widget.Calendar.prototype={Config:null,parent:null,index:-1,cells:null,cellDates:null,id:null,oDomContainer:null,today:null,renderStack:null,_renderStack:null,_pageDate:null,_selectedDates:null,domEventMap:null};YAHOO.widget.Calendar.prototype.init=function(id,containerId,config){this.initEvents();this.today=new Date();YAHOO.widget.DateMath.clearTime(this.today);this.id=id;this.oDomContainer=document.getElementById(containerId);this.cfg=new YAHOO.util.Config(this);this.Options={};this.Locale={};this.initStyles();YAHOO.util.Dom.addClass(this.oDomContainer,this.Style.CSS_CONTAINER);YAHOO.util.Dom.addClass(this.oDomContainer,this.Style.CSS_SINGLE);this.cellDates=[];this.cells=[];this.renderStack=[];this._renderStack=[];this.setupConfig();if(config){this.cfg.applyConfig(config,true);} +this.cfg.fireQueue();};YAHOO.widget.Calendar.prototype.configIframe=function(type,args,obj){var useIframe=args[0];if(YAHOO.util.Dom.inDocument(this.oDomContainer)){if(useIframe){var pos=YAHOO.util.Dom.getStyle(this.oDomContainer,"position");if(this.browser=="ie"&&(pos=="absolute"||pos=="relative")){if(!YAHOO.util.Dom.inDocument(this.iframe)){this.iframe=document.createElement("iframe");this.iframe.src="javascript:false;";YAHOO.util.Dom.setStyle(this.iframe,"opacity","0");this.oDomContainer.insertBefore(this.iframe,this.oDomContainer.firstChild);}}}else{if(this.iframe){if(this.iframe.parentNode){this.iframe.parentNode.removeChild(this.iframe);} +this.iframe=null;}}}};YAHOO.widget.Calendar.prototype.configTitle=function(type,args,obj){var title=args[0];var close=this.cfg.getProperty("close");var titleDiv;if(title&&title!==""){titleDiv=YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE,"div",this.oDomContainer)[0]||document.createElement("div");titleDiv.className=YAHOO.widget.CalendarGroup.CSS_2UPTITLE;titleDiv.innerHTML=title;this.oDomContainer.insertBefore(titleDiv,this.oDomContainer.firstChild);YAHOO.util.Dom.addClass(this.oDomContainer,"withtitle");}else{titleDiv=YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE,"div",this.oDomContainer)[0]||null;if(titleDiv){YAHOO.util.Event.purgeElement(titleDiv);this.oDomContainer.removeChild(titleDiv);} +if(!close){YAHOO.util.Dom.removeClass(this.oDomContainer,"withtitle");}}};YAHOO.widget.Calendar.prototype.configClose=function(type,args,obj){var close=args[0];var title=this.cfg.getProperty("title");var linkClose;if(close===true){linkClose=YAHOO.util.Dom.getElementsByClassName("link-close","a",this.oDomContainer)[0]||document.createElement("a");linkClose.href="javascript:void(null);";linkClose.className="link-close";YAHOO.util.Event.addListener(linkClose,"click",this.hide,this,true);var imgClose=document.createElement("img");imgClose.src=YAHOO.widget.Calendar.IMG_ROOT+"us/my/bn/x_d.gif";imgClose.className=YAHOO.widget.CalendarGroup.CSS_2UPCLOSE;linkClose.appendChild(imgClose);this.oDomContainer.appendChild(linkClose);YAHOO.util.Dom.addClass(this.oDomContainer,"withtitle");}else{linkClose=YAHOO.util.Dom.getElementsByClassName("link-close","a",this.oDomContainer)[0]||null;if(linkClose){YAHOO.util.Event.purgeElement(linkClose);this.oDomContainer.removeChild(linkClose);} +if(!title||title===""){YAHOO.util.Dom.removeClass(this.oDomContainer,"withtitle");}}};YAHOO.widget.Calendar.prototype.initEvents=function(){this.beforeSelectEvent=new YAHOO.util.CustomEvent("beforeSelect");this.selectEvent=new YAHOO.util.CustomEvent("select");this.beforeDeselectEvent=new YAHOO.util.CustomEvent("beforeDeselect");this.deselectEvent=new YAHOO.util.CustomEvent("deselect");this.changePageEvent=new YAHOO.util.CustomEvent("changePage");this.beforeRenderEvent=new YAHOO.util.CustomEvent("beforeRender");this.renderEvent=new YAHOO.util.CustomEvent("render");this.resetEvent=new YAHOO.util.CustomEvent("reset");this.clearEvent=new YAHOO.util.CustomEvent("clear");this.beforeSelectEvent.subscribe(this.onBeforeSelect,this,true);this.selectEvent.subscribe(this.onSelect,this,true);this.beforeDeselectEvent.subscribe(this.onBeforeDeselect,this,true);this.deselectEvent.subscribe(this.onDeselect,this,true);this.changePageEvent.subscribe(this.onChangePage,this,true);this.renderEvent.subscribe(this.onRender,this,true);this.resetEvent.subscribe(this.onReset,this,true);this.clearEvent.subscribe(this.onClear,this,true);};YAHOO.widget.Calendar.prototype.doSelectCell=function(e,cal){var target=YAHOO.util.Event.getTarget(e);var cell,index,d,date;while(target.tagName.toLowerCase()!="td"&&!YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} +cell=target;if(YAHOO.util.Dom.hasClass(cell,cal.Style.CSS_CELL_SELECTABLE)){index=cell.id.split("cell")[1];d=cal.cellDates[index];date=new Date(d[0],d[1]-1,d[2]);var link;if(cal.Options.MULTI_SELECT){link=cell.getElementsByTagName("a")[0];if(link){link.blur();} +var cellDate=cal.cellDates[index];var cellDateIndex=cal._indexOfSelectedFieldArray(cellDate);if(cellDateIndex>-1){cal.deselectCell(index);}else{cal.selectCell(index);}}else{link=cell.getElementsByTagName("a")[0];if(link){link.blur();} +cal.selectCell(index);}}};YAHOO.widget.Calendar.prototype.doCellMouseOver=function(e,cal){var target;if(e){target=YAHOO.util.Event.getTarget(e);}else{target=this;} +while(target.tagName.toLowerCase()!="td"){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} +if(YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){YAHOO.util.Dom.addClass(target,cal.Style.CSS_CELL_HOVER);}};YAHOO.widget.Calendar.prototype.doCellMouseOut=function(e,cal){var target;if(e){target=YAHOO.util.Event.getTarget(e);}else{target=this;} +while(target.tagName.toLowerCase()!="td"){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} +if(YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){YAHOO.util.Dom.removeClass(target,cal.Style.CSS_CELL_HOVER);}};YAHOO.widget.Calendar.prototype.setupConfig=function(){this.cfg.addProperty("pagedate",{value:new Date(),handler:this.configPageDate});this.cfg.addProperty("selected",{value:[],handler:this.configSelected});this.cfg.addProperty("title",{value:"",handler:this.configTitle});this.cfg.addProperty("close",{value:false,handler:this.configClose});this.cfg.addProperty("iframe",{value:true,handler:this.configIframe,validator:this.cfg.checkBoolean});this.cfg.addProperty("mindate",{value:null,handler:this.configMinDate});this.cfg.addProperty("maxdate",{value:null,handler:this.configMaxDate});this.cfg.addProperty("MULTI_SELECT",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("START_WEEKDAY",{value:0,handler:this.configOptions,validator:this.cfg.checkNumber});this.cfg.addProperty("SHOW_WEEKDAYS",{value:true,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_HEADER",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_FOOTER",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("HIDE_BLANK_WEEKS",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("NAV_ARROW_LEFT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/callt.gif",handler:this.configOptions});this.cfg.addProperty("NAV_ARROW_RIGHT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/calrt.gif",handler:this.configOptions});this.cfg.addProperty("MONTHS_SHORT",{value:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],handler:this.configLocale});this.cfg.addProperty("MONTHS_LONG",{value:["January","February","March","April","May","June","July","August","September","October","November","December"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_1CHAR",{value:["S","M","T","W","T","F","S"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_SHORT",{value:["Su","Mo","Tu","We","Th","Fr","Sa"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_MEDIUM",{value:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_LONG",{value:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],handler:this.configLocale});var refreshLocale=function(){this.cfg.refireEvent("LOCALE_MONTHS");this.cfg.refireEvent("LOCALE_WEEKDAYS");};this.cfg.subscribeToConfigEvent("START_WEEKDAY",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("MONTHS_SHORT",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("MONTHS_LONG",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG",refreshLocale,this,true);this.cfg.addProperty("LOCALE_MONTHS",{value:"long",handler:this.configLocaleValues});this.cfg.addProperty("LOCALE_WEEKDAYS",{value:"short",handler:this.configLocaleValues});this.cfg.addProperty("DATE_DELIMITER",{value:",",handler:this.configLocale});this.cfg.addProperty("DATE_FIELD_DELIMITER",{value:"/",handler:this.configLocale});this.cfg.addProperty("DATE_RANGE_DELIMITER",{value:"-",handler:this.configLocale});this.cfg.addProperty("MY_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MY_YEAR_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_DAY_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_DAY_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_YEAR_POSITION",{value:3,handler:this.configLocale,validator:this.cfg.checkNumber});};YAHOO.widget.Calendar.prototype.configPageDate=function(type,args,obj){var val=args[0];var month,year,aMonthYear;if(val){if(val instanceof Date){val=YAHOO.widget.DateMath.findMonthStart(val);this.cfg.setProperty("pagedate",val,true);if(!this._pageDate){this._pageDate=this.cfg.getProperty("pagedate");} +return;}else{aMonthYear=val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER"));month=parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1],10)-1;year=parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1],10);}}else{month=this.today.getMonth();year=this.today.getFullYear();} +this.cfg.setProperty("pagedate",new Date(year,month,1),true);if(!this._pageDate){this._pageDate=this.cfg.getProperty("pagedate");}};YAHOO.widget.Calendar.prototype.configMinDate=function(type,args,obj){var val=args[0];if(typeof val=='string'){val=this._parseDate(val);this.cfg.setProperty("mindate",new Date(val[0],(val[1]-1),val[2]));}};YAHOO.widget.Calendar.prototype.configMaxDate=function(type,args,obj){var val=args[0];if(typeof val=='string'){val=this._parseDate(val);this.cfg.setProperty("maxdate",new Date(val[0],(val[1]-1),val[2]));}};YAHOO.widget.Calendar.prototype.configSelected=function(type,args,obj){var selected=args[0];if(selected){if(typeof selected=='string'){this.cfg.setProperty("selected",this._parseDates(selected),true);}} +if(!this._selectedDates){this._selectedDates=this.cfg.getProperty("selected");}};YAHOO.widget.Calendar.prototype.configOptions=function(type,args,obj){type=type.toUpperCase();var val=args[0];this.Options[type]=val;};YAHOO.widget.Calendar.prototype.configLocale=function(type,args,obj){type=type.toUpperCase();var val=args[0];this.Locale[type]=val;this.cfg.refireEvent("LOCALE_MONTHS");this.cfg.refireEvent("LOCALE_WEEKDAYS");};YAHOO.widget.Calendar.prototype.configLocaleValues=function(type,args,obj){type=type.toUpperCase();var val=args[0];switch(type){case"LOCALE_MONTHS":switch(val){case"short":this.Locale.LOCALE_MONTHS=this.cfg.getProperty("MONTHS_SHORT").concat();break;case"long":this.Locale.LOCALE_MONTHS=this.cfg.getProperty("MONTHS_LONG").concat();break;} +break;case"LOCALE_WEEKDAYS":switch(val){case"1char":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_1CHAR").concat();break;case"short":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_SHORT").concat();break;case"medium":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_MEDIUM").concat();break;case"long":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_LONG").concat();break;} +var START_WEEKDAY=this.cfg.getProperty("START_WEEKDAY");if(START_WEEKDAY>0){for(var w=0;w';html[html.length]='
';var renderLeft,renderRight=false;if(this.parent){if(this.index===0){renderLeft=true;} +if(this.index==(this.parent.cfg.getProperty("pages")-1)){renderRight=true;}}else{renderLeft=true;renderRight=true;} +var cal=this.parent||this;if(renderLeft){html[html.length]=' ';} +html[html.length]=this.buildMonthLabel();if(renderRight){html[html.length]=' ';} +html[html.length]='
';html[html.length]='';html[html.length]='';if(this.cfg.getProperty("SHOW_WEEKDAYS")){html=this.buildWeekdays(html);} +html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.buildWeekdays=function(html){html[html.length]='';if(this.cfg.getProperty("SHOW_WEEK_HEADER")){html[html.length]=' ';} +for(var i=0;i'+this.Locale.LOCALE_WEEKDAYS[i]+'';} +if(this.cfg.getProperty("SHOW_WEEK_FOOTER")){html[html.length]=' ';} +html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.renderBody=function(workingDate,html){var startDay=this.cfg.getProperty("START_WEEKDAY");this.preMonthDays=workingDate.getDay();if(startDay>0){this.preMonthDays-=startDay;} +if(this.preMonthDays<0){this.preMonthDays+=7;} +this.monthDays=YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate();this.postMonthDays=YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays;workingDate=YAHOO.widget.DateMath.subtract(workingDate,YAHOO.widget.DateMath.DAY,this.preMonthDays);var useDate,weekNum,weekClass;useDate=this.cfg.getProperty("pagedate");html[html.length]='';var i=0;var tempDiv=document.createElement("div");var cell=document.createElement("td");tempDiv.appendChild(cell);var jan1=new Date(useDate.getFullYear(),0,1);var cal=this.parent||this;for(var r=0;r<6;r++){weekNum=YAHOO.widget.DateMath.getWeekNumber(workingDate,useDate.getFullYear(),startDay);weekClass="w"+weekNum;if(r!==0&&this.isDateOOM(workingDate)&&this.cfg.getProperty("HIDE_BLANK_WEEKS")===true){break;}else{html[html.length]='';if(this.cfg.getProperty("SHOW_WEEK_HEADER")){html=this.renderRowHeader(weekNum,html);} +for(var d=0;d<7;d++){var cellRenderers=[];this.clearElement(cell);YAHOO.util.Dom.addClass(cell,"calcell");cell.id=this.id+"_cell"+i;cell.innerHTML=i;var renderer=null;if(workingDate.getFullYear()==this.today.getFullYear()&&workingDate.getMonth()==this.today.getMonth()&&workingDate.getDate()==this.today.getDate()){cellRenderers[cellRenderers.length]=cal.renderCellStyleToday;} +this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()];if(this.isDateOOM(workingDate)){cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth;}else{YAHOO.util.Dom.addClass(cell,"wd"+workingDate.getDay());YAHOO.util.Dom.addClass(cell,"d"+workingDate.getDate());for(var s=0;s=d1.getTime()&&workingDate.getTime()<=d2.getTime()){renderer=rArray[2];if(workingDate.getTime()==d2.getTime()){this.renderStack.splice(s,1);}} +break;case YAHOO.widget.Calendar.WEEKDAY:var weekday=rArray[1][0];if(workingDate.getDay()+1==weekday){renderer=rArray[2];} +break;case YAHOO.widget.Calendar.MONTH:month=rArray[1][0];if(workingDate.getMonth()+1==month){renderer=rArray[2];} +break;} +if(renderer){cellRenderers[cellRenderers.length]=renderer;}}} +if(this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()])>-1){cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected;} +var mindate=this.cfg.getProperty("mindate");var maxdate=this.cfg.getProperty("maxdate");if(mindate){mindate=YAHOO.widget.DateMath.clearTime(mindate);} +if(maxdate){maxdate=YAHOO.widget.DateMath.clearTime(maxdate);} +if((mindate&&(workingDate.getTime()maxdate.getTime()))){cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate;}else{cellRenderers[cellRenderers.length]=cal.styleCellDefault;cellRenderers[cellRenderers.length]=cal.renderCellDefault;} +for(var x=0;x=0&&i<=6){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_TOP);} +if((i%7)===0){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_LEFT);} +if(((i+1)%7)===0){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_RIGHT);} +var postDays=this.postMonthDays;if(postDays>=7&&this.cfg.getProperty("HIDE_BLANK_WEEKS")){var blankWeeks=Math.floor(postDays/7);for(var p=0;p=((this.preMonthDays+postDays+this.monthDays)-7)){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_BOTTOM);} +html[html.length]=tempDiv.innerHTML;i++;} +if(this.cfg.getProperty("SHOW_WEEK_FOOTER")){html=this.renderRowFooter(weekNum,html);} +html[html.length]='';}} +html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.renderFooter=function(html){return html;};YAHOO.widget.Calendar.prototype.render=function(){this.beforeRenderEvent.fire();var workingDate=YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate"));this.resetRenderers();this.cellDates.length=0;YAHOO.util.Event.purgeElement(this.oDomContainer,true);var html=[];html[html.length]='';html=this.renderHeader(html);html=this.renderBody(workingDate,html);html=this.renderFooter(html);html[html.length]='
';this.oDomContainer.innerHTML=html.join("\n");this.applyListeners();this.cells=this.oDomContainer.getElementsByTagName("td");this.cfg.refireEvent("title");this.cfg.refireEvent("close");this.cfg.refireEvent("iframe");this.renderEvent.fire();};YAHOO.widget.Calendar.prototype.applyListeners=function(){var root=this.oDomContainer;var cal=this.parent||this;var linkLeft,linkRight;linkLeft=YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT,"a",root);linkRight=YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT,"a",root);if(linkLeft){this.linkLeft=linkLeft[0];YAHOO.util.Event.addListener(this.linkLeft,"mousedown",cal.previousMonth,cal,true);} +if(linkRight){this.linkRight=linkRight[0];YAHOO.util.Event.addListener(this.linkRight,"mousedown",cal.nextMonth,cal,true);} +if(this.domEventMap){var el,elements;for(var cls in this.domEventMap){if(this.domEventMap.hasOwnProperty(cls)){var items=this.domEventMap[cls];if(!(items instanceof Array)){items=[items];} +for(var i=0;i'+weekNum+'';return html;};YAHOO.widget.Calendar.prototype.renderRowFooter=function(weekNum,html){html[html.length]=''+weekNum+'';return html;};YAHOO.widget.Calendar.prototype.renderCellDefault=function(workingDate,cell){cell.innerHTML=''+this.buildDayLabel(workingDate)+"";};YAHOO.widget.Calendar.prototype.styleCellDefault=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_SELECTABLE);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT1);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT2);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT3);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT4);};YAHOO.widget.Calendar.prototype.renderCellStyleToday=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_TODAY);};YAHOO.widget.Calendar.prototype.renderCellStyleSelected=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_SELECTED);};YAHOO.widget.Calendar.prototype.renderCellNotThisMonth=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_OOM);cell.innerHTML=workingDate.getDate();return YAHOO.widget.Calendar.STOP_RENDER;};YAHOO.widget.Calendar.prototype.renderBodyCellRestricted=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL);YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_RESTRICTED);cell.innerHTML=workingDate.getDate();return YAHOO.widget.Calendar.STOP_RENDER;};YAHOO.widget.Calendar.prototype.addMonths=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.MONTH,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.subtractMonths=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.MONTH,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.addYears=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.YEAR,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.subtractYears=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.YEAR,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.nextMonth=function(){this.addMonths(1);};YAHOO.widget.Calendar.prototype.previousMonth=function(){this.subtractMonths(1);};YAHOO.widget.Calendar.prototype.nextYear=function(){this.addYears(1);};YAHOO.widget.Calendar.prototype.previousYear=function(){this.subtractYears(1);};YAHOO.widget.Calendar.prototype.reset=function(){this.cfg.resetProperty("selected");this.cfg.resetProperty("pagedate");this.resetEvent.fire();};YAHOO.widget.Calendar.prototype.clear=function(){this.cfg.setProperty("selected",[]);this.cfg.setProperty("pagedate",new Date(this.today.getTime()));this.clearEvent.fire();};YAHOO.widget.Calendar.prototype.select=function(date){this.beforeSelectEvent.fire();var selected=this.cfg.getProperty("selected");var aToBeSelected=this._toFieldArray(date);for(var a=0;a-1){if(this.cfg.getProperty("pagedate").getMonth()==dCellDate.getMonth()&&this.cfg.getProperty("pagedate").getFullYear()==dCellDate.getFullYear()){YAHOO.util.Dom.removeClass(cell,this.Style.CSS_CELL_SELECTED);} +selected.splice(cellDateIndex,1);} +if(this.parent){this.parent.cfg.setProperty("selected",selected);}else{this.cfg.setProperty("selected",selected);} +this.deselectEvent.fire(selectDate);return this.getSelectedDates();};YAHOO.widget.Calendar.prototype.deselectAll=function(){this.beforeDeselectEvent.fire();var selected=this.cfg.getProperty("selected");var count=selected.length;var sel=selected.concat();if(this.parent){this.parent.cfg.setProperty("selected",[]);}else{this.cfg.setProperty("selected",[]);} +if(count>0){this.deselectEvent.fire(sel);} +return this.getSelectedDates();};YAHOO.widget.Calendar.prototype._toFieldArray=function(date){var returnDate=[];if(date instanceof Date){returnDate=[[date.getFullYear(),date.getMonth()+1,date.getDate()]];}else if(typeof date=='string'){returnDate=this._parseDates(date);}else if(date instanceof Array){for(var i=0;i0){this.init(id,containerId,config);}};YAHOO.widget.CalendarGroup.prototype.init=function(id,containerId,config){this.initEvents();this.initStyles();this.pages=[];this.id=id;this.containerId=containerId;this.oDomContainer=document.getElementById(containerId);YAHOO.util.Dom.addClass(this.oDomContainer,YAHOO.widget.CalendarGroup.CSS_CONTAINER);YAHOO.util.Dom.addClass(this.oDomContainer,YAHOO.widget.CalendarGroup.CSS_MULTI_UP);this.cfg=new YAHOO.util.Config(this);this.Options={};this.Locale={};this.setupConfig();if(config){this.cfg.applyConfig(config,true);} +this.cfg.fireQueue();if(this.browser=="opera"){var fixWidth=function(){var startW=this.oDomContainer.offsetWidth;var w=0;for(var p=0;p0){this.oDomContainer.style.width=w+"px";}};this.renderEvent.subscribe(fixWidth,this,true);}};YAHOO.widget.CalendarGroup.prototype.setupConfig=function(){this.cfg.addProperty("pages",{value:2,validator:this.cfg.checkNumber,handler:this.configPages});this.cfg.addProperty("pagedate",{value:new Date(),handler:this.configPageDate});this.cfg.addProperty("selected",{value:[],handler:this.delegateConfig});this.cfg.addProperty("title",{value:"",handler:this.configTitle});this.cfg.addProperty("close",{value:false,handler:this.configClose});this.cfg.addProperty("iframe",{value:true,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("mindate",{value:null,handler:this.delegateConfig});this.cfg.addProperty("maxdate",{value:null,handler:this.delegateConfig});this.cfg.addProperty("MULTI_SELECT",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("START_WEEKDAY",{value:0,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("SHOW_WEEKDAYS",{value:true,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_HEADER",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_FOOTER",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("HIDE_BLANK_WEEKS",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("NAV_ARROW_LEFT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/callt.gif",handler:this.delegateConfig});this.cfg.addProperty("NAV_ARROW_RIGHT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/calrt.gif",handler:this.delegateConfig});this.cfg.addProperty("MONTHS_SHORT",{value:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],handler:this.delegateConfig});this.cfg.addProperty("MONTHS_LONG",{value:["January","February","March","April","May","June","July","August","September","October","November","December"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_1CHAR",{value:["S","M","T","W","T","F","S"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_SHORT",{value:["Su","Mo","Tu","We","Th","Fr","Sa"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_MEDIUM",{value:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_LONG",{value:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],handler:this.delegateConfig});this.cfg.addProperty("LOCALE_MONTHS",{value:"long",handler:this.delegateConfig});this.cfg.addProperty("LOCALE_WEEKDAYS",{value:"short",handler:this.delegateConfig});this.cfg.addProperty("DATE_DELIMITER",{value:",",handler:this.delegateConfig});this.cfg.addProperty("DATE_FIELD_DELIMITER",{value:"/",handler:this.delegateConfig});this.cfg.addProperty("DATE_RANGE_DELIMITER",{value:"-",handler:this.delegateConfig});this.cfg.addProperty("MY_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MY_YEAR_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_DAY_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_DAY_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_YEAR_POSITION",{value:3,handler:this.delegateConfig,validator:this.cfg.checkNumber});};YAHOO.widget.CalendarGroup.prototype.initEvents=function(){var me=this;var sub=function(fn,obj,bOverride){for(var p=0;p0){year+=1;} +cal.setYear(year);}};YAHOO.widget.CalendarGroup.prototype.render=function(){this.renderHeader();for(var p=0;p=0;--p){var cal=this.pages[p];cal.previousMonth();}};YAHOO.widget.CalendarGroup.prototype.nextYear=function(){for(var p=0;p 11) { - while (newMonth > 11) { - newMonth -= 12; - years += 1; - } - } - - d.setMonth(newMonth); - d.setFullYear(date.getFullYear() + years); - break; - case this.DAY: - d.setDate(date.getDate() + amount); - break; - case this.YEAR: - d.setFullYear(date.getFullYear() + amount); - break; - case this.WEEK: - d.setDate(date.getDate() + (amount * 7)); - break; - } - return d; - }, - - /** - * Subtracts the specified amount of time from the this instance. - * @method subtract - * @param {Date} date The JavaScript Date object to perform subtraction on - * @param {Number} field The this field constant to be used for performing subtraction. - * @param {Number} amount The number of units (measured in the field constant) to subtract from the date. - * @return {Date} The resulting Date object - */ - subtract : function(date, field, amount) { - return this.add(date, field, (amount*-1)); - }, - - /** - * Determines whether a given date is before another date on the calendar. - * @method before - * @param {Date} date The Date object to compare with the compare argument - * @param {Date} compareTo The Date object to use for the comparison - * @return {Boolean} true if the date occurs before the compared date; false if not. - */ - before : function(date, compareTo) { - var ms = compareTo.getTime(); - if (date.getTime() < ms) { - return true; - } else { - return false; - } - }, - - /** - * Determines whether a given date is after another date on the calendar. - * @method after - * @param {Date} date The Date object to compare with the compare argument - * @param {Date} compareTo The Date object to use for the comparison - * @return {Boolean} true if the date occurs after the compared date; false if not. - */ - after : function(date, compareTo) { - var ms = compareTo.getTime(); - if (date.getTime() > ms) { - return true; - } else { - return false; - } - }, - - /** - * Determines whether a given date is between two other dates on the calendar. - * @method between - * @param {Date} date The date to check for - * @param {Date} dateBegin The start of the range - * @param {Date} dateEnd The end of the range - * @return {Boolean} true if the date occurs between the compared dates; false if not. - */ - between : function(date, dateBegin, dateEnd) { - if (this.after(date, dateBegin) && this.before(date, dateEnd)) { - return true; - } else { - return false; - } - }, - - /** - * Retrieves a JavaScript Date object representing January 1 of any given year. - * @method getJan1 - * @param {Number} calendarYear The calendar year for which to retrieve January 1 - * @return {Date} January 1 of the calendar year specified. - */ - getJan1 : function(calendarYear) { - return new Date(calendarYear,0,1); - }, - - /** - * Calculates the number of days the specified date is from January 1 of the specified calendar year. - * Passing January 1 to this function would return an offset value of zero. - * @method getDayOffset - * @param {Date} date The JavaScript date for which to find the offset - * @param {Number} calendarYear The calendar year to use for determining the offset - * @return {Number} The number of days since January 1 of the given year - */ - getDayOffset : function(date, calendarYear) { - var beginYear = this.getJan1(calendarYear); // Find the start of the year. This will be in week 1. - - // Find the number of days the passed in date is away from the calendar year start - var dayOffset = Math.ceil((date.getTime()-beginYear.getTime()) / this.ONE_DAY_MS); - return dayOffset; - }, - - /** - * Calculates the week number for the given date. This function assumes that week 1 is the - * week in which January 1 appears, regardless of whether the week consists of a full 7 days. - * The calendar year can be specified to help find what a the week number would be for a given - * date if the date overlaps years. For instance, a week may be considered week 1 of 2005, or - * week 53 of 2004. Specifying the optional calendarYear allows one to make this distinction - * easily. - * @method getWeekNumber - * @param {Date} date The JavaScript date for which to find the week number - * @param {Number} calendarYear OPTIONAL - The calendar year to use for determining the week number. Default is - * the calendar year of parameter "date". - * @param {Number} weekStartsOn OPTIONAL - The integer (0-6) representing which day a week begins on. Default is 0 (for Sunday). - * @return {Number} The week number of the given date. - */ - getWeekNumber : function(date, calendarYear) { - date = this.clearTime(date); - var nearestThurs = new Date(date.getTime() + (4 * this.ONE_DAY_MS) - ((date.getDay()) * this.ONE_DAY_MS)); - - var jan1 = new Date(nearestThurs.getFullYear(),0,1); - var dayOfYear = ((nearestThurs.getTime() - jan1.getTime()) / this.ONE_DAY_MS) - 1; - - var weekNum = Math.ceil((dayOfYear)/ 7); - return weekNum; - }, - - /** - * Determines if a given week overlaps two different years. - * @method isYearOverlapWeek - * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. - * @return {Boolean} true if the date overlaps two different years. - */ - isYearOverlapWeek : function(weekBeginDate) { - var overlaps = false; - var nextWeek = this.add(weekBeginDate, this.DAY, 6); - if (nextWeek.getFullYear() != weekBeginDate.getFullYear()) { - overlaps = true; - } - return overlaps; - }, - - /** - * Determines if a given week overlaps two different months. - * @method isMonthOverlapWeek - * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. - * @return {Boolean} true if the date overlaps two different months. - */ - isMonthOverlapWeek : function(weekBeginDate) { - var overlaps = false; - var nextWeek = this.add(weekBeginDate, this.DAY, 6); - if (nextWeek.getMonth() != weekBeginDate.getMonth()) { - overlaps = true; - } - return overlaps; - }, - - /** - * Gets the first day of a month containing a given date. - * @method findMonthStart - * @param {Date} date The JavaScript Date used to calculate the month start - * @return {Date} The JavaScript Date representing the first day of the month - */ - findMonthStart : function(date) { - var start = new Date(date.getFullYear(), date.getMonth(), 1); - return start; - }, - - /** - * Gets the last day of a month containing a given date. - * @method findMonthEnd - * @param {Date} date The JavaScript Date used to calculate the month end - * @return {Date} The JavaScript Date representing the last day of the month - */ - findMonthEnd : function(date) { - var start = this.findMonthStart(date); - var nextMonth = this.add(start, this.MONTH, 1); - var end = this.subtract(nextMonth, this.DAY, 1); - return end; - }, - - /** - * Clears the time fields from a given date, effectively setting the time to midnight. - * @method clearTime - * @param {Date} date The JavaScript Date for which the time fields will be cleared - * @return {Date} The JavaScript Date cleared of all time fields - */ - clearTime : function(date) { - date.setHours(12,0,0,0); - return date; - } -}; - -/** -* The Calendar component is a UI control that enables users to choose one or more dates from a graphical calendar presented in a one-month ("one-up") or two-month ("two-up") interface. Calendars are generated entirely via script and can be navigated without any page refreshes. -* @module calendar -* @title Calendar -* @namespace YAHOO.widget -* @requires yahoo,dom,event -*/ - -/** -* Calendar is the base class for the Calendar widget. In its most basic -* implementation, it has the ability to render a calendar widget on the page -* that can be manipulated to select a single date, move back and forth between -* months and years. -*

To construct the placeholder for the calendar widget, the code is as -* follows: -*

-* <div id="cal1Container"></div> -* -* Note that the table can be replaced with any kind of element. -*

-* @namespace YAHOO.widget -* @class Calendar -* @constructor -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.Calendar = function(id, containerId, config) { - this.init(id, containerId, config); -}; - -/** -* The path to be used for images loaded for the Calendar -* @property YAHOO.widget.Calendar.IMG_ROOT -* @static -* @type String -*/ -YAHOO.widget.Calendar.IMG_ROOT = (window.location.href.toLowerCase().indexOf("https") === 0 ? "https://a248.e.akamai.net/sec.yimg.com/i/" : "http://us.i1.yimg.com/us.yimg.com/i/"); - -/** -* Type constant used for renderers to represent an individual date (M/D/Y) -* @property YAHOO.widget.Calendar.DATE -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.DATE = "D"; - -/** -* Type constant used for renderers to represent an individual date across any year (M/D) -* @property YAHOO.widget.Calendar.MONTH_DAY -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.MONTH_DAY = "MD"; - -/** -* Type constant used for renderers to represent a weekday -* @property YAHOO.widget.Calendar.WEEKDAY -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.WEEKDAY = "WD"; - -/** -* Type constant used for renderers to represent a range of individual dates (M/D/Y-M/D/Y) -* @property YAHOO.widget.Calendar.RANGE -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.RANGE = "R"; - -/** -* Type constant used for renderers to represent a month across any year -* @property YAHOO.widget.Calendar.MONTH -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.MONTH = "M"; - -/** -* Constant that represents the total number of date cells that are displayed in a given month -* @property YAHOO.widget.Calendar.DISPLAY_DAYS -* @static -* @final -* @type Number -*/ -YAHOO.widget.Calendar.DISPLAY_DAYS = 42; - -/** -* Constant used for halting the execution of the remainder of the render stack -* @property YAHOO.widget.Calendar.STOP_RENDER -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.STOP_RENDER = "S"; - -YAHOO.widget.Calendar.prototype = { - - /** - * The configuration object used to set up the calendars various locale and style options. - * @property Config - * @private - * @deprecated Configuration properties should be set by calling Calendar.cfg.setProperty. - * @type Object - */ - Config : null, - - /** - * The parent CalendarGroup, only to be set explicitly by the parent group - * @property parent - * @type CalendarGroup - */ - parent : null, - - /** - * The index of this item in the parent group - * @property index - * @type Number - */ - index : -1, - - /** - * The collection of calendar table cells - * @property cells - * @type HTMLTableCellElement[] - */ - cells : null, - - /** - * The collection of calendar cell dates that is parallel to the cells collection. The array contains dates field arrays in the format of [YYYY, M, D]. - * @property cellDates - * @type Array[](Number[]) - */ - cellDates : null, - - /** - * The id that uniquely identifies this calendar. This id should match the id of the placeholder element on the page. - * @property id - * @type String - */ - id : null, - - /** - * The DOM element reference that points to this calendar's container element. The calendar will be inserted into this element when the shell is rendered. - * @property oDomContainer - * @type HTMLElement - */ - oDomContainer : null, - - /** - * A Date object representing today's date. - * @property today - * @type Date - */ - today : null, - - /** - * The list of render functions, along with required parameters, used to render cells. - * @property renderStack - * @type Array[] - */ - renderStack : null, - - /** - * A copy of the initial render functions created before rendering. - * @property _renderStack - * @private - * @type Array - */ - _renderStack : null, - - /** - * A Date object representing the month/year that the calendar is initially set to - * @property _pageDate - * @private - * @type Date - */ - _pageDate : null, - - /** - * The private list of initially selected dates. - * @property _selectedDates - * @private - * @type Array - */ - _selectedDates : null, - - /** - * A map of DOM event handlers to attach to cells associated with specific CSS class names - * @property domEventMap - * @type Object - */ - domEventMap : null -}; - - - -/** -* Initializes the Calendar widget. -* @method init -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.Calendar.prototype.init = function(id, containerId, config) { - this.initEvents(); - this.today = new Date(); - YAHOO.widget.DateMath.clearTime(this.today); - - this.id = id; - this.oDomContainer = document.getElementById(containerId); - - /** - * The Config object used to hold the configuration variables for the Calendar - * @property cfg - * @type YAHOO.util.Config - */ - this.cfg = new YAHOO.util.Config(this); - - /** - * The local object which contains the Calendar's options - * @property Options - * @type Object - */ - this.Options = {}; - - /** - * The local object which contains the Calendar's locale settings - * @property Locale - * @type Object - */ - this.Locale = {}; - - this.initStyles(); - - YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_CONTAINER); - YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_SINGLE); - - this.cellDates = []; - this.cells = []; - this.renderStack = []; - this._renderStack = []; - - this.setupConfig(); - - if (config) { - this.cfg.applyConfig(config, true); - } - - this.cfg.fireQueue(); -}; - -/** -* Renders the built-in IFRAME shim for the IE6 and below -* @method configIframe -*/ -YAHOO.widget.Calendar.prototype.configIframe = function(type, args, obj) { - var useIframe = args[0]; - - if (YAHOO.util.Dom.inDocument(this.oDomContainer)) { - if (useIframe) { - var pos = YAHOO.util.Dom.getStyle(this.oDomContainer, "position"); - - if (this.browser == "ie" && (pos == "absolute" || pos == "relative")) { - if (! YAHOO.util.Dom.inDocument(this.iframe)) { - this.iframe = document.createElement("iframe"); - this.iframe.src = "javascript:false;"; - YAHOO.util.Dom.setStyle(this.iframe, "opacity", "0"); - this.oDomContainer.insertBefore(this.iframe, this.oDomContainer.firstChild); - } - } - } else { - if (this.iframe) { - if (this.iframe.parentNode) { - this.iframe.parentNode.removeChild(this.iframe); - } - this.iframe = null; - } - } - } -}; - -/** -* Default handler for the "title" property -* @method configTitle -*/ -YAHOO.widget.Calendar.prototype.configTitle = function(type, args, obj) { - var title = args[0]; - var close = this.cfg.getProperty("close"); - - var titleDiv; - - if (title && title !== "") { - titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || document.createElement("div"); - titleDiv.className = YAHOO.widget.CalendarGroup.CSS_2UPTITLE; - titleDiv.innerHTML = title; - this.oDomContainer.insertBefore(titleDiv, this.oDomContainer.firstChild); - YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); - } else { - titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || null; - - if (titleDiv) { - YAHOO.util.Event.purgeElement(titleDiv); - this.oDomContainer.removeChild(titleDiv); - } - if (! close) { - YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); - } - } -}; - -/** -* Default handler for the "close" property -* @method configClose -*/ -YAHOO.widget.Calendar.prototype.configClose = function(type, args, obj) { - var close = args[0]; - var title = this.cfg.getProperty("title"); - - var linkClose; - - if (close === true) { - linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || document.createElement("a"); - linkClose.href = "javascript:void(null);"; - linkClose.className = "link-close"; - YAHOO.util.Event.addListener(linkClose, "click", this.hide, this, true); - var imgClose = document.createElement("img"); - imgClose.src = YAHOO.widget.Calendar.IMG_ROOT + "us/my/bn/x_d.gif"; - imgClose.className = YAHOO.widget.CalendarGroup.CSS_2UPCLOSE; - linkClose.appendChild(imgClose); - this.oDomContainer.appendChild(linkClose); - YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); - } else { - linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || null; - - if (linkClose) { - YAHOO.util.Event.purgeElement(linkClose); - this.oDomContainer.removeChild(linkClose); - } - if (! title || title === "") { - YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); - } - } -}; - -/** -* Initializes Calendar's built-in CustomEvents -* @method initEvents -*/ -YAHOO.widget.Calendar.prototype.initEvents = function() { - - /** - * Fired before a selection is made - * @event beforeSelectEvent - */ - this.beforeSelectEvent = new YAHOO.util.CustomEvent("beforeSelect"); - - /** - * Fired when a selection is made - * @event selectEvent - * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. - */ - this.selectEvent = new YAHOO.util.CustomEvent("select"); - - /** - * Fired before a selection is made - * @event beforeDeselectEvent - */ - this.beforeDeselectEvent = new YAHOO.util.CustomEvent("beforeDeselect"); - - /** - * Fired when a selection is made - * @event deselectEvent - * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. - */ - this.deselectEvent = new YAHOO.util.CustomEvent("deselect"); - - /** - * Fired when the Calendar page is changed - * @event changePageEvent - */ - this.changePageEvent = new YAHOO.util.CustomEvent("changePage"); - - /** - * Fired before the Calendar is rendered - * @event beforeRenderEvent - */ - this.beforeRenderEvent = new YAHOO.util.CustomEvent("beforeRender"); - - /** - * Fired when the Calendar is rendered - * @event renderEvent - */ - this.renderEvent = new YAHOO.util.CustomEvent("render"); - - /** - * Fired when the Calendar is reset - * @event resetEvent - */ - this.resetEvent = new YAHOO.util.CustomEvent("reset"); - - /** - * Fired when the Calendar is cleared - * @event clearEvent - */ - this.clearEvent = new YAHOO.util.CustomEvent("clear"); - - this.beforeSelectEvent.subscribe(this.onBeforeSelect, this, true); - this.selectEvent.subscribe(this.onSelect, this, true); - this.beforeDeselectEvent.subscribe(this.onBeforeDeselect, this, true); - this.deselectEvent.subscribe(this.onDeselect, this, true); - this.changePageEvent.subscribe(this.onChangePage, this, true); - this.renderEvent.subscribe(this.onRender, this, true); - this.resetEvent.subscribe(this.onReset, this, true); - this.clearEvent.subscribe(this.onClear, this, true); -}; - - -/** -* The default event function that is attached to a date link within a calendar cell -* when the calendar is rendered. -* @method doSelectCell -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doSelectCell = function(e, cal) { - var target = YAHOO.util.Event.getTarget(e); - - var cell,index,d,date; - - while (target.tagName.toLowerCase() != "td" && ! YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - cell = target; - - if (YAHOO.util.Dom.hasClass(cell, cal.Style.CSS_CELL_SELECTABLE)) { - index = cell.id.split("cell")[1]; - d = cal.cellDates[index]; - date = new Date(d[0],d[1]-1,d[2]); - - var link; - - if (cal.Options.MULTI_SELECT) { - link = cell.getElementsByTagName("a")[0]; - if (link) { - link.blur(); - } - - var cellDate = cal.cellDates[index]; - var cellDateIndex = cal._indexOfSelectedFieldArray(cellDate); - - if (cellDateIndex > -1) { - cal.deselectCell(index); - } else { - cal.selectCell(index); - } - - } else { - link = cell.getElementsByTagName("a")[0]; - if (link) { - link.blur(); - } - cal.selectCell(index); - } - } -}; - -/** -* The event that is executed when the user hovers over a cell -* @method doCellMouseOver -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doCellMouseOver = function(e, cal) { - var target; - if (e) { - target = YAHOO.util.Event.getTarget(e); - } else { - target = this; - } - - while (target.tagName.toLowerCase() != "td") { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - YAHOO.util.Dom.addClass(target, cal.Style.CSS_CELL_HOVER); - } -}; - -/** -* The event that is executed when the user moves the mouse out of a cell -* @method doCellMouseOut -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doCellMouseOut = function(e, cal) { - var target; - if (e) { - target = YAHOO.util.Event.getTarget(e); - } else { - target = this; - } - - while (target.tagName.toLowerCase() != "td") { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - YAHOO.util.Dom.removeClass(target, cal.Style.CSS_CELL_HOVER); - } -}; - -YAHOO.widget.Calendar.prototype.setupConfig = function() { - - /** - * The month/year representing the current visible Calendar date (mm/yyyy) - * @config pagedate - * @type String - * @default today's date - */ - this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); - - /** - * The date or range of dates representing the current Calendar selection - * @config selected - * @type String - * @default [] - */ - this.cfg.addProperty("selected", { value:[], handler:this.configSelected } ); - - /** - * The title to display above the Calendar's month header - * @config title - * @type String - * @default "" - */ - this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); - - /** - * Whether or not a close button should be displayed for this Calendar - * @config close - * @type Boolean - * @default false - */ - this.cfg.addProperty("close", { value:false, handler:this.configClose } ); - - /** - * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. - * @config iframe - * @type Boolean - * @default true - */ - this.cfg.addProperty("iframe", { value:true, handler:this.configIframe, validator:this.cfg.checkBoolean } ); - - /** - * The minimum selectable date in the current Calendar (mm/dd/yyyy) - * @config mindate - * @type String - * @default null - */ - this.cfg.addProperty("mindate", { value:null, handler:this.configMinDate } ); - - /** - * The maximum selectable date in the current Calendar (mm/dd/yyyy) - * @config maxdate - * @type String - * @default null - */ - this.cfg.addProperty("maxdate", { value:null, handler:this.configMaxDate } ); - - - // Options properties - - /** - * True if the Calendar should allow multiple selections. False by default. - * @config MULTI_SELECT - * @type Boolean - * @default false - */ - this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * The weekday the week begins on. Default is 0 (Sunday). - * @config START_WEEKDAY - * @type number - * @default 0 - */ - this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.configOptions, validator:this.cfg.checkNumber } ); - - /** - * True if the Calendar should show weekday labels. True by default. - * @config SHOW_WEEKDAYS - * @type Boolean - * @default true - */ - this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row headers. False by default. - * @config SHOW_WEEK_HEADER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row footers. False by default. - * @config SHOW_WEEK_FOOTER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should suppress weeks that are not a part of the current month. False by default. - * @config HIDE_BLANK_WEEKS - * @type Boolean - * @default false - */ - this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_LEFT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" - */ - this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.configOptions } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_RIGHT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" - */ - this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.configOptions } ); - - // Locale properties - - /** - * The short month labels for the current locale. - * @config MONTHS_SHORT - * @type String[] - * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - */ - this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.configLocale } ); - - /** - * The long month labels for the current locale. - * @config MONTHS_LONG - * @type String[] - * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" - */ - this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.configLocale } ); - - /** - * The 1-character weekday labels for the current locale. - * @config WEEKDAYS_1CHAR - * @type String[] - * @default ["S", "M", "T", "W", "T", "F", "S"] - */ - this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.configLocale } ); - - /** - * The short weekday labels for the current locale. - * @config WEEKDAYS_SHORT - * @type String[] - * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] - */ - this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.configLocale } ); - - /** - * The medium weekday labels for the current locale. - * @config WEEKDAYS_MEDIUM - * @type String[] - * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] - */ - this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.configLocale } ); - - /** - * The long weekday labels for the current locale. - * @config WEEKDAYS_LONG - * @type String[] - * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] - */ - this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.configLocale } ); - - /** - * Refreshes the locale values used to build the Calendar. - * @method refreshLocale - * @private - */ - var refreshLocale = function() { - this.cfg.refireEvent("LOCALE_MONTHS"); - this.cfg.refireEvent("LOCALE_WEEKDAYS"); - }; - - this.cfg.subscribeToConfigEvent("START_WEEKDAY", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("MONTHS_SHORT", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("MONTHS_LONG", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG", refreshLocale, this, true); - - /** - * The setting that determines which length of month labels should be used. Possible values are "short" and "long". - * @config LOCALE_MONTHS - * @type String - * @default "long" - */ - this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.configLocaleValues } ); - - /** - * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". - * @config LOCALE_WEEKDAYS - * @type String - * @default "short" - */ - this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.configLocaleValues } ); - - /** - * The value used to delimit individual dates in a date string passed to various Calendar functions. - * @config DATE_DELIMITER - * @type String - * @default "," - */ - this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.configLocale } ); - - /** - * The value used to delimit date fields in a date string passed to various Calendar functions. - * @config DATE_FIELD_DELIMITER - * @type String - * @default "/" - */ - this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.configLocale } ); - - /** - * The value used to delimit date ranges in a date string passed to various Calendar functions. - * @config DATE_RANGE_DELIMITER - * @type String - * @default "-" - */ - this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.configLocale } ); - - /** - * The position of the month in a month/year date string - * @config MY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/year date string - * @config MY_YEAR_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day date string - * @config MD_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/year date string - * @config MD_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day/year date string - * @config MDY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/day/year date string - * @config MDY_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/day/year date string - * @config MDY_YEAR_POSITION - * @type Number - * @default 3 - */ - this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.configLocale, validator:this.cfg.checkNumber } ); -}; - -/** -* The default handler for the "pagedate" property -* @method configPageDate -*/ -YAHOO.widget.Calendar.prototype.configPageDate = function(type, args, obj) { - var val = args[0]; - var month, year, aMonthYear; - - if (val) { - if (val instanceof Date) { - val = YAHOO.widget.DateMath.findMonthStart(val); - this.cfg.setProperty("pagedate", val, true); - if (! this._pageDate) { - this._pageDate = this.cfg.getProperty("pagedate"); - } - return; - } else { - aMonthYear = val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER")); - month = parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1], 10)-1; - year = parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1], 10); - } - } else { - month = this.today.getMonth(); - year = this.today.getFullYear(); - } - - this.cfg.setProperty("pagedate", new Date(year, month, 1), true); - if (! this._pageDate) { - this._pageDate = this.cfg.getProperty("pagedate"); - } -}; - -/** -* The default handler for the "mindate" property -* @method configMinDate -*/ -YAHOO.widget.Calendar.prototype.configMinDate = function(type, args, obj) { - var val = args[0]; - if (typeof val == 'string') { - val = this._parseDate(val); - this.cfg.setProperty("mindate", new Date(val[0],(val[1]-1),val[2])); - } -}; - -/** -* The default handler for the "maxdate" property -* @method configMaxDate -*/ -YAHOO.widget.Calendar.prototype.configMaxDate = function(type, args, obj) { - var val = args[0]; - if (typeof val == 'string') { - val = this._parseDate(val); - this.cfg.setProperty("maxdate", new Date(val[0],(val[1]-1),val[2])); - } -}; - -/** -* The default handler for the "selected" property -* @method configSelected -*/ -YAHOO.widget.Calendar.prototype.configSelected = function(type, args, obj) { - var selected = args[0]; - - if (selected) { - if (typeof selected == 'string') { - this.cfg.setProperty("selected", this._parseDates(selected), true); - } - } - if (! this._selectedDates) { - this._selectedDates = this.cfg.getProperty("selected"); - } -}; - -/** -* The default handler for all configuration options properties -* @method configOptions -*/ -YAHOO.widget.Calendar.prototype.configOptions = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - this.Options[type] = val; -}; - -/** -* The default handler for all configuration locale properties -* @method configLocale -*/ -YAHOO.widget.Calendar.prototype.configLocale = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - this.Locale[type] = val; - - this.cfg.refireEvent("LOCALE_MONTHS"); - this.cfg.refireEvent("LOCALE_WEEKDAYS"); - -}; - -/** -* The default handler for all configuration locale field length properties -* @method configLocaleValues -*/ -YAHOO.widget.Calendar.prototype.configLocaleValues = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - - switch (type) { - case "LOCALE_MONTHS": - switch (val) { - case "short": - this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_SHORT").concat(); - break; - case "long": - this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_LONG").concat(); - break; - } - break; - case "LOCALE_WEEKDAYS": - switch (val) { - case "1char": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_1CHAR").concat(); - break; - case "short": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_SHORT").concat(); - break; - case "medium": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_MEDIUM").concat(); - break; - case "long": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_LONG").concat(); - break; - } - - var START_WEEKDAY = this.cfg.getProperty("START_WEEKDAY"); - - if (START_WEEKDAY > 0) { - for (var w=0;w'; - html[html.length] = '
'; - - var renderLeft, renderRight = false; - - if (this.parent) { - if (this.index === 0) { - renderLeft = true; - } - if (this.index == (this.parent.cfg.getProperty("pages") -1)) { - renderRight = true; - } - } else { - renderLeft = true; - renderRight = true; - } - - var cal = this.parent || this; - - if (renderLeft) { - html[html.length] = ' '; - } - - html[html.length] = this.buildMonthLabel(); - - if (renderRight) { - html[html.length] = ' '; - } - - - html[html.length] = '
'; - html[html.length] = ''; - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEKDAYS")) { - html = this.buildWeekdays(html); - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the Calendar's weekday headers. -* @method buildWeekdays -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.buildWeekdays = function(html) { - - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { - html[html.length] = ' '; - } - - for(var i=0;i'; - } - - if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { - html[html.length] = ' '; - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the calendar body. -* @method renderBody -* @param {Date} workingDate The current working Date being used for the render process -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderBody = function(workingDate, html) { - - var startDay = this.cfg.getProperty("START_WEEKDAY"); - - this.preMonthDays = workingDate.getDay(); - if (startDay > 0) { - this.preMonthDays -= startDay; - } - if (this.preMonthDays < 0) { - this.preMonthDays += 7; - } - - this.monthDays = YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate(); - this.postMonthDays = YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays; - - workingDate = YAHOO.widget.DateMath.subtract(workingDate, YAHOO.widget.DateMath.DAY, this.preMonthDays); - - var useDate,weekNum,weekClass; - useDate = this.cfg.getProperty("pagedate"); - - html[html.length] = ''; - - var i = 0; - - var tempDiv = document.createElement("div"); - var cell = document.createElement("td"); - tempDiv.appendChild(cell); - - var jan1 = new Date(useDate.getFullYear(),0,1); - - var cal = this.parent || this; - - for (var r=0;r<6;r++) { - - weekNum = YAHOO.widget.DateMath.getWeekNumber(workingDate, useDate.getFullYear(), startDay); - - weekClass = "w" + weekNum; - - if (r !== 0 && this.isDateOOM(workingDate) && this.cfg.getProperty("HIDE_BLANK_WEEKS") === true) { - break; - } else { - - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { html = this.renderRowHeader(weekNum, html); } - - for (var d=0;d<7;d++){ // Render actual days - - var cellRenderers = []; - - this.clearElement(cell); - - YAHOO.util.Dom.addClass(cell, "calcell"); - - cell.id = this.id + "_cell" + i; - - cell.innerHTML = i; - - var renderer = null; - - if (workingDate.getFullYear() == this.today.getFullYear() && - workingDate.getMonth() == this.today.getMonth() && - workingDate.getDate() == this.today.getDate()) { - cellRenderers[cellRenderers.length]=cal.renderCellStyleToday; - } - - this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]; // Add this date to cellDates - - if (this.isDateOOM(workingDate)) { - cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth; - } else { - - YAHOO.util.Dom.addClass(cell, "wd" + workingDate.getDay()); - YAHOO.util.Dom.addClass(cell, "d" + workingDate.getDate()); - - for (var s=0;s= d1.getTime() && workingDate.getTime() <= d2.getTime()) { - renderer = rArray[2]; - - if (workingDate.getTime()==d2.getTime()) { - this.renderStack.splice(s,1); - } - } - break; - case YAHOO.widget.Calendar.WEEKDAY: - - var weekday = rArray[1][0]; - if (workingDate.getDay()+1 == weekday) { - renderer = rArray[2]; - } - break; - case YAHOO.widget.Calendar.MONTH: - - month = rArray[1][0]; - if (workingDate.getMonth()+1 == month) { - renderer = rArray[2]; - } - break; - } - - if (renderer) { - cellRenderers[cellRenderers.length]=renderer; - } - } - - } - - if (this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]) > -1) { - cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected; - } - - var mindate = this.cfg.getProperty("mindate"); - var maxdate = this.cfg.getProperty("maxdate"); - - if (mindate) { - mindate = YAHOO.widget.DateMath.clearTime(mindate); - } - if (maxdate) { - maxdate = YAHOO.widget.DateMath.clearTime(maxdate); - } - - if ( - (mindate && (workingDate.getTime() < mindate.getTime())) || - (maxdate && (workingDate.getTime() > maxdate.getTime())) - ) { - cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate; - } else { - cellRenderers[cellRenderers.length]=cal.styleCellDefault; - cellRenderers[cellRenderers.length]=cal.renderCellDefault; - } - - - - for (var x=0;x= 0 && i <= 6) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TOP); - } - if ((i % 7) === 0) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_LEFT); - } - if (((i+1) % 7) === 0) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RIGHT); - } - - var postDays = this.postMonthDays; - if (postDays >= 7 && this.cfg.getProperty("HIDE_BLANK_WEEKS")) { - var blankWeeks = Math.floor(postDays/7); - for (var p=0;p= ((this.preMonthDays+postDays+this.monthDays)-7)) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_BOTTOM); - } - - html[html.length] = tempDiv.innerHTML; - - i++; - } - - if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { html = this.renderRowFooter(weekNum, html); } - - html[html.length] = ''; - } - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the calendar footer. In the default implementation, there is -* no footer. -* @method renderFooter -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderFooter = function(html) { return html; }; - -/** -* Renders the calendar after it has been configured. The render() method has a specific call chain that will execute -* when the method is called: renderHeader, renderBody, renderFooter. -* Refer to the documentation for those methods for information on -* individual render tasks. -* @method render -*/ -YAHOO.widget.Calendar.prototype.render = function() { - this.beforeRenderEvent.fire(); - - // Find starting day of the current month - var workingDate = YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate")); - - this.resetRenderers(); - this.cellDates.length = 0; - - YAHOO.util.Event.purgeElement(this.oDomContainer, true); - - var html = []; - - html[html.length] = ''; - html = this.renderHeader(html); - html = this.renderBody(workingDate, html); - html = this.renderFooter(html); - html[html.length] = '
'; - - this.oDomContainer.innerHTML = html.join("\n"); - - this.applyListeners(); - this.cells = this.oDomContainer.getElementsByTagName("td"); - - this.cfg.refireEvent("title"); - this.cfg.refireEvent("close"); - this.cfg.refireEvent("iframe"); - - this.renderEvent.fire(); -}; - -/** -* Applies the Calendar's DOM listeners to applicable elements. -* @method applyListeners -*/ -YAHOO.widget.Calendar.prototype.applyListeners = function() { - - var root = this.oDomContainer; - var cal = this.parent || this; - - var linkLeft, linkRight; - - linkLeft = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT, "a", root); - linkRight = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT, "a", root); - - if (linkLeft) { - this.linkLeft = linkLeft[0]; - YAHOO.util.Event.addListener(this.linkLeft, "mousedown", cal.previousMonth, cal, true); - } - - if (linkRight) { - this.linkRight = linkRight[0]; - YAHOO.util.Event.addListener(this.linkRight, "mousedown", cal.nextMonth, cal, true); - } - - if (this.domEventMap) { - var el,elements; - for (var cls in this.domEventMap) { - if (this.domEventMap.hasOwnProperty(cls)) { - var items = this.domEventMap[cls]; - - if (! (items instanceof Array)) { - items = [items]; - } - - for (var i=0;i'; - return html; -}; - -/** -* Renders the row footer for a week. -* @method renderRowFooter -* @param {Number} weekNum The week number of the current row -* @param {Array} cell The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderRowFooter = function(weekNum, html) { - html[html.length] = '' + weekNum + ''; - return html; -}; - -/** -* Renders a single standard calendar cell in the calendar widget table. -* All logic for determining how a standard default cell will be rendered is -* encapsulated in this method, and must be accounted for when extending the -* widget class. -* @method renderCellDefault -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellDefault = function(workingDate, cell) { - cell.innerHTML = '' + this.buildDayLabel(workingDate) + ""; -}; - -/** -* Styles a selectable cell. -* @method styleCellDefault -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.styleCellDefault = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTABLE); -}; - - -/** -* Renders a single standard calendar cell using the CSS hightlight1 style -* @method renderCellStyleHighlight1 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT1); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight2 style -* @method renderCellStyleHighlight2 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT2); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight3 style -* @method renderCellStyleHighlight3 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT3); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight4 style -* @method renderCellStyleHighlight4 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT4); -}; - -/** -* Applies the default style used for rendering today's date to the current calendar cell -* @method renderCellStyleToday -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleToday = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TODAY); -}; - -/** -* Applies the default style used for rendering selected dates to the current calendar cell -* @method renderCellStyleSelected -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleSelected = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTED); -}; - -/** -* Applies the default style used for rendering dates that are not a part of the current -* month (preceding or trailing the cells for the current month) -* @method renderCellNotThisMonth -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderCellNotThisMonth = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_OOM); - cell.innerHTML=workingDate.getDate(); - return YAHOO.widget.Calendar.STOP_RENDER; -}; - -/** -* Renders the current calendar cell as a non-selectable "black-out" date using the default -* restricted style. -* @method renderBodyCellRestricted -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderBodyCellRestricted = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL); - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RESTRICTED); - cell.innerHTML=workingDate.getDate(); - return YAHOO.widget.Calendar.STOP_RENDER; -}; - -// END BUILT-IN TABLE CELL RENDERERS - -// BEGIN MONTH NAVIGATION METHODS - -/** -* Adds the designated number of months to the current calendar month, and sets the current -* calendar page date to the new month. -* @method addMonths -* @param {Number} count The number of months to add to the current calendar -*/ -YAHOO.widget.Calendar.prototype.addMonths = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Subtracts the designated number of months from the current calendar month, and sets the current -* calendar page date to the new month. -* @method subtractMonths -* @param {Number} count The number of months to subtract from the current calendar -*/ -YAHOO.widget.Calendar.prototype.subtractMonths = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Adds the designated number of years to the current calendar, and sets the current -* calendar page date to the new month. -* @method addYears -* @param {Number} count The number of years to add to the current calendar -*/ -YAHOO.widget.Calendar.prototype.addYears = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Subtcats the designated number of years from the current calendar, and sets the current -* calendar page date to the new month. -* @method subtractYears -* @param {Number} count The number of years to subtract from the current calendar -*/ -YAHOO.widget.Calendar.prototype.subtractYears = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Navigates to the next month page in the calendar widget. -* @method nextMonth -*/ -YAHOO.widget.Calendar.prototype.nextMonth = function() { - this.addMonths(1); -}; - -/** -* Navigates to the previous month page in the calendar widget. -* @method previousMonth -*/ -YAHOO.widget.Calendar.prototype.previousMonth = function() { - this.subtractMonths(1); -}; - -/** -* Navigates to the next year in the currently selected month in the calendar widget. -* @method nextYear -*/ -YAHOO.widget.Calendar.prototype.nextYear = function() { - this.addYears(1); -}; - -/** -* Navigates to the previous year in the currently selected month in the calendar widget. -* @method previousYear -*/ -YAHOO.widget.Calendar.prototype.previousYear = function() { - this.subtractYears(1); -}; - -// END MONTH NAVIGATION METHODS - -// BEGIN SELECTION METHODS - -/** -* Resets the calendar widget to the originally selected month and year, and -* sets the calendar to the initial selection(s). -* @method reset -*/ -YAHOO.widget.Calendar.prototype.reset = function() { - this.cfg.resetProperty("selected"); - this.cfg.resetProperty("pagedate"); - this.resetEvent.fire(); -}; - -/** -* Clears the selected dates in the current calendar widget and sets the calendar -* to the current month and year. -* @method clear -*/ -YAHOO.widget.Calendar.prototype.clear = function() { - this.cfg.setProperty("selected", []); - this.cfg.setProperty("pagedate", new Date(this.today.getTime())); - this.clearEvent.fire(); -}; - -/** -* Selects a date or a collection of dates on the current calendar. This method, by default, -* does not call the render method explicitly. Once selection has completed, render must be -* called for the changes to be reflected visually. -* @method select -* @param {String/Date/Date[]} date The date string of dates to select in the current calendar. Valid formats are -* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). -* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). -* This method can also take a JavaScript Date object or an array of Date objects. -* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. -*/ -YAHOO.widget.Calendar.prototype.select = function(date) { - this.beforeSelectEvent.fire(); - - var selected = this.cfg.getProperty("selected"); - var aToBeSelected = this._toFieldArray(date); - - for (var a=0;a -1) { - if (this.cfg.getProperty("pagedate").getMonth() == dCellDate.getMonth() && - this.cfg.getProperty("pagedate").getFullYear() == dCellDate.getFullYear()) { - YAHOO.util.Dom.removeClass(cell, this.Style.CSS_CELL_SELECTED); - } - - selected.splice(cellDateIndex, 1); - } - - - if (this.parent) { - this.parent.cfg.setProperty("selected", selected); - } else { - this.cfg.setProperty("selected", selected); - } - - this.deselectEvent.fire(selectDate); - return this.getSelectedDates(); -}; - -/** -* Deselects all dates on the current calendar. -* @method deselectAll -* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. -* Assuming that this function executes properly, the return value should be an empty array. -* However, the empty array is returned for the sake of being able to check the selection status -* of the calendar. -*/ -YAHOO.widget.Calendar.prototype.deselectAll = function() { - this.beforeDeselectEvent.fire(); - - var selected = this.cfg.getProperty("selected"); - var count = selected.length; - var sel = selected.concat(); - - if (this.parent) { - this.parent.cfg.setProperty("selected", []); - } else { - this.cfg.setProperty("selected", []); - } - - if (count > 0) { - this.deselectEvent.fire(sel); - } - - return this.getSelectedDates(); -}; - -// END SELECTION METHODS - -// BEGIN TYPE CONVERSION METHODS - -/** -* Converts a date (either a JavaScript Date object, or a date string) to the internal data structure -* used to represent dates: [[yyyy,mm,dd],[yyyy,mm,dd]]. -* @method _toFieldArray -* @private -* @param {String/Date/Date[]} date The date string of dates to deselect in the current calendar. Valid formats are -* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). -* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). -* This method can also take a JavaScript Date object or an array of Date objects. -* @return {Array[](Number[])} Array of date field arrays -*/ -YAHOO.widget.Calendar.prototype._toFieldArray = function(date) { - var returnDate = []; - - if (date instanceof Date) { - returnDate = [[date.getFullYear(), date.getMonth()+1, date.getDate()]]; - } else if (typeof date == 'string') { - returnDate = this._parseDates(date); - } else if (date instanceof Array) { - for (var i=0;i -*
-*
-* -* The tables for the calendars ("cal1_0" and "cal1_1") will be inserted into those containers. -* @namespace YAHOO.widget -* @class CalendarGroup -* @constructor -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.CalendarGroup = function(id, containerId, config) { - if (arguments.length > 0) { - this.init(id, containerId, config); - } -}; - -/** -* Initializes the calendar group. All subclasses must call this method in order for the -* group to be initialized properly. -* @method init -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.CalendarGroup.prototype.init = function(id, containerId, config) { - this.initEvents(); - this.initStyles(); - - /** - * The collection of Calendar pages contained within the CalendarGroup - * @property pages - * @type YAHOO.widget.Calendar[] - */ - this.pages = []; - - /** - * The unique id associated with the CalendarGroup - * @property id - * @type String - */ - this.id = id; - - /** - * The unique id associated with the CalendarGroup container - * @property containerId - * @type String - */ - this.containerId = containerId; - - /** - * The outer containing element for the CalendarGroup - * @property oDomContainer - * @type HTMLElement - */ - this.oDomContainer = document.getElementById(containerId); - - YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_CONTAINER); - YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_MULTI_UP); - - /** - * The Config object used to hold the configuration variables for the CalendarGroup - * @property cfg - * @type YAHOO.util.Config - */ - this.cfg = new YAHOO.util.Config(this); - - /** - * The local object which contains the CalendarGroup's options - * @property Options - * @type Object - */ - this.Options = {}; - - /** - * The local object which contains the CalendarGroup's locale settings - * @property Locale - * @type Object - */ - this.Locale = {}; - - this.setupConfig(); - - if (config) { - this.cfg.applyConfig(config, true); - } - - this.cfg.fireQueue(); - - // OPERA HACK FOR MISWRAPPED FLOATS - if (this.browser == "opera"){ - var fixWidth = function() { - var startW = this.oDomContainer.offsetWidth; - var w = 0; - for (var p=0;p 0) { - this.oDomContainer.style.width = w + "px"; - } - }; - this.renderEvent.subscribe(fixWidth,this,true); - } -}; - - -YAHOO.widget.CalendarGroup.prototype.setupConfig = function() { - /** - * The number of pages to include in the CalendarGroup. This value can only be set once, in the CalendarGroup's constructor arguments. - * @config pages - * @type Number - * @default 2 - */ - this.cfg.addProperty("pages", { value:2, validator:this.cfg.checkNumber, handler:this.configPages } ); - - /** - * The month/year representing the current visible Calendar date (mm/yyyy) - * @config pagedate - * @type String - * @default today's date - */ - this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); - - /** - * The date or range of dates representing the current Calendar selection - * @config selected - * @type String - * @default [] - */ - this.cfg.addProperty("selected", { value:[], handler:this.delegateConfig } ); - - /** - * The title to display above the CalendarGroup's month header - * @config title - * @type String - * @default "" - */ - this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); - - /** - * Whether or not a close button should be displayed for this CalendarGroup - * @config close - * @type Boolean - * @default false - */ - this.cfg.addProperty("close", { value:false, handler:this.configClose } ); - - /** - * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. - * @config iframe - * @type Boolean - * @default true - */ - this.cfg.addProperty("iframe", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The minimum selectable date in the current Calendar (mm/dd/yyyy) - * @config mindate - * @type String - * @default null - */ - this.cfg.addProperty("mindate", { value:null, handler:this.delegateConfig } ); - - /** - * The maximum selectable date in the current Calendar (mm/dd/yyyy) - * @config maxdate - * @type String - * @default null - */ - this.cfg.addProperty("maxdate", { value:null, handler:this.delegateConfig } ); - - // Options properties - - /** - * True if the Calendar should allow multiple selections. False by default. - * @config MULTI_SELECT - * @type Boolean - * @default false - */ - this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The weekday the week begins on. Default is 0 (Sunday). - * @config START_WEEKDAY - * @type number - * @default 0 - */ - this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * True if the Calendar should show weekday labels. True by default. - * @config SHOW_WEEKDAYS - * @type Boolean - * @default true - */ - this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row headers. False by default. - * @config SHOW_WEEK_HEADER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row footers. False by default. - * @config SHOW_WEEK_FOOTER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should suppress weeks that are not a part of the current month. False by default. - * @config HIDE_BLANK_WEEKS - * @type Boolean - * @default false - */ - this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_LEFT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" - */ - this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.delegateConfig } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_RIGHT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" - */ - this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.delegateConfig } ); - - // Locale properties - - /** - * The short month labels for the current locale. - * @config MONTHS_SHORT - * @type String[] - * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - */ - this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.delegateConfig } ); - - /** - * The long month labels for the current locale. - * @config MONTHS_LONG - * @type String[] - * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" - */ - this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.delegateConfig } ); - - /** - * The 1-character weekday labels for the current locale. - * @config WEEKDAYS_1CHAR - * @type String[] - * @default ["S", "M", "T", "W", "T", "F", "S"] - */ - this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.delegateConfig } ); - - /** - * The short weekday labels for the current locale. - * @config WEEKDAYS_SHORT - * @type String[] - * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] - */ - this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.delegateConfig } ); - - /** - * The medium weekday labels for the current locale. - * @config WEEKDAYS_MEDIUM - * @type String[] - * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] - */ - this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.delegateConfig } ); - - /** - * The long weekday labels for the current locale. - * @config WEEKDAYS_LONG - * @type String[] - * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] - */ - this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.delegateConfig } ); - - /** - * The setting that determines which length of month labels should be used. Possible values are "short" and "long". - * @config LOCALE_MONTHS - * @type String - * @default "long" - */ - this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.delegateConfig } ); - - /** - * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". - * @config LOCALE_WEEKDAYS - * @type String - * @default "short" - */ - this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.delegateConfig } ); - - /** - * The value used to delimit individual dates in a date string passed to various Calendar functions. - * @config DATE_DELIMITER - * @type String - * @default "," - */ - this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.delegateConfig } ); - - /** - * The value used to delimit date fields in a date string passed to various Calendar functions. - * @config DATE_FIELD_DELIMITER - * @type String - * @default "/" - */ - this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.delegateConfig } ); - - /** - * The value used to delimit date ranges in a date string passed to various Calendar functions. - * @config DATE_RANGE_DELIMITER - * @type String - * @default "-" - */ - this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.delegateConfig } ); - - /** - * The position of the month in a month/year date string - * @config MY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/year date string - * @config MY_YEAR_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day date string - * @config MD_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/year date string - * @config MD_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day/year date string - * @config MDY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/day/year date string - * @config MDY_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/day/year date string - * @config MDY_YEAR_POSITION - * @type Number - * @default 3 - */ - this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - -}; - -/** -* Initializes CalendarGroup's built-in CustomEvents -* @method initEvents -*/ -YAHOO.widget.CalendarGroup.prototype.initEvents = function() { - var me = this; - - /** - * Proxy subscriber to subscribe to the CalendarGroup's child Calendars' CustomEvents - * @method sub - * @private - * @param {Function} fn The function to subscribe to this CustomEvent - * @param {Object} obj The CustomEvent's scope object - * @param {Boolean} bOverride Whether or not to apply scope correction - */ - var sub = function(fn, obj, bOverride) { - for (var p=0;p0) { - year+=1; - } - cal.setYear(year); - } -}; -/** -* Calls the render function of all child calendars within the group. -* @method render -*/ -YAHOO.widget.CalendarGroup.prototype.render = function() { - this.renderHeader(); - for (var p=0;p=0;--p) { - var cal = this.pages[p]; - cal.previousMonth(); - } -}; - -/** -* Navigates to the next year in the currently selected month in the calendar widget. -* @method nextYear -*/ -YAHOO.widget.CalendarGroup.prototype.nextYear = function() { - for (var p=0;p 11) { + while (newMonth > 11) { + newMonth -= 12; + years += 1; + } + } + + d.setMonth(newMonth); + d.setFullYear(date.getFullYear() + years); + break; + case this.DAY: + d.setDate(date.getDate() + amount); + break; + case this.YEAR: + d.setFullYear(date.getFullYear() + amount); + break; + case this.WEEK: + d.setDate(date.getDate() + (amount * 7)); + break; + } + return d; + }, + + /** + * Subtracts the specified amount of time from the this instance. + * @method subtract + * @param {Date} date The JavaScript Date object to perform subtraction on + * @param {Number} field The this field constant to be used for performing subtraction. + * @param {Number} amount The number of units (measured in the field constant) to subtract from the date. + * @return {Date} The resulting Date object + */ + subtract : function(date, field, amount) { + return this.add(date, field, (amount*-1)); + }, + + /** + * Determines whether a given date is before another date on the calendar. + * @method before + * @param {Date} date The Date object to compare with the compare argument + * @param {Date} compareTo The Date object to use for the comparison + * @return {Boolean} true if the date occurs before the compared date; false if not. + */ + before : function(date, compareTo) { + var ms = compareTo.getTime(); + if (date.getTime() < ms) { + return true; + } else { + return false; + } + }, + + /** + * Determines whether a given date is after another date on the calendar. + * @method after + * @param {Date} date The Date object to compare with the compare argument + * @param {Date} compareTo The Date object to use for the comparison + * @return {Boolean} true if the date occurs after the compared date; false if not. + */ + after : function(date, compareTo) { + var ms = compareTo.getTime(); + if (date.getTime() > ms) { + return true; + } else { + return false; + } + }, + + /** + * Determines whether a given date is between two other dates on the calendar. + * @method between + * @param {Date} date The date to check for + * @param {Date} dateBegin The start of the range + * @param {Date} dateEnd The end of the range + * @return {Boolean} true if the date occurs between the compared dates; false if not. + */ + between : function(date, dateBegin, dateEnd) { + if (this.after(date, dateBegin) && this.before(date, dateEnd)) { + return true; + } else { + return false; + } + }, + + /** + * Retrieves a JavaScript Date object representing January 1 of any given year. + * @method getJan1 + * @param {Number} calendarYear The calendar year for which to retrieve January 1 + * @return {Date} January 1 of the calendar year specified. + */ + getJan1 : function(calendarYear) { + return new Date(calendarYear,0,1); + }, + + /** + * Calculates the number of days the specified date is from January 1 of the specified calendar year. + * Passing January 1 to this function would return an offset value of zero. + * @method getDayOffset + * @param {Date} date The JavaScript date for which to find the offset + * @param {Number} calendarYear The calendar year to use for determining the offset + * @return {Number} The number of days since January 1 of the given year + */ + getDayOffset : function(date, calendarYear) { + var beginYear = this.getJan1(calendarYear); // Find the start of the year. This will be in week 1. + + // Find the number of days the passed in date is away from the calendar year start + var dayOffset = Math.ceil((date.getTime()-beginYear.getTime()) / this.ONE_DAY_MS); + return dayOffset; + }, + + /** + * Calculates the week number for the given date. This function assumes that week 1 is the + * week in which January 1 appears, regardless of whether the week consists of a full 7 days. + * The calendar year can be specified to help find what a the week number would be for a given + * date if the date overlaps years. For instance, a week may be considered week 1 of 2005, or + * week 53 of 2004. Specifying the optional calendarYear allows one to make this distinction + * easily. + * @method getWeekNumber + * @param {Date} date The JavaScript date for which to find the week number + * @param {Number} calendarYear OPTIONAL - The calendar year to use for determining the week number. Default is + * the calendar year of parameter "date". + * @param {Number} weekStartsOn OPTIONAL - The integer (0-6) representing which day a week begins on. Default is 0 (for Sunday). + * @return {Number} The week number of the given date. + */ + getWeekNumber : function(date, calendarYear) { + date = this.clearTime(date); + var nearestThurs = new Date(date.getTime() + (4 * this.ONE_DAY_MS) - ((date.getDay()) * this.ONE_DAY_MS)); + + var jan1 = new Date(nearestThurs.getFullYear(),0,1); + var dayOfYear = ((nearestThurs.getTime() - jan1.getTime()) / this.ONE_DAY_MS) - 1; + + var weekNum = Math.ceil((dayOfYear)/ 7); + return weekNum; + }, + + /** + * Determines if a given week overlaps two different years. + * @method isYearOverlapWeek + * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. + * @return {Boolean} true if the date overlaps two different years. + */ + isYearOverlapWeek : function(weekBeginDate) { + var overlaps = false; + var nextWeek = this.add(weekBeginDate, this.DAY, 6); + if (nextWeek.getFullYear() != weekBeginDate.getFullYear()) { + overlaps = true; + } + return overlaps; + }, + + /** + * Determines if a given week overlaps two different months. + * @method isMonthOverlapWeek + * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. + * @return {Boolean} true if the date overlaps two different months. + */ + isMonthOverlapWeek : function(weekBeginDate) { + var overlaps = false; + var nextWeek = this.add(weekBeginDate, this.DAY, 6); + if (nextWeek.getMonth() != weekBeginDate.getMonth()) { + overlaps = true; + } + return overlaps; + }, + + /** + * Gets the first day of a month containing a given date. + * @method findMonthStart + * @param {Date} date The JavaScript Date used to calculate the month start + * @return {Date} The JavaScript Date representing the first day of the month + */ + findMonthStart : function(date) { + var start = new Date(date.getFullYear(), date.getMonth(), 1); + return start; + }, + + /** + * Gets the last day of a month containing a given date. + * @method findMonthEnd + * @param {Date} date The JavaScript Date used to calculate the month end + * @return {Date} The JavaScript Date representing the last day of the month + */ + findMonthEnd : function(date) { + var start = this.findMonthStart(date); + var nextMonth = this.add(start, this.MONTH, 1); + var end = this.subtract(nextMonth, this.DAY, 1); + return end; + }, + + /** + * Clears the time fields from a given date, effectively setting the time to 12 noon. + * @method clearTime + * @param {Date} date The JavaScript Date for which the time fields will be cleared + * @return {Date} The JavaScript Date cleared of all time fields + */ + clearTime : function(date) { + date.setHours(12,0,0,0); + return date; + } +}; + +/** +* The Calendar component is a UI control that enables users to choose one or more dates from a graphical calendar presented in a one-month ("one-up") or two-month ("two-up") interface. Calendars are generated entirely via script and can be navigated without any page refreshes. +* @module calendar +* @title Calendar +* @namespace YAHOO.widget +* @requires yahoo,dom,event +*/ + +/** +* Calendar is the base class for the Calendar widget. In its most basic +* implementation, it has the ability to render a calendar widget on the page +* that can be manipulated to select a single date, move back and forth between +* months and years. +*

To construct the placeholder for the calendar widget, the code is as +* follows: +*

+* <div id="cal1Container"></div> +* +* Note that the table can be replaced with any kind of element. +*

+* @namespace YAHOO.widget +* @class Calendar +* @constructor +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.Calendar = function(id, containerId, config) { + this.init(id, containerId, config); +}; + +/** +* The path to be used for images loaded for the Calendar +* @property YAHOO.widget.Calendar.IMG_ROOT +* @static +* @type String +*/ +YAHOO.widget.Calendar.IMG_ROOT = (window.location.href.toLowerCase().indexOf("https") === 0 ? "https://a248.e.akamai.net/sec.yimg.com/i/" : "http://us.i1.yimg.com/us.yimg.com/i/"); + +/** +* Type constant used for renderers to represent an individual date (M/D/Y) +* @property YAHOO.widget.Calendar.DATE +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.DATE = "D"; + +/** +* Type constant used for renderers to represent an individual date across any year (M/D) +* @property YAHOO.widget.Calendar.MONTH_DAY +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.MONTH_DAY = "MD"; + +/** +* Type constant used for renderers to represent a weekday +* @property YAHOO.widget.Calendar.WEEKDAY +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.WEEKDAY = "WD"; + +/** +* Type constant used for renderers to represent a range of individual dates (M/D/Y-M/D/Y) +* @property YAHOO.widget.Calendar.RANGE +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.RANGE = "R"; + +/** +* Type constant used for renderers to represent a month across any year +* @property YAHOO.widget.Calendar.MONTH +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.MONTH = "M"; + +/** +* Constant that represents the total number of date cells that are displayed in a given month +* @property YAHOO.widget.Calendar.DISPLAY_DAYS +* @static +* @final +* @type Number +*/ +YAHOO.widget.Calendar.DISPLAY_DAYS = 42; + +/** +* Constant used for halting the execution of the remainder of the render stack +* @property YAHOO.widget.Calendar.STOP_RENDER +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.STOP_RENDER = "S"; + +YAHOO.widget.Calendar.prototype = { + + /** + * The configuration object used to set up the calendars various locale and style options. + * @property Config + * @private + * @deprecated Configuration properties should be set by calling Calendar.cfg.setProperty. + * @type Object + */ + Config : null, + + /** + * The parent CalendarGroup, only to be set explicitly by the parent group + * @property parent + * @type CalendarGroup + */ + parent : null, + + /** + * The index of this item in the parent group + * @property index + * @type Number + */ + index : -1, + + /** + * The collection of calendar table cells + * @property cells + * @type HTMLTableCellElement[] + */ + cells : null, + + /** + * The collection of calendar cell dates that is parallel to the cells collection. The array contains dates field arrays in the format of [YYYY, M, D]. + * @property cellDates + * @type Array[](Number[]) + */ + cellDates : null, + + /** + * The id that uniquely identifies this calendar. This id should match the id of the placeholder element on the page. + * @property id + * @type String + */ + id : null, + + /** + * The DOM element reference that points to this calendar's container element. The calendar will be inserted into this element when the shell is rendered. + * @property oDomContainer + * @type HTMLElement + */ + oDomContainer : null, + + /** + * A Date object representing today's date. + * @property today + * @type Date + */ + today : null, + + /** + * The list of render functions, along with required parameters, used to render cells. + * @property renderStack + * @type Array[] + */ + renderStack : null, + + /** + * A copy of the initial render functions created before rendering. + * @property _renderStack + * @private + * @type Array + */ + _renderStack : null, + + /** + * A Date object representing the month/year that the calendar is initially set to + * @property _pageDate + * @private + * @type Date + */ + _pageDate : null, + + /** + * The private list of initially selected dates. + * @property _selectedDates + * @private + * @type Array + */ + _selectedDates : null, + + /** + * A map of DOM event handlers to attach to cells associated with specific CSS class names + * @property domEventMap + * @type Object + */ + domEventMap : null +}; + + + +/** +* Initializes the Calendar widget. +* @method init +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.Calendar.prototype.init = function(id, containerId, config) { + this.initEvents(); + this.today = new Date(); + YAHOO.widget.DateMath.clearTime(this.today); + + this.id = id; + this.oDomContainer = document.getElementById(containerId); + + /** + * The Config object used to hold the configuration variables for the Calendar + * @property cfg + * @type YAHOO.util.Config + */ + this.cfg = new YAHOO.util.Config(this); + + /** + * The local object which contains the Calendar's options + * @property Options + * @type Object + */ + this.Options = {}; + + /** + * The local object which contains the Calendar's locale settings + * @property Locale + * @type Object + */ + this.Locale = {}; + + this.initStyles(); + + YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_CONTAINER); + YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_SINGLE); + + this.cellDates = []; + this.cells = []; + this.renderStack = []; + this._renderStack = []; + + this.setupConfig(); + + if (config) { + this.cfg.applyConfig(config, true); + } + + this.cfg.fireQueue(); +}; + +/** +* Renders the built-in IFRAME shim for the IE6 and below +* @method configIframe +*/ +YAHOO.widget.Calendar.prototype.configIframe = function(type, args, obj) { + var useIframe = args[0]; + + if (YAHOO.util.Dom.inDocument(this.oDomContainer)) { + if (useIframe) { + var pos = YAHOO.util.Dom.getStyle(this.oDomContainer, "position"); + + if (this.browser == "ie" && (pos == "absolute" || pos == "relative")) { + if (! YAHOO.util.Dom.inDocument(this.iframe)) { + this.iframe = document.createElement("iframe"); + this.iframe.src = "javascript:false;"; + YAHOO.util.Dom.setStyle(this.iframe, "opacity", "0"); + this.oDomContainer.insertBefore(this.iframe, this.oDomContainer.firstChild); + } + } + } else { + if (this.iframe) { + if (this.iframe.parentNode) { + this.iframe.parentNode.removeChild(this.iframe); + } + this.iframe = null; + } + } + } +}; + +/** +* Default handler for the "title" property +* @method configTitle +*/ +YAHOO.widget.Calendar.prototype.configTitle = function(type, args, obj) { + var title = args[0]; + var close = this.cfg.getProperty("close"); + + var titleDiv; + + if (title && title !== "") { + titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || document.createElement("div"); + titleDiv.className = YAHOO.widget.CalendarGroup.CSS_2UPTITLE; + titleDiv.innerHTML = title; + this.oDomContainer.insertBefore(titleDiv, this.oDomContainer.firstChild); + YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); + } else { + titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || null; + + if (titleDiv) { + YAHOO.util.Event.purgeElement(titleDiv); + this.oDomContainer.removeChild(titleDiv); + } + if (! close) { + YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); + } + } +}; + +/** +* Default handler for the "close" property +* @method configClose +*/ +YAHOO.widget.Calendar.prototype.configClose = function(type, args, obj) { + var close = args[0]; + var title = this.cfg.getProperty("title"); + + var linkClose; + + if (close === true) { + linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || document.createElement("a"); + linkClose.href = "javascript:void(null);"; + linkClose.className = "link-close"; + YAHOO.util.Event.addListener(linkClose, "click", this.hide, this, true); + var imgClose = document.createElement("img"); + imgClose.src = YAHOO.widget.Calendar.IMG_ROOT + "us/my/bn/x_d.gif"; + imgClose.className = YAHOO.widget.CalendarGroup.CSS_2UPCLOSE; + linkClose.appendChild(imgClose); + this.oDomContainer.appendChild(linkClose); + YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); + } else { + linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || null; + + if (linkClose) { + YAHOO.util.Event.purgeElement(linkClose); + this.oDomContainer.removeChild(linkClose); + } + if (! title || title === "") { + YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); + } + } +}; + +/** +* Initializes Calendar's built-in CustomEvents +* @method initEvents +*/ +YAHOO.widget.Calendar.prototype.initEvents = function() { + + /** + * Fired before a selection is made + * @event beforeSelectEvent + */ + this.beforeSelectEvent = new YAHOO.util.CustomEvent("beforeSelect"); + + /** + * Fired when a selection is made + * @event selectEvent + * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. + */ + this.selectEvent = new YAHOO.util.CustomEvent("select"); + + /** + * Fired before a selection is made + * @event beforeDeselectEvent + */ + this.beforeDeselectEvent = new YAHOO.util.CustomEvent("beforeDeselect"); + + /** + * Fired when a selection is made + * @event deselectEvent + * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. + */ + this.deselectEvent = new YAHOO.util.CustomEvent("deselect"); + + /** + * Fired when the Calendar page is changed + * @event changePageEvent + */ + this.changePageEvent = new YAHOO.util.CustomEvent("changePage"); + + /** + * Fired before the Calendar is rendered + * @event beforeRenderEvent + */ + this.beforeRenderEvent = new YAHOO.util.CustomEvent("beforeRender"); + + /** + * Fired when the Calendar is rendered + * @event renderEvent + */ + this.renderEvent = new YAHOO.util.CustomEvent("render"); + + /** + * Fired when the Calendar is reset + * @event resetEvent + */ + this.resetEvent = new YAHOO.util.CustomEvent("reset"); + + /** + * Fired when the Calendar is cleared + * @event clearEvent + */ + this.clearEvent = new YAHOO.util.CustomEvent("clear"); + + this.beforeSelectEvent.subscribe(this.onBeforeSelect, this, true); + this.selectEvent.subscribe(this.onSelect, this, true); + this.beforeDeselectEvent.subscribe(this.onBeforeDeselect, this, true); + this.deselectEvent.subscribe(this.onDeselect, this, true); + this.changePageEvent.subscribe(this.onChangePage, this, true); + this.renderEvent.subscribe(this.onRender, this, true); + this.resetEvent.subscribe(this.onReset, this, true); + this.clearEvent.subscribe(this.onClear, this, true); +}; + + +/** +* The default event function that is attached to a date link within a calendar cell +* when the calendar is rendered. +* @method doSelectCell +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doSelectCell = function(e, cal) { + var target = YAHOO.util.Event.getTarget(e); + + var cell,index,d,date; + + while (target.tagName.toLowerCase() != "td" && ! YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + cell = target; + + if (YAHOO.util.Dom.hasClass(cell, cal.Style.CSS_CELL_SELECTABLE)) { + index = cell.id.split("cell")[1]; + d = cal.cellDates[index]; + date = new Date(d[0],d[1]-1,d[2]); + + var link; + + if (cal.Options.MULTI_SELECT) { + link = cell.getElementsByTagName("a")[0]; + if (link) { + link.blur(); + } + + var cellDate = cal.cellDates[index]; + var cellDateIndex = cal._indexOfSelectedFieldArray(cellDate); + + if (cellDateIndex > -1) { + cal.deselectCell(index); + } else { + cal.selectCell(index); + } + + } else { + link = cell.getElementsByTagName("a")[0]; + if (link) { + link.blur(); + } + cal.selectCell(index); + } + } +}; + +/** +* The event that is executed when the user hovers over a cell +* @method doCellMouseOver +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doCellMouseOver = function(e, cal) { + var target; + if (e) { + target = YAHOO.util.Event.getTarget(e); + } else { + target = this; + } + + while (target.tagName.toLowerCase() != "td") { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + YAHOO.util.Dom.addClass(target, cal.Style.CSS_CELL_HOVER); + } +}; + +/** +* The event that is executed when the user moves the mouse out of a cell +* @method doCellMouseOut +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doCellMouseOut = function(e, cal) { + var target; + if (e) { + target = YAHOO.util.Event.getTarget(e); + } else { + target = this; + } + + while (target.tagName.toLowerCase() != "td") { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + YAHOO.util.Dom.removeClass(target, cal.Style.CSS_CELL_HOVER); + } +}; + +YAHOO.widget.Calendar.prototype.setupConfig = function() { + + /** + * The month/year representing the current visible Calendar date (mm/yyyy) + * @config pagedate + * @type String + * @default today's date + */ + this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); + + /** + * The date or range of dates representing the current Calendar selection + * @config selected + * @type String + * @default [] + */ + this.cfg.addProperty("selected", { value:[], handler:this.configSelected } ); + + /** + * The title to display above the Calendar's month header + * @config title + * @type String + * @default "" + */ + this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); + + /** + * Whether or not a close button should be displayed for this Calendar + * @config close + * @type Boolean + * @default false + */ + this.cfg.addProperty("close", { value:false, handler:this.configClose } ); + + /** + * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. + * @config iframe + * @type Boolean + * @default true + */ + this.cfg.addProperty("iframe", { value:true, handler:this.configIframe, validator:this.cfg.checkBoolean } ); + + /** + * The minimum selectable date in the current Calendar (mm/dd/yyyy) + * @config mindate + * @type String + * @default null + */ + this.cfg.addProperty("mindate", { value:null, handler:this.configMinDate } ); + + /** + * The maximum selectable date in the current Calendar (mm/dd/yyyy) + * @config maxdate + * @type String + * @default null + */ + this.cfg.addProperty("maxdate", { value:null, handler:this.configMaxDate } ); + + + // Options properties + + /** + * True if the Calendar should allow multiple selections. False by default. + * @config MULTI_SELECT + * @type Boolean + * @default false + */ + this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * The weekday the week begins on. Default is 0 (Sunday). + * @config START_WEEKDAY + * @type number + * @default 0 + */ + this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.configOptions, validator:this.cfg.checkNumber } ); + + /** + * True if the Calendar should show weekday labels. True by default. + * @config SHOW_WEEKDAYS + * @type Boolean + * @default true + */ + this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row headers. False by default. + * @config SHOW_WEEK_HEADER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row footers. False by default. + * @config SHOW_WEEK_FOOTER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should suppress weeks that are not a part of the current month. False by default. + * @config HIDE_BLANK_WEEKS + * @type Boolean + * @default false + */ + this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_LEFT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" + */ + this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.configOptions } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_RIGHT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" + */ + this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.configOptions } ); + + // Locale properties + + /** + * The short month labels for the current locale. + * @config MONTHS_SHORT + * @type String[] + * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + */ + this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.configLocale } ); + + /** + * The long month labels for the current locale. + * @config MONTHS_LONG + * @type String[] + * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" + */ + this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.configLocale } ); + + /** + * The 1-character weekday labels for the current locale. + * @config WEEKDAYS_1CHAR + * @type String[] + * @default ["S", "M", "T", "W", "T", "F", "S"] + */ + this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.configLocale } ); + + /** + * The short weekday labels for the current locale. + * @config WEEKDAYS_SHORT + * @type String[] + * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] + */ + this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.configLocale } ); + + /** + * The medium weekday labels for the current locale. + * @config WEEKDAYS_MEDIUM + * @type String[] + * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] + */ + this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.configLocale } ); + + /** + * The long weekday labels for the current locale. + * @config WEEKDAYS_LONG + * @type String[] + * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + */ + this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.configLocale } ); + + /** + * Refreshes the locale values used to build the Calendar. + * @method refreshLocale + * @private + */ + var refreshLocale = function() { + this.cfg.refireEvent("LOCALE_MONTHS"); + this.cfg.refireEvent("LOCALE_WEEKDAYS"); + }; + + this.cfg.subscribeToConfigEvent("START_WEEKDAY", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("MONTHS_SHORT", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("MONTHS_LONG", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG", refreshLocale, this, true); + + /** + * The setting that determines which length of month labels should be used. Possible values are "short" and "long". + * @config LOCALE_MONTHS + * @type String + * @default "long" + */ + this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.configLocaleValues } ); + + /** + * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". + * @config LOCALE_WEEKDAYS + * @type String + * @default "short" + */ + this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.configLocaleValues } ); + + /** + * The value used to delimit individual dates in a date string passed to various Calendar functions. + * @config DATE_DELIMITER + * @type String + * @default "," + */ + this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.configLocale } ); + + /** + * The value used to delimit date fields in a date string passed to various Calendar functions. + * @config DATE_FIELD_DELIMITER + * @type String + * @default "/" + */ + this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.configLocale } ); + + /** + * The value used to delimit date ranges in a date string passed to various Calendar functions. + * @config DATE_RANGE_DELIMITER + * @type String + * @default "-" + */ + this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.configLocale } ); + + /** + * The position of the month in a month/year date string + * @config MY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/year date string + * @config MY_YEAR_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day date string + * @config MD_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/year date string + * @config MD_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day/year date string + * @config MDY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/day/year date string + * @config MDY_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/day/year date string + * @config MDY_YEAR_POSITION + * @type Number + * @default 3 + */ + this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.configLocale, validator:this.cfg.checkNumber } ); +}; + +/** +* The default handler for the "pagedate" property +* @method configPageDate +*/ +YAHOO.widget.Calendar.prototype.configPageDate = function(type, args, obj) { + var val = args[0]; + var month, year, aMonthYear; + + if (val) { + if (val instanceof Date) { + val = YAHOO.widget.DateMath.findMonthStart(val); + this.cfg.setProperty("pagedate", val, true); + if (! this._pageDate) { + this._pageDate = this.cfg.getProperty("pagedate"); + } + return; + } else { + aMonthYear = val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER")); + month = parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1], 10)-1; + year = parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1], 10); + } + } else { + month = this.today.getMonth(); + year = this.today.getFullYear(); + } + + this.cfg.setProperty("pagedate", new Date(year, month, 1), true); + if (! this._pageDate) { + this._pageDate = this.cfg.getProperty("pagedate"); + } +}; + +/** +* The default handler for the "mindate" property +* @method configMinDate +*/ +YAHOO.widget.Calendar.prototype.configMinDate = function(type, args, obj) { + var val = args[0]; + if (typeof val == 'string') { + val = this._parseDate(val); + this.cfg.setProperty("mindate", new Date(val[0],(val[1]-1),val[2])); + } +}; + +/** +* The default handler for the "maxdate" property +* @method configMaxDate +*/ +YAHOO.widget.Calendar.prototype.configMaxDate = function(type, args, obj) { + var val = args[0]; + if (typeof val == 'string') { + val = this._parseDate(val); + this.cfg.setProperty("maxdate", new Date(val[0],(val[1]-1),val[2])); + } +}; + +/** +* The default handler for the "selected" property +* @method configSelected +*/ +YAHOO.widget.Calendar.prototype.configSelected = function(type, args, obj) { + var selected = args[0]; + + if (selected) { + if (typeof selected == 'string') { + this.cfg.setProperty("selected", this._parseDates(selected), true); + } + } + if (! this._selectedDates) { + this._selectedDates = this.cfg.getProperty("selected"); + } +}; + +/** +* The default handler for all configuration options properties +* @method configOptions +*/ +YAHOO.widget.Calendar.prototype.configOptions = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + this.Options[type] = val; +}; + +/** +* The default handler for all configuration locale properties +* @method configLocale +*/ +YAHOO.widget.Calendar.prototype.configLocale = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + this.Locale[type] = val; + + this.cfg.refireEvent("LOCALE_MONTHS"); + this.cfg.refireEvent("LOCALE_WEEKDAYS"); + +}; + +/** +* The default handler for all configuration locale field length properties +* @method configLocaleValues +*/ +YAHOO.widget.Calendar.prototype.configLocaleValues = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + + switch (type) { + case "LOCALE_MONTHS": + switch (val) { + case "short": + this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_SHORT").concat(); + break; + case "long": + this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_LONG").concat(); + break; + } + break; + case "LOCALE_WEEKDAYS": + switch (val) { + case "1char": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_1CHAR").concat(); + break; + case "short": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_SHORT").concat(); + break; + case "medium": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_MEDIUM").concat(); + break; + case "long": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_LONG").concat(); + break; + } + + var START_WEEKDAY = this.cfg.getProperty("START_WEEKDAY"); + + if (START_WEEKDAY > 0) { + for (var w=0;w'; + html[html.length] = '
'; + + var renderLeft, renderRight = false; + + if (this.parent) { + if (this.index === 0) { + renderLeft = true; + } + if (this.index == (this.parent.cfg.getProperty("pages") -1)) { + renderRight = true; + } + } else { + renderLeft = true; + renderRight = true; + } + + var cal = this.parent || this; + + if (renderLeft) { + html[html.length] = ' '; + } + + html[html.length] = this.buildMonthLabel(); + + if (renderRight) { + html[html.length] = ' '; + } + + + html[html.length] = '
'; + html[html.length] = ''; + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEKDAYS")) { + html = this.buildWeekdays(html); + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the Calendar's weekday headers. +* @method buildWeekdays +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.buildWeekdays = function(html) { + + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { + html[html.length] = ' '; + } + + for(var i=0;i'; + } + + if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { + html[html.length] = ' '; + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the calendar body. +* @method renderBody +* @param {Date} workingDate The current working Date being used for the render process +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderBody = function(workingDate, html) { + + var startDay = this.cfg.getProperty("START_WEEKDAY"); + + this.preMonthDays = workingDate.getDay(); + if (startDay > 0) { + this.preMonthDays -= startDay; + } + if (this.preMonthDays < 0) { + this.preMonthDays += 7; + } + + this.monthDays = YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate(); + this.postMonthDays = YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays; + + workingDate = YAHOO.widget.DateMath.subtract(workingDate, YAHOO.widget.DateMath.DAY, this.preMonthDays); + + var useDate,weekNum,weekClass; + useDate = this.cfg.getProperty("pagedate"); + + html[html.length] = ''; + + var i = 0; + + var tempDiv = document.createElement("div"); + var cell = document.createElement("td"); + tempDiv.appendChild(cell); + + var jan1 = new Date(useDate.getFullYear(),0,1); + + var cal = this.parent || this; + + for (var r=0;r<6;r++) { + + weekNum = YAHOO.widget.DateMath.getWeekNumber(workingDate, useDate.getFullYear(), startDay); + + weekClass = "w" + weekNum; + + if (r !== 0 && this.isDateOOM(workingDate) && this.cfg.getProperty("HIDE_BLANK_WEEKS") === true) { + break; + } else { + + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { html = this.renderRowHeader(weekNum, html); } + + for (var d=0;d<7;d++){ // Render actual days + + var cellRenderers = []; + + this.clearElement(cell); + + YAHOO.util.Dom.addClass(cell, "calcell"); + + cell.id = this.id + "_cell" + i; + + cell.innerHTML = i; + + var renderer = null; + + if (workingDate.getFullYear() == this.today.getFullYear() && + workingDate.getMonth() == this.today.getMonth() && + workingDate.getDate() == this.today.getDate()) { + cellRenderers[cellRenderers.length]=cal.renderCellStyleToday; + } + + this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]; // Add this date to cellDates + + if (this.isDateOOM(workingDate)) { + cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth; + } else { + + YAHOO.util.Dom.addClass(cell, "wd" + workingDate.getDay()); + YAHOO.util.Dom.addClass(cell, "d" + workingDate.getDate()); + + for (var s=0;s= d1.getTime() && workingDate.getTime() <= d2.getTime()) { + renderer = rArray[2]; + + if (workingDate.getTime()==d2.getTime()) { + this.renderStack.splice(s,1); + } + } + break; + case YAHOO.widget.Calendar.WEEKDAY: + + var weekday = rArray[1][0]; + if (workingDate.getDay()+1 == weekday) { + renderer = rArray[2]; + } + break; + case YAHOO.widget.Calendar.MONTH: + + month = rArray[1][0]; + if (workingDate.getMonth()+1 == month) { + renderer = rArray[2]; + } + break; + } + + if (renderer) { + cellRenderers[cellRenderers.length]=renderer; + } + } + + } + + if (this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]) > -1) { + cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected; + } + + var mindate = this.cfg.getProperty("mindate"); + var maxdate = this.cfg.getProperty("maxdate"); + + if (mindate) { + mindate = YAHOO.widget.DateMath.clearTime(mindate); + } + if (maxdate) { + maxdate = YAHOO.widget.DateMath.clearTime(maxdate); + } + + if ( + (mindate && (workingDate.getTime() < mindate.getTime())) || + (maxdate && (workingDate.getTime() > maxdate.getTime())) + ) { + cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate; + } else { + cellRenderers[cellRenderers.length]=cal.styleCellDefault; + cellRenderers[cellRenderers.length]=cal.renderCellDefault; + } + + + + for (var x=0;x= 0 && i <= 6) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TOP); + } + if ((i % 7) === 0) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_LEFT); + } + if (((i+1) % 7) === 0) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RIGHT); + } + + var postDays = this.postMonthDays; + if (postDays >= 7 && this.cfg.getProperty("HIDE_BLANK_WEEKS")) { + var blankWeeks = Math.floor(postDays/7); + for (var p=0;p= ((this.preMonthDays+postDays+this.monthDays)-7)) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_BOTTOM); + } + + html[html.length] = tempDiv.innerHTML; + + i++; + } + + if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { html = this.renderRowFooter(weekNum, html); } + + html[html.length] = ''; + } + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the calendar footer. In the default implementation, there is +* no footer. +* @method renderFooter +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderFooter = function(html) { return html; }; + +/** +* Renders the calendar after it has been configured. The render() method has a specific call chain that will execute +* when the method is called: renderHeader, renderBody, renderFooter. +* Refer to the documentation for those methods for information on +* individual render tasks. +* @method render +*/ +YAHOO.widget.Calendar.prototype.render = function() { + this.beforeRenderEvent.fire(); + + // Find starting day of the current month + var workingDate = YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate")); + + this.resetRenderers(); + this.cellDates.length = 0; + + YAHOO.util.Event.purgeElement(this.oDomContainer, true); + + var html = []; + + html[html.length] = ''; + html = this.renderHeader(html); + html = this.renderBody(workingDate, html); + html = this.renderFooter(html); + html[html.length] = '
'; + + this.oDomContainer.innerHTML = html.join("\n"); + + this.applyListeners(); + this.cells = this.oDomContainer.getElementsByTagName("td"); + + this.cfg.refireEvent("title"); + this.cfg.refireEvent("close"); + this.cfg.refireEvent("iframe"); + + this.renderEvent.fire(); +}; + +/** +* Applies the Calendar's DOM listeners to applicable elements. +* @method applyListeners +*/ +YAHOO.widget.Calendar.prototype.applyListeners = function() { + + var root = this.oDomContainer; + var cal = this.parent || this; + + var linkLeft, linkRight; + + linkLeft = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT, "a", root); + linkRight = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT, "a", root); + + if (linkLeft) { + this.linkLeft = linkLeft[0]; + YAHOO.util.Event.addListener(this.linkLeft, "mousedown", cal.previousMonth, cal, true); + } + + if (linkRight) { + this.linkRight = linkRight[0]; + YAHOO.util.Event.addListener(this.linkRight, "mousedown", cal.nextMonth, cal, true); + } + + if (this.domEventMap) { + var el,elements; + for (var cls in this.domEventMap) { + if (this.domEventMap.hasOwnProperty(cls)) { + var items = this.domEventMap[cls]; + + if (! (items instanceof Array)) { + items = [items]; + } + + for (var i=0;i'; + return html; +}; + +/** +* Renders the row footer for a week. +* @method renderRowFooter +* @param {Number} weekNum The week number of the current row +* @param {Array} cell The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderRowFooter = function(weekNum, html) { + html[html.length] = '' + weekNum + ''; + return html; +}; + +/** +* Renders a single standard calendar cell in the calendar widget table. +* All logic for determining how a standard default cell will be rendered is +* encapsulated in this method, and must be accounted for when extending the +* widget class. +* @method renderCellDefault +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellDefault = function(workingDate, cell) { + cell.innerHTML = '' + this.buildDayLabel(workingDate) + ""; +}; + +/** +* Styles a selectable cell. +* @method styleCellDefault +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.styleCellDefault = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTABLE); +}; + + +/** +* Renders a single standard calendar cell using the CSS hightlight1 style +* @method renderCellStyleHighlight1 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT1); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight2 style +* @method renderCellStyleHighlight2 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT2); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight3 style +* @method renderCellStyleHighlight3 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT3); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight4 style +* @method renderCellStyleHighlight4 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT4); +}; + +/** +* Applies the default style used for rendering today's date to the current calendar cell +* @method renderCellStyleToday +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleToday = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TODAY); +}; + +/** +* Applies the default style used for rendering selected dates to the current calendar cell +* @method renderCellStyleSelected +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleSelected = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTED); +}; + +/** +* Applies the default style used for rendering dates that are not a part of the current +* month (preceding or trailing the cells for the current month) +* @method renderCellNotThisMonth +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderCellNotThisMonth = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_OOM); + cell.innerHTML=workingDate.getDate(); + return YAHOO.widget.Calendar.STOP_RENDER; +}; + +/** +* Renders the current calendar cell as a non-selectable "black-out" date using the default +* restricted style. +* @method renderBodyCellRestricted +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderBodyCellRestricted = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL); + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RESTRICTED); + cell.innerHTML=workingDate.getDate(); + return YAHOO.widget.Calendar.STOP_RENDER; +}; + +// END BUILT-IN TABLE CELL RENDERERS + +// BEGIN MONTH NAVIGATION METHODS + +/** +* Adds the designated number of months to the current calendar month, and sets the current +* calendar page date to the new month. +* @method addMonths +* @param {Number} count The number of months to add to the current calendar +*/ +YAHOO.widget.Calendar.prototype.addMonths = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Subtracts the designated number of months from the current calendar month, and sets the current +* calendar page date to the new month. +* @method subtractMonths +* @param {Number} count The number of months to subtract from the current calendar +*/ +YAHOO.widget.Calendar.prototype.subtractMonths = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Adds the designated number of years to the current calendar, and sets the current +* calendar page date to the new month. +* @method addYears +* @param {Number} count The number of years to add to the current calendar +*/ +YAHOO.widget.Calendar.prototype.addYears = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Subtcats the designated number of years from the current calendar, and sets the current +* calendar page date to the new month. +* @method subtractYears +* @param {Number} count The number of years to subtract from the current calendar +*/ +YAHOO.widget.Calendar.prototype.subtractYears = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Navigates to the next month page in the calendar widget. +* @method nextMonth +*/ +YAHOO.widget.Calendar.prototype.nextMonth = function() { + this.addMonths(1); +}; + +/** +* Navigates to the previous month page in the calendar widget. +* @method previousMonth +*/ +YAHOO.widget.Calendar.prototype.previousMonth = function() { + this.subtractMonths(1); +}; + +/** +* Navigates to the next year in the currently selected month in the calendar widget. +* @method nextYear +*/ +YAHOO.widget.Calendar.prototype.nextYear = function() { + this.addYears(1); +}; + +/** +* Navigates to the previous year in the currently selected month in the calendar widget. +* @method previousYear +*/ +YAHOO.widget.Calendar.prototype.previousYear = function() { + this.subtractYears(1); +}; + +// END MONTH NAVIGATION METHODS + +// BEGIN SELECTION METHODS + +/** +* Resets the calendar widget to the originally selected month and year, and +* sets the calendar to the initial selection(s). +* @method reset +*/ +YAHOO.widget.Calendar.prototype.reset = function() { + this.cfg.resetProperty("selected"); + this.cfg.resetProperty("pagedate"); + this.resetEvent.fire(); +}; + +/** +* Clears the selected dates in the current calendar widget and sets the calendar +* to the current month and year. +* @method clear +*/ +YAHOO.widget.Calendar.prototype.clear = function() { + this.cfg.setProperty("selected", []); + this.cfg.setProperty("pagedate", new Date(this.today.getTime())); + this.clearEvent.fire(); +}; + +/** +* Selects a date or a collection of dates on the current calendar. This method, by default, +* does not call the render method explicitly. Once selection has completed, render must be +* called for the changes to be reflected visually. +* @method select +* @param {String/Date/Date[]} date The date string of dates to select in the current calendar. Valid formats are +* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). +* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). +* This method can also take a JavaScript Date object or an array of Date objects. +* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. +*/ +YAHOO.widget.Calendar.prototype.select = function(date) { + this.beforeSelectEvent.fire(); + + var selected = this.cfg.getProperty("selected"); + var aToBeSelected = this._toFieldArray(date); + + for (var a=0;a -1) { + if (this.cfg.getProperty("pagedate").getMonth() == dCellDate.getMonth() && + this.cfg.getProperty("pagedate").getFullYear() == dCellDate.getFullYear()) { + YAHOO.util.Dom.removeClass(cell, this.Style.CSS_CELL_SELECTED); + } + + selected.splice(cellDateIndex, 1); + } + + + if (this.parent) { + this.parent.cfg.setProperty("selected", selected); + } else { + this.cfg.setProperty("selected", selected); + } + + this.deselectEvent.fire(selectDate); + return this.getSelectedDates(); +}; + +/** +* Deselects all dates on the current calendar. +* @method deselectAll +* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. +* Assuming that this function executes properly, the return value should be an empty array. +* However, the empty array is returned for the sake of being able to check the selection status +* of the calendar. +*/ +YAHOO.widget.Calendar.prototype.deselectAll = function() { + this.beforeDeselectEvent.fire(); + + var selected = this.cfg.getProperty("selected"); + var count = selected.length; + var sel = selected.concat(); + + if (this.parent) { + this.parent.cfg.setProperty("selected", []); + } else { + this.cfg.setProperty("selected", []); + } + + if (count > 0) { + this.deselectEvent.fire(sel); + } + + return this.getSelectedDates(); +}; + +// END SELECTION METHODS + +// BEGIN TYPE CONVERSION METHODS + +/** +* Converts a date (either a JavaScript Date object, or a date string) to the internal data structure +* used to represent dates: [[yyyy,mm,dd],[yyyy,mm,dd]]. +* @method _toFieldArray +* @private +* @param {String/Date/Date[]} date The date string of dates to deselect in the current calendar. Valid formats are +* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). +* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). +* This method can also take a JavaScript Date object or an array of Date objects. +* @return {Array[](Number[])} Array of date field arrays +*/ +YAHOO.widget.Calendar.prototype._toFieldArray = function(date) { + var returnDate = []; + + if (date instanceof Date) { + returnDate = [[date.getFullYear(), date.getMonth()+1, date.getDate()]]; + } else if (typeof date == 'string') { + returnDate = this._parseDates(date); + } else if (date instanceof Array) { + for (var i=0;i +*
+*
+* +* The tables for the calendars ("cal1_0" and "cal1_1") will be inserted into those containers. +* @namespace YAHOO.widget +* @class CalendarGroup +* @constructor +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.CalendarGroup = function(id, containerId, config) { + if (arguments.length > 0) { + this.init(id, containerId, config); + } +}; + +/** +* Initializes the calendar group. All subclasses must call this method in order for the +* group to be initialized properly. +* @method init +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.CalendarGroup.prototype.init = function(id, containerId, config) { + this.initEvents(); + this.initStyles(); + + /** + * The collection of Calendar pages contained within the CalendarGroup + * @property pages + * @type YAHOO.widget.Calendar[] + */ + this.pages = []; + + /** + * The unique id associated with the CalendarGroup + * @property id + * @type String + */ + this.id = id; + + /** + * The unique id associated with the CalendarGroup container + * @property containerId + * @type String + */ + this.containerId = containerId; + + /** + * The outer containing element for the CalendarGroup + * @property oDomContainer + * @type HTMLElement + */ + this.oDomContainer = document.getElementById(containerId); + + YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_CONTAINER); + YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_MULTI_UP); + + /** + * The Config object used to hold the configuration variables for the CalendarGroup + * @property cfg + * @type YAHOO.util.Config + */ + this.cfg = new YAHOO.util.Config(this); + + /** + * The local object which contains the CalendarGroup's options + * @property Options + * @type Object + */ + this.Options = {}; + + /** + * The local object which contains the CalendarGroup's locale settings + * @property Locale + * @type Object + */ + this.Locale = {}; + + this.setupConfig(); + + if (config) { + this.cfg.applyConfig(config, true); + } + + this.cfg.fireQueue(); + + // OPERA HACK FOR MISWRAPPED FLOATS + if (this.browser == "opera"){ + var fixWidth = function() { + var startW = this.oDomContainer.offsetWidth; + var w = 0; + for (var p=0;p 0) { + this.oDomContainer.style.width = w + "px"; + } + }; + this.renderEvent.subscribe(fixWidth,this,true); + } +}; + + +YAHOO.widget.CalendarGroup.prototype.setupConfig = function() { + /** + * The number of pages to include in the CalendarGroup. This value can only be set once, in the CalendarGroup's constructor arguments. + * @config pages + * @type Number + * @default 2 + */ + this.cfg.addProperty("pages", { value:2, validator:this.cfg.checkNumber, handler:this.configPages } ); + + /** + * The month/year representing the current visible Calendar date (mm/yyyy) + * @config pagedate + * @type String + * @default today's date + */ + this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); + + /** + * The date or range of dates representing the current Calendar selection + * @config selected + * @type String + * @default [] + */ + this.cfg.addProperty("selected", { value:[], handler:this.delegateConfig } ); + + /** + * The title to display above the CalendarGroup's month header + * @config title + * @type String + * @default "" + */ + this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); + + /** + * Whether or not a close button should be displayed for this CalendarGroup + * @config close + * @type Boolean + * @default false + */ + this.cfg.addProperty("close", { value:false, handler:this.configClose } ); + + /** + * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. + * @config iframe + * @type Boolean + * @default true + */ + this.cfg.addProperty("iframe", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The minimum selectable date in the current Calendar (mm/dd/yyyy) + * @config mindate + * @type String + * @default null + */ + this.cfg.addProperty("mindate", { value:null, handler:this.delegateConfig } ); + + /** + * The maximum selectable date in the current Calendar (mm/dd/yyyy) + * @config maxdate + * @type String + * @default null + */ + this.cfg.addProperty("maxdate", { value:null, handler:this.delegateConfig } ); + + // Options properties + + /** + * True if the Calendar should allow multiple selections. False by default. + * @config MULTI_SELECT + * @type Boolean + * @default false + */ + this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The weekday the week begins on. Default is 0 (Sunday). + * @config START_WEEKDAY + * @type number + * @default 0 + */ + this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * True if the Calendar should show weekday labels. True by default. + * @config SHOW_WEEKDAYS + * @type Boolean + * @default true + */ + this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row headers. False by default. + * @config SHOW_WEEK_HEADER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row footers. False by default. + * @config SHOW_WEEK_FOOTER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should suppress weeks that are not a part of the current month. False by default. + * @config HIDE_BLANK_WEEKS + * @type Boolean + * @default false + */ + this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_LEFT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" + */ + this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.delegateConfig } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_RIGHT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" + */ + this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.delegateConfig } ); + + // Locale properties + + /** + * The short month labels for the current locale. + * @config MONTHS_SHORT + * @type String[] + * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + */ + this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.delegateConfig } ); + + /** + * The long month labels for the current locale. + * @config MONTHS_LONG + * @type String[] + * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" + */ + this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.delegateConfig } ); + + /** + * The 1-character weekday labels for the current locale. + * @config WEEKDAYS_1CHAR + * @type String[] + * @default ["S", "M", "T", "W", "T", "F", "S"] + */ + this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.delegateConfig } ); + + /** + * The short weekday labels for the current locale. + * @config WEEKDAYS_SHORT + * @type String[] + * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] + */ + this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.delegateConfig } ); + + /** + * The medium weekday labels for the current locale. + * @config WEEKDAYS_MEDIUM + * @type String[] + * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] + */ + this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.delegateConfig } ); + + /** + * The long weekday labels for the current locale. + * @config WEEKDAYS_LONG + * @type String[] + * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + */ + this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.delegateConfig } ); + + /** + * The setting that determines which length of month labels should be used. Possible values are "short" and "long". + * @config LOCALE_MONTHS + * @type String + * @default "long" + */ + this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.delegateConfig } ); + + /** + * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". + * @config LOCALE_WEEKDAYS + * @type String + * @default "short" + */ + this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.delegateConfig } ); + + /** + * The value used to delimit individual dates in a date string passed to various Calendar functions. + * @config DATE_DELIMITER + * @type String + * @default "," + */ + this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.delegateConfig } ); + + /** + * The value used to delimit date fields in a date string passed to various Calendar functions. + * @config DATE_FIELD_DELIMITER + * @type String + * @default "/" + */ + this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.delegateConfig } ); + + /** + * The value used to delimit date ranges in a date string passed to various Calendar functions. + * @config DATE_RANGE_DELIMITER + * @type String + * @default "-" + */ + this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.delegateConfig } ); + + /** + * The position of the month in a month/year date string + * @config MY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/year date string + * @config MY_YEAR_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day date string + * @config MD_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/year date string + * @config MD_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day/year date string + * @config MDY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/day/year date string + * @config MDY_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/day/year date string + * @config MDY_YEAR_POSITION + * @type Number + * @default 3 + */ + this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + +}; + +/** +* Initializes CalendarGroup's built-in CustomEvents +* @method initEvents +*/ +YAHOO.widget.CalendarGroup.prototype.initEvents = function() { + var me = this; + + /** + * Proxy subscriber to subscribe to the CalendarGroup's child Calendars' CustomEvents + * @method sub + * @private + * @param {Function} fn The function to subscribe to this CustomEvent + * @param {Object} obj The CustomEvent's scope object + * @param {Boolean} bOverride Whether or not to apply scope correction + */ + var sub = function(fn, obj, bOverride) { + for (var p=0;p0) { + year+=1; + } + cal.setYear(year); + } +}; +/** +* Calls the render function of all child calendars within the group. +* @method render +*/ +YAHOO.widget.CalendarGroup.prototype.render = function() { + this.renderHeader(); + for (var p=0;p=0;--p) { + var cal = this.pages[p]; + cal.previousMonth(); + } +}; + +/** +* Navigates to the next year in the currently selected month in the calendar widget. +* @method nextYear +*/ +YAHOO.widget.CalendarGroup.prototype.nextYear = function() { + for (var p=0;p