

/* 2a. setup fastfacts tooltips */
var fastFacts = {
	// show an item's fast facts:
	showTip: function(tipEl) {
		if($(tipEl)) {
			$(tipEl).tipFade.start({ 'opacity': 1, 'right': 90 });
		}
	},
	// hide an item's fast facts:
	hideTip: function(tipEl) {
		if($(tipEl)) {
			$(tipEl).tipFade.start({ 'opacity': 0, 'right': 50 });
		}
	},
	// intialise
	init: function() {
		// reset positioning by adding class to each 'fastFacts'
		$$('div.fastFacts').addClass('toolTip').each(function(item, index) {
			item.setProperty('id', 'tip' + index);	// add a unique ID to each 'fastFacts'
			item.setStyle('opacity', '0');	// hide
			// initialise Fx for each item:
			item.tipFade = new Fx.Styles(item, {duration: 250, wait: false});
			// attach mouse and click behaviours to fastFact
			item.addEvents({
				'mouseenter': function() {
					fastFacts.showTip('tip' + index);
					try {
						item.setStyle('cursor','pointer');	// show mouse cursor too... using "try" because this css not always supported (IE5.5 example)
					} catch(e) {
						return false;
					}
				},
				'mouseleave': function() {
					fastFacts.hideTip('tip' + index);
				},
				'click': function() {
					// includes onclick to allow a click anywhere. Enhanced via js to avoid keyboard-assisted tabbing focus confusion
					var parEl = item.getParent();	// get parent div
					var aEl = parEl.getElement('a');	// get the first link in div - must be product link
					window.self.location = aEl.getProperty('href');
				}
			});
		});
		// add tooltip mouse behaviours to FIRST image in a product div (the main product image)
		$$('div.product').each(function(item, index) {
			var imgEl = item.getElement('img');	// get the first image in div - must be main product image
			var aEl = item.getElement('a');	// get the first link in div - must be product link
			// attach mouse and click behaviours to image element
			if (imgEl != undefined)  //BOR
			{
			imgEl.addEvents({
				'mouseenter': function() {
					fastFacts.showTip('tip' + index);
					try {
						imgEl.setStyle('cursor','pointer');	// show mouse cursor too... using "try" because this css not always supported (IE5.5 example)
					} catch(e) {
						return false;
					}
				},
				'mouseleave': function() {
					fastFacts.hideTip('tip' + index);
				},
				'click': function() {
					// includes onclick to allow a click anywhere. Enhanced via js to avoid keyboard-assisted tabbing focus confusion
					window.self.location = aEl.getProperty('href');	
				}
			});
			}
			// also add behaviours to 1st link in the div (assistive, via keyboard focus):
			if (aEl != undefined)  //BOR
			{
			aEl.addEvents({
				'focus': function() {
					fastFacts.showTip('tip' + index);
				},
				'blur': function() {
					fastFacts.hideTip('tip' + index);
				}
			});
			} 
		});
	}
}

/* 2b. setup techinfo tooltips */
var techInfo = {
	init: function() {
		var toolTipContainer = new Element( 'div', {'id':'toolTipContainer'});
		techInfo.tipFadeIn = new Fx.Styles(toolTipContainer, {duration: 250, wait: true, onComplete: function() {
			techInfo.tipFadeOpen = true;
		}});
		techInfo.tipFadeOut = new Fx.Styles(toolTipContainer, {duration: 250, wait: true, onComplete: function() {
			techInfo.tipFadeOpen = false;
			techInfo.tipOpenId = null;
		}});
		$(toolTipContainer)
			.injectAfter('sport')
			.addEvents({
				'mouseenter': function() {
					clearTimeout(techInfo.interval);
				},
				'mouseleave': function() {
					techInfo.interval = setTimeout(function() {techInfo.hideTip()}, 250);
				}
			})
		;
		$$('#essentials .copy').addEvents({'scroll': function() {
			var top = parseInt($('toolTipContainer').getStyle('top'));
			var newScrollY =  this.getSize().scroll.y;
			techInfo.deltaScrollY = newScrollY - techInfo.scrollY;
			techInfo.scrollY = newScrollY;
			$('toolTipContainer').setStyle('top', top - techInfo.deltaScrollY);
			
		}});
		$$('.techInfo').getParent().each(function(item, index) {
			item
				.setProperty('id', 'techInfo' + index)
				.addEvents({
					'mouseenter': function() {
						//always cleartimeout when mouse over!
						clearTimeout(techInfo.interval);
						// different button and already open, or not open yet
						if (techInfo.tipOpenId !== this.id && techInfo.tipFadeOpen || !techInfo.tipFadeOpen) {
							techInfo.showTip(this);
							techInfo.tipOpenId = this.id;
						} 
					},
					'mouseleave': function() {
						techInfo.interval = setTimeout(function() {techInfo.hideTip()}, 250);
					}
				})
				.getChildren()
					.filterByClass('toolTip')
			;
		});
	},
	scrollY: 0,
	deltaScrollY: 0,
	interval: null,
	tipOpenId: null,
	tipFadeOpen: false,
	tipFadeIn: null,
	tipFadeOut: null,
	showTip: function(elem) {
		$(elem).getChildren().filterByClass('toolTip').each(function(item) {
			$('toolTipContainer').innerHTML = '';
			item.clone()
				//.setProperty('id', $(elem).id + '_open')
				.injectInside('toolTipContainer')
			;
		});
		var pos = techInfo.position(elem);
		$('toolTipContainer').setStyles({
			'left': pos.x,
			'top': pos.y,
			'visibility':'visible',
			'opacity':0
		});
		techInfo.tipFadeIn.start({'opacity': 1, 'top': pos.y + 10});
	},
	hideTip: function() {
		var pos = $('toolTipContainer').getPosition();
		pos.y -= 10;
		techInfo.tipFadeOut.start({'opacity': 0, 'top': pos.y});
	},
	position: function(elem) {
		var pos = $(elem).getPosition();
		$$('#toolTipContainer .wrap').each(function(item) {
			pos.y -= (item.getSize().size.y + 34);
		});
		$$('#essentials .copy').each(function(item) {
			pos.y -= item.getSize().scroll.y;
		});
		return {'x': pos.x - 40, 'y': pos.y};
	}
}

/* 3. setup product detail page */
var detailPanels = {
	/*
	NOTE:
	the toggle function requires a link to a named div - ie href="#summary"
	the full href is then used as an id css selector via $$(), which drives show/hide, class="selected" etc
	*/
	toggle: function(targEl) {
		this.panelArr.each(function(ref) {
			if (ref == targEl) {
				$$(ref).setStyle('display', 'block');
				$$('#prodNav a[href=' + ref + ']').addClass('selected');
			} else {
				$$(ref).setStyle('display', 'none');
				$$('#prodNav a[href=' + ref + ']').removeClass('selected');
			}
		});
	},
	// initialise
	init: function() {
		// create an array for toggling
		this.panelArr = new Array();
		$$('#prodNav li a').each(function(item, index) {
			var ref = item.getProperty('href');
			// append the href (ie "#summary") to the panel array
			detailPanels.panelArr[index] = ref;
			item.addEvent('click', function(e) {
				var e = new Event(e);
				detailPanels.toggle(ref);
				//return false;
				e.stop();
			});
			/* ALSO:
			search the product detail (uses css attribute selector) area for matching links not in the
			tabbed nav (ie a "more detail" link in the summary) via css attribute selector
			*/
			var rel = $$('#detailPanel a[href=' + ref + ']');	// matching example would be: href="#summary"
			if (rel.length > 0) {
				rel.each(function(item, index) {
					item.addEvent('click', function(e) {
						var e = new Event(e);
						detailPanels.toggle(ref);
						//return false;
						e.stop();
					});
				});
			}
		});
		// loop through the array that has been assembled, and hide named panels - skipping the first one, which is default selected (ie #summary)
		for (var i = 1; i < this.panelArr.length; i++) {
			$$(this.panelArr[i]).setStyle('display', 'none');
		}
	}
}

/* 4. product "Buy" form */
var addForm = {
	// display "selected" state for a radio - search for selected item
	showSelected: function(pass) {
		$$("input[name=" + pass + "]").each(function(item, index) {
			var parEl = item.getParent();
			if (item.checked == true) {
				parEl.addClass('selected');
			} else {
				parEl.removeClass('selected');
			}
		});
	},
	init: function() {
		// set up classnames
		$('productAttributes').addClass('jsenabled');
		// affix focus and blur events to radio items (assistive)
		$$('#productAttributes label input').each(function(item, index) {
			item.passed = item.getAttribute('name');
			item.parEl = item.getParent();
			item.addEvents({
				'focus': function() {
					item.parEl.addClass('focus');
				},
				'blur': function() {
					item.parEl.removeClass('focus');
				},
				'click': function() {
					addForm.showSelected(item.passed);
				}
			});
		});
		// affix rollover to buttons (assistive)
		if ($('addBtn')) {
			$('addBtn').addEvents({
				'mouseenter': function() {
					$('addBtn').setProperty('src', 'images/structural/btn_addToBasket_on.gif');
				},
				'mouseleave': function() {
					$('addBtn').setProperty('src', 'images/structural/btn_addToBasket.gif');
				}
			});
		}
		if ($('updBtn')) {
			$('updBtn').addEvents({
				'mouseenter': function() {
					$('updBtn').setProperty('src', 'images/structural/btn_updateBasket_on.gif');
				},
				'mouseleave': function() {
					$('updBtn').setProperty('src', 'images/structural/btn_updateBasket.gif');
				}
			});
		}
	}
}


/* 6. floating Window */
var floatingWindow = {
	init: function() {
		$('closeFloatingWindow').addEvent('click', function() {
			floatingWindow.hide();
		});
		window.addEvents({
			'resize': function() {
				floatingWindow.resize();
			},
			'scroll': function() {
				floatingWindow.resize();
			}
		});
	},
	openNow: null,
	openOnClose: null,
	// needs to be triggered whenever the content changes to correctly position an set the shadow
	resize: function() {
		if (floatingWindow.openNow !== null) {
			$('floatingWindowContainer').setStyle('top', window.getHeight() / 2 - $('floatingWindowContent').getSize().size.y / 2 + window.getScrollTop());
			$('floatingWindowShadow').setStyle('height', $('floatingWindowContent').getSize().size.y - 2);
		}
	},
	show: function(id, openOnClose) {
		// close open floating window
		floatingWindow.hide();
		floatingBasket.hide();
		if (window.ie6) $$('select').setStyle('display','none');
		if (openOnClose) {
			floatingWindow.openOnClose = openOnClose;
		}
		// open new floating window
		if ($(id)) {
			floatingWindow.openNow = id;
			if ($(id).hasClass('narrow')) {
				$('floatingWindow').addClass('narrow');
			}
			$('floatingWindowContainer').setStyle('display', 'block');
			$(id).setStyle('display', 'block');
			floatingWindow.resize();
		}
	},
	hide: function() {
		if (floatingWindow.openNow !== null) {
			if (window.ie6) $$('select').setStyle('display','inline');
			if (floatingWindow.openNow !== null) {
				$(floatingWindow.openNow).setStyle('display', 'none');
				floatingWindow.openNow = null;
				if ($('floatingWindow').hasClass('narrow')) {
					$('floatingWindow').removeClass('narrow');
				}
				$('floatingWindowContainer').setStyle('display', 'none');
			}
			if (floatingWindow.openOnClose !== null) {
				floatingBasket.show(floatingWindow.openOnClose, true);
				floatingWindow.openOnClose = null;
			}
		}
	}
}

/* 7. signin form switch*/
var signinForm = {
	init: function() {
		$('signinFaceB').setStyle('display', 'none');
		$('showSigninBtn').setStyle('display', 'block');
		$('showSigninBtn').addEvent('click', function() {
			$('signinFaceA').setStyle('display', 'none');
			$('signinFaceB').setStyle('display', 'block');
		});
	}
}

/* 8. address form */
var addressForm = {
	init: function() {
		$('copyAddressBtn').setStyle('display', 'block');
		addressForm.copyPaymentFields = $('copyAddressD').checked;
		addressForm.addEvents();
		if (addressForm.copyPaymentFields) {
			addressForm.toggleDeliveryFields();
		}
		$('copyAddressD').addEvent('click', function() {
			addressForm.copyPaymentFields = !addressForm.copyPaymentFields;
			addressForm.toggleDeliveryFields();
		});
		
	},
	copyPaymentFields: false,
	toggleDeliveryFields: function() {
		var loggedIn = ($('copyAddressD').className.indexOf('loggedIn') >= 0);
		var fields = (loggedIn) ? addressForm.fieldMappingLoggedIn : addressForm.fieldMapping;
		var copy = addressForm.copyPaymentFields
		for (i = 0; i < fields.length; i++) {
			if ($(fields[i][1])) {
				if (!loggedIn || i == 0) { // only disable fields if not logged in or if it's the first dropdown
					$(fields[i][1]).disabled = copy;
				}
				if (copy) {
					$(fields[i][1]).value = $(fields[i][0]).value;
				}
			}
		}
	},
	addEvents: function() {
		var events = new Array('keyup','change','blur'); // specify the events in this array
		var fields = addressForm.fieldMapping;
		for (var i = 0; i < fields.length; i++) {
			if ($(fields[i][0]) && $(fields[i][1])) {
				var args = "'" + fields[i][0] + "','" + fields[i][1] + "'";
				for (var j = 0; j < events.length; j++) {
					eval("$(fields[i][0]).addEvent('" + events[j] + "', function() { addressForm.copyField(" + args + ")});");
				}
			}
		}
	},
	copyField: function(source, target) {
		if (addressForm.copyPaymentFields) {
			$(target).value = $(source).value;
		}
	},
	// id's can be changed , if an id does not exist, nothing will happen
	fieldMapping: new Array(
		new Array('firstnameP',		'firstnameD'),
		new Array('lastnameP',		'lastnameD'),
		new Array('streetLine1P',	'streetLine1D'),
		new Array('streetLine2P',	'streetLine2D'),
		new Array('cityP',			'cityD'),
		new Array('countyP',		'countyD'),
		new Array('countryP',		'countryD'),
		new Array('postcodeP',		'postcodeD'),
		new Array('phonenumberP',	'phonenumberD')
	),
	fieldMappingLoggedIn: new Array(
		new Array('savedAddressP',	'savedAddressD'),
		new Array('firstnameP',		'firstnameD'),
		new Array('lastnameP',		'lastnameD'),
		new Array('streetLine1P',	'streetLine1D'),
		new Array('streetLine2P',	'streetLine2D'),
		new Array('cityP',			'cityD'),
		new Array('countyP',		'countyD'),
		new Array('countryP',		'countryD'),
		new Array('postcodeP',		'postcodeD'),
		new Array('phonenumberP',	'phonenumberD')
	)
}

/* 9. */
var genericRollover = {
	init: function() {
		if (window.ie6 || window.webkit) {
			$$('.btn').each(function(item, index) {
				// fix IE6 rendering bug
				if (window.ie6) {
					genericRollover.over(item);
					genericRollover.out(item);
				}
				// fix hover bugs
				item.addEvents({
					'mouseenter': function() {
						genericRollover.over(this);
					},
					'focus': function() {
						genericRollover.over(this);
					},
					'mouseleave': function() {
						genericRollover.out(this);
					},
					'blur': function() {
						genericRollover.out(this);
					}
				});
			});
		} else
		if (window.gecko) {
			// compensate for extra padding in Firefox
			if ($$('button.btn')) {
				$$('button.btn').each(function(item, index) {
					item.setStyles({
						'margin-top'   :parseInt(item.getStyle('margin-top'))    - 0 + 'px',
						'margin-right' :parseInt(item.getStyle('margin-right'))  - 3 + 'px',
						'margin-bottom':parseInt(item.getStyle('margin-bottom')) - 0 + 'px',
						'margin-left'  :parseInt(item.getStyle('margin-left'))   - 3 + 'px'
					});
				});
			}
		}
		if (window.webkit) {
			// compensate for extra padding in Safari
			if ($$('button.btn')) {
				$$('button.btn').each(function(item, index) {
					item.setStyles({
						'margin-top'   :parseInt(item.getStyle('margin-top'))    - 0 + 'px',
						'margin-right' :parseInt(item.getStyle('margin-right'))  - 2 + 'px',
						'margin-bottom':parseInt(item.getStyle('margin-bottom')) - 0 + 'px',
						'margin-left'  :parseInt(item.getStyle('margin-left'))   - 2 + 'px'
					});
				});
			}
		}
		
		
	},
	over: function(button) {
			if (button.className.indexOf('_') < 0) {
				button.className += '_hover';	
			}
	},
	out: function(button) {
		button.className = button.className.replace('_hover','');
	}
}

/* 10. NoScroll */
var noScroll = {
	init: function() {
		$$('.col2').each(function(item) {
			noScroll.toggle(item , 4);
		});
		$$('.col3').each(function(item) {
			noScroll.toggle(item , 6);
		});
	},
	toggle: function (item, maxNoScroll) {
		// add all {trigger} classes if criteria are met
		if (item.getChildren().length <= maxNoScroll) {
			var triggers = item.className.match(/\{(\w+)\}/g);
			if (triggers) {
				for (var i = 0; i < triggers.length; i++) {
					item.addClass(triggers[i].replace(/\{(\w+)\}/, '$1'));
				}
			}
		}
	}
}

// 11. imageTabs
var imageTabs = {
	init: function() {
		$('imagesTabs').getChildren().filterByTag('dt').each(function(item) {
			item.getChildren().filterByTag('a').each(function(item) {
				if (imageTabs.selectClass === null) {
					imageTabs.selectClass = item.getParent().className.match(/\{(\w+)\}/g).toString().replace(/\{(\w+)\}/, '$1');
				}
				item.addEvents({
					'mouseenter': function() {
						imageTabs.selectTab(this);
					},
					'focus': function() {
						imageTabs.selectTab(this);
					}
				});
			});
		});
	},
	selectClass: null,
	resetTabs: function() {
		$$('#imagesTabs .' + imageTabs.selectClass).removeClass(imageTabs.selectClass);
	},
	selectTab:function(elem) {
		imageTabs.resetTabs();
		$(elem).getParent()
			.addClass(imageTabs.selectClass)
			.getNext().addClass(imageTabs.selectClass)
		;
	}
}

/* DomReady Event makes initial function calls */
window.addEvent('domready', function() { 
	
	// 2a. initialise tooltips where present
	// not required  BOR
	/*
	if ($$('div.fastFacts').length > 0) {
		fastFacts.init();
	}
	*/
	// 2b. initialise tooltips where present
	if ($$('div.techInfo').length > 0) {
		techInfo.init();
	}
	// 3. initialise product detail panel if present
	if ($('productDetail')) {
		detailPanels.init();
		addForm.init();
	}
	
	// 6. initialise floating notice
	if ($('floatingWindowContainer')) {
		floatingWindow.init();
	}
	// 7. initialise signin form switch
	if ($('signinFaceA')) {
		signinForm.init();
	}
	// 8. initialise address form
	if ($('copyAddressBtn')) {
		addressForm.init();
	}
	// 9.
	if ($$('.btn')) {
		genericRollover.init();
	}
	// 10.
	if ($$('.col2') || $$('.col3')) {
		noScroll.init();	
	}
	// 11. imageTabs
	if ($('imagesTabs')) {
		imageTabs.init();
	}
	
});
