var preloadQueue = Array();
var preloadImages = Array();
var slider, galleryTw;
var galleryHolder, gallerySlider, galleryThumbs, galleryNav;

function init(alreadyIn) {
	galleryHolder = $('galleryHolder');
	gallerySlider = $('gallerySlider');
	galleryThumbs = $('galleryThumbs');
	galleryNav = $('galleryNav');
	if(galleryHolder)	setupGallery(galleryHolder, alreadyIn);
	if(!alreadyIn) fade_in($('content'));
}
function setupGallery(galleryHolder, alreadyIn) {
	if(!slider) slider = new Slider(gallerySlider, false, 0);

	if(gallerySlider.offsetLeft+gallerySlider.offsetWidth < getWinWidth()) 
		gallerySlider.style.marginLeft = ((gallerySlider.offsetWidth-getWinWidth())*-1)+'px';	// window wider than scroll with offset

	// setup key strokes
	function checkGalleryKeys(e) {
		var e = e ? e : window.event;

		var to = false; 

		if(projectLB && projectLB.offsetWidth) {
			switch(e.keyCode) {
				case 37:		projectLB.getPrevious();break;
				case 39: case 13: 	projectLB.getNext(); 	break;
				case 27:		projectLB.close();	break;
			}
		} else {
			switch(e.keyCode) {
				case 37:	// left
					to = parseInt(gallerySlider.style.marginLeft) + gallerySlider.firstChild.offsetWidth;
					break;
				case 39:	// right
					to = parseInt(gallerySlider.style.marginLeft) - gallerySlider.firstChild.offsetWidth;
					break;
				case 34:	// page down
					to = parseInt(gallerySlider.style.marginLeft) - getWinWidth();
					break;
				case 33:	// page up
					to = parseInt(gallerySlider.style.marginLeft) + getWinWidth();
					break;
			}
			if(to!==false) {
				var max = gallerySlider.offsetWidth*-1+getWinWidth()*2;
				var max = gallerySlider.offsetWidth*-1+getWinWidth()*1;

				if(to > 0)	to = 0;
				if(to < max)	to = max;
				if(galleryHolder.tween)	galleryHolder.tween.stop(false, true);
				galleryHolder.tween = new Tween(gallerySlider, 'marginLeft', 'out.normal', gallerySlider.style.marginLeft, to, .4, true);
				galleryHolder.tween.onchange = function(pos) { galleryHolder.onchange(); }
			}
		}
	}
	addEventHandler(window, 'keyup', checkGalleryKeys);

	// setup mouse over items
	function toggleSlideProp(fadeTo, ignore, prop) {
		var anyTw;
		for(var i in slider.slides) {
			var slide = slider.slides[i];
			if(slide.style) {
				var obj = slide[prop];
				if(slide!=ignore) {
					if(slide.objTw)	slide[prop+'Tw'].stop();
					anyTw = slide[prop+'Tw'] = new Tween(obj, 'alpha', false, obj.style.opacity?obj.style.opacity:1, fadeTo, .3, true, 30);
				}
			}
		}
		return anyTw;
	}
	for(var k in slider.slides) {
		slider.slides[k].indx = k;
		if(slider.slides[k].firstChild) {
			slider.slides[k].overlay = slider.slides[k].firstChild;
			slider.slides[k].overlay.style.opacity = 1;
			slider.slides[k].details = slider.slides[k].firstChild.childNodes[1];
			slider.slides[k].details.style.opacity = 0;
			slider.slides[k].details.firstChild.onclick = function() { this.parentNode.onclick(); }
			slider.slides[k].preview = slider.slides[k].childNodes[1].firstChild;
			slider.slides[k].preview.style.opacity = 1;
		}

		slider.slides[k].onmouseover = function(e) { 
			if(galleryHolder.suspendMvmt)	return;
			if(!e)	e = window.event;
			this.className = this.className + ' hover';
			this.over = true;
			
			var previewTw = toggleSlideProp(.2, this,  'preview');
			toggleSlideProp(0, this, 'overlay');
			toggleSlideProp(0, this,  'details');

			if(this.overlayTw)	this.overlayTw.stop();
			if(this.detailsTw)	this.detailsTw.stop();

			var o = this;
			this.overlayTw = new Tween(this.overlay, 'alpha', false, this.overlay.style.opacity, 1, .5, true, 10);
			this.overlayTw.onstop = function() { 
				var obj = this.obj.parentNode;
				obj.detailsTw = new Tween(obj.details, 'alpha', false, obj.details.style.opacity, 1, .5, true, 10);
			}
		}
		slider.slides[k].onmouseout = function() { 
		}
	}
	//var maxSpeed = 5000;
	var maxSpeed = 3000;		// with faster transition tweens
	var deadPercent = .40;
	var tolerance = .1;
	var lastChild = galleryHolder.firstChild.childNodes[galleryHolder.firstChild.childNodes.length-1];
	var distance = lastChild.offsetWidth + lastChild.offsetLeft - galleryHolder.offsetWidth - 20;
	var fullDistance = distance + 20 + parseFloat(galleryHolder.firstChild.style.marginLeft)*-1;
	galleryHolder.firstChild.style.width = fullDistance+galleryHolder.offsetWidth+'px';

	galleryHolder.checkItemHover = function() {
		var orig = galleryHolder.firstChild.overIndx;
		for(var i in galleryHolder.firstChild.childNodes) {
			if(isOver(galleryHolder.firstChild.childNodes[i]) && i!=galleryHolder.firstChild.overIndx) {
				galleryHolder.firstChild.childNodes[i].onmouseover();
				galleryHolder.firstChild.overIndx = i;
			}
		} 
	}

	galleryHolder.onmouseover = function() {
		this.className = this.className + ' hover';
		this.intervalCheck = setInterval(this.checkItemHover, 200);
	};
	galleryNav.onmouseover = function() { galleryHolder.onmouseover(); }
	galleryHolder.priorPerc = 0;
	galleryHolder.onmousemove = function(e) {
		if(this.suspendMvmt)	return;
		var debug = false;
		if(!e)	e = window.event;
		var x = (mousePos ? mousePos.x : 0) - Left(this);
		var posPerc = x / this.offsetWidth;
	
		if(posPerc<deadPercent || posPerc>1-deadPercent) {	// not in center (dead area)
			var distance = posPerc > .5 ? parseFloat(fullDistance) + parseFloat(this.firstChild.style.marginLeft) : parseFloat(this.firstChild.style.marginLeft)*-1;
			if(distance == 0)	return;
			posPerc = posPerc > .5 ? (posPerc-(1-deadPercent))/(deadPercent*2)+.5 : posPerc*.5 / deadPercent;
			var speed = maxSpeed*(posPerc>.5?posPerc-0.5:0.5-posPerc);
			var duration = distance/speed;

			if(!this.tween || (posPerc!=this.priorPerc) && (Math.abs(posPerc-this.priorPerc) > tolerance) && duration) {
				if(debug)	trace('changing % to '+posPerc+' change of '+Math.abs(posPerc-this.priorPerc)+ " ("+posPerc+"-"+this.priorPerc+")", false);

				var to = posPerc>.5 ? fullDistance*-1 : 0;
				if(this.tween && (this.priorPerc-.5)*(posPerc-.5)>0) {
					this.tween.changeDuration(duration);
				} else {
					if(this.tween)	this.tween.stop(false, true);
					this.tween = new Tween(this.firstChild, 'marginLeft', 'out.normal', this.firstChild.style.marginLeft, to, duration, true);
					this.tween.onchange = function(pos) { this.obj.parentNode.onchange(); }
					this.tween.onstop = function() { 
						if(posPerc<.5)	$('galleryMoveRight').style.display = 'none';
						else 		$('galleryMoveLeft').style.display = 'none';
					}
				}

				this.priorPerc = posPerc;
				$('galleryMoveRight').style.display = posPerc>.5?'block':'none';
				$('galleryMoveLeft').style.display = posPerc>.5?'none':'block';
			}
		} else if(this.tween) {
			this.tween.stop(true);
			this.tween = false;
		}
	}
	galleryHolder.onchange = function() {
		if(this.suspendMvmt)	return;
		var slider = this.firstChild;
		setThumbPerspectives(slider);
		setScroll($('galleryScroll'), (parseFloat(slider.style.marginLeft)*-1) / (slider.offsetWidth-this.offsetWidth));
		var orig = slider.overIndx;
		for(var i in slider.childNodes) {
			var obj = slider.childNodes[i];
			if(isOver(obj) && (i!=slider.overIndx)) {
				obj.onmouseover();
				slider.overIndx = i;
			}
		}
		if(parseInt(gallerySlider.style.marginLeft)==0) 
			$('galleryMoveLeft').style.display='none';
		if(parseInt(gallerySlider.style.marginLeft)<=(gallerySlider.offsetWidth*-1+getWinWidth())) 
			$('galleryMoveRight').style.display='none';
		if(orig!=undefined && orig!=slider.overIndx && slider.childNodes[orig])	slider.childNodes[orig].onmouseout();
	}
	galleryHolder.onmouseout = function(e) {
		if(!e)	e = window.event;
		if(!e || (e.relatedTarget==null) || (!isAncestor(e.relatedTarget, this))) {
			this.className = this.className.replace(/hover/g, '');
			if(this.tween) {
				this.tween.stop(true);
				this.tween = false;
			}
			$('galleryMoveRight').style.display='none';
			$('galleryMoveLeft').style.display='none';

			if(this.firstChild.childNodes[this.firstChild.overIndx]) 
				this.firstChild.childNodes[this.firstChild.overIndx].onmouseout();
			if(this.intervalCheck) {
				clearInterval(this.intervalCheck);
				this.firstChild.overIndx = false;
			}

			toggleSlideProp(1, false,  'overlay');
			toggleSlideProp(0, false,  'details');

			for(var i in slider.slides) {
				if(slider.slides[i].className) 
					slider.slides[i].className = slider.slides[i].className.replace(/hover/g, '');
				slider.slides[i].over = false;
			}
		}
	}
	galleryHolder.moveTo = function(px, time) {
		if(this.tween)	{
			this.tween.stop(false,false);
			this.tween = false;
		}
		this.tween = new Tween(this.firstChild, 'marginLeft', 'out.normal', this.firstChild.style.marginLeft, px*-1, time, true);
		this.tween.onchange = function() { galleryHolder.onchange(); };
		return this.tween;
	}

	// nav hiding
	function toggleNav(on) {
		var navs = $('mainNav').childNodes;
		if(!window.navTw)	window.navTw = Array();
		for(var i in navs) {
			if(navs[i].id != _i && navs[i].style) {
				if(window.navTw[i]) {
					window.navTw[i].stop();
					window.navTw[i] = false;
				}
				window.navTw[i] = new Tween(navs[i], 'alpha', 'out.normal', navs[i].style.opacity==0?1:navs[i].style.opacity, on?1.1:0.4, .2, 1);
			}
		}
	}
	window.onmouseout = function() { toggleSlideProp(1, false, 'preview'); }
	window.onmouseleave = function() { toggleSlideOpacity(1, false, 'preview'); }
	$('header').onmouseout = function() { toggleNav(false); }
	$('header').onmouseover = function() { toggleNav(true); }
	$('header').onmouseout();

	$('galleryScroll').firstChild.style.width = ($('galleryScroll').offsetWidth*(galleryHolder.offsetWidth/gallerySlider.offsetWidth))+'px';
	$('galleryScroll').firstChild.onmousedown = function() { return false; };
	$('galleryScroll').onmousedown = function() {
		// turn all full color on
		toggleSlideProp(1, false, 'overlay');
		toggleSlideProp(1, false, 'preview');
		toggleSlideProp(0, false, 'details');
		galleryHolder.suspendMvmt = true;

		//galleryHolder.onmouseout(null);

		// move to position of click
		var to = ((mousePos.x-Left(this))/this.offsetWidth) * (gallerySlider.offsetWidth-galleryHolder.offsetWidth);
		var tw = galleryHolder.moveTo(to,.4);
		tw.onstop = function() { galleryHolder.suspendMvmt = false; };

		var max = this.offsetWidth-this.firstChild.offsetWidth;
		this.slide = function(to) { 
			galleryHolder.suspendMvmt = true;
			if(galleryHolder.tween) {
				galleryHolder.tween.stop(false,false);
				galleryHolder.tween = false;
			}
			if(!to) {
				to = mousePos.x - Left(this) - this.firstChild.offsetWidth/2; 
			}
			if(to<0)	to = 0;
			if(to>max) 	to = max;
			this.firstChild.style.marginLeft = to+'px';
			gallerySlider.style.marginLeft = to/max * (gallerySlider.offsetWidth-galleryHolder.offsetWidth)*-1+'px';
		}
		if(this.tout)	clearTimeout(this.tout);
		this.tout = setTimeout("$('galleryScroll').handler=addEventHandler(document, 'mousemove', function(){ $('galleryScroll').slide(); setThumbPerspectives($('gallerySlider'));});", 200);
		this.onmouseup = function() { 
			if(this.handler!=undefined) 	clearEventHandler(document, 'mousemove', this.handler); 
			if(this.tout)			clearTimeout(this.tout); 
			galleryHolder.suspendMvmt=false; 
		};

		document.onmouseup = function() { $('galleryScroll').onmouseup(); };
	};

	galleryHolder.onchange();
	window.onscroll = function(e, forceAtBottom) {
		$('footer').style.position = 'absolute';
		if((forceAtBottom!=true) && (Top($('bottomOfContent')) < getWinHeight()-40)) {
			$('footer').style.bottom='0px';// content is smaller than page, place at bottom
		} else {
			$('footer').style.position = 'relative';
			$('footer').style.bottom='';// content is larger than win, place default
		}
	}
	window.onresize = function() { init(true);window.onscroll(); }
	window.onscroll();


	// fade in the scroll bar seconds later
	if(!alreadyIn) setTimeout('fade_in($(\'galleryScroll\'));', 500);
}
function setThumbPerspectives(slider) {
	var debug = false;
	var holder = slider.parentNode;
	var w = holder.offsetWidth;
	var itemsPerScreen = w/slider.firstChild.offsetWidth;
	if(debug)	$('debug').innerHTML = '';
	for(var i in slider.childNodes) {
		var item = slider.childNodes[i];
		if(item.preview && Left(item)+item.offsetWidth > Left(holder) && Left(item) < Left(holder)+w) {	// in frame
			var thumbImg = item.preview.firstChild;
			var overImg = item.overlay.firstChild.firstChild;

			var percentIn = (item.offsetLeft+item.offsetWidth/2) / w;
			if(item.offsetLeft-slider.offsetLeft+20 < w/2) {				// make sure left most items can be fully visible
				percentIn+=.5;
			}
			thumbImg.style.marginLeft = (thumbImg.offsetWidth-item.offsetWidth)*-1*percentIn+'px';
			overImg.style.marginLeft = thumbImg.offsetLeft+'px';
		}
	}
}
function setScroll(scroll, perc) {
	scroll.firstChild.style.marginLeft = ((scroll.offsetWidth-scroll.firstChild.offsetWidth)*perc)+'px';
}
function moveGallery(indx) {
	slider.goto(indx);
}

