/* External links */

var ivoSpeed = 600;
var isAnimating = false;
var currentSlidingContent = null;

function getParamFromReq(param) {
  param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+param+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function externalLinks(element) {
	if (element == undefined) element = document; 
	if (!element.getElementsByTagName) return; 
	var anchors = element.getElementsByTagName("a"); 
	for (var i = 0; i < anchors.length; i++) { 
		var anchor = anchors[i]; 
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank"; 
		}
	}
}

if (window.addEventListener) {
	window.addEventListener('load', externalLinks, false); 
} else if (window.attachEvent) { 
	window.attachEvent('onload', externalLinks);
}

/* Menu */

$(document).ready(function() {
	$("li#projectsItem").addClass("selected");
	$("a#projects").addClass("linkSelected");


	$('ul.subList').hide();
	
	$('a.mainMenu').click(function() {
		return openMainMenuElement(this);
	});
	
	$("#menu .subList li a").click(function() {
		// if ($('#menu').get(0).loading) return false;
		var fromDirection = 'right';
		var li = this.parentNode;
		
		var indexNew = $('.subList li').index(li);
		
		if ($('li.subSelected').length > 0) {
			var indexPrev = $('.subList li').index($('li.subSelected').get(0));
			if (indexPrev > indexNew) fromDirection = 'left';
		}
		$('#projectNav').css('visibility', 'visible');

		$('div#menu .subList li').removeClass('subSelected');
		$(li).addClass('subSelected');
		
		var numProjects = $('ul.subList a').length;

		// $('#menu').get(0).loading = true;

		$.ajax({
			url: this.href,
			cache: true,
			success: function(html) {
				var newContent = $('<div class="slidingContent"></div>').html(html);
				
				currentSlidingContent = newContent;
				
				var toMarginLeft = '-666px';
				var fromMarginLeft = '1000px';
				if (fromDirection == 'right') {
					toMarginLeft = '666px';
					fromMarginLeft = '-1000px';
				}
				
				isAnimating = true;
				
				// slide out an old slidingcontent
				$('div.slidingContent').animate({ marginLeft: fromMarginLeft, opacity : 'hide' }, ivoSpeed, 'linear', function() { 
				   //executed after slide
					this.isGone = true;
					$(this).remove();
					// flash
					
					if (isdefined('flashPlayer')) {
						$('#player1').html('').flash(
							{
								src: flashPlayer,
								width: flashWidth,
								height: flashHeight,
								flashvars: flashVars
							},
							{ version: 7 }
						);
					}
					
				});
				
				newContent.css('margin-left', toMarginLeft).animate({ marginLeft: "0" }, ivoSpeed, function() {
					if ($('div.pictureBrowser > img', newContent)) {
						enableImageNavigation(newContent);
						enableEmbiggen(newContent);
					}
					isAnimating = false;
				});
				$('div#content').append(newContent);

				setTimeout(function(){
				if (isdefined('flashPlayer') && newContent.find('script').length == 0) {
					/*alert('test');
				  var regexS = '<script type="text/javascript">\s*\n((.*\n)+?).*</script>';
				  var regex = new RegExp( regexS, 'gi' );
				  var results = regex.exec( html );
					alert(results[1]);

					var newScript = $('<script type="text/javascript">'+ results[1] +'</script>');
					$('body').append(newScript);*/
					$('#player1').html('').flash(
						{
							src: flashPlayer,
							width: flashWidth,
							height: flashHeight,
							flashvars: flashVars
						},
						{ version: 7 }
					);					
				}
			}, 500);

				

				externalLinks(newContent.get(0));
								
				if (indexNew + 1 < numProjects) {
					$('a#gotoNextProject').css('opacity', '1.0');
				} else {
					$('a#gotoNextProject').css('opacity', '0.2');
				}
				if (indexNew > 0) {
					$('a#gotoPreviousProject').css('opacity', '1.0');
				} else {
					$('a#gotoPreviousProject').css('opacity', '0.2');	
				}
			}
		});
		return false;
	});
	
	$('a#projects').click(function() {
		$('div#menu .subList li').removeClass('subSelected');
		$('#projectNav').css('visibility', 'hidden');
		loadProjectOverview(true);
		return false;
	});
	
	$('a#gotoNextProject, a#gotoPreviousProject').click(function() {
		var whereAreWe = $('li.subSelected');
		if (whereAreWe.length == 0) {
			alert('We are nowhere...');
			return;
		}
		
		var indexPrev = $('.subList li').index($('li.subSelected').get(0));
		
		if (this == $('a#gotoNextProject').get(0)) {
			var indexNew = indexPrev + 1;
		} else {
			var indexNew = indexPrev - 1;
		}
		
		var numProjects = $('ul.subList a').length;
		
		if (indexNew < numProjects) {
			if (indexNew >= 0) {
				// var oldMainMenu = $('ul.subList:visible').get(0);
				var oldMainMenu = $('ul.subList a').get(indexPrev).parentNode.parentNode;
				var newMainMenu = $('ul.subList a').get(indexNew).parentNode.parentNode;
				if (oldMainMenu != newMainMenu) {
					$('a.mainMenu', newMainMenu.parentNode).click();
				}
				$($('ul.subList a').get(indexNew)).click();
			} else {
				// start of the line!
			}
		} else {
			// end of the line!
		}
	});
	
	var path = getParamFromReq('path');
	if (path) {
		var $activeProject = $('div#menu a[href='+ path +']:first');
		if ($activeProject.length == 1) {
			var $parentMenuItem = $activeProject.parent().parents('li:first').find('a.mainMenu:first');
			openMainMenuElement($parentMenuItem[0]);
			$activeProject.click();
			return false;
		}
	}
	
	loadProjectOverview();
	return false;
});

function openMainMenuElement(element, noHighlight) {
	// close all open trees
	$('ul.subList:visible').slideUp(200);
	// open the child tree
	$('ul.subList', element.parentNode).slideDown(200);
	
	var li = element.parentNode;
	$('div#menu li').removeClass('selected');
	// $('div#menu .subList li').removeClass('subSelected');
	$(li).addClass('selected');
	
	// let's give the pictures some color!
			
	if (!noHighlight) highlightImagesForMainMenuElement(li);
	
	return false;
}

function highlightImagesForMainMenuElement(liElement) {
	$('#projectOverview a img').each(function() {
		href = this.parentNode.pathname;
		if ($.browser.msie) {
			href = '/' + href;
		}
		var links = $('a[href=' + href + ']', liElement);
		if (links.length > 0) {
			this.src = this.srcOver;
		} else {
			this.src = this.srcOut;
		}
	});
}

function loadProjectOverview(animate) {
	if ($('#projectOverview').length > 0) return;
	var newContent = $('<div class="slidingContent"></div>');
	newContent.load("/pages/overview.html", function() {
		if (animate) {
			$('div.slidingContent').animate({ marginLeft: "1000px", opacity : 'hide' }, ivoSpeed, 'linear', function() { $(this).remove(); });
			newContent.css('margin-left', '-666px').animate({ marginLeft: "0"}, ivoSpeed);
		}
		$('#content').append(newContent);

		$('#projectOverview img').each(function() {
			this.srcOut = this.src;
			this.srcOver = this.src.substring(0, this.src.lastIndexOf('.jpg')) + '_over' + '.jpg';
		});

		$('#projectOverview img').hover(function() {
			this.src = this.srcOver;
		}, function() {
			this.src = this.srcOut;
		});
		
		$('#projectOverview a').click(function() {
			var href = this.pathname;
			if ($.browser.msie) {
				href = '/' + href;
			}			
			var link = $('ul.subList a[href=' + href + ']').get(0);
			if (link == undefined) return false;
			var ul = link.parentNode.parentNode;
			openMainMenuElement($('a.mainMenu', ul.parentNode).get(0), true);
			$('ul.subList a[href=' + href + ']').click();
			return false;
		});
	});
}

/* Image nav */

function enableImageNavigation(element) {
	var htmlMagnify = '';
	if ($('.embiggen', element).length > 0) {
		htmlMagnify = '<a href="#magnify" class="magnify"><img class="navigation" src="/images/magnify.png" height="16" width="20" /></a>';
	}
	$('div.pictureBrowser', element).append(
'<div class="imageNav">\
<a class="backward" href="#previous"><img class="navigation" src="/images/project_arrow_left.png" height="16" width="8" /></a>\
<span class="currentPicture">1</span> / <span class="numPictures">?</span>\
		<a class="forward" href="#next"><img class="navigation" src="/images/project_arrow_right.png" height="16" width="8" /></a>'
	+ htmlMagnify + '</div>');
	var height = ($('div.pictureBrowser img', element).attr('height') - $('div.imageNav', element).height()) + 'px';
	$('div.imageNav', element).css('top', height);
	$('div.pictureBrowser', element).hover(function() {
		$('div.imageNav', element).fadeIn(300);
	}, function() {
		$('div.imageNav', element).fadeOut(300);
	});
	element.numPictures = $('div.pictureBrowser > img', element).length;
	element.currentPicture = element.numPictures - 1;
	element.isPlaying = true;
	$('span.numPictures', element).text(element.numPictures);
	$('div.pictureBrowser > img', element).hide();
	$('div.pictureBrowser > img, div.imageNav', element).mouseover(function() {
		element.isPlaying = false;
	}).mouseout(function() {
		element.isPlaying = true;
	});
	setTimeout(function() {
		nextPicture(element);
	}, ivoSpeed);
	
	$('.backward', element).click(function() {
		previousPictureClicked(element);
	});
	$('.forward', element).click(function() {
		nextPictureClicked(element);
	});
}

function enableEmbiggen(element) {
	$('img.embiggen', element).click(function() {
		var src = this.src.substring(0, this.src.indexOf('360.jpg')) + '700.jpg';
		var image = '<img src="' + src + '" style="margin-top: 80px; border: 1px solid #cccccc;" class="embiggened" />';
		$('#lightbox').prepend(image);
		$('#lightbox').fadeIn(500);
		$('#lightbox').click(function() {
			$(this).fadeOut(function() {
				$('.embiggened', this).remove();
			});
		});
	});
	$('a.magnify', element).click(function() {
		$('img.active').trigger('click');
	});
}


function previousPictureClicked(element) {
	$('img:eq(' + element.currentPicture + ')', element).removeClass('active');
	$('img:eq(' + element.currentPicture + ')', element).hide();
	element.currentPicture--;
	if (element.currentPicture < 0) element.currentPicture = element.numPictures - 1;
	$('span.currentPicture').text(element.currentPicture + 1);
	$('img:eq(' + element.currentPicture + ')', element).show();
	$('img:eq(' + element.currentPicture + ')', element).addClass('active');
}

function nextPictureClicked(element) {
	$('img:eq(' + element.currentPicture + ')', element).removeClass('active');
	$('img:eq(' + element.currentPicture + ')', element).hide();
	element.currentPicture++;
	if (element.currentPicture >= element.numPictures) element.currentPicture = 0;
	$('span.currentPicture').text(element.currentPicture + 1);
	$('img:eq(' + element.currentPicture + ')', element).show();
	$('img:eq(' + element.currentPicture + ')', element).addClass('active');
}

function nextPicture(element) {
	if (element != currentSlidingContent) return; // cancel a rogue thread
	// element = currentSlidingContent;
	// if (element.isGone) return;
	// if (isAnimating) return;
	if (!element.isPlaying) {
		setTimeout(function() {
			nextPicture(element);
		}, 1000);		
		return;
	}
	$('img:eq(' + element.currentPicture + ')', element).removeClass('active');
	$('img:eq(' + element.currentPicture + ')', element).fadeOut(500, function() {
		
		element.currentPicture++;
		if (element.currentPicture >= element.numPictures) element.currentPicture = 0;
		$('span.currentPicture').text(element.currentPicture + 1);
		$('img:eq(' + element.currentPicture + ')', element).fadeIn(500, function() {
			if (element.numPictures > 1) {
				setTimeout(function() {
					nextPicture(element, false);
				}, 4000);}
			$('img:eq(' + element.currentPicture + ')', element).addClass('active');
		});
	});
}

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

$(document).ready(function() {
$('a.xxl').click(function() {
	//$('#xlImage').fadeIn(500);
	$('#whiteContainer').fadeIn(500);
	return false;
	});
});