﻿/*extern YAHOO, window, Image */
/*global PB */
/*members Event, MouseOvers, add, addListener, applied, apply, 
    doMouseOver, el, elements, getTarget, height, hoverSrc, length, 
    nodeName, preloads, push, src, toLowerCase, type, util, waiting, width
*/
PB = {
	MouseOvers: {
		preloads:    [ ],
		elements:    [ ],
		waiting:     false,
		/** Add a mouseover effect
		  * @param  {string | img}  el
		  * @param  {string}        hoverURL
		  */
		add: function (el, hoverURL) {
			this.elements.push({ el: el, src: null, hoverSrc: hoverURL, applied: false });
		},
		/** Applies all loaded mouse over effects that have not already been applied.
		  * Performs pre-loading of hover URLs that match elements that are found in
		  * the document.
		  * It is safe to call this whenever--any real work will be defered until the
		  * DOM is available.
		  */
		apply: function () {
			if (this.waiting === true) {
				return;
			}

			this.waiting = true;
			YAHOO.util.Event.addListener(window, 'load', function () {
				this.waiting = false;
				var els = this.elements;
				var y = this.preloads.length;
				var x, z, el, evs = [];
				for (x = 0; x < els.length; x++) {

					if (els[x].applied === true) {
						continue;
					}

					el = document.getElementById(els[x].el);
					if (el === null || el.nodeName.toLowerCase() !== 'img') {
						continue;
					}

					z = els.length;
					while (z--) {
						if (els[z].el === el && els[z].applied === true) {
							els[x].applied = true;
							continue;
						}
					}

					els[x].el  = el;
					els[x].src = el.src;

					this.preloads[y] = new Image(el.width, el.height);
					this.preloads[y].src = els[x].hoverSrc;
					els[x].hoverSrc = this.preloads[y].src;
					els[x].applied = true;
					evs.push(el);
				}

				if (evs.length) {
					YAHOO.util.Event.addListener(evs, 'mouseover', this.doMouseOver, this, true);
					YAHOO.util.Event.addListener(evs, 'mouseout' , this.doMouseOver, this, true);
				}
			}, this, true);
		},
		doMouseOver: function (e) {
			var el   = YAHOO.util.Event.getTarget(e);
			var type = e.type;
			var els  = this.elements;
			var mo   = null;
			var x    = els.length;

			while (x--) {
				if (els[x].el === el) {
					break;
				}
			}
			if (x === -1) {
				return;
			}

			mo = els[x];
			el.src = (type === 'mouseover') ? mo.hoverSrc : mo.src;

		}
	}
};
