// These utils require Yahoo UI Library v2.5.0 (yahoo-dom-event-dragdrop)

function $(id) {return document.getElementById(id)}

var mUtils = {};


// Static methods

mUtils.ui = {

	watermark : function(el, strMessage, color)
	{
		if(!color) color = "#d5d5d5";
		YAHOO.util.Event.removeListener(el, "blur");
		YAHOO.util.Event.removeListener(el, "focus");
		YAHOO.util.Event.on(el, "blur", function() {
			mUtils.ui.watermark(el, strMessage, color);
		});
		YAHOO.util.Event.on(el, "focus", function() {
			if (el.value == strMessage) {
				el.value = "";
				el.style.color = "#000";
			}	
		});
		if (el.value == "" || el.value == strMessage) {
			el.style.color = color;
			el.value = strMessage;
		}
	},
	
	isIE : function()
	{
		if (navigator.userAgent.indexOf("MSIE") != -1) return true;
		else return false;
	},
	
	isIE6 : function()
	{
		if (navigator.userAgent.indexOf('MSIE 6.') != -1) return true;
		else return false;
	},
	
	highlighter : function(elFormContainer, color, focus)
	{
		if (elFormContainer == null) return;
		var textInputs = this.getTextInputs(elFormContainer);
		if (textInputs.length != 0) {
			for (var i = 0; i < textInputs.length; i++)
			{
				YAHOO.util.Event.on(textInputs[i], "focus" ,function() {
					this.style.backgroundColor = color;
				});
				YAHOO.util.Event.on(textInputs[i], "blur" ,function() {
					this.style.backgroundColor = "";
				});
			}
		}
		if (focus) textInputs[0].focus();
	},
	
	getTextInputs : function(elFormContainer)
	{
		var textInputs = new Array();
		var inputs = elFormContainer.getElementsByTagName("input");
		var textareas = elFormContainer.getElementsByTagName("textarea");
		for (var i = 0; i < inputs.length; i++)
		{
			if ((inputs[i].type == "text" || inputs[i].type == "file" || inputs[i].type == "password") && !(inputs[i].disabled)) {
				textInputs.push(inputs[i]);
			}
		}
		for (i = 0; i < textareas.length; i++) {
			textInputs.push(textareas[i]);
		}
		return textInputs;
	},
	
	hovermenu : function(elNavList)
	{
		var navItems = elNavList.getElementsByTagName("li");
		for (var i = 0; i < navItems.length; i++)
		{
			YAHOO.util.Event.on(navItems[i], "mouseover", function() {
				this.className = this.className + " hover"
			});
			YAHOO.util.Event.on(navItems[i], "mouseout", function() {
				this.className = this.className.replace(/hover/,"")
			});
		}
	}
}


//Hoverlist

mUtils.hoverlist = function(elList) {
	this.list = elList;
}

mUtils.hoverlist.prototype = {

	init : function()
	{
		this.listItems = YAHOO.util.Dom.getElementsByClassName("hoverItem", "li", this.list);
		this.listContent = this.list.getElementsByTagName("div");
		
		for(var i = 0; i < this.listItems.length; i++)
		{
			YAHOO.util.Event.on(this.listItems[i], "mouseover", this.reveal, new Array(this, i));
			
			if (mUtils.ui.isIE())
			{
				YAHOO.util.Event.on(this.listItems[i], "mouseleave", this.hide, new Array(this, i));
			}
			else
			{
				YAHOO.util.Event.on(this.listItems[i], "mouseout", this.hide, new Array(this, i));
			}
		}
	},

	reveal : function(ev, args)
	{
		var obj = args[0];
		var i = args[1];

		var currentDiv = obj.listContent[i];

		YAHOO.util.Event.on(this, "mousemove", function(ev) {

			var mousePos = obj.getMousePosition(ev);
			var mouseX = mousePos[0];
			var mouseY = mousePos[1];

			var vWidth = YAHOO.util.Dom.getViewportWidth();
			var vHeight = YAHOO.util.Dom.getViewportHeight();

			//Make sure the popup doesn't slide off
			//right edge by fixing its position
			if (mouseX > (vWidth - 396)) currentDiv.style.left = (vWidth - 376) + "px";
			else currentDiv.style.left = mouseX + 20 + "px";

			//...or off bottom edge, this time by
			//moving it above the mouse for last two items
			if ((obj.listItems.length > 4) && (i > (obj.listItems.length - 3)))
				currentDiv.style.bottom = (vHeight - mouseY) + 5 + "px";
			else currentDiv.style.top = mouseY + 20 + "px";

			obj.listItems[i].className = "contentVisible";

		});
	},

	hide : function(ev, args)
	{
		var obj = args[0];
		var i = args[1];
		
		obj.listItems[i].className = "";
		
		YAHOO.util.Event.removeListener(this, "mousemove");
	},
	
	getMousePosition : function(ev)
	{
		var mouseX = ev.pageX;
		var mouseY = ev.pageY;
		
		if (mUtils.ui.isIE())
		{
			mouseX = ev.clientX + YAHOO.util.Dom.getDocumentScrollLeft();
			mouseY = ev.clientY + YAHOO.util.Dom.getDocumentScrollTop();
		}
		return new Array(mouseX, mouseY);
	}
}


// Overlay (requires Overlay.css)

mUtils.overlay = function(overlayUrl) {
	this.overlayUrl = overlayUrl;
}

mUtils.overlay.prototype = {

	init : function()
	{
		this.mask = document.createElement("div");
		this.mask.className = "overlay-mask";
		
		if (document.body.offsetHeight >= YAHOO.util.Dom.getViewportHeight())
		{
    		this.mask.style.height = document.body.offsetHeight + 20 + "px";
		}
		else
		{
			this.mask.style.height = YAHOO.util.Dom.getViewportHeight() + "px";
		}
		
		this.frame = document.createElement("iframe");
		this.frame.className = "overlay-frame";
		this.frame.frameBorder = "0";
		this.frame.src = this.overlayUrl;
		
		if (mUtils.ui.isIE6())
		{
			this.frame.className = "overlay-frame overlay-frame-ie";
			this.frame.style.top = YAHOO.util.Dom.getDocumentScrollTop() + 50 + "px";
		}
		
		document.body.appendChild(this.mask);
		document.body.appendChild(this.frame);
	},
	
	destroy : function()
	{
		document.body.removeChild(this.frame);
		document.body.removeChild(this.mask);
	}
}

//Draggable List

var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var DDM = YAHOO.util.DragDropMgr;

mUtils.draglist = function(elList) {
	this.list = elList;
	this.listItems = this.list.getElementsByTagName("li");
}

mUtils.draglist.prototype = {

    init: function()
    {
		new YAHOO.util.DDTarget(this.list);
		
		var dragHandles = YAHOO.util.Dom.getElementsByClassName("dragHandle", "img", this.list);
		
		for (i=0; i<this.listItems.length; i++)
		{
			var dragItem = new DDList(this.listItems[i]);
			dragItem.setHandleElId(dragHandles[i]);
		}
    }
}

var DDList = function(id) {

    DDList.superclass.constructor.call(this, id);

    var el = this.getDragEl();
    this.goingUp = false;
    this.lastY = 0;
};

YAHOO.lang.extend(DDList, YAHOO.util.DDProxy, {

    startDrag: function(x, y) {
        // make the proxy look like the source element
        var dragEl = this.getDragEl();
        var clickEl = this.getEl();
        Dom.setStyle(clickEl, "visibility", "hidden");

        dragEl.innerHTML = clickEl.innerHTML;
		dragEl.className = clickEl.className;
		dragEl.style.opacity = ".5";
		dragEl.style.width = clickEl.style.width;
		dragEl.style.height = clickEl.style.height;
		dragEl.style.borderWidth = clickEl.style.borderWidth;
    },

    endDrag: function(e) {

        var srcEl = this.getEl();
        var proxy = this.getDragEl();

        // Show the proxy element and animate it to the src element's location
        Dom.setStyle(proxy, "visibility", "");
        var a = new YAHOO.util.Motion( 
            proxy, { 
                points: { 
                    to: Dom.getXY(srcEl)
                }
            }, 
            0.2, 
            YAHOO.util.Easing.easeOut 
        )
        var proxyid = proxy.id;
        var thisid = this.id;

        // Hide the proxy and show the source element when finished with the animation
        a.onComplete.subscribe(function() {
                Dom.setStyle(proxyid, "visibility", "hidden");
                Dom.setStyle(thisid, "visibility", "");
            });
        a.animate();
    },

    onDragDrop: function(e, id) {

        // If there is one drop interaction, the li was dropped either on the list,
        // or it was dropped on the current location of the source element.
        if (DDM.interactionInfo.drop.length === 1) {

            // The position of the cursor at the time of the drop (YAHOO.util.Point)
            var pt = DDM.interactionInfo.point; 

            // The region occupied by the source element at the time of the drop
            var region = DDM.interactionInfo.sourceRegion; 

            // Check to see if we are over the source element's location.  We will
            // append to the bottom of the list once we are sure it was a drop in
            // the negative space (the area of the list without any list items)
            if (!region.intersect(pt)) {
                var destEl = Dom.get(id);
                var destDD = DDM.getDDById(id);
                if (destEl.tagName != "UL") {
					destEl = Dom.getAncestorByTagName(destEl, "ul");
                }
                destEl.appendChild(this.getEl());
                destDD.isEmpty = false;
                DDM.refreshCache();
            }

        }
    },

    onDrag: function(e) {

        // Keep track of the direction of the drag for use during onDragOver
        var y = Event.getPageY(e);

        if (y < this.lastY) {
            this.goingUp = true;
        } else if (y > this.lastY) {
            this.goingUp = false;
        }

        this.lastY = y;
    },

    onDragOver: function(e, id) {
    
        var srcEl = this.getEl();
        var destEl = Dom.get(id);

        // We are only concerned with list items, we ignore the dragover
        // notifications for the list.
        if (destEl.nodeName.toLowerCase() == "li"
			
			//Use this this condition if no swapping between multiple lists
			&& srcEl.parentNode == destEl.parentNode)
		{
            var orig_p = srcEl.parentNode;
            var p = destEl.parentNode;

            if (this.goingUp) {
                p.insertBefore(srcEl, destEl); // insert above
            } else {
                p.insertBefore(srcEl, destEl.nextSibling); // insert below
            }
            DDM.refreshCache();
        }
    }
});

//Lightbox

mUtils.lightbox = function(elContainer, getTagsByClass) {
	if (getTagsByClass)
	{
		this.items = YAHOO.util.Dom.getElementsByClassName("galleryItem", "a", elContainer);
	}
	else this.items = elContainer.getElementsByTagName("a");
}

mUtils.lightbox.prototype = {

	init : function()
	{
		for (i=0; i<this.items.length; i++)
		{
			YAHOO.util.Event.on(this.items[i], "click", this.initImage, new Array(this, i));
		}
	},
	
	initImage : function(ev, args)
	{
		this.blur();
		YAHOO.util.Event.preventDefault(ev);
		
		var obj = args[0];
		obj.createLightbox();
		obj.loadImage(args[1], false);
	},
	
	loadImage : function(intItemNumber, imageLoaded)
	{
		if(imageLoaded)
		{
			this.clearImage(intItemNumber, this);
			return;
		}
		
		this.infobar.style.display = "none";
		YAHOO.util.Event.on(this.image, "load", this.animStart, this, true);
		this.image.src = this.items[intItemNumber].href;

		this.viewer.className = "gallery-viewer gallery-loading";
		this.currentItem = intItemNumber;
		
		var nextItemNumber = this.currentItem + 1;
		if (nextItemNumber == this.items.length) nextItemNumber = 0;
		this.imagePreload.src = this.items[nextItemNumber].href;
	},
	
	clearImage : function(intItemNumber, obj)
	{
		var animImageFadeOut = new YAHOO.util.Anim(this.image, {opacity:{to:0}}, 0.4, YAHOO.util.Easing.easeOut);
		animImageFadeOut.onComplete.subscribe(function() {
			obj.handleClearedImage(intItemNumber);
		});
		
		this.order.innerHTML = "";
		this.caption.innerHTML = "&nbsp;";
		var infobarSlideOut = new YAHOO.util.Anim(this.infobar, {top:{to:this.totalImageHeight - 60}}, 0.5, YAHOO.util.Easing.easeOut);
		
		infobarSlideOut.animate();
		animImageFadeOut.animate();
	},

	handleClearedImage : function(intItemNumber)
	{
		this.loadImage(intItemNumber, false);
	},

	animStart : function()
	{
		this.viewer.className = "gallery-viewer";

		this.totalImageWidth = this.image.width
				+ parseInt(YAHOO.util.Dom.getStyle(this.image, "border-left-width"))
				+ parseInt(YAHOO.util.Dom.getStyle(this.image, "border-right-width"));
		
		this.totalImageHeight = this.image.height
				+ parseInt(YAHOO.util.Dom.getStyle(this.image, "border-top-width"))
				+ parseInt(YAHOO.util.Dom.getStyle(this.image, "border-bottom-width"));
						
		var animWidth = new YAHOO.util.Anim(this.viewer, {width:{to: this.totalImageWidth}}, 0.7, YAHOO.util.Easing.easeBothStrong);
		var animHeight = new YAHOO.util.Anim(this.viewer, {height:{to: this.totalImageHeight}}, 0.7, YAHOO.util.Easing.easeBothStrong);
		animHeight.onComplete.subscribe(this.handleContainerReady, this, true);

		animWidth.animate();
		animHeight.animate();
	},

	handleContainerReady : function()
	{
		YAHOO.util.Event.removeListener(this.image, "load");
		
		var animImageFadeIn = new YAHOO.util.Anim(this.image, {opacity:{to:1}}, 0.4, YAHOO.util.Easing.easeOut);
		animImageFadeIn.onComplete.subscribe(this.showInfoBar, this, true);
		animImageFadeIn.animate();
	},

	showInfoBar : function()
	{	
		this.order.innerHTML = "Image " + (this.currentItem + 1) + " of " + this.items.length;
		
		if (this.items[this.currentItem].title) {
			this.caption.innerHTML = this.items[this.currentItem].title;
		} else {
			this.caption.innerHTML = "&nbsp;";
		}
		
		this.infobar.style.display = "block";
		this.infobar.style.top = this.totalImageHeight - 60 + "px";
		this.infobar.style.width = this.totalImageWidth
				- parseInt(YAHOO.util.Dom.getStyle(this.infobar, "padding-left"))
				- parseInt(YAHOO.util.Dom.getStyle(this.infobar, "padding-right"))
				+ "px";
		
		var infobarSlideIn = new YAHOO.util.Anim(this.infobar, {top:{to:this.totalImageHeight}}, 0.5, YAHOO.util.Easing.easeOut);
		infobarSlideIn.animate();
	},
	
	loadPrevImage : function()
	{
		var newItemNumber = this.currentItem - 1;
		if (newItemNumber == -1) newItemNumber = this.items.length - 1;
		this.loadImage(newItemNumber, true);
	},

	loadNextImage : function()
	{
		var newItemNumber = this.currentItem + 1;
		if (newItemNumber == this.items.length) newItemNumber = 0;
		this.loadImage(newItemNumber, true);
	},

	createLightbox : function()
	{
		this.mask = document.createElement("div");
		this.mask.className = "gallery-mask";
		
		if (document.body.offsetHeight >= YAHOO.util.Dom.getViewportHeight()) {
    		this.mask.style.height = document.body.offsetHeight + 20 + "px";
		} else {
			this.mask.style.height = YAHOO.util.Dom.getViewportHeight() + "px";
		}

		this.order = document.createElement("span");
		this.caption = document.createElement("strong");
		this.caption.className = "gallery-caption";
		
		this.infobar = document.createElement("div");
		this.infobar.className = "gallery-infobar";

		this.imagePreload = document.createElement("img");
		this.imagePreload.className = "gallery-image-preload";
		
		this.image = document.createElement("img");
		this.image.className = "gallery-image";
		
		this.btnClose = document.createElement("button");
		this.btnClose.innerHTML = "Close Lightbox";
		
		this.btnCloseWrapper = document.createElement("div");
		this.btnCloseWrapper.className = "gallery-close-wrapper";
		this.btnCloseWrapper.style.top = YAHOO.util.Dom.getDocumentScrollTop() + 20 + "px";
		this.btnCloseWrapper.appendChild(this.btnClose);
		
		this.viewer = document.createElement("div");
		this.viewer.className = "gallery-viewer";
		this.viewer.appendChild(this.imagePreload);
		this.viewer.appendChild(this.image);
		this.viewer.appendChild(this.infobar);
		
		this.spaceBar = new YAHOO.util.KeyListener(document, {keys:32}, {fn:this.destroyLightbox, scope:this, correctScope:true});
		this.spaceBar.enable();
		
		if (this.items.length > 1)
		{
			this.infobar.appendChild(this.order);
			
			this.btnPrev = document.createElement("a");
			this.btnPrev.className = "gallery-prev";
			YAHOO.util.Event.on(this.btnPrev, "click", this.loadPrevImage, this, true);
			
			this.btnNext = document.createElement("a");
			this.btnNext.className = "gallery-next";
			YAHOO.util.Event.on(this.btnNext, "click", this.loadNextImage, this, true);
			
			this.viewer.appendChild(this.btnPrev);
			this.viewer.appendChild(this.btnNext);
			
			this.spaceBar.disable();
			this.spaceBar = new YAHOO.util.KeyListener(document, {keys:32}, {fn:this.loadNextImage, scope:this, correctScope:true});
			this.spaceBar.enable();
			
			this.fwArrow = new YAHOO.util.KeyListener(document, {keys:39}, {fn:this.loadNextImage, scope:this, correctScope:true});
			this.fwArrow.enable();
			
			this.bkArrow = new YAHOO.util.KeyListener(document, {keys:37}, {fn:this.loadPrevImage, scope:this, correctScope:true});
			this.bkArrow.enable();
		}
		
		this.infobar.appendChild(this.caption);
		this.overlay = document.createElement("div");
		this.overlay.className = "gallery-overlay";
		this.overlay.appendChild(this.viewer);
		this.overlay.style.top = YAHOO.util.Dom.getDocumentScrollTop() + 60 + "px";

		YAHOO.util.Event.on(this.btnClose, "click", this.destroyLightbox, this, true);
		YAHOO.util.Event.on(this.mask, "click", this.destroyLightbox, this, true);
		YAHOO.util.Event.on(this.overlay, "click", this.handleOverlayClick, this, true);
		
		this.escKeyClose = new YAHOO.util.KeyListener(document, {keys:27}, {fn:this.destroyLightbox, scope:this, correctScope:true});
		this.escKeyClose.enable();

		document.body.appendChild(this.mask);
		document.body.appendChild(this.overlay);
		document.body.appendChild(this.btnCloseWrapper);
		return;
	},

	handleOverlayClick : function(ev)
	{
		var origin = YAHOO.util.Event.getTarget(ev, false);
		if (origin == this.overlay)
		{
			this.destroyLightbox();
		}
	},

	destroyLightbox : function()
	{
		YAHOO.util.Event.removeListener(this.btnClose, "click");
		YAHOO.util.Event.removeListener(this.mask, "click");
		YAHOO.util.Event.removeListener(this.overlay, "click");
		
		this.escKeyClose.disable();
		this.spaceBar.disable();
		if (this.fwArrow) this.fwArrow.disable();
		if (this.bkArrow) this.bkArrow.disable();
		
		document.body.removeChild(this.btnCloseWrapper);
		
		var overlayFadeOut = new YAHOO.util.Anim(this.overlay, {opacity:{to:0}}, 0.4, YAHOO.util.Easing.easeOut);
		overlayFadeOut.onComplete.subscribe(this.maskFadeOut, this, true);
		overlayFadeOut.animate();
	},

	maskFadeOut : function()
	{	
		var maskFadeOut = new YAHOO.util.Anim(this.mask, {opacity:{to:0}}, 0.4, YAHOO.util.Easing.easeOut);
		maskFadeOut.onComplete.subscribe(this.removeElementsFromDOM, this, true);
		maskFadeOut.animate();
	},

	removeElementsFromDOM : function()
	{
		document.body.removeChild(this.mask);
		document.body.removeChild(this.overlay);
	}
}


//Flash Gallery

mUtils.flashGallery = function(strXmlDataSource, elFlashContainer, elThumbsList, strFilepath, strWidth, strHeight) {
	this.container = elFlashContainer;
	this.thumbsList = elThumbsList;
	this.flashFile = strFilepath + "?xmlDataSource=" + strXmlDataSource;
	this.width = strWidth;
	this.height = strHeight;
}

mUtils.flashGallery.prototype = {

	init : function()
	{
		var thumbs = this.thumbsList.getElementsByTagName("a");
		for (var i=0; i<thumbs.length; i++)
		{
			YAHOO.util.Event.on(thumbs[i], "click", this.reloadFlash, new Array(this, i));
		}
		this.loadFlash(this.flashFile);
	},
	
	loadFlash : function(flashFile)
	{
		var so = new SWFObject(flashFile, "flashGallery", this.width, this.height, "6", "fff");
		so.write(this.container);
	},
	
	reloadFlash : function(ev, args)
	{
		this.blur();
		YAHOO.util.Event.preventDefault(ev);
		
		var newFlashName = args[0].flashFile + "&count=" + args[1];
		args[0].loadFlash(newFlashName);
	}
}