// JavaScript Document


var BrowserDetect = 
{
/*
* Nick - Browser detect function
* 
* Usage:  
* 
* e.g. alert('You\'re using ' + BrowserDetect.browser + ' ' + BrowserDetect.version + ' on ' + BrowserDetect.OS + '!');
*/
	init: function () 
	{
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) 
	{
		for (var i=0;i<data.length;i++)	
		{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();

function fnShow(elementName) {
	if (document.getElementById) {
		var element = document.getElementById(elementName);
		if (element)
		{
			element.style.display = "block";
		}
	}		 
}

function fnHide(elementName) {
	if (document.getElementById){
		var element = document.getElementById(elementName);
		if (element)
		{
			element.style.display = "none";
		}
	}		 
}

function fnShowHide(obj, obj2){
	 if(document.getElementById){
		 var el = document.getElementById(obj);
		 var el2 = document.getElementById(obj2);
	
	
		 if(el.style.display == "none"){
			 el.style.display = "block";
			 el2.style.display = "none";
		
		
		 }else{
		 	el.style.display = "none";
		 }
	
	 }
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function doMouseClick(targetName) {
	trace("doMouseClick");
	var event = null;
	var target = null;

	if (document.getElementById) {
		target = document.getElementById(targetName);
	}

	trace("target " + target);	
	if (document.createEvent)
	{
		// Non-IE browser
		event = document.createEvent("MouseEvents");
		event.initMouseEvent('click',
			true, // Click events bubble
			true, // and they can be cancelled
			document.defaultView, // Use the default view
			1, // Just a single click
			0, 0, 0, 0, // Don't bother with co-ordinates
			false, // Don't apply any key modifiers
			false,
			false,
			false,
			0, // 0 - left, 1 - middle, 2 - right
			null); // Click events don't have any targets other than
					// the recipient of the click
		target.dispatchEvent(event);
		trace("FF/Safari onClick event fired");	
	} else {
		// IE
		target.fireEvent('onClick');
		trace("IE onClick event fired");	
	}
	
/*if(target && target.dispatchEvent && event && event.initMouseEvent) {
	} */

}

function setDeliveryInformation(productType)
{
	var deliveryDiv = document.getElementById("prodzoomdelivery");
	var deliveryContent = "<br/><br/>";
	if (productType != "clearanceauction")
	{
		deliveryContent = "This item can be delivered to you on<br/>" +
		document.getElementById('activeDeliveryDate').innerHTML +
		".<br/>";
	}
	deliveryContent += "<a href='javascript:DisplayDeliveryPricing(8);'>Click here for delivery pricing information.</a>";
	deliveryDiv.innerHTML = deliveryContent;
}

/*
* Show product info overlay.
* Requires hidden link named "prodzoomanchor" - see end of index.jsp
*/
var imageLoadTimeout;
function showProductLayer(gameType, gameID, roomID, productID, colourScheme) 
{
	// Set the mouseover links on the details tab back to default
	swapLinks(0);
	
	trace("showProductLayer");
	// biggest image - if images haven't loaded yet, need to loop round
	// until they have
	var imageLink = document.getElementById(gameType + 'HugeImageSrc' + gameID).innerHTML;
	var imageAlt = document.getElementById(gameType + 'HugeImageAlt' + gameID).innerHTML;
	if (imageLink != "")
	{
		var image = document.getElementById("prodzoomimage"); 
		image.src = imageLink;
		image.alt = imageAlt.replace(/\&amp;/g,'&');
	} else {
		if (imageLoadTimeout != null)
		{
			clearTimeout(imageLoadTimeout);
			imageLoadTimeout = null;
		}
		imageLoadTimeout = setTimeout("showProductInfo('" + gameType + "', '" + gameID + "', '" + roomID + "', '" + productID + "')", 400);
		return;
	}

	trace("Loaded image");
	// Description for title bar
/*	var descriptionHTML = document.getElementById(gameType + 'DescC' + gameID).innerHTML;
	descriptionParts = descriptionHTML.split(/[<>]/);
	trace(descriptionParts.length);
	for (i = 0; i < descriptionParts.length; i++)
	{
		trace(descriptionParts[i]);
	} 
	var descIndex = 2; 

	if (descriptionHTML.search(/href/) == -1)
	{
		// Between games, the description is not a link, just text
		descIndex = 0;
	}
	document.getElementById("prodzoomtitle").innerHTML = descriptionParts[descIndex]; */
	document.getElementById("prodzoomtitle").innerHTML = document.getElementById(gameType + 'DescC' + gameID).innerHTML;

	trace("Loaded title");	 
	// Current price
	var price = "This game is now closed";
	var priceText = document.getElementById(gameType + 'PriceText' + gameID).innerHTML;
	var closed = (priceText.search(/Now/) < 0); 
	if (!closed)
	{
		price = document.getElementById(gameType + 'Price' + gameID).innerHTML;
	}
	trace(price);
	document.getElementById("prodzoomprice").innerHTML = price;
	trace("loaded price");
	// Old price is not displayed for games
	try {
		document.getElementById("prodzoomoldprice").innerHTML = "";
	} catch (e) {
		//and it might be commented out!
	}

	if ( gameType == "Web" )
	{
		var promoClassName = document.getElementById("WebPromoDetailIcon" + gameID).innerHTML; 
		document.getElementById("prodzoompromoicon").className = promoClassName;
	} else {
		document.getElementById("prodzoompromoicon").innerHTML = "";
	}

	// Quantity left
	if (gameType == "TV")
	{
		if  (!closed)
		{
			var qtyLeft = document.getElementById(gameType + 'Qty' + gameID).innerHTML;
			document.getElementById("prodzoomquantity").innerHTML = qtyLeft; //.split(" ", 1);
		} else {
			document.getElementById("prodzoomquantity").innerHTML = "&nbsp;";
		} 
		trace("Loaded quantity");	
	} else {
		document.getElementById("prodzoomquantity").innerHTML = "&nbsp;";
	}

	// video
	var videoLink = document.getElementById(gameType + 'VideoLink' + gameID).innerHTML;

	insertVideo(videoLink);
	trace("Loaded video");

	// short description ....
	if (!closed)
	{	
		setDeliveryInformation("game");
	}	

	// Buy link
	if (!closed)
	{
		var buyAction = document.getElementById(gameType + 'BuyLink' + gameID).innerHTML;
/*		var buyText = document.getElementById(gameType + 'Buy' + gameID).innerHTML;
		if (buyText.search(/href/) >= 0)
		{
			// There's an action, so display "buy now"
			var buyParts = buyText.split(/[<>]/);
			var anchor = buyParts[1];
			var anchorParts = anchor.split(/\"/);
			buyAction = anchorParts[1];
		}*/
		
		if (buyAction != "")
		{
			document.getElementById("prodzoombuy").innerHTML = 
				"<a href=\"" + buyAction + "\" class='prodzoombuynow'>" + 
				"<img src='/img/prodzoom/color" + colourScheme + "/btn-buy.gif' " +
				"alt='buy now' width='78' height='12' id='BuyImage' " +
				"onmouseover=\"MM_swapImage('BuyImage','','/img/prodzoom/color" + colourScheme + "/btn-buy_Over.gif',1)\" " +
				"onmouseout='MM_swapImgRestore()' />" +
				"</a>";
		}
	} else {
		document.getElementById("prodzoombuy").innerHTML = ""; 
	}
	
	// Details link
	document.getElementById("prodzoomdetails").innerHTML = 
		"<a href='/games-current.jsp?game=" + gameType + gameID + "&detail=true' class='viewfull'>" +
		"<img src='/img/prodzoom/color" + colourScheme + "/btn-viewdetails.gif' " +
		"alt='view full details' width='137' height='12' id='ViewImage' " +
		"onmouseover=\"MM_swapImage('ViewImage','','/img/prodzoom/color" + colourScheme + "/btn-viewdetails_Over.gif',1)\" " +
		"onmouseout='MM_swapImgRestore()' /></a>";

	// IFrame 'Gems Details' link
	document.getElementById('detailFrame').src="/PageResource/HiddenLayers/scrollable.jsp?product=" + productID;

	showProductDetails();

	// Refresh product review summary, ignoring any errors
	try {
		updateReviewSection(productID, "/games-current.jsp?game=" + gameType + gameID + "&detail=true");
	} catch (e) {}
	
	trace("loaded links");
	doMouseClick('prodzoomanchor');
	incrementProductPopularity(productID);
	trace("showProductLayer() done");
}

function showShopProductInfo(productType, productIndex)
{
	// Set the mouseover links on the details tab back to default
	swapLinks(0);

	// Description for title bar
	var description = document.getElementById('desc' + productIndex).innerHTML;
	
	var colourScheme = 9;
	/*var colourScheme = 4;
	if(productType == "game" )
	{
		colourScheme = 8;
	}
	else if ( productType == "preweb" )
	{
		colourScheme = 8;
	}
	else if ( productType == "clearance" )
	{
		colourScheme = 8;
	}
	else if ( productType == "shop" )
	{
		colourScheme = 8;
	}*/

	var promoIcon = document.getElementById("prodzoompromoicon");
	if (productType == "game")
	{
		var promoClassName = document.getElementById("promoDetailIcon" + productIndex).innerHTML; 
		promoIcon.className = promoClassName;
	} else {
		promoIcon.className = "";
	}

	if (productType == "game" || productType == "clearanceauction")
	{
		var fullDescription = document.getElementById('fulldesc' + productIndex).innerHTML;
		if (fullDescription.search(/Ex-Demo/) >= 0)
		{
			description += " (EX-DEMO PRODUCT)";		
		}
	}
	document.getElementById("prodzoomtitle").innerHTML = description;

	// Old price
	var oldprice = "";

	// Current price
	var price = "";

	if (productType == "shop" || productType == "preweb" || 
		productType == "clearance")
	{
		if (productType == "preweb" || productType == "clearance")
		{
			// Just one fixed price
			try {
				oldprice = document.getElementById('oldprice' + productIndex).innerHTML;
			} catch (e) {
				// oldprice element might be commented out!
			}
		}

		price = document.getElementById('price' + productIndex).innerHTML;
		
	} 
	else if (productType == "game")
	{
		// Show buy now price and bid price
		price = "<span class='left'>Buy Now for </span><span class='right'>";
		price += document.getElementById('buyprice' + productIndex).innerHTML;
		price += "</span><br/><span class='left'> or place a Forward Bid for </span><span class='right'>";		
		price += document.getElementById('bidprice' + productIndex).innerHTML;
		price += "</span>";		
	}
	else if (productType = "clearanceauction")
	{
		var bidText = document.getElementById('buyprice' + productIndex).innerHTML; 
		price = bidText;
		price += "<br/><span class='left'>";
		if (bidText == "0 Bids")
		{
			price += "Start Price";
		} else {
			price += "Current Highest Bid";
		}
		price += "</span><span class='right'>";
		price += document.getElementById('price' + productIndex).innerHTML;
		price += "</span>";		
	}
	
	if (productType == "preweb" || productType == "clearance")
	{
		var oldpriceElement;
		try {
			oldpriceElement = document.getElementById("prodzoomoldprice");
			// test if old/new prices are same

			if (oldprice=="" || oldprice==price)
			{
				// same, so don't output the old price
				oldpriceElement.innerHTML = "";
			}
			else	
			{
				// different so output them both
				oldpriceElement.innerHTML = oldprice;
			}
		} catch (e) {
			// element "prodzoomoldprice" might be commented out
		}
	} 
	else
	{
		oldpriceElement = document.getElementById("prodzoomoldprice");
		oldpriceElement.innerHTML = "";
	}	
	
	var prodzoompriceDiv = document.getElementById("prodzoomprice");		
	prodzoompriceDiv.innerHTML = price;
	if (productType == "game")
	{
		prodzoompriceDiv.style.paddingBottom = "10px";
	}

	setDeliveryInformation(productType);
	
	// biggest image
	var imageSource = document.getElementById("hugeimage" + productIndex).innerHTML;
	var image = document.getElementById("prodzoomimage"); 
	if (imageSource != "")
	{
		image.src = imageSource;
	}

	// video
	var videoLink = document.getElementById('video' + productIndex).innerHTML;
	insertVideo(videoLink);

	// Buy link
 	var buyAction = "";
 	var buyLinkElement = document.getElementById('buy' + productIndex);
 	if (buyLinkElement != null)
 	{
		var buyText = buyLinkElement.innerHTML;
		if (buyText.search(/href/) >= 0)
		{
			// There's an action, so display "buy now"
			var buyParts = buyText.split(/[<>]/);
			var anchor = buyParts[1];
			var anchorParts = anchor.split(/\"/);
			buyAction = anchorParts[1];
		}
 	}
	
	if (buyAction != "")
	{
		document.getElementById("prodzoombuy").innerHTML = 
			"<a href=\"" + buyAction + "\" class='prodzoombuynow'>" + 
			"<img src='/img/prodzoom/color" + colourScheme + "/btn-buy.gif' " +
			"alt='buy now' width='78' height='12' id='BuyImage' " +
			"onmouseover=\"MM_swapImage('BuyImage','','/img/prodzoom/color" + colourScheme + "/btn-buy_Over.gif',1)\" " +
			"onmouseout='MM_swapImgRestore()' />" +   
			"</a>";
	}

	if (productType == "game" || productType == "clearanceauction")
	{
		// Bid link
	 	var bidAction = "";
		var bidText = (document.getElementById('bid' + productIndex)).innerHTML;
		if (bidText.search(/href/) >= 0)
		{
			var bidParts = bidText.split(/[<>]/);
			var anchor = bidParts[1];
			var anchorParts = anchor.split(/\"/);
			bidAction = anchorParts[1];
		}
		
		if (bidAction != "")
		{
			// There's an action, so display "Place Bid"
			if (productType == "game")
			{
				document.getElementById("prodzoombid").innerHTML = 
					"<br/><a href=\"" + bidAction + "\" class='prodzoombid'>" + 
					"<img src='/img/prodzoom/color" + colourScheme + "/btn-bid.gif' " +
					"alt='place forward bid' width='161' height='12' id='BidImage' " +
					"onmouseover=\"MM_swapImage('BidImage','','/img/prodzoom/color" + colourScheme + "/btn-bid_Over.gif',1)\" " +
					"onmouseout='MM_swapImgRestore()' />" +   
					"</a>";
			} else {
				document.getElementById("prodzoombid").innerHTML = 
					"<a href=\"" + bidAction + "\" class='prodzoombid' style='width:94px;'>" + 
					"<img src='/img/prodzoom/color" + colourScheme + "/btn-bidnow.gif' " +
					"alt='bid now' width='84' height='12' id='BidImage' " +
					"onmouseover=\"MM_swapImage('BidImage','','/img/prodzoom/color" + colourScheme + "/btn-bidnow_Over.gif',1)\" " +
					"onmouseout='MM_swapImgRestore()' />" +   
					"</a>";
			}
		}
	}

	var futureBidHTML = "";
	if (productType == "game")
	{
		futureBidHTML = document.getElementById('forwardbid' + productIndex).innerHTML;
	}
	document.getElementById("prodzoomfuturebid").innerHTML = futureBidHTML;

	var gameStartHTML = "";
	var startTime = "";
	if (productType == "game" || productType == "clearanceauction")
	{
		// Game start time / auction end time
		startTime = document.getElementById('start' + productIndex).innerHTML;
	}
	if (startTime != "")
	{
		if (productType == "game")
		{
			gameStartHTML = 
				"Game starts at " + startTime + ".<br/>";
		}
		if (productType == "clearanceauction")
		{
			gameStartHTML = 
				"Auction ends at " + startTime + ".<br/>";
		}
	}
	document.getElementById("prodzoomgamestart").innerHTML = gameStartHTML;

	if (productType != "game" && productType != "clearanceauction")
	{
		document.getElementById("prodzoombid").innerHTML = "";
	}
	
	// Details link
	var detailsLink = document.getElementById('details' + productIndex).innerHTML;
	document.getElementById("prodzoomdetails").innerHTML = 
		"<a href='" + detailsLink + "&colourScheme=" + colourScheme + "' class='viewfull'>" +
		"<img src='/img/prodzoom/color" + colourScheme + "/btn-viewdetails.gif' " +
		"alt='view full details' width='137' height='12' id='ViewImage' " +
		"onmouseover=\"MM_swapImage('ViewImage','','/img/prodzoom/color" + colourScheme + "/btn-viewdetails_Over.gif',1)\" " +
		"onmouseout='MM_swapImgRestore()' /></a>";

	// IFrame 'Gems Details' link
	// NOTE :- we can't get the product ID from anywhere else, so we have to substring the link from the details section - Nick
	var detailsParams = detailsLink.substring(17);
	document.getElementById('detailFrame').src="/PageResource/HiddenLayers/scrollable.jsp?" + detailsParams;
	
	// Next On TV
	/*
	if (document.getElementById('prodzoomnextontv') != null)
	{
		if( document.getElementById('nextOnTV' + productIndex) )
		{
			var nextOnTV = document.getElementById('nextOnTV' + productIndex).innerHTML;
			document.getElementById("prodzoomnextontv").innerHTML = nextOnTV;
		} else
		{
			document.getElementById("prodzoomnextontv").innerHTML = "";
		}
	} */
	
// set our video and details holders back to default
	showProductDetails();
	
	// Extract productID from detailsLink, e.g.
	// /shop-detail.jsp?product=ULU4760&category=clearance
	var productIDStart = detailsLink.indexOf("=") + 1;
	var productIDEnd = detailsLink.indexOf("&");
	var productID = detailsLink.substring(productIDStart, productIDEnd);

	// Refresh product review summary, ignoring any errors
	try {
		updateReviewSection(productID, detailsLink + "&colourScheme=" + colourScheme);
	} catch (e) {}

	doMouseClick('prodzoomanchor');

	incrementProductPopularity(productID);

	var htmled = document.getElementById("detailFrame");
//	htmled.contentWindow.document.write( "This is some text within the iframe" );
	htmled.contentWindow.focus();
}

function insertVideo(videoLink)
{
	trace(videoLink);

/*  Video embedding is now handled by an IFrame that contains the Shockwave object embedded on a separate page. 
	This is for two reasons - first, because it allows us to test whether the link is valid or not via a small 
	java servlet and display the 'no content available' message if necessary; and second because it prevents both 
	IE6 and 7 from producing some annoying display glitches when switching between the new 3D View/Gem Details tabs.
	
	- Nick. */
	
//		var embedParam = "<embed src='" + videoLink + "' quality='high' " + 
//							"pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' " + 
//							"width='240' height='180' wmode='transparent'></embed>";
//	trace(embedParam);	
//		var video = 
//			"<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' " +
//			"codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' " + 
//			"width='240' height='180'>" +
//			"<param name='movie' value='" + videoLink + "' />" +
//			"<param name='quality' value='high' />" +
//			"<param name='wmode' value='transparent' />" +
//			"<param name='menu' value='false' />" + embedParam + 
//			"</object>";
//	trace(video);	
	
	var videoFrame = document.getElementById('videoFrame');
	if (videoFrame != null)
	{
		videoFrame.src="/PageResource/HiddenLayers/embedVideo.jsp?video=" + videoLink;
	}
}

function DisplayDeliveryPricing(bandid)
{
	//open pop-up
	var url = "/deliverypricing.jsp?id=" + bandid;
	deliveryWindow = window.open(url,"DeliveryWin","toolbar=0,location=0,directories=0,status=0,menubar=0,resizable=0,scrollbars=1,height=350,width=650,screenX=20,screenY=20,top=20,left=20");
    deliveryWindow.opener = self;
    deliveryWindow.focus();
} 

function forwardTo(forwardURL)
{
	if (document.images)
        window.location.replace(forwardURL);		//stops going into the history
    else
        window.location.href = forwardURL;
}        

function trace( msg ){
  if( typeof( jsTrace ) != 'undefined' ){
    jsTrace.send( msg );
  }
}

/*
 * Set the source file of an iframe without adding the file to the
 * browser's history.
 * Does not click in IE.
 */
function setIFrameSource(iFrameID, uri, onLoadFunction) {
    var originalFrame = document.getElementById(iFrameID);
    // Create a new hidden iframe.
    replacementFrame = originalFrame.cloneNode(true);
    replacementFrame.style.position = "absolute";
    replacementFrame.style.visibility = "hidden";
    // keep the original iframe id unique!
    replacementFrame.id = "";
    // Listen for the onload event.
    addEvent(replacementFrame, 'load', function () {
	    // First, remove the event listener or the old iframe
	    // we intend to discard will not be freed...
	    // NB "this" refers to replacementFrame and 
	    // "arguments.callee" is a reference to this load function
	    removeEvent(this, 'load', arguments.callee);
	    // Show the iframe.
	    this.style.position = "";
	    this.style.visibility = "";
	    // Replace the old iframe with the new one.
	    originalFrame.parentNode.replaceChild(this, originalFrame);
	    // Reset the iframe id.
	    this.id = originalFrame.id;
	    // Change the originalFrame id
	    originalFrame.id = originalFrame.id + "old"; 
	    // Run the parameter onload function if there is one
	    if (onLoadFunction != null)
	    {
			setTimeout(onLoadFunction, 1);
	    }
	} , false);
    // Set its src first...
    replacementFrame.src = uri;
    // ...and then append it to the body of the document.
    document.body.appendChild(replacementFrame);
}

function addEvent(obj, type, fn )
{ 
	if (obj.addEventListener)
	{
		// Firefox, Safari
		obj.addEventListener( type, fn, false ); 
	} 
	else if (obj.attachEvent) 
	{
		// IE 
		obj["e"+type+fn] = fn; 
		obj[type+fn] = function() { obj["e"+type+fn]( window.event );}; 
		obj.attachEvent( "on"+type, obj[type+fn] );
	} 
} 
	
function removeEvent( obj, type, fn ) 
{ 
	if (obj.removeEventListener) 
		obj.removeEventListener( type, fn, false ); 
	else if (obj.detachEvent) 
	{ 
		obj.detachEvent( "on"+type, obj[type+fn] ); 
		obj[type+fn] = null; 
		obj["e"+type+fn] = null;
	} 
}

function countdown(yr,m,d,hr,tomn){
	var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
	theyear=yr;themonth=m;theday=d;thehour=hr;themin=tomn
	var today=new Date()
	var todayy=today.getFullYear()
	var todaym=today.getMonth()
	var todayd=today.getDate()
	var todayh=today.getHours()
	var todaymin=today.getMinutes()
	var todaysec=today.getSeconds()
	var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec
	futurestring=montharray[m-1]+" "+d+", "+yr+" "+hr+":"+tomn+":00"
	dd=Date.parse(futurestring)-Date.parse(todaystring)
	dday=Math.floor(dd/(60*60*1000*24)*1)
	dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
	dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
	dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)

	if(dday==0&&dhour==0&&dmin==0&&dsec==1){
		return
	}
	else
	{
		// document.getElementById("CountdownTimer").innerHTML="<b>Only "+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds to snatch in time for Christmas</b>"
	}
	// setTimeout("countdown(theyear,themonth,theday,thehour,themin)",1000)
}

function resizeFrameWindow(frameID)
{
	var frameElement = parent.document.getElementById(frameID);
	var framePageHeight = document.body.scrollHeight;
	if (navigator.userAgent.indexOf("Firefox") != -1)
	{
		// Firefox - have to get scrollHeight a different way.
		// TODO - This isn't perfect - when reducing height smaller than previous 
		// resize, it doesn't shrink!
		framePageHeight = frameElement.contentDocument.documentElement.scrollHeight;
	}
	var heightValue = framePageHeight + "px";
	frameElement.style.height = heightValue; 
}


/*
	Cross-Browser Split 0.2.1
	By Steven Levithan <http://stevenlevithan.com>
	MIT license
*/

var nativeSplit = nativeSplit || String.prototype.split;

String.prototype.split = function (s /* separator */, limit) {
	// If separator is not a regex, use the native split method
	if (!(s instanceof RegExp))
		return nativeSplit.apply(this, arguments);

	/* Behavior for limit: If it's...
	 - Undefined: No limit
	 - NaN or zero: Return an empty array
	 - A positive number: Use limit after dropping any decimal
	 - A negative number: No limit
	 - Other: Type-convert, then use the above rules */
	if (limit === undefined || +limit < 0) {
		limit = false;
	} else {
		limit = Math.floor(+limit);
		if (!limit)
			return [];
	}

	var	flags = (s.global ? "g" : "") + (s.ignoreCase ? "i" : "") + (s.multiline ? "m" : ""),
		s2 = new RegExp("^" + s.source + "$", flags),
		output = [],
		lastLastIndex = 0,
		i = 0,
		match;

	if (!s.global)
		s = new RegExp(s.source, "g" + flags);

	while ((!limit || i++ <= limit) && (match = s.exec(this))) {
		var zeroLengthMatch = !match[0].length;

		// Fix IE's infinite-loop-resistant but incorrect lastIndex
		if (zeroLengthMatch && s.lastIndex > match.index)
			s.lastIndex = match.index; // The same as s.lastIndex--

		if (s.lastIndex > lastLastIndex) {
			// Fix browsers whose exec methods don't consistently return undefined for non-participating capturing groups
			if (match.length > 1) {
				match[0].replace(s2, function () {
					for (var j = 1; j < arguments.length - 2; j++) {
						if (arguments[j] === undefined)
							match[j] = undefined;
					}
				});
			}

			output = output.concat(this.slice(lastLastIndex, match.index), (match.index === this.length ? [] : match.slice(1)));
			lastLastIndex = s.lastIndex;
		}

		if (zeroLengthMatch)
			s.lastIndex++;
	}

	return (lastLastIndex === this.length) ?
		(s.test("") ? output : output.concat("")) :
		(limit      ? output : output.concat(this.slice(lastLastIndex)));
};

function swapButtonImage(event, overImageSrc)
{
	var targ;
	if (!event)
	{
		var event = window.event;
	}
	if (event.target)
	{
		targ = event.target;
	}
	else if (event.srcElement)
	{
		targ = event.srcElement;
	}
	if (targ.nodeType==3) // defeat Safari bug
	{
		targ = targ.parentNode;
	}
	MM_swapImage(targ.id,'',overImageSrc,1);
}

function addButtonEvents(button, swapFunction)
{
	if (button.addEventListener){
		// Firefox, Safari, Chrome, Opera
		button.addEventListener('mouseover', swapFunction, false); 
		button.addEventListener('mouseout', MM_swapImgRestore, false);  
	} else if (button.attachEvent) {
		// IE6, IE7
		button.attachEvent('onmouseout', MM_swapImgRestore);  
		button.attachEvent('onmouseover', swapFunction);
	}
}

function removeButtonEvents(button, swapFunction)
{
	if (button.removeEventListener) {
		// Firefox, Safari, Chrome, Opera
		button.removeEventListener('mouseover', swapFunction, false); 
		button.removeEventListener('mouseout', MM_swapImgRestore, false);  
	} else if (button.detachEvent) {
		// IE6, IE7
		button.detachEvent('onmouseout', MM_swapImgRestore);
		button.detachEvent('onmouseover', swapFunction);
	}
}

function showProductDetails()
{
/* Set the size of the video and details containers to show/hide them. We cannot do this using the 'display:block' 
 * style unfortunately, as Explorer does not like it.
 * - Nick */
	document.getElementById('prodzoomvideo').style.width = "240px";	
	document.getElementById('prodzoomvideo').style.height = "180px";	
	document.getElementById('videoFrame').style.width = "240px";	
	document.getElementById('videoFrame').style.height = "180px";	

	document.getElementById('prodzoomdetail').style.width = "0px";	
	document.getElementById('prodzoomdetail').style.height = "0px";	
	document.getElementById('detailFrame').style.width = "0px";	
	document.getElementById('detailFrame').style.height = "0px";	
}

function showGemDetails()
{
	document.getElementById('prodzoomvideo').style.width = "0px";	
	document.getElementById('prodzoomvideo').style.height = "0px";	
	document.getElementById('videoFrame').style.width = "0px";	
	document.getElementById('videoFrame').style.height = "0px";	

	document.getElementById('prodzoomdetail').style.width = "240px";	
	document.getElementById('prodzoomdetail').style.height = "180px";	
	document.getElementById('detailFrame').style.width = "240px";	
	document.getElementById('detailFrame').style.height = "180px";	
}


function swapLinks(detailSelected)
{
/* Swap the selected links in the product zoom overlay */
	if (detailSelected == 0)
	{
// show the 3D view tab
		document.getElementById('3DView_btn').src="/img/prodzoom/3D_View_HI.gif";
		document.getElementById('GemDetails_btn').src="/img/prodzoom/Gem_Details_LO.gif";

		document.getElementById('3DView_btn').onmouseover=function() 
		{
// empty function
		}

		document.getElementById('3DView_btn').onmouseout=function() 
		{
// empty function
		}

		document.getElementById('GemDetails_btn').onmouseover=function() 
		{
			MM_swapImage('GemDetails_btn','','/img/prodzoom/Gem_Details_Over.gif',1)
		}

		document.getElementById('GemDetails_btn').onmouseout=function() 
		{
			MM_swapImgRestore();
		}
	}
	else
	{
// show the details view tab
		document.getElementById('3DView_btn').src="/img/prodzoom/3D_View_LO.gif";
		document.getElementById('GemDetails_btn').src="/img/prodzoom/Gem_Details_HI.gif";
	
		document.getElementById('3DView_btn').onmouseover=function() 
		{
			MM_swapImage('3DView_btn','','/img/prodzoom/3D_View_Over.gif',1);
		}

		document.getElementById('3DView_btn').onmouseout=function() 
		{
			MM_swapImgRestore();
		}

		document.getElementById('GemDetails_btn').onmouseover=function() 
		{
// empty function
		}

		document.getElementById('GemDetails_btn').onmouseout=function() 
		{
// empty function
		}
	}
}

function changeOpenerWindowURLTo(url)
{
	if (window.opener != null &&
		!window.opener.closed)
	{
		// If window that current window was opened from is still open,
		// change it's url to the parameter url
		window.opener.location = url;
		window.opener.focus();
	} 
	else 
	{
		// Open the url in a new window
		window.open(url, "_blank", "");
	}
}

/*
* Function to trim a string. Note: - trims spaces from both left and right of string. 
*/
function trim(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}

	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}

	return sString;
}


//Open video media page as popup
function showVideo(title,titleImg,loStream,hiStream,banner)
{
	var url = "/TV/collections.jsp?title=" + title + "&titleImg=" + titleImg + "&lo=" + loStream + "&hi=" + hiStream + "&banner=" + banner;

	var videoWin = window.open(url, "GemsTV_videoPopup", "toolbar=0,location=0,directories=0,menubar=0,height=526,width=900,screenX=20,screenY=20,top=100,left=90,scrollbars=0");
	videoWin.opener = self;
	videoWin.focus();
}


/*
 * Function to set the correct dimensions of the lightbox overlay, to grey out the background. 
 */
function setOverlaySize()
{
	var _docHeight;
	var _docWidth;

	if (window.innerHeight && window.scrollMaxY) 
	{
// Firefox
		_docHeight = window.innerHeight + window.scrollMaxY + "px";
		// adjust width slightly to allow for the scrollbar
		_docWidth = window.innerWidth + window.scrollMaxX-20 + "px";
	} 
	else if (document.body.scrollHeight > document.body.offsetHeight)
	{ 
// Explorer 
		_docHeight = document.body.scrollHeight + "px";

		// fix for Explorer 7
		if (document.body.scrollWidth < 934)
			_docWidth = 934 + "px";
		else
			_docWidth = document.body.scrollWidth + "px";
	}
	else 
	{ 
// Explorer 6 Strict, Mozilla (not FF) and Safari
		_docHeight = document.body.offsetHeight + "px";

// fix for Explorer 6 
		_docWidth = screen.availwidth + "px";

	}

	var ovl = document.getElementById("overlay"); 

	ovl.style.height = _docHeight;
	ovl.style.width = _docWidth;
}

function addLoadEvent(functionToRunAfterLoad) 
{
	if (typeof window.onload != 'function') 
	{
		window.onload = functionToRunAfterLoad; 
	} else {
		var existingOnLoadFunctions = window.onload;
		window.onload = function() 
		{ 
			if (existingOnLoadFunctions) 
			{ 
				existingOnLoadFunctions(); 
			} 
			functionToRunAfterLoad(); 
		} 
	} 
} 