/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
Version: 0.11.4
*/

/**
 * 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
 */

/**
 * The YAHOO global namespace object
 * @class YAHOO
 * @static
 */
if (typeof YAHOO == "undefined") {
    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
 * @method namespace
 * @static
 * @param  {String} ns The name of the namespace
 * @return {Object}    A reference to the namespace object
 */
YAHOO.namespace = function(ns) {

    if (!ns || !ns.length) {
        return null;
    }

    var levels = ns.split(".");
    var nsobj = YAHOO;

    // YAHOO is implied, so it is ignored if it is included
    for (var i=(levels[0] == "YAHOO") ? 1 : 0; i<levels.length; ++i) {
        nsobj[levels[i]] = nsobj[levels[i]] || {};
        nsobj = nsobj[levels[i]];
    }

    return nsobj;
};

/**
 * Uses YAHOO.widget.Logger to output a log message, if the widget is available.
 *
 * @method log
 * @static
 * @param  {string}  sMsg       The message to log.
 * @param  {string}  sCategory  The log category for the message.  Default
 *                              categories are "info", "warn", "error", time".
 *                              Custom categories can be used as well. (opt)
 * @param  {string}  sSource    The source of the the message (opt)
 * @return {boolean}            True if the log operation was successful.
 */
YAHOO.log = function(sMsg, sCategory, sSource) {
    var l = YAHOO.widget.Logger;
    if(l && l.log) {
        return l.log(sMsg, sCategory, sSource);
    } else {
        return false;
    }
};

/**
 * Utility to set up the prototype, constructor and superclass properties to
 * support an inheritance strategy that can chain constructors and methods.
 *
 * @method extend
 * @static
 * @param {function} subclass   the object to modify
 * @param {function} superclass the object to inherit
 */
YAHOO.extend = function(subclass, superclass) {
    var f = function() {};
    f.prototype = superclass.prototype;
    subclass.prototype = new f();
    subclass.prototype.constructor = subclass;
    subclass.superclass = superclass.prototype;
    if (superclass.prototype.constructor == Object.prototype.constructor) {
        superclass.prototype.constructor = superclass;
    }
};

YAHOO.namespace("util");
YAHOO.namespace("widget");
YAHOO.namespace("example");

//yahoo
/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
Version: 0.11.4
*/

/**
 * 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}  oScope 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 log system
 * @namespace YAHOO.util
 * @class CustomEvent
 * @constructor
 */
YAHOO.util.CustomEvent = function(type, oScope, silent) {

    /**
     * The type of event, returned to subscribers when the event fires
     * @property type
     * @type string
     */
    this.type = type;

    /**
     * The scope the the event will fire from by default.  Defaults to the window
     * obj
     * @property scope
     * @type object
     */
    this.scope = oScope || window;

    /**
     * By default all custom events are logged in the debug build, set silent
     * to true to disable logging for this event.
     * @property silent
     * @type boolean
     */
    this.silent = silent;

    /**
     * The subscribers to this event
     * @property subscribers
     * @type Subscriber[]
     */
    this.subscribers = [];

    if (!this.silent) {
    }

    // Only add subscribe events for events that are not generated by CustomEvent
    //if (oScope && (oScope.constructor != this.constructor)) {

        /*
         * 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.
         *
         * type CustomEvent
         */
        //this.subscribeEvent =
                //new YAHOO.util.CustomEvent("subscribe", this, true);

    //}
};

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}  bOverride If true, the obj passed in becomes the execution
     *                            scope of the listener
     */
    subscribe: function(fn, obj, bOverride) {
        //if (this.subscribeEvent) {
            //this.subscribeEvent.fire(fn, obj, bOverride);
        //}

        this.subscribers.push( new YAHOO.util.Subscriber(fn, obj, bOverride) );
    },

    /**
     * Unsubscribes the caller from this event
     * @method unsubscribe
     * @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 subscriber was found and detached.
     */
    unsubscribe: function(fn, obj) {
        var found = false;
        for (var i=0, len=this.subscribers.length; i<len; ++i) {
            var s = this.subscribers[i];
            if (s && s.contains(fn, obj)) {
                this._delete(i);
                found = true;
            }
        }

        return found;
    },

    /**
     * Notifies the subscribers.  The callback functions will be executed
     * from the scope specified when the event was created, and with the following
     * parameters:
     *   <pre>
     *   - 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
     *   </pre>
     * @method fire
     * @param {Array} an arbitrary set of parameters to pass to the handler
     */
    fire: function() {
        var len=this.subscribers.length;
        if (!len && this.silent) {
            return;
        }

        var args = [];

        for (var i=0; i<arguments.length; ++i) {
            args.push(arguments[i]);
        }

        if (!this.silent) {
        }

        for (i=0; i<len; ++i) {
            var s = this.subscribers[i];
            if (s) {
                if (!this.silent) {
                }
                var scope = (s.override) ? s.obj : this.scope;
                s.fn.call(scope, this.type, args, s.obj);
            }
        }
    },

    /**
     * Removes all listeners
     * @method unsubscribeAll
     */
    unsubscribeAll: function() {
        for (var i=0, len=this.subscribers.length; i<len; ++i) {
            this._delete(len - 1 - i);
        }
    },

    /**
     * @method _delete
     * @private
     */
    _delete: function(index) {
        var s = this.subscribers[index];
        if (s) {
            delete s.fn;
            delete s.obj;
        }

        // delete this.subscribers[index];
        this.subscribers.splice(index, 1);
    },

    /**
     * @method toString
     */
    toString: function() {
         return "CustomEvent: " + "'" + this.type  + "', " +
             "scope: " + 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}  bOverride If true, the obj passed in becomes the execution
 *                            scope of the listener
 * @class Subscriber
 * @constructor
 */
YAHOO.util.Subscriber = function(fn, obj, bOverride) {

    /**
     * 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 = obj || null;

    /**
     * The default execution scope for the event listener is defined when the
     * event is created (usually the object which contains the event).
     * By setting override to true, the execution scope becomes the custom
     * object passed in by the subscriber
     * @property override
     * @type boolean
     */
    this.override = (bOverride);
};

/**
 * 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) {
    return (this.fn == fn && this.obj == obj);
};

/**
 * @method toString
 */
YAHOO.util.Subscriber.prototype.toString = function() {
    return "Subscriber { obj: " + (this.obj || "")  +
           ", override: " +  (this.override || "no") + " }";
};

// The first instance of Event will win if it is loaded more than once.
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.
 * @namespace YAHOO.util
 * @class Event
 */
    YAHOO.util.Event = function() {

        /**
         * True after the onload event has fired
         * @property loadComplete
         * @type boolean
         * @private
         */
        var loadComplete =  false;

        /**
         * Cache of wrapped listeners
         * @property listeners
         * @type array
         * @private
         */
        var listeners = [];

        /**
         * Listeners that will be attached during the onload event
         * @property delayedListeners
         * @type array
         * @private
         */
        var delayedListeners = [];

        /**
         * User-defined unload function that will be fired before all events
         * are detached
         * @property unloadListeners
         * @type array
         * @private
         */
        var unloadListeners = [];

        /**
         * Cache of DOM0 event handlers to work around issues with DOM2 events
         * in Safari
         * @property legacyEvents
         * @private
         */
        var legacyEvents = [];

        /**
         * Listener stack for DOM0 events
         * @property legacyHandlers
         * @private
         */
        var legacyHandlers = [];

        /**
         * 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
         * @private
         */
        var retryCount = 0;

        /**
         * onAvailable listeners
         * @property onAvailStack
         * @private
         */
        var onAvailStack = [];

        /**
         * Lookup table for legacy events
         * @property legacyMap
         * @private
         */
        var legacyMap = [];

        /**
         * Counter for auto id generation
         * @property counter
         * @private
         */
        var counter = 0;

        return { // PREPROCESS

            /**
             * 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 200@amp;50 ms, so it will poll
             * for 10 seconds or until all outstanding handlers are bound
             * (whichever comes first).
             * @property POLL_RETRYS
             * @type int
             */
            POLL_RETRYS: 200,

            /**
             * The poll interval in milliseconds
             * @property POLL_INTERVAL
             * @type int
             */
            POLL_INTERVAL: 50,

            /**
             * Element to bind, int constant
             * @property EL
             * @type int
             */
            EL: 0,

            /**
             * Type of event, int constant
             * @property TYPE
             * @type int
             */
            TYPE: 1,

            /**
             * Function to execute, int constant
             * @property FN
             * @type int
             */
            FN: 2,

            /**
             * Function wrapped for scope correction and cleanup, int constant
             * @property WFN
             * @type int
             */
            WFN: 3,

            /**
             * Object passed in by the user that will be returned as a
             * parameter to the callback, int constant
             * @property SCOPE
             * @type int
             */
            SCOPE: 3,

            /**
             * Adjusted scope, 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
             */
            ADJ_SCOPE: 4,

            /**
             * Safari detection is necessary to work around the preventDefault
             * bug that makes it so you can't cancel a href click from the
             * handler.  There is not a capabilities check we can use here.
             * @property isSafari
             * @private
             */
            isSafari: (/Safari|Konqueror|KHTML/gi).test(navigator.userAgent),

            /**
             * IE detection needed to properly calculate pageX and pageY.
             * capabilities checking didn't seem to work because another
             * browser that does not provide the properties have the values
             * calculated in a different manner than IE.
             * @property isIE
             * @private
             */
            isIE: (!this.isSafari && !navigator.userAgent.match(/opera/gi) &&
                    navigator.userAgent.match(/msie/gi)),

            /**
             * @method addDelayedListener
             * @private
             */
            addDelayedListener: function(el, sType, fn, oScope, bOverride) {
                delayedListeners[delayedListeners.length] =
                    [el, sType, fn, oScope, bOverride];

                // If this happens after the inital page load, we need to
                // reset the poll counter so that we continue to search for
                // the element for a fixed period of time.
                if (loadComplete) {
                    retryCount = this.POLL_RETRYS;
                    this.startTimeout(0);
                    // this._tryPreloadAttach();
                }
            },

            /**
             * @method startTimeout
             * @private
             */
            startTimeout: function(interval) {
                var i = (interval || interval === 0) ? interval : this.POLL_INTERVAL;
                var self = this;
                var callback = function() { self._tryPreloadAttach(); };
                this.timeout = setTimeout(callback, i);
            },

            /**
             * 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.
             *
             * @method onAvailable
             *
             * @param {string}   p_id the id of the element to look for.
             * @param {function} p_fn what to execute when the element is found.
             * @param {object}   p_obj an optional object to be passed back as
             *                   a parameter to p_fn.
             * @param {boolean}  p_override If set to true, p_fn will execute
             *                   in the scope of p_obj
             *
             */
            onAvailable: function(p_id, p_fn, p_obj, p_override) {
                onAvailStack.push( { id:       p_id,
                                     fn:       p_fn,
                                     obj:      p_obj,
                                     override: p_override } );

                retryCount = this.POLL_RETRYS;
                this.startTimeout(0);
                // this._tryPreloadAttach();
            },

            /**
             * Appends an event handler
             *
             * @method addListener
             *
             * @param {Object}   el        The html element to assign the
             *                             event to
             * @param {String}   sType     The type of event to append
             * @param {Function} fn        The method the event invokes
             * @param {Object}   oScope    An arbitrary object that will be
             *                             passed as a parameter to the handler
             * @param {boolean}  bOverride If true, the obj passed in becomes
             *                             the execution scope of the listener
             * @return {boolean} True if the action was successful or defered,
             *                        false if one or more of the elements
             *                        could not have the event bound to it.
             */
            addListener: function(el, sType, fn, oScope, bOverride) {

                if (!fn || !fn.call) {
                    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<len; ++i) {
                        ok = ( this.on(el[i],
                                       sType,
                                       fn,
                                       oScope,
                                       bOverride) && ok );
                    }
                    return ok;

                } else if (typeof el == "string") {
                    var oEl = this.getEl(el);
                    // If the el argument is a string, we assume it is
                    // actually the id of the element.  If the page is loaded
                    // we convert el to the actual element, otherwise we
                    // defer attaching the event until onload event fires

                    // check to see if we need to delay hooking up the event
                    // until after the page loads.
                    if (loadComplete && oEl) {
                        el = oEl;
                    } else {
                        // defer adding the event until onload fires
                        this.addDelayedListener(el,
                                                sType,
                                                fn,
                                                oScope,
                                                bOverride);

                        return true;
                    }
                }

                // Element should be an html element or an array if we get
                // here.
                if (!el) {
                    return false;
                }

                // we need to make sure we fire registered unload events
                // prior to automatically unhooking them.  So we hang on to
                // these instead of attaching them to the window and fire the
                // handles explicitly during our one unload event.
                if ("unload" == sType && oScope !== this) {
                    unloadListeners[unloadListeners.length] =
                            [el, sType, fn, oScope, bOverride];
                    return true;
                }

                // if the user chooses to override the scope, we use the custom
                // object passed in, otherwise the executing scope will be the
                // HTML element that the event is registered on
                var scope = (bOverride) ? oScope : el;

                // wrap the function so we can return the oScope object when
                // the event fires;
                var wrappedFn = function(e) {
                        return fn.call(scope, YAHOO.util.Event.getEvent(e),
                                oScope);
                    };

                var li = [el, sType, fn, wrappedFn, scope];
                var index = listeners.length;
                // cache the listener so we can try to automatically unload
                listeners[index] = li;

                if (this.useLegacyEvent(el, sType)) {
                    var legacyIndex = this.getLegacyIndex(el, sType);

                    // Add a new dom0 wrapper if one is not detected for this
                    // element
                    if ( legacyIndex == -1 ||
                                el != legacyEvents[legacyIndex][0] ) {

                        legacyIndex = legacyEvents.length;
                        legacyMap[el.id + sType] = legacyIndex;

                        // cache the signature for the DOM0 event, and
                        // include the existing handler for the event, if any
                        legacyEvents[legacyIndex] =
                            [el, sType, el["on" + sType]];
                        legacyHandlers[legacyIndex] = [];

                        el["on" + sType] =
                            function(e) {
                                YAHOO.util.Event.fireLegacyEvent(
                                    YAHOO.util.Event.getEvent(e), legacyIndex);
                            };
                    }

                    // add a reference to the wrapped listener to our custom
                    // stack of events
                    //legacyHandlers[legacyIndex].push(index);
                    legacyHandlers[legacyIndex].push(li);

                // DOM2 Event model
                } else if (el.addEventListener) {
                    el.addEventListener(sType, wrappedFn, false);
                // IE
                } else if (el.attachEvent) {
                    el.attachEvent("on" + sType, wrappedFn);
                }

                return true;

            },

            /**
             * When using legacy events, the handler is routed to this object
             * so we can fire our custom listener stack.
             * @method fireLegacyEvent
             * @private
             */
            fireLegacyEvent: function(e, legacyIndex) {
                var ok = true;

                var le = legacyHandlers[legacyIndex];
                for (var i=0,len=le.length; i<len; ++i) {
                    var li = le[i];
                    if ( li && li[this.WFN] ) {
                        var scope = li[this.ADJ_SCOPE];
                        var ret = li[this.WFN].call(scope, e);
                        ok = (ok && ret);
                    }
                }

                return ok;
            },

            /**
             * Returns the legacy event index that matches the supplied
             * signature
             * @method getLegacyIndex
             * @private
             */
            getLegacyIndex: function(el, sType) {
                var key = this.generateId(el) + sType;
                if (typeof legacyMap[key] == "undefined") {
                    return -1;
                } else {
                    return legacyMap[key];
                }
            },

            /**
             * Logic that determines when we should automatically use legacy
             * events instead of DOM2 events.
             * @method useLegacyEvent
             * @private
             */
            useLegacyEvent: function(el, sType) {
                if (!el.addEventListener && !el.attachEvent) {
                    return true;
                } else if (this.isSafari) {
                    if ("click" == sType || "dblclick" == sType) {
                        return true;
                    }
                }
                return false;
            },

            /**
             * Removes an event handler
             *
             * @method removeListener
             *
             * @param {Object} el the html element or the id of the element to
             * assign the event to.
             * @param {String} sType the type of event to remove
             * @param {Function} fn the method the event invokes
             * @return {boolean} true if the unbind was successful, false
             * otherwise
             */
            removeListener: function(el, sType, fn, index) {

                if (!fn || !fn.call) {
                    return false;
                }

                var i, len;

                // The el argument can be a string
                if (typeof el == "string") {
                    el = this.getEl(el);
                // The el argument can be an array of elements or element ids.
                } else if ( this._isValidCollection(el)) {
                    var ok = true;
                    for (i=0,len=el.length; i<len; ++i) {
                        ok = ( this.removeListener(el[i], sType, fn) && ok );
                    }
                    return ok;
                }

                if ("unload" == sType) {

                    for (i=0, len=unloadListeners.length; i<len; i++) {
                        var li = unloadListeners[i];
                        if (li &&
                            li[0] == el &&
                            li[1] == sType &&
                            li[2] == fn) {
                                unloadListeners.splice(i, 1);
                                return true;
                        }
                    }

                    return false;
                }

                var cacheItem = null;

                //var index = arguments[3];

                if ("undefined" == typeof index) {
                    index = this._getCacheIndex(el, sType, fn);
                }

                if (index >= 0) {
                    cacheItem = listeners[index];
                }

                if (!el || !cacheItem) {
                    return false;
                }

                if (this.useLegacyEvent(el, sType)) {
                    var legacyIndex = this.getLegacyIndex(el, sType);
                    var llist = legacyHandlers[legacyIndex];
                    if (llist) {
                        for (i=0, len=llist.length; i<len; ++i) {
                            li = llist[i];
                            if (li &&
                                li[this.EL] == el &&
                                li[this.TYPE] == sType &&
                                li[this.FN] == fn) {
                                    llist.splice(i, 1);
                            }
                        }
                    }

                } else if (el.removeEventListener) {
                    el.removeEventListener(sType, cacheItem[this.WFN], false);
                } else if (el.detachEvent) {
                    el.detachEvent("on" + sType, cacheItem[this.WFN]);
                }

                // removed the wrapped handler
                delete listeners[index][this.WFN];
                delete listeners[index][this.FN];
                listeners.splice(index, 1);

                return true;

            },

            /**
             * Returns the event's target element
             * @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
             */
            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.
             * @method resolveTextNode
             * @param {HTMLElement} node to resolve
             * @return  the normized node
             */
            resolveTextNode: function(node) {
                if (node && node.nodeName &&
                        "#TEXT" == node.nodeName.toUpperCase()) {
                    return node.parentNode;
                } else {
                    return node;
                }
            },

            /**
             * Returns the event's pageX
             * @method getPageX
             * @param {Event} ev the event
             * @return {int} the event's pageX
             */
            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
             */
            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
             * @type int[]
             */
            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
             */
            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
             */
            getTime: function(ev) {
                if (!ev.time) {
                    var t = new Date().getTime();
                    try {
                        ev.time = t;
                    } catch(e) {
                        // can't set the time property
                        return t;
                    }
                }

                return ev.time;
            },

            /**
             * Convenience method for stopPropagation + preventDefault
             * @method stopEvent
             * @param {Event} ev the event
             */
            stopEvent: function(ev) {
                this.stopPropagation(ev);
                this.preventDefault(ev);
            },

            /**
             * Stops event propagation
             * @method stopPropagation
             * @param {Event} ev the event
             */
            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
             */
            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} the event parameter from the handler
             * @return {Event} the event
             */
            getEvent: function(e) {
                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
             */
            getCharCode: function(ev) {
                return ev.charCode || ((ev.type == "keypress") ? ev.keyCode : 0);
            },

            /**
             * Locating the saved event handler data by function ref
             *
             * @method _getCacheIndex
             * @private
             */
            _getCacheIndex: function(el, sType, fn) {
                for (var i=0,len=listeners.length; i<len; ++i) {
                    var li = listeners[i];
                    if ( li                 &&
                         li[this.FN] == fn  &&
                         li[this.EL] == el  &&
                         li[this.TYPE] == sType ) {
                        return i;
                    }
                }

                return -1;
            },

            /**
             * Generates an unique ID for the element if it does not already
             * have one.
             * @method generateId
             * @param el the element
             * @return {string} the id of the element
             */
            generateId: function(el) {
                var id = el.id;

                if (!id) {
                    id = "yuievtautoid-" + counter;
                    ++counter;
                    el.id = id;
                }

                return id;
            },

            /**
             * We want to be able to use getElementsByTagName as a collection
             * to attach a group of events to.  Unfortunately, different
             * browsers return different types of collections.  This function
             * tests to determine if the object is array-like.  It will also
             * fail if the object is an array, but is empty.
             * @method _isValidCollection
             * @param o the object to test
             * @return {boolean} true if the object is array-like and populated
             * @private
             */
            _isValidCollection: function(o) {

                return ( o                    && // o is something
                         o.length             && // o is indexed
                         typeof o != "string" && // o is not a string
                         !o.tagName           && // o is not an HTML element
                         !o.alert             && // o is not a window
                         typeof o[0] != "undefined" );

            },

            /**
             * @private
             * @property elCache
             * DOM element cache
             */
            elCache: {},

            /**
             * We cache elements bound by id because when the unload event
             * fires, we can no longer use document.getElementById
             * @method getEl
             * @private
             */
            getEl: function(id) {
                return document.getElementById(id);
            },

            /**
             * Clears the element cache
             * @deprecated
             * @private
             */
            clearCache: function() { },

            /**
             * hook up any deferred listeners
             * @method _load
             * @private
             */
            _load: function(e) {
                loadComplete = true;
                var EU = YAHOO.util.Event;
                EU._simpleRemove(window, "load", EU._load);
            },

            /**
             * Polling function that runs before the onload event fires,
             * attempting to attach to DOM Nodes as soon as they are
             * available
             * @method _tryPreloadAttach
             * @private
             */
            _tryPreloadAttach: function() {

                if (this.locked) {
                    return false;
                }

                this.locked = true;

                // keep trying until after the page is loaded.  We need to
                // check the page load state prior to trying to bind the
                // elements so that we can be certain all elements have been
                // tested appropriately
                var tryAgain = !loadComplete;
                if (!tryAgain) {
                    tryAgain = (retryCount > 0);
                }

                // Delayed listeners
                var stillDelayed = [];

                for (var i=0,len=delayedListeners.length; i<len; ++i) {
                    var d = delayedListeners[i];
                    // There may be a race condition here, so we need to
                    // verify the array element is usable.
                    if (d) {

                        // el will be null if document.getElementById did not
                        // work
                        var el = this.getEl(d[this.EL]);

                        if (el) {
                            this.on(el, d[this.TYPE], d[this.FN],
                                    d[this.SCOPE], d[this.ADJ_SCOPE]);
                            delete delayedListeners[i];
                        } else {
                            stillDelayed.push(d);
                        }
                    }
                }

                delayedListeners = stillDelayed;

                // onAvailable
                var notAvail = [];
                for (i=0,len=onAvailStack.length; i<len ; ++i) {
                    var item = onAvailStack[i];
                    if (item) {
                        el = this.getEl(item.id);

                        if (el) {
                            var scope = (item.override) ? item.obj : el;
                            item.fn.call(scope, item.obj);
                            delete onAvailStack[i];
                        } else {
                            notAvail.push(item);
                        }
                    }
                }

                retryCount = (stillDelayed.length === 0 &&
                                    notAvail.length === 0) ? 0 : retryCount - 1;

                if (tryAgain) {
                    this.startTimeout();
                }

                this.locked = false;

                return true;

            },

            /**
             * 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
             */
            purgeElement: function(el, recurse, sType) {
                var elListeners = this.getListeners(el, sType);
                if (elListeners) {
                    for (var i=0,len=elListeners.length; i<len ; ++i) {
                        var l = elListeners[i];
                        // can't use the index on the changing collection
                        //this.removeListener(el, l.type, l.fn, l.index);
                        this.removeListener(el, l.type, l.fn);
                    }
                }

                if (recurse && el && el.childNodes) {
                    for (i=0,len=el.childNodes.length; i<len ; ++i) {
                        this.purgeElement(el.childNodes[i], recurse, sType);
                    }
                }
            },

            /**
             * Returns all listeners attached to the given element via addListener.
             * Optionally, you can specify a specific type of event to return.
             * @method getListeners
             * @param el {HTMLElement} the element to inspect
             * @param sType {string} optional type of listener to return. If
             * left out, all listeners will be returned
             * @return {Object} the listener. Contains the following fields:
             *    type:   (string)   the type of event
             *    fn:     (function) the callback supplied to addListener
             *    obj:    (object)   the custom object supplied to addListener
             *    adjust: (boolean)  whether or not to adjust the default scope
             *    index:  (int)      its position in the Event util listener cache
             */
            getListeners: function(el, sType) {
                var elListeners = [];
                if (listeners && listeners.length > 0) {
                    for (var i=0,len=listeners.length; i<len ; ++i) {
                        var l = listeners[i];
                        if ( l  && l[this.EL] === el &&
                                (!sType || sType === l[this.TYPE]) ) {
                            elListeners.push({
                                type:   l[this.TYPE],
                                fn:     l[this.FN],
                                obj:    l[this.SCOPE],
                                adjust: l[this.ADJ_SCOPE],
                                index:  i
                            });
                        }
                    }
                }

                return (elListeners.length) ? elListeners : null;
            },

            /**
             * Removes all listeners registered by pe.event.  Called
             * automatically during the unload event.
             * @method _unload
             * @private
             */
            _unload: function(e) {

                var EU = YAHOO.util.Event;

                for (var i=0,len=unloadListeners.length; i<len; ++i) {
                    var l = unloadListeners[i];
                    if (l) {
                        var scope = (l[EU.ADJ_SCOPE]) ? l[EU.SCOPE]: window;
                        l[EU.FN].call(scope, EU.getEvent(e), l[EU.SCOPE] );
                        delete unloadListeners[i];
                        l=null;
                    }
                }

                if (listeners && listeners.length > 0) {
                    //for (i=0,len=listeners.length; i<len ; ++i) {
                    var j = listeners.length;
                    while (j) {
                        var index = j-1;
                        l = listeners[index];
                        if (l) {
                            EU.removeListener(l[EU.EL], l[EU.TYPE],
                                    l[EU.FN], index);
                        }

                        l=null;

                        j = j - 1;
                    }

                    EU.clearCache();
                }

                for (i=0,len=legacyEvents.length; i<len; ++i) {
                    // dereference the element
                    delete legacyEvents[i][0];
                    // delete the array item
                    delete legacyEvents[i];
                }

                EU._simpleRemove(window, "unload", EU._unload);

            },

            /**
             * Returns scrollLeft
             * @method _getScrollLeft
             * @private
             */
            _getScrollLeft: function() {
                return this._getScroll()[1];
            },

            /**
             * Returns scrollTop
             * @method _getScrollTop
             * @private
             */
            _getScrollTop: function() {
                return this._getScroll()[0];
            },

            /**
             * Returns the scrollTop and scrollLeft.  Used to calculate the
             * pageX and pageY in Internet Explorer
             * @method _getScroll
             * @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];
                }
            },

            /**
             * Adds a DOM event directly without the caching, cleanup, scope adj, etc
             *
             * @param el the elment to bind the handler to
             * @param {string} sType the type of event handler
             * @param {function} fn the callback to invoke
             * @param {boolen} capture or bubble phase
             * @private
             */
            _simpleAdd: function (el, sType, fn, capture) {
                if (el.addEventListener) {
                    el.addEventListener(sType, fn, (capture));
                } else if (el.attachEvent) {
                    el.attachEvent("on" + sType, fn);
                }
            },

            /**
             * Basic remove listener
             *
             * @param el the elment to bind the handler to
             * @param {string} sType the type of event handler
             * @param {function} fn the callback to invoke
             * @param {boolen} capture or bubble phase
             * @private
             */
            _simpleRemove: function (el, sType, fn, capture) {
                if (el.removeEventListener) {
                    el.removeEventListener(sType, fn, (capture));
                } else if (el.detachEvent) {
                    el.detachEvent("on" + sType, fn);
                }
            }
        };

    } ();

    /**
     * YAHOO.util.Event.on is an alias for addListener
     * @method on
     * @see addListener
     */
    YAHOO.util.Event.on = YAHOO.util.Event.addListener;

    if (document && document.body) {
        YAHOO.util.Event._load();
    } else {
        YAHOO.util.Event._simpleAdd(window, "load", YAHOO.util.Event._load);
    }
    YAHOO.util.Event._simpleAdd(window, "unload", YAHOO.util.Event._unload);
    YAHOO.util.Event._tryPreloadAttach();
}

//event
/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
Version: 0.11.3
*/

/**
 * @class Provides helper methods for DOM elements.
 */
YAHOO.util.Dom = function() {
   var ua = navigator.userAgent.toLowerCase();
   var isOpera = (ua.indexOf('opera') > -1);
   var isSafari = (ua.indexOf('safari') > -1);
   var isIE = (window.ActiveXObject);

   var id_counter = 0;
   var util = YAHOO.util; // internal shorthand
   var property_cache = {}; // to cache case conversion for set/getStyle

   var toCamel = function(property) {
      var convert = function(prop) {
         var test = /(-[a-z])/i.exec(prop);
         return prop.replace(RegExp.$1, RegExp.$1.substr(1).toUpperCase());
      };

      while(property.indexOf('-') > -1) {
         property = convert(property);
      }

      return property;
   };

   var toHyphen = function(property) {
      if (property.indexOf('-') > -1) { // assume hyphen
         return property;
      }

      var converted = '';
      for (var i = 0, len = property.length;i < len; ++i) {
         if (property.charAt(i) == property.charAt(i).toUpperCase()) {
            converted = converted + '-' + property.charAt(i).toLowerCase();
         } else {
            converted = converted + property.charAt(i);
         }
      }

      return converted;
      //return property.replace(/([a-z])([A-Z]+)/g, function(m0, m1, m2) {return (m1 + '-' + m2.toLowerCase())});
   };

   // improve performance by only looking up once
   var cacheConvertedProperties = function(property) {
      property_cache[property] = {
         camel: toCamel(property),
         hyphen: toHyphen(property)
      };
   };

   return {
      /**
       * Returns an HTMLElement reference
       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID for getting a DOM reference, an actual DOM reference, or an Array of IDs and/or HTMLElements.
       * @return {HTMLElement/Array} A DOM reference to an HTML element or an array of HTMLElements.
       */
      get: function(el) {
         if (!el) { return null; } // nothing to work with

         if (typeof el != 'string' && !(el instanceof Array) ) { // assuming HTMLElement or HTMLCollection, so pass back as is
            return el;
         }

         if (typeof el == 'string') { // ID
            return document.getElementById(el);
         }
         else { // array of ID's and/or elements
            var collection = [];
            for (var i = 0, len = el.length; i < len; ++i) {
               collection[collection.length] = util.Dom.get(el[i]);
            }

            return collection;
         }

         return null; // safety, should never happen
      },

      /**
       * Normalizes currentStyle and ComputedStyle.
       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
       * @param {String} property The style property whose value is returned.
       * @return {String/Array} The current value of the style property for the element(s).
       */
      getStyle: function(el, property) {
         var f = function(el) {
            var value = null;
            var dv = document.defaultView;

            if (!property_cache[property]) {
               cacheConvertedProperties(property);
            }

            var camel = property_cache[property]['camel'];
            var hyphen = property_cache[property]['hyphen'];

            if (property == 'opacity' && el.filters) {// IE opacity
               value = 1;
               try {
                  value = el.filters.item('DXImageTransform.Microsoft.Alpha').opacity / 100;
               } catch(e) {
                  try {
                     value = el.filters.item('alpha').opacity / 100;
                  } catch(e) {}
               }
            } else if (el.style[camel]) { // camelCase for valid styles
               value = el.style[camel];
            }
            else if (isIE && el.currentStyle && el.currentStyle[camel]) { // camelCase for currentStyle; isIE to workaround broken Opera 9 currentStyle
               value = el.currentStyle[camel];
            }
            else if ( dv && dv.getComputedStyle ) { // hyphen-case for computedStyle
               var computed = dv.getComputedStyle(el, '');

               if (computed && computed.getPropertyValue(hyphen)) {
                  value = computed.getPropertyValue(hyphen);
               }
            }

            return value;
         };

         return util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Wrapper for setting style properties of HTMLElements.  Normalizes "opacity" across modern browsers.
       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
       * @param {String} property The style property to be set.
       * @param {String} val The value to apply to the given property.
       */
      setStyle: function(el, property, val) {
         if (!property_cache[property]) {
            cacheConvertedProperties(property);
         }

         var camel = property_cache[property]['camel'];

         var f = function(el) {
            switch(property) {
               case 'opacity' :
                  if (isIE && typeof el.style.filter == 'string') { // in case not appended
                     el.style.filter = 'alpha(opacity=' + val * 100 + ')';

                     if (!el.currentStyle || !el.currentStyle.hasLayout) {
                        el.style.zoom = 1; // when no layout or cant tell
                     }
                  } else {
                     el.style.opacity = val;
                     el.style['-moz-opacity'] = val;
                     el.style['-khtml-opacity'] = val;
                  }

                  break;
               default :
                  el.style[camel] = val;
            }


         };

         util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Gets the current position of an element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
       @ return {Array} The XY position of the element(s)
       */
      getXY: function(el) {
         var f = function(el) {

         // has to be part of document to have pageXY
            if (el.offsetParent === null || this.getStyle(el, 'display') == 'none') {
               return false;
            }

            var parentNode = null;
            var pos = [];
            var box;

            if (el.getBoundingClientRect) { // IE
               box = el.getBoundingClientRect();
               var doc = document;
               if ( !this.inDocument(el) && parent.document != document) {// might be in a frame, need to get its scroll
                  doc = parent.document;

                  if ( !this.isAncestor(doc.documentElement, el) ) {
                     return false;
                  }

               }

               var scrollTop = Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
               var scrollLeft = Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);

               return [box.left + scrollLeft, box.top + scrollTop];
            }
            else { // safari, opera, & gecko
               pos = [el.offsetLeft, el.offsetTop];
               parentNode = el.offsetParent;
               if (parentNode != el) {
                  while (parentNode) {
                     pos[0] += parentNode.offsetLeft;
                     pos[1] += parentNode.offsetTop;
                     parentNode = parentNode.offsetParent;
                  }
               }
               if (isSafari && this.getStyle(el, 'position') == 'absolute' ) { // safari doubles in some cases
                  pos[0] -= document.body.offsetLeft;
                  pos[1] -= document.body.offsetTop;
               }
            }

            if (el.parentNode) { parentNode = el.parentNode; }
            else { parentNode = null; }

            while (parentNode && parentNode.tagName.toUpperCase() != 'BODY' && parentNode.tagName.toUpperCase() != 'HTML')
            { // account for any scrolled ancestors
               if (util.Dom.getStyle(parentNode, 'display') != 'inline') { // work around opera inline scrollLeft/Top bug
                  pos[0] -= parentNode.scrollLeft;
                  pos[1] -= parentNode.scrollTop;
               }

               if (parentNode.parentNode) { parentNode = parentNode.parentNode; }
               else { parentNode = null; }
            }


            return pos;
         };

         return util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Gets the current X position of an element based on page coordinates.  The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
       * @return {String/Array} The X position of the element(s)
       */
      getX: function(el) {
         var f = function(el) {
            return util.Dom.getXY(el)[0];
         };

         return util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Gets the current Y position of an element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
       * @return {String/Array} The Y position of the element(s)
       */
      getY: function(el) {
         var f = function(el) {
            return util.Dom.getXY(el)[1];
         };

         return util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Set the position of an html element in page coordinates, regardless of how the element is positioned.
       * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
       * @param {Array} pos Contains X & Y values for new position (coordinates are page-based)
       * @param {Boolean} noRetry By default we try and set the position a second time if the first fails
       */
      setXY: function(el, pos, noRetry) {
         var f = function(el) {
            var style_pos = this.getStyle(el, 'position');
            if (style_pos == 'static') { // default to relative
               this.setStyle(el, 'position', 'relative');
               style_pos = 'relative';
            }

            var pageXY = this.getXY(el);
            if (pageXY === false) { // has to be part of doc to have pageXY
               return false;
            }

            var delta = [ // assuming pixels; if not we will have to retry
               parseInt( this.getStyle(el, 'left'), 10 ),
               parseInt( this.getStyle(el, 'top'), 10 )
            ];

            if ( isNaN(delta[0]) ) {// in case of 'auto'
               delta[0] = (style_pos == 'relative') ? 0 : el.offsetLeft;
            }
            if ( isNaN(delta[1]) ) { // in case of 'auto'
               delta[1] = (style_pos == 'relative') ? 0 : el.offsetTop;
            }

            if (pos[0] !== null) { el.style.left = pos[0] - pageXY[0] + delta[0] + 'px'; }
            if (pos[1] !== null) { el.style.top = pos[1] - pageXY[1] + delta[1] + 'px'; }

            var newXY = this.getXY(el);

            // if retry is true, try one more time if we miss
            if (!noRetry && (newXY[0] != pos[0] || newXY[1] != pos[1]) ) {
               this.setXY(el, pos, true);
            }

         };

         util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Set the X position of an html element in page coordinates, regardless of how the element is positioned.
       * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
       * @param {Int} x to use as the X coordinate for the element(s).
       */
      setX: function(el, x) {
         util.Dom.setXY(el, [x, null]);
      },

      /**
       * Set the Y position of an html element in page coordinates, regardless of how the element is positioned.
       * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
       * @param {Int} x to use as the Y coordinate for the element(s).
       */
      setY: function(el, y) {
         util.Dom.setXY(el, [null, y]);
      },

      /**
       * Returns the region position of the given element.
       * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
       * @return {Region/Array} A Region or array of Region instances containing "top, left, bottom, right" member data.
       */
      getRegion: function(el) {
         var f = function(el) {
            var region = new YAHOO.util.Region.getRegion(el);
            return region;
         };

         return util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Returns the width of the client (viewport).
       * Now using getViewportWidth.  This interface left intact for back compat.
       * @return {Int} The width of the viewable area of the page.
       */
      getClientWidth: function() {
         return util.Dom.getViewportWidth();
      },

      /**
       * Returns the height of the client (viewport).
       * Now using getViewportHeight.  This interface left intact for back compat.
       * @return {Int} The height of the viewable area of the page.
       */
      getClientHeight: function() {
         return util.Dom.getViewportHeight();
      },

      /**
       * Returns a array of HTMLElements with the given class
       * For optimized performance, include a tag and/or root node if possible
       * @param {String} className The class name to match against
       * @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 {Array} An array of elements that have the given class name
       */
      getElementsByClassName: function(className, tag, root) {
         var method = function(el) { return util.Dom.hasClass(el, className) };
         return util.Dom.getElementsBy(method, tag, root);
      },

      /**
       * Determines whether an HTMLElement has the given className
       * @param {String/HTMLElement/Array} el The element or collection to test
       * @param {String} className the class name to search for
       * @return {Boolean/Array} A boolean value or array of boolean values
       */
      hasClass: function(el, className) {
         var re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');

         var f = function(el) {
            return re.test(el['className']);
         };

         return util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Adds a class name to a given element or collection of elements
       * @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
       */
      addClass: function(el, className) {
         var f = function(el) {
            if (this.hasClass(el, className)) { return; } // already present


            el['className'] = [el['className'], className].join(' ');
         };

         util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Removes a class name from a given element or collection of elements
       * @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
       */
      removeClass: function(el, className) {
         var re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', 'g');

         var f = function(el) {
            if (!this.hasClass(el, className)) { return; } // not present


            var c = el['className'];
            el['className'] = c.replace(re, ' ');
            if ( this.hasClass(el, className) ) { // in case of multiple adjacent
               this.removeClass(el, className);
            }

         };

         util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Replace a class with another class for a given element or collection of elements.
       * If no oldClassName is present, the newClassName is simply added.
       * @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
       */
      replaceClass: function(el, oldClassName, newClassName) {
         if (oldClassName === newClassName) { // avoid infinite loop
            return false;
         };

         var re = new RegExp('(?:^|\\s+)' + oldClassName + '(?:\\s+|$)', 'g');

         var f = function(el) {

            if ( !this.hasClass(el, oldClassName) ) {
               this.addClass(el, newClassName); // just add it if nothing to replace
               return; // note return
            }

            el['className'] = el['className'].replace(re, ' ' + newClassName + ' ');

            if ( this.hasClass(el, oldClassName) ) { // in case of multiple adjacent
               this.replaceClass(el, oldClassName, newClassName);
            }
         };

         util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Generates a unique ID
       * @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';
         el = el || {};

         var f = function(el) {
            if (el) {
               el = util.Dom.get(el);
            } else {
               el = {}; // just generating ID in this case
            }

            if (!el.id) {
               el.id = prefix + id_counter++;
            } // dont override existing


            return el.id;
         };

         return util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Determines whether an HTMLElement is an ancestor of another HTML element in the DOM hierarchy
       * @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 = util.Dom.get(haystack);
         if (!haystack || !needle) { return false; }

         var f = function(needle) {
            if (haystack.contains && !isSafari) { // safari "contains" is broken
               return haystack.contains(needle);
            }
            else if ( haystack.compareDocumentPosition ) {
               return !!(haystack.compareDocumentPosition(needle) & 16);
            }
            else { // loop up and test each parent
               var parent = needle.parentNode;

               while (parent) {
                  if (parent == haystack) {
                     return true;
                  }
                  else if (!parent.tagName || parent.tagName.toUpperCase() == 'HTML') {
                     return false;
                  }

                  parent = parent.parentNode;
               }
               return false;
            }
         };

         return util.Dom.batch(needle, f, util.Dom, true);
      },

      /**
       * Determines whether an HTMLElement is present in the current document
       * @param {String/HTMLElement} el The element to search for
       * @return {Boolean} Whether or not the element is present in the current document
       */
      inDocument: function(el) {
         var f = function(el) {
            return this.isAncestor(document.documentElement, el);
         };

         return util.Dom.batch(el, f, util.Dom, true);
      },

      /**
       * Returns a array of HTMLElements that pass the test applied by supplied boolean method
       * For optimized performance, include a tag and/or root node if possible
       * @param {Function} method A boolean method to test elements with
       * @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
       */
      getElementsBy: function(method, tag, root) {
         tag = tag || '*';
         root = util.Dom.get(root) || document;

         var nodes = [];
         var elements = root.getElementsByTagName(tag);

         if ( !elements.length && (tag == '*' && root.all) ) {
            elements = root.all; // IE < 6
         }

         for (var i = 0, len = elements.length; i < len; ++i)
         {
            if ( method(elements[i]) ) { nodes[nodes.length] = elements[i]; }
         }


         return nodes;
      },

      /**
       * Returns an array of elements that have had the supplied method applied.
       * The method is called with the element(s) as the first arg, and the optional param as the second ( method(el, o) )
       * @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 {Generic} (optional) o An optional arg that is passed to the supplied method
       * @param {Boolean} (optional) override Whether or not to override the scope of "method" with "o"
       * @return {HTMLElement/Array} The element(s) with the method applied
       */
      batch: function(el, method, o, override) {
         var id = el;
         el = util.Dom.get(el);

         var scope = (override) ? o : window;

         if (!el || el.tagName || !el.length) { // is null or not a collection (tagName for SELECT and others that can be both an element and a collection)
            if (!el) {
               return false;
            }
            return method.call(scope, el, o);
         }

         var collection = [];

         for (var i = 0, len = el.length; i < len; ++i) {
            if (!el[i]) {
               id = id[i];
            }
            collection[collection.length] = method.call(scope, el[i], o);
         }

         return collection;
      },

      /**
       * Returns the height of the document.
       * @return {Int} The height of the actual document (which includes the body and its margin).
       */
      getDocumentHeight: function() {
         var scrollHeight=-1,windowHeight=-1,bodyHeight=-1;
         var marginTop = parseInt(util.Dom.getStyle(document.body, 'marginTop'), 10);
         var marginBottom = parseInt(util.Dom.getStyle(document.body, 'marginBottom'), 10);

         var mode = document.compatMode;

         if ( (mode || isIE) && !isOpera ) { // (IE, Gecko)
            switch (mode) {
               case 'CSS1Compat': // Standards mode
                  scrollHeight = ((window.innerHeight && window.scrollMaxY) ?  window.innerHeight+window.scrollMaxY : -1);
                  windowHeight = [document.documentElement.clientHeight,self.innerHeight||-1].sort(function(a, b){return(a-b);})[1];
                  bodyHeight = document.body.offsetHeight + marginTop + marginBottom;
                  break;

               default: // Quirks
                  scrollHeight = document.body.scrollHeight;
                  bodyHeight = document.body.clientHeight;
            }
         } else { // Safari & Opera
            scrollHeight = document.documentElement.scrollHeight;
            windowHeight = self.innerHeight;
            bodyHeight = document.documentElement.clientHeight;
         }

         var h = [scrollHeight,windowHeight,bodyHeight].sort(function(a, b){return(a-b);});
         return h[2];
      },

      /**
       * Returns the width of the document.
       * @return {Int} The width of the actual document (which includes the body and its margin).
       */
      getDocumentWidth: function() {
         var docWidth=-1,bodyWidth=-1,winWidth=-1;
         var marginRight = parseInt(util.Dom.getStyle(document.body, 'marginRight'), 10);
         var marginLeft = parseInt(util.Dom.getStyle(document.body, 'marginLeft'), 10);

         var mode = document.compatMode;

         if (mode || isIE) { // (IE, Gecko, Opera)
            switch (mode) {
               case 'CSS1Compat': // Standards mode
                  docWidth = document.documentElement.clientWidth;
                  bodyWidth = document.body.offsetWidth + marginLeft + marginRight;
                  break;

               default: // Quirks
                  bodyWidth = document.body.clientWidth;
                  docWidth = document.body.scrollWidth;
                  break;
            }
         } else { // Safari
            docWidth = document.documentElement.clientWidth;
            bodyWidth = document.body.offsetWidth + marginLeft + marginRight;
         }

         var w = Math.max(docWidth, bodyWidth);
         return w;
      },

      /**
       * Returns the current height of the viewport.
       * @return {Int} The height of the viewable area of the page (excludes scrollbars).
       */
      getViewportHeight: function() {
         var height = -1;
         var mode = document.compatMode;

         if ( (mode || isIE) && !isOpera ) {
            switch (mode) { // (IE, Gecko)
               case 'CSS1Compat': // Standards mode
                  height = document.documentElement.clientHeight;
                  break;

               default: // Quirks
                  height = document.body.clientHeight;
            }
         } else { // Safari, Opera
            height = self.innerHeight;
         }

         return height;
      },

      /**
       * Returns the current width of the viewport.
       * @return {Int} The width of the viewable area of the page (excludes scrollbars).
       */

      getViewportWidth: function() {
         var width = -1;
         var mode = document.compatMode;

         if (mode || isIE) { // (IE, Gecko, Opera)
            switch (mode) {
            case 'CSS1Compat': // Standards mode
               width = document.documentElement.clientWidth;
               break;

            default: // Quirks
               width = document.body.clientWidth;
            }
         } else { // Safari
            width = self.innerWidth;
         }
         return width;
      }
   };
}();

/**
 * @class 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.
 *
 * @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
     * @type int
     */
    this.top = t;

    /**
     * The region's top extent as index, for symmetry with set/getXY
     * @type int
     */
    this[1] = t;

    /**
     * The region's right extent
     * @type int
     */
    this.right = r;

    /**
     * The region's bottom extent
     * @type int
     */
    this.bottom = b;

    /**
     * The region's left extent
     * @type int
     */
    this.left = l;

    /**
     * The region's left extent as index, for symmetry with set/getXY
     * @type int
     */
    this[0] = l;
};

/**
 * Returns true if this region contains the region passed in
 *
 * @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    );

};

/**
 * Returns the area of the region
 *
 * @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
 *
 * @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    );
    var r = Math.min( this.right,  region.right  );
    var b = Math.min( this.bottom, region.bottom );
    var 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.
 *
 * @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    );
    var r = Math.max( this.right,  region.right  );
    var b = Math.max( this.bottom, region.bottom );
    var l = Math.min( this.left,   region.left   );

    return new YAHOO.util.Region(t, r, b, l);
};

/**
 * 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   +
             "}" );
};

/**
 * Returns a region that is occupied by the DOM element
 *
 * @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);

    var t = p[1];
    var r = p[0] + el.offsetWidth;
    var b = p[1] + el.offsetHeight;
    var l = p[0];

    return new YAHOO.util.Region(t, r, b, l);
};

/////////////////////////////////////////////////////////////////////////////

/**
 * @class
 *
 * A point is a region that is special in that it represents a single point on
 * the grid.
 *
 * @param {int} x The X position of the point
 * @param {int} y The Y position of the point
 * @constructor
 * @extends Region
 */
YAHOO.util.Point = function(x, y) {
   if (x instanceof Array) { // accept output from Dom.getXY
      y = x[1];
      x = x[0];
   }

    /**
     * The X position of the point, which is also the right, left and index zero (for Dom.getXY symmetry)
     * @type int
     */

    this.x = this.right = this.left = this[0] = x;

    /**
     * The Y position of the point, which is also the top, bottom and index one (for Dom.getXY symmetry)
     * @type int
     */
    this.y = this.top = this.bottom = this[1] = y;
};

YAHOO.util.Point.prototype = new YAHOO.util.Region();

//dom
/*

Copyright (c) 2006, Yahoo! Inc. All rights reserved.

Code licensed under the BSD License:

http://developer.yahoo.com/yui/license.txt

version: 0.11.3

*/



/****************************************************************************/

/****************************************************************************/

/****************************************************************************/

/**

 * Singleton providing core logging functionality. Saves logs written through the

 * global YAHOO.log function or written by LogWriter. Provides access to logs

 * for reading by LogReader. Log messages can be automatically output to browser

 * console such as the Firebug extension to Firefox or Safari's JavaScript

 * console, if present.

 *

 * requires YAHOO.util.Event Event utility

 */

YAHOO.widget.Logger = {

    // Initialize members

    loggerEnabled: true,

    _browserConsoleEnabled: false,

    categories: ["info","warn","error","time","window"],

    sources: ["global"],

    _stack: [], // holds all log msgs

    maxStackEntries: 5,

    _startTime: new Date().getTime(), // static start timestamp

    _lastTime: null // timestamp of last logged message

};



/***************************************************************************

 * Events

 ***************************************************************************/

/**

 * Fired when a new category has been created. Subscribers receive the following

 * array:<br>

 *     - args[0] The category name

 */

YAHOO.widget.Logger.categoryCreateEvent = new YAHOO.util.CustomEvent("categoryCreate", this, true);



/**

 * Fired when a new source has been named. Subscribers receive the following

 * array:<br>

 *     - args[0] The source name

 */

YAHOO.widget.Logger.sourceCreateEvent = new YAHOO.util.CustomEvent("sourceCreate", this, true);



/**

 * Fired when a new log message has been created. Subscribers receive the

 * following array:<br>

 *     - args[0] The log message

 */

YAHOO.widget.Logger.newLogEvent = new YAHOO.util.CustomEvent("newLog", this, true);



/**

 * Fired when the Logger has been reset has been created.

 */

YAHOO.widget.Logger.logResetEvent = new YAHOO.util.CustomEvent("logReset", this, true);



/***************************************************************************

 * Public methods

 ***************************************************************************/

/**

 * Saves a log message to the stack and fires newLogEvent. If the log message is

 * assigned to an unknown category, creates a new category. If the log message is

 * from an unknown source, creates a new source.  If browser console is enabled,

 * outputs the log message to browser console.

 *

 * @param {string} sMsg The log message

 * @param {string} sCategory Category of log message, or null

 * @param {string} sSource Source of LogWriter, or null if global

 */

YAHOO.widget.Logger.log = function(sMsg, sCategory, sSource) {

    if(this.loggerEnabled) {

        if(!sCategory) {

            sCategory = "info"; // default category

        }

        else {

            sCategory = sCategory.toLocaleLowerCase();

            if(this._isNewCategory(sCategory)) {

                this._createNewCategory(sCategory);

            }

        }

        var sClass = "global"; // default source

        var sDetail = null;

        if(sSource) {

            var spaceIndex = sSource.indexOf(" ");

            if(spaceIndex > 0) {

                sClass = sSource.substring(0,spaceIndex);// substring until first space

                sDetail = sSource.substring(spaceIndex,sSource.length);// the rest of the source

            }

            else {

                sClass = sSource;

            }

            if(this._isNewSource(sClass)) {

                this._createNewSource(sClass);

            }

        }



        var timestamp = new Date();

        var logEntry = {

            time: timestamp,

            category: sCategory,

            source: sClass,

            sourceDetail: sDetail,

            msg: sMsg

        };



        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.

 *

 */

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 messages.

 *

 * @return {array} Array of log messages.

 */

YAHOO.widget.Logger.getStack = function() {

    return this._stack;

};



/**

 * Public accessor to internal start time.

 *

 * @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.

 */

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.

 */

YAHOO.widget.Logger.enableBrowserConsole = function() {

    this._browserConsoleEnabled = true;

    YAHOO.log("Logger output to the function console.log() has been enabled.");

};



/***************************************************************************

 * Private methods

 ***************************************************************************/

/**

 * Creates a new category of log messages and fires categoryCreateEvent.

 *

 * @param {string} category Category name

 * @private

 */

YAHOO.widget.Logger._createNewCategory = function(category) {

    this.categories.push(category);

    this.categoryCreateEvent.fire(category);

};



/**

 * Checks to see if a category has already been created.

 *

 * @param {string} category Category name

 * @return {boolean} Returns true if category is unknown, else returns false

 * @private

 */

YAHOO.widget.Logger._isNewCategory = function(category) {

    for(var i=0; i < this.categories.length; i++) {

        if(category == this.categories[i]) {

            return false;

        }

    }

    return true;

};



/**

 * Creates a new source of log messages and fires sourceCreateEvent.

 *

 * @param {string} source Source name

 * @private

 */

YAHOO.widget.Logger._createNewSource = function(source) {

    this.sources.push(source);

    this.sourceCreateEvent.fire(source);

};



/**

 * Checks to see if a source has already been created.

 *

 * @param {string} source Source name

 * @return {boolean} Returns true if source is unknown, else returns false

 * @private

 */

YAHOO.widget.Logger._isNewSource = function(source) {

    if(source) {

        for(var i=0; i < this.sources.length; i++) {

            if(source == this.sources[i]) {

                return false;

            }

        }

        return true;

    }

};



/**

 * Outputs a log message to global console.log() function.

 *

 * @param {object} entry Log entry object

 * @private

 */

YAHOO.widget.Logger._printToBrowserConsole = function(entry) {

    if(window.console && console.log) {

        var category = entry.category;

        var label = entry.category.substring(0,4).toUpperCase();



        var time = entry.time;

        if (time.toLocaleTimeString) {

            var 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): " +

            entry.source + ": " +

            entry.msg;



        console.log(output);

    }

};



/***************************************************************************

 * Private event handlers

 ***************************************************************************/

/**

 * Handles logging of messages due to window error events.

 *

 * @param {string} msg The error message

 * @param {string} url URL of the error

 * @param {string} line Line number of the error

 * @private

 */

YAHOO.widget.Logger._onWindowError = function(msg,url,line) {

    // Logger is not in scope of this event handler

    try {

        YAHOO.widget.Logger.log(msg+' ('+url+', line '+line+')', "window");

        if(YAHOO.widget.Logger._origOnWindowError) {

            YAHOO.widget.Logger._origOnWindowError();

        }

    }

    catch(e) {

        return false;

    }

};



/**

 * Handle native JavaScript errors

 */

//NB: Not all browsers support the window.onerror event

if(window.onerror) {

    // Save any previously defined handler to call

    YAHOO.widget.Logger._origOnWindowError = window.onerror;

}

window.onerror = YAHOO.widget.Logger._onWindowError;



/**

 * First log

 */

YAHOO.widget.Logger.log("Logger initialized");



/****************************************************************************/

/****************************************************************************/

/****************************************************************************/

/**

 * Class providing ability to log messages through YAHOO.widget.Logger from a

 * named source.

 *

 * @constructor

 * @param {string} sSource Source of LogWriter instance

 */

YAHOO.widget.LogWriter = function(sSource) {

    if(!sSource) {

        YAHOO.log("Could not instantiate LogWriter due to invalid source.", "error", "LogWriter");

        return;

    }

    this._source = sSource;

 };



/***************************************************************************

 * Public methods

 ***************************************************************************/

 /**

 * Public accessor to the unique name of the LogWriter instance.

 *

 * @return {string} Unique name of the LogWriter instance

 */

YAHOO.widget.LogWriter.prototype.toString = function() {

    return "LogWriter " + this._sSource;

};



/**

 * Logs a message attached to the source of the LogWriter.

 *

 * @param {string} sMsg The log message

 * @param {string} sCategory Category name

 */

YAHOO.widget.LogWriter.prototype.log = function(sMsg, sCategory) {

    YAHOO.widget.Logger.log(sMsg, sCategory, this._source);

};



/**

 * Public accessor to get the source name.

 *

 * @return {string} The LogWriter source

 */

YAHOO.widget.LogWriter.prototype.getSource = function() {

    return this._sSource;

};



/**

 * Public accessor to set the source name.

 *

 * @param {string} sSource Source of LogWriter instance

 */

YAHOO.widget.LogWriter.prototype.setSource = function(sSource) {

    if(!sSource) {

        YAHOO.log("Could not set source due to invalid source.", "error", this.toString());

        return;

    }

    else {

        this._sSource = sSource;

    }

};

/***************************************************************************

 * Private members

 ***************************************************************************/

/**

 * Source of the log writer instance.

 *

 * @type string

 * @private

 */

YAHOO.widget.LogWriter.prototype._source = null;







/****************************************************************************/

/****************************************************************************/

/****************************************************************************/



/**

 * Class providing UI to read messages logged to YAHOO.widget.Logger.

 *

 * requires YAHOO.util.Dom DOM utility

 * requires YAHOO.util.Event Event utility

 * optional YAHOO.util.DragDrop Drag and drop utility

 *

 * @constructor

 * @param {el or ID} containerEl DOM element object or ID of container to wrap reader UI

 * @param {object} oConfig Optional object literal of configuration params

 */

YAHOO.widget.LogReader = function(containerEl, oConfig) {

    var oSelf = this;

    this._sName = YAHOO.widget.LogReader._index;

    YAHOO.widget.LogReader._index++;



    // Parse config vars here

    if (typeof oConfig == "object") {

        for(var param in oConfig) {

            this[param] = oConfig[param];

        }

    }



    // Attach container...

    if(containerEl) {

        if(typeof containerEl == "string") {

            this._containerEl = document.getElementById(containerEl);

        }

        else if(containerEl.tagName) {

            this._containerEl = containerEl;

        }

        this._containerEl.className = "yui-log";

    }

    // ...or create container from scratch

    if(!this._containerEl) {

        if(YAHOO.widget.LogReader._defaultContainerEl) {

            this._containerEl =  YAHOO.widget.LogReader._defaultContainerEl;

        }

        else {

            this._containerEl = document.body.appendChild(document.createElement("div"));

            this._containerEl.id = "yui-log";

            this._containerEl.className = "yui-log";



            YAHOO.widget.LogReader._defaultContainerEl = this._containerEl;

        }



        // If implementer has provided container values, trust and set those

        var containerStyle = this._containerEl.style;

        if(this.width) {

            containerStyle.width = this.width;

        }

        if(this.left) {

            containerStyle.left = this.left;

        }

        if(this.right) {

            containerStyle.right = this.right;

        }

        if(this.bottom) {

            containerStyle.bottom = this.bottom;

        }

        if(this.top) {

            containerStyle.top = this.top;

        }

        if(this.fontSize) {

            containerStyle.fontSize = this.fontSize;

        }

    }



    if(this._containerEl) {

        // Create header

        if(!this._hdEl) {

            this._hdEl = this._containerEl.appendChild(document.createElement("div"));

            this._hdEl.id = "yui-log-hd" + this._sName;

            this._hdEl.className = "yui-log-hd";



            this._collapseEl = this._hdEl.appendChild(document.createElement("div"));

            this._collapseEl.className = "yui-log-btns";



            this._collapseBtn = document.createElement("input");

            this._collapseBtn.type = "button";

            this._collapseBtn.style.fontSize = YAHOO.util.Dom.getStyle(this._containerEl,"fontSize");

            this._collapseBtn.className = "yui-log-button";

            this._collapseBtn.value = "Collapse";

            this._collapseBtn = this._collapseEl.appendChild(this._collapseBtn);

            YAHOO.util.Event.addListener(oSelf._collapseBtn,'click',oSelf._onClickCollapseBtn,oSelf);



            this._title = this._hdEl.appendChild(document.createElement("h4"));

            this._title.innerHTML = "Logger Console";



            // If Drag and Drop utility is available...

            // ...and this container was created from scratch...

            // ...then make the header draggable

            if(YAHOO.util.DD &&

            (YAHOO.widget.LogReader._defaultContainerEl == this._containerEl)) {

                var ylog_dd = new YAHOO.util.DD(this._containerEl.id);

                ylog_dd.setHandleElId(this._hdEl.id);

                this._hdEl.style.cursor = "move";

            }

        }

        // Ceate console

        if(!this._consoleEl) {

            this._consoleEl = this._containerEl.appendChild(document.createElement("div"));

            this._consoleEl.className = "yui-log-bd";



            // If implementer has provided console, trust and set those

            if(this.height) {

                this._consoleEl.style.height = this.height;

            }

        }

        // Don't create footer if disabled

        if(!this._ftEl && this.footerEnabled) {

            this._ftEl = this._containerEl.appendChild(document.createElement("div"));

            this._ftEl.className = "yui-log-ft";



            this._btnsEl = this._ftEl.appendChild(document.createElement("div"));

            this._btnsEl.className = "yui-log-btns";



            this._pauseBtn = document.createElement("input");

            this._pauseBtn.type = "button";

            this._pauseBtn.style.fontSize = YAHOO.util.Dom.getStyle(this._containerEl,"fontSize");

            this._pauseBtn.className = "yui-log-button";

            this._pauseBtn.value = "Pause";

            this._pauseBtn = this._btnsEl.appendChild(this._pauseBtn);

            YAHOO.util.Event.addListener(oSelf._pauseBtn,'click',oSelf._onClickPauseBtn,oSelf);



            this._clearBtn = document.createElement("input");

            this._clearBtn.type = "button";

            this._clearBtn.style.fontSize = YAHOO.util.Dom.getStyle(this._containerEl,"fontSize");

            this._clearBtn.className = "yui-log-button";

            this._clearBtn.value = "Clear";

            this._clearBtn = this._btnsEl.appendChild(this._clearBtn);

            YAHOO.util.Event.addListener(oSelf._clearBtn,'click',oSelf._onClickClearBtn,oSelf);



            this._categoryFiltersEl = this._ftEl.appendChild(document.createElement("div"));

            this._categoryFiltersEl.className = "yui-log-categoryfilters";

            this._sourceFiltersEl = this._ftEl.appendChild(document.createElement("div"));

            this._sourceFiltersEl.className = "yui-log-sourcefilters";

        }

    }



    // Initialize internal vars

    if(!this._buffer) {

        this._buffer = []; // output buffer

    }

    this._lastTime = YAHOO.widget.Logger.getStartTime(); // timestamp of last log message to console

    

    // Subscribe to Logger custom events

    YAHOO.widget.Logger.newLogEvent.subscribe(this._onNewLog, this);

    YAHOO.widget.Logger.logResetEvent.subscribe(this._onReset, this);



    // Initialize category filters

    this._categoryFilters = [];

    var catsLen = YAHOO.widget.Logger.categories.length;

    if(this._categoryFiltersEl) {

        for(var i=0; i < catsLen; i++) {

            this._createCategoryCheckbox(YAHOO.widget.Logger.categories[i]);

        }

    }

    // Initialize source filters

    this._sourceFilters = [];

    var sourcesLen = YAHOO.widget.Logger.sources.length;

    if(this._sourceFiltersEl) {

        for(var j=0; j < sourcesLen; j++) {

            this._createSourceCheckbox(YAHOO.widget.Logger.sources[j]);

        }

    }

    YAHOO.widget.Logger.categoryCreateEvent.subscribe(this._onCategoryCreate, this);

    YAHOO.widget.Logger.sourceCreateEvent.subscribe(this._onSourceCreate, this);



    this._filterLogs();

    YAHOO.log("LogReader initialized", null, this.toString());

};



/***************************************************************************

 * Public members

 ***************************************************************************/

/**

 * Whether or not the log reader is enabled to output log messages. Default:

 * true.

 *

 * @type boolean

 */

YAHOO.widget.LogReader.prototype.logReaderEnabled = true;



/**

 * Public member to access CSS width of the log reader container.

 *

 * @type string

 */

YAHOO.widget.LogReader.prototype.width = null;



/**

 * Public member to access CSS height of the log reader container.

 *

 * @type string

 */

YAHOO.widget.LogReader.prototype.height = null;



/**

 * Public member to access CSS top position of the log reader container.

 *

 * @type string

 */

YAHOO.widget.LogReader.prototype.top = null;



/**

 * Public member to access CSS left position of the log reader container.

 *

 * @type string

 */

YAHOO.widget.LogReader.prototype.left = null;



/**

 * Public member to access CSS right position of the log reader container.

 *

 * @type string

 */

YAHOO.widget.LogReader.prototype.right = null;



/**

 * Public member to access CSS bottom position of the log reader container.

 *

 * @type string

 */

YAHOO.widget.LogReader.prototype.bottom = null;



/**

 * Public member to access CSS font size of the log reader container.

 *

 * @type string

 */

YAHOO.widget.LogReader.prototype.fontSize = null;



/**

 * Whether or not the footer UI is enabled for the log reader. Default: true.

 *

 * @type boolean

 */

YAHOO.widget.LogReader.prototype.footerEnabled = true;



/**

 * Whether or not output is verbose (more readable). Setting to true will make

 * output more compact (less readable). Default: true.

 *

 * @type boolean

 */

YAHOO.widget.LogReader.prototype.verboseOutput = true;



/**

 * Whether or not newest message is printed on top. Default: true.

 *

 * @type boolean

 */

YAHOO.widget.LogReader.prototype.newestOnTop = true;



/**

 * Maximum number of messages a LogReader console will display. Default: 500;

 *

 * @type number

 */

YAHOO.widget.LogReader.prototype.thresholdMax = 500;



/**

 * When a LogReader console reaches its thresholdMax, it will clear out messages

 * and print out the latest thresholdMin number of messages. Default: 100;

 *

 * @type number

 */

YAHOO.widget.LogReader.prototype.thresholdMin = 100;



/***************************************************************************

 * Public methods

 ***************************************************************************/

 /**

 * Public accessor to the unique name of the LogReader instance.

 *

 * @return {string} Unique name of the LogReader instance

 */

YAHOO.widget.LogReader.prototype.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 log reader.

 */

YAHOO.widget.LogReader.prototype.pause = function() {

    this._timeout = null;

    this.logReaderEnabled = false;

};



/**

 * Resumes output of log messages, including outputting any log messages that

 * have been saved to buffer while paused.

 */

YAHOO.widget.LogReader.prototype.resume = function() {

    this.logReaderEnabled = true;

    this._printBuffer();

};



/**

 * Hides UI of log reader. Logging functionality is not disrupted.

 */

YAHOO.widget.LogReader.prototype.hide = function() {

    this._containerEl.style.display = "none";

};



/**

 * Shows UI of log reader. Logging functionality is not disrupted.

 */

YAHOO.widget.LogReader.prototype.show = function() {

    this._containerEl.style.display = "block";

};



/**

 * Updates title to given string.

 *

 * @param {string} sTitle String to display in log reader's title bar.

 */

YAHOO.widget.LogReader.prototype.setTitle = function(sTitle) {

    this._title.innerHTML = this._HTML2Text(sTitle);

};

 /***************************************************************************

 * Private members

 ***************************************************************************/

/**

 * Internal class member to index multiple log reader instances.

 *

 * @type number

 * @private

 */

YAHOO.widget.LogReader._index = 0;



/**

 * Name of LogReader instance.

 *

 * @type string

 * @private

 */

YAHOO.widget.LogReader.prototype._sName = null;



/**

 * A class member shared by all log readers 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.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader._defaultContainerEl = null;



/**

 * Buffer of log messages for batch output.

 *

 * @type array

 * @private

 */

YAHOO.widget.LogReader.prototype._buffer = null;



/**

 * Number of log messages output to console.

 *

 * @type number

 * @private

 */

YAHOO.widget.LogReader.prototype._consoleMsgCount = 0;



/**

 * Date of last output log message.

 *

 * @type date

 * @private

 */

YAHOO.widget.LogReader.prototype._lastTime = null;



/**

 * Batched output timeout ID.

 *

 * @type number

 * @private

 */

YAHOO.widget.LogReader.prototype._timeout = null;



/**

 * Array of filters for log message categories.

 *

 * @type array

 * @private

 */

YAHOO.widget.LogReader.prototype._categoryFilters = null;



/**

 * Array of filters for log message sources.

 *

 * @type array

 * @private

 */

YAHOO.widget.LogReader.prototype._sourceFilters = null;



/**

 * Log reader container element.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._containerEl = null;



/**

 * Log reader header element.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._hdEl = null;



/**

 * Log reader collapse element.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._collapseEl = null;



/**

 * Log reader collapse button element.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._collapseBtn = null;



/**

 * Log reader title header element.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._title = null;



/**

 * Log reader console element.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._consoleEl = null;



/**

 * Log reader footer element.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._ftEl = null;



/**

 * Log reader buttons container element.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._btnsEl = null;



/**

 * Container element for log reader category filter checkboxes.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._categoryFiltersEl = null;



/**

 * Container element for log reader source filter checkboxes.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._sourceFiltersEl = null;



/**

 * Log reader pause button element.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._pauseBtn = null;



/**

 * Clear button element.

 *

 * @type HTMLElement

 * @private

 */

YAHOO.widget.LogReader.prototype._clearBtn = null;

/***************************************************************************

 * Private methods

 ***************************************************************************/

/**

 * Creates the UI for a category filter in the log reader footer element.

 *

 * @param {string} category Category name

 * @private

 */

YAHOO.widget.LogReader.prototype._createCategoryCheckbox = function(category) {

    var oSelf = this;



    if(this._ftEl) {

        var parentEl = this._categoryFiltersEl;

        var filters = this._categoryFilters;



        var filterEl = parentEl.appendChild(document.createElement("span"));

        filterEl.className = "yui-log-filtergrp";

            // Append el at the end so IE 5.5 can set "type" attribute

            // and THEN set checked property

            var categoryChk = document.createElement("input");

            categoryChk.id = "yui-log-filter-" + category + this._sName;

            categoryChk.className = "yui-log-filter-" + category;

            categoryChk.type = "checkbox";

            categoryChk.category = category;

            categoryChk = filterEl.appendChild(categoryChk);

            categoryChk.checked = true;



            // Add this checked filter to the internal array of filters

            filters.push(category);

            // Subscribe to the click event

            YAHOO.util.Event.addListener(categoryChk,'click',oSelf._onCheckCategory,oSelf);



            // Create and class the text label

            var categoryChkLbl = filterEl.appendChild(document.createElement("label"));

            categoryChkLbl.htmlFor = categoryChk.id;

            categoryChkLbl.className = category;

            categoryChkLbl.innerHTML = category;

    }

};



YAHOO.widget.LogReader.prototype._createSourceCheckbox = function(source) {

    var oSelf = this;



    if(this._ftEl) {

        var parentEl = this._sourceFiltersEl;

        var filters = this._sourceFilters;



        var filterEl = parentEl.appendChild(document.createElement("span"));

        filterEl.className = "yui-log-filtergrp";



        // Append el at the end so IE 5.5 can set "type" attribute

        // and THEN set checked property

        var sourceChk = document.createElement("input");

        sourceChk.id = "yui-log-filter" + source + this._sName;

        sourceChk.className = "yui-log-filter" + source;

        sourceChk.type = "checkbox";

        sourceChk.source = source;

        sourceChk = filterEl.appendChild(sourceChk);

        sourceChk.checked = true;



        // Add this checked filter to the internal array of filters

        filters.push(source);

        // Subscribe to the click event

        YAHOO.util.Event.addListener(sourceChk,'click',oSelf._onCheckSource,oSelf);



        // Create and class the text label

        var sourceChkLbl = filterEl.appendChild(document.createElement("label"));

        sourceChkLbl.htmlFor = sourceChk.id;

        sourceChkLbl.className = source;

        sourceChkLbl.innerHTML = source;

    }

};



/**

 * Reprints all log messages in the stack through filters.

 *

 * @private

 */

YAHOO.widget.LogReader.prototype._filterLogs = function() {

    // Reprint stack with new filters

    if (this._consoleEl !== null) {

        this._clearConsole();

        this._printToConsole(YAHOO.widget.Logger.getStack());

    }

};



/**

 * Clears all outputted log messages from the console and resets the time of the

 * last output log message.

 *

 * @private

 */

YAHOO.widget.LogReader.prototype._clearConsole = function() {

    // Clear the buffer of any pending messages

    this._timeout = null;

    this._buffer = [];

    this._consoleMsgCount = 0;



    // Reset the rolling timer

    this._lastTime = YAHOO.widget.Logger.getStartTime();



    var consoleEl = this._consoleEl;

    while(consoleEl.hasChildNodes()) {

        consoleEl.removeChild(consoleEl.firstChild);

    }

};



/**

 * Sends buffer of log messages to output and clears buffer.

 *

 * @private

 */

YAHOO.widget.LogReader.prototype._printBuffer = function() {

    this._timeout = null;



    if(this._consoleEl !== null) {

        var thresholdMax = this.thresholdMax;

        thresholdMax = (thresholdMax && !isNaN(thresholdMax)) ? thresholdMax : 500;

        if(this._consoleMsgCount < thresholdMax) {

            var entries = [];

            for (var i=0; i<this._buffer.length; i++) {

                entries[i] = this._buffer[i];

            }

            this._buffer = [];

            this._printToConsole(entries);

        }

        else {

            this._filterLogs();

        }

        

        if(!this.newestOnTop) {

            this._consoleEl.scrollTop = this._consoleEl.scrollHeight;

        }

    }

};



/**

 * Cycles through an array of log messages, and outputs each one to the console

 * if its category has not been filtered out.

 *

 * @param {array} aEntries

 * @private

 */

YAHOO.widget.LogReader.prototype._printToConsole = function(aEntries) {

    // Manage the number of messages displayed in the console

    var entriesLen = aEntries.length;

    var thresholdMin = this.thresholdMin;

    if(isNaN(thresholdMin) || (thresholdMin > this.thresholdMax)) {

        thresholdMin = 0;

    }

    var entriesStartIndex = (entriesLen > thresholdMin) ? (entriesLen - thresholdMin) : 0;

    

    // Iterate through all log entries to print the ones that filter through

    var sourceFiltersLen = this._sourceFilters.length;

    var categoryFiltersLen = this._categoryFilters.length;

    for(var i=entriesStartIndex; i<entriesLen; i++) {

        var entry = aEntries[i];

        var category = entry.category;

        var source = entry.source;

        var sourceDetail = entry.sourceDetail;

        var okToPrint = false;

        var okToFilterCats = false;



        for(var j=0; j<sourceFiltersLen; j++) {

            if(source == this._sourceFilters[j]) {

                okToFilterCats = true;

                break;

            }

        }

        if(okToFilterCats) {

            for(var k=0; k<categoryFiltersLen; k++) {

                if(category == this._categoryFilters[k]) {

                    okToPrint = true;

                    break;

                }

            }

        }

        if(okToPrint) {

            // To format for console, calculate the elapsed time

            // to be from the last item that passed through the filter,

            // not the absolute previous item in the stack

            var label = entry.category.substring(0,4).toUpperCase();



            var time = entry.time;

            if (time.toLocaleTimeString) {

                var localTime  = time.toLocaleTimeString();

            }

            else {

                localTime = time.toString();

            }



            var msecs = time.getTime();

            var startTime = YAHOO.widget.Logger.getStartTime();

            var totalTime = msecs - startTime;

            var elapsedTime = msecs - this._lastTime;

            this._lastTime = msecs;



            var verboseOutput = (this.verboseOutput);

            var container = (verboseOutput) ? "CODE" : "PRE";

            var sourceAndDetail = (sourceDetail) ?

                source + " " + sourceDetail : source;



            // Verbose uses code tag instead of pre tag (for wrapping)

            // and includes extra line breaks

            var output =  (verboseOutput) ?

                ["<p><span class='", category, "'>", label, "</span> ",

                totalTime, "ms (+", elapsedTime, ") ",

                localTime, ": ",

                "</p><p>",

                sourceAndDetail,

                ": </p><p>",

                this._HTML2Text(entry.msg),

                "</p>"] :

                

                ["<p><span class='", category, "'>", label, "</span> ",

                totalTime, "ms (+", elapsedTime, ") ",

                localTime, ": ",

                sourceAndDetail, ": ",

                this._HTML2Text(entry.msg),"</p>"];



            var oNewElement = (this.newestOnTop) ?

                this._consoleEl.insertBefore(document.createElement(container),this._consoleEl.firstChild):

                this._consoleEl.appendChild(document.createElement(container));



            oNewElement.innerHTML = output.join("");

            this._consoleMsgCount++;

        }

    }

};



/**

 * Converts input chars "<", ">", and "&" to HTML entities.

 *

 * @private

 */

YAHOO.widget.LogReader.prototype._HTML2Text = function(html) {

    if(html) {

        return html.replace(/&/g, "&#38;").replace(/</g, "&#60;").replace(/>/g, "&#62;");

    }

    else return "";

};



/***************************************************************************

 * Private event handlers

 ***************************************************************************/

/**

 * Handles Logger's categoryCreateEvent.

 *

 * @param {string} type The event

 * @param {array} args Data passed from event firer

 * @param {object} oSelf The log reader instance

 * @private

 */

YAHOO.widget.LogReader.prototype._onCategoryCreate = function(type, args, oSelf) {

    var category = args[0];

    if(oSelf._ftEl) {

        oSelf._createCategoryCheckbox(category);

    }

};



/**

 * Handles Logger's sourceCreateEvent.

 *

 * @param {string} type The event

 * @param {array} args Data passed from event firer

 * @param {object} oSelf The log reader instance

 * @private

 */

YAHOO.widget.LogReader.prototype._onSourceCreate = function(type, args, oSelf) {

    var source = args[0];

    if(oSelf._ftEl) {

        oSelf._createSourceCheckbox(source);

    }

};



/**

 * Handles check events on the category filter checkboxes.

 *

 * @param {event} v The click event

 * @param {object} oSelf The log reader instance

 * @private

 */

YAHOO.widget.LogReader.prototype._onCheckCategory = function(v, oSelf) {

    var newFilter = this.category;

    var filtersArray = oSelf._categoryFilters;



    if(!this.checked) { // Remove category from filters

        for(var i=0; i<filtersArray.length; i++) {

            if(newFilter == filtersArray[i]) {

                filtersArray.splice(i, 1);

                break;

            }

        }

    }

    else { // Add category to filters

        filtersArray.push(newFilter);

    }

    oSelf._filterLogs();

};



/**

 * Handles check events on the category filter checkboxes.

 *

 * @param {event} v The click event

 * @param {object} oSelf The log reader instance

 * @private

 */

YAHOO.widget.LogReader.prototype._onCheckSource = function(v, oSelf) {

    var newFilter = this.source;

    var filtersArray = oSelf._sourceFilters;



    if(!this.checked) { // Remove category from filters

        for(var i=0; i<filtersArray.length; i++) {

            if(newFilter == filtersArray[i]) {

                filtersArray.splice(i, 1);

                break;

            }

        }

    }

    else { // Add category to filters

        filtersArray.push(newFilter);

    }

    oSelf._filterLogs();

};



/**

 * Handles click events on the collapse button.

 *

 * @param {event} v The click event

 * @param {object} oSelf The log reader instance

 * @private

 */

YAHOO.widget.LogReader.prototype._onClickCollapseBtn = function(v, oSelf) {

    var btn = oSelf._collapseBtn;

    if(btn.value == "Expand") {

        oSelf._consoleEl.style.display = "block";

        if(oSelf._ftEl) {

            oSelf._ftEl.style.display = "block";

        }

        btn.value = "Collapse";

    }

    else {

        oSelf._consoleEl.style.display = "none";

        if(oSelf._ftEl) {

            oSelf._ftEl.style.display = "none";

        }

        btn.value = "Expand";

    }

};



/**

 * Handles click events on the pause button.

 *

 * @param {event} v The click event

 * @param {object} oSelf The log reader instance

 * @private

 */

YAHOO.widget.LogReader.prototype._onClickPauseBtn = function(v, oSelf) {

    var btn = oSelf._pauseBtn;

    if(btn.value == "Resume") {

        oSelf.resume();

        btn.value = "Pause";

    }

    else {

        oSelf.pause();

        btn.value = "Resume";

    }

};



/**

 * Handles click events on the clear button.

 *

 * @param {event} v The click event

 * @param {object} oSelf The log reader instance

 * @private

 */

YAHOO.widget.LogReader.prototype._onClickClearBtn = function(v, oSelf) {

    oSelf._clearConsole();

};



/**

 * Handles Logger's newLogEvent.

 *

 * @param {string} type The newLog event

 * @param {array} args Data passed from event firer

 * @param {object} oSelf The log reader instance

 * @private

 */

YAHOO.widget.LogReader.prototype._onNewLog = function(type, args, oSelf) {

    var logEntry = args[0];

    oSelf._buffer.push(logEntry);



    if (oSelf.logReaderEnabled === true && oSelf._timeout === null) {

        oSelf._timeout = setTimeout(function(){oSelf._printBuffer();}, 100);

    }

};



/**

 * Handles Logger's resetEvent.

 *

 * @param {string} type The click event

 * @param {array} args Data passed from event firer

 * @param {object} oSelf The log reader instance

 * @private

 */

YAHOO.widget.LogReader.prototype._onReset = function(type, args, oSelf) {

    oSelf._filterLogs();

};



//logger
/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
Version: 0.11.4
*/

/**
 * 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:
 * <ul>
 * <li>linked element: the element that is passed into the constructor.
 * This is the element which defines the boundaries for interaction with
 * other DragDrop objects.</li>
 * <li>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.</li>
 * <li>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}
 * </li>
 * </ul>
 * 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:
 * <pre>
 *  dd = new YAHOO.util.DragDrop("div1", "group1");
 * </pre>
 * 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...
 * <pre>
 *  dd.onDragDrop = function(e, id) {
 *   alert("dd was dropped on " + id);
 *  }
 * </pre>
 * @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 = {

    /**
     * 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.
     *
     * @type String
     */
    id: null,

    /**
     * Configuration attributes passed into the constructor
     * @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
     *
     * @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.
     *
     * @type String
     * @private
     */
    handleElId: null,

    /**
     * An associative array of HTML tags that will be ignored if clicked.
     * @type {string: string}
     */
    invalidHandleTypes: null,

    /**
     * An associative array of ids for elements that will be ignored if clicked
     * @type {string: string}
     */
    invalidHandleIds: null,

    /**
     * An indexted array of css class names for elements that will be ignored
     * if clicked.
     * @type string[]
     */
    invalidHandleClasses: null,

    /**
     * The linked element's absolute X position at the time the drag was
     * started
     *
     * @type int
     * @private
     */
    startPageX: 0,

    /**
     * The linked element's absolute X position at the time the drag was
     * started
     *
     * @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.
     * @type {string: string}
     */
    groups: null,

    /**
     * Individual drag/drop instances can be locked.  This will prevent
     * onmousedown start drag.
     *
     * @type boolean
     * @private
     */
    locked: false,

    /**
     * Lock this instance
     */
    lock: function() { this.locked = true; },

    /**
     * Unlock this instace
     */
    unlock: function() { this.locked = false; },

    /**
     * By default, all insances can be a drop target.  This can be disabled by
     * setting isTarget to false.
     *
     * @type boolean
     */
    isTarget: true,

    /**
     * The padding configured for this drag and drop object for calculating
     * the drop zone intersection with this object.
     * @type int[]
     */
    padding: null,

    /**
     * @private
     */
    _domRef: null,

    /**
     * Internal typeof flag
     * @private
     */
    __ygDragDrop: true,

    /**
     * Set to true when horizontal contraints are applied
     *
     * @type boolean
     * @private
     */
    constrainX: false,

    /**
     * Set to true when vertical contraints are applied
     *
     * @type boolean
     * @private
     */
    constrainY: false,

    /**
     * The left constraint
     *
     * @type int
     * @private
     */
    minX: 0,

    /**
     * The right constraint
     *
     * @type int
     * @private
     */
    maxX: 0,

    /**
     * The up constraint
     *
     * @type int
     * @private
     */
    minY: 0,

    /**
     * The down constraint
     *
     * @type int
     * @private
     */
    maxY: 0,

    /**
     * Maintain offsets when we resetconstraints.  Used to maintain the
     * slider thumb value, and this needs to be fixed.
     * @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.
     * @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.
     * @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
     * @type boolean
     */
    primaryButtonOnly: true,

    /**
     * The availabe property is false until the linked dom element is accessible.
     * @type boolean
     */
    available: false,

    /**
     * Code that executes immediately before the startDrag event
     * @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.
     *
     * @param {int} X click location
     * @param {int} Y click location
     */
    startDrag: function(x, y) { /* override this */ },

    /**
     * Code that executes immediately before the onDrag event
     * @private
     */
    b4Drag: function(e) { },

    /**
     * Abstract method called during the onMouseMove event while dragging an
     * object.
     *
     * @param {Event} e
     */
    onDrag: function(e) { /* override this */ },

    /**
     * Code that executes immediately before the onDragEnter event
     * @private
     */
    // b4DragEnter: function(e) { },

    /**
     * Abstract method called when this element fist begins hovering over
     * another DragDrop obj
     *
     * @param {Event} e
     * @param {String || YAHOO.util.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
     * @private
     */
    b4DragOver: function(e) { },

    /**
     * Abstract method called when this element is hovering over another
     * DragDrop obj
     *
     * @param {Event} e
     * @param {String || YAHOO.util.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
     * @private
     */
    b4DragOut: function(e) { },

    /**
     * Abstract method called when we are no longer hovering over an element
     *
     * @param {Event} e
     * @param {String || YAHOO.util.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
     * @private
     */
    b4DragDrop: function(e) { },

    /**
     * Abstract method called when this item is dropped on another DragDrop
     * obj
     *
     * @param {Event} e
     * @param {String || YAHOO.util.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 */ },

    /**
     * Code that executes immediately before the endDrag event
     * @private
     */
    b4EndDrag: function(e) { },

    /**
     * Fired when we are done dragging the object
     *
     * @param {Event} e
     */
    endDrag: function(e) { /* override this */ },

    /**
     * Code executed immediately before the onMouseDown event

     * @param {Event} e
     * @private
     */
    b4MouseDown: function(e) {  },

    /**
     * Event handler that fires when a drag/drop obj gets a mousedown
     * @param {Event} e
     */
    onMouseDown: function(e) { /* override this */ },

    /**
     * Event handler that fires when a drag/drop obj gets a mouseup
     * @param {Event} e
     */
    onMouseUp: function(e) { /* override this */ },

    /**
     * Override the onAvailable method to do what is needed after the initial
     * position was determined.
     */
    onAvailable: function () {
        this.logger.log("onAvailable (base)");
    },

    /**
     * Returns a reference to the linked element
     *
     * @return {HTMLElement} the html element
     */
    getEl: function() {
        if (!this._domRef) {
            this._domRef = YAHOO.util.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
     *
     * @return {HTMLElement} the html element
     */
    getDragEl: function() {
        return YAHOO.util.Dom.get(this.dragElId);
    },

    /**
     * Sets up the DragDrop object.  Must be called in the constructor of any
     * YAHOO.util.DragDrop subclass
     *
     * @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);
        YAHOO.util.Event.addListener(this.id, "mousedown",
                                          this.handleMouseDown, this, true);
    },

    /**
     * Initializes Targeting functionality only... the object does not
     * get a mousedown handler.
     *
     * @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 || {};

        // create a local reference to the drag and drop manager
        this.DDM = YAHOO.util.DDM;
        // initialize the groups array
        this.groups = {};

        // 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;

        YAHOO.util.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.
     */
    applyConfig: function() {

        // 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);

    },

    /**
     * Executed when the linked element is available
     * @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.
     * @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 dd element
     */
    setInitPosition: function(diffX, diffY) {
        var el = this.getEl();

        if (!this.DDM.verifyEl(el)) {
            this.logger.log(this.id + " element is broken");
            return;
        }

        var dx = diffX || 0;
        var dy = diffY || 0;

        var p = YAHOO.util.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 + " inital 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.
     * @param pos current position (from previous lookup)
     * @private
     */
    setStartPosition: function(pos) {
        var p = pos || YAHOO.util.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.
     *
     * @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
     * @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
     *
     * @param id 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.
     *
     * @param id the id of the element that will be used to initiate the drag
     */
    setHandleElId: function(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
     */
    setOuterHandleElId: function(id) {
        this.logger.log("Adding outer handle event: " + id);
        YAHOO.util.Event.addListener(id, "mousedown",
                this.handleMouseDown, this, true);
        this.setHandleElId(id);
    },

    /**
     * Remove all drag and drop hooks for this element
     */
    unreg: function() {
        this.logger.log("DragDrop obj cleanup " + this.id);
        YAHOO.util.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.)
     *
     * @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
     *
     * @param {Event} e
     * @param {YAHOO.util.DragDrop} oDD the clicked dd object (this dd obj)
     * @private
     */
    handleMouseDown: function(e, oDD) {

        this.logger.log("isLocked: " + this.isLocked());

        var EU = YAHOO.util.Event;

        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.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(EU.getPageX(e), EU.getPageY(e));
        if ( !this.DDM.isOverTarget(pt, this) )  {
                this.logger.log("Click was not over the element: " + this.id);
        } else {

            this.logger.log("click is over target");

            //  check to see if the handle was clicked
            var srcEl = EU.getTarget(e);

            if (this.isValidHandleChild(srcEl) &&
                    (this.id == this.handleElId ||
                     this.DDM.handleWasClicked(srcEl, this.id)) ) {

                this.logger.log("click was a valid handle");

                // set the initial element position
                this.setStartPosition();

                this.logger.log("firing onMouseDown events");


                this.b4MouseDown(e);
                this.onMouseDown(e);
                this.DDM.handleMouseDown(e, this);

                this.DDM.stopEvent(e);
            }
        }
    },

    /**
     * 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.
     *
     * @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
     * @param {string} id the element id of the element you wish to ignore
     */
    addInvalidHandleId: function(id) {
        this.invalidHandleIds[id] = id;
    },


    /**
     * Lets you specify a css class of elements that will not initiate a drag
     * @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
     *
     * @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
     * @param {string} the id of the element to re-enable
     */
    removeInvalidHandleId: function(id) {
        delete this.invalidHandleIds[id];
    },

    /**
     * Unsets an invalid css class
     * @param {string} the class of the element(s) you wish to re-enable
     */
    removeInvalidHandleClass: function(cssClass) {
        for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
            if (this.invalidHandleClasses[i] == cssClass) {
                delete this.invalidHandleClasses[i];
            }
        }
    },

    /**
     * Checks the tag exclusion list to see if this click should be ignored
     *
     * @param {ygNode} node
     * @return {boolean} true if this is a valid tag type, false if not
     */
    isValidHandleChild: function(node) {

        var valid = true;
        // var n = (node.nodeName == "#text") ? node.parentNode : node;
        var nodeName;
        try {
            nodeName = node.nodeName.toUpperCase();
        } catch(e) {
            nodeName = node.nodeName;
        }
        valid = valid && !this.invalidHandleTypes[nodeName];
        valid = valid && !this.invalidHandleIds[node.id];

        for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
            valid = !YAHOO.util.Dom.hasClass(node, this.invalidHandleClasses[i]);
        }

        this.logger.log("Valid handle? ... " + valid);

        return valid;

    },

    /**
     * Create the array of horizontal tick marks if an interval was specified
     * in setXConstraint().
     *
     * @private
     */
    setXTicks: function(iStartX, iTickSize) {
        this.xTicks = [];
        this.xTickSize = iTickSize;

        var tickMap = {};

        for (var i = this.initPageX; 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().
     *
     * @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.
     *
     * @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 = iLeft;
        this.rightConstraint = iRight;

        this.minX = this.initPageX - iLeft;
        this.maxX = this.initPageX + iRight;
        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.
     */
    clearConstraints: function() {
        this.logger.log("Clearing constraints");
        this.constrainX = false;
        this.constrainY = false;
        this.clearTicks();
    },

    /**
     * Clears any tick interval defined for this instance
     */
    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.
     *
     * @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 = iUp;
        this.bottomConstraint = iDown;

        this.minY = this.initPageY - iUp;
        this.maxY = this.initPageY + iDown;
        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.
     * @param {boolean} maintainOffset
     */
    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.
     *
     * @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<len; ++i) {
                var next = i + 1;
                if (tickArray[next] && tickArray[next] >= 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
     * @return {string} string representation of the dd obj
     */
    toString: function() {
        return ("DragDrop " + this.id);
    }

};

// Only load the library once.  Rewriting the manager class would orphan
// existing drag and drop instances.
if (!YAHOO.util.DragDropMgr) {

    /**
     * Handles 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.  This class should not be instantiated; all methods
     * are are static.
     *
     * @constructor
     */
    YAHOO.util.DragDropMgr = new function() {

        /**
         * Two dimensional Array of registered DragDrop objects.  The first
         * dimension is the DragDrop item group, the second the DragDrop
         * object.
         *
         * @type {string: string}
         * @private
         */
        this.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.
         *
         * @type {string: string}
         * @private
         */
        this.handleIds = {};

        /**
         * the DragDrop object that is currently being dragged
         *
         * @type DragDrop
         * @private
         **/
        this.dragCurrent = null;

        /**
         * the DragDrop object(s) that are being hovered over
         *
         * @type Array
         * @private
         */
        this.dragOvers = {};

        /**
         * @private
         */
        this.logger = null;

        /**
         * the X distance between the cursor and the object being dragged
         *
         * @type int
         * @private
         */
        this.deltaX = 0;

        /**
         * the Y distance between the cursor and the object being dragged
         *
         * @type int
         * @private
         */
        this.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)
         *
         * @type boolean
         */
        this.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.
         *
         * @type boolean
         */
        this.stopPropagation = true;

        /**
         * @private
         */
        this.initalized = false;

        /**
         * All drag and drop can be disabled.
         *
         * @private
         */
        this.locked = false;

        /**
         * Called the first time an element is registered.
         *
         * @private
         */
        this.init = function() {
            this.logger = (YAHOO.widget.LogWriter) ?
                new YAHOO.widget.LogWriter("DragDropMgr") : YAHOO;
            this.initialized = true;
        };

        /**
         * In point mode, drag and drop interaction is defined by the
         * location of the cursor during the drag/drop
         * @type int
         */
        this.POINT     = 0;

        /**
         * In intersect mode, drag and drop interactio nis defined by the
         * overlap of two or more drag and drop objects.
         * @type int
         */
        this.INTERSECT = 1;

        /**
         * The current drag and drop mode.  Default it point mode
         * @type int
         */
        this.mode = this.POINT;

        /**
         * Runs method on all drag and drop objects
         * @private
         */
        this._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
         * @private
         */
        this._onLoad = function() {

            this.init();

            this.logger.log("DDM onload");

            var EU = YAHOO.util.Event;

            EU.on(document, "mouseup",   this.handleMouseUp, this, true);
            EU.on(document, "mousemove", this.handleMouseMove, this, true);
            EU.on(window,   "unload",    this._onUnload, this, true);
            EU.on(window,   "resize",    this._onResize, this, true);
            // EU.on(window,   "mouseout",    this._test);

        };

        /**
         * Reset constraints on all drag and drop objs
         * @private
         */
        this._onResize = function(e) {
            this.logger.log("window resize");
            this._execOnAll("resetConstraints", []);
        };

        /**
         * Lock all drag and drop functionality
         */
        this.lock = function() { this.locked = true; };

        /**
         * Unlock all drag and drop functionality
         */
        this.unlock = function() { this.locked = false; };

        /**
         * Is drag and drop locked?
         *
         * @return {boolean} True if drag and drop is locked, false otherwise.
         */
        this.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.
         *
         * @private
         */
        this.locationCache = {};

        /**
         * Set useCache to false if you want to force object the lookup of each
         * drag and drop linked element constantly during a drag.
         * @type boolean
         */
        this.useCache = true;

        /**
         * The number of pixels that the mouse needs to move after the
         * mousedown before the drag is initiated.  Default=3;
         * @type int
         */
        this.clickPixelThresh = 3;

        /**
         * The number of milliseconds after the mousedown event to initiate the
         * drag if we don't get a mouseup event. Default=1000
         * @type int
         */
        this.clickTimeThresh = 1000;

        /**
         * Flag that indicates that either the drag pixel threshold or the
         * mousdown time threshold has been met
         * @type boolean
         * @private
         */
        this.dragThreshMet = false;

        /**
         * Timeout used for the click time threshold
         * @type Object
         * @private
         */
        this.clickTimeout = null;

        /**
         * The X position of the mousedown event stored for later use when a
         * drag threshold is met.
         * @type int
         * @private
         */
        this.startX = 0;

        /**
         * The Y position of the mousedown event stored for later use when a
         * drag threshold is met.
         * @type int
         * @private
         */
        this.startY = 0;

        /**
         * Each DragDrop instance must be registered with the DragDropMgr.
         * This is executed in DragDrop.init()
         *
         * @param {DragDrop} oDD the DragDrop object to register
         * @param {String} sGroup the name of the group this element belongs to
         */
        this.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.
         * @private
         */
        this.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.
         * @private
         */
        this._remove = function(oDD) {
            for (var g in oDD.groups) {
                if (g && this.ids[g][oDD.id]) {
                    delete this.ids[g][oDD.id];
                    //this.logger.log("NEW LEN " + this.ids.length, "warn");
                }
            }
            delete this.handleIds[oDD.id];
        };

        /**
         * Each DragDrop handle element must be registered.  This is done
         * automatically when executing DragDrop.setHandleElId()
         *
         * @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
         */
        this.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.
         *
         * @param {String} id the element id to check
         * @return {boolean} true if this element is a DragDrop item,
         * false otherwise
         */
        this.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.
         *
         * @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
         */
        this.getRelated = function(p_oDD, bTargetsOnly) {
            var oDDs = [];
            for (var i in p_oDD.groups) {
                for (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
         *
         * @param {DragDrop} the drag obj
         * @param {DragDrop) the target
         * @return {boolean} true if the target is a legal target for the
         * dd obj
         */
        this.isLegalTarget = function (oDD, oTargetDD) {
            var targets = this.getRelated(oDD, true);
            for (var i=0, len=targets.length;i<len;++i) {
                if (targets[i].id == oTargetDD.id) {
                    return true;
                }
            }

            return false;
        };

        /**
         * My goal is to be able to transparently determine if an object is
         * typeof DragDrop, and the exact subclass of DragDrop.  typeof
         * returns "object", oDD.constructor.toString() always returns
         * "DragDrop" and not the name of the subclass.  So for now it just
         * evaluates a well-known variable in DragDrop.
         *
         * @param {Object} the object to evaluate
         * @return {boolean} true if typeof oDD = DragDrop
         */
        this.isTypeOfDD = function (oDD) {
            return (oDD && oDD.__ygDragDrop);
        };

        /**
         * Utility function to determine if a given element has been
         * registered as a drag drop handle for the given Drag Drop object.
         *
         * @param {String} id the element id to check
         * @return {boolean} true if this element is a DragDrop handle, false
         * otherwise
         */
        this.isHandle = function(sDDId, sHandleId) {
            return ( this.handleIds[sDDId] &&
                            this.handleIds[sDDId][sHandleId] );
        };

        /**
         * Returns the DragDrop instance for a given id
         *
         * @param {String} id the id of the DragDrop object
         * @return {DragDrop} the drag drop object, null if it is not found
         */
        this.getDDById = function(id) {
            for (var i in this.ids) {
                if (this.ids[i][id]) {
                    return this.ids[i][id];
                }
            }
            return null;
        };

        /**
         * Fired after a registered DragDrop object gets the mousedown event.
         * Sets up the events required to track the object being dragged
         *
         * @param {Event} e the event
         * @param oDD the DragDrop object being dragged
         * @private
         */
        this.handleMouseDown = function(e, oDD) {

            this.currentTarget = YAHOO.util.Event.getTarget(e);

            this.logger.log("mousedown - adding event handlers");
            this.dragCurrent = oDD;

            var el = oDD.getEl();

            // track start position
            this.startX = YAHOO.util.Event.getPageX(e);
            this.startY = YAHOO.util.Event.getPageY(e);

            this.deltaX = this.startX - el.offsetLeft;
            this.deltaY = this.startY - el.offsetTop;

            this.dragThreshMet = false;

            this.clickTimeout = setTimeout(
                    function() {
                        var DDM = YAHOO.util.DDM;
                        DDM.startDrag(DDM.startX, DDM.startY);
                    },
                    this.clickTimeThresh );
        };

        /**
         * Fired when either the drag pixel threshol or the mousedown hold
         * time threshold has been met.
         *
         * @param x {int} the X position of the original mousedown
         * @param y {int} the Y position of the original mousedown
         */
        this.startDrag = function(x, y) {
            this.logger.log("firing drag start events");
            clearTimeout(this.clickTimeout);
            if (this.dragCurrent) {
                this.dragCurrent.b4StartDrag(x, y);
                this.dragCurrent.startDrag(x, y);
            }
            this.dragThreshMet = true;
        };

        /**
         * Internal function to handle the mouseup event.  Will be invoked
         * from the context of the document.
         *
         * @param {Event} e the event
         * @private
         */
        this.handleMouseUp = function(e) {

            if (! this.dragCurrent) {
                return;
            }

            clearTimeout(this.clickTimeout);

            if (this.dragThreshMet) {
                this.logger.log("mouseup detected - completing drag");
                this.fireEvents(e, true);
            } else {
                this.logger.log("drag threshold not met");
            }

            this.stopDrag(e);

            this.stopEvent(e);
        };

        /**
         * Utility to stop event propagation and event default, if these
         * features are turned on.
         *
         * @param {Event} e the event as returned by this.getEvent()
         */
        this.stopEvent = function(e) {
            if (this.stopPropagation) {
                YAHOO.util.Event.stopPropagation(e);
            }

            if (this.preventDefault) {
                YAHOO.util.Event.preventDefault(e);
            }
        };

        /**
         * Internal function to clean up event handlers after the drag
         * operation is complete
         *
         * @param {Event} e the event
         * @private
         */
        this.stopDrag = function(e) {
            // this.logger.log("mouseup - removing event handlers");

            // Fire the drag end event for the item that was dragged
            if (this.dragCurrent) {
                if (this.dragThreshMet) {
                    this.logger.log("firing endDrag events");
                    this.dragCurrent.b4EndDrag(e);
                    this.dragCurrent.endDrag(e);
                }

                this.logger.log("firing mouseUp event");
                this.dragCurrent.onMouseUp(e);
            }

            this.dragCurrent = null;
            this.dragOvers = {};
        };


        /**
         * Internal function to handle the mousemove event.  Will be invoked
         * from the context of the html element.
         *
         * @TODO figure out what we can do about mouse events lost when the
         * user drags objects beyond the window boundary.  Currently we can
         * detect this in internet explorer by verifying that the mouse is
         * down during the mousemove event.  Firefox doesn't give us the
         * button state on the mousemove event.
         *
         * @param {Event} e the event
         * @private
         */
        this.handleMouseMove = function(e) {
            //this.logger.log("handlemousemove");
            if (! this.dragCurrent) {
                // this.logger.log("no current drag obj");
                return true;
            }

            // var button = e.which || e.button;
            // this.logger.log("which: " + e.which + ", button: "+ e.button);

            // check for IE mouseup outside of page boundary
            if (YAHOO.util.Event.isIE && !e.button) {
                this.logger.log("button failure");
                this.stopEvent(e);
                return this.handleMouseUp(e);
            }

            if (!this.dragThreshMet) {
                var diffX = Math.abs(this.startX - YAHOO.util.Event.getPageX(e));
                var diffY = Math.abs(this.startY - YAHOO.util.Event.getPageY(e));
                // this.logger.log("diffX: " + diffX + "diffY: " + diffY);
                if (diffX > this.clickPixelThresh ||
                            diffY > this.clickPixelThresh) {
                    this.logger.log("pixel threshold met");
                    this.startDrag(this.startX, this.startY);
                }
            }

            if (this.dragThreshMet) {
                this.dragCurrent.b4Drag(e);
                this.dragCurrent.onDrag(e);
                this.fireEvents(e, false);
            }

            this.stopEvent(e);

            return true;
        };

        /**
         * Iterates over all of the DragDrop elements to find ones we are
         * hovering over or dropping on
         *
         * @param {Event} e the event
         * @param {boolean} isDrop is this a drop op or a mouseover op?
         * @private
         */
        this.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 (!dc || dc.isLocked()) {
                return;
            }

            var x = YAHOO.util.Event.getPageX(e);
            var y = YAHOO.util.Event.getPageY(e);
            var pt = new YAHOO.util.Point(x,y);

            // cache the previous dragOver array
            var oldOvers = [];

            var outEvts   = [];
            var overEvts  = [];
            var dropEvts  = [];
            var 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)) {
                    outEvts.push( ddo );
                }

                oldOvers[i] = true;
                delete this.dragOvers[i];
            }

            for (var sGroup in dc.groups) {
                // this.logger.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)) {
                            // look for drop interactions
                            if (isDrop) {
                                dropEvts.push( oDD );
                            // look for drag enter and drag over interactions
                            } else {

                                // initial drag over: dragEnter fires
                                if (!oldOvers[oDD.id]) {
                                    enterEvts.push( oDD );
                                // subsequent drag overs: dragOver fires
                                } else {
                                    overEvts.push( oDD );
                                }

                                this.dragOvers[oDD.id] = oDD;
                            }
                        }
                    }
                }
            }

            if (this.mode) {
                if (outEvts.length) {
                    this.logger.log(dc.id+" onDragOut: " + outEvts);
                    dc.b4DragOut(e, outEvts);
                    dc.onDragOut(e, outEvts);
                }

                if (enterEvts.length) {
                    this.logger.log(dc.id+" onDragEnter: " + enterEvts);
                    dc.onDragEnter(e, enterEvts);
                }

                if (overEvts.length) {
                    this.logger.log(dc.id+" onDragOver: " + overEvts);
                    dc.b4DragOver(e, overEvts);
                    dc.onDragOver(e, overEvts);
                }

                if (dropEvts.length) {
                    this.logger.log(dc.id+" onDragDrop: " + dropEvts);
                    dc.b4DragDrop(e, dropEvts);
                    dc.onDragDrop(e, dropEvts);
                }

            } else {
                // fire dragout events
                var len = 0;
                for (i=0, len=outEvts.length; i<len; ++i) {
                    this.logger.log(dc.id+" onDragOut: " + outEvts[i].id);
                    dc.b4DragOut(e, outEvts[i].id);
                    dc.onDragOut(e, outEvts[i].id);
                }

                // fire enter events
                for (i=0,len=enterEvts.length; i<len; ++i) {
                    this.logger.log(dc.id + " onDragEnter " + enterEvts[i].id);
                    // dc.b4DragEnter(e, oDD.id);
                    dc.onDragEnter(e, enterEvts[i].id);
                }

                // fire over events
                for (i=0,len=overEvts.length; i<len; ++i) {
                    this.logger.log(dc.id + " onDragOver " + overEvts[i].id);
                    dc.b4DragOver(e, overEvts[i].id);
                    dc.onDragOver(e, overEvts[i].id);
                }

                // fire drop events
                for (i=0, len=dropEvts.length; i<len; ++i) {
                    this.logger.log(dc.id + " dropped on " + dropEvts[i].id);
                    dc.b4DragDrop(e, dropEvts[i].id);
                    dc.onDragDrop(e, dropEvts[i].id);
                }

            }

        };

        /**
         * 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.
         *
         * @param  {DragDrop[]} dds The array of drag and drop objects
         * targeted
         * @return {DragDrop}       The best single match
         */
        this.getBestMatch = function(dds) {
            var winner = null;
            // Return null if the input is not what we expect
            //if (!dds || !dds.length || dds.length == 0) {
               // winner = null;
            // If there is only one item, it wins
            //} else if (dds.length == 1) {

            var len = dds.length;

            if (len == 1) {
                winner = dds[0];
            } else {
                // Loop through the targeted items
                for (var i=0; i<len; ++i) {
                    var dd = dds[i];
                    // If the cursor is over the object, it wins.  If the
                    // cursor is over multiple matches, the first one we come
                    // to wins.
                    if (dd.cursorIsOver) {
                        winner = dd;
                        break;
                    // Otherwise the object with the most overlap wins
                    } else {
                        if (!winner ||
                            winner.overlap.getArea() < dd.overlap.getArea()) {
                            winner = dd;
                        }
                    }
                }
            }

            return winner;
        };

        /**
         * Refreshes the cache of the top-left and bottom-right points of the
         * drag and drop objects in the specified group(s).  This is in the
         * format that is stored in the drag and drop instance, so typical
         * usage is:
         *
         * 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.
         *
         * @param {Object} groups an associative array of groups to refresh
         */
        this.refreshCache = function(groups) {
            this.logger.log("refreshing element location cache");
            for (var sGroup in groups) {
                if ("string" != typeof sGroup) {
                    continue;
                }
                for (var i in this.ids[sGroup]) {
                    var oDD = this.ids[sGroup][i];

                    if (this.isTypeOfDD(oDD)) {
                    // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
                        var loc = this.getLocation(oDD);
                        if (loc) {
                            this.locationCache[oDD.id] = loc;
                        } else {
                            delete this.locationCache[oDD.id];
                            this.logger.log("Could not get the loc for " + oDD.id,
                                    "warn");
                            // this will unregister the drag and drop object if
                            // the element is not in a usable state
                            // oDD.unreg();
                        }
                    }
                }
            }
        };

        /**
         * 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
         * @param {HTMLElement} el the element to check
         * @return {boolean} true if the element looks usable
         */
        this.verifyEl = function(el) {
            try {
                if (el) {
                    var parent = el.offsetParent;
                    if (parent) {
                        return true;
                    }
                }
            } catch(e) {
                this.logger.log("detected problem with an element");
            }

            return false;
        };

        /**
         * Returns a Region object containing the drag and drop element's position
         * and size, including the padding configured for it
         *
         * @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.
         */
        this.getLocation = function(oDD) {
            if (! this.isTypeOfDD(oDD)) {
                this.logger.log(oDD + " is not a DD obj");
                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) {
                this.logger.log("getXY failed");
                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
         *
         * @param {YAHOO.util.Point} pt The point to evaluate
         * @param {DragDrop} oTarget the DragDrop object we are inspecting
         * @return {boolean} true if the mouse is over the target
         * @private
         */
        this.isOverTarget = function(pt, oTarget, intersect) {
            // use cache if available
            var loc = this.locationCache[oTarget.id];
            if (!loc || !this.useCache) {
                this.logger.log("cache not populated");
                loc = this.getLocation(oTarget);
                this.locationCache[oTarget.id] = loc;

                this.logger.log("cache: " + loc);
            }

            if (!loc) {
                this.logger.log("could not get the location of the element");
                return false;
            }

            //this.logger.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 also done. Otherwise we need to evaluate the
            // location of the target as related to the actual location of the
            // dragged element.
            var dc = this.dragCurrent;
            if (!dc || !dc.getTargetCoord ||
                    (!intersect && !dc.constrainX && !dc.constrainY)) {
                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.
            var pos = dc.getTargetCoord(pt.x, pt.y);

            var el = dc.getDragEl();
            var 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;
            }
        };

        /**
         * @private
         */
        this._onUnload = function(e, me) {
            this.unregAll();
        };

        /**
         * Cleans up the drag and drop events and objects.
         * @private
         */
        this.unregAll = function() {
            this.logger.log("unregister all");

            if (this.dragCurrent) {
                this.stopDrag();
                this.dragCurrent = null;
            }

            this._execOnAll("unreg", []);

            for (i in this.elementCache) {
                delete this.elementCache[i];
            }

            this.elementCache = {};
            this.ids = {};
        };

        /**
         * A cache of DOM elements
         * @private
         */
        this.elementCache = {};

        /**
         * Get the wrapper for the DOM element specified
         *
         * @param {String} id the id of the elment to get
         * @return {YAHOO.util.DDM.ElementWrapper} the wrapped element
         * @private
         * @deprecated
         */
        this.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
         *
         * @param {String} id the id of the elment to get
         * @return {Object} The element
         * @deprecated
         */
        this.getElement = function(id) {
            return YAHOO.util.Dom.get(id);
        };

        /**
         * Returns the style property for the DOM element (i.e.,
         * document.getElById(id).style)
         *
         * @param {String} id the id of the elment to get
         * @return {Object} The style property of the element
         * @deprecated
         */
        this.getCss = function(id) {
            var el = YAHOO.util.Dom.get(id);
            return (el) ? el.style : null;
        };

        /**
         * Inner class for cached elements
         * @private
         * @deprecated
         */
        this.ElementWrapper = function(el) {
                /**
                 * @private
                 */
                this.el = el || null;
                /**
                 * @private
                 */
                this.id = this.el && el.id;
                /**
                 * @private
                 */
                this.css = this.el && el.style;
            };

        /**
         * Returns the X position of an html element
         * @param el the element for which to get the position
         * @return {int} the X coordinate
         * @deprecated
         */
        this.getPosX = function(el) {
            return YAHOO.util.Dom.getX(el);
        };

        /**
         * Returns the Y position of an html element
         * @param el the element for which to get the position
         * @return {int} the Y coordinate
         * @deprecated
         */
        this.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
         *
         * @param n1 the first node to swap
         * @param n2 the other node to swap
         */
        this.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);
                }
            }
        };

        /**
         * @private
         */
        this.getScroll = function () {
            var t, l;
            if (document.documentElement && document.documentElement.scrollTop) {
                t = document.documentElement.scrollTop;
                l = document.documentElement.scrollLeft;
            } else if (document.body) {
                t = document.body.scrollTop;
                l = document.body.scrollLeft;
            }
            return { top: t, left: l };
        };

        /**
         * Returns the specified element style property
         * @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
         */
        this.getStyle = function(el, styleProp) {
            return YAHOO.util.Dom.getStyle(el, styleProp);
        };

        /**
         * Gets the scrollTop
         * @return {int} the document's scrollTop
         */
        this.getScrollTop = function () { return this.getScroll().top; };

        /**
         * Gets the scrollLeft
         * @return {int} the document's scrollTop
         */
        this.getScrollLeft = function () { return this.getScroll().left; };

        /**
         * Sets the x/y position of an element to the location of the
         * target element.
         * @param {HTMLElement} moveEl      The element to move
         * @param {HTMLElement} targetEl    The position reference element
         */
        this.moveToEl = function (moveEl, targetEl) {
            var aCoord = YAHOO.util.Dom.getXY(targetEl);
            this.logger.log("moveToEl: " + aCoord);
            YAHOO.util.Dom.setXY(moveEl, aCoord);
        };

        /**
         * Gets the client height
         * @return {int} client height in px
         * @deprecated
         */
        this.getClientHeight = function() {
            return YAHOO.util.Dom.getClientHeight();
        };

        /**
         * Gets the client width
         * @return {int} client width in px
         * @deprecated
         */
        this.getClientWidth = function() {
            return YAHOO.util.Dom.getClientWidth();
        };

        /**
         * numeric array sort function
         */
        this.numericSort = function(a, b) { return (a - b); };

        /**
         * @private
         */
        this._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.
         * @private
         */
        this._addListeners = function() {
            var DDM = YAHOO.util.DDM;
            if ( YAHOO.util.Event && document ) {
                DDM._onLoad();
            } else {
                if (DDM._timeoutCount > 2000) {
                    DDM.logger.log("DragDrop requires the Event Utility");
                } 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.
         * @param node the html element to inspect
         */
        this.handleWasClicked = function(node, id) {
            if (this.isHandle(id, node.id)) {
                this.logger.log("clicked node is a handle");
                return true;
            } else {
                // check to see if this is a text node child of the one we want
                var p = node.parentNode;
                // this.logger.log("p: " + p);

                while (p) {
                    if (this.isHandle(id, p.id)) {
                        return true;
                    } else {
                        this.logger.log(p.id + " is not a handle");
                        p = p.parentNode;
                    }
                }
            }

            return false;
        };

    } ();

    // shorter alias, save a few bytes
    YAHOO.util.DDM = YAHOO.util.DragDropMgr;
    YAHOO.util.DDM._addListeners();

}

//YAHOO.util.DragDropMgr.enableWindow = function(win) {
    //var EU = YAHOO.util.Event;
    //EU.on(win.document, "mouseup",   this.handleMouseUp,   this, true);
    //EU.on(win.document, "mousemove", this.handleMouseMove, this, true);
//};

/**
 * A DragDrop implementation where the linked element follows the
 * mouse cursor during a drag.
 *
 * @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.util.DD.prototype = new YAHOO.util.DragDrop();
YAHOO.extend(YAHOO.util.DD, YAHOO.util.DragDrop);

/**
 * When set to true, the utility automatically tries to scroll the browser
 * window wehn a drag and drop element is dragged near the viewport boundary.
 * Defaults to true.
 *
 * @type boolean
 */
YAHOO.util.DD.prototype.scroll = true;

/**
 * Sets the pointer offset to the distance between the linked element's top
 * left corner and the location the element was clicked
 *
 * @param {int} iPageX the X coordinate of the click
 * @param {int} iPageY the Y coordinate of the click
 */
YAHOO.util.DD.prototype.autoOffset = function(iPageX, iPageY) {
    // var el = this.getEl();
    // var aCoord = YAHOO.util.Dom.getXY(el);
    // var x = iPageX - aCoord[0];
    // var y = iPageY - aCoord[1];
    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)
 *
 * @param {int} iDeltaX the distance from the left
 * @param {int} iDeltaY the distance from the top
 */
YAHOO.util.DD.prototype.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.
 *
 * @param {int} iPageX the X coordinate of the mousedown or drag event
 * @param {int} iPageY the Y coordinate of the mousedown or drag event
 */

YAHOO.util.DD.prototype.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();

    // if (!this.cssVerified) {
        // var pos = el.style.position;
        // this.logger.log("drag element position: " + pos);
    // }

    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.
 *
 * @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
 */
YAHOO.util.DD.prototype.alignElWithMouse = function(el, iPageX, iPageY) {
    var oCoord = this.getTargetCoord(iPageX, iPageY);
    // this.logger.log("****alignElWithMouse : " + el.id + ", " + aCoord + ", " + el.style.display);

    // this.deltaSetXY = null;
    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 ];

        // this.logger.log("css X: " + YAHOO.util.Dom.getStyle(el, "left"));
        // this.logger.log("css Y: " + YAHOO.util.Dom.getStyle(el, "top"));
        // this.logger.log("deltaSetXY: " + this.deltaSetXY);
    } 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);

    this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
};

/**
 * 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.
 */
YAHOO.util.DD.prototype.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.
 *
 * @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
 */
YAHOO.util.DD.prototype.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);
        }
    }
};

/**
 * 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.
 *
 * @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
 */
YAHOO.util.DD.prototype.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};
};

YAHOO.util.DD.prototype.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.
 */
YAHOO.util.DD.prototype.b4MouseDown = function(e) {
    // 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.
 */
YAHOO.util.DD.prototype.b4Drag = function(e) {
	
	var oCoord = this.getTargetCoord(YAHOO.util.Event.getPageX(e),  YAHOO.util.Event.getPageY(e));
//	var clientH = this.DDM.getClientHeight();
//  var clientW = this.DDM.getClientWidth();
    
//  var clientH = window.innerHeight;
//  var clientW = window.innerWeight;
//  var clientH = document.documentElement.clientHeight;
//  var clientW = document.documentElement.clientWidth;
    
    var scrollH = document.body.scrollHeight;
    var scrollW = document.body.scrollWidth;
//	alert(clientH + " : " + clientH1 + " : " + oCoord.y);
//	alert(clientW + " : " + clientW1 + " : " + oCoord.x);
//	alert(oCoord.x +  ' : ' + oCoord.y);
	if(!(((oCoord.x < 0) || (oCoord.y < 0) || oCoord.x > (scrollW-486)) || (oCoord.y > (scrollH-316)))){
//	alert('a : ' + oCoord.y + ' : ' + clientH1 );
    	    this.setDragElPos(YAHOO.util.Event.getPageX(e),
                        YAHOO.util.Event.getPageY(e));
    }/*else{
    	alert('w : ' + oCoord.x + ' : ' + clientW1 );
    	alert('h : ' + oCoord.y + ' : ' + clientH1 );
    }*/
};


YAHOO.util.DD.prototype.toString = function() {
    return ("DD " + this.id);
};

///////////////////////////////////////////////////////////////////////////////
// Debugging ygDragDrop events that can be overridden
///////////////////////////////////////////////////////////////////////////////
/*
YAHOO.util.DD.prototype.startDrag = function(x, y) {
    this.logger.log(this.id.toString()  + " startDrag");
};

YAHOO.util.DD.prototype.onDrag = function(e) {
    this.logger.log(this.id.toString() + " onDrag");
};

YAHOO.util.DD.prototype.onDragEnter = function(e, id) {
    this.logger.log(this.id.toString() + " onDragEnter: " + id);
};

YAHOO.util.DD.prototype.onDragOver = function(e, id) {
    this.logger.log(this.id.toString() + " onDragOver: " + id);
};

YAHOO.util.DD.prototype.onDragOut = function(e, id) {
    this.logger.log(this.id.toString() + " onDragOut: " + id);
};

YAHOO.util.DD.prototype.onDragDrop = function(e, id) {
    this.logger.log(this.id.toString() + " onDragDrop: " + id);
};

YAHOO.util.DD.prototype.endDrag = function(e) {
    this.logger.log(this.id.toString() + " endDrag");
};
*/

/**
 * 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.
 *
 * @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();
    }
};

YAHOO.extend(YAHOO.util.DDProxy, YAHOO.util.DD);

/**
 * The default drag frame div id
 * @type String
 */
YAHOO.util.DDProxy.dragElId = "ygddfdiv";

/**
 * 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.
 *
 * @type boolean
 */
YAHOO.util.DDProxy.prototype.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.
 *
 * @type boolean
 */
YAHOO.util.DDProxy.prototype.centerFrame = false;

/**
 * Create the drag frame if needed
 */
YAHOO.util.DDProxy.prototype.createFrame = function() {
    var self = this;
    var body = document.body;

    if (!body || !body.firstChild) {
        setTimeout( function() { self.createFrame(); }, 50 );
        return;
    }

    var div = this.getDragEl();

    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;

        // 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
 */
YAHOO.util.DDProxy.prototype.initFrame = function() {
    // YAHOO.util.DDProxy.createFrame();
    // this.setDragElId(YAHOO.util.DDProxy.dragElId);

    this.createFrame();

};

YAHOO.util.DDProxy.prototype.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);

    //this.logger.log("dragElId: " + this.dragElId);
};

/**
 * Resizes the drag frame to the dimensions of the clicked object, positions
 * it over the object, and finally displays it
 *
 * @param {int} iPageX X click position
 * @param {int} iPageY Y click position
 * @private
 */
YAHOO.util.DDProxy.prototype.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");
};

YAHOO.util.DDProxy.prototype._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
YAHOO.util.DDProxy.prototype.b4MouseDown = function(e) {
    var x = YAHOO.util.Event.getPageX(e);
    var y = YAHOO.util.Event.getPageY(e);
    this.autoOffset(x, y);
    this.setDragElPos(x, y);
};

// overrides YAHOO.util.DragDrop
YAHOO.util.DDProxy.prototype.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
YAHOO.util.DDProxy.prototype.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.
YAHOO.util.DDProxy.prototype.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", "");
};

YAHOO.util.DDProxy.prototype.toString = function() {
    return ("DDProxy " + this.id);
};

/**
 * 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.
 *
 * @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);

YAHOO.util.DDTarget.prototype.toString = function() {
    return ("DDTarget " + this.id);
};

//dragdrop-debug

/* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */

/**
 * @class a DragDrop implementation that moves the object as it is being dragged,
 * and keeps the object being dragged on top.  This is a subclass of DD rather
 * than DragDrop, and inherits the implementation of most of the event listeners
 * from that class.
 *
 * @extends YAHOO.util.DD
 * @constructor
 * @param {String} id the id of the linked element
 * @param {String} sGroup the group of related DragDrop items
 */
YAHOO.example.DDOnTop = function(id, sGroup, config) {
    if (id) {
        this.init(id, sGroup, config);
        this.logger = this.logger || YAHOO;
    }
};

// YAHOO.example.DDOnTop.prototype = new YAHOO.util.DD();
YAHOO.extend(YAHOO.example.DDOnTop, YAHOO.util.DD);

/**
 * The inital z-index of the element, stored so we can restore it later
 *
 * @type int
 */
YAHOO.example.DDOnTop.prototype.origZ = 0;

YAHOO.example.DDOnTop.prototype.startDrag = function(x, y) {
    this.logger.log(this.id + " startDrag");

    var style = this.getEl().style;

    // store the original z-index
    this.origZ = style.zIndex;

    // The z-index needs to be set very high so the element will indeed be on top
    style.zIndex = 999;
};

YAHOO.example.DDOnTop.prototype.endDrag = function(e) {
    this.logger.log(this.id + " endDrag");

    // restore the original z-index
    this.getEl().style.zIndex = this.origZ;
};
//DD
YAHOO.example.DDApp = function() {
    var dd, logger;
    return {
        init: function() {
            dd = new YAHOO.example.DDOnTop("bookmark_handle");
            dd.setHandleElId("mini_bookmark_handle");           
        }
    };
} ();
    
//YAHOO.util.Event.addListener(window, "load", YAHOO.example.DDApp.init);
YAHOO.example.DDApp.init();