window.addEvent('domready', function() {								 
									 
	var checkForDivOn = document.getElementById('checkall');
	var checkForDivOff = document.getElementById('clearall');
	var checkAddressOption = document.getElementById('savedAdds');
	var checkForLogin = document.getElementById('pwordStrengthIndicator')
	
	showArrows();
	
	if ( (checkForDivOn != null) && (checkForDivOff != null) ) {
		swapLinks('clearall','checkall');
	}
	if (checkAddressOption == null) {
		var getButton = document.getElementById('selAltAdd');
		if (getButton != null) {
			getButton.style.display = "none";
		}
	} else {
		checkIfSelected();
	}
	if (checkForLogin != null) {
		checkForLogin.style.display = "block";	
		passwordTest();
	}
});

// Function to create an array of all elements with a specific tag and class name
function getElementsByClassName(oElm, strTagName, strClassName) {
	var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++) {
        oElement = arrElements[i];
        if(oRegExp.test(oElement.className)) {
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

// Function to get a list of all divs with the class 'arrows' and to change the
// style to display the div.
function showArrows() {
	var getArrows = getElementsByClassName(document,'div','arrows');
	for (var i = 0; i < getArrows.length; i++) {
		getArrows[i].style.display = 'block';
		// tests to see if corresponding input is >1 and changes down arrow if true
		arrowInput = getArrows[i].className.replace("arrows ", "");
		if (arrowInput) {
			if (document.getElementById(arrowInput) && document.getElementById(arrowInput).value > 1) {
				inputName = "downArrow" + getArrows[i].className.replace("arrows qty", "");
				document.getElementById(inputName).src="/scholl/images/arrow-dn-on.png";
			}
		}
	}
}

// search button hover effect - non-essential to functionality so it's in js
function searchButtonSwitch() {
	if (searchButton = document.getElementById('search_search')) {
		searchButton.onmouseover = function() { this.src = "/scholl/images/buttons/search-icon-over.png"; }
		searchButton.onmouseout = function() { this.src = "/scholl/images/buttons/search-icon.png"; }
	}
}

// Up and Down arrows
function adjustQty(qtyId,dir,arrowId){
	//alert(qtyId);
	var inputValue = document.getElementById(qtyId).value;
	
	if (dir == 'down') {
		if(document.getElementById(qtyId).value - 1 < 1 ) {
			return;
		} else {
			 document.getElementById(qtyId).value--;
			 if (document.getElementById(qtyId).value ==1 ) {
				document.getElementById(arrowId).src="/scholl/images/arrow-dn-off.png";
				return;
			}
			return;
		}
	} else { //dir = up
		document.getElementById(qtyId).value++;
		document.getElementById(arrowId).src="/scholl/images/arrow-dn-on.png";
		return;
	}
}

// Function to check that the quantity field contains a valid number
function checkVal(qtyId,arrowId){
	var qtyField = document.getElementById(qtyId);
    if ((isNaN(qtyField.value) || qtyField.value == "")) {
	   	//alert("Please enter a valid number in the quantity box");
	   	qtyField.value = 1;
		document.getElementById(arrowId).src="/scholl/images/arrow-dn-off.png";
	   	qtyField.focus();
	  	return false;
	}	
}

// Functions to manipulate checkboxes on Merchandised List page
function checkFormBox() {
	var e = document.AddToBasketMerchandisedList;
	for (var i = 0; i < e.length; i++) {  
		if (e[i].type == "checkbox") {
       		if (!e[i].checked) {
            	e[i].checked = true;
            }
		}
    }
}

function clearFormBox() {
	var e = document.AddToBasketMerchandisedList;
	for (var i = 0; i < e.length; i++) {
		if (e[i].type == "checkbox") {
        	if (e[i].checked) {
            	e[i].checked = false;
            }
        }
    }
}
function swapLinks(id_off, id_on) {
	var getLinkOff = document.getElementById(id_off);
	var getLinkOn = document.getElementById(id_on);
    getLinkOff.style.display = "none";
    getLinkOn.style.display = "block";
	return;
}

function checkLink() {
	var getLinkDiv = document.getElementById("checkall");
   	if (getLinkDiv.style.display == "none") {
      swapLinks('clearall','checkall');
    }
}

function submitPaymentForm() {
	if(document.getElementById('paymentForm')) {
		document.getElementById('paymentForm').submit();
	}
}

function initNoPaymentRequiredForm() {
	if(document.getElementById('noPaymentRequiredForm')) {
		deactivateAllFields();
	}
}

function checkIfSelected() {
	var getBttns = document.getElementById("savedAdds");
	var getRadio = getBttns.getElementsByTagName('input');
	
	for (var i = 0; i < getRadio.length; i++) {	
		if (getRadio[i].checked) {
			hideAddressFields();
			break;
		}
	}
}

	
function passwordTest() {
	var passwordMsg = document.getElementById("passwordStrength");
	if (passwordInput = document.getElementById("registrationInfo.password").value) {		
		// reset variables
		lengthScore = 0;
		typeScore = 0;

		// test for length
		if (passwordInput.length < 6) { lengthScore = 0; }
		else if (passwordInput.length < 8) { lengthScore = 1; }
		else if (passwordInput.length > 7) { lengthScore = 2; }

		// test for content
		// passwordInput.match(/[a-z]/) passwordInput.match(/[A-Z]/) passwordInput.match(/\d+/) passwordInput.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)
		if (passwordInput.match(/[a-z]/)) { typeScore += 1; }
		if (passwordInput.match(/[A-Z]/)) { typeScore += 1; }
		if (passwordInput.match(/\d+/)) { typeScore += 1; }
		if (passwordInput.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)) { typeScore += 1; }
		// set classes/text from score
		switch (lengthScore) {
			case 1:
				if (typeScore > 1) { passwordMsg.className = "strength2"; }
				break;
			case 2:
				if (typeScore > 2) { passwordMsg.className = "strength3"; }
				else if (typeScore > 1) { passwordMsg.className = "strength2"; }
				break;
			default:
				passwordMsg.className = "strength1";
		}
	} else { passwordMsg.className = ""; }
}


function blockMultipleClicks(form) {
	if (form.getAttribute('submitted')) { return false; }
	form.setAttribute('submitted','true');
}

// Tooltips
window.addEvent('domready', function(){
	var tips = $$('a.tooltip-1', 'a.tooltip-2', 'a.tooltip-3');
	tips.each(function(tipLink) {

		// Cancel the title display
		tipLink.title = "";
		
		var tip = $(tipLink.className);

		// Get Y position
		var tipLinkY = tipLink.getPosition($('pageWrapper')).y;
		var tipY = tipLinkY - tip.getSize().y;
		
		// Get X position
		var tipLinkX = tipLink.getPosition($('pageWrapper')).x;
		var tipLinkMid = tipLinkX + tipLink.getSize().x / 2;
		var tipX = tipLinkMid - $(tipLink.className).getSize().x / 2;
		
		//IE6 Iframe fix for the 2nd link
		if(Browser.Engine.trident4 && tip.id == "tooltip-2") {
			var tipIFrame = new Element('iframe', {'class':'tipIFrame', 'src':'Javascript:(\'#\')', 'styles': {
					'width' : tip.getSize().x,
					'height' : tip.getSize().y
				}
			});
			tipIFrame.inject(tip, 'bottom');
			tipLink.store('tipIFrame',tipIFrame);
		}
		
		tipLink.store('tipRef', $(tipLink.className));

		tipLink.addEvents({
			'mouseover' : function(){
				this.retrieve('tipRef').setStyles({'top' : tipY,'left' : tipX});
			},
			'mouseout' : function(){ 
				this.retrieve('tipRef').setStyles({ 'top' : -9999,'left' : -9999});
			}
		});
	 });

});

window.addEvent('domready', searchButtonSwitch);
window.addEvent('domready', submitPaymentForm);
window.addEvent('domready', initNoPaymentRequiredForm);

// show/hide left nav
function addToggle() {
	if (nav = $("secondNav")) {
		navItems = nav.getElementsByTagName("dl")
		for (i=0; i<navItems.length; i++) {
			if (navItems[i].className == "showHide") {
				subcats = navItems[i].getElementsByTagName("dd");
				if (subcats.length > 3) {
					// hide list items
					for (j=3; j<subcats.length; j++) { subcats[j].style.display = "none"; }

					// add toggle link
					navItems[i].id = "navItem_" + i;
					moreLink = document.createElement("dd");
					moreLink.innerHTML = "<a href='#' onclick='showNav(\"navItem_" + i + "\"); return false;'>More ></a>";
					navItems[i].appendChild(moreLink);
				}
			}
		}
	}
}

function showNav(list) {
	navToShow = $(list);
	navToShow.lastChild.innerHTML = "<a href='#' onclick='hideNav(\"" + list + "\"); return false;'>< Less</a>"

	subcats = navToShow.getElementsByTagName("dd");
	for (i=3; i<subcats.length; i++) { subcats[i].style.display = "block"; }
}

function hideNav(list) {
	navToShow = $(list);
	navToShow.lastChild.innerHTML = "<a href='#' onclick='showNav(\"" + list + "\"); return false;'>More ></a>"

	subcats = navToShow.getElementsByTagName("dd");
	for (i=3; i<subcats.length-1; i++) { subcats[i].style.display = "none"; }
}

//window.addEvent('domready', addToggle);

// product image switcher
var pos = 0; // tracks rel image selection for zoom viewer
function imageViewer() {
	if (thumbsBlock = document.getElementById("productThumbs")) {
		thumbs = thumbsBlock.getElementsByTagName('a');
		for (i=0; i<thumbs.length; i++) {
			if (thumbs[i].className == "thumbImage") {
				thumbs[i].onclick = function() {
					if ($('mediaWrapper')) {
						$('mediaWrapper').style.top = "-1000em";
						$('mediaWrapper').style.left = "-1000em";
					}
					$('primaryImage').src = this.href;
					
					//deal with stripping the thumbnail alt text and
					//applying it to the primary image
					var thumbnailTitle = this.title;
					var endOfThumbnailSpecificAltText = (thumbnailTitle.indexOf(':')+1);
					thumbnailTitle = thumbnailTitle.substr(endOfThumbnailSpecificAltText);
					$('primaryImage').title = thumbnailTitle;
					
					$('primaryImage').style.display = "block";

					relImgs = $$("#productThumbs a");
					pos = relImgs.indexOf(this);

					return false;
				};
			} else if (thumbs[i].className == "thumbMedia") {
				thumbs[i].onclick = function() {
					$('primaryImage').style.display = "none";
					$('mediaWrapper').src = this.href;
					$('mediaWrapper').style.top = "0";
					$('mediaWrapper').style.left = "0";
					return false;
				};
			}
		}
	}
}

window.addEvent('domready', imageViewer);

// variant prod selection switcher
function variantSwitch() {
	if (productSelect = $$("select.productVariant")) {
		for (i=0; i<productSelect.length; i++) {
			productSelect[i].onchange = function() { this.form.action += '#bundles'; this.form.submit(); }
		}
	}
}
//variant prod selection switcher which is used in onchange event
//rename the css class to "productVariantManual" to avoid conflicts with variantSwitch()
function variantSwitchManual(oform,productid, actionName) {
	if(!actionName) { oform.action += '#bundles' + productid; }
	else { oform.action = actionName + '#bundles' + productid; }
	oform.submit();
}
window.addEvent('domready', variantSwitch);

// image zoom viewer
var containerWidth;

function addZoomLink() {

	// add overlay bg to end of page.
	// This is outside of the condition so review guidelines can use it too. Needs to be genericised.
	var imageZoomOverlayBg = new Element('div', {
		'id': 'imageZoomOverlay',
		'style': 'display: none; width:' + $(document).getScrollSize().x + 'px; height: ' + $(document).getScrollSize().y + 'px;',
		'html': '<iframe style="width: ' + $(document).getScrollSize().x + 'px; height: ' + $(document).getScrollSize().y + 'px;" ></iframe>'
	}).inject($(document.body)).setStyle('opacity', 0);

	if (typeof zoomEnabled != 'undefined' && zoomEnabled) {
		// add "zoom" link to main image
		var zoomLink = new Element('p', {'html': '<a href="#" onclick="launchZoom(); return false;">' + zoomButtonText.zoomBtn + '</a>'}).inject($$("div.productImage")[0]);
		
		// Make the image clickable to launch the zoom
		$("primaryImage").setProperty("title", zoomButtonText.imgZoomLink + " " + $("primaryImage").getProperty("title")).setStyle("cursor","pointer").addEvent("click", function(){ launchZoom(); });
		
		// add overlay contents after bg
		var imageZoomOverlay = new Element('div', {
			'id': 'imageZoomWindow',
			'html': '<p class="closeButton"><a href="#" onclick="hideZoom(); return false;">' + zoomButtonText.closeBtn + '</a></p><div class="zoomedImage"><img id="zoomedImage" src="" alt="" /></div><p id="status"></p>'
		}).inject($(document.body)).setStyle('opacity', 0);

		// clone the related images and add to the window
		var relatedImages = $("productThumbs").clone().inject($("imageZoomWindow")).set('id', 'zoomRelatedImages');

		// turn on the quick image swap
		swapZoomedImage();
	};
}

function launchZoom() {
	
	// Set the coorindates so the window is in the centre of the viewport
	// Briefly set the zoomed window style to block, so we can get the dimensions
	var zHeight = $("imageZoomWindow").setStyle('display', 'block').getSize().y; // Zoomed Window height
	var vpHeight = $(window).getSize().y; // Viewport height
	var scrHeight = $(window).getScroll().y; // Window scroll size

	// Calulcate the top position.
	// If rendering on a small screen, ie. height of zoomed window >= height of viewport, set top to scroll height.
	var yPos = (zHeight >= vpHeight) ? scrHeight : Math.round((vpHeight/2 - zHeight/2) + scrHeight);

	// show overlay and window
	$("imageZoomOverlay").setStyle('display', 'block').fade([0.6, 0]);
	$("imageZoomWindow").setStyle('top', yPos).fade(1);

	// set main image in zoom to primary image adn modify width to container
	containerWidth = $$(".zoomedImage")[0].getStyle('width').toInt();
	$("zoomedImage").set('src', imageLinks[pos]).setStyle('width', containerWidth);

	// set offsets to work out the 0,0 of the container
	leftOffset = $$(".zoomedImage")[0].getPosition().x;
	topOffset = $$(".zoomedImage")[0].getPosition().y;

	// set offset level relative to hmc defined zoom level
	if (zoomLevel == null || zoomLevel < 2) { zoomLevel = 2; }
	var offsetLevel = zoomLevel - 1;

	$$(".zoomedImage")[0].addEvent('mousemove', function(e) {
		//$("status").set('html', $$(".zoomedImage")[0].getScrollSize().x);
		$("zoomedImage").setStyles({
			top: -(e.page.y - topOffset) * offsetLevel,
			left: -(e.page.x - leftOffset) * offsetLevel
		});
	}).addEvent('mouseenter', function() {
		// show larger image in place of small
		$("zoomedImage").setStyle('width', containerWidth * zoomLevel);
	}).addEvent('mouseleave', function() {
		// change image back to normal size on mouseout
		// need to change position to be top left again
		$("zoomedImage").setStyles({
			top: 0,
			left: 0,
			width: containerWidth
		});
	});
}

function hideZoom() {
	// hide overlay and window
	$("imageZoomWindow").fade(0);
	$("imageZoomOverlay").fade(0);
}

function swapZoomedImage() {
	$$("#zoomRelatedImages a").each(function(item, index) {
		// set each href to the extraLargeImage
		item.href = imageLinks[index];

		// set each onclick to swap the main image
		item.addEvent('click', function() {
			$("zoomedImage").set('src', item.href);
			return false;
		});
	});
}

window.addEvent('domready', addZoomLink)

// open review guidlines overlay
function initRevGuidlines() {
	if ($("reviewGuidelines")) {
		// clone guidlines, remove the original and add to the end of the page
		var guidlinesCopy = $("reviewGuidelines").clone().set('id', 'reviewGuidelines').setStyle('opacity', 0);
		$("reviewGuidelines").dispose();
		guidlinesCopy.inject($(document.body));
	}
}

function openRevGuidlines() {
	// show overlay and window
	$("imageZoomOverlay").setStyle('display', 'block').fade([0.6, 0]);
	$("reviewGuidelines").setStyle('display', 'block').fade(1);
	$(document.body).scrollTo(0,0);
}

function hideRevGuidlines() {
	// hide overlay and window
	$("reviewGuidelines").fade(0);
	$("imageZoomOverlay").fade(0);
}

window.addEvent('domready', initRevGuidlines)