// wait until page has loaded
$(document).ready(function() {

	// set up global variables
	var atime   = 300;
	var busy    = 0;
	var boxes   = $('div.box').size();
	var current = 0;

	// add #script to body
	$('body').addClass('json');

	// create navigation list
	$('div#wrapper').prepend('<div class="section" id="controls"><h2>Portfolio</h2><ul></ul></div>');

	// fill out navigation list
	for (var i = 1; i <= boxes; i++) {
		var title = $('div.box').eq(i - 1).children('h3').eq(0).children('a').eq(0).html();
		if (!title) title = $('div.box').eq(i - 1).children('h3').eq(0).html();
		$('div#controls ul').eq(0).append('<li><a class="box' + i + '" href="#">' + title + '</a></li>');
		$('div#controls').append($('div.clients'));
	}

	// attach events to portfolio links
	$('div#controls ul li a').click(function() {
		window.clearInterval(to);
		change(getIndex(jQuery(this)));
		return false;
	});

	// create prev/next links
	$('div#portfolio').append('<p class="prevnext"><a href="#" class="prev">&lt; Previous</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="next">Next &gt;</a></p>');

	// attach event to prev button
	$('p.prevnext a.prev').click(function() {
		window.clearInterval(to);
		prevbox();
		return false;
	});

	// attach even to next button
	$('p.prevnext a.next').click(function() {
		window.clearInterval(to);
		nextbox();
		return false;
	});

	// swap out box
	function change(c) {
		current = parseFloat(c);
		if (current > boxes) current = 1;
		if (current < 1) current = boxes;
		var t = $('div#controls ul li a').eq(current - 1);
		// don't change boxes if busy or box is already visible
		if (!busy && t.attr('class').indexOf('current') < 0) {
			busy = 1;
			$('div#controls ul li a.current').removeClass('current');
			t.addClass('current');
			var index = getIndex(t);
			var box = $('div.box').eq(index - 1);
			box.css('z-index', 1);
			box.animate({left: 9}, atime, "backout", function() {
				// hide the other boxes
				for (var i = 1; i <= boxes; i++) {
					box = $('div.box').eq(i - 1);
					if (i != index) box.css('left', '425px');
					box.css('z-index', 0);
				}
				busy = 0;
			});
		}
	}

	// move to selected box
	function nextbox() {
		change(current + 1);
	}

	function prevbox() {
		change(current - 1);
	}

	// gets index from classname (box1, box2, etc)
	function getIndex(t) {
		var keyoff = 'box';
		var cn = t.attr('class');
		var istart = cn.lastIndexOf(keyoff) + keyoff.length;
		var ilength = cn.indexOf(' ', cn.lastIndexOf(keyoff)) - istart;
		if (ilength < 1) ilength = cn.length - istart;
		return parseFloat(cn.substr(istart, ilength));
	}

	// bring up with first box
	nextbox();

	// start slideshow
	var to = setInterval(nextbox, 6765);

});

