/* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ /** * The YAHOO object is the single global object used by YUI Library. It * contains utility function for setting up namespaces, inheritance, and * logging. YAHOO.util, YAHOO.widget, and YAHOO.example are namespaces * created automatically for and used by the library. * @module yahoo * @title YAHOO Global */ /** * YAHOO_config is not included as part of the library. Instead it is an * object that can be defined by the implementer immediately before * including the YUI library. The properties included in this object * will be used to configure global properties needed as soon as the * library begins to load. * @class YAHOO_config * @static */ /** * A reference to a function that will be executed every time a YAHOO module * is loaded. As parameter, this function will receive the version * information for the module. See * YAHOO.env.getVersion for the description of the version data structure. * @property listener * @type Function * @static * @default undefined */ /** * Set to true if the library will be dynamically loaded after window.onload. * Defaults to false * @property injecting * @type boolean * @static * @default undefined */ /** * Instructs the yuiloader component to dynamically load yui components and * their dependencies. See the yuiloader documentation for more information * about dynamic loading * @property load * @static * @default undefined * @see yuiloader */ /** * Forces the use of the supplied locale where applicable in the library * @property locale * @type string * @static * @default undefined */ if (typeof YAHOO == "undefined" || !YAHOO) { /** * The YAHOO global namespace object. If YAHOO is already defined, the * existing YAHOO object will not be overwritten so that defined * namespaces are preserved. * @class YAHOO * @static */ var YAHOO = {}; } /** * Returns the namespace specified and creates it if it doesn't exist *
 * YAHOO.namespace("property.package");
 * YAHOO.namespace("YAHOO.property.package");
 * 
* Either of the above would create YAHOO.property, then * YAHOO.property.package * * Be careful when naming packages. Reserved words may work in some browsers * and not others. For instance, the following will fail in Safari: *
 * YAHOO.namespace("really.long.nested.namespace");
 * 
* This fails because "long" is a future reserved word in ECMAScript * * For implementation code that uses YUI, do not create your components * in the namespaces defined by YUI ( * YAHOO.util, * YAHOO.widget, * YAHOO.lang, * YAHOO.tool, * YAHOO.example, * YAHOO.env) -- create your own namespace (e.g., 'companyname'). * * @method namespace * @static * @param {String*} arguments 1-n namespaces to create * @return {Object} A reference to the last namespace object created */ YAHOO.namespace = function() { var a=arguments, o=null, i, j, d; for (i=0; i *
name:
The name of the module
*
version:
The version in use
*
build:
The build number in use
*
versions:
All versions that were registered
*
builds:
All builds that were registered.
*
mainClass:
An object that was was stamped with the * current version and build. If * mainClass.VERSION != version or mainClass.BUILD != build, * multiple versions of pieces of the library have been * loaded, potentially causing issues.
* * * @method getVersion * @static * @param {String} name the name of the module (event, slider, etc) * @return {Object} The version info */ YAHOO.env.getVersion = function(name) { return YAHOO.env.modules[name] || null; }; /** * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. YAHOO.env.ua stores a version * number for the browser engine, 0 otherwise. This value may or may not map * to the version number of the browser using the engine. The value is * presented as a float so that it can easily be used for boolean evaluation * as well as for looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost (e.g., Gecko 1.8.0.9 * reports 1.8). * @class YAHOO.env.ua * @static */ /** * parses a user agent string (or looks for one in navigator to parse if * not supplied). * @method parseUA * @since 2.9.0 * @static */ YAHOO.env.parseUA = function(agent) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, nav = navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 *
         * Firefox 1.0.0.4: 1.7.8   <-- Reports 1.7
         * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8
         * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81
         * Firefox 3.0   <-- 1.9
         * Firefox 3.5   <-- 1.91
         * 
* @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 *
         * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the
         *                                   latest available for Mac OSX 10.3.
         * Safari 2.0.2:         416     <-- hasOwnProperty introduced
         * Safari 2.0.4:         418     <-- preventDefault fixed
         * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run
         *                                   different versions of webkit
         * Safari 2.0.4 (419.3): 419     <-- Tiger installations that have been
         *                                   updated, but not updated
         *                                   to the latest patch.
         * Webkit 212 nightly:   522+    <-- Safari 3.0 precursor (with native
         * SVG and many major issues fixed).
         * Safari 3.0.4 (523.12) 523.12  <-- First Tiger release - automatic
         * update from 2.x via the 10.4.11 OS patch.
         * Webkit nightly 1/2008:525+    <-- Supports DOMContentLoaded event.
         *                                   yahoo.com user agent hack removed.
         * 
* http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @static */ os: null }, ua = agent || (navigator && navigator.userAgent), loc = window && window.location, href = loc && loc.href, m; o.secure = href && (href.toLowerCase().indexOf("https") === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh/i).test(ua)) { o.os = 'macintosh'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/); if (m) { // Nokia N-series, Android, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { o.mobile = 'Android'; m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } } m = ua.match(/Chrome\/([^\s]*)/); if (m && m[1]) { o.chrome = numberify(m[1]); // Chrome } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } return o; }; YAHOO.env.ua = YAHOO.env.parseUA(); /* * Initializes the global by creating the default namespaces and applying * any new configuration information that is detected. This is the setup * for env. * @method init * @static * @private */ (function() { YAHOO.namespace("util", "widget", "example"); /*global YAHOO_config*/ if ("undefined" !== typeof YAHOO_config) { var l=YAHOO_config.listener, ls=YAHOO.env.listeners,unique=true, i; if (l) { // if YAHOO is loaded multiple times we need to check to see if // this is a new config object. If it is, add the new component // load listener to the stack for (i=0; i': '>', '"': '"', "'": ''', '/': '/', '`': '`' }, // ADD = ["toString", "valueOf", "hasOwnProperty"], ADD = ["toString", "valueOf"], OB = { /** * Determines wheather or not the provided object is an array. * @method isArray * @param {any} o The object being testing * @return {boolean} the result */ isArray: function(o) { return OP.toString.apply(o) === ARRAY_TOSTRING; }, /** * Determines whether or not the provided object is a boolean * @method isBoolean * @param {any} o The object being testing * @return {boolean} the result */ isBoolean: function(o) { return typeof o === 'boolean'; }, /** * Determines whether or not the provided object is a function. * Note: Internet Explorer thinks certain functions are objects: * * var obj = document.createElement("object"); * YAHOO.lang.isFunction(obj.getAttribute) // reports false in IE * * var input = document.createElement("input"); // append to body * YAHOO.lang.isFunction(input.focus) // reports false in IE * * You will have to implement additional tests if these functions * matter to you. * * @method isFunction * @param {any} o The object being testing * @return {boolean} the result */ isFunction: function(o) { return (typeof o === 'function') || OP.toString.apply(o) === FUNCTION_TOSTRING; }, /** * Determines whether or not the provided object is null * @method isNull * @param {any} o The object being testing * @return {boolean} the result */ isNull: function(o) { return o === null; }, /** * Determines whether or not the provided object is a legal number * @method isNumber * @param {any} o The object being testing * @return {boolean} the result */ isNumber: function(o) { return typeof o === 'number' && isFinite(o); }, /** * Determines whether or not the provided object is of type object * or function * @method isObject * @param {any} o The object being testing * @return {boolean} the result */ isObject: function(o) { return (o && (typeof o === 'object' || L.isFunction(o))) || false; }, /** * Determines whether or not the provided object is a string * @method isString * @param {any} o The object being testing * @return {boolean} the result */ isString: function(o) { return typeof o === 'string'; }, /** * Determines whether or not the provided object is undefined * @method isUndefined * @param {any} o The object being testing * @return {boolean} the result */ isUndefined: function(o) { return typeof o === 'undefined'; }, /** * IE will not enumerate native functions in a derived object even if the * function was overridden. This is a workaround for specific functions * we care about on the Object prototype. * @property _IEEnumFix * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @static * @private */ _IEEnumFix: (YAHOO.env.ua.ie) ? function(r, s) { var i, fname, f; for (i=0;i * Returns a copy of the specified string with special HTML characters * escaped. The following characters will be converted to their * corresponding character entities: * & < > " ' / ` *

* *

* This implementation is based on the * OWASP * HTML escaping recommendations. In addition to the characters * in the OWASP recommendation, we also escape the ` * character, since IE interprets it as an attribute delimiter when used in * innerHTML. *

* * @method escapeHTML * @param {String} html String to escape. * @return {String} Escaped string. * @static * @since 2.9.0 */ escapeHTML: function (html) { return html.replace(/[&<>"'\/`]/g, function (match) { return HTML_CHARS[match]; }); }, /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @static * @param {Function} subc the object to modify * @param {Function} superc the object to inherit * @param {Object} overrides additional properties/methods to add to the * subclass prototype. These will override the * matching items obtained from the superclass * if present. */ extend: function(subc, superc, overrides) { if (!superc||!subc) { throw new Error("extend failed, please check that " + "all dependencies are included."); } var F = function() {}, i; F.prototype=superc.prototype; subc.prototype=new F(); subc.prototype.constructor=subc; subc.superclass=superc.prototype; if (superc.prototype.constructor == OP.constructor) { superc.prototype.constructor=superc; } if (overrides) { for (i in overrides) { if (L.hasOwnProperty(overrides, i)) { subc.prototype[i]=overrides[i]; } } L._IEEnumFix(subc.prototype, overrides); } }, /** * Applies all properties in the supplier to the receiver if the * receiver does not have these properties yet. Optionally, one or * more methods/properties can be specified (as additional * parameters). This option will overwrite the property if receiver * has it already. If true is passed as the third parameter, all * properties will be applied and _will_ overwrite properties in * the receiver. * * @method augmentObject * @static * @since 2.3.0 * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param {String*|boolean} arguments zero or more properties methods * to augment the receiver with. If none specified, everything * in the supplier will be used unless it would * overwrite an existing property in the receiver. If true * is specified as the third parameter, all properties will * be applied and will overwrite an existing property in * the receiver */ augmentObject: function(r, s) { if (!s||!r) { throw new Error("Absorb failed, verify dependencies."); } var a=arguments, i, p, overrideList=a[2]; if (overrideList && overrideList!==true) { // only absorb the specified properties for (i=2; i 0) ? L.dump(o[i], d-1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push("]"); // objects {k1 => v1, k2 => v2} } else { s.push("{"); for (i in o) { if (L.hasOwnProperty(o, i)) { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d-1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } } if (s.length > 1) { s.pop(); } s.push("}"); } return s.join(""); }, /** * Does variable substitution on a string. It scans through the string * looking for expressions enclosed in { } braces. If an expression * is found, it is used a key on the object. If there is a space in * the key, the first word is used for the key and the rest is provided * to an optional function to be used to programatically determine the * value (the extra information might be used for this decision). If * the value for the key in the object, or what is returned from the * function has a string value, number value, or object value, it is * substituted for the bracket expression and it repeats. If this * value is an object, it uses the Object's toString() if this has * been overridden, otherwise it does a shallow dump of the key/value * pairs. * * By specifying the recurse option, the string is rescanned after * every replacement, allowing for nested template substitutions. * The side effect of this option is that curly braces in the * replacement content must be encoded. * * @method substitute * @since 2.3.0 * @param s {String} The string that will be modified. * @param o {Object} An object containing the replacement values * @param f {Function} An optional function that can be used to * process each match. It receives the key, * value, and any extra metadata included with * the key inside of the braces. * @param recurse {boolean} default true - if not false, the replaced * string will be rescanned so that nested substitutions are possible. * @return {String} the substituted string */ substitute: function (s, o, f, recurse) { var i, j, k, key, v, meta, saved=[], token, lidx=s.length, DUMP='dump', SPACE=' ', LBRACE='{', RBRACE='}', dump, objstr; for (;;) { i = s.lastIndexOf(LBRACE, lidx); if (i < 0) { break; } j = s.indexOf(RBRACE, i); if (i + 1 > j) { break; } //Extract key and meta info token = s.substring(i + 1, j); key = token; meta = null; k = key.indexOf(SPACE); if (k > -1) { meta = key.substring(k + 1); key = key.substring(0, k); } // lookup the value v = o[key]; // if a substitution function was provided, execute it if (f) { v = f(key, v, meta); } if (L.isObject(v)) { if (L.isArray(v)) { v = L.dump(v, parseInt(meta, 10)); } else { meta = meta || ""; // look for the keyword 'dump', if found force obj dump dump = meta.indexOf(DUMP); if (dump > -1) { meta = meta.substring(4); } objstr = v.toString(); // use the toString if it is not the Object toString // and the 'dump' meta info was not found if (objstr === OBJECT_TOSTRING || dump > -1) { v = L.dump(v, parseInt(meta, 10)); } else { v = objstr; } } } else if (!L.isString(v) && !L.isNumber(v)) { // This {block} has no replace string. Save it for later. v = "~-" + saved.length + "-~"; saved[saved.length] = token; // break; } s = s.substring(0, i) + v + s.substring(j + 1); if (recurse === false) { lidx = i-1; } } // restore saved {block}s for (i=saved.length-1; i>=0; i=i-1) { s = s.replace(new RegExp("~-" + i + "-~"), "{" + saved[i] + "}", "g"); } return s; }, /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @since 2.3.0 * @param s {string} the string to trim * @return {string} the trimmed string */ trim: function(s){ try { return s.replace(/^\s+|\s+$/g, ""); } catch(e) { return s; } }, /** * Returns a new object containing all of the properties of * all the supplied objects. The properties from later objects * will overwrite those in earlier objects. * @method merge * @since 2.3.0 * @param arguments {Object*} the objects to merge * @return the new merged object */ merge: function() { var o={}, a=arguments, l=a.length, i; for (i=0; i * var A = function() {}; * A.prototype.foo = 'foo'; * var a = new A(); * a.foo = 'foo'; * alert(a.hasOwnProperty('foo')); // true * alert(YAHOO.lang.hasOwnProperty(a, 'foo')); // false when using fallback * * @method hasOwnProperty * @param {any} o The object being testing * @param prop {string} the name of the property to test * @return {boolean} the result */ L.hasOwnProperty = (OP.hasOwnProperty) ? function(o, prop) { return o && o.hasOwnProperty && o.hasOwnProperty(prop); } : function(o, prop) { return !L.isUndefined(o[prop]) && o.constructor.prototype[prop] !== o[prop]; }; // new lang wins OB.augmentObject(L, OB, true); /* * An alias for YAHOO.lang * @class YAHOO.util.Lang */ YAHOO.util.Lang = L; /** * Same as YAHOO.lang.augmentObject, except it only applies prototype * properties. This is an alias for augmentProto. * @see YAHOO.lang.augmentObject * @method augment * @static * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param {String*|boolean} arguments zero or more properties methods to * augment the receiver with. If none specified, everything * in the supplier will be used unless it would * overwrite an existing property in the receiver. if true * is specified as the third parameter, all properties will * be applied and will overwrite an existing property in * the receiver */ L.augment = L.augmentProto; /** * An alias for YAHOO.lang.augment * @for YAHOO * @method augment * @static * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param {String*} arguments zero or more properties methods to * augment the receiver with. If none specified, everything * in the supplier will be used unless it would * overwrite an existing property in the receiver */ YAHOO.augment = L.augmentProto; /** * An alias for YAHOO.lang.extend * @method extend * @static * @param {Function} subc the object to modify * @param {Function} superc the object to inherit * @param {Object} overrides additional properties/methods to add to the * subclass prototype. These will override the * matching items obtained from the superclass if present. */ YAHOO.extend = L.extend; })(); YAHOO.register("yahoo", YAHOO, {version: "2.9.0", build: "2800"}); /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires * @param {Object} context The context the event will fire from. "this" will * refer to this object in the callback. Default value: * the window object. The listener can override this. * @param {boolean} silent pass true to prevent the event from writing to * the debugsystem * @param {int} signature the signature that the custom event subscriber * will receive. YAHOO.util.CustomEvent.LIST or * YAHOO.util.CustomEvent.FLAT. The default is * YAHOO.util.CustomEvent.LIST. * @param fireOnce {boolean} If configured to fire once, the custom event * will only notify subscribers a single time regardless of how many times * the event is fired. In addition, new subscribers will be notified * immediately if the event has already been fired. * @namespace YAHOO.util * @class CustomEvent * @constructor */ YAHOO.util.CustomEvent = function(type, context, silent, signature, fireOnce) { /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the event will fire from by default. Defaults to the window obj. * @property scope * @type object */ this.scope = context || window; /** * By default all custom events are logged in the debug build. Set silent to true * to disable debug output for this event. * @property silent * @type boolean */ this.silent = silent; /** * If configured to fire once, the custom event will only notify subscribers * a single time regardless of how many times the event is fired. In addition, * new subscribers will be notified immediately if the event has already been * fired. * @property fireOnce * @type boolean * @default false */ this.fireOnce = fireOnce; /** * Indicates whether or not this event has ever been fired. * @property fired * @type boolean * @default false */ this.fired = false; /** * For fireOnce events the arguments the event was fired with are stored * so that new subscribers get the proper payload. * @property firedWith * @type Array */ this.firedWith = null; /** * Custom events support two styles of arguments provided to the event * subscribers. *
    *
  • YAHOO.util.CustomEvent.LIST: *
      *
    • param1: event name
    • *
    • param2: array of arguments sent to fire
    • *
    • param3: a custom object supplied by the subscriber
    • *
    *
  • *
  • YAHOO.util.CustomEvent.FLAT *
      *
    • param1: the first argument passed to fire. If you need to * pass multiple parameters, use and array or object literal
    • *
    • param2: a custom object supplied by the subscriber
    • *
    *
  • *
* @property signature * @type int */ this.signature = signature || YAHOO.util.CustomEvent.LIST; /** * The subscribers to this event * @property subscribers * @type Subscriber[] */ this.subscribers = []; if (!this.silent) { YAHOO.log( "Creating " + this, "info", "Event" ); } var onsubscribeType = "_YUICEOnSubscribe"; // Only add subscribe events for events that are not generated by // CustomEvent if (type !== onsubscribeType) { /** * Custom events provide a custom event that fires whenever there is * a new subscriber to the event. This provides an opportunity to * handle the case where there is a non-repeating event that has * already fired has a new subscriber. * * @event subscribeEvent * @type YAHOO.util.CustomEvent * @param fn {Function} The function to execute * @param obj An object to be passed along when the event fires. * Defaults to the custom event. * @param override If true, the obj passed in becomes the * execution context of the listener. If an object, that object becomes * the execution context. Defaults to the custom event. */ this.subscribeEvent = new YAHOO.util.CustomEvent(onsubscribeType, this, true); } /** * In order to make it possible to execute the rest of the subscriber * stack when one thows an exception, the subscribers exceptions are * caught. The most recent exception is stored in this property * @property lastError * @type Error */ this.lastError = null; }; /** * Subscriber listener sigature constant. The LIST type returns three * parameters: the event type, the array of args passed to fire, and * the optional custom object * @property YAHOO.util.CustomEvent.LIST * @static * @type int */ YAHOO.util.CustomEvent.LIST = 0; /** * Subscriber listener sigature constant. The FLAT type returns two * parameters: the first argument passed to fire and the optional * custom object * @property YAHOO.util.CustomEvent.FLAT * @static * @type int */ YAHOO.util.CustomEvent.FLAT = 1; YAHOO.util.CustomEvent.prototype = { /** * Subscribes the caller to this event * @method subscribe * @param {Function} fn The function to execute * @param {Object} obj An object to be passed along when the event * fires. * @param {boolean|Object} overrideContext If true, the obj passed in * becomes the execution. * context of the listener. If an object, that object becomes the execution * context. */ subscribe: function(fn, obj, overrideContext) { if (!fn) { throw new Error("Invalid callback for subscriber to '" + this.type + "'"); } if (this.subscribeEvent) { this.subscribeEvent.fire(fn, obj, overrideContext); } var s = new YAHOO.util.Subscriber(fn, obj, overrideContext); if (this.fireOnce && this.fired) { this.notify(s, this.firedWith); } else { this.subscribers.push(s); } }, /** * Unsubscribes subscribers. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} obj The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {boolean} True if the subscriber was found and detached. */ unsubscribe: function(fn, obj) { if (!fn) { return this.unsubscribeAll(); } var found = false; for (var i=0, len=this.subscribers.length; i *
  • The type of event
  • *
  • All of the arguments fire() was executed with as an array
  • *
  • The custom object (if any) that was passed into the subscribe() * method
  • * * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise */ fire: function() { this.lastError = null; var errors = [], len=this.subscribers.length; var args=[].slice.call(arguments, 0), ret=true, i, rebuild=false; if (this.fireOnce) { if (this.fired) { YAHOO.log('fireOnce event has already fired: ' + this.type); return true; } else { this.firedWith = args; } } this.fired = true; if (!len && this.silent) { //YAHOO.log('DEBUG no subscribers'); return true; } if (!this.silent) { YAHOO.log( "Firing " + this + ", " + "args: " + args + ", " + "subscribers: " + len, "info", "Event" ); } // make a copy of the subscribers so that there are // no index problems if one subscriber removes another. var subs = this.subscribers.slice(); for (i=0; i " + s, "info", "Event" ); } if (this.signature == YAHOO.util.CustomEvent.FLAT) { if (args.length > 0) { param = args[0]; } try { ret = s.fn.call(scope, param, s.obj); } catch(e) { this.lastError = e; // errors.push(e); YAHOO.log(this + " subscriber exception: " + e, "error", "Event"); if (throwErrors) { throw e; } } } else { try { ret = s.fn.call(scope, this.type, args, s.obj); } catch(ex) { this.lastError = ex; YAHOO.log(this + " subscriber exception: " + ex, "error", "Event"); if (throwErrors) { throw ex; } } } return ret; }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed */ unsubscribeAll: function() { var l = this.subscribers.length, i; for (i=l-1; i>-1; i--) { this._delete(i); } this.subscribers=[]; return l; }, /** * @method _delete * @private */ _delete: function(index) { var s = this.subscribers[index]; if (s) { delete s.fn; delete s.obj; } // this.subscribers[index]=null; this.subscribers.splice(index, 1); }, /** * @method toString */ toString: function() { return "CustomEvent: " + "'" + this.type + "', " + "context: " + this.scope; } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The function to execute * @param {Object} obj An object to be passed along when the event fires * @param {boolean} overrideContext If true, the obj passed in becomes the execution * context of the listener * @class Subscriber * @constructor */ YAHOO.util.Subscriber = function(fn, obj, overrideContext) { /** * The callback that will be execute when the event fires * @property fn * @type function */ this.fn = fn; /** * An optional custom object that will passed to the callback when * the event fires * @property obj * @type object */ this.obj = YAHOO.lang.isUndefined(obj) ? null : obj; /** * The default execution context for the event listener is defined when the * event is created (usually the object which contains the event). * By setting overrideContext to true, the execution context becomes the custom * object passed in by the subscriber. If overrideContext is an object, that * object becomes the context. * @property overrideContext * @type boolean|object */ this.overrideContext = overrideContext; }; /** * Returns the execution context for this listener. If overrideContext was set to true * the custom obj will be the context. If overrideContext is an object, that is the * context, otherwise the default context will be used. * @method getScope * @param {Object} defaultScope the context to use if this listener does not * override it. */ YAHOO.util.Subscriber.prototype.getScope = function(defaultScope) { if (this.overrideContext) { if (this.overrideContext === true) { return this.obj; } else { return this.overrideContext; } } return defaultScope; }; /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute * @param {Object} obj an object to be passed along when the event fires * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ YAHOO.util.Subscriber.prototype.contains = function(fn, obj) { if (obj) { return (this.fn == fn && this.obj == obj); } else { return (this.fn == fn); } }; /** * @method toString */ YAHOO.util.Subscriber.prototype.toString = function() { return "Subscriber { obj: " + this.obj + ", overrideContext: " + (this.overrideContext || "no") + " }"; }; /** * The Event Utility provides utilities for managing DOM Events and tools * for building event systems * * @module event * @title Event Utility * @namespace YAHOO.util * @requires yahoo */ // The first instance of Event will win if it is loaded more than once. // @TODO this needs to be changed so that only the state data that needs to // be preserved is kept, while methods are overwritten/added as needed. // This means that the module pattern can't be used. if (!YAHOO.util.Event) { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ YAHOO.util.Event = function() { /** * True after the onload event has fired * @property loadComplete * @type boolean * @static * @private */ var loadComplete = false, /** * Cache of wrapped listeners * @property listeners * @type array * @static * @private */ listeners = [], /** * User-defined unload function that will be fired before all events * are detached * @property unloadListeners * @type array * @static * @private */ unloadListeners = [], /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property retryCount * @static * @private */ retryCount = 0, /** * onAvailable listeners * @property onAvailStack * @static * @private */ onAvailStack = [], /** * Counter for auto id generation * @property counter * @static * @private */ counter = 0, /** * Normalized keycodes for webkit/safari * @property webkitKeymap * @type {int: int} * @private * @static * @final */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9 // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) }, isIE = YAHOO.env.ua.ie, // String constants used by the addFocusListener and removeFocusListener methods FOCUSIN = "focusin", FOCUSOUT = "focusout"; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 500@amp;40 ms, so it will poll * for 20 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 500, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * Element to bind, int constant * @property EL * @type int * @static * @final */ EL: 0, /** * Type of event, int constant * @property TYPE * @type int * @static * @final */ TYPE: 1, /** * Function to execute, int constant * @property FN * @type int * @static * @final */ FN: 2, /** * Function wrapped for context correction and cleanup, int constant * @property WFN * @type int * @static * @final */ WFN: 3, /** * Object passed in by the user that will be returned as a * parameter to the callback, int constant. Specific to * unload listeners * @property OBJ * @type int * @static * @final */ UNLOAD_OBJ: 3, /** * Adjusted context, either the element we are registering the event * on or the custom object passed in by the listener, int constant * @property ADJ_SCOPE * @type int * @static * @final */ ADJ_SCOPE: 4, /** * The original obj passed into addListener * @property OBJ * @type int * @static * @final */ OBJ: 5, /** * The original context parameter passed into addListener * @property OVERRIDE * @type int * @static * @final */ OVERRIDE: 6, /** * The original capture parameter passed into addListener * @property CAPTURE * @type int * @static * @final */ CAPTURE: 7, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * Safari detection * @property isSafari * @private * @static * @deprecated use YAHOO.env.ua.webkit */ isSafari: YAHOO.env.ua.webkit, /** * webkit version * @property webkit * @type string * @private * @static * @deprecated use YAHOO.env.ua.webkit */ webkit: YAHOO.env.ua.webkit, /** * IE detection * @property isIE * @private * @static * @deprecated use YAHOO.env.ua.ie */ isIE: isIE, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * Map of special event types * @property _specialTypes * @static * @private */ _specialTypes: { focusin: (isIE ? "focusin" : "focus"), focusout: (isIE ? "focusout" : "blur") }, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * Errors thrown by subscribers of custom events are caught * and the error message is written to the debug console. If * this property is set to true, it will also re-throw the * error. * @property throwErrors * @type boolean * @default false */ throwErrors: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!this._interval) { // var self = this; // var callback = function() { self._tryPreloadAttach(); }; // this._interval = setInterval(callback, this.POLL_INTERVAL); this._interval = YAHOO.lang.later(this.POLL_INTERVAL, this, this._tryPreloadAttach, null, true); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * *

    The callback is executed with a single parameter: * the custom object parameter, if provided.

    * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} overrideContext If set to true, fn will execute * in the context of obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static */ onAvailable: function(id, fn, obj, overrideContext, checkContent) { var a = (YAHOO.lang.isString(id)) ? [id] : id; for (var i=0; iThe callback is executed with a single parameter: * the custom object parameter, if provided.

    * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} overrideContext If set to true, fn will execute * in the context of obj. If an object, fn will * exectute in the context of that object * * @static */ onContentReady: function(id, fn, obj, overrideContext) { this.onAvailable(id, fn, obj, overrideContext, true); }, /** * Executes the supplied callback when the DOM is first usable. This * will execute immediately if called after the DOMReady event has * fired. @todo the DOMContentReady event does not fire when the * script is dynamically injected into the page. This means the * DOMReady custom event will never fire in FireFox or Opera when the * library is injected. It _will_ fire in Safari, and the IE * implementation would allow for us to fire it if the defered script * is not available. We want this to behave the same in all browsers. * Is there a way to identify when the script has been injected * instead of included inline? Is there a way to know whether the * window onload event has fired without having had a listener attached * to it when it did so? * *

    The callback is a CustomEvent, so the signature is:

    *

    type <string>, args <array>, customobject <object>

    *

    For DOMReady events, there are no fire argments, so the * signature is:

    *

    "DOMReady", [], obj

    * * * @method onDOMReady * * @param {function} fn what to execute when the element is found. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} overrideContext If set to true, fn will execute * in the context of obj, if set to an object it * will execute in the context of that object * * @static */ // onDOMReady: function(fn, obj, overrideContext) { onDOMReady: function() { this.DOMReadyEvent.subscribe.apply(this.DOMReadyEvent, arguments); }, /** * Appends an event handler * * @method _addListener * * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {String} sType The type of event to append * @param {Function} fn The method the event invokes * @param {Object} obj An arbitrary object that will be * passed as a parameter to the handler * @param {Boolean|object} overrideContext If true, the obj passed in becomes * the execution context of the listener. If an * object, this object becomes the execution * context. * @param {boolen} capture capture or bubble phase * @return {Boolean} True if the action was successful or defered, * false if one or more of the elements * could not have the listener attached, * or if the operation throws an exception. * @private * @static */ _addListener: function(el, sType, fn, obj, overrideContext, bCapture) { if (!fn || !fn.call) { YAHOO.log(sType + " addListener failed, invalid callback", "error", "Event"); return false; } // The el argument can be an array of elements or element ids. if ( this._isValidCollection(el)) { var ok = true; for (var i=0,len=el.length; i-1; i--) { ok = ( this.removeListener(el[i], sType, fn) && ok ); } return ok; } if (!fn || !fn.call) { // this.logger.debug("Error, function is not valid " + fn); //return false; return this.purgeElement(el, false, sType); } if ("unload" == sType) { for (i=unloadListeners.length-1; i>-1; i--) { li = unloadListeners[i]; if (li && li[0] == el && li[1] == sType && li[2] == fn) { unloadListeners.splice(i, 1); // unloadListeners[i]=null; return true; } } return false; } var cacheItem = null; // The index is a hidden parameter; needed to remove it from // the method signature because it was tempting users to // try and take advantage of it, which is not possible. var index = arguments[3]; if ("undefined" === typeof index) { index = this._getCacheIndex(listeners, el, sType, fn); } if (index >= 0) { cacheItem = listeners[index]; } if (!el || !cacheItem) { // this.logger.debug("cached listener not found"); return false; } // this.logger.debug("Removing handler: " + el + ", " + sType); var bCapture = cacheItem[this.CAPTURE] === true ? true : false; try { this._simpleRemove(el, sType, cacheItem[this.WFN], bCapture); } catch(ex) { this.lastError = ex; return false; } // removed the wrapped handler delete listeners[index][this.WFN]; delete listeners[index][this.FN]; listeners.splice(index, 1); // listeners[index]=null; return true; }, /** * Returns the event's target element. Safari sometimes provides * a text node, and this is automatically resolved to the text * node's parent so that it behaves like other browsers. * @method getTarget * @param {Event} ev the event * @param {boolean} resolveTextNode when set to true the target's * parent will be returned if the target is a * text node. @deprecated, the text node is * now resolved automatically * @return {HTMLElement} the event's target * @static */ getTarget: function(ev, resolveTextNode) { var t = ev.target || ev.srcElement; return this.resolveTextNode(t); }, /** * In some cases, some browsers will return a text node inside * the actual element that was targeted. This normalizes the * return value for getTarget and getRelatedTarget. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolveTextNode * @param {HTMLElement} node node to resolve * @return {HTMLElement} the normized node * @static */ resolveTextNode: function(n) { try { if (n && 3 == n.nodeType) { return n.parentNode; } } catch(e) { return null; } return n; }, /** * Returns the event's pageX * @method getPageX * @param {Event} ev the event * @return {int} the event's pageX * @static */ getPageX: function(ev) { var x = ev.pageX; if (!x && 0 !== x) { x = ev.clientX || 0; if ( this.isIE ) { x += this._getScrollLeft(); } } return x; }, /** * Returns the event's pageY * @method getPageY * @param {Event} ev the event * @return {int} the event's pageY * @static */ getPageY: function(ev) { var y = ev.pageY; if (!y && 0 !== y) { y = ev.clientY || 0; if ( this.isIE ) { y += this._getScrollTop(); } } return y; }, /** * Returns the pageX and pageY properties as an indexed array. * @method getXY * @param {Event} ev the event * @return {[x, y]} the pageX and pageY properties of the event * @static */ getXY: function(ev) { return [this.getPageX(ev), this.getPageY(ev)]; }, /** * Returns the event's related target * @method getRelatedTarget * @param {Event} ev the event * @return {HTMLElement} the event's relatedTarget * @static */ getRelatedTarget: function(ev) { var t = ev.relatedTarget; if (!t) { if (ev.type == "mouseout") { t = ev.toElement; } else if (ev.type == "mouseover") { t = ev.fromElement; } } return this.resolveTextNode(t); }, /** * Returns the time of the event. If the time is not included, the * event is modified using the current time. * @method getTime * @param {Event} ev the event * @return {Date} the time of the event * @static */ getTime: function(ev) { if (!ev.time) { var t = new Date().getTime(); try { ev.time = t; } catch(ex) { this.lastError = ex; return t; } } return ev.time; }, /** * Convenience method for stopPropagation + preventDefault * @method stopEvent * @param {Event} ev the event * @static */ stopEvent: function(ev) { this.stopPropagation(ev); this.preventDefault(ev); }, /** * Stops event propagation * @method stopPropagation * @param {Event} ev the event * @static */ stopPropagation: function(ev) { if (ev.stopPropagation) { ev.stopPropagation(); } else { ev.cancelBubble = true; } }, /** * Prevents the default behavior of the event * @method preventDefault * @param {Event} ev the event * @static */ preventDefault: function(ev) { if (ev.preventDefault) { ev.preventDefault(); } else { ev.returnValue = false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} boundEl the element the listener is attached to * @return {Event} the event * @static */ getEvent: function(e, boundEl) { var ev = e || window.event; if (!ev) { var c = this.getEvent.caller; while (c) { ev = c.arguments[0]; if (ev && Event == ev.constructor) { break; } c = c.caller; } } return ev; }, /** * Returns the charcode for an event * @method getCharCode * @param {Event} ev the event * @return {int} the event's charCode * @static */ getCharCode: function(ev) { var code = ev.keyCode || ev.charCode || 0; // webkit key normalization if (YAHOO.env.ua.webkit && (code in webkitKeymap)) { code = webkitKeymap[code]; } return code; }, /** * Locating the saved event handler data by function ref * * @method _getCacheIndex * @static * @private */ _getCacheIndex: function(a, el, sType, fn) { for (var i=0, l=a.length; i 0 && onAvailStack.length > 0); } // onAvailable var notAvail = []; var executeItem = function (el, item) { var context = el; if (item.overrideContext) { if (item.overrideContext === true) { context = item.obj; } else { context = item.overrideContext; } } item.fn.call(context, item.obj); }; var i, len, item, el, ready=[]; // onAvailable onContentReady for (i=0, len=onAvailStack.length; i-1; i--) { item = onAvailStack[i]; if (!item || !item.id) { onAvailStack.splice(i, 1); } } this.startInterval(); } else { if (this._interval) { // clearInterval(this._interval); this._interval.cancel(); this._interval = null; } } this.locked = false; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} sType optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, sType) { var oEl = (YAHOO.lang.isString(el)) ? this.getEl(el) : el; var elListeners = this.getListeners(oEl, sType), i, len; if (elListeners) { for (i=elListeners.length-1; i>-1; i--) { var l = elListeners[i]; this.removeListener(oEl, l.type, l.fn); } } if (recurse && oEl && oEl.childNodes) { for (i=0,len=oEl.childNodes.length; i-1; j--) { l = listeners[j]; if (l) { try { EU.removeListener(l[EU.EL], l[EU.TYPE], l[EU.FN], j); } catch(e2) {} } } l=null; } try { EU._simpleRemove(window, "unload", EU._unload); EU._simpleRemove(window, "load", EU._load); } catch(e3) {} }, /** * Returns scrollLeft * @method _getScrollLeft * @static * @private */ _getScrollLeft: function() { return this._getScroll()[1]; }, /** * Returns scrollTop * @method _getScrollTop * @static * @private */ _getScrollTop: function() { return this._getScroll()[0]; }, /** * Returns the scrollTop and scrollLeft. Used to calculate the * pageX and pageY in Internet Explorer * @method _getScroll * @static * @private */ _getScroll: function() { var dd = document.documentElement, db = document.body; if (dd && (dd.scrollTop || dd.scrollLeft)) { return [dd.scrollTop, dd.scrollLeft]; } else if (db) { return [db.scrollTop, db.scrollLeft]; } else { return [0, 0]; } }, /** * Used by old versions of CustomEvent, restored for backwards * compatibility * @method regCE * @private * @static * @deprecated still here for backwards compatibility */ regCE: function() {}, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method _simpleAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} sType the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ _simpleAdd: function () { if (window.addEventListener) { return function(el, sType, fn, capture) { el.addEventListener(sType, fn, (capture)); }; } else if (window.attachEvent) { return function(el, sType, fn, capture) { el.attachEvent("on" + sType, fn); }; } else { return function(){}; } }(), /** * Basic remove listener * * @method _simpleRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} sType the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ _simpleRemove: function() { if (window.removeEventListener) { return function (el, sType, fn, capture) { el.removeEventListener(sType, fn, (capture)); }; } else if (window.detachEvent) { return function (el, sType, fn) { el.detachEvent("on" + sType, fn); }; } else { return function(){}; } }() }; }(); (function() { var EU = YAHOO.util.Event; /** * Appends an event handler. This is an alias for addListener * * @method on * * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {String} sType The type of event to append * @param {Function} fn The method the event invokes * @param {Object} obj An arbitrary object that will be * passed as a parameter to the handler * @param {Boolean|object} overrideContext If true, the obj passed in becomes * the execution context of the listener. If an * object, this object becomes the execution * context. * @return {Boolean} True if the action was successful or defered, * false if one or more of the elements * could not have the listener attached, * or if the operation throws an exception. * @static */ EU.on = EU.addListener; /** * YAHOO.util.Event.onFocus is an alias for addFocusListener * @method onFocus * @see addFocusListener * @static * @deprecated use YAHOO.util.Event.on and specify "focusin" as the event type. */ EU.onFocus = EU.addFocusListener; /** * YAHOO.util.Event.onBlur is an alias for addBlurListener * @method onBlur * @see addBlurListener * @static * @deprecated use YAHOO.util.Event.on and specify "focusout" as the event type. */ EU.onBlur = EU.addBlurListener; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ // Internet Explorer: use the readyState of a defered script. // This isolates what appears to be a safe moment to manipulate // the DOM prior to when the document's readyState suggests // it is safe to do so. if (EU.isIE) { if (self !== self.top) { document.onreadystatechange = function() { if (document.readyState == 'complete') { document.onreadystatechange = null; EU._ready(); } }; } else { // Process onAvailable/onContentReady items when the // DOM is ready. YAHOO.util.Event.onDOMReady( YAHOO.util.Event._tryPreloadAttach, YAHOO.util.Event, true); var n = document.createElement('p'); EU._dri = setInterval(function() { try { // throws an error if doc is not ready n.doScroll('left'); clearInterval(EU._dri); EU._dri = null; EU._ready(); n = null; } catch (ex) { } }, EU.POLL_INTERVAL); } // The document's readyState in Safari currently will // change to loaded/complete before images are loaded. } else if (EU.webkit && EU.webkit < 525) { EU._dri = setInterval(function() { var rs=document.readyState; if ("loaded" == rs || "complete" == rs) { clearInterval(EU._dri); EU._dri = null; EU._ready(); } }, EU.POLL_INTERVAL); // FireFox and Opera: These browsers provide a event for this // moment. The latest WebKit releases now support this event. } else { EU._simpleAdd(document, "DOMContentLoaded", EU._ready); } ///////////////////////////////////////////////////////////// EU._simpleAdd(window, "load", EU._load); EU._simpleAdd(window, "unload", EU._unload); EU._tryPreloadAttach(); })(); } /** * EventProvider is designed to be used with YAHOO.augment to wrap * CustomEvents in an interface that allows events to be subscribed to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * * @Class EventProvider */ YAHOO.util.EventProvider = function() { }; YAHOO.util.EventProvider.prototype = { /** * Private storage of custom events * @property __yui_events * @type Object[] * @private */ __yui_events: null, /** * Private storage of custom event subscribers * @property __yui_subscribers * @type Object[] * @private */ __yui_subscribers: null, /** * Subscribe to a CustomEvent by event type * * @method subscribe * @param p_type {string} the type, or name of the event * @param p_fn {function} the function to exectute when the event fires * @param p_obj {Object} An object to be passed along when the event * fires * @param overrideContext {boolean} If true, the obj passed in becomes the * execution scope of the listener */ subscribe: function(p_type, p_fn, p_obj, overrideContext) { this.__yui_events = this.__yui_events || {}; var ce = this.__yui_events[p_type]; if (ce) { ce.subscribe(p_fn, p_obj, overrideContext); } else { this.__yui_subscribers = this.__yui_subscribers || {}; var subs = this.__yui_subscribers; if (!subs[p_type]) { subs[p_type] = []; } subs[p_type].push( { fn: p_fn, obj: p_obj, overrideContext: overrideContext } ); } }, /** * Unsubscribes one or more listeners the from the specified event * @method unsubscribe * @param p_type {string} The type, or name of the event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param p_fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param p_obj {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {boolean} true if the subscriber was found and detached. */ unsubscribe: function(p_type, p_fn, p_obj) { this.__yui_events = this.__yui_events || {}; var evts = this.__yui_events; if (p_type) { var ce = evts[p_type]; if (ce) { return ce.unsubscribe(p_fn, p_obj); } } else { var ret = true; for (var i in evts) { if (YAHOO.lang.hasOwnProperty(evts, i)) { ret = ret && evts[i].unsubscribe(p_fn, p_obj); } } return ret; } return false; }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param p_type {string} The type, or name of the event */ unsubscribeAll: function(p_type) { return this.unsubscribe(p_type); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method createEvent * * @param p_type {string} the type, or name of the event * @param p_config {object} optional config params. Valid properties are: * *
      *
    • * scope: defines the default execution scope. If not defined * the default scope will be this instance. *
    • *
    • * silent: if true, the custom event will not generate log messages. * This is false by default. *
    • *
    • * fireOnce: if true, the custom event will only notify subscribers * once regardless of the number of times the event is fired. In * addition, new subscribers will be executed immediately if the * event has already fired. * This is false by default. *
    • *
    • * onSubscribeCallback: specifies a callback to execute when the * event has a new subscriber. This will fire immediately for * each queued subscriber if any exist prior to the creation of * the event. *
    • *
    * * @return {CustomEvent} the custom event * */ createEvent: function(p_type, p_config) { this.__yui_events = this.__yui_events || {}; var opts = p_config || {}, events = this.__yui_events, ce; if (events[p_type]) { YAHOO.log("EventProvider createEvent skipped: '"+p_type+"' already exists"); } else { ce = new YAHOO.util.CustomEvent(p_type, opts.scope || this, opts.silent, YAHOO.util.CustomEvent.FLAT, opts.fireOnce); events[p_type] = ce; if (opts.onSubscribeCallback) { ce.subscribeEvent.subscribe(opts.onSubscribeCallback); } this.__yui_subscribers = this.__yui_subscribers || {}; var qs = this.__yui_subscribers[p_type]; if (qs) { for (var i=0; i *
  • The first argument fire() was executed with
  • *
  • The custom object (if any) that was passed into the subscribe() * method
  • * * @method fireEvent * @param p_type {string} the type, or name of the event * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. * @return {boolean} the return value from CustomEvent.fire * */ fireEvent: function(p_type) { this.__yui_events = this.__yui_events || {}; var ce = this.__yui_events[p_type]; if (!ce) { YAHOO.log(p_type + "event fired before it was created."); return null; } var args = []; for (var i=1; i 0) { // Substring until first space sClass = sSource.substring(0,spaceIndex); // The rest of the source sDetail = sSource.substring(spaceIndex,sSource.length); } else { sClass = sSource; } if(this._isNewSource(sClass)) { this._createNewSource(sClass); } } var timestamp = new Date(); var logEntry = new YAHOO.widget.LogMsg({ msg: sMsg, time: timestamp, category: sCategory, source: sClass, sourceDetail: sDetail }); var stack = this._stack; var maxStackEntries = this.maxStackEntries; if(maxStackEntries && !isNaN(maxStackEntries) && (stack.length >= maxStackEntries)) { stack.shift(); } stack.push(logEntry); this.newLogEvent.fire(logEntry); if(this._browserConsoleEnabled) { this._printToBrowserConsole(logEntry); } return true; } else { return false; } }; /** * Resets internal stack and startTime, enables Logger, and fires logResetEvent. * * @method reset */ YAHOO.widget.Logger.reset = function() { this._stack = []; this._startTime = new Date().getTime(); this.loggerEnabled = true; this.log("Logger reset"); this.logResetEvent.fire(); }; /** * Public accessor to internal stack of log message objects. * * @method getStack * @return {Object[]} Array of log message objects. */ YAHOO.widget.Logger.getStack = function() { return this._stack; }; /** * Public accessor to internal start time. * * @method getStartTime * @return {Date} Internal date of when Logger singleton was initialized. */ YAHOO.widget.Logger.getStartTime = function() { return this._startTime; }; /** * Disables output to the browser's global console.log() function, which is used * by the Firebug extension to Firefox as well as Safari. * * @method disableBrowserConsole */ YAHOO.widget.Logger.disableBrowserConsole = function() { YAHOO.log("Logger output to the function console.log() has been disabled."); this._browserConsoleEnabled = false; }; /** * Enables output to the browser's global console.log() function, which is used * by the Firebug extension to Firefox as well as Safari. * * @method enableBrowserConsole */ YAHOO.widget.Logger.enableBrowserConsole = function() { this._browserConsoleEnabled = true; YAHOO.log("Logger output to the function console.log() has been enabled."); }; /** * Surpresses native JavaScript errors and outputs to console. By default, * Logger does not handle JavaScript window error events. * NB: Not all browsers support the window.onerror event. * * @method handleWindowErrors */ YAHOO.widget.Logger.handleWindowErrors = function() { if(!YAHOO.widget.Logger._windowErrorsHandled) { // Save any previously defined handler to call if(window.error) { YAHOO.widget.Logger._origOnWindowError = window.onerror; } window.onerror = YAHOO.widget.Logger._onWindowError; YAHOO.widget.Logger._windowErrorsHandled = true; YAHOO.log("Logger handling of window.onerror has been enabled."); } else { YAHOO.log("Logger handling of window.onerror had already been enabled."); } }; /** * Unsurpresses native JavaScript errors. By default, * Logger does not handle JavaScript window error events. * NB: Not all browsers support the window.onerror event. * * @method unhandleWindowErrors */ YAHOO.widget.Logger.unhandleWindowErrors = function() { if(YAHOO.widget.Logger._windowErrorsHandled) { // Revert to any previously defined handler to call if(YAHOO.widget.Logger._origOnWindowError) { window.onerror = YAHOO.widget.Logger._origOnWindowError; YAHOO.widget.Logger._origOnWindowError = null; } else { window.onerror = null; } YAHOO.widget.Logger._windowErrorsHandled = false; YAHOO.log("Logger handling of window.onerror has been disabled."); } else { YAHOO.log("Logger handling of window.onerror had already been disabled."); } }; ///////////////////////////////////////////////////////////////////////////// // // Public events // ///////////////////////////////////////////////////////////////////////////// /** * Fired when a new category has been created. * * @event categoryCreateEvent * @param sCategory {String} Category name. */ YAHOO.widget.Logger.categoryCreateEvent = new YAHOO.util.CustomEvent("categoryCreate", this, true); /** * Fired when a new source has been named. * * @event sourceCreateEvent * @param sSource {String} Source name. */ YAHOO.widget.Logger.sourceCreateEvent = new YAHOO.util.CustomEvent("sourceCreate", this, true); /** * Fired when a new log message has been created. * * @event newLogEvent * @param sMsg {String} Log message. */ YAHOO.widget.Logger.newLogEvent = new YAHOO.util.CustomEvent("newLog", this, true); /** * Fired when the Logger has been reset has been created. * * @event logResetEvent */ YAHOO.widget.Logger.logResetEvent = new YAHOO.util.CustomEvent("logReset", this, true); ///////////////////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////////////////// /** * Creates a new category of log messages and fires categoryCreateEvent. * * @method _createNewCategory * @param sCategory {String} Category name. * @private */ YAHOO.widget.Logger._createNewCategory = function(sCategory) { this.categories.push(sCategory); this.categoryCreateEvent.fire(sCategory); }; /** * Checks to see if a category has already been created. * * @method _isNewCategory * @param sCategory {String} Category name. * @return {Boolean} Returns true if category is unknown, else returns false. * @private */ YAHOO.widget.Logger._isNewCategory = function(sCategory) { for(var i=0; i < this.categories.length; i++) { if(sCategory == this.categories[i]) { return false; } } return true; }; /** * Creates a new source of log messages and fires sourceCreateEvent. * * @method _createNewSource * @param sSource {String} Source name. * @private */ YAHOO.widget.Logger._createNewSource = function(sSource) { this.sources.push(sSource); this.sourceCreateEvent.fire(sSource); }; /** * Checks to see if a source already exists. * * @method _isNewSource * @param sSource {String} Source name. * @return {Boolean} Returns true if source is unknown, else returns false. * @private */ YAHOO.widget.Logger._isNewSource = function(sSource) { if(sSource) { for(var i=0; i < this.sources.length; i++) { if(sSource == this.sources[i]) { return false; } } return true; } }; /** * Outputs a log message to global console.log() function. * * @method _printToBrowserConsole * @param oEntry {Object} Log entry object. * @private */ YAHOO.widget.Logger._printToBrowserConsole = function(oEntry) { if ((window.console && console.log) || (window.opera && opera.postError)) { var category = oEntry.category; var label = oEntry.category.substring(0,4).toUpperCase(); var time = oEntry.time; var localTime; if (time.toLocaleTimeString) { localTime = time.toLocaleTimeString(); } else { localTime = time.toString(); } var msecs = time.getTime(); var elapsedTime = (YAHOO.widget.Logger._lastTime) ? (msecs - YAHOO.widget.Logger._lastTime) : 0; YAHOO.widget.Logger._lastTime = msecs; var output = localTime + " (" + elapsedTime + "ms): " + oEntry.source + ": "; if (window.console) { console.log(output, oEntry.msg); } else { opera.postError(output + oEntry.msg); } } }; ///////////////////////////////////////////////////////////////////////////// // // Private event handlers // ///////////////////////////////////////////////////////////////////////////// /** * Handles logging of messages due to window error events. * * @method _onWindowError * @param sMsg {String} The error message. * @param sUrl {String} URL of the error. * @param sLine {String} Line number of the error. * @private */ YAHOO.widget.Logger._onWindowError = function(sMsg,sUrl,sLine) { // Logger is not in scope of this event handler try { YAHOO.widget.Logger.log(sMsg+' ('+sUrl+', line '+sLine+')', "window"); if(YAHOO.widget.Logger._origOnWindowError) { YAHOO.widget.Logger._origOnWindowError(); } } catch(e) { return false; } }; ///////////////////////////////////////////////////////////////////////////// // // First log // ///////////////////////////////////////////////////////////////////////////// YAHOO.widget.Logger.log("Logger initialized"); } /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ (function () { var Logger = YAHOO.widget.Logger, u = YAHOO.util, Dom = u.Dom, Event = u.Event, d = document; function make(el,props) { el = d.createElement(el); if (props) { for (var p in props) { if (props.hasOwnProperty(p)) { el[p] = props[p]; } } } return el; } /** * The LogReader class provides UI to read messages logged to YAHOO.widget.Logger. * * @class LogReader * @constructor * @param elContainer {HTMLElement} (optional) DOM element reference of an existing DIV. * @param elContainer {String} (optional) String ID of an existing DIV. * @param oConfigs {Object} (optional) Object literal of configuration params. */ function LogReader(elContainer, oConfigs) { this._sName = LogReader._index; LogReader._index++; this._init.apply(this,arguments); /** * Render the LogReader immediately upon instantiation. If set to false, * you must call myLogReader.render() to generate the UI. * * @property autoRender * @type {Boolean} * @default true */ if (this.autoRender !== false) { this.render(); } } ///////////////////////////////////////////////////////////////////////////// // // Static member variables // ///////////////////////////////////////////////////////////////////////////// YAHOO.lang.augmentObject(LogReader, { /** * Internal class member to index multiple LogReader instances. * * @property _memberName * @static * @type Number * @default 0 * @private */ _index : 0, /** * Node template for the log entries * @property ENTRY_TEMPLATE * @static * @type {HTMLElement} * @default pre element with class yui-log-entry */ ENTRY_TEMPLATE : (function () { return make('pre',{ className: 'yui-log-entry' }); })(), /** * Template used for innerHTML of verbose entry output. * @property VERBOSE_TEMPLATE * @static * @default "<p><span class='{category}'>{label}</span>{totalTime}ms (+{elapsedTime}) {localTime}:</p><p>{sourceAndDetail}</p><p>{message}</p>" */ VERBOSE_TEMPLATE : "

    {label} {totalTime}ms (+{elapsedTime}) {localTime}:

    {sourceAndDetail}

    {message}

    ", /** * Template used for innerHTML of compact entry output. * @property BASIC_TEMPLATE * @static * @default "<p><span class='{category}'>{label}</span>{totalTime}ms (+{elapsedTime}) {localTime}: {sourceAndDetail}: {message}</p>" */ BASIC_TEMPLATE : "

    {label} {totalTime}ms (+{elapsedTime}) {localTime}: {sourceAndDetail}: {message}

    " }); ///////////////////////////////////////////////////////////////////////////// // // Public member variables // ///////////////////////////////////////////////////////////////////////////// LogReader.prototype = { /** * Whether or not LogReader is enabled to output log messages. * * @property logReaderEnabled * @type Boolean * @default true */ logReaderEnabled : true, /** * Public member to access CSS width of the LogReader container. * * @property width * @type String */ width : null, /** * Public member to access CSS height of the LogReader container. * * @property height * @type String */ height : null, /** * Public member to access CSS top position of the LogReader container. * * @property top * @type String */ top : null, /** * Public member to access CSS left position of the LogReader container. * * @property left * @type String */ left : null, /** * Public member to access CSS right position of the LogReader container. * * @property right * @type String */ right : null, /** * Public member to access CSS bottom position of the LogReader container. * * @property bottom * @type String */ bottom : null, /** * Public member to access CSS font size of the LogReader container. * * @property fontSize * @type String */ fontSize : null, /** * Whether or not the footer UI is enabled for the LogReader. * * @property footerEnabled * @type Boolean * @default true */ footerEnabled : true, /** * Whether or not output is verbose (more readable). Setting to true will make * output more compact (less readable). * * @property verboseOutput * @type Boolean * @default true */ verboseOutput : true, /** * Custom output format for log messages. Defaults to null, which falls * back to verboseOutput param deciding between LogReader.VERBOSE_TEMPLATE * and LogReader.BASIC_TEMPLATE. Use bracketed place holders to mark where * message info should go. Available place holder names include: *
      *
    • category
    • *
    • label
    • *
    • sourceAndDetail
    • *
    • message
    • *
    • localTime
    • *
    • elapsedTime
    • *
    • totalTime
    • *
    * * @property entryFormat * @type String * @default null */ entryFormat : null, /** * Whether or not newest message is printed on top. * * @property newestOnTop * @type Boolean */ newestOnTop : true, /** * Output timeout buffer in milliseconds. * * @property outputBuffer * @type Number * @default 100 */ outputBuffer : 100, /** * Maximum number of messages a LogReader console will display. * * @property thresholdMax * @type Number * @default 500 */ thresholdMax : 500, /** * When a LogReader console reaches its thresholdMax, it will clear out messages * and print out the latest thresholdMin number of messages. * * @property thresholdMin * @type Number * @default 100 */ thresholdMin : 100, /** * True when LogReader is in a collapsed state, false otherwise. * * @property isCollapsed * @type Boolean * @default false */ isCollapsed : false, /** * True when LogReader is in a paused state, false otherwise. * * @property isPaused * @type Boolean * @default false */ isPaused : false, /** * Enables draggable LogReader if DragDrop Utility is present. * * @property draggable * @type Boolean * @default true */ draggable : true, ///////////////////////////////////////////////////////////////////////////// // // Public methods // ///////////////////////////////////////////////////////////////////////////// /** * Public accessor to the unique name of the LogReader instance. * * @method toString * @return {String} Unique name of the LogReader instance. */ toString : function() { return "LogReader instance" + this._sName; }, /** * Pauses output of log messages. While paused, log messages are not lost, but * get saved to a buffer and then output upon resume of LogReader. * * @method pause */ pause : function() { this.isPaused = true; this._timeout = null; this.logReaderEnabled = false; if (this._btnPause) { this._btnPause.value = "Resume"; } }, /** * Resumes output of log messages, including outputting any log messages that * have been saved to buffer while paused. * * @method resume */ resume : function() { this.isPaused = false; this.logReaderEnabled = true; this._printBuffer(); if (this._btnPause) { this._btnPause.value = "Pause"; } }, /** * Adds the UI to the DOM, attaches event listeners, and bootstraps initial * UI state. * * @method render */ render : function () { if (this.rendered) { return; } this._initContainerEl(); this._initHeaderEl(); this._initConsoleEl(); this._initFooterEl(); this._initCategories(); this._initSources(); this._initDragDrop(); // Subscribe to Logger custom events Logger.newLogEvent.subscribe(this._onNewLog, this); Logger.logResetEvent.subscribe(this._onReset, this); Logger.categoryCreateEvent.subscribe(this._onCategoryCreate, this); Logger.sourceCreateEvent.subscribe(this._onSourceCreate, this); this.rendered = true; this._filterLogs(); }, /** * Removes the UI from the DOM entirely and detaches all event listeners. * Implementers should note that Logger will still accumulate messages. * * @method destroy */ destroy : function () { Event.purgeElement(this._elContainer,true); this._elContainer.innerHTML = ''; this._elContainer.parentNode.removeChild(this._elContainer); this.rendered = false; }, /** * Hides UI of LogReader. Logging functionality is not disrupted. * * @method hide */ hide : function() { this._elContainer.style.display = "none"; }, /** * Shows UI of LogReader. Logging functionality is not disrupted. * * @method show */ show : function() { this._elContainer.style.display = "block"; }, /** * Collapses UI of LogReader. Logging functionality is not disrupted. * * @method collapse */ collapse : function() { this._elConsole.style.display = "none"; if(this._elFt) { this._elFt.style.display = "none"; } this._btnCollapse.value = "Expand"; this.isCollapsed = true; }, /** * Expands UI of LogReader. Logging functionality is not disrupted. * * @method expand */ expand : function() { this._elConsole.style.display = "block"; if(this._elFt) { this._elFt.style.display = "block"; } this._btnCollapse.value = "Collapse"; this.isCollapsed = false; }, /** * Returns related checkbox element for given filter (i.e., category or source). * * @method getCheckbox * @param {String} Category or source name. * @return {Array} Array of all filter checkboxes. */ getCheckbox : function(filter) { return this._filterCheckboxes[filter]; }, /** * Returns array of enabled categories. * * @method getCategories * @return {String[]} Array of enabled categories. */ getCategories : function() { return this._categoryFilters; }, /** * Shows log messages associated with given category. * * @method showCategory * @param {String} Category name. */ showCategory : function(sCategory) { var filtersArray = this._categoryFilters; // Don't do anything if category is already enabled // Use Array.indexOf if available... if(filtersArray.indexOf) { if(filtersArray.indexOf(sCategory) > -1) { return; } } // ...or do it the old-fashioned way else { for(var i=0; i -1) { return; } } // ...or do it the old-fashioned way else { for(var i=0; i", and "&" to HTML entities. * * @method html2Text * @param sHtml {String} String to convert. * @private */ html2Text : function(sHtml) { if(sHtml) { sHtml += ""; return sHtml.replace(/&/g, "&"). replace(//g, ">"); } return ""; }, ///////////////////////////////////////////////////////////////////////////// // // Private member variables // ///////////////////////////////////////////////////////////////////////////// /** * Name of LogReader instance. * * @property _sName * @type String * @private */ _sName : null, //TODO: remove /** * A class member shared by all LogReaders if a container needs to be * created during instantiation. Will be null if a container element never needs to * be created on the fly, such as when the implementer passes in their own element. * * @property _elDefaultContainer * @type HTMLElement * @private */ //YAHOO.widget.LogReader._elDefaultContainer = null; /** * Buffer of log message objects for batch output. * * @property _buffer * @type Object[] * @private */ _buffer : null, /** * Number of log messages output to console. * * @property _consoleMsgCount * @type Number * @default 0 * @private */ _consoleMsgCount : 0, /** * Date of last output log message. * * @property _lastTime * @type Date * @private */ _lastTime : null, /** * Batched output timeout ID. * * @property _timeout * @type Number * @private */ _timeout : null, /** * Hash of filters and their related checkbox elements. * * @property _filterCheckboxes * @type Object * @private */ _filterCheckboxes : null, /** * Array of filters for log message categories. * * @property _categoryFilters * @type String[] * @private */ _categoryFilters : null, /** * Array of filters for log message sources. * * @property _sourceFilters * @type String[] * @private */ _sourceFilters : null, /** * LogReader container element. * * @property _elContainer * @type HTMLElement * @private */ _elContainer : null, /** * LogReader header element. * * @property _elHd * @type HTMLElement * @private */ _elHd : null, /** * LogReader collapse element. * * @property _elCollapse * @type HTMLElement * @private */ _elCollapse : null, /** * LogReader collapse button element. * * @property _btnCollapse * @type HTMLElement * @private */ _btnCollapse : null, /** * LogReader title header element. * * @property _title * @type HTMLElement * @private */ _title : null, /** * LogReader console element. * * @property _elConsole * @type HTMLElement * @private */ _elConsole : null, /** * LogReader footer element. * * @property _elFt * @type HTMLElement * @private */ _elFt : null, /** * LogReader buttons container element. * * @property _elBtns * @type HTMLElement * @private */ _elBtns : null, /** * Container element for LogReader category filter checkboxes. * * @property _elCategoryFilters * @type HTMLElement * @private */ _elCategoryFilters : null, /** * Container element for LogReader source filter checkboxes. * * @property _elSourceFilters * @type HTMLElement * @private */ _elSourceFilters : null, /** * LogReader pause button element. * * @property _btnPause * @type HTMLElement * @private */ _btnPause : null, /** * Clear button element. * * @property _btnClear * @type HTMLElement * @private */ _btnClear : null, ///////////////////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////////////////// /** * Initializes the instance's message buffer, start time, etc * * @method _init * @param container {String|HTMLElement} (optional) the render target * @param config {Object} (optional) instance configuration * @protected */ _init : function (container, config) { // Internal vars this._buffer = []; // output buffer this._filterCheckboxes = {}; // pointers to checkboxes this._lastTime = Logger.getStartTime(); // timestamp of last log message to console // Parse config vars here if (config && (config.constructor == Object)) { for(var param in config) { if (config.hasOwnProperty(param)) { this[param] = config[param]; } } } this._elContainer = Dom.get(container); YAHOO.log("LogReader initialized", null, this.toString()); }, /** * Initializes the primary container element. * * @method _initContainerEl * @private */ _initContainerEl : function() { // Default the container if unset or not a div if(!this._elContainer || !/div$/i.test(this._elContainer.tagName)) { this._elContainer = d.body.insertBefore(make("div"),d.body.firstChild); // Only position absolutely if an in-DOM element is not supplied Dom.addClass(this._elContainer,"yui-log-container"); } Dom.addClass(this._elContainer,"yui-log"); // If implementer has provided container values, trust and set those var style = this._elContainer.style, styleProps = ['width','right','top','fontSize'], prop,i; for (i = styleProps.length - 1; i >= 0; --i) { prop = styleProps[i]; if (this[prop]){ style[prop] = this[prop]; } } if(this.left) { style.left = this.left; style.right = "auto"; } if(this.bottom) { style.bottom = this.bottom; style.top = "auto"; } // Opera needs a little prodding to reflow sometimes if (YAHOO.env.ua.opera) { d.body.style += ''; } }, /** * Initializes the header element. * * @method _initHeaderEl * @private */ _initHeaderEl : function() { // Destroy header if present if(this._elHd) { // Unhook DOM events Event.purgeElement(this._elHd, true); // Remove DOM elements this._elHd.innerHTML = ""; } // Create header // TODO: refactor this into an innerHTML this._elHd = make("div",{ className: "yui-log-hd" }); Dom.generateId(this._elHd, 'yui-log-hd' + this._sName); this._elCollapse = make("div",{ className: 'yui-log-btns' }); this._btnCollapse = make("input",{ type: 'button', className: 'yui-log-button', value: 'Collapse' }); Event.on(this._btnCollapse,'click',this._onClickCollapseBtn,this); this._title = make("h4",{ innerHTML : "Logger Console" }); this._elCollapse.appendChild(this._btnCollapse); this._elHd.appendChild(this._elCollapse); this._elHd.appendChild(this._title); this._elContainer.appendChild(this._elHd); }, /** * Initializes the console element. * * @method _initConsoleEl * @private */ _initConsoleEl : function() { // Destroy console if(this._elConsole) { // Unhook DOM events Event.purgeElement(this._elConsole, true); // Remove DOM elements this._elConsole.innerHTML = ""; } // Ceate console this._elConsole = make("div", { className: "yui-log-bd" }); // If implementer has provided console, trust and set those if(this.height) { this._elConsole.style.height = this.height; } this._elContainer.appendChild(this._elConsole); }, /** * Initializes the footer element. * * @method _initFooterEl * @private */ _initFooterEl : function() { // Don't create footer elements if footer is disabled if(this.footerEnabled) { // Destroy console if(this._elFt) { // Unhook DOM events Event.purgeElement(this._elFt, true); // Remove DOM elements this._elFt.innerHTML = ""; } // TODO: use innerHTML this._elFt = make("div",{ className: "yui-log-ft" }); this._elBtns = make("div", { className: "yui-log-btns" }); this._btnPause = make("input", { type: "button", className: "yui-log-button", value: "Pause" }); Event.on(this._btnPause,'click',this._onClickPauseBtn,this); this._btnClear = make("input", { type: "button", className: "yui-log-button", value: "Clear" }); Event.on(this._btnClear,'click',this._onClickClearBtn,this); this._elCategoryFilters = make("div", { className: "yui-log-categoryfilters" }); this._elSourceFilters = make("div", { className: "yui-log-sourcefilters" }); this._elBtns.appendChild(this._btnPause); this._elBtns.appendChild(this._btnClear); this._elFt.appendChild(this._elBtns); this._elFt.appendChild(this._elCategoryFilters); this._elFt.appendChild(this._elSourceFilters); this._elContainer.appendChild(this._elFt); } }, /** * Initializes Drag and Drop on the header element. * * @method _initDragDrop * @private */ _initDragDrop : function() { // If Drag and Drop utility is available... // ...and draggable is true... // ...then make the header draggable if(u.DD && this.draggable && this._elHd) { var ylog_dd = new u.DD(this._elContainer); ylog_dd.setHandleElId(this._elHd.id); //TODO: use class name this._elHd.style.cursor = "move"; } }, /** * Initializes category filters. * * @method _initCategories * @private */ _initCategories : function() { // Initialize category filters this._categoryFilters = []; var aInitialCategories = Logger.categories; for(var j=0; j < aInitialCategories.length; j++) { var sCategory = aInitialCategories[j]; // Add category to the internal array of filters this._categoryFilters.push(sCategory); // Add checkbox element if UI is enabled if(this._elCategoryFilters) { this._createCategoryCheckbox(sCategory); } } }, /** * Initializes source filters. * * @method _initSources * @private */ _initSources : function() { // Initialize source filters this._sourceFilters = []; var aInitialSources = Logger.sources; for(var j=0; j < aInitialSources.length; j++) { var sSource = aInitialSources[j]; // Add source to the internal array of filters this._sourceFilters.push(sSource); // Add checkbox element if UI is enabled if(this._elSourceFilters) { this._createSourceCheckbox(sSource); } } }, /** * Creates the UI for a category filter in the LogReader footer element. * * @method _createCategoryCheckbox * @param sCategory {String} Category name. * @private */ _createCategoryCheckbox : function(sCategory) { if(this._elFt) { var filter = make("span",{ className: "yui-log-filtergrp" }), checkid = Dom.generateId(null, "yui-log-filter-" + sCategory + this._sName), check = make("input", { id: checkid, className: "yui-log-filter-" + sCategory, type: "checkbox", category: sCategory }), label = make("label", { htmlFor: checkid, className: sCategory, innerHTML: sCategory }); // Subscribe to the click event Event.on(check,'click',this._onCheckCategory,this); this._filterCheckboxes[sCategory] = check; // Append el at the end so IE 5.5 can set "type" attribute // and THEN set checked property filter.appendChild(check); filter.appendChild(label); this._elCategoryFilters.appendChild(filter); check.checked = true; } }, /** * Creates a checkbox in the LogReader footer element to filter by source. * * @method _createSourceCheckbox * @param sSource {String} Source name. * @private */ _createSourceCheckbox : function(sSource) { if(this._elFt) { var filter = make("span",{ className: "yui-log-filtergrp" }), checkid = Dom.generateId(null, "yui-log-filter-" + sSource + this._sName), check = make("input", { id: checkid, className: "yui-log-filter-" + sSource, type: "checkbox", source: sSource }), label = make("label", { htmlFor: checkid, className: sSource, innerHTML: sSource }); // Subscribe to the click event Event.on(check,'click',this._onCheckSource,this); this._filterCheckboxes[sSource] = check; // Append el at the end so IE 5.5 can set "type" attribute // and THEN set checked property filter.appendChild(check); filter.appendChild(label); this._elSourceFilters.appendChild(filter); check.checked = true; } }, /** * Reprints all log messages in the stack through filters. * * @method _filterLogs * @private */ _filterLogs : function() { // Reprint stack with new filters if (this._elConsole !== null) { this.clearConsole(); this._printToConsole(Logger.getStack()); } }, /** * Sends buffer of log messages to output and clears buffer. * * @method _printBuffer * @private */ _printBuffer : function() { this._timeout = null; if(this._elConsole !== null) { var thresholdMax = this.thresholdMax; thresholdMax = (thresholdMax && !isNaN(thresholdMax)) ? thresholdMax : 500; if(this._consoleMsgCount < thresholdMax) { var entries = []; for (var i=0; i this.thresholdMax)) { thresholdMin = 0; } entriesStartIndex = (entriesLen > thresholdMin) ? (entriesLen - thresholdMin) : 0; // Iterate through all log entries for(i=entriesStartIndex; i -1; } } else { YAHOO.log('hasClass called with invalid arguments', 'warn', 'Dom'); } return ret; }, /** * Adds a class name to a given element or collection of elements. * @method addClass * @param {String | HTMLElement | Array} el The element or collection to add the class to * @param {String} className the class name to add to the class attribute * @return {Boolean | Array} A pass/fail boolean or array of booleans */ addClass: function(el, className) { return Y.Dom.batch(el, Y.Dom._addClass, className); }, _addClass: function(el, className) { var ret = false, current; if (el && className) { current = Y.Dom._getAttribute(el, CLASS_NAME) || EMPTY; if ( !Y.Dom._hasClass(el, className) ) { Y.Dom.setAttribute(el, CLASS_NAME, trim(current + SPACE + className)); ret = true; } } else { YAHOO.log('addClass called with invalid arguments', 'warn', 'Dom'); } return ret; }, /** * Removes a class name from a given element or collection of elements. * @method removeClass * @param {String | HTMLElement | Array} el The element or collection to remove the class from * @param {String} className the class name to remove from the class attribute * @return {Boolean | Array} A pass/fail boolean or array of booleans */ removeClass: function(el, className) { return Y.Dom.batch(el, Y.Dom._removeClass, className); }, _removeClass: function(el, className) { var ret = false, current, newClass, attr; if (el && className) { current = Y.Dom._getAttribute(el, CLASS_NAME) || EMPTY; Y.Dom.setAttribute(el, CLASS_NAME, current.replace(Y.Dom._getClassRegex(className), EMPTY)); newClass = Y.Dom._getAttribute(el, CLASS_NAME); if (current !== newClass) { // else nothing changed Y.Dom.setAttribute(el, CLASS_NAME, trim(newClass)); // trim after comparing to current class ret = true; if (Y.Dom._getAttribute(el, CLASS_NAME) === '') { // remove class attribute if empty attr = (el.hasAttribute && el.hasAttribute(_CLASS)) ? _CLASS : CLASS_NAME; YAHOO.log('removeClass removing empty class attribute', 'info', 'Dom'); el.removeAttribute(attr); } } } else { YAHOO.log('removeClass called with invalid arguments', 'warn', 'Dom'); } return ret; }, /** * Replace a class with another class for a given element or collection of elements. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String | HTMLElement | Array} el The element or collection to remove the class from * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @return {Boolean | Array} A pass/fail boolean or array of booleans */ replaceClass: function(el, oldClassName, newClassName) { return Y.Dom.batch(el, Y.Dom._replaceClass, { from: oldClassName, to: newClassName }); }, _replaceClass: function(el, classObj) { var className, from, to, ret = false, current; if (el && classObj) { from = classObj.from; to = classObj.to; if (!to) { ret = false; } else if (!from) { // just add if no "from" ret = Y.Dom._addClass(el, classObj.to); } else if (from !== to) { // else nothing to replace // May need to lead with DBLSPACE? current = Y.Dom._getAttribute(el, CLASS_NAME) || EMPTY; className = (SPACE + current.replace(Y.Dom._getClassRegex(from), SPACE + to). replace(/\s+/g, SPACE)). // normalize white space split(Y.Dom._getClassRegex(to)); // insert to into what would have been the first occurrence slot className.splice(1, 0, SPACE + to); Y.Dom.setAttribute(el, CLASS_NAME, trim(className.join(EMPTY))); ret = true; } } else { YAHOO.log('replaceClass called with invalid arguments', 'warn', 'Dom'); } return ret; }, /** * Returns an ID and applies it to the element "el", if provided. * @method generateId * @param {String | HTMLElement | Array} el (optional) An optional element array of elements to add an ID to (no ID is added if one is already present). * @param {String} prefix (optional) an optional prefix to use (defaults to "yui-gen"). * @return {String | Array} The generated ID, or array of generated IDs (or original ID if already present on an element) */ generateId: function(el, prefix) { prefix = prefix || 'yui-gen'; var f = function(el) { if (el && el.id) { // do not override existing ID YAHOO.log('generateId returning existing id ' + el.id, 'info', 'Dom'); return el.id; } var id = prefix + YAHOO.env._id_counter++; YAHOO.log('generateId generating ' + id, 'info', 'Dom'); if (el) { if (el[OWNER_DOCUMENT] && el[OWNER_DOCUMENT].getElementById(id)) { // in case one already exists // use failed id plus prefix to help ensure uniqueness return Y.Dom.generateId(el, id + prefix); } el.id = id; } return id; }; // batch fails when no element, so just generate and return single ID return Y.Dom.batch(el, f, Y.Dom, true) || f.apply(Y.Dom, arguments); }, /** * Determines whether an HTMLElement is an ancestor of another HTML element in the DOM hierarchy. * @method isAncestor * @param {String | HTMLElement} haystack The possible ancestor * @param {String | HTMLElement} needle The possible descendent * @return {Boolean} Whether or not the haystack is an ancestor of needle */ isAncestor: function(haystack, needle) { haystack = Y.Dom.get(haystack); needle = Y.Dom.get(needle); var ret = false; if ( (haystack && needle) && (haystack[NODE_TYPE] && needle[NODE_TYPE]) ) { if (haystack.contains && haystack !== needle) { // contains returns true when equal ret = haystack.contains(needle); } else if (haystack.compareDocumentPosition) { // gecko ret = !!(haystack.compareDocumentPosition(needle) & 16); } } else { YAHOO.log('isAncestor failed; invalid input: ' + haystack + ',' + needle, 'error', 'Dom'); } YAHOO.log('isAncestor(' + haystack + ',' + needle + ' returning ' + ret, 'info', 'Dom'); return ret; }, /** * Determines whether an HTMLElement is present in the current document. * @method inDocument * @param {String | HTMLElement} el The element to search for * @param {Object} doc An optional document to search, defaults to element's owner document * @return {Boolean} Whether or not the element is present in the current document */ inDocument: function(el, doc) { return Y.Dom._inDoc(Y.Dom.get(el), doc); }, _inDoc: function(el, doc) { var ret = false; if (el && el[TAG_NAME]) { doc = doc || el[OWNER_DOCUMENT]; ret = Y.Dom.isAncestor(doc[DOCUMENT_ELEMENT], el); } else { YAHOO.log('inDocument failed: invalid input', 'error', 'Dom'); } return ret; }, /** * Returns an array of HTMLElements that pass the test applied by supplied boolean method. * For optimized performance, include a tag and/or root node when possible. * Note: This method operates against a live collection, so modifying the * collection in the callback (removing/appending nodes, etc.) will have * side effects. Instead you should iterate the returned nodes array, * as you would with the native "getElementsByTagName" method. * @method getElementsBy * @param {Function} method - A boolean method for testing elements which receives the element as its only argument. * @param {String} tag (optional) The tag name of the elements being collected * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point * @param {Function} apply (optional) A function to apply to each element when found * @param {Any} o (optional) An optional arg that is passed to the supplied method * @param {Boolean} overrides (optional) Whether or not to override the scope of "method" with "o" * @return {Array} Array of HTMLElements */ getElementsBy: function(method, tag, root, apply, o, overrides, firstOnly) { tag = tag || '*'; root = (root) ? Y.Dom.get(root) : null || document; var ret = (firstOnly) ? null : [], elements; // in case Dom.get() returns null if (root) { elements = root.getElementsByTagName(tag); for (var i = 0, len = elements.length; i < len; ++i) { if ( method(elements[i]) ) { if (firstOnly) { ret = elements[i]; break; } else { ret[ret.length] = elements[i]; } } } if (apply) { Y.Dom.batch(ret, apply, o, overrides); } } YAHOO.log('getElementsBy returning ' + ret, 'info', 'Dom'); return ret; }, /** * Returns the first HTMLElement that passes the test applied by the supplied boolean method. * @method getElementBy * @param {Function} method - A boolean method for testing elements which receives the element as its only argument. * @param {String} tag (optional) The tag name of the elements being collected * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point * @return {HTMLElement} */ getElementBy: function(method, tag, root) { return Y.Dom.getElementsBy(method, tag, root, null, null, null, true); }, /** * Runs the supplied method against each item in the Collection/Array. * The method is called with the element(s) as the first arg, and the optional param as the second ( method(el, o) ). * @method batch * @param {String | HTMLElement | Array} el (optional) An element or array of elements to apply the method to * @param {Function} method The method to apply to the element(s) * @param {Any} o (optional) An optional arg that is passed to the supplied method * @param {Boolean} overrides (optional) Whether or not to override the scope of "method" with "o" * @return {Any | Array} The return value(s) from the supplied method */ batch: function(el, method, o, overrides) { var collection = [], scope = (overrides) ? o : null; el = (el && (el[TAG_NAME] || el.item)) ? el : Y.Dom.get(el); // skip get() when possible if (el && method) { if (el[TAG_NAME] || el.length === undefined) { // element or not array-like return method.call(scope, el, o); } for (var i = 0; i < el.length; ++i) { collection[collection.length] = method.call(scope || el[i], el[i], o); } } else { YAHOO.log('batch called with invalid arguments', 'warn', 'Dom'); return false; } return collection; }, /** * Returns the height of the document. * @method getDocumentHeight * @return {Int} The height of the actual document (which includes the body and its margin). */ getDocumentHeight: function() { var scrollHeight = (document[COMPAT_MODE] != CSS1_COMPAT || isSafari) ? document.body.scrollHeight : documentElement.scrollHeight, h = Math.max(scrollHeight, Y.Dom.getViewportHeight()); YAHOO.log('getDocumentHeight returning ' + h, 'info', 'Dom'); return h; }, /** * Returns the width of the document. * @method getDocumentWidth * @return {Int} The width of the actual document (which includes the body and its margin). */ getDocumentWidth: function() { var scrollWidth = (document[COMPAT_MODE] != CSS1_COMPAT || isSafari) ? document.body.scrollWidth : documentElement.scrollWidth, w = Math.max(scrollWidth, Y.Dom.getViewportWidth()); YAHOO.log('getDocumentWidth returning ' + w, 'info', 'Dom'); return w; }, /** * Returns the current height of the viewport. * @method getViewportHeight * @return {Int} The height of the viewable area of the page (excludes scrollbars). */ getViewportHeight: function() { var height = self.innerHeight, // Safari, Opera mode = document[COMPAT_MODE]; if ( (mode || isIE) && !isOpera ) { // IE, Gecko height = (mode == CSS1_COMPAT) ? documentElement.clientHeight : // Standards document.body.clientHeight; // Quirks } YAHOO.log('getViewportHeight returning ' + height, 'info', 'Dom'); return height; }, /** * Returns the current width of the viewport. * @method getViewportWidth * @return {Int} The width of the viewable area of the page (excludes scrollbars). */ getViewportWidth: function() { var width = self.innerWidth, // Safari mode = document[COMPAT_MODE]; if (mode || isIE) { // IE, Gecko, Opera width = (mode == CSS1_COMPAT) ? documentElement.clientWidth : // Standards document.body.clientWidth; // Quirks } YAHOO.log('getViewportWidth returning ' + width, 'info', 'Dom'); return width; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * For performance reasons, IDs are not accepted and argument validation omitted. * @method getAncestorBy * @param {HTMLElement} node The HTMLElement to use as the starting point * @param {Function} method - A boolean method for testing elements which receives the element as its only argument. * @return {Object} HTMLElement or null if not found */ getAncestorBy: function(node, method) { while ( (node = node[PARENT_NODE]) ) { // NOTE: assignment if ( Y.Dom._testElement(node, method) ) { YAHOO.log('getAncestorBy returning ' + node, 'info', 'Dom'); return node; } } YAHOO.log('getAncestorBy returning null (no ancestor passed test)', 'error', 'Dom'); return null; }, /** * Returns the nearest ancestor with the given className. * @method getAncestorByClassName * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point * @param {String} className * @return {Object} HTMLElement */ getAncestorByClassName: function(node, className) { node = Y.Dom.get(node); if (!node) { YAHOO.log('getAncestorByClassName failed: invalid node argument', 'error', 'Dom'); return null; } var method = function(el) { return Y.Dom.hasClass(el, className); }; return Y.Dom.getAncestorBy(node, method); }, /** * Returns the nearest ancestor with the given tagName. * @method getAncestorByTagName * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point * @param {String} tagName * @return {Object} HTMLElement */ getAncestorByTagName: function(node, tagName) { node = Y.Dom.get(node); if (!node) { YAHOO.log('getAncestorByTagName failed: invalid node argument', 'error', 'Dom'); return null; } var method = function(el) { return el[TAG_NAME] && el[TAG_NAME].toUpperCase() == tagName.toUpperCase(); }; return Y.Dom.getAncestorBy(node, method); }, /** * Returns the previous sibling that is an HTMLElement. * For performance reasons, IDs are not accepted and argument validation omitted. * Returns the nearest HTMLElement sibling if no method provided. * @method getPreviousSiblingBy * @param {HTMLElement} node The HTMLElement to use as the starting point * @param {Function} method A boolean function used to test siblings * that receives the sibling node being tested as its only argument * @return {Object} HTMLElement or null if not found */ getPreviousSiblingBy: function(node, method) { while (node) { node = node.previousSibling; if ( Y.Dom._testElement(node, method) ) { return node; } } return null; }, /** * Returns the previous sibling that is an HTMLElement * @method getPreviousSibling * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point * @return {Object} HTMLElement or null if not found */ getPreviousSibling: function(node) { node = Y.Dom.get(node); if (!node) { YAHOO.log('getPreviousSibling failed: invalid node argument', 'error', 'Dom'); return null; } return Y.Dom.getPreviousSiblingBy(node); }, /** * Returns the next HTMLElement sibling that passes the boolean method. * For performance reasons, IDs are not accepted and argument validation omitted. * Returns the nearest HTMLElement sibling if no method provided. * @method getNextSiblingBy * @param {HTMLElement} node The HTMLElement to use as the starting point * @param {Function} method A boolean function used to test siblings * that receives the sibling node being tested as its only argument * @return {Object} HTMLElement or null if not found */ getNextSiblingBy: function(node, method) { while (node) { node = node.nextSibling; if ( Y.Dom._testElement(node, method) ) { return node; } } return null; }, /** * Returns the next sibling that is an HTMLElement * @method getNextSibling * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point * @return {Object} HTMLElement or null if not found */ getNextSibling: function(node) { node = Y.Dom.get(node); if (!node) { YAHOO.log('getNextSibling failed: invalid node argument', 'error', 'Dom'); return null; } return Y.Dom.getNextSiblingBy(node); }, /** * Returns the first HTMLElement child that passes the test method. * @method getFirstChildBy * @param {HTMLElement} node The HTMLElement to use as the starting point * @param {Function} method A boolean function used to test children * that receives the node being tested as its only argument * @return {Object} HTMLElement or null if not found */ getFirstChildBy: function(node, method) { var child = ( Y.Dom._testElement(node.firstChild, method) ) ? node.firstChild : null; return child || Y.Dom.getNextSiblingBy(node.firstChild, method); }, /** * Returns the first HTMLElement child. * @method getFirstChild * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point * @return {Object} HTMLElement or null if not found */ getFirstChild: function(node, method) { node = Y.Dom.get(node); if (!node) { YAHOO.log('getFirstChild failed: invalid node argument', 'error', 'Dom'); return null; } return Y.Dom.getFirstChildBy(node); }, /** * Returns the last HTMLElement child that passes the test method. * @method getLastChildBy * @param {HTMLElement} node The HTMLElement to use as the starting point * @param {Function} method A boolean function used to test children * that receives the node being tested as its only argument * @return {Object} HTMLElement or null if not found */ getLastChildBy: function(node, method) { if (!node) { YAHOO.log('getLastChild failed: invalid node argument', 'error', 'Dom'); return null; } var child = ( Y.Dom._testElement(node.lastChild, method) ) ? node.lastChild : null; return child || Y.Dom.getPreviousSiblingBy(node.lastChild, method); }, /** * Returns the last HTMLElement child. * @method getLastChild * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point * @return {Object} HTMLElement or null if not found */ getLastChild: function(node) { node = Y.Dom.get(node); return Y.Dom.getLastChildBy(node); }, /** * Returns an array of HTMLElement childNodes that pass the test method. * @method getChildrenBy * @param {HTMLElement} node The HTMLElement to start from * @param {Function} method A boolean function used to test children * that receives the node being tested as its only argument * @return {Array} A static array of HTMLElements */ getChildrenBy: function(node, method) { var child = Y.Dom.getFirstChildBy(node, method), children = child ? [child] : []; Y.Dom.getNextSiblingBy(child, function(node) { if ( !method || method(node) ) { children[children.length] = node; } return false; // fail test to collect all children }); return children; }, /** * Returns an array of HTMLElement childNodes. * @method getChildren * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point * @return {Array} A static array of HTMLElements */ getChildren: function(node) { node = Y.Dom.get(node); if (!node) { YAHOO.log('getChildren failed: invalid node argument', 'error', 'Dom'); } return Y.Dom.getChildrenBy(node); }, /** * Returns the left scroll value of the document * @method getDocumentScrollLeft * @param {HTMLDocument} document (optional) The document to get the scroll value of * @return {Int} The amount that the document is scrolled to the left */ getDocumentScrollLeft: function(doc) { doc = doc || document; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft); }, /** * Returns the top scroll value of the document * @method getDocumentScrollTop * @param {HTMLDocument} document (optional) The document to get the scroll value of * @return {Int} The amount that the document is scrolled to the top */ getDocumentScrollTop: function(doc) { doc = doc || document; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop); }, /** * Inserts the new node as the previous sibling of the reference node * @method insertBefore * @param {String | HTMLElement} newNode The node to be inserted * @param {String | HTMLElement} referenceNode The node to insert the new node before * @return {HTMLElement} The node that was inserted (or null if insert fails) */ insertBefore: function(newNode, referenceNode) { newNode = Y.Dom.get(newNode); referenceNode = Y.Dom.get(referenceNode); if (!newNode || !referenceNode || !referenceNode[PARENT_NODE]) { YAHOO.log('insertAfter failed: missing or invalid arg(s)', 'error', 'Dom'); return null; } return referenceNode[PARENT_NODE].insertBefore(newNode, referenceNode); }, /** * Inserts the new node as the next sibling of the reference node * @method insertAfter * @param {String | HTMLElement} newNode The node to be inserted * @param {String | HTMLElement} referenceNode The node to insert the new node after * @return {HTMLElement} The node that was inserted (or null if insert fails) */ insertAfter: function(newNode, referenceNode) { newNode = Y.Dom.get(newNode); referenceNode = Y.Dom.get(referenceNode); if (!newNode || !referenceNode || !referenceNode[PARENT_NODE]) { YAHOO.log('insertAfter failed: missing or invalid arg(s)', 'error', 'Dom'); return null; } if (referenceNode.nextSibling) { return referenceNode[PARENT_NODE].insertBefore(newNode, referenceNode.nextSibling); } else { return referenceNode[PARENT_NODE].appendChild(newNode); } }, /** * Creates a Region based on the viewport relative to the document. * @method getClientRegion * @return {Region} A Region object representing the viewport which accounts for document scroll */ getClientRegion: function() { var t = Y.Dom.getDocumentScrollTop(), l = Y.Dom.getDocumentScrollLeft(), r = Y.Dom.getViewportWidth() + l, b = Y.Dom.getViewportHeight() + t; return new Y.Region(t, r, b, l); }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {String | HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val) { Y.Dom.batch(el, Y.Dom._setAttribute, { attr: attr, val: val }); }, _setAttribute: function(el, args) { var attr = Y.Dom._toCamel(args.attr), val = args.val; if (el && el.setAttribute) { // set as DOM property, except for BUTTON, which errors on property setter if (Y.Dom.DOT_ATTRIBUTES[attr] && el.tagName && el.tagName != 'BUTTON') { el[attr] = val; } else { attr = Y.Dom.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val); } } else { YAHOO.log('setAttribute method not available for ' + el, 'error', 'Dom'); } }, /** * Provides a normalized attribute interface. * @method getAttribute * @param {String | HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr) { return Y.Dom.batch(el, Y.Dom._getAttribute, attr); }, _getAttribute: function(el, attr) { var val; attr = Y.Dom.CUSTOM_ATTRIBUTES[attr] || attr; if (Y.Dom.DOT_ATTRIBUTES[attr]) { val = el[attr]; } else if (el && 'getAttribute' in el) { if (/^(?:href|src)$/.test(attr)) { // use IE flag to return exact value val = el.getAttribute(attr, 2); } else { val = el.getAttribute(attr); } } else { YAHOO.log('getAttribute method not available for ' + el, 'error', 'Dom'); } return val; }, _toCamel: function(property) { var c = propertyCache; function tU(x,l) { return l.toUpperCase(); } return c[property] || (c[property] = property.indexOf('-') === -1 ? property : property.replace( /-([a-z])/gi, tU )); }, _getClassRegex: function(className) { var re; if (className !== undefined) { // allow empty string to pass if (className.exec) { // already a RegExp re = className; } else { re = reCache[className]; if (!re) { // escape special chars (".", "[", etc.) className = className.replace(Y.Dom._patterns.CLASS_RE_TOKENS, '\\$1'); className = className.replace(/\s+/g, SPACE); // convert line breaks and other delims re = reCache[className] = new RegExp(C_START + className + C_END, G); } } } return re; }, _patterns: { ROOT_TAG: /^body|html$/i, // body for quirks mode, html for standards, CLASS_RE_TOKENS: /([\.\(\)\^\$\*\+\?\|\[\]\{\}\\])/g }, _testElement: function(node, method) { return node && node[NODE_TYPE] == 1 && ( !method || method(node) ); }, _calcBorders: function(node, xy2) { var t = parseInt(Y.Dom[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y.Dom[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (isGecko) { if (RE_TABLE.test(node[TAG_NAME])) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; } }; var _getComputedStyle = Y.Dom[GET_COMPUTED_STYLE]; // fix opera computedStyle default color unit (convert to rgb) if (UA.opera) { Y.Dom[GET_COMPUTED_STYLE] = function(node, att) { var val = _getComputedStyle(node, att); if (RE_COLOR.test(att)) { val = Y.Dom.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (UA.webkit) { Y.Dom[GET_COMPUTED_STYLE] = function(node, att) { var val = _getComputedStyle(node, att); if (val === 'rgba(0, 0, 0, 0)') { val = 'transparent'; } return val; }; } if (UA.ie && UA.ie >= 8) { Y.Dom.DOT_ATTRIBUTES.type = true; // IE 8 errors on input.setAttribute('type') } })(); /** * A region is a representation of an object on a grid. It is defined * by the top, right, bottom, left extents, so is rectangular by default. If * other shapes are required, this class could be extended to support it. * @namespace YAHOO.util * @class Region * @param {Int} t the top extent * @param {Int} r the right extent * @param {Int} b the bottom extent * @param {Int} l the left extent * @constructor */ YAHOO.util.Region = function(t, r, b, l) { /** * The region's top extent * @property top * @type Int */ this.top = t; /** * The region's top extent * @property y * @type Int */ this.y = t; /** * The region's top extent as index, for symmetry with set/getXY * @property 1 * @type Int */ this[1] = t; /** * The region's right extent * @property right * @type int */ this.right = r; /** * The region's bottom extent * @property bottom * @type Int */ this.bottom = b; /** * The region's left extent * @property left * @type Int */ this.left = l; /** * The region's left extent * @property x * @type Int */ this.x = l; /** * The region's left extent as index, for symmetry with set/getXY * @property 0 * @type Int */ this[0] = l; /** * The region's total width * @property width * @type Int */ this.width = this.right - this.left; /** * The region's total height * @property height * @type Int */ this.height = this.bottom - this.top; }; /** * Returns true if this region contains the region passed in * @method contains * @param {Region} region The region to evaluate * @return {Boolean} True if the region is contained with this region, * else false */ YAHOO.util.Region.prototype.contains = function(region) { return ( region.left >= this.left && region.right <= this.right && region.top >= this.top && region.bottom <= this.bottom ); // this.logger.debug("does " + this + " contain " + region + " ... " + ret); }; /** * Returns the area of the region * @method getArea * @return {Int} the region's area */ YAHOO.util.Region.prototype.getArea = function() { return ( (this.bottom - this.top) * (this.right - this.left) ); }; /** * Returns the region where the passed in region overlaps with this one * @method intersect * @param {Region} region The region that intersects * @return {Region} The overlap region, or null if there is no overlap */ YAHOO.util.Region.prototype.intersect = function(region) { var t = Math.max( this.top, region.top ), r = Math.min( this.right, region.right ), b = Math.min( this.bottom, region.bottom ), l = Math.max( this.left, region.left ); if (b >= t && r >= l) { return new YAHOO.util.Region(t, r, b, l); } else { return null; } }; /** * Returns the region representing the smallest region that can contain both * the passed in region and this region. * @method union * @param {Region} region The region that to create the union with * @return {Region} The union region */ YAHOO.util.Region.prototype.union = function(region) { var t = Math.min( this.top, region.top ), r = Math.max( this.right, region.right ), b = Math.max( this.bottom, region.bottom ), l = Math.min( this.left, region.left ); return new YAHOO.util.Region(t, r, b, l); }; /** * toString * @method toString * @return string the region properties */ YAHOO.util.Region.prototype.toString = function() { return ( "Region {" + "top: " + this.top + ", right: " + this.right + ", bottom: " + this.bottom + ", left: " + this.left + ", height: " + this.height + ", width: " + this.width + "}" ); }; /** * Returns a region that is occupied by the DOM element * @method getRegion * @param {HTMLElement} el The element * @return {Region} The region that the element occupies * @static */ YAHOO.util.Region.getRegion = function(el) { var p = YAHOO.util.Dom.getXY(el), t = p[1], r = p[0] + el.offsetWidth, b = p[1] + el.offsetHeight, l = p[0]; return new YAHOO.util.Region(t, r, b, l); }; ///////////////////////////////////////////////////////////////////////////// /** * A point is a region that is special in that it represents a single point on * the grid. * @namespace YAHOO.util * @class Point * @param {Int} x The X position of the point * @param {Int} y The Y position of the point * @constructor * @extends YAHOO.util.Region */ YAHOO.util.Point = function(x, y) { if (YAHOO.lang.isArray(x)) { // accept input from Dom.getXY, Event.getXY, etc. y = x[1]; // dont blow away x yet x = x[0]; } YAHOO.util.Point.superclass.constructor.call(this, y, x, y, x); }; YAHOO.extend(YAHOO.util.Point, YAHOO.util.Region); (function() { /** * Internal methods used to add style management functionality to DOM. * @module dom * @class IEStyle * @namespace YAHOO.util.Dom */ var Y = YAHOO.util, CLIENT_TOP = 'clientTop', CLIENT_LEFT = 'clientLeft', PARENT_NODE = 'parentNode', RIGHT = 'right', HAS_LAYOUT = 'hasLayout', PX = 'px', OPACITY = 'opacity', AUTO = 'auto', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', VISIBLE = 'visible', TRANSPARENT = 'transparent', HEIGHT = 'height', WIDTH = 'width', STYLE = 'style', CURRENT_STYLE = 'currentStyle', // IE getComputedStyle // TODO: unit-less lineHeight (e.g. 1.22) re_size = /^width|height$/, re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, ComputedStyle = { /** * @method get * @description Method used by DOM to get style information for IE * @param {HTMLElement} el The element to check * @param {String} property The property to check * @returns {String} The computed style */ get: function(el, property) { var value = '', current = el[CURRENT_STYLE][property]; if (property === OPACITY) { value = Y.Dom.getStyle(el, OPACITY); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.Dom.IE_COMPUTED[property]) { // use compute function value = Y.Dom.IE_COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = Y.Dom.IE.ComputedStyle.getPixel(el, property); } else { value = current; } return value; }, /** * @method getOffset * @description Determine the offset of an element * @param {HTMLElement} el The element to check * @param {String} prop The property to check. * @return {String} The offset */ getOffset: function(el, prop) { var current = el[CURRENT_STYLE][prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. value = '', actual; if (current == AUTO) { actual = el[offset]; // offsetHeight/Top etc. if (actual === undefined) { // likely "right" or "bottom" value = 0; } value = actual; if (re_size.test(prop)) { // account for box model diff el[STYLE][prop] = actual; if (el[offset] > actual) { // the difference is padding + border (works in Standards & Quirks modes) value = actual - (el[offset] - actual); } el[STYLE][prop] = AUTO; // revert to auto } } else { // convert units to px if (!el[STYLE][pixel] && !el[STYLE][prop]) { // need to map style.width to currentStyle (no currentStyle.pixelWidth) el[STYLE][prop] = current; // no style.pixelWidth if no style.width } value = el[STYLE][pixel]; } return value + PX; }, /** * @method getBorderWidth * @description Try to determine the width of an elements border * @param {HTMLElement} el The element to check * @param {String} property The property to check * @return {String} The elements border width */ getBorderWidth: function(el, property) { // clientHeight/Width = paddingBox (e.g. offsetWidth - borderWidth) // clientTop/Left = borderWidth var value = null; if (!el[CURRENT_STYLE][HAS_LAYOUT]) { // TODO: unset layout? el[STYLE].zoom = 1; // need layout to measure client } switch(property) { case BORDER_TOP_WIDTH: value = el[CLIENT_TOP]; break; case BORDER_BOTTOM_WIDTH: value = el.offsetHeight - el.clientHeight - el[CLIENT_TOP]; break; case BORDER_LEFT_WIDTH: value = el[CLIENT_LEFT]; break; case BORDER_RIGHT_WIDTH: value = el.offsetWidth - el.clientWidth - el[CLIENT_LEFT]; break; } return value + PX; }, /** * @method getPixel * @description Get the pixel value from a style property * @param {HTMLElement} node The element to check * @param {String} att The attribute to check * @return {String} The pixel value */ getPixel: function(node, att) { // use pixelRight to convert to px var val = null, styleRight = node[CURRENT_STYLE][RIGHT], current = node[CURRENT_STYLE][att]; node[STYLE][RIGHT] = current; val = node[STYLE].pixelRight; node[STYLE][RIGHT] = styleRight; // revert return val + PX; }, /** * @method getMargin * @description Get the margin value from a style property * @param {HTMLElement} node The element to check * @param {String} att The attribute to check * @return {String} The margin value */ getMargin: function(node, att) { var val; if (node[CURRENT_STYLE][att] == AUTO) { val = 0 + PX; } else { val = Y.Dom.IE.ComputedStyle.getPixel(node, att); } return val; }, /** * @method getVisibility * @description Get the visibility of an element * @param {HTMLElement} node The element to check * @param {String} att The attribute to check * @return {String} The value */ getVisibility: function(node, att) { var current; while ( (current = node[CURRENT_STYLE]) && current[att] == 'inherit') { // NOTE: assignment in test node = node[PARENT_NODE]; } return (current) ? current[att] : VISIBLE; }, /** * @method getColor * @description Get the color of an element * @param {HTMLElement} node The element to check * @param {String} att The attribute to check * @return {String} The value */ getColor: function(node, att) { return Y.Dom.Color.toRGB(node[CURRENT_STYLE][att]) || TRANSPARENT; }, /** * @method getBorderColor * @description Get the bordercolor of an element * @param {HTMLElement} node The element to check * @param {String} att The attribute to check * @return {String} The value */ getBorderColor: function(node, att) { var current = node[CURRENT_STYLE], val = current[att] || current.color; return Y.Dom.Color.toRGB(Y.Dom.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; IEComputed.top = IEComputed.right = IEComputed.bottom = IEComputed.left = IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = ComputedStyle.getColor; IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.Dom.IE_COMPUTED = IEComputed; Y.Dom.IE_ComputedStyle = ComputedStyle; })(); (function() { /** * Add style management functionality to DOM. * @module dom * @class Color * @namespace YAHOO.util.Dom */ var TO_STRING = 'toString', PARSE_INT = parseInt, RE = RegExp, Y = YAHOO.util; Y.Dom.Color = { /** * @property KEYWORDS * @type Object * @description Color keywords used when converting to Hex */ KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, /** * @property re_RGB * @private * @type Regex * @description Regex to parse rgb(0,0,0) formatted strings */ re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, /** * @property re_hex * @private * @type Regex * @description Regex to parse #123456 formatted strings */ re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, /** * @property re_hex3 * @private * @type Regex * @description Regex to parse #123 formatted strings */ re_hex3: /([0-9A-F])/gi, /** * @method toRGB * @description Converts a hex or color string to an rgb string: rgb(0,0,0) * @param {String} val The string to convert to RGB notation. * @returns {String} The converted string */ toRGB: function(val) { if (!Y.Dom.Color.re_RGB.test(val)) { val = Y.Dom.Color.toHex(val); } if(Y.Dom.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, /** * @method toHex * @description Converts an rgb or color string to a hex string: #123456 * @param {String} val The string to convert to hex notation. * @returns {String} The converted string */ toHex: function(val) { val = Y.Dom.Color.KEYWORDS[val] || val; if (Y.Dom.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Dom.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; }()); YAHOO.register("dom", YAHOO.util.Dom, {version: "2.9.0", build: "2800"}); /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ /** * The Connection Manager provides a simplified interface to the XMLHttpRequest * object. It handles cross-browser instantiantion of XMLHttpRequest, negotiates the * interactive states and server response, returning the results to a pre-defined * callback you create. * * @namespace YAHOO.util * @module connection * @requires yahoo * @requires event */ /** * The Connection Manager singleton provides methods for creating and managing * asynchronous transactions. * * @class YAHOO.util.Connect */ YAHOO.util.Connect = { /** * @description Array of MSFT ActiveX ids for XMLHttpRequest. * @property _msxml_progid * @private * @static * @type array */ _msxml_progid:[ 'Microsoft.XMLHTTP', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP' ], /** * @description Object literal of HTTP header(s) * @property _http_header * @private * @static * @type object */ _http_headers:{}, /** * @description Determines if HTTP headers are set. * @property _has_http_headers * @private * @static * @type boolean */ _has_http_headers:false, /** * @description Determines if a default header of * Content-Type of 'application/x-www-form-urlencoded' * will be added to any client HTTP headers sent for POST * transactions. * @property _use_default_post_header * @private * @static * @type boolean */ _use_default_post_header:true, /** * @description The default header used for POST transactions. * @property _default_post_header * @private * @static * @type boolean */ _default_post_header:'application/x-www-form-urlencoded; charset=UTF-8', /** * @description The default header used for transactions involving the * use of HTML forms. * @property _default_form_header * @private * @static * @type boolean */ _default_form_header:'application/x-www-form-urlencoded', /** * @description Determines if a default header of * 'X-Requested-With: XMLHttpRequest' * will be added to each transaction. * @property _use_default_xhr_header * @private * @static * @type boolean */ _use_default_xhr_header:true, /** * @description The default header value for the label * "X-Requested-With". This is sent with each * transaction, by default, to identify the * request as being made by YUI Connection Manager. * @property _default_xhr_header * @private * @static * @type boolean */ _default_xhr_header:'XMLHttpRequest', /** * @description Determines if custom, default headers * are set for each transaction. * @property _has_default_header * @private * @static * @type boolean */ _has_default_headers:true, /** * @description Property modified by setForm() to determine if the data * should be submitted as an HTML form. * @property _isFormSubmit * @private * @static * @type boolean */ _isFormSubmit:false, /** * @description Determines if custom, default headers * are set for each transaction. * @property _has_default_header * @private * @static * @type boolean */ _default_headers:{}, /** * @description Collection of polling references to the polling mechanism in handleReadyState. * @property _poll * @private * @static * @type object */ _poll:{}, /** * @description Queue of timeout values for each transaction callback with a defined timeout value. * @property _timeOut * @private * @static * @type object */ _timeOut:{}, /** * @description The polling frequency, in milliseconds, for HandleReadyState. * when attempting to determine a transaction's XHR readyState. * The default is 50 milliseconds. * @property _polling_interval * @private * @static * @type int */ _polling_interval:50, /** * @description A transaction counter that increments the transaction id for each transaction. * @property _transaction_id * @private * @static * @type int */ _transaction_id:0, /** * @description Custom event that fires at the start of a transaction * @property startEvent * @private * @static * @type CustomEvent */ startEvent: new YAHOO.util.CustomEvent('start'), /** * @description Custom event that fires when a transaction response has completed. * @property completeEvent * @private * @static * @type CustomEvent */ completeEvent: new YAHOO.util.CustomEvent('complete'), /** * @description Custom event that fires when handleTransactionResponse() determines a * response in the HTTP 2xx range. * @property successEvent * @private * @static * @type CustomEvent */ successEvent: new YAHOO.util.CustomEvent('success'), /** * @description Custom event that fires when handleTransactionResponse() determines a * response in the HTTP 4xx/5xx range. * @property failureEvent * @private * @static * @type CustomEvent */ failureEvent: new YAHOO.util.CustomEvent('failure'), /** * @description Custom event that fires when a transaction is successfully aborted. * @property abortEvent * @private * @static * @type CustomEvent */ abortEvent: new YAHOO.util.CustomEvent('abort'), /** * @description A reference table that maps callback custom events members to its specific * event name. * @property _customEvents * @private * @static * @type object */ _customEvents: { onStart:['startEvent', 'start'], onComplete:['completeEvent', 'complete'], onSuccess:['successEvent', 'success'], onFailure:['failureEvent', 'failure'], onUpload:['uploadEvent', 'upload'], onAbort:['abortEvent', 'abort'] }, /** * @description Member to add an ActiveX id to the existing xml_progid array. * In the event(unlikely) a new ActiveX id is introduced, it can be added * without internal code modifications. * @method setProgId * @public * @static * @param {string} id The ActiveX id to be added to initialize the XHR object. * @return void */ setProgId:function(id) { this._msxml_progid.unshift(id); YAHOO.log('ActiveX Program Id ' + id + ' added to _msxml_progid.', 'info', 'Connection'); }, /** * @description Member to override the default POST header. * @method setDefaultPostHeader * @public * @static * @param {boolean} b Set and use default header - true or false . * @return void */ setDefaultPostHeader:function(b) { if(typeof b == 'string'){ this._default_post_header = b; this._use_default_post_header = true; YAHOO.log('Default POST header set to ' + b, 'info', 'Connection'); } else if(typeof b == 'boolean'){ this._use_default_post_header = b; } }, /** * @description Member to override the default transaction header.. * @method setDefaultXhrHeader * @public * @static * @param {boolean} b Set and use default header - true or false . * @return void */ setDefaultXhrHeader:function(b) { if(typeof b == 'string'){ this._default_xhr_header = b; YAHOO.log('Default XHR header set to ' + b, 'info', 'Connection'); } else{ this._use_default_xhr_header = b; } }, /** * @description Member to modify the default polling interval. * @method setPollingInterval * @public * @static * @param {int} i The polling interval in milliseconds. * @return void */ setPollingInterval:function(i) { if(typeof i == 'number' && isFinite(i)){ this._polling_interval = i; YAHOO.log('Default polling interval set to ' + i +'ms', 'info', 'Connection'); } }, /** * @description Instantiates a XMLHttpRequest object and returns an object with two properties: * the XMLHttpRequest instance and the transaction id. * @method createXhrObject * @private * @static * @param {int} transactionId Property containing the transaction id for this transaction. * @return object */ createXhrObject:function(transactionId) { var obj,http,i; try { // Instantiates XMLHttpRequest in non-IE browsers and assigns to http. http = new XMLHttpRequest(); // Object literal with http and tId properties obj = { conn:http, tId:transactionId, xhr: true }; YAHOO.log('XHR object created for transaction ' + transactionId, 'info', 'Connection'); } catch(e) { for(i=0; i= 200 && httpStatus < 300) || httpStatus === 1223 || xdrS){ responseObject = o.xdr ? o.r : this.createResponseObject(o, args); if(callback && callback.success){ if(!callback.scope){ callback.success(responseObject); YAHOO.log('Success callback. HTTP code is ' + httpStatus, 'info', 'Connection'); } else{ // If a scope property is defined, the callback will be fired from // the context of the object. callback.success.apply(callback.scope, [responseObject]); YAHOO.log('Success callback with scope. HTTP code is ' + httpStatus, 'info', 'Connection'); } } // Fire global custom event -- successEvent this.successEvent.fire(responseObject); if(o.successEvent){ // Fire transaction custom event -- successEvent o.successEvent.fire(responseObject); } } else{ 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. // XDR transactions will not resolve to this case, since the // response object is already built in the xdr response. responseObject = this.createExceptionObject(o.tId, args, (isAbort?isAbort:false)); if(callback && callback.failure){ if(!callback.scope){ callback.failure(responseObject); YAHOO.log('Failure callback. Exception detected. Status code is ' + httpStatus, 'warn', 'Connection'); } else{ callback.failure.apply(callback.scope, [responseObject]); YAHOO.log('Failure callback with scope. Exception detected. Status code is ' + httpStatus, 'warn', 'Connection'); } } break; default: responseObject = (o.xdr) ? o.response : this.createResponseObject(o, args); if(callback && callback.failure){ if(!callback.scope){ callback.failure(responseObject); YAHOO.log('Failure callback. HTTP status code is ' + httpStatus, 'warn', 'Connection'); } else{ callback.failure.apply(callback.scope, [responseObject]); YAHOO.log('Failure callback with scope. HTTP status code is ' + httpStatus, 'warn', 'Connection'); } } } // Fire global custom event -- failureEvent this.failureEvent.fire(responseObject); if(o.failureEvent){ // Fire transaction custom event -- failureEvent o.failureEvent.fire(responseObject); } } 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 = {}, headerObj = {}, i, headerStr, header, delimitPos; try { headerStr = o.conn.getAllResponseHeaders(); header = headerStr.split('\n'); for(i=0; i' + '' + '' + '
    ', c = document.createElement('div'); document.body.appendChild(c); c.innerHTML = o; } /** * @description This method calls the public method on the * Flash transport to start the XDR transaction. It is analogous * to Connection Manager's asyncRequest method. * @method xdr * @private * @static * @param {object} The transaction object. * @param {string} HTTP request method. * @param {string} URI for the transaction. * @param {object} The transaction's callback object. * @param {object} The JSON object used as HTTP POST data. * @return {void} */ function _xdr(o, m, u, c, d) { _fn[parseInt(o.tId)] = { 'o':o, 'c':c }; if (d) { c.method = m; c.data = d; } o.conn.send(u, c, o.tId); } /** * @description This method instantiates the Flash transport and * establishes a static reference to it, used for all XDR requests. * @method transport * @public * @static * @param {string} URI to connection.swf. * @return {void} */ function _init(uri) { _swf(uri); YCM._transport = document.getElementById('YUIConnectionSwf'); } function _xdrReady() { YCM.xdrReadyEvent.fire(); } /** * @description This method fires the global and transaction start * events. * @method _xdrStart * @private * @static * @param {object} The transaction object. * @param {string} The transaction's callback object. * @return {void} */ function _xdrStart(o, cb) { if (o) { // Fire global custom event -- startEvent YCM.startEvent.fire(o, cb.argument); if(o.startEvent){ // Fire transaction custom event -- startEvent o.startEvent.fire(o, cb.argument); } } } /** * @description This method is the initial response handler * for XDR transactions. The Flash transport calls this * function and sends the response payload. * @method handleXdrResponse * @private * @static * @param {object} The response object sent from the Flash transport. * @return {void} */ function _handleXdrResponse(r) { var o = _fn[r.tId].o, cb = _fn[r.tId].c; if (r.statusText === 'xdr:start') { _xdrStart(o, cb); return; } r.responseText = decodeURI(r.responseText); o.r = r; if (cb.argument) { o.r.argument = cb.argument; } this.handleTransactionResponse(o, cb, r.statusText === 'xdr:abort' ? true : false); delete _fn[r.tId]; } // Bind the functions to Connection Manager as static fields. YCM.xdr = _xdr; YCM.swf = _swf; YCM.transport = _init; YCM.xdrReadyEvent = new YAHOO.util.CustomEvent('xdrReady'); YCM.xdrReady = _xdrReady; YCM.handleXdrResponse = _handleXdrResponse; })(); /** * @for YAHOO.util.Connect */ (function(){ var YCM = YAHOO.util.Connect, YE = YAHOO.util.Event, dM = document.documentMode ? document.documentMode : false; /** * @description Property modified by setForm() to determine if a file(s) * upload is expected. * @property _isFileUpload * @private * @static * @type boolean */ YCM._isFileUpload = false; /** * @description Property modified by setForm() to set a reference to the HTML * form node if the desired action is file upload. * @property _formNode * @private * @static * @type object */ YCM._formNode = null; /** * @description Property modified by setForm() to set the HTML form data * for each transaction. * @property _sFormData * @private * @static * @type string */ YCM._sFormData = null; /** * @description Tracks the name-value pair of the "clicked" submit button if multiple submit * buttons are present in an HTML form; and, if YAHOO.util.Event is available. * @property _submitElementValue * @private * @static * @type string */ YCM._submitElementValue = null; /** * @description Custom event that fires when handleTransactionResponse() determines a * response in the HTTP 4xx/5xx range. * @property failureEvent * @private * @static * @type CustomEvent */ YCM.uploadEvent = new YAHOO.util.CustomEvent('upload'); /** * @description Determines whether YAHOO.util.Event is available and returns true or false. * If true, an event listener is bound at the document level to trap click events that * resolve to a target type of "Submit". This listener will enable setForm() to determine * the clicked "Submit" value in a multi-Submit button, HTML form. * @property _hasSubmitListener * @private * @static */ YCM._hasSubmitListener = function() { if(YE){ YE.addListener( document, 'click', function(e){ var obj = YE.getTarget(e), name = obj.nodeName.toLowerCase(); if((name === 'input' || name === 'button') && (obj.type && obj.type.toLowerCase() == 'submit')){ YCM._submitElementValue = encodeURIComponent(obj.name) + "=" + encodeURIComponent(obj.value); } }); return true; } return false; }(); /** * @description This method assembles the form label and value pairs and * constructs an encoded string. * asyncRequest() will automatically initialize the transaction with a * a HTTP header Content-Type of application/x-www-form-urlencoded. * @method setForm * @public * @static * @param {string || object} form id or name attribute, or form object. * @param {boolean} optional enable file upload. * @param {boolean} optional enable file upload over SSL in IE only. * @return {string} string of the HTML form field name and value pairs.. */ function _setForm(formId, isUpload, secureUri) { var oForm, oElement, oName, oValue, oDisabled, hasSubmit = false, data = [], item = 0, i,len,j,jlen,opt; this.resetFormState(); if(typeof formId == 'string'){ // Determine if the argument is a form id or a form name. // Note form name usage is deprecated by supported // here for legacy reasons. oForm = (document.getElementById(formId) || document.forms[formId]); } else if(typeof formId == 'object'){ // Treat argument as an HTML form object. oForm = formId; } else{ YAHOO.log('Unable to create form object ' + formId, 'warn', 'Connection'); return; } // If the isUpload argument is true, setForm will call createFrame to initialize // an iframe as the form target. // // The argument secureURI is also required by IE in SSL environments // where the secureURI string is a fully qualified HTTP path, used to set the source // of the iframe, to a stub resource in the same domain. if(isUpload){ // Create iframe in preparation for file upload. this.createFrame(secureUri?secureUri:null); // Set form reference and file upload properties to true. this._isFormSubmit = true; this._isFileUpload = true; this._formNode = oForm; return; } // Iterate over the form elements collection to construct the // label-value pairs. for (i=0,len=oForm.elements.length; i -1) { opt = oElement.options[oElement.selectedIndex]; data[item++] = oName + encodeURIComponent( (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text); } break; case 'select-multiple': if (oElement.selectedIndex > -1) { for(j=oElement.selectedIndex, jlen=oElement.options.length; j'); // 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{ 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); YAHOO.log('File upload iframe created. Id is:' + frameId, 'info', 'Connection'); } /** * @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. */ function _appendPostData(postData){ var formElements = [], postMessage = postData.split('&'), i, delimitPos; for(i=0; i < postMessage.length; i++){ delimitPos = postMessage[i].indexOf('='); if(delimitPos != -1){ formElements[i] = document.createElement('input'); formElements[i].type = 'hidden'; formElements[i].name = decodeURIComponent(postMessage[i].substring(0,delimitPos)); formElements[i].value = decodeURIComponent(postMessage[i].substring(delimitPos+1)); this._formNode.appendChild(formElements[i]); } } return formElements; } /** * @description Uploads HTML form, inclusive of files/attachments, using the * iframe created in createFrame to facilitate the transaction. * @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. * @param {string} postData POST data to be submitted in addition to HTML form. * @return {void} */ function _uploadFile(o, callback, uri, postData){ // Each iframe has an id prefix of "yuiIO" followed // by the unique transaction id. var frameId = 'yuiIO' + o.tId, uploadEncoding = 'multipart/form-data', io = document.getElementById(frameId), ie8 = (dM >= 8) ? true : false, oConn = this, args = (callback && callback.argument)?callback.argument:null, oElements,i,prop,obj, rawFormAttributes, uploadCallback; // Track original HTML form attribute values. rawFormAttributes = { action:this._formNode.getAttribute('action'), method:this._formNode.getAttribute('method'), target:this._formNode.getAttribute('target') }; // Initialize the HTML form properties in case they are // not defined in the HTML form. this._formNode.setAttribute('action', uri); this._formNode.setAttribute('method', 'POST'); this._formNode.setAttribute('target', frameId); if(YAHOO.env.ua.ie && !ie8){ // IE does not respect property enctype for HTML forms. // Instead it uses the property - "encoding". this._formNode.setAttribute('encoding', uploadEncoding); } else{ this._formNode.setAttribute('enctype', uploadEncoding); } if(postData){ oElements = this.appendPostData(postData); } // Start file upload. this._formNode.submit(); // Fire global custom event -- startEvent this.startEvent.fire(o, args); if(o.startEvent){ // Fire transaction custom event -- startEvent o.startEvent.fire(o, args); } // Start polling if a callback is present and the timeout // property has been defined. if(callback && callback.timeout){ this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout); } // Remove HTML elements created by appendPostData if(oElements && oElements.length > 0){ for(i=0; i < oElements.length; i++){ this._formNode.removeChild(oElements[i]); } } // Restore HTML form attributes to their original // values prior to file upload. for(prop in rawFormAttributes){ if(YAHOO.lang.hasOwnProperty(rawFormAttributes, prop)){ if(rawFormAttributes[prop]){ this._formNode.setAttribute(prop, rawFormAttributes[prop]); } else{ this._formNode.removeAttribute(prop); } } } // Reset HTML form state 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. uploadCallback = function() { var body, pre, text; if(callback && callback.timeout){ window.clearTimeout(oConn._timeOut[o.tId]); delete oConn._timeOut[o.tId]; } // Fire global custom event -- completeEvent oConn.completeEvent.fire(o, args); if(o.completeEvent){ // Fire transaction custom event -- completeEvent o.completeEvent.fire(o, args); } obj = { tId : o.tId, argument : args }; try { body = io.contentWindow.document.getElementsByTagName('body')[0]; pre = io.contentWindow.document.getElementsByTagName('pre')[0]; if (body) { if (pre) { text = pre.textContent?pre.textContent:pre.innerText; } else { text = body.textContent?body.textContent:body.innerText; } } obj.responseText = text; // responseText and responseXML will be populated with the same data from the iframe. // Since the HTTP headers cannot be read from the iframe obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; } catch(e){} if(callback && callback.upload){ if(!callback.scope){ callback.upload(obj); YAHOO.log('Upload callback.', 'info', 'Connection'); } else{ callback.upload.apply(callback.scope, [obj]); YAHOO.log('Upload callback with scope.', 'info', 'Connection'); } } // Fire global custom event -- uploadEvent oConn.uploadEvent.fire(obj); if(o.uploadEvent){ // Fire transaction custom event -- uploadEvent o.uploadEvent.fire(obj); } YE.removeListener(io, "load", uploadCallback); setTimeout( function(){ document.body.removeChild(io); oConn.releaseObject(o); YAHOO.log('File upload iframe destroyed. Id is:' + frameId, 'info', 'Connection'); }, 100); }; // Bind the onload handler to the iframe to detect the file upload response. YE.addListener(io, "load", uploadCallback); } YCM.setForm = _setForm; YCM.resetFormState = _resetFormState; YCM.createFrame = _createFrame; YCM.appendPostData = _appendPostData; YCM.uploadFile = _uploadFile; })(); YAHOO.register("connection", YAHOO.util.Connect, {version: "2.9.0", build: "2800"}); /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ (function() { var Y = YAHOO.util; /* Copyright (c) 2006, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ /** * The animation module provides allows effects to be added to HTMLElements. * @module animation * @requires yahoo, event, dom */ /** * * Base animation class that provides the interface for building animated effects. *

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

    * @class Anim * @namespace YAHOO.util * @requires YAHOO.util.AnimMgr * @requires YAHOO.util.Easing * @requires YAHOO.util.Dom * @requires YAHOO.util.Event * @requires YAHOO.util.CustomEvent * @constructor * @param {String | HTMLElement} el Reference to the element that will be animated * @param {Object} attributes The attribute(s) to be animated. * Each attribute is an object with at minimum a "to" or "by" member defined. * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). * All attribute names use camelCase. * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) */ var Anim = function(el, attributes, duration, method) { if (!el) { YAHOO.log('element required to create Anim instance', 'error', 'Anim'); } this.init(el, attributes, duration, method); }; Anim.NAME = 'Anim'; 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 (this.constructor.NAME + ': ' + 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) { var el = this.getEl(); if ( this.patterns.noNegatives.test(attr) ) { val = (val > 0) ? val : 0; } if (attr in el && !('style' in el && attr in el.style)) { el[attr] = val; } else { Y.Dom.setStyle(el, 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 = Y.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 if ('style' in el) { // use offsets for width/height and abs pos top/left if ( box || (Y.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; } } else if (attr in el) { val = el[attr]; } return val; }, /** * Returns the unit to use when none is supplied. * @method getDefaultUnit * @param {attr} attr The name of the attribute. * @return {String} The default unit to be used. */ getDefaultUnit: function(attr) { if ( this.patterns.defaultUnit.test(attr) ) { return 'px'; } return ''; }, /** * Sets the actual values to be used during the animation. Should only be needed for subclass use. * @method setRuntimeAttribute * @param {Object} attr The attribute object * @private */ setRuntimeAttribute: function(attr) { var start; var end; var attributes = this.attributes; this.runtimeAttributes[attr] = {}; var isset = function(prop) { return (typeof prop !== 'undefined'); }; if ( !isset(attributes[attr]['to']) && !isset(attributes[attr]['by']) ) { return false; // note return; nothing to animate to } start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr); // To beats by, per SMIL 2.1 spec if ( isset(attributes[attr]['to']) ) { end = attributes[attr]['to']; } else if ( isset(attributes[attr]['by']) ) { if (start.constructor == Array) { end = []; for (var i = 0, len = start.length; i < len; ++i) { end[i] = start[i] + attributes[attr]['by'][i] * 1; // times 1 to cast "by" } } else { end = start + attributes[attr]['by'] * 1; } } 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); return true; }, /** * 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 = Y.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 = !YAHOO.lang.isUndefined(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 || Y.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 = Y.AnimMgr.fps; /** * Changes the animated element * @method setEl */ this.setEl = function(element) { el = Y.Dom.get(element); }; /** * Returns a reference to the animated element. * @method getEl * @return {HTMLElement} */ this.getEl = function() { return el; }; /** * Checks whether the element is currently animated. * @method isAnimated * @return {Boolean} current value of isAnimated. */ this.isAnimated = function() { return isAnimated; }; /** * Returns the animation start time. * @method getStartTime * @return {Date} current value of startTime. */ this.getStartTime = function() { return startTime; }; this.runtimeAttributes = {}; var logger = {}; logger.log = function() {YAHOO.log.apply(window, arguments)}; logger.log('creating new instance of ' + this); /** * Starts the animation by registering it with the animation manager. * @method animate */ this.animate = function() { if ( this.isAnimated() ) { return false; } this.currentFrame = 0; this.totalFrames = ( this.useSeconds ) ? Math.ceil(Y.AnimMgr.fps * this.duration) : this.duration; if (this.duration === 0 && this.useSeconds) { // jump to last frame if zero second duration this.totalFrames = 1; } Y.AnimMgr.registerElement(this); return true; }; /** * 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 (!this.isAnimated()) { // nothing to stop return false; } if (finish) { this.currentFrame = this.totalFrames; this._onTween.fire(); } Y.AnimMgr.stop(this); }; this._handleStart = function() { this.onStart.fire(); this.runtimeAttributes = {}; for (var attr in this.attributes) { if (this.attributes.hasOwnProperty(attr)) { 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 */ this._handleTween = 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) { if (runtimeAttributes.hasOwnProperty(attr)) { this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); } } this.afterTween.fire(data); actualFrames += 1; }; this._handleComplete = 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 Y.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 Y.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 Y.CustomEvent('tween', this); /** * Custom event that fires between each frame * Listen via subscribe method (e.g. myAnim.afterTween.subscribe(someFunction) * @event afterTween */ this.afterTween = new Y.CustomEvent('afterTween', this); /** * Custom event that fires after onTween * @private */ this._onTween = new Y.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 Y.CustomEvent('complete', this); /** * Custom event that fires after onComplete * @private */ this._onComplete = new Y.CustomEvent('_complete', this, true); this._onStart.subscribe(this._handleStart); this._onTween.subscribe(this._handleTween); this._onComplete.subscribe(this._handleComplete); } }; Y.Anim = Anim; })(); /** * Handles animation queueing and threading. * Used by Anim and subclasses. * @class AnimMgr * @namespace YAHOO.util */ YAHOO.util.AnimMgr = new function() { /** * Reference to the animation Interval. * @property thread * @private * @type Int */ var thread = null; /** * The current queue of registered animation objects. * @property queue * @private * @type Array */ var queue = []; /** * The number of active animations. * @property tweenCount * @private * @type Int */ var tweenCount = 0; /** * Base frame rate (frames per second). * Arbitrarily high for better x-browser calibration (slower browsers drop more frames). * @property fps * @type Int * */ this.fps = 1000; /** * Interval delay in milliseconds, defaults to fastest possible. * @property delay * @type Int * */ this.delay = 20; /** * 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(); }; var _unregisterQueue = []; var _unregistering = false; var doUnregister = function() { var next_args = _unregisterQueue.shift(); unRegister.apply(YAHOO.util.AnimMgr,next_args); if (_unregisterQueue.length) { arguments.callee(); } }; var unRegister = function(tween, index) { index = index || getIndex(tween); if (!tween.isAnimated() || index === -1) { return false; } tween._onComplete.fire(); queue.splice(index, 1); tweenCount -= 1; if (tweenCount <= 0) { this.stop(); } return true; }; /** * 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() { _unregisterQueue.push(arguments); if (!_unregistering) { _unregistering = true; doUnregister(); _unregistering = false; } } /** * 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) { this.unRegister(queue[0], 0); } 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; } }; this._queue = queue; this._getIndex = getIndex; }; /** * Used to calculate Bezier splines for any number of control points. * @class Bezier * @namespace YAHOO.util * */ YAHOO.util.Bezier = new function() { /** * Get the current position of the animated element based on t. * Each point is an array of "x" and "y" values (0 = x, 1 = y) * At least 2 points are required (start and end). * First point is start. Last point is end. * Additional control points are optional. * @method getPosition * @param {Array} points An array containing Bezier points * @param {Number} t A number between 0 and 1 which is the basis for determining current position * @return {Array} An array containing int x and y member data */ this.getPosition = function(points, t) { var n = points.length; var tmp = []; for (var i = 0; i < n; ++i){ tmp[i] = [points[i][0], points[i][1]]; // save input } for (var j = 1; j < n; ++j) { for (i = 0; i < n - j; ++i) { tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; } } return [ tmp[0][0], tmp[0][1] ]; }; }; (function() { /** * Anim subclass for color transitions. *

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

    * @class ColorAnim * @namespace YAHOO.util * @requires YAHOO.util.Anim * @requires YAHOO.util.AnimMgr * @requires YAHOO.util.Easing * @requires YAHOO.util.Bezier * @requires YAHOO.util.Dom * @requires YAHOO.util.Event * @constructor * @extends YAHOO.util.Anim * @param {HTMLElement | String} el Reference to the element that will be animated * @param {Object} attributes The attribute(s) to be animated. * Each attribute is an object with at minimum a "to" or "by" member defined. * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). * All attribute names use camelCase. * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) */ var ColorAnim = function(el, attributes, duration, method) { ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); }; ColorAnim.NAME = 'ColorAnim'; ColorAnim.DEFAULT_BGCOLOR = '#fff'; // shorthand var Y = YAHOO.util; YAHOO.extend(ColorAnim, Y.Anim); var superclass = ColorAnim.superclass; var proto = ColorAnim.prototype; 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); var that = this; if (this.patterns.transparent.test(val)) { // bgcolor default var parent = YAHOO.util.Dom.getAncestorBy(el, function(node) { return !that.patterns.transparent.test(val); }); if (parent) { val = Y.Dom.getStyle(parent, attr); } else { val = ColorAnim.DEFAULT_BGCOLOR; } } } 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; } }; Y.ColorAnim = ColorAnim; })(); /*! 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. * @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. * @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. * @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. * @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. * @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. * @method easeBothStrong * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeBothStrong: function (t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t*t + b; } return -c/2 * ((t-=2)*t*t*t - 2) + b; }, /** * Snap in elastic effect. * @method elasticIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} a Amplitude (optional) * @param {Number} p Period (optional) * @return {Number} The computed value for the current animation frame */ elasticIn: function (t, b, c, d, a, p) { if (t == 0) { return b; } if ( (t /= d) == 1 ) { return b+c; } if (!p) { p=d*.3; } if (!a || a < Math.abs(c)) { a = c; var s = p/4; } else { var s = p/(2*Math.PI) * Math.asin (c/a); } return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, /** * Snap out elastic effect. * @method elasticOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} a Amplitude (optional) * @param {Number} p Period (optional) * @return {Number} The computed value for the current animation frame */ elasticOut: function (t, b, c, d, a, p) { if (t == 0) { return b; } if ( (t /= d) == 1 ) { return b+c; } if (!p) { p=d*.3; } if (!a || a < Math.abs(c)) { a = c; var s = p / 4; } else { var s = p/(2*Math.PI) * Math.asin (c/a); } return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, /** * Snap both elastic effect. * @method elasticBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} a Amplitude (optional) * @param {Number} p Period (optional) * @return {Number} The computed value for the current animation frame */ elasticBoth: function (t, b, c, d, a, p) { if (t == 0) { return b; } if ( (t /= d/2) == 2 ) { return b+c; } if (!p) { p = d*(.3*1.5); } if ( !a || a < Math.abs(c) ) { a = c; var s = p/4; } else { var s = p/(2*Math.PI) * Math.asin (c/a); } if (t < 1) { return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; } return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, /** * Backtracks slightly, then reverses direction and moves to end. * @method backIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} s Overshoot (optional) * @return {Number} The computed value for the current animation frame */ backIn: function (t, b, c, d, s) { if (typeof s == 'undefined') { s = 1.70158; } return c*(t/=d)*t*((s+1)*t - s) + b; }, /** * Overshoots end, then reverses and comes back to end. * @method backOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} s Overshoot (optional) * @return {Number} The computed value for the current animation frame */ backOut: function (t, b, c, d, s) { if (typeof s == 'undefined') { s = 1.70158; } return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, /** * Backtracks slightly, then reverses direction, overshoots end, * then reverses and comes back to end. * @method backBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} s Overshoot (optional) * @return {Number} The computed value for the current animation frame */ backBoth: function (t, b, c, d, s) { if (typeof s == 'undefined') { s = 1.70158; } if ((t /= d/2 ) < 1) { return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; } return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, /** * Bounce off of start. * @method bounceIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ bounceIn: function (t, b, c, d) { return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; }, /** * Bounces off end. * @method bounceOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ bounceOut: function (t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; }, /** * Bounces off start and end. * @method bounceBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ bounceBoth: function (t, b, c, d) { if (t < d/2) { return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b; } return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; } }; (function() { /** * Anim subclass for moving elements along a path defined by the "points" * member of "attributes". All "points" are arrays with x, y coordinates. *

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

    * @class Motion * @namespace YAHOO.util * @requires YAHOO.util.Anim * @requires YAHOO.util.AnimMgr * @requires YAHOO.util.Easing * @requires YAHOO.util.Bezier * @requires YAHOO.util.Dom * @requires YAHOO.util.Event * @requires YAHOO.util.CustomEvent * @constructor * @extends YAHOO.util.ColorAnim * @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) */ var Motion = function(el, attributes, duration, method) { if (el) { // dont break existing subclasses not using YAHOO.extend Motion.superclass.constructor.call(this, el, attributes, duration, method); } }; Motion.NAME = 'Motion'; // shorthand var Y = YAHOO.util; YAHOO.extend(Motion, Y.ColorAnim); var superclass = Motion.superclass; var proto = Motion.prototype; 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'); }; Y.Motion = Motion; })(); (function() { /** * Anim subclass for scrolling elements to a position defined by the "scroll" * member of "attributes". All "scroll" members are arrays with x, y scroll positions. *

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

    * @class Scroll * @namespace YAHOO.util * @requires YAHOO.util.Anim * @requires YAHOO.util.AnimMgr * @requires YAHOO.util.Easing * @requires YAHOO.util.Bezier * @requires YAHOO.util.Dom * @requires YAHOO.util.Event * @requires YAHOO.util.CustomEvent * @extends YAHOO.util.ColorAnim * @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) */ var Scroll = function(el, attributes, duration, method) { if (el) { // dont break existing subclasses not using YAHOO.extend Scroll.superclass.constructor.call(this, el, attributes, duration, method); } }; Scroll.NAME = 'Scroll'; // shorthand var Y = YAHOO.util; YAHOO.extend(Scroll, Y.ColorAnim); var superclass = Scroll.superclass; var proto = Scroll.prototype; 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); } }; Y.Scroll = Scroll; })(); YAHOO.register("animation", YAHOO.util.Anim, {version: "2.9.0", build: "2800"}); /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ /** * The drag and drop utility provides a framework for building drag and drop * applications. In addition to enabling drag and drop for specific elements, * the drag and drop elements are tracked by the manager class, and the * interactions between the various elements are tracked during the drag and * the implementing code is notified about these important moments. * @module dragdrop * @title Drag and Drop * @requires yahoo,dom,event * @namespace YAHOO.util */ // Only load the library once. Rewriting the manager class would orphan // existing drag and drop instances. if (!YAHOO.util.DragDropMgr) { /** * DragDropMgr is a singleton that tracks the element interaction for * all DragDrop items in the window. Generally, you will not call * this class directly, but it does have helper methods that could * be useful in your DragDrop implementations. * @class DragDropMgr * @static */ YAHOO.util.DragDropMgr = function() { var Event = YAHOO.util.Event, Dom = YAHOO.util.Dom; return { /** * This property is used to turn on global use of the shim element on all DragDrop instances, defaults to false for backcompat. (Use: YAHOO.util.DDM.useShim = true) * @property useShim * @type Boolean * @static */ useShim: false, /** * This property is used to determine if the shim is active over the screen, default false. * @private * @property _shimActive * @type Boolean * @static */ _shimActive: false, /** * This property is used when useShim is set on a DragDrop object to store the current state of DDM.useShim so it can be reset when a drag operation is done. * @private * @property _shimState * @type Boolean * @static */ _shimState: false, /** * This property is used when useShim is set to true, it will set the opacity on the shim to .5 for debugging. Use: (YAHOO.util.DDM._debugShim = true;) * @private * @property _debugShim * @type Boolean * @static */ _debugShim: false, /** * This method will create a shim element (giving it the id of yui-ddm-shim), it also attaches the mousemove and mouseup listeners to it and attaches a scroll listener on the window * @private * @method _sizeShim * @static */ _createShim: function() { YAHOO.log('Creating Shim Element', 'info', 'DragDropMgr'); var s = document.createElement('div'); s.id = 'yui-ddm-shim'; if (document.body.firstChild) { document.body.insertBefore(s, document.body.firstChild); } else { document.body.appendChild(s); } s.style.display = 'none'; s.style.backgroundColor = 'red'; s.style.position = 'absolute'; s.style.zIndex = '99999'; Dom.setStyle(s, 'opacity', '0'); this._shim = s; Event.on(s, "mouseup", this.handleMouseUp, this, true); Event.on(s, "mousemove", this.handleMouseMove, this, true); Event.on(window, 'scroll', this._sizeShim, this, true); }, /** * This method will size the shim, called from activate and on window scroll event * @private * @method _sizeShim * @static */ _sizeShim: function() { if (this._shimActive) { YAHOO.log('Sizing Shim', 'info', 'DragDropMgr'); var s = this._shim; s.style.height = Dom.getDocumentHeight() + 'px'; s.style.width = Dom.getDocumentWidth() + 'px'; s.style.top = '0'; s.style.left = '0'; } }, /** * This method will create the shim element if needed, then show the shim element, size the element and set the _shimActive property to true * @private * @method _activateShim * @static */ _activateShim: function() { if (this.useShim) { YAHOO.log('Activating Shim', 'info', 'DragDropMgr'); if (!this._shim) { this._createShim(); } this._shimActive = true; var s = this._shim, o = '0'; if (this._debugShim) { o = '.5'; } Dom.setStyle(s, 'opacity', o); this._sizeShim(); s.style.display = 'block'; } }, /** * This method will hide the shim element and set the _shimActive property to false * @private * @method _deactivateShim * @static */ _deactivateShim: function() { YAHOO.log('Deactivating Shim', 'info', 'DragDropMgr'); this._shim.style.display = 'none'; this._shimActive = false; }, /** * The HTML element created to use as a shim over the document to track mouse movements * @private * @property _shim * @type HTMLElement * @static */ _shim: null, /** * Two dimensional Array of registered DragDrop objects. The first * dimension is the DragDrop item group, the second the DragDrop * object. * @property ids * @type {string: string} * @private * @static */ ids: {}, /** * Array of element ids defined as drag handles. Used to determine * if the element that generated the mousedown event is actually the * handle and not the html element itself. * @property handleIds * @type {string: string} * @private * @static */ handleIds: {}, /** * the DragDrop object that is currently being dragged * @property dragCurrent * @type DragDrop * @private * @static **/ dragCurrent: null, /** * the DragDrop object(s) that are being hovered over * @property dragOvers * @type Array * @private * @static */ dragOvers: {}, /** * the X distance between the cursor and the object being dragged * @property deltaX * @type int * @private * @static */ deltaX: 0, /** * the Y distance between the cursor and the object being dragged * @property deltaY * @type int * @private * @static */ deltaY: 0, /** * Flag to determine if we should prevent the default behavior of the * events we define. By default this is true, but this can be set to * false if you need the default behavior (not recommended) * @property preventDefault * @type boolean * @static */ preventDefault: true, /** * Flag to determine if we should stop the propagation of the events * we generate. This is true by default but you may want to set it to * false if the html element contains other features that require the * mouse click. * @property stopPropagation * @type boolean * @static */ stopPropagation: true, /** * Internal flag that is set to true when drag and drop has been * initialized * @property initialized * @private * @static */ initialized: false, /** * All drag and drop can be disabled. * @property locked * @private * @static */ locked: false, /** * Provides additional information about the the current set of * interactions. Can be accessed from the event handlers. It * contains the following properties: * * out: onDragOut interactions * enter: onDragEnter interactions * over: onDragOver interactions * drop: onDragDrop interactions * point: The location of the cursor * draggedRegion: The location of dragged element at the time * of the interaction * sourceRegion: The location of the source elemtn at the time * of the interaction * validDrop: boolean * @property interactionInfo * @type object * @static */ interactionInfo: null, /** * Called the first time an element is registered. * @method init * @private * @static */ init: function() { this.initialized = true; }, /** * In point mode, drag and drop interaction is defined by the * location of the cursor during the drag/drop * @property POINT * @type int * @static * @final */ POINT: 0, /** * In intersect mode, drag and drop interaction is defined by the * cursor position or the amount of overlap of two or more drag and * drop objects. * @property INTERSECT * @type int * @static * @final */ INTERSECT: 1, /** * In intersect mode, drag and drop interaction is defined only by the * overlap of two or more drag and drop objects. * @property STRICT_INTERSECT * @type int * @static * @final */ STRICT_INTERSECT: 2, /** * The current drag and drop mode. Default: POINT * @property mode * @type int * @static */ mode: 0, /** * Runs method on all drag and drop objects * @method _execOnAll * @private * @static */ _execOnAll: function(sMethod, args) { for (var i in this.ids) { for (var j in this.ids[i]) { var oDD = this.ids[i][j]; if (! this.isTypeOfDD(oDD)) { continue; } oDD[sMethod].apply(oDD, args); } } }, /** * Drag and drop initialization. Sets up the global event handlers * @method _onLoad * @private * @static */ _onLoad: function() { this.init(); YAHOO.log("DragDropMgr onload", "info", "DragDropMgr"); Event.on(document, "mouseup", this.handleMouseUp, this, true); Event.on(document, "mousemove", this.handleMouseMove, this, true); Event.on(window, "unload", this._onUnload, this, true); Event.on(window, "resize", this._onResize, this, true); // Event.on(window, "mouseout", this._test); }, /** * Reset constraints on all drag and drop objs * @method _onResize * @private * @static */ _onResize: function(e) { YAHOO.log("window resize", "info", "DragDropMgr"); this._execOnAll("resetConstraints", []); }, /** * Lock all drag and drop functionality * @method lock * @static */ lock: function() { this.locked = true; }, /** * Unlock all drag and drop functionality * @method unlock * @static */ unlock: function() { this.locked = false; }, /** * Is drag and drop locked? * @method isLocked * @return {boolean} True if drag and drop is locked, false otherwise. * @static */ isLocked: function() { return this.locked; }, /** * Location cache that is set for all drag drop objects when a drag is * initiated, cleared when the drag is finished. * @property locationCache * @private * @static */ locationCache: {}, /** * Set useCache to false if you want to force object the lookup of each * drag and drop linked element constantly during a drag. * @property useCache * @type boolean * @static */ useCache: true, /** * The number of pixels that the mouse needs to move after the * mousedown before the drag is initiated. Default=3; * @property clickPixelThresh * @type int * @static */ clickPixelThresh: 3, /** * The number of milliseconds after the mousedown event to initiate the * drag if we don't get a mouseup event. Default=1000 * @property clickTimeThresh * @type int * @static */ clickTimeThresh: 1000, /** * Flag that indicates that either the drag pixel threshold or the * mousdown time threshold has been met * @property dragThreshMet * @type boolean * @private * @static */ dragThreshMet: false, /** * Timeout used for the click time threshold * @property clickTimeout * @type Object * @private * @static */ clickTimeout: null, /** * The X position of the mousedown event stored for later use when a * drag threshold is met. * @property startX * @type int * @private * @static */ startX: 0, /** * The Y position of the mousedown event stored for later use when a * drag threshold is met. * @property startY * @type int * @private * @static */ startY: 0, /** * Flag to determine if the drag event was fired from the click timeout and * not the mouse move threshold. * @property fromTimeout * @type boolean * @private * @static */ fromTimeout: false, /** * Each DragDrop instance must be registered with the DragDropMgr. * This is executed in DragDrop.init() * @method regDragDrop * @param {DragDrop} oDD the DragDrop object to register * @param {String} sGroup the name of the group this element belongs to * @static */ regDragDrop: function(oDD, sGroup) { if (!this.initialized) { this.init(); } if (!this.ids[sGroup]) { this.ids[sGroup] = {}; } this.ids[sGroup][oDD.id] = oDD; }, /** * Removes the supplied dd instance from the supplied group. Executed * by DragDrop.removeFromGroup, so don't call this function directly. * @method removeDDFromGroup * @private * @static */ removeDDFromGroup: function(oDD, sGroup) { if (!this.ids[sGroup]) { this.ids[sGroup] = {}; } var obj = this.ids[sGroup]; if (obj && obj[oDD.id]) { delete obj[oDD.id]; } }, /** * Unregisters a drag and drop item. This is executed in * DragDrop.unreg, use that method instead of calling this directly. * @method _remove * @private * @static */ _remove: function(oDD) { for (var g in oDD.groups) { if (g) { var item = this.ids[g]; if (item && item[oDD.id]) { delete item[oDD.id]; } } } delete this.handleIds[oDD.id]; }, /** * Each DragDrop handle element must be registered. This is done * automatically when executing DragDrop.setHandleElId() * @method regHandle * @param {String} sDDId the DragDrop id this element is a handle for * @param {String} sHandleId the id of the element that is the drag * handle * @static */ regHandle: function(sDDId, sHandleId) { if (!this.handleIds[sDDId]) { this.handleIds[sDDId] = {}; } this.handleIds[sDDId][sHandleId] = sHandleId; }, /** * Utility function to determine if a given element has been * registered as a drag drop item. * @method isDragDrop * @param {String} id the element id to check * @return {boolean} true if this element is a DragDrop item, * false otherwise * @static */ isDragDrop: function(id) { return ( this.getDDById(id) ) ? true : false; }, /** * Returns the drag and drop instances that are in all groups the * passed in instance belongs to. * @method getRelated * @param {DragDrop} p_oDD the obj to get related data for * @param {boolean} bTargetsOnly if true, only return targetable objs * @return {DragDrop[]} the related instances * @static */ getRelated: function(p_oDD, bTargetsOnly) { var oDDs = []; for (var i in p_oDD.groups) { for (var j in this.ids[i]) { var dd = this.ids[i][j]; if (! this.isTypeOfDD(dd)) { continue; } if (!bTargetsOnly || dd.isTarget) { oDDs[oDDs.length] = dd; } } } return oDDs; }, /** * Returns true if the specified dd target is a legal target for * the specifice drag obj * @method isLegalTarget * @param {DragDrop} the drag obj * @param {DragDrop} the target * @return {boolean} true if the target is a legal target for the * dd obj * @static */ isLegalTarget: function (oDD, oTargetDD) { var targets = this.getRelated(oDD, true); for (var i=0, len=targets.length;i this.clickPixelThresh || diffY > this.clickPixelThresh) { YAHOO.log("pixel threshold met", "info", "DragDropMgr"); this.startDrag(this.startX, this.startY); } } if (this.dragThreshMet) { if (dc && dc.events.b4Drag) { dc.b4Drag(e); dc.fireEvent('b4DragEvent', { e: e}); } if (dc && dc.events.drag) { dc.onDrag(e); dc.fireEvent('dragEvent', { e: e}); } if (dc) { this.fireEvents(e, false); } } this.stopEvent(e); } }, /** * Iterates over all of the DragDrop elements to find ones we are * hovering over or dropping on * @method fireEvents * @param {Event} e the event * @param {boolean} isDrop is this a drop op or a mouseover op? * @private * @static */ fireEvents: function(e, isDrop) { var dc = this.dragCurrent; // If the user did the mouse up outside of the window, we could // get here even though we have ended the drag. // If the config option dragOnly is true, bail out and don't fire the events if (!dc || dc.isLocked() || dc.dragOnly) { return; } var x = YAHOO.util.Event.getPageX(e), y = YAHOO.util.Event.getPageY(e), pt = new YAHOO.util.Point(x,y), pos = dc.getTargetCoord(pt.x, pt.y), el = dc.getDragEl(), events = ['out', 'over', 'drop', 'enter'], curRegion = new YAHOO.util.Region( pos.y, pos.x + el.offsetWidth, pos.y + el.offsetHeight, pos.x ), oldOvers = [], // cache the previous dragOver array inGroupsObj = {}, b4Results = {}, inGroups = [], data = { outEvts: [], overEvts: [], dropEvts: [], enterEvts: [] }; // Check to see if the object(s) we were hovering over is no longer // being hovered over so we can fire the onDragOut event for (var i in this.dragOvers) { var ddo = this.dragOvers[i]; if (! this.isTypeOfDD(ddo)) { continue; } if (! this.isOverTarget(pt, ddo, this.mode, curRegion)) { data.outEvts.push( ddo ); } oldOvers[i] = true; delete this.dragOvers[i]; } for (var sGroup in dc.groups) { // YAHOO.log("Processing group " + sGroup); if ("string" != typeof sGroup) { continue; } for (i in this.ids[sGroup]) { var oDD = this.ids[sGroup][i]; if (! this.isTypeOfDD(oDD)) { continue; } if (oDD.isTarget && !oDD.isLocked() && oDD != dc) { if (this.isOverTarget(pt, oDD, this.mode, curRegion)) { inGroupsObj[sGroup] = true; // look for drop interactions if (isDrop) { data.dropEvts.push( oDD ); // look for drag enter and drag over interactions } else { // initial drag over: dragEnter fires if (!oldOvers[oDD.id]) { data.enterEvts.push( oDD ); // subsequent drag overs: dragOver fires } else { data.overEvts.push( oDD ); } this.dragOvers[oDD.id] = oDD; } } } } } this.interactionInfo = { out: data.outEvts, enter: data.enterEvts, over: data.overEvts, drop: data.dropEvts, point: pt, draggedRegion: curRegion, sourceRegion: this.locationCache[dc.id], validDrop: isDrop }; for (var inG in inGroupsObj) { inGroups.push(inG); } // notify about a drop that did not find a target if (isDrop && !data.dropEvts.length) { YAHOO.log(dc.id + " dropped, but not on a target", "info", "DragDropMgr"); this.interactionInfo.validDrop = false; if (dc.events.invalidDrop) { dc.onInvalidDrop(e); dc.fireEvent('invalidDropEvent', { e: e }); } } for (i = 0; i < events.length; i++) { var tmp = null; if (data[events[i] + 'Evts']) { tmp = data[events[i] + 'Evts']; } if (tmp && tmp.length) { var type = events[i].charAt(0).toUpperCase() + events[i].substr(1), ev = 'onDrag' + type, b4 = 'b4Drag' + type, cev = 'drag' + type + 'Event', check = 'drag' + type; if (this.mode) { YAHOO.log(dc.id + ' ' + ev + ': ' + tmp, "info", "DragDropMgr"); if (dc.events[b4]) { dc[b4](e, tmp, inGroups); b4Results[ev] = dc.fireEvent(b4 + 'Event', { event: e, info: tmp, group: inGroups }); } if (dc.events[check] && (b4Results[ev] !== false)) { dc[ev](e, tmp, inGroups); dc.fireEvent(cev, { event: e, info: tmp, group: inGroups }); } } else { for (var b = 0, len = tmp.length; b < len; ++b) { YAHOO.log(dc.id + ' ' + ev + ': ' + tmp[b].id, "info", "DragDropMgr"); if (dc.events[b4]) { dc[b4](e, tmp[b].id, inGroups[0]); b4Results[ev] = dc.fireEvent(b4 + 'Event', { event: e, info: tmp[b].id, group: inGroups[0] }); } if (dc.events[check] && (b4Results[ev] !== false)) { dc[ev](e, tmp[b].id, inGroups[0]); dc.fireEvent(cev, { event: e, info: tmp[b].id, group: inGroups[0] }); } } } } } }, /** * Helper function for getting the best match from the list of drag * and drop objects returned by the drag and drop events when we are * in INTERSECT mode. It returns either the first object that the * cursor is over, or the object that has the greatest overlap with * the dragged element. * @method getBestMatch * @param {DragDrop[]} dds The array of drag and drop objects * targeted * @return {DragDrop} The best single match * @static */ getBestMatch: function(dds) { var winner = null; var len = dds.length; if (len == 1) { winner = dds[0]; } else { // Loop through the targeted items for (var i=0; i * YAHOO.util.DragDropMgr.refreshCache(ddinstance.groups); * * Alternatively: * * YAHOO.util.DragDropMgr.refreshCache({group1:true, group2:true}); * * @TODO this really should be an indexed array. Alternatively this * method could accept both. * @method refreshCache * @param {Object} groups an associative array of groups to refresh * @static */ refreshCache: function(groups) { YAHOO.log("refreshing element location cache", "info", "DragDropMgr"); // refresh everything if group array is not provided var g = groups || this.ids; for (var sGroup in g) { if ("string" != typeof sGroup) { continue; } for (var i in this.ids[sGroup]) { var oDD = this.ids[sGroup][i]; if (this.isTypeOfDD(oDD)) { var loc = this.getLocation(oDD); if (loc) { this.locationCache[oDD.id] = loc; } else { delete this.locationCache[oDD.id]; YAHOO.log("Could not get the loc for " + oDD.id, "warn", "DragDropMgr"); } } } } }, /** * This checks to make sure an element exists and is in the DOM. The * main purpose is to handle cases where innerHTML is used to remove * drag and drop objects from the DOM. IE provides an 'unspecified * error' when trying to access the offsetParent of such an element * @method verifyEl * @param {HTMLElement} el the element to check * @return {boolean} true if the element looks usable * @static */ verifyEl: function(el) { try { if (el) { var parent = el.offsetParent; if (parent) { return true; } } } catch(e) { YAHOO.log("detected problem with an element", "info", "DragDropMgr"); } return false; }, /** * Returns a Region object containing the drag and drop element's position * and size, including the padding configured for it * @method getLocation * @param {DragDrop} oDD the drag and drop object to get the * location for * @return {YAHOO.util.Region} a Region object representing the total area * the element occupies, including any padding * the instance is configured for. * @static */ getLocation: function(oDD) { if (! this.isTypeOfDD(oDD)) { YAHOO.log(oDD + " is not a DD obj", "info", "DragDropMgr"); return null; } var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l; try { pos= YAHOO.util.Dom.getXY(el); } catch (e) { } if (!pos) { YAHOO.log("getXY failed", "info", "DragDropMgr"); return null; } x1 = pos[0]; x2 = x1 + el.offsetWidth; y1 = pos[1]; y2 = y1 + el.offsetHeight; t = y1 - oDD.padding[0]; r = x2 + oDD.padding[1]; b = y2 + oDD.padding[2]; l = x1 - oDD.padding[3]; return new YAHOO.util.Region( t, r, b, l ); }, /** * Checks the cursor location to see if it over the target * @method isOverTarget * @param {YAHOO.util.Point} pt The point to evaluate * @param {DragDrop} oTarget the DragDrop object we are inspecting * @param {boolean} intersect true if we are in intersect mode * @param {YAHOO.util.Region} pre-cached location of the dragged element * @return {boolean} true if the mouse is over the target * @private * @static */ isOverTarget: function(pt, oTarget, intersect, curRegion) { // use cache if available var loc = this.locationCache[oTarget.id]; if (!loc || !this.useCache) { YAHOO.log("cache not populated", "info", "DragDropMgr"); loc = this.getLocation(oTarget); this.locationCache[oTarget.id] = loc; YAHOO.log("cache: " + loc, "info", "DragDropMgr"); } if (!loc) { YAHOO.log("could not get the location of the element", "info", "DragDropMgr"); return false; } //YAHOO.log("loc: " + loc + ", pt: " + pt); oTarget.cursorIsOver = loc.contains( pt ); // DragDrop is using this as a sanity check for the initial mousedown // in this case we are done. In POINT mode, if the drag obj has no // contraints, we are done. Otherwise we need to evaluate the // region the target as occupies to determine if the dragged element // overlaps with it. var dc = this.dragCurrent; if (!dc || (!intersect && !dc.constrainX && !dc.constrainY)) { //if (oTarget.cursorIsOver) { //YAHOO.log("over " + oTarget + ", " + loc + ", " + pt, "warn"); //} return oTarget.cursorIsOver; } oTarget.overlap = null; // Get the current location of the drag element, this is the // location of the mouse event less the delta that represents // where the original mousedown happened on the element. We // need to consider constraints and ticks as well. if (!curRegion) { var pos = dc.getTargetCoord(pt.x, pt.y); var el = dc.getDragEl(); curRegion = new YAHOO.util.Region( pos.y, pos.x + el.offsetWidth, pos.y + el.offsetHeight, pos.x ); } var overlap = curRegion.intersect(loc); if (overlap) { oTarget.overlap = overlap; return (intersect) ? true : oTarget.cursorIsOver; } else { return false; } }, /** * unload event handler * @method _onUnload * @private * @static */ _onUnload: function(e, me) { this.unregAll(); }, /** * Cleans up the drag and drop events and objects. * @method unregAll * @private * @static */ unregAll: function() { YAHOO.log("unregister all", "info", "DragDropMgr"); if (this.dragCurrent) { this.stopDrag(); this.dragCurrent = null; } this._execOnAll("unreg", []); //for (var i in this.elementCache) { //delete this.elementCache[i]; //} //this.elementCache = {}; this.ids = {}; }, /** * A cache of DOM elements * @property elementCache * @private * @static * @deprecated elements are not cached now */ elementCache: {}, /** * Get the wrapper for the DOM element specified * @method getElWrapper * @param {String} id the id of the element to get * @return {YAHOO.util.DDM.ElementWrapper} the wrapped element * @private * @deprecated This wrapper isn't that useful * @static */ getElWrapper: function(id) { var oWrapper = this.elementCache[id]; if (!oWrapper || !oWrapper.el) { oWrapper = this.elementCache[id] = new this.ElementWrapper(YAHOO.util.Dom.get(id)); } return oWrapper; }, /** * Returns the actual DOM element * @method getElement * @param {String} id the id of the elment to get * @return {Object} The element * @deprecated use YAHOO.util.Dom.get instead * @static */ getElement: function(id) { return YAHOO.util.Dom.get(id); }, /** * Returns the style property for the DOM element (i.e., * document.getElById(id).style) * @method getCss * @param {String} id the id of the elment to get * @return {Object} The style property of the element * @deprecated use YAHOO.util.Dom instead * @static */ getCss: function(id) { var el = YAHOO.util.Dom.get(id); return (el) ? el.style : null; }, /** * Inner class for cached elements * @class DragDropMgr.ElementWrapper * @for DragDropMgr * @private * @deprecated */ ElementWrapper: function(el) { /** * The element * @property el */ this.el = el || null; /** * The element id * @property id */ this.id = this.el && el.id; /** * A reference to the style property * @property css */ this.css = this.el && el.style; }, /** * Returns the X position of an html element * @method getPosX * @param el the element for which to get the position * @return {int} the X coordinate * @for DragDropMgr * @deprecated use YAHOO.util.Dom.getX instead * @static */ getPosX: function(el) { return YAHOO.util.Dom.getX(el); }, /** * Returns the Y position of an html element * @method getPosY * @param el the element for which to get the position * @return {int} the Y coordinate * @deprecated use YAHOO.util.Dom.getY instead * @static */ getPosY: function(el) { return YAHOO.util.Dom.getY(el); }, /** * Swap two nodes. In IE, we use the native method, for others we * emulate the IE behavior * @method swapNode * @param n1 the first node to swap * @param n2 the other node to swap * @static */ swapNode: function(n1, n2) { if (n1.swapNode) { n1.swapNode(n2); } else { var p = n2.parentNode; var s = n2.nextSibling; if (s == n1) { p.insertBefore(n1, n2); } else if (n2 == n1.nextSibling) { p.insertBefore(n2, n1); } else { n1.parentNode.replaceChild(n2, n1); p.insertBefore(n1, s); } } }, /** * Returns the current scroll position * @method getScroll * @private * @static */ getScroll: function () { var t, l, dde=document.documentElement, db=document.body; if (dde && (dde.scrollTop || dde.scrollLeft)) { t = dde.scrollTop; l = dde.scrollLeft; } else if (db) { t = db.scrollTop; l = db.scrollLeft; } else { YAHOO.log("could not get scroll property", "info", "DragDropMgr"); } return { top: t, left: l }; }, /** * Returns the specified element style property * @method getStyle * @param {HTMLElement} el the element * @param {string} styleProp the style property * @return {string} The value of the style property * @deprecated use YAHOO.util.Dom.getStyle * @static */ getStyle: function(el, styleProp) { return YAHOO.util.Dom.getStyle(el, styleProp); }, /** * Gets the scrollTop * @method getScrollTop * @return {int} the document's scrollTop * @static */ getScrollTop: function () { return this.getScroll().top; }, /** * Gets the scrollLeft * @method getScrollLeft * @return {int} the document's scrollTop * @static */ getScrollLeft: function () { return this.getScroll().left; }, /** * Sets the x/y position of an element to the location of the * target element. * @method moveToEl * @param {HTMLElement} moveEl The element to move * @param {HTMLElement} targetEl The position reference element * @static */ moveToEl: function (moveEl, targetEl) { var aCoord = YAHOO.util.Dom.getXY(targetEl); YAHOO.log("moveToEl: " + aCoord, "info", "DragDropMgr"); YAHOO.util.Dom.setXY(moveEl, aCoord); }, /** * Gets the client height * @method getClientHeight * @return {int} client height in px * @deprecated use YAHOO.util.Dom.getViewportHeight instead * @static */ getClientHeight: function() { return YAHOO.util.Dom.getViewportHeight(); }, /** * Gets the client width * @method getClientWidth * @return {int} client width in px * @deprecated use YAHOO.util.Dom.getViewportWidth instead * @static */ getClientWidth: function() { return YAHOO.util.Dom.getViewportWidth(); }, /** * Numeric array sort function * @method numericSort * @static */ numericSort: function(a, b) { return (a - b); }, /** * Internal counter * @property _timeoutCount * @private * @static */ _timeoutCount: 0, /** * Trying to make the load order less important. Without this we get * an error if this file is loaded before the Event Utility. * @method _addListeners * @private * @static */ _addListeners: function() { var DDM = YAHOO.util.DDM; if ( YAHOO.util.Event && document ) { DDM._onLoad(); } else { if (DDM._timeoutCount > 2000) { YAHOO.log("DragDrop requires the Event Utility", "error", "DragDropMgr"); } else { setTimeout(DDM._addListeners, 10); if (document && document.body) { DDM._timeoutCount += 1; } } } }, /** * Recursively searches the immediate parent and all child nodes for * the handle element in order to determine wheter or not it was * clicked. * @method handleWasClicked * @param node the html element to inspect * @static */ handleWasClicked: function(node, id) { if (this.isHandle(id, node.id)) { YAHOO.log("clicked node is a handle", "info", "DragDropMgr"); return true; } else { // check to see if this is a text node child of the one we want var p = node.parentNode; // YAHOO.log("p: " + p); while (p) { if (this.isHandle(id, p.id)) { return true; } else { YAHOO.log(p.id + " is not a handle", "info", "DragDropMgr"); p = p.parentNode; } } } return false; } }; }(); // shorter alias, save a few bytes YAHOO.util.DDM = YAHOO.util.DragDropMgr; YAHOO.util.DDM._addListeners(); } (function() { var Event=YAHOO.util.Event; var Dom=YAHOO.util.Dom; /** * Defines the interface and base operation of items that that can be * dragged or can be drop targets. It was designed to be extended, overriding * the event handlers for startDrag, onDrag, onDragOver, onDragOut. * Up to three html elements can be associated with a DragDrop instance: *
      *
    • linked element: the element that is passed into the constructor. * This is the element which defines the boundaries for interaction with * other DragDrop objects.
    • *
    • handle element(s): The drag operation only occurs if the element that * was clicked matches a handle element. By default this is the linked * element, but there are times that you will want only a portion of the * linked element to initiate the drag operation, and the setHandleElId() * method provides a way to define this.
    • *
    • drag element: this represents an the element that would be moved along * with the cursor during a drag operation. By default, this is the linked * element itself as in {@link YAHOO.util.DD}. setDragElId() lets you define * a separate element that would be moved, as in {@link YAHOO.util.DDProxy} *
    • *
    * This class should not be instantiated until the onload event to ensure that * the associated elements are available. * The following would define a DragDrop obj that would interact with any * other DragDrop obj in the "group1" group: *
     *  dd = new YAHOO.util.DragDrop("div1", "group1");
     * 
    * Since none of the event handlers have been implemented, nothing would * actually happen if you were to run the code above. Normally you would * override this class or one of the default implementations, but you can * also override the methods you want on an instance of the class... *
     *  dd.onDragDrop = function(e, id) {
     *    alert("dd was dropped on " + id);
     *  }
     * 
    * @namespace YAHOO.util * @class DragDrop * @constructor * @param {String} id of the element that is linked to this instance * @param {String} sGroup the group of related DragDrop objects * @param {object} config an object containing configurable attributes * Valid properties for DragDrop: * padding, isTarget, maintainOffset, primaryButtonOnly, */ YAHOO.util.DragDrop = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); } }; YAHOO.util.DragDrop.prototype = { /** * An Object Literal containing the events that we will be using: mouseDown, b4MouseDown, mouseUp, b4StartDrag, startDrag, b4EndDrag, endDrag, mouseUp, drag, b4Drag, invalidDrop, b4DragOut, dragOut, dragEnter, b4DragOver, dragOver, b4DragDrop, dragDrop * By setting any of these to false, then event will not be fired. * @property events * @type object */ events: null, /** * @method on * @description Shortcut for EventProvider.subscribe, see YAHOO.util.EventProvider.subscribe */ on: function() { this.subscribe.apply(this, arguments); }, /** * The id of the element associated with this object. This is what we * refer to as the "linked element" because the size and position of * this element is used to determine when the drag and drop objects have * interacted. * @property id * @type String */ id: null, /** * Configuration attributes passed into the constructor * @property config * @type object */ config: null, /** * The id of the element that will be dragged. By default this is same * as the linked element , but could be changed to another element. Ex: * YAHOO.util.DDProxy * @property dragElId * @type String * @private */ dragElId: null, /** * the id of the element that initiates the drag operation. By default * this is the linked element, but could be changed to be a child of this * element. This lets us do things like only starting the drag when the * header element within the linked html element is clicked. * @property handleElId * @type String * @private */ handleElId: null, /** * An associative array of HTML tags that will be ignored if clicked. * @property invalidHandleTypes * @type {string: string} */ invalidHandleTypes: null, /** * An associative array of ids for elements that will be ignored if clicked * @property invalidHandleIds * @type {string: string} */ invalidHandleIds: null, /** * An indexted array of css class names for elements that will be ignored * if clicked. * @property invalidHandleClasses * @type string[] */ invalidHandleClasses: null, /** * The linked element's absolute X position at the time the drag was * started * @property startPageX * @type int * @private */ startPageX: 0, /** * The linked element's absolute X position at the time the drag was * started * @property startPageY * @type int * @private */ startPageY: 0, /** * The group defines a logical collection of DragDrop objects that are * related. Instances only get events when interacting with other * DragDrop object in the same group. This lets us define multiple * groups using a single DragDrop subclass if we want. * @property groups * @type {string: string} */ groups: null, /** * Individual drag/drop instances can be locked. This will prevent * onmousedown start drag. * @property locked * @type boolean * @private */ locked: false, /** * Lock this instance * @method lock */ lock: function() { this.locked = true; }, /** * Unlock this instace * @method unlock */ unlock: function() { this.locked = false; }, /** * By default, all instances can be a drop target. This can be disabled by * setting isTarget to false. * @property isTarget * @type boolean */ isTarget: true, /** * The padding configured for this drag and drop object for calculating * the drop zone intersection with this object. * @property padding * @type int[] */ padding: null, /** * If this flag is true, do not fire drop events. The element is a drag only element (for movement not dropping) * @property dragOnly * @type Boolean */ dragOnly: false, /** * If this flag is true, a shim will be placed over the screen/viewable area to track mouse events. Should help with dragging elements over iframes and other controls. * @property useShim * @type Boolean */ useShim: false, /** * Cached reference to the linked element * @property _domRef * @private */ _domRef: null, /** * Internal typeof flag * @property __ygDragDrop * @private */ __ygDragDrop: true, /** * Set to true when horizontal contraints are applied * @property constrainX * @type boolean * @private */ constrainX: false, /** * Set to true when vertical contraints are applied * @property constrainY * @type boolean * @private */ constrainY: false, /** * The left constraint * @property minX * @type int * @private */ minX: 0, /** * The right constraint * @property maxX * @type int * @private */ maxX: 0, /** * The up constraint * @property minY * @type int * @type int * @private */ minY: 0, /** * The down constraint * @property maxY * @type int * @private */ maxY: 0, /** * The difference between the click position and the source element's location * @property deltaX * @type int * @private */ deltaX: 0, /** * The difference between the click position and the source element's location * @property deltaY * @type int * @private */ deltaY: 0, /** * Maintain offsets when we resetconstraints. Set to true when you want * the position of the element relative to its parent to stay the same * when the page changes * * @property maintainOffset * @type boolean */ maintainOffset: false, /** * Array of pixel locations the element will snap to if we specified a * horizontal graduation/interval. This array is generated automatically * when you define a tick interval. * @property xTicks * @type int[] */ xTicks: null, /** * Array of pixel locations the element will snap to if we specified a * vertical graduation/interval. This array is generated automatically * when you define a tick interval. * @property yTicks * @type int[] */ yTicks: null, /** * By default the drag and drop instance will only respond to the primary * button click (left button for a right-handed mouse). Set to true to * allow drag and drop to start with any mouse click that is propogated * by the browser * @property primaryButtonOnly * @type boolean */ primaryButtonOnly: true, /** * The availabe property is false until the linked dom element is accessible. * @property available * @type boolean */ available: false, /** * By default, drags can only be initiated if the mousedown occurs in the * region the linked element is. This is done in part to work around a * bug in some browsers that mis-report the mousedown if the previous * mouseup happened outside of the window. This property is set to true * if outer handles are defined. * * @property hasOuterHandles * @type boolean * @default false */ hasOuterHandles: false, /** * Property that is assigned to a drag and drop object when testing to * see if it is being targeted by another dd object. This property * can be used in intersect mode to help determine the focus of * the mouse interaction. DDM.getBestMatch uses this property first to * determine the closest match in INTERSECT mode when multiple targets * are part of the same interaction. * @property cursorIsOver * @type boolean */ cursorIsOver: false, /** * Property that is assigned to a drag and drop object when testing to * see if it is being targeted by another dd object. This is a region * that represents the area the draggable element overlaps this target. * DDM.getBestMatch uses this property to compare the size of the overlap * to that of other targets in order to determine the closest match in * INTERSECT mode when multiple targets are part of the same interaction. * @property overlap * @type YAHOO.util.Region */ overlap: null, /** * Code that executes immediately before the startDrag event * @method b4StartDrag * @private */ b4StartDrag: function(x, y) { }, /** * Abstract method called after a drag/drop object is clicked * and the drag or mousedown time thresholds have beeen met. * @method startDrag * @param {int} X click location * @param {int} Y click location */ startDrag: function(x, y) { /* override this */ }, /** * Code that executes immediately before the onDrag event * @method b4Drag * @private */ b4Drag: function(e) { }, /** * Abstract method called during the onMouseMove event while dragging an * object. * @method onDrag * @param {Event} e the mousemove event */ onDrag: function(e) { /* override this */ }, /** * Abstract method called when this element fist begins hovering over * another DragDrop obj * @method onDragEnter * @param {Event} e the mousemove event * @param {String|DragDrop[]} id In POINT mode, the element * id this is hovering over. In INTERSECT mode, an array of one or more * dragdrop items being hovered over. */ onDragEnter: function(e, id) { /* override this */ }, /** * Code that executes immediately before the onDragOver event * @method b4DragOver * @private */ b4DragOver: function(e) { }, /** * Abstract method called when this element is hovering over another * DragDrop obj * @method onDragOver * @param {Event} e the mousemove event * @param {String|DragDrop[]} id In POINT mode, the element * id this is hovering over. In INTERSECT mode, an array of dd items * being hovered over. */ onDragOver: function(e, id) { /* override this */ }, /** * Code that executes immediately before the onDragOut event * @method b4DragOut * @private */ b4DragOut: function(e) { }, /** * Abstract method called when we are no longer hovering over an element * @method onDragOut * @param {Event} e the mousemove event * @param {String|DragDrop[]} id In POINT mode, the element * id this was hovering over. In INTERSECT mode, an array of dd items * that the mouse is no longer over. */ onDragOut: function(e, id) { /* override this */ }, /** * Code that executes immediately before the onDragDrop event * @method b4DragDrop * @private */ b4DragDrop: function(e) { }, /** * Abstract method called when this item is dropped on another DragDrop * obj * @method onDragDrop * @param {Event} e the mouseup event * @param {String|DragDrop[]} id In POINT mode, the element * id this was dropped on. In INTERSECT mode, an array of dd items this * was dropped on. */ onDragDrop: function(e, id) { /* override this */ }, /** * Abstract method called when this item is dropped on an area with no * drop target * @method onInvalidDrop * @param {Event} e the mouseup event */ onInvalidDrop: function(e) { /* override this */ }, /** * Code that executes immediately before the endDrag event * @method b4EndDrag * @private */ b4EndDrag: function(e) { }, /** * Fired when we are done dragging the object * @method endDrag * @param {Event} e the mouseup event */ endDrag: function(e) { /* override this */ }, /** * Code executed immediately before the onMouseDown event * @method b4MouseDown * @param {Event} e the mousedown event * @private */ b4MouseDown: function(e) { }, /** * Event handler that fires when a drag/drop obj gets a mousedown * @method onMouseDown * @param {Event} e the mousedown event */ onMouseDown: function(e) { /* override this */ }, /** * Event handler that fires when a drag/drop obj gets a mouseup * @method onMouseUp * @param {Event} e the mouseup event */ onMouseUp: function(e) { /* override this */ }, /** * Override the onAvailable method to do what is needed after the initial * position was determined. * @method onAvailable */ onAvailable: function () { //this.logger.log("onAvailable (base)"); }, /** * Returns a reference to the linked element * @method getEl * @return {HTMLElement} the html element */ getEl: function() { if (!this._domRef) { this._domRef = Dom.get(this.id); } return this._domRef; }, /** * Returns a reference to the actual element to drag. By default this is * the same as the html element, but it can be assigned to another * element. An example of this can be found in YAHOO.util.DDProxy * @method getDragEl * @return {HTMLElement} the html element */ getDragEl: function() { return Dom.get(this.dragElId); }, /** * Sets up the DragDrop object. Must be called in the constructor of any * YAHOO.util.DragDrop subclass * @method init * @param id the id of the linked element * @param {String} sGroup the group of related items * @param {object} config configuration attributes */ init: function(id, sGroup, config) { this.initTarget(id, sGroup, config); Event.on(this._domRef || this.id, "mousedown", this.handleMouseDown, this, true); // Event.on(this.id, "selectstart", Event.preventDefault); for (var i in this.events) { this.createEvent(i + 'Event'); } }, /** * Initializes Targeting functionality only... the object does not * get a mousedown handler. * @method initTarget * @param id the id of the linked element * @param {String} sGroup the group of related items * @param {object} config configuration attributes */ initTarget: function(id, sGroup, config) { // configuration attributes this.config = config || {}; this.events = {}; // create a local reference to the drag and drop manager this.DDM = YAHOO.util.DDM; // initialize the groups object this.groups = {}; // assume that we have an element reference instead of an id if the // parameter is not a string if (typeof id !== "string") { YAHOO.log("id is not a string, assuming it is an HTMLElement"); this._domRef = id; id = Dom.generateId(id); } // set the id this.id = id; // add to an interaction group this.addToGroup((sGroup) ? sGroup : "default"); // We don't want to register this as the handle with the manager // so we just set the id rather than calling the setter. this.handleElId = id; Event.onAvailable(id, this.handleOnAvailable, this, true); // create a logger instance this.logger = (YAHOO.widget.LogWriter) ? new YAHOO.widget.LogWriter(this.toString()) : YAHOO; // the linked element is the element that gets dragged by default this.setDragElId(id); // by default, clicked anchors will not start drag operations. // @TODO what else should be here? Probably form fields. this.invalidHandleTypes = { A: "A" }; this.invalidHandleIds = {}; this.invalidHandleClasses = []; this.applyConfig(); }, /** * Applies the configuration parameters that were passed into the constructor. * This is supposed to happen at each level through the inheritance chain. So * a DDProxy implentation will execute apply config on DDProxy, DD, and * DragDrop in order to get all of the parameters that are available in * each object. * @method applyConfig */ applyConfig: function() { this.events = { mouseDown: true, b4MouseDown: true, mouseUp: true, b4StartDrag: true, startDrag: true, b4EndDrag: true, endDrag: true, drag: true, b4Drag: true, invalidDrop: true, b4DragOut: true, dragOut: true, dragEnter: true, b4DragOver: true, dragOver: true, b4DragDrop: true, dragDrop: true }; if (this.config.events) { for (var i in this.config.events) { if (this.config.events[i] === false) { this.events[i] = false; } } } // configurable properties: // padding, isTarget, maintainOffset, primaryButtonOnly this.padding = this.config.padding || [0, 0, 0, 0]; this.isTarget = (this.config.isTarget !== false); this.maintainOffset = (this.config.maintainOffset); this.primaryButtonOnly = (this.config.primaryButtonOnly !== false); this.dragOnly = ((this.config.dragOnly === true) ? true : false); this.useShim = ((this.config.useShim === true) ? true : false); }, /** * Executed when the linked element is available * @method handleOnAvailable * @private */ handleOnAvailable: function() { //this.logger.log("handleOnAvailable"); this.available = true; this.resetConstraints(); this.onAvailable(); }, /** * Configures the padding for the target zone in px. Effectively expands * (or reduces) the virtual object size for targeting calculations. * Supports css-style shorthand; if only one parameter is passed, all sides * will have that padding, and if only two are passed, the top and bottom * will have the first param, the left and right the second. * @method setPadding * @param {int} iTop Top pad * @param {int} iRight Right pad * @param {int} iBot Bot pad * @param {int} iLeft Left pad */ setPadding: function(iTop, iRight, iBot, iLeft) { // this.padding = [iLeft, iRight, iTop, iBot]; if (!iRight && 0 !== iRight) { this.padding = [iTop, iTop, iTop, iTop]; } else if (!iBot && 0 !== iBot) { this.padding = [iTop, iRight, iTop, iRight]; } else { this.padding = [iTop, iRight, iBot, iLeft]; } }, /** * Stores the initial placement of the linked element. * @method setInitialPosition * @param {int} diffX the X offset, default 0 * @param {int} diffY the Y offset, default 0 * @private */ setInitPosition: function(diffX, diffY) { var el = this.getEl(); if (!this.DDM.verifyEl(el)) { if (el && el.style && (el.style.display == 'none')) { this.logger.log(this.id + " can not get initial position, element style is display: none"); } else { this.logger.log(this.id + " element is broken"); } return; } var dx = diffX || 0; var dy = diffY || 0; var p = Dom.getXY( el ); this.initPageX = p[0] - dx; this.initPageY = p[1] - dy; this.lastPageX = p[0]; this.lastPageY = p[1]; this.logger.log(this.id + " initial position: " + this.initPageX + ", " + this.initPageY); this.setStartPosition(p); }, /** * Sets the start position of the element. This is set when the obj * is initialized, the reset when a drag is started. * @method setStartPosition * @param pos current position (from previous lookup) * @private */ setStartPosition: function(pos) { var p = pos || Dom.getXY(this.getEl()); this.deltaSetXY = null; this.startPageX = p[0]; this.startPageY = p[1]; }, /** * Add this instance to a group of related drag/drop objects. All * instances belong to at least one group, and can belong to as many * groups as needed. * @method addToGroup * @param sGroup {string} the name of the group */ addToGroup: function(sGroup) { this.groups[sGroup] = true; this.DDM.regDragDrop(this, sGroup); }, /** * Remove's this instance from the supplied interaction group * @method removeFromGroup * @param {string} sGroup The group to drop */ removeFromGroup: function(sGroup) { this.logger.log("Removing from group: " + sGroup); if (this.groups[sGroup]) { delete this.groups[sGroup]; } this.DDM.removeDDFromGroup(this, sGroup); }, /** * Allows you to specify that an element other than the linked element * will be moved with the cursor during a drag * @method setDragElId * @param id {string} the id of the element that will be used to initiate the drag */ setDragElId: function(id) { this.dragElId = id; }, /** * Allows you to specify a child of the linked element that should be * used to initiate the drag operation. An example of this would be if * you have a content div with text and links. Clicking anywhere in the * content area would normally start the drag operation. Use this method * to specify that an element inside of the content div is the element * that starts the drag operation. * @method setHandleElId * @param id {string} the id of the element that will be used to * initiate the drag. */ setHandleElId: function(id) { if (typeof id !== "string") { YAHOO.log("id is not a string, assuming it is an HTMLElement"); id = Dom.generateId(id); } this.handleElId = id; this.DDM.regHandle(this.id, id); }, /** * Allows you to set an element outside of the linked element as a drag * handle * @method setOuterHandleElId * @param id the id of the element that will be used to initiate the drag */ setOuterHandleElId: function(id) { if (typeof id !== "string") { YAHOO.log("id is not a string, assuming it is an HTMLElement"); id = Dom.generateId(id); } this.logger.log("Adding outer handle event: " + id); Event.on(id, "mousedown", this.handleMouseDown, this, true); this.setHandleElId(id); this.hasOuterHandles = true; }, /** * Remove all drag and drop hooks for this element * @method unreg */ unreg: function() { this.logger.log("DragDrop obj cleanup " + this.id); Event.removeListener(this.id, "mousedown", this.handleMouseDown); this._domRef = null; this.DDM._remove(this); }, /** * Returns true if this instance is locked, or the drag drop mgr is locked * (meaning that all drag/drop is disabled on the page.) * @method isLocked * @return {boolean} true if this obj or all drag/drop is locked, else * false */ isLocked: function() { return (this.DDM.isLocked() || this.locked); }, /** * Fired when this object is clicked * @method handleMouseDown * @param {Event} e * @param {YAHOO.util.DragDrop} oDD the clicked dd object (this dd obj) * @private */ handleMouseDown: function(e, oDD) { var button = e.which || e.button; this.logger.log("button: " + button); if (this.primaryButtonOnly && button > 1) { this.logger.log("Mousedown was not produced by the primary button"); return; } if (this.isLocked()) { this.logger.log("Drag and drop is disabled, aborting"); return; } this.logger.log("mousedown " + this.id); this.logger.log("firing onMouseDown events"); // firing the mousedown events prior to calculating positions var b4Return = this.b4MouseDown(e), b4Return2 = true; if (this.events.b4MouseDown) { b4Return2 = this.fireEvent('b4MouseDownEvent', e); } var mDownReturn = this.onMouseDown(e), mDownReturn2 = true; if (this.events.mouseDown) { if (mDownReturn === false) { //Fixes #2528759 - Mousedown function returned false, don't fire the event and cancel everything. mDownReturn2 = false; } else { mDownReturn2 = this.fireEvent('mouseDownEvent', e); } } if ((b4Return === false) || (mDownReturn === false) || (b4Return2 === false) || (mDownReturn2 === false)) { this.logger.log('b4MouseDown or onMouseDown returned false, exiting drag'); return; } this.DDM.refreshCache(this.groups); // var self = this; // setTimeout( function() { self.DDM.refreshCache(self.groups); }, 0); // Only process the event if we really clicked within the linked // element. The reason we make this check is that in the case that // another element was moved between the clicked element and the // cursor in the time between the mousedown and mouseup events. When // this happens, the element gets the next mousedown event // regardless of where on the screen it happened. var pt = new YAHOO.util.Point(Event.getPageX(e), Event.getPageY(e)); if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) { this.logger.log("Click was not over the element: " + this.id); } else { if (this.clickValidator(e)) { this.logger.log("click was a valid handle"); // set the initial element position this.setStartPosition(); // start tracking mousemove distance and mousedown time to // determine when to start the actual drag this.DDM.handleMouseDown(e, this); // this mousedown is mine this.DDM.stopEvent(e); } else { this.logger.log("clickValidator returned false, drag not initiated"); } } }, /** * @method clickValidator * @description Method validates that the clicked element * was indeed the handle or a valid child of the handle * @param {Event} e */ clickValidator: function(e) { var target = YAHOO.util.Event.getTarget(e); return ( this.isValidHandleChild(target) && (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) ); }, /** * Finds the location the element should be placed if we want to move * it to where the mouse location less the click offset would place us. * @method getTargetCoord * @param {int} iPageX the X coordinate of the click * @param {int} iPageY the Y coordinate of the click * @return an object that contains the coordinates (Object.x and Object.y) * @private */ getTargetCoord: function(iPageX, iPageY) { // this.logger.log("getTargetCoord: " + iPageX + ", " + iPageY); var x = iPageX - this.deltaX; var y = iPageY - this.deltaY; if (this.constrainX) { if (x < this.minX) { x = this.minX; } if (x > this.maxX) { x = this.maxX; } } if (this.constrainY) { if (y < this.minY) { y = this.minY; } if (y > this.maxY) { y = this.maxY; } } x = this.getTick(x, this.xTicks); y = this.getTick(y, this.yTicks); // this.logger.log("getTargetCoord " + // " iPageX: " + iPageX + // " iPageY: " + iPageY + // " x: " + x + ", y: " + y); return {x:x, y:y}; }, /** * Allows you to specify a tag name that should not start a drag operation * when clicked. This is designed to facilitate embedding links within a * drag handle that do something other than start the drag. * @method addInvalidHandleType * @param {string} tagName the type of element to exclude */ addInvalidHandleType: function(tagName) { var type = tagName.toUpperCase(); this.invalidHandleTypes[type] = type; }, /** * Lets you to specify an element id for a child of a drag handle * that should not initiate a drag * @method addInvalidHandleId * @param {string} id the element id of the element you wish to ignore */ addInvalidHandleId: function(id) { if (typeof id !== "string") { YAHOO.log("id is not a string, assuming it is an HTMLElement"); id = Dom.generateId(id); } this.invalidHandleIds[id] = id; }, /** * Lets you specify a css class of elements that will not initiate a drag * @method addInvalidHandleClass * @param {string} cssClass the class of the elements you wish to ignore */ addInvalidHandleClass: function(cssClass) { this.invalidHandleClasses.push(cssClass); }, /** * Unsets an excluded tag name set by addInvalidHandleType * @method removeInvalidHandleType * @param {string} tagName the type of element to unexclude */ removeInvalidHandleType: function(tagName) { var type = tagName.toUpperCase(); // this.invalidHandleTypes[type] = null; delete this.invalidHandleTypes[type]; }, /** * Unsets an invalid handle id * @method removeInvalidHandleId * @param {string} id the id of the element to re-enable */ removeInvalidHandleId: function(id) { if (typeof id !== "string") { YAHOO.log("id is not a string, assuming it is an HTMLElement"); id = Dom.generateId(id); } delete this.invalidHandleIds[id]; }, /** * Unsets an invalid css class * @method removeInvalidHandleClass * @param {string} cssClass the class of the element(s) you wish to * re-enable */ removeInvalidHandleClass: function(cssClass) { for (var i=0, len=this.invalidHandleClasses.length; i= this.minX; i = i - iTickSize) { if (!tickMap[i]) { this.xTicks[this.xTicks.length] = i; tickMap[i] = true; } } for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) { if (!tickMap[i]) { this.xTicks[this.xTicks.length] = i; tickMap[i] = true; } } this.xTicks.sort(this.DDM.numericSort) ; this.logger.log("xTicks: " + this.xTicks.join()); }, /** * Create the array of vertical tick marks if an interval was specified in * setYConstraint(). * @method setYTicks * @private */ setYTicks: function(iStartY, iTickSize) { // this.logger.log("setYTicks: " + iStartY + ", " + iTickSize // + ", " + this.initPageY + ", " + this.minY + ", " + this.maxY ); this.yTicks = []; this.yTickSize = iTickSize; var tickMap = {}; for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) { if (!tickMap[i]) { this.yTicks[this.yTicks.length] = i; tickMap[i] = true; } } for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) { if (!tickMap[i]) { this.yTicks[this.yTicks.length] = i; tickMap[i] = true; } } this.yTicks.sort(this.DDM.numericSort) ; this.logger.log("yTicks: " + this.yTicks.join()); }, /** * By default, the element can be dragged any place on the screen. Use * this method to limit the horizontal travel of the element. Pass in * 0,0 for the parameters if you want to lock the drag to the y axis. * @method setXConstraint * @param {int} iLeft the number of pixels the element can move to the left * @param {int} iRight the number of pixels the element can move to the * right * @param {int} iTickSize optional parameter for specifying that the * element * should move iTickSize pixels at a time. */ setXConstraint: function(iLeft, iRight, iTickSize) { this.leftConstraint = parseInt(iLeft, 10); this.rightConstraint = parseInt(iRight, 10); this.minX = this.initPageX - this.leftConstraint; this.maxX = this.initPageX + this.rightConstraint; if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); } this.constrainX = true; this.logger.log("initPageX:" + this.initPageX + " minX:" + this.minX + " maxX:" + this.maxX); }, /** * Clears any constraints applied to this instance. Also clears ticks * since they can't exist independent of a constraint at this time. * @method clearConstraints */ clearConstraints: function() { this.logger.log("Clearing constraints"); this.constrainX = false; this.constrainY = false; this.clearTicks(); }, /** * Clears any tick interval defined for this instance * @method clearTicks */ clearTicks: function() { this.logger.log("Clearing ticks"); this.xTicks = null; this.yTicks = null; this.xTickSize = 0; this.yTickSize = 0; }, /** * By default, the element can be dragged any place on the screen. Set * this to limit the vertical travel of the element. Pass in 0,0 for the * parameters if you want to lock the drag to the x axis. * @method setYConstraint * @param {int} iUp the number of pixels the element can move up * @param {int} iDown the number of pixels the element can move down * @param {int} iTickSize optional parameter for specifying that the * element should move iTickSize pixels at a time. */ setYConstraint: function(iUp, iDown, iTickSize) { this.logger.log("setYConstraint: " + iUp + "," + iDown + "," + iTickSize); this.topConstraint = parseInt(iUp, 10); this.bottomConstraint = parseInt(iDown, 10); this.minY = this.initPageY - this.topConstraint; this.maxY = this.initPageY + this.bottomConstraint; if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); } this.constrainY = true; this.logger.log("initPageY:" + this.initPageY + " minY:" + this.minY + " maxY:" + this.maxY); }, /** * resetConstraints must be called if you manually reposition a dd element. * @method resetConstraints */ resetConstraints: function() { //this.logger.log("resetConstraints"); // Maintain offsets if necessary if (this.initPageX || this.initPageX === 0) { //this.logger.log("init pagexy: " + this.initPageX + ", " + //this.initPageY); //this.logger.log("last pagexy: " + this.lastPageX + ", " + //this.lastPageY); // figure out how much this thing has moved var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0; var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0; this.setInitPosition(dx, dy); // This is the first time we have detected the element's position } else { this.setInitPosition(); } if (this.constrainX) { this.setXConstraint( this.leftConstraint, this.rightConstraint, this.xTickSize ); } if (this.constrainY) { this.setYConstraint( this.topConstraint, this.bottomConstraint, this.yTickSize ); } }, /** * Normally the drag element is moved pixel by pixel, but we can specify * that it move a number of pixels at a time. This method resolves the * location when we have it set up like this. * @method getTick * @param {int} val where we want to place the object * @param {int[]} tickArray sorted array of valid points * @return {int} the closest tick * @private */ getTick: function(val, tickArray) { if (!tickArray) { // If tick interval is not defined, it is effectively 1 pixel, // so we return the value passed to us. return val; } else if (tickArray[0] >= val) { // The value is lower than the first tick, so we return the first // tick. return tickArray[0]; } else { for (var i=0, len=tickArray.length; i= val) { var diff1 = val - tickArray[i]; var diff2 = tickArray[next] - val; return (diff2 > diff1) ? tickArray[i] : tickArray[next]; } } // The value is larger than the last tick, so we return the last // tick. return tickArray[tickArray.length - 1]; } }, /** * toString method * @method toString * @return {string} string representation of the dd obj */ toString: function() { return ("DragDrop " + this.id); } }; YAHOO.augment(YAHOO.util.DragDrop, YAHOO.util.EventProvider); /** * @event mouseDownEvent * @description Provides access to the mousedown event. The mousedown does not always result in a drag operation. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4MouseDownEvent * @description Provides access to the mousedown event, before the mouseDownEvent gets fired. Returning false will cancel the drag. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event mouseUpEvent * @description Fired from inside DragDropMgr when the drag operation is finished. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4StartDragEvent * @description Fires before the startDragEvent, returning false will cancel the startDrag Event. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event startDragEvent * @description Occurs after a mouse down and the drag threshold has been met. The drag threshold default is either 3 pixels of mouse movement or 1 full second of holding the mousedown. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4EndDragEvent * @description Fires before the endDragEvent. Returning false will cancel. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event endDragEvent * @description Fires on the mouseup event after a drag has been initiated (startDrag fired). * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragEvent * @description Occurs every mousemove event while dragging. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragEvent * @description Fires before the dragEvent. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event invalidDropEvent * @description Fires when the dragged objects is dropped in a location that contains no drop targets. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragOutEvent * @description Fires before the dragOutEvent * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragOutEvent * @description Fires when a dragged object is no longer over an object that had the onDragEnter fire. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragEnterEvent * @description Occurs when the dragged object first interacts with another targettable drag and drop object. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragOverEvent * @description Fires before the dragOverEvent. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragOverEvent * @description Fires every mousemove event while over a drag and drop object. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragDropEvent * @description Fires before the dragDropEvent * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragDropEvent * @description Fires when the dragged objects is dropped on another. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ })(); /** * A DragDrop implementation where the linked element follows the * mouse cursor during a drag. * @class DD * @extends YAHOO.util.DragDrop * @constructor * @param {String} id the id of the linked element * @param {String} sGroup the group of related DragDrop items * @param {object} config an object containing configurable attributes * Valid properties for DD: * scroll */ YAHOO.util.DD = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); } }; YAHOO.extend(YAHOO.util.DD, YAHOO.util.DragDrop, { /** * When set to true, the utility automatically tries to scroll the browser * window when a drag and drop element is dragged near the viewport boundary. * Defaults to true. * @property scroll * @type boolean */ scroll: true, /** * Sets the pointer offset to the distance between the linked element's top * left corner and the location the element was clicked * @method autoOffset * @param {int} iPageX the X coordinate of the click * @param {int} iPageY the Y coordinate of the click */ autoOffset: function(iPageX, iPageY) { var x = iPageX - this.startPageX; var y = iPageY - this.startPageY; this.setDelta(x, y); // this.logger.log("autoOffset el pos: " + aCoord + ", delta: " + x + "," + y); }, /** * Sets the pointer offset. You can call this directly to force the * offset to be in a particular location (e.g., pass in 0,0 to set it * to the center of the object, as done in YAHOO.widget.Slider) * @method setDelta * @param {int} iDeltaX the distance from the left * @param {int} iDeltaY the distance from the top */ setDelta: function(iDeltaX, iDeltaY) { this.deltaX = iDeltaX; this.deltaY = iDeltaY; this.logger.log("deltaX:" + this.deltaX + ", deltaY:" + this.deltaY); }, /** * Sets the drag element to the location of the mousedown or click event, * maintaining the cursor location relative to the location on the element * that was clicked. Override this if you want to place the element in a * location other than where the cursor is. * @method setDragElPos * @param {int} iPageX the X coordinate of the mousedown or drag event * @param {int} iPageY the Y coordinate of the mousedown or drag event */ setDragElPos: function(iPageX, iPageY) { // the first time we do this, we are going to check to make sure // the element has css positioning var el = this.getDragEl(); this.alignElWithMouse(el, iPageX, iPageY); }, /** * Sets the element to the location of the mousedown or click event, * maintaining the cursor location relative to the location on the element * that was clicked. Override this if you want to place the element in a * location other than where the cursor is. * @method alignElWithMouse * @param {HTMLElement} el the element to move * @param {int} iPageX the X coordinate of the mousedown or drag event * @param {int} iPageY the Y coordinate of the mousedown or drag event */ alignElWithMouse: function(el, iPageX, iPageY) { var oCoord = this.getTargetCoord(iPageX, iPageY); // this.logger.log("****alignElWithMouse : " + el.id + ", " + aCoord + ", " + el.style.display); if (!this.deltaSetXY) { var aCoord = [oCoord.x, oCoord.y]; YAHOO.util.Dom.setXY(el, aCoord); var newLeft = parseInt( YAHOO.util.Dom.getStyle(el, "left"), 10 ); var newTop = parseInt( YAHOO.util.Dom.getStyle(el, "top" ), 10 ); this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ]; } else { YAHOO.util.Dom.setStyle(el, "left", (oCoord.x + this.deltaSetXY[0]) + "px"); YAHOO.util.Dom.setStyle(el, "top", (oCoord.y + this.deltaSetXY[1]) + "px"); } this.cachePosition(oCoord.x, oCoord.y); var self = this; setTimeout(function() { self.autoScroll.call(self, oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth); }, 0); }, /** * Saves the most recent position so that we can reset the constraints and * tick marks on-demand. We need to know this so that we can calculate the * number of pixels the element is offset from its original position. * @method cachePosition * @param iPageX the current x position (optional, this just makes it so we * don't have to look it up again) * @param iPageY the current y position (optional, this just makes it so we * don't have to look it up again) */ cachePosition: function(iPageX, iPageY) { if (iPageX) { this.lastPageX = iPageX; this.lastPageY = iPageY; } else { var aCoord = YAHOO.util.Dom.getXY(this.getEl()); this.lastPageX = aCoord[0]; this.lastPageY = aCoord[1]; } }, /** * Auto-scroll the window if the dragged object has been moved beyond the * visible window boundary. * @method autoScroll * @param {int} x the drag element's x position * @param {int} y the drag element's y position * @param {int} h the height of the drag element * @param {int} w the width of the drag element * @private */ autoScroll: function(x, y, h, w) { if (this.scroll) { // The client height var clientH = this.DDM.getClientHeight(); // The client width var clientW = this.DDM.getClientWidth(); // The amt scrolled down var st = this.DDM.getScrollTop(); // The amt scrolled right var sl = this.DDM.getScrollLeft(); // Location of the bottom of the element var bot = h + y; // Location of the right of the element var right = w + x; // The distance from the cursor to the bottom of the visible area, // adjusted so that we don't scroll if the cursor is beyond the // element drag constraints var toBot = (clientH + st - y - this.deltaY); // The distance from the cursor to the right of the visible area var toRight = (clientW + sl - x - this.deltaX); // this.logger.log( " x: " + x + " y: " + y + " h: " + h + // " clientH: " + clientH + " clientW: " + clientW + // " st: " + st + " sl: " + sl + " bot: " + bot + // " right: " + right + " toBot: " + toBot + " toRight: " + toRight); // How close to the edge the cursor must be before we scroll // var thresh = (document.all) ? 100 : 40; var thresh = 40; // How many pixels to scroll per autoscroll op. This helps to reduce // clunky scrolling. IE is more sensitive about this ... it needs this // value to be higher. var scrAmt = (document.all) ? 80 : 30; // Scroll down if we are near the bottom of the visible page and the // obj extends below the crease if ( bot > clientH && toBot < thresh ) { window.scrollTo(sl, st + scrAmt); } // Scroll up if the window is scrolled down and the top of the object // goes above the top border if ( y < st && st > 0 && y - st < thresh ) { window.scrollTo(sl, st - scrAmt); } // Scroll right if the obj is beyond the right border and the cursor is // near the border. if ( right > clientW && toRight < thresh ) { window.scrollTo(sl + scrAmt, st); } // Scroll left if the window has been scrolled to the right and the obj // extends past the left border if ( x < sl && sl > 0 && x - sl < thresh ) { window.scrollTo(sl - scrAmt, st); } } }, /* * Sets up config options specific to this class. Overrides * YAHOO.util.DragDrop, but all versions of this method through the * inheritance chain are called */ applyConfig: function() { YAHOO.util.DD.superclass.applyConfig.call(this); this.scroll = (this.config.scroll !== false); }, /* * Event that fires prior to the onMouseDown event. Overrides * YAHOO.util.DragDrop. */ b4MouseDown: function(e) { this.setStartPosition(); // this.resetConstraints(); this.autoOffset(YAHOO.util.Event.getPageX(e), YAHOO.util.Event.getPageY(e)); }, /* * Event that fires prior to the onDrag event. Overrides * YAHOO.util.DragDrop. */ b4Drag: function(e) { this.setDragElPos(YAHOO.util.Event.getPageX(e), YAHOO.util.Event.getPageY(e)); }, toString: function() { return ("DD " + this.id); } ////////////////////////////////////////////////////////////////////////// // Debugging ygDragDrop events that can be overridden ////////////////////////////////////////////////////////////////////////// /* startDrag: function(x, y) { this.logger.log(this.id.toString() + " startDrag"); }, onDrag: function(e) { this.logger.log(this.id.toString() + " onDrag"); }, onDragEnter: function(e, id) { this.logger.log(this.id.toString() + " onDragEnter: " + id); }, onDragOver: function(e, id) { this.logger.log(this.id.toString() + " onDragOver: " + id); }, onDragOut: function(e, id) { this.logger.log(this.id.toString() + " onDragOut: " + id); }, onDragDrop: function(e, id) { this.logger.log(this.id.toString() + " onDragDrop: " + id); }, endDrag: function(e) { this.logger.log(this.id.toString() + " endDrag"); } */ /** * @event mouseDownEvent * @description Provides access to the mousedown event. The mousedown does not always result in a drag operation. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4MouseDownEvent * @description Provides access to the mousedown event, before the mouseDownEvent gets fired. Returning false will cancel the drag. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event mouseUpEvent * @description Fired from inside DragDropMgr when the drag operation is finished. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4StartDragEvent * @description Fires before the startDragEvent, returning false will cancel the startDrag Event. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event startDragEvent * @description Occurs after a mouse down and the drag threshold has been met. The drag threshold default is either 3 pixels of mouse movement or 1 full second of holding the mousedown. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4EndDragEvent * @description Fires before the endDragEvent. Returning false will cancel. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event endDragEvent * @description Fires on the mouseup event after a drag has been initiated (startDrag fired). * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragEvent * @description Occurs every mousemove event while dragging. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragEvent * @description Fires before the dragEvent. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event invalidDropEvent * @description Fires when the dragged objects is dropped in a location that contains no drop targets. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragOutEvent * @description Fires before the dragOutEvent * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragOutEvent * @description Fires when a dragged object is no longer over an object that had the onDragEnter fire. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragEnterEvent * @description Occurs when the dragged object first interacts with another targettable drag and drop object. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragOverEvent * @description Fires before the dragOverEvent. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragOverEvent * @description Fires every mousemove event while over a drag and drop object. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragDropEvent * @description Fires before the dragDropEvent * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragDropEvent * @description Fires when the dragged objects is dropped on another. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ }); /** * A DragDrop implementation that inserts an empty, bordered div into * the document that follows the cursor during drag operations. At the time of * the click, the frame div is resized to the dimensions of the linked html * element, and moved to the exact location of the linked element. * * References to the "frame" element refer to the single proxy element that * was created to be dragged in place of all DDProxy elements on the * page. * * @class DDProxy * @extends YAHOO.util.DD * @constructor * @param {String} id the id of the linked html element * @param {String} sGroup the group of related DragDrop objects * @param {object} config an object containing configurable attributes * Valid properties for DDProxy in addition to those in DragDrop: * resizeFrame, centerFrame, dragElId */ YAHOO.util.DDProxy = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); this.initFrame(); } }; /** * The default drag frame div id * @property YAHOO.util.DDProxy.dragElId * @type String * @static */ YAHOO.util.DDProxy.dragElId = "ygddfdiv"; YAHOO.extend(YAHOO.util.DDProxy, YAHOO.util.DD, { /** * By default we resize the drag frame to be the same size as the element * we want to drag (this is to get the frame effect). We can turn it off * if we want a different behavior. * @property resizeFrame * @type boolean */ resizeFrame: true, /** * By default the frame is positioned exactly where the drag element is, so * we use the cursor offset provided by YAHOO.util.DD. Another option that works only if * you do not have constraints on the obj is to have the drag frame centered * around the cursor. Set centerFrame to true for this effect. * @property centerFrame * @type boolean */ centerFrame: false, /** * Creates the proxy element if it does not yet exist * @method createFrame */ createFrame: function() { var self=this, body=document.body; if (!body || !body.firstChild) { setTimeout( function() { self.createFrame(); }, 50 ); return; } var div=this.getDragEl(), Dom=YAHOO.util.Dom; if (!div) { div = document.createElement("div"); div.id = this.dragElId; var s = div.style; s.position = "absolute"; s.visibility = "hidden"; s.cursor = "move"; s.border = "2px solid #aaa"; s.zIndex = 999; s.height = "25px"; s.width = "25px"; var _data = document.createElement('div'); Dom.setStyle(_data, 'height', '100%'); Dom.setStyle(_data, 'width', '100%'); /** * If the proxy element has no background-color, then it is considered to the "transparent" by Internet Explorer. * Since it is "transparent" then the events pass through it to the iframe below. * So creating a "fake" div inside the proxy element and giving it a background-color, then setting it to an * opacity of 0, it appears to not be there, however IE still thinks that it is so the events never pass through. */ Dom.setStyle(_data, 'background-color', '#ccc'); Dom.setStyle(_data, 'opacity', '0'); div.appendChild(_data); // appendChild can blow up IE if invoked prior to the window load event // while rendering a table. It is possible there are other scenarios // that would cause this to happen as well. body.insertBefore(div, body.firstChild); } }, /** * Initialization for the drag frame element. Must be called in the * constructor of all subclasses * @method initFrame */ initFrame: function() { this.createFrame(); }, applyConfig: function() { //this.logger.log("DDProxy applyConfig"); YAHOO.util.DDProxy.superclass.applyConfig.call(this); this.resizeFrame = (this.config.resizeFrame !== false); this.centerFrame = (this.config.centerFrame); this.setDragElId(this.config.dragElId || YAHOO.util.DDProxy.dragElId); }, /** * Resizes the drag frame to the dimensions of the clicked object, positions * it over the object, and finally displays it * @method showFrame * @param {int} iPageX X click position * @param {int} iPageY Y click position * @private */ showFrame: function(iPageX, iPageY) { var el = this.getEl(); var dragEl = this.getDragEl(); var s = dragEl.style; this._resizeProxy(); if (this.centerFrame) { this.setDelta( Math.round(parseInt(s.width, 10)/2), Math.round(parseInt(s.height, 10)/2) ); } this.setDragElPos(iPageX, iPageY); YAHOO.util.Dom.setStyle(dragEl, "visibility", "visible"); }, /** * The proxy is automatically resized to the dimensions of the linked * element when a drag is initiated, unless resizeFrame is set to false * @method _resizeProxy * @private */ _resizeProxy: function() { if (this.resizeFrame) { var DOM = YAHOO.util.Dom; var el = this.getEl(); var dragEl = this.getDragEl(); var bt = parseInt( DOM.getStyle(dragEl, "borderTopWidth" ), 10); var br = parseInt( DOM.getStyle(dragEl, "borderRightWidth" ), 10); var bb = parseInt( DOM.getStyle(dragEl, "borderBottomWidth" ), 10); var bl = parseInt( DOM.getStyle(dragEl, "borderLeftWidth" ), 10); if (isNaN(bt)) { bt = 0; } if (isNaN(br)) { br = 0; } if (isNaN(bb)) { bb = 0; } if (isNaN(bl)) { bl = 0; } this.logger.log("proxy size: " + bt + " " + br + " " + bb + " " + bl); var newWidth = Math.max(0, el.offsetWidth - br - bl); var newHeight = Math.max(0, el.offsetHeight - bt - bb); this.logger.log("Resizing proxy element"); DOM.setStyle( dragEl, "width", newWidth + "px" ); DOM.setStyle( dragEl, "height", newHeight + "px" ); } }, // overrides YAHOO.util.DragDrop b4MouseDown: function(e) { this.setStartPosition(); var x = YAHOO.util.Event.getPageX(e); var y = YAHOO.util.Event.getPageY(e); this.autoOffset(x, y); // This causes the autoscroll code to kick off, which means autoscroll can // happen prior to the check for a valid drag handle. // this.setDragElPos(x, y); }, // overrides YAHOO.util.DragDrop b4StartDrag: function(x, y) { // show the drag frame this.logger.log("start drag show frame, x: " + x + ", y: " + y); this.showFrame(x, y); }, // overrides YAHOO.util.DragDrop b4EndDrag: function(e) { this.logger.log(this.id + " b4EndDrag"); YAHOO.util.Dom.setStyle(this.getDragEl(), "visibility", "hidden"); }, // overrides YAHOO.util.DragDrop // By default we try to move the element to the last location of the frame. // This is so that the default behavior mirrors that of YAHOO.util.DD. endDrag: function(e) { var DOM = YAHOO.util.Dom; this.logger.log(this.id + " endDrag"); var lel = this.getEl(); var del = this.getDragEl(); // Show the drag frame briefly so we can get its position // del.style.visibility = ""; DOM.setStyle(del, "visibility", ""); // Hide the linked element before the move to get around a Safari // rendering bug. //lel.style.visibility = "hidden"; DOM.setStyle(lel, "visibility", "hidden"); YAHOO.util.DDM.moveToEl(lel, del); //del.style.visibility = "hidden"; DOM.setStyle(del, "visibility", "hidden"); //lel.style.visibility = ""; DOM.setStyle(lel, "visibility", ""); }, toString: function() { return ("DDProxy " + this.id); } /** * @event mouseDownEvent * @description Provides access to the mousedown event. The mousedown does not always result in a drag operation. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4MouseDownEvent * @description Provides access to the mousedown event, before the mouseDownEvent gets fired. Returning false will cancel the drag. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event mouseUpEvent * @description Fired from inside DragDropMgr when the drag operation is finished. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4StartDragEvent * @description Fires before the startDragEvent, returning false will cancel the startDrag Event. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event startDragEvent * @description Occurs after a mouse down and the drag threshold has been met. The drag threshold default is either 3 pixels of mouse movement or 1 full second of holding the mousedown. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4EndDragEvent * @description Fires before the endDragEvent. Returning false will cancel. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event endDragEvent * @description Fires on the mouseup event after a drag has been initiated (startDrag fired). * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragEvent * @description Occurs every mousemove event while dragging. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragEvent * @description Fires before the dragEvent. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event invalidDropEvent * @description Fires when the dragged objects is dropped in a location that contains no drop targets. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragOutEvent * @description Fires before the dragOutEvent * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragOutEvent * @description Fires when a dragged object is no longer over an object that had the onDragEnter fire. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragEnterEvent * @description Occurs when the dragged object first interacts with another targettable drag and drop object. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragOverEvent * @description Fires before the dragOverEvent. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragOverEvent * @description Fires every mousemove event while over a drag and drop object. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event b4DragDropEvent * @description Fires before the dragDropEvent * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ /** * @event dragDropEvent * @description Fires when the dragged objects is dropped on another. * @type YAHOO.util.CustomEvent See Element.addListener for more information on listening for this event. */ }); /** * A DragDrop implementation that does not move, but can be a drop * target. You would get the same result by simply omitting implementation * for the event callbacks, but this way we reduce the processing cost of the * event listener and the callbacks. * @class DDTarget * @extends YAHOO.util.DragDrop * @constructor * @param {String} id the id of the element that is a drop target * @param {String} sGroup the group of related DragDrop objects * @param {object} config an object containing configurable attributes * Valid properties for DDTarget in addition to those in * DragDrop: * none */ YAHOO.util.DDTarget = function(id, sGroup, config) { if (id) { this.initTarget(id, sGroup, config); } }; // YAHOO.util.DDTarget.prototype = new YAHOO.util.DragDrop(); YAHOO.extend(YAHOO.util.DDTarget, YAHOO.util.DragDrop, { toString: function() { return ("DDTarget " + this.id); } }); YAHOO.register("dragdrop", YAHOO.util.DragDropMgr, {version: "2.9.0", build: "2800"}); /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ /** * Provides Attribute configurations. * @namespace YAHOO.util * @class Attribute * @constructor * @param hash {Object} The intial Attribute. * @param {YAHOO.util.AttributeProvider} The owner of the Attribute instance. */ YAHOO.util.Attribute = function(hash, owner) { if (owner) { this.owner = owner; this.configure(hash, true); } }; YAHOO.util.Attribute.INVALID_VALUE = {}; YAHOO.util.Attribute.prototype = { /** * The name of the attribute. * @property name * @type String */ name: undefined, /** * The value of the attribute. * @property value * @type String */ value: null, /** * The owner of the attribute. * @property owner * @type YAHOO.util.AttributeProvider */ owner: null, /** * Whether or not the attribute is read only. * @property readOnly * @type Boolean */ readOnly: false, /** * Whether or not the attribute can only be written once. * @property writeOnce * @type Boolean */ writeOnce: false, /** * The attribute's initial configuration. * @private * @property _initialConfig * @type Object */ _initialConfig: null, /** * Whether or not the attribute's value has been set. * @private * @property _written * @type Boolean */ _written: false, /** * A function to call when setting the attribute's value. * The method receives the new value as the first arg and the attribute name as the 2nd * @property method * @type Function */ method: null, /** * The function to use when setting the attribute's value. * The setter receives the new value as the first arg and the attribute name as the 2nd * The return value of the setter replaces the value passed to set(). * @property setter * @type Function */ setter: null, /** * The function to use when getting the attribute's value. * The getter receives the new value as the first arg and the attribute name as the 2nd * The return value of the getter will be used as the return from get(). * @property getter * @type Function */ getter: null, /** * The validator to use when setting the attribute's value. * @property validator * @type Function * @return Boolean */ validator: null, /** * Retrieves the current value of the attribute. * @method getValue * @return {any} The current value of the attribute. */ getValue: function() { var val = this.value; if (this.getter) { val = this.getter.call(this.owner, this.name, val); } return val; }, /** * Sets the value of the attribute and fires beforeChange and change events. * @method setValue * @param {Any} value The value to apply to the attribute. * @param {Boolean} silent If true the change events will not be fired. * @return {Boolean} Whether or not the value was set. */ setValue: function(value, silent) { var beforeRetVal, owner = this.owner, name = this.name, invalidValue = YAHOO.util.Attribute.INVALID_VALUE, event = { type: name, prevValue: this.getValue(), newValue: value }; if (this.readOnly || ( this.writeOnce && this._written) ) { YAHOO.log( 'setValue ' + name + ', ' + value + ' failed: read only', 'error', 'Attribute'); return false; // write not allowed } if (this.validator && !this.validator.call(owner, value) ) { YAHOO.log( 'setValue ' + name + ', ' + value + ' validation failed', 'error', 'Attribute'); return false; // invalid value } if (!silent) { beforeRetVal = owner.fireBeforeChangeEvent(event); if (beforeRetVal === false) { YAHOO.log('setValue ' + name + ' cancelled by beforeChange event', 'info', 'Attribute'); return false; } } if (this.setter) { value = this.setter.call(owner, value, this.name); if (value === undefined) { YAHOO.log('setter for ' + this.name + ' returned undefined', 'warn', 'Attribute'); } if (value === invalidValue) { return false; } } if (this.method) { if (this.method.call(owner, value, this.name) === invalidValue) { return false; } } this.value = value; // TODO: set before calling setter/method? this._written = true; event.type = name; if (!silent) { this.owner.fireChangeEvent(event); } return true; }, /** * Allows for configuring the Attribute's properties. * @method configure * @param {Object} map A key-value map of Attribute properties. * @param {Boolean} init Whether or not this should become the initial config. */ configure: function(map, init) { map = map || {}; if (init) { this._written = false; // reset writeOnce } this._initialConfig = this._initialConfig || {}; for (var key in map) { if ( map.hasOwnProperty(key) ) { this[key] = map[key]; if (init) { this._initialConfig[key] = map[key]; } } } }, /** * Resets the value to the initial config value. * @method resetValue * @return {Boolean} Whether or not the value was set. */ resetValue: function() { return this.setValue(this._initialConfig.value); }, /** * Resets the attribute config to the initial config state. * @method resetConfig */ resetConfig: function() { this.configure(this._initialConfig, true); }, /** * Resets the value to the current value. * Useful when values may have gotten out of sync with actual properties. * @method refresh * @return {Boolean} Whether or not the value was set. */ refresh: function(silent) { this.setValue(this.value, silent); } }; (function() { var Lang = YAHOO.util.Lang; /* Copyright (c) 2006, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ /** * Provides and manages YAHOO.util.Attribute instances * @namespace YAHOO.util * @class AttributeProvider * @uses YAHOO.util.EventProvider */ YAHOO.util.AttributeProvider = function() {}; YAHOO.util.AttributeProvider.prototype = { /** * A key-value map of Attribute configurations * @property _configs * @protected (may be used by subclasses and augmentors) * @private * @type {Object} */ _configs: null, /** * Returns the current value of the attribute. * @method get * @param {String} key The attribute whose value will be returned. * @return {Any} The current value of the attribute. */ get: function(key){ this._configs = this._configs || {}; var config = this._configs[key]; if (!config || !this._configs.hasOwnProperty(key)) { YAHOO.log(key + ' not found', 'error', 'AttributeProvider'); return null; } return config.getValue(); }, /** * Sets the value of a config. * @method set * @param {String} key The name of the attribute * @param {Any} value The value to apply to the attribute * @param {Boolean} silent Whether or not to suppress change events * @return {Boolean} Whether or not the value was set. */ set: function(key, value, silent){ this._configs = this._configs || {}; var config = this._configs[key]; if (!config) { YAHOO.log('set failed: ' + key + ' not found', 'error', 'AttributeProvider'); return false; } return config.setValue(value, silent); }, /** * Returns an array of attribute names. * @method getAttributeKeys * @return {Array} An array of attribute names. */ getAttributeKeys: function(){ this._configs = this._configs; var keys = [], key; for (key in this._configs) { if ( Lang.hasOwnProperty(this._configs, key) && !Lang.isUndefined(this._configs[key]) ) { keys[keys.length] = key; } } return keys; }, /** * Sets multiple attribute values. * @method setAttributes * @param {Object} map A key-value map of attributes * @param {Boolean} silent Whether or not to suppress change events */ setAttributes: function(map, silent){ for (var key in map) { if ( Lang.hasOwnProperty(map, key) ) { this.set(key, map[key], silent); } } }, /** * Resets the specified attribute's value to its initial value. * @method resetValue * @param {String} key The name of the attribute * @param {Boolean} silent Whether or not to suppress change events * @return {Boolean} Whether or not the value was set */ resetValue: function(key, silent){ this._configs = this._configs || {}; if (this._configs[key]) { this.set(key, this._configs[key]._initialConfig.value, silent); return true; } return false; }, /** * Sets the attribute's value to its current value. * @method refresh * @param {String | Array} key The attribute(s) to refresh * @param {Boolean} silent Whether or not to suppress change events */ refresh: function(key, silent) { this._configs = this._configs || {}; var configs = this._configs; key = ( ( Lang.isString(key) ) ? [key] : key ) || this.getAttributeKeys(); for (var i = 0, len = key.length; i < len; ++i) { if (configs.hasOwnProperty(key[i])) { this._configs[key[i]].refresh(silent); } } }, /** * Adds an Attribute to the AttributeProvider instance. * @method register * @param {String} key The attribute's name * @param {Object} map A key-value map containing the * attribute's properties. * @deprecated Use setAttributeConfig */ register: function(key, map) { this.setAttributeConfig(key, map); }, /** * Returns the attribute's properties. * @method getAttributeConfig * @param {String} key The attribute's name * @private * @return {object} A key-value map containing all of the * attribute's properties. */ getAttributeConfig: function(key) { this._configs = this._configs || {}; var config = this._configs[key] || {}; var map = {}; // returning a copy to prevent overrides for (key in config) { if ( Lang.hasOwnProperty(config, key) ) { map[key] = config[key]; } } return map; }, /** * Sets or updates an Attribute instance's properties. * @method setAttributeConfig * @param {String} key The attribute's name. * @param {Object} map A key-value map of attribute properties * @param {Boolean} init Whether or not this should become the intial config. */ setAttributeConfig: function(key, map, init) { this._configs = this._configs || {}; map = map || {}; if (!this._configs[key]) { map.name = key; this._configs[key] = this.createAttribute(map); } else { this._configs[key].configure(map, init); } }, /** * Sets or updates an Attribute instance's properties. * @method configureAttribute * @param {String} key The attribute's name. * @param {Object} map A key-value map of attribute properties * @param {Boolean} init Whether or not this should become the intial config. * @deprecated Use setAttributeConfig */ configureAttribute: function(key, map, init) { this.setAttributeConfig(key, map, init); }, /** * Resets an attribute to its intial configuration. * @method resetAttributeConfig * @param {String} key The attribute's name. * @private */ resetAttributeConfig: function(key){ this._configs = this._configs || {}; this._configs[key].resetConfig(); }, // wrapper for EventProvider.subscribe // to create events on the fly subscribe: function(type, callback) { this._events = this._events || {}; if ( !(type in this._events) ) { this._events[type] = this.createEvent(type); } YAHOO.util.EventProvider.prototype.subscribe.apply(this, arguments); }, on: function() { this.subscribe.apply(this, arguments); }, addListener: function() { this.subscribe.apply(this, arguments); }, /** * Fires the attribute's beforeChange event. * @method fireBeforeChangeEvent * @param {String} key The attribute's name. * @param {Obj} e The event object to pass to handlers. */ fireBeforeChangeEvent: function(e) { var type = 'before'; type += e.type.charAt(0).toUpperCase() + e.type.substr(1) + 'Change'; e.type = type; return this.fireEvent(e.type, e); }, /** * Fires the attribute's change event. * @method fireChangeEvent * @param {String} key The attribute's name. * @param {Obj} e The event object to pass to the handlers. */ fireChangeEvent: function(e) { e.type += 'Change'; return this.fireEvent(e.type, e); }, createAttribute: function(map) { return new YAHOO.util.Attribute(map, this); } }; YAHOO.augment(YAHOO.util.AttributeProvider, YAHOO.util.EventProvider); })(); (function() { // internal shorthand var Dom = YAHOO.util.Dom, AttributeProvider = YAHOO.util.AttributeProvider, specialTypes = { mouseenter: true, mouseleave: true }; /** * Element provides an wrapper object to simplify adding * event listeners, using dom methods, and managing attributes. * @module element * @namespace YAHOO.util * @requires yahoo, dom, event */ /** * Element provides an wrapper object to simplify adding * event listeners, using dom methods, and managing attributes. * @class Element * @uses YAHOO.util.AttributeProvider * @constructor * @param el {HTMLElement | String} The html element that * represents the Element. * @param {Object} map A key-value map of initial config names and values */ var Element = function(el, map) { this.init.apply(this, arguments); }; Element.DOM_EVENTS = { 'click': true, 'dblclick': true, 'keydown': true, 'keypress': true, 'keyup': true, 'mousedown': true, 'mousemove': true, 'mouseout': true, 'mouseover': true, 'mouseup': true, 'mouseenter': true, 'mouseleave': true, 'focus': true, 'blur': true, 'submit': true, 'change': true }; Element.prototype = { /** * Dom events supported by the Element instance. * @property DOM_EVENTS * @type Object */ DOM_EVENTS: null, DEFAULT_HTML_SETTER: function(value, key) { var el = this.get('element'); if (el) { el[key] = value; } return value; }, DEFAULT_HTML_GETTER: function(key) { var el = this.get('element'), val; if (el) { val = el[key]; } return val; }, /** * Wrapper for HTMLElement method. * @method appendChild * @param {YAHOO.util.Element || HTMLElement} child The element to append. * @return {HTMLElement} The appended DOM element. */ appendChild: function(child) { child = child.get ? child.get('element') : child; return this.get('element').appendChild(child); }, /** * Wrapper for HTMLElement method. * @method getElementsByTagName * @param {String} tag The tagName to collect * @return {HTMLCollection} A collection of DOM elements. */ getElementsByTagName: function(tag) { return this.get('element').getElementsByTagName(tag); }, /** * Wrapper for HTMLElement method. * @method hasChildNodes * @return {Boolean} Whether or not the element has childNodes */ hasChildNodes: function() { return this.get('element').hasChildNodes(); }, /** * Wrapper for HTMLElement method. * @method insertBefore * @param {HTMLElement} element The HTMLElement to insert * @param {HTMLElement} before The HTMLElement to insert * the element before. * @return {HTMLElement} The inserted DOM element. */ insertBefore: function(element, before) { element = element.get ? element.get('element') : element; before = (before && before.get) ? before.get('element') : before; return this.get('element').insertBefore(element, before); }, /** * Wrapper for HTMLElement method. * @method removeChild * @param {HTMLElement} child The HTMLElement to remove * @return {HTMLElement} The removed DOM element. */ removeChild: function(child) { child = child.get ? child.get('element') : child; return this.get('element').removeChild(child); }, /** * Wrapper for HTMLElement method. * @method replaceChild * @param {HTMLElement} newNode The HTMLElement to insert * @param {HTMLElement} oldNode The HTMLElement to replace * @return {HTMLElement} The replaced DOM element. */ replaceChild: function(newNode, oldNode) { newNode = newNode.get ? newNode.get('element') : newNode; oldNode = oldNode.get ? oldNode.get('element') : oldNode; return this.get('element').replaceChild(newNode, oldNode); }, /** * Registers Element specific attributes. * @method initAttributes * @param {Object} map A key-value map of initial attribute configs */ initAttributes: function(map) { }, /** * Adds a listener for the given event. These may be DOM or * customEvent listeners. Any event that is fired via fireEvent * can be listened for. All handlers receive an event object. * @method addListener * @param {String} type The name of the event to listen for * @param {Function} fn The handler to call when the event fires * @param {Any} obj A variable to pass to the handler * @param {Object} scope The object to use for the scope of the handler */ addListener: function(type, fn, obj, scope) { scope = scope || this; var Event = YAHOO.util.Event, el = this.get('element') || this.get('id'), self = this; if (specialTypes[type] && !Event._createMouseDelegate) { YAHOO.log("Using a " + type + " event requires the event-mouseenter module", "error", "Event"); return false; } if (!this._events[type]) { // create on the fly if (el && this.DOM_EVENTS[type]) { Event.on(el, type, function(e, matchedEl) { // Supplement IE with target, currentTarget relatedTarget if (e.srcElement && !e.target) { e.target = e.srcElement; } if ((e.toElement && !e.relatedTarget) || (e.fromElement && !e.relatedTarget)) { e.relatedTarget = Event.getRelatedTarget(e); } if (!e.currentTarget) { e.currentTarget = el; } // Note: matchedEl el is passed back for delegated listeners self.fireEvent(type, e, matchedEl); }, obj, scope); } this.createEvent(type, {scope: this}); } return YAHOO.util.EventProvider.prototype.subscribe.apply(this, arguments); // notify via customEvent }, /** * Alias for addListener * @method on * @param {String} type The name of the event to listen for * @param {Function} fn The function call when the event fires * @param {Any} obj A variable to pass to the handler * @param {Object} scope The object to use for the scope of the handler */ on: function() { return this.addListener.apply(this, arguments); }, /** * Alias for addListener * @method subscribe * @param {String} type The name of the event to listen for * @param {Function} fn The function call when the event fires * @param {Any} obj A variable to pass to the handler * @param {Object} scope The object to use for the scope of the handler */ subscribe: function() { return this.addListener.apply(this, arguments); }, /** * Remove an event listener * @method removeListener * @param {String} type The name of the event to listen for * @param {Function} fn The function call when the event fires */ removeListener: function(type, fn) { return this.unsubscribe.apply(this, arguments); }, /** * Wrapper for Dom method. * @method addClass * @param {String} className The className to add */ addClass: function(className) { Dom.addClass(this.get('element'), className); }, /** * Wrapper for Dom method. * @method getElementsByClassName * @param {String} className The className to collect * @param {String} tag (optional) The tag to use in * conjunction with class name * @return {Array} Array of HTMLElements */ getElementsByClassName: function(className, tag) { return Dom.getElementsByClassName(className, tag, this.get('element') ); }, /** * Wrapper for Dom method. * @method hasClass * @param {String} className The className to add * @return {Boolean} Whether or not the element has the class name */ hasClass: function(className) { return Dom.hasClass(this.get('element'), className); }, /** * Wrapper for Dom method. * @method removeClass * @param {String} className The className to remove */ removeClass: function(className) { return Dom.removeClass(this.get('element'), className); }, /** * Wrapper for Dom method. * @method replaceClass * @param {String} oldClassName The className to replace * @param {String} newClassName The className to add */ replaceClass: function(oldClassName, newClassName) { return Dom.replaceClass(this.get('element'), oldClassName, newClassName); }, /** * Wrapper for Dom method. * @method setStyle * @param {String} property The style property to set * @param {String} value The value to apply to the style property */ setStyle: function(property, value) { return Dom.setStyle(this.get('element'), property, value); // TODO: always queuing? }, /** * Wrapper for Dom method. * @method getStyle * @param {String} property The style property to retrieve * @return {String} The current value of the property */ getStyle: function(property) { return Dom.getStyle(this.get('element'), property); }, /** * Apply any queued set calls. * @method fireQueue */ fireQueue: function() { var queue = this._queue; for (var i = 0, len = queue.length; i < len; ++i) { this[queue[i][0]].apply(this, queue[i][1]); } }, /** * Appends the HTMLElement into either the supplied parentNode. * @method appendTo * @param {HTMLElement | Element} parentNode The node to append to * @param {HTMLElement | Element} before An optional node to insert before * @return {HTMLElement} The appended DOM element. */ appendTo: function(parent, before) { parent = (parent.get) ? parent.get('element') : Dom.get(parent); this.fireEvent('beforeAppendTo', { type: 'beforeAppendTo', target: parent }); before = (before && before.get) ? before.get('element') : Dom.get(before); var element = this.get('element'); if (!element) { YAHOO.log('appendTo failed: element not available', 'error', 'Element'); return false; } if (!parent) { YAHOO.log('appendTo failed: parent not available', 'error', 'Element'); return false; } if (element.parent != parent) { if (before) { parent.insertBefore(element, before); } else { parent.appendChild(element); } } YAHOO.log(element + 'appended to ' + parent); this.fireEvent('appendTo', { type: 'appendTo', target: parent }); return element; }, get: function(key) { var configs = this._configs || {}, el = configs.element; // avoid loop due to 'element' if (el && !configs[key] && !YAHOO.lang.isUndefined(el.value[key]) ) { this._setHTMLAttrConfig(key); } return AttributeProvider.prototype.get.call(this, key); }, setAttributes: function(map, silent) { // set based on configOrder var done = {}, configOrder = this._configOrder; // set based on configOrder for (var i = 0, len = configOrder.length; i < len; ++i) { if (map[configOrder[i]] !== undefined) { done[configOrder[i]] = true; this.set(configOrder[i], map[configOrder[i]], silent); } } // unconfigured (e.g. Dom attributes) for (var att in map) { if (map.hasOwnProperty(att) && !done[att]) { this.set(att, map[att], silent); } } }, set: function(key, value, silent) { var el = this.get('element'); if (!el) { this._queue[this._queue.length] = ['set', arguments]; if (this._configs[key]) { this._configs[key].value = value; // so "get" works while queueing } return; } // set it on the element if not configured and is an HTML attribute if ( !this._configs[key] && !YAHOO.lang.isUndefined(el[key]) ) { this._setHTMLAttrConfig(key); } return AttributeProvider.prototype.set.apply(this, arguments); }, setAttributeConfig: function(key, map, init) { this._configOrder.push(key); AttributeProvider.prototype.setAttributeConfig.apply(this, arguments); }, createEvent: function(type, config) { this._events[type] = true; return AttributeProvider.prototype.createEvent.apply(this, arguments); }, init: function(el, attr) { this._initElement(el, attr); }, destroy: function() { var el = this.get('element'); YAHOO.util.Event.purgeElement(el, true); // purge DOM listeners recursively this.unsubscribeAll(); // unsubscribe all custom events if (el && el.parentNode) { el.parentNode.removeChild(el); // pull from the DOM } // revert initial configs this._queue = []; this._events = {}; this._configs = {}; this._configOrder = []; }, _initElement: function(el, attr) { this._queue = this._queue || []; this._events = this._events || {}; this._configs = this._configs || {}; this._configOrder = []; attr = attr || {}; attr.element = attr.element || el || null; var isReady = false; // to determine when to init HTMLElement and content var DOM_EVENTS = Element.DOM_EVENTS; this.DOM_EVENTS = this.DOM_EVENTS || {}; for (var event in DOM_EVENTS) { if (DOM_EVENTS.hasOwnProperty(event)) { this.DOM_EVENTS[event] = DOM_EVENTS[event]; } } if (typeof attr.element === 'string') { // register ID for get() access this._setHTMLAttrConfig('id', { value: attr.element }); } if (Dom.get(attr.element)) { isReady = true; this._initHTMLElement(attr); this._initContent(attr); } YAHOO.util.Event.onAvailable(attr.element, function() { if (!isReady) { // otherwise already done this._initHTMLElement(attr); } this.fireEvent('available', { type: 'available', target: Dom.get(attr.element) }); }, this, true); YAHOO.util.Event.onContentReady(attr.element, function() { if (!isReady) { // otherwise already done this._initContent(attr); } this.fireEvent('contentReady', { type: 'contentReady', target: Dom.get(attr.element) }); }, this, true); }, _initHTMLElement: function(attr) { /** * The HTMLElement the Element instance refers to. * @attribute element * @type HTMLElement */ this.setAttributeConfig('element', { value: Dom.get(attr.element), readOnly: true }); }, _initContent: function(attr) { this.initAttributes(attr); this.setAttributes(attr, true); this.fireQueue(); }, /** * Sets the value of the property and fires beforeChange and change events. * @private * @method _setHTMLAttrConfig * @param {YAHOO.util.Element} element The Element instance to * register the config to. * @param {String} key The name of the config to register * @param {Object} map A key-value map of the config's params */ _setHTMLAttrConfig: function(key, map) { var el = this.get('element'); map = map || {}; map.name = key; map.setter = map.setter || this.DEFAULT_HTML_SETTER; map.getter = map.getter || this.DEFAULT_HTML_GETTER; map.value = map.value || el[key]; this._configs[key] = new YAHOO.util.Attribute(map, this); } }; /** * Fires when the Element's HTMLElement can be retrieved by Id. *

    See: Element.addListener

    *

    Event fields:
    * <String> type available
    * <HTMLElement> * target the HTMLElement bound to this Element instance
    *

    Usage:
    * var handler = function(e) {var target = e.target};
    * myTabs.addListener('available', handler);

    * @event available */ /** * Fires when the Element's HTMLElement subtree is rendered. *

    See: Element.addListener

    *

    Event fields:
    * <String> type contentReady
    * <HTMLElement> * target the HTMLElement bound to this Element instance
    *

    Usage:
    * var handler = function(e) {var target = e.target};
    * myTabs.addListener('contentReady', handler);

    * @event contentReady */ /** * Fires before the Element is appended to another Element. *

    See: Element.addListener

    *

    Event fields:
    * <String> type beforeAppendTo
    * <HTMLElement/Element> * target the HTMLElement/Element being appended to *

    Usage:
    * var handler = function(e) {var target = e.target};
    * myTabs.addListener('beforeAppendTo', handler);

    * @event beforeAppendTo */ /** * Fires after the Element is appended to another Element. *

    See: Element.addListener

    *

    Event fields:
    * <String> type appendTo
    * <HTMLElement/Element> * target the HTMLElement/Element being appended to *

    Usage:
    * var handler = function(e) {var target = e.target};
    * myTabs.addListener('appendTo', handler);

    * @event appendTo */ YAHOO.augment(Element, AttributeProvider); YAHOO.util.Element = Element; })(); YAHOO.register("element", YAHOO.util.Element, {version: "2.9.0", build: "2800"}); /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ /** * Provides a mechanism to fetch remote resources and * insert them into a document * This utility can fetch JavaScript and CSS files, inserting script * tags for script and link tags for CSS. Note, this * is done via the normal browser mechanisms for inserting * these resources and making the content available to * code that would access it. Be careful when retreiving * remote resources. Only use this utility to fetch * files from sites you trust. * * @module get * @requires yahoo */ /** * Fetches and inserts one or more script or link nodes into the document. * This utility can fetch JavaScript and CSS files, inserting script * tags for script and link tags for CSS. Note, this * is done via the normal browser mechanisms for inserting * these resources and making the content available to * code that would access it. Be careful when retreiving * remote resources. Only use this utility to fetch * files from sites you trust. * * @namespace YAHOO.util * @class YAHOO.util.Get */ YAHOO.util.Get = function() { /** * hash of queues to manage multiple requests * @property queues * @private */ var queues={}, /** * queue index used to generate transaction ids * @property qidx * @type int * @private */ qidx=0, /** * node index used to generate unique node ids * @property nidx * @type int * @private */ nidx=0, /** * interal property used to prevent multiple simultaneous purge * processes * @property purging * @type boolean * @private */ _purging=false, ua=YAHOO.env.ua, lang=YAHOO.lang, _fail, _purge, _track, /** * Generates an HTML element, this is not appended to a document * @method _node * @param type {string} the type of element * @param attr {string} the attributes * @param win {Window} optional window to create the element in * @return {HTMLElement} the generated node * @private */ _node = function(type, attr, win) { var w = win || window, d=w.document, n=d.createElement(type), i; for (i in attr) { if (attr.hasOwnProperty(i)) { n.setAttribute(i, attr[i]); } } return n; }, /** * Generates a link node * @method _linkNode * @param url {string} the url for the css file * @param win {Window} optional window to create the node in * @return {HTMLElement} the generated node * @private */ _linkNode = function(url, win, attributes) { var o = { id: "yui__dyn_" + (nidx++), type: "text/css", rel: "stylesheet", href: url }; if (attributes) { lang.augmentObject(o, attributes); } return _node("link", o, win); }, /** * Generates a script node * @method _scriptNode * @param url {string} the url for the script file * @param win {Window} optional window to create the node in * @return {HTMLElement} the generated node * @private */ _scriptNode = function(url, win, attributes) { var o = { id: "yui__dyn_" + (nidx++), type: "text/javascript", src: url }; if (attributes) { lang.augmentObject(o, attributes); } return _node("script", o, win); }, /** * Returns the data payload for callback functions * @method _returnData * @private */ _returnData = function(q, msg) { return { tId: q.tId, win: q.win, data: q.data, nodes: q.nodes, msg: msg, purge: function() { _purge(this.tId); } }; }, _get = function(nId, tId) { var q = queues[tId], n = (lang.isString(nId)) ? q.win.document.getElementById(nId) : nId; if (!n) { _fail(tId, "target node not found: " + nId); } return n; }, /** * The request is complete, so executing the requester's callback * @method _finish * @param id {string} the id of the request * @private */ _finish = function(id) { YAHOO.log("Finishing transaction " + id); var q = queues[id], msg, context; q.finished = true; if (q.aborted) { msg = "transaction " + id + " was aborted"; _fail(id, msg); return; } // execute success callback if (q.onSuccess) { context = q.scope || q.win; q.onSuccess.call(context, _returnData(q)); } }, /** * Timeout detected * @method _timeout * @param id {string} the id of the request * @private */ _timeout = function(id) { YAHOO.log("Timeout " + id, "info", "get"); var q = queues[id], context; if (q.onTimeout) { context = q.scope || q; q.onTimeout.call(context, _returnData(q)); } }, /** * Loads the next item for a given request * @method _next * @param id {string} the id of the request * @param loaded {string} the url that was just loaded, if any * @private */ _next = function(id, loaded) { YAHOO.log("_next: " + id + ", loaded: " + loaded, "info", "Get"); var q = queues[id], w=q.win, d=w.document, h=d.getElementsByTagName("head")[0], n, msg, url, s, extra; if (q.timer) { // Y.log('cancel timer'); q.timer.cancel(); } if (q.aborted) { msg = "transaction " + id + " was aborted"; _fail(id, msg); return; } if (loaded) { q.url.shift(); if (q.varName) { q.varName.shift(); } } else { // This is the first pass: make sure the url is an array q.url = (lang.isString(q.url)) ? [q.url] : q.url; if (q.varName) { q.varName = (lang.isString(q.varName)) ? [q.varName] : q.varName; } } if (q.url.length === 0) { // Safari 2.x workaround - There is no way to know when // a script is ready in versions of Safari prior to 3.x. // Adding an extra node reduces the problem, but doesn't // eliminate it completely because the browser executes // them asynchronously. if (q.type === "script" && ua.webkit && ua.webkit < 420 && !q.finalpass && !q.varName) { // Add another script node. This does not guarantee that the // scripts will execute in order, but it does appear to fix the // problem on fast connections more effectively than using an // arbitrary timeout. It is possible that the browser does // block subsequent script execution in this case for a limited // time. extra = _scriptNode(null, q.win, q.attributes); extra.innerHTML='YAHOO.util.Get._finalize("' + id + '");'; q.nodes.push(extra); h.appendChild(extra); } else { _finish(id); } return; } url = q.url[0]; // if the url is undefined, this is probably a trailing comma problem in IE if (!url) { q.url.shift(); YAHOO.log('skipping empty url'); return _next(id); } YAHOO.log("attempting to load " + url, "info", "Get"); if (q.timeout) { // Y.log('create timer'); q.timer = lang.later(q.timeout, q, _timeout, id); } if (q.type === "script") { n = _scriptNode(url, w, q.attributes); } else { n = _linkNode(url, w, q.attributes); } // track this node's load progress _track(q.type, n, id, url, w, q.url.length); // add the node to the queue so we can return it to the user supplied callback q.nodes.push(n); // add it to the head or insert it before 'insertBefore' if (q.insertBefore) { s = _get(q.insertBefore, id); if (s) { s.parentNode.insertBefore(n, s); } } else { h.appendChild(n); } YAHOO.log("Appending node: " + url, "info", "Get"); // FireFox does not support the onload event for link nodes, so there is // no way to make the css requests synchronous. This means that the css // rules in multiple files could be applied out of order in this browser // if a later request returns before an earlier one. Safari too. if ((ua.webkit || ua.gecko) && q.type === "css") { _next(id, url); } }, /** * Removes processed queues and corresponding nodes * @method _autoPurge * @private */ _autoPurge = function() { if (_purging) { return; } _purging = true; var i, q; for (i in queues) { if (queues.hasOwnProperty(i)) { q = queues[i]; if (q.autopurge && q.finished) { _purge(q.tId); delete queues[i]; } } } _purging = false; }, /** * Saves the state for the request and begins loading * the requested urls * @method queue * @param type {string} the type of node to insert * @param url {string} the url to load * @param opts the hash of options for this request * @private */ _queue = function(type, url, opts) { var id = "q" + (qidx++), q; opts = opts || {}; if (qidx % YAHOO.util.Get.PURGE_THRESH === 0) { _autoPurge(); } queues[id] = lang.merge(opts, { tId: id, type: type, url: url, finished: false, aborted: false, nodes: [] }); q = queues[id]; q.win = q.win || window; q.scope = q.scope || q.win; q.autopurge = ("autopurge" in q) ? q.autopurge : (type === "script") ? true : false; q.attributes = q.attributes || {}; q.attributes.charset = opts.charset || q.attributes.charset || 'utf-8'; lang.later(0, q, _next, id); return { tId: id }; }; /** * Detects when a node has been loaded. In the case of * script nodes, this does not guarantee that contained * script is ready to use. * @method _track * @param type {string} the type of node to track * @param n {HTMLElement} the node to track * @param id {string} the id of the request * @param url {string} the url that is being loaded * @param win {Window} the targeted window * @param qlength the number of remaining items in the queue, * including this one * @param trackfn {Function} function to execute when finished * the default is _next * @private */ _track = function(type, n, id, url, win, qlength, trackfn) { var f = trackfn || _next, rs, q, a, freq, w, l, i, msg; // IE supports the readystatechange event for script and css nodes if (ua.ie) { n.onreadystatechange = function() { rs = this.readyState; if ("loaded" === rs || "complete" === rs) { YAHOO.log(id + " onload " + url, "info", "Get"); n.onreadystatechange = null; f(id, url); } }; // webkit prior to 3.x is problemmatic } else if (ua.webkit) { if (type === "script") { // Safari 3.x supports the load event for script nodes (DOM2) if (ua.webkit >= 420) { n.addEventListener("load", function() { YAHOO.log(id + " DOM2 onload " + url, "info", "Get"); f(id, url); }); // Nothing can be done with Safari < 3.x except to pause and hope // for the best, particularly after last script is inserted. The // scripts will always execute in the order they arrive, not // necessarily the order in which they were inserted. To support // script nodes with complete reliability in these browsers, script // nodes either need to invoke a function in the window once they // are loaded or the implementer needs to provide a well-known // property that the utility can poll for. } else { // Poll for the existence of the named variable, if it // was supplied. q = queues[id]; if (q.varName) { freq = YAHOO.util.Get.POLL_FREQ; YAHOO.log("Polling for " + q.varName[0]); q.maxattempts = YAHOO.util.Get.TIMEOUT/freq; q.attempts = 0; q._cache = q.varName[0].split("."); q.timer = lang.later(freq, q, function(o) { a = this._cache; l = a.length; w = this.win; for (i=0; i this.maxattempts) { msg = "Over retry limit, giving up"; q.timer.cancel(); _fail(id, msg); } else { YAHOO.log(a[i] + " failed, retrying"); } return; } } YAHOO.log("Safari poll complete"); q.timer.cancel(); f(id, url); }, null, true); } else { lang.later(YAHOO.util.Get.POLL_FREQ, null, f, [id, url]); } } } // FireFox and Opera support onload (but not DOM2 in FF) handlers for // script nodes. Opera, but not FF, supports the onload event for link // nodes. } else { n.onload = function() { YAHOO.log(id + " onload " + url, "info", "Get"); f(id, url); }; } }; /* * The request failed, execute fail handler with whatever * was accomplished. There isn't a failure case at the * moment unless you count aborted transactions * @method _fail * @param id {string} the id of the request * @private */ _fail = function(id, msg) { YAHOO.log("get failure: " + msg, "warn", "Get"); var q = queues[id], context; // execute failure callback if (q.onFailure) { context = q.scope || q.win; q.onFailure.call(context, _returnData(q, msg)); } }; /** * Removes the nodes for the specified queue * @method _purge * @private */ _purge = function(tId) { if (queues[tId]) { var q = queues[tId], nodes = q.nodes, l = nodes.length, d = q.win.document, h = d.getElementsByTagName("head")[0], sib, i, node, attr; if (q.insertBefore) { sib = _get(q.insertBefore, tId); if (sib) { h = sib.parentNode; } } for (i=0; i *
    onSuccess
    *
    * callback to execute when the script(s) are finished loading * The callback receives an object back with the following * data: *
    *
    win
    *
    the window the script(s) were inserted into
    *
    data
    *
    the data object passed in when the request was made
    *
    nodes
    *
    An array containing references to the nodes that were * inserted
    *
    purge
    *
    A function that, when executed, will remove the nodes * that were inserted
    *
    *
    *
    *
    onFailure
    *
    * callback to execute when the script load operation fails * The callback receives an object back with the following * data: *
    *
    win
    *
    the window the script(s) were inserted into
    *
    data
    *
    the data object passed in when the request was made
    *
    nodes
    *
    An array containing references to the nodes that were * inserted successfully
    *
    purge
    *
    A function that, when executed, will remove any nodes * that were inserted
    *
    *
    *
    *
    onTimeout
    *
    * callback to execute when a timeout occurs. * The callback receives an object back with the following * data: *
    *
    win
    *
    the window the script(s) were inserted into
    *
    data
    *
    the data object passed in when the request was made
    *
    nodes
    *
    An array containing references to the nodes that were * inserted
    *
    purge
    *
    A function that, when executed, will remove the nodes * that were inserted
    *
    *
    *
    *
    scope
    *
    the execution context for the callbacks
    *
    win
    *
    a window other than the one the utility occupies
    *
    autopurge
    *
    * setting to true will let the utilities cleanup routine purge * the script once loaded *
    *
    data
    *
    * data that is supplied to the callback when the script(s) are * loaded. *
    *
    varName
    *
    * variable that should be available when a script is finished * loading. Used to help Safari 2.x and below with script load * detection. The type of this property should match what was * passed into the url parameter: if loading a single url, a * string can be supplied. If loading multiple scripts, you * must supply an array that contains the variable name for * each script. *
    *
    insertBefore
    *
    node or node id that will become the new node's nextSibling
    * *
    charset
    *
    Node charset, deprecated, use 'attributes'
    *
    attributes
    *
    A hash of attributes to apply to dynamic nodes.
    *
    timeout
    *
    Number of milliseconds to wait before aborting and firing the timeout event
    *
             * // assumes yahoo, dom, and event are already on the page
             *   YAHOO.util.Get.script(
             *   ["http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js",
             *    "http://yui.yahooapis.com/2.7.0/build/animation/animation-min.js"], {
             *     onSuccess: function(o) {
             *       YAHOO.log(o.data); // foo
             *       new YAHOO.util.DDProxy("dd1"); // also new o.reference("dd1"); would work
             *       this.log("won't cause error because YAHOO is the scope");
             *       this.log(o.nodes.length === 2) // true
             *       // o.purge(); // optionally remove the script nodes immediately
             *     },
             *     onFailure: function(o) {
             *       YAHOO.log("transaction failed");
             *     },
             *     data: "foo",
             *     timeout: 10000, // 10 second timeout
             *     scope: YAHOO,
             *     // win: otherframe // target another window/frame
             *     autopurge: true // allow the utility to choose when to remove the nodes
             *   });
             * 
    * @return {tId: string} an object containing info about the transaction */ script: function(url, opts) { return _queue("script", url, opts); }, /** * Fetches and inserts one or more css link nodes into the * head of the current document or the document in a specified * window. * @method css * @static * @param url {string} the url or urls to the css file(s) * @param opts Options: *
    *
    onSuccess
    *
    * callback to execute when the css file(s) are finished loading * The callback receives an object back with the following * data: *
    win
    *
    the window the link nodes(s) were inserted into
    *
    data
    *
    the data object passed in when the request was made
    *
    nodes
    *
    An array containing references to the nodes that were * inserted
    *
    purge
    *
    A function that, when executed, will remove the nodes * that were inserted
    *
    *
    * *
    scope
    *
    the execution context for the callbacks
    *
    win
    *
    a window other than the one the utility occupies
    *
    data
    *
    * data that is supplied to the callbacks when the nodes(s) are * loaded. *
    *
    insertBefore
    *
    node or node id that will become the new node's nextSibling
    *
    charset
    *
    Node charset, deprecated, use 'attributes'
    *
    attributes
    *
    A hash of attributes to apply to dynamic nodes.
    * *
             *      YAHOO.util.Get.css("http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css");
             * 
    *
             *      YAHOO.util.Get.css(["http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css",
             *                          "http://yui.yahooapis.com/2.7.0/build/logger/assets/skins/sam/logger.css"]);
             * 
    * @return {tId: string} an object containing info about the transaction */ css: function(url, opts) { return _queue("css", url, opts); } }; }(); YAHOO.register("get", YAHOO.util.Get, {version: "2.9.0", build: "2800"}); /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ /** * The YAHOO object is the single global object used by YUI Library. It * contains utility function for setting up namespaces, inheritance, and * logging. YAHOO.util, YAHOO.widget, and YAHOO.example are namespaces * created automatically for and used by the library. * @module yahoo * @title YAHOO Global */ /** * YAHOO_config is not included as part of the library. Instead it is an * object that can be defined by the implementer immediately before * including the YUI library. The properties included in this object * will be used to configure global properties needed as soon as the * library begins to load. * @class YAHOO_config * @static */ /** * A reference to a function that will be executed every time a YAHOO module * is loaded. As parameter, this function will receive the version * information for the module. See * YAHOO.env.getVersion for the description of the version data structure. * @property listener * @type Function * @static * @default undefined */ /** * Set to true if the library will be dynamically loaded after window.onload. * Defaults to false * @property injecting * @type boolean * @static * @default undefined */ /** * Instructs the yuiloader component to dynamically load yui components and * their dependencies. See the yuiloader documentation for more information * about dynamic loading * @property load * @static * @default undefined * @see yuiloader */ /** * Forces the use of the supplied locale where applicable in the library * @property locale * @type string * @static * @default undefined */ if (typeof YAHOO == "undefined" || !YAHOO) { /** * The YAHOO global namespace object. If YAHOO is already defined, the * existing YAHOO object will not be overwritten so that defined * namespaces are preserved. * @class YAHOO * @static */ var YAHOO = {}; } /** * Returns the namespace specified and creates it if it doesn't exist *
     * YAHOO.namespace("property.package");
     * YAHOO.namespace("YAHOO.property.package");
     * 
    * Either of the above would create YAHOO.property, then * YAHOO.property.package * * Be careful when naming packages. Reserved words may work in some browsers * and not others. For instance, the following will fail in Safari: *
     * YAHOO.namespace("really.long.nested.namespace");
     * 
    * This fails because "long" is a future reserved word in ECMAScript * * For implementation code that uses YUI, do not create your components * in the namespaces defined by YUI ( * YAHOO.util, * YAHOO.widget, * YAHOO.lang, * YAHOO.tool, * YAHOO.example, * YAHOO.env) -- create your own namespace (e.g., 'companyname'). * * @method namespace * @static * @param {String*} arguments 1-n namespaces to create * @return {Object} A reference to the last namespace object created */ YAHOO.namespace = function() { var a=arguments, o=null, i, j, d; for (i=0; i *
    name:
    The name of the module
    *
    version:
    The version in use
    *
    build:
    The build number in use
    *
    versions:
    All versions that were registered
    *
    builds:
    All builds that were registered.
    *
    mainClass:
    An object that was was stamped with the * current version and build. If * mainClass.VERSION != version or mainClass.BUILD != build, * multiple versions of pieces of the library have been * loaded, potentially causing issues.
    * * * @method getVersion * @static * @param {String} name the name of the module (event, slider, etc) * @return {Object} The version info */ YAHOO.env.getVersion = function(name) { return YAHOO.env.modules[name] || null; }; /** * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. YAHOO.env.ua stores a version * number for the browser engine, 0 otherwise. This value may or may not map * to the version number of the browser using the engine. The value is * presented as a float so that it can easily be used for boolean evaluation * as well as for looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost (e.g., Gecko 1.8.0.9 * reports 1.8). * @class YAHOO.env.ua * @static */ /** * parses a user agent string (or looks for one in navigator to parse if * not supplied). * @method parseUA * @since 2.9.0 * @static */ YAHOO.env.parseUA = function(agent) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, nav = navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 *
             * Firefox 1.0.0.4: 1.7.8   <-- Reports 1.7
             * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8
             * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81
             * Firefox 3.0   <-- 1.9
             * Firefox 3.5   <-- 1.91
             * 
    * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 *
             * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the
             *                                   latest available for Mac OSX 10.3.
             * Safari 2.0.2:         416     <-- hasOwnProperty introduced
             * Safari 2.0.4:         418     <-- preventDefault fixed
             * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run
             *                                   different versions of webkit
             * Safari 2.0.4 (419.3): 419     <-- Tiger installations that have been
             *                                   updated, but not updated
             *                                   to the latest patch.
             * Webkit 212 nightly:   522+    <-- Safari 3.0 precursor (with native
             * SVG and many major issues fixed).
             * Safari 3.0.4 (523.12) 523.12  <-- First Tiger release - automatic
             * update from 2.x via the 10.4.11 OS patch.
             * Webkit nightly 1/2008:525+    <-- Supports DOMContentLoaded event.
             *                                   yahoo.com user agent hack removed.
             * 
    * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @static */ os: null }, ua = agent || (navigator && navigator.userAgent), loc = window && window.location, href = loc && loc.href, m; o.secure = href && (href.toLowerCase().indexOf("https") === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh/i).test(ua)) { o.os = 'macintosh'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/); if (m) { // Nokia N-series, Android, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { o.mobile = 'Android'; m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } } m = ua.match(/Chrome\/([^\s]*)/); if (m && m[1]) { o.chrome = numberify(m[1]); // Chrome } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } return o; }; YAHOO.env.ua = YAHOO.env.parseUA(); /* * Initializes the global by creating the default namespaces and applying * any new configuration information that is detected. This is the setup * for env. * @method init * @static * @private */ (function() { YAHOO.namespace("util", "widget", "example"); /*global YAHOO_config*/ if ("undefined" !== typeof YAHOO_config) { var l=YAHOO_config.listener, ls=YAHOO.env.listeners,unique=true, i; if (l) { // if YAHOO is loaded multiple times we need to check to see if // this is a new config object. If it is, add the new component // load listener to the stack for (i=0; i': '>', '"': '"', "'": ''', '/': '/', '`': '`' }, // ADD = ["toString", "valueOf", "hasOwnProperty"], ADD = ["toString", "valueOf"], OB = { /** * Determines wheather or not the provided object is an array. * @method isArray * @param {any} o The object being testing * @return {boolean} the result */ isArray: function(o) { return OP.toString.apply(o) === ARRAY_TOSTRING; }, /** * Determines whether or not the provided object is a boolean * @method isBoolean * @param {any} o The object being testing * @return {boolean} the result */ isBoolean: function(o) { return typeof o === 'boolean'; }, /** * Determines whether or not the provided object is a function. * Note: Internet Explorer thinks certain functions are objects: * * var obj = document.createElement("object"); * YAHOO.lang.isFunction(obj.getAttribute) // reports false in IE * * var input = document.createElement("input"); // append to body * YAHOO.lang.isFunction(input.focus) // reports false in IE * * You will have to implement additional tests if these functions * matter to you. * * @method isFunction * @param {any} o The object being testing * @return {boolean} the result */ isFunction: function(o) { return (typeof o === 'function') || OP.toString.apply(o) === FUNCTION_TOSTRING; }, /** * Determines whether or not the provided object is null * @method isNull * @param {any} o The object being testing * @return {boolean} the result */ isNull: function(o) { return o === null; }, /** * Determines whether or not the provided object is a legal number * @method isNumber * @param {any} o The object being testing * @return {boolean} the result */ isNumber: function(o) { return typeof o === 'number' && isFinite(o); }, /** * Determines whether or not the provided object is of type object * or function * @method isObject * @param {any} o The object being testing * @return {boolean} the result */ isObject: function(o) { return (o && (typeof o === 'object' || L.isFunction(o))) || false; }, /** * Determines whether or not the provided object is a string * @method isString * @param {any} o The object being testing * @return {boolean} the result */ isString: function(o) { return typeof o === 'string'; }, /** * Determines whether or not the provided object is undefined * @method isUndefined * @param {any} o The object being testing * @return {boolean} the result */ isUndefined: function(o) { return typeof o === 'undefined'; }, /** * IE will not enumerate native functions in a derived object even if the * function was overridden. This is a workaround for specific functions * we care about on the Object prototype. * @property _IEEnumFix * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @static * @private */ _IEEnumFix: (YAHOO.env.ua.ie) ? function(r, s) { var i, fname, f; for (i=0;i * Returns a copy of the specified string with special HTML characters * escaped. The following characters will be converted to their * corresponding character entities: * & < > " ' / ` *

    * *

    * This implementation is based on the * OWASP * HTML escaping recommendations. In addition to the characters * in the OWASP recommendation, we also escape the ` * character, since IE interprets it as an attribute delimiter when used in * innerHTML. *

    * * @method escapeHTML * @param {String} html String to escape. * @return {String} Escaped string. * @static * @since 2.9.0 */ escapeHTML: function (html) { return html.replace(/[&<>"'\/`]/g, function (match) { return HTML_CHARS[match]; }); }, /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @static * @param {Function} subc the object to modify * @param {Function} superc the object to inherit * @param {Object} overrides additional properties/methods to add to the * subclass prototype. These will override the * matching items obtained from the superclass * if present. */ extend: function(subc, superc, overrides) { if (!superc||!subc) { throw new Error("extend failed, please check that " + "all dependencies are included."); } var F = function() {}, i; F.prototype=superc.prototype; subc.prototype=new F(); subc.prototype.constructor=subc; subc.superclass=superc.prototype; if (superc.prototype.constructor == OP.constructor) { superc.prototype.constructor=superc; } if (overrides) { for (i in overrides) { if (L.hasOwnProperty(overrides, i)) { subc.prototype[i]=overrides[i]; } } L._IEEnumFix(subc.prototype, overrides); } }, /** * Applies all properties in the supplier to the receiver if the * receiver does not have these properties yet. Optionally, one or * more methods/properties can be specified (as additional * parameters). This option will overwrite the property if receiver * has it already. If true is passed as the third parameter, all * properties will be applied and _will_ overwrite properties in * the receiver. * * @method augmentObject * @static * @since 2.3.0 * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param {String*|boolean} arguments zero or more properties methods * to augment the receiver with. If none specified, everything * in the supplier will be used unless it would * overwrite an existing property in the receiver. If true * is specified as the third parameter, all properties will * be applied and will overwrite an existing property in * the receiver */ augmentObject: function(r, s) { if (!s||!r) { throw new Error("Absorb failed, verify dependencies."); } var a=arguments, i, p, overrideList=a[2]; if (overrideList && overrideList!==true) { // only absorb the specified properties for (i=2; i 0) ? L.dump(o[i], d-1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push("]"); // objects {k1 => v1, k2 => v2} } else { s.push("{"); for (i in o) { if (L.hasOwnProperty(o, i)) { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d-1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } } if (s.length > 1) { s.pop(); } s.push("}"); } return s.join(""); }, /** * Does variable substitution on a string. It scans through the string * looking for expressions enclosed in { } braces. If an expression * is found, it is used a key on the object. If there is a space in * the key, the first word is used for the key and the rest is provided * to an optional function to be used to programatically determine the * value (the extra information might be used for this decision). If * the value for the key in the object, or what is returned from the * function has a string value, number value, or object value, it is * substituted for the bracket expression and it repeats. If this * value is an object, it uses the Object's toString() if this has * been overridden, otherwise it does a shallow dump of the key/value * pairs. * * By specifying the recurse option, the string is rescanned after * every replacement, allowing for nested template substitutions. * The side effect of this option is that curly braces in the * replacement content must be encoded. * * @method substitute * @since 2.3.0 * @param s {String} The string that will be modified. * @param o {Object} An object containing the replacement values * @param f {Function} An optional function that can be used to * process each match. It receives the key, * value, and any extra metadata included with * the key inside of the braces. * @param recurse {boolean} default true - if not false, the replaced * string will be rescanned so that nested substitutions are possible. * @return {String} the substituted string */ substitute: function (s, o, f, recurse) { var i, j, k, key, v, meta, saved=[], token, lidx=s.length, DUMP='dump', SPACE=' ', LBRACE='{', RBRACE='}', dump, objstr; for (;;) { i = s.lastIndexOf(LBRACE, lidx); if (i < 0) { break; } j = s.indexOf(RBRACE, i); if (i + 1 > j) { break; } //Extract key and meta info token = s.substring(i + 1, j); key = token; meta = null; k = key.indexOf(SPACE); if (k > -1) { meta = key.substring(k + 1); key = key.substring(0, k); } // lookup the value v = o[key]; // if a substitution function was provided, execute it if (f) { v = f(key, v, meta); } if (L.isObject(v)) { if (L.isArray(v)) { v = L.dump(v, parseInt(meta, 10)); } else { meta = meta || ""; // look for the keyword 'dump', if found force obj dump dump = meta.indexOf(DUMP); if (dump > -1) { meta = meta.substring(4); } objstr = v.toString(); // use the toString if it is not the Object toString // and the 'dump' meta info was not found if (objstr === OBJECT_TOSTRING || dump > -1) { v = L.dump(v, parseInt(meta, 10)); } else { v = objstr; } } } else if (!L.isString(v) && !L.isNumber(v)) { // This {block} has no replace string. Save it for later. v = "~-" + saved.length + "-~"; saved[saved.length] = token; // break; } s = s.substring(0, i) + v + s.substring(j + 1); if (recurse === false) { lidx = i-1; } } // restore saved {block}s for (i=saved.length-1; i>=0; i=i-1) { s = s.replace(new RegExp("~-" + i + "-~"), "{" + saved[i] + "}", "g"); } return s; }, /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @since 2.3.0 * @param s {string} the string to trim * @return {string} the trimmed string */ trim: function(s){ try { return s.replace(/^\s+|\s+$/g, ""); } catch(e) { return s; } }, /** * Returns a new object containing all of the properties of * all the supplied objects. The properties from later objects * will overwrite those in earlier objects. * @method merge * @since 2.3.0 * @param arguments {Object*} the objects to merge * @return the new merged object */ merge: function() { var o={}, a=arguments, l=a.length, i; for (i=0; i * var A = function() {}; * A.prototype.foo = 'foo'; * var a = new A(); * a.foo = 'foo'; * alert(a.hasOwnProperty('foo')); // true * alert(YAHOO.lang.hasOwnProperty(a, 'foo')); // false when using fallback * * @method hasOwnProperty * @param {any} o The object being testing * @param prop {string} the name of the property to test * @return {boolean} the result */ L.hasOwnProperty = (OP.hasOwnProperty) ? function(o, prop) { return o && o.hasOwnProperty && o.hasOwnProperty(prop); } : function(o, prop) { return !L.isUndefined(o[prop]) && o.constructor.prototype[prop] !== o[prop]; }; // new lang wins OB.augmentObject(L, OB, true); /* * An alias for YAHOO.lang * @class YAHOO.util.Lang */ YAHOO.util.Lang = L; /** * Same as YAHOO.lang.augmentObject, except it only applies prototype * properties. This is an alias for augmentProto. * @see YAHOO.lang.augmentObject * @method augment * @static * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param {String*|boolean} arguments zero or more properties methods to * augment the receiver with. If none specified, everything * in the supplier will be used unless it would * overwrite an existing property in the receiver. if true * is specified as the third parameter, all properties will * be applied and will overwrite an existing property in * the receiver */ L.augment = L.augmentProto; /** * An alias for YAHOO.lang.augment * @for YAHOO * @method augment * @static * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param {String*} arguments zero or more properties methods to * augment the receiver with. If none specified, everything * in the supplier will be used unless it would * overwrite an existing property in the receiver */ YAHOO.augment = L.augmentProto; /** * An alias for YAHOO.lang.extend * @method extend * @static * @param {Function} subc the object to modify * @param {Function} superc the object to inherit * @param {Object} overrides additional properties/methods to add to the * subclass prototype. These will override the * matching items obtained from the superclass if present. */ YAHOO.extend = L.extend; })(); YAHOO.register("yahoo", YAHOO, {version: "2.9.0", build: "2800"}); /** * Provides a mechanism to fetch remote resources and * insert them into a document * This utility can fetch JavaScript and CSS files, inserting script * tags for script and link tags for CSS. Note, this * is done via the normal browser mechanisms for inserting * these resources and making the content available to * code that would access it. Be careful when retreiving * remote resources. Only use this utility to fetch * files from sites you trust. * * @module get * @requires yahoo */ /** * Fetches and inserts one or more script or link nodes into the document. * This utility can fetch JavaScript and CSS files, inserting script * tags for script and link tags for CSS. Note, this * is done via the normal browser mechanisms for inserting * these resources and making the content available to * code that would access it. Be careful when retreiving * remote resources. Only use this utility to fetch * files from sites you trust. * * @namespace YAHOO.util * @class YAHOO.util.Get */ YAHOO.util.Get = function() { /** * hash of queues to manage multiple requests * @property queues * @private */ var queues={}, /** * queue index used to generate transaction ids * @property qidx * @type int * @private */ qidx=0, /** * node index used to generate unique node ids * @property nidx * @type int * @private */ nidx=0, /** * interal property used to prevent multiple simultaneous purge * processes * @property purging * @type boolean * @private */ _purging=false, ua=YAHOO.env.ua, lang=YAHOO.lang, _fail, _purge, _track, /** * Generates an HTML element, this is not appended to a document * @method _node * @param type {string} the type of element * @param attr {string} the attributes * @param win {Window} optional window to create the element in * @return {HTMLElement} the generated node * @private */ _node = function(type, attr, win) { var w = win || window, d=w.document, n=d.createElement(type), i; for (i in attr) { if (attr.hasOwnProperty(i)) { n.setAttribute(i, attr[i]); } } return n; }, /** * Generates a link node * @method _linkNode * @param url {string} the url for the css file * @param win {Window} optional window to create the node in * @return {HTMLElement} the generated node * @private */ _linkNode = function(url, win, attributes) { var o = { id: "yui__dyn_" + (nidx++), type: "text/css", rel: "stylesheet", href: url }; if (attributes) { lang.augmentObject(o, attributes); } return _node("link", o, win); }, /** * Generates a script node * @method _scriptNode * @param url {string} the url for the script file * @param win {Window} optional window to create the node in * @return {HTMLElement} the generated node * @private */ _scriptNode = function(url, win, attributes) { var o = { id: "yui__dyn_" + (nidx++), type: "text/javascript", src: url }; if (attributes) { lang.augmentObject(o, attributes); } return _node("script", o, win); }, /** * Returns the data payload for callback functions * @method _returnData * @private */ _returnData = function(q, msg) { return { tId: q.tId, win: q.win, data: q.data, nodes: q.nodes, msg: msg, purge: function() { _purge(this.tId); } }; }, _get = function(nId, tId) { var q = queues[tId], n = (lang.isString(nId)) ? q.win.document.getElementById(nId) : nId; if (!n) { _fail(tId, "target node not found: " + nId); } return n; }, /** * The request is complete, so executing the requester's callback * @method _finish * @param id {string} the id of the request * @private */ _finish = function(id) { YAHOO.log("Finishing transaction " + id); var q = queues[id], msg, context; q.finished = true; if (q.aborted) { msg = "transaction " + id + " was aborted"; _fail(id, msg); return; } // execute success callback if (q.onSuccess) { context = q.scope || q.win; q.onSuccess.call(context, _returnData(q)); } }, /** * Timeout detected * @method _timeout * @param id {string} the id of the request * @private */ _timeout = function(id) { YAHOO.log("Timeout " + id, "info", "get"); var q = queues[id], context; if (q.onTimeout) { context = q.scope || q; q.onTimeout.call(context, _returnData(q)); } }, /** * Loads the next item for a given request * @method _next * @param id {string} the id of the request * @param loaded {string} the url that was just loaded, if any * @private */ _next = function(id, loaded) { YAHOO.log("_next: " + id + ", loaded: " + loaded, "info", "Get"); var q = queues[id], w=q.win, d=w.document, h=d.getElementsByTagName("head")[0], n, msg, url, s, extra; if (q.timer) { // Y.log('cancel timer'); q.timer.cancel(); } if (q.aborted) { msg = "transaction " + id + " was aborted"; _fail(id, msg); return; } if (loaded) { q.url.shift(); if (q.varName) { q.varName.shift(); } } else { // This is the first pass: make sure the url is an array q.url = (lang.isString(q.url)) ? [q.url] : q.url; if (q.varName) { q.varName = (lang.isString(q.varName)) ? [q.varName] : q.varName; } } if (q.url.length === 0) { // Safari 2.x workaround - There is no way to know when // a script is ready in versions of Safari prior to 3.x. // Adding an extra node reduces the problem, but doesn't // eliminate it completely because the browser executes // them asynchronously. if (q.type === "script" && ua.webkit && ua.webkit < 420 && !q.finalpass && !q.varName) { // Add another script node. This does not guarantee that the // scripts will execute in order, but it does appear to fix the // problem on fast connections more effectively than using an // arbitrary timeout. It is possible that the browser does // block subsequent script execution in this case for a limited // time. extra = _scriptNode(null, q.win, q.attributes); extra.innerHTML='YAHOO.util.Get._finalize("' + id + '");'; q.nodes.push(extra); h.appendChild(extra); } else { _finish(id); } return; } url = q.url[0]; // if the url is undefined, this is probably a trailing comma problem in IE if (!url) { q.url.shift(); YAHOO.log('skipping empty url'); return _next(id); } YAHOO.log("attempting to load " + url, "info", "Get"); if (q.timeout) { // Y.log('create timer'); q.timer = lang.later(q.timeout, q, _timeout, id); } if (q.type === "script") { n = _scriptNode(url, w, q.attributes); } else { n = _linkNode(url, w, q.attributes); } // track this node's load progress _track(q.type, n, id, url, w, q.url.length); // add the node to the queue so we can return it to the user supplied callback q.nodes.push(n); // add it to the head or insert it before 'insertBefore' if (q.insertBefore) { s = _get(q.insertBefore, id); if (s) { s.parentNode.insertBefore(n, s); } } else { h.appendChild(n); } YAHOO.log("Appending node: " + url, "info", "Get"); // FireFox does not support the onload event for link nodes, so there is // no way to make the css requests synchronous. This means that the css // rules in multiple files could be applied out of order in this browser // if a later request returns before an earlier one. Safari too. if ((ua.webkit || ua.gecko) && q.type === "css") { _next(id, url); } }, /** * Removes processed queues and corresponding nodes * @method _autoPurge * @private */ _autoPurge = function() { if (_purging) { return; } _purging = true; var i, q; for (i in queues) { if (queues.hasOwnProperty(i)) { q = queues[i]; if (q.autopurge && q.finished) { _purge(q.tId); delete queues[i]; } } } _purging = false; }, /** * Saves the state for the request and begins loading * the requested urls * @method queue * @param type {string} the type of node to insert * @param url {string} the url to load * @param opts the hash of options for this request * @private */ _queue = function(type, url, opts) { var id = "q" + (qidx++), q; opts = opts || {}; if (qidx % YAHOO.util.Get.PURGE_THRESH === 0) { _autoPurge(); } queues[id] = lang.merge(opts, { tId: id, type: type, url: url, finished: false, aborted: false, nodes: [] }); q = queues[id]; q.win = q.win || window; q.scope = q.scope || q.win; q.autopurge = ("autopurge" in q) ? q.autopurge : (type === "script") ? true : false; q.attributes = q.attributes || {}; q.attributes.charset = opts.charset || q.attributes.charset || 'utf-8'; lang.later(0, q, _next, id); return { tId: id }; }; /** * Detects when a node has been loaded. In the case of * script nodes, this does not guarantee that contained * script is ready to use. * @method _track * @param type {string} the type of node to track * @param n {HTMLElement} the node to track * @param id {string} the id of the request * @param url {string} the url that is being loaded * @param win {Window} the targeted window * @param qlength the number of remaining items in the queue, * including this one * @param trackfn {Function} function to execute when finished * the default is _next * @private */ _track = function(type, n, id, url, win, qlength, trackfn) { var f = trackfn || _next, rs, q, a, freq, w, l, i, msg; // IE supports the readystatechange event for script and css nodes if (ua.ie) { n.onreadystatechange = function() { rs = this.readyState; if ("loaded" === rs || "complete" === rs) { YAHOO.log(id + " onload " + url, "info", "Get"); n.onreadystatechange = null; f(id, url); } }; // webkit prior to 3.x is problemmatic } else if (ua.webkit) { if (type === "script") { // Safari 3.x supports the load event for script nodes (DOM2) if (ua.webkit >= 420) { n.addEventListener("load", function() { YAHOO.log(id + " DOM2 onload " + url, "info", "Get"); f(id, url); }); // Nothing can be done with Safari < 3.x except to pause and hope // for the best, particularly after last script is inserted. The // scripts will always execute in the order they arrive, not // necessarily the order in which they were inserted. To support // script nodes with complete reliability in these browsers, script // nodes either need to invoke a function in the window once they // are loaded or the implementer needs to provide a well-known // property that the utility can poll for. } else { // Poll for the existence of the named variable, if it // was supplied. q = queues[id]; if (q.varName) { freq = YAHOO.util.Get.POLL_FREQ; YAHOO.log("Polling for " + q.varName[0]); q.maxattempts = YAHOO.util.Get.TIMEOUT/freq; q.attempts = 0; q._cache = q.varName[0].split("."); q.timer = lang.later(freq, q, function(o) { a = this._cache; l = a.length; w = this.win; for (i=0; i this.maxattempts) { msg = "Over retry limit, giving up"; q.timer.cancel(); _fail(id, msg); } else { YAHOO.log(a[i] + " failed, retrying"); } return; } } YAHOO.log("Safari poll complete"); q.timer.cancel(); f(id, url); }, null, true); } else { lang.later(YAHOO.util.Get.POLL_FREQ, null, f, [id, url]); } } } // FireFox and Opera support onload (but not DOM2 in FF) handlers for // script nodes. Opera, but not FF, supports the onload event for link // nodes. } else { n.onload = function() { YAHOO.log(id + " onload " + url, "info", "Get"); f(id, url); }; } }; /* * The request failed, execute fail handler with whatever * was accomplished. There isn't a failure case at the * moment unless you count aborted transactions * @method _fail * @param id {string} the id of the request * @private */ _fail = function(id, msg) { YAHOO.log("get failure: " + msg, "warn", "Get"); var q = queues[id], context; // execute failure callback if (q.onFailure) { context = q.scope || q.win; q.onFailure.call(context, _returnData(q, msg)); } }; /** * Removes the nodes for the specified queue * @method _purge * @private */ _purge = function(tId) { if (queues[tId]) { var q = queues[tId], nodes = q.nodes, l = nodes.length, d = q.win.document, h = d.getElementsByTagName("head")[0], sib, i, node, attr; if (q.insertBefore) { sib = _get(q.insertBefore, tId); if (sib) { h = sib.parentNode; } } for (i=0; i *
    onSuccess
    *
    * callback to execute when the script(s) are finished loading * The callback receives an object back with the following * data: *
    *
    win
    *
    the window the script(s) were inserted into
    *
    data
    *
    the data object passed in when the request was made
    *
    nodes
    *
    An array containing references to the nodes that were * inserted
    *
    purge
    *
    A function that, when executed, will remove the nodes * that were inserted
    *
    *
    *
    *
    onFailure
    *
    * callback to execute when the script load operation fails * The callback receives an object back with the following * data: *
    *
    win
    *
    the window the script(s) were inserted into
    *
    data
    *
    the data object passed in when the request was made
    *
    nodes
    *
    An array containing references to the nodes that were * inserted successfully
    *
    purge
    *
    A function that, when executed, will remove any nodes * that were inserted
    *
    *
    *
    *
    onTimeout
    *
    * callback to execute when a timeout occurs. * The callback receives an object back with the following * data: *
    *
    win
    *
    the window the script(s) were inserted into
    *
    data
    *
    the data object passed in when the request was made
    *
    nodes
    *
    An array containing references to the nodes that were * inserted
    *
    purge
    *
    A function that, when executed, will remove the nodes * that were inserted
    *
    *
    *
    *
    scope
    *
    the execution context for the callbacks
    *
    win
    *
    a window other than the one the utility occupies
    *
    autopurge
    *
    * setting to true will let the utilities cleanup routine purge * the script once loaded *
    *
    data
    *
    * data that is supplied to the callback when the script(s) are * loaded. *
    *
    varName
    *
    * variable that should be available when a script is finished * loading. Used to help Safari 2.x and below with script load * detection. The type of this property should match what was * passed into the url parameter: if loading a single url, a * string can be supplied. If loading multiple scripts, you * must supply an array that contains the variable name for * each script. *
    *
    insertBefore
    *
    node or node id that will become the new node's nextSibling
    * *
    charset
    *
    Node charset, deprecated, use 'attributes'
    *
    attributes
    *
    A hash of attributes to apply to dynamic nodes.
    *
    timeout
    *
    Number of milliseconds to wait before aborting and firing the timeout event
    *
             * // assumes yahoo, dom, and event are already on the page
             *   YAHOO.util.Get.script(
             *   ["http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js",
             *    "http://yui.yahooapis.com/2.7.0/build/animation/animation-min.js"], {
             *     onSuccess: function(o) {
             *       YAHOO.log(o.data); // foo
             *       new YAHOO.util.DDProxy("dd1"); // also new o.reference("dd1"); would work
             *       this.log("won't cause error because YAHOO is the scope");
             *       this.log(o.nodes.length === 2) // true
             *       // o.purge(); // optionally remove the script nodes immediately
             *     },
             *     onFailure: function(o) {
             *       YAHOO.log("transaction failed");
             *     },
             *     data: "foo",
             *     timeout: 10000, // 10 second timeout
             *     scope: YAHOO,
             *     // win: otherframe // target another window/frame
             *     autopurge: true // allow the utility to choose when to remove the nodes
             *   });
             * 
    * @return {tId: string} an object containing info about the transaction */ script: function(url, opts) { return _queue("script", url, opts); }, /** * Fetches and inserts one or more css link nodes into the * head of the current document or the document in a specified * window. * @method css * @static * @param url {string} the url or urls to the css file(s) * @param opts Options: *
    *
    onSuccess
    *
    * callback to execute when the css file(s) are finished loading * The callback receives an object back with the following * data: *
    win
    *
    the window the link nodes(s) were inserted into
    *
    data
    *
    the data object passed in when the request was made
    *
    nodes
    *
    An array containing references to the nodes that were * inserted
    *
    purge
    *
    A function that, when executed, will remove the nodes * that were inserted
    *
    *
    * *
    scope
    *
    the execution context for the callbacks
    *
    win
    *
    a window other than the one the utility occupies
    *
    data
    *
    * data that is supplied to the callbacks when the nodes(s) are * loaded. *
    *
    insertBefore
    *
    node or node id that will become the new node's nextSibling
    *
    charset
    *
    Node charset, deprecated, use 'attributes'
    *
    attributes
    *
    A hash of attributes to apply to dynamic nodes.
    * *
             *      YAHOO.util.Get.css("http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css");
             * 
    *
             *      YAHOO.util.Get.css(["http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css",
             *                          "http://yui.yahooapis.com/2.7.0/build/logger/assets/skins/sam/logger.css"]);
             * 
    * @return {tId: string} an object containing info about the transaction */ css: function(url, opts) { return _queue("css", url, opts); } }; }(); YAHOO.register("get", YAHOO.util.Get, {version: "2.9.0", build: "2800"}); /*jslint evil: true, strict: false, regexp: false*/ /** * Provides dynamic loading for the YUI library. It includes the dependency * info for the library, and will automatically pull in dependencies for * the modules requested. It supports rollup files (such as utilities.js * and yahoo-dom-event.js), and will automatically use these when * appropriate in order to minimize the number of http connections * required to load all of the dependencies. * * @module yuiloader * @namespace YAHOO.util */ /** * YUILoader provides dynamic loading for YUI. * @class YAHOO.util.YUILoader * @todo * version management, automatic sandboxing */ (function() { var Y = YAHOO, util = Y.util, lang = Y.lang, env = Y.env, PROV = "_provides", SUPER = "_supersedes", REQ = "expanded", AFTER = "_after", VERSION = "2.9.0"; // version hack for cdn testing // if (/VERSION/.test(VERSION)) { // VERSION = "2.8.2"; // } var YUI = { dupsAllowed: {'yahoo': true, 'get': true}, /* * The library metadata for the current release The is the default * value for YAHOO.util.YUILoader.moduleInfo * @property YUIInfo * @static */ info: { // 'root': '2.5.2/build/', // 'base': 'http://yui.yahooapis.com/2.5.2/build/', 'root': VERSION + '/build/', 'base': 'http://yui.yahooapis.com/' + VERSION + '/build/', 'comboBase': 'http://yui.yahooapis.com/combo?', 'skin': { 'defaultSkin': 'sam', 'base': 'assets/skins/', 'path': 'skin.css', 'after': ['reset', 'fonts', 'grids', 'base'], 'rollup': 3 }, dupsAllowed: ['yahoo', 'get'], 'moduleInfo': { 'animation': { 'type': 'js', 'path': 'animation/animation-min.js', 'requires': ['dom', 'event'] }, 'autocomplete': { 'type': 'js', 'path': 'autocomplete/autocomplete-min.js', 'requires': ['dom', 'event', 'datasource'], 'optional': ['connection', 'animation'], 'skinnable': true }, 'base': { 'type': 'css', 'path': 'base/base-min.css', 'after': ['reset', 'fonts', 'grids'] }, 'button': { 'type': 'js', 'path': 'button/button-min.js', 'requires': ['element'], 'optional': ['menu'], 'skinnable': true }, 'calendar': { 'type': 'js', 'path': 'calendar/calendar-min.js', 'requires': ['event', 'dom'], supersedes: ['datemath'], 'skinnable': true }, 'carousel': { 'type': 'js', 'path': 'carousel/carousel-min.js', 'requires': ['element'], 'optional': ['animation'], 'skinnable': true }, 'charts': { 'type': 'js', 'path': 'charts/charts-min.js', 'requires': ['element', 'json', 'datasource', 'swf'] }, 'colorpicker': { 'type': 'js', 'path': 'colorpicker/colorpicker-min.js', 'requires': ['slider', 'element'], 'optional': ['animation'], 'skinnable': true }, 'connection': { 'type': 'js', 'path': 'connection/connection-min.js', 'requires': ['event'], 'supersedes': ['connectioncore'] }, 'connectioncore': { 'type': 'js', 'path': 'connection/connection_core-min.js', 'requires': ['event'], 'pkg': 'connection' }, 'container': { 'type': 'js', 'path': 'container/container-min.js', 'requires': ['dom', 'event'], // button is also optional, but this creates a circular // dependency when loadOptional is specified. button // optionally includes menu, menu requires container. 'optional': ['dragdrop', 'animation', 'connection'], 'supersedes': ['containercore'], 'skinnable': true }, 'containercore': { 'type': 'js', 'path': 'container/container_core-min.js', 'requires': ['dom', 'event'], 'pkg': 'container' }, 'cookie': { 'type': 'js', 'path': 'cookie/cookie-min.js', 'requires': ['yahoo'] }, 'datasource': { 'type': 'js', 'path': 'datasource/datasource-min.js', 'requires': ['event'], 'optional': ['connection'] }, 'datatable': { 'type': 'js', 'path': 'datatable/datatable-min.js', 'requires': ['element', 'datasource'], 'optional': ['calendar', 'dragdrop', 'paginator'], 'skinnable': true }, datemath: { 'type': 'js', 'path': 'datemath/datemath-min.js', 'requires': ['yahoo'] }, 'dom': { 'type': 'js', 'path': 'dom/dom-min.js', 'requires': ['yahoo'] }, 'dragdrop': { 'type': 'js', 'path': 'dragdrop/dragdrop-min.js', 'requires': ['dom', 'event'] }, 'editor': { 'type': 'js', 'path': 'editor/editor-min.js', 'requires': ['menu', 'element', 'button'], 'optional': ['animation', 'dragdrop'], 'supersedes': ['simpleeditor'], 'skinnable': true }, 'element': { 'type': 'js', 'path': 'element/element-min.js', 'requires': ['dom', 'event'], 'optional': ['event-mouseenter', 'event-delegate'] }, 'element-delegate': { 'type': 'js', 'path': 'element-delegate/element-delegate-min.js', 'requires': ['element'] }, 'event': { 'type': 'js', 'path': 'event/event-min.js', 'requires': ['yahoo'] }, 'event-simulate': { 'type': 'js', 'path': 'event-simulate/event-simulate-min.js', 'requires': ['event'] }, 'event-delegate': { 'type': 'js', 'path': 'event-delegate/event-delegate-min.js', 'requires': ['event'], 'optional': ['selector'] }, 'event-mouseenter': { 'type': 'js', 'path': 'event-mouseenter/event-mouseenter-min.js', 'requires': ['dom', 'event'] }, 'fonts': { 'type': 'css', 'path': 'fonts/fonts-min.css' }, 'get': { 'type': 'js', 'path': 'get/get-min.js', 'requires': ['yahoo'] }, 'grids': { 'type': 'css', 'path': 'grids/grids-min.css', 'requires': ['fonts'], 'optional': ['reset'] }, 'history': { 'type': 'js', 'path': 'history/history-min.js', 'requires': ['event'] }, 'imagecropper': { 'type': 'js', 'path': 'imagecropper/imagecropper-min.js', 'requires': ['dragdrop', 'element', 'resize'], 'skinnable': true }, 'imageloader': { 'type': 'js', 'path': 'imageloader/imageloader-min.js', 'requires': ['event', 'dom'] }, 'json': { 'type': 'js', 'path': 'json/json-min.js', 'requires': ['yahoo'] }, 'layout': { 'type': 'js', 'path': 'layout/layout-min.js', 'requires': ['element'], 'optional': ['animation', 'dragdrop', 'resize', 'selector'], 'skinnable': true }, 'logger': { 'type': 'js', 'path': 'logger/logger-min.js', 'requires': ['event', 'dom'], 'optional': ['dragdrop'], 'skinnable': true }, 'menu': { 'type': 'js', 'path': 'menu/menu-min.js', 'requires': ['containercore'], 'skinnable': true }, 'paginator': { 'type': 'js', 'path': 'paginator/paginator-min.js', 'requires': ['element'], 'skinnable': true }, 'profiler': { 'type': 'js', 'path': 'profiler/profiler-min.js', 'requires': ['yahoo'] }, 'profilerviewer': { 'type': 'js', 'path': 'profilerviewer/profilerviewer-min.js', 'requires': ['profiler', 'yuiloader', 'element'], 'skinnable': true }, 'progressbar': { 'type': 'js', 'path': 'progressbar/progressbar-min.js', 'requires': ['element'], 'optional': ['animation'], 'skinnable': true }, 'reset': { 'type': 'css', 'path': 'reset/reset-min.css' }, 'reset-fonts-grids': { 'type': 'css', 'path': 'reset-fonts-grids/reset-fonts-grids.css', 'supersedes': ['reset', 'fonts', 'grids', 'reset-fonts'], 'rollup': 4 }, 'reset-fonts': { 'type': 'css', 'path': 'reset-fonts/reset-fonts.css', 'supersedes': ['reset', 'fonts'], 'rollup': 2 }, 'resize': { 'type': 'js', 'path': 'resize/resize-min.js', 'requires': ['dragdrop', 'element'], 'optional': ['animation'], 'skinnable': true }, 'selector': { 'type': 'js', 'path': 'selector/selector-min.js', 'requires': ['yahoo', 'dom'] }, 'simpleeditor': { 'type': 'js', 'path': 'editor/simpleeditor-min.js', 'requires': ['element'], 'optional': ['containercore', 'menu', 'button', 'animation', 'dragdrop'], 'skinnable': true, 'pkg': 'editor' }, 'slider': { 'type': 'js', 'path': 'slider/slider-min.js', 'requires': ['dragdrop'], 'optional': ['animation'], 'skinnable': true }, 'storage': { 'type': 'js', 'path': 'storage/storage-min.js', 'requires': ['yahoo', 'event', 'cookie'], 'optional': ['swfstore'] }, 'stylesheet': { 'type': 'js', 'path': 'stylesheet/stylesheet-min.js', 'requires': ['yahoo'] }, 'swf': { 'type': 'js', 'path': 'swf/swf-min.js', 'requires': ['element'], 'supersedes': ['swfdetect'] }, 'swfdetect': { 'type': 'js', 'path': 'swfdetect/swfdetect-min.js', 'requires': ['yahoo'] }, 'swfstore': { 'type': 'js', 'path': 'swfstore/swfstore-min.js', 'requires': ['element', 'cookie', 'swf'] }, 'tabview': { 'type': 'js', 'path': 'tabview/tabview-min.js', 'requires': ['element'], 'optional': ['connection'], 'skinnable': true }, 'treeview': { 'type': 'js', 'path': 'treeview/treeview-min.js', 'requires': ['event', 'dom'], 'optional': ['json', 'animation', 'calendar'], 'skinnable': true }, 'uploader': { 'type': 'js', 'path': 'uploader/uploader-min.js', 'requires': ['element'] }, 'utilities': { 'type': 'js', 'path': 'utilities/utilities.js', 'supersedes': ['yahoo', 'event', 'dragdrop', 'animation', 'dom', 'connection', 'element', 'yahoo-dom-event', 'get', 'yuiloader', 'yuiloader-dom-event'], 'rollup': 8 }, 'yahoo': { 'type': 'js', 'path': 'yahoo/yahoo-min.js' }, 'yahoo-dom-event': { 'type': 'js', 'path': 'yahoo-dom-event/yahoo-dom-event.js', 'supersedes': ['yahoo', 'event', 'dom'], 'rollup': 3 }, 'yuiloader': { 'type': 'js', 'path': 'yuiloader/yuiloader-min.js', 'supersedes': ['yahoo', 'get'] }, 'yuiloader-dom-event': { 'type': 'js', 'path': 'yuiloader-dom-event/yuiloader-dom-event.js', 'supersedes': ['yahoo', 'dom', 'event', 'get', 'yuiloader', 'yahoo-dom-event'], 'rollup': 5 }, 'yuitest': { 'type': 'js', 'path': 'yuitest/yuitest-min.js', 'requires': ['logger'], 'optional': ['event-simulate'], 'skinnable': true } } }, ObjectUtil: { appendArray: function(o, a) { if (a) { for (var i=0; i *
    DEBUG
    *
    Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the logger widget
    *
    RAW
    *
    Selects the non-minified version of the library (e.g., event.js). * * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: *
             *  myFilter: {
             *      'searchExp': "-min\\.js",
             *      'replaceStr': "-debug.js"
             *  }
             * 
    * @property filter * @type string|{searchExp: string, replaceStr: string} */ this.filter = null; /** * The list of requested modules * @property required * @type {string: boolean} */ this.required = {}; /** * The library metadata * @property moduleInfo */ this.moduleInfo = lang.merge(YUI.info.moduleInfo); /** * List of rollup files found in the library metadata * @property rollups */ this.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ this.loadOptional = false; /** * All of the derived dependencies in sorted order, which * will be populated when either calculate() or insert() * is called * @property sorted * @type string[] */ this.sorted = []; /** * Set when beginning to compute the dependency tree. * Composed of what YAHOO reports to be loaded combined * with what has been loaded by the tool * @propery loaded * @type {string: boolean} */ this.loaded = {}; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ this.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ this.inserted = {}; /** * Provides the information used to skin the skinnable components. * The following skin definition would result in 'skin1' and 'skin2' * being loaded for calendar (if calendar was requested), and * 'sam' for all other skinnable components: * * * skin: { * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. ex: * // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/ * base: 'assets/skins/', * * // The name of the rollup css file for the skin * path: 'skin.css', * * // The number of skinnable components requested that are * // required before using the rollup file rather than the * // individual component css files * rollup: 3, * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * calendar: ['skin1', 'skin2'] * } * } * * @property skin */ var self = this; env.listeners.push(function(m) { if (self._useYahooListener) { //Y.log("YAHOO listener: " + m.name); self.loadNext(m.name); } }); this.skin = lang.merge(YUI.info.skin); this._config(o); }; Y.util.YUILoader.prototype = { FILTERS: { RAW: { 'searchExp': "-min\\.js", 'replaceStr': ".js" }, DEBUG: { 'searchExp': "-min\\.js", 'replaceStr': "-debug.js" } }, SKIN_PREFIX: "skin-", _config: function(o) { // apply config values if (o) { for (var i in o) { if (lang.hasOwnProperty(o, i)) { if (i == "require") { this.require(o[i]); } else { this[i] = o[i]; } } } } // fix filter var f = this.filter; if (lang.isString(f)) { f = f.toUpperCase(); // the logger must be available in order to use the debug // versions of the library if (f === "DEBUG") { this.require("logger"); } // hack to handle a a bug where LogWriter is being instantiated // at load time, and the loader has no way to sort above it // at the moment. if (!Y.widget.LogWriter) { Y.widget.LogWriter = function() { return Y; }; } this.filter = this.FILTERS[f]; } }, /** Add a new module to the component metadata. *
    *
    name:
    required, the component name
    *
    type:
    required, the component type (js or css)
    *
    path:
    required, the path to the script from "base"
    *
    requires:
    array of modules required by this component
    *
    optional:
    array of optional modules for this component
    *
    supersedes:
    array of the modules this component replaces
    *
    after:
    array of modules the components which, if present, should be sorted above this one
    *
    rollup:
    the number of superseded modules required for automatic rollup
    *
    fullpath:
    If fullpath is specified, this is used instead of the configured base + path
    *
    skinnable:
    flag to determine if skin assets should automatically be pulled in
    *
    * @method addModule * @param o An object containing the module data * @return {boolean} true if the module was added, false if * the object passed in did not provide all required attributes */ addModule: function(o) { if (!o || !o.name || !o.type || (!o.path && !o.fullpath)) { return false; } o.ext = ('ext' in o) ? o.ext : true; o.requires = o.requires || []; this.moduleInfo[o.name] = o; this.dirty = true; return true; }, /** * Add a requirement for one or more module * @method require * @param what {string[] | string*} the modules to load */ require: function(what) { var a = (typeof what === "string") ? arguments : what; this.dirty = true; YUI.ObjectUtil.appendArray(this.required, a); }, /** * Adds the skin def to the module info * @method _addSkin * @param skin {string} the name of the skin * @param mod {string} the name of the module * @return {string} the module name for the skin * @private */ _addSkin: function(skin, mod) { // Add a module definition for the skin rollup css var name = this.formatSkin(skin), info = this.moduleInfo, sinf = this.skin, ext = info[mod] && info[mod].ext; // Y.log('ext? ' + mod + ": " + ext); if (!info[name]) { // Y.log('adding skin ' + name); this.addModule({ 'name': name, 'type': 'css', 'path': sinf.base + skin + '/' + sinf.path, //'supersedes': '*', 'after': sinf.after, 'rollup': sinf.rollup, 'ext': ext }); } // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!info[name]) { var mdef = info[mod], pkg = mdef.pkg || mod; // Y.log('adding skin ' + name); this.addModule({ 'name': name, 'type': 'css', 'after': sinf.after, 'path': pkg + '/' + sinf.base + skin + '/' + mod + '.css', 'ext': ext }); } } return name; }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param mod The module definition from moduleInfo */ getRequires: function(mod) { if (!mod) { return []; } if (!this.dirty && mod.expanded) { return mod.expanded; } mod.requires=mod.requires || []; var i, d=[], r=mod.requires, o=mod.optional, info=this.moduleInfo, m; for (i=0; iformatSkin, providing the skin name and * module name if the string matches the pattern for skins. * @method parseSkin * @param mod {string} the module name to parse * @return {skin: string, module: string} the parsed skin name * and module name, or null if the supplied string does not match * the skin pattern */ parseSkin: function(mod) { if (mod.indexOf(this.SKIN_PREFIX) === 0) { var a = mod.split("-"); return {skin: a[1], module: a[2]}; } return null; }, /** * Look for rollup packages to determine if all of the modules a * rollup supersedes are required. If so, include the rollup to * help reduce the total number of connections required. Called * by calculate() * @method _rollup * @private */ _rollup: function() { var i, j, m, s, rollups={}, r=this.required, roll, info = this.moduleInfo; // find and cache rollup modules if (this.dirty || !this.rollups) { for (i in info) { if (lang.hasOwnProperty(info, i)) { m = info[i]; //if (m && m.rollup && m.supersedes) { if (m && m.rollup) { rollups[i] = m; } } } this.rollups = rollups; } // make as many passes as needed to pick up rollup rollups for (;;) { var rolled = false; // go through the rollup candidates for (i in rollups) { // there can be only one if (!r[i] && !this.loaded[i]) { m =info[i]; s = m.supersedes; roll=false; if (!m.rollup) { continue; } var skin = (m.ext) ? false : this.parseSkin(i), c = 0; // Y.log('skin? ' + i + ": " + skin); if (skin) { for (j in r) { if (lang.hasOwnProperty(r, j)) { if (i !== j && this.parseSkin(j)) { c++; roll = (c >= m.rollup); if (roll) { // Y.log("skin rollup " + lang.dump(r)); break; } } } } } else { // check the threshold for (j=0;j= m.rollup); if (roll) { // Y.log("over thresh " + c + ", " + lang.dump(r)); break; } } } } if (roll) { // Y.log("rollup: " + i + ", " + lang.dump(this, 1)); // add the rollup r[i] = true; rolled = true; // expand the rollup's dependencies this.getRequires(m); } } } // if we made it here w/o rolling up something, we are done if (!rolled) { break; } } }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @private */ _reduce: function() { var i, j, s, m, r=this.required; for (i in r) { // remove if already loaded if (i in this.loaded) { delete r[i]; // remove anything this module supersedes } else { var skinDef = this.parseSkin(i); if (skinDef) { //YAHOO.log("skin found in reduce: " + skinDef.skin + ", " + skinDef.module); // the skin rollup will not have a module name if (!skinDef.module) { var skin_pre = this.SKIN_PREFIX + skinDef.skin; //YAHOO.log("skin_pre: " + skin_pre); for (j in r) { if (lang.hasOwnProperty(r, j)) { m = this.moduleInfo[j]; var ext = m && m.ext; if (!ext && j !== i && j.indexOf(skin_pre) > -1) { // Y.log ("removing component skin: " + j); delete r[j]; } } } } } else { m = this.moduleInfo[i]; s = m && m.supersedes; if (s) { for (j=0; j -1) { return true; } // check if this module should be sorted after the other if (after && YUI.ArrayUtil.indexOf(after, bb) > -1) { return true; } // if loadOptional is not specified, optional dependencies still // must be sorted correctly when present. if (checkOptional && optional && YUI.ArrayUtil.indexOf(optional, bb) > -1) { return true; } // check if this module requires one the other supersedes var ss=info[bb] && info[bb].supersedes; if (ss) { for (ii=0; ii startLen) { YAHOO.util.Get.script(self._filter(js), { data: self._loading, onSuccess: callback, onFailure: self._onFailure, onTimeout: self._onTimeout, insertBefore: self.insertBefore, charset: self.charset, timeout: self.timeout, scope: self }); } else { this.loadNext(); } }; // load the css first // YAHOO.log('combining css: ' + css); if (css.length > startLen) { YAHOO.util.Get.css(this._filter(css), { data: this._loading, onSuccess: loadScript, onFailure: this._onFailure, onTimeout: this._onTimeout, insertBefore: this.insertBefore, charset: this.charset, timeout: this.timeout, scope: self }); } else { loadScript(); } return; } else { // this._combineComplete = true; this.loadNext(this._loading); } }, /** * inserts the requested modules and their dependencies. * type can be "js" or "css". Both script and * css are inserted if type is not provided. * @method insert * @param o optional options object * @param type {string} the type of dependency to insert */ insert: function(o, type) { // if (o) { // Y.log("insert: " + lang.dump(o, 1) + ", " + type); // } else { // Y.log("insert: " + this.toString() + ", " + type); // } // build the dependency list this.calculate(o); // set a flag to indicate the load has started this._loading = true; // flag to indicate we are done with the combo service // and any additional files will need to be loaded // individually // this._combineComplete = false; // keep the loadType (js, css or undefined) cached this.loadType = type; if (this.combine) { return this._combine(); } if (!type) { // Y.log("trying to load css first"); var self = this; this._internalCallback = function() { self._internalCallback = null; self.insert(null, "js"); }; this.insert(null, "css"); return; } // start the load this.loadNext(); }, /** * Interns the script for the requested modules. The callback is * provided a reference to the sandboxed YAHOO object. This only * applies to the script: css can not be sandboxed; css will be * loaded into the page normally if specified. * @method sandbox * @param callback {Function} the callback to exectued when the load is * complete. */ sandbox: function(o, type) { // if (o) { // YAHOO.log("sandbox: " + lang.dump(o, 1) + ", " + type); // } else { // YAHOO.log("sandbox: " + this.toString() + ", " + type); // } var self = this, success = function(o) { var idx=o.argument[0], name=o.argument[2]; // store the response in the position it was requested self._scriptText[idx] = o.responseText; // YAHOO.log("received: " + o.responseText.substr(0, 100) + ", " + idx); if (self.onProgress) { self.onProgress.call(self.scope, { name: name, scriptText: o.responseText, xhrResponse: o, data: self.data }); } // only generate the sandbox once everything is loaded self._loadCount++; if (self._loadCount >= self._stopCount) { // the variable to find var v = self.varName || "YAHOO"; // wrap the contents of the requested modules in an anonymous function var t = "(function() {\n"; // return the locally scoped reference. var b = "\nreturn " + v + ";\n})();"; var ref = eval(t + self._scriptText.join("\n") + b); self._pushEvents(ref); if (ref) { self.onSuccess.call(self.scope, { reference: ref, data: self.data }); } else { self._onFailure.call(self.varName + " reference failure"); } } }, failure = function(o) { self.onFailure.call(self.scope, { msg: "XHR failure", xhrResponse: o, data: self.data }); }; self._config(o); if (!self.onSuccess) { throw new Error("You must supply an onSuccess handler for your sandbox"); } self._sandbox = true; // take care of any css first (this can't be sandboxed) if (!type || type !== "js") { self._internalCallback = function() { self._internalCallback = null; self.sandbox(null, "js"); }; self.insert(null, "css"); return; } // get the connection manager if not on the page if (!util.Connect) { // get a new loader instance to load connection. var ld = new YAHOO.util.YUILoader(); ld.insert({ base: self.base, filter: self.filter, require: "connection", insertBefore: self.insertBefore, charset: self.charset, onSuccess: function() { self.sandbox(null, "js"); }, scope: self }, "js"); return; } self._scriptText = []; self._loadCount = 0; self._stopCount = self.sorted.length; self._xhr = []; self.calculate(); var s=self.sorted, l=s.length, i, m, url; for (i=0; i= 0; --i) { if (stack[i] === value) { throw new Error("JSON.stringify. Cyclical reference"); } } arr = isArray(value); // Add the object to the processing stack stack.push(value); if (arr) { // Array for (i = value.length - 1; i >= 0; --i) { a[i] = _serialize(value, i) || NULL; } } else { // Object // If whitelist provided, take only those keys keys = w || value; i = 0; for (k in keys) { if (l.hasOwnProperty(keys, k)) { v = _serialize(value, k); if (v) { a[i++] = _string(k) + colon + v; } } } } // remove the array from the stack stack.pop(); if (space && a.length) { return arr ? OPEN_A + CR + _indent(a.join(COMMA_CR), space) + CR + CLOSE_A : OPEN_O + CR + _indent(a.join(COMMA_CR), space) + CR + CLOSE_O; } else { return arr ? OPEN_A + a.join(COMMA) + CLOSE_A : OPEN_O + a.join(COMMA) + CLOSE_O; } } // process the input return _serialize({'':o},''); } /* Public API */ YAHOO.lang.JSON = { /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeParse * @type Boolean * @default true * @static */ useNativeParse : !!Native, /** * Leverage native JSON stringify if the browser has a native * implementation. In general, this is a good idea. See the Known Issues * section in the JSON user guide for caveats. The default value is true * for browsers with native JSON support. * * @property useNativeStringify * @type Boolean * @default true * @static */ useNativeStringify : !!Native, /** * Four step determination whether a string is safe to eval. In three steps, * escape sequences, safe values, and properly placed open square brackets * are replaced with placeholders or removed. Then in the final step, the * result of all these replacements is checked for invalid characters. * * @method isSafe * @param str {String} JSON string to be tested * @return {boolean} is the string safe for eval? * @static */ isSafe : function (s) { return _isSafe(_prepare(s)); }, /** *

    Parse a JSON string, returning the native JavaScript * representation.

    * *

    When lang.JSON.useNativeParse is true, this will defer to the native * JSON.parse if the browser has a native implementation. Otherwise, a * JavaScript implementation based on http://www.json.org/json2.js * is used.

    * * @method parse * @param s {string} JSON string data * @param reviver {function} (optional) function(k,v) passed each key:value * pair of object literals, allowing pruning or altering values * @return {MIXED} the native JavaScript representation of the JSON string * @throws SyntaxError * @static */ parse : function (s,reviver) { if (typeof s !== 'string') { s += ''; } return Native && YAHOO.lang.JSON.useNativeParse ? Native.parse(s,reviver) : _parse(s,reviver); }, /** *

    Converts an arbitrary value to a JSON string representation.

    * *

    Objects with cyclical references will trigger an exception.

    * *

    If a whitelist is provided, only matching object keys will be * included. Alternately, a replacer function may be passed as the * second parameter. This function is executed on every value in the * input, and its return value will be used in place of the original value. * This is useful to serialize specialized objects or class instances.

    * *

    If a positive integer or non-empty string is passed as the third * parameter, the output will be formatted with carriage returns and * indentation for readability. If a String is passed (such as "\t") it * will be used once for each indentation level. If a number is passed, * that number of spaces will be used.

    * *

    When lang.JSON.useNativeStringify is true, this will defer to the * native JSON.stringify if the browser has a native implementation. * Otherwise, a JavaScript implementation is used.

    * * @method stringify * @param o {MIXED} any arbitrary object to convert to JSON string * @param w {Array|Function} (optional) whitelist of acceptable object keys * to include OR a function(value,key) to alter values * before serialization * @param space {Number|String} (optional) indentation character(s) or * depthy of spaces to format the output * @return {string} JSON string representation of the input * @throws Error * @static */ stringify : function (o,w,space) { return Native && YAHOO.lang.JSON.useNativeStringify ? Native.stringify(o,w,space) : _stringify(o,w,space); }, /** * Serializes a Date instance as a UTC date string. Used internally by * the JavaScript implementation of stringify. If you need a different * Date serialization format, override this method. If you change this, * you should also set useNativeStringify to false, since native JSON * implementations serialize Dates per the ECMAScript 5 spec. You've been * warned. * * @method dateToString * @param d {Date} The Date to serialize * @return {String} stringified Date in UTC format YYYY-MM-DDTHH:mm:SSZ * @static */ dateToString : function (d) { function _zeroPad(v) { return v < 10 ? '0' + v : v; } return d.getUTCFullYear() + '-' + _zeroPad(d.getUTCMonth() + 1) + '-' + _zeroPad(d.getUTCDate()) + 'T' + _zeroPad(d.getUTCHours()) + COLON + _zeroPad(d.getUTCMinutes()) + COLON + _zeroPad(d.getUTCSeconds()) + 'Z'; }, /** * Reconstitute Date instances from the default JSON UTC serialization. * Reference this from a reviver function to rebuild Dates during the * parse operation. * * @method stringToDate * @param str {String} String serialization of a Date * @return {Date} */ stringToDate : function (str) { var m = str.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?Z$/); if (m) { var d = new Date(); d.setUTCFullYear(m[1], m[2]-1, m[3]); d.setUTCHours(m[4], m[5], m[6], (m[7] || 0)); return d; } return str; } }; /** *

    Four step determination whether a string is safe to eval. In three steps, * escape sequences, safe values, and properly placed open square brackets * are replaced with placeholders or removed. Then in the final step, the * result of all these replacements is checked for invalid characters.

    * *

    This is an alias for isSafe.

    * * @method isValid * @param str {String} JSON string to be tested * @return {boolean} is the string safe for eval? * @static * @deprecated use isSafe */ YAHOO.lang.JSON.isValid = YAHOO.lang.JSON.isSafe; })(); YAHOO.register("json", YAHOO.lang.JSON, {version: "2.9.0", build: "2800"}); /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ (function () { /** * Config is a utility used within an Object to allow the implementer to * maintain a list of local configuration properties and listen for changes * to those properties dynamically using CustomEvent. The initial values are * also maintained so that the configuration can be reset at any given point * to its initial state. * @namespace YAHOO.util * @class Config * @constructor * @param {Object} owner The owner Object to which this Config Object belongs */ YAHOO.util.Config = function (owner) { if (owner) { this.init(owner); } if (!owner) { YAHOO.log("No owner specified for Config object", "error", "Config"); } }; var Lang = YAHOO.lang, CustomEvent = YAHOO.util.CustomEvent, Config = YAHOO.util.Config; /** * Constant representing the CustomEvent type for the config changed event. * @property YAHOO.util.Config.CONFIG_CHANGED_EVENT * @private * @static * @final */ Config.CONFIG_CHANGED_EVENT = "configChanged"; /** * Constant representing the boolean type string * @property YAHOO.util.Config.BOOLEAN_TYPE * @private * @static * @final */ Config.BOOLEAN_TYPE = "boolean"; 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, /** * Maintains the local collection of configuration property objects and * their specified values * @property config * @private * @type Object */ config: null, /** * 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 */ initialConfig: null, /** * Maintains the local, normalized CustomEvent queue * @property eventQueue * @private * @type Object */ eventQueue: null, /** * Custom Event, notifying subscribers when Config properties are set * (setProperty is called without the silent flag * @event configChangedEvent */ configChangedEvent: null, /** * Initializes the configuration Object and all of its local members. * @method init * @param {Object} owner The owner Object to which this Config * Object belongs */ init: function (owner) { this.owner = owner; this.configChangedEvent = this.createEvent(Config.CONFIG_CHANGED_EVENT); this.configChangedEvent.signature = CustomEvent.LIST; this.queueInProgress = false; this.config = {}; this.initialConfig = {}; this.eventQueue = []; }, /** * 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) { return (typeof val == Config.BOOLEAN_TYPE); }, /** * 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) { return (!isNaN(val)); }, /** * 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 */ fireEvent: function ( key, value ) { YAHOO.log("Firing Config event: " + key + "=" + value, "info", "Config"); var property = this.config[key]; if (property && property.event) { property.event.fire(value); } }, /** * 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 */ addProperty: function ( key, propertyObject ) { key = key.toLowerCase(); YAHOO.log("Added property: " + key, "info", "Config"); this.config[key] = propertyObject; propertyObject.event = this.createEvent(key, { scope: this.owner }); propertyObject.event.signature = CustomEvent.LIST; propertyObject.key = key; if (propertyObject.handler) { propertyObject.event.subscribe(propertyObject.handler, this.owner); } 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 */ getConfig: function () { var cfg = {}, currCfg = this.config, prop, property; for (prop in currCfg) { if (Lang.hasOwnProperty(currCfg, prop)) { property = currCfg[prop]; if (property && 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 */ getProperty: function (key) { var property = this.config[key.toLowerCase()]; if (property && 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 */ resetProperty: function (key) { key = key.toLowerCase(); var property = this.config[key]; if (property && property.event) { if (key in this.initialConfig) { this.setProperty(key, this.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. */ setProperty: function (key, value, silent) { var property; key = key.toLowerCase(); YAHOO.log("setProperty: " + key + "=" + value, "info", "Config"); if (this.queueInProgress && ! silent) { // Currently running through a queue... this.queueProperty(key,value); return true; } else { property = this.config[key]; if (property && property.event) { if (property.validator && !property.validator(value)) { return false; } else { property.value = value; if (! silent) { this.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. */ queueProperty: function (key, value) { key = key.toLowerCase(); YAHOO.log("queueProperty: " + key + "=" + value, "info", "Config"); var property = this.config[key], foundDuplicate = false, iLen, queueItem, queueItemKey, queueItemValue, sLen, supercedesCheck, qLen, queueItemCheck, queueItemCheckKey, queueItemCheckValue, i, s, q; if (property && property.event) { if (!Lang.isUndefined(value) && property.validator && !property.validator(value)) { // validator return false; } else { if (!Lang.isUndefined(value)) { property.value = value; } else { value = property.value; } foundDuplicate = false; iLen = this.eventQueue.length; for (i = 0; i < iLen; i++) { queueItem = this.eventQueue[i]; if (queueItem) { queueItemKey = queueItem[0]; queueItemValue = queueItem[1]; if (queueItemKey == key) { /* found a dupe... push to end of queue, null current item, and break */ this.eventQueue[i] = null; this.eventQueue.push( [key, (!Lang.isUndefined(value) ? value : queueItemValue)]); foundDuplicate = true; break; } } } // this is a refire, or a new property in the queue if (! foundDuplicate && !Lang.isUndefined(value)) { this.eventQueue.push([key, value]); } } if (property.supercedes) { sLen = property.supercedes.length; for (s = 0; s < sLen; s++) { supercedesCheck = property.supercedes[s]; qLen = this.eventQueue.length; for (q = 0; q < qLen; q++) { queueItemCheck = this.eventQueue[q]; if (queueItemCheck) { queueItemCheckKey = queueItemCheck[0]; queueItemCheckValue = queueItemCheck[1]; if (queueItemCheckKey == supercedesCheck.toLowerCase() ) { this.eventQueue.push([queueItemCheckKey, queueItemCheckValue]); this.eventQueue[q] = null; break; } } } } } YAHOO.log("Config event queue: " + this.outputEventQueue(), "info", "Config"); return true; } else { return false; } }, /** * Fires the event for a property using the property's current value. * @method refireEvent * @param {String} key The name of the property */ refireEvent: function (key) { key = key.toLowerCase(); var property = this.config[key]; if (property && property.event && !Lang.isUndefined(property.value)) { if (this.queueInProgress) { this.queueProperty(key); } else { this.fireEvent(key, property.value); } } }, /** * Applies a key-value Object literal to the configuration, replacing * any existing values, and queueing the property events. * Although the values will be set, fireQueue() must be called for their * associated events to execute. * @method applyConfig * @param {Object} userConfig The configuration Object literal * @param {Boolean} init When set to true, the initialConfig will * be set to the userConfig passed in, so that calling a reset will * reset the properties to the passed values. */ applyConfig: function (userConfig, init) { var sKey, oConfig; if (init) { oConfig = {}; for (sKey in userConfig) { if (Lang.hasOwnProperty(userConfig, sKey)) { oConfig[sKey.toLowerCase()] = userConfig[sKey]; } } this.initialConfig = oConfig; } for (sKey in userConfig) { if (Lang.hasOwnProperty(userConfig, sKey)) { this.queueProperty(sKey, userConfig[sKey]); } } }, /** * Refires the events for all configuration properties using their * current values. * @method refresh */ refresh: function () { var prop; for (prop in this.config) { if (Lang.hasOwnProperty(this.config, prop)) { this.refireEvent(prop); } } }, /** * Fires the normalized list of queued property change events * @method fireQueue */ fireQueue: function () { var i, queueItem, key, value, property; this.queueInProgress = true; for (i = 0;i < this.eventQueue.length; i++) { queueItem = this.eventQueue[i]; if (queueItem) { key = queueItem[0]; value = queueItem[1]; property = this.config[key]; property.value = value; // Clear out queue entry, to avoid it being // re-added to the queue by any queueProperty/supercedes // calls which are invoked during fireEvent this.eventQueue[i] = null; this.fireEvent(key,value); } } this.queueInProgress = false; this.eventQueue = []; }, /** * Subscribes an external handler to the change event for any * given property. * @method subscribeToConfigEvent * @param {String} key The property name * @param {Function} handler The handler function to use subscribe to * the property's event * @param {Object} obj The Object to use for scoping the event handler * (see CustomEvent documentation) * @param {Boolean} overrideContext Optional. If true, will override * "this" within the handler to map to the scope Object passed into the * method. * @return {Boolean} True, if the subscription was successful, * otherwise false. */ subscribeToConfigEvent: function (key, handler, obj, overrideContext) { var property = this.config[key.toLowerCase()]; if (property && property.event) { if (!Config.alreadySubscribed(property.event, handler, obj)) { property.event.subscribe(handler, obj, overrideContext); } return true; } else { return false; } }, /** * Unsubscribes an external handler from the change event for any * given property. * @method unsubscribeFromConfigEvent * @param {String} key The property name * @param {Function} handler The handler function to use subscribe to * the property's event * @param {Object} obj The Object to use for scoping the event * handler (see CustomEvent documentation) * @return {Boolean} True, if the unsubscription was successful, * otherwise false. */ unsubscribeFromConfigEvent: function (key, handler, obj) { var property = this.config[key.toLowerCase()]; if (property && property.event) { return property.event.unsubscribe(handler, obj); } else { return false; } }, /** * Returns a string representation of the Config object * @method toString * @return {String} The Config object in string format. */ toString: function () { var output = "Config"; if (this.owner) { output += " [" + this.owner.toString() + "]"; } return output; }, /** * Returns a string representation of the Config object's current * CustomEvent queue * @method outputEventQueue * @return {String} The string list of CustomEvents currently queued * for execution */ outputEventQueue: function () { var output = "", queueItem, q, nQueue = this.eventQueue.length; for (q = 0; q < nQueue; q++) { queueItem = this.eventQueue[q]; if (queueItem) { output += queueItem[0] + "=" + queueItem[1] + ", "; } } return output; }, /** * Sets all properties to null, unsubscribes all listeners from each * property's change event and all listeners from the configChangedEvent. * @method destroy */ destroy: function () { var oConfig = this.config, sProperty, oProperty; for (sProperty in oConfig) { if (Lang.hasOwnProperty(oConfig, sProperty)) { oProperty = oConfig[sProperty]; oProperty.event.unsubscribeAll(); oProperty.event = null; } } this.configChangedEvent.unsubscribeAll(); this.configChangedEvent = null; this.owner = null; this.config = null; this.initialConfig = null; this.eventQueue = null; } }; /** * Checks to determine if a particular function/Object pair are already * subscribed to the specified CustomEvent * @method YAHOO.util.Config.alreadySubscribed * @static * @param {YAHOO.util.CustomEvent} evt The CustomEvent for which to check * the subscriptions * @param {Function} fn The function to look for in the subscribers list * @param {Object} obj The execution scope Object for the subscription * @return {Boolean} true, if the function/Object pair is already subscribed * to the CustomEvent passed in */ Config.alreadySubscribed = function (evt, fn, obj) { var nSubscribers = evt.subscribers.length, subsc, i; if (nSubscribers > 0) { i = nSubscribers - 1; do { subsc = evt.subscribers[i]; if (subsc && subsc.obj == obj && subsc.fn == fn) { return true; } } while (i--); } return false; }; YAHOO.lang.augmentProto(Config, YAHOO.util.EventProvider); }()); (function () { /** * The Container family of components is designed to enable developers to * create different kinds of content-containing modules on the web. Module * and Overlay are the most basic containers, and they can be used directly * or extended to build custom containers. Also part of the Container family * are four UI controls that extend Module and Overlay: Tooltip, Panel, * Dialog, and SimpleDialog. * @module container * @title Container * @requires yahoo, dom, event * @optional dragdrop, animation, button */ /** * Module is a JavaScript representation of the Standard Module Format. * Standard Module Format is a simple standard for markup containers where * child nodes representing the header, body, and footer of the content are * denoted using the CSS classes "hd", "bd", and "ft" respectively. * Module is the base class for all other classes in the YUI * Container package. * @namespace YAHOO.widget * @class Module * @constructor * @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. */ YAHOO.widget.Module = function (el, userConfig) { if (el) { this.init(el, userConfig); } else { YAHOO.log("No element or element ID specified" + " for Module instantiation", "error"); } }; var Dom = YAHOO.util.Dom, Config = YAHOO.util.Config, Event = YAHOO.util.Event, CustomEvent = YAHOO.util.CustomEvent, Module = YAHOO.widget.Module, UA = YAHOO.env.ua, m_oModuleTemplate, m_oHeaderTemplate, m_oBodyTemplate, m_oFooterTemplate, /** * Constant representing the name of the Module's events * @property EVENT_TYPES * @private * @final * @type Object */ EVENT_TYPES = { "BEFORE_INIT": "beforeInit", "INIT": "init", "APPEND": "append", "BEFORE_RENDER": "beforeRender", "RENDER": "render", "CHANGE_HEADER": "changeHeader", "CHANGE_BODY": "changeBody", "CHANGE_FOOTER": "changeFooter", "CHANGE_CONTENT": "changeContent", "DESTROY": "destroy", "BEFORE_SHOW": "beforeShow", "SHOW": "show", "BEFORE_HIDE": "beforeHide", "HIDE": "hide" }, /** * Constant representing the Module's configuration properties * @property DEFAULT_CONFIG * @private * @final * @type Object */ DEFAULT_CONFIG = { "VISIBLE": { key: "visible", value: true, validator: YAHOO.lang.isBoolean }, "EFFECT": { key: "effect", suppressEvent: true, supercedes: ["visible"] }, "MONITOR_RESIZE": { key: "monitorresize", value: true }, "APPEND_TO_DOCUMENT_BODY": { key: "appendtodocumentbody", value: false } }; /** * Constant representing the prefix path to use for non-secure images * @property YAHOO.widget.Module.IMG_ROOT * @static * @final * @type String */ Module.IMG_ROOT = null; /** * Constant representing the prefix path to use for securely served images * @property YAHOO.widget.Module.IMG_ROOT_SSL * @static * @final * @type String */ Module.IMG_ROOT_SSL = null; /** * Constant for the default CSS class name that represents a Module * @property YAHOO.widget.Module.CSS_MODULE * @static * @final * @type String */ Module.CSS_MODULE = "yui-module"; /** * CSS classname representing the module header. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @property YAHOO.widget.Module.CSS_HEADER * @static * @final * @type String */ Module.CSS_HEADER = "hd"; /** * CSS classname representing the module body. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @property YAHOO.widget.Module.CSS_BODY * @static * @final * @type String */ Module.CSS_BODY = "bd"; /** * CSS classname representing the module footer. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @property YAHOO.widget.Module.CSS_FOOTER * @static * @final * @type String */ 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 */ Module.RESIZE_MONITOR_SECURE_URL = "javascript:false;"; /** * Constant representing the buffer amount (in pixels) to use when positioning * the text resize monitor offscreen. The resize monitor is positioned * offscreen by an amount eqaul to its offsetHeight + the buffer value. * * @property YAHOO.widget.Module.RESIZE_MONITOR_BUFFER * @static * @type Number */ // Set to 1, to work around pixel offset in IE8, which increases when zoom is used Module.RESIZE_MONITOR_BUFFER = 1; /** * Singleton CustomEvent fired when the font size is changed in the browser. * Opera's "zoom" functionality currently does not support text * size detection. * @event YAHOO.widget.Module.textResizeEvent */ Module.textResizeEvent = new CustomEvent("textResize"); /** * Helper utility method, which forces a document level * redraw for Opera, which can help remove repaint * irregularities after applying DOM changes. * * @method YAHOO.widget.Module.forceDocumentRedraw * @static */ Module.forceDocumentRedraw = function() { var docEl = document.documentElement; if (docEl) { docEl.className += " "; docEl.className = YAHOO.lang.trim(docEl.className); } }; function createModuleTemplate() { if (!m_oModuleTemplate) { m_oModuleTemplate = document.createElement("div"); m_oModuleTemplate.innerHTML = ("
    " + "
    "); m_oHeaderTemplate = m_oModuleTemplate.firstChild; m_oBodyTemplate = m_oHeaderTemplate.nextSibling; m_oFooterTemplate = m_oBodyTemplate.nextSibling; } return m_oModuleTemplate; } function createHeader() { if (!m_oHeaderTemplate) { createModuleTemplate(); } return (m_oHeaderTemplate.cloneNode(false)); } function createBody() { if (!m_oBodyTemplate) { createModuleTemplate(); } return (m_oBodyTemplate.cloneNode(false)); } function createFooter() { if (!m_oFooterTemplate) { createModuleTemplate(); } return (m_oFooterTemplate.cloneNode(false)); } Module.prototype = { /** * The class's constructor function * @property contructor * @type Function */ constructor: 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, /** * A string representing the root path for all images created by * a Module instance. * @deprecated It is recommend that any images for a Module be applied * via CSS using the "background-image" property. * @property imageRoot * @type String */ imageRoot: Module.IMG_ROOT, /** * Initializes the custom events for Module which are fired * automatically at appropriate times by the Module class. * @method initEvents */ initEvents: function () { var SIGNATURE = CustomEvent.LIST; /** * CustomEvent fired prior to class initalization. * @event beforeInitEvent * @param {class} classRef class reference of the initializing * class, such as this.beforeInitEvent.fire(Module) */ this.beforeInitEvent = this.createEvent(EVENT_TYPES.BEFORE_INIT); this.beforeInitEvent.signature = SIGNATURE; /** * CustomEvent fired after class initalization. * @event initEvent * @param {class} classRef class reference of the initializing * class, such as this.beforeInitEvent.fire(Module) */ this.initEvent = this.createEvent(EVENT_TYPES.INIT); this.initEvent.signature = SIGNATURE; /** * CustomEvent fired when the Module is appended to the DOM * @event appendEvent */ this.appendEvent = this.createEvent(EVENT_TYPES.APPEND); this.appendEvent.signature = SIGNATURE; /** * CustomEvent fired before the Module is rendered * @event beforeRenderEvent */ this.beforeRenderEvent = this.createEvent(EVENT_TYPES.BEFORE_RENDER); this.beforeRenderEvent.signature = SIGNATURE; /** * CustomEvent fired after the Module is rendered * @event renderEvent */ this.renderEvent = this.createEvent(EVENT_TYPES.RENDER); this.renderEvent.signature = SIGNATURE; /** * 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 = this.createEvent(EVENT_TYPES.CHANGE_HEADER); this.changeHeaderEvent.signature = SIGNATURE; /** * 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 = this.createEvent(EVENT_TYPES.CHANGE_BODY); this.changeBodyEvent.signature = SIGNATURE; /** * 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 = this.createEvent(EVENT_TYPES.CHANGE_FOOTER); this.changeFooterEvent.signature = SIGNATURE; /** * CustomEvent fired when the content of the Module is modified * @event changeContentEvent */ this.changeContentEvent = this.createEvent(EVENT_TYPES.CHANGE_CONTENT); this.changeContentEvent.signature = SIGNATURE; /** * CustomEvent fired when the Module is destroyed * @event destroyEvent */ this.destroyEvent = this.createEvent(EVENT_TYPES.DESTROY); this.destroyEvent.signature = SIGNATURE; /** * CustomEvent fired before the Module is shown * @event beforeShowEvent */ this.beforeShowEvent = this.createEvent(EVENT_TYPES.BEFORE_SHOW); this.beforeShowEvent.signature = SIGNATURE; /** * CustomEvent fired after the Module is shown * @event showEvent */ this.showEvent = this.createEvent(EVENT_TYPES.SHOW); this.showEvent.signature = SIGNATURE; /** * CustomEvent fired before the Module is hidden * @event beforeHideEvent */ this.beforeHideEvent = this.createEvent(EVENT_TYPES.BEFORE_HIDE); this.beforeHideEvent.signature = SIGNATURE; /** * CustomEvent fired after the Module is hidden * @event hideEvent */ this.hideEvent = this.createEvent(EVENT_TYPES.HIDE); this.hideEvent.signature = SIGNATURE; }, /** * String identifying whether the current platform is windows or mac. This property * currently only identifies these 2 platforms, and returns false otherwise. * @property platform * @deprecated Use YAHOO.env.ua * @type {String|Boolean} */ 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 user-agent of the browser * @deprecated Use YAHOO.env.ua * @property browser * @type {String|Boolean} */ browser: function () { var ua = navigator.userAgent.toLowerCase(); /* Check Opera first in case of spoof and check Safari before Gecko since Safari's user agent string includes "like Gecko" */ if (ua.indexOf('opera') != -1) { return 'opera'; } else if (ua.indexOf('msie 7') != -1) { return 'ie7'; } else if (ua.indexOf('msie') != -1) { return 'ie'; } else if (ua.indexOf('safari') != -1) { return 'safari'; } else if (ua.indexOf('gecko') != -1) { 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(DEFAULT_CONFIG.VISIBLE.key, { handler: this.configVisible, value: DEFAULT_CONFIG.VISIBLE.value, validator: DEFAULT_CONFIG.VISIBLE.validator }); /** *

    * Object or array of objects representing the ContainerEffect * classes that are active for animating the container. *

    *

    * NOTE: Although this configuration * property is introduced at the Module level, an out of the box * implementation is not shipped for the Module class so setting * the proroperty on the Module class has no effect. The Overlay * class is the first class to provide out of the box ContainerEffect * support. *

    * @config effect * @type Object * @default null */ this.cfg.addProperty(DEFAULT_CONFIG.EFFECT.key, { handler: this.configEffect, suppressEvent: DEFAULT_CONFIG.EFFECT.suppressEvent, supercedes: DEFAULT_CONFIG.EFFECT.supercedes }); /** * 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(DEFAULT_CONFIG.MONITOR_RESIZE.key, { handler: this.configMonitorResize, value: DEFAULT_CONFIG.MONITOR_RESIZE.value }); /** * Specifies if the module should be rendered as the first child * of document.body or appended as the last child when render is called * with document.body as the "appendToNode". *

    * Appending to the body while the DOM is still being constructed can * lead to Operation Aborted errors in IE hence this flag is set to * false by default. *

    * * @config appendtodocumentbody * @type Boolean * @default false */ this.cfg.addProperty(DEFAULT_CONFIG.APPEND_TO_DOCUMENT_BODY.key, { value: DEFAULT_CONFIG.APPEND_TO_DOCUMENT_BODY.value }); }, /** * 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. *

    * If the element passed in does not have an id, one will be generated * for it. *

    * @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) { var elId, child; this.initEvents(); this.beforeInitEvent.fire(Module); /** * The Module's Config object used for monitoring * configuration properties. * @property cfg * @type YAHOO.util.Config */ this.cfg = new Config(this); if (this.isSecure) { this.imageRoot = Module.IMG_ROOT_SSL; } if (typeof el == "string") { elId = el; el = document.getElementById(el); if (! el) { el = (createModuleTemplate()).cloneNode(false); el.id = elId; } } this.id = Dom.generateId(el); this.element = el; child = this.element.firstChild; if (child) { var fndHd = false, fndBd = false, fndFt = false; do { // We're looking for elements if (1 == child.nodeType) { if (!fndHd && Dom.hasClass(child, Module.CSS_HEADER)) { this.header = child; fndHd = true; } else if (!fndBd && Dom.hasClass(child, Module.CSS_BODY)) { this.body = child; fndBd = true; } else if (!fndFt && Dom.hasClass(child, Module.CSS_FOOTER)){ this.footer = child; fndFt = true; } } } while ((child = child.nextSibling)); } this.initDefaultConfig(); Dom.addClass(this.element, Module.CSS_MODULE); if (userConfig) { this.cfg.applyConfig(userConfig, true); } /* Subscribe to the fireQueue() method of Config so that any queued configuration changes are excecuted upon render of the Module */ if (!Config.alreadySubscribed(this.renderEvent, this.cfg.fireQueue, this.cfg)) { this.renderEvent.subscribe(this.cfg.fireQueue, this.cfg, true); } this.initEvent.fire(Module); }, /** * Initialize an empty IFRAME that is placed out of the visible area * that can be used to detect text resize. * @method initResizeMonitor */ initResizeMonitor: function () { var isGeckoWin = (UA.gecko && this.platform == "windows"); if (isGeckoWin) { // Help prevent spinning loading icon which // started with FireFox 2.0.0.8/Win var self = this; setTimeout(function(){self._initResizeMonitor();}, 0); } else { this._initResizeMonitor(); } }, /** * Create and initialize the text resize monitoring iframe. * * @protected * @method _initResizeMonitor */ _initResizeMonitor : function() { var oDoc, oIFrame, sHTML; function fireTextResize() { Module.textResizeEvent.fire(); } if (!UA.opera) { oIFrame = Dom.get("_yuiResizeMonitor"); var supportsCWResize = this._supportsCWResize(); if (!oIFrame) { oIFrame = document.createElement("iframe"); if (this.isSecure && Module.RESIZE_MONITOR_SECURE_URL && UA.ie) { oIFrame.src = Module.RESIZE_MONITOR_SECURE_URL; } if (!supportsCWResize) { // Can't monitor on contentWindow, so fire from inside iframe sHTML = [" to your HTML Add class="sortable" to any table you'd like to make sortable Click on the headers to sort Thanks to many, many people for contributions and suggestions. Licenced as X11: http://www.kryogenix.org/code/browser/licence.html This basically means: do what you want with it. */ var stIsIE = 0; if (navigator.appVersion.indexOf("MSIE") != -1) { stIsIE = 1; } sorttable = { init: function() { // quit if this function has already been called if (arguments.callee.done) { return; } // flag this function so we don't do the same thing twice arguments.callee.done = true; if (!document.createElement || !document.getElementsByTagName) { return; } sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/; forEach(document.getElementsByTagName("table"), function(table) { if (table.className.search(/\bsortable\b/) != -1) { var customMethodName = table.getAttribute("custom-sort-method"); if (customMethodName) { sorttable.makeSortable(table, customMethodName); } else { sorttable.makeSortable(table); } } }); }, makeSortable: function(table, customClickHanderName) { if (table.getElementsByTagName("thead").length == 0) { // table doesn't have a tHead. Since it should have, create one and // put the first table row in it. the = document.createElement("thead"); the.appendChild(table.rows[0]); table.insertBefore(the, table.firstChild); } // Safari doesn't support table.tHead, sigh if (table.tHead == null) { table.tHead = table.getElementsByTagName("thead")[0]; } // if creating the table head made an empty tbody element nuke it var tBody = table.getElementsByTagName("tbody"); if (tBody.length > 1) { var is_empty = 1; for (var i = 0; i < tBody[0].childNodes.length; i++) { if (tBody[0].childNodes[i].nodeType != 3) { is_empty = 0; break; } } if (is_empty) { table.removeChild(tBody[0]); } } if (table.tHead.rows.length != 1) { return; } // can't cope with two header rows // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as // "total" rows, for example). This is B&R, since what you're supposed // to do is put them in a tfoot. So, if there are sortbottom rows, // for backwards compatibility, move them to tfoot (creating it if needed). sortbottomrows = []; for (var i = 0; i < table.rows.length; i++) { if (table.rows[i].className.search(/\bsortbottom\b/) != -1) { sortbottomrows[sortbottomrows.length] = table.rows[i]; } } if (sortbottomrows) { if (table.tFoot == null) { // table doesn't have a tfoot. Create one. tfo = document.createElement("tfoot"); table.appendChild(tfo); } for (var i = 0; i < sortbottomrows.length; i++) { tfo.appendChild(sortbottomrows[i]); } delete sortbottomrows; } // work through each column and calculate its type headrow = table.tHead.rows[0].cells; for (var i = 0; i < headrow.length; i++) { // manually override the type with a sorttable_type attribute if (!headrow[i].className.match(/\bsorttable_nosort\b/) && !( headrow[i].getAttribute("nonsortable") != null && headrow[i].getAttribute("nonsortable").length > 0 ) ) { mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/); if (mtch) { override = mtch[1]; } if (mtch && typeof sorttable["sort_" + override] == "function") { headrow[i].sorttable_sortfunction = sorttable["sort_" + override]; } else { headrow[i].sorttable_sortfunction = sorttable.guessType(table, i); } // make it clickable to sort headrow[i].sorttable_columnindex = i; headrow[i].sorttable_tbody = table.tBodies[0]; headrow[i].className += " clickable"; sorttable.initializeHeader(headrow[i]); // Build the sort handler dean_addEvent(headrow[i], "click", function(e) { var customClickHandler = null; if (customClickHanderName) { customClickHandler = window[customClickHanderName]; } if (this.className.search(/\bsorttable_sorted\b/) != -1) { // if we're already sorted by this column, just // reverse the table, which is quicker if (!customClickHanderName) { sorttable.reverse(this.sorttable_tbody); } this.className = this.className.replace("sorttable_sorted", "sorttable_sorted_reverse"); this.removeChild(document.getElementById("sorttable_sortfwdind")); sortrevind = document.createElement("span"); sortrevind.id = "sorttable_sortrevind"; sortrevind.className = "sortable_reverse"; sortrevind.innerHTML = stIsIE ? ' 5' : " ▴"; this.appendChild(sortrevind); if (customClickHandler) { // Normalize the event for ie. if (!e.currentTarget) { e.currentTarget = this; } customClickHandler(e); } return; } if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) { // if we're already sorted by this column in reverse, just // re-reverse the table, which is quicker if (!customClickHanderName) { sorttable.reverse(this.sorttable_tbody); } this.className = this.className.replace("sorttable_sorted_reverse", "sorttable_sorted"); this.removeChild(document.getElementById("sorttable_sortrevind")); sortfwdind = document.createElement("span"); sortfwdind.id = "sorttable_sortfwdind"; sortfwdind.className = "sortable_forward"; sortfwdind.innerHTML = stIsIE ? ' 6' : " ▾"; this.appendChild(sortfwdind); if (customClickHandler) { // Normalize the event for ie. if (!e.currentTarget) { e.currentTarget = this; } customClickHandler(e); } return; } // remove sorttable_sorted classes theadrow = this.parentNode; forEach(theadrow.childNodes, function(cell) { if (cell.nodeType == 1) { // an element cell.className = cell.className.replace("sorttable_sorted_reverse", ""); cell.className = cell.className.replace("sorttable_sorted", ""); } }); sortfwdind = document.getElementById("sorttable_sortfwdind"); if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); } sortrevind = document.getElementById("sorttable_sortrevind"); if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); } // Customize the initial direction for this column. var isDefaultReverse = this.getAttribute("sortable-default-reverse") === "1"; if (!isDefaultReverse) { this.className += " sorttable_sorted"; sortfwdind = document.createElement("span"); sortfwdind.id = "sorttable_sortfwdind"; sortfwdind.innerHTML = stIsIE ? ' 6' : " ▾"; this.appendChild(sortfwdind); } else { this.className += " sorttable_sorted_reverse"; sortrevind = document.createElement("span"); sortrevind.id = "sorttable_sortrevind"; sortrevind.className = "sortable_reverse"; sortrevind.innerHTML = stIsIE ? ' 5' : " ▴"; this.appendChild(sortrevind); } if (customClickHandler) { // Normalize the event for ie. if (!e.currentTarget) { e.currentTarget = this; } // Rely on this method to trigger sorting, client or server customClickHandler(e); } else { // Do the client sorting // build an array to sort. This is a Schwartzian transform thing, // i.e., we "decorate" each row with the actual sort key, // sort based on the sort keys, and then put the rows back in order // which is a lot faster because you only do getInnerText once per row row_array = []; col = this.sorttable_columnindex; rows = this.sorttable_tbody.rows; for (var j = 0; j < rows.length; j++) { row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]]; } row_array.sort(this.sorttable_sortfunction); // sorttable.shaker_sort(row_array, this.sorttable_sortfunction); tb = this.sorttable_tbody; for (var j = 0; j < row_array.length; j++) { var new_class, other_class; if ((j % 2) == 0) { new_class = "info-even"; other_class = "info-odd"; } else { new_class = "info-odd"; other_class = "info-even"; } var row_class = row_array[j][1].className; row_class = row_class.replace(other_class, new_class).replace(/^\s+|\s+$/, "").replace(/\s+/, " "); row_array[j][1].className = row_class; tb.appendChild(row_array[j][1]); } delete row_array; } }); } } }, initializeHeader: function(current) { if (current.className.search(/\bsorttable_sorted\b/) != -1) { sortfwdind = document.createElement("span"); sortfwdind.id = "sorttable_sortfwdind"; sortfwdind.className = "sortable_forward"; sortfwdind.innerHTML = stIsIE ? ' 6' : " ▾"; current.appendChild(sortfwdind); } if (current.className.search(/\bsorttable_sorted_reverse\b/) != -1) { sortrevind = document.createElement("span"); sortrevind.id = "sorttable_sortrevind"; sortrevind.className = "sortable_reverse"; sortrevind.innerHTML = stIsIE ? ' 5' : " ▴"; current.appendChild(sortrevind); } }, guessType: function(table, column) { // guess the type of a column based on its first non-blank row sortfn = sorttable.sort_alpha; if (!table.tBodies[0]) { return sortfn; } for (var i = 0; i < table.tBodies[0].rows.length; i++) { text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]); if (text != "") { if (text.match(/^-?[�$�]?[\d,.]+%?\s(Bytes|KB|MB|GB|TB|PB)$/)) { return sorttable.sort_space; } if (text.match(/^-?[�$�]?[\d,.]+%?$/)) { return sorttable.sort_numeric; } // check for a date: dd/mm/yyyy or dd/mm/yy // can have / or . or - as separator // can be mm/dd as well possdate = text.match(sorttable.DATE_RE); if (possdate) { // looks like a date first = parseInt(possdate[1]); second = parseInt(possdate[2]); if (first > 12) { // definitely dd/mm return sorttable.sort_ddmm; } else if (second > 12) { return sorttable.sort_mmdd; } else { // looks like a date, but we can't tell which, so assume // that it's dd/mm (English imperialism!) and keep looking sortfn = sorttable.sort_ddmm; } } } } return sortfn; }, getInnerText: function(node) { // gets the text we want to use for sorting for a cell. // strips leading and trailing whitespace. // this is *not* a generic getInnerText function; it's special to sorttable. // for example, you can override the cell text with a customkey attribute. // it also gets .value for fields. if (!node) { return ""; } hasInputs = (typeof node.getElementsByTagName == "function") && node.getElementsByTagName("input").length; if (node.nodeType != 3 && node.getAttribute("sorttable_customkey") != null) { return node.getAttribute("sorttable_customkey"); } else if (typeof node.textContent != "undefined" && !hasInputs) { return node.textContent.replace(/^\s+|\s+$/g, ""); } else if (typeof node.innerText != "undefined" && !hasInputs) { return node.innerText.replace(/^\s+|\s+$/g, ""); } else if (typeof node.text != "undefined" && !hasInputs) { return node.text.replace(/^\s+|\s+$/g, ""); } else { switch (node.nodeType) { case 3: if (node.nodeName.toLowerCase() == "input") { return node.value.replace(/^\s+|\s+$/g, ""); } case 4: return node.nodeValue.replace(/^\s+|\s+$/g, ""); break; case 1: case 11: var innerText = ""; for (var i = 0; i < node.childNodes.length; i++) { innerText += sorttable.getInnerText(node.childNodes[i]); } return innerText.replace(/^\s+|\s+$/g, ""); break; default: return ""; } } }, reverse: function(tbody) { // reverse the rows in a tbody newrows = []; for (var i = 0; i < tbody.rows.length; i++) { newrows[newrows.length] = tbody.rows[i]; } for (var i = newrows.length - 1; i >= 0; i--) { tbody.appendChild(newrows[i]); } delete newrows; }, /* sort functions each sort function takes two parameters, a and b you are comparing a[0] and b[0] */ sort_space: function(a, b) { abytesunit = a[0].split(/\s+/); aa = unit_to_bytes(abytesunit[0], abytesunit[1]); if (isNaN(aa)) { aa = 0; } bbytesunit = b[0].split(/\s+/); bb = unit_to_bytes(bbytesunit[0], bbytesunit[1]); if (isNaN(bb)) { bb = 0; } return aa - bb; }, sort_numeric: function(a, b) { aa = parseFloat(a[0].replace(/[^0-9.-]/g, "")); if (isNaN(aa)) { aa = 0; } bb = parseFloat(b[0].replace(/[^0-9.-]/g, "")); if (isNaN(bb)) { bb = 0; } return aa - bb; }, sort_alpha: function(a, b) { if (a[0] == b[0]) { return 0; } if (a[0] < b[0]) { return -1; } return 1; }, sort_ddmm: function(a, b) { mtch = a[0].match(sorttable.DATE_RE); y = mtch[3]; m = mtch[2]; d = mtch[1]; if (m.length == 1) { m = "0" + m; } if (d.length == 1) { d = "0" + d; } dt1 = y + m + d; mtch = b[0].match(sorttable.DATE_RE); y = mtch[3]; m = mtch[2]; d = mtch[1]; if (m.length == 1) { m = "0" + m; } if (d.length == 1) { d = "0" + d; } dt2 = y + m + d; if (dt1 == dt2) { return 0; } if (dt1 < dt2) { return -1; } return 1; }, sort_mmdd: function(a, b) { mtch = a[0].match(sorttable.DATE_RE); y = mtch[3]; d = mtch[2]; m = mtch[1]; if (m.length == 1) { m = "0" + m; } if (d.length == 1) { d = "0" + d; } dt1 = y + m + d; mtch = b[0].match(sorttable.DATE_RE); y = mtch[3]; d = mtch[2]; m = mtch[1]; if (m.length == 1) { m = "0" + m; } if (d.length == 1) { d = "0" + d; } dt2 = y + m + d; if (dt1 == dt2) { return 0; } if (dt1 < dt2) { return -1; } return 1; }, shaker_sort: function(list, comp_func) { // A stable sort function to allow multi-level sorting of data // see: http://en.wikipedia.org/wiki/Cocktail_sort // thanks to Joseph Nahmias var b = 0; var t = list.length - 1; var swap = true; while (swap) { swap = false; for (var i = b; i < t; ++i) { if ( comp_func(list[i], list[i + 1]) > 0 ) { var q = list[i]; list[i] = list[i + 1]; list[i + 1] = q; swap = true; } } // for t--; if (!swap) { break; } for (var i = t; i > b; --i) { if ( comp_func(list[i], list[i - 1]) < 0 ) { var q = list[i]; list[i] = list[i - 1]; list[i - 1] = q; swap = true; } } // for b++; } // while(swap) } }; /* ****************************************************************** Supporting functions: bundled here to avoid depending on a library ****************************************************************** */ YAHOO.util.Event.onDOMReady(sorttable.init); // written by Dean Edwards, 2005 // with input from Tino Zijdel, Matthias Miller, Diego Perini // http://dean.edwards.name/weblog/2005/10/add-event/ function dean_addEvent(element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else { // assign each event handler a unique ID if (!handler.$$guid) { handler.$$guid = dean_addEvent.guid++; } // create a hash table of event types for the element if (!element.events) { element.events = {}; } // create a hash table of event handlers for each element/event pair var handlers = element.events[type]; if (!handlers) { handlers = element.events[type] = {}; // store the existing event handler (if there is one) if (element["on" + type]) { handlers[0] = element["on" + type]; } } // store the event handler in the hash table handlers[handler.$$guid] = handler; // assign a global event handler to do all the work element["on" + type] = handleEvent; } }; // a counter used to create unique IDs dean_addEvent.guid = 1; function removeEvent(element, type, handler) { if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else { // delete the event handler from the hash table if (element.events && element.events[type]) { delete element.events[type][handler.$$guid]; } } }; function handleEvent(event) { var returnValue = true; // grab the event object (IE uses a global event object) event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event); // get a reference to the hash table of event handlers var handlers = this.events[event.type]; // execute each event handler for (var i in handlers) { this.$$handleEvent = handlers[i]; if (this.$$handleEvent(event) === false) { returnValue = false; } } return returnValue; }; function fixEvent(event) { // add W3C standard event methods event.preventDefault = fixEvent.preventDefault; event.stopPropagation = fixEvent.stopPropagation; return event; }; fixEvent.preventDefault = function() { this.returnValue = false; }; fixEvent.stopPropagation = function() { this.cancelBubble = true; }; // Dean's forEach: http://dean.edwards.name/base/forEach.js /* forEach, version 1.0 Copyright 2006, Dean Edwards License: http://www.opensource.org/licenses/mit-license.php */ // array-like enumeration if (!Array.forEach) { // mozilla already supports this Array.forEach = function(array, block, context) { for (var i = 0; i < array.length; i++) { block.call(context, array[i], i, array); } }; } // generic enumeration Function.prototype.forEach = function(object, block, context) { for (var key in object) { if (typeof this.prototype[key] == "undefined") { block.call(context, object[key], key, object); } } }; // character enumeration String.forEach = function(string, block, context) { Array.forEach(string.split(""), function(chr, index) { block.call(context, chr, index, string); }); }; // globally resolve forEach enumeration var forEach = function(object, block, context) { if (object) { var resolve = Object; // default if (object instanceof Function) { // functions have a "length" property resolve = Function; } else if (object.forEach instanceof Function) { // the object implements a custom forEach method so use that object.forEach(block, context); return; } else if (typeof object == "string") { // the object is a string resolve = String; } else if (typeof object.length == "number") { // the object is array-like resolve = Array; } resolve.forEach(object, block, context); } }; function unit_to_bytes(num, bytes) { switch (bytes) { case "KB": return parseFloat(num) * 1024; case "MB": return parseFloat(num) * 1024 * 1024; case "GB": return parseFloat(num) * 1024 * 1024 * 1024; case "TB": return parseFloat(num) * 1024 * 1024 * 1024 * 1024; case "PB": return parseFloat(num) * 1024 * 1024 * 1024 * 1024 * 1024; default: return parseFloat(num); } } /* ***** BEGIN LICENSE BLOCK ***** # cpanel12 - xmlapi.js Copyright(c) 1997-2020 cPanel, L.L.C. # All rights reserved. # copyright@cpanel.net http://cpanel.net # This code is subject to the cPanel license. Unauthorized copying is prohibited * ***** END LICENSE BLOCK ***** * ***** BEGIN APPLICABLE CODE BLOCK ***** */ var use_fast_proto = 1; function cpanel_api1() { var argv = cpanel_api1.arguments; var mycallback = argv[0]; var module = argv[1]; var func = argv[2]; var argc = argv.length; var callback = { success: cpanel_api1_parser, argument: mycallback }; var sFormData; if (use_fast_proto) { sFormData = "cpanel_xmlapi_module=" + encodeURIComponent(module) + "&cpanel_xmlapi_func=" + encodeURIComponent(func) + "&cpanel_xmlapi_apiversion=1"; var argnum = 0; for (var i = 3; i < argc; i++) { sFormData += "&arg-" + argnum + "=" + encodeURIComponent(argv[i]); argnum++; } } else { sFormData = "xmlin=1" + module + "" + func + ""; for (var i = 3; i < argc; i++) { sFormData += "" + argv[i] + ""; } sFormData += ""; } if (sFormData.length < 2000) { YAHOO.util.Connect.asyncRequest("GET", CPANEL.security_token + "/xml-api/cpanel?" + sFormData, callback); } else { YAHOO.util.Connect.asyncRequest("POST", CPANEL.security_token + "/xml-api/cpanel", callback, sFormData); } } function cpanel_api1_parser(o) { var mycallback = o.argument; var rootNode = o.responseXML; var cpanelresultEl = rootNode.getElementsByTagName("cpanelresult")[0]; var cpaneldataEl = cpanelresultEl.getElementsByTagName("data")[0]; var dataresultEl = cpaneldataEl.getElementsByTagName("result")[0]; var parsed_data; if (dataresultEl.firstChild) { parsed_data = dataresultEl.firstChild.nodeValue; } if (mycallback) { mycallback(parsed_data); } } function cpanel_api2() { var argv = cpanel_api2.arguments; var mycallback = argv[0]; var module = argv[1]; var func = argv[2]; var argc = argv.length; var callback = { success: cpanel_api2_parser, argument: mycallback }; var sFormData; if (use_fast_proto) { sFormData = "cpanel_xmlapi_module=" + encodeURIComponent(module) + "&cpanel_xmlapi_func=" + encodeURIComponent(func) + "&cpanel_xmlapi_apiversion=2"; for (var i = 3; i < argc; i += 2) { sFormData += "&" + encodeURIComponent(argv[i]) + "=" + encodeURIComponent(argv[i + 1]); } } else { sFormData = "xmlin=2" + module + "" + func + ""; for (var i = 3; i < argc; i += 2) { sFormData += "<" + argv[i] + ">" + argv[i + 1] + ""; } sFormData += ""; } if (sFormData.length < 2000) { YAHOO.util.Connect.asyncRequest("GET", CPANEL.security_token + "/xml-api/cpanel?" + sFormData, callback); } else { YAHOO.util.Connect.asyncRequest("POST", CPANEL.security_token + "/xml-api/cpanel", callback, sFormData); } } function cpanel_api2_parser(o) { var mycallback = o.argument; var rootNode = o.responseXML; var cpanelresultEl = rootNode.getElementsByTagName("cpanelresult")[0]; var cpaneldataEl = cpanelresultEl.getElementsByTagName("data"); if (mycallback) { mycallback(cpaneldataEl); } } /* ***** BEGIN LICENSE BLOCK ***** # cpanel12 - jsonapi.js Copyright(c) 1997-2020 cPanel, L.L.C. # All rights reserved. # copyright@cpanel.net http://cpanel.net # This code is subject to the cPanel license. Unauthorized copying is prohibited * ***** END LICENSE BLOCK ***** * ***** BEGIN APPLICABLE CODE BLOCK ***** */ function cpanel_jsonapi1() { var argv = cpanel_jsonapi1.arguments; var mycallback = argv[0]; var module = argv[1]; var func = argv[2]; var argc = argv.length; var callback = { success: cpanel_jsonapi1_parser, failure: mycallback, argument: mycallback }; var sFormData = "cpanel_jsonapi_module=" + encodeURIComponent(module) + "&cpanel_jsonapi_func=" + encodeURIComponent(func) + "&cpanel_jsonapi_apiversion=1"; var argnum = 0; for (var i = 3; i < argc; i++) { sFormData += "&arg-" + argnum + "=" + encodeURIComponent(argv[i]); argnum++; } if (sFormData.length < 2000) { YAHOO.util.Connect.asyncRequest("GET", CPANEL.security_token + "/json-api/cpanel?" + sFormData, callback); } else { YAHOO.util.Connect.asyncRequest("POST", CPANEL.security_token + "/json-api/cpanel", callback, sFormData); } } function cpanel_jsonapi1_parser(o) { var mycallback = o.argument; var jsonCode = fastJsonParse(o.responseText); if (mycallback) { mycallback(jsonCode.cpanelresult.data.result); } } function cpanel_jsonapi2() { var argv = cpanel_jsonapi2.arguments; var mycallback = argv[0]; var module = argv[1]; var func = argv[2]; var argc = argv.length; var callback = { success: cpanel_jsonapi2_parser, failure: mycallback, argument: mycallback }; var sFormData = "cpanel_jsonapi_module=" + encodeURIComponent(module) + "&cpanel_jsonapi_func=" + encodeURIComponent(func) + "&cpanel_jsonapi_apiversion=2"; for (var i = 3; i < argc; i += 2) { sFormData += "&" + encodeURIComponent(argv[i]) + "=" + encodeURIComponent(argv[i + 1]); } if (sFormData.length < 2000) { YAHOO.util.Connect.asyncRequest("GET", CPANEL.security_token + "/json-api/cpanel?" + sFormData, callback); } else { YAHOO.util.Connect.asyncRequest("POST", CPANEL.security_token + "/json-api/cpanel", callback, sFormData); } } function cpanel_jsonapi2_parser(o) { var mycallback = o.argument; var jsonCode = fastJsonParse(o.responseText); if (mycallback) { mycallback(jsonCode.cpanelresult.data); } } var validate_data_panel_initted = 0; var validate_data_panel; var realtime_validate_inited = {}; var cached_url_depth; var validate_working_form; var valImgs = []; var validateElMap = {}; var check_elements = {}; var match_validators = { /* email validations */ "fullemailaddress": eval("/^([a-zA-Z0-9\_\'\+\*\$\%\^\&\!\.\-])+[\@\+](([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9:]{2,4})+$/"), "emailcharplus": eval("/^([a-zA-Z0-9\_\'\+.\-])/"), "emailaddress": /^[^\@]\@[^\.]\./, "emailchars": /^[a-z0-9\_\-\@\.]+$/, /* http://www.remote.org/jochen/mail/info/chars.html*/ "email_localpart_chars": /^\w[\w-.+%]*/, /* C. Oakman - changed this to match our backend validation script */ "email_localpart_chars_cap": /^[A-Za-z0-9\_\-\.]+$/, /* http://www.remote.org/jochen/mail/info/chars.html*/ "atsign": /\@/, "notestsign": /\@/, /* hosts, domains and ip addresses */ "hostname": /^((\*\.|[a-zA-Z0-9])([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/, "fqdn_domain": /^((\*\.|[a-zA-Z0-9])([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.){2}[a-zA-Z]{2,6}$/, "fullipaddr": /^(\d{1,3}\.){3}\d{1,3}$/, "is_ipcidr_or_host": /^[a-z0-9\.\-\/]+$/, "ipcidr": /^\d+\.\d+\.\d+\.\d+\/?\d*$/, "host": /^[\w\.\-]+$/, "wildhost": /^[\*\w\.\-]+$/, "wildhostsql": /^[\%\w\.\-]+$/, /* number */ "unlimitedornum": /^[0-9]*$|^unlimited$/, "numeric": /^[0-9]+$/, "decimal_numeric": /^[-+]?[0-9]+(\.[0-9]+)?$/, "decimal_numeric_unlimited": /^[-+]?[0-9]+(\.[0-9]+)?$|^unlimited$/, /* alpha */ "alphanum": /^[a-z0-9\_\-]+$/i, /* web validations */ "start_www.": /^www[.]/i, /* files */ "jpg_gif_png_jpeg": /\.(gif|jpg|png|jpeg)$/, "html": /\.(html)$/, /* misc */ "spaces_dots_ats_fwdslashes_hyphens": /[\s\.\@\/\-]/, "spaces_dots_ats_fwdslashes": /[\s\.\@\/]+/, "two_dots": /[^\.]\.[^\.]\.[^\.]/, "spaces_ats_fwdslashes": /[\s\@\/]+/, "start_end_dashes": /(?:^[-]|[-]$)/, "start_end_space": /(?:^[\s]|[\s]$)/, "slashes_dots": /[\.\/\\]/, "noascii0_255": /[\0\255]/, "spaces": /\s+/, "forwardslash": /\//, "dot": /\./, "empty": /^$/, "start_end_dots": /(^[.]|[.]$)/, "start_dot": /^\./, "underscore": /\_/, "protocol": /^\S+[:][/][/]/, "only_spaces": /^\s+$/, /* TLS */ "ssl_chars": /^[\-\w\!\+\@\~\:]+$/, /* Dovecot, Courier, and FTP Config values */ "whole_nums": /^\d+$/, "1_9only": /^[1-9]$/ }; var offsetQuirk = 0; if (navigator.appVersion.indexOf("MSIE") != -1 || navigator.appVersion.indexOf("Opera") != -1) { offsetQuirk = 1; } var validgen = 0; var validateFocusEl; var validators = {}; var newest_listener; /* register_validator('FORMID','nomatch','empty',[document.mainform.password],"A password must be specified."); register_validator('FORMID','nomatch','spaces',[document.mainform.email],"Sorry, the username cannot contain any spaces."); register_validator('FORMID','nomatch','atsign',[document.mainform.email],"Sorry, the username cannot contain an @ sign."); register_validator('FORMID','nomatch','forwardslash',[document.mainform.email],"Sorry, the username cannot contain a forward slash ."); register_validator('FORMID','match','unlimitedornum',[document.mainform.quota],"Sorry, quota must be a number or unlimited."); register_validator('FORMID','Eleq','',[document.mainform.password,document.mainform.password2],"The passwords don't match. please retry."); */ function password_strength_validator_init() { if (!self["passkey_handler"]) { alert("Javascript Order Error. You cannot call password_strength_validator_init before passkey_handler has been loaded."); return; } passkey_handler(); hide_password_tip_panel(); } function init_validate_dialog() { if (validate_data_panel_initted) { return; } validate_data_panel_initted = 1; if (!document.getElementById("validate_data_panel")) { var newpanel = document.createElement("div"); newpanel.id = "validate_data_panel"; newpanel.style.display = "none"; newpanel.innerHTML = '
    Inputs not Valid!
    '; document.body.appendChild(newpanel); } validate_data_panel = new YAHOO.widget.Dialog("validate_data_panel", { width: "300px", fixedcenter: true, constraintoviewport: true, close: true, draggable: false, modal: false, buttons: [{ text: "Close", handler: function() { validate_data_panel.hide(); }, isDefault: true }], visible: false }); validate_data_panel.beforeHideEvent.subscribe(handle_hide_validate, validate_data_panel, true); validate_data_panel.render(); validate_data_panel.hide(); document.getElementById("validate_data_panel").style.display = ""; } var handle_hide_validate = function() { if (validateFocusEl) { validateFocusEl.focus(); } }; function realtime_validate_init(formId) { if (!formId) { alert("realtime_validate_init must be called with a formId"); return; } if (realtime_validate_inited[formId]) { return; } realtime_validate_inited[formId] = 1; YAHOO.util.Event.addListener(window, "resize", reposition_all_validator_imgs); if (!validators[formId]) { alert("No validators registerd for that formId: " + formId); return; } for (var i = 0; i < validators[formId].length; i++) { var Els = validators[formId][i].Els; for (var j = 0; j < Els.length; j++) { if (!Els[j].id) { Els[j].id = "validgen" + validgen++; } validateElMap[Els[j].id] = formId; } } for (var elId in validateElMap) { var thisEl = document.getElementById(elId); if (thisEl.tagName == "TEXTAREA" || thisEl.type == "text" || thisEl.type == "password" || thisEl.type == "textbox") { YAHOO.util.Event.addListener(thisEl, "keyup", function() { single_validate(this.id); }, thisEl, true); } else if (thisEl.tagName == "SELECT" || thisEl.type == "file") { YAHOO.util.Event.addListener(thisEl, "change", function() { single_validate(this.id); }, thisEl, true); } } } function single_validate(ElId, formId) { if (!formId) { formId = validateElMap[ElId]; } if (!formId) { formId = document.getElementById(ElId).form.id; } do_validate(formId, 1, 0, ElId); } function validate_box(ElId, formId) { if (!formId) { formId = validateElMap[ElId]; } if (!formId) { formId = document.getElementById(ElId).form.id; } do_validate(formId, 0, 1, ElId); } function do_validate(formId, noalert, noupdate, check_element) { var form_valid = 1; if (!formId) { alert("do_validate requires at least one argument (formId)"); return false; } var alerts = []; var element_statuses = {}; var formValidators = validators[formId] || []; validateFocusEl = 0; if (check_element && check_element != "" && check_elements[check_element] == null) { check_elements[check_element] = {}; for (var i = 0; i < formValidators.length; i++) { var add_elements = 0; for (var ei = 0; ei < formValidators[i].Els.length; ei++) { if (formValidators[i].Els[ei].id == check_element) { add_elements = 1; break; } } if (add_elements) { for (var ei = 0; ei < formValidators[i].Els.length; ei++) { check_elements[check_element][formValidators[i].Els[ei].id] = 1; } } } } for (var i = 0; i < formValidators.length; i++) { var currentValidator = formValidators[i]; if (currentValidator.required) { if (!currentValidator.required()) { for (var ei = 0; ei < currentValidator.Els.length; ei++) { setup_accept_image(currentValidator.Els[ei].id, 2); YAHOO.util.Dom.removeClass(currentValidator.Els[ei], "formverifyfailed"); } continue; } } if (check_element && check_element != "") { var affects_this = 0; for (var ei = 0; ei < currentValidator.Els.length; ei++) { if (check_elements[check_element][currentValidator.Els[ei].id]) { affects_this = 1; } } if (!affects_this) { continue; } } var is_valid = 1; var els = currentValidator.Els[0]; switch (currentValidator.method) { case "match": var matchkey = (typeof (currentValidator.vkey) == "string" ? match_validators[currentValidator.vkey] : currentValidator.vkey); if (matchkey == null) { alert("Unknown regex key used for match: " + currentValidator.vkey + ". Valid keys are: " + validate_listmatchers()); } if (!currentValidator.Els[0].value.match(matchkey)) { is_valid = 0; } break; case "nomatch": var matchkey = (typeof (currentValidator.vkey) == "string" ? match_validators[currentValidator.vkey] : currentValidator.vkey); if (matchkey == null) { alert("Unknown regex key used for match: " + currentValidator.vkey + ". Valid keys are: " + validate_listmatchers()); } if (currentValidator.method == "match") { /* match*/ if (!els.value.match(matchkey)) { is_valid = 0; } } else { /* no match*/ if (els.value.match(matchkey)) { is_valid = 0; } } break; case "noeqtxt": if (els.value == currentValidator.vkey) { is_valid = 0; } break; case "minlength": if (els.value.length < currentValidator.vkey) { is_valid = 0; } break; case "maxlength": if (els.value.length > currentValidator.vkey) { is_valid = 0; } break; case "NotEleq": if (els.value == currentValidator.Els[1].value) { is_valid = 0; } break; case "Eleq": if (els.value != currentValidator.Els[1].value) { is_valid = 0; } break; case "func": var myfunc = currentValidator.vkey; if (!myfunc(currentValidator.Els)) { is_valid = 0; } break; default: alert("Unknown validator: " + currentValidator.method); form_valid = 0; make_elements_valid_status(currentValidator.Els, 0, element_statuses); } if (!is_valid) { if (!currentValidator.msg || currentValidator.msg.match(/^\s*$/)) { alert("Missing validation message for validator: " + currentValidator.method + " key: " + currentValidator.vkey); } alerts.push(currentValidator.msg); if (!validateFocusEl) { validateFocusEl = currentValidator.Els[0]; } make_elements_valid_status(currentValidator.Els, 0, element_statuses); form_valid = 0; } else { make_elements_valid_status(currentValidator.Els, 1, element_statuses); } } if (!noupdate) { apply_elements_status(element_statuses); } if (!noalert && alerts.length) { init_validate_dialog(); // validate_data_panel.setHeader("Inputs not Valid!"); var formatted_alerts = []; for (var i = 0; i < alerts.length; i++) { formatted_alerts.push('

    ' + alerts[i] + "

    "); } document.getElementById("inputs_val").innerHTML = formatted_alerts.join("\n"); validate_data_panel.show(); validateFocusEl.focus(); } return (form_valid ? true : false); } function register_validator(validatemethod, vkey, validateEls, vmsg, required, formId) { if (!vmsg) { alert("register_validator requires 4 arguments: (validatemethod, vkey, validateEls, vmsg, [required func]"); return; } if (self.password_str_handle_validate) { password_str_handle_validate = 0; } if (!formId && validateEls && validateEls.length > 0 && !!validateEls[0]) { formId = validateEls[0].form.id; } if (!formId) { alert("register_validator requires either a list of form elements from which the formId could be derived or the formId parameter."); return; } if (!validators[formId] || validators[formId] == null) { validators[formId] = []; } validators[formId].push({ method: validatemethod, vkey: vkey, Els: validateEls, msg: vmsg, required: required }); } var reset_validators = function() { validators = {}; }; var _deactivate_validator = function(formId, formValidators, validatorId) { // if auto realtime_validate is enabled remove the action if (realtime_validate_inited[formId]) { for (var elId = 0; elId < formValidators[validatorId].Els; elId++) { var thisEl = formValidators[validatorId].Els[elId]; if (thisEl.tagName == "TEXTAREA" || thisEl.type == "text" || thisEl.type == "password" || thisEl.type == "textbox") { YAHOO.util.Event.removeListener(thisEl, "keyup"); } else if (thisEl.tagName == "SELECT" || thisEl.type == "file") { YAHOO.util.Event.removeListener(thisEl, "change"); } } } formValidators.splice(validatorId, 1); // remove the validator }; var remove_validator = function(config) { if (!config.formid && !config.action && !config.elementid) { alert("please pass {formid:'element_id', action:'validator_action', elementid:'elementname'}"); } else { var formValidators = validators[config.formid]; // This is a reference to the array of validators for this form // Search though the array of validators for the one we one and call _deactivate_validator // on it once we find the element in it for (var validatorId = 0; validatorId < formValidators.length; validatorId++) { if (formValidators[validatorId].vkey === config.action) { // check to see if there is more than one element and process each for (var elId = 0; elId < formValidators[validatorId].Els.length; elId++) { if (formValidators[validatorId].Els[elId].id === config.elementid) { _deactivate_validator(config.formid, formValidators, validatorId); break; } } } } } }; function apply_elements_status(elist) { for (var elId in elist) { if (elist[elId]) { setup_accept_image(elId, 1); YAHOO.util.Dom.removeClass(elId, "formverifyfailed"); } else { setup_accept_image(elId, 0); YAHOO.util.Dom.addClass(elId, "formverifyfailed"); } } } function setup_accept_image(parentElId, show) { var imgElIdCon = parentElId + "_status_image_con"; var imgElCon = document.getElementById(imgElIdCon); if (!imgElCon) { var parentEl = document.getElementById(parentElId); var newdiv = document.createElement("div"); newdiv.style.display = "block"; newdiv.style.position = "absolute"; newdiv.style.padding = 0; newdiv.style.margin = 0; newdiv.id = imgElIdCon; newdiv.innerHTML = " "; if (show) { newdiv.className = "accept"; } else { newdiv.className = "reject"; } if (parentEl.nextSibling) { parentEl.parentNode.insertBefore(newdiv, parentEl.nextSibling); } else { parentEl.parentNode.appendChild(newdiv); } imgElCon = newdiv; reposition_validator_img(imgElCon); YAHOO.util.Event.addListener(imgElCon, "click", function() { validate_box(getPreviousInput(this).id); }, imgElCon, true); valImgs.push(imgElCon.id); return; } if (show == 2) { imgElCon.style.display = "none"; } else if (show) { imgElCon.className = "accept"; imgElCon.style.display = ""; } else { imgElCon.className = "reject"; imgElCon.style.display = ""; } } function reposition_all_validator_imgs() { for (var i = 0; i < valImgs.length; i++) { reposition_validator_img(document.getElementById(valImgs[i])); } } function reposition_validator_img(imgElCon) { parentElId = getPreviousInput(imgElCon).id; parentEl = document.getElementById(parentElId); if (!parentEl) { alert("Could not get parent for " + parentElId + " next aw: " + imgElCon.id); return; } var parentReg = YAHOO.util.Region.getRegion(parentEl); // check to see if the input element has a specific validator positioning class var parentElPos; if (YAHOO.util.Dom.hasClass(parentEl, "validator_position_right") == true) { parentElPos = "right"; } if ((parentElPos && parentElPos == "right") || parentEl.tagName == "SELECT" || parentEl.tagName == "TEXTAREA" || parentEl.type == "file") { imgElCon.style.left = (parentReg.left + parentEl.offsetWidth + 3) + "px"; } else { imgElCon.style.left = (parentReg.left + parentEl.offsetWidth - 16 - (offsetQuirk ? 4 : 2)) + "px"; } imgElCon.style.top = (parentReg.top + ((parentEl.offsetHeight - 16) / 2) - (offsetQuirk ? 2 : 0)) + "px"; } function make_elements_valid_status(Els, status, elist) { for (var i = 0; i < Els.length; i++) { if (!Els[i].id) { Els[i].id = "validgen" + validgen++; } if (i > 0) { continue; } /* ignore elements that are not first in the list */ if (status && elist[Els[i].id] != 0) { elist[Els[i].id] = 1; } else { elist[Els[i].id] = 0; } } } function getPreviousInput(El) { while (El.previousSibling && (El.tagName != "INPUT" || El.type == "submit" || El.type == "button") && El.tagName != "SELECT" && El.tagName != "TEXTAREA") { El = El.previousSibling; } return El; } function validate_listmatchers() { var allowed_matchers = []; for (var matcher in match_validators) { allowed_matchers.push(matcher); } return allowed_matchers.join(" "); } function get_url_depth() { if (cached_url_depth) { return cached_url_depth; } var thisurl = window.location.href; var urlpath = thisurl.split("/"); urlpath.shift(); // http urlpath.shift(); // : urlpath.shift(); // HOST urlpath.pop(); // PAGE if (thisurl.match(/\/frontend\//)) { urlpath.shift(); urlpath.shift(); } var dotdot = []; for (i = 0; i < urlpath.length; i++) { dotdot.push(".."); } cached_url_depth = dotdot.join("/"); return cached_url_depth; } function radio_value_is(El, val) { if (isArray(El)) { for (var i = 0; i < El.length; i++) { if (El[i].value == val && El[i].checked) { return true; } } } else { if (El.value == val && El.checked) { return true; } } return false; } function isArray(tobj) { if (tobj.length > 0) { if (tobj[0] && tobj[0].length == 1) { return false; } return true; } return false; } var popupwindows = {}; function popupwindow_init(Elid, pixels, opts) { // Modified 5/1/12 -- can optionally pass opts {} which will override the // default initialization. IE (opts = {fixedcenter=false,modal=true}) will // override fixedcenter's true default and add a modal true value to // the initialization. No other values are touched. PAH var Elid; if (popupwindows[Elid]) { return; } if (!opts) { opts = {}; } if (!pixels) { pixels = "500px"; } var init = { effect: { effect: YAHOO.widget.ContainerEffect.FADE, duration: 0.25 }, width: pixels, buttons: [{ text: "Close", handler: function() { popupwindows[Elid].hide(); }, isDefault: true }], fixedcenter: true, constraintoviewport: true, underlay: "none", close: true, visible: false, draggable: true, modal: false }; for (var opt in opts) { init[opt] = opts[opt]; } document.getElementById(Elid).style.display = ""; popupwindows[Elid] = new YAHOO.widget.Dialog(Elid, init); popupwindows[Elid].render(); popupwindows[Elid].beforeHideEvent.subscribe(handle_hide_popupwindow, Elid, true); } function handle_hide_popupwindow(ev, inc, Elid) { set_popup_display(Elid, "none"); } function set_popup_display(Elid, dstyle) { var Elc = document.getElementById(Elid + "-content"); if (!Elc) { alert("The " + Elid + "'-content' id is missing"); } Elc.style.display = dstyle; var winc = document.getElementById(Elid + "_win"); if (!winc) { return; } winc.style.display = dstyle; } function popupwindow_hide(Elid) { popupwindows[Elid].hide(); } function popupwindow_show(Elid) { set_popup_display(Elid, ""); popupwindows[Elid].render(); popupwindows[Elid].show(); } /* ***** BEGIN LICENSE BLOCK ***** # cpanel12 - interfacereset.js Copyright(c) 1997-2020 cPanel, L.L.C. # All rights reserved. # copyright@cpanel.net http://cpanel.net # This code is subject to the cPanel license. Unauthorized copying is prohibited * ***** END LICENSE BLOCK ***** * ***** BEGIN APPLICABLE CODE BLOCK ***** */ var interfaceConfigs = []; function register_interfacecfg_nvdata(nvname) { interfaceConfigs.push(nvname); } var reset_all_interface_settings = function(securityToken) { var sFormData = "names=" + interfaceConfigs.join("|"); for (var i = 0; i < interfaceConfigs.length; i++) { sFormData += "&" + interfaceConfigs[i] + "="; NVData[interfaceConfigs[i]] = ""; } var successFunction = function() { window.location.reload(); }; var token = securityToken || CPANEL.security_token; var apiUrl = token + "/frontend/" + window.thisTheme + "/nvset.xml"; fetch(apiUrl, { method: "POST", body: sFormData, }) .then(function(res) { successFunction(); }) .catch(function(error) { console.error("Error:", error); }); }; register_interfacecfg_nvdata("ignorecharencoding");