var siteAddr = location.protocol + '//' + location.host + '/';
var themeCol;
window.onload = function(){
	themeCol = getTheme('body');
}
function getTheme(e){
		themeCol = $$(e).get('id');
		return themeCol;
}
/* Pre Load Images */
var imgPath = siteAddr + '_img/front_end/'; 
var preImgs = [
	imgPath + 'themes/'+themeCol+'/open.gif',
	imgPath + 'themes/'+themeCol+'closed.gif',
	imgPath + 'themes/'+themeCol+'basopen.gif',
	imgPath + 'themes/'+themeCol+'loader.gif',
	imgPath + 'keywords/kbgtop.png',
	imgPath + 'keywords/kbgbase.png',
	imgPath + 'keywords/kbgrep.png',
	imgPath + 'buttons/pifsubmit.gif',
	imgPath + 'brands/scroll_bg.gif'
];
var preImgLoads = new Asset.images(preImgs);


// for forms
document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; opacity: 0; filter: alpha(opacity=0); z-index: 5; } .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');

window.addEvent('domready', function(){
	//Prevent the search from processing if nothing has been entered
	if($('topSearchBut')){
		$('topSearchBut').addEvent('click', function(e){
			var searchVal = $('mainsearch').get('value');
			var searchTitle = $('mainsearch').get('title');
			if(searchVal == searchTitle){
				alert('Please enter a search term');
				e.stop();
			}
		});
	}
		
	//Call to function to clear input areas with a class of textarea	
	var textareas = $$('.textarea').length;
	if(textareas > 0){
		$$('.textarea').addEvent('focus', function(e){inputClear(e,this);});
		// apply styling if inputs have alternate values
		$$('.textarea').each(function(e){
			var selectVal = e.get('value');
			var selectTitle = e.get('title');
			if(selectVal != selectTitle){
				e.addClass('highon');
			}
		});
	}
	var pwrdBoxes = $$('.passwordClear').length;
	if(pwrdBoxes > 0){
		setHandlers();
	}
	var scrollCount = $$('.smoothAnchor').length;
	if(scrollCount > 0){
		var mySmoothScroll = new Fx.SmoothScroll({duration:1000, links: '.smoothAnchor', wheelStops: false});
	}
	if(Browser.Engine.trident4 && $$('.viewopts')){
		$$('#topnav ul li').addEvent('mouseenter', function(e){ieSelectLists('on');});
		$$('#topnav ul li').addEvent('mouseout', function(e){ieSelectLists('off');});
	}
	if(Browser.Engine.trident4 && $('seoblock')){
		$('seoblock').setStyle('bottom', '0px');
	}
	if($('seoblock')){
		var seoSize = $('seoblock').getSize();
		$('container').setStyle('padding-bottom', parseInt(seoSize.y));
		$('seoblock').setStyle('left', '10px');
	}
	
	//call the minibasket sliding functionality if it exists
	if($('showBasInfo')){
		showminibasket();
	}
	//call to show the hidden forgotten password block
	if($('pwBlock')){
		$('showFPBlock').addEvent('click', function(e){
			$('loginForm').addClass('hide');
			$('pwBlock').removeClass('hide');
		});
		$('showLBlock').addEvent('click', function(e){
			$('loginForm').removeClass('hide');
			$('pwBlock').addClass('hide');
		});
	}
	//Reassurance & Comments
	if($('sComm') || $('rea')){
		// define general variables
		var reaphTotal = $$('.reaTxt').length;
		var comphTotal = $$('.sCommTxt').length;
		var phraseCount = 1;
		var commCount = 1;
		var reaStart = 2; // start at 2 for the initial load on reasurance
		var commStart = 2; // start at 2 for the initial load on reasurance
		var i = 0;
		var reaTimer = 3500;//reasurance timer
		var commTimer = 6500;//comments timer
		
		//Reasurance block
		if($('rea')){
			$$('.reaOpZero').set('opacity','0'); // set the opcity of any with class to 0		
			$$('.reaOpZero').removeClass('hide');
			var reaLoop = function(){			
				var nxtRea = 'reaTxt_' + reaStart;
				showNextPhrase('reaTxt_' + phraseCount, nxtRea);
				phraseCount++; // count phrase up
				reaStart++; // count starting next reasurance up
				if(reaStart > reaphTotal){
					reaStart = 1;
				}	
				if(phraseCount > reaphTotal){
					phraseCount = 1;
				}
			}
			if(reaphTotal > 1){var periodicalTab = reaLoop.periodical(reaTimer, this);} // only call the periodic function if there is more than 1 phrase
		}
		
		//Comments block
		if($('sComm')){
			$$('.reaOpZero').set('opacity','0'); // set the opcity of any with class to 0	
			var commLoop = function(){			
				var nxtComm = 'sCommTxt_' + commStart;
				showNextPhrase('sCommTxt_' + commCount, nxtComm);
				commCount++; // count phrase up
				commStart++; // count starting next comment up
				if(commStart > comphTotal){
					commStart = 1;
				}	
				if(commCount > comphTotal){
					commCount = 1;
				}
			}
			if(comphTotal > 1){var periodicalTab = commLoop.periodical(commTimer, this);} // only call the periodic function if there is more than 1 comment
		}
	}
	
	//Form select conversion
	var countSelects = $$('.select').length;
	if(!Browser.Engine.trident4 && countSelects > 0){
		var Custom = sortSelects();
	}
	if(!Browser.Engine.trident4 && countSelects > 0){
		$$('.styled').addEvent('change', function(e){
			var selectVal = this.getProperty('value');
			var getLastLabel = this.getPrevious('label');
			if(getLastLabel.hasClass('chglbl') && selectVal != ''){
				if(getLastLabel.hasClass('altAdd')){
					var addArray;
					if(getLastLabel.hasClass('aasingle')){
						addArray = selectVal.split('|');
						getLastLabel.set('html', addArray[1]);
					}else{
						addArray = selectVal.split('#');
						getLastLabel.set('html', addArray[5]);
					}
				} else{
					getLastLabel.set('html', selectVal);
				}
				getLastLabel.addClass('highon');
			}
		});
		$$('.styled').each(function(e){
			var selectVal = e.get('value');
			var getLastLabel = e.getPrevious('label');
			if(selectVal != ''){
				if(getLastLabel.hasClass('altAdd')){
					var addArray;
					if(getLastLabel.hasClass('aasingle')){
						addArray = selectVal.split('|');
						getLastLabel.set('html', addArray[1]);
					}else{
						addArray = selectVal.split('#');
						getLastLabel.set('html', addArray[5]);
					}
				} else{
					getLastLabel.set('html', selectVal);
				}
				getLastLabel.addClass('highon');
			}
		});
	}
	
	//Logo Scrolling section
	if($('brandslide')){
		logoScroll();
	}
	
	// Pop up call
	var popCount = $$('.prodpop').length;
	if(popCount > 0){
		callPopUp();
	}
	
	//Fading banners
	if($('bantabs')){
		fadeBanBlock();
	}
	// if they click spec link
	if($('proddescarea')){
		if($('proddetslinks')){
			var linktowrite = $('proddescarea').addEvent('click', function(e){
				var getHref = $('proddescarea').get('href'); // get the name of the link
				var cleanHref = getHref.replace('#',''); // clean up the name of the link
				showhidediv($(cleanHref),e);
			});	
		}
		var scrolltodesc = new Fx.SmoothScroll({duration:1000, links: '#proddescarea'});
	}
	// if they click the write a review link
	if($('prodreviewread')){
		if($('proddetslinks')){
			$('prodreviewread').addEvent('click', function(e){showhidediv($('prodrev_link'),e);});
		}
		var scrolltoread = new Fx.SmoothScroll({duration:1000, links: '#prodreviewread'});
	}
	// if they click the addon link
	if($('prodaddonread')){
		var scrolltoadd = new Fx.SmoothScroll({duration:1000, links: '#prodaddonread'});
	}
	// if there are bundles available
	if($('prodbundleread')){
		var scrolltobun = new Fx.SmoothScroll({duration:1000, links: '#prodbundleread'});
	}
	// if they click the info pages link
	if($('prodpgsread')){
		var scrolltowrite = new Fx.SmoothScroll({duration:1000, links: '#prodpgsread'});
	}
	// hide relevant divs on page load if javascript is on
	if($('proddetslinks')){
		$$('.prodmaindetails').addClass('hide');
		$$('.infohead').addClass('hide');
		$('proddesc').removeClass('hide');
		$('proddetslinks').removeClass('hide');
		//Call to function sort generic links
		$$('#proddetslinks a').addEvent('click', function(e){showhidediv(this,e);});
	}

	//show / hide the similar products info box
	if($('simHelp')){
		injectHelp();
		$$('#simHelp img').addEvents({
			'mouseenter' : function(){
				showHelp();
			},
			'mouseout' : function(){
				showHelp();
			}
		});
	}
	// Email click
	if($('mailfriend')){
		$('mailfriend').addEvent('click', function(e){injectDivs(e,this,'mail');});
	}	
	/* Accounts */
	if($('memtabs')){
		$$('#memtabs li a').addEvent('click', function(e){
			e.stop();
			var thisID = this.get('id');
			var fixID = thisID.split('_');
			$$('#memtabs li a').removeClass('memTabOn');
			this.addClass('memTabOn');
			$$('.memBlock').addClass('hide');
			$(fixID[0]).removeClass('hide');
		});
	}	
});

// function for clearing text boxes
function inputClear(e,ele){
	// Get the value and title
	var inputValue = ele.value;
	var inputTitle = ele.title;
	if(inputValue == inputTitle){
		//Remove the default text and highlight the entry
		ele.set('value', '');
		ele.addClass('highon');
		// Check to see something has been entered
		ele.addEvent('blur', function(){
			if(ele.value == ''){
				// Give the input its old value
				ele.set('value', inputValue);
				// Remove the hihglight class if the title and value stays the same
				ele.removeClass('highon');
			}
		});
	}
}
function setHandlers(){
    $$('.passwordClear').removeEvents();
    $$('.passwordClear').addEvent('focus', function(e){
        if(this.get("type") == "text"){
            var name  = this.get("name");
            var id    = this.get("id");
            var title = this.get("title");
            this.getParent().innerHTML = '<input type="password" name="'+name+'" id="'+id+'" value="" title="'+title+'" class="textarea" />';
            document.getElementById(id).focus();
            setHandlers();
        }
    });
    $$('.passwordClear').addEvent('blur', function(e){
        if(this.get("type") == "password" && this.value.trim() == ""){
            var name  = this.get("name");
            var id    = this.get("id");
            var title = this.get("title");
            this.getParent().innerHTML = '<input type="text" name="'+name+'" id="'+id+'" title="'+title+'" value="'+title+'" class="textarea" />';
            setHandlers();
        }
    });
}

// funtion to replace ie6 selects when a drop down goes over them listing pages
function ieSelectLists(onOff){
	if(onOff == 'on'){
		$$('.amPageBlock').addClass('ampage');	
		$$('.azPageBlock').addClass('azpage');
	} else{
		$$('.amPageBlock').removeClass('ampage');	
		$$('.azPageBlock').removeClass('azpage');
	}
}

// function for bookmarking page
function bookmark_us(e, url, title){
	e.stop();
	if(window.sidebar){ // firefox
   		window.sidebar.addPanel(title, url, "");
   	}	
	else if(window.opera && window.print){ // opera
	    var elem = document.createElement('a');
	    elem.setAttribute('href',url);
	    elem.setAttribute('title',title);
	    elem.setAttribute('rel','sidebar');
	    elem.click();
	} 
	else if(document.all){// ie
	    window.external.AddFavorite(url, title);
	}
	else{ //Should never use this but just incase
		alert('Sorry, This feature is not currently supported by your browser. To bookmark this page please use the standard browser process.');
	}
}
// for maps
function load() {

	map = new GMap2(document.getElementById("mapDiv"));
	//map.setCenter(whereDon, 8);
	map.addControl(new GSmallZoomControl3D());
	map.addControl(new GMenuMapTypeControl());
	

	// store locations
	var pointsLatArray = new Array('53.818402');
	var pointsLongArray = new Array('-1.514325');
	var countArray = pointsLatArray.length;
	var curZoomOut = 1;
	if(countArray < 2){
		curZoomOut = 8;
	}
	
	// store details

	// get the address details
	var pointDets = new Array('The Store,<br />Address');
	var bounds = new GLatLngBounds();
	//var pointDets = new Array(responseText);
	// Loop for each point
	var marker;
	var where;
	var markDets;
	var i = 0;
	for(i = 0;i<=0;i++){
            where = new GLatLng(pointsLatArray[i], pointsLongArray[i]);
            markDets = pointDets[i];
            marker = createMarker(where, markDets);
            bounds.extend(where);
            map.addOverlay(marker);
	}

	//set the zoom level and centre by figuring bounds and then -1 for neatness
	var currZoom = map.getBoundsZoomLevel(bounds); 	
	map.setCenter(bounds.getCenter(), currZoom-curZoomOut);
}
function createMarker(point, html) {
	var marker = new GMarker(point);
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}
// Sliding Mini basket
function showminibasket(){
	var closed = 0;
	var mySlide = new Fx.Slide('sideBasInfo').hide();
	$('showBasInfo').addEvent('click', function(e){
		e = new Event(e);
		mySlide.toggle();
		if(closed == 0){
			$('showBasInfo').set('html','<img src="'+siteAddr+'_img/front_end/themes/'+themeCol+'/basopen.gif" alt="Show your basket overview" width="22" height="22" />');
			closed = 1;
		}else{
			$('showBasInfo').set('html','<img src="'+siteAddr+'_img/front_end/themes/'+themeCol+'/basclosed.gif" alt="Hide your basket overview" width="22" height="22" />');
			closed = 0;
		}
		e.stop();
	});
}

// Reassurance and comments Phrases
function showNextPhrase(thisPhrase, nextPhrase){
	$(thisPhrase).fade('out'); // fade out current phrase 
	$(nextPhrase).fade('in'); // fade in next phrase 
}


// form Selects Conversion
function sortSelects(){
	var labelArray = $$('.select');
	var labels = $$('.select').setStyle('position','absolute');
	// Set each label it's bg
	labelArray.each(function(ele){
		ele.addClass('selectBg');
		ele.removeClass('hide');
	});		
	var inputs = $$('#container input'), span = Array(), textnode, option, active;
	inputs = $$('#container select');
	for(a = 0; a < inputs.length; a++) {
		if(inputs[a].className == 'styled') {
			option = inputs[a].getElementsByTagName('option');
			active = option[0].childNodes[0].nodeValue;
			textnode = document.createTextNode(active);
			for(b = 0; b < option.length; b++) {
				if(option[b].selected == true) {
					textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
				}
			}
		}
	}
}

// Logo Scrolling Banner
function logoScroll(){
	var timing = 1700;
	var bsItemCount = $$('.bsBrand').length;
	if(bsItemCount > 8){
		var periodLoop = setScroll.periodical(timing);
		$('bsScreen').addEvent('mouseover', function(e){ $clear(periodLoop);});
		$('bsScreen').addEvent('mouseout', function(e){ periodLoop = setScroll.periodical(timing);});
	}
	if(bsItemCount <= 8){
		$('bsScreen').setStyle('margin-left', '0');
	}
	function setScroll(){
		var bsItems = $$('.bsBrand');
		var firstEle = bsItems.getLast();
		firstEle.inject($('bsScreen'), 'top');
		firstEle.setStyle('margin-left', '-100px');
		var maximise = new Fx.Morph(firstEle, {duration: timing, transition: Fx.Transitions.linear});
		maximise.start({
			'margin-left': [-97, 0]
		});
	}
}

// Pop Up
function callPopUp(){
	var genBg = $('popbg');
	var eleScrollLen = $$('.popScroll').length;
	if(eleScrollLen > 0){
		var eleScroll = $$('.popScroll')
		eleScroll.each(function(ele){
			var scrollID = ele.id;
			var scrolltowrite = new Fx.SmoothScroll({duration:1000, links: '#'+scrollID});
		});
	}

	if(genBg){
		screenPos();
		genBg.addEvent('click', function(e){fadeOut(e);});
	}		

	if($('requestInfo')){
		$('requestInfo').addEvent('click', function(e){injectDivs(e,this,'produpdate');});
	}
	$$('.closePop').addEvent('click', function(e){fadeOut(e);});
	
	// close the screen 
	if($('popbg')){
		document.addEvent('keydown', function(event){
			if(event.key == 'esc'){
				var useEsc = genBg.get('opacity');
				if(useEsc > 0){
					escFadeOut();
				}
			}
		});
	}
}

//function to get the sceen & browser window dimentios and place the pop up accordingly
function screenPos(){
	var contSize = $('container').getSize(); //get the container height
	if($('footerLinkHold')){
		var footLSize = $('footerLinkHold').getSize(); //get the container height
	}
	var footSize = $('footer').getSize(); //get the container height
	
	// set the total screen height
	if($('footerLinkHold')){
		var screenHeight =  contSize.y + footLSize.y + footSize.y + 167;
	} else{
		var screenHeight =  contSize.y + footSize.y + 167;
	}
	
	var win = window.getSize(); // get windows dimensions
	var screenSizeW = win.x; // get the windows width
	var screenSizeH = win.y; // get the windows height
	
	//set the height of the backgrond div
	$('popbg').set({
		'styles':{
			'height': screenHeight
		}
	});
	
	//set  the poistion on the viewing panel;
	var popView = $('pop_view').getSize(); // get the size of the containing div
	// set the x position
	var popVX = (screenSizeW/2) -  (popView.x/2);
	var popVY = (screenSizeH/2) -  (popView.y/2);
	if(popVY < 0){
		popVY = 0;
	}
	$('pop_view').set({
		'styles':{
			'left': popVX,
			'top': popVY
		}
	});
}

//fading in function
function fadeIn(e){
	e.stop();
	$('popbg').fade('0','0.55');
	$('pop_view').fade('0','1');
}
//closing fade function
function fadeOut(e){
	e.stop();
	$('popbg').fade('0.55','0').get('tween').chain(function(){
		$('popbg').dispose();
	});
	$('pop_view').fade('1','0').get('tween').chain(function(){	
		$('pop_view').dispose();
	});
}
//closing fade function
function escFadeOut(){
	$('popbg').fade('0.55','0');
	$('pop_view').fade('1','0');
}

// create the pop up
function injectDivs(e,ele,type){
	e.stop;
	var escClose = true;
	var fixedPop = false;
	var popBg = new Element('div',{'id':'popbg','class':'hide'});
	var popView = new Element('div',{'id':'pop_view','class':'hide'});
	var popClose = new Element('div',{'id':'closeband'});
	var popHold;
	switch(type){
		case 'produpdate': popHold = new Element('div',{'id':'injectprodupdate', 'class':'mainPopInfo'}); fixedPop = true; type = 'produpdate'; break;
		case 'mail': popHold = new Element('div',{'id':'mailBlock', 'class':'mainPopInfo'}); type = 'mail'; fixedPop = true; break;
		default: popHold = new Element('div',{'id':'injectprodupdate', 'class':'mainPopInfo'}); type = 'produpdate'; break;
	}
	//inject the needed divs
	popBg.inject($('footer'),'after');
	popView.inject($('popbg'),'after');
	popClose.inject($('pop_view'));
	popHold.inject($('closeband'),'after');
	
	//set the required content and styling
	$('popbg').setStyle('opacity','0');
	$('pop_view').setStyle('opacity','0');
	if(type == 'mail'){
		$('pop_view').addClass('mailpop');
	}
	if(fixedPop){
		$('pop_view').addClass('fixedPop');
	}
	$('popbg').removeClass('hide');
	$('pop_view').removeClass('hide');
	$('closeband').set('html', '<p class="textRight"><a href="#" title="Close" class="closePop"><img src="'+siteAddr+'_img/front_end/icons/close.gif" alt="Close" /></a></p>');
	switch(type){
		case 'produpdate':injectProdUpdate(); break;
		case 'mail':mailInject(); break;
		default:injectProdUpdate(); break;
	}
	
	//position the screen, fade in and scroll to the top of the page
	screenPos();
	fadeIn(e);
	// set the bits for closing windows
	$('popbg').addEvent('click', function(e){fadeOut(e);});
	$$('.closePop').addEvent('click', function(e){fadeOut(e);});
	document.addEvent('keydown', function(event){
		if(event.key == 'esc' && escClose){
			var useEsc = $('popbg').get('opacity');
			if(useEsc > 0){
				fadeOut(event);
			}
			escClose = false;
		}
	});
}

//for terms pop up
function injectProdUpdate(){
	var termText = '<p>Would you like to know more about the <b>'+$('stockRequestProduct').value+'</b>? Simply fill in your name and either an email address or phone number, and we will contact you as soon as possible with the latest stock availability, and anything else you need to know&hellip;</p>';
	termText+= '<form id="prodInfoForm" action="" method="post">';
	termText+= '<ul class="leftList">';
	termText+= '<li><label class="hide">Your Name</label><input type="text" name="sName" id="sName" title="Your Name" value="Your Name" class="textarea" /></li>';
	termText+= '<li><label class="hide">Email or Phone</label><input type="text" name="sContact" title="Email or Phone" value="Email or Phone" class="textarea" /></li>';
	termText+= '</ul>';
	termText+= '<p class="textRight"><input type="image" src="'+siteAddr+'_img/front_end/buttons/pifsubmit.gif" name="submit" alt="Submit your details" class="imgbut" /></p>';
	termText+= '<input type="hidden" name="sProduct" value="'+$('stockRequestProduct').value+'" />';
	termText+= '<input type="hidden" name="action" value="stock_contact" />';
	termText+= '</form>';
	$('pop_view').addClass('prodUpdate');
	$('injectprodupdate').set('html',termText);
	$$('.textarea').addEvent('focus', function(e){inputClear(e,this);});
}
// for mail to a friend
function mailInject(){
	var mailProd = $$('.genhtag h1 b').get('text');
	var mailText = '<h3>Mail a Friend</h3>';
	mailText += '<p class="extraMarg">Email the <b>' + mailProd + '</b> page link to your friend.</p>';
	mailText += '<p class="extraMarg">Simply fill out the form below and then send your resulting email to your friend.</p>';
	mailText += '<form id="eMailer" name="eMailer"><input id="friendEmail" type="text" name="email" value="Enter your friends email address" title="Enter your friends email address" class="textarea"><input id="theirname" type="text" name="theirname" value="Enter your name" title="Enter your name" class="textarea"><p id="sendMail" class="noMarg textRight"><img src="'+siteAddr+'_img/front_end/themes/'+themeCol+'/sendemail.gif" title="Send your email" alt ="Send your email" /></p></form>';
	
	$('mailBlock').set('html',mailText);
	$$('.textarea').addEvent('focus', function(e){inputClear(this.id);});
	$('sendMail').addEvent('click', function(e){mailThisUrl();});
}

function mailThisUrl(){
	var theirName = $('theirname').value;
	var initialsubj="Think this may interest you";
	var initialmsg="Hi,%0D%0A%0D%0AFound this product and thought of you: %0D%0A%0D%0A" + window.location + '%0D%0A%0D%0AThanks%0D%0A%0D%0A' + theirName;
	checkEmailAddress(document.eMailer.email, theirName);
	if(goodMail){
		window.location = "mailto:"+document.eMailer.email.value+"?subject="+initialsubj+"&body="+initialmsg;
   	}
}

function checkEmailAddress(field, theirName) {
	var goodEmail = field.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\..{2,2}))$)\b/gi);
	if (goodEmail && theirName != 'Enter your friends email address' && theirName != '') {
		goodMail = true;
	}
	else {
		alert('Please ensure you have entered a valid email address and name');
		field.focus();
		field.select();
		goodMail = false;
   }
}
// End Pop up

//fading through banners
function fadeBanBlock(){
	// define general variables
	var tabTotal = $$('.bantab').length;
	var tabcount = 1;
	var exCount = 2;
	var pauseTab = 1;
	var theTimer = 5000;
	$$('.opZero').set('opacity','0');
	if($('bantabs')){
		var tabLoop = function(){
			var nextTab = 'fadban_' + exCount + '_block';
			showNextTabBlock('fadban_' + tabcount, nextTab, tabTotal);
			//move the counter for the tabs up by one to ensure it moves to the next block
			tabcount++;
			exCount++;
			if(exCount > tabTotal){
				exCount = 1;
			}	
			if(tabcount > tabTotal){
				tabcount = 1;
			}	
		}
			
		if(tabTotal > 1) { var periodicalTab = tabLoop.periodical(theTimer, this); }
		
		$$('.fadebanlink').addEvent('click', function(e){
			showTabBlock(this, e, tabcount, tabTotal);
			$clear(tabcount);
			$clear(exCount);
			tabcount = this.id.replace('fadban_', '');
			exCount = parseInt(tabcount)+1;
			if(exCount > tabTotal){
				exCount = 1;
			}
			$clear(periodicalTab);
			periodicalTab = tabLoop.periodical(theTimer);
		});
		
	}
}
//function to set the visible block
function showTabBlock(ele, e, tabcount, tabTotal){
	e.stop();
	var linkID = ele.id; // get the links id
	var cleanLink = 'fadban_' + tabcount + '_block'; // get the name of the ID to be revealed
	var nextBlock = linkID + '_block';
	var fadeOutBlock = $(cleanLink).fade('out');
	$(nextBlock).fade('in');
	setSpecialTab(linkID, tabTotal, 'clicked');
}
function showNextTabBlock(relBlock, nextBlock, tabTotal){
	var relBlockName = relBlock + '_block';
	var fadeOutBlock = $(relBlockName).fade('out');
	$(nextBlock).fade('in');
	setSpecialTab(relBlock, tabTotal, 'normBan');
}

// function for colouring tabs up correctly
function setSpecialTab(linkID, tabTotal, type){
	var thisTab;
	if(type == 'normBan'){
		var cleanTabNo = linkID.replace('fadban_', ''); 
		var thisTabNo = parseInt(cleanTabNo)+1;
		if(thisTabNo > tabTotal){
			thisTabNo = 1;
		}
		thisTab = 'fadban_'+thisTabNo;
	}
	else if(type == 'clicked'){
		thisTab = linkID;
	}
	
	$$('.tabpanel a').removeClass('banon');
	$(thisTab).addClass('banon');
}
// end fading

// Basket functions
function updateBasketProductQty() {
	document.Basket.submit();	
}

function addBasketOption(prod, option, val, url) {
	window.location = url+"basket/addOption/"+prod+"|"+option+"|"+val;
}
//end basket functions


// Product page view elements 
// function to set products per page and sort by mode
function perPageSortBy(formnum) {
	if(formnum == 1) { document.products.submit(); }
	else if(formnum == 2) { document.products2.submit(); }
}

// Inject the show hide box
function injectHelp(){
	var helpText = 'Simply check any of the attributes you&#39;d like below and click the find button. We&#39;ll then show you all the products we have which match your needs.'
	var helpInfo = new Element('p', {'id':'simInfo', 'class':'textCenter'});
	helpInfo.inject('simHelp');
	$('simInfo').set('html', helpText);
	$('simInfo').setStyle('opacity', '0');
	$('simInfo').addClass('simHide');
}
/*----- Page Tabs -----*/
// function for hiding / showing divs
function showhidediv(link, e){
	e.stop(); // stop the a tag
	var linkID = link.id; // get the links id
	var cleanLink = linkID.replace('_link',''); // get the name of the ID to be revealed
	$$('.prodmaindetails').addClass('hide'); // apply a hide class to all the generic informational divs
	$(cleanLink).removeClass('hide'); // remove the hide class from the relevant div
	setTab(linkID);
}
// function for colouring tabs up correctly
function setTab(linkID){
	$$('.genalt_nav a').removeClass('gennavon');
	$(linkID).addClass('gennavon');
}
/*----- End Page Tabs -----*/

// function to show / hide help similar products box
function showHelp(){
	if($('simInfo').hasClass('simHide')){
		$('simInfo').fade('in');
		$('simInfo').removeClass('simHide')
	}else{
		$('simInfo').fade('out');
		$('simInfo').addClass('simHide');
	}
}

function singleOptionCheck(opt_id, count_id, total_count) {
	var price_change = 0.00;
	var tmps;
	var tmp;
	
	for(i=1; i<=total_count; i++) {
		if(i != count_id) {
			if($('option_'+opt_id+'_'+i).checked == true) {
				tmps = $('option_'+opt_id+'_'+i).value;
				tmp = tmps.split('|');
				price_change = price_change - parseFloat(tmp[1]);
			}
			$('option_'+opt_id+'_'+i).checked = false;	
		}
	}
	
	if($('option_'+opt_id+'_'+count_id).checked == true) {
		tmps = $('option_'+opt_id+'_'+count_id).value;
		tmp = tmps.split('|');
		price_change = price_change + parseFloat(tmp[1]);	
	} else {
		tmps = $('option_'+opt_id+'_'+count_id).value;
		tmp = tmps.split('|');
		price_change = price_change - parseFloat(tmp[1]);
	}
	
	withOptionPrice(price_change);
}

function withOptionPrice(price) {
	var base_price = parseFloat($('base_price').value);
	var full_price = parseFloat($('full_price').value);
	var new_price  = Math.max(base_price, full_price + parseFloat(price));
	$('full_price').value = new_price;
	if(new_price > base_price) {
		$('optPrice').set('html', new_price);
		$('optPriceBox').removeClass('hide');
		$('theOpts').setStyle('margin-bottom', '5px');
	} else {
		$('optPriceBox').addClass('hide');
		$('theOpts').setStyle('margin-bottom', '0');
	}
}
// end product viw elements

// Sliding banners
window.addEvent('load', function() {							 
	var slideTimer = 9000;  //time between slides... 1000 = 1 Second
	var transitionTime = 1800; //Slide Time... 1000 = 1 Second
	var items = $$('.feat_block');  //Get the array of divs
	var numItems = items.length; // count the number of banners
	var prevFeat = $('prevbtn');
	var nextFeat = $('nextbtn');
	var featNum = 0;  //first Slide number created
	var isPaused = 0;
	var sliding = 0;
	
	if($('scrollBlock')){	
		$('banload').dispose(); // get rid of the loader div
	}
	if($('scrollBlock') && numItems > 1){	
				
		//Setup positions
		items.each(function(element, index) {
			
			if(index == 0){
				element.removeClass('first_item');
				element.setStyle('left', "0");
			}
			else{
				element.setStyle('left', "747px");
			}
		
		});
			
		//Slider
		var slideForward = function(){ 
			$('nextbtn').addClass('activeban');
				//get item to slide out
			var curItem = items[featNum];  
			sliding = 1;
			if(featNum < (numItems - 1)){
				featNum++; 
			}
			else{
				featNum = 0;
			}		
		
			var newItem = items[featNum];
					
			var item_in = new Fx.Morph(newItem, {
				     duration: transitionTime, 
				     transition: Fx.Transitions.Quad.easeInOut, 
				     wait:false
			});
			
			var item_out = new Fx.Morph(curItem, {
				     duration: transitionTime, 
				     transition: Fx.Transitions.Quad.easeInOut, 
				     wait:false
			});
			
			//beginning value
			item_in.start({
				'left': [747, 0]
			});
			
			item_out.start({
				'left': '-747'
			});
			//pause the slider
			item_in.addEvent('complete', function(){
				sliding = 0;
				$('nextbtn').removeClass('activeban');
			});
			item_out.addEvent('complete', function(){
				sliding = 0;
				$('nextbtn').removeClass('activeban');
			});
			
		};
			
			
		var slideBackward = function(){ 
			$('prevbtn').addClass('activeban');
			var curItem = items[featNum];  
			if(featNum > 0){
				featNum--; 
			}
			else{
				featNum = (numItems - 1);
			}
			
			var newItem = items[featNum];
			
			
			var item_in = new Fx.Morph(newItem, {
				 duration: transitionTime, 
				 transition: Fx.Transitions.Quad.easeInOut, 
				 wait:false
			});
			
			var item_out = new Fx.Morph(curItem, {
				 duration: transitionTime, 
				 transition: Fx.Transitions.Quad.easeInOut, 
				 wait:false
			});
	
			item_in.start({
				'left': [-747, 0]
			});
			
			//no beginning values needed
			item_out.start({
				'left': '747'
			});
			//pause the slider
			item_in.addEvent('complete', function(){
				sliding = 0;
				$('prevbtn').removeClass('activeban');
			});
			item_out.addEvent('complete', function(){
				sliding = 0;
				$('prevbtn').removeClass('activeban');
			});			
		};
		//call the slider function periodically
		var theTimer = slideForward.periodical(slideTimer, this); 
		
		//scroll buttons
		if(nextFeat){
			nextFeat.addEvent('click', function(e){
				e.stop();
				if(sliding == 0){
					sliding = 1;
					if(isPaused == 0){
						$clear(theTimer);
						theTimer = slideForward.periodical(slideTimer);
					}
					slideForward();
				}
			});
			
			prevFeat.addEvent('click', function(e){
				e.stop();
				if(sliding == 0){
					sliding = 1;
					if(isPaused == 0){
						$clear(theTimer);
						theTimer = slideForward.periodical(slideTimer);
					}				     
					slideBackward();
				}
			});
		}
	}
});


