document.observe('dom:loaded', init);

Event.observe(window,'load', function() {
	updateDefaultOffsets();
	if ($('intro-nav')) {
		updateIntroOffset();
	}
	Event.observe(document.onresize ? document : window, 'resize', function() {
		updateDefaultOffsets();
		if ($('intro-nav')) {
			updateIntroOffset();
		}
	});
});
function db(a) {
	$('debug') ? $('debug').innerHTML += a +'<br />' : '';
}

function init() {

	// update screen size
	if (document.viewport.getHeight() > 900) {
//	if (document.viewport.getHeight() > 500) {
		db('large');
		_BASE_SCREEN = _SCREENSIZE_LARGE;
	}

	// update home graphic
	
	// initialize contact information shroud
	initContact();

	// initialize the homepage graphic (load graphic, resize, position)
	initIntro();

	// initialize navigation
	initNavigation();

	initGallery();

	initKeystrokes();

	initSlider();

	initZoomImages();
}

function initZoomImages() {
	// preload images
	for (var i=0; i<_ZOOM_COUNT; i++) {
		_ZOOM_CLOSE[i] = new Image();
		_ZOOM_CLOSE[i].src = _ZOOM_SRC_PREFIX+i+_ZOOM_SRC_SUFFIX;
	}
}
function initKeystrokes() {
	Event.observe(document, 'keyup', function(evt) {
		var kCode;

		// default event object
		if (!evt) {
			var evt = window.event;
		}

		// extract keycode
		kCode = evt.keyCode ? evt.keyCode : evt.which ? evt.which : null;

		// check direction
		if (kCode != null) {
			if (kCode == _KEY_CODE_LEFT) {
				pictureLeft();
			}
			else if (kCode == _KEY_CODE_RIGHT) {
				pictureRight();
			}
		}

	});
}
function initNavigation() {
	$$('div#header ul li a:not([rel*=inline])').each(function(e, index) {

		e.setAttribute('offset',index);

		if (e.getAttribute('target') != '_blank') {
			Event.observe(e, 'click', function(evt) {
				if (_ZOOMED) {
					zoomOut();
					setTimeout(function() {
						changePage(evt);
					}, 600);
				}
				else {
					changePage(evt);
				}
				
				// remove border
				// prevent default
				evt.stop();
			});
		}
	});
	Element.observe(document,'mousemove',function(evt) {
		if ($('arrow-left')) {
			if (!_MOUSE_TRACK_LOCK) {
				if (_ARROWS_HIDDEN) { // if the arrows are not hidden
					if (Event.pointerY(evt) > 50) { // past the top
						db('start anim');
						_ARROWS_HIDDEN = false;
						_MOUSE_TRACK_LOCK = true;
						var l = new Effect.Appear('arrow-left',{ duration: 0.3, queue: 'parallel' });
						var r = new Effect.Appear('arrow-right',{ duration: 0.3, queue: 'parallel' });
						var ls = new Effect.Appear('arrow-left-small',{ duration: 0.3, queue: 'parallel' });
						var rs = new Effect.Appear('arrow-right-small',{ duration: 0.3, queue: 'parallel' });
						var rs = new Effect.Appear('zoom',{ duration: 0.3, from: 0, to: 0.5, queue: 'parallel' });
						db('finished anim');
						setTimeout(function() {
							_MOUSE_TRACK_LOCK = false;
						}, 300);
					}
				}
				else if ((!$('arrow-left').visible())||(!$('arrow-right').visible())||(!$('arrow-left-small').visible())||(!$('arrow-right-small').visible())||(!$('zoom').visible())) {
					if (Event.pointerY(evt) > 50) { // past the top				
						_MOUSE_TRACK_LOCK = true;
						$('arrow-left').visible() ? '' : l = new Effect.Appear('arrow-left',{ duration: 0.3, queue: 'parallel' });
						$('arrow-right').visible() ? '' : r = new Effect.Appear('arrow-right',{ duration: 0.3, queue: 'parallel' });
						$('arrow-left-small').visible() ? '' : ls = new Effect.Appear('arrow-left-small',{ duration: 0.3, queue: 'parallel' });
						$('arrow-right-small').visible() ? '' : rs = new Effect.Appear('arrow-right-small',{ duration: 0.3, queue: 'parallel' });
						$('zoom').visible() ? '' : zz = new Effect.Appear('zoom',{ duration: 0.3, queue: 'parallel' });
						setTimeout(function() {
							_MOUSE_TRACK_LOCK = false;
						}, 300);
					}
				}
				else {
					if (Event.pointerY(evt) <= 50) { // at the top
						db('start anim');
						_ARROWS_HIDDEN = true;
						_MOUSE_TRACK_LOCK = true;
						var l = new Effect.Fade('arrow-left',{ duration: 0.3, queue: 'parallel' });
						var r = new Effect.Fade('arrow-right',{ duration: 0.3, queue: 'parallel' });
						var ls = new Effect.Fade('arrow-left-small',{ duration: 0.3, queue: 'parallel' });
						var rs = new Effect.Fade('arrow-right-small',{ duration: 0.3, queue: 'parallel' });
						var rs = new Effect.Fade('zoom',{ duration: 0.3, from: 0.5, to: 0, queue: 'parallel' });
						db('finished anim out');
						setTimeout(function() {
							_MOUSE_TRACK_LOCK = false;
						}, 300);
					}
				}
			}
		}
	});
/*
	Element.observe('header','mouseover',function() {
		if ($('arrow-left')) {
			var h = Effect.Fade('arrow-left',{ duration: 0.3, queue: 'parallel' });
		}
	});
	Element.observe('header','mouseout',function() {
		if ($('arrow-left')) {
			var h = Effect.Appear('arrow-left',{ duration: 0.3, queue: 'parallel' });
		}
	});*/
}
function initSlider() {
	if ($('handle')) {
		var s = new Control.Slider($('handle'),$('track'), {
			axis: 'vertical',
			onSlide: function(v) { scroll(v) },
			onChange: function(v) { scroll(v) }
		});
	}
}
function scroll(pos) {
	var p = pos * ($('list').getHeight()-$('client-list').getHeight()); 
	$('list').setStyle('margin-top: -'+p+'px');
}
function initContact() {
	$(_ID_SHROUD).setStyle({ display: 'none' }).removeClassName(_CSS_CLASS_HIDDEN);
	$('content-contact').setStyle({ display: 'none' }).removeClassName(_CSS_CLASS_HIDDEN);

	// display contact information
	Element.observe('nav-contact', 'click', function(e) {
		updateDefaultOffsets();
		var f = new Effect.Appear(_ID_SHROUD, { from: 0.0, to: 0.85, queue: 'end', duration: 0.5 });
		var c = new Effect.Appear('content-contact', { from: 0.0, to: 1.0, queue: 'end', duration: 0.5 });
		e.stop();
	});

	// hide contact information
	Element.observe('content-contact', 'click', function(e) {
		var c = new Effect.Fade('content-contact', { from: 1.0, to: 0.0, queue: 'end', duration: 0.5 });
		var f = new Effect.Fade(_ID_SHROUD, { from: 0.85, to: 0.0, queue: 'end', duration: 0.5 });
		e.stop();
	});
}
function updateDefaultOffsets() {
	// center contact information
	var vp = document.viewport.getDimensions();
	var h = vp.height;
	var c = 250; //$('content-about').getHeight();
	var p = (h / 2) - (c / 2);

	$('content-contact').setStyle({ marginTop: p+'px' });

	// center photo

	db('detected resize');
	if ($(_ID_PHOTO)) {
		db('resizing photo');

		// update photo container size
		var container = $(_ID_PHOTO_CONTAINER);

		// update height
		var nh = eval(vp.height - 50 - (($(_ID_THUMBNAILS) && (!_ZOOMED)) ? 100 : ''));
		container.setStyle({ height: nh + 'px', width: vp.width });

		if (!_ZOOMED) {
			// update photo height and width
			var d = $(_ID_PHOTO).getDimensions();
			var w = d.width;
			var h = d.height;
			var ar = _PHOTO_AR != null ? _PHOTO_AR : w / h;
			
			newh = nh;
			neww = newh * ar;
			
			// if the new width is greater than the viewport width, update
			if (neww > vp.width) {
				neww = vp.width;
				newh = neww / ar;
				db('neww > vpwidth');
			}

			//db('new w: '+neww+' new h: '+newh);
			if (((neww != '') || (neww != 0)) && ((newh != '') || (newh != 0))) {

				$(_ID_PHOTO).width = neww;
				$(_ID_PHOTO).height = newh;

				$(_ID_PHOTO).setStyle({ width: neww+'px', height: newh+'px' });
			// update photo center

				var l = (vp.width / 2) - (neww / 2);
				var t = (nh / 2) - (newh / 2);
				$(_ID_PHOTO).setStyle({ marginTop: t+'px', marginLeft: l+'px', marginBottom: t+'px' });
				db('new comp');
			}
		}
	
	}
	if ($(_ID_PHOTO_INTRO)) {


		db('resizing photo intro');
		// update photo container size
		var container = $(_ID_PHOTO_CONTAINER);

		// update height
//		var nh = eval(vp.height - 50 - (($(_ID_THUMBNAILS) && (!_ZOOMED)) ? 100 : ''));
		container.setStyle({ height: eval(vp.height - 50) + 'px', width: vp.width });

		// update position of the image
		var d = $(_ID_PHOTO_INTRO).getDimensions();
		var w = d.width;
		var h = d.height; 
		var ar = _PHOTO_AR != null ? _PHOTO_AR : w / h;

		// update width if the image is not wide enough

		var neww = vp.width;
		var newh = neww / ar;

		var mt = ((vp.height-50) / 2) - (newh / 2);
		var ml = 0;
		if (newh < vp.height) {
			newh = vp.height;
			neww = newh * ar;

			// update margin
			mt = 0;
			ml = (vp.width / 2) - (neww / 2);
		}

		$(_ID_PHOTO_INTRO).width = neww;
		$(_ID_PHOTO_INTRO).height = newh;

		// update image vertical position
		$(_ID_PHOTO_INTRO).setStyle({ width: neww+'px', height: newh+'px', marginTop: mt+'px', marginLeft: ml+'px' });

		db(mt);

		if (_FIRST_LOAD) {
			_FIRST_LOAD = false;
			setTimeout(updateDefaultOffsets,100);
		}
	}

	if ($('zoom')) {
		$('zoom').setStyle({
			left: Math.ceil((vp.width / 2) - 20)+'px'
		});
	}
}


function changeImage(uri) {
	db('loading image');
	if (!_LOCK_TRANSITION) {
		
		_PHOTO_AR = null;
		_LOCK_TRANSITION = true;
		_TEMP_IMAGE != null ? _TEMP_IMAGE.stopObserving() : '';

		// show loading
		// first center it
		var v = document.viewport.getDimensions();
		var d = $('loading').getDimensions();
		$('loading').setStyle({ left: ((v.width/2)-(d.width/2))+'px', top: ((v.height/2)-(d.height/2))+'px' });
		$('loading').setStyle({ display: 'none' });
		$('loading').removeClassName('hidden');
		var p = Effect.Appear('loading', { duration: 1.0, queue: 'end' });


		// get file name
		var arrFn = uri.split('/');
		var l = arrFn.length - 1;
		var g = l - 1;
		var gname = arrFn[g];
		var fn = arrFn[l];

		// load image details
		var url = '/ajax/photo-info.php';
		var s = new Ajax.Request(url, {
			method: 'get',
			parameters: { size: _BASE_SCREEN, filename: fn, gallery: gname },
			onSuccess: function(tp) {
				_FIRST_LOAD = true;
				db('image loaded');
				var jsr = tp.responseText.evalJSON(); // width, height

				// calculate new width and height
				_PHOTO_SIZE.width = jsr.width;
				_PHOTO_SIZE.height = jsr.height;

				_PHOTO_AR = jsr.width / jsr.height;
				newh = eval(document.viewport.getHeight() - 50 - ($(_ID_THUMBNAILS) ? 100 : ''));
				neww = newh * _PHOTO_AR;

				if (neww > document.viewport.getWidth()) {
					neww = document.viewport.getWidth();
					newh = neww / _PHOTO_AR;
					db('TT neww > vpwidth');
				}
				_TEMP_IMAGE = new Image(neww, newh);
				
				db('created new image');
				Element.observe(_TEMP_IMAGE, 'load', function() {

					// hide load
					var l = Effect.Fade('loading', { duration: 0.5, queue: 'parallel' });

					var p = $(_ID_PHOTO_CONTAINER_EFFECT).firstDescendant();
					if (p != null) {
						p.remove();
					}

					// update photo div
					$(_ID_PHOTO_CONTAINER_EFFECT).setStyle({ height: $(_ID_PHOTO_CONTAINER).getHeight()+'px' }).insert({ top: this });	
					$(_ID_PHOTO_CONTAINER_EFFECT).setStyle({ display: 'none' });
					$(_ID_PHOTO_CONTAINER_EFFECT).removeClassName(_CSS_CLASS_HIDDEN);

					var s = Effect.Appear(_ID_PHOTO_CONTAINER_EFFECT, { duration: 1.0 });
					var t = this.src;
					this.width = neww;
					this.height = newh;



					var sizes = { width: neww, height: newh };
					_TEMP_TIMEOUT = setTimeout(function() {

						if ((neww >= $(_ID_PHOTO).getWidth())&&(newh >= $(_ID_PHOTO).getHeight())) {
							db('no fade');
							var nh = eval(document.viewport.getHeight() - 50 - (($(_ID_THUMBNAILS) && (!_ZOOMED)) ? 100 : ''));
							$(_ID_PHOTO).setStyle({ marginLeft: eval((document.viewport.getWidth() / 2) - (sizes.width / 2))+'px', marginTop: eval((nh / 2) - (sizes.height / 2))+'px', width: sizes.width+'px', height: sizes.height+'px' });
							$(_ID_PHOTO).setAttribute('width', sizes.width);
							$(_ID_PHOTO).setAttribute('height', sizes.height);
							$(_ID_PHOTO).src = t;
							_LOCK_TRANSITION = false;
							setTimeout(removeEffectContainerImage, 100);
						}
						else {
							db('fade out');
							Effect.Fade(_ID_PHOTO, { duration: 0.3 });
							setTimeout(function() {
								var nh = eval(document.viewport.getHeight() - 50 - (($(_ID_THUMBNAILS) && (!_ZOOMED)) ? 100 : ''));
								$(_ID_PHOTO).setStyle({ marginLeft: eval((document.viewport.getWidth() / 2) - (sizes.width / 2))+'px', marginTop: eval((nh / 2) - (sizes.height / 2))+'px', width: sizes.width+'px', height: sizes.height+'px' });
								$(_ID_PHOTO).setAttribute('width', sizes.width);
								$(_ID_PHOTO).setAttribute('height', sizes.height);
								$(_ID_PHOTO).src = t;
								_LOCK_TRANSITION = false;
								setTimeout(removeEffectContainerImage, 100);
							}, 300);
						}
					}, 1000);
				});
				Element.extend(_TEMP_IMAGE);
				_TEMP_IMAGE.src = uri;
				_TEMP_IMAGE.width = neww;
				_TEMP_IMAGE.height = newh;

				// update photo center
				var l = (document.viewport.getWidth() / 2) - (neww / 2);
				var nh = eval(document.viewport.getHeight() - 50 - (($(_ID_THUMBNAILS) && (!_ZOOMED)) ? 100 : ''));
				var t = (nh / 2) - (newh / 2);
				_TEMP_IMAGE.setStyle({ marginLeft: l+'px', marginTop: t+'px' });



				// db($(_ID_PHOTO).getStyle('top'));
				_TEMP_IMAGE.addClassName(_CSS_CLASS_REL);
				//galleryUpdateOffsets();
			}
		});

	}
	/*
	
	PSEUDO:

	1. preload image
	2. create div
		i. create image in div
		ii. crop image within div
	3. fade div above image

	*/
}

function removeEffectContainerImage() {
//	!_LOCK_TRANSITION ? $(_ID_PHOTO_CONTAINER_EFFECT).firstDescendant().remove() : setTimeout(removeEffectContainerImage, 100);

	if (!_LOCK_TRANSITION) {
		Effect.Appear(_ID_PHOTO, { duration: 0 });
		setTimeout(function() {
			$(_ID_PHOTO_CONTAINER_EFFECT).firstDescendant().remove();
			$(_ID_PHOTO_CONTAINER_EFFECT).addClassName(_CSS_CLASS_HIDDEN);
		}, 100);
	}
	else {
		setTimeout(removeEffectContainerImage, 100);
	}
}


function getParentObject(objTest,attribute) {
	var objParent = objTest;
	var attVal = objTest.getAttribute(attribute);
	if (attVal == null) {
		var anc = objTest.ancestors();
		for (var i=0; i<anc.length; i++) {
			if (anc[i].getAttribute(attribute) != null) {
				attVal = anc[i].getAttribute(attribute);
				objParent = anc[i];
				break;
			}
		}
	}
	return objParent;
}

function pxToInt(px) {
	return ((px!=null)&&(px.length != 1)) ? px.substring(0,px.length-2) : 0;
}
function changePage(evt) {

	_THUMBS = null;
	_TEMP_IMAGE != null ? _TEMP_IMAGE.stopObserving() : '';
	_TEMP_TIMEOUT != null ? clearTimeout(_TEMP_TIMEOUT) : '';
	_LOCK_TRANSITION = false;
	$('loading').addClassName('hidden');
	var caller = getParentObject(evt.element(),'offset');
	if (caller != null) {
		
		//caller.blur();
		$$('a.active').each(function(a) {
			a.removeClassName('active');
		});
		// update navigation
		caller.addClassName('active');
		// load new page
		var url = caller.getAttribute('href');

		// if its intro, clear the interval
		_INTRO_INT == null ? '' : clearInterval(_INTRO_INT);
		_INTRO_INT = null;
		db('requesting: '+_BASE_SCREEN);

		var a = new Ajax.Request(url, {
			method: 'get',
			parameters: { raw: 'true', size: _BASE_SCREEN },
			onSuccess: function(tp) {
				// destroy old photo object
				_PHOTO_DRAG == null ? '' : _PHOTO_DRAG.destroy();
				_GALLERY_OFFSET = 0;
										
				// fade out content
				var s = Effect.Fade('body', { from: 1.0, to: 0.0, queue: 'end', duration: 0.5 });
				// change content
				setTimeout(function() {
					$('body').innerHTML = tp.responseText;

					db('initIntro');
					initIntro();
					db('initGallery');
					initGallery();
					initSlider();

//							updateDefaultOffsets();
///							galleryInit();
//							galleryUpdateOffsets();

				}, 500);
				var n = Effect.Appear('body', { from: 0.0, to: 1.0, queue: 'end', duration: 0.5, delay: 0.6	});


			}
		});
	}
}