// initialise all the script objects
$(document).ready(function() { 
	$('a[rel="imageshow"]').colorbox({transition:'fade', speed:500, current:''});
	vidLBox.init();
	homeRotator.init();
	calorEnquiryForm.init();
	heroTeaser.init();
	doFlashHeaders.init();
	
	miniNavBuilder.init();
	productImageCarousel.init();
	productLinkManage.init();
	productMagnifyTrigger.init();
	
	galleryEnable.init();	// Used on Calor network
	
	/* replaced by behavioural tracking code
	if ($("#homeFlashBanner").length > 0) { 
		var flashvars = {}, params = { wmode:"transparent" }, attributes = {};
		swfobject.embedSWF("/static-flash/house3.swf", "homeFlashBanner", "700", "370", "9.0.0", false, flashvars, params, attributes);
	}
	*/
	behaviouralTracking.init();
	
	// do navigation for IE6
	if(typeof(isIEVersion) != "undefined") {
		if(isIEVersion == 6) {
			$('div#nav ul.nav li').each(function(s, e) {
				if($(e).parent().hasClass('nav')) {
					$(e).mouseenter(function(){ $(e).addClass('hover'); });
					$(e).mouseleave(function(){ $(e).removeClass('hover'); });
				}
			});	
		}
	}

	if ($('.checkoutConfirmationCycle .mid .slider').length > 0) {
		$('.checkoutConfirmationCycle .mid .slider').cycle({
			fx: 'scrollLeft',
			timeout: 5000,
			pager: '.controls div'
		});
	}

});


var productMagnifyTrigger = {
	init:function() {
		$('div.productFeaturesPanel div.mainImage div.mainImageMagnify').click(function(e) {
			e.preventDefault();
			$('div.productFeaturesPanel div.mainImage a').trigger('click');
		});
	}
}


var productLinkManage = {
	elem:null,
	init:function() {
		
		var obj = this, pp = $('div.productPackPanel').eq(0), npp = $('div.productNonPackPanel').eq(0);
	
		if($('div.productFeaturesPanel div.productInfo p.featureBuyNowLink a').length > 0) {
			var obj = this;
			obj.elem = $('div.productFeaturesPanel div.productInfo p.featureBuyNowLink a').eq(0);
			
			var htmlOut = '<div style="display: none;"><div id="productOptionsPicker"><div class="left"></div><div class="right"></div></div></div>';
			$('body').append(htmlOut);
			
//			if($('div.productPackPanel').length > 0 && $('div.productNonPackPanel').length > 0) {
			if($('div.productPackPanel').length > 0) {
				
				// add cloned copy of panel to colorbox container
				pp.clone().appendTo('#productOptionsPicker div.left');
				npp.clone().appendTo('#productOptionsPicker div.right');
				
				// ensure the panels look vertically aligned
				if(parseInt(pp.height(), 10) > parseInt(npp.height(), 10)) {
					$('#productOptionsPicker div.right').css({'padding-top': Math.round((parseInt(pp.height(), 10)-parseInt(npp.height(), 10))/2)});
				} 
				else if(parseInt(pp.height(), 10) < parseInt(npp.height(), 10)) {
					$('#productOptionsPicker div.left').css({'padding-top': Math.round((parseInt(npp.height(), 10)-parseInt(pp.height(), 10))/2)});
				}
				if($('div.productNonPackPanel').length > 0){
					$(obj.elem).colorbox({width:"640px", inline:true, href:"#productOptionsPicker"});
				}else{
					$(obj.elem).colorbox({width:"354px", inline:true, href:"#productOptionsPicker"});
				};
			}
		}
		
		var pp_cb = $('#productOptionsPicker div.productPackPanel').eq(0), npp_cb = $('#productOptionsPicker div.productNonPackPanel').eq(0);		
		
		$.each([pp, npp], function(i, el) { obj.addTracker(el, 0); }); // normal links tracked with value "0"
		$.each([pp_cb, npp_cb], function(i, el) { obj.addTracker(el, 1); }); // cloned links tracked with value "1"
		
	}, 
	
	addTracker:function(el, val) {
		if(el.length > 0) {
			el.click(function(e) {
				_gaq.push(['_trackEvent', '2010PortHeat', 'clickout', el.find('a').eq(0).attr('href').split('?')[0], val]);
			});
		}
	}
}


// "mininav" sliding navigation
function MiniNav(elem){
	
	this.htmlOut = '';
	this.elem = elem;
	
	this.panelWidth = 0;
	this.panelNum = 5;			// 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) {
		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);
	
	// 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);
	
	var height = 0;
	elem.find('div.hider ul li').each(function(s, e) {
		var elemHeight = 0;
		var getHeight = parseInt($(e).height(), 10);
		height = getHeight > height ? getHeight : height;
	});
	
	elem.find('div.hider').css({'height':height});

	if(this.panelCentre == true) {
		elem.find('div.hider ul').each(function(s, e) {
			var listWidth = 0;
			$(e).find('li').each(function(x, y) {
				listWidth += parseInt($(y).css('width'), 10);
			});
			
			$(e).find('li').eq(0).css({'padding-left': (parseInt($(e).width(), 10)-listWidth)/2});
		});
	}

	// add next/prev buttons and set up click events
	if(elem.find('div.hider ul li').length > obj.panelNum) {
		elem.find('div.productCarouselInner').append('<a href="#" class="prev">&nbsp;</a><a href="#" class="next">&nbsp;</a>');		
		elem.find('a.prev').click(function(ev){ obj.scroll('left', ev, $(this)); });
		elem.find('a.next').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.productCarousel').length < 1 || $('div.productCarousel div.hider ul li').length < 1) return;
		var miniNav = new Array();
		$('div.productCarousel').each(function(s, e) {
			//$(e).addClass('js');
			
			miniNav[s] = new MiniNav($(e));
		});
	}
}


var productImageCarousel = {
	grouping:'.productImages',
	item:'a[rel="imageshow"]',
	initCheck:false, // set to true after initial page load url check
	
	qsParam: 'dimg',
	itemPos:null, // if there is a default image to open, this is the position
	panelWidth:240,
	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
	twoPanelEndlessScroll: true, // set to false when only two panels and the scroll effect goes left, right, left instead of forever left	
	elems: Array('#subImageCarousel'),

	init:function() {
		var obj = this;
		//var qStr = ''+location.search; // turn querystring into a text string
		
		$('a[rel="imageshow"]').each(function(s, e) {
			//if(qStr.indexOf(obj.qsParam + "=" + $(this).find('img').eq(0).attr('src')) > -1 && obj.itemPos == null) { obj.itemPos = s; }
			$(e).colorbox({ transition:'elastic',  speed:500,  current:'' });
		});
		
		if(obj.itemPos != null) {  $('a[rel="imageshow"]').eq(obj.itemPos).trigger('click'); }
		
		// for normal pages, return now, gallery requires more controls, below:
		if($('#subImageCarousel').length < 1) { return; }
		
		// set up scrolling
		$.each(obj.elems, function(index, elem) {
			if($(elem + ' div.hider ul').length > 1) { // check there are multiple panels required to scroll
				
				// set width of slider
				$(elem).data("panelNum", $(elem + ' div.slider ul').length); // assign number of panels as data to the container element
				$(elem + ' div.slider').css({'width':parseInt(obj.panelWidth, 10) * parseInt($(elem).data("panelNum"), 10)});
			
				$(elem + ' div.next a').click(function(ev) {
					ev.preventDefault();
					obj.scroll(obj.returnNext(elem), ev, elem, 'next');
				});
				$(elem + ' div.prev a').click(function(ev) {
					ev.preventDefault();
					obj.scroll(obj.returnPrev(elem), ev, elem, 'prev');
				});
				
				$(elem).data("visibleSet", 0); // set initial visible set to 0
				$(elem).data("scrolling", false);
			}
			
		});
	},

	// find the next/previous item in the set and return the number indicator for that item
	returnNext:function(elem) {
		return (parseInt($(elem).data("visibleSet"), 10)+1) > (parseInt($(elem).data("panelNum"), 10)-1) ? 0 : parseInt($(elem).data("visibleSet"), 10)+1; // +1 to account for zero indexing, +1 to get the next increment
	},	
	returnPrev:function(elem) {
		return (parseInt($(elem).data("visibleSet"), 10)-1) < 0 ? (parseInt($(elem).data("panelNum"), 10)-1) : (parseInt($(elem).data("visibleSet"), 10)-1);
	},
	
	scroll:function(set, event, elem, action) {
		var obj = this;
		
		event = (!event ? null : event);
		elem = (!elem ? null : elem);
		if(event != null) { event.preventDefault(); }
		
		if(set == $(elem).data("visibleSet")) { return; }

		if($(elem).data("scrolling") == false) {
			// handles special scroll scenarios, i.e. going from first to last or last to first
			if((parseInt($(elem).data("visibleSet"), 10)+1 == parseInt($(elem).data("panelNum"), 10) && set == 0 && action == 'next') || (parseInt($(elem).data("visibleSet"), 10) == 0 && set+1 == parseInt($(elem).data("panelNum"), 10)) || (parseInt($(elem).data("visibleSet"), 10) === 0 && action == 'prev')) {
				if((parseInt($(elem).data("visibleSet"), 10) == 1 && $(elem).data("panelNum") == 2 && obj.twoPanelEndlessScroll == true) || ($(elem).data("panelNum") > 2) ) {
					obj.specialScroll(set, event, elem);
					return;
				}
			}
			
			// handles special scroll of going from item zero to item 1 in a 2 panel scenario
			if(parseInt($(elem).data("visibleSet"), 10) === 0 && action == 'prev') { 
				obj.specialScroll(set, event, elem);
				return;
			}
			
			var obj = obj;
			var s = $(elem + ' div.slider').eq(0);
			var newPos = ( 0 - (parseInt(set, 10) * obj.panelWidth) );
			
			$(elem).data("visibleSet", set);
			$(elem).data("scrolling", true);
			s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem); });
		}
	},

	specialScroll:function(set, event, elem) {
		var obj = this;
		var s = $(elem + ' 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($(elem).data("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') {
			$(elem + ' div.slider').append($(elem + ' div.slider ul').eq(set).clone());
		} else {
			s.css({'left': (0-parseInt(obj.panelWidth, 10)) });
			$(elem + ' div.slider').prepend($(elem + ' div.slider ul').eq(set).clone());
		}
		$(elem + ' div.slider').eq(0).css({'width': parseInt($(elem + ' div.slider').eq(0).css('width'), 10) + parseInt(obj.panelWidth, 10)});
		
		var newPos = ( start == 'first' ? 0 : 0 - ((parseInt($(elem).data("visibleSet"), 10) * obj.panelWidth) + obj.panelWidth) );
		$(elem).data("visibleSet", set);
		$(elem).data("scrolling", true);
		s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem, start); });	
	},	
	
	stopScroll:function(elem, special){ 
		
		if(typeof(special) != 'undefined') {
			
			var obj = this;
			var s = $(elem + ' div.slider').eq(0);
			
			if(special == 'last') {
				s.css({'left':0});
				$(elem + ' div.slider ul').eq($(elem + ' div.slider ul').length-1).remove();
			} else if(special == 'first') {
				s.css({'left': (0 - (parseInt($(elem + ' div.slider ul').length, 10)-1) * this.panelWidth) + this.panelWidth  });
				$(elem + ' div.slider ul').eq(0).remove();
			}
			$(elem + ' div.slider').eq(0).css({'width': parseInt($(elem + ' div.slider').eq(0).css('width'), 10) - parseInt(this.panelWidth, 10)});
		}
		$(elem).data("scrolling", false); 
	}
	
}


var doFlashHeaders = {
	
	width: 700,
	height: 245,
	dir:'/static-flash/',
	container: 'flashHeaderReplace',
	target: 'flashHeaderReplaceTarget',
	filename: false, // stores the filename via the switch statement below
	flashvars: {},
	params: { wmode:"transparent" }, 
	attributes: {},
	
	init:function(){

		switch(location.pathname) {
			case '/shop/bbqs/':
				this.filename = 'shop_header_bbq.swf';
				this.height = 200;
			break;
			case '/shop/caravanning/':
				this.filename = 'shop_header_caravanning.swf';
				this.height = 200;
			break;
			case '/shop/cookers/':
				this.filename = 'shop_header_cooking.swf';
				this.height = 200;
			break;
			case '/shop/cylinder-gas/':
				this.filename = 'shop_header_cylinder_gas.swf';
				this.height = 200;
			break;
			case '/shop/fires/':
				this.filename = 'shop_header_fires.swf';
				this.height = 200;
			break;			
			case '/shop/portable-heaters/':
				this.filename = 'shop_header_portable_heaters.swf';
				this.height = 200;
			break;	
			case '/shop/toolbox/':
				this.filename = 'shop_header_tool_box.swf';
				this.height = 200;
			break;
			case '/heating/domestic-central-heating/new-energy-saving-solutions/chp/baxi-ecogen/':
				this.filename = 'ecogen_house-header.swf';
				this.height = 200;
			break;				
			case '/heating/domestic-central-heating/new-energy-saving-solutions/chp/fuel-cell-boiler/':
				this.filename = 'ecogen_house-header.swf';
				this.height = 200;
			break;				
			case '/heating/domestic-central-heating/new-energy-saving-solutions/chp/':
				this.filename = 'ecogen_house-header.swf';
				this.height = 200;
			break;				
		}

		if(this.filename == false) {  return;  }
		this.outputFlash();
	},
	
	outputFlash:function() {
		
		//remove corner overlays
		$('div.title').eq(0).find('div.cr-tl').remove();
		$('div.title').eq(0).find('div.cr-bl').remove();
		$('div.title').eq(0).find('div.cr-br').remove();
		
		// create flash container and populate
		$('div.title').eq(0).removeClass('title').addClass('flashTitle').css({'background':'transparent'}).prepend('<div id="' + this.container + '" style="height: ' + this.height + 'px;"><div id="' + this.target + '">&nbsp;</div></div>');
		swfobject.embedSWF(this.dir + this.filename, this.target, this.width, this.height, "9.0.0", false, this.flashvars, this.params, this.attributes);
	
	}

}


var heroTeaser = {

	panelWidth:224,
	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
	
	twoPanelEndlessScroll: true, // set to false when only two panels and the scroll effect goes left, right, left instead of forever left
	
	init: function() {
		var obj = this;
		
		if($('#heroSmall').length < 1 || $('#heroSmall div.slider div.img').length < 2) return; // don't scroll if there's only one item!
		obj.panelNum = $('#heroSmall div.slider div.img').length;
		
		// set width of slider
		$('#heroSmall div.slider').css({'width':parseInt(obj.panelWidth, 10) * parseInt(obj.panelNum, 10)});
		$('#heroSmall li a').each(function(s, e) {
			$(e).click(function(ev) {
				obj.scroll(s, ev, $(e));
			});
		});
		
		// set up contextual linkage
		$('#heroSmall div.hider').after('<p class="more"><a href="#">Find out more</a></p>');
		$('#heroSmall p.more a').eq(0).attr({ 'href': $('#heroSmall div.img').eq(0).find('a').eq(0).attr('href') });
		
		if(obj.scrollSelf) { obj.createAutoScroll(); }
	},

	scroll:function(set, event, elem) {
		var obj = this;
		
		event = (!event ? null : event);
		elem = (!elem ? null : elem);
		if(event != null) { event.preventDefault(); }
		if(elem != null) { elem.blur(); }
		
		if(set == obj.visibleSet) { return; }
		
		if(obj.scrolling == false) {
			// special rule is required to go from the last element to the first or vice versa
			if( (parseInt(obj.visibleSet, 10)+1 == parseInt(obj.panelNum, 10) && set == 0) || (parseInt(obj.visibleSet, 10) == 0 && set+1 == parseInt(obj.panelNum, 10)) ) {
				if( (parseInt(obj.visibleSet, 10) == 1 && obj.panelNum == 2 && obj.twoPanelEndlessScroll == true) || (obj.panelNum > 2) ) {
					obj.specialScroll(set, event, elem);
					return;
				}
			}
			
			var obj = obj;
			var s = $('#heroSmall div.slider').eq(0);
			
			var newPos = ( 0 - (parseInt(set, 10) * obj.panelWidth) );
			
			obj.visibleSet = set;
			$('#heroSmall li').removeClass('selected');
			$('#heroSmall li').eq(obj.visibleSet).addClass('selected');

			obj.scrolling = true;
			if(elem != null) {
				clearInterval(obj.timeout);
				obj.timeout = null;
			}
			
			s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem); });
		}
	},
	
	specialScroll:function(set, event, elem) {
		var obj = this;
		var s = $('#heroSmall 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(obj.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') {
			$('#heroSmall div.slider').append($('#heroSmall div.slider div.img').eq(set).clone());
		} else {
			s.css({'left': (0-parseInt(obj.panelWidth, 10)) });
			$('#heroSmall div.slider').prepend($('#heroSmall div.slider div.img').eq(set).clone());
		}
		$('#heroSmall div.slider').eq(0).css({'width': parseInt($('#heroSmall div.slider').eq(0).css('width'), 10) + parseInt(obj.panelWidth, 10)});
		
		var newPos = ( start == 'first' ? 0 : 0 - ((parseInt(obj.visibleSet, 10) * obj.panelWidth) + obj.panelWidth) );
		
		obj.visibleSet = set;
		$('#heroSmall li').removeClass('selected');
		$('#heroSmall li').eq(obj.visibleSet).addClass('selected');
		
		obj.scrolling = true;
		if(elem != null) {
			clearInterval(obj.timeout);
			obj.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 = $('#heroSmall div.slider').eq(0);
			
			if(special == 'last') {
				s.css({'left':0});
				$('#heroSmall div.slider div.img').eq($('#heroSmall div.slider div.img').length-1).remove();
			} else if(special == 'first') {
				s.css({'left': (0 - (parseInt($('#heroSmall div.slider div.img').length, 10)-1) * this.panelWidth) + this.panelWidth  });
				$('#heroSmall div.slider div.img').eq(0).remove();
			}
			
			$('#heroSmall div.slider').eq(0).css({'width': parseInt($('#heroSmall div.slider').eq(0).css('width'), 10) - parseInt(this.panelWidth, 10)});
		
		}
		$('#heroSmall p.more a').eq(0).attr({ 'href': $('#heroSmall div.img').eq(this.visibleSet).find('a').eq(0).attr('href') });
		
		if(elem != null && this.scrollSelf) { this.createAutoScroll(); }
		this.scrolling = false; 
	}
	
}


// rotating section on the homepage
var homeRotator = {

	panelWidth:680,
	panelNum:0,
	
	scrolling: false,	// is the object currently scrolling
	scrollSpeed: 1000,  // speed of scroll
	scrollInt: 6000,	// 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
	
	twoPanelEndlessScroll: true, // set to false when only two panels and the scroll effect goes left, right, left instead of forever left
	
	init: function() {
		var obj = this;
		
		if($('div.homeContentRow').length < 1) { return; }
		// do some height sizing on the non-rotating section
		var h = 0;
		$('div.homeContentRow').eq(0).find('div.homeContent').each(function(s, e) {
			if(parseInt($(e).css('height'), 10) > h) { h = parseInt($(e).css('height'), 10); }
		});
		if(h > 0) { $('div.homeContentRow').eq(0).find('div.homeContent').css({'height':h}); }
		h = null;		
		
		if($('#homeRowRotate').length < 1 || $('#homeRowRotate div.slider div.homeContentRow').length < 2) return; // don't scroll if there's only one item!
		obj.panelNum = $('#homeRowRotate div.slider div.homeContentRow').length;

		// do some height setting
		var h = 0;
		$('#homeRowRotate div.slider div.homeContentRow div.homeContent').each(function(s, e) {
			var fullHeight = parseInt($(e).height(), 10);
			if(fullHeight > h) { h = fullHeight; }
		});
		
		if(h > 0) { $('div#homeRowRotate div.hider, div#homeRowRotate div.homeContent, div#homeRowRotate div.homeContentRow, div#homeRowRotate div.hider div.homeContent').css({'height':h}); }
		h = null;
		
		// set width of slider
		$('#homeRowRotate div.slider').css({'width':parseInt(obj.panelWidth, 10) * parseInt(obj.panelNum, 10)});
		$('#homeRowRotate li a').each(function(s, e) {
			$(e).click(function(ev) {
				obj.scroll(s, ev, $(e));
			});
		});
		
		// create navigation
		var navList = '';
		navList += '<ul>';
		for(var i = 0; i < obj.panelNum; i++) { navList += '<li><a href="#">&nbsp;</a></li>'; }
		navList += '</ul>';
		$('#homeRowRotate').append(navList);
		$('#homeRowRotate li').eq(0).addClass('selected');
		
		$('#homeRowRotate li a').each(function(s, e) {
			$(e).click(function(ev) {
				obj.scroll(s, ev, $(e));
			});
		});
		
		if(obj.scrollSelf) { obj.createAutoScroll(); }
	},

	scroll:function(set, event, elem) {
		var obj = this;
		
		event = (!event ? null : event);
		elem = (!elem ? null : elem);
		if(event != null) { event.preventDefault(); }
		if(elem != null) { elem.blur(); }
		
		if(set == obj.visibleSet) { return; }
		
		
		if(obj.scrolling == false) {
			
			// special rule is required to go from the last element to the first or vice versa
			if( (parseInt(obj.visibleSet, 10)+1 == parseInt(obj.panelNum, 10) && set == 0) || (parseInt(obj.visibleSet, 10) == 0 && set+1 == parseInt(obj.panelNum, 10)) ) {
				if( (parseInt(obj.visibleSet, 10) == 1 && obj.panelNum == 2 && obj.twoPanelEndlessScroll == true) || (obj.panelNum > 2) ) {
					obj.specialScroll(set, event, elem);
					return;
				}
			}
			
			var obj = obj;
			var s = $('#homeRowRotate div.slider').eq(0);
			
			var newPos = ( 0 - (parseInt(set, 10) * obj.panelWidth) );
			
			obj.visibleSet = set;
			$('#homeRowRotate li').removeClass('selected');
			$('#homeRowRotate li').eq(obj.visibleSet).addClass('selected');

			obj.scrolling = true;
			if(elem != null) {
				clearInterval(obj.timeout);
				obj.timeout = null;
			}
			
			s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem); });
		}
	},
	
	specialScroll:function(set, event, elem) {
		var obj = this;
		var s = $('#homeRowRotate 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(obj.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') {
			$('#homeRowRotate div.slider').append($('#homeRowRotate div.slider div.homeContentRow').eq(set).clone());
		} else {
			s.css({'left': (0-parseInt(obj.panelWidth, 10)) });
			$('#homeRowRotate div.slider').prepend($('#homeRowRotate div.slider div.homeContentRow').eq(set).clone());
		}
		$('#homeRowRotate div.slider').eq(0).css({'width': parseInt($('#homeRowRotate div.slider').eq(0).css('width'), 10) + parseInt(obj.panelWidth, 10)});
		
		var newPos = ( start == 'first' ? 0 : 0 - ((parseInt(obj.visibleSet, 10) * obj.panelWidth) + obj.panelWidth) );
		
		obj.visibleSet = set;
		$('#homeRowRotate li').removeClass('selected');
		$('#homeRowRotate li').eq(obj.visibleSet).addClass('selected');
		
		obj.scrolling = true;
		if(elem != null) {
			clearInterval(obj.timeout);
			obj.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 = $('#homeRowRotate div.slider').eq(0);
			
			if(special == 'last') {
				s.css({'left':0});
				$('#homeRowRotate div.slider div.homeContentRow').eq($('#homeRowRotate div.slider div.homeContentRow').length-1).remove();
			} else if(special == 'first') {
				s.css({'left': (0 - (parseInt($('#homeRowRotate div.slider div.homeContentRow').length, 10)-1) * this.panelWidth) + this.panelWidth  });
				$('#homeRowRotate div.slider div.homeContentRow').eq(0).remove();
			}
			
			$('#homeRowRotate div.slider').eq(0).css({'width': parseInt($('#homeRowRotate div.slider').eq(0).css('width'), 10) - parseInt(this.panelWidth, 10)});
		}
		$('#homeRowRotate p.more a').eq(0).attr({ 'href': $('#homeRowRotate div.homeContentRow').eq(this.visibleSet).find('a').eq(0).attr('href') });
		
		if(elem != null && this.scrollSelf) { this.createAutoScroll(); }
		this.scrolling = false; 
	}
	
}


// video lightbox
var vidLBox = { 

	init:function(){
	
		if($('#mediaPanelVidHeader').length < 1) { return; }
		if($('#colorbox_target').length < 1) {
			$('body').append('<div style="display: none"><div id="colorbox_target" style="width: 400px; height: 288px;"></div></div>'); // originally "580", "400"
		}
		
		$('#mediaPanelVidHeader a[rel="videoshow"]').colorbox({
			inline:true, 
			href: "#colorbox_target",
			onComplete:function(){ 
				//alert($(this).html()+'-'+$(this).attr('href'));
				var flashvars = { file:$(this).attr('href'), autostart:true, 'plugins':'googlytics-1' }
				var params = { wmode:'transparent', allowfullscreen:'true', allowscriptaccess:'always' }, attributes = {};
				swfobject.embedSWF("/javascript/player.swf", 'colorbox_target', "400", "288", "9.0.0", false, flashvars, params, attributes);	
			}
		});
		
		// if there are additional images and videos, create the switcher, default video off
		if($('#mediaPanelImages').length > 0) {
			
			$('#mediaPanelVidHeader').css({'display':'none'});

			$('#mediaPanelImages').click(function(e) {
				e.preventDefault();
				$('#mediaPanelVideo').removeClass('selected');
				$(this).addClass('selected');
				$('#mediaPanelImgHeader').css({'display':'block'});
				$('#mediaPanelVidHeader').css({'display':'none'});
			});

			$('#mediaPanelVideo').click(function(e) {
				e.preventDefault();
				$('#mediaPanelImages').removeClass('selected');
				$(this).addClass('selected');
				$('#mediaPanelImgHeader').css({'display':'none'});
				$('#mediaPanelVidHeader').css({'display':'block'});				
			});
		}
	}
}


var calorEnquiryForm = {

	formName:	'#calorForm',

	init:function() {
	
		if($(this.formName).length < 1) return;
		$(this.formName).validate({
			errorPlacement: function(error, element) {
				if(error) { 
				
					if(element.attr('id') == 'cfMonFriMorning') {
						element.parents('.fields').find('.field').eq(1).after(error);
					} else {
						element.parents('.field').after(error);
					}
				}
			}
		});
	
		this.buildUserChoice();
		this.addEvents();
		this.setFormFromUrl();
		this.addStandardValidationRules();
		$(this.formName + ' select,' + this.formName + ' input:checkbox,' + this.formName + ' input:radio,' + this.formName + ' input:file').uniform();
	},
	buildUserChoice:function() {
	
		var select = '';
		
		select += 	'<div id="userChoice">';
		select += 	'	<select id="enquiryType" name="enquiryType">';
		select +=   '		<option value="">--- Choose an option ---</option>';
		select +=   '		<option value="requestBrochure">Request Brochure</option>';
		select +=   '		<option value="requestAppointment">Request Appointment</option>';
		select +=   '		<option value="requestAppointmentCalorforce">Request Appointment Calorforce</option>';
		select +=	'		<option value="enquiries">Enquiries</option>';
		select +=   '		<option value="websiteFeedback">Website Feedback</option>';
		select +=	'		<option value="movingProperty">Moving Property</option>';
		select +=	'		<option value="recommendFriend">Recommend a Friend</option>';
		select +=	'		<option value="becomeInstaller">Become an Installer</option>';
		select += 	'		<option value="becomeStockist">Become a Stockist</option>';
		select += 	'		<option value="calorforceEnquiry">CalorForce Enquiries</option>';
		select += 	'		<option value="signUpAndWin">Love to Shop Competition</option>';
		select += 	'		<option value="newsletterSignUp">Newsletter Sign Up</option>';
		select += 	'		<option value="businessIncentive">Business Incentive Scheme</option>';
		select += 	'	</select>';
		select +=   '</div>';
		
		$(this.formName).prepend(select);

	},
	addEvents:function() {
	
		var obj = this;

		// user choice select box event
		$(this.formName + ' #userChoice select').change(function(){

			$(obj.formName + ' .customPanel').hide();
			obj.setForm('#' + $(this).val() + 'Panel');
			
			// output bottom message if on requestAppointmentCalorforce
			if($(this).val() == 'requestAppointmentCalorforce') {
				$('#formMsg').html('Enquiries sent via the form will be responded to within 48 hours excluding bank holidays and weekend.');
				$('#formMsg').css({'display':'block'});
			} else {
				$('#formMsg').html('');
				$('#formMsg').css({'display':'none'});
			}
		});
		
		// user choice on intended use
		$(this.formName + ' #intendedUse').change(function(){

			if( $(this).val() == 'In the home') {
				$('#requestAppointmentCurrentBoiler').show();
				obj.addRequestAppointmentAdditionalValidationRules();
			} 
			else {
				$('#requestAppointmentCurrentBoiler').hide();
				$("#currentFuelCooking").rules("remove");
				$("#currentFuelHeating").rules("remove");
			}

		});
		
		// user choice currentFuelCooking
		$(this.formName + ' #currentFuelCooking').change(function(){
			$(this).val() == 'Other' ? $('#cookingFuelOther').parent().show() : $('#cookingFuelOther').parent().hide();
		});

		// user choice currentFuelHeating
		$(this.formName + ' #currentFuelHeating').change(function(){
			$(this).val() == 'Other' ? $('#heatingFuelOther').parent().show() : $('#heatingFuelOther').parent().hide();
		});
		
		// user choice compCurrentFuelCooking
		$(this.formName + ' #compCurrentFuelCooking').change(function(){
			$(this).val() == 'Other' ? $('#compCookingFuelOther').parent().show() : $('#compCookingFuelOther').parent().hide();
		});

		// user choice compCurrentFuelHeating
		$(this.formName + ' #compCurrentFuelHeating').change(function(){
			$(this).val() == 'Other' ? $('#compHeatingFuelOther').parent().show() : $('#compHeatingFuelOther').parent().hide();
		});
		
		// user choice btccCompCurrentFuelCooking
		$(this.formName + ' #btccCompCurrentFuelCooking').change(function(){
			$(this).val() == 'Other' ? $('#btccCompCookingFuelOther').parent().show() : $('#btccCompCookingFuelOther').parent().hide();
		});

		// user choice btccCompCurrentFuelHeating
		$(this.formName + ' #btccCompCurrentFuelHeating').change(function(){
			$(this).val() == 'Other' ? $('#btccCompHeatingFuelOther').parent().show() : $('#btccCompHeatingFuelOther').parent().hide();
		});
		
		// user choice property fuel supply other
		$(this.formName + ' #propertyFuelSupply').change(function(){
			$(this).val() == 'Other' ? $('#propertyFuelSupplyOther').parent().show() : $('#propertyFuelSupplyOther').parent().hide();
		});
		
		// user choice friendCurrentFuel
		$(this.formName + ' #friendCurrentFuel').change(function(){
			$(this).val() == 'Other' ? $('#friendCurrentFuelOther').parent().show() : $('#friendCurrentFuelOther').parent().hide();
		});
		
		// user choice currentMembershipOther
		$(this.formName + ' #currentMembershipOther').click(function(){
			$(this).attr('checked') == true ? $('#currentMembershipOtherName').parent().show() : $('#currentMembershipOtherName').parent().hide();
		});
		
		// user choice busIncCurrentMembershipOther
		$(this.formName + ' #busIncCurrentMembershipOther').click(function(){
			$(this).attr('checked') == true ? $('#busIncCurrentMembershipOtherName').parent().show() : $('#busIncCurrentMembershipOtherName').parent().hide();
		});
		
	},
	setForm:function(activeCustomPanel) {
		// hide all the custom panels
		$(this.formName + ' .customPanel').hide();
		
		// now set the active custom panel
		$(activeCustomPanel).show();
		
		this.clearAllValidationRules();
		this.addStandardValidationRules();
		this.addCustomValidationRules(activeCustomPanel);
	
	},
	setFormFromUrl:function() {
		
		var str;
		str = window.location.href;

		if( str.indexOf('request-brochure') >= 0 ){
			$('#enquiryType').val('requestBrochure');
			this.setForm('#requestBrochurePanel');
		}
		else if( str.indexOf('request-appointment-calorforce') >= 0 ) {
			$('#enquiryType').val('requestAppointmentCalorforce');
			this.setForm('#requestAppointmentCalorforcePanel');
		}
		else if( str.indexOf('request-appointment') >= 0 ) {
		  $('#enquiryType').val('requestAppointment');
			this.setForm('#requestAppointmentPanel');
		}
		else if( str.indexOf('website-feedback') >= 0 ) {
			$('#enquiryType').val('websiteFeedback');
			this.setForm('#websiteFeedbackPanel');
		}
		else if( str.indexOf('moving-property') >= 0 ) {
			$('#enquiryType').val('movingProperty');
			this.setForm('#movingPropertyPanel');
		}
		else if( str.indexOf('recommend-friend') >= 0 ) {
			$('#enquiryType').val('recommendFriend');
			this.setForm('#recommendFriendPanel');
		}
		else if( str.indexOf('become-installer') >= 0 ) {
			$('#enquiryType').val('becomeInstaller');
			this.setForm('#becomeInstallerPanel');
		}
		else if( str.indexOf('become-stockist') >= 0 ) {
			$('#enquiryType').val('becomeStockist');
			this.setForm('#becomeStockistPanel');
		}
		else if( str.indexOf('calorforce-enquiries') >= 0 ) {
			$('#enquiryType').val('calorforceEnquiry');
			this.setForm('#calorforceEnquiryPanel');
		}
		else if( str.indexOf('enquiries') >= 0 ) {
			$('#enquiryType').val('enquiries');
			this.setForm('#enquiriesPanel');
		}
		else if( str.indexOf('sign-up-and-win') >= 0 ) {
			$('#enquiryType').val('signUpAndWin');
			this.setForm('#signUpAndWinPanel');
		}
		else if( str.indexOf('newsletter-sign-up') >= 0 ) {
			$('#enquiryType').val('newsletterSignUp');
			this.setForm('#newsletterSignUpPanel');
		}
		else if( str.indexOf('business-incentive-scheme') >= 0 ) {
			$('#enquiryType').val('businessIncentive');
			this.setForm('#businessIncentivePanel');
		}
		else if( str.indexOf('btcc-competition') >= 0 ) {
			$('#enquiryType').val('btccCompetition');
			this.setForm('#btccCompetitionPanel');
		}
		else {
			// Do nothing as this is the default state
		}
		
	},
	clearAllValidationRules:function() {
	  var fields = $(this.formName + " :input");
		 jQuery.each(fields, function() {
		  if (this.id !== '') $('#'+this.id).rules("remove");
	  });
	},
	addCustomValidationRules:function(activePanel) {

		if(activePanel == '#requestBrochurePanel'){
			this.addRequestBrochureValidationRules();
		}
		else if(activePanel == '#requestAppointmentCalorforcePanel'){
			this.addRequestAppointmentCalorforceValidationRules();
		}
		else if(activePanel == '#requestAppointmentPanel'){
			this.addRequestAppointmentValidationRules();
		}
		else if(activePanel == '#enquiriesPanel'){
			this.addEnquiriesValidationRules();
		}
		else if(activePanel == '#websiteFeedbackPanel'){
			this.addWebsiteFeedbackValidationRules();
		}
		else if(activePanel == '#movingPropertyPanel'){
			this.addMovingPropertyValidationRules();
		}
		else if(activePanel == '#recommendFriendPanel'){
			this.addRecommendFriendValidationRules();
		}
		else if(activePanel == '#becomeInstallerPanel'){
			this.addBecomeInstallerValidationRules();
		}
		else if(activePanel == '#becomeStockistPanel'){
			this.addBecomeStockistValidationRules();
		}
		else if(activePanel == '#calorforceEnquiryPanel'){
			this.addCalorforceEnquiryValidationRules();
		}
		else if(activePanel == '#signUpAndWinPanel'){
			this.addSignUpAndWinValidationRules();
		}
		else if(activePanel == '#newsletterSignUpPanel'){
			this.addNewsletterSignUpValidationRules();
		}
		else if(activePanel == '#businessIncentivePanel'){
			this.addBusinessIncentiveValidationRules();
		}
		else if(activePanel == '#btccCompetitionPanel'){
			this.addBtccCompetitionValidationRules();
		}
		else {
			// Do nothing as this is the default state
		}
		
	},
	addStandardValidationRules:function() {	

		
		$("#title").rules("add", {
		  required: true,
		  messages: {
			required: "You must choose an option"
		  }
		});
		
		$("#forename").rules("add", {
		  required: true,
		  maxlength: 50,
		  messages: {
			required: "This field is mandatory",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
	
		$("#surname").rules("add", {
		  required: true,
		  maxlength: 50,
		  messages: {
			required: "This field is mandatory",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		
		$("#addr1").rules("add", {
		  required: true,
		  maxlength: 100,
		  messages: {
			required: "This field is mandatory",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		
		$("#town").rules("add", {
		  required: true,
		  maxlength: 100,
		  messages: {
			required: "This field is mandatory",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		
		$("#postcode").rules("add", {
		  required: true,
		  maxlength: 10,
		  messages: {
			required: "This field is mandatory",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		
		$("#email").rules("add", {
		  required: true,
		  email: true,
		  maxlength: 100,
		  messages: {
			required: "This field is mandatory",
			email: "Must be a valid E-Mail Address",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		
		$("#contactMeBy").rules("add", {
		  required: true,
		  messages: {
			required: "You must choose an option"
		  }
		});
		
		$("#privacyPolicy").rules("add", {
		  required: true,
		  messages: {
			required: "You must agree to the privacy policy"
		  }
		});
	
	},
	addRequestBrochureValidationRules:function() {
		$("#businessBrochure").rules("add", {
		  required: function() {
			  return $('#homeBrochure').val() == '' ? true : false;
		  },
		  messages: {
			required: "You must choose either a Business or Home Brochure"
		  }
		});
		
		$("#homeBrochure").rules("add", {
		  required: function() {
			  return $('#businessBrochure').val() == '' ? true : false;
		  },
		  messages: {
			required: "You must choose either a Business or Home Brochure"
		  }
		}); 
	},
	addRequestAppointmentValidationRules:function() {
	
		$("#intendedUse").rules("add", {
		  required: true,
		  messages: {
			required: "You must choose an intended use"
		  }
		});
		
		$("#monFriMorning").rules("add", {
			required : true,
			minlength: 1
		});
		
	},
	addRequestAppointmentAdditionalValidationRules:function() {
	
		$('#currentFuelCooking').rules("add", {
			required : true		
		});
		
		$('#currentFuelHeating').rules("add", {
			required: true
		});

	},
	addRequestAppointmentCalorforceValidationRules:function() {

		$("#calorforceMonFriMorning").rules("add", {
			required : true,
			minlength: 1
		});
		
		$("#enquiryNature").rules("add", {
		  required: true,
		  messages: {
			required: "You must choose an option"
		  }
		});

	},
	addEnquiriesValidationRules:function() {
		
		$("#yourEnquiry").rules("add",{
			required: true
		});
		
	},
	addWebsiteFeedbackValidationRules:function() {
		
		$("#comments").rules("add",{
			required: true
		});
		
	},
	addMovingPropertyValidationRules:function() {
		
		$("#accountNo").rules("add", {
		  required: true,
		  messages: {
			required: "You must enter your account number"
		  }
		});
		
		$("#movingDateDD").rules("add", {
		  required: true,
		  messages: {
			required: "You must enter a day"
		  }
		});
		
		$("#movingDateMM").rules("add", {
		  required: true,
		  messages: {
			required: "You must enter a month"
		  }
		});
		
		$("#movingDateYYYY").rules("add", {
		  required: true,
		  messages: {
			required: "You must enter a year"
		  }
		});
		
		$("#newAddr1").rules("add", {
		  required: true,
		  messages: {
			required: "You must enter address line 1"
		  }
		});
		
		$("#newTown").rules("add", {
		  required: true,
		  messages: {
			required: "You must enter your town/city"
		  }
		});

		$("#newPostcode").rules("add", {
		  required: true,
		  messages: {
			required: "You must enter your post code"
		  }
		});
		
		$("#newMonFriMorning").rules("add", {
			required : true,
			minlength: 1
		});

	},
	addRecommendFriendValidationRules:function() {
		
		$("#recommendAccountNo").rules("add", {
		  required: true,
		  messages: {
			required: "You must enter your account number"
		  }
		});

		$("#friendConsent").rules("add", {
		  required: true,
		  messages: {
			required: "You must have your friends consent"
		  }
		});
	
	},
	addBecomeInstallerValidationRules:function() {
		
		$("#lastYearMains").rules("add", {
			required : true,
			minlength: 1
		});
		
		$("#signature").rules("add", {
			required: true,
			messages: {
				required: "You must sign your name to join the scheme"
			}
		});
		
		$("#installerSchemeTerms").rules("add", {
			  required: true,
			  messages: {
				required: "You must agree to the installer scheme terms & conditions"
			  }
		});
		
	},
	addBecomeStockistValidationRules:function() {
		
		$("#currentStockistStatus").rules("add", {
		  required: true,
		  messages: {
			required: "You must choose an option"
		  }
		});
		
	},
	addCalorforceEnquiryValidationRules:function() {
	
		$('#calorforceEnquiryNature').rules("add", {
			required: true
		});
	
		$("#cfMonFriMorning").rules("add", {
			required : true,
			minlength: 1
		});

	},
	addSignUpAndWinValidationRules:function() {
	
		$('#compCurrentFuelCooking').rules("add", {
			required : true		
		});
		
		$('#compCurrentFuelHeating').rules("add", {
			required: true
		});
		
		$("#competitionTerms").rules("add", {
			  required: true,
			  messages: {
				required: "You must agree to the competition terms & conditions"
			  }
		});

	},
	addNewsletterSignUpValidationRules:function() {
		
		

	},
	addBusinessIncentiveValidationRules:function() {
		
		$("#busIncLastYearMains").rules("add", {
			required : true,
			minlength: 1
		});
		
		$("#busIncName").rules("add", {
		  required: true,
		  maxlength: 50,
		  messages: {
			required: "This field is mandatory",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		
		$("#busIncAddr1").rules("add", {
		  required: true,
		  maxlength: 100,
		  messages: {
			required: "This field is mandatory",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		
		$("#busIncTown").rules("add", {
		  required: true,
		  maxlength: 100,
		  messages: {
			required: "This field is mandatory",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		
		$("#busIncPostcode").rules("add", {
		  required: true,
		  maxlength: 10,
		  messages: {
			required: "This field is mandatory",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		
		$("#busIncTelephone").rules("add", {
		  required: true,
		  maxlength: 100,
		  messages: {
			required: "This field is mandatory",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		
		/*
		$("#busIncEmail").rules("add", {
		  required: true,
		  email: true,
		  maxlength: 100,
		  messages: {
			required: "This field is mandatory",
			email: "Must be a valid E-Mail Address",
			maxlength: jQuery.format("Can be up to {0} characters long")
		  }
		});
		*/
		
		$("#busIncConfirmConsent").rules("add", {
			  required: true,
			  messages: {
				required: "You must confirm consent"
			  }
		});
		
		$("#busIncTerms").rules("add", {
			  required: true,
			  messages: {
				required: "You must agree to the business incentive scheme terms & conditions"
			  }
		});
		
	},
	addBtccCompetitionValidationRules:function() {
	
		$('#btccCompCurrentFuelCooking').rules("add", {
			required : true		
		});
		
		$('#btccCompCurrentFuelHeating').rules("add", {
			required: true
		});
		
		$("#btccCompetitionTerms").rules("add", {
			  required: true,
			  messages: {
				required: "You must agree to the competition terms & conditions"
			  }
		});

	}
};

var galleryEnable = {
	grouping:'.lbox',
	item:'a[rel="imageshow"]',
	initCheck:false, // set to true after initial page load url check
	
	qsParam: 'dimg',
	itemPos:null, // if there is a default image to open, this is the position
	panelWidth:670,
	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
	twoPanelEndlessScroll: true, // set to false when only two panels and the scroll effect goes left, right, left instead of forever left	
	elems: Array('#galleryImages','#galleryVideo'),

	init:function() {
		var obj = this;
		var qStr = ''+location.search; // turn querystring into a text string
		$('a[rel="imageshow"]').each(function(s, e) {
			if(qStr.indexOf(obj.qsParam + "=" + $(this).find('img').eq(0).attr('src')) > -1 && obj.itemPos == null) { obj.itemPos = s; }
			$(e).colorbox({ transition:'elastic',  speed:500,  current:'' });
		});
		if(obj.itemPos != null) {  $('a[rel="imageshow"]').eq(obj.itemPos).trigger('click'); }
		
		// for normal pages, return now, gallery requires more controls, below:
		if($('#galleryImages').length < 1) { return; }
		
		// set up scrolling
		$.each(obj.elems, function(index, elem) {
			if($(elem + ' div.galleryBody ul').length > 1) { // check there are multiple panels required to scroll
				
				// create next/previous links
				var html = '<div class="left"><p class="buttonDark"><a href="" class="prev"><span>Previous Set</span></a></p></div><div class="right"><p class="buttonDark"><a href="" class="next"><span>Next Set</span></a></p></div>';
				$(elem + ' div.galleryFooter').append(html);
				
				// set width of slider
				$(elem).data("panelNum", $(elem + ' div.slider ul').length); // assign number of panels as data to the container element
				$(elem + ' div.slider').css({'width':parseInt(obj.panelWidth, 10) * parseInt($(elem).data("panelNum"), 10)});
			
				$(elem + ' a.next').click(function(ev) {
					ev.preventDefault();
					obj.scroll(obj.returnNext(elem), ev, elem, 'next');
				});
				$(elem + ' a.prev').click(function(ev) {
					ev.preventDefault();
					obj.scroll(obj.returnPrev(elem), ev, elem, 'prev');
				});
				
				$(elem).data("visibleSet", 0); // set initial visible set to 0
				$(elem).data("scrolling", false);
			}
		});
	},

	// find the next/previous item in the set and return the number indicator for that item
	returnNext:function(elem) {
		return (parseInt($(elem).data("visibleSet"), 10)+1) > (parseInt($(elem).data("panelNum"), 10)-1) ? 0 : parseInt($(elem).data("visibleSet"), 10)+1; // +1 to account for zero indexing, +1 to get the next increment
	},	
	returnPrev:function(elem) {
		return (parseInt($(elem).data("visibleSet"), 10)-1) < 0 ? (parseInt($(elem).data("panelNum"), 10)-1) : (parseInt($(elem).data("visibleSet"), 10)-1);
	},
	
	scroll:function(set, event, elem, action) {
		var obj = this;
		
		event = (!event ? null : event);
		elem = (!elem ? null : elem);
		if(event != null) { event.preventDefault(); }
		
		if(set == $(elem).data("visibleSet")) { return; }

		if($(elem).data("scrolling") == false) {
			// handles special scroll scenarios, i.e. going from first to last or last to first
			if((parseInt($(elem).data("visibleSet"), 10)+1 == parseInt($(elem).data("panelNum"), 10) && set == 0 && action == 'next') || (parseInt($(elem).data("visibleSet"), 10) == 0 && set+1 == parseInt($(elem).data("panelNum"), 10)) || (parseInt($(elem).data("visibleSet"), 10) === 0 && action == 'prev')) {
				if((parseInt($(elem).data("visibleSet"), 10) == 1 && $(elem).data("panelNum") == 2 && obj.twoPanelEndlessScroll == true) || ($(elem).data("panelNum") > 2) ) {
					obj.specialScroll(set, event, elem);
					return;
				}
			}
			
			// handles special scroll of going from item zero to item 1 in a 2 panel scenario
			if(parseInt($(elem).data("visibleSet"), 10) === 0 && action == 'prev') { 
				obj.specialScroll(set, event, elem);
				return;
			}
			
			var obj = obj;
			var s = $(elem + ' div.slider').eq(0);
			var newPos = ( 0 - (parseInt(set, 10) * obj.panelWidth) );
			
			$(elem).data("visibleSet", set);
			$(elem).data("scrolling", true);
			s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem); });
		}
	},

	specialScroll:function(set, event, elem) {
		var obj = this;
		var s = $(elem + ' 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($(elem).data("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') {
			$(elem + ' div.slider').append($(elem + ' div.slider ul').eq(set).clone());
		} else {
			s.css({'left': (0-parseInt(obj.panelWidth, 10)) });
			$(elem + ' div.slider').prepend($(elem + ' div.slider ul').eq(set).clone());
		}
		$(elem + ' div.slider').eq(0).css({'width': parseInt($(elem + ' div.slider').eq(0).css('width'), 10) + parseInt(obj.panelWidth, 10)});
		
		var newPos = ( start == 'first' ? 0 : 0 - ((parseInt($(elem).data("visibleSet"), 10) * obj.panelWidth) + obj.panelWidth) );
		$(elem).data("visibleSet", set);
		$(elem).data("scrolling", true);
		s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem, start); });	
	},	
	
	stopScroll:function(elem, special){ 
		
		if(typeof(special) != 'undefined') {
			
			var obj = this;
			var s = $(elem + ' div.slider').eq(0);
			
			if(special == 'last') {
				s.css({'left':0});
				$(elem + ' div.slider ul').eq($(elem + ' div.slider ul').length-1).remove();
			} else if(special == 'first') {
				s.css({'left': (0 - (parseInt($(elem + ' div.slider ul').length, 10)-1) * this.panelWidth) + this.panelWidth  });
				$(elem + ' div.slider ul').eq(0).remove();
			}
			$(elem + ' div.slider').eq(0).css({'width': parseInt($(elem + ' div.slider').eq(0).css('width'), 10) - parseInt(this.panelWidth, 10)});
		}
		$(elem).data("scrolling", false); 
	}
	
}

var normaliseCNFormBoxes = {

	heighest: 0,

	init:function(){		
		var obj = this;
		$('.cnFormBoxContainer .cnFormBoxMid').each(function(i){
			if( $(this).height() > obj.heighest ) {
				obj.heighest = $(this).height();
			}
		});
		
		$('.cnFormBoxContainer .cnFormBoxMid').css({ 'min-height' : obj.heighest + 'px' });
	}

}

var addSwitchingFlash = {
	
	init:function(){
	
		if ($("#widget").length > 0) {
			
			$('#widget').html('<img src="/static-images/switching-alt.jpg" width="698" height="560" alt="" />');
			var flashvars = {  }, params = { allowfullscreen: true, wmode:"opaque" }, attributes = {};
			swfobject.embedSWF("/static-flash/switching_interactive.swf", "widget", "698", "560", "9.0.0", false, flashvars, params, attributes);
			
		}
	
	}
	
}

/* start of behavioural tracking code */

	/* behavioural tracking 
		requires tracking global variable to be passed in homepage snippet in this format:
		
		<script type="text/javascript">
		var trackingTypes = {
			1:{ type : 'image', src : '/path/to/image.jpg' },                      // standard image, no link
			2:{ type : 'link', src : '/path/to/image.jpg', link : '/link/url/' },  // standard image with link
			3:{ type : 'flash', src : '/path/to/flash.swf' }                       // static flash
		}
		</script>
		
		Then this code in the snippet on individual pages:
		
		<!-- behavioural tracking cookie -->
		<script type="text/javascript">setTrackingType(2, 30);</script> 
		
		param 1 = the type from the homepage snippet (i.e. linked image in the above example)
		param 2 = number of days to store the cookie, if unset, defaults to 7 days
		
	*/
	
	function setTrackingType(num, days) {
		if(typeof num !== 'undefined') {
			var days = typeof days !== 'undefined' ? days : 7;
			$.cookie('trackType', num, { expires: days, path: '/' }); 
		}
	}
	
	var behaviouralTracking = {
		
		trackObj : null,
		
		init: function() {
			var obj = this;
			if ($("#homeFlashBanner").length > 0) { 
				if(!$.cookie('trackType') || typeof trackingTypes === 'undefined') { // no cookie set or defining variable missing, show default banner
					obj.defaultOutput();
				} else { // cookie set, try and display custom 
					var cookieVal = jQuery.trim($.cookie('trackType'));
					if(typeof trackingTypes[cookieVal] !== 'undefined') {
						obj.trackObj =  trackingTypes[cookieVal];
						switch (obj.trackObj['type']) {
							case 'image':
								$('#homeFlashBanner').html('<div class="tl"></div><img title="" alt="" src="' + obj.trackObj['src'] + '">');
							break;
							case 'link':
								$('#homeFlashBanner').html('<div class="tl"></div><a href="' + obj.trackObj['link'] + '"><img title="" alt="" src="' + obj.trackObj['src'] + '"></a>');
							break;
							case 'flash':
								var flashvars = {}, params = { wmode:"transparent" }, attributes = {};
								swfobject.embedSWF(obj.trackObj['src'], "homeFlashBanner", "700", "370", "9.0.0", false, flashvars, params, attributes);
							break;
							default:
								obj.defaultOutput(); // should not be possible to reach this stage...
							break;
						}
						// set styles inline - these could be added to the main/ie6 css at a later stage if required...
						$('#homeFlashBanner').css('position','relative');
						$('#homeFlashBanner div.tl').css({
							'position': 'absolute',
							'top' : '0',
							'left' : '0',
							'width' : '9px', 
							'height' : '9px',
							'background' : 'url(/static-images/title-cr-tl.png) no-repeat 0 0'
						});
						if(typeof isIEVersion !== 'undefined' && isIEVersion == 6) {
							$('#homeFlashBanner div.tl').css('background', 'url(/static-images/title-cr-tl.gif) no-repeat 0 0');
						}
						
					} else { obj.defaultOutput(); }
				}
			}		
		},
		
		defaultOutput: function() {
			var flashvars = {}, params = { wmode:"transparent" }, attributes = {};
			swfobject.embedSWF("/static-flash/house3.swf", "homeFlashBanner", "700", "370", "9.0.0", false, flashvars, params, attributes);	
		}
	}

/* end of behavioural tracking code */

