//======================================================
//Support Presentation JavaScript
//Copyright (c) 2007 Daniel Phillimore - Roger Clark Motorsport
//Permission denied for this code to be copied or
//... => reproduced in any way
//======================================================

//=================================
//Global settings/params

var objCurrentSubmenu = null;

/* ===== Faded image swap configuration ===== */
var useRandomBannerShuffle = false;

// Define images for faded shuffle
			var map_name_urlBannerImage = {
	"fuel_rails[600x240].jpg": "http://www.rogerclarkmotorsport.co.uk/shop.asp?catsLevel=215"
	, "facebook[600x240].jpg": "http://www.facebook.com/rogerclarkmotorsport"
	, "stroker-kit[600x240].jpg": "/shop.asp?catsLevel=302"
	, "twitter[600x240].jpg": "http://twitter.com/_RCMS"
	//"stocking-fillers[600x240].jpg": "/shop.asp?catsLevel=209"
	//, "xmas_turbo_2011[600x240].jpg": "/shop_detail.asp?productID=1637"
};
var bannerImageRootPath = "images/banner/";
var bannerImageFiles = [
			"fuel_rails[600x240].jpg"
			,
			"facebook[600x240].jpg"
			,
			"stroker-kit[600x240].jpg"
			,
			"twitter[600x240].jpg"
			,
			"IMG_1797[600x240].jpg"
			,
			"TOTB_2007_0106[600x240].jpg"
			,
			"OllyClarkinactionatKnockhill[600x240].jpg"
			,
			"roger_clark[600x240].jpg"
			,
			"yellow[600x240].jpg"
			,
			"subaruroger[600x240].jpg"
			,
			"Genius[600x240].jpg"
			,
			"184s[600x240].jpg"
			,
			"374s[600x240].jpg"
			,
			"IMG_5591[600x240].jpg"
			,
			"100_0889[600x240].jpg"
			,
			"ASI07 002[600x240].jpg"
			,
			"cyprus[600x240].jpg"
			,
			"DSC_0167[600x240].jpg"
			,
			"DSC_0191[600x240].jpg"
			,
			"DSC_1031[600x240].jpg"
			,
			"DSC_1092[600x240].jpg"
			,
			"gobstopper studio shoot redline 018[600x240].jpg"
			,
			"gobstopper studio shoot redline 014[600x240].jpg"
			,
			"IMG_0351[600x240].jpg"
			,
			"IMG_0367[600x240].jpg"
			,
			"IMG_0373[600x240].jpg"
			,
			"IMG_0740[600x240].jpg"
			,
			"IMG_0795[600x240].jpg"
			,
			"IMG_0935[600x240].jpg"
			,
			"IMG_0938[600x240].jpg"
			,
			"IMG_1315[600x240].jpg"
			,
			"IMG_7024[600x240].jpg"
			,
			"IMG_7194[600x240].jpg"
			,
			"IMG_7250[600x240].jpg"
			,
			"IMG_7264[600x240].jpg"
			,
			"IMG_7284[600x240].jpg"
			,
			"IMG_7345[600x240].jpg"
			,
			"Knockhill12[600x240].jpg"
			,
			"Knockhill15[600x240].jpg"
			,
			"Knockhill20[600x240].jpg"
			,
			"Knockhill8[600x240].jpg"
			,
			"rogerandkids[600x240].jpg"
			,
			"Silverstone10[600x240].jpg"
			,
			"Silverstone12[600x240].jpg"
			,
			"Silverstone7[600x240].jpg"
			,
			"ta24[600x240].jpg"
			
			];

// Time (milliseconds) between swaps
var bannerImageSwapInterval = 4500; //1250;
// Amount to shift opacity on each interval elapse
var bannerImageSwapOpacityShift = 10;
// Time (milliseconds) between each interval elapse
var bannerImageSwapOpacityShiftInterval = 120;
/* ===== /Faded image swap configuration ===== */

// Calculate maximum image index available for banner
var bannerImageCount = bannerImageFiles.length - 1;

// References to banner image swap elements
var bannerImage1 = null, bannerImage2 = null;

// Indexes of banner images in current swap
var oldTransitionIndex = 0;
var newTransitionIndex = 0;
// Current opacity of new image fading in
var nextBannerImageOpacity = 0;

var bannerImageFree = null;

// For checkout
var objFreightData = {};
//=================================

// EDIT 26/1/08: also hooked DOMContentLoaded (this is legacy fallback)
window.onload = init;

var boolInited = false;	// Flag stops multiple init()s

// Offer some deterrent against downloading pictures etc
document.onmousedown = document.oncontextmenu = DownloadDeterrent;

//hide any errors which do occur (should not be any) from user
//window.onerror = disableErrors;

// Disables browser error reporting
function disableErrors() {
	return true;
}

// Offer some deterrent against downloading pictures etc
function DownloadDeterrent( evt ) {
	if ( !evt ) evt = window.event;
	var elPopupMenu;
	
	// Find popup menu; disable deterrent if not found
	if ( !(elPopupMenu = document.getElementById("ulPopupMenu")) ) {
		return;
	}
	
	// Right-click
	if ( evt.type != "mousedown" || evt.button == 2 ) {
		evt.cancelBubble = true;
		evt.returnValue = false;
		if ( evt.preventDefault ) {
			evt.preventDefault();
		}
		if ( evt.stopPropagation ) {
			evt.stopPropagation();
		}
		
		var intScrollX = window.pageXOffset != null ? window.pageXOffset : document.documentElement.scrollLeft
				, intScrollY = window.pageYOffset != null ? window.pageYOffset : document.documentElement.scrollTop;
		
		var colItems = elPopupMenu.getElementsByTagName("li");
		for (var intItem = 0 ; intItem < colItems.length ; ++intItem) {
			colItems[intItem].onmouseover = function() {
					this.className = this.className.replace(/\s*clsHover/g, "");
					this.className += " clsHover";
				};
			colItems[intItem].onmouseout = function() {
					this.className = this.className.replace(/\s*clsHover/g, "");
				};
		}
		
		elPopupMenu.className = elPopupMenu.className.replace(/\s*clsOpen/g, "");
		elPopupMenu.className += " clsOpen";
		
		var left = evt.clientX + intScrollX
				, top = evt.clientY + intScrollY
				, intPageRight = document.documentElement.clientWidth + intScrollX
				, intPageBottom = document.documentElement.clientHeight + intScrollY;
		
		if ( left > intPageRight - elPopupMenu.offsetWidth ) {
			left = intPageRight - elPopupMenu.offsetWidth;
		}
		if ( top > intPageBottom - elPopupMenu.offsetHeight ) {
			top = intPageBottom - elPopupMenu.offsetHeight;
		}
		
		// Position with cursor
		elPopupMenu.style.left = left + "px";
		elPopupMenu.style.top = top + "px";
		
		return false;
	// Other button
	} else {
		// Ensure popup menu is hidden
		elPopupMenu.className = elPopupMenu.className.replace(/\s*clsOpen/g, "");
	}
}

// Menu items hover
function MenuLinkOn() {
	this.className = "clsMenuLinkHover";
}

// Menu items hover off
function MenuLinkOff() {
	this.className = "clsMenuLink";
}

// Shop cart add controls for products
function Shop_IncrementQuantity() {
	var id = this.id.split("_")[ 1 ], txtQuantity;
	if ( id && (txtQuantity = document.getElementById("txtQuantity_" + id)) ) {
		txtQuantity.value++;
	}
	// Prevent any default action (selecting text of link etc.)
	return false;
}
function Shop_DecrementQuantity() {
	var id = this.id.split("_")[ 1 ], txtQuantity;
	if ( id && (txtQuantity = document.getElementById("txtQuantity_" + id)) && txtQuantity.value > 1 ) {
		txtQuantity.value--;
	}
	// Prevent any default action (selecting text of link etc.)
	return false;
}

// Initialise graphics system
function init() {
	initRCMProductsScroll();
	initMenu();
	initShopCartAddControls();
	initProductColourSwap();
	initThumbnailSwap();
	initFreightSwap();
	initMaskedEmailLinks();
	initUKZones();
	initHomePageBanner();
}

function initHomePageBanner() {
	// Store refs to banner image container
	bannerImage1 = document.getElementById("imgBanner1");
	bannerImage2 = document.getElementById("imgBanner2");
	
	// Only applies to home page
	if ( bannerImage1 && bannerImage2 ) {
		// Show image after load
		bannerImage1.onload = ImageLoaded;
		bannerImage2.onload = ImageLoaded;
		bannerImage1.onerror = bannerImage1.onabort = bannerImage_onError;
		bannerImage2.onerror = bannerImage2.onabort = bannerImage_onError;
		bannerImage1.onclick = bannerImage_onClick;
		bannerImage2.onclick = bannerImage_onClick;
		
		bannerImageFree = bannerImage2;
		
		// Start with new image
		bannerImage1.src = bannerImageRootPath + bannerImageFiles[0];
	}
}

function bannerImage_onClick( evt ) {
	if ( !evt ) { evt = window.event; }
	
	var target = evt.target || evt.srcElement;
	var name = target.getAttribute("src").match(/[^\/]+$/)[ 0 ];
	var url;
	
	// Follow link, if current image has one
	if ( src = map_name_urlBannerImage[ name ] ) {
		location.href = src;
	}
}

function initProductColourSwap() {
	var divColourSwap, imgProductImage, slctColour;
	// colour swap present; enable interaction
	if ((divColourSwap = document.getElementById("divProductDetails_ColourSwap"))
			&& (imgProductImage = document.getElementById("imgLeftProductImage"))
			&& (slctColour = document.getElementById("slctProductColour"))) {
		
		var colImages = divColourSwap.getElementsByTagName("img");
		
		// when colour is selected from dropdown, update large image etc.
		//	(NB: in W3C-compliant browsers (not IE), onmousemove will fire as user hovers over options in dropdown)
		slctColour.onchange = slctColour.onmousemove = function (evt) {
				if (!evt) evt = window.event;
				colImages[this.selectedIndex].onmouseover();
			};
		
		for (var intImage = 0 ; intImage < colImages.length ; ++intImage) {
			colImages[intImage].intIndex = intImage;
			colImages[intImage].onmouseover = function () {
					imgProductImage.src = this.getAttribute("rel");
					imgProductImage.alt = "Selected colour swatch: " + this.getAttribute("src");
					
					slctColour.selectedIndex = this.intIndex;
				};
		}
	}
}

function initRCMProductsScroll() {
	//iframe will not validate, so replace static product image with iframe for scrolling
	var imgRCMProducts_Static = document.getElementById("imgHome_RCMProducts");
	if (imgRCMProducts_Static) {
		//W3C-compat, FF etc.
		if (!document.all) {
			var ifmRCMProducts = document.createElement("iframe");
			imgRCMProducts_Static.parentNode.replaceChild(ifmRCMProducts, imgRCMProducts_Static);
			//load page (simplifies scroller load system etc.)
			ifmRCMProducts.src = "rcm_list_iframe.asp?list_catID=209";
			ifmRCMProducts.className = "clsColumnSection_Image";
			ifmRCMProducts.frameBorder = ifmRCMProducts.border = 0;
		//IE and compatibles
		} else {
			//must use innerHTML for frameborder to be respected
			imgRCMProducts_Static.parentNode.innerHTML = "<iframe frameborder='0' class='clsColumnSection_Image' src='rcm_list_iframe.asp?list_catID=209'></iframe>";
		}
	}
	
	//fixed scrolling list
	//iframe will not validate, so replace static product image with iframe for scrolling
	var imgFixedList_Static = document.getElementById("imgHome_FixedList1");
	if (imgFixedList_Static) {
		//W3C-compat, FF etc.
		if (!document.all) {
			var ifmFixedList = document.createElement("iframe");
			imgFixedList_Static.parentNode.replaceChild(ifmFixedList, imgFixedList_Static);
			//load page (simplifies scroller load system etc.)
			ifmFixedList.src = "rcm_list_iframe.asp?list_fixedID=0";
			ifmFixedList.className = "clsColumnSection_Image";
			ifmFixedList.style.height = "42px";
			ifmFixedList.frameBorder = ifmFixedList.border = 0;
		//IE and compatibles
		} else {
			//must use innerHTML for frameborder to be respected
			imgFixedList_Static.parentNode.innerHTML = "<iframe frameborder='0' class='clsColumnSection_Image' style='height: 42px;' src='rcm_list_iframe.asp?list_fixedID=0'></iframe>";
		}
	}
}

// Sets up view UK zones link on member settings pages
function initUKZones() {
	var objHoverLink = document.getElementById("lnkViewUKZones");
	var objHoverDiv = document.getElementById("divViewUKZones");
	if (objHoverLink && objHoverDiv)
	{
		objHoverLink.onmousedown = HandleUKZones_Show;
	}
}

function HandleUKZones_Show() {
	var objHoverLink = document.getElementById("lnkViewUKZones");
	var objHoverDiv = document.getElementById("divViewUKZones");
	if (objHoverLink && objHoverDiv)
	{
		objHoverLink.onmousedown = HandleUKZones_Hide;
		objHoverLink.innerHTML = "Click to hide United Kingdom Zones";
		objHoverDiv.style.display = "block";
	}
}
function HandleUKZones_Hide() {
	var objHoverLink = document.getElementById("lnkViewUKZones");
	var objHoverDiv = document.getElementById("divViewUKZones");
	if (objHoverLink && objHoverDiv)
	{
		objHoverLink.onmousedown = HandleUKZones_Show;
		objHoverLink.innerHTML = "Click to view United Kingdom Zones";
		objHoverDiv.style.display = "none";
	}
}

// Enable inc/dec cart quantity controls
function initShopCartAddControls() {
	var list_el = document.getElementsByTagName("div"), idx, el;
	
	for ( idx = 0 ; idx < list_el.length ; ++idx ) {
		el = list_el[ idx ];
		if ( el.id.split("_")[ 0 ] === "cmdDecrement" ) {
			el.onclick = Shop_DecrementQuantity;
		} else if ( el.id.split("_")[ 0 ] === "cmdIncrement" ) {
			el.onclick = Shop_IncrementQuantity;
		}
	}
	
	list_el = document.getElementsByTagName("input");
	
	for ( idx = 0 ; idx < list_el.length ; ++idx ) {
		el = list_el[ idx ];
		if ( el.id.split("_")[ 0 ] === "cmdDecrement" ) {
			el.onclick = Shop_DecrementQuantity;
		} else if ( el.id.split("_")[ 0 ] === "cmdIncrement" ) {
			el.onclick = Shop_IncrementQuantity;
		}
	}
}

// Ensures an image element is not shown until its image is fully loaded
function ImageLoaded() {
	this.style.visibility = "visible";
	
	// Swap image (with fade effect)
	window.setTimeout(swapBannerImages, bannerImageSwapInterval);
}

// Ensures graceful handling of unloadable images
function bannerImage_onError() {
	// Skip to next image
	oldTransitionIndex++;
	newTransitionIndex++;
	
	// Proceed with banner swap, but with errored image skipped
	//	(no need for timeout here - this is a new swap)
	window.setTimeout(swapBannerImages, bannerImageSwapInterval);
}

// Swaps the current image
function swapBannerImages() {
	// Random shuffling through banner images
	if ( useRandomBannerShuffle ) {
		// Generate random image index within available bounds
		newTransitionIndex = Math.floor(Math.random() * bannerImageCount);
	// Use serial cycle
	} else {
		// Get next image in scrolling banner cycle
		newTransitionIndex = oldTransitionIndex + 1;
		// Reset to first if reached end of cycle
		if ( newTransitionIndex > bannerImageCount ) {
			newTransitionIndex = 0;
		}
	}
	
	if ( bannerImageFree == bannerImage1 ) {
		bannerImageFree = bannerImage2;
	} else {
		bannerImageFree = bannerImage1;
	}
	
	nextBannerImageOpacity = 0;
	// IE DirectX filters support
	if ( bannerImage2.filters ) { bannerImage2.filters.alpha.opacity = 0; }
	// W3C & old Firefox support
	bannerImage2.style.opacity = bannerImage2.style.MozOpacity = 0;
	
	// Show image after load
	bannerImage2.style.visibility = "hidden";
	
	// Only start fading images into each other once both are loaded
	bannerImage2.onload = WaitForImageLoadBeforeFade;
	bannerImage2.onerror = bannerImage2.onabort = WaitForImageLoadBeforeFade_Error;
	
	// Get path of next image and display in banner
	bannerImage2.src = bannerImageRootPath + bannerImageFiles[newTransitionIndex];
}

//ensures an image element is not faded until its image is fully loaded
function WaitForImageLoadBeforeFade() {
	bannerImage2.style.visibility = "visible";
	//set timeout to start fade of transition
	//window.setTimeout(FadeTransition, bannerImageSwapInterval);
	FadeTransition();
}

//ensures graceful handling of unloadable images (or user aborted with Stop button)
function WaitForImageLoadBeforeFade_Error() {
	//skip to next image
	oldTransitionIndex++;
	newTransitionIndex++;
	//proceed with banner swap, but with errored image skipped
	//... => (no need for timeout here - this is a new swap)
	window.setTimeout(swapBannerImages, bannerImageSwapInterval);
}

// Handles fading the transition between images in a swap
function FadeTransition() {
	// Shift opacity on each interval elapse
	nextBannerImageOpacity += bannerImageSwapOpacityShift;
	// Finished transition
	if ( nextBannerImageOpacity > 100 ) {
		// IE DirectX filters support
		if ( bannerImage1.filters ) { bannerImage1.filters.alpha.opacity = 100; }
		
		bannerImage1.style.MozOpacity = bannerImage1.style.opacity = 1;
		
		// New image is now the "old" one, so shift index
		oldTransitionIndex = newTransitionIndex;
		
		/* ====== Prevent flicker ====== */
		// Move new image in front to enable load of next image behind (hidden)
		
		bannerImage2.style.zIndex = 2;
		bannerImage1.style.zIndex = 1;
		
		var objTemp = bannerImage1;
		bannerImage1 = bannerImage2;
		bannerImage2 = objTemp;
		/* ====== /Prevent flicker ====== */
		
		// No "new" image is now selected
		newTransitionIndex = -1;
		
		// Swap image (with fade effect)
		window.setTimeout(swapBannerImages, bannerImageSwapInterval);
	// Not yet finished transition
	} else {
		// IE DirectX filters support
		if ( bannerImage1.filters ) {
			// Old image fades out
			bannerImage1.filters.alpha.opacity = 100 - nextBannerImageOpacity;
			// New image fades in
			bannerImage2.filters.alpha.opacity = nextBannerImageOpacity;
		}
		bannerImage1.style.opacity = bannerImage1.style.MozOpacity = (100 - nextBannerImageOpacity) / 100;
		bannerImage2.style.opacity = bannerImage2.style.MozOpacity = (nextBannerImageOpacity) / 100;
		
		// Fade needs to continue until images are faded in/out
		window.setTimeout(FadeTransition, bannerImageSwapOpacityShiftInterval);
	}
}

// Initialises the thumbnail swap system by assigning event handlers for directing link url to image src
function initThumbnailSwap() {
	var idx, list = document.links, len;
	
	// Only allow to run once
	if ( boolInited ) { return; }
	boolInited = true;
	
	var elLargeSwap = document.getElementById("imgThumbnailSwap_Large_Image");
	
	if ( list && elLargeSwap ) {
		for ( idx = 0, len = list.length ; idx < len ; ++idx ) {
			// Only add thumbnail swap functionality to correct elements
			if ( list[ idx ].className == "clsThumbnailSwap_Thumbnail" ) {
				// Add event handler to get image source URL from hyperlink
				//	(degrades gracefully as direct link to image)
				list[ idx ].onclick = SwapThumbnail;
			}
		}
		elLargeSwap.onclick = ExpandLargeImage;
	}
}
// Event handler
function SwapThumbnail() {
	var elLargeSwap;
	if ( elLargeSwap = document.getElementById("imgThumbnailSwap_Large_Image") ) {
		//swap source image
		elLargeSwap.src = (this.href.charAt(this.href.length - 1) == "#") ? "images/blank.gif" : this.href;
	}
	return false;
}

// Allows expansion of large image loaded from thumbnail
function ExpandLargeImage() {
	// Open popup with expanded version of image
	window.open(this.src, "wndRCM_Expand");
}

function initFreightSwap() {
	var objDeliverySelect = document.getElementById("slctDelivery");
	if ( objDeliverySelect ) {
		objDeliverySelect.onchange = UpdateFreight;
	}
}

function UpdateFreight() {
	var objThisFreightData;
	
	if ( objThisFreightData = objFreightData[ this.options[ this.selectedIndex ].text ] ) {
		var objDeliveryTotalDiv = document.getElementById("divDeliveryTotal");
		if (objDeliveryTotalDiv) objDeliveryTotalDiv.innerHTML = objThisFreightData["intDeliveryTotal"];
		var objGrossTotalDiv = document.getElementById("divGrossTotal");
		if (objGrossTotalDiv) objGrossTotalDiv.innerHTML = objThisFreightData["intGrossTotal"];
		var objTotalVATDiv = document.getElementById("divTotalVAT");
		if (objTotalVATDiv) objTotalVATDiv.innerHTML = objThisFreightData["intTotalVAT"];
		var objNetTotalDiv = document.getElementById("divNetTotal");
		if (objNetTotalDiv) objNetTotalDiv.innerHTML = objThisFreightData["intNetTotal"];
	}
}

function initMaskedEmailLinks() {
	if (document.links)
	{
		//can't iterate over doc.links array in IE
		for (var intLink = 0 ; intLink < document.links.length ; intLink++)
		{
			//only apply e-mail functionality to certain class
			if (document.links[intLink].className.indexOf("clsEmailLink") > -1)
			{
				document.links[intLink].onclick = SendEmail;
			}
		}
	}
}

//removes need for hardcoded mailto: links
function SendEmail() {
	top.location.href = "mailto:" + (this.textContent || this.innerText);
	
	return false;
}

function initMenu() {
	document.onmouseover = ShowSubmenu;
}

function ShowSubmenu(evt) {
	if ( !evt ) evt = window.event;
	
	var objSourceElement = evt.target || evt.srcElement;
	
	if ( objSourceElement ) {
		var objSubmenu = document.getElementById(objSourceElement.id + "_Submenu");
		
		//hide any currently showing submenu
		if (objCurrentSubmenu && objSourceElement != objCurrentSubmenu && objSourceElement.parentNode.className != "clsSubmenu") {
			objCurrentSubmenu.style.visibility = "hidden";
			
			//remove hover from submenu parent
			var objSubmenuParent = document.getElementById(objCurrentSubmenu.id.split("_")[0]);
			if (objSubmenuParent && objSubmenuParent.className != "clsMenuItem clsSelectedMenuItem")
				objSubmenuParent.className = "clsMenuItem";
		}
		
		var objThisSubmenu = null;
		
		if (objSourceElement.parentNode.className == "clsSubmenu")
		{
			objThisSubmenu = objSourceElement.parentNode;
		}
		else if (objSourceElement.className == "clsSubmenu")
		{
			objThisSubmenu = objSourceElement;
		}
		
		//parent of submenu must remain in hovered state
		if (objThisSubmenu && objThisSubmenu.className == "clsSubmenu")
		{
			var objSubmenuParent = document.getElementById(objThisSubmenu.id.split("_")[0]);
			if (objSubmenuParent && objSubmenuParent.className != "clsMenuItem clsSelectedMenuItem")
				objSubmenuParent.className = "clsMenuItem clsMenuItem_Hover";
		}
		
		//check submenu exists
		if (objSubmenu)
		{
			//store reference to now open submenu for future closing
			objCurrentSubmenu = objSubmenu;
			
			objSubmenu.style.left = objSourceElement.offsetLeft + "px";
			objSubmenu.style.top = (objSourceElement.offsetTop + 22) + "px";
			objSubmenu.style.visibility = "visible"; //show submenu
		}
	}
}

//======================================================
//Support Presentation JavaScript
//Copyright (c) 2007 Daniel Phillimore - Roger Clark Motorsport
//Permission denied for this code to be copied or
//... => reproduced in any way
//======================================================
