// CR638
var associatedProducts = new Array();

function registerAssociatedProduct(productId, checkboxId, quantity) {
	var associatedProduct = new Object();
	associatedProduct.productId = productId;
	associatedProduct.checkboxId = checkboxId;
	associatedProduct.quantity = quantity;
	associatedProduct.isFitting = false;
	associatedProducts[associatedProducts.length] = associatedProduct;
}
function registerFitting(productId, checkboxId, quantity, parentProductId) {
	var associatedProduct = new Object();
	associatedProduct.productId = productId;
	associatedProduct.checkboxId = checkboxId;
	associatedProduct.quantity = quantity;
	associatedProduct.isFitting = true;
	var fitting = new Object();
	fitting.fittingProductId = productId;
	fitting.parentProductId = parentProductId;
	associatedProduct.fitting = fitting;
	associatedProducts[associatedProducts.length] = associatedProduct;
}

function print_page_setup() {
	blocks=new Array(
		"pageheader",
		"mainnav",
		"search",
		"breadcrumb",
		"prodColRight",
		"footer"
	);
	hide(blocks)
	document.getElementsByTagName("body")[0].className="blankBody";
	printID=window.setTimeout("print_win()",500); // gives window time to redraw
};

function pre_print(){
};

function print_win() {
	clearTimeout(printID);
	t=1000;
	if(confirm("Print now?")) window.print()
	else t=0;
	showID=window.setTimeout("show(blocks)",t);
};

function hide(b){
	for (var i=0; i<b.length; i++) {
		if(document.getElementById(b[i])) {
			document.getElementById(b[i]).style.display="none";
		}
	}
};

function show(b){
	for (var i=0; i<b.length; i++) {
		if(document.getElementById(b[i])) {		
			document.getElementById(b[i]).style.display="block";
		}
	}
	document.getElementsByTagName("body")[0].className="";
};
	
function imageClick() {
   	var href = $(this).attr("href");
   	if (!(/[\w]+:\/\/[\w.]+\/\S*\S*[.]swf|jsp\S*/.test(href))) {
        $('#fullImage')
        	.attr('src',href)
			.attr('jqimg',href.replace('$prod$','$prodzoom$'));
   	}
	return false;
}
    
function validateQtyField(){
	var field = document.getElementById('WC_CachedProductOnlyDisplay_FormInput_quantity_In_OrderItemAddForm_1').value;
  	if (!isNaN(field) && field > 0 && field < 100){
		return true;
	}
  	else {
		alert(pageDetails.invalidInputMsg);
  		return false;
  	}
}

function carousel(jqObject,id) {
    jqObject
      .before('<img class="thumb-carousel-left" id="' + id + 'leftButton" src="' + pageDetails.jspStoreImgDir + 'images/thumb-carousel-button-left.jpg" alt="Shift items left" />')
      .after('<img class="thumb-carousel-right" id="' + id + 'rightButton" src="' + pageDetails.jspStoreImgDir + 'images/thumb-carousel-button-right.jpg" alt="Shift items right" />')
      .jCarouselLite({
        btnNext: 	"#" + id + "leftButton",
        btnPrev: 	"#" + id + "rightButton"
      });
	$(jqObject).find('a[class!=s7video]').click(imageClick);
};
  
function bv_readall_reviews() {
	bv_readall("#tab3");
}
  
function bv_readall_qas() {
	bv_readall("#tab4");
}
  
function bv_readall(pTab) {
	$(pTab).click();
}

function showvideo(el) {

	// extract the flv name from the href
	var rx = new RegExp(/e2\/Washford\/Videos\/(.*)\.flv/);
	var m = rx.exec($(el).attr("href"));
	if (!m || !m[1]) {
    	return true;
	}

	var videoName = m[1];
	var $imgDiv = $('#productFullImage');
	var $vidDiv = $('#scene7Video');

	$(el).unbind(
		'click'
	).click(function(){
		return hidevideo(el);
	}).attr(
		"videoactive", "true"
	).find("img").attr("src", "http://washford.scene7.com/is/image/Washford/returntoimage");

	$vidDiv.css({
		top:$imgDiv.position().top,
		left:$imgDiv.position().left,
		width:$imgDiv.width(),
		height:$imgDiv.height(),
		visibility:'visible',
		display:'block'
	});

	$imgDiv.css({
		visibility:'hidden',
		display:'none'
	});

	var viewerType = 'videoplayer';
	var myName = 's7player';

	var viewerUrl = "";  //Build Viewer Path to Viewer swf
 		viewerUrl += S7Config.isViewerRoot;
 		viewerUrl += "flash/" + viewerType + ".swf?";
 		viewerUrl += "&contentroot=/skins/Scene7SharedAssets/";
 		viewerUrl += "&instanceName=" + myName;
 		viewerUrl += "&movie=" + S7Config.contentRoot + "e2/Washford/Videos/" + videoName + ".flv";
 		viewerUrl += "&company=Washford";
 		viewerUrl += "&config=" + S7Config.contentRoot + "e2/Washford/eVideo_FS_PDP.xml";
 		viewerUrl += "&locale=en";

	// swfobject replaces rather than inserts, so create a temp child element
	var target = $vidDiv.html('<span id="swftgt"></span>');
	swfobject.embedSWF(
 		viewerUrl
 	    ,"swftgt"
 	    ,"300"
 	    ,"200"
 	    ,"9.0.115"
 	    ,false
 	    ,{} //flashvars
 	    ,{//params
			allowscriptaccess:"always"
			,quality:"high"
			,salign:"tl"
			,wmode:"transparent"
			,method:"prog"
			,allowfullscreen:"true"
 	    }
 	    ,{//attributes
			id: myName
 			,name: myName
		}
	);

	return false;
}

function hidevideo(el) {

	$(el).unbind(
		'click'
	).click(function(){
		return showvideo(el);
	}).removeAttr(
		"videoactive"
	).find("img").attr("src", "http://washford.scene7.com/is/image/Washford/playvideo");
	
	var $imgDiv = $('#productFullImage');
	var $vidDiv = $('#scene7Video');

	try {
		S7Config.setFlashParam('s7player','videoPlayback','stop');
	} catch (err){
	}
	$('#s7player').remove(); // without this IE7 has some problems in some cases

	$vidDiv.css({
		visibility:'hidden',
		display:'none'
	});
	
	$imgDiv.css({
		visibility:'visible',
		display:'block'
	});

	return false;
}

function PDPz1_zp(pids,
					zone,
					symbolic,
					target_id,
					category,
					rec_attributes,
					target_attributes,
					target_header_txt)
{
	var IDX_CATID = 9;
	var IDX_ITEMID = 2;
	var IDX_ITEMNAME = 1;
	var IDX_PRICE = 3;
	var IDX_WASPRICE = 4;
	var IDX_SAVING = 5;
	var IDX_RATING = 7;
	var IDX_PROMOTEXT = 6;
	var IDX_IMAGE = 8;
	if(symbolic != '_NR_')
	{
		var $sprod = $('#tradeupcol');
		if($sprod)
			$sprod.remove();
		
		var $e_zonediv = $(document.createElement('div'));
		$e_zonediv.attr('id', 'tradeupcol');
		
		var $e_h2 = $(document.createElement('h2'));
		$e_h2.text('Other customers went on to buy');
		
		var $zone = $(document.createElement('ul'));
		$zone.attr('id', 'pdp_zone1');
		
		$e_zonediv.append($e_h2);
		$e_zonediv.append($zone);
		$('#helpandadvicecol').after($e_zonediv);
		
		$zone.html('');
		for(var i=0; i<pids.length; i++)
		{
			var $e_li = $(document.createElement('li'));
			
			var $e_div1 = $(document.createElement('div'));
			$e_div1.addClass('tradeupprodimage');
			
			var $e_div2 = $(document.createElement('div'));
			$e_div2.addClass('tradeupproddescription');
			
			var $e_div3 = $(document.createElement('div'));
			$e_div3.addClass('tradeupprodprice');
			
			var $e_a1 =  $(document.createElement('a'));
			$e_a1.attr('href', 'product_storeId_' +
								storeId +
								'_catalogId_' +
								catalogId +
								'_productId_' +
								rec_attributes[i][IDX_ITEMID] +
								'_categoryId_' +
								rec_attributes[i][IDX_CATID] +
								'_langId_-1?cm_sp=Intelligent_Offer-_-Product_Details_Zone_1-_-Blank&iozone=PDPz1');
			var $e_a2 = $e_a1.clone();
			var $e_a3 = $e_a1.clone();
			$e_a1.attr('title', rec_attributes[i][IDX_ITEMNAME]);
			$e_a2.attr('title', rec_attributes[i][IDX_ITEMNAME]);
								
			var $e_img = $(document.createElement('img'));
			$e_img.attr('src', 'http://washford.scene7.com/is/image/Washford/'+rec_attributes[i][IDX_IMAGE]+'?$prodthumb$');
			// CR663.3.1: Start
			$e_img.attr('alt', rec_attributes[i][IDX_ITEMNAME]);
			// CR663.3.1: End
			
			$e_a1.append($e_img);
			$e_a2.html(rec_attributes[i][IDX_ITEMNAME]);
			$e_a3.html(currency + rec_attributes[i][IDX_PRICE]);
			$e_div1.append($e_a1);
			$e_div3.append($e_a3);
			$e_div2.append($e_a2);
			$e_div2.append($e_div3);
			$e_li.append($e_div1);
			$e_li.append($e_div2);
			$zone.append($e_li);
		}
	}
}

function PDPz2_zp(pids,
					zone,
					symbolic,
					target_id,
					category,
					rec_attributes,
					target_attributes,
					target_header_txt)
{
	var IDX_CATID = 9;
	var IDX_ITEMID = 2;
	var IDX_ITEMNAME = 1;
	var IDX_PRICE = 3;
	var IDX_WASPRICE = 4;
	var IDX_SAVING = 5;
	var IDX_RATING = 7;
	var IDX_PROMOTEXT = 6;
	var IDX_IMAGE = 8;
	
	if(symbolic != '_NR_')
	{
		var zone = document.getElementById('bottompanelcol2-inner');
		if(!zone)
		{
			var $col = $('#bottompanelcol2');
			var $printpag = $col.children('.printpag');
			$col.html('');
			
			var $tabs = $(document.createElement('ul'));
			$tabs.attr('class', 'tabs');
			var $li = $(document.createElement('li'));
			var $tab1 = $(document.createElement('a'));
			$tab1.attr('id', 'tab1');
			$tab1.attr('class', 'tab active');
			$tab1.attr('tablocator', 'Have you considered tab');
			$tab1.attr('href', '#dtab');
			$tab1.attr('title', 'Have you considered?');
			var $span = $(document.createElement('span'));
			$span.text('Have you considered?');
			$tab1.append($span);
			$li.append($tab1);
			$tabs.append($li);
			$col.append($tabs);
			
			var $clear1 = $(document.createElement('div'));
			$clear1.attr('class', 'clear');
			var $clear2 = $clear1.clone();
			var $border = $(document.createElement('div'));
			$border.attr('id', 'bottompanelcol2-border');
			var $zone = $(document.createElement('div'));
			$zone.attr('id', 'bottompanelcol2-inner');
			$border.append($zone);
			var $clearboth = $(document.createElement('div'));
			$clearboth.attr('class', 'clearBoth');
			$clear1.append($border);
			$clear1.append($clearboth);
			$clear1.append($printpag);
			$col.append($clear1);
			$col.append($clear2);
		}
		else
		{
			var $zone = $(zone);
		}
		
		$zone.html('');
		var catentry_idx = 40; //default to 40 which is unlikely to be used (30 was used!!!).
		for(var i=0; i<pids.length; i++)
		{
			var $e_div1 = $(document.createElement('div'));
			$e_div1.addClass('relatedproduct');
			
			var $e_div2 = $(document.createElement('div'));
			$e_div2.addClass('relprodimage');
			
			var $e_div3 = $(document.createElement('div'));
			$e_div3.addClass('relproddescandprice');
			
			var $e_div4 = $(document.createElement('div'));
			$e_div4.addClass('relproddesc');
			
			var $e_div5 = $(document.createElement('div'));
			$e_div5.addClass('relprodprice');
			
			var $e_div6 = $(document.createElement('div'));
			$e_div6.addClass('relprodbuy');
			
			var $e_div7 = $(document.createElement('div'));
			$e_div7.addClass('clearBoth');
			
			var $e_a1 = $(document.createElement('a'));
			$e_a1.attr('href', 'HalfordsProductDetailsLiteView?storeId=' +
								storeId +
								'&langId=-1' +
								'&productId=' +
								rec_attributes[i][IDX_ITEMID] +
								'&cm_sp=Intelligent_Offer-_-Product_Details_Zone_2-_-Blank&iozone=PDPz2&TB_iframe=true&TB_C_ID=productdetails&TB_C_TITLE=' +
								escape(rec_attributes[i][IDX_ITEMNAME]) +
								'&width=800');
			$e_a1.attr('title', 'Link to product description of ' + rec_attributes[i][IDX_ITEMNAME]);
			$e_a1.attr('class', 'thickbox');
			$e_a1.attr('rel', 'nofollow');
			var $e_a2 = $e_a1.clone();
			
			var $e_img = $(document.createElement('img'));
			$e_img.attr('src', 'http://washford.scene7.com/is/image/Washford/'+rec_attributes[i][IDX_IMAGE]+'?$prodthumb$');
			$e_img.attr('alt', 'Click to view product details');
			
			var $e_input1 = $(document.createElement('input'));
			$e_input1.attr('name', 'catEntryId_' + (catentry_idx+i));
			$e_input1.attr('id', 'catEntryId_' + (catentry_idx+i));
			$e_input1.attr('type', 'checkbox');
			$e_input1.attr('value', rec_attributes[i][IDX_ITEMID]);
			$e_input1.bind('click', {details:rec_attributes[i]}, function(e){
				var el = $(e.currentTarget);
				if (!el.attr('checked') || !cmCreateProductviewTag) {
					updateCMCookie(e.data.details[IDX_ITEMID], '');
					return;
				}

				var pageId = 'Product: ' + e.data.details[IDX_ITEMNAME] + ' (' + e.data.details[IDX_ITEMID] + ')';
				if (cG7) {
					cG7.cM0[cm_ClientID] = pageId;
				}
				// CR580
				cmCreateProductviewTag(	pageId
										, e.data.details[IDX_ITEMID]
										, e.data.details[IDX_ITEMNAME]
										, e.data.details[IDX_CATID]
										, storeId			// WSC "Store ID" value
										, "N"				// Flag to count as a PageView: "Y" or "N"
										, "masterItemCategory" // no longer used but maintained for param order
										, null //allows client to override WSC auto-catID value with extraparm1
										, null //totalreviewcount
										, e.data.details[IDX_RATING] //avgRating
										, null //total rating only count
										, null //buyagainperc
										, e.data.details[IDX_RATING] + "-_--_--_--_--_-" + escape(e.data.details[IDX_PROMOTEXT]) + "-_--_-PDPz2"
										);
				resetCMCookie(e.data.details[IDX_ITEMID], 
					e.data.details[IDX_RATING], 
					'', 
					'', 
					'', 
					'', 
					escape(e.data.details[IDX_PROMOTEXT]), 
					'', 
					'PDPz2');
				
			});
			
			var $e_input2 = $(document.createElement('input'));
			$e_input2.attr('name', 'quantity_' + (catentry_idx+i));
			$e_input2.attr('type', 'hidden');
			$e_input2.attr('value', 1);
			
			$e_a1.append($e_img);
			$e_a2.html(rec_attributes[i][IDX_ITEMNAME]);
			$e_div2.append($e_a1);
			$e_div4.append($e_a2);
			$e_div5.html(currency + rec_attributes[i][IDX_PRICE]);
			$e_div6.html('Tick to buy ');
			$e_div6.append($e_input1);
			$e_div6.append($e_input2);
			$e_div3.append($e_div4);
			$e_div3.append($e_div5);
			$e_div3.append($e_div6);
			
			$e_div1.append($e_div2);
			$e_div1.append($e_div3);
			$e_div1.append($e_div7);
			
			$zone.append($e_div1);
			
			registerAssociatedProduct(rec_attributes[i][IDX_ITEMID], 'catEntryId_' + (catentry_idx+i), '1');
			
		}
		
		$('#bottompanelcol2>.tabs>li:first>a>span').html('Customers also bought');
	}

	tb_init('a.thickbox, area.thickbox, input.thickbox');
}

function updateCMCookie(productId, zoneId)
{
	var cmCookieName = 'CM_COOKIE';
	var cmSessionCookie = readCookie(cmCookieName);
	var pProductIndex = cmSessionCookie.indexOf(productId);
	if(pProductIndex < 0)
	{
		var newProductCookie = productId + '%5e%3ah%5e%3d' + escape(zoneId) +'%5e%7c%5e%3b';
		cmSessionCookie += newProductCookie;
	}
	else
	{
		var pStartIndex = cmSessionCookie.indexOf('h%5e%3d', pProductIndex);
		var pEndIndex = cmSessionCookie.indexOf('%5e%3b', pStartIndex);
		var cookieStr = '%5e%3ah%5e%3d' + zoneId +'%5e%7c%5e%3b';
		cmSessionCookie = cmSessionCookie.substring(0, pStartIndex) + cookieStr + cmSessionCookie.substring(pEndIndex);
	}
	document.cookie = cmCookieName + '=' + cmSessionCookie;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return "";
}

function resetCMCookie(productId,
						avgRating,
						numOfReviews,
						buyAgainPerc,
						fulfillmentMethod,
						webExclusive,
						promoName,
						productType,
						ioZone)
{
	var cmCookieName = 'CM_COOKIE';
	var cmSessionCookie = readCookie(cmCookieName);
	var cookieStr = productId + '%5e%3a'
		+ 'a%5e%3d' + avgRating + '%5e%7c'
		+ 'b%5e%3d' + numOfReviews + '%5e%7c'
		+ 'c%5e%3d' + buyAgainPerc + '%5e%7c'
		+ 'd%5e%3d' + fulfillmentMethod + '%5e%7c'
		+ 'e%5e%3d' + webExclusive + '%5e%7c'
		+ 'f%5e%3d' + promoName + '%5e%7c'
		+ 'g%5e%3d' + productType + '%5e%7c'
		+ 'h%5e%3d' + ioZone + '%5e%7c'
	
	var pProductIndex = cmSessionCookie.indexOf(escape(productId));
	if(pProductIndex < 0)
	{
		cmSessionCookie += cookieStr + "%5e%3b";
	}
	else
	{
		var pEndIndex = cmSessionCookie.indexOf('%5e%3b', pProductIndex);
		cmSessionCookie = cmSessionCookie.substring(0, pProductIndex) + cmSessionCookie.substring(pEndIndex + 6) + cookieStr + "%5e%3b";
	}
		
	document.cookie = cmCookieName + '=' + cmSessionCookie;
}

var productName;

function _setProductName(name) {
	productName = name;
}


var currentScene7PdpTarget = "";
function s7_doLargerScene7Overlay() {
	findThumbnailLinksToAddClasses();
	// on page load, set the dialog options.
	$('#dialog').jqm({ onShow: s7_fillDialogContent, onHide: s7_clearDialogAndContent, overlayClass: "jqmDarkOverlay" });
}
function findThumbnailLinksToAddClasses(){
	var temp = $("#thumbs").find("li");
	var max = temp.length;
	var thumbArray = new Array();
	for (i = 0; i < max; i++) {
		var TestLink = $(temp[i]).find("a").attr("href"); 
	   	if (/[\w]+:\/\/[\w.]+\/\S*\S*[.]swf|jsp\S*/.test(TestLink)) {
	   		$(temp[i]).find("a").removeClass("s7video").addClass("jqModal");
	   	}
	}
}
function s7_fillDialogContent() {
	// check arguments to see what the calling link id was
	var args = Array.prototype.slice.call(arguments);
	var linkType = "image";
	if(args[0]["t"].id == "viewLarger"){
		currentScene7PdpTarget = s7_getScene7ProductID($("#fullImage").attr("src"));
	} else {
		currentScene7PdpTarget = s7_getScene7ProductID(args[0]["t"].href);
		if(/videoplayer*/g.test(args[0]["t"].href)){
			linkType = "video";
		} else if(/flash_spin*/g.test(args[0]["t"].href)) {
			linkType = "spin";
		}
	}
	// set dialog styles
	$("#dialog").css({ "display": "block" });
	// create a default placeholder in dialog for flash
	$("#dialog #dialogContent").empty().append(
		"<div id=\"scene7_container\"><div id=\"scene7_placeholder\"></div></div>"
	);
	// parse the thumbnails in the PDP and append the with different methods in the overlay
	s7_addThumbnailsFromPDP();
	s7_addEventsForOverlayThumbnails();
	s7_isThereATarget();
}
function s7_clearDialogAndContent() {
	currentScene7PdpTarget = "";
	$("#dialog").css({ "display": "none" });
	$("#dialog #dialogContent").empty();
	$(".jqmDarkOverlay").remove();
}
function s7_addThumbnailsFromPDP() {
	var temp = $("#thumbs").find("li");
	var max = temp.length;
	if (max > 0) {
		//
		// If there are thumbnails, use them as the basis for thumbnails in the main viewer
		//
		var thumbArray = new Array();
		var firstItem;
		var foundDuplicate = false;
		var min3 = (max <= 3) ? 0 : 3;
		for (i = min3; i < max; i++) {
			if (i > min3) {
				if ($(temp[i]).find("a").attr("href") === $(thumbArray[0]).find("a").attr("href")) {
					foundDuplicate = true;
				}
			}
			if (!foundDuplicate) {
				thumbArray.push($(temp[i]));
			}
		}
		var s7_ul = document.createElement("ul");
		$(s7_ul).attr("id", "scene7_thumbList");
		var s7_li = document.createElement("li");
		for (i = 0; i < thumbArray.length; i++) {
			s7_li = document.createElement("li");
			
			var s7_a = document.createElement("a");
			$(s7_a).attr("href",$($(thumbArray[i])).find("a").attr("href"));
			$(s7_a).attr("class",$($(thumbArray[i])).find("a").attr("class"));

			var s7_img = document.createElement("img");
			$(s7_img).attr("src",$($(thumbArray[i])).find("img").attr("src"));

			$(s7_a).append(s7_img);
			$(s7_li).append(s7_a);
			
			$(s7_li).find("a").attr({ "rev": s7_getScene7ProductID($($(thumbArray[i])).find("a").attr("href")), "type": s7_getScene7ImageType($(thumbArray[i])) });

			$(s7_ul).append(s7_li);
		}
		$("#dialog #dialogContent").append(s7_ul);
		isTheMainImageIncludedInTheThumbnails();
	} else {
		//
		// If there are no thumbnails, then use the main image and the
		// viewLarger as the basis to make a thumbnail in the large item
		//
		s7_ul = document.createElement("ul");
		$(s7_ul).attr("id", "scene7_thumbList");
		s7_li = document.createElement("li");
		var s7_li_a = document.createElement("a");
		$(s7_li_a).attr({
			"href": $("#fullImage").attr("src"),
			"rev": s7_getScene7ProductID($("#fullImage").attr("src")), 
			"type": "image"
		});
		$(s7_li).append(s7_li_a);
		var imagePath = $("#fullImage").attr("src");
		imagePath = imagePath.replace(/\$prod\$/g, '\$prodthumb\$');
		var s7_li_img = document.createElement("img");
		$(s7_li_img).attr({"src":imagePath});
		$(s7_li_a).append(s7_li_img);
		$(s7_ul).append(s7_li);
		$("#dialog #dialogContent").append(s7_ul);
	}
}
function isTheMainImageIncludedInTheThumbnails(){
	var mainImageId = s7_getScene7ProductID($("#fullImage").attr("src"));
	var mainImageIncluded = false;
	$("#scene7_thumbList").find("a").each(function(){
		if($(this).attr("rev") == mainImageId){
			mainImageIncluded = true;
		}
	});
	if(!mainImageIncluded){
		var s7_li = document.createElement("li");
		var s7_li_a = document.createElement("a");
		$(s7_li_a).attr({
			"href": $("#fullImage").attr("src"),
			"rev": mainImageId, 
			"type": "image"
		});
		$(s7_li).append(s7_li_a);
		var imagePath = $("#fullImage").attr("src");
		imagePath = imagePath.replace(/\$prod\$/g, '\$prodthumb\$');
		var s7_li_img = document.createElement("img");
		$(s7_li_img).attr({"src":imagePath});
		$(s7_li_a).append(s7_li_img);
		$("#scene7_thumbList").append(s7_li);
	}
}
function s7_getScene7ProductID(link) {
	var ID = "";
	if (link.lastIndexOf("is\/image") > 0) {
		ID = link.substring(link.lastIndexOf("\/") + 1, link.indexOf("?"));
	} else if (link.lastIndexOf("spin\/flash_spin.jsp") > 0) {
		ID = getUrlVariable(link, "sku");
	} else if (link.lastIndexOf("flash\/videoplayer.swf") > 0) {
		var temp = getUrlVariable(link, "encodingXml");
		ID = temp.substring(temp.lastIndexOf("\/") + 1, temp.lastIndexOf(".xml"));
	}
	return ID;
}
function s7_getScene7ImageType(link) {
	var href = $(link).find("a").attr("href");
	if (href.lastIndexOf("is\/image") > 0) {
		return "image";
	} else if (href.lastIndexOf("spin\/flash_spin.jsp") > 0) {
		return "spin";
	} else if (href.lastIndexOf("flash\/videoplayer.swf") > 0) {
		return "video";
	}
	return "nothing";
}
function s7_addEventsForOverlayThumbnails() {
	$("#scene7_thumbList").find("a").removeClass("jqModal").unbind("click").bind("click", s7_show_scene7_viewer);
}
function s7_isThereATarget() {
	if (currentScene7PdpTarget != "") {
		var currentTargetLink = $("#scene7_thumbList").find("a[rev='" + currentScene7PdpTarget + "']");
		$(currentTargetLink).click();
	}
}
function s7_setCurrentThumbnail(whichThumbnail) {
	$("#scene7_thumbList").find("li").removeClass("current");
	$(whichThumbnail).parent().addClass("current");
}
function s7_show_scene7_viewer() {
	s7_setCurrentThumbnail(this);
	s7_clearScene7Placeholder();
	var thisType = $(this).attr("type");
	/*********/
	var flashvars = {};
	var params = {
		allowfullscreen: "true",
		allowscriptaccess: "always",
		menu: "false",
		quality: "high",
		pluginspage: "http://www.adobe.com/go/getflashplayer",
		scale: "noscale",
		salign: "LT",
		wmode: "transparent"
	};
	var attributes = {};
	var contentID = $(this).attr("rev");
	/*********/
	if (thisType == "video") {
		var viewerUrl = "http://washford.scene7.com/s7viewers/flash/videoplayer.swf?method=&contentRoot=/skins/&config=Washford/HalfordsVideoViewer&locale=en";
		viewerUrl += "&movie=/e2//Washford/Videos/" + contentID;
		swfobject.embedSWF(viewerUrl, "scene7_placeholder", "750", "430", "7.0.14.0", "expressInstall.swf", flashvars, params, attributes);
		try {
			cmCreateConversionEventTag(productName, "2", "Videos");
		} catch (e) {}
	} else if (thisType == "spin") {
		var viewerUrl = "http://washford.scene7.com/s7viewers/flash/genericspin.swf?serverUrl=/is/image/&contentRoot=%2fskins&config=Washford/HalfordsSpinViewer&locale=en";
		viewerUrl += "&image=Washford/" + contentID;
		swfobject.embedSWF(viewerUrl, "scene7_placeholder", "750", "430", "7.0.14.0", "expressInstall.swf", flashvars, params, attributes);
		try {
			cmCreateConversionEventTag(productName, "2", "Spinset 360");
		} catch (e) {}
	} else if (thisType == "image") {
		var viewerUrl = "http://washford.scene7.com/s7viewers/flash/genericzoom.swf?serverUrl=/is/image/&contentRoot=%2fskins&config=Washford/HalfordsZoomViewer2&locale=en";
		viewerUrl += "&image=Washford/" + contentID;
		swfobject.embedSWF(viewerUrl, "scene7_placeholder", "750", "430", "7.0.14.0", "expressInstall.swf", flashvars, params, attributes);
	}
	$(this).blur();
	return false;
}
function s7_clearScene7Placeholder() {
	$("#scene7_placeholder").remove();
	$("#scene7_container").append("<div id=\"scene7_placeholder\"></div>");
}
function getUrlVariable(url, variable) {
	if (url === undefined) {
		url = window.location.href;
	}
	var vars = [], hash;
	var hashes = url.slice(url.indexOf('?') + 1).split('&');
	for (var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	if (variable === undefined) {
		return vars;
	}
	return vars[variable];
}

$(document).ready(function() {
			
	var activeTabId = "tab1";
	var requestedTabId = "";
	if (document.location.href.indexOf("#") != -1) {
		requestedTabId = document.location.href.substr(document.location.href.indexOf("#") + 1);
	}

    $(".content").hide();
    $("#itab1content").show(); 
    $("#dtab1content").show(); 

    if ($("#itab1content").find("li a").length <= 3){
		$("#itab1content").find('a[class!=s7video]').unbind("click").bind("click",imageClick);
	}

    $("a.tab")
		.click(function() {
	        // toggle tabs  
	        $(this).parent().parent().find(".active").removeClass("active");
	        $(this).addClass("active");   
	           
	        // slide all elements with the class 'content' up   
	        var content = $("#" + $(this).attr("tablocator"));
	        content.parent().find(".content").hide();   
	        content.show();
	
	        if (content.find("li a").length > 3 && $("#" + content.attr("id") + "leftButton").length == 0) {
	          carousel(content, content.attr("id"));
	        }
	    })
	    .each(function() {
			$(this).attr("tablocator", $(this).attr("title"));
			
			var currentTabId = $(this).attr("id");

			// CR626: Start
			if (currentTabId == "tab0") {
				activeTabId = currentTabId;
			}
			// CR626: End

			try {
				if (currentTabId == requestedTabId) {
					activeTabId = requestedTabId;
				}
				if (currentTabId == activeTabId) {
					$(this).click();
				}
			} catch (err) {}
	
			var tabTitle = "";
			try {
				tabTitle = $(this).children("span").text();
				$(this).attr("title", "Display " + tabTitle + " tab");
			} catch (err) {
				$(this).attr("title", "Display tab");
			}
		});
    
    // when a non-s7 video link is clicked, search for all active s7 videos and simulate a click on their icon to stop them
    /**
    $("div[@id^=itab] a[class!=s7video]").click(imageClick).click(function(){
    	$("a[videoactive=true]").trigger('click');
	});
    /**/
    
    $("div[id^=itab] a[class=s7video]").each(function(i,el){
   		//$(el).click(function(){return showvideo(el);});
    	$(el).removeClass("s7video").addClass("jqModal");
		$(el).find("img").attr("src", "http://washford.scene7.com/is/image/Washford/playvideo");
    });

    $("#itab1content")
    	.each(function() {
		    if ($(this).find("li a").length > 3)
		    	carousel($(this), "itab1content");
    	});
    
	// CR613
	$('.definingattributes-dd-opt ul')
		.each(function(){
			$(this).parent().append('<select id="facetSelector"> </select>');
			$(this).find('li>*:first-child').each(function(){
				if ($(this).attr('tagName') == 'A') {
					$('#facetSelector').append('<option value="' + $(this).attr('href') + '">' + $(this).find('span').text() + '</option>');
				}
				else {
					$('#facetSelector').append('<option value="" selected="selected">' + $(this).text() + '</option>');
				}
			});
	    })
	    .remove();
    
    $('#facetSelector').change(function() {
		window.location.replace($(this).attr('value'));
		return;
    });
    
    $(".productFullImage").find('img[@src$="$prod$"]').each(function() {
      $(this).attr('jqimg',$(this).attr('src').replace('$prod$','$prodzoom$'));
    });
      
  	$('#mouseOffMessage').hide();

	$(".jqzoom")
	  	.mouseover(function() {
	  		$('#mouseOffMessage').show();
	  		$('#mouseOverMessage').hide();
	  	})
	  	.mouseout(function() {
	  		$('#mouseOffMessage').hide();
	  		$('#mouseOverMessage').show();
	  	})
		.jqueryzoom({
	        xzoom: 421, 
	        yzoom: 274,
	        offset: 60,
	        offsetTop: 26,
	        preload: 0
	  	});
	  	
	$("#OrderItemAddForm").submit(function(event) {
		var lReturn = $(this).attr('disableSubmit') == 'Y' ? false : true;
		$(this).attr('disableSubmit', 'N');
		return lReturn;
	});

	$('#reserveYourBikeForXmas').click(function() {	
		if (this.checked) {
			tb_show(null, '#TB_inline?height=200&width=350&inlineId=reserveYourBikeForXmasPopup', null);
		}
	});	

	positionTooltip = function(event) {
		var x = event.pageX - 200;
		var y = event.pageY + 20;
		$('div#tooltip').css({"top":y, "left":x});
	}

	showTooltip = function(event) {
		hideTooltip();
		var text = $(this).attr('tiptext');
		
		$('<div id="tooltip">' + text + '</div>').appendTo('body');
		positionTooltip(event);
	}

	hideTooltip = function() {
		$('div#tooltip').remove();
	}

	$(".randctip[@id=available]").tooltip({text: pageDetails.rAndCAvailableMsg});
	$(".randctip[@id=notavailable]").tooltip({text: pageDetails.rAndCNotAvailableMsg});
	
	$(".deliverytip[@id=available]").tooltip({text: pageDetails.hDAvailableMsg});
	$(".deliverytip[@id=notavailable]").tooltip({text: pageDetails.hDNotAvailableMsg});
	
	$("#webexclusivedescription").tooltip({text: pageDetails.webExclusiveMsg});
	
	$('#storeFitOption').click(function() {
		$(this).attr('checked') && $('#mobileFitOption').attr('checked', false);
	});
	
	$('#mobileFitOption').click(function() {
		$(this).attr('checked') && $('#storeFitOption').attr('checked', false);
	});
	
	//Product variation behaviour	
	
	//create status div for swatched but not for drop down
	if ($(".definingattributes-dd:has(label)").length>0) var statusHtml='';
	else var statusHtml = '<div class="swatchstatus">&#160;</div>';
	
	var selectedValue="";
	var t;
	//set up variations
	$(".variations")	
	//show the content
	.fadeIn("slow")
	//append status div
	.find("label:first").after(statusHtml).end()
	//set up selected
	.find(".colourItem").each(function() {
		//set selected		
		if ($(this).find("span").hasClass("current")) {
			selectedValue = $(this).find("span.current img").attr("alt");
			$(".swatchstatus").html(selectedValue);			
		}			
	})
	//set up hover function
	.mouseover(function() {
		if (t) clearTimeout(t);		
		$(this).parent().parent().parent().find(".swatchstatus").html($(this).find("span img").attr("alt"));
		
	})
	.mouseout(function() {
		//delay change back to stop flicker if rolling between
		t=setTimeout(function(){$(".swatchstatus").html(selectedValue)}, 100);			
	}).end()
	.find('a').click(function() {
		window.location.replace($(this).attr("href"));		
	});	
	
	s7_doLargerScene7Overlay();

});

