
var basePath = $$('link')[0].href;
basePath = basePath.split('css')[0];
var flashPath = basePath + 'flash/';

document.write('<style type="text/css">');
document.write(".popuplink { visibility: hidden; }");
document.write("#bodyMedia { overflow: hidden; }");
document.write("#bodyCopyShorter { overflow: hidden; }");
document.write("#bodyCopyvac { overflow: hidden; }");
document.write("#mediaText { width: 360px; overflow: hidden; }");
document.write(".scrollBars { display: inline; }");
document.write("#mediaContainer .scrollBars { display: block; }");
document.write("#countries { visibility: hidden; }");
document.write('</style>');

/*
* Orginal: http://adomas.org/javascript-mouse-wheel/
* prototype extension by "Frank Monnerjahn" themonnie @gmail.com
*/
Object.extend(Event, {
	wheel:function (event){
		var delta = 0;
		if (!event) event = window.event;
		if (event.wheelDelta) {
			delta = event.wheelDelta/120;
			if (window.opera) delta = -delta;
		}
		else if (event.detail) {
			delta = -event.detail/3;
		}
		return Math.round(delta); //Safari Round
    }
});

window.onresize = function () { Popup.resized() };

Event.observe(window, 'load', function() {
	//Google Analytics
	if (typeof pageTracker != 'undefined') {
		var productExtraLinks = $$('#prodButtons li a');
		for (var i = 0; i < productExtraLinks.length; i++) {
			productExtraLinks[i].observe('click', function() {
				pageTracker._trackPageview(this.href);
			});
		}
	}
});

//function init() {
Event.domReady.add(function() {
	var date = new Date().format('j F Y');
	var time = new Date().format('h:ia');
	$$('.insertDate').each(function(foo, e) {
		$(e).innerHTML = date + ' | <span class="whitecopy">' + time + '</span>';
	}.bind(date, time));

	ContentScroll.init();
	//new PopupScroll('popupscroller', 'scrollHandle', 'scrollTrack', 'scrollUp', 'scrollDown');
	TypeWriter.init();
	SubMenu.init();
	new Accordion({
		toggleActiveClassName: 'active'
	});
	var e = $('countries');
	if (e) {
		e.style.visibility = 'visible';
	}

	var agent = navigator.userAgent.toLowerCase();
	if (eregi('msie', agent) && !eregi('opera', agent)) {
		var val = explode(' ', stristr(agent,'msie'));
		var browser = val[0];
		var version = val[1];
		// clean up extraneous garbage that may be in the name
		browser = browser.replace(/[^a-z,A-Z]+/g, '');
		// clean up extraneous garbage that may be in the version
		version = version.replace(/[^0-9,\.,a-z,A-Z]+/g, '');
		if (version < 7) {
			replacePngs();
		}
	}

	var as = document.getElementsByTagName('a');
	for (var i = 0; i < as.length; i++) {
		if (/\bpopuplink\b/.test(as[i].className)) {
			as[i].onclick = function () {
				var q = this.href.match(/\?(.*)/);
				var loc = this.href.substring(0, this.href.lastIndexOf('/') + 1);
				if (q) {
					//Popup.load('extra/' + q[1] + '.xml');
					window.scrollTo(0,0);
					Popup.load(loc + q[1] + '.xml');
				}
				return false;
			}
			as[i].style.visibility = 'visible';
		}
	}

	var overlay = document.getElementById('op');
	if (overlay) {
		var sizes = Popup.getSizes();
		overlay.style.height = sizes.page.height + 'px';
		if (/msie/gi.test(navigator.userAgent.toLowerCase())) {
			overlay.style.background = 'none';
			overlay.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\', src=\'overlay.png\')';
			overlay.style.width = sizes.page.width + 'px';
		}
	}
	//tooltips
	new Tooltip();
});

function replacePngs() {
	var imgs = document.getElementsByTagName('img');
	var pngs = new Array();
	for (var i = 0; i < imgs.length; i++) {
		if (/\.png$/i.test(imgs[i].src)) {
			var o = imgs[i];
			var p = imgs[i].parentNode;
			p.style.width = o.offsetWidth + 'px';
			p.style.height = o.offsetHeight + 'px';
			p.style.display = 'block';
			//o.style.display = 'none';
			o.style.visibility = 'hidden';
			//o.style.styleFloat = 'left';
			p.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'crop\', src=\'' + imgs[i].src + '\')';
			if (p.nodeName == 'A') {
				p.style.cursor = 'pointer';
			}
			//trace(imgs[i].src);
		}
	}
}


TypeWriter = {
	date:	'typedate',
	news:	'typenews',
	items:	[],
	curItem: 0,
	curChar: 0,
	timing:	50,
	timer:	null,
	holdtime: 3000,
	init:	function () {
		TypeWriter.date = document.getElementById(TypeWriter.date);
		TypeWriter.news = document.getElementById(TypeWriter.news);
		if (!TypeWriter.date || !TypeWriter.news) {
			return;
		}
		if (tickerItems) {
			TypeWriter.items = tickerItems;
			TypeWriter.write();
		}
	},
	pause:	function () {
		clearTimeout(TypeWriter.timer);
	},
	play:	function () {
		TypeWriter.timer = setTimeout('TypeWriter.write()', TypeWriter.timing);
	},
	write:	function () {
		if (TypeWriter.curChar > TypeWriter.items[TypeWriter.curItem].news.length) {
			TypeWriter.curChar = 0;
			TypeWriter.curItem++;
			if (TypeWriter.curItem >= TypeWriter.items.length) {
				TypeWriter.curItem = 0;
			}
		}
		if (TypeWriter.curChar == 0) {
			document.getElementById('prefooter').onclick = function () {
				var path = (window.location.href.indexOf('/html/') != -1) ? '../' : '';
				var path = '';
				//path += 'extra/' + TypeWriter.items[TypeWriter.curItem].link + '.xml';
				path += TypeWriter.items[TypeWriter.curItem].extraFolder + TypeWriter.items[TypeWriter.curItem].link + '.xml';
				Popup.load(path);
			}
			TypeWriter.date.innerHTML = TypeWriter.items[TypeWriter.curItem].date.toUpperCase();
		}
		TypeWriter.news.innerHTML = TypeWriter.items[TypeWriter.curItem].news.substr(0, TypeWriter.curChar++).toUpperCase();
		if (TypeWriter.curChar > TypeWriter.items[TypeWriter.curItem].news.length) {
			TypeWriter.timer = setTimeout('TypeWriter.write()', TypeWriter.holdtime);
		}
		else {
			TypeWriter.timer = setTimeout('TypeWriter.write()', TypeWriter.timing);
		}
	}
}

PopupScroll = Class.create({
	slider: null,
	pe: null,
	options: {
		axis: 'vertical',
		onSlide: null,
		onChange: null,
		scrollValue: 0.1
	},
	initialize: function(target, handle, track, scrollUp, scrollDown, options) {
		this.target = $(target);
		if (!this.target || !$(handle) || !$(track)) return;

		//work out slider height
		var targetHeight = parseInt(this.target.getStyle('height'));
		var parentHeight = parseInt($(this.target.parentNode).getStyle('height')) - 20; //-20 is an extra margin at the bottom

		if (targetHeight <= parentHeight) return;

		var handleHeight = (targetHeight > parentHeight) ? Math.round(parentHeight / targetHeight * 100) : 100;
		$(handle).setStyle({
			height: handleHeight + '%'
		});

		options = Object.extend(this.options, options || {});
		options.onSlide = this.scroll.bind(this);
		options.onChange = this.scroll.bind(this);
		this.slider = new Control.Slider(handle, track, this.options);

		if ($(scrollUp)) {
			$(scrollUp).observe('mousedown', function() {
				this.up();
				this.pe = new PeriodicalExecuter(function() {
					this.up();
				}.bind(this), 0.1);
			}.bindAsEventListener(this));
			$(scrollUp).observe('mouseup', function() {
				if (this.pe) {
					this.pe.stop();
					this.pe = null;
				}
			}.bindAsEventListener(this));
		}
		if ($(scrollDown)) {
			$(scrollDown).observe('mousedown', function() {
				this.down();
				this.pe = new PeriodicalExecuter(function() {
					this.down();
				}.bind(this), 0.1);
			}.bindAsEventListener(this));
			$(scrollDown).observe('mouseup', function() {
				if (this.pe) {
					this.pe.stop();
					this.pe = null;
				}
			}.bindAsEventListener(this));
		}

		Event.observe(this.target, "mousewheel", function(evt) {
			evt.stop();
			if ((Event.wheel(evt) < 0 && !Prototype.Browser.Opera) || (Prototype.Browser.Opera && Event.wheel(evt) > 0)) this.down();
			else this.up();
		}.bindAsEventListener(this));
		Event.observe(this.target, "DOMMouseScroll", function(evt) { //gecko
			evt.stop();
			if (Event.wheel(evt) < 0) this.down();
			else this.up();
		}.bindAsEventListener(this));
	},
	up: function() {
		this.slider.setValueBy(-this.options.scrollValue);
	},
	down: function() {
		this.slider.setValueBy(this.options.scrollValue);
	},
	scroll: function(value) {
		var parentHeight = parseInt($(this.target.parentNode).getStyle('height')) - 20;
		var location = Math.ceil((this.target.getHeight() - parentHeight) * (- value));
		this.target.setStyle({
			marginTop: location + 'px'
		});
	}
});


ContentScroll = {
	duration:	15,
	steps:		15,
	obj:		null,
	baseH:		0,
	smallH:		0,
	scrollers:	null,
	scrolling:	false,
	contHeight: 0,
	init:		function () {
		/*
		var divs = document.getElementsByTagName('div');
		var c1 = 'leftContent';
		for (var i = 0; i < divs.length; i++) {
			if (new RegExp('\\b' + c1 + '\\b').test(divs[i].className)) {
				ContentScroll.obj = divs[i];
				i = divs.length;
			}
		}
		if (!ContentScroll.obj) {
			return;
		}
		*/
		/*
		ContentScroll.obj = $('bodyCopyShorter');
		if (!ContentScroll.obj) {
			return;
		}
		*/

		var o = document.getElementById('scroller');
		if (o) {
			ContentScroll.obj = o.parentNode;
		}
		if (!ContentScroll.obj || !ContentScroll.obj.nodeName == 'DIV') {
			return;
		}

		ContentScroll.baseH = ContentScroll.obj.offsetHeight;
		//ContentScroll.smallH  = ContentScroll.baseH - 18;
		ContentScroll.smallH  = ContentScroll.baseH;
		ContentScroll.resize();
	},
	resize:		function () {
		// get the height of the content
		var h = 0;
		var d = ContentScroll.obj;
		for (i = 0; i < d.childNodes.length; i++) {
			var j = d.childNodes[i].offsetHeight;
			if (!isNaN(j)) {
				h += j;
			}
		}
		ContentScroll.contHeight = h;
	},
	up:			function () {
		if (ContentScroll.scrolling) {
			return false;
		}
		var o = ContentScroll.obj;
		var current = o.scrollTop;
		var target = current - ContentScroll.smallH + 20; // give 20 pixels grace
		if (target < 0) {
			target = 0;
		}
		ContentScroll.slide(target);
		return false;
	},
	down:		function () {
		if (ContentScroll.scrolling) {
			return false;
		}
		var o = ContentScroll.obj;
		var current = o.scrollTop;
		var target = current + ContentScroll.smallH - 20; // give 20 pixels grace
		var maxScrollHeight = ContentScroll.contHeight - ContentScroll.smallH;
		if (target > maxScrollHeight) {
			target = maxScrollHeight;
		}
		ContentScroll.slide(target);
		return false;
	},
	slide:		function (target) {
		ContentScroll.scrolling = true;
		var current = ContentScroll.obj.scrollTop;
		if (target < current) {
			var increment = Math.round((target - current - ContentScroll.steps) / ContentScroll.steps);
			if (increment == 0) {
				increment = -1;
			}
			var location = current + increment;
		}
		else if (target > current) {
			var increment = Math.round((target - current) / ContentScroll.steps);
			if (increment == 0) {
				increment = 1;
			}
			var location = current + increment;
		}
		else if (target == current) {
			ContentScroll.scrolling = false;
			return;
		}
		ContentScroll.obj.scrollTop = location;
		setTimeout('ContentScroll.slide(' + target + ')', ContentScroll.duration);
	}
}

Popup = {
	overlay: 'overlay',
	outerCont: 'popouter',
	innerCont: 'popinner',
	intrans:	false,
	duration: 1.0,
	created: false,
	content:	null,
	overlayOpacity: 0.8, // percent opaque
	create:	function () {
		var overlay = document.createElement('div');
		overlay.setAttribute('id', Popup.overlay);
		overlay.onclick = function (event) {
			Popup.hide();
		}
		var outer = document.createElement('div');
		outer.setAttribute('id', Popup.outerCont);
		outer.onclick = function (event) {
			Popup.hide();
		}
		var inner = document.createElement('div');
		inner.setAttribute('id', Popup.innerCont);
		inner.onclick = function (event) {
			Popup.cancelBubble(event);
		}

		var sizes = Popup.getSizes();
		overlay.style.height = sizes.page.height + 'px';
		if (/msie/gi.test(navigator.userAgent.toLowerCase())) {
			overlay.style.width = sizes.page.width + 'px';
			/*
			overlay.style.background = 'none';
			var path = '';
			if (window.location.href.indexOf('/recruitment/') != -1) {
				path += (window.location.href.indexOf('/html/') != -1) ? '../' : '../../';
			}
			overlay.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\', src=\'' + path  +'images/overlay.png\')';
			overlay.style.width = sizes.page.width + 'px';
			*/
		}

		outer.appendChild(inner);

		overlay.style.display = 'none';
		outer.style.display = 'none';
		document.getElementsByTagName('body')[0].appendChild(overlay);
		document.getElementsByTagName('body')[0].appendChild(outer);

		Popup.overlay = document.getElementById(Popup.overlay);
		Popup.outerCont = document.getElementById(Popup.outerCont);
		Popup.innerCont = document.getElementById(Popup.innerCont);

		Popup.created = true;
	},
	show:	function (oXML) {
		if (!Popup.created) {
			Popup.create();
		}
		var str = oXML.responseText;
		var path = (window.location.href.indexOf('/html/') != -1) ? '../' : '';
		str = str.replace(/"images\//, '"' + path + 'images/');
		str = str.replace(/"uploads\//, '"' + path + 'uploads/');
		str = str.replace(/"..\/images\//, '"' + path + 'images/');
		str = str.replace(/"..\/uploads\//, '"' + path + 'uploads/');
		Popup.innerCont.innerHTML = str;

		if (document.getElementById('popclose')) {
			var a = document.createElement('a');
			a.href = '#';
			a.onclick = function () {
				Popup.hide();
				return false;
			}
			document.getElementById('popclose').appendChild(a);
		}

		if ($('FLVvid')) {
			$('FLVvid').style.display = 'none';
		}
		if ($('flvLink')) {
			var videoParams = $('flvLink').href.split('?');
			var video = videoParams[0];
			var videoParams = videoParams[1].split('&');
			var videoWidth = videoParams[0].replace(/w=/, '') + 'px';
			var videoHeight = videoParams[1].replace(/h=/, '') + 'px';
			$('popinner').style.width = (parseInt(videoWidth) + 40 + 10 + 40 + 10) + 'px';
			$('flvContainer').style.width = videoWidth;
			$('flvContainer').style.height = videoHeight;
			$('FLVText').style.width = videoWidth;
			$('FLVText').style.height = videoHeight;
			(function() {
//				swfobject.embedSWF(flashPath  + 'flv_player.swf', 'FLVvid', '600px', '366px', '9', + flashPath + 'swfobject-2.1/expressInstall.swf', {flvFile: video});
				swfobject.embedSWF(flashPath  + 'player-licensed.swf', 'FLVvid', videoWidth, videoHeight, '9', + flashPath + 'swfobject-2.1/expressInstall.swf', {file: video, autostart: 'true', skin: flashPath + 'Modieus_Slim/stylish_slim.swf'});
				$('FLVvid').style.width = videoWidth;
				$('FLVvid').style.height = videoHeight;
			}).delay(Popup.duration);
			$('popinner').addClassName('flash');
			
			var closeLink = $$('#popclose a');
			if (closeLink) {
				closeLink = closeLink[0];
				if (/MSIE\s6/.test(navigator.userAgent)) {
					var regex = /url\(['"](.*)['"]\)/;
					var matches = regex.exec(closeLink.getStyle('backgroundImage'));
					if (matches) {
						var filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="resize", src="' + matches[1] + '")';
						closeLink.setStyle({
							background: 'none',
							filter: filter,
							cursor: 'hand'
						});
					}
				}
			}
		}
		else {
			$('popinner').removeClassName('flash');
			$('popinner').style.width = '500px';
		}

		//Popup.overlay.style.visibility = 'hidden';
//		Popup.outerCont.style.visibility = 'hidden';
		Popup.overlay.style.display = 'block';
		Popup.outerCont.style.display = 'block';
//		PopupScroll.init();
		new PopupScroll('popupscroller', 'scrollHandle', 'scrollTrack', 'scrollUp', 'scrollDown');

		Popup.intrans = true;
		TypeWriter.pause();
		$(Popup.overlay).appear({from: 0.0, to: Popup.overlayOpacity, duration: Popup.duration});
//		var e1 = new Effect.Appear(Popup.overlay, {from: 0.0, to: Popup.overlayOpacity, duration: Popup.duration});
		//var e2 = new Effect.AppearGrow(Popup.innerCont, {duration: Popup.duration});
		var e2 = new Effect.AppearGrow(($('flvContainer') || $('mediaContainer')), {duration: Popup.duration});
		Popup.startTrans();

		//forms
		Popup.setForms();
	},
	hide:		function () {
		/*
		Popup.overlay.style.display = 'none';
		Popup.outerCont.style.display = 'none';
		*/
		if (Popup.intrans) {
			return;
		}

		if ($('FLVvid')) {
			$('FLVvid').style.display = 'none';
			(function() {$('popinner').removeClassName('flash')}).delay(Popup.duration);
		}

		var e1 = new Effect.Fade(Popup.overlay, {from: Popup.overlayOpacity, to: 0.0, duration: Popup.duration});
		var e2 = new Effect.FadeShrink(($('flvContainer') || $('mediaContainer')),{duration: Popup.duration});
		setTimeout('Popup.delContent()', Popup.duration * 1000);
		Popup.startTrans();
		TypeWriter.play();
		return false;
	},
	delContent:	function () {
		Popup.innerCont.innerHTML = '';
	},
	stopTrans:	function () {
		Popup.intrans = false;

		if ($('FLVvid')) {
			$('FLVvid').style.display = 'block';
		}
	},
	startTrans: function () {
		Popup.intrans = true;
		setTimeout('Popup.stopTrans()', Popup.duration * 1000);
	},
	load:	function (href) {
	    var con = Popup.xhcon();
	    if (!con) {
			return;
		}
		con.connect(href, 'GET', Math.random(), Popup.show);
	},
	resized:	function () {
		if (Popup.created && /msie/gi.test(navigator.userAgent.toLowerCase())) {
			var sizes = Popup.getSizes();
			overlay.style.height = sizes.page.height + 'px';
			overlay.style.width = sizes.page.width + 'px';
		}
	},
	getSizes: function () {
		var xScroll, yScroll;

		if (window.innerHeight && window.scrollMaxY) {
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		}
		else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		}
		else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		}
		else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		}
		else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}

		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		}
		else {
			pageHeight = yScroll;
		}

		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){
			pageWidth = windowWidth;
		}
		else {
			pageWidth = xScroll;
		}


		return { page: {width: pageWidth, height: pageHeight}, window: {width: windowWidth, height: windowHeight }};
	},
	getDimensions: function(element) {
		if (!element) {
			return false;
		}
		if (element.style.display != 'none') {
			return {width: element.offsetWidth, height: element.offsetHeight};
		}

		// All *Width and *Height properties give 0 on elements with display none,
		// so enable the element temporarily
		var els = element.style;
		var originalVisibility = els.visibility;
		var originalPosition = els.position;
		els.visibility = 'hidden';
		els.position = 'absolute';
		els.display = '';
		var originalWidth = element.clientWidth;
		var originalHeight = element.clientHeight;
		els.display = 'none';
		els.position = originalPosition;
		els.visibility = originalVisibility;
		return {width: originalWidth, height: originalHeight};
	},
	cloneNode:	function (oldNode, deep) {
		deep = (deep) ? true : false;
		// a replacement to the normal dom clone node
		// this will copy xml nodes to html nodes
		// which can then be inserted into the document
		// scope in all browsers
		// See for for the bug http://www.quirksmode.org/blog/archives/2005/12/xmlhttp_notes_c.html
		var newNode = null;
		if (oldNode.nodeType == '3') {
			// textnode
			newNode = $t(oldNode.nodeValue);
		}
		else if (oldNode.nodeType == '1') {
			// element node
			newNode = document.createElement(oldNode.nodeName);
			if (deep) {
				for (var i = 0; i < oldNode.childNodes.length; i++) {
					newNode.appendChild(Jargon.cloneNode(oldNode.childNodes[i], true));
				}
			}
		}
		return newNode;
	},
	cancelBubble:	function (eObj) {
		if (!eObj) var eObj = window.event;
		if (!eObj) return;
		eObj.cancelBubble = true;
		if (eObj.stopPropagation) {
			eObj.stopPropagation();
		}
	},
	setForms:	function () {
		var inputsWithCharsLimit = $$('.charLimited');
		var charactersLimit = null;
		if (inputsWithCharsLimit.length > 0) {
			var charactersLimit = new CharactersLimit(inputsWithCharsLimit[0], $('charsRemaining'), 250);
		};
		if ($('frmGuideRequest')) {
			$('frmGuideRequest').observe('submit', function(evt) {
				evt.stop();
				var res = checkForm(evt, ['fldName', 'fldCompany', 'fldAddress', 'fldPostCode', 'fldCountry', 'fldEmail', 'fldPhone']);
				if (res) {
					this.request({
						parameters: {ajax: 1},
						onComplete: function(resp) {
							formComplete($('popupscroller'), resp, 'Thank you for your request, you should receive your mini guide within 5 working days.')
						}
					});
				}
			});
		}
		if ($('frmProductEnquiry')) {
			//get product name
			if ($('prodName')) {
				var prodName = $('prodName').innerHTML;
				//set product name
				var el = $$('#' + Popup.innerCont.getAttribute('id') + ' .prodName');
				if (el.length > 0) {
					el[0].innerHTML = prodName;
				}
				if ($('fldProdName')) {
					$('fldProdName').value = prodName;
				}
			}

			$('frmProductEnquiry').observe('submit', function(evt) {
				evt.stop();
				var res = true;
				if (!charactersLimit.checkLength(evt)) {
					alert('Sorry, you have reached the maximum number of characters (' + charactersLimit.limit + '). Your comments must be shorter.');
					res = false;
				}
				res *= checkForm(evt, ['fldName', 'fldCompany', 'fldAddress', 'fldCity', 'fldPostCode', 'fldCountry', 'fldEmail', 'fldPhone', 'fldComments']);
				if (res) {
					this.request({
						parameters: {ajax: 1},
						onComplete: function(resp) {
							formComplete($('popupscroller'), resp, 'Thank you for your enquiry, someone from out Sales Department will contact you within 5 working days.')
						}
					});
				}
			}.bindAsEventListener($('frmProductEnquiry'), charactersLimit));
		}
		if ($('frmEnquiry')) {
			$('frmEnquiry').observe('submit', function(evt) {
				evt.stop();
				var res = true;
				if (!charactersLimit.checkLength(evt)) {
					alert('Sorry, you have reached the maximum number of characters (' + charactersLimit.limit + '). Your comments must be shorter.');
					res = false;
				}
				res *= checkForm(evt, [{name: 'Enquire about', fields: ['fldWaterDosing', 'fldMixing', 'fldDoughHandling', 'fldProving', 'fldOvens', 'fldFrying', 'fldSlicing', 'fldConfectionery', 'fldRefrigeration', 'fldOther']}, 'fldName', 'fldCompany', 'fldAddress', 'fldCity', 'fldPostCode', 'fldCountry', 'fldEmail', 'fldPhone', 'fldComments']);
				if (res) {
					this.request({
						parameters: {ajax: 1},
						onComplete: function(resp) {
							formComplete($('popupscroller'), resp, 'Thank you for your enquiry, we will contact you within 5 working days.')
						}
					});
				}
			}.bindAsEventListener($('frmEnquiry'), charactersLimit));
		}

		//enable reset buttons
		if ($('btnReset')) {
			$('btnReset').observe('click', function(evt) {
				//get parent forms
				var parent = evt.element();
				do {
					parent = parent.parentNode;
				}
				while (parent.tagName.toLowerCase() != 'form' && parent.tagName.toLowerCase() != 'html');
				if (parent.tagName.toLowerCase() == 'form') {
					parent.reset();
					charactersLimit.checkLength(evt);
				}
			}.bindAsEventListener(charactersLimit));
		}
	},
	xhcon:		function () {
		var xmlhttp, bComplete = false;
		try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
		catch (e) { try { xmlhttp = new XMLHttpRequest(); }
		catch (e) { xmlhttp = false; }}}
		if (!xmlhttp) {
			return null;
		}
		this.connect = function(sURL, sMethod, sVars, fnDone) {
			if (!xmlhttp) {
				return false;
			}
			bComplete = false;
			sMethod = sMethod.toUpperCase();

			try {
				if (sMethod == "GET") {
					xmlhttp.open(sMethod, sURL+"?"+sVars, true);
					sVars = "";
				}
				else {
					xmlhttp.open(sMethod, sURL, true);
					xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
					xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				}
				xmlhttp.onreadystatechange = function() {
					if (xmlhttp.readyState == 4 && !bComplete) {
						bComplete = true;
						fnDone(xmlhttp);
					}
				};
				xmlhttp.send(sVars);
			}
			catch(z) { return false; }
			return true;
		};
		return this;
	}
}



/*
function $(element) {
	if (typeof element == 'string' && element.length > 0) {
		element = document.getElementById(element);
	}
	return element;
}
*/
function eregi(pattern, string) {
    var reg = new RegExp(pattern, ['gi']);
    return reg.test(string);
}
function stristr(haystack, needle) {
    var reg = new RegExp(needle, ['gi']);
    var pos = haystack.search(reg);
    if (pos == -2) {
        return false;
    }
    return haystack.substring(pos,haystack.length);
}
function explode(separator, str) {
    var reg = new RegExp(separator, ['gi']);
    return str.split(reg);
}


/************************************************
*                                               *
*            Date object                        *
*                                               *
************************************************/

// format is used in a similar way to http://uk.php.net/date
// restricted chars must be escaped with a '\', however in javascript
// when writing the string the '\' itself must be escaped
// E.g. var str = new Date().format('\\Year: Y');  -> Year: 2005
//      var str = new Date().format('\Year: Y');   -> 2005ear: 2005
// note only the 1 '\' in the second example
Date.prototype.format = function (str) {
  this.procProps();
  var pos = 0;
  var buff = '';
  var esc = false;
  while (pos < str.length) {
    var c = str.charAt(pos);
    if (c == '\\' && !esc) {
      esc = true;
    }
    else if (this.isReservedChar(c) && !esc) {
      buff += eval('this.' + c);
    }
    else {
      buff += c;
      esc = false;
    }
    pos++;
  }
  return buff;
}
Date.prototype.isReservedChar = function (c) {
  for (var i = 0; i < this.reservedChars.length; i++) {
    if (this.reservedChars[i] == c) {
      return true;
    }
  }
  return false;
}
Date.prototype.strPad = function (strIn, padLength) {
  var strPad = '0';
  var strIn = new String(strIn);
  var j = strIn.length;
  for (var i = j; i < padLength; i++) {
    strIn = strPad + strIn;
  }
  return strIn;
}
Date.prototype.procProps = function () {
  // see http://uk.php.net/date for a list of the properties
  // D - A textual representation of a day, three letters (Sun through Sat)
  // l (lowercase 'L') - A full textual representation of the day of the week (Sunday through Saturday)
  // d - Day of the month, 2 digits with leading zeros (01 to 31)
  // j - Day of the month without leading zeros (1 to 31)
  // F - A full textual representation of a month, such as January or March (January through December)
  // m - Numeric representation of a month, with leading zeros (01 through 12)
  // M - A short textual representation of a month, three letters (	Jan through Dec)
  // Y - A full numeric representation of a year, 4 digits (Examples: 1999 or 2003)
  // y - A two digit representation of a year (Examples: 99 or 03)
  // H - 24-hour format of an hour with leading zeros (00 through 23)
  // i - Minutes with leading zeros (00 to 59)
  // s - Seconds, with leading zeros (00 through 59)
  // S - English ordinal suffix for the day of the month, 2 characters (st, nd, rd & th)
  this.reservedChars = ['D', 'l', 'd', 'j', 'F', 'm', 'M', 'Y', 'y', 'a', 'A', 'h', 'H', 'i', 's', 'S'];
  if (isNaN(this.getDate()) || isNaN(this.getMonth()) || isNaN(this.getFullYear())) {
    this.setFullYear(1900, 0, 1);
  }
  var shortDays = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
  var longDays = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
  var monthNames = new Array ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
  var shortMonthNames = new Array ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
  this.D = shortDays[this.getDay()];
  this.l = longDays[this.getDay()];
  this.d = this.strPad(this.getDate(), 2);
  this.j = this.getDate();
  this.F = monthNames[this.getMonth()];
  this.m = this.strPad(this.getMonth() + 1, 2);
  this.M = shortMonthNames[this.getMonth()];
  this.Y = this.getFullYear();
  this.y = (this.getYear() > 100) ? this.strPad(this.getYear() - 100, 2) : this.strPad(this.getYear(), 2);
  this.a = (this.getHours() >= 12) ? 'pm' : 'am';
  this.A = (this.getHours() >= 12) ? 'PM' : 'AM';
  this.i = this.strPad(this.getMinutes(), 2);
  this.h = (this.getHours() > 12) ? (this.getHours() - 12) : this.getHours();
  this.H = this.strPad(this.getHours(), 2);
  this.s = this.strPad(this.getSeconds(), 2);
  switch (this.getDate()) {
    case 1:
      this.S = 'st';
      break;
    case 2:
      this.S = 'nd';
      break;
    case 3:
      this.S = 'rd';
      break;
    case 21:
      this.S = 'st';
      break;
    case 22:
      this.S = 'nd';
      break;
    case 23:
      this.S = 'rd';
      break;
    case 31:
      this.S = 'st';
      break;
    default:
      this.S = 'th';
      break;
  }
}




Effect.AppearGrow = function(element) {
	element = $(element);
	element.style.display = 'block';
	element.style.visibility = 'hidden';

	var options = Object.extend({
		direction: 'center',
		moveTransition: Effect.Transitions.sinoidal,
		scaleTransition: Effect.Transitions.sinoidal,
		opacityTransition: Effect.Transitions.full
	}, arguments[1] || {});

	var dims = element.getDimensions();

	var oldStyle = {
		top: element.style.top,
		left: element.style.left,
		height: dims.height + 'px',
		width: dims.width + 'px',
		//height: element.style.height,
		//width: element.style.width,
		opacity: element.getInlineOpacity() };

	//var dims = element.getDimensions();
	var initialMoveX = dims.width / 2;
	var initialMoveY = dims.height / 2;
	var moveX = -dims.width / 2;
	var moveY = -dims.height / 2;

	var appearOptions = Object.extend({
		sync: true,
		from: 0.0,
		to: 1.0,
		// force Safari to render floated elements properly
		afterFinishInternal: function(effect) {
			effect.element.forceRerendering();
		},
		beforeSetup: function(effect) {
			effect.element.setOpacity(effect.options.from);
			effect.element.show();
		}
	}, arguments[1] || {});

	return new Effect.Move(element, {
		x: initialMoveX,
		y: initialMoveY,
		duration: 0.01,
		beforeSetup: function(effect) {
			effect.element.hide();
			effect.element.makeClipping();
			effect.element.makePositioned();
			effect.element.setOpacity(0.0);
		},
		afterFinishInternal: function(effect) {
			new Effect.Parallel(
				[
					new Effect.Opacity(element, appearOptions),
					//new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
					new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
					new Effect.Scale(effect.element, 100, {
						scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
						sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
				], Object.extend({
						 beforeSetup: function(effect) {
							effect.effects[0].element.setStyle({height: '0px', width: '0px'});
							effect.effects[0].element.show();
							element.style.display = 'block';
							element.style.visibility = 'visible';
						 },
						 afterFinishInternal: function(effect) {
							effect.effects[0].element.undoClipping();
							effect.effects[0].element.undoPositioned();
							effect.effects[0].element.setStyle(oldStyle);
						 }
					 }, options)
			)
		}
	});
}



Effect.FadeShrink = function(element) {
	element = $(element);
	var options = Object.extend({
		direction: 'center',
		moveTransition: Effect.Transitions.sinoidal,
		scaleTransition: Effect.Transitions.sinoidal,
		opacityTransition: Effect.Transitions.none
	}, arguments[1] || {});
	var oldStyle = {
	top: element.style.top,
	left: element.style.left,
	height: element.style.height,
	width: element.style.width,
	opacity: element.getInlineOpacity() };

	var dims = element.getDimensions();
	var moveX = dims.width / 2;
	var moveY = dims.height / 2;

	var fadeOptions = Object.extend({
		sync: true,
		from: 1.0,
		to: 0.0,
		// force Safari to render floated elements properly
		afterFinishInternal: function(effect) {
			effect.element.forceRerendering();
		},
		beforeSetup: function(effect) {
			effect.element.setOpacity(effect.options.from);
			effect.element.show();
		}
	}, arguments[1] || {});

	return new Effect.Parallel(
		[
			new Effect.Opacity(element, fadeOptions),
			//new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
			new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
			new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
		], Object.extend({
				beforeStartInternal: function(effect) {
					effect.effects[0].element.makePositioned();
					effect.effects[0].element.makeClipping();
				},
				afterFinishInternal: function(effect) {
					effect.effects[0].element.hide();
					effect.effects[0].element.undoClipping();
					effect.effects[0].element.undoPositioned();
					effect.effects[0].element.setStyle(oldStyle);
				}
			 }, options)
	);
}

SubMenu = {
	hovering: false,
	currentActiveLis: new Hash,
	init: function () {
		if (!$('menu')) return;

		var submenus = $$('#menu .submenu');

		SubMenu.shadows = ['ne', 'ee', 'se', 'ss', 'sw'];
		SubMenu.submenus = submenus;
		var uls = $('menu').getElementsByTagName('ul');
		SubMenu.menu = uls[0];

		SubMenu.isIE6 = /MSIE\s6/.test(navigator.userAgent);
		SubMenu.isIE = /MSIE/.test(navigator.userAgent);

		//set the hover of the menu so that it stays higlighted when hovering the submenus
//		SubMenu.setMenuHiliting();

		// set the menu to be in position but hidden so that the sizes will be calculated correctly
		SubMenu.submenus.each(function (submenu) {
			submenu.setStyle({
				visibility: 'hidden',
				display: 'block'
			})
		});

		// do the setup required for all browsers
//		SubMenu.submenus.each(function (submenu) {
//			var topLink = submenu.getElementsByTagName('a');
//			if (topLink.length > 0) {
//				topLink[0].addClassName('top');
//			}
//			var s = {};
//
//			// increase the width of the submenu by 1
//			// to make the right edge line up with the
//			// right edge of the menu above
//			var size = submenu.getSize().size;
//			submenu.setStyles({
//			//	width: size.x + 1 - 8
//			});
//
//			SubMenu.shadows.each(function (shadow) {
//				var e = $(document.createElement('div'));
//				e.addClass(shadow.toString());
//				submenu.appendChild(e);
//				e.size = e.getSize().size;
//				s[shadow] = e;
//			});
//
//			var size = submenu.getSize().size;
//			var offset = {x: 3, y: 4};
//			var offset = {x: 0, y: 0};
//
//			s.ee.setStyles({
//				height: size.y - s.ne.size.y -  s.se.size.y - offset.y
//			})
//			s.ss.setStyles({
//				width: size.x - s.sw.size.x - s.se.size.x - offset.x
//			})
//		}, this);

		if (SubMenu.isIE) {
			SubMenu.prepForIE();
		}
//		if (SubMenu.isIE6) {
			SubMenu.prepForIE6();
//		}

		// hide the menu again
		SubMenu.submenus.each(function (submenu) {
			submenu.setStyle({
				display: '',
				visibility: ''
			})
		});
	},
	prepForIE: function () {
		SubMenu.prepForIE6();
//		SubMenu.submenus.each(function (submenu) {
//			var paddings = $E('a', submenu).getStyles('paddingLeft', 'paddingRight');
//			var width = 0;
//			var links = submenu.getElements('a')
//			links.each(function (e) {
//				width = e.offsetWidth > width ? e.offsetWidth : width;
//			});
//			width = width - parseInt(paddings.paddingLeft) - parseInt(paddings.paddingRight);
//			links.each(function (e) {
//				e.setStyle('width', width);
//			});
//		});
	},
	prepForIE6: function () {
//		$$('#menu li').each(function (e) {
		var lis = ['nb1', 'nb2', 'nb3', 'nb4', 'nb5', 'nb6', 'nb7'];
		lis.each(function (e) {
			e = $(e);
//			e.addEvent('mouseenter', function () {e.addClass('hover')});
//			e.addEvent('mouseleave', function () {e.removeClass('hover')});
			SubMenu.currentActiveLis.set(e.getAttribute('id'), false);
			e.observe('mouseover', function () {
				if (!SubMenu.currentActiveLis.get(e.getAttribute('id'))) {
					e.addClassName('hover');
					SubMenu.currentActiveLis.set(e.getAttribute('id'), true);
				}
			});
			e.observe('mouseout', function () {
				SubMenu.currentActiveLis.set(e.getAttribute('id'), false);
				function removeHoverClass() {
					if (!SubMenu.currentActiveLis.get(e.getAttribute('id'))) {
						e.removeClassName('hover');
					}
				}
				removeHoverClass.delay(0.05);
			}.bind(SubMenu));
		});

//		var regex = /url\(['"](.*)['"]\)/;
//		SubMenu.submenus.each(function (submenu) {
//			var p = submenu.getParent();
//
//			var size = submenu.getSize().size;
//			//p.addEvent('mouseenter', function () {submenu.setStyles({display: 'block'})});
//			//p.addEvent('mouseleave', function () {submenu.setStyles({display: ''})});
//
//			SubMenu.shadows.each(function (shadow) {
//				var e = $E('.' + shadow, submenu);
//				if (shadow.substr(0, 1) == 's') {
//					e.setStyles({
//						bottom: 'auto',
//						top: size.y - e.getSize().size.y - parseInt(e.getStyle('bottom'))
//					})
//				}
//				if (shadow.substr(1, 1) == 'e') {
//					e.setStyles({
//						right: 'auto',
//						left: size.x - e.getSize().size.x - parseInt(e.getStyle('right'))
//					})
//				}
//
//				var matches = regex.exec(e.getStyle('backgroundImage'));
//				if (matches) {
//					e.setStyles({
//						background: 'none',
//						filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="crop", src="' + matches[1] + '")'
//					})
//				}
//			});
//		}, this);
	},
	setMenuHiliting: function () {
		if (SubMenu.menu) {
//			var children = $(SubMenu.menu).getChildren();
			children = $(SubMenu.menu).childNodes;
			//$(SubMenu.menu).childNodes.each(function(e) {
			for (var i = 0; i < children.length; i++) {
				e = $(children[i]);
				if (e.nodeType != 3) {
					if (e.tagName.toLowerCase() == 'li') {
//						e.addEvent('mouseenter', function() {this.addClass('hover')});
//						e.addEvent('mouseleave', function() {this.removeClass('hover')});
						e.observe('mouseover', function(ev) {Event.element(ev).addClassName('hover')});
						e.observe('mouseout', function(ev) {Event.element(ev).removeClassName('hover')});
					}
				}
			};
		}
	}
};


Accordion = Class.create({
	options: {
		duration : 0.2,
		toggleClassName: 'accordion_toggle',
		toggleActiveClassName: 'accordion_toggle_active',
		contentClassName: 'accordion_content',
		onEvent: 'click',
		sync: true
	},
	moving: false,
	initialize: function(options) {
		this.options = Object.extend(this.options, options || {});

		//activate triggers
		$$('.' + this.options.toggleClassName).each(function(e) {
			e = $(e);
			e.observe(this.options.onEvent, function (e, evt) {
				evt.stop();
				this.activate(e);
			}.bind(this, e));

			//hide content (assume next sibling)
			$(e.next(0)).setStyle({display: 'none', overflow: 'hidden'});
		}.bind(this));
	},
	activate: function(accordionToggle) {
		if (this.moving) return;
		this.moving = true;

		var effects = [];

		//show current (if activating)
		var showCurrent = false;
		if (!$(accordionToggle).hasClassName(this.options.toggleActiveClassName)) {
			$(accordionToggle).addClassName(this.options.toggleActiveClassName);
			effects.push(new Effect.BlindDown($(accordionToggle.next(0)), this.options));
			showCurrent = true;
		}

		//hide all current active
		var accordions = $$('.' + this.options.toggleClassName);
		for (var i = 0; i < accordions.length; i++) {
			e = $(accordions[i]);
			if (e.hasClassName(this.options.toggleActiveClassName) && (e != accordionToggle || !showCurrent)) {
				e.removeClassName(this.options.toggleActiveClassName);
				effects.push(new Effect.BlindUp($(e.next(0)), this.options));
			}
		};

		new Effect.Parallel(effects, {
			duration: this.options.duration,
			afterFinish : function() {this.moving = false}.bind(this)
		}, this);
	}
});

CharactersLimit = Class.create({
	input: null,
	display: null,
	limit: 0,
	lastCheckedValue: '',
	initialize: function(input, display, limit) {
		this.input = $(input);
		if (!this.input) return;
		this.display = $(display);
		this.limit = parseInt(limit);
		this.lastCheckedValue = this.input.value;

		this.input.observe('keyup', this.checkLength.bindAsEventListener(this));
		this.input.observe('paste', function(evt) {
			this.checkLength.bind(this).delay(0.01, evt);
		}.bindAsEventListener(this));
	},
	checkLength: function(evt) {
		var keyCode = (Prototype.Browser.IE) ? null : evt.keyCode;
		if (this.input.value != this.lastCheckedValue && keyCode != 8 && keyCode != 46) {
			if (this.limit > 0 && this.input.value.length > this.limit) {
				alert('Sorry, you have reach the maximum number of characters (' + this.limit + ').');
			}
		}
		this.update();
		return (this.input.value.length <= this.limit);
	},
	update: function() {
		this.lastCheckedValue = this.input.value;
		if (this.display) {
			this.display.innerHTML = this.limit - this.input.value.length;
		}
	}
});

function checkForm(evt, fields) {
	var errorMsg;
	var badFields = new Array();

	fields.each(function(e) {
		if (typeof(e) == 'object') { //set of checkboxes
			var atLeastOneSelected = false;
			for (var i = 0; i < e.fields.length; i++) {
				if ($(e.fields[i]).checked) atLeastOneSelected = true;
			}
			if (!atLeastOneSelected) {
				badFields.push({id: $(e.fields[0]).getAttribute('id'), name: e.name});
			}
		}
		if ($(e).value == '') {
			badFields.push({id: $(e).getAttribute('id'), name: $(e).getAttribute('name')});
		}
	}, badFields);

	var badFieldsLength = badFields.length;
	if (badFieldsLength > 0) {
		errorMsg = 'Please fill in the following fields:\n';
		for (i = 0; i < badFieldsLength; i++) {
			errorMsg += '- ' + badFields[i].name + '\n';
		}
		// damn FF bug 236791
		document.getElementById(badFields[0].id).setAttribute('autocomplete', 'off');
		document.getElementById(badFields[0].id).focus();
		document.getElementById(badFields[0].id).setAttribute('autocomplete', '');
		alert(errorMsg);
		evt.stop();
		return false;
	}
	else {
		return true;
	}
}

function formComplete (el, resp, message) {
	el = $(el);
	if (el) {
		if (resp.responseText == 'success') {
			//empty form
			el.childElements().each(function(e) {
				if (e.tagName.toLowerCase() != 'h1') {
					$(e).remove();
				}
			});
			var messageContainer = new Element('p');
			messageContainer.innerHTML = message;
			el.insert(messageContainer);

			var e1 = $('mediaText');
			var e2 = $('popclose');
			var h = 0;
			h += e1.offsetHeight;
			h += parseInt(e1.getStyle('margin-top'));
			h += e2.offsetHeight;
			h += parseInt(e2.getStyle('margin-bottom'));
			// resize the container

			new Effect.Scale('mediaContainer', (h / $('mediaContainer').offsetHeight) * 100, {
				scaleX: false,
				scaleContent: false
			});
		}
		else {
			alert('An error occured. Please try again later.');
		}
	}
}

function isArray(obj) {
	//returns true is it is an array
	return !(obj.constructor.toString().indexOf('Array') == -1)
}

Tooltip = Class.create({
	container: null,
	messageContainer: null,
	options: {
		targetClass: 'tooltip',
		tooltipId: 'tooltipContainer',
		tooltipMessageId: 'tooltipMessage'
	},
	initialize: function() {
		this.setup();
		
		$$('a.' + this.options.targetClass).each(function(e) {
			if (e.title) {
				var title = e.title;
				e.observe('mouseover', function() {
					this.show(title, e);
				}.bind(this));
				e.observe('mouseout', function() {
					this.hide(title, e);
				}.bind(this));
				e.title = '';
			}
		}.bind(this));
	},
	show: function(message, target) {
		var offset = target.cumulativeOffset();
		this.container.style.left = offset.left + 'px';
		this.container.style.top = offset.top + 'px';
		
		this.messageContainer.innerHTML = message;
		
		this.container.style.display = 'block';
	},
	hide: function() {
		this.container.style.display = 'none';
	},
	setup: function() {
		this.container = document.createElement('div');
		this.container.setAttribute('id', this.options.tooltipId);
		
		this.messageContainer = document.createElement('div');
		this.messageContainer.setAttribute('id', this.options.tooltipMessageId);
		this.container.appendChild(this.messageContainer);
		
		this.hide();
		
		body = document.getElementsByTagName('body')[0];
		body.appendChild(this.container);
	}
});
