/*	All YUI library methods migrated to jQuery.
 *  Lee Daffen - lee.daffen@net-a-porter.com
 */

var bigWidth, // width of the zoom image
	smallWidth, // width of zoomed image
	bigHeight; // height of the zoom image

var bigX = 0, // zoom image x position
	bigY = 0; // zooom image y position

var smallHeight,
	bigBoxWidth,
	bigBoxHeight,
	factorY,
	factorX,
	easing = 0.5,
	zoomInterval = 0,
	mouseX = 0,
	mouseY = 0,
	sHeight,
	alsolikesHeight,
	elements,
	alsolikeelements,
	scrollBorder,
	thumbsPos = [],
	thumbsPosDown = [],
	divscrollBorder,
	divthumbsPos = [],
	divthumbsPosDown = [],
	divthumbsPosPast = [],
	divthumbsPosDownPast = [],
	imgAmount,
	divAmount,
	i = 0,
	idc = 0,
	dividc = 0,
	dividcPast = 0,
	delay = 0,
	hideInterval,
	str = window.location,
	zoomImageShown = false,
	nr,
	issueNumber,
	pageNumber,
	images,
	scrollHeight,
	alsolikescrollHeight,
	eventscrollHeight;

var fadeOut,
	fadeIn;

//ratio between the small and big images of the product
//hard-coded, we could work this out dynamically
var zoomRatio = 0.25;

var zoomWindowBoxWidth = 0,
	zoomWindowBoxHeight = 0;

//Number of items displayed for thumbnails/may also like/etc before scrolling is enabled
var numberOfItemsDisplayedBeforeScrolling = 4;

function doFadeIn() {
	document.getElementById("zoom-image").style.zIndex = "10";
	document.getElementById("zoom-box").style.zIndex = "50";
	document.getElementById("zoom-box-overlay").style.zIndex = "100";
	//document.getElementById("why-shop-holder").style.visibility = "hidden";
	if(document.getElementById("view-more")) document.getElementById("view-more").style.visibility = "hidden";
	if(document.getElementById("marketing-area")) document.getElementById("marketing-area").style.visibility = "hidden";

	$("#zoom-box").fadeIn("normal");
}

function doFadeOut() {
	//document.getElementById("why-shop-holder").style.visibility = "visible";
	if(document.getElementById("view-more")) document.getElementById("view-more").style.visibility = "visible";
	if(document.getElementById("marketing-area")) document.getElementById("marketing-area").style.visibility = "visible";


	$("#zoom-box").fadeOut("normal", function() {
		document.getElementById("zoom-image").style.zIndex = "-100";
		document.getElementById("zoom-box").style.zIndex = "-101";
		document.getElementById("zoom-box-overlay").style.zIndex = "-102";
	});
}

function initProductPage() {

	sHeight = 90;
	alsolikesHeight = 210;

	$("body").mousemove(function(event){
		mouseX = event.pageX;
		mouseY = event.pageY;
	});

	// elements = countElements("thumbnails-mask","img");
	// alsolikeelements = countElementslike("also-like-mask","a");

	// scrollHeight = sHeight * elements ;
	// alsolikescrollHeight = alsolikesHeight * alsolikeelements ;
	// document.getElementById("thumbnails-loop").style.top = scrollHeight+'px';

	smallWidth = 230;
	smallHeight = 345;

	//get the width and height of the zoom display area
	bigBoxWidth = document.getElementById('zoom-box').offsetWidth;
	bigBoxHeight = document.getElementById('zoom-box').offsetHeight;

	$("#up-arrow").click(moveThumbnailsLeft);
	$("#down-arrow").click(moveThumbnailsRight);
	/*you may also like*/
	$("#up-arrow-like").click(moveRecommendedLeft);
	$("#down-arrow-like").click(moveRecommendedRight);

	// zoom onload vars
	var oUpArrow = document.getElementById("up-arrow"),
		oDownArrow = document.getElementById("down-arrow"),
		oUpArrowlike = document.getElementById("up-arrow-like"),
		oDownArrowlike = document.getElementById("down-arrow-like");

	countsImages('thumbnails-mask');
	countsImageslike('also-like-mask');

	//show the zoom when we hover over the product image
	//document.getElementById('medium-image-container').onmouseover = showBig;

	//show the zoom when the product image is clicked
	document.getElementById('medium-image-container').onclick = showBig;
	document.getElementById('zoom-text').onclick = showBig;

	bigWidth = document.getElementById('zoom-image').offsetWidth;
	bigHeight = document.getElementById('zoom-image').offsetHeight;

	/*
		Set the height and width of the box which shows where you are
		zooming on the original normal sized product image. This box
		should be same size in relation to the normal product image
		as the zoom-box is to the extra large sized product image.
	*/

	zoomWindowBoxWidth = (zoomRatio * bigBoxWidth);
	zoomWindowBoxHeight = (zoomRatio * bigBoxHeight);

	document.getElementById('zoomWindowBox').style.width = zoomWindowBoxWidth + 'px';
	document.getElementById('zoomWindowBox').style.height = zoomWindowBoxHeight + 'px';

	$("#sizes").addClass("script-loaded");

		// survey init workaround
	try {
		attachRemoteScript();
	} catch(e){
		// do nothing
	}

}

function initReverse() {

	sHeight = 90;
	pastHeight = 300;

	$("#up-arrow").click(moveThumbnailsLeft);
	$("#down-arrow").click(moveThumbnailsRight);
	/*past sales*/
	$("#up-arrow-past").click(movePastLeft);
	$("#down-arrow-past").click(movePastRight);

	countsImages('thumbnails-mask');
	countsImagespast('past-flash-mask');

	$("#sizes").addClass("script-loaded");
}

function initGiveaway() {
	sHeight = 345;

	var eventLength = countsImages('coming-up-mask', 1);

	$("#up-arrow-coming-up").click(moveThumbnailsLeft);
	$("#down-arrow-coming-up").click(moveThumbnailsRight);
}

function initEventsPage() {
	eventsHeight = 270;
	pastHeight = 270;

	var eventLength = countsImagesevents('coming-up-mask');
	var pastLength = countsImagespast('past-flash-mask');

	if(eventLength > 3) {
		$("#up-arrow-coming-up").click(moveEventsLeft);
		$("#down-arrow-coming-up").click(moveEventsRight);
	}
	if(pastLength > 3) {
		$("#up-arrow-past").click(movePastLeft);
		$("#down-arrow-past").click(movePastRight);
	}

		// survey init workaround
	try {
		attachRemoteScript();
	} catch(e){
		// do nothing
	}

}

/* scroll thumbnails start */
function countsImages(element_id,visible) {
var numberOfItems = visible || numberOfItemsDisplayedBeforeScrolling;

	if (document.getElementById(element_id) != undefined) {
		images = document.getElementById(element_id).getElementsByTagName('IMG');

		bufferToLeft = 0;
		if (images.length > numberOfItems) {
			bufferToLeft = 1;
		}

		for ( var d = 0; d < images.length; d++) {
			thumbsPos.push(sHeight * (d - bufferToLeft));
			thumbsPosDown.unshift(sHeight * (d - 1));
			document.getElementById(images[d].id).style.left = thumbsPos[d] + 'px';
		}
	}
}
function countsImageslike(element_id) {
	/*carousel without a continuous scroll*/
	if (document.getElementById(element_id) != undefined) {
		divs = document.getElementById(element_id).getElementsByTagName('A');

		for ( var d = 0; d < divs.length; d++) {
			divthumbsPos.push(alsolikesHeight * d);
			divthumbsPosDown.unshift(alsolikesHeight * (d - 1));
			document.getElementById(divs[d].id).style.left = divthumbsPos[d] + 'px';
		}
	}
}

function countsImagesevents(element_id) {
	if(document.getElementById(element_id) != undefined) {
		var containerEl = document.getElementById(element_id);
		divs = containerEl.getElementsByTagName('DIV');

		bufferToLeft = 0;
		if (divs.length > 3) {
			bufferToLeft = 1;
		}
		for ( var d = 0; d < divs.length; d++) {
			divthumbsPos.push(eventsHeight * (d - bufferToLeft));
			divthumbsPosDown.unshift(eventsHeight * (d - 1));
			document.getElementById(divs[d].id).style.left = divthumbsPos[d] + 'px';
		}
		return divs.length;
	} else {
		return 0;
	}
}
function countsImagespast(element_id) {
	if(document.getElementById(element_id) != undefined) {
		pastdivs = document.getElementById(element_id).getElementsByTagName('DIV');

		bufferToLeft = 0;
		if (pastdivs.length > 3) {
			bufferToLeftPast = 1;
		}
		for ( var d = 0; d < pastdivs.length; d++) {
			divthumbsPosPast.push(pastHeight * (d - bufferToLeft));
			divthumbsPosDownPast.unshift(pastHeight * (d - 1));
			document.getElementById(pastdivs[d].id).style.left = divthumbsPosPast[d] + 'px';
		}
		return pastdivs.length;
	} else {
		return 0;
	}
}
// scroll functionality

/*
 * Responsible for moving the thumbnail viewing area to the left
 */
function moveThumbnailsLeft(e) {
	idc = moveLeft(idc, images, thumbsPos, sHeight);
}

/*
 * Responsible for moving the 'you may also like' viewing area to the left
 */
function moveRecommendedLeft(e) {
	/*continuousscroll set to false*/
	dividc = moveLeft(dividc, divs, divthumbsPos, alsolikesHeight, false);
}

/*
 * Responsible for moving the events viewing area to the left
 */
function moveEventsLeft(e) {
	dividc = moveLeft(dividc, divs, divthumbsPos, eventsHeight);
}
/*
 * Responsible for moving the events viewing area to the left
 */
function movePastLeft(e) {
	dividcPast = moveLeft(dividcPast, pastdivs, divthumbsPosPast, pastHeight);
}

/*
 * Responsible for moving the thumbnail viewing area to the Right
 */
function moveThumbnailsRight(e) {
	idc = moveRight(idc, images, thumbsPos, sHeight);
}

/*
 * Responsible for moving the 'you may also like' viewing area to the Right
 */
function moveRecommendedRight(e) {
	/*continuousscroll set to false*/
	dividc = moveRight(dividc, divs, divthumbsPos, alsolikesHeight, false);
}

/*
 * Responsible for moving the events viewing area to the left
 */
function moveEventsRight(e) {
	dividc = moveRight(dividc, divs, divthumbsPos, eventsHeight);
}

/*
 * Responsible for moving the 'you may also like' viewing area to the Right
 */
function movePastRight(e) {
	dividcPast = moveRight(dividcPast, pastdivs, divthumbsPosPast, pastHeight);
}


/*
 * Used by the for scrolling thumbnails, may also like items, etc
 * - Moves and animates the items
 */



function moveLeft(idxOfLeftItem, imageArray, posArray, spacing, continuousscroll) {

	/*arrow hidden when not in use and displayed when they're clickable*/
	if(idxOfLeftItem != imageArray.length - 1){
	$("#down-arrow-like").removeClass("disabled-arrow");
	}

	if(idxOfLeftItem == 1) {
	$("#up-arrow-like").addClass("disabled-arrow");
	}

	/*if the carousel shouldn't have a continuous scroll and the index of the left item is 0 don't move anything*/
	if(continuousscroll == false && idxOfLeftItem == 0){
			return idxOfLeftItem;
	}
	else{
		idxOfLeftItem--;
		if (idxOfLeftItem < 0) {
			idxOfLeftItem = imageArray.length - 1;
		}

		// remove the first element
		var tempPoss = posArray.shift();
		// add the element to the end of the array
		posArray.push(tempPoss);

		// moves this element off the screen
		//**if image is still in view then it will disapear and not animate off to the right**
		document.getElementById(imageArray[idxOfLeftItem].id).style.left = -spacing + 'px';

		var moves = [];

		for (d = 0; d < imageArray.length; d++) {
			$(imageArray[d]).animate({
				left: posArray[d]
			}, 350);
		}
		return idxOfLeftItem;
	}
}

function moveRight(idxOfLeftItem, imageArray, posArray, spacing, continuousscroll) {
	/*if the carousel shouldn't have a continuous scroll and the index of the left item is the number of images - the amount of images visible(4) don't move anything*/
imageAmount = imageArray.length - 1;

lastimage = imageArray.length - 4;

/*arrow hidden when not in use and displayed when they're clickable*/
$("#up-arrow-like").removeClass("disabled-arrow");

if(idxOfLeftItem == lastimage - 1){
$("#down-arrow-like").addClass("disabled-arrow");
}

if(continuousscroll == false && idxOfLeftItem == lastimage){
	return idxOfLeftItem;
}
else{
	// current left item will move to the far right
	if (document.getElementById(imageArray[idxOfLeftItem].id).offsetTop < spacing) {
		document.getElementById(imageArray[idxOfLeftItem].id).style.left = (imageAmount * spacing) + 'px';
	}

	// shift the counter
	if (idxOfLeftItem < (imageArray.length - 1)) {
		idxOfLeftItem++;
	} else {
		idxOfLeftItem = 0;
	}

	//take last item off
	var tempPos = posArray.pop();
	//put last item on the front
	posArray.unshift(tempPos);

	var moves = [];

	for ( var d = 0; d < imageArray.length; d++) {
		$(imageArray[d]).animate({
			left: posArray[d]
		}, 350);
	}
	return idxOfLeftItem;
}
}


/* zoom */

function clearIntrv() {
	clearTimeout(hideInterval);
}

function hideBig() {
	hideInterval = setTimeout("hideDelay()", 180);
}

// zoom function
function animateBigImage() {
	var xPos =  mouseX,
		yPos =  mouseY,
		bigXPos = $("#zoom-image").offset().left,
		bigYPos = $("#zoom-image").offset().top;

	//X and Y coordinates of the normal sized product image
	//from the page corner
	var largeXOffset = $("#medium-image-container").offset().left,
		largeYOffset = $("#medium-image-container").offset().top;

	var mediumImageWidth = document.getElementById("medium-image-container").offsetWidth,
    	mediumImageHeight = document.getElementById("medium-image-container").offsetHeight;

    /*
     * Work out if the cursor is within some custom bounds of the product image. If it is, then
     * stop animating.
     */
    var offsetXMargin = 50,
		offsetYMargin = 30;

    if(xPos < (largeXOffset - offsetXMargin) ||
       xPos > (largeXOffset + mediumImageWidth + offsetXMargin) ||
       yPos < (largeYOffset - offsetYMargin) ||
       yPos > (largeYOffset + mediumImageHeight + offsetYMargin))
    {
        hideBig();
        return;
    }

    factorX = (bigWidth-bigBoxWidth)/smallWidth;
    factorY = (bigHeight-bigBoxHeight)/smallHeight;

    var targetX = 0 - (factorX * (xPos-largeXOffset)),
    	targetY = 0 - (factorY * (yPos-largeYOffset));

    targetX = Math.round(targetX);
    targetY = Math.round(targetY);

    bigX +=  ((targetX-bigX)*easing);
    bigY +=  ((targetY-bigY)*easing);

    bigY = Math.round(bigY);
    bigX = Math.round(bigX);

    document.getElementById("zoom-image").style.left  = bigX + "px";
    document.getElementById("zoom-image").style.top = bigY + "px";
    // 	var moveImage = new YAHOO.util.Anim('zoom-image', {top:{to:bigY}, left:{to:bigX}}, 0.25 ,YAHOO.util.Easing.easeOut);
    // 	moveImage.animate();

    // Work out where zoom-box is in relation to the extra large zoom image.
    // Apply the zoom ratio to work out where our small box which shows where
    // you are zooming should be located in relation to the normal sized product image
    var windowBoxXOffset = bigX * -1 * zoomRatio;
    var windowBoxYOffset = bigY * -1 * zoomRatio;

    // Make sure our X and Y coordinates are integers.
    windowBoxXOffset = Math.round(windowBoxXOffset);
    windowBoxYOffset = Math.round(windowBoxYOffset);

    // Set the coordinates for the small box which shows where
    // you are zooming
    document.getElementById("zoomWindowBox").style.left  = windowBoxXOffset + "px";
    document.getElementById("zoomWindowBox").style.top  = windowBoxYOffset + "px";
}

function prepViewLargeImageLink(product_id, img, cache_url, channel) {
	var fullsize_link = document.getElementById("full-size-image-link");
	if (fullsize_link != null) {
		fullsize_link.onclick = function() {

			message = "<iframe class='overlay-iframe' src='/" + channel + "/ViewFullSizeImage.ice?productID=" + product_id + "&currentImage=" + img + "' height='835px' width='99%' border='0' frameborder='no' marginWidth='1' marginHeight='1'></iframe>";

			NAP.overlayPanel({
				title: "Full Size Product Image",
				top: 5,
				height: 860,
				width: 550,
				theme: "dark",
				message: message,
				addClass: "product-image-overlay"
			});
		};
	}
}

function loadBig(img, prodId, channel, cache_url, element) {
	prepViewLargeImageLink(prodId, img, cache_url, channel);
    loadZoomImage(img,prodId, cache_url);
    document.getElementById("medium-image").src = cache_url + "/images/products/" + prodId + "/" + img + "_l.jpg";

    var thumbnails = document.getElementById("thumbnails-container").getElementsByTagName("IMG"),
		element = element || {};

    for(var i=0; i < thumbnails.length; i++) {
        var thisEl = thumbnails[i],
                thisSrc = thisEl.src;

        if(thisEl.id == element.id) {
			if(thisEl.runtimeStyle != undefined && thisEl.runtimeStyle.filter != "") {
				thisEl.runtimeStyle.filter = thisEl.runtimeStyle.filter.replace(/_greybg_/i,"_grey_");
			} else {
                thisSrc = thisSrc.replace(/_greybg_/i,"_grey_");
				thisEl.src = thisSrc;
            }
			if(thumbnails.length > numberOfItemsDisplayedBeforeScrolling) {
				if(thumbsPos[i] != 0) {
					moveThumbnailsRight();
				} else {
					moveThumbnailsLeft();
				}
			}
        } else {
            if(thisEl.runtimeStyle != undefined && thisEl.runtimeStyle.filter != "") {
				thisEl.runtimeStyle.filter = thisEl.runtimeStyle.filter.replace(/_grey_/i,"_greybg_");
			} else {
				thisSrc = thisSrc.replace(/_grey_/i,"_greybg_");
                thisEl.src = thisSrc;
			}
        }
    }
}

function loadZoomImage(img, prodId, cache_url) {
    var zoomImage = document.getElementById("zoom-image"),
        imgSplit = img.split("_revauc");

    img = imgSplit[0];

    if(zoomImage) {
        zoomImage.src = cache_url + "/images/products/"
                + prodId + "/" + img + "_xl.jpg";
    }
}

function hideDelay() {
    zoomImg = document.getElementById("zoomWindowBox");
    if (zoomImg.style.visibility != "hidden") {
        clearInterval(zoomInterval);

        document.getElementById("zoom-text").innerHTML = "Click to zoom";
        document.getElementById("zoomWindowBox").style.visibility = "hidden";

        //fadeOut.animate();
		doFadeOut();
    }
}

function hideBigBox() {
	document.getElementById("zoom-image").style.visibility = "hidden";
}

// show zoom image
function showBig() {
	clearIntrv();
	if(document.getElementById("zoomWindowBox").style.visibility != "visible") {
		document.getElementById("zoom-image").style.visibility = "visible";
		document.getElementById("zoom-box").style.visibility = "visible";
		//fadeIn.animate();
		doFadeIn();
		document.getElementById("zoom-text").innerHTML = "Roll off to exit";
		document.getElementById("zoomWindowBox").style.visibility = "visible";

		largeImageShown = true;

		zoomInterval = setInterval(animateBigImage, 10);
	}
}

/* product page */
function choosesize() {
	var sizelist = document.getElementsByName("sku");
	for ( var i = 0; i < sizelist.length; i++) {
		var labelid = sizelist[i].value;
		if (sizelist[i].checked == true) {
			document.getElementById(labelid + "label").className = "selected";
		} else if (sizelist[i].checked == false) {
			document.getElementById(labelid + "label").className = "";
		}
	}
}

function rollover(borderId, borderClass) {
	document.getElementById(borderId).className = borderClass;
}

function rolloverme(thisarrow, currentstate) {
	if (currentstate == "off") {
		thisarrow.src = thisarrow.src.replace(/_off\./, "_on.");
	} else {
		thisarrow.src = thisarrow.src.replace(/_on\./, "_off.");
	}
}

function changetabs(tabButtonId, tabButtonsParentId) {
     $('#' + tabButtonsParentId).children().each(function() {
        var thisTabButton = $(this);
        var thisTabButtonId = thisTabButton.attr("id");
        var thisTabContent = $("#" + thisTabButtonId.replace("-tab", ""));

        if(thisTabButtonId == tabButtonId) {
            thisTabButton.addClass("selected");
            thisTabContent.css("display", "block");
        } else {
            thisTabButton.removeClass("selected");
            thisTabContent.css("display", "none");
        }
    });
}

sfHover = function() {
	var containerEl = document.getElementById("nav");
	if(containerEl != undefined) {
		var sfEls = containerEl.getElementsByTagName("LI");
		for ( var i = 0; i < sfEls.length; i++) {
			sfEls[i].onmouseover = function() {
				this.className += (this.className.length > 0 ? " " : "")
						+ "sfhover";
			};
			sfEls[i].onmouseout = function() {
				this.className = this.className.replace(new RegExp(
						"( ?|^)sfhover\\b"), "");
			};
		}
	}
};
mcAccessible = function() {
	var containerEl = document.getElementById("nav");
	if(containerEl != undefined) {
		var mcEls = document.getElementById("nav").getElementsByTagName("A");
		for ( var i = 0; i < mcEls.length; i++) {
			mcEls[i].onfocus = function() {
				this.className += (this.className.length > 0 ? " " : "")
						+ "sffocus"; // a:focus
				this.parentNode.className += (this.parentNode.className.length > 0 ? " "
						: "")
						+ "sfhover"; // li < a:focus
				if (this.parentNode.parentNode.parentNode.nodeName == "LI") {
					this.parentNode.parentNode.parentNode.className += (this.parentNode.parentNode.parentNode.className.length > 0 ? " "
							: "")
							+ "sfhover"; // li < ul < li < a:focus
					if (this.parentNode.parentNode.parentNode.parentNode.parentNode.nodeName == "LI") {
						this.parentNode.parentNode.parentNode.parentNode.parentNode.className += (this.parentNode.parentNode.parentNode.parentNode.parentNode.className.length > 0 ? " "
								: "")
								+ "sfhover"; // li < ul < li < ul < li < a:focus
					}
				}
			};
			mcEls[i].onblur = function() {
				this.className = this.className.replace(new RegExp(
						"( ?|^)sffocus\\b"), "");
				this.parentNode.className = this.parentNode.className.replace(
						new RegExp("( ?|^)sfhover\\b"), "");
				if (this.parentNode.parentNode.parentNode.nodeName == "LI") {
					this.parentNode.parentNode.parentNode.className = this.parentNode.parentNode.parentNode.className
							.replace(new RegExp("( ?|^)sfhover\\b"), "");
					if (this.parentNode.parentNode.parentNode.parentNode.parentNode.nodeName == "LI") {
						this.parentNode.parentNode.parentNode.parentNode.parentNode.className = this.parentNode.parentNode.parentNode.parentNode.parentNode.className
								.replace(new RegExp("( ?|^)sfhover\\b"), "");
					}
				}
			};
		}
	}
};

// only ie needs the sfHover script. all need the accessibility script...
// thanks http://www.brothercake.com/site/resources/outnet/styles/onload/

if (window.addEventListener) {
	window.addEventListener("load", mcAccessible, false); // gecko, safari, konqueror and standard
} else if (document.addEventListener) {
	document.addEventListener("load", mcAccessible, false); // opera 7
} else if (window.attachEvent) { // win/ie
	window.attachEvent("onload", sfHover);
	window.attachEvent("onload", mcAccessible);
} else { // mac/ie5
	if (typeof window.onload == "function") {
		var existing = onload;
		window.onload = function() {
			existing();
			sfHover();
			mcAccessible();
		};
	} else {
		window.onload = function() {
			sfHover();
			mcAccessible();
		};
	}
}

/**
 * Useful function for processing query parameters
 */

function getParameterValue(parameterName) {
	var queryString = window.location.search.substring(1);
	var parameters = [];
	parameters = queryString.split('&');
	for ( var i = 0; i < parameters.length; i++) {
		if (parameters[i].indexOf(parameterName) >= 0) {
			var parameterValue = [];
			parameterValue = parameters[i].split('=');
			return parameterValue[1];
		}
	}
	return "";
}

/**
 * Javascript for the productlisting pages (filters, etc)
 */

function ToggleFilter(newUrl) {
	window.location = newUrl;
}

/*rotating banner on sitemap */
var action_re = /([^\/]+).gif$/;

function questionAction() {
    var currenttext =  document.getElementById("questionAction").innerHTML; /*source of image*/
	help(actionList[currenttext].loc);
}

function switchquestions() {
	var currenttext =  document.getElementById("questionAction").innerHTML; /*source of image*/
	var nextBannerIdx = (actionList[currenttext].idx +1) % actionList.length;
	 document.getElementById("questionAction").innerHTML = actionList[nextBannerIdx];
}

function setfaqs() {
    document.getElementById("questionAction").innerHTML = actionList[0];
}

/*script to make iframe resizable - called on loading iframe*/
function resizeIframe(iframeName) {
	var iframe = document.getElementById(iframeName);

    // FF
    if (iframe.contentDocument) {
   		iframe.style.height = iframe.contentDocument.height + "px";
   		}

    // IE7
    if (iframe.contentWindow.document.body) {
        iframe.style.height = iframe.contentWindow.document.body.scrollHeight + "px";
    }
}

function validateEmail() {
    if(!isGoodEmail(document.emailreg.email.value, false)) {
		alert("Please make sure that you\ninput a valid e-mail address");
		document.emailreg.email.focus();
		return false;
    }
    return true;
}

function isGoodEmail(emailStr, thankyouflag) {
    if (thankyouflag == null) {
            thankyouflag=true;
    }
    var emailPat=/^(.+)@(.+)$/;
    var specialChars="\\(\\)<>@,;:\!\\\\\\\"\\.\\[\\]";
    var validChars="\[^\\s" + specialChars + "\]";
    var firstChars=validChars;
    var quotedUser="(\"[^\"]*\")";
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom="(" + firstChars + validChars + "*" + ")";
    var word="(" + atom + "|" + quotedUser + ")";
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
    var matchArray=emailStr.match(emailPat);
    if (matchArray==null) {
            return false;
    }
    var user=matchArray[1];
    var domain=matchArray[2];

    // See if "user" is valid
    if (user.match(userPat)==null) {
            return false;
    }
    var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null) {
            // this is an IP address
            for (var i=1;i<=4;i++) {
				if(IPArray[i]>255) {
						return false;
				}
            }
            return true;
    }

    // Domain is symbolic name
    var domainArray=domain.match(domainPat);
    if (domainArray==null) {
            return false;
    }
    var atomPat=new RegExp(atom,"g");
    var domArr=domain.match(atomPat);
    var len=domArr.length;
    if(domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) {
       // the address must end in a two letter or three letter word.
       return false;
    }
    if (domArr[domArr.length-1].length==3 && len<2) {
       return false;
    }

    // default behavior - keep existing uses continue to work
    if(thankyouflag) {
    // Everything's valid:
       window.open("Thank You", "newFormWindow", "width=340,height=260");
    }
    return true;
}

function launchGenericPopUp(winName, url, w, h, incScroll) {

    // url#name  > url?exclude=T#name
    if (url!=null) {
        var tmp = url.split('#');
        url = tmp[0];
        url += url.indexOf('?') == -1 ? '?' : '&';
        url += 'exclude=T';
        if (tmp.length>1) {
            url += '#' + tmp[1];
        }
    }

	var newWindow = window.open(url, '_blank', 'width='+w+',height='+h+',menubar=no,location=no,resizable=1,status=no,scrollbars='+incScroll);
	if (window.focus) {
		newWindow.focus();
	}
}

//The following are wrappers to the above launchGenericPopUp.
//launchGenericPopup isn't called directly and is instead
//called via one of the following 4 methods.

function launchPopUp(name, url, w, h) {
	launchGenericPopUp(name, url, w, h, 1);
}

function launchPopUpNoScroll(name, url, w, h) {
	launchGenericPopUp(name, url, w, h, 0);
}

/**
 * Used by SizeChart duplicated in NAP global.js
 */
function showtab(tabname, pagename) {
    $(".tabButton").removeClass("selected");
    $(".tabBody").hide();

    //set target tab as selected
    $("#" + tabname).addClass("selected");

    // Show the selected tab
    $("#" + pagename).show();
}

function clearDefaultSearch(el) {
    if (el.defaultValue == el.value) el.value = "";
}

function logout() {
    document.logOutForm.submit();
}

function checkSearchForm(f) {
    if (!f.keywords.value) {
        return false;
    }
    return true;
}

function help(url,w,h) {
	var popupWidth = (w == undefined) ? 750 : w ;
	var popupHeight = (h == undefined) ? 580 : h ;
	if (url) {
		launchPopUp('Help', url, popupWidth, popupHeight);
	}
}

function clearDefault(el) {
  if (el.defaultValue==el.value) el.value = "";
}

//Convert Sizes (product details radio buttons)
function convertSizes(theseSizes, otherSizes, currenltyShowingOriginalSizes) {
    var sizesUl = document.getElementById("sizes");
    var sizeRadioButtons = sizesUl.getElementsByTagName("LI");

    for (var i=0; i<sizeRadioButtons.length; i++) {
        if ( otherSizes[i] != '') {
            var thisSizeLi = sizeRadioButtons[i];
            var thisSizeRadioLabel = thisSizeLi.getElementsByTagName('LABEL')[0];
            var thisSizeRadioText = otherSizes[i];

            thisSizeRadioLabel.innerHTML = '<span>' + thisSizeRadioText + '</span>'
        }
    }

    var sizeAnchor = document.getElementById('convert-size-link');
    //If we are currenltyShowingOriginalSizes, we are now changing to show US sizes, so update
    //the link to allow the user to change back to original sizing
    var sizeAnchorText = 'Show ' + (currenltyShowingOriginalSizes? 'original': 'US') + ' sizes';

    sizeAnchor.innerHTML = sizeAnchorText;
    sizeAnchor.onclick = function() { return convertSizes(otherSizes, theseSizes, !currenltyShowingOriginalSizes); }

    //We don't want to use the anchors href if the user has javascript enabled.
    return false;
}

function rollOverImage(imageElem, cache_image_url, event) {
	var e = window.event || event;

	function changeImageOver() {
		imageElem.src = cache_image_url;
	}

	function changeImageOut() {
		imageElem.src = cache_image_url;
	}

	if(imageElem) {
		if(e.type == "mouseover") {
			imageTimeout = setTimeout(changeImageOver, 200);
		} else if(e.type == "mouseout") {
			clearTimeout(imageTimeout);
			changeImageOut();
		}
	}
}

function setPopupHeight(pixels) {
	if( typeof( window.innerWidth ) == "number" ) {
		//Non-IE
		window.innerHeight = pixels;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		document.documentElement.clientHeight = pixels;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		document.body.clientHeight = pixels;
	}
}

function reloadPopupParentWindow() {
    window.opener.top.location.reload();
}

/*

Paul Le paul.le@net-a-porter.com
Drop down menu for top nav

*/

$(document).ready(function() {

	var showTimeout,
		hideTimeout;

	$("li.main-menu div").hide();

	$("li.main-menu").hover(function(e) {

		var that = $(this);

		clearTimeout(hideTimeout);

		showTimeout = setTimeout(function () {
			$("li.main-menu div").hide();
			$("li.main-menu").removeClass("hovered");

			var menuID = that.find("a").html();
			if (menuID) menuID = menuID.toLowerCase()+"-menu";
			menuID = menuID.replace(/ /, "-");

			$("#"+menuID).show();

			that.addClass("hovered");

		}, 300);

	}, function(e) {

		hideTimeout = setTimeout(function () {
			$("li.main-menu div").hide();
			$("li.main-menu").removeClass("hovered");

		}, 300);

		clearTimeout(showTimeout);
	});
});