/*  
 *  (c) 2006 Flipswap, Inc.
 *
*/
YAHOO.namespace("flipswap");
var $D = YAHOO.util.Dom;
var $E = YAHOO.util.Event;
var $ = $D.get;

function hideModals() {
	var modals = $D.getElementsByClassName("modal", "div", document.body);
	
	if (modals != null) {
		$D.batch(modals, function(modal) {
			getEl(modal).hide();
		});	
	}
}

function initButtons(root) {
	/*var buttons = $D.getElementsByClassName("button", "input", root);			
	$E.on(buttons, "mouseover", function() {
	   var substr1 = this.src.substring(0, this.src.lastIndexOf("."));
	   var substr2 = this.src.substring(this.src.lastIndexOf("."));
	   this.src = substr1 + "Over" + substr2;
	});
	 
	$E.on(buttons, "mouseout", function() {
		var split = this.src.split("Over");
		this.src = split[0] +  split[1];
	});*/
}

function init() {
	initButtons(document.body);
	hideModals();
	$E.addListener($D.getElementsByClassName("modalTrigger"), "click", function() {
		Modal.showOverlayWithIndicator();
	});
	
	/*$E.addListener($D.getElementsByClassName("manufacturerTrigger"), "mouseover", function(e) {
		SideMenu.show(e);		
	});
	
	$E.addListener($D.getElementsByClassName("manufacturerTrigger"), "mouseout", function(e) {
		SideMenu.hide(e);
	});*/
}

$E.onDOMReady(init);

YAHOO.flipswap.Element = function(id) {
	this.init(id);
};

var $$ = function(id) {
	return new YAHOO.flipswap.Element(id);
};

YAHOO.flipswap.Element.prototype = {
	init: function(id) {
		this.el = $(id);
	},
	
	getDimensions: function() {		
		if ($D.getStyle(this.el, "display") != "none")
	      return {width: this.el.offsetWidth, height: this.el.offsetHeight};
	
	   	// All *Width and *Height properties give 0 on elements with display none,
		// so enable the element temporarily
		var els = this.el.style;
		var originalVisibility = els.visibility;
		var originalPosition = els.position;
		els.visibility = 'hidden';
		els.position = 'absolute';
		els.display = '';
		var originalWidth = this.el.clientWidth;
		var originalHeight = this.el.clientHeight;
		els.display = 'none';
		els.position = originalPosition;
		els.visibility = originalVisibility;
		return {width: originalWidth, height: originalHeight};
	},
	
	getHeight: function() {			
		return this.getDimensions()["height"];
	},
	
	getWidth: function() {
		return this.getDimensions()["width"];
	},
	
	getTop: function() {
		return $D.getY(this.el);
	},
	
	getBottom: function() {
		return this.getTop() + this.getHeight();
	},
	
	getLeft: function() {
		return $D.getX(this.el);
	},
	
	getRight: function() {
		return this.getLeft() + this.getWidth();
	},
	
	getCenterCoords: function() {
		var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
		var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
	
		var viewPortWidth = YAHOO.util.Dom.getViewportWidth();
		var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
				
		var elementWidth = this.getWidth();
		var elementHeight = this.getHeight();	
					
		var x = Math.round((viewPortWidth / 2) - (elementWidth / 2) + scrollX);
		var y = Math.round((viewPortHeight / 2) - (elementHeight / 2) + scrollY);
		
		return {x: x < 0 ? 0 : x, y: y < 0 ? 0 : y};
	},
	
	center: function() {
		var centerCoords = this.getCenterCoords();
		$D.setStyle(this.el, "position", "absolute");
		$D.setStyle(this.el, "left", centerCoords["x"] + "px");				
		$D.setStyle(this.el, "top", centerCoords["y"] + "px");
	}
};

function initHelp() {
	 $E.on($D.getElementsByClassName("questionLabel"), "mouseover", function(e) {
            var span = this.parentNode.getElementsByTagName("span").item(0);
            $D.setStyle(span, "display", "block");
            $D.setXY(span, [$E.getPageX(e) + 10,$E.getPageY(e) - 15 - $$(span).getHeight()]);

            if (YAHOO.ext.util.Browser.isIE && !YAHOO.ext.util.Browser.isIE7)
                    $D.setStyle($("questionsTable").getElementsByTagName("select"), "visibility", "hidden");
    });

    $E.on($D.getElementsByClassName("questionLabel"), "mousemove", function(e) {
            var span = this.parentNode.getElementsByTagName("span").item(0);
            $D.setXY(span, [$E.getPageX(e) + 10,$E.getPageY(e) - 15 - $$(span).getHeight()]);
    });

    $E.on($D.getElementsByClassName("questionLabel"), "mouseout", function() {
            var span = this.parentNode.getElementsByTagName("span");
            $D.setStyle(span, "display", "none");

            if (YAHOO.ext.util.Browser.isIE && !YAHOO.ext.util.Browser.isIE7)
                    $D.setStyle($("questionsTable").getElementsByTagName("select"), "visibility", "visible");
    });
}

YAHOO.flipswap.Ratings = function(id) {
	this.init(id);
};

YAHOO.flipswap.Ratings.prototype = {		
	init: function(id) {
		this.id = $(id);
		var definition = getEl(YAHOO.ext.DomHelper.append(this.id, {tag : "p", cls: "ratingDefinition"}), true);
		definition.hide();
		definition.setStyle("position", "absolute");	
		definition.setRight(47);
		if (YAHOO.ext.util.Browser.isIE7)
    	definition.setTop(375);
		
		this.definition = definition;		
		this.ratingListItems = this.id.getElementsByTagName("li");
		$E.on(this.ratingListItems, "mouseout", this._reset, this, true);
		$E.on(this.ratingListItems, "mouseover", this._highlight, this, true);		
		$E.on(this.ratingListItems, "click", this._select, this, true);
		
		this.ratingRadios = this.id.getElementsByTagName("input");		
		this.selectedRatingIndex = -1;		

		var index = 0;
		while (this.selectedRatingIndex == -1 && index < this.ratingRadios.length) {
			if (this.ratingRadios[index].checked)
				this.selectedRatingIndex = index;
				
			index++;
		}			
		
		this._reset()
	},	
	
	_select: function(e) {
		var index = 0;
		var found = false;
		while (!found && index < this.ratingListItems.length) {
			var el = this.ratingListItems[index++];
			if (el == $E.getTarget(e))
				found = true;
		}	
					
		this.ratingRadios[--index].checked = true;
		this.selectedRatingIndex = index;			
	},
	
	_highlight: function(e) {	
		this._clear();	
		var index = 0;	
		var found = false;	
		while (!found && index < this.ratingListItems.length) {
			var el = this.ratingListItems[index++];
			el.className = "ratingSelected";
			
			if (el == $E.getTarget(e)) {
				found = true;								
			}
		}
		
		this.definition.update(this.ratingRadios[--index].title);				
		this.definition.show();		
	},
	
	_clear: function() {
		for (i = 0; i < this.ratingListItems.length; i++) {
			this.ratingListItems[i].className = "";
		}
	},
	
	_reset: function(e) {			
		for (i = 0; i < this.ratingListItems.length; i++) {
			if (i > this.selectedRatingIndex)
				this.ratingListItems[i].className = "";
			else
				this.ratingListItems[i].className = "ratingSelected";							
		}				
		
		this.definition.hide();		
	}
};

var Slider = function() {
	var CLASSNAME = "faderLI";
	var MAX_VISIBLE_ITEMS = 1;
	var HEIGHT = 148;
	var TIMEOUT = 5000;
	var index = 0;
	var el;
	var size;	
	var f;
	
	var next = function() {		
		var attributes = {
			points : {
				by : [0, -HEIGHT]
			}
		};
		
		var anim = new YAHOO.util.Motion(el, attributes, 0.5, YAHOO.util.Easing.easeOut);		
		index++;
		anim.animate();
	};	
	
	var reset = function() {
		var attributes = {
			points : {
				by : [0, HEIGHT * ((size / MAX_VISIBLE_ITEMS) - 1)]
			}
		};
		
		var anim = new YAHOO.util.Motion(el, attributes, 0.5, YAHOO.util.Easing.easeOut);
		index = 0;
		anim.animate();
	}
	
	var autoPlay = function() {		
		if (index < (size/MAX_VISIBLE_ITEMS) -1)
			next();
		else
			reset();
			
		Slider.play();
	}
	
	return {
		init: function(id) {
			el = $(id);
			size = $D.getElementsByClassName(CLASSNAME, "li", el).length;			
			Slider.play();		
		},
		
		play: function() {			
			f = window.setTimeout(autoPlay, TIMEOUT);
		},
		
		stop: function() {
			window.clearTimeout(f);			
		}
	};	
}();

YAHOO.flipswap.Effect = function() {	
	return {
		blindUp: function(id, callback) {
			var el = getEl(id);
			//el.setStyle("overflow", "hidden");			
			var onComplete = function() {
				if(typeof callback == 'function')
				    callback();
					 
				el.hide();
			};
			el.setHeight(0, true, 0.4, onComplete);
		},		
		
		blindDown: function(id, callback) {	
			var el = getEl(id);			
			el.setStyle("display", "block");		
			el.setStyle("visibility", "hidden");
			el.setStyle("overflow", "hidden");			
			el.setStyle("height", "");
			el.setXY(el.getCenterXY(true));
			
			var height = el.getHeight();		
			el.setStyle("height", 0);
			el.show();										
			
			var onComplete = function() {
				el.setStyle("height", "");
				callback();
			}
			el.setHeight(height, true, 0.5, onComplete);							
		}
	};
}();

YAHOO.flipswap.Exploder = function(idToShow) {
	this.el = getEl(idToShow);
	this.size = this.el.getSize();
	this.xy = this.el.getCenterXY(true);
	this.el.hide();
	this.el.setStyle("display", "none");	
	this.exploder = getEl(YAHOO.ext.DomHelper.append(this.el.dom.parentNode, {tag : 'div', cls: 'exploder'}), true);
	this.exploder.setOpacity(0.5);
};

YAHOO.flipswap.Exploder.prototype = {		
	show: function(target, callback) {
		if (!this.el.isVisible()) {
			this.exploder.setXY(target.getXY());
			this.exploder.setSize(20,20);
			this.exploder.show();			
			this.exploder.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height, true, .35, this._showEl.createDelegate(this, [callback]));
		}
	},
	
	hide : function(target, callback){        
        var p = target.getXY();
        this.exploder.show();
        this.el.hide();        
        this.exploder.setBounds(p[0], p[1], 20, 20, true, .35, this._hideEl.createDelegate(this, [callback]));
    },
	
	_showEl: function(callback) {
		this.el.setStyle("display", "block");
		this.el.setBox(this.exploder.getBox());
      this.el.show();
      this.exploder.hide();	
		
		if(typeof callback == 'function'){
		    callback();
		}	
	},
	
	_hideEl : function(callback){
		this.exploder.hide();
		if(typeof callback == 'function'){
		    callback();
		}
	}
};

var SideMenu = function() {
	var menu;	
	var menuHide;
	var target;
	
	var hideMenu = function(isMenu) {
		$D.setStyle(menu, "display", "none");
		
		if (isMenu)
			$D.replaceClass(target, "manufacturerTriggerOver", "manufacturerTrigger");
	}	
	
	return {
		show: function(e) {			
			if (menu != null)
				hideMenu();

			if (e != null) {
				var tempTarget = $E.getTarget(e);
				if (target != tempTarget) {
					$D.replaceClass(target, "manufacturerTriggerOver", "manufacturerTrigger");					
					target = tempTarget;
				}
								
				$D.replaceClass(target, "manufacturerTrigger", "manufacturerTriggerOver");
				menu = $D.getElementsByClassName("submenu", "div", target.parentNode)[0];
				$D.setStyle(menu, "zIndex", 1000);
			}
			
			if (menuHide != null)
				clearTimeout(menuHide);	
			
			if ($E.getListeners(menu) == null) {								
				$E.on(menu, "mouseover", function() {SideMenu.show()});
				$E.on(menu, "mouseout", function() {SideMenu.hide(true)});
			}			
			
			$D.setStyle(menu, "display", "block");			
		},
		
		hide: function(isMenu) {
			var temp = function() {
				hideMenu(isMenu);
			}
			menuHide = window.setTimeout(temp, 200);			
		}		
	};
}();

var Modal = function() {
	var OVERLAYID = "fs_overlay";
	var OVERLAYMINWIDTH = 938;
	var TOPPADDING = 30;
	var BOTTOMPADDING = 30;
	var overlay;
	var modalEl;
	var targetEl;
	var indicator;
	var modalObj;
	
	var initOverlay = function() {				
		if (overlay == null) {
			overlay = YAHOO.ext.Element.get(YAHOO.ext.DomHelper.append(document.body, {tag: "div", id: OVERLAYID}), false);			
			overlay.setStyle("zIndex", 998);
			overlay.setStyle("backgroundColor", "#000");
			overlay.setStyle("display", "none");
			overlay.setStyle("overflow", "hidden");
			overlay.setOpacity(0);
			overlay.setStyle("position","absolute");
			overlay.setTop(0);
			overlay.setLeft(0);
			overlay.setStyle("minWidth", OVERLAYMINWIDTH + "px");
			overlay.setStyle("width", "100%");
			overlay.setStyle("height", $D.getDocumentHeight() + "px");			
		}
	};	
	
	var hideSelects = function() {		
		if (YAHOO.ext.util.Browser.isIE) {
			//Necessary for IE
			var selects = document.getElementsByTagName("select");
			
			// alert("hideSelects");
				
			if (selects != null && selects.length > 0)
				YAHOO.util.Dom.batch(selects, function(element) {				
						$D.setStyle(element, "visibility", "hidden");
				});	
			
				// Make sure that Manufacturer control shows (only applicable for cart page after clear)
				var manuDD = document.getElementsByName("manufacturerDD");
				YAHOO.util.Dom.batch(manuDD, function(element) {
					$D.setStyle(element, "visibility", "visible");	
				});
		}
	};
	
	var showSelects = function() {
		if (YAHOO.ext.util.Browser.isIE) {
			var selects = document.getElementsByTagName("select");
			
			// alert("showSelects");
				
			if (selects != null && selects.length > 0)
				YAHOO.util.Dom.batch(selects, function(element) {
					$D.setStyle(element, "visibility", "visible");	
				});
		}
	};
	
	var showOverlay = function(onComplete) {
		initOverlay();
		if (!overlay.isVisible()) {
			overlay.setStyle("display", "block");
			overlay.show();
			overlay.setOpacity(0.6);
			hideSelects();	
			if ($("questionsTable") != null)	
				$D.setStyle($("questionsTable").getElementsByTagName("select"), "visibility", "visible");	
		}
		
		if(typeof onComplete == 'function'){
	   	onComplete();
		}
	};
	
	var hideOverlay = function(onComplete) {	
		if (overlay.isVisible()) {	
			var f = function() {
				overlay.hide();
				overlay.setStyle("display", "none");								
				showSelects();
				if(typeof onComplete == 'function'){
			   	onComplete();
				}
			};
	
			overlay.setOpacity(0);
			f();
		}
	};
	
	var moveWithinBounds = function() {			
		var vph = $D.getViewportHeight();
		var scrollTop = self.pageYOffset|| document.documentElement.scrollTop || document.body.scrollTop || 0;			
		var centerCoords = modalEl.getCenterXY(true);
		var topTooLow = modalEl.getTop() > scrollTop + TOPPADDING;
		var bottomTooHigh = modalEl.getBottom() < scrollTop + vph - BOTTOMPADDING;
		var topTooHigh = modalEl.getTop() < scrollTop + TOPPADDING;
		var bottomTooLow = modalEl.getBottom() > scrollTop + vph - BOTTOMPADDING;
		var isSmall = modalEl.getHeight() <= vph - TOPPADDING - BOTTOMPADDING;
		var y = centerCoords[1]; 			
		
		if (!isSmall && (topTooHigh || bottomTooLow)) {
			if (topTooLow || bottomTooHigh && isSmall)
				if (topTooLow && isSmall)
					y = scrollTop + vph - BOTTOMPADDING - modalEl.getHeight();				
				else
					y = scrollTop + TOPPADDING;						
			else if (bottomTooHigh)
				y = scrollTop + vph - BOTTOMPADDING - modalEl.getHeight();			
		}		
		
		if (y + modalEl.getHeight() > $D.getDocumentHeight())
			y = $D.getDocumentHeight() - BOTTOMPADDING - modalEl.getHeight();													
		
		modalEl.setLocation(centerCoords[0],y,true,0.5);
	};
	
	var fixOverlayDimensions = function() {		
		overlay.setWidth($D.getDocumentWidth() + "px");	
		overlay.setHeight($D.getDocumentHeight() + "px");
	};	
	
	var moveAndFixOverlay = function() {
		fixOverlayDimensions();
		moveWithinBounds();
	};
	
	var centerIndicator = function() {
		if (indicator != null)
			indicator.setXY(indicator.getCenterXY(true));
		else			
			showIndicator();
	};
		
	var showIndicator = function() {		
		if (indicator == null) {
			indicator = getEl(YAHOO.ext.DomHelper.append(document.body, {tag: "div", id: "indicator"}), true);
			indicator.setStyle("zIndex", 999);
			indicator.setStyle("position", "absolute");
		}
				
		if (!indicator.isVisible())
			indicator.show();
					
		if (indicator != null)
			centerIndicator();	
			
		$E.on(window, "resize", centerIndicator);						
	};	
	
	var hideIndicator = function() {
		if (indicator != null)
			indicator.hide();
			
		$E.removeListener(window, "resize", centerIndicator);
	};
			
	return {
		show: function(modal) {
			Slider.stop();										
			modalEl = getEl(modal);		
			modalObj = $(modalEl.id);		
			showIndicator();
			
			//Clean up listeners
			$E.removeListener(window, "resize", fixOverlayDimensions);			
			$E.on(window, "scroll", moveWithinBounds);	
			$E.on(window, "resize", moveAndFixOverlay);	
											
			var onComplete = function() {				
				initButtons(modal);				
			};
			
			var onComplete2 = function() {				
				//By restacking the divs, we avoid dealing with IE zIndex bug					
				if (modalObj.parentNode != document.body) {
					modalObj.parentNode.removeChild(modalObj);
					document.body.insertBefore(modalObj, document.body.firstChild);
				}				
				
				YAHOO.flipswap.Effect.blindDown(modal, onComplete);				
			}			
			
			hideIndicator();			
			showOverlay(onComplete2);			
			return false;		
		},
		
		hide: function() {								
			YAHOO.flipswap.Effect.blindUp(modalEl.id);
			hideOverlay();			
			$E.removeListener(window, "resize", fixOverlayDimensions);	
			$E.removeListener(window, "scroll", moveWithinBounds);
			$E.removeListener(window, "resize", centerIndicator);
			Slider.play();
			return false;	
		},
		
		showOverlayWithIndicator: function() {			
			showOverlay();
			$E.on(window, "resize", fixOverlayDimensions);
			showIndicator();									
		},
		
		center: function() {
			modalEl.setXY(modalEl.getCenterXY(true));			
		}
	};
}();

function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}