
function trace() {
	for (var i = 0; i < arguments.length; i++) {
		if (typeof console != 'undefined' && console.log) {
			console.log(arguments[i]);
		}
		else {
			alert(arguments[i]);
		}
	}
}

var contactLink = null;
var glossaryLink = null;

window.addEvent('domready', function () {
	//glossary
	var e = $$('#vl1 a');
	glossaryLink = new ContentFetcher(e, 'content', {
		adoptOnly: 'glossary',
		onComplete: function() {
			new Glossary('glossary');
			contactLink.hide();
		}
	});
	//contact
	var contactLinks = $$('#vl2 a').extend($$('#sw4 a'));
	contactLink = new ContentFetcher(contactLinks, 'content', {
		adoptOnly: 'contactUs',
		onComplete: function() {
			glossaryLink.hide();
			initContactForm();
		}
	});

	new Glossary('glossary');

	new jpForm('searchForm', {valuesToConsiderNull: ["I'm looking for..."]});
	new jpForm('subscribe', {autoClear: false, afterSending: submitNewsletterForm});

	new SubMenu('navigation', {addShadow: false});

	// init the contact form if they've opened it up in a new window/tab
	initContactForm();

	var galleryMainImage = $$('#bigPhoto img');
	if (galleryMainImage.length) {
		new jp_ImageSwapper(galleryMainImage[0], $$('#photoGallery a'));
	}
});

function initContactForm () {
	new jpForm('frmContactForm', {autoClear: false, afterSending: submitContactForm});

	$$('.contact-close').addEvent('click', function () {
		contactLink.hide();
		return false;
	});
	$$('.contact-form-show').addEvent('click', function () {
		$$('#contact-form').removeClass('hidden');
		$$('#contact-details').addClass('hidden');
		return false;
	});
	$$('.contact-return').addEvent('click', function () {
		$$('#contact-form').addClass('hidden');
		$$('#contact-details').removeClass('hidden');
		return false;
	});

	var togglers = $$('#accordion h6');
	var elements = $$('#accordion div.data');
	var options = {
		show: -1,
		alwaysHide: true,
		opacity: false
	};
	new Accordion(togglers, elements, options);
}



function submitContactForm(evt, oForm) {
	new Event(evt).stop();

	var form = oForm.form;

	var parent = form.getParent();
	form.setStyle('display', 'none');
	var e = new Element('div').addClass('ajax-loading').injectInside(parent);
	new Element('p').set('html', 'Please wait...').injectInside(e);

	new Image().src = 'images/thankyou.gif'; //preload thank you image
	form.set('send', {
		onSuccess: function() {
			e.removeClass('ajax-loading');
			e.empty();
			new Element('p').set('html', 'Thank You.').injectInside(e);

			var img = $$('#contactUs img');
			if (img) {
				img.set('src', 'images/thankyou.gif');
			}
		}
	}).send();

	form.empty();
}

function submitNewsletterForm(evt, oForm) {
	new Event(evt).stop();

	var form = oForm.form;

	var parent = form.getParent();
	form.setStyle('display', 'none');
	var e = new Element('div').addClass('ajax-loading').injectInside(parent);
	new Element('p').set('html', 'Please wait...').injectInside(e);

	form.set('send', {
		onSuccess: function() {
			e.removeClass('ajax-loading');
			e.empty();
			new Element('p').set('html', 'Thank You.').injectInside(e);
		}
	}).send();

	form.empty();
}


var Glossary = new Class({
	Implements: Options,
	element: null,
	options: {
		definition: 'definition'
	},
	initialize: function (el, options) {
		this.element = $(el);
		if (!this.element) {
			return;
		}

		this.setOptions(options);

		if (!this.options.definition) {
			return;
		}

		var items = this.element.getElements('a');
		items.addEvent('click', this.item.bindWithEvent(this));
	},
	item: function (evt) {
		evt.stop();
		var e = evt.target;
		var definition = $(this.options.definition);
		if (definition) {
			var parent = e.getParent();
			var dd = parent.getNext();
			if (dd.get('tag') == 'dd') {
				definition.set('html', (e.get('text') + '<br /><br />' + dd.get('text')));
			}
		}
	}
});

var jpForm = new Class({
	Implements: [Options, Events],
	form: null,
	fields: [],
	errorMessageContainer: null,
	options: {
		autoClear: true,
		valuesToConsiderNull: [],
		errorMessageContainerTag: 'div',
		errorMessageContainerId: 'jpFrmMessage',
		errorMessage: 'Please fill in all the required fields.',
		autoScrollOnError: false, //in case of error, scroll back to the top of the form (usefull in case the error message displays out of the screen)
		afterSending: null
	},
	initialize: function(form, options) {
		this.form = $(form);
		if (!this.form) return;
		this.setOptions(options);

		this.errorMessageContainer = $(this.options.errorMessageContainerId);

		//get all fields
		this.form.getElements('input, textarea').each(function(e) {
			this.fields.push(new jpField(e, this.options));
		}, this);

		//submit event
		this.form.addEvent('submit', function(evt) {this.fireEvent('submit', evt)}.bindWithEvent(this));
		this.addEvent('submit', function(evt) {this.submit(evt)}.bindWithEvent(this));
	},
	submit: function(evt) {
		//check fields
		var checked = true;
		for (var i = 0; i < this.fields.length; i++) {
			checked *= this.fields[i].check();
		}
		if (checked) {
			for (var i = 0; i < this.fields.length; i++) {
				this.fields[i].clearNullFields();
			}
			if (this.options.afterSending) {
				(this.options.afterSending)(evt, this);
			}
		}
		else {
			new Event(evt).stop();
//			alert(this.options.errorMessage);
			if (!this.errorMessageContainer) {
				this.errorMessageContainer = new Element(this.options.errorMessageContainerTag, {id: this.options.errorMessageContainerId});
				this.errorMessageContainer.injectTop(this.form);
			}
			this.errorMessageContainer.set('html', this.options.errorMessage);
			if (this.options.autoScrollOnError) { //go back to the top of the form
				new Fx.Scroll(window, {wheelStops: false, duration: 100}).toElement(this.form);
			}
		}
	}
});

var jpField = new Class({
	element: null,
	cleared: false,
	initialValue: '',
	type: null,
	options: {
		autoClear: true,
		valuesToConsiderNull: [], //those values will be considered null
		requiredClass: 'jpFrmRequired',
		errorClass: 'jpFrmError',
		emailClass: 'jpFrmEmail',
		numericClass: 'jpFrmNumeric'
	},
	initialize: function(element, options) {
		this.element = $(element);
		if (!this.element) return;
		this.setOptions(options);

		this.initialValue = this.element.value;

		var tag = this.element.get('tag');
		if (tag == 'input') {
			this.type = this.element.getAttribute('type') || 'text';
		}
		else {
			this.type = tag;
		}

		if (this.options.autoClear && (this.type == 'text' || this.type == 'password')) {
			this.element.addEvent('focus', function() {
				this.clearDefault();
			}.bind(this));
			this.element.addEvent('blur', function() {
				this.setToDefault();
			}.bind(this));
		}
	},
	getValue: function(getActualValue) {
		var value = this.element.value;
		if (!getActualValue) {
			var i = 0;
			while (i < this.options.valuesToConsiderNull.length) {
				if (value == this.options.valuesToConsiderNull[i]) {
					value = '';
					break;
				}
				i++;
			}
		}
		return value;
	},
	clearNullFields: function() {
		this.element.value = this.getValue();
	},
	isRequired: function() {
		return this.element.hasClass(this.options.requiredClass);
	},
	check: function() {
		var checked = true;
		if (this.isRequired()) {
			switch (this.type) {
				case 'text':
				case 'password':
				case 'textarea':
				case 'file':
					var value = this.getValue();
					checked = value != '';
					if (checked) {
						if (this.element.hasClass(this.options.emailClass)) {
							checked = value.match(/.+\@.+\..+/) ? true : false;
						}
						else if (this.element.hasClass(this.options.numericClass)) {
							checked = value.match(/\d+/) ? true : false;
						}
					}
					break;
			}
		}

		if (!checked) {
			// highlight field
			this.element.addClass(this.options.errorClass);
		}
		else {
			this.element.removeClass(this.options.errorClass);
		}
		return checked;
	},
	clearDefault: function() {
		if (this.element && !this.cleared) {
			this.element.value = '';
		}
		this.cleared = true;
	},
	setToDefault: function () {
		if (this.getValue(true) == '') {
			this.element.value = this.initialValue;
			this.cleared = false;
		}
	}
});
jpField.implement(new Options);

var SubMenu = new Class({
	Implements: Options,
	menuBarId: 'menu',
	options: {
		addShadow: true,
		glow: false
	},
	initialize: function (menuBarId, options) {
		this.setOptions(options);
		this.menuBarId = menuBarId || this.menuBarId;
		var submenus = $$('#' + this.menuBarId +  ' ul.navbar ul');

		if (this.options.glow) {
			this.shadows = ['ne', 'ee', 'se', 'ss', 'sw', 'ww', 'nw', 'nn'];
		}
		else {
			this.shadows = ['ne', 'ee', 'se', 'ss', 'sw'];
		}
		this.submenus = submenus;

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

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

		// do the setup required for all browsers
		this.submenus.each(function (submenu) {
			var topLink = submenu.getElement('a');
			if (topLink) {
				topLink.addClass('top');
			}
			var s = {};

			//add shadows
			if (this.options.addShadow) {
				this.shadows.each(function (shadow) {
					var e = $(document.createElement('div'));
					e.addClass(shadow.toString());
					submenu.appendChild(e);
					e.size = e.getSize();
					s[shadow] = e;
				});

				var size = submenu.getSize();
				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
				});
				if (this.options.glow) {
					s.ww.setStyles({
						height: size.y - s.nw.size.y -  s.sw.size.y - offset.y
					});
					s.nn.setStyles({
						width: size.x - s.nw.size.x - s.ne.size.x - offset.x
					});
				}
			}
		}, this);

		if (this.isIE) {
			this.prepForIE();
		}
		if (this.isIE6) {
			this.prepForIE6();
		}

		// hide the menu again
		this.submenus.each(function (submenu) {
			submenu.setStyles({
				display: '',
				visibility: ''
			})
		});
	},
	prepForIE: function () {
		this.submenus.each(function (submenu) {
			var paddings = submenu.getElement('a').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 () {
		$$('#' + this.menuBarId +  ' li').each(function (e) {
			e.addEvent('mouseenter', function () {e.addClass('hover')});
			e.addEvent('mouseleave', function () {e.removeClass('hover')});
		});

		var regex = /url\(['"](.*)['"]\)/;
		this.submenus.each(function (submenu) {
			var p = submenu.getParent();

			var size = submenu.getSize();
			//p.addEvent('mouseenter', function () {submenu.setStyles({display: 'block'})});
			//p.addEvent('mouseleave', function () {submenu.setStyles({display: ''})});

			if (this.options.addShadow) {
				this.shadows.each(function (shadow) {
					var e = submenu.getElement('.' + shadow);
					if (shadow.substr(0, 1) == 's') {
						e.setStyles({
							bottom: 'auto',
							top: size.y - e.getSize().y - parseInt(e.getStyle('bottom'))
						})
					}
					if (shadow.substr(1, 1) == 'e') {
						e.setStyles({
							right: 'auto',
							left: size.x - e.getSize().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] + '")'
						})
					}
				});
			}

			var as = submenu.getElementsByTagName('a');
			preloadedImages = [];
			$A(as).each(function (e) {
				var matches = regex.exec(e.getStyle('backgroundImage'));
				if (matches) {
					var img = matches[1].replace('.png', '_ie6.png');
					var hoverImg = matches[1].replace('.png', '_hover.png');
					e.setStyles({
						background: 'none',
						cursor: 'pointer',
						filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="crop", src="' + img + '")'
					})

					e.addEvent('mouseenter', function () {e.setStyles({
						filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="crop", src="' + hoverImg + '")'
					})});
					e.addEvent('mouseleave', function () {e.setStyles({
						filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="crop", src="' + img + '")'
					})});

					//preload images
					preloadedImages.push(new Image());
					preloadedImages[preloadedImages.length - 1].src = img;
				}
			});
		}, this);
	}
});

var jp_ImageSwapper = new Class({
	Implements: Options,
	mainImage: null,
	thumbs: [],
	initialize: function(mainImage, thumbs) {
		this.mainImage = $(mainImage);
		if (typeof thumbs.length != 'undefined') {
			thumbs.each(function(e) {
				e = $(e);
				if (e) {
					this.thumbs.push(e);
//					new Image().src = e.get('href'); //preload in cache
				}
			}.bind(this));
		}
		if (!this.mainImage || this.mainImage.tagName.toLowerCase() != 'img') {
			return;
		}
		this.setEvents();
	},
	setEvents: function() {
		this.thumbs.each(function(e) {
			e.addEvent('click', function(evt, e) {
				evt.stop();
				this.swap(e.get('href'));
			}.bindWithEvent(this, e));
		}, this);
	},
	swap: function(src) {
		this.mainImage.set('src', src);
	}
});

