function trace() {
	$A(arguments).each(function (a) {
		console.log(a);
	});
}

window.isIE = /MSIE/.test(navigator.userAgent);
window.isIE6 = /MSIE\s6/.test(navigator.userAgent);
window.isIE7 = /MSIE\s7/.test(navigator.userAgent);

if (window.isIE) {
	document.write('<style type="text/css">\n');
	document.write('#bottomBar ul.thumbnails li a img {\n');
	document.write('	filter:alpha(opacity=10);\n');
	document.write('}\n');
	document.write('#bottomBar ul.thumbnails li a.selected img, #bottomBar ul.thumbnails li a.selected:hover img {\n');
	document.write('	filter:alpha(opacity=100);\n');
	document.write('}\n');
	document.write('#bottomBar ul.thumbnails li a:hover img {\n');
	document.write('	filter:alpha(opacity=50);\n');
	document.write('}\n');
	document.write('</style>\n');
}
document.write('<style type="text/css">.thumbnails img { visibility: hidden }</style>');
document.write('<style type="text/css">.thumbnails a img { visibility: visible }</style>');

var gm = null;

window.addEvent('load', function() {
	new IEMenu($E('#topBar ul'));

	// get the root path
	var path = '';
	$A(document.getElementsByTagName('script')).each(function (s) {
		if (s.src.match(/js\/lightbown\.js$/)) {
			path = s.src.replace(/js\/lightbown\.js$/, '');
		}
	});

	// create the wrapper and flascontent divs
	new Element('div', {id: 'flashcontent'}).injectInside(new Element('div', {id: 'wrapper'}).injectInside(document.body));

	gm = new JPGalleryManager(path, /lightbox\.html$/.test(window.location.href));
	var sm = new jpSlideMenu($E('ul.thumbnails'), $('prev'), $('fwrd'), {duration: 500, wait: false, transition: Fx.Transitions.linear});
});

function flashSwapping() {
	$('flashcontent').setStyles({
		background: gm.links[gm.selected].getElement('img').getStyle('background-color')
	});
}

var IEMenu = new Class({
	initialize: function (ul) {
		this.isIE = /MSIE/.test(navigator.userAgent);
		this.isIE7 = /MSIE\s7/.test(navigator.userAgent);
		if (!this.isIE || this.isIE7) {
			return;
		}
		ul.getChildren().each(function (el) {
			el.addEvent('mouseover', function () { $(this).addClass('sfhover'); });
			el.addEvent('mouseout', function () { $(this).removeClass('sfhover'); });
		}, this);
	}
});

var jpSlideMenu = new Class({
	element: null,
	prev: null,
	next: null,
	width: 0,
	pages: 0,
	current: 0,
	moving: false,
	options: {
		onStart: Class.empty,
		onComplete: Class.empty
	},
	initialize: function (element, prev, next, options) {
		this.setOptions(options);

		// find the widths
		var width = 0;
		element.getChildren().each(function (e) {
			var widths = e.getStyles('margin-left', 'margin-right');
			for (var property in widths) {
				width += isNaN(parseInt(widths[property])) ? 0 : parseInt(widths[property]);
			}
			width += e.getSize().size.x;
		});

		var el = new Element('div', {styles: {
			width: width,
			position: 'absolute',
			top: 0,
			left: 0
		}}).injectAfter(element);
		element.remove();
		element.injectInside(el);

		this.element = el;
		this.prev = prev;
		this.next = next;
		this.width = this.element.getParent().getSize().size.x;

		options = options || {};
		options.onStart = this.onStart.bind(this);
		options.onComplete = this.onComplete.bind(this);
		this.fx = new Fx.Styles(this.element, options);

		this.pages = Math.ceil(width / this.width);
		this.current = 1;


		this.pagelinks = [];
		var pagenav = new Element('ul', {
			'class': 'pagenav',
			styles: {
				visibility: 'hidden'
			}
		}).injectInside(this.element.getParent());

		var width = 0;
		for (var i = 1; i <= this.pages; i++) {
			var li = new Element('li', i == 1 ? {'class': 'first'} : {}).injectInside(pagenav);
			var link = new Element('a', {
					href: '#' + i,
					'class': i == 1 ? 'selected' : ''
				}
			).setText(i).addEvent('click', function (evt, num) {
				evt.stop();
				this.show(num);
			}.bindWithEvent(this, i)).injectInside(li);

			this.pagelinks.push(link);

			var widths = li.getStyles('margin-left', 'margin-right');
			for (var property in widths) {
				width += isNaN(parseInt(widths[property])) ? 0 : parseInt(widths[property]);
			}
			width += li.getSize().size.x;
		}
		pagenav.setStyles({
			left: (this.width - width) / 2,
			visibility: 'visible'
		})

		this.prev.addEvent('click', function(evt) {
			new Event(evt).stop();
			this.back();
		}.bind(this));

		this.next.addEvent('click', function(evt) {
			new Event(evt).stop();
			this.forward();
		}.bind(this));
	},
	onStart: function () {
		this.moving = true;
		this.pagelinks.each(function (e, i) {
			e.removeClass('selected');
			if (i + 1 == this.current) {
				e.addClass('selected');
			}
		}.bind(this));

		this.fireEvent('onStart', this.current, 10);
	},
	onComplete: function () {
		this.moving = false;
		this.fireEvent('onComplete', this.current, 10);
	},
	back: function () {
		this.show(this.current - 1);
	},
	forward: function () {
		this.show(this.current + 1);
	},
	show: function (page) {
		if (page < 1 || page > this.pages || this.moving) {
			return;
		}

		this.current = page;
		this.fx.start({
			left: ((this.current - 1) * -this.width)
		})
	}
});
jpSlideMenu.implement(new Events, new Options);

var JPGalleryManager = new Class({
	path: '',
	gallery: null,
	links: [],
	selected: 0,
	addRemoveButton: null,
	overlayContent: null,
	initialize: function (path, view) {
		// view is whether we are viewing the lightbox or not
		this.view = view;
		this.path = path;
		this.gallery = new JPGallery(this.path);

		window.addEvent('resize', this.gallery.resize.bind(this.gallery));

		/*
		var ul = new Element('ul', {'class': 'lightboxButtons'}).injectInside('bottomBar');

		// add the fashion shoot button
		var el = new Element('a', {href: '#'}).setText('Fullscreen');
		this.fullScreenButton = new Element('li').injectInside(ul).appendChild(el);
		el.addEvent('click', function (evt) {
			evt.stop();
			window.moveTo(0, 0);
			window.resizeTo(screen.availWidth, screen.availHeight);
		}.bindWithEvent(this));


		// add the project info button
		var el = new Element('a', {href: '#'}).setText('Show Project Info');
		this.projectInfoButton = new Element('li').injectInside(ul).appendChild(el);
		el.addEvent('click', function (evt) {
			evt.stop();
			if (this.overlayContent == 'projectInfo') {
				this.hideInfo();
			}
			else {
				this.showInfo();
			}
		}.bindWithEvent(this));

		if (!this.view) {
			// add to lightbox button
			var el = new Element('a', {href: '#'}).setText('Add to Lightbox');
			this.addRemoveButton = new Element('li').injectInside(ul).appendChild(el);
			el.addEvent('click', function (evt) {
				evt.stop();
				this.add();
				var c1 = this.addRemoveButton.getStyle('background-color');
				var c2 = '#ffffff';
				this.addRemoveButton.setStyle('background-color', c2);
				var fx = new Fx.Styles(this.addRemoveButton, { duration: 300, onComplete: function () {
					this.addRemoveButton.setStyle('background-color', '');
				}.bind(this)});
				fx.start({ 'background-color': c1 });
			}.bindWithEvent(this));
		}
		else {
			// viewing lightbox

			// clear the thumbnails list
			$E('ul.thumbnails').empty();

			// get all the thumbnails
			this.gallery.items.each(function (item) {
				new Element('img', {src: item.thumb, styles: {background: item.background || 'transparent'}}).injectInside(
					new Element('li').injectInside($E('ul.thumbnails'))
				);
			}, this);

			var el = new Element('a', {href: '#'}).setText('Remove from Lightbox');
			this.addRemoveButton = new Element('li').injectInside($E('ul.lightboxButtons')).appendChild(el);
			el.addEvent('click', function (evt) {
				evt.stop();
				this.remove();
				var c1 = this.addRemoveButton.getStyle('background-color');
				var c2 = '#ffffff';
				this.addRemoveButton.setStyle('background-color', c2);
				var fx = new Fx.Styles(this.addRemoveButton, { duration: 300, onComplete: function () {
					this.addRemoveButton.setStyle('background-color', '');
				}.bind(this)});
				fx.start({ 'background-color': c1 });
			}.bindWithEvent(this));

			if (this.gallery.items.length == 0) {
				this.overlayContent == 'projectInfo';
				this.showInfo();
			}
		}
		*/

		var thumbnails = $ES('ul.thumbnails img');

		thumbnails.each(function (e) {
			var p = e.parentNode;
			var el = new Element('a', {href: '#'}).injectInside(p);
			p.removeChild(e);
			p.appendChild(el);
			el.appendChild(e);
			this.links.push(el);
		}, this);

		this.links.each(function (e, i) {
			e.addEvent('click', function (evt) {
				evt.stop();
				this.select(e);
			}.bindWithEvent(this));
		}, this);

		if (this.links.length > 0) {
			this.select(this.links[0]);
		}

		// pages not to be followed directly
		$ES('a.nolink').each(function (el) {
			el.addEvent('click', function (evt, el) {
				evt.stop();
				this.showCopy(el.href);
			}.bindWithEvent(this, el));
		}, this);
	},
	showInfo: function () {
		this.showOverlay();
		this.projectInfoButton.setText('Hide Project Info');
		if (this.view && this.links[this.selected]) {
			var extCopy = new Element('div', {id: 'extCopy'}).injectInside($('copy').getParent());
			this.gallery.showCopy(this.links[this.selected].getElement('img').src, 'copy', 'extCopy');
			this.overlayContent = 'extCopy';
		}
		else {
			//this.overlay = new Element('div', { id: 'overlay', styles: { opacity: 0.8 }}).injectInside($('copy').getParent());
			$('copy').setStyle('display', 'block');
			this.overlayContent = 'projectInfo';
		}
	},
	hideInfo: function () {
		this.projectInfoButton.setText('Show Project Info');
		$('copy').setStyle('display', 'none');
		this.overlayContent = null;
		this.overlay.remove();
		this.overlay = null;
	},
	select: function (el) {
		this.links.each(function (e, i) {
			e.removeClass('selected');
			if (e == el) {
				this.selected = i;
				el.addClass('selected');
			}
		}, this);
		var img = el.getElement('img');
		var src = img.src;
		//this.gallery.showImage(src.replace('/thumbs', ''));
		this.gallery.showImage(src.replace('/images/thumbs', '/flash/contents').replace('.jpg', '.swf'));
	},
	add: function () {
		if ((this.links.length + 1) >= this.limit) {
			return;
		}
		var img = this.links[this.selected].getElement('img');
		this.gallery.add({
			thumb: img.src,
			page: window.location.href,
			background: img.getStyle('background-color')
		});
	},
	remove: function () {
		var el = this.links[this.selected];
		if (!el) {
			return;
		}
		var img = this.links[this.selected].getElement('img');
		this.gallery.remove({
			thumb: img.src,
			page: window.location.href,
			background: img.getStyle('background-color')
		});
		el.getParent().remove();
		this.links.remove(el);
		this.selected--;
		if (this.selected < 0) {
			this.selected = 0;
		}
		if (this.links.length > 0) {
			this.select(this.links[this.selected]);
		}
		else {
			this.gallery.showImage();
			this.showInfo();
		}
	},
	showCopy: function (url) {
		this.showOverlay();
		var extCopy = new Element('div', {id: 'extCopy'}).injectInside($('copy').getParent());
		this.gallery.getCopy(url, 'copy', 'extCopy');
		this.overlayContent = 'extCopy';
	},
	hideCopy: function () {
		if ($('extCopy')) $('extCopy').remove();
		this.overlayContent = null;
		this.overlay.remove();
		this.overlay = null;
	},
	showOverlay: function () {
		this.hideOverlay();
		this.overlay = new Element('div', { id: 'overlay', styles: { opacity: 0.8 }}).injectInside(document.body);
		this.overlay.addEvent('click', function (evt) {
			evt.stop();
			this.hideOverlay();
		}.bindWithEvent(this));
	},
	hideOverlay: function () {
		switch (this.overlayContent) {
			case 'projectInfo':
				this.hideInfo();
				break;
			case 'extCopy':
				this.hideCopy();
				break;
		}
	}
});

var JPGallery = new Class({
	max: 12,
	cookieduration: 30,
	cookiename: 'jplightbox',
	hash: null,
	items: [],
	path: '',
	movieId: 'flashbg',
	initialize: function (path) {
		this.path = path;
		this.hash = new Hash.Cookie(this.cookiename, {duration: this.cookieduration, path: '/' });
		this.items = this.hash.get('items') || [];
	},
	add: function (o) {
		var match = false;
		this.items.each(function (i) {
			if (i.thumb == o.thumb) {
				match = true;
			}
		}, this);
		if (!match) {
			if (this.items.length >= this.max) {
				// remove the first item from the array
				this.items = this.items.copy(1);
			}
			this.items.push(o);
			this.hash.set('items', this.items);
		}
	},
	remove: function (o) {
		var temp = [];
		this.items.each(function (i) {
			if (i.thumb != o.thumb) {
				temp.push(i);
			}
		}, this);
		this.items = temp;
		this.hash.set('items', this.items);
	},
	showCopy: function (thumb, id, newId) {
		var item = null;
		this.items.each(function (o, i) {
			if (o.thumb == thumb) {
				item = o;
			}
		}, this);
		if (!item) {
			return;
		}
		this.getCopy(item.page, id, newId);
	},
	getCopy: function (url, id, newId) {
		//this.loadedUrls = this.loadedUrls || [];

		if (!newId) newId = id;
		$(newId).setText('');
		new Ajax(url, {
			method: 'get',
			onComplete: function (response) {
				var regex = new RegExp('<div id="' + id + '">([\\s\\S]*?)<\\/div>', 'gim');
				var matches = regex.exec(new String(response));
				if (matches) {
					$(newId).setHTML(matches[1]);
				}
			}
		}).request();
	},
	resize: function() {
		var h = $('wrapper').getSize().size.y - 198;
		$('flashcontent').setStyle('height', h);
		if (window.isIE6) {
			var movie = this.getFlashMovieObject(this.movieId);
			movie.style.height = h + 'px';
		}
	},
	showImage: function (src, background) {
		if (!src) {
			$('flashcontent').setHTML('');
			return;
		}
		if (this.getFlashMovieObject(this.movieId) == null) {
			var h = $('wrapper').getSize().size.y - 198;
			$('flashcontent').setStyles({
				'height': h
			});

			var so = new SWFObject(this.path + 'flash/' + this.movieId + '.swf', this.movieId, '100%', '100%', '8', background);
			so.addParam('wmode', 'transparent');
			so.addVariable('bg', src);
			so.useExpressInstall(this.path + 'flash/expressinstall.swf');
			so.write('flashcontent');
		}
		else {
			var movie = this.getFlashMovieObject(this.movieId);
			movie.SetVariable('/:bg', src);
			//movie.GotoFrame(2);
			movie.GotoFrame('10');
			//movie.GotoAndPlay('loadpic');
		}
	},
	getFlashMovieObject: function (movieName) {
		if (window.document[movieName]) {
			return window.document[movieName];
		}
		if (window.isIE && document.embeds && document.embeds[movieName]) {
			return document.embeds[movieName];
		}
		else if ($(movieName)){
			return $(movieName);
		}
		return null;
	}
});

