
isIE8 = Browser.Engine.trident && Browser.Engine.version == 5 && /MSIE\s8/.test(navigator.userAgent);
isIE7 = Browser.Engine.trident && Browser.Engine.version == 5 && /MSIE\s7/.test(navigator.userAgent) && !isIE8;
isIE6 = Browser.Engine.trident && Browser.Engine.version == 4 && /MSIE\s6/.test(navigator.userAgent) && !isIE8 && !isIE7;

// Prevent flickering on the home page on IE
document.write('<style type="text/css">#home-sliders * {display: none;}</style>');

window.addEvent('domready', function () {
	$$('#left-menu', '.list-column', '.lower-right .links').each(function (el) {
		new BHMenu(el);
	});

	// Home page Customer Viewpoints link
	if (!isIE6) {
		$$('.lower-right .clip-link a').each(function (el) {
			new BHImageLink(el);
		});
	}

	$$('#site-select select').each(function (e) {
		var ps = new PseudoSelect(e);
		ps.addEvent('change', function () {
			window.location = ps.get('value');
		});
	});

	new BHDemoAccordions();
	new BHTeamAccordions();
	new BHBusinessAccordions();
	new BHPartnerAccordions();
	new BHOfficeAccordions();

	// Home page animation
	var homeSliders = $('home-sliders');
	if (homeSliders) {
		var homeSlidersAltImage = homeSliders.getElement('img');
		if (homeSlidersAltImage) {
			var fileName = homeSlidersAltImage.get('src').replace(/.*images\/(.+)\.[^\.]+$/i, '$1');
			if (fileName) {
				swfobject.embedSWF(
					jpSiteURL + 'flash/' + fileName + '.swf', 'home-sliders',
					924, 320, '9.0.0',
					jpSiteURL + 'flash/swfobject-2.1/expressInstall.swf',
					{
						link1: escape($('slide-link-1').get('href')),
						link2: escape($('slide-link-2').get('href')),
						link3: escape($('slide-link-3').get('href')),
						link4: escape($('slide-link-4').get('href')),
						link5: escape($('slide-link-5').get('href'))
					},
					{
						wmode: 'opaque',
						quality: 'high'
					}
				);
			}
		}
	}

	// Forms
	$$('form').each(function(e) {
		new jpForm(e, {
			autoFocus: false,
			errorMessage: 'Please complete all the required fields.'
		});
	});
});

var BHDemoAccordions = new Class({
	initialize: function() {
		var options = {
			duration: 500,
			display: -1,
			opacity: false,
			alwaysHide: true,
			onActive: this.active.bind(this),
			onBackground: this.background.bind(this)
		};
		this.togglers = $$('#demos .demos-title a');
		this.elements = $$('#demos .demos-list');
		this.accordion = new Fx.Accordion(this.togglers, this.elements, options);
		this.togglers.addEvent('click', this.evtClick.bindWithEvent(this));
	},
	evtClick: function (evt) {
		evt.stop();
	},
	active: function (toggler, element) {
		toggler.removeClass('closed');
	},
	background: function (toggler, element) {
		toggler.addClass('closed');
	}
});

var BHOfficeAccordions = new Class({
	initialize: function() {
		$$('.location-map').each(function(el, i) {
			var options = {
				duration: 500,
				display: i > 0 ? -1 : 0, // Open the first map
				opacity: false,
				alwaysHide: true,
				onActive: this.active.bind(this),
				onBackground: this.background.bind(this)
			};
			togglers = el.getElements('p.view-hide a');
			togglers.addEvent('click', this.evtClick.bindWithEvent(this));
			elements = el.getElements('.map-wrapper');
			new Fx.Accordion(togglers, elements, options);
		}, this);
	},
	evtClick: function (evt) {
		evt.stop();
	},
	active: function (toggler, element) {
		element.getParent().addClass('open');
	},
	background: function (toggler, element) {
		element.getParent().removeClass('open');
	}
});

var BHAccordions = new Class({
	accordion: null,
	headers: [],
	clones: [],
	togglers: [],
	elements: [],
	closers: [],
	initialize: function() {
		this.init();
	},
	init: function () {
		var options = {
			duration: 500,
			display: -1,
			opacity: false,
			alwaysHide: true,
			onActive: this.active.bind(this),
			onBackground: this.background.bind(this)
		};
		this.accordion = new Fx.Accordion(this.togglers, this.elements, options);
		this.togglers.addEvent('click', this.evtClick.bindWithEvent(this));
		this.closers.addEvent('click', this.evtClick.bindWithEvent(this));

		// duplicate the headings for rollovers
		this.headers.each(function (el) {
			var clone = el.clone(true).addClass('clone').inject(el, 'after');
			el.addClass('cloned');
			this.clones.push(clone);
		}, this);
		this.togglers.addEvent('mouseenter', this.evtMouseEnter.bindWithEvent(this));
		this.togglers.addEvent('mouseleave', this.evtMouseLeave.bindWithEvent(this));
	},
	evtMouseEnter: function (evt) {
		var el = this.findHeaders($(evt.target));
		if (el) {
			el.setStyle('display', 'block');
		}
	},
	evtMouseLeave: function (evt) {
		var el = this.findHeaders($(evt.target));
		if (el) {
			el.setStyle('display', '');
		}
	},
	findHeaders: function (el) {
		var parents = $(el).getParents('div');
		var elements = [];
		parents.each(function (p) {
			if (elements.length) {
				return;
			}
			this.clones.each(function (clone) {
				if (p.hasChild(clone)) {
					elements.push(clone);
				}
			});
		}, this);
		return $$(elements);
	},
	active: function (toggler, element) {
		element.getParent().addClass('open');
	},
	background: function (toggler, element) {
		element.getParent().removeClass('open');
	},
	evtClick: function (evt) {
		evt.stop();
		var el = $(evt.target);
		if (el.getParent().hasClass('close')) {
			this.close();
		}
	},
	close: function () {
		this.accordion.display(-1);
	}
});

var BHBusinessAccordions = new Class({
	Extends: BHAccordions,
	initialize: function() {
		this.headers = $$('.benefit-header h4');
		this.togglers = $$('.benefit .read-more a');
		this.elements = $$('.benefit-info-wrapper');
		this.closers = $$('.benefit-info-wrapper .close a');
		this.init();
	}
});

var BHTeamAccordions = new Class({
	Extends: BHAccordions,
	initialize: function() {
		this.headers = $$('.team-member-header h5');
		this.togglers = $$('.team-member .read-more');
		this.elements = $$('.member-info-wrapper');
		this.closers = $$('.member-info-wrapper .close a');
		this.init();
	}
});

var BHPartnerAccordions = new Class({
	Extends: BHAccordions,
	initialize: function(){
		this.headers = $$('.partner-header h4');
		this.togglers = $$('.partner .read-more');
		this.elements = $$('.partner-info-wrapper');
		this.closers = $$('.partner-info-wrapper .close a');
		this.init();
	}
});

var BHMenu = new Class({
	options: {
		offsetX: 0,
		offsetY: -6,
		'class': 'cloned'
	},
	tab: null,
	initialize: function(container) {
		this.container = $(container);
		if (!this.container) {
			return;
		}
		if (!Browser.Engine.trident || Browser.Engine.version > 4) { // if > IE 6
			this.tab = this.container.getElement('.selected-option');
		}
		this.positionTab(this.container.getElement('li.on a'));

		var links = this.container.getElements('a');
		links.each(function (el) {
			var li = el.getParent();
			if (li.hasClass('on')) {
				// don't activate for the current link
				return;
			}
			var span = new Element('span', {'class': 'clone'}).inject(el, 'after');
			var clone = el.clone(true).inject(span);
			span.setStyles({
				width: 0,
				display: 'none'
			});
			span.set('tween', {
				duration: 250,
				transition: 'linear',
				onComplete: this.complete
			});
			li.addEvent('mouseenter', this.evtEnter.bindWithEvent(this, li));
			li.addEvent('mouseleave', this.evtLeave.bindWithEvent(this, li));
		}, this);
	},
	positionTab: function (el) {
		if (!el || !this.tab) {
			return;
		}
		var pos = el.getPosition(this.container);
		this.tab.setStyles({
			top: pos.y + this.options.offsetY,
			display: 'block'
		});
	},
	evtEnter: function (evt, li) {
		var el = li.getElement('.clone');
		if (el) {
			this.enter(el);
		}
	},
	evtLeave: function (evt, li) {
		var el = li.getElement('.clone');
		if (el) {
			this.leave(el);
		}
	},
	enter: function (el) {
		if (!el) {
			return;
		}
		el.setStyle('display', 'block');
		var width = el.getElement('a').getSize().x;
		el.tween('width', width);
	},
	leave: function (el) {
		if (!el) {
			return;
		}
		el.tween('width', 0);
	},
	complete: function (el) {
		var w = el.getStyle('width').toInt();
		if (w === 0) {
			el.setStyle('display', 'none');
		}
		else {
			el.setStyle('display', 'block');
		}
	}
});

var BHImageLink = new Class({
	Implements: Options,
	el: null,
	linkCover: null,
	fx: null,
	options: {
		minWidth: 35,
		maxWidth: 65,
		duration: 250
	},
	initialize: function(el, options) {
		this.setOptions(options);
		this.el = $(el);
		if (!this.el) return;
		this.prepare();
	},
	prepare: function() {
		// Remove background image and put it in a new div element
		var bgImg = this.el.getStyle('background-image');
		if (bgImg) {
			this.el.setStyle('background-image', 'none');
			this.linkCover = new Element('div', {'class': 'link-cover'}).injectAfter(this.el);
			this.linkCover.setStyles({
				width: this.options.minWidth + 'px',
				height: this.el.getStyle('height'),
				'background-image': bgImg
			});
		}
		this.fx = new Fx.Tween(this.linkCover, {
			property: 'width',
			link: 'cancel',
			duration: this.options.duration
		});
		// Add event
		this.el.addEvent('mouseenter', this.activate.bindWithEvent(this));
		this.el.addEvent('mouseleave', this.deactivate.bindWithEvent(this));
	},
	activate: function() {
		this.fx.start(this.options.maxWidth + 'px');
	},
	deactivate: function() {
		this.fx.start(this.options.minWidth + 'px');
	}
});



var PseudoSelect = new Class({
	Implements: [Options, Events],
	element: null,
	toggler: null,
	input: null,
	list: null,
	optionElements: [],
	options: {
		selectedClass: 'selected'
	},
	open: false,
	evtClose: null,
	initialize: function(element, options) {
		if (!element) {
			return;
		}

		this.setOptions(options);

		this.replaceSelect(element);

		if (!this.element || !this.toggler || !this.input || !this.list || !this.optionElements) {
			return;
		}

		this.open = false;
		this.list.setStyle('display', 'none');
		this.toggler.addEvent('mousedown', this.toggleClicked.bind(this));

		// populate the selected value
		var selected = this.list.getElement('.' + this.options.selectedClass);
		if (!selected) {
			selected = this.optionElements[0];
		}
		this.setSelected(selected);


		$(document.body).addEvent('mousedown', this.close.bind(this));

		// add option events
		this.optionElements.each(function (option) {
			option.addEvent('click', this.optionClicked.bind(this));
		}, this);

		// fix the widths of the lists
		this.list.setStyles({
			display: 'block',
			visibility: 'hidden'
		});
		var width = this.list.getSize().x;

		var lis = this.optionElements;
		var w = 0;
		this.optionElements.each(function (option) {
			var size = option.getSize();
			w = (size.x > w) ? size.x : w;
		});
		var paddings = parseInt(lis[0].getStyle('paddingLeft')) + parseInt(lis[0].getStyle('paddingRight'));
		var borders = parseInt(this.list.getStyle('borderLeftWidth')) + parseInt(this.list.getStyle('borderRightWidth'));
		var listPaddings = parseInt(this.list.getStyle('paddingLeft')) + parseInt(this.list.getStyle('paddingRight'));
		if (w < width) {
			w = width;
		}
		if (!isNaN(paddings)) {
			w -= paddings;
		}
		if (!isNaN(borders)) {
			w -= borders;
		}
		if (!isNaN(listPaddings)) {
			w -= listPaddings;
		}
		if (w > 0) {
			this.optionElements.each(function (option) {
				option.setStyle('width', w);
			});
		}

		this.list.setStyles({
			display: 'none',
			visibility: ''
		});

		// add hover styles for IE6
		this.isIE6 = /MSIE\s6/.test(navigator.userAgent);
		if (this.isIE6) {
			this.optionElements.each(function (option) {
				option.addEvent('mouseenter', function () { this.addClass('hover'); });
				option.addEvent('mouseleave', function () { this.removeClass('hover'); });
			});
		}

		this.element.set = this.set.bind(this);

		return this.element;
	},
	replaceSelect: function (select) {
		this.element = new Element('div', {
			'class': select.get('class')
		});
		this.element.addClass('pseudo-select');

		this.element.get = function (prop) {
			var property = Element.Properties.get(prop);
			var v = (property && property.get) ? property.get.apply(this.element, Array.slice(arguments, 1)) : this.element.getProperty(prop);
			return (v && $defined(v)) ? v : this.input.get(prop);
		}.bind(this);

		var value = select.get('value');

		this.input = new Element('input', {
			id: select.get('id'),
			type: 'hidden',
			name: select.get('name'),
			value: value
		}).inject(this.element);
		this.toggler = new Element('span').inject(this.element);
		this.label = new Element('em').inject(this.toggler);
		this.list = new Element('ul').inject(this.element);

		var label = '';
		select.getElements('option').each(function (option) {
			var li = new Element('li', {
				'class': option.get('class'),
				'html': option.get('text') + ' <span>' + option.value + '</span>'
			}).inject(this.list);
			this.optionElements.push(li);
			if (option.value == value && !label) {
				li.addClass('selected');
				this.label.set('text', value);
			}
		}, this);

		// do the replacement
		if (select.getParent()) {
			this.element.replaces(select);
		}
	},
	toggleClicked: function (evt) {
		this.open = !this.open;
		this.list.setStyle('display', this.open ? 'block' : 'none');
		this.toggler.toggleClass('open');
	},
	optionClicked: function (evt) {
		var el = evt.target;
		if (!this.open || !el) {
			return false;
		}

		this.setSelected(el);

		this.toggleClicked();
	},
	setSelected: function (el) {
		if (!el) {
			return;
		}
		var value = el.getElement('span').get('text');

		var e = el.clone(true);
		e.getElement('span').destroy();
		var text = e.get('text');

		this.optionElements.each(function (option) {
			this.element.removeClass(option.get('class'));
			option.removeClass(this.options.selectedClass);
		}, this);
		this.element.addClass(el.get('class'));

		this.element.removeClass(this.options.selectedClass); // don't add the selected class
		el.addClass(this.options.selectedClass);

		this.input.set('value', value);
		this.element.fireEvent('change');
		this.label.set('text', text);
	},
	close: function (evt) {
		if (this.open && !this.element.hasChild(evt.target)) {
			evt.stop();
			this.toggleClicked();
		}
	},
	set: function (prop, value) {
		if ($type(prop) == 'string' && prop == 'value') {
			this.optionElements.each(function (option) {
				var val = option.getElement('span').get('text');
				if (val == value) {
					this.setSelected(option);
				}
			}, this);
			return this.element;
		}
		else {
			return this.element.set(arguments);
		}
	}
});
