
// INIT ========================================================================

$(document).ready(function() {
	// on all pages
	InitClientLogin();
	InitSiteOptions();
	MarginParas();

	// bind window resize
	var resizeTimer = null;
	$(window).bind('resize', function() {
		if (resizeTimer) clearTimeout(resizeTimer);
		resizeTimer = setTimeout(HandleResize, 100);
	});
	
});

// GLOBAL ======================================================================
$.fn.image = function(src, f) {
	return this.each(function() {
		var i = new Image();
		i.src = src;
		i.onload = f;
		this.appendChild(i);
	});
}

// set client login box
function InitClientLogin(){
	$("#login-link").show();
	$("#client-login").hide();
	$("#client-login .close").show();
	$("#login-link").toggle(
		function (){
			$("#client-login").slideDown("fast");
			$(this).html("<span class='slash'>/</span> Close Client Login");
		},
		function (){
			$("#client-login").slideUp("fast");
			$(this).html("<span class='slash'>/</span> Client Login");
		}
	);
	$("#client-login .close").click(
		function(){
			$("#login-link").trigger('click');
		}
	);
}

function InitSiteOptions(){
// setup box & launch link
	$("#options-link").show();
	$("#site-options").hide();
	$("#site-options .close").show();
	$("#options-link").toggle(
		function (){
			$("#site-options").slideDown("fast");
			$(this).html("<span class='slash'>/</span> Close Site Options");
		},
		function (){
			$("#site-options").slideUp("fast");
			$(this).html("<span class='slash'>/</span> Site Options");
		}
	);
	$("#site-options .close").click(
		function(){
			$("#options-link").trigger('click');
		}
	);
	// append alt stylesheet
	//$("head").append("<link rel='stylesheet' title='Light' type='text/css' href='/Css/light.css' media='screen' />");
	// set links to change stylesheet
	$(".options-list a").each(
		function(){
			$(this).click(
				function(){
					SwitchStyle(this.getAttribute("rel"));
					return false;
				}
			);
		}
	);
	// disable alt stylesheets
	$('link[@title*=Light]').each(
		function(){
			this.disabled = true;
		}
	);
	// check cookie
	var c = readCookie('style');
	if (c) SwitchStyle(c);
}

function SwitchStyle(styleName){
        $('link[@media*=screen]').each(function(i)
        {
                this.disabled = true;
                if (this.getAttribute('title') == styleName) this.disabled = false;
        });
		createCookie('style', styleName, 365);
}

function CheckScreenSize(){
	var dimensions = {width: 0, height: 0};
    if (document.documentElement) {
        dimensions.width = document.documentElement.offsetWidth;
        dimensions.height = document.documentElement.offsetHeight;
    } else if (window.innerWidth && window.innerHeight) {
        dimensions.width = window.innerWidth;
        dimensions.height = window.innerHeight;
    }
	return dimensions;
}

function MarginParas(){
	//alert( $("h4").prev().val() );
	$("h4").prev("p").each(
		function(){
			$(this).addClass("extra-bottom-margin");
		}
	);
	$("h3").prev("p").each(
		function(){
			$(this).addClass("extra-bottom-margin");
		}
	);
	$("h1").next(".news-date").each(
		function(){
			$(this).addClass("article-news-date");
		}
	);
}

// HOME ========================================================================

function HomepageLayout(){
	var theWidth = CheckScreenSize().width;
	if( theWidth < 1460 && theWidth > 1100) {
	/* 1024 */
		$("#news-col").removeClass("med-col");
		$("#news-col").addClass("lrg-col");
	}else {
	/* 1600 or 800 */
		$("#news-col").removeClass("lrg-col");
		$("#news-col").addClass("med-col");
	}
}

function HandleResize(){
	// if homepage?
	HomepageLayout();
}

// setup flash image rotator
function InitFlash(Context){
	
	// if we're on the project detail page, grab the first image/caption & reinsert it above the flash holder. 
	// Is hidden via Css, & revealed in Print stylesheet. This is so when printing a project page user still gets some 
	// visual content (which would be hidden along with the flash otherwise).
	if(Context == "port"){
		$(".home-site-promo").before( "<div class='hide-for-print'>"+$("#project-rotator li:first").html()+"</div>" );
	}
	
	var so = new SWFObject("/Flash/navImgRotator.swf", "imgRotator", "640", "360", "8", "#000000");
	so.addVariable("theData", BuildProjectXML());
	so.addVariable("Context", Context);
	so.addParam("wmode", "transparent");
	so.write("flash-container");
	
	if( $("#flash-container #project-rotator").length == 0){
		$("#flash-container").addClass("contains-flash");
	}

	window.imgRotator = document.getElementById('imgRotator');
	$(window.imgRotator).width("64em");
	$(window.imgRotator).height("36em");
	$(".project-abstract").css({ display:"none" });
	InitVideo();


	var tempHolder = '<div id="temp-holder" style="display:none;"></div>';
	$('body').append(tempHolder);
}

// build XML to pass to flash from DOM
function BuildProjectXML(){
	var theXML = "<projects>";
	$("#project-rotator li").each(
		function() {
			var theTitle = $(this).find(".project-quote .source").text(); //$(this).children("h4").text();
			var theImg = $(this).children("a").children("img").attr("src");
			var theAbstract = $(this).find(".project-quote .quote").text(); //$(this).children("p").text();
			var theUrl = $(this).children("a").attr("href");
			//theXML += "<project title='"+theTitle+"' img='"+theImg+"' abstract='"+theAbstract+"' url='"+theUrl+"' />";
			theXML += "<project><title><![CDATA[" + theTitle + "]]></title><img>" + escape(theImg) + "</img><abstract><![CDATA[" + theAbstract + "]]></abstract><url>" + escape(theUrl) + "</url></project>";
		}
	);
	theXML += "</projects>";
	return theXML;
}

// called from flash, displays abstract for rotated project on page
function ShowAbstract(theAbstract) {
	var holder = $('#temp-holder');
	holder.html(theAbstract);
	//console.log('[' + theAbstract + '] : [' + holder.html() + ']');
	var format = '<div class="project-quote"><blockquote><p>[QUOTE]<span class="source">&ndash; [SOURCE]</span></p></blockquote></div>';
	var source = holder.find('h4').text();
	var quote = holder.find('p');
	quote.find('a').remove();
	quote = quote.text();
	quote = quote.replace(source, '');

	//console.log('['+source + '] [' + quote+'] [' + format + ']');
	
	if (quote.length > 10) {
		format = format.replace('[QUOTE]', quote);
		format = format.replace('[SOURCE]', source);
		$(".project-abstract").html(format);
		$(".project-abstract").fadeIn("slow");
		//console.log(format);
	} else {
		/*
		var link = $(theAbstract).find('a');
		var html = '<p><a href="' + link.attr('href') + '">' + link.text() + '</a></p>';
		$(".project-abstract").fadeIn("slow");
		$(".project-abstract").html(html);
		*/
		$(".project-abstract").hide();
	}
}

function InitVideo(){
	$(".video-holder").show();
	$(".video-link").click(function(){
		flashMovie = document.getElementById("imgRotator");
		var theTitle = $(this).parents("li").children("h5").children("a").text();
		var theAbstract = $(this).parents("li").children("p").text();
		flashMovie.LaunchVideo($(this).attr("href"), theTitle, theAbstract);
		return false;
	});
}

// CONTACT =====================================================================

function InitContactPage(){
	currentRoute = "";
	ShowHideDirections("#southern-directions", "#from-southern", "", "", "slide");
	ShowHideDirections("#northern-directions", "#from-northern", "", "", "slide");
	ShowHideDirections("#newmarket-directions", "#from-newmarket", "", "", "slide");
	ShowHideDirections("#strand-directions", "#from-strand", "", "", "slide");
	setRouteLinks();
	
	//Use js to insert map link for xhtml validation
	$("#gMap p").html("<a href=\"http://maps.google.co.nz/maps?f=q&hl=en&geocode=&q=terabyte&sll=-41.244772,172.617188&sspn=27.267014,55.195313&ie=UTF8&ll=-36.852565,174.777954&spn=0.0142,0.026951&z=16&iwloc=A\" rel=\"external\">Click here to find us on Google Maps</a>");
}

// sets the show / hide on directions
function ShowHideDirections(theTarget, theLauncher, openText, closedText, showType) {
	
	$(theTarget).hide();
	
	$(theLauncher).toggle(
		function(){
			$(".directions-link").each( function(){
				if(this.isOpen){
					$(this).trigger("click");
					//alert("go");
				}
			});
			$(theTarget).slideDown(200);
			$(".route-text").hide();
			$(this).parent().next(".route-text").show();
			this.isOpen = true;
			return false;
		},
		function(){
			$(theTarget).slideUp(200);
			$(this).parent().next(".route-text").hide();
			this.isOpen = false;
			return false;
		}
	);

}

// loader for Google Map on contact page
function loadGMap() {
	
	$("#gMap").height("40em");
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("gMap"));
		//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
		map.addControl(new GLargeMapControl());
		var geocoder = new GClientGeocoder();
		
		var address = "16 York Street, Parnell, Auckland, New Zealand";
		
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					alert(address + " not found");
				} else {
					map.setCenter(point, 17);
					
					baseIcon = new GIcon();
				    baseIcon.iconSize = new GSize(37, 43);
					baseIcon.iconAnchor = new GPoint(18, 43);
				    baseIcon.infoWindowAnchor = new GPoint(9, 2);
				    baseIcon.infoShadowAnchor = new GPoint(18, 25);
					baseIcon.image = "/Images/Global/map_icon.png";
					
					var marker = new GMarker(point, baseIcon);
					map.addOverlay(marker);
					
					//marker.openInfoWindowHtml(address);
				}
			}
		);
		
	}
	
}

function showRouteOnMap(route, launcher){
	
	if(currentRoute != ""){ map.removeOverlay(currentRoute); }
	
	switch(route){
	
	case 1: /* from northern & southern motorways */
		var polyline = new GPolyline([
			new GLatLng(-36.85273712538665, 174.77346897125244),
			new GLatLng(-36.85088274365454, 174.77527141571045),
			new GLatLng(-36.851226151072794, 174.77630138397217),
			new GLatLng(-36.85048782321647, 174.77709531784058),
			new GLatLng(-36.84986968278299, 174.77827548980713),
			new GLatLng(-36.85089991406209, 174.77887630462646)
		], "#b31111", 5);
		break;
	case 2: /* from newmarket */
		var polyline = new GPolyline([
			new GLatLng(-36.86456633509247, 174.7791337966919),
			new GLatLng(-36.86218003818444, 174.78177309036255),
			new GLatLng(-36.86046323172769, 174.78276014328003),
			new GLatLng(-36.85891807293982, 174.78293180465698),
			new GLatLng(-36.85764758564406, 174.78185892105103),
			new GLatLng(-36.85199881212365, 174.778254032135),
			new GLatLng(-36.851226151072794, 174.77630138397217),
			new GLatLng(-36.85048782321647, 174.77709531784058),
			new GLatLng(-36.84986968278299, 174.77827548980713),
			new GLatLng(-36.85089991406209, 174.77887630462646)
		], "#b31111", 5);
		break;
	case 3: /* from strand */
		var polyline = new GPolyline([
			new GLatLng(-36.8494060741779, 174.78248119354248),
			new GLatLng(-36.84997270653566, 174.78185892105103),
			new GLatLng(-36.848890950208286, 174.77954149246216),
			new GLatLng(-36.84950909855533, 174.77750301361084),
			new GLatLng(-36.850298947503184, 174.77647304534912),
			new GLatLng(-36.851123129009295, 174.77591514587402),
			new GLatLng(-36.851226151072794, 174.77630138397217),
			new GLatLng(-36.85048782321647, 174.77709531784058),
			new GLatLng(-36.84986968278299, 174.77827548980713),
			new GLatLng(-36.85089991406209, 174.77887630462646)
		], "#b31111", 5);
		break;
	
	}
	
	map.addOverlay(polyline);
	map.setZoom(16);
	currentRoute = polyline;
	
}

function setRouteLinks(){
	$("#from-southern").click( function(){showRouteOnMap(1)} );
	$("#from-northern").click( function(){showRouteOnMap(1)} );
	$("#from-newmarket").click( function(){showRouteOnMap(2)} );
	$("#from-strand").click( function(){showRouteOnMap(3)} );
}

// PORTFOLIO ===================================================================

function InitPortfolio(){
	/*$("#portfolio-list").removeClass("image-listing");
	$("#portfolio-list").addClass("thumbnail-list");*/
	Equalise($(".thumbnail-list li span.title"));
	InitFilters();
	InitViews();
	SetBiggerClick();
}

function InitClientColapse() {

	$('.client-portfolio-list > h2').each(function() {
		var text = $(this).text();
		$(this).html('<a href="#">' + text + '</a>');
		$(this).addClass('closed');
	});

	$('.client-portfolio-list > h2 > a').toggle(
		function() {
			var wrapper = $(this).parents('.client-portfolio-list');
			wrapper.find('ul').slideDown('fast');
			wrapper.children('h2').removeClass('closed').addClass('open');
		}, function() {
			var wrapper = $(this).parents('.client-portfolio-list');
			wrapper.find('ul').slideUp('fast');
			wrapper.children('h2').removeClass('open').addClass('closed');
		}
	);
}

function InitFilters() {
	State = "thumbs-view";
    var action = "stack"; // or "stack"
	if(!window.location.search){ // only do fade filtering if they're on the straight port page, not if they've ocome in on query string filtering

		$(".filter-list li a").click(
			function() {
				$(".filter-list li a").removeClass("selected");
				$(this).addClass("selected");
				var filterBy = $(this).attr("rel");
				var filterTitle = $(this).text();
				filterTitle = filterTitle.replace('/', '<span>/</span>');
				$("#portfolio-list li").each(
					function() {
						if ($(this).hasClass(filterBy) || filterBy == "All") {
							if (State == "thumbs-view") {
								if (action == "fade") {
									$(this).fadeTo("fast", 1);
								} else {
									$(this).hide();
									$(this).addClass("visable");
								}
							} else {
								$(this).show();
							}
						} else {
							if (State == "thumbs-view") {
								if (action == "fade") {
									$(this).fadeTo("fast", 0.20);
								} else {
									$(this).hide();
									$(this).removeClass("visable");
								}
							} else {
								$(this).hide();
							}
						}
					}
				);
				if (State == "thumbs-view") {
					// **** setup stack view *****//
					$("#portfolio-list li.visable").each(function() {
						$(this).removeClass("no-right-margin");
					});
					SetListClass("#portfolio-list li.visable", "no-right-margin", "5");
					$("#portfolio-list li.visable").fadeIn(800);
				}
				if (filterBy == "All") {
					$("#portfolio-list-head").html("<span>/</span> All Projects");
				} else {
					$("#portfolio-list-head").html(filterTitle);
				}
				return false;
			}
		);
		
	}
}

function InitViews() {
	$(".switch-view").show();
	$("#portfolio-list li p").hide();
	/*
	$("#portfolio-list li").addClass("clickable");
	$(".view-list li a").click(
	function(){
	$(".view-list li a").each(function(){
	$(this).removeClass("selected");
	});
	$(this).addClass("selected");
	var theView = $(this).attr("rel");
	switch(theView){
	case("thumbs-view"):
	$("#view-all").trigger("click");
	$("#portfolio-list").addClass("thumbnail-list");
	$("#portfolio-list").removeClass("image-listing");
	$("#portfolio-list li p").hide();
	$("#portfolio-list li").show();
	State = "thumbs-view";
	break;
	case("img-list-view"):
	$("#view-all").trigger("click");
	$("#portfolio-list").removeClass("thumbnail-list");
	$("#portfolio-list").addClass("image-listing");
	$("#portfolio-list li p").show();
	State = "list-view";
	break;
	default:
	// oops
	break;
	}
	return false;
	}
	);
	*/
}

// JOBS ========================================================================
function InitJobs(){
	// set inputs type 'file'
	if( jQuery.browser.mozilla  ){
		$(".file-input").attr("size", 45);
	}
	$(".contact-form").hide();
	$(".apply-for-job").css({"display":"block"});
	$(".job-contact-form").css({"margin": "-2em 0 3em 0"});
	$(".apply-for-job").toggle(
		function(){
			//$(this).parent().next(".contact-form").slideDown("fast");
			$(this).next(".contact-form").slideDown("fast");
			$(this).text("Close this form");
			return false;
		},
		function(){
			//$(this).parent().next(".contact-form").slideUp("fast");
			$(this).next(".contact-form").slideUp("fast");
			$(this).text("Apply for this job");
			return false;
		}
	);
}

// SERVICES ====================================================================
function InitServices(){
	$(".service-container").hide();
	$(".show-service").addClass("cursor");
	$(".show-service").each(function() { var text = $(this).text(); $(this).html('<a href="#" class="closed">' + text + '</a>'); });
	$(".click-below").show();
	/*$(".show-service").hover(
		function(){
			if(!this.isSelected){
				$(this).addClass("selected-service");
			}
		},
		function(){
			if(!this.isSelected){
				$(this).removeClass("selected-service");
			}
		}
	);*/
	$(".show-service a").toggle(
		function() {
			$(this).parent().next(".service-container").slideDown("fast");
			//$(this).addClass("selected-service");
			$(this).removeClass('closed').addClass('open');
			this.isSelected = true;
			return false;
		},
		function() {
			$(this).parent().next(".service-container").slideUp("fast");
			//$(this).removeClass("selected-service");
			$(this).removeClass('open').addClass('closed');
			this.isSelected = false
			return false;
		}
	);
	// auto open & scroll to service if directly linked to
	if(location.hash){
		$(location.hash + ' a').trigger("click");
		var pos = $(location.hash).offset();
		$("html").animate({ scrollTop: pos.top + "px" }, { duration: 500 });
	}
	
}

// UTILS =======================================================================

// COOKIES =====================================================================
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name)
{
	createCookie(name,"",-1);
}


function getTwits() {
	$.getJSON('http://search.twitter.com/search.json?q=TerabyteNZ&callback=?', function(data) {
		if (data != null) {
			$.each(data, function(i, tweets) {
				if (tweets.length != undefined) {
					if (tweets[0] != undefined) {
						if (tweets[0].created_at != undefined) {
							for (var i = 0; i < tweets.length && i < 2; i++) {
								/*var extraInfo = '<br /> <span class="date-time">' + timeAgo(tweets[i].created_at) + 
								'</span>';
								$("<p>" + tweets[i].text + extraInfo + "</p>").tweetify().appendTo(".twitter-pod");*/
								var extraInfo = '<br /> <span class="date-time">' + timeAgo(tweets[i].created_at) +
								', From: '+tweets[i].from_user+'</span>';
								$("<p>" + tweets[i].text + extraInfo + "</p>").tweetify().appendTo(".twitter-pod");
							}
						}
					}
				}
			});
			$("<a href=\"http://twitter.com/TerabyteNZ\" class=\"find-or-follow follow-tweets floatLeft clear\">Follow us</a>").appendTo(".twitter-pod");
			Equalise($(".short"));
		} else {

		}
	});
}

$.fn.tweetify = function() {
	this.each(function() {
		$(this).html(
			$(this).html()
				.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi, '<a href="$1">$1</a>')
				.replace(/(^|\s)#(\w+)/g, '$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>')
				.replace(/(^|\s)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
		);
	});
	return $(this);
}

function timeAgo(dateString) {
	var rightNow = new Date();
	var then = new Date(dateString);
	if ($.browser.msie) {
		// IE can't parse these crazy Ruby dates
		then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
	}
	var diff = rightNow - then;
	var second = 1000, minute = second * 60, hour = minute * 60, day = hour * 24, week = day * 7;
	if (isNaN(diff) || diff < 0) {
		return ""; // return blank string if unknown
	}

	if (diff < second * 7) {
		// within 7 seconds
		return "right now";
	}

	if (diff < minute) {
		return Math.floor(diff / second) + " seconds ago";
	}

	if (diff < minute * 2) {
		return "about 1 minute ago";
	}

	if (diff < hour) {
		return Math.floor(diff / minute) + " minutes ago";
	}

	if (diff < hour * 2) {
		return "about 1 hour ago";
	}

	if (diff < day) {
		return Math.floor(diff / hour) + " hours ago";
	}

	if (diff > day && diff < day * 2) {
		return "yesterday";
	}

	if (diff < day * 365) {
		return Math.floor(diff / day) + " days ago";
	}

	else {
		return "over a year ago";
	}
}

function Initsignup() {

	var showBtn = '<a class="show-newsletter" href="#">Subscribe for our newsletter</a>';
	var hideBtn = '<a class="hide-newsletter" style="display:none;" href="#">Back to latest news</a>';

	if ($('.news-letter-pod .signup-succsess').length == 0) {
		$('.news-letter-pod').append(showBtn);
		$('.news-letter-pod').append(hideBtn);

		var newsHeight = $('.latest-news-cont').height();
		var formHeight = $('.signup-newsletter ul').height();

		$('.show-newsletter').click(function() {
			$('.latest-news-cont').hide();
			$('fieldset.signup-newsletter').show();
			$(this).hide();
			$('.hide-newsletter').show();
			$('.signup-newsletter').css('min-height', Math.max(newsHeight, formHeight)+'px');
			return false;
		});
		$('.hide-newsletter').click(function() {
			$('fieldset.signup-newsletter').hide();
			$('.latest-news-cont').show();
			$(this).hide();
			$('.show-newsletter').show();
			return false;
		});
	}

}

var Twitter = {

	WrapUrls: function(text) {
		var urlPattern = /(http:\/\/[A-Za-z0-9\.\-\/]+)/g;
		var urlsAdded = text.replace(urlPattern, '<a rel="external" href="$1">$1</a>');
		var usernames = /(@[A-Za-z0-9_]{1,15})/g;
		var usernamesAdded = urlsAdded.replace(usernames, '<a rel="external" href="http://www.twitter.com/$1">$1</a>');
		return usernamesAdded;
	},

	InitTwitterFeed: function() {

		//Ultimate Hikes ID: 97349912
		//Tweet/Retweets Feed: http://search.twitter.com/search.json?q=from%3AUltimateHikes
		//Mentions Feed (i.e. #UltimateHikes): http://search.twitter.com/search.json?q=%23UltimateHikes&callback=?
		//consider favourites feed: http://twitter.com/favorites/Username.json?callback=TWTR.Widget.receiveCallback_1&clientsource=TWITTERINC_WIDGET
		$.getJSON('http://search.twitter.com/search.json?q=TerabyteNZ&callback=?',
            function(data) {
            	$.each(data, function(i, tweets) {
            		if (tweets.length != undefined) {
            			if (tweets[0] != undefined) {
            				if (tweets[0].created_at != undefined) {
            					for (var i = 0; i < tweets.length && i < 2; i++) {
            						var extraInfo = '<br /> <span class="date-time">' + timeAgo(tweets[i].created_at) +
									', From: ' + Twitter.WrapUrls("@"+tweets[i].from_user) + '</span>';            						
            						$("<p>"
								        + Twitter.WrapUrls(tweets[i].text) +
								        extraInfo +
							        "</p>").appendTo(".twitter-pod");
            					}
            				}
            			}
            		}
            	});
            	$("<a href=\"http://twitter.com/TerabyteNZ\" class=\"find-or-follow follow-tweets floatLeft clear\">Follow us</a>").appendTo(".twitter-pod");
            	Equalise($(".short"));
            	$('.twitter-pod p a').click(function(event) {
            		window.open(this.href);
            		event.preventDefault();
            	});
            }
        );
	}
}

var javarotator = {
	timeOutID: "", //Gets Set my setInterval
	init: function() {
		$('.java-rotator li:not(.loaded)').each(function() {
			var path = $(this).text();
			var link = $(this).find('a');
			var item = $(this);
			$(this).image(path, function() {
				if (link.length > 0) {
					item.html('<a href="' + link.attr('href') + '" title="' + link.attr('title') + '"><img src="' + path + '" alt="' + link.attr('title') + '" /></a>');
				} else {
					item.html('<img src="' + path + '" alt="' + link.attr('title') + '" />');
				}
				item.addClass('loaded');
				javarotator.checkstatus(item);
			});
		});
		javarotator.timeOutID = setInterval("javarotator.movenext($(\".java-rotator\"))", 8000);
	},
	checkstatus: function(item) {
		item = item.parent();

		if (item.find('li').length == item.find('.loaded').length) {
			item.find('.loaded').addClass('item').removeClass('loaded');

			item.append('<li class="control prev"><a title="previous item" href="#" class="prev"></a></li><li class="control next"><a title="next item" href="#" class="next"></a></li>');

			item.find('a.next').click(function() {
			clearTimeout(javarotator.timeOutID); //clear the automatic timer
				javarotator.movenext(item);
				return false;
			});

			item.find('a.prev').click(function() {
				clearTimeout(javarotator.timeOutID); //clear the automatic timer
				javarotator.moveprev(item);
				return false;
			});

			$('.java-rotator .item a').each(function() {
				var title = $(this).attr('title');
				//$(this).append('<span class="overlay">View the ' + title + ' project</span>');
				//var titleOverlay = $(this).find('.overlay');
				//titleOverlay.css({ 'opacity': '0', 'display': 'block' });
			});
			$('.java-rotator .item a').hover(
				function() {
					var titleOverlay = $(this).find('.overlay');
					var titleHeight = titleOverlay.height();
					var padding = (360 - titleHeight) / 2;
					titleOverlay.css({ 'padding-top': padding + 'px', 'padding-bottom': padding + 'px', 'height': titleHeight + 'px' });
					$(this).find('.overlay').show().fadeTo('fast', .75);
				}, function() {
					$(this).find('.overlay').fadeTo('fast', 0);
				}
			);
		}
	},
	movenext: function(item) {
		var pauseTime = 0;
		var noOfImgs = item.find('.item').length;
		var current = item.find('.current');
		var next;
		for (var i = 0; i < noOfImgs; i++) {
			if (item.find('.item').eq(i).is('.current') && i < (noOfImgs - 1)) {
				next = item.find('.item').eq(i + 1);
				//console.log(item.find('.item').eq(i).hasClass('.current') + ' index[' + i + ']');
				break;
			} else {
				next = item.find('.item').eq(0);
			}
		}

		next.addClass('current').hide().fadeIn(500);
		current.removeClass('current').show().fadeOut(350);
	},
	moveprev: function(item) {
		var pauseTime = 0;
		var noOfImgs = item.find('.item').length;
		var current = item.find('.current');
		var next;
		for (var i = 0; i < noOfImgs; i++) {
			if (item.find('.item').eq(i).is('.current') && i > 0) {
				next = item.find('.item').eq(i - 1);
				break;
			} else {
				next = item.find('.item').eq(noOfImgs - 1);
			}
		}

		next.addClass('current').hide().fadeIn(500);
		current.removeClass('current').show().fadeOut(350);
	}
}

var clientrotator = {
	init: function() {
		var highest = 0;
		for (var i = 0; i < $('.client-rotator li').length; i++) {
			highest = Math.max(highest, $('.client-rotator li').eq(i).height());
		}
		$('.client-rotator').height(highest);
		$('.client-rotator').append('<li class="controls"><a class="prev" title="Show previuos quote" href="#">&laquo;</a><a class="next" title="Show next quote" href="#">&raquo;</a></li>');

		$('.client-rotator a.prev').click(function() {
			clientrotator.moveprev($(this).parent().parent()); 
			return false; 
		});
		$('.client-rotator a.next').click(function() {
			clientrotator.movenext($(this).parent().parent());
			return false; 
		});
	},
	movenext: function(item) {
		var pauseTime = 0;
		var noOfImgs = item.find('.item').length;
		var current = item.find('.current');
		var next;
		for (var i = 0; i < noOfImgs; i++) {
			if (item.find('.item').eq(i).is('.current') && i < (noOfImgs - 1)) {
				next = item.find('.item').eq(i + 1);
				//console.log(item.find('.item').eq(i).hasClass('.current') + ' index[' + i + ']');
				break;
			} else {
				next = item.find('.item').eq(0);
			}
		}

		next.addClass('current').hide().fadeIn(500);
		current.removeClass('current').show().fadeOut(350);
	},
	moveprev: function(item) {
		var pauseTime = 0;
		var noOfImgs = item.find('.item').length;
		var current = item.find('.current');
		var next;
		for (var i = 0; i < noOfImgs; i++) {
			if (item.find('.item').eq(i).is('.current') && i > 0) {
				next = item.find('.item').eq(i - 1);
				break;
			} else {
				next = item.find('.item').eq(noOfImgs - 1);
			}
		}

		next.addClass('current').hide().fadeIn(500);
		current.removeClass('current').show().fadeOut(350);
	}
}

var terabyte = {
	javarotator: javarotator,
	clientrotator: clientrotator
}