From 541bb378ddece2eab135a8066a16994e94436dea Mon Sep 17 00:00:00 2001 From: Giulio Cesare Solaroli Date: Mon, 03 Oct 2011 16:04:12 +0000 Subject: Merge pull request #1 from gcsolaroli/master First version of the restructured repository --- (limited to 'frontend/beta/js/YUI') diff --git a/frontend/beta/js/YUI/animation.js b/frontend/beta/js/YUI/animation.js new file mode 100644 index 0000000..333f946 --- a/dev/null +++ b/frontend/beta/js/YUI/animation.js @@ -0,0 +1,1272 @@ +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 0.12.0 +*/ + +/** + * 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] ]; + + }; +}; +/** + * 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) + */ +(function() { + 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; + } +}; + +/** + * 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) + */ +(function() { + 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'); + }; +})(); +/** + * 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) + */ +(function() { + 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/frontend/beta/js/YUI/autocomplete.js b/frontend/beta/js/YUI/autocomplete.js new file mode 100644 index 0000000..a5722cc --- a/dev/null +++ b/frontend/beta/js/YUI/autocomplete.js @@ -0,0 +1,3066 @@ +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.com/yui/license.txt +version: 0.12.0 +*/ + + /** + * The AutoComplete control provides the front-end logic for text-entry suggestion and + * completion functionality. + * + * @module autocomplete + * @requires yahoo, dom, event, datasource + * @optional animation, connection, json + * @namespace YAHOO.widget + * @title AutoComplete Widget + */ + +/****************************************************************************/ +/****************************************************************************/ +/****************************************************************************/ + +/** + * The AutoComplete class provides the customizable functionality of a plug-and-play DHTML + * auto completion widget. Some key features: + * + * + * @class AutoComplete + * @constructor + * @param elInput {HTMLElement} DOM element reference of an input field + * @param elInput {String} String ID of an input field + * @param elContainer {HTMLElement} DOM element reference of an existing DIV + * @param elContainer {String} String ID of an existing DIV + * @param oDataSource {Object} Instance of YAHOO.widget.DataSource for query/results + * @param oConfigs {Object} (optional) Object literal of configuration params + */ +YAHOO.widget.AutoComplete = function(elInput,elContainer,oDataSource,oConfigs) { + if(elInput && elContainer && oDataSource) { + // Validate DataSource + if (oDataSource && (oDataSource instanceof YAHOO.widget.DataSource)) { + this.dataSource = oDataSource; + } + else { + return; + } + + // Validate input element + 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; + } + + // Validate container element + 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; + } + + // Set any config params passed in to override defaults + if (typeof oConfigs == "object") { + for(var sConfig in oConfigs) { + if (sConfig) { + this[sConfig] = oConfigs[sConfig]; + } + } + } + + // Initialization sequence + this._initContainer(); + this._initProps(); + this._initList(); + this._initContainerHelpers(); + + // Set up events + var oSelf = this; + var oTextbox = this._oTextbox; + // Events are actually for the content module within the container + var oContent = this._oContainer._oContent; + + // Dom events + 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); + + // Custom events + 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); + + // Finish up + oTextbox.setAttribute("autocomplete","off"); + YAHOO.widget.AutoComplete._nIndex++; + } + // Required arguments were not found + else { + } +}; + +///////////////////////////////////////////////////////////////////////////// +// +// Public member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * The DataSource object that encapsulates the data used for auto completion. + * This object should be an inherited object from YAHOO.widget.DataSource. + * + * @property dataSource + * @type Object + */ +YAHOO.widget.AutoComplete.prototype.dataSource = null; + +/** + * Number of characters that must be entered before querying for results. A negative value + * effectively turns off the widget. A value of 0 allows queries of null or empty string + * values. + * + * @property minQueryLength + * @type Number + * @default 1 + */ +YAHOO.widget.AutoComplete.prototype.minQueryLength = 1; + +/** + * Maximum number of results to display in results container. + * + * @property maxResultsDisplayed + * @type Number + * @default 10 + */ +YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed = 10; + +/** + * Number of seconds to delay before submitting a query request. If a query + * request is received before a previous one has completed its delay, the + * previous request is cancelled and the new request is set to the delay. + * + * @property queryDelay + * @type Number + * @default 0.5 + */ +YAHOO.widget.AutoComplete.prototype.queryDelay = 0.5; + +/** + * Class name of a highlighted item within results container. + * + * @property highlighClassName + * @type String + * @default "yui-ac-highlight" + */ +YAHOO.widget.AutoComplete.prototype.highlightClassName = "yui-ac-highlight"; + +/** + * Class name of a pre-highlighted item within results container. + * + * @property prehighlightClassName + * @type String + */ +YAHOO.widget.AutoComplete.prototype.prehighlightClassName = null; + +/** + * Query delimiter. A single character separator for multiple delimited + * selections. Multiple delimiter characteres may be defined as an array of + * strings. A null value or empty string indicates that query results cannot + * be delimited. This feature is not recommended if you need forceSelection to + * be true. + * + * @property delimChar + * @type String | String[] + */ +YAHOO.widget.AutoComplete.prototype.delimChar = null; + +/** + * Whether or not the first item in results container should be automatically highlighted + * on expand. + * + * @property autoHighlight + * @type Boolean + * @default true + */ +YAHOO.widget.AutoComplete.prototype.autoHighlight = true; + +/** + * Whether or not the input field should be automatically updated + * with the first query result as the user types, auto-selecting the substring + * that the user has not typed. + * + * @property typeAhead + * @type Boolean + * @default false + */ +YAHOO.widget.AutoComplete.prototype.typeAhead = false; + +/** + * Whether or not to animate the expansion/collapse of the results container in the + * horizontal direction. + * + * @property animHoriz + * @type Boolean + * @default false + */ +YAHOO.widget.AutoComplete.prototype.animHoriz = false; + +/** + * Whether or not to animate the expansion/collapse of the results container in the + * vertical direction. + * + * @property animVert + * @type Boolean + * @default true + */ +YAHOO.widget.AutoComplete.prototype.animVert = true; + +/** + * Speed of container expand/collapse animation, in seconds.. + * + * @property animSpeed + * @type Number + * @default 0.3 + */ +YAHOO.widget.AutoComplete.prototype.animSpeed = 0.3; + +/** + * Whether or not to force the user's selection to match one of the query + * results. Enabling this feature essentially transforms the input field into a + * <select> field. This feature is not recommended with delimiter character(s) + * defined. + * + * @property forceSelection + * @type Boolean + * @default false + */ +YAHOO.widget.AutoComplete.prototype.forceSelection = false; + +/** + * Whether or not to allow browsers to cache user-typed input in the input + * field. Disabling this feature will prevent the widget from setting the + * autocomplete="off" on the input field. When autocomplete="off" + * and users click the back button after form submission, user-typed input can + * be prefilled by the browser from its cache. This caching of user input may + * not be desired for sensitive data, such as credit card numbers, in which + * case, implementers should consider setting allowBrowserAutocomplete to false. + * + * @property allowBrowserAutocomplete + * @type Boolean + * @default true + */ +YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete = true; + +/** + * Whether or not the results container should always be displayed. + * Enabling this feature displays the container when the widget is instantiated + * and prevents the toggling of the container to a collapsed state. + * + * @property alwaysShowContainer + * @type Boolean + * @default false + */ +YAHOO.widget.AutoComplete.prototype.alwaysShowContainer = false; + +/** + * Whether or not to use an iFrame to layer over Windows form elements in + * IE. Set to true only when the results container will be on top of a + * <select> field in IE and thus exposed to the IE z-index bug (i.e., + * 5.5 < IE < 7). + * + * @property useIFrame + * @type Boolean + * @default false + */ +YAHOO.widget.AutoComplete.prototype.useIFrame = false; + +/** + * Whether or not the results container should have a shadow. + * + * @property useShadow + * @type Boolean + * @default false + */ +YAHOO.widget.AutoComplete.prototype.useShadow = false; + +///////////////////////////////////////////////////////////////////////////// +// +// Public methods +// +///////////////////////////////////////////////////////////////////////////// + + /** + * Public accessor to the unique name of the AutoComplete instance. + * + * @method toString + * @return {String} Unique name of the AutoComplete instance. + */ +YAHOO.widget.AutoComplete.prototype.toString = function() { + return "AutoComplete " + this._sName; +}; + + /** + * Returns true if container is in an expanded state, false otherwise. + * + * @method isContainerOpen + * @return {Boolean} Returns true if container is in an expanded state, false otherwise. + */ +YAHOO.widget.AutoComplete.prototype.isContainerOpen = function() { + return this._bContainerOpen; +}; + +/** + * Public accessor to the internal array of DOM <li> elements that + * display query results within the results container. + * + * @method getListItems + * @return {HTMLElement[]} Array of <li> elements within the results container. + */ +YAHOO.widget.AutoComplete.prototype.getListItems = function() { + return this._aListItems; +}; + +/** + * Public accessor to the data held in an <li> element of the + * results container. + * + * @method getListItemData + * @return {Object | Array} Object or array of result data or null + */ +YAHOO.widget.AutoComplete.prototype.getListItemData = function(oListItem) { + if(oListItem._oResultData) { + return oListItem._oResultData; + } + else { + return false; + } +}; + +/** + * Sets HTML markup for the results container header. This markup will be + * inserted within a <div> tag with a class of "ac_hd". + * + * @method setHeader + * @param sHeader {String} HTML markup for results container header. + */ +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"; + } +}; + +/** + * Sets HTML markup for the results container footer. This markup will be + * inserted within a <div> tag with a class of "ac_ft". + * + * @method setFooter + * @param sFooter {String} HTML markup for results container footer. + */ +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"; + } +}; + +/** + * Sets HTML markup for the results container body. This markup will be + * inserted within a <div> tag with a class of "ac_bd". + * + * @method setBody + * @param sHeader {String} HTML markup for results container body. + */ +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; +}; + +/** + * Overridable method that converts a result item object into HTML markup + * for display. Return data values are accessible via the oResultItem object, + * and the key return value will always be oResultItem[0]. Markup will be + * displayed within <li> element tags in the container. + * + * @method formatResult + * @param oResultItem {Object} Result item representing one query result. Data is held in an array. + * @param sQuery {String} The current query string. + * @return {String} HTML markup of formatted result data. + */ +YAHOO.widget.AutoComplete.prototype.formatResult = function(oResultItem, sQuery) { + var sResult = oResultItem[0]; + if(sResult) { + return sResult; + } + else { + return ""; + } +}; + +/** + * Overridable method called before container expands allows implementers to access data + * and DOM elements. + * + * @method doBeforeExpandContainer + * @return {Boolean} Return true to continue expanding container, false to cancel the expand. + */ +YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer = function(oResultItem, sQuery) { + return true; +}; + +/** + * Makes query request to the DataSource. + * + * @method sendQuery + * @param sQuery {String} Query string. + */ +YAHOO.widget.AutoComplete.prototype.sendQuery = function(sQuery) { + this._sendQuery(sQuery); +}; + +///////////////////////////////////////////////////////////////////////////// +// +// Public events +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Fired when the input field receives focus. + * + * @event textboxFocusEvent + * @param oSelf {Object} The AutoComplete instance. + */ +YAHOO.widget.AutoComplete.prototype.textboxFocusEvent = null; + +/** + * Fired when the input field receives key input. + * + * @event textboxKeyEvent + * @param oSelf {Object} The AutoComplete instance. + * @param nKeycode {Number} The keycode number. + */ +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. + */ +YAHOO.widget.AutoComplete.prototype.dataRequestEvent = null; + +/** + * Fired when the AutoComplete instance receives query results from the data + * source. + * + * @event dataReturnEvent + * @param oSelf {Object} The AutoComplete instance. + * @param sQuery {String} The query string. + * @param aResults {Array} Results array. + */ +YAHOO.widget.AutoComplete.prototype.dataReturnEvent = null; + +/** + * Fired when the AutoComplete instance does not receive query results from the + * DataSource due to an error. + * + * @event dataErrorEvent + * @param oSelf {Object} The AutoComplete instance. + * @param sQuery {String} The query string. + */ +YAHOO.widget.AutoComplete.prototype.dataErrorEvent = null; + +/** + * Fired when the results container is expanded. + * + * @event containerExpandEvent + * @param oSelf {Object} The AutoComplete instance. + */ +YAHOO.widget.AutoComplete.prototype.containerExpandEvent = null; + +/** + * Fired when the input field has been prefilled by the type-ahead + * feature. + * + * @event typeAheadEvent + * @param oSelf {Object} The AutoComplete instance. + * @param sQuery {String} The query string. + * @param sPrefill {String} The prefill string. + */ +YAHOO.widget.AutoComplete.prototype.typeAheadEvent = null; + +/** + * Fired when result item has been moused over. + * + * @event itemMouseOverEvent + * @param oSelf {Object} The AutoComplete instance. + * @param elItem {HTMLElement} The <li> element item moused to. + */ +YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent = null; + +/** + * Fired when result item has been moused out. + * + * @event itemMouseOutEvent + * @param oSelf {Object} The AutoComplete instance. + * @param elItem {HTMLElement} The <li> element item moused from. + */ +YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent = null; + +/** + * Fired when result item has been arrowed to. + * + * @event itemArrowToEvent + * @param oSelf {Object} The AutoComplete instance. + * @param elItem {HTMLElement} The <li> element item arrowed to. + */ +YAHOO.widget.AutoComplete.prototype.itemArrowToEvent = null; + +/** + * Fired when result item has been arrowed away from. + * + * @event itemArrowFromEvent + * @param oSelf {Object} The AutoComplete instance. + * @param elItem {HTMLElement} The <li> element item arrowed from. + */ +YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent = null; + +/** + * Fired when an item is selected via mouse click, ENTER key, or TAB key. + * + * @event itemSelectEvent + * @param oSelf {Object} The AutoComplete instance. + * @param elItem {HTMLElement} The selected <li> element item. + * @param oData {Object} The data returned for the item, either as an object, + * or mapped from the schema into an array. + */ +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. + * + * @event unmatchedItemSelectEvent + * @param oSelf {Object} The AutoComplete instance. + * @param sQuery {String} The user-typed query string. + */ +YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent = null; + +/** + * Fired if forceSelection is enabled and the user's input has been cleared + * because it did not match one of the returned query results. + * + * @event selectionEnforceEvent + * @param oSelf {Object} The AutoComplete instance. + */ +YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent = null; + +/** + * Fired when the results container is collapsed. + * + * @event containerCollapseEvent + * @param oSelf {Object} The AutoComplete instance. + */ +YAHOO.widget.AutoComplete.prototype.containerCollapseEvent = null; + +/** + * Fired when the input field loses focus. + * + * @event textboxBlurEvent + * @param oSelf {Object} The AutoComplete instance. + */ +YAHOO.widget.AutoComplete.prototype.textboxBlurEvent = null; + +///////////////////////////////////////////////////////////////////////////// +// +// Private member variables +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Internal class variable to index multiple AutoComplete instances. + * + * @property _nIndex + * @type Number + * @default 0 + * @private + */ +YAHOO.widget.AutoComplete._nIndex = 0; + +/** + * Name of AutoComplete instance. + * + * @property _sName + * @type String + * @private + */ +YAHOO.widget.AutoComplete.prototype._sName = null; + +/** + * Text input field DOM element. + * + * @property _oTextbox + * @type HTMLElement + * @private + */ +YAHOO.widget.AutoComplete.prototype._oTextbox = null; + +/** + * Whether or not the input field is currently in focus. If query results come back + * but the user has already moved on, do not proceed with auto complete behavior. + * + * @property _bFocused + * @type Boolean + * @private + */ +YAHOO.widget.AutoComplete.prototype._bFocused = true; + +/** + * Animation instance for container expand/collapse. + * + * @property _oAnim + * @type Boolean + * @private + */ +YAHOO.widget.AutoComplete.prototype._oAnim = null; + +/** + * Container DOM element. + * + * @property _oContainer + * @type HTMLElement + * @private + */ +YAHOO.widget.AutoComplete.prototype._oContainer = null; + +/** + * Whether or not the results container is currently open. + * + * @property _bContainerOpen + * @type Boolean + * @private + */ +YAHOO.widget.AutoComplete.prototype._bContainerOpen = false; + +/** + * Whether or not the mouse is currently over the results + * container. This is necessary in order to prevent clicks on container items + * from being text input field blur events. + * + * @property _bOverContainer + * @type Boolean + * @private + */ +YAHOO.widget.AutoComplete.prototype._bOverContainer = false; + +/** + * Array of <li> elements references that contain query results within the + * results container. + * + * @property _aListItems + * @type Array + * @private + */ +YAHOO.widget.AutoComplete.prototype._aListItems = null; + +/** + * Number of <li> elements currently displayed in results container. + * + * @property _nDisplayedItems + * @type Number + * @private + */ +YAHOO.widget.AutoComplete.prototype._nDisplayedItems = 0; + +/** + * Internal count of <li> elements displayed and hidden in results container. + * + * @property _maxResultsDisplayed + * @type Number + * @private + */ +YAHOO.widget.AutoComplete.prototype._maxResultsDisplayed = 0; + +/** + * Current query string + * + * @property _sCurQuery + * @type String + * @private + */ +YAHOO.widget.AutoComplete.prototype._sCurQuery = null; + +/** + * Past queries this session (for saving delimited queries). + * + * @property _sSavedQuery + * @type String + * @private + */ +YAHOO.widget.AutoComplete.prototype._sSavedQuery = null; + +/** + * Pointer to the currently highlighted <li> element in the container. + * + * @property _oCurItem + * @type HTMLElement + * @private + */ +YAHOO.widget.AutoComplete.prototype._oCurItem = null; + +/** + * Whether or not an item has been selected since the container was populated + * with results. Reset to false by _populateList, and set to true when item is + * selected. + * + * @property _bItemSelected + * @type Boolean + * @private + */ +YAHOO.widget.AutoComplete.prototype._bItemSelected = false; + +/** + * Key code of the last key pressed in textbox. + * + * @property _nKeyCode + * @type Number + * @private + */ +YAHOO.widget.AutoComplete.prototype._nKeyCode = null; + +/** + * Delay timeout ID. + * + * @property _nDelayID + * @type Number + * @private + */ +YAHOO.widget.AutoComplete.prototype._nDelayID = -1; + +/** + * Src to iFrame used when useIFrame = true. Supports implementations over SSL + * as well. + * + * @property _iFrameSrc + * @type String + * @private + */ +YAHOO.widget.AutoComplete.prototype._iFrameSrc = "javascript:false;"; + +/** + * For users typing via certain IMEs, queries must be triggered by intervals, + * since key events yet supported across all browsers for all IMEs. + * + * @property _queryInterval + * @type Object + * @private + */ +YAHOO.widget.AutoComplete.prototype._queryInterval = null; + +/** + * Internal tracker to last known textbox value, used to determine whether or not + * to trigger a query via interval for certain IME users. + * + * @event _sLastTextboxValue + * @type String + * @private + */ +YAHOO.widget.AutoComplete.prototype._sLastTextboxValue = null; + +///////////////////////////////////////////////////////////////////////////// +// +// Private methods +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Updates and validates latest public config properties. + * + * @method __initProps + * @private + */ +YAHOO.widget.AutoComplete.prototype._initProps = function() { + // Correct any invalid values + 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) { + } +}; + +/** + * Initializes the results container helpers if they are enabled and do + * not exist + * + * @method _initContainerHelpers + * @private + */ +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); + } +}; + +/** + * Initializes the results container once at object creation + * + * @method _initContainer + * @private + */ +YAHOO.widget.AutoComplete.prototype._initContainer = function() { + if(!this._oContainer._oContent) { + // The oContent div helps size the iframe and shadow properly + 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 { + } +}; + +/** + * Clears out contents of container body and creates up to + * YAHOO.widget.AutoComplete#maxResultsDisplayed <li> elements in an + * <ul> element. + * + * @method _initList + * @private + */ +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) || // alt,pause/break,caps lock + (nKeyCode == 27) || // esc + (nKeyCode >= 33 && nKeyCode <= 35) || // page up,page down,end + (nKeyCode >= 36 && nKeyCode <= 38) || // home,left,up + (nKeyCode == 40) || // down + (nKeyCode >= 44 && nKeyCode <= 45)) { // print screen,insert + return true; + } + return false; +}; + +/** + * Makes query request to the DataSource. + * + * @method _sendQuery + * @param sQuery {String} Query string. + * @private + */ +YAHOO.widget.AutoComplete.prototype._sendQuery = function(sQuery) { + // Widget has been effectively turned off + if(this.minQueryLength == -1) { + this._toggleContainer(false); + return; + } + // Delimiter has been enabled + var aDelimChar = (this.delimChar) ? this.delimChar : null; + if(aDelimChar) { + // Loop through all possible delimiters and find the latest one + // A " " may be a false positive if they are defined as delimiters AND + // are used to separate delimited queries + var nDelimIndex = -1; + for(var i = aDelimChar.length-1; i >= 0; i--) { + var nNewIndex = sQuery.lastIndexOf(aDelimChar[i]); + if(nNewIndex > nDelimIndex) { + nDelimIndex = nNewIndex; + } + } + // If we think the last delimiter is a space (" "), make sure it is NOT + // a false positive by also checking the char directly before it + if(aDelimChar[i] == " ") { + for (var j = aDelimChar.length-1; j >= 0; j--) { + if(sQuery[nDelimIndex - 1] == aDelimChar[j]) { + nDelimIndex--; + break; + } + } + } + // A delimiter has been found so extract the latest query + if (nDelimIndex > -1) { + var nQueryStart = nDelimIndex + 1; + // Trim any white space from the beginning... + while(sQuery.charAt(nQueryStart) == " ") { + nQueryStart += 1; + } + // ...and save the rest of the string for later + this._sSavedQuery = sQuery.substring(0,nQueryStart); + // Here is the query itself + sQuery = sQuery.substr(nQueryStart); + } + else if(sQuery.indexOf(this._sSavedQuery) < 0){ + this._sSavedQuery = null; + } + } + + // Don't search queries that are too short + if (sQuery && (sQuery.length < this.minQueryLength) || (!sQuery && this.minQueryLength > 0)) { + if (this._nDelayID != -1) { + clearTimeout(this._nDelayID); + } + this._toggleContainer(false); + return; + } + + sQuery = encodeURIComponent(sQuery); + this._nDelayID = -1; // Reset timeout ID because request has been made + this.dataRequestEvent.fire(this, sQuery); + this.dataSource.getResults(this._populateList, sQuery, this); +}; + +/** + * Populates the array of <li> elements in the container with query + * results. This method is passed to YAHOO.widget.DataSource#getResults as a + * callback function so results from the DataSource instance are returned to the + * AutoComplete instance. + * + * @method _populateList + * @param sQuery {String} The query string. + * @param aResults {Array} An array of query result objects from the DataSource. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +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; + + // Fill items with data + 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; + + } + + // Empty out remaining items if any + 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) { + // Go to the first item + var oFirstItem = aItems[0]; + oSelf._toggleHighlight(oFirstItem,"to"); + oSelf.itemArrowToEvent.fire(oSelf, oFirstItem); + oSelf._typeAhead(oFirstItem,sQuery); + } + else { + oSelf._oCurItem = null; + } + + // Expand the container + var ok = oSelf.doBeforeExpandContainer(oSelf._oTextbox, oSelf._oContainer, sQuery, aResults); + oSelf._toggleContainer(ok); + } + else { + oSelf._toggleContainer(false); + } + oSelf.dataReturnEvent.fire(oSelf, sQuery, aResults); +}; + +/** + * When forceSelection is true and the user attempts + * leave the text input box without selecting an item from the query results, + * the user selection is cleared. + * + * @method _clearSelection + * @private + */ +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; + + // Fire custom event + this.selectionEnforceEvent.fire(this); +}; + +/** + * Whether or not user-typed value in the text input box matches any of the + * query results. + * + * @method _textMatchesOption + * @return {Boolean} True if user-input text matches a result, false otherwise. + * @private + */ +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); +}; + +/** + * Updates in the text input box with the first query result as the user types, + * selecting the substring that the user has not typed. + * + * @method _typeAhead + * @param oItem {HTMLElement} The <li> element item whose data populates the input field. + * @param sQuery {String} Query string. + * @private + */ +YAHOO.widget.AutoComplete.prototype._typeAhead = function(oItem, sQuery) { + // Don't update if turned off + if (!this.typeAhead) { + return; + } + + var oTextbox = this._oTextbox; + var sValue = this._oTextbox.value; // any saved queries plus what user has typed + + // Don't update with type-ahead if text selection is not supported + if(!oTextbox.setSelectionRange && !oTextbox.createTextRange) { + return; + } + + // Select the portion of text that the user has not typed + 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); +}; + +/** + * Selects text in the input field. + * + * @method _selectText + * @param oTextbox {HTMLElement} Text input box element in which to select text. + * @param nStart {Number} Starting index of text string to select. + * @param nEnd {Number} Ending index of text selection. + * @private + */ +YAHOO.widget.AutoComplete.prototype._selectText = function(oTextbox, nStart, nEnd) { + if (oTextbox.setSelectionRange) { // For Mozilla + oTextbox.setSelectionRange(nStart,nEnd); + } + else if (oTextbox.createTextRange) { // For IE + var oTextRange = oTextbox.createTextRange(); + oTextRange.moveStart("character", nStart); + oTextRange.moveEnd("character", nEnd-oTextbox.value.length); + oTextRange.select(); + } + else { + oTextbox.select(); + } +}; + +/** + * Syncs results container with its helpers. + * + * @method _toggleContainerHelpers + * @param bShow {Boolean} True if container is expanded, false if collapsed + * @private + */ +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; + } + } +}; + +/** + * Animates expansion or collapse of the container. + * + * @method _toggleContainer + * @param bShow {Boolean} True if container should be expanded, false if container should be collapsed + * @private + */ +YAHOO.widget.AutoComplete.prototype._toggleContainer = function(bShow) { + var oContainer = this._oContainer; + + // Implementer has container always open so don't mess with it + if(this.alwaysShowContainer && this._bContainerOpen) { + return; + } + + // Clear contents of container + 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; + } + + // Container is already closed + if (!bShow && !this._bContainerOpen) { + oContainer._oContent.style.display = "none"; + return; + } + + // If animation is enabled... + var oAnim = this._oAnim; + if (oAnim && oAnim.getEl() && (this.animHoriz || this.animVert)) { + // If helpers need to be collapsed, do it right away... + // but if helpers need to be expanded, wait until after the container expands + if(!bShow) { + this._toggleContainerHelpers(bShow); + } + + if(oAnim.isAnimated()) { + oAnim.stop(); + } + + // Clone container to grab current size offscreen + var oClone = oContainer._oContent.cloneNode(true); + oContainer.appendChild(oClone); + oClone.style.top = "-9000px"; + oClone.style.display = "block"; + + // Current size of the container is the EXPANDED size + var wExp = oClone.offsetWidth; + var hExp = oClone.offsetHeight; + + // Calculate COLLAPSED sizes based on horiz and vert anim + var wColl = (this.animHoriz) ? 0 : wExp; + var hColl = (this.animVert) ? 0 : hExp; + + // Set animation sizes + oAnim.attributes = (bShow) ? + {width: { to: wExp }, height: { to: hExp }} : + {width: { to: wColl}, height: { to: hColl }}; + + // If opening anew, set to a collapsed size... + if(bShow && !this._bContainerOpen) { + oContainer._oContent.style.width = wColl+"px"; + oContainer._oContent.style.height = hColl+"px"; + } + // Else, set it to its last known size. + else { + oContainer._oContent.style.width = wExp+"px"; + oContainer._oContent.style.height = hExp+"px"; + } + + oContainer.removeChild(oClone); + oClone = null; + + var oSelf = this; + var onAnimComplete = function() { + // Finish the collapse + oAnim.onComplete.unsubscribeAll(); + + if(bShow) { + oSelf.containerExpandEvent.fire(oSelf); + } + else { + oContainer._oContent.style.display = "none"; + oSelf.containerCollapseEvent.fire(oSelf); + } + oSelf._toggleContainerHelpers(bShow); + }; + + // Display container and animate it + oContainer._oContent.style.display = "block"; + oAnim.onComplete.subscribe(onAnimComplete); + oAnim.animate(); + this._bContainerOpen = bShow; + } + // Else don't animate, just show or hide + 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; + } + +}; + +/** + * Toggles the highlight on or off for an item in the container, and also cleans + * up highlighting of any previous item. + * + * @method _toggleHighlight + * @param oNewItem {HTMLElement} The <li> element item to receive highlight behavior. + * @param sType {String} Type "mouseover" will toggle highlight on, and "mouseout" will toggle highlight off. + * @private + */ +YAHOO.widget.AutoComplete.prototype._toggleHighlight = function(oNewItem, sType) { + var sHighlight = this.highlightClassName; + if(this._oCurItem) { + // Remove highlight from old item + YAHOO.util.Dom.removeClass(this._oCurItem, sHighlight); + } + + if((sType == "to") && sHighlight) { + // Apply highlight to new item + YAHOO.util.Dom.addClass(oNewItem, sHighlight); + this._oCurItem = oNewItem; + } +}; + +/** + * Toggles the pre-highlight on or off for an item in the container. + * + * @method _togglePrehighlight + * @param oNewItem {HTMLElement} The <li> element item to receive highlight behavior. + * @param sType {String} Type "mouseover" will toggle highlight on, and "mouseout" will toggle highlight off. + * @private + */ +YAHOO.widget.AutoComplete.prototype._togglePrehighlight = function(oNewItem, sType) { + if(oNewItem == this._oCurItem) { + return; + } + + var sPrehighlight = this.prehighlightClassName; + if((sType == "mouseover") && sPrehighlight) { + // Apply prehighlight to new item + YAHOO.util.Dom.addClass(oNewItem, sPrehighlight); + } + else { + // Remove prehighlight from old item + YAHOO.util.Dom.removeClass(oNewItem, sPrehighlight); + } +}; + +/** + * Updates the text input box value with selected query result. If a delimiter + * has been defined, then the value gets appended with the delimiter. + * + * @method _updateValue + * @param oItem {HTMLElement} The <li> element item with which to update the value. + * @private + */ +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(); + + // First clear text field + oTextbox.value = ""; + // Grab data to put into text field + if(sDelimChar) { + if(sSavedQuery) { + oTextbox.value = sSavedQuery; + } + oTextbox.value += sResultKey + sDelimChar; + if(sDelimChar != " ") { + oTextbox.value += " "; + } + } + else { oTextbox.value = sResultKey; } + + // scroll to bottom of textarea if necessary + if(oTextbox.type == "textarea") { + oTextbox.scrollTop = oTextbox.scrollHeight; + } + + // move cursor to end + var end = oTextbox.value.length; + this._selectText(oTextbox,end,end); + + this._oCurItem = oItem; +}; + +/** + * Selects a result item from the container + * + * @method _selectItem + * @param oItem {HTMLElement} The selected <li> element item. + * @private + */ +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); +}; + +/** + * For values updated by type-ahead, the right arrow key jumps to the end + * of the textbox, otherwise the container is closed. + * + * @method _jumpSelection + * @private + */ +YAHOO.widget.AutoComplete.prototype._jumpSelection = function() { + if(!this.typeAhead) { + return; + } + else { + this._toggleContainer(false); + } +}; + +/** + * Triggered by up and down arrow keys, changes the current highlighted + * <li> element item. Scrolls container if necessary. + * + * @method _moveSelection + * @param nKeyCode {Number} Code of key pressed. + * @private + */ +YAHOO.widget.AutoComplete.prototype._moveSelection = function(nKeyCode) { + if(this._bContainerOpen) { + // Determine current item's id number + var oCurItem = this._oCurItem; + var nCurItemIndex = -1; + + if (oCurItem) { + nCurItemIndex = oCurItem._nItemIndex; + } + + var nNewItemIndex = (nKeyCode == 40) ? + (nCurItemIndex + 1) : (nCurItemIndex - 1); + + // Out of bounds + if (nNewItemIndex < -2 || nNewItemIndex >= this._nDisplayedItems) { + return; + } + + if (oCurItem) { + // Unhighlight current item + this._toggleHighlight(oCurItem, "from"); + this.itemArrowFromEvent.fire(this, oCurItem); + } + if (nNewItemIndex == -1) { + // Go back to query (remove type-ahead string) + 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) { + // Close container + this._toggleContainer(false); + return; + } + + var oNewItem = this._aListItems[nNewItemIndex]; + + // Scroll the container if necessary + 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 < this._nDisplayedItems)) { + // User is keying down + if(nKeyCode == 40) { + // Bottom of selected item is below scroll area... + if((oNewItem.offsetTop+oNewItem.offsetHeight) > (oContent.scrollTop + oContent.offsetHeight)) { + // Set bottom of scroll area to bottom of selected item + oContent.scrollTop = (oNewItem.offsetTop+oNewItem.offsetHeight) - oContent.offsetHeight; + } + // Bottom of selected item is above scroll area... + else if((oNewItem.offsetTop+oNewItem.offsetHeight) < oContent.scrollTop) { + // Set top of selected item to top of scroll area + oContent.scrollTop = oNewItem.offsetTop; + + } + } + // User is keying up + else { + // Top of selected item is above scroll area + if(oNewItem.offsetTop < oContent.scrollTop) { + // Set top of scroll area to top of selected item + this._oContainer._oContent.scrollTop = oNewItem.offsetTop; + } + // Top of selected item is below scroll area + else if(oNewItem.offsetTop > (oContent.scrollTop + oContent.offsetHeight)) { + // Set bottom of selected item to bottom of scroll area + 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); + } + } +}; + +///////////////////////////////////////////////////////////////////////////// +// +// Private event handlers +// +///////////////////////////////////////////////////////////////////////////// + +/** + * Handles <li> element mouseover events in the container. + * + * @method _onItemMouseover + * @param v {HTMLEvent} The mouseover event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +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); +}; + +/** + * Handles <li> element mouseout events in the container. + * + * @method _onItemMouseout + * @param v {HTMLEvent} The mouseout event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +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); +}; + +/** + * Handles <li> element click events in the container. + * + * @method _onItemMouseclick + * @param v {HTMLEvent} The click event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onItemMouseclick = function(v,oSelf) { + // In case item has not been moused over + oSelf._toggleHighlight(this,"to"); + oSelf._selectItem(this); +}; + +/** + * Handles container mouseover events. + * + * @method _onContainerMouseover + * @param v {HTMLEvent} The mouseover event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onContainerMouseover = function(v,oSelf) { + oSelf._bOverContainer = true; +}; + +/** + * Handles container mouseout events. + * + * @method _onContainerMouseout + * @param v {HTMLEvent} The mouseout event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onContainerMouseout = function(v,oSelf) { + oSelf._bOverContainer = false; + // If container is still active + if(oSelf._oCurItem) { + oSelf._toggleHighlight(oSelf._oCurItem,"to"); + } +}; + +/** + * Handles container scroll events. + * + * @method _onContainerScroll + * @param v {HTMLEvent} The scroll event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onContainerScroll = function(v,oSelf) { + oSelf._oTextbox.focus(); +}; + +/** + * Handles container resize events. + * + * @method _onContainerResize + * @param v {HTMLEvent} The resize event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onContainerResize = function(v,oSelf) { + oSelf._toggleContainerHelpers(oSelf._bContainerOpen); +}; + +/** + * Handles textbox keydown events of functional keys, mainly for UI behavior. + * + * @method _onTextboxKeyDown + * @param v {HTMLEvent} The keydown event. + * @param oSelf {object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown = function(v,oSelf) { + var nKeyCode = v.keyCode; + + switch (nKeyCode) { + case 9: // tab + if(oSelf.delimChar && (oSelf._nKeyCode != nKeyCode)) { + if(oSelf._bContainerOpen) { + YAHOO.util.Event.stopEvent(v); + } + } + // select an item or clear out + if(oSelf._oCurItem) { + oSelf._selectItem(oSelf._oCurItem); + } + else { + oSelf._toggleContainer(false); + } + break; + case 13: // enter + 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: // esc + oSelf._toggleContainer(false); + return; + case 39: // right + oSelf._jumpSelection(); + break; + case 38: // up + YAHOO.util.Event.stopEvent(v); + oSelf._moveSelection(nKeyCode); + break; + case 40: // down + YAHOO.util.Event.stopEvent(v); + oSelf._moveSelection(nKeyCode); + break; + default: + break; + } +}; + +/** + * Handles textbox keypress events. + * @method _onTextboxKeyPress + * @param v {HTMLEvent} The keypress event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress = function(v,oSelf) { + var nKeyCode = v.keyCode; + + //Expose only to Mac browsers, where stopEvent is ineffective on keydown events (bug 790337) + var isMac = (navigator.userAgent.toLowerCase().indexOf("mac") != -1); + if(isMac) { + switch (nKeyCode) { + case 9: // tab + if(oSelf.delimChar && (oSelf._nKeyCode != nKeyCode)) { + if(oSelf._bContainerOpen) { + YAHOO.util.Event.stopEvent(v); + } + } + break; + case 13: // enter + if(oSelf._nKeyCode != nKeyCode) { + if(oSelf._bContainerOpen) { + YAHOO.util.Event.stopEvent(v); + } + } + break; + case 38: // up + case 40: // down + YAHOO.util.Event.stopEvent(v); + break; + default: + break; + } + } + + //TODO: (?) limit only to non-IE, non-Mac-FF for Korean IME support (bug 811948) + // Korean IME detected + else if(nKeyCode == 229) { + oSelf._queryInterval = setInterval(function() { oSelf._onIMEDetected(oSelf); },500); + } +}; + +/** + * Handles textbox keyup events that trigger queries. + * + * @method _onTextboxKeyUp + * @param v {HTMLEvent} The keyup event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp = function(v,oSelf) { + // Check to see if any of the public properties have been updated + oSelf._initProps(); + + var nKeyCode = v.keyCode; + oSelf._nKeyCode = nKeyCode; + var sText = this.value; //string in textbox + + // Filter out chars that don't trigger queries + if (oSelf._isIgnoreKey(nKeyCode) || (sText.toLowerCase() == oSelf._sCurQuery)) { + return; + } + else { + oSelf.textboxKeyEvent.fire(oSelf, nKeyCode); + } + + // Set timeout on the request + 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 { + // No delay so send request immediately + oSelf._sendQuery(sText); + } +}; + +/** + * Handles text input box receiving focus. + * + * @method _onTextboxFocus + * @param v {HTMLEvent} The focus event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onTextboxFocus = function (v,oSelf) { + oSelf._oTextbox.setAttribute("autocomplete","off"); + oSelf._bFocused = true; + oSelf.textboxFocusEvent.fire(oSelf); +}; + +/** + * Handles text input box losing focus. + * + * @method _onTextboxBlur + * @param v {HTMLEvent} The focus event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onTextboxBlur = function (v,oSelf) { + // Don't treat as a blur if it was a selection via mouse click + if(!oSelf._bOverContainer || (oSelf._nKeyCode == 9)) { + // Current query needs to be validated + 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); + } +}; + +/** + * Handles form submission event. + * + * @method _onFormSubmit + * @param v {HTMLEvent} The submit event. + * @param oSelf {Object} The AutoComplete instance. + * @private + */ +YAHOO.widget.AutoComplete.prototype._onFormSubmit = function(v,oSelf) { + if(oSelf.allowBrowserAutocomplete) { + oSelf._oTextbox.setAttribute("autocomplete","on"); + } + else { + 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 {String} 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/frontend/beta/js/YUI/calendar.js b/frontend/beta/js/YUI/calendar.js new file mode 100644 index 0000000..3593551 --- a/dev/null +++ b/frontend/beta/js/YUI/calendar.js @@ -0,0 +1,4239 @@ +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version 0.12.0 +*/ + +/** +* 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. +* @class YAHOO.util.Config +* @constructor +* @param {Object} owner The owner Object to which this Config Object belongs +*/ +YAHOO.util.Config = function(owner) { + if (owner) { + this.init(owner); + } +}; + +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 ) { + 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(); + + 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(); + + 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(); + + 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 Widget +* @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= 200 && httpStatus < 300){ + try + { + responseObject = this.createResponseObject(o, callback.argument); + if(callback.success){ + if(!callback.scope){ + callback.success(responseObject); + } + else{ + // If a scope property is defined, the callback will be fired from + // the context of the object. + callback.success.apply(callback.scope, [responseObject]); + } + } + } + catch(e){} + } + else{ + try + { + switch(httpStatus){ + // The following cases are wininet.dll error codes that may be encountered. + case 12002: // Server timeout + case 12029: // 12029 to 12031 correspond to dropped connections. + case 12030: + case 12031: + case 12152: // Connection closed by server. + case 13030: // See above comments for variable status. + responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort?isAbort:false)); + if(callback.failure){ + if(!callback.scope){ + callback.failure(responseObject); + } + else{ + callback.failure.apply(callback.scope, [responseObject]); + } + } + break; + default: + responseObject = this.createResponseObject(o, callback.argument); + if(callback.failure){ + if(!callback.scope){ + callback.failure(responseObject); + } + else{ + callback.failure.apply(callback.scope, [responseObject]); + } + } + } + } + catch(e){} + } + + this.releaseObject(o); + responseObject = null; + }, + + /** + * @description This method evaluates the server response, creates and returns the results via + * its properties. Success and failure cases will differ in the response + * object's property values. + * @method createResponseObject + * @private + * @static + * @param {object} o The connection object + * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback + * @return {object} + */ + createResponseObject:function(o, callbackArg) + { + var obj = {}; + var headerObj = {}; + + try + { + var headerStr = o.conn.getAllResponseHeaders(); + var header = headerStr.split('\n'); + for(var i=0; i'); + + // IE will throw a security exception in an SSL environment if the + // iframe source is undefined. + if(typeof secureUri == 'boolean'){ + io.src = 'javascript:false'; + } + else if(typeof secureURI == 'string'){ + // Deprecated + io.src = secureUri; + } + } + else{ + var io = document.createElement('iframe'); + io.id = frameId; + io.name = frameId; + } + + io.style.position = 'absolute'; + io.style.top = '-1000px'; + io.style.left = '-1000px'; + + document.body.appendChild(io); + }, + + /** + * @description Parses the POST data and creates hidden form elements + * for each key-value, and appends them to the HTML form object. + * @method appendPostData + * @private + * @static + * @param {string} postData The HTTP POST data + * @return {array} formElements Collection of hidden fields. + */ + appendPostData:function(postData) + { + var formElements = new Array(); + var postMessage = postData.split('&'); + for(var i=0; i < postMessage.length; i++){ + var delimitPos = postMessage[i].indexOf('='); + if(delimitPos != -1){ + formElements[i] = document.createElement('input'); + formElements[i].type = 'hidden'; + formElements[i].name = postMessage[i].substring(0,delimitPos); + formElements[i].value = postMessage[i].substring(delimitPos+1); + this._formNode.appendChild(formElements[i]); + } + } + + return formElements; + }, + + /** + * @description Uploads HTML form, including files/attachments, to the + * iframe created in createFrame. + * @method uploadFile + * @private + * @static + * @param {int} id The transaction id. + * @param {object} callback - User-defined callback object. + * @param {string} uri Fully qualified path of resource. + * @return {void} + */ + uploadFile:function(id, callback, uri, postData){ + + // Each iframe has an id prefix of "yuiIO" followed + // by the unique transaction id. + var frameId = 'yuiIO' + id; + var io = document.getElementById(frameId); + + // Initialize the HTML form properties in case they are + // not defined in the HTML form. + this._formNode.action = uri; + this._formNode.method = 'POST'; + this._formNode.target = frameId; + + if(this._formNode.encoding){ + // IE does not respect property enctype for HTML forms. + // Instead use property encoding. + this._formNode.encoding = 'multipart/form-data'; + } + else{ + this._formNode.enctype = 'multipart/form-data'; + } + + if(postData){ + var oElements = this.appendPostData(postData); + } + + this._formNode.submit(); + + if(oElements && oElements.length > 0){ + try + { + for(var i=0; i < oElements.length; i++){ + this._formNode.removeChild(oElements[i]); + } + } + catch(e){} + } + + // Reset HTML form status properties. + this.resetFormState(); + + // Create the upload callback handler that fires when the iframe + // receives the load event. Subsequently, the event handler is detached + // and the iframe removed from the document. + + var uploadCallback = function() + { + var obj = {}; + obj.tId = id; + obj.argument = callback.argument; + + try + { + obj.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; + obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; + } + catch(e){} + + if(callback.upload){ + if(!callback.scope){ + callback.upload(obj); + } + else{ + callback.upload.apply(callback.scope, [obj]); + } + } + + if(YAHOO.util.Event){ + YAHOO.util.Event.removeListener(io, "load", uploadCallback); + } + else if(window.detachEvent){ + io.detachEvent('onload', uploadCallback); + } + else{ + io.removeEventListener('load', uploadCallback, false); + } + setTimeout(function(){ document.body.removeChild(io); }, 100); + }; + + + // Bind the onload handler to the iframe to detect the file upload response. + if(YAHOO.util.Event){ + YAHOO.util.Event.addListener(io, "load", uploadCallback); + } + else if(window.attachEvent){ + io.attachEvent('onload', uploadCallback); + } + else{ + io.addEventListener('load', uploadCallback, false); + } + }, + + /** + * @description Method to terminate a transaction, if it has not reached readyState 4. + * @method abort + * @public + * @static + * @param {object} o The connection object returned by asyncRequest. + * @param {object} callback User-defined callback object. + * @param {string} isTimeout boolean to indicate if abort was a timeout. + * @return {boolean} + */ + abort:function(o, callback, isTimeout) + { + if(this.isCallInProgress(o)){ + o.conn.abort(); + window.clearInterval(this._poll[o.tId]); + delete this._poll[o.tId]; + if(isTimeout){ + delete this._timeOut[o.tId]; + } + + this.handleTransactionResponse(o, callback, true); + + return true; + } + else{ + return false; + } + }, + + /** + * Public method to check if the transaction is still being processed. + * + * @method isCallInProgress + * @public + * @static + * @param {object} o The connection object returned by asyncRequest + * @return {boolean} + */ + isCallInProgress:function(o) + { + // if the XHR object assigned to the transaction has not been dereferenced, + // then check its readyState status. Otherwise, return false. + if(o.conn){ + return o.conn.readyState != 4 && o.conn.readyState != 0; + } + else{ + //The XHR object has been destroyed. + return false; + } + }, + + /** + * @description Dereference the XHR instance and the connection object after the transaction is completed. + * @method releaseObject + * @private + * @static + * @param {object} o The connection object + * @return {void} + */ + releaseObject:function(o) + { + //dereference the XHR instance. + o.conn = null; + //dereference the connection object. + o = null; + } +}; \ No newline at end of file diff --git a/frontend/beta/js/YUI/container.js b/frontend/beta/js/YUI/container.js new file mode 100644 index 0000000..ec0f864 --- a/dev/null +++ b/frontend/beta/js/YUI/container.js @@ -0,0 +1,4561 @@ +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version 0.12.0 +*/ + +/** +* 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. +* @class YAHOO.util.Config +* @constructor +* @param {Object} owner The owner Object to which this Config Object belongs +*/ +YAHOO.util.Config = function(owner) { + if (owner) { + this.init(owner); + } +}; + +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 ) { + 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(); + + 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(); + + 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(); + + 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;iOR +* @param {HTMLElement} el The element representing the Module +* @param {Object} userConfig The configuration Object literal containing the configuration that should be set for this module. See configuration documentation for more details. +*/ +YAHOO.widget.Module = function(el, userConfig) { + if (el) { + this.init(el, userConfig); + } +}; + +/** +* Constant representing the prefix path to use for non-secure images +* @property YAHOO.widget.Module.IMG_ROOT +* @static +* @final +* @type String +*/ +YAHOO.widget.Module.IMG_ROOT = "http://us.i1.yimg.com/us.yimg.com/i/"; + +/** +* Constant representing the prefix path to use for securely served images +* @property YAHOO.widget.Module.IMG_ROOT_SSL +* @static +* @final +* @type String +*/ +YAHOO.widget.Module.IMG_ROOT_SSL = "https://a248.e.akamai.net/sec.yimg.com/i/"; + +/** +* Constant for the default CSS class name that represents a Module +* @property YAHOO.widget.Module.CSS_MODULE +* @static +* @final +* @type String +*/ +YAHOO.widget.Module.CSS_MODULE = "module"; + +/** +* Constant representing the module header +* @property YAHOO.widget.Module.CSS_HEADER +* @static +* @final +* @type String +*/ +YAHOO.widget.Module.CSS_HEADER = "hd"; + +/** +* Constant representing the module body +* @property YAHOO.widget.Module.CSS_BODY +* @static +* @final +* @type String +*/ +YAHOO.widget.Module.CSS_BODY = "bd"; + +/** +* Constant representing the module footer +* @property YAHOO.widget.Module.CSS_FOOTER +* @static +* @final +* @type String +*/ +YAHOO.widget.Module.CSS_FOOTER = "ft"; + +/** +* Constant representing the url for the "src" attribute of the iframe used to monitor changes to the browser's base font size +* @property YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL +* @static +* @final +* @type String +*/ +YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL = "javascript:false;"; + +YAHOO.widget.Module.prototype = { + /** + * The class's constructor function + * @property contructor + * @type Function + */ + constructor : YAHOO.widget.Module, + + /** + * The main module element that contains the header, body, and footer + * @property element + * @type HTMLElement + */ + element : null, + + /** + * The header element, denoted with CSS class "hd" + * @property header + * @type HTMLElement + */ + header : null, + + /** + * The body element, denoted with CSS class "bd" + * @property body + * @type HTMLElement + */ + body : null, + + /** + * The footer element, denoted with CSS class "ft" + * @property footer + * @type HTMLElement + */ + footer : null, + + /** + * The id of the element + * @property id + * @type String + */ + id : null, + + /** + * The String representing the image root + * @property imageRoot + * @type String + */ + imageRoot : YAHOO.widget.Module.IMG_ROOT, + + /** + * Initializes the custom events for Module which are fired automatically at appropriate times by the Module class. + * @method initEvents + */ + initEvents : function() { + + /** + * CustomEvent fired prior to class initalization. + * @event beforeInitEvent + * @param {class} classRef class reference of the initializing class, such as this.beforeInitEvent.fire(YAHOO.widget.Module) + */ + this.beforeInitEvent = new YAHOO.util.CustomEvent("beforeInit"); + + /** + * CustomEvent fired after class initalization. + * @event initEvent + * @param {class} classRef class reference of the initializing class, such as this.beforeInitEvent.fire(YAHOO.widget.Module) + */ + this.initEvent = new YAHOO.util.CustomEvent("init"); + + /** + * CustomEvent fired when the Module is appended to the DOM + * @event appendEvent + */ + this.appendEvent = new YAHOO.util.CustomEvent("append"); + + /** + * CustomEvent fired before the Module is rendered + * @event beforeRenderEvent + */ + this.beforeRenderEvent = new YAHOO.util.CustomEvent("beforeRender"); + + /** + * CustomEvent fired after the Module is rendered + * @event renderEvent + */ + this.renderEvent = new YAHOO.util.CustomEvent("render"); + + /** + * CustomEvent fired when the header content of the Module is modified + * @event changeHeaderEvent + * @param {String/HTMLElement} content String/element representing the new header content + */ + this.changeHeaderEvent = new YAHOO.util.CustomEvent("changeHeader"); + + /** + * CustomEvent fired when the body content of the Module is modified + * @event changeBodyEvent + * @param {String/HTMLElement} content String/element representing the new body content + */ + this.changeBodyEvent = new YAHOO.util.CustomEvent("changeBody"); + + /** + * CustomEvent fired when the footer content of the Module is modified + * @event changeFooterEvent + * @param {String/HTMLElement} content String/element representing the new footer content + */ + this.changeFooterEvent = new YAHOO.util.CustomEvent("changeFooter"); + + /** + * CustomEvent fired when the content of the Module is modified + * @event changeContentEvent + */ + this.changeContentEvent = new YAHOO.util.CustomEvent("changeContent"); + + /** + * CustomEvent fired when the Module is destroyed + * @event destroyEvent + */ + this.destroyEvent = new YAHOO.util.CustomEvent("destroy"); + + /** + * CustomEvent fired before the Module is shown + * @event beforeShowEvent + */ + this.beforeShowEvent = new YAHOO.util.CustomEvent("beforeShow"); + + /** + * CustomEvent fired after the Module is shown + * @event showEvent + */ + this.showEvent = new YAHOO.util.CustomEvent("show"); + + /** + * CustomEvent fired before the Module is hidden + * @event beforeHideEvent + */ + this.beforeHideEvent = new YAHOO.util.CustomEvent("beforeHide"); + + /** + * CustomEvent fired after the Module is hidden + * @event hideEvent + */ + this.hideEvent = new YAHOO.util.CustomEvent("hide"); + }, + + /** + * String representing the current user-agent platform + * @property platform + * @type String + */ + platform : function() { + var ua = navigator.userAgent.toLowerCase(); + if (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1) { + return "windows"; + } else if (ua.indexOf("macintosh") != -1) { + return "mac"; + } else { + return false; + } + }(), + + /** + * String representing the current user-agent browser + * @property browser + * @type String + */ + browser : function() { + var ua = navigator.userAgent.toLowerCase(); + if (ua.indexOf('opera')!=-1) { // Opera (check first in case of spoof) + return 'opera'; + } else if (ua.indexOf('msie 7')!=-1) { // IE7 + return 'ie7'; + } else if (ua.indexOf('msie') !=-1) { // IE + return 'ie'; + } else if (ua.indexOf('safari')!=-1) { // Safari (check before Gecko because it includes "like Gecko") + return 'safari'; + } else if (ua.indexOf('gecko') != -1) { // Gecko + return 'gecko'; + } else { + return false; + } + }(), + + /** + * Boolean representing whether or not the current browsing context is secure (https) + * @property isSecure + * @type Boolean + */ + isSecure : function() { + if (window.location.href.toLowerCase().indexOf("https") === 0) { + return true; + } else { + return false; + } + }(), + + /** + * Initializes the custom events for Module which are fired automatically at appropriate times by the Module class. + */ + initDefaultConfig : function() { + // Add properties // + + /** + * Specifies whether the Module is visible on the page. + * @config visible + * @type Boolean + * @default true + */ + this.cfg.addProperty("visible", { value:true, handler:this.configVisible, validator:this.cfg.checkBoolean } ); + + /** + * Object or array of objects representing the ContainerEffect classes that are active for animating the container. + * @config effect + * @type Object + * @default null + */ + this.cfg.addProperty("effect", { suppressEvent:true, supercedes:["visible"] } ); + + /** + * Specifies whether to create a special proxy iframe to monitor for user font resizing in the document + * @config monitorresize + * @type Boolean + * @default true + */ + this.cfg.addProperty("monitorresize", { value:true, handler:this.configMonitorResize } ); + }, + + /** + * The Module class's initialization method, which is executed for Module and all of its subclasses. This method is automatically called by the constructor, and sets up all DOM references for pre-existing markup, and creates required markup if it is not already present. + * @method init + * @param {String} el The element ID representing the Module OR + * @param {HTMLElement} el The element representing the Module + * @param {Object} userConfig The configuration Object literal containing the configuration that should be set for this module. See configuration documentation for more details. + */ + init : function(el, userConfig) { + + this.initEvents(); + + this.beforeInitEvent.fire(YAHOO.widget.Module); + + /** + * The Module's Config object used for monitoring configuration properties. + * @property cfg + * @type YAHOO.util.Config + */ + this.cfg = new YAHOO.util.Config(this); + + if (this.isSecure) { + this.imageRoot = YAHOO.widget.Module.IMG_ROOT_SSL; + } + + if (typeof el == "string") { + var elId = el; + + el = document.getElementById(el); + if (! el) { + el = document.createElement("DIV"); + el.id = elId; + } + } + + this.element = el; + + if (el.id) { + this.id = el.id; + } + + var childNodes = this.element.childNodes; + + if (childNodes) { + for (var i=0;iOR + * @param {HTMLElement} headerContent The HTMLElement to append to the header + */ + setHeader : function(headerContent) { + if (! this.header) { + this.header = document.createElement("DIV"); + this.header.className = YAHOO.widget.Module.CSS_HEADER; + } + + if (typeof headerContent == "string") { + this.header.innerHTML = headerContent; + } else { + this.header.innerHTML = ""; + this.header.appendChild(headerContent); + } + + this.changeHeaderEvent.fire(headerContent); + this.changeContentEvent.fire(); + }, + + /** + * Appends the passed element to the header. If no header is present, one will be automatically created. + * @method appendToHeader + * @param {HTMLElement} element The element to append to the header + */ + appendToHeader : function(element) { + if (! this.header) { + this.header = document.createElement("DIV"); + this.header.className = YAHOO.widget.Module.CSS_HEADER; + } + + this.header.appendChild(element); + this.changeHeaderEvent.fire(element); + this.changeContentEvent.fire(); + }, + + /** + * Sets the Module's body content to the HTML specified, or appends the passed element to the body. If no body is present, one will be automatically created. + * @method setBody + * @param {String} bodyContent The HTML used to set the body OR + * @param {HTMLElement} bodyContent The HTMLElement to append to the body + */ + setBody : function(bodyContent) { + if (! this.body) { + this.body = document.createElement("DIV"); + this.body.className = YAHOO.widget.Module.CSS_BODY; + } + + if (typeof bodyContent == "string") + { + this.body.innerHTML = bodyContent; + } else { + this.body.innerHTML = ""; + this.body.appendChild(bodyContent); + } + + this.changeBodyEvent.fire(bodyContent); + this.changeContentEvent.fire(); + }, + + /** + * Appends the passed element to the body. If no body is present, one will be automatically created. + * @method appendToBody + * @param {HTMLElement} element The element to append to the body + */ + appendToBody : function(element) { + if (! this.body) { + this.body = document.createElement("DIV"); + this.body.className = YAHOO.widget.Module.CSS_BODY; + } + + this.body.appendChild(element); + this.changeBodyEvent.fire(element); + this.changeContentEvent.fire(); + }, + + /** + * Sets the Module's footer content to the HTML specified, or appends the passed element to the footer. If no footer is present, one will be automatically created. + * @method setFooter + * @param {String} footerContent The HTML used to set the footer OR + * @param {HTMLElement} footerContent The HTMLElement to append to the footer + */ + setFooter : function(footerContent) { + if (! this.footer) { + this.footer = document.createElement("DIV"); + this.footer.className = YAHOO.widget.Module.CSS_FOOTER; + } + + if (typeof footerContent == "string") { + this.footer.innerHTML = footerContent; + } else { + this.footer.innerHTML = ""; + this.footer.appendChild(footerContent); + } + + this.changeFooterEvent.fire(footerContent); + this.changeContentEvent.fire(); + }, + + /** + * Appends the passed element to the footer. If no footer is present, one will be automatically created. + * @method appendToFooter + * @param {HTMLElement} element The element to append to the footer + */ + appendToFooter : function(element) { + if (! this.footer) { + this.footer = document.createElement("DIV"); + this.footer.className = YAHOO.widget.Module.CSS_FOOTER; + } + + this.footer.appendChild(element); + this.changeFooterEvent.fire(element); + this.changeContentEvent.fire(); + }, + + /** + * Renders the Module by inserting the elements that are not already in the main Module into their correct places. Optionally appends the Module to the specified node prior to the render's execution. NOTE: For Modules without existing markup, the appendToNode argument is REQUIRED. If this argument is ommitted and the current element is not present in the document, the function will return false, indicating that the render was a failure. + * @method render + * @param {String} appendToNode The element id to which the Module should be appended to prior to rendering OR + * @param {HTMLElement} appendToNode The element to which the Module should be appended to prior to rendering + * @param {HTMLElement} moduleElement OPTIONAL. The element that represents the actual Standard Module container. + * @return {Boolean} Success or failure of the render + */ + render : function(appendToNode, moduleElement) { + this.beforeRenderEvent.fire(); + + if (! moduleElement) { + moduleElement = this.element; + } + + var me = this; + var appendTo = function(element) { + if (typeof element == "string") { + element = document.getElementById(element); + } + + if (element) { + element.appendChild(me.element); + me.appendEvent.fire(); + } + }; + + if (appendToNode) { + appendTo(appendToNode); + } else { // No node was passed in. If the element is not pre-marked up, this fails + if (! YAHOO.util.Dom.inDocument(this.element)) { + return false; + } + } + + // Need to get everything into the DOM if it isn't already + + if (this.header && ! YAHOO.util.Dom.inDocument(this.header)) { + // There is a header, but it's not in the DOM yet... need to add it + var firstChild = moduleElement.firstChild; + if (firstChild) { // Insert before first child if exists + moduleElement.insertBefore(this.header, firstChild); + } else { // Append to empty body because there are no children + moduleElement.appendChild(this.header); + } + } + + if (this.body && ! YAHOO.util.Dom.inDocument(this.body)) { + // There is a body, but it's not in the DOM yet... need to add it + if (this.footer && YAHOO.util.Dom.isAncestor(this.moduleElement, this.footer)) { // Insert before footer if exists in DOM + moduleElement.insertBefore(this.body, this.footer); + } else { // Append to element because there is no footer + moduleElement.appendChild(this.body); + } + } + + if (this.footer && ! YAHOO.util.Dom.inDocument(this.footer)) { + // There is a footer, but it's not in the DOM yet... need to add it + moduleElement.appendChild(this.footer); + } + + this.renderEvent.fire(); + return true; + }, + + /** + * Removes the Module element from the DOM and sets all child elements to null. + * @method destroy + */ + destroy : function() { + if (this.element) { + var parent = this.element.parentNode; + } + if (parent) { + parent.removeChild(this.element); + } + + this.element = null; + this.header = null; + this.body = null; + this.footer = null; + + this.destroyEvent.fire(); + }, + + /** + * Shows the Module element by setting the visible configuration property to true. Also fires two events: beforeShowEvent prior to the visibility change, and showEvent after. + * @method show + */ + show : function() { + this.cfg.setProperty("visible", true); + }, + + /** + * Hides the Module element by setting the visible configuration property to false. Also fires two events: beforeHideEvent prior to the visibility change, and hideEvent after. + * @method hide + */ + hide : function() { + this.cfg.setProperty("visible", false); + }, + + // BUILT-IN EVENT HANDLERS FOR MODULE // + + /** + * Default event handler for changing the visibility property of a Module. By default, this is achieved by switching the "display" style between "block" and "none". + * This method is responsible for firing showEvent and hideEvent. + * @param {String} type The CustomEvent type (usually the property name) + * @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property. + * @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner. + * @method configVisible + */ + configVisible : function(type, args, obj) { + var visible = args[0]; + if (visible) { + this.beforeShowEvent.fire(); + YAHOO.util.Dom.setStyle(this.element, "display", "block"); + this.showEvent.fire(); + } else { + this.beforeHideEvent.fire(); + YAHOO.util.Dom.setStyle(this.element, "display", "none"); + this.hideEvent.fire(); + } + }, + + /** + * Default event handler for the "monitorresize" configuration property + * @param {String} type The CustomEvent type (usually the property name) + * @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property. + * @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner. + * @method configMonitorResize + */ + configMonitorResize : function(type, args, obj) { + var monitor = args[0]; + if (monitor) { + this.initResizeMonitor(); + } else { + YAHOO.util.Event.removeListener(this.resizeMonitor, "resize", this.onDomResize); + this.resizeMonitor = null; + } + } +}; + +/** +* Returns a String representation of the Object. +* @method toString +* @return {String} The string representation of the Module +*/ +YAHOO.widget.Module.prototype.toString = function() { + return "Module " + this.id; +}; + +/** +* Overlay is a Module that is absolutely positioned above the page flow. It has convenience methods for positioning and sizing, as well as options for controlling zIndex and constraining the Overlay's position to the current visible viewport. Overlay also contains a dynamicly generated IFRAME which is placed beneath it for Internet Explorer 6 and 5.x so that it will be properly rendered above SELECT elements. +* @class Overlay +* @namespace YAHOO.widget +* @extends YAHOO.widget.Module +* @param {String} el The element ID representing the Overlay OR +* @param {HTMLElement} el The element representing the Overlay +* @param {Object} userConfig The configuration object literal containing 10/23/2006the configuration that should be set for this Overlay. See configuration documentation for more details. +* @constructor +*/ +YAHOO.widget.Overlay = function(el, userConfig) { + YAHOO.widget.Overlay.superclass.constructor.call(this, el, userConfig); +}; + +YAHOO.extend(YAHOO.widget.Overlay, YAHOO.widget.Module); + +/** +* The URL that will be placed in the iframe +* @property YAHOO.widget.Overlay.IFRAME_SRC +* @static +* @final +* @type String +*/ +YAHOO.widget.Overlay.IFRAME_SRC = "javascript:false;" + +/** +* Constant representing the top left corner of an element, used for configuring the context element alignment +* @property YAHOO.widget.Overlay.TOP_LEFT +* @static +* @final +* @type String +*/ +YAHOO.widget.Overlay.TOP_LEFT = "tl"; + +/** +* Constant representing the top right corner of an element, used for configuring the context element alignment +* @property YAHOO.widget.Overlay.TOP_RIGHT +* @static +* @final +* @type String +*/ +YAHOO.widget.Overlay.TOP_RIGHT = "tr"; + +/** +* Constant representing the top bottom left corner of an element, used for configuring the context element alignment +* @property YAHOO.widget.Overlay.BOTTOM_LEFT +* @static +* @final +* @type String +*/ +YAHOO.widget.Overlay.BOTTOM_LEFT = "bl"; + +/** +* Constant representing the bottom right corner of an element, used for configuring the context element alignment +* @property YAHOO.widget.Overlay.BOTTOM_RIGHT +* @static +* @final +* @type String +*/ +YAHOO.widget.Overlay.BOTTOM_RIGHT = "br"; + +/** +* Constant representing the default CSS class used for an Overlay +* @property YAHOO.widget.Overlay.CSS_OVERLAY +* @static +* @final +* @type String +*/ +YAHOO.widget.Overlay.CSS_OVERLAY = "overlay"; + +/** +* The Overlay initialization method, which is executed for Overlay and all of its subclasses. This method is automatically called by the constructor, and sets up all DOM references for pre-existing markup, and creates required markup if it is not already present. +* @method init +* @param {String} el The element ID representing the Overlay OR +* @param {HTMLElement} el The element representing the Overlay +* @param {Object} userConfig The configuration object literal containing the configuration that should be set for this Overlay. See configuration documentation for more details. +*/ +YAHOO.widget.Overlay.prototype.init = function(el, userConfig) { + YAHOO.widget.Overlay.superclass.init.call(this, el/*, userConfig*/); // Note that we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level + + this.beforeInitEvent.fire(YAHOO.widget.Overlay); + + YAHOO.util.Dom.addClass(this.element, YAHOO.widget.Overlay.CSS_OVERLAY); + + if (userConfig) { + this.cfg.applyConfig(userConfig, true); + } + + if (this.platform == "mac" && this.browser == "gecko") { + if (! YAHOO.util.Config.alreadySubscribed(this.showEvent,this.showMacGeckoScrollbars,this)) { + this.showEvent.subscribe(this.showMacGeckoScrollbars,this,true); + } + if (! YAHOO.util.Config.alreadySubscribed(this.hideEvent,this.hideMacGeckoScrollbars,this)) { + this.hideEvent.subscribe(this.hideMacGeckoScrollbars,this,true); + } + } + + this.initEvent.fire(YAHOO.widget.Overlay); +}; + +/** +* Initializes the custom events for Overlay which are fired automatically at appropriate times by the Overlay class. +* @method initEvents +*/ +YAHOO.widget.Overlay.prototype.initEvents = function() { + YAHOO.widget.Overlay.superclass.initEvents.call(this); + + /** + * CustomEvent fired before the Overlay is moved. + * @event beforeMoveEvent + * @param {Number} x x coordinate + * @param {Number} y y coordinate + */ + this.beforeMoveEvent = new YAHOO.util.CustomEvent("beforeMove", this); + + /** + * CustomEvent fired after the Overlay is moved. + * @event moveEvent + * @param {Number} x x coordinate + * @param {Number} y y coordinate + */ + this.moveEvent = new YAHOO.util.CustomEvent("move", this); +}; + +/** +* Initializes the class's configurable properties which can be changed using the Overlay's Config object (cfg). +* @method initDefaultConfig +*/ +YAHOO.widget.Overlay.prototype.initDefaultConfig = function() { + YAHOO.widget.Overlay.superclass.initDefaultConfig.call(this); + + // Add overlay config properties // + + /** + * The absolute x-coordinate position of the Overlay + * @config x + * @type Number + * @default null + */ + this.cfg.addProperty("x", { handler:this.configX, validator:this.cfg.checkNumber, suppressEvent:true, supercedes:["iframe"] } ); + + /** + * The absolute y-coordinate position of the Overlay + * @config y + * @type Number + * @default null + */ + this.cfg.addProperty("y", { handler:this.configY, validator:this.cfg.checkNumber, suppressEvent:true, supercedes:["iframe"] } ); + + /** + * An array with the absolute x and y positions of the Overlay + * @config xy + * @type Number[] + * @default null + */ + this.cfg.addProperty("xy",{ handler:this.configXY, suppressEvent:true, supercedes:["iframe"] } ); + + /** + * The array of context arguments for context-sensitive positioning. The format is: [id or element, element corner, context corner]. For example, setting this property to ["img1", "tl", "bl"] would align the Overlay's top left corner to the context element's bottom left corner. + * @config context + * @type Array + * @default null + */ + this.cfg.addProperty("context", { handler:this.configContext, suppressEvent:true, supercedes:["iframe"] } ); + + /** + * True if the Overlay should be anchored to the center of the viewport. + * @config fixedcenter + * @type Boolean + * @default false + */ + this.cfg.addProperty("fixedcenter", { value:false, handler:this.configFixedCenter, validator:this.cfg.checkBoolean, supercedes:["iframe","visible"] } ); + + /** + * CSS width of the Overlay. + * @config width + * @type String + * @default null + */ + this.cfg.addProperty("width", { handler:this.configWidth, suppressEvent:true, supercedes:["iframe"] } ); + + /** + * CSS height of the Overlay. + * @config height + * @type String + * @default null + */ + this.cfg.addProperty("height", { handler:this.configHeight, suppressEvent:true, supercedes:["iframe"] } ); + + /** + * CSS z-index of the Overlay. + * @config zIndex + * @type Number + * @default null + */ + this.cfg.addProperty("zIndex", { value:null, handler:this.configzIndex } ); + + /** + * True if the Overlay should be prevented from being positioned out of the viewport. + * @config constraintoviewport + * @type Boolean + * @default false + */ + this.cfg.addProperty("constraintoviewport", { value:false, handler:this.configConstrainToViewport, validator:this.cfg.checkBoolean, supercedes:["iframe","x","y","xy"] } ); + + /** + * True if the Overlay should have an IFRAME shim (for correcting the select z-index bug in IE6 and below). + * @config iframe + * @type Boolean + * @default true for IE6 and below, false for all others + */ + this.cfg.addProperty("iframe", { value:(this.browser == "ie" ? true : false), handler:this.configIframe, validator:this.cfg.checkBoolean, supercedes:["zIndex"] } ); +}; + +/** +* Moves the Overlay to the specified position. This function is identical to calling this.cfg.setProperty("xy", [x,y]); +* @method moveTo +* @param {Number} x The Overlay's new x position +* @param {Number} y The Overlay's new y position +*/ +YAHOO.widget.Overlay.prototype.moveTo = function(x, y) { + this.cfg.setProperty("xy",[x,y]); +}; + +/** +* Adds a special CSS class to the Overlay when Mac/Gecko is in use, to work around a Gecko bug where +* scrollbars cannot be hidden. See https://bugzilla.mozilla.org/show_bug.cgi?id=187435 +* @method hideMacGeckoScrollbars +*/ +YAHOO.widget.Overlay.prototype.hideMacGeckoScrollbars = function() { + YAHOO.util.Dom.removeClass(this.element, "show-scrollbars"); + YAHOO.util.Dom.addClass(this.element, "hide-scrollbars"); +}; + +/** +* Removes a special CSS class from the Overlay when Mac/Gecko is in use, to work around a Gecko bug where +* scrollbars cannot be hidden. See https://bugzilla.mozilla.org/show_bug.cgi?id=187435 +* @method showMacGeckoScrollbars +*/ +YAHOO.widget.Overlay.prototype.showMacGeckoScrollbars = function() { + YAHOO.util.Dom.removeClass(this.element, "hide-scrollbars"); + YAHOO.util.Dom.addClass(this.element, "show-scrollbars"); +}; + +// BEGIN BUILT-IN PROPERTY EVENT HANDLERS // + +/** +* The default event handler fired when the "visible" property is changed. This method is responsible for firing showEvent and hideEvent. +* @method configVisible +* @param {String} type The CustomEvent type (usually the property name) +* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property. +* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner. +*/ +YAHOO.widget.Overlay.prototype.configVisible = function(type, args, obj) { + var visible = args[0]; + + var currentVis = YAHOO.util.Dom.getStyle(this.element, "visibility"); + + if (currentVis == "inherit") { + var e = this.element.parentNode; + while (e.nodeType != 9 && e.nodeType != 11) { + currentVis = YAHOO.util.Dom.getStyle(e, "visibility"); + if (currentVis != "inherit") { break; } + e = e.parentNode; + } + if (currentVis == "inherit") { + currentVis = "visible"; + } + } + + var effect = this.cfg.getProperty("effect"); + + var effectInstances = []; + if (effect) { + if (effect instanceof Array) { + for (var i=0;i rightConstraint) { + x = rightConstraint; + } + + if (y < topConstraint) { + y = topConstraint; + } else if (y > bottomConstraint) { + y = bottomConstraint; + } + + this.cfg.setProperty("x", x, true); + this.cfg.setProperty("y", y, true); + this.cfg.setProperty("xy", [x,y], true); +}; + +/** +* Centers the container in the viewport. +* @method center +*/ +YAHOO.widget.Overlay.prototype.center = function() { + var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; + var scrollY = document.documentElement.scrollTop || document.body.scrollTop; + + var viewPortWidth = YAHOO.util.Dom.getClientWidth(); + var viewPortHeight = YAHOO.util.Dom.getClientHeight(); + + var elementWidth = this.element.offsetWidth; + var elementHeight = this.element.offsetHeight; + + var x = (viewPortWidth / 2) - (elementWidth / 2) + scrollX; + var y = (viewPortHeight / 2) - (elementHeight / 2) + scrollY; + + this.cfg.setProperty("xy", [parseInt(x, 10), parseInt(y, 10)]); + + this.cfg.refireEvent("iframe"); +}; + +/** +* Synchronizes the Panel's "xy", "x", and "y" properties with the Panel's position in the DOM. This is primarily used to update position information during drag & drop. +* @method syncPosition +*/ +YAHOO.widget.Overlay.prototype.syncPosition = function() { + var pos = YAHOO.util.Dom.getXY(this.element); + this.cfg.setProperty("x", pos[0], true); + this.cfg.setProperty("y", pos[1], true); + this.cfg.setProperty("xy", pos, true); +}; + +/** +* Event handler fired when the resize monitor element is resized. +* @method onDomResize +* @param {DOMEvent} e The resize DOM event +* @param {Object} obj The scope object +*/ +YAHOO.widget.Overlay.prototype.onDomResize = function(e, obj) { + YAHOO.widget.Overlay.superclass.onDomResize.call(this, e, obj); + var me = this; + setTimeout(function() { + me.syncPosition(); + me.cfg.refireEvent("iframe"); + me.cfg.refireEvent("context"); + }, 0); +}; + +/** +* Removes the Overlay element from the DOM and sets all child elements to null. +* @method destroy +*/ +YAHOO.widget.Overlay.prototype.destroy = function() { + if (this.iframe) { + this.iframe.parentNode.removeChild(this.iframe); + } + + this.iframe = null; + + YAHOO.widget.Overlay.superclass.destroy.call(this); +}; + +/** +* Returns a String representation of the object. +* @method toString +* @return {String} The string representation of the Overlay. +*/ +YAHOO.widget.Overlay.prototype.toString = function() { + return "Overlay " + this.id; +}; + +/** +* A singleton CustomEvent used for reacting to the DOM event for window scroll +* @event YAHOO.widget.Overlay.windowScrollEvent +*/ +YAHOO.widget.Overlay.windowScrollEvent = new YAHOO.util.CustomEvent("windowScroll"); + +/** +* A singleton CustomEvent used for reacting to the DOM event for window resize +* @event YAHOO.widget.Overlay.windowResizeEvent +*/ +YAHOO.widget.Overlay.windowResizeEvent = new YAHOO.util.CustomEvent("windowResize"); + +/** +* The DOM event handler used to fire the CustomEvent for window scroll +* @method YAHOO.widget.Overlay.windowScrollHandler +* @static +* @param {DOMEvent} e The DOM scroll event +*/ +YAHOO.widget.Overlay.windowScrollHandler = function(e) { + if (YAHOO.widget.Module.prototype.browser == "ie" || YAHOO.widget.Module.prototype.browser == "ie7") { + if (! window.scrollEnd) { + window.scrollEnd = -1; + } + clearTimeout(window.scrollEnd); + window.scrollEnd = setTimeout(function() { YAHOO.widget.Overlay.windowScrollEvent.fire(); }, 1); + } else { + YAHOO.widget.Overlay.windowScrollEvent.fire(); + } +}; + +/** +* The DOM event handler used to fire the CustomEvent for window resize +* @method YAHOO.widget.Overlay.windowResizeHandler +* @static +* @param {DOMEvent} e The DOM resize event +*/ +YAHOO.widget.Overlay.windowResizeHandler = function(e) { + if (YAHOO.widget.Module.prototype.browser == "ie" || YAHOO.widget.Module.prototype.browser == "ie7") { + if (! window.resizeEnd) { + window.resizeEnd = -1; + } + clearTimeout(window.resizeEnd); + window.resizeEnd = setTimeout(function() { YAHOO.widget.Overlay.windowResizeEvent.fire(); }, 100); + } else { + YAHOO.widget.Overlay.windowResizeEvent.fire(); + } +}; + +/** +* A boolean that indicated whether the window resize and scroll events have already been subscribed to. +* @property YAHOO.widget.Overlay._initialized +* @private +* @type Boolean +*/ +YAHOO.widget.Overlay._initialized = null; + +if (YAHOO.widget.Overlay._initialized === null) { + YAHOO.util.Event.addListener(window, "scroll", YAHOO.widget.Overlay.windowScrollHandler); + YAHOO.util.Event.addListener(window, "resize", YAHOO.widget.Overlay.windowResizeHandler); + + YAHOO.widget.Overlay._initialized = true; +} + +/** +* OverlayManager is used for maintaining the focus status of multiple Overlays.* @namespace YAHOO.widget +* @namespace YAHOO.widget +* @class OverlayManager +* @constructor +* @param {Array} overlays Optional. A collection of Overlays to register with the manager. +* @param {Object} userConfig The object literal representing the user configuration of the OverlayManager +*/ +YAHOO.widget.OverlayManager = function(userConfig) { + this.init(userConfig); +}; + +/** +* The CSS class representing a focused Overlay +* @property YAHOO.widget.OverlayManager.CSS_FOCUSED +* @static +* @final +* @type String +*/ +YAHOO.widget.OverlayManager.CSS_FOCUSED = "focused"; + +YAHOO.widget.OverlayManager.prototype = { + /** + * The class's constructor function + * @property contructor + * @type Function + */ + constructor : YAHOO.widget.OverlayManager, + + /** + * The array of Overlays that are currently registered + * @property overlays + * @type YAHOO.widget.Overlay[] + */ + overlays : null, + + /** + * Initializes the default configuration of the OverlayManager + * @method initDefaultConfig + */ + initDefaultConfig : function() { + /** + * The collection of registered Overlays in use by the OverlayManager + * @config overlays + * @type YAHOO.widget.Overlay[] + * @default null + */ + this.cfg.addProperty("overlays", { suppressEvent:true } ); + + /** + * The default DOM event that should be used to focus an Overlay + * @config focusevent + * @type String + * @default "mousedown" + */ + this.cfg.addProperty("focusevent", { value:"mousedown" } ); + }, + + /** + * Initializes the OverlayManager + * @method init + * @param {YAHOO.widget.Overlay[]} overlays Optional. A collection of Overlays to register with the manager. + * @param {Object} userConfig The object literal representing the user configuration of the OverlayManager + */ + init : function(userConfig) { + /** + * The OverlayManager's Config object used for monitoring configuration properties. + * @property cfg + * @type YAHOO.util.Config + */ + this.cfg = new YAHOO.util.Config(this); + + this.initDefaultConfig(); + + if (userConfig) { + this.cfg.applyConfig(userConfig, true); + } + this.cfg.fireQueue(); + + /** + * The currently activated Overlay + * @property activeOverlay + * @private + * @type YAHOO.widget.Overlay + */ + var activeOverlay = null; + + /** + * Returns the currently focused Overlay + * @method getActive + * @return {YAHOO.widget.Overlay} The currently focused Overlay + */ + this.getActive = function() { + return activeOverlay; + }; + + /** + * Focuses the specified Overlay + * @method focus + * @param {YAHOO.widget.Overlay} overlay The Overlay to focus + * @param {String} overlay The id of the Overlay to focus + */ + this.focus = function(overlay) { + var o = this.find(overlay); + if (o) { + this.blurAll(); + activeOverlay = o; + YAHOO.util.Dom.addClass(activeOverlay.element, YAHOO.widget.OverlayManager.CSS_FOCUSED); + this.overlays.sort(this.compareZIndexDesc); + var topZIndex = YAHOO.util.Dom.getStyle(this.overlays[0].element, "zIndex"); + if (! isNaN(topZIndex) && this.overlays[0] != overlay) { + activeOverlay.cfg.setProperty("zIndex", (parseInt(topZIndex, 10) + 2)); + } + this.overlays.sort(this.compareZIndexDesc); + } + }; + + /** + * Removes the specified Overlay from the manager + * @method remove + * @param {YAHOO.widget.Overlay} overlay The Overlay to remove + * @param {String} overlay The id of the Overlay to remove + */ + this.remove = function(overlay) { + var o = this.find(overlay); + if (o) { + var originalZ = YAHOO.util.Dom.getStyle(o.element, "zIndex"); + o.cfg.setProperty("zIndex", -1000, true); + this.overlays.sort(this.compareZIndexDesc); + this.overlays = this.overlays.slice(0, this.overlays.length-1); + o.cfg.setProperty("zIndex", originalZ, true); + + o.cfg.setProperty("manager", null); + o.focusEvent = null; + o.blurEvent = null; + o.focus = null; + o.blur = null; + } + }; + + /** + * Removes focus from all registered Overlays in the manager + * @method blurAll + */ + this.blurAll = function() { + activeOverlay = null; + for (var o=0;o 0) { + return true; + } + } else { + return false; + } + }, + + /** + * Attempts to locate an Overlay by instance or ID. + * @method find + * @param {YAHOO.widget.Overlay} overlay An Overlay to locate within the manager + * @param {String} overlay An Overlay id to locate within the manager + * @return {YAHOO.widget.Overlay} The requested Overlay, if found, or null if it cannot be located. + */ + find : function(overlay) { + if (overlay instanceof YAHOO.widget.Overlay) { + for (var o=0;o zIndex2) { + return -1; + } else if (zIndex1 < zIndex2) { + return 1; + } else { + return 0; + } + }, + + /** + * Shows all Overlays in the manager. + * @method showAll + */ + showAll : function() { + for (var o=0;oOR +* @param {HTMLElement} el The element representing the Tooltip +* @param {Object} userConfig The configuration object literal containing the configuration that should be set for this Overlay. See configuration documentation for more details. +*/ +YAHOO.widget.Tooltip = function(el, userConfig) { + YAHOO.widget.Tooltip.superclass.constructor.call(this, el, userConfig); +}; + +YAHOO.extend(YAHOO.widget.Tooltip, YAHOO.widget.Overlay); + +/** +* Constant representing the Tooltip CSS class +* @property YAHOO.widget.Tooltip.CSS_TOOLTIP +* @static +* @final +* @type String +*/ +YAHOO.widget.Tooltip.CSS_TOOLTIP = "tt"; + +/** +* The Tooltip initialization method. This method is automatically called by the constructor. A Tooltip is automatically rendered by the init method, and it also is set to be invisible by default, and constrained to viewport by default as well. +* @method init +* @param {String} el The element ID representing the Tooltip OR +* @param {HTMLElement} el The element representing the Tooltip +* @param {Object} userConfig The configuration object literal containing the configuration that should be set for this Tooltip. See configuration documentation for more details. +*/ +YAHOO.widget.Tooltip.prototype.init = function(el, userConfig) { + if (document.readyState && document.readyState != "complete") { + var deferredInit = function() { + this.init(el, userConfig); + }; + YAHOO.util.Event.addListener(window, "load", deferredInit, this, true); + } else { + YAHOO.widget.Tooltip.superclass.init.call(this, el); + + this.beforeInitEvent.fire(YAHOO.widget.Tooltip); + + YAHOO.util.Dom.addClass(this.element, YAHOO.widget.Tooltip.CSS_TOOLTIP); + + if (userConfig) { + this.cfg.applyConfig(userConfig, true); + } + + this.cfg.queueProperty("visible",false); + this.cfg.queueProperty("constraintoviewport",true); + + this.setBody(""); + this.render(this.cfg.getProperty("container")); + + this.initEvent.fire(YAHOO.widget.Tooltip); + } +}; + +/** +* Initializes the class's configurable properties which can be changed using the Overlay's Config object (cfg). +* @method initDefaultConfig +*/ +YAHOO.widget.Tooltip.prototype.initDefaultConfig = function() { + YAHOO.widget.Tooltip.superclass.initDefaultConfig.call(this); + + /** + * Specifies whether the Tooltip should be kept from overlapping its context element. + * @config preventoverlap + * @type Boolean + * @default true + */ + this.cfg.addProperty("preventoverlap", { value:true, validator:this.cfg.checkBoolean, supercedes:["x","y","xy"] } ); + + /** + * The number of milliseconds to wait before showing a Tooltip on mouseover. + * @config showdelay + * @type Number + * @default 200 + */ + this.cfg.addProperty("showdelay", { value:200, handler:this.configShowDelay, validator:this.cfg.checkNumber } ); + + /** + * The number of milliseconds to wait before automatically dismissing a Tooltip after the mouse has been resting on the context element. + * @config autodismissdelay + * @type Number + * @default 5000 + */ + this.cfg.addProperty("autodismissdelay", { value:5000, handler:this.configAutoDismissDelay, validator:this.cfg.checkNumber } ); + + /** + * The number of milliseconds to wait before hiding a Tooltip on mouseover. + * @config hidedelay + * @type Number + * @default 250 + */ + this.cfg.addProperty("hidedelay", { value:250, handler:this.configHideDelay, validator:this.cfg.checkNumber } ); + + /** + * Specifies the Tooltip's text. + * @config text + * @type String + * @default null + */ + this.cfg.addProperty("text", { handler:this.configText, suppressEvent:true } ); + + /** + * Specifies the container element that the Tooltip's markup should be rendered into. + * @config container + * @type HTMLElement/String + * @default document.body + */ + this.cfg.addProperty("container", { value:document.body, handler:this.configContainer } ); + + /** + * Specifies the element or elements that the Tooltip should be anchored to on mouseover. + * @config context + * @type HTMLElement[]/String[] + * @default null + */ + +}; + +// BEGIN BUILT-IN PROPERTY EVENT HANDLERS // + +/** +* The default event handler fired when the "text" property is changed. +* @method configText +* @param {String} type The CustomEvent type (usually the property name) +* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property. +* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner. +*/ +YAHOO.widget.Tooltip.prototype.configText = function(type, args, obj) { + var text = args[0]; + if (text) { + this.setBody(text); + } +}; + +/** +* The default event handler fired when the "container" property is changed. +* @method configContainer +* @param {String} type The CustomEvent type (usually the property name) +* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property. +* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner. +*/ +YAHOO.widget.Tooltip.prototype.configContainer = function(type, args, obj) { + var container = args[0]; + if (typeof container == 'string') { + this.cfg.setProperty("container", document.getElementById(container), true); + } +}; + +/** +* The default event handler fired when the "context" property is changed. +* @method configContext +* @param {String} type The CustomEvent type (usually the property name) +* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property. +* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner. +*/ +YAHOO.widget.Tooltip.prototype.configContext = function(type, args, obj) { + var context = args[0]; + if (context) { + + // Normalize parameter into an array + if (! (context instanceof Array)) { + if (typeof context == "string") { + this.cfg.setProperty("context", [document.getElementById(context)], true); + } else { // Assuming this is an element + this.cfg.setProperty("context", [context], true); + } + context = this.cfg.getProperty("context"); + } + + + // Remove any existing mouseover/mouseout listeners + if (this._context) { + for (var c=0;cOR +* @param {HTMLElement} el The element representing the Panel +* @param {Object} userConfig The configuration object literal containing the configuration that should be set for this Panel. See configuration documentation for more details. +*/ +YAHOO.widget.Panel = function(el, userConfig) { + YAHOO.widget.Panel.superclass.constructor.call(this, el, userConfig); +}; + +YAHOO.extend(YAHOO.widget.Panel, YAHOO.widget.Overlay); + +/** +* Constant representing the default CSS class used for a Panel +* @property YAHOO.widget.Panel.CSS_PANEL +* @static +* @final +* @type String +*/ +YAHOO.widget.Panel.CSS_PANEL = "panel"; + +/** +* Constant representing the default CSS class used for a Panel's wrapping container +* @property YAHOO.widget.Panel.CSS_PANEL_CONTAINER +* @static +* @final +* @type String +*/ +YAHOO.widget.Panel.CSS_PANEL_CONTAINER = "panel-container"; + +/** +* The Overlay initialization method, which is executed for Overlay and all of its subclasses. This method is automatically called by the constructor, and sets up all DOM references for pre-existing markup, and creates required markup if it is not already present. +* @method init +* @param {String} el The element ID representing the Overlay OR +* @param {HTMLElement} el The element representing the Overlay +* @param {Object} userConfig The configuration object literal containing the configuration that should be set for this Overlay. See configuration documentation for more details. +*/ +YAHOO.widget.Panel.prototype.init = function(el, userConfig) { + YAHOO.widget.Panel.superclass.init.call(this, el/*, userConfig*/); // Note that we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level + + this.beforeInitEvent.fire(YAHOO.widget.Panel); + + YAHOO.util.Dom.addClass(this.element, YAHOO.widget.Panel.CSS_PANEL); + + this.buildWrapper(); + + if (userConfig) { + this.cfg.applyConfig(userConfig, true); + } + + this.beforeRenderEvent.subscribe(function() { + var draggable = this.cfg.getProperty("draggable"); + if (draggable) { + if (! this.header) { + this.setHeader(" "); + } + } + }, this, true); + + var me = this; + + this.showMaskEvent.subscribe(function() { + var checkFocusable = function(el) { + if (el.tagName == "A" || el.tagName == "BUTTON" || el.tagName == "SELECT" || el.tagName == "INPUT" || el.tagName == "TEXTAREA" || el.tagName == "FORM") { + if (! YAHOO.util.Dom.isAncestor(me.element, el)) { + YAHOO.util.Event.addListener(el, "focus", el.blur); + return true; + } + } else { + return false; + } + }; + + this.focusableElements = YAHOO.util.Dom.getElementsBy(checkFocusable); + }, this, true); + + this.hideMaskEvent.subscribe(function() { + for (var i=0;i