var W3CDOM = (document.createElement && document.getElementsByTagName);
var dirty = false;
function topnav()
{
        if (dirty) return;
	var moo = document.getElementsByClassName('over');
	var mouseOvers = new Array();
	var mouseOuts = new Array();

	for (var i=0; i < moo.length; i++) {
		moo[i].onmouseover = mouseGoesOver;
		moo[i].onmouseout = mouseGoesOut;
		var suffix = moo[i].src.substring(moo[i].src.lastIndexOf('.'));
		mouseOuts[i] = new Image();
		mouseOuts[i].src = moo[i].src;
		mouseOvers[i] = new Image();
		mouseOvers[i].src = moo[i].src.substring(0,moo[i].src.lastIndexOf('.')) + "_over" + suffix;
		moo[i].number = i;
	}
        dirty = true;
	function mouseGoesOver()
	{
		this.src = mouseOvers[this.number].src;
	}
	function mouseGoesOut()
	{
		this.src = mouseOuts[this.number].src;
	}
}

function popUp(url, height, width) {
	window.open(url, '', "width="+width+", height="+height+", resizable=yes, toolbar=no, menubar=no, location=no");
}

// url encode method
function URLEncode(clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

/* top nav tooltip */
Event.observe(window,"load",navToolTip);
var dv = null;
function navToolTip(e) {
	/* workaround until prototype library conflicts are resolved */
	var arr = new Array("primarynav_womens","primarynav_beauty","primarynav_mens","primarynav_apartment","primarynav_sale","primarynav_general_category","primarynav_blog","primarynav_whatsnew","primarynav_brands","primarynav_trends");
	for (var i=0; i<arr.length; i++) {
		var cur = $(arr[i]);
		if (cur) {
			var children = cur.descendants();
			children.each(function(c) {
				var curTag = c.tagName.toLowerCase();
				if (curTag.indexOf('a') >= 0) {
					if (c.title.toLowerCase().indexOf("men's") >= 0) {
						Event.observe(c, 'mouseover', shopMensAndWomen);
					} else if (c.title.toLowerCase().indexOf("mens") >= 0) {
						Event.observe(c, 'mouseover', shopMensAndWomen);
					} else if (c.title.toLowerCase().indexOf("beauty") >= 0) {
						Event.observe(c, 'mouseover', shopBeauty);
					} else if (c.title.toLowerCase().indexOf("apartment") >= 0) {
						Event.observe(c, 'mouseover', shopApartment);
					} else if (c.title.toLowerCase().indexOf("sale") >= 0) {
						Event.observe(c, 'mouseover', shopSale);
					} else if (c.title.toLowerCase().indexOf("gifts") >= 0) {
						Event.observe(c, 'mouseover', shopGifts);
					} else if (c.title.toLowerCase().indexOf("blog") >= 0) {
						Event.observe(c, 'mouseover', visitUoBlog);
					} else if (c.title.toLowerCase().indexOf("new") >= 0) {
						Event.observe(c, 'mouseover', whatsNew);
					} else if (c.title.toLowerCase().indexOf("trends") >= 0) {
						Event.observe(c, 'mouseover', shopTrends);
					} else if (c.title.toLowerCase().indexOf("brands") >= 0) {
						Event.observe(c, 'mouseover', shopBrands);
					}
					Event.observe(c, 'mouseout', removeToolTip);
					c.removeAttribute("title");
				}
			});
		}
	}
}
function shopMensAndWomen(e) {
	createDiv('Shop Clothing, Accessories and Shoes', Event.pointerX(e), Event.pointerY(e));
}
function shopBeauty(e) {
	createDiv('Shop Beauty Products', Event.pointerX(e), Event.pointerY(e));
}
function shopApartment(e) {
	createDiv('Shop Bedding, Wall Art, Furniture and More', Event.pointerX(e), Event.pointerY(e));
}
function shopSale(e) {
	createDiv('Shop Sale', Event.pointerX(e), Event.pointerY(e));
}
function shopGifts(e) {
	createDiv('Shop Holiday Gifts', Event.pointerX(e), Event.pointerY(e));
}
function visitUoBlog(e) {
	createDiv('Visit the UO Blog', Event.pointerX(e), Event.pointerY(e));
}
function whatsNew(e) {
	createDiv("Shop What's New", Event.pointerX(e), Event.pointerY(e));
}
function shopTrends(e) {
	createDiv('Shop Trends', Event.pointerX(e), Event.pointerY(e));
}
function shopBrands(e) {
	createDiv("Shop Brands", Event.pointerX(e), Event.pointerY(e));
}
function createDiv(txt, x, y) {
	dv = document.createElement('div');
	document.body.appendChild(dv);
	//set the inner styling of the div tag 
	dv.style.position = "absolute";       
	dv.style.left = x + "px";
	dv.style.top = y + "px";
	dv.style.zIndex = 9999;
	dv.style.overflow = "hidden";
	dv.style.padding = "4px";
	dv.style.margin = "8px";
	dv.style.background = "#ffffff";
	dv.style.border = "solid 1px #999999";
	dv.style.color = "#999999";
	//set the html content inside the div tag
	dv.innerHTML = txt;
}
function removeToolTip() {
	if (dv != null) {
		document.body.removeChild(dv);
		dv = null;
	}
}

/* tooltip for CID message */
var cidDiv = null;
Event.observe(window,"load",showCidToolTip);
Event.observe(window,"load",showSavedCidToolTip);
function showCidToolTip(e) {
	// check if objects exist
	if ($("cidToolTip")) {
		Event.observe($("cidToolTip"), 'mouseover', cidToolTip);
		Event.observe($("cidToolTip"), 'mouseout', removeCidToolTip);
	}
}
function showSavedCidToolTip(e) {
	if ($("savedCidToolTip")) {
		Event.observe($("savedCidToolTip"), 'mouseover', cidToolTip);
		Event.observe($("savedCidToolTip"), 'mouseout', removeCidToolTip);
	}
}
function createCidDiv(txt, x, y) {
	cidDiv = document.createElement('div');
	document.body.appendChild(cidDiv);
	//set the inner styling of the div tag 
	cidDiv.style.position = "absolute";       
	cidDiv.style.left = x + "px";
	cidDiv.style.top = y + "px";
	cidDiv.style.zIndex = 9999;
	cidDiv.style.width = "260px";
	cidDiv.style.height = "80px"
	cidDiv.style.overflow = "hidden";
	cidDiv.style.padding = "4px";
	cidDiv.style.margin = "8px";
	cidDiv.style.background = "#ffffff";
	cidDiv.style.border = "solid 1px #999999";
	cidDiv.style.color = "#000000";
	cidDiv.style.fontSize = "11px";
	cidDiv.style.lineHeight = "14px";
	//set the html content inside the div tag
	cidDiv.innerHTML = txt;
}
function cidToolTip(e) {
	var content = '<div id="cidContent" style="position:relative;">';
	content += '<iframe src="" border="0" frameborder="0" height="80" width="260" class="selectBlocker"></iframe>';
	content += '<div style="position:absolute; top:0px; left:0px; z-index:2">This is the 3 or 4 digit code found on the back of your credit card or front of an American Express card. It helps protect your card from unauthorized use.';
	content += '<br/><img src="/urban/images/2007_holiday/cid.jpg" style="padding-top:3px;" /></div></div>';
	createCidDiv(content, Event.pointerX(e), Event.pointerY(e));
}
function removeCidToolTip() {
	if (cidDiv != null) {
		document.body.removeChild(cidDiv);
		cidDiv = null;
	}
}

/* tool tip for mobile terms and conditions */
Event.observe(window,"load",showMobileTermsToolTip);
function showMobileTermsToolTip(e) {
	var aTags = document.getElementsByTagName("a");
	if ((aTags.length > 0) && ((location.href.indexOf("myaccount.") > 0) || (location.href.indexOf("account_menu.") > 0) || (location.href.indexOf("emailsignup.") > 0))) {
		for (var i=0; i<aTags.length; i++) {
			var c = aTags[i];
			if (c.href == "http://form.acumob.com/resources/uo/uohelp.php") {
				c.href = "javascript:void(0)";
				c.target = "_self";
				Event.observe(c, 'mouseover', mobileTermsTip);
				Event.observe(c, 'mouseout', removeToolTip);
				break;
			} else {
				continue;
			}
		}
	}
}
function createMobileTermsDiv(txt, x, y) {
	dv = document.createElement('div');
	document.body.appendChild(dv);
	//set the inner styling of the div tag 
	dv.style.position = "absolute";       
	dv.style.left = x + "px";
	dv.style.top = y + "px";
	dv.style.zIndex = 9999;
	dv.style.width = "260px";
	dv.style.overflow = "hidden";
	dv.style.padding = "4px";
	dv.style.margin = "-80px 0px 0px -55px";
	dv.style.background = "#ffffff";
	dv.style.border = "solid 1px #999999";
	dv.style.color = "#000000";
	dv.style.fontSize = "11px";
	dv.style.lineHeight = "14px";
	//set the html content inside the div tag
	dv.innerHTML = txt;
}
function mobileTermsTip(e) {
	var content = "To receive monthly text promotions and updates, enter your mobile number. 2 msgs per month. Msg &amp; Data Rates May Apply. To discontinue service reply STOP to 868686. All major carriers supported.";
	createMobileTermsDiv(content, Event.pointerX(e), Event.pointerY(e));
}

/* add coremetrics element tags */
var tagsTimer = null;
function addPageElementTags() {
	if (location.href.indexOf("productdetail.jsp") > 0) {
		// pass an array of ids to function to add cm pageElementTags
		$w("addToWishlistLink shareThisProductLink emailAFriendLink checkAvailabilityLink sizeChartLink photoTabLink videoTabLink detailsTabLink reviewsTabLink askAndAnswerTabLink").each(function(x) {
			if ($(x)) {
				Event.observe(x, 'mouseup', function(e) {
					cmCreatePageElementTag(x,"Product Detail");
				});
			}
		});
	}
	if (location.href.indexOf("gift_card_balance_check.jsp") > 0) {
		var inputObj = $$("input[type='submit']");
		if (inputObj) {
			inputObj.each(function(e) {
				if (e.hasClassName("submitBtn")) {
					Event.observe(e, 'mouseup', function(e) {
						cmCreatePageElementTag("CheckBalance","GCChecker");
					});
				}
			});	
		}
	}
	// add to more uo links
	if ($("facebookMoreUO")) {
		clearTimeout(tagsTimer);
		tagsTimer = null;
		$w("facebookMoreUO twitterMoreUO textMoreUO rssMoreUO").each(function(m) {
			if ($(m)) {
				Event.observe(m, 'mouseup', function(e) {
					cmCreatePageElementTag(m,"More UO");
				});
				
			}
		});
	} else {
		tagsTimer = setTimeout("addPageElementTags()",100);	
	}
}
addPageElementTags();

/* add utility function for form focus issues with IE */
function check4Return(e, frmName, btnName) {
	if (e.keyCode == 13) {
		if ((document.forms[frmName]) && (document.forms[frmName].elements[btnName])) {
			document.forms[frmName].elements[btnName].focus();
		}
	}
}

/* add pageElement tags to checkout buttons */
var checkoutTimer = null;
function checkoutPageElementTags() {
	// add to login page
	if (location.href.indexOf("checkout_login.jsp") >= 0) {
		// sign-in button
		if ($("fLogin")) {
			Event.observe($("fLogin"), 'mouseup', function(e) {
				cmCreatePageElementTag("Sign-In","Checkout Login");
			});
		}
		// name for sign-up button: Continue
		if (document.forms['regForm']) {
			var signup = document.forms['regForm'].elements['Continue'];
			if (signup) {
				Event.observe(signup, 'mouseup', function(e) {
					cmCreatePageElementTag("Sign-Up","Checkout Login");
				});
			}
		}
		// name for guest checkout button: Continue
		if (document.forms['guestCheckoutForm']) {
			var guest = document.forms['guestCheckoutForm'].elements['Continue'];
			if (guest) {
				Event.observe(guest, 'mouseup', function(e) {
					cmCreatePageElementTag("Guest","Checkout Login");
				});
			}
		}
		if (($("fLogin")) && (document.forms['regForm'])) {
			clearTimeout(checkoutTimer);
			checkoutTimer = null;
		} else {
			// set timer
			checkoutTimer = setTimeout("checkoutPageElementTags()",100);
		}	
	} else if (location.href.indexOf("checkout_autologged.jsp") >= 0) {
		// we've got your back
		if ($("fLogin")) {
			clearTimeout(checkoutTimer);
			checkoutTimer = null;
			Event.observe($("fLogin"), 'click', function(e) {
				cmCreatePageElementTag("Sign-In", "Checkout AutoLogged");		
			});
		} else {
			// set timer
			checkoutTimer = setTimeout("checkoutPageElementTags()",100);
		}	
	} else if (location.href.indexOf("full/shipping.jsp") >= 0) {
		// shipping page
		if (document.forms['shippingForm']) {
			var signup = $$("div.shoppingcart_checkout h5.button_checkout a");
			signup.each(function(s) {
				Event.observe(s, 'mouseup', function(e) {
					// check if guest checkout or not
					if (document.forms['guestAccountForm']) {
						cmCreatePageElementTag("Shipping Page","Guest Checkout");
					} else {
						cmCreatePageElementTag("Shipping Page","Regular Checkout");
					}	
				});
			});
		}
		if ($("guestAccountForm")) {
			var guest = $("continueBtn");
			Event.observe(guest, 'mouseup', function(e) {
				cmCreatePageElementTag("Shipping Page Create Account","Guest Checkout");
			});
		}
		if (document.forms['shippingForm']) {
			clearTimeout(checkoutTimer);
			checkoutTimer = null;
		} else {
			// set timer
			checkoutTimer = setTimeout("checkoutPageElementTags()",100);
		}
	} else if (location.href.indexOf("checkout/billing.jsp") >= 0) {
		if (document.forms['billingform']) {
			clearTimeout(checkoutTimer);
			checkoutTimer = null;
			var continueBtn = $$('div.shoppingcart_checkout h5.button_checkout input[value="Continue Checkout"]');
			continueBtn.each(function(c) {
				Event.observe(c, 'click', function(e) {
					// check for saved credit cards
					if ($("saveCard")) {
						// regular checkout
						cmCreatePageElementTag("Billing Page","Regular Checkout");
					} else {
						// guest checkout cannot save credit cards
						cmCreatePageElementTag("Billing Page","Guest Checkout");
					}
				});
			});
		} else {
			// set timer
			checkoutTimer = setTimeout("checkoutPageElementTags()",100);
		}
	} else if (location.href.indexOf("guest_co_thankyou.jsp") >= 0) {
		// thank you
		if ($("guestAccountForm")) {
			var guest = $("continueBtn");
			Event.observe(guest, 'mouseup', function(e) {
				cmCreatePageElementTag("Thank You Page Create Account","Guest Checkout");
			});
		}
	}
}
checkoutPageElementTags();

/* SHARE WIDGET */
// array of social networking sites
var shareSites = new Array("facebook","twitter","stumbleupon","tumblr","buzz","polyvore");
// facebook
shareSites["facebook"] = new Array("icon","name","url");
shareSites["facebook"]["name"] = "Facebook";
shareSites["facebook"]["icon"] = "/urban/images/2007_holiday/facebook-icon.gif";
shareSites["facebook"]["url"] = "http://www.facebook.com/sharer.php?u=URL&t=TITLE";
// twitter
shareSites["twitter"] = new Array("icon","name","url");
shareSites["twitter"]["name"] = "Twitter";
shareSites["twitter"]["icon"] = "/urban/images/2007_holiday/twitter_icon.png";
shareSites["twitter"]["url"] = "http://twitter.com/home/?status=URL";
// stumbleupon
shareSites["stumbleupon"] = new Array("icon","name","url");
shareSites["stumbleupon"]["name"] = "StumbleUpon";
shareSites["stumbleupon"]["icon"] = "/urban/images/2007_holiday/stumbleupon-icon.jpg";
shareSites["stumbleupon"]["url"] = "http://www.stumbleupon.com/submit?&url=URL&title=TITLE";
// tumblr
shareSites["tumblr"] = new Array("icon","name","url");
shareSites["tumblr"]["name"] = "Tumblr";
shareSites["tumblr"]["icon"] = "/urban/images/2007_holiday/tumblr-icon.gif";
shareSites["tumblr"]["url"] = "http://tumblr.com/share?v=2&u=URL&t=TITLE";
// google buzz
shareSites["buzz"] = new Array("icon","name","url");
shareSites["buzz"]["name"] = "Google Buzz";
shareSites["buzz"]["icon"] = "/urban/images/2007_holiday/buzz-icon.png";
shareSites["buzz"]["url"] = "http://www.google.com/buzz/post?url=URL&message=TITLE";
// polyvore
shareSites["polyvore"] = new Array("icon","name","url");
shareSites["polyvore"]["name"] = "Polyvore";
shareSites["polyvore"]["icon"] = "/urban/images/2007_holiday/polyvore_icon.png";
shareSites["polyvore"]["url"] = "http://www.polyvore.com/cgi/add?url=URL&title=TITLE&imgurl=IMGURL";
// display share widget on page
function displayShareWidget() {
	var shareObj = $("shareUO");
	var output = "";
	if (shareObj) {
		for (i in shareSites) {
			if (shareSites[i]["icon"] && shareSites[i]["name"]) {
				output += '<a href="javascript:shareIt(\'' + i + '\')" title="' + shareSites[i]["name"] + '">';
				output += '<img src="' + shareSites[i]["icon"] + '" height="16" width="16" alt="' + shareSites[i]["name"] + '" border="0" /></a>';
			}
		}
		shareObj.innerHTML = output;
	}
}
// create share url and launch pop-up to post to social site
function shareIt(site) {
	// add page element tag
	cmCreatePageElementTag(site,"Product Detail");
	var textareaObj = $$("textarea");
	var url = "";
	var imgurl = "";
	if (textareaObj) {
		textareaObj.each(function(e){
			if (e.value.length > 0) {
				url = URLEncode(e.value);
			}
		});
	} else {
		url = URLEncode(window.location.href);	
	}
	var title = URLEncode(document.title);
	var targetURL = "";
	if (shareSites[site]) {
		targetURL = shareSites[site]["url"];
		targetURL = targetURL.replace("URL", url);
		targetURL = targetURL.replace("TITLE", title);
		if (site == "polyvore") {
			var prodID = document.forms['socialTaggingForm'].elements['prodID'].value;
			imgurl = document.images['imgl'+prodID].src;
			if (imgurl.length > 0) {
				targetURL = targetURL.replace("IMGURL", imgurl);
			}
		}
		window.open(targetURL,"","resizable=yes,scrollbars=yes,width=600,height=400");
	}
}

/* gift card balance checker */
function showGCBalanceChecker() {
	// blur link
	$("giftCardBalanceLink").blur();
	// declare variables
	var obj = $('giftCardFrmWrapper');
	var frm2 = $('billingform');
	// check if objects exist
	if ((obj) && (frm2)) {
		// set display
		if (obj.style.display == "none") {
			obj.style.display = "block";
		} else {
			obj.style.display = "none";
		}
		// set value of gift card checker gc number with same already entered in gift card field
		if ((frm2.elements['GiftCardNumberToCheck']) && (frm2.elements['giftCardNumber'])) {
			frm2.elements['GiftCardNumberToCheck'].value = frm2.elements['giftCardNumber'].value;
		}
	}
}

// gift card sub menu hover
Event.observe(window,"load",showGCmenu);
function showGCmenu() {
	Event.observe($("giftCardWrapper"), 'mouseover', showMenu);
	Event.observe($("giftCardWrapper"), 'mouseout', hideMenu);
}
function showMenu() {
	var obj = $("giftCardSubNav");
	if (obj) {
		obj.style.display = "block";
	}
}
function hideMenu() {
	var obj = $("giftCardSubNav");
	if (obj) {
		obj.style.display = "none";
	}
}

// gift card balance retrieval ajax
function checkGCbalance() {
	// blur submit button
	$("balanceCheckSubmit").blur();
	// declare variables				
	var url = "/urban/checkout/giftcardBalance_ajax.jsp";
	var qString = "";
	var gcNum = $("GiftCardNumberToCheck");
	var gcPin = $("giftCardPin");
	// check if objects exist
	if (gcNum && gcPin) {
		// check for values
		if ((gcNum.value.length > 0) && (gcPin.value.length > 0)) {
			qString = "?gcNum="+gcNum.value+"&gcPin="+gcPin.value;
			url += qString;
			// ajax call
			new Ajax.Request(url, {
				method: 'get',
				onSuccess: function(transport) {
					// display message
					var msg = $("giftCardAjaxMsg")
					if (msg) {
						msg.innerHTML = transport.responseText;
					}
				},
			    onFailure: function(transport) {
			    	// do nothing
			    }
			});
		} else {
			// both fields not filled out
			alert("Please fill out both the Gift Card Number and PIN fields before submitting.");
			// focus on empty field
			if (gcPin.value.length <= 0) {
				gcPin.focus();
			} else {
				gcNum.focus();
			}
		}
	} else {
		// objects do not exist
	}
}

// add jsp info to contact us form
function injectContactFooter() {
	// check for values
	var errors = false;
	var errMsg = "Please fill out all fields before submitting the form.";
	var firstName = $("firstName");
	if (firstName) {
		if (firstName.value.length == 0) {
			alert(errMsg);
			firstName.focus();
			return false;
		}
	}
	var lastName = $("lastName");
	if (lastName) {
		if (lastName.value.length == 0) {
			alert(errMsg);
			lastName.focus();
			return false;
		}
	}
	var emailAddress = $("emailAddress");
	if (emailAddress) {
		if (emailAddress.value.length == 0) {
			alert(errMsg);
			emailAddress.focus();
			return false;
		}
	}
	var subject = $("subject");
	if (subject) {
		if (subject.options[subject.options.selectedIndex].value.length == 0) {
			alert(errMsg);
			subject.focus();
			return false;
		}
	}
	var message = $("message");
	if (message) {
		if (message.value.length == 0) {
			alert(errMsg);
			message.focus();
			return false;
		}
	}
	// get fields
	var messageObj = $("message");
	var numItemsInCartObj = $("numItemsInCart");
	var originOfOrderObj = $("originOfOrder");
	var currentOrderObj = $("currentOrder");
	var serverInstanceObj = $("serverInstance");
	var userAgent = navigator.userAgent;
	try {
		messageObj.style.display = "none";
		str = "Number of Items in Cart: " + numItemsInCartObj.value + "<br>\r\n";
		str += "Origin of Order: " + originOfOrderObj.value + "<br>\r\n";
		str += "ATG Order ID: " + currentOrderObj.value + "<br>\r\n";
		str += "Server Info: " + serverInstanceObj.value + "<br>\r\n";
		str += "User Agent: " + userAgent + "<br>\r\n";
		messageObj.value += "<br>\r\n<br>\r\n" + str;
	} catch (err) {
		errors = true;
		//alert(err);
	}
	if (errors) {
		return false;
	} else {
		return true;
	}
}

// facebook like box
function addFbLikeBox() {
	var obj = $("connect_facebook");
	if (obj) {
		var fbDomain = "http://www.facebook.com";
		if (location.href.indexOf("https:") >= 0) {
			fbDomain = fbDomain.replace("http:","https:");
		}
		var fbLikeBox = '<span id="fbLikeBox"><iframe src="'+fbDomain+'/plugins/likebox.php?id=13473238797&amp;width=292&amp;connections=0&amp;stream=false&amp;header=false&amp;height=62" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:292px; height:62px;" allowTransparency="true"></iframe></span>';
		obj.innerHTML = fbLikeBox;
	}
}
Event.observe(window,"load",addFbLikeBox);