$(function() {
	
	var gallery = {
		throbber: $('#li').throbber(),
		ssp: new SSP('/ssp_director/images.php?gallery=1&w=948&h=573&s=0&q=80&sh=1&tw=100&th=100&ts=0&tlw=20&tlh=20&tq=60&tsh=1&pw=40&ph=0&aps=0'),
		flipper: null,
		resizeTimeout: null,
		allPhotos: [],
		randomPhotos: [],
		special: [ 'random', 'about', 'contact', 'clients', 'login' ],
		aboutPage: 1
		};
	
	showLoading();
	
	$('#about_more').click(onAboutMore);
	$('#login_field').keypress(onLoginType);
	
	$('#mc').outerGlow({ src: 'images/content_shadow_%d.png', size: 50, offset: '25 28 26 25' });
	$('#glow').innerGlow({ src: 'images/body_shadow_%d.gif', size: 50 });
	
	gallery.numSpecial = gallery.special.length;
	gallery.specialHash = {};
	gallery.specialElements = {};
	for(var i = 0; i < gallery.numSpecial; i++) {
		gallery.specialHash[gallery.special[i]] = i;
		gallery.specialElements[gallery.special[i]] = $('#page_'+gallery.special[i]);
		}
	$('#page_gallery').empty();
	
	gallery.ssp.setOnload(onSSPLoad);
		
	$('#prev').click(onPrev);
	$('#next').click(onNext);
	
	
	
	if(!$.browser.safari) {
		setupResize();
		}
	
	function setupResize() {
		$(window).resize(onResize);
		onResize();
		}
	
	function resizeHandler() {
		if($(document).width() < 1050) {
			$('body').addClass('mini');
			}
		else {
			$('body').removeClass('mini');
			}
		
		if($(document).width() > 1200 && $(window).height() > 960) {
			$('body').addClass('mega');
			
			// max out #glow
			$('#glow').width(1200).height(880);
			
			// center #glow in viewport
			$('#glow').css('left', Math.round( ($(window).width() - 1200)/2 )+'px');
			$('#glow').css('top', Math.round( ($(window).height() - 960)/2 )+'px');
			}
		else {
			$('body').removeClass('mega');
			
			// cling #glow to viewport
			$('#glow').css('left',0).css('top',0);
			$('#glow').width($(window).width() < 830 ? 830 : $(window).width());
			$('#glow').height($(window).height() < 670 ? 670 : $(window).height());
			}
		
		// center #mt in #glow
		$('#mt').css('left', Math.round( ($('#glow').outerWidth() - $('#mt').outerWidth()) / 2 )+'px');
		$('#mt').css('top', Math.round( ($('#glow').outerHeight() - $('#mt').outerHeight()) / 2 )+'px');
		
		}
	
	function onResize() {
		resizeHandler();
		if(gallery.resizeTimeout !== null) {
			clearTimeout(gallery.resizeTimeout);
			gallery.resizeTimeout = null;
			}
		gallery.resizeTimeout = setTimeout(resizeHandler, 100);
		}
	
	function onSSPLoad() {
		build();
			$('#ht a').click(function() {
				onHistoryChange(this.href.substr(this.href.indexOf('#')+1));
				return false;
				});
			onHistoryChange(window.location.hash.substr(window.location.hash.indexOf('#')+1));
// 		$.historyInit(onHistoryChange);
		hideLoading();
		if($.browser.safari) {
			setTimeout(setupResize, 0);
			}
		}

	function build() {
		$.each(gallery.ssp.albums, function() {
			var album = this;
			
			if(album.title == 'random') {
				gallery.randomPhotos = album.images;
				}
			else {
				// extract menu name, menu item name
				var name = album.title.split('|');
				if(name.length == 1) name.push(name[0]);
				
				// set marker for where this menu item will link
				var albumIndex = gallery.allPhotos.length+gallery.numSpecial;
				
				// add these photos to the list
				for(var i = 0; i < album.images.length; i++) {
					gallery.allPhotos.push({
						'albumIndex': albumIndex,
						'albumTitle': name[1],
						'image': album.images[i],
						'total': album.images.length,
						'num': i
						});
					}
				
				// try to find this menu by name
				var menu = $('#navt td[@menuname='+name[0]+']');
				
				// make and add the menu if not found
				if(!menu.length) {
					var menu = $('<td><div class="container"><div class="menu"><table class="layout"></table></div><a></a></div></td>');
					menu.attr('menuname', name[0]);
					var link = $('a', menu[0])
					link.attr('href', '#'+escape(albumIndex));
					link.text(name[0]);
					menu.appendTo('#navt > tbody > tr');
					}
				
				// make and add the menu item
				var submenu = $('<tr><td><a></a></td></tr>');
				var link = $('a', submenu[0]);
				link.attr('href', '#'+escape(albumIndex));
				link.text(name[1]);
				$('table', menu[0]).append(submenu);
				}
			});
		
		// apply .first class to every first <td> and <a>
		$('#navt td:first-child, #navt table td:first-child a').addClass('first');
		
		// attach events
		$('#navt, #navt td').hover(onMenuOver, onMenuOut);
		$('#navt a').click(onMenuClick);
		
		// build flipper
		$('#mc ul').flipper({
			at: null,
			num: gallery.allPhotos.length + gallery.numSpecial,
			animateOutSpeed: 200,
			animateInSpeed: 1000,
			loadItemHandler: onMakeFlipperItem,
			initHandler: onInitFlipper,
			beforeChangeHandler: onPhotoChange,
			afterChangeHandler: onAfterPhotoChange,
			startLoadingHandler: showLoading,
			stopLoadingHandler: hideLoading
			});
		
		}
	
	function showLoading() {
		gallery.throbber.show();
		}
	
	function hideLoading() {
		gallery.throbber.hide();
		}
	
	function onMenuOver() {
		var self = this;
		var undef;
		if(this.menutimer !== undef) clearTimeout(this.menutimer);
		this.menutimer = setTimeout(function() { self.menutimer = undef; $(self).addClass('hover'); }, 100);
		}
	
	function onMenuOut() {
		var self = this;
		var undef;
		if(this.menutimer !== undef) clearTimeout(this.menutimer);
		this.menutimer = setTimeout(function() { self.menutimer = undef; $(self).removeClass('hover'); }, 200);
		}
	
	function onMenuClick() {
		var href = $(this).attr('href');
		var id = unescape(href.substr(href.lastIndexOf('#')+1));
		if(gallery.flipper) gallery.flipper.go(id);
		return false;
		}
	
	function onAfterPhotoChange(oldN, newN) {
		$('#mc').css('background', 'white');
		}
	
	function onPhotoChange(oldN, newN) {
		var firstTime = oldN == null;
		var specialChange = firstTime || oldN < gallery.numSpecial != newN < gallery.numSpecial;
		var specialMode = newN < gallery.numSpecial;
		
		if(specialChange) {
			if(specialMode) {
				// go into special mode
				$('#navt td, #navt a').removeClass('active');
				$('body').addClass('nonumbers');
				$('#an').text('');
				}
			else {
				// go into gallery mode
				$('#ht a').removeClass('active');
				$('body').removeClass('nonumbers');
				}
			}
		if(specialMode) {
			var newHash = gallery.special[newN];
// 			if(window.location.hash != '#'+newHash) window.location.hash = newHash;
			$('#ht a').removeClass('active');
			$('#ht a[@href$=#'+newHash+']').addClass('active');
			}
		else {
			var galleryChange = firstTime || specialChange || gallery.allPhotos[oldN-gallery.numSpecial].albumIndex != gallery.allPhotos[newN-gallery.numSpecial].albumIndex;
			if(galleryChange) {
				window.setTimeout(function() { // deferring the change like this avoids an odd animation glitch in firefox
					$('#an').text(gallery.allPhotos[newN-gallery.numSpecial].albumTitle);
					selectMenu(gallery.allPhotos[newN-gallery.numSpecial].albumIndex);
					updateDigits('total', gallery.allPhotos[newN-gallery.numSpecial].total);
					}, 0);
				}
			updateDigits('current', gallery.allPhotos[newN-gallery.numSpecial].num+1);
// 			if(window.location.hash != '#'+newN) window.location.hash = newN;
			}
		}
	
	function onLoginType(e) {
		if(e.keyCode == 13) {
			window.open('http://www.douglaslevere.com/clients/'+escape($('#login_field')[0].value), '_blank', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=800,height=700');
			}
		}
	
	function onAboutMore() {
		$('.about_text').hide();
		gallery.aboutPage++;
		if($('#about_page_'+gallery.aboutPage).length) {
			$('#about_page_'+gallery.aboutPage).show();
			if($('#about_page_'+(gallery.aboutPage+1)).length) {
				$('#about_more').text('more >');
				}
			else {
				$('#about_more').text('< back');
				}
			}
		else {
			gallery.aboutPage = 1;
			$('#about_page_1').show();
			$('#about_more').text('more >');
			}
		return false;
		}
	
	function onInitFlipper() {
		gallery.flipper = this;
		}
	
	function onHistoryChange(index) {
		if(!String(index).length) index = 'random';
		if(parseInt(index) != index) index = gallery.specialHash[index];
		if(gallery.flipper) gallery.flipper.go(index);
		}
	
	function selectMenu(id) {
		$('#navt td, #navt a').removeClass('active');
		var el = $('#navt .menu a[@href$=#'+escape(id)+']');
		el.addClass('active');
		el.parents().filter('td').eq(1).addClass('active');
		}
	
	function onNext() {
		if(gallery.flipper) {
			if(gallery.flipper.at() == gallery.flipper.num()-1) {
				gallery.flipper.go(gallery.numSpecial);
				}
			else if(gallery.flipper.at() < gallery.numSpecial) {
				gallery.flipper.go(gallery.numSpecial);
				}
			else {
				gallery.flipper.next();
				}
			}
		return false;
		}

	function onPrev() {
		if(gallery.flipper) {
			if(gallery.flipper.at() == gallery.numSpecial) {
				gallery.flipper.go(gallery.flipper.num()-1);
				}
			else if(gallery.flipper.at() < gallery.numSpecial) {
				gallery.flipper.go(gallery.numSpecial);
				}
			else {
				gallery.flipper.prev();
				}
			}
		return false;
		}

	function updateDigits(group, value) {
		if(String(value).length < 2) value = '0'+value;
		if(group == 'total') {
			$('#numbers_total, #numbers_total2').html(value);
			}
		else {
			$('#numbers_counter, #numbers_counter2').html(value);
			}
		}
	
	function onMakeFlipperItem(n) {
		if(n < gallery.numSpecial) {
			var name = gallery.special[n];
			if(name == 'random') {
				var content = $('<li class="gallery_image" style="display: none"><img width="752" height="476" /></li>');
				if(gallery.randomPhotos.length) {
					var i = gallery.randomPhotos[Math.floor(Math.random()*gallery.randomPhotos.length)];
					content.find('img').attr('src', i.src);
					}
				return content;
				}
			else {
				return gallery.specialElements[name];
				}
			}
		else {
			n = n-gallery.numSpecial;
			var i = gallery.allPhotos[n].image;
			var c = String(i.caption).split(/\|/);
			
			function makeCaptionPart(s) {
				if(!s) return [];
				var l = s.indexOf("[");
				var r = s.indexOf("]");
				if(l == 0 && r > 0) {
					var el = $('<b></b>');
					el.text(s.substr(1,r-1));
					return [el].concat(makeCaptionPart(s.substr(r+1)));
					}
				else {
					var el = $('<span></span>');
					el.text(l>=0 ? s.substr(0,l) : s);
					return [el].concat(makeCaptionPart(l>=0 ? s.substr(l) : ''));
					}
				}
			
			function makeCaption(s) {
				var l = makeCaptionPart(s);
				var el = $('<span></span>');
				for(var x = 0; x < l.length; x++) {
					el.append(l[x]);
					}
				return el;
				}
			
			var caption = $('<div class="caption"></div>');
			if(c.length == 2) {
				var left = makeCaption(c[0]);
				left.attr('class', 'left');
				caption.append(left);
				var right = makeCaption(c[1]);
				right.attr('class', 'right');
				caption.append(right);
				}
			else {
				var full = makeCaption(c[0]);
				full.attr('class', 'full');
				caption.append(full);
				}
		
			var content = $('<li class="gallery_image"><img width="752" height="476" /></li>');
			if(caption.text()) content.append(caption);
			content.find('img').attr('src', i.src)
			if(i.link) {
				content.find('img').click(function(){window.location = i.link}).css('cursor', 'pointer');
				}
			if($.browser.msie)
				content.hover(function(){$(this).addClass('hover')}, function(){$(this).removeClass('hover')});
	
			return content;
			}
		}
	});


