var basePath = window.location.toString().indexOf('/html/') >= 0 ? '../' : '';
//var flashPath = basePath + 'flash/';
//var flashVersion = '9.0.0';
//var swfInstallFile = 'swfobject-2.1/expressInstall.swf';
//var flashParams = {
//	quality: 'high',
//	wmode: 'transparent'
//};
var JobBoardInstance;
var HistoryManager;
var ContentFetcherInstance;

/**
 * Array.implement: David Walsh, http://davidwalsh.name/array-shuffling-mootools
 */
Array.implement({
	shuffle: function() {
		//destination array
		for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
		return this;
	}
});

document.write('<style type="text/css">#logoBox li { display: none; }</style>');
document.write('<style type="text/css">.fade-at-start { visibility: hidden; }</style>');

window.addEvent('domready', function () {
	// Forms
	new jpForm('enquiry');
	new jpForm('cv-form', {autoFocus: false});
	new jpForm('frmApply');
	new jpForm('frmJobs', {autoFocus: false, resetToNull: true});
	
	var f = $('frmJobUpdates');
	if (f && false) {
		f.addEvent('submit', function (evt) {
			evt.stop();

			var parent = this.getParent();
			parent.addClass('ajax-loading');
			this.setStyle('display', 'none');
			parent.getChildren().each(function(e){
				if (e != this) {
					e.destroy();
				}
			}, this);

			this.set('send', {
				onComplete: function(response) {
					parent.removeClass('ajax-loading');
					parent.adopt(new Element('p').set('text', 'Thank you for your details, we will be in touch at the earliest opportunity.'));
				}
			});
			this.send();
		});
	}

	ContentFetcherInstance = new ContentFetcher($$('a.jpLightbox'), {
		adoptOnly: 'jpLightboxContent',
		fixFlash: false, //whether to hide flash (things may be getting too slow)
		addCloseButton: false,
		closeButtonOptions: {
			'text': 'Close this window'
		},
		onReady: function(contents) {
			var regex = new RegExp('(apply|send|job)-(\\d+)\.shtml(\\?preview)?');
			contents.getElements('a').each(function (el) {
				var matches = regex.exec(el.get('href'));
				if (matches) {
					var action = 'view';
					if (matches[1] == 'send' || matches[1] == 'apply') {
						action = matches[1];
					}
					var url = '#job/' + matches[2] + '/' + action;
					if (matches[3]) {
						url += '/preview';
					}
					el.set('href', url);
				}
			});

			//add the close button in custom way
			var btnList = contents.getElement('ul.buttonsList');
			if (btnList) {
				var li = new Element('li', {'class': 'end'}).injectInside(btnList);
				new Element('a', this.options.closeButtonOptions).injectInside(li);
			}
			
			// Forms validation
			new jpForm('frmApply', {autoFocus: !Browser.Engine.trident});
		},
		onClose: function() {
			JobBoardInstance.reset();
		}
	});

	HistoryManager = new HistoryManagerX();

	//job board
	HistoryManager.initialize({
		iframeSrc: '_blank.html'
	});

	JobBoardInstance = new JobBoard('jobs');
	HistoryManager.start();

	//client logos
	$$('#logoBox li').setStyle('display', 'block');
	new Jp_Showcase($$('#logoBox li'), {
		delay: 6000, //time the case will be shown
		duration: 2000, //effect duration
		fastDuration: 1000,
		fadeOnStart: true,
		stopOnMouseOver: false,
		randomize: true
	});
	
	// Quick search button
	$$('input.qsearch-go').addEvent('mouseenter', function(e) {
		this.addClass('hover');
	});
	$$('input.qsearch-go').addEvent('mouseleave', function(e) {
		this.removeClass('hover');
	});
});

window.addEvent('load', function () {
	$$('.fade-at-start').each(function(e) {
		new Fx.Tween(e, {property: 'opacity', duration: 500}).start(0, 1);
	});
});




var JobBoard = new Class({
	Implements: Options,
	rollovers: null,
	container: null,
	job: null,
	history: null,
	regex: null,
	factory: null,
	multibox: null,
	options: {
		key: 'job'
	},
	initialize: function (container, options) {
		this.factory = new JobBoard.Factory(this.options.key);
		this.regex = new RegExp('^' + this.options.key + '\/(\\d+)\/?(view|apply|send)?\/?(preview)?');

		this.history = HistoryManager.register(
			'job',								// key
			[],									// defaults
			function (values) {
				this.show(this.factory.getJob(values));
			}.bind(this),						// onMatch
			function(values) {
				var job = this.factory.getJob(values);
				if (!job) {
					return 'job/';
				}
				this.show(job);
				return job.toAnchor();
			}.bind(this),						// onGenerate
			this.regex,							// regex
			{}									// options
		);
		this.container = $(container);
		if (this.container) {
			this.rollovers = new JobBoard.Rollovers(this);
		}
	},
	load: function (href) {
		this.parseHref(href)
	},
	parseHref: function (href) {
		var parts = href.split('#');
		var anchor = parts[1] || '';
		var matches = this.regex.exec(anchor);
		if (matches && !isNaN(matches[1])) {
			this.history.setValues([matches[1], matches[2]]);
		}
	},
	show: function (job) {
		if (!job) {
			return;
		}

		var url = basePath + job.toUrl();

		ContentFetcherInstance.visible = false;
		ContentFetcherInstance.load(url);
	},
	reset: function() {
		this.history.setValues([0])
	}
});

JobBoard.Factory = new Class({
	key: null,
	initialize: function (key) {
		this.key = key;
	},
	getJob: function () {
		var args = ($type(arguments[0]) == 'array') ? arguments[0] : arguments;
		var id = $defined(args[0]) ? args[0] : null;
		var action = $defined(args[1]) ? args[1] : null;
		var preview = $defined(args[2]) && args[2] == 'preview';

		if (!id) {
			return null;
		}

		return {
			key: this.key,
			id: id,
			action: action,
			preview: preview,
			toAnchor: function () {
				var a = this.key + '/' + this.id;
				if (this.action) {
					a += '/' + this.action;
				}
				else {
					a += '/view';
				}
				if (this.preview) {
					a += '/preview';
				}
				return a;
			},
			toUrl: function () {
				var url = '';
				switch (this.action) {
					case 'apply':
					case 'send':
						url = this.action;
						break;
					case 'view':
					default:
						url = 'job';
						break;
				}
				url += '-' + this.id + '.shtml';
				if (this.preview) {
					url += '?preview';
				}
				return url;
			}
		};
	}
});

JobBoard.Rollovers = new Class({
	Implements: Options,
	board: null,
	jb: null,
	options: {
		className: 'job',
		oddClass: 'jobDetails',
		evenClass: 'jobDescription'
	},
	initialize: function(jb, options) {
		this.jb = jb;
		this.board = jb.container;
		if (!this.board) return;

		this.setOptions(options);
		this.setup();
	},
	setup: function() {
		this.board.getElements('.' + this.options.className + ' a').each(function(el) {
			el.addEvent('mouseover', function() {
				el.getParent('div').addClass(this.options.className + '-hover');
			}.bind(this));
			el.addEvent('mouseout', function() {
				el.getParent('div').removeClass(this.options.className + '-hover');
			}.bind(this));
		}, this);
	}
});


function trace (s) {
	$A(arguments).each(function (s) {
		if (typeof console == 'undefined' || window.webkit) {
			if (!document.getElementById('debug')) {
				var o = document.createElement('pre');
				o.id = 'debug';
				//o.style.color = 'white';
				o.style.fontSize = '10pt';
				o.style.position = 'absolute';
				o.style.top = '0px';
				o.style.right = '0px';
				o.style.textAlign = 'left';
				document.getElementsByTagName('body')[0].appendChild(o);
			}

			s = new String(s);
			s = s.replace('<', '&lt;');
			s = s.replace('>', '&gt;');
			document.getElementById('debug').innerHTML += s + '<br />';
		}
		else {
			console.log(s);
		}
	});
}

