
// initialise all the script objects
$(document).ready(function() { 
	inputClearing.init();
	styleNav.init();
	subNav.init();
	miniNavBuilder.init();
	normaliser.init(['div.panel.w748.catalogue ul li a', 'div.panelLinks', 'div.panelProductDesc div.related ul li']);
	linkStyler.init(['div.panel.w748.links ul li[class!=file] a', 'div.panelLinks ul li[class!=file] a']);
	lightBoxEnable.init();
	feedBackForm.init();
	supplierForm.init();
	signUpForm.init();
	googErrorStyle.init();
	homePromo.init();
	
	bookmarks.init();
});


// add sIFR outside of document.ready
if(typeof(sIFR) != 'undefined'){
	var mainHead = { src: '/flash/sifr.swf' };
	sIFR.activate(mainHead);

	sIFR.replace(mainHead, {
		selector: 'div.chunkyHeader h2',
		wmode: 'transparent',
		css: [
			'.sIFR-root { leading: -20; text-align: right; text-transform: uppercase; color: #ffffff; margin: 0; padding: 0; font-size: 58px; }'
		]
	});
	sIFR.replace(mainHead, {
		selector: 'div.chunkyHeader h3',
		wmode: 'transparent',
		css: [
			'.sIFR-root { leading: -10; text-transform: uppercase; color: #ffffff; margin: 0; padding: 0; font-size: 38px; }'
		]
	});
}
 
var googErrorStyle = {

	init:function(){

		if($('div#goog-wm').length < 1) return;
		
		// remove the text nodes and bold element
		$('div#goog-wm li').contents().filter(function() { return this.nodeType == Node.TEXT_NODE; }).remove();
		$('div#goog-wm li b').remove();
		
		// now insert our own styled html content
		$('div#goog-wm li form').prepend('<label for="goog-wm-qt">Search site:</label>');
		$('div#goog-wm li form #goog-wm-sb').attr({'value':''});
	}
}

// validation for the customer enquiry form
var supplierForm = {
	
	formID:'sEnquiry',	// form id
	init:function(){
		if($('#'+this.formID).length < 1) return;
		this.doVadlidate();
	},
	
	doVadlidate:function(){
		$('#'+this.formID).validate({
			//set the rules for the field names
			rules: {
				title: "required",
				firstname: {
					required: true, 
					maxlength: 100
				},
				surname: {
					required: true,
					maxlength: 100
				},
				email: {
					required: true,
					email: true,
					maxlength: 100
				},
				company: {
					required: true,
					maxlength: 100
				},
				telephoneNumber: {
					required: true,
					maxlength: 100
				},
				volume: {
					required: true,
					maxlength: 1000
				},
				availableFrom: {
					required: true,
					maxlength: 1000
				},
				message: {
					required: true,
					maxlength: 1000
				},
				comments: {
					maxlength: 1000
				},
				recaptcha_response_field: {
					required: true
				}
			},
			
			//set messages to appear inline
			messages: 
			{
				title: "Please select your title",
				firstname: 
				{ 
					required: "Please enter your forename",
					maxlength: "Your forename must be less than 100 characters"
				},
				surname:
				{ 
					required: "Please enter your surname",
					maxlength: "Your surname must be less than 100 characters"
				},
				email: 
				{
					required: "Please enter your email address",
					email: "Please enter a valid E-mail address",
					maxlength: "Your E-Mail must be less than 100 characters"
				},
				company:
				{ 
					required: "Please enter your company",
					maxlength: "Your company must be less than 100 characters"
				},
				telephoneNumber:
				{ 
					required: "Please enter your telephone number",
					maxlength: "Your telephone number must be less than 100 characters"
				},
				message:
				{ 
					required: "Please enter your Products",
					maxlength: "Your Products must be less than 1000 characters"
				},
				availableFrom:
				{ 
					required: "Please enter Available From",
					maxlength: "Your Available From must be less than 1000 characters"
				},
				volume:
				{ 
					required: "Please enter your Volume",
					maxlength: "Your Volume must be less than 1000 characters"
				},
				comments:
				{ 
					maxlength: "Your Comments must be less than 1000 characters"
				},
				recaptcha_response_field: "You must enter the two words displayed above"
			},
			
			errorPlacement: function(error, element) {
				// do some custom rules on the error message based on type...
				if(element.attr('id') == 'firstname') { error.addClass('left'); } 
				else if(element.attr('id') == 'surname') { error.addClass('right'); }
				else if(element.attr('id') == 'recaptcha_response_field') {
					element.parents('div.captcha').append(error);
					return;
				}
				element.parent().append(error);
			}
		});	
	}
}


// validation for the customer enquiry form
var feedBackForm = {
	
	formID:'enquiry',	// form id
	init:function(){
		if($('#'+this.formID).length < 1) return;
		this.doVadlidate();
	},
	
	doVadlidate:function(){
		$('#'+this.formID).validate({
			//set the rules for the field names
			rules: {
				title: "required",
				firstname: {
					required: true, 
					maxlength: 100
				},
				surname: {
					required: true,
					maxlength: 100
				},
				email: {
					required: true,
					email: true,
					maxlength: 100
				},
				message: {
					required: true,
					maxlength: 1000
				},
				recaptcha_response_field: {
					required: true
				}
			},
			
			//set messages to appear inline
			messages: 
			{
				title: "Please select your title",
				firstname: 
				{ 
					required: "Please enter your forename",
					maxlength: "Your forename must be less than 100 characters"
				},
				surname:
				{ 
					required: "Please enter your surname",
					maxlength: "Your surname must be less than 100 characters"
				},
				email: 
				{
					required: "Please enter your email address",
					email: "Please enter a valid E-mail address",
					maxlength: "Your E-Mail must be less than 100 characters"
				},
				message: 
				{
					required: "Please enter a message",
					maxlength: "Your message must be 1000 characters or less"
				},
				recaptcha_response_field: "You must enter the two words displayed above"
			},
			
			errorPlacement: function(error, element) {
				// do some custom rules on the error message based on type...
				if(element.attr('id') == 'firstname') { error.addClass('left'); } 
				else if(element.attr('id') == 'surname') { error.addClass('right'); }
				else if(element.attr('id') == 'recaptcha_response_field') {
					element.parents('div.captcha').append(error);
					return;
				}
				element.parent().append(error);
			}
		});	
	}
}



// validation for the newsletter signup form
var signUpForm = {
	
	formID:'register',	// form id
	init:function(){
		if($('#'+this.formID).length < 1) return;
		this.doVadlidate();
	},
	
	doVadlidate:function(){
		$('#'+this.formID).validate({
			//set the rules for the field names
			rules: {
				title: "required",
				forename: {
					required: true, 
					maxlength: 100
				},
				surname: {
					required: true,
					maxlength: 100
				},
				username: {
					required: true,
					email: true,
					maxlength: 100
				},
				recaptcha_response_field: {
					required: true
				},
				password: {
					required: true,
					minlength: 6,
					maxlength: 100
				},
				confirmpassword: {
					required: true,
					minlength: 6,
					equalTo: "#password"
				},
				external_source_identifier: {
					maxlength: 500
				},
				optin_t1_m1: "required",
				privacyAgreement: "required"
			},
			
			//set messages to appear inline
			messages: 
			{
				title: "Please select your title",
				forename: 
				{ 
					required: "Please enter your forename",
					maxlength: "Your forename must be less than 100 characters"
				},
				surname:
				{ 
					required: "Please enter your surname",
					maxlength: "Your surname must be less than 100 characters"
				},
				username: 
				{
					required: "Please enter your email address",
					email: "Please enter a valid E-mail address",
					maxlength: "Your E-Mail must be less than 100 characters"
				},
				password:
				{ 
					required: "Please enter a password",
					minlength: "Your password must be at least 6 characters long",
					maxlength: "Your password must be less than 100 characters"
				},
				confirmpassword: 
				{
					required: "Please confirm your password",
					minlength: "Your password must be at least 6 characters long",
					equalTo: "Please enter the same password as above"
				},				
				external_source_identifier:
				{ 
					maxlength: "Your competition answer must be less than 500 characters"
				},				
				recaptcha_response_field: "You must enter the two words displayed above",
				privacyAgreement: "You must agree to the Privacy Policy and Terms and Conditions",
				optin_t1_m1: "You must agree to accept emails"
			},
			
			errorPlacement: function(error, element) {
				// do some custom rules on the error message based on type...
				if(element.attr('id') == 'firstname') { error.addClass('left'); } 
				else if(element.attr('id') == 'surname') { error.addClass('right'); }
				else if(element.attr('id') == 'recaptcha_response_field') {
					element.parents('div.captcha').append(error);
					return;
				}
				element.parent().append(error);
			}
		});	
	}
}


var lightBoxEnable = {
	grouping:'.lbox',
	item:'a[rel="imageshow"]',
	
	init:function() {
		if($(lightBoxEnable.grouping).length < 1) return;
		$(lightBoxEnable.grouping).each(function(s, e) {
			$(e).find('a[rel="imageshow"]').colorbox({transition:'fade', speed:500, current:''});
		});
	}
}


var normaliser = {

	// pass in an [array] of html element selectors and normaliser will normalise the height based on the tallest element
	// NOTE: when normalising elements containing images, the image must be loaded or have a fixed, set height (in the css or html)
	// otherwise their height is discounted in webkit-based browsers
	init:function(arr) {
		if(!arr) return;
		$.each(arr, function(inc, selector) {
			var heightInc = 0;
			if($(selector).length > 0) {
				$(selector).each(function(s, e){
					var tmpHeightInc = $(e).height();
					if(heightInc < tmpHeightInc) { heightInc = tmpHeightInc; }
				});
			if(heightInc > 0) { $(selector).css({'height':heightInc}); }
			}
			

		});
	}
}


var linkStyler = {

	init:function(arr){
		if(!arr) return;
		$.each(arr, function(inc, selector) {
			$(selector).prepend('&gt;&nbsp;');
		});
	}
}










var homePromo = {

	panelWidth:740,
	panelNum:0,
	
	scrolling: false,	// is the object currently scrolling
	scrollSpeed: 1000,  // speed of scroll
	scrollInt: 3500,	// interval between auto scroll
	scrollSelf: true,	// set auto scroll on or off
	
	visibleSet:0,
	
	timeout: null,		// used for autoscrolling to track the interval status - do not amend
	
	init: function() {
		if($('#homeScroller').length < 1 || $('#homeScroller div.nav li').length < 2) return; // don't scroll if there's only one item!
		this.panelNum = $('#homeScroller div.nav li').length;
		
		// set width of slider
		$('#homeScroller div.slider').css({'width':parseInt(this.panelWidth, 10) * parseInt(this.panelNum, 10)});
		
		// auto centre buttons if less than 4
		if(this.panelNum < 4) {
			
			var innerWidth = 0;
			$('#homeScroller div.nav li').each(function(s, e) {
				innerWidth += parseInt($('#homeScroller div.nav li').eq(s).css('width'), 10);
				innerWidth += parseInt($('#homeScroller div.nav li').eq(s).css('margin-left'), 10);
				innerWidth += parseInt($('#homeScroller div.nav li').eq(s).css('margin-right'), 10);
				innerWidth += parseInt($('#homeScroller div.nav li').eq(s).css('padding-left'), 10);
				innerWidth += parseInt($('#homeScroller div.nav li').eq(s).css('padding-right'), 10);
			});
			
			var marginOffset = (parseInt($('#homeScroller div.nav ul').width(), 10) - innerWidth)/2;
			$('#homeScroller div.nav ul').css({'margin-left' : parseInt($('#homeScroller div.nav ul').css('margin-left'), 10) + marginOffset });
		}
		
		// make the whole region clickable
		$('div#homeScroller div.hsContainer').click(function(ev) { location.href = $(this).find('a').eq(0).attr('href'); });
		
		
		// set first button selected state
		$('#homeScroller div.nav li').eq(this.visibleSet).addClass('selected');
		
		$('#homeScroller div.nav li a').each(function(s, e) {
			$(e).click(function(ev) {
				homePromo.scroll(s, ev, $(e));
			});
		});
		if(this.scrollSelf) { this.createAutoScroll(); }
	},

	scroll:function(set, event, elem) {
	
		event = (!event ? null : event);
		elem = (!elem ? null : elem);
		if(event != null) { event.preventDefault(); }
		if(elem != null) { elem.blur(); }
		
		if(set == this.visibleSet) { return; }
		
		if(this.scrolling == false) {
			// special rule is required to go from the last element to the first or vice versa
			if( (parseInt(this.visibleSet, 10)+1 == parseInt(this.panelNum, 10) && set == 0) || (parseInt(this.visibleSet, 10) == 0 && set+1 == parseInt(this.panelNum, 10)) ) {
				this.specialScroll(set, event, elem);
				return;
			}
			
			var obj = this;
			var s = $('#homeScroller div.slider').eq(0);
			
			var newPos = ( 0 - (parseInt(set, 10) * this.panelWidth) );
			
			this.visibleSet = set;
			$('#homeScroller div.nav li').removeClass('selected');
			$('#homeScroller div.nav li').eq(this.visibleSet).addClass('selected');

			this.scrolling = true;
			if(elem != null) {
				clearInterval(this.timeout);
				this.timeout = null;
			}
			
			s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem); });
		}
	},
	
	specialScroll:function(set, event, elem) {
		var obj = this;
		var s = $('#homeScroller div.slider').eq(0);
		var start = 'last'; // default is going from last to first as this occurs naturally in the auto-scrolling action

		if(parseInt(this.visibleSet, 10)+1 == 1) { start = 'first'; }
		
		// clone the last item before the first or the first item after the last depending on start
		if(start == 'last') {
			$('#homeScroller div.slider').append($('#homeScroller div.slider div.hsContainer').eq(set).clone());
		} else {
			s.css({'left': (0-parseInt(this.panelWidth, 10)) });
			$('#homeScroller div.slider').prepend($('#homeScroller div.slider div.hsContainer').eq(set).clone());
		}
		$('#homeScroller div.slider').eq(0).css({'width': parseInt($('#homeScroller div.slider').eq(0).css('width'), 10) + parseInt(this.panelWidth, 10)});
		
		var newPos = ( start == 'first' ? 0 : 0 - ((parseInt(this.visibleSet, 10) * this.panelWidth) + this.panelWidth) );
		
		this.visibleSet = set;
		$('#homeScroller div.nav li').removeClass('selected');
		$('#homeScroller div.nav li').eq(this.visibleSet).addClass('selected');
		
		this.scrolling = true;
		if(elem != null) {
			clearInterval(this.timeout);
			this.timeout = null;
		}
		
		s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem, start); });	
	},
	
	createAutoScroll:function(){
		var obj = this;
		this.timeout = setInterval( function(){
			obj.autoScroll();
		}, obj.scrollInt);	
	},
	
	// automatically scroll to the next item
	autoScroll:function() { this.scroll(this.returnNext()); },
	
	// find the next item in the set and return the number indicator for that item
	returnNext:function() {
		return (parseInt(this.visibleSet, 10)+1) > (parseInt(this.panelNum, 10)-1) ? 0 : parseInt(this.visibleSet, 10)+1; // +1 to account for zero indexing, +1 to get the next increment
	},
	
	stopScroll:function(elem, special){ 
		
		if(typeof(special) != 'undefined') {
			
			var obj = this;
			var s = $('#homeScroller div.slider').eq(0);
			
			if(special == 'last') {
				s.css({'left':0});
				$('#homeScroller div.slider div.hsContainer').eq($('#homeScroller div.slider div.hsContainer').length-1).remove();
			} else if(special == 'first') {
				s.css({'left': (0 - (parseInt($('#homeScroller div.slider div.hsContainer').length, 10)-1) * this.panelWidth) + this.panelWidth  });
				$('#homeScroller div.slider div.hsContainer').eq(0).remove();
			}
			
			$('#homeScroller div.slider').eq(0).css({'width': parseInt($('#homeScroller div.slider').eq(0).css('width'), 10) - parseInt(this.panelWidth, 10)});
		
		}
		
		if(elem != null && this.scrollSelf) { this.createAutoScroll(); }
		this.scrolling = false; 
	}
	
}




// "mininav" sliding navigation
function MiniNav(elem){
	
	this.htmlOut = '';
	this.elem = elem;
	
	this.panelWidth = 0;
	this.panelNum = 4;			// change default by passing in class name from containing UL in format numItems_[INT]
	
	this.scrolling = false;
	this.scrollSpeed = 1200;
	
	this.panelCentre = true;
	this.visibleSet = 0;
	
	var obj = this;
	
	// build html output
	obj.htmlOut = '<ul>';
	elem.find('div.hider ul li').each(function(s, e) {
		
		// check if we need to change the default number of items
		if(s == 0) {
			var classesArr = $(e).parent().attr('class').split(" ");
			for(var i = 0; i < classesArr.length; i++) {
				if(classesArr[i].split("_")[0] == 'numItems') { obj.panelNum = parseInt(classesArr[i].split("_")[1], 10); }
			}
		}
		
		obj.htmlOut += '<li>' + $(e).html() + '</li>';
		if( (s > 0) && ((s+1) % obj.panelNum == 0) && (s+1) < elem.find('div.hider ul li').length) { obj.htmlOut += '</ul><ul>'; }
	});
	obj.htmlOut + '</ul>';
	elem.find('div.hider ul').replaceWith(obj.htmlOut);
	
	if(elem.find('div.hider ul li').length > obj.panelNum) { elem.find('div.hider').addClass('narrow'); }
	
	// set sizes
	this.panelWidth = elem.find('div.hider ul').eq(0).width();
	elem.find('div.slider').width(this.panelWidth * elem.find('div.hider ul').length);
	
	// vertically centre text if this is a sub cat menu
	elem.find('div.subCatTab a').each(function(s, e){
		var addPadd = parseInt($(e).css('padding-top'), 10) + (parseInt($(e).height(), 10) - parseInt($(e).css('font-size'), 10))/2;
		$(e).css({'padding-top':addPadd});
		$(e).css({'height' : (parseInt($(e).height(), 10) - addPadd), 'min-height' : (parseInt($(e).css('min-height'), 10) - addPadd) });
	});	
	
	var height = 0;
	// set height to account for longer product names
	elem.find('div.hider span.text strong').each(function(s, e) {
		var elemHeight = 0;
		
		var getHeight = parseInt($(e).height(), 10);
		var getMinHeight = parseInt($(e).css('min-height'), 10);
		
		//elemHeight += parseInt($(e).css('height'), 10);
		//elemHeight += parseInt($(e).height(), 10) > parseInt($(e).css('min-height'), 10) ? parseInt($(e).height(), 10) : parseInt($(e).css('min-height'), 10);
		
		elemHeight += (getHeight > getMinHeight ? getHeight : getMinHeight);
		
		//alert(parseInt($(e).css('min-height')));
		
		height = elemHeight > height ? elemHeight : height;
	});
	
	
	
	elem.find('div.hider').css({'height':height+30});
	elem.find('div.hider span.text strong').css({'height':height}); // this sets the pound badge to the same height everywhere, comment out to have them try to sit at the styled position
	
	//alert(height);
	
	height = null;
	
	// reposition list items to centre of UL where less than visible number
	if(this.panelCentre == true) {
		
		
		elem.find('div.hider ul').each(function(s, e) {
			
			// this spreads out the padding so items < panel num are spaced out more as per bg295
			var listWidth = 0;
			$(e).find('li').each(function(x, y) {
				//listWidth += parseInt($(y).width(), 10);
				listWidth += parseInt($(y).css('width'), 10);
			});
			var padding = ((parseInt($(e).width(), 10) - listWidth) / ( parseInt($(e).find('li').length, 10) + 1 ));
			
			//alert(parseInt($(e).width(), 10) + '-' + listWidth);
			
			$(e).find('li').css({'margin-left': Math.floor(padding)});
			
			
			/*
			this centers the items without creating a margin for each one as per the design
			//if($(e).find('li').length < obj.panelNum) {
				var liElem = $(e).find('li').eq(0);
				var margin = parseInt( ( obj.panelWidth - ( $(e).find('li').length * obj.totalWidth(liElem) ) ) / 2, 10);
				if(margin < 0) { margin = 0; }
				$(e).find('li').eq(0).css({'margin-left':margin});
			//}
			*/
		});
		
		
	}
	
	// add next/prev buttons and set up click events
	if(elem.find('div.hider ul li').length > obj.panelNum) {
		
		
		
		elem.append('<div class="nav prev"><a href="#">&nbsp;</a></div><div class="nav next"><a href="#">&nbsp;</a></div>');
		elem.find('div.prev a').click(function(ev){ obj.scroll('left', ev, $(this)); });
		elem.find('div.next a').click(function(ev){ obj.scroll('right', ev, $(this)); });
	}
	
}

// changes default number of items to display per visible section
MiniNav.prototype.setPanelNum = function(num) { this.panelNum = num; }

// returns total width of an element, including margin and padding right and left
MiniNav.prototype.totalWidth = function(elem) {
	var totalWidth = 0;
	totalWidth += parseInt(elem.width(), 10),
	totalWidth += parseInt(elem.css('margin-left'), 10),
	totalWidth += parseInt(elem.css('margin-right'), 10),
	totalWidth += parseInt(elem.css('padding-left'), 10),
	totalWidth += parseInt(elem.css('padding-right'), 10)
	return totalWidth;
}

// handle the scrolling of the mininav
MiniNav.prototype.scroll = function(dir, event, elem) {
	event.preventDefault();
	elem.blur();
	
	if(this.scrolling == false) {
		var obj = this;
		var s = this.elem.find('div.slider').eq(0);
		
		var newPos = (dir == 'right' ? 0 - ((this.visibleSet+1) * this.panelWidth) : 0 - ((this.visibleSet-1) * this.panelWidth));

		if(dir == 'right' && parseInt((newPos + s.width()), 10) <= 0) { return; }
		if(dir == 'left' && s.position().left >= 0) { return; }
		
		this.visibleSet = (dir == 'right' ? this.visibleSet+1 : this.visibleSet-1);
		
		this.scrolling = true;
		s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(); });		
	}
}

// update property to indicate scroll has ended
MiniNav.prototype.stopScroll = function() { this.scrolling = false; }

// builder object creates a mininav instance for each menu added to the page
var miniNavBuilder = {
	init:function(){
		
		if($('div.slidingNav').length < 1 || $('div.slidingNav div.hider ul li').length < 1) return;
		var miniNav = new Array();
		$('div.slidingNav').each(function(s, e) {
			//$(e).addClass('js');
			
			miniNav[s] = new MiniNav($(e));
		});
	}
}

// sub navigation functionality (to allow expanding/contracting of menus)
var subNav = {
	sliding:false,
	init:function(){
		if($('div.subnav').length < 1) return;
		$('div.subnav li').each(function(s, e) {
			if($(e).children('ul').length > 0) {
				$(e).children('a').before('<a href="#" class="expander"><img class="close" src="/static-images/subnav-minus.gif" alt="Close the menu" title=""/><img class="open" src="/static-images/subnav-plus.gif" alt="Open the menu" title=""/></a>');
				$(e).children('a.expander').click(function(ev) {
					if(subNav.sliding == false) {
						subNav.slding = true;
						subNav.toggle($(e));
						ev.preventDefault();
						$(this).blur();
					}
				});
				subNav.firstView();
			} else {
				$(e).children('a').prepend('&gt;&nbsp;');
			}
		});
	},
	
	toggle:function(elem){
		
		var ulElem = $(elem).find('ul').eq(0);
		if (ulElem.is(':hidden')) {
			
			ulElem.slideDown("slow", function() { subNav.sliding = false; });
			elem.find('a.expander img.open').eq(0).hide();
			elem.find('a.expander img.close').eq(0).show();
			
		} else {
			
			ulElem.slideUp("slow", function() { subNav.sliding = false; });
			elem.find('a.expander img.open').eq(0).show();
			elem.find('a.expander img.close').eq(0).hide();			
		}
	},
	
	// this will need some logic to determine which menus are preselected once we know more about how the menus are created...
	firstView:function() {
		// this causes the parent categories of the selected category to default open
		/*
		$('div.subnav li').each(function(s, e) {
			if($(e).hasClass('selected')) {
				$(e).parents('li').addClass('selected');
			}
		});
		*/
		
		$('div.subnav li').each(function(s, e) {
			
			if(!$(e).hasClass('selected')) {
				
				$(e).find('a.expander img.close').eq(0).hide();
				$(e).find('ul').eq(0).hide();	
				
			} else {
			
				$(e).find('a.expander img.open').eq(0).hide();
				// default the parent trail down to this category to be open
				$(e).parents('li').find('a.expander img.close').eq(0).show();
				$(e).parents('li').find('a.expander img.open').eq(0).hide();
				$(e).parents('li').find('ul').eq(0).show();	
			
			}
			
		});
	}
}


// little device independent script to clear/reset values and colours in input fields - add fields to check to the .each iteration
var inputClearing = {
	init:function(){
		$.each(['form#search', 'form#newsletter', 'form#storefinder'], function(s, e){ // add all the forms/sub elements of forms to check here
			if($(e).length > 0) {
				$(e).find('input[type=text]').focus(function() {
					if(!$(this).data('fv')) { $(this).data('fv', { value: $(this).attr('value'), colour: $(this).css('color') }); }
					if($(this).attr('value') == $(this).data('fv').value) { $(this).attr({value:''}); }
					$(this).css({'color':'#fff'});
				});	
				$(e).find('input[type=text]').blur(function() {
					if($(this).attr('value') == '' || $(this).attr('value') == $(this).data('fv').value) { $(this).attr({'value':$(this).data('fv').value}); }
					$(this).css({'color':$(this).data('fv').colour});
				});				
			}
		});
	}
}


// add some additional styling elements to the global nav without polluting the raw xhtml
var styleNav = {

	init:function(){
		if($('ul#nav').length < 1) return;
		
		$('ul#nav').addClass('js');
		$('ul#nav li').each(function(s, e) {
			var thisLink = $(e).find('a').eq(0);
			
			thisLink.prepend('<span class="left"></span>').append('<span class="right"></span>').append('<span class="div"></span>');
			if(!$(e).hasClass('selected')) {
				$(e).mouseenter(function(ev){
					thisLink.addClass('hover');
					if($(e).prev().length > 0) { $(e).prev().find('a').eq(0).addClass('prevhover'); }
				});
				$(e).mouseleave(function(ev){
					thisLink.removeClass('hover');
					if($(e).prev().length > 0) { $(e).prev().find('a').eq(0).removeClass('prevhover'); }
				});
			}
		});
		
		$('ul#nav li').eq(0).addClass('first');
		$('ul#nav li').eq($('ul#nav li').length-1).addClass('last');
		
		/* do some IE6-only styling to replicate proper behaviour of width auto on navigation buttons */
		if (typeof document.body.style.maxHeight == "undefined") {
			$('ul#nav li a').each(function(s, e) {
				var w = parseInt($(e).width(), 10) + 3;
				if(s==0 || s==($('ul#nav li a').length-1)) { w += 6; }
				$(e).width(w);
			});
		}
	}
}

var bookmarks = {
	
	// add bookmarks here and also create an entry in main.css if a non-default image is to be used
	items: {
		favourites : { 
			name: 'Bookmark', 
			url: location.href, 
			className: 'bmFavourites' 
		},
		facebook : { 
			name: 'Facebook', 
			url: 'http://www.facebook.com/share.php?u=' + escape(location.href), 
			className: 'bmFacebook' 
		},
		twitter : { 
			name: 'Twitter', 
			url: 'http://twitter.com/home?status=' + escape(location.href), 
			className: 'bmTwitter' 
		},
		google : { 
			name: 'Google', 
			url: 'http://www.google.com/bookmarks/mark?op=add&bkmk=' + escape(location.href) + '&title=' + escape(document.title) + '&annotation=', 
			className: 'bmGoogle' 
		},
		live : { 
			name: 'Live', 
			url: 'http://favorites.live.com/quickAdd.aspx?url=' + escape(location.href) + '&title=' + escape(document.title) + '&text=', 
			className: 'bmLive' 
		},
		myspace : { 
			name: 'MySpace', 
			url: 'http://www.myspace.com/Modules/PostTo/Pages/?c=' + escape(location.href) + '&t=' + escape(document.title), 
			className: 'bmMySpace' 
		},
		digg : { 
			name: 'Digg', 
			url: 'http://digg.com/submit?phase=2&url=' + escape(location.href) + '&title=' + escape(document.title), 
			className: 'bmDigg' 
		},
		delicious : { 
			name: 'Delicious', 
			url: 'http://del.icio.us/post?url=' + escape(location.href) + '&title=' + escape(document.title), 
			className: 'bmDelicious' 
		},
		stumbleUpon : { 
			name: 'Stumbleupon', 
			url: 'http://www.stumbleupon.com/submit?url=' + escape(location.href) + '&title=' + escape(document.title), 
			className: 'bmStumble' 
		}
	},

	init:function() {
		if($('div#bookmark').length < 1) { return; }
		var obj = this;
		obj.buildHTML();
		obj.attachEvents();
		
	},
	
	buildHTML:function() {
		var obj = this;
		var listLeft = '', listRight = '', inc = 0, favSupport = false;
		
		if(window.sidebar || window.external || window.opera) { favSupport = true; }
		
		for(var i in obj.items) {
			if(favSupport == true || i != 'favourites') {
				var listItem = '<li class="' + obj.items[i].className + '"><a href="' + obj.items[i].url + '" target="_blank">' + obj.items[i].name + '</a></li>';
				if(inc % 2 == 0) { listLeft += listItem; }
				else { listRight += listItem; }
				inc++;
			}
		}

		var outputHTML = '';
		outputHTML += '<div class="bookmark">';
		//outputHTML += '    <h2>Social Bookmarks</h2>';
		outputHTML += '    <div class="panelAnchor">';
		outputHTML += '        <p><a href="#"><img src="/static-images/bookmarks/bookmark.jpg" width="121" height="13" alt="" /></a></p>';
		outputHTML += '        <div class="anchorElem">';
		outputHTML += '            <div class="panel">';
		outputHTML += '                <div class="inner">';
		
		if(listLeft != '') {
			outputHTML += '                <ul>';
			outputHTML += listLeft;
			outputHTML += '                </ul>';
		}
		
		if(listRight != '') {
			outputHTML += '                <ul>';
			outputHTML += listRight;
			outputHTML += '                </ul>';
		}
		
		outputHTML += '                </div>';
		outputHTML += '            </div>';
		outputHTML += '        </div>';
		outputHTML += '    </div>';
		outputHTML += '</div>';
		
		$('div#bookmark').html(outputHTML);
		
		// this is required later in our attach events method for opera to set a bookmark for the "favourites" option
		if(window.opera) { if ($('#bookmark div.bookmark li.bmFavourites a').attr('rel') != ''){  $('#bookmark div.bookmark li.bmFavourites a').attr('rel','sidebar'); } }
		
	},
	
	attachEvents:function(){
		var obj = this;
		$('#bookmark div.bookmark div.panelAnchor').mouseenter(function(ev) {
			$('#bookmark div.bookmark div.panel').show();
		});
		$('#bookmark div.bookmark div.panelAnchor').mouseleave(function(ev) {
			$('#bookmark div.bookmark div.panel').hide();
		});	
	
		// add special rule to handle the add to favourites/bookmarks link
		if($('#bookmark div.bookmark li.bmFavourites a').length > 0) {
			$('#bookmark div.bookmark li.bmFavourites a').click(function(ev) {
				ev.preventDefault();
				if (window.sidebar) {  window.sidebar.addPanel(document.title, location.href,''); }
				else if( window.external ) { window.external.AddFavorite( location.href, document.title); }
			});
		}
	}
}
