(function($) {
	$.fn.randomize = function(childElem,itemsPerLine,maxItems) {
		return this.each(function() {
			var $this = $(this);
			var elems = $this.children(childElem);

			elems.sort(function() { return (Math.round(Math.random())-0.5); });  

			$this.remove(childElem);

			for(var i=0; i < elems.length; i++){
				$this.append(elems[i]);
				if(i >= maxItems){
					$(elems[i]).css('display','none');
				}
				var remainderAmount = ((i+1) % itemsPerLine);
				if(remainderAmount == 0){
					$(elems[i]).attr('class','people height');
				}
			}
		});    
	}
})(jQuery);



var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function nav_open(){
	nav_canceltimer();
	nav_close();
	$(".people").css('z-index','1');
	$(this).css('z-index','200');

	var documentWidth = $(window).width();
	var pageWidth = $('#container').width();
	var pageMargin = (documentWidth-pageWidth)/2;
	var divLeft = $(this).position().left - pageMargin;
	var popUpWidth = $(this).find('.people-pop-up').width();
	var popUpOffset = 20;
	var maximumLeftPos = divLeft + popUpOffset + popUpWidth;

	if((maximumLeftPos + pageMargin + 20) > documentWidth){
		var offsetAmount = (maximumLeftPos - divLeft - 96);
		popUpLeft = '-' + offsetAmount  + 'px';
	}else{
		popUpLeft = popUpOffset + 'px';
	}

	ddmenuitem = $(this).find('.people-pop-up').css({'left': popUpLeft, 'display': 'block'});
}

function nav_close(){
	$(this).css('z-index','1');
	if(ddmenuitem) ddmenuitem.css('display', 'none');
}

function nav_timer(){
	closetimer = window.setTimeout(nav_close, timeout);
}

function nav_canceltimer(){
	if(closetimer){
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}


$(document).ready(function(){

	//Flickr link (can't be embedded into macro)
	//$('.facebook').attr('href','http://www.facebook.com/search/?q=Octopus&init=quick#/group.php?v=wall&ref=search&gid=5346349162');

	var bodyClass = $('body').attr('class');
	var thumbnailItems = 0
	if (bodyClass = 'our-clients'){
		thumbnailItems = 100;
	}else{
		thumbnailItems = 8;
	}

	$('embed').each(function(){
		var embedHref = $(this).attr('src');
		var isYouTube = embedHref.indexOf('youtube.com');
		if(isYouTube > 0){
			$(this).attr({'width':'230px','height':'186px'});
		}
	});


	$('.latest-news-items, .macro-header').prev('p').remove();


	//Open external links in new window
	$(".new").attr("target","_blank");
	
	//Expandable items
	$("h3.expandable").click(function(){
		$(this).next().animate({ height: "toggle" }, 500);
		$("a",this).toggleClass("open"); 
		return false;
	});

	//People tooltips
	$('.people').bind('mouseover', nav_open);
	$('.people').bind('mouseout',  nav_timer);

	//Randomise thumbnails
	$('div.thumbs-people').randomize('div.people',6,12);
	$('div.thumbs-other').randomize('div.people',4,thumbnailItems);

});


document.onclick = nav_close;