// portfolio page
document.whenReady ( function ( ) {
	if ( window.oldBrowser || !$(document.body).hasClass ( "portfolio" ) ) return;

	var wrapper = document.getElementById("listingsWrapper");
	var maxPos = 0;

	var round = function ( x, f ) {
		var f = Math.pow ( 10, parseInt ( f ) || 3 );
		return Math.round ( x * f ) / f;
	}

	var main = document.getElementById("main");
	main.parentNode.insertBefore ( DOM.create ( "div", {
		'class' : "title",
		child : main.getElementsByTagName("h3")[0]
	} ), main );

	var globalOffset = -1 * ( parseInt ( wrapper.style.marginLeft ) || 0 );
	var currentUpdate = ( new Date() ).getTime();
	$("li",wrapper).each ( function ( i ) {
		var offset = i * this.offsetWidth;
		var img = this.getElementsByTagName("img")[0];
		this.style.left = offset + "px";
		maxPos = offset;
	} );

	var viewer = DOM.create ( "div", {
		insertAfter : wrapper,
		id : "viewer",
		children : [
			DOM.create ( "div", {
				'class' : "left",
				child : DOM.create ( "span", { onclick : function ( ) { scrollToItem ( currentItem - 1 ); } } )
			} ),
			DOM.create ( "div", {
				'class' : "right",
				child : DOM.create ( "span", { onclick : function ( ) { scrollToItem ( currentItem + 1 ); } } )
			} ),
			DOM.create ( "div", { 'class' : "data" } ),
			DOM.create ( "div", { 'class' : "overlay" } )
		]
	} );
	viewer.startLoading = function ( ) {
		$('.data',this).empty();
		$(this).addClass ( "loading" );
	}
	viewer.stopLoading = function ( ) {
		$(this).removeClass ( "loading" );
		if ( $.browser.opera ) {
			var self = this;
			this.style.display = "none";
			setTimeout ( function ( ) { self.style.display = "block"; }, 1 );
		}
	}
	viewer.load = function ( data ) {
		var title = data.title;
		var description = ( data.brief || "" );
		if ( description != "" ) {
			title += ":";
			description = " " + description;
		}
		$('.data',this).html ( '<p><strong>' + title + '</strong>' + description + '</p><p class="right"><a href="' + data.url + '" title="See the full overview">[More]</a></p>' );
		this.stopLoading();
	}

	var navigation = DOM.create ( "div", {
		insertAfter : "main",
		id : "navigation"
	} );
	
	var track = DOM.create ( "div", {
		parent : navigation,
		id : "track"
	} );

	var handle = DOM.create ( "div", {
		parent : navigation,
		id : "handle"
	} );

	var currentItem = -1;
	var scrollToItem = function ( i ) {
		if ( i == currentItem ) return;
		var item = $('li',navigation)[i];
		if ( item &&  ( item.className == "" ) ) {
			viewer.startLoading();
			$('li:eq(' + currentItem + ') span',navigation).removeClass ( "selected" );
			currentItem = i;
			var pItem = $('li',wrapper)[currentItem];
			var pos = pItem.offsetLeft + ( pItem.offsetWidth / 2 );
			$(wrapper).stop().animate ( { marginLeft : -pos + "px" } );
			$(handle).stop().animate ( { left : item.offsetLeft + item.offsetWidth / 2 }, {
				easing : "easeOutSine",
				complete : function ( ) {
					$('li:eq(' + currentItem + ') span',navigation).addClass ( "selected" );
					var url = $('li:eq('+i+') a',wrapper)[0].href;
					SERVER.get ( url, {
						headers : { "Accept" : "text/json" },
						onSuccess : function ( rsp ) {
							if ( currentItem == i ) {
								var data = eval ( "("+rsp.response+")" );
								//alert ( data );
								data.url = url;
								viewer.load ( data );
							}
						},
						onError : function ( err ) {
							if ( currentItem == i )
								viewer.stopLoading();
						}
					} );
				}
			} );
		}
	}

	var items = DOM.create ( "ul", {
		parent : navigation
	} );

	var count = $('#listingsWrapper li').length;
	$('#listingsWrapper li').each ( function ( i ) {
		var x = 100 / ( count - 1 ) * i;
		var label = $('li img',wrapper)[i].title;
		( DOM.create ( "li", {
			parent : items,
			child : DOM.create ( "span", { innerHTML : '<em>' + label + '</em>' } ),
			style : {
				left : x + "%"
			},
			onmouseover : function ( ) { $('span',this).addClass ( "hover" ); },
			onmouseout : function ( ) { $('span',this).removeClass ( "hover" ); }
		} ) ).onclick = function ( ) {
			scrollToItem ( i );
		};
	} );

	$('#listingsWrapper li a').each ( function ( i ) {
		this.onfocus = function ( ) {
			scrollToItem ( i );
		};
	} );

	DOM.create ( "li", {
		parent : items,
		'class' : "previous",
		onclick : function ( ) {
			scrollToItem ( currentItem - 1 );
		}
	} );

	DOM.create ( "li", {
		parent : items,
		'class' : "next",
		onclick : function ( ) {
			scrollToItem ( currentItem + 1 );
		}
	} );

	var getNearestItem = function ( ) {
		var pos = getPos();
		var is = $('li',items);
		for ( var i = 1; i < is.length - 2; i ++ ) {
			var diff = Math.abs ( ( is[i].offsetLeft + is[i].offsetWidth / 2 ) - pos );
			var pDiff = Math.abs ( ( is[i-1].offsetLeft + is[i-1].offsetWidth / 2 ) - pos );
			if ( pDiff < diff )
				return i - 1;
		}
		return is.length - 3;
	}

	var normalise = function ( ) {
		scrollToItem ( getNearestItem() );
	}

	var getPos = function ( percentage ) {
		var pos = Math.ceil ( handle.offsetLeft + handle.offsetWidth / 2 );
		if ( percentage ) return 100 / navigation.offsetWidth * pos;
		return pos;
	}

	var updateListing = function ( ) {
		var percentage = getPos ( true );
		$(wrapper).stop().css ( { marginLeft : ( percentage / -100 ) * maxPos + "px" } );
		//console.log ( percentage, maxPos );
	}

	var mouseMove = function ( e ) {
		currentItem = -1;
		e = e || window.event;
		var offset = ( handle.offsetWidth / -2 ) + handle.offset;
		var pos = Math.min ( Math.max ( e.clientX - offset - navigation.offsetLeft, 0 ), navigation.offsetWidth );
		handle.style.left = pos + "px";
		updateListing();
		$('li span',navigation).removeClass("hover")[getNearestItem()].className = "hover";
		return false;
	}

	handle.onmousedown = function ( e ) {
		$('li span',navigation).removeClass("selected");
		viewer.startLoading();
		e = e || window.event;
		handle.offset = e.layerX || ( handle.offsetWidth / 2 );
		window.onmousemove = mouseMove;
		window.onmouseup = function ( ) {
			window.onmouseup = null;
			window.onmousemove = null;
			normalise();
			$('li span',navigation).removeClass('hover');
		}
		return false;
	}

	scrollToItem ( 0 );

} );

// individual project page
document.whenReady ( function ( ) {
	if ( !$(document.body).hasClass ( "project" ) ) return;

	var extras = $("#additionalImages ul li a");
	if ( extras.length ) {
		$("img.primary").wrap('<div id="slideshow"><div class="image"></div></div>');
		extras.each ( function ( ) {
			var img = document.createElement ( "img" );
			img.src = this.href;
			img.alt = this.innerHTML;
			img.className = "primary";
			$('#slideshow').append ( img );
			$(img).wrap('<div class="image"></div>');
			$(img.parentNode).hide();
		} );
		$("#additionalImages").remove();
		var controls = DOM.create ( "div", {
			parent : "slideshow",
			'class' : "controls"
		} );
		$(controls).html ( '<div class="buttons"></div><div class="timer"><div></div></div>' );
		var b = $(".buttons",controls)[0];
		var buttons = {
			previous : DOM.create ( "span", {
				'class' : "previous",
				onclick : function ( ) { pause(); tick(-1); },
				parent : b
			} ),
			play : DOM.create ( "span", {
				'class' : "play",
				onclick : function ( ) { play(); },
				parent : b
			} ),
			pause : DOM.create ( "span", {
				'class' : "pause",
				onclick : function ( ) { pause(); },
				parent : b
			} ),
			next : DOM.create ( "span", {
				'class' : "next",
				onclick : function ( ) { pause(); tick(); },
				parent : b
			} )
		}
		$(b).append ( '<span class="counter">1 of ' + ( extras.length + 1 ) + '</span>' );
		$(controls).hide();
		$("#slideshow").hover ( function ( ) {
			$(controls).slideDown(); // bizarrely, because of the placement; this seems backwards
		}, function ( ) {
			$(controls).slideUp(); // see above
		} );
		var currentImageIndex = 0;
		var paused = false;
		var showNextImage = function ( dir ) {
			dir = dir / Math.abs ( dir );
			var l = $("#slideshow .image").length;
			var current = currentImageIndex;
			var next = currentImageIndex + dir;
			if ( next < 0 ) next = l - 1;
			if ( next == l ) next = 0;
			$("#slideshow .image:eq("+current+")").hide();
			$("#slideshow .image:eq("+next+")").show();
			$("#slideshow .controls .buttons .counter").text ( ( next + 1 ) + " of " + l );
			currentImageIndex = next;
		}
		var tick = function ( dir ) {
			$("#slideshow .controls .timer div").stop().css("width",0);
			showNextImage ( dir == null ? 1 : dir );
			if ( !paused ) play();
		}
		var play = function ( ) {
			$("#slideshow .controls .buttons .play").hide();
			$("#slideshow .controls .buttons .pause").show();
			var w = ( 100 - parseInt ( $("#slideshow .controls .timer div").css("width") ) ) / 100;
			setTimeout ( function ( ) {
				$("#slideshow .controls .timer div").animate ( { width : "100%" }, {
					complete : tick,
					duration: 5000 * w,
					easing: "linear"
				} );
			}, 1 );
		}
		var pause = function ( ) {
			paused = true;
			$("#slideshow .controls .buttons .play").show();
			$("#slideshow .controls .buttons .pause").hide();
			$("#slideshow .controls .timer div").stop();
		}
		play();
	}
} );
