function tabs_init()
{
	$(this).children('h2').after('<ul class="tab_links clearfix"></ul>');
		
	var tabs = [];
	$(this).children('.tab')
		.each(
			function()
			{
				var id = $(this).attr('id');
				var name = $(this).children('h3').text();
				tabs.push([id, name]);
				$(this).children('h3').remove();
				$(this).hide();
			}
		);
		
	for (var i in tabs)
	{
		$(this).children('.tab_links')
			.append('<li><a href="#' + tabs[i][0] + '">' + tabs[i][1] + '</a></li>')
	}
	
	$(this).children('.tab_links').children('li').click(tab_click);
	$(this).children('.tab_links').children('li:first').trigger('click');
	$(this).children('.tab_links').children('li:last').addClass('last');
}

function tab_click()
{	
	$(this)
		.siblings('.current')
			.removeClass('current')
			.click(tab_click);
			
	$(this)
		.addClass('current')
		.unbind('click');
	
	$(this).parent().parent().children('.tab').hide();
	
	// Anchor contains full path in ie6 so must split
	var anchor = $(this).children('a').attr('href').split("#");
	var anchor = '#' + anchor[1];
	$(anchor).show();
	
	footer_stick();
	
	return false;
}

function footer_init()
{
	//$('#footer_sitemap').hide();
	var padding_left = $('#footer h4').css('padding-left').replace('px','');
	$('#footer h4').css('padding-left', 0);
	$('#footer h4 a')
		.css('padding-left', padding_left+'px')
		.addClass('tictac_open')
		.click(footer_toggle);
	footer_toggle();
	footer_stick();
	$(window).bind('resize', footer_stick);
}

function footer_toggle()
{
	$('body').addClass('body_js');
	$('#footer h4 a')
		.toggleClass('tictac_open')
		.toggleClass('tictac_closed');
	$('#footer_sitemap').toggle();
	//footer_stick();
}

function footer_stick()
{
	var window_height = $(window).height();
	var content_height = $('#header').height() 
		+ $('#content').height()
		+ $('#footer').height() 
		+ parseInt($('#header').css('padding-top').replace('px',''))
		+ parseInt($('#content').css('padding-bottom').replace('px',''));
		
	if (window_height >= content_height)
	{
		$('#footer')
			.css('position','relative')
			.css('top', (window_height - content_height - 1) + 'px');
	};
}

function search_init()
{
	$('#s')
		.bind('focus blur', function()
			{
				var s = $(this).attr('value');
				if (s == 'Search the site')
					$(this).attr('value', '');
				else if (!s || s == '')
					$(this).attr('value', 'Search the site');
			}
		);
}

function newsletter_init()
{
	if ($('#newsletter_email').length == 0)
		return false;
	
	$('#newsletter_email')
		.bind('focus blur', function()
			{
				var a = $(this).attr('value');
				if (a == 'Email address')
					$(this).attr('value', '');
				else if (!a || a == '')
					$(this).attr('value', 'Email address');
			}
		);
}

function home_carousel_init()
{
	if ($('#home_carousel').length == 0)
		return false;
	
	//$('#home_carousel img').css('position', 'absolute');
	$('#home_carousel img:gt(0)').hide();
	$('#home_carousel').data('current', 0);
	setInterval('home_carousel_next()', 6000);
}

function home_carousel_next()
{
	var current = $('#home_carousel').data('current');
	$('#home_carousel img:eq('+current+')').fadeOut(1000);	
	var next = ($('#home_carousel img').length > (current+1)) ? current+1 : 0;
	$('#home_carousel').data('current', next);
	$('#home_carousel img:eq('+(next)+')').fadeIn(2000);
	
}


function what_we_do_carousel_init()
{
	if ($('#what_we_do_carousel').length == 0)
		return false;
	
	//$('#what_we_do_carousel img').css('position', 'absolute');
	$('#what_we_do_carousel img:gt(0)').hide();
	$('#what_we_do_carousel').data('current', 0);
	setInterval('what_we_do_carousel_next()', 4000);
}

function what_we_do_carousel_next()
{
	var current = $('#what_we_do_carousel').data('current');
	$('#what_we_do_carousel img:eq('+current+')').fadeOut(1500);	
	var next = ($('#what_we_do_carousel img').length > (current+1)) ? current+1 : 0;
	$('#what_we_do_carousel').data('current', next);
	$('#what_we_do_carousel img:eq('+(next)+')').fadeIn(2300);
	
}


function contact_map_init()
{
	if ($('#contact_map').length == 0)
		return false;
		
	if (typeof(window['GBrowserIsCompatible']) == 'undefined')
		return false;
		
	if (GBrowserIsCompatible()) 
	{
		
		$('#contact_map').addClass('contact_map');
		var map = new GMap2(document.getElementById("contact_map"));
		
		var point = new GLatLng(51.522701,-0.08548);
		map.setCenter(new GLatLng(51.525473,-0.085166), 15);

		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());

		
		
		// Create Foviance 'disc' marker icon
		var icon = new GIcon();
		icon.image = "http://www.foviance.com/wp-content/uploads/2009/05/foviance-disc-small.jpg";
		icon.iconSize = new GSize(20, 20);
		icon.iconAnchor = new GPoint(5, 19);
		icon.infoWindowAnchor = new GPoint(5, 1);
		

		var marker = new GMarker(point, icon);
		GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml('<p style=\"float:right;margin-right:5px;width:120px;height:110px\">Foviance\'s London office is located at 14 Bonhill Street, London.<br/><a href=\"http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&q=14+Bonhill+St,+Islington,+Greater+London+EC2A+4,+United+Kingdom&sll=53.800651,-4.064941&sspn=19.248626,57.084961&ie=UTF8&cd=2&geocode=FZssEgMdJrL-_w&split=0&hq=&hnear=14+Bonhill+St,+London+EC2A+4BX,+United+Kingdom&ll=51.522673,-0.084787&spn=0.001198,0.003484&z=19&layer=c&cbll=51.522666,-0.084649&panoid=OuapaOzC0N-eS84gyfBuWQ&cbp=12,316.63,,0,-9.83\">Google street view</a></p><img style=\"margin-right:8px\" src=\"http://www.foviance.com/wp-content/uploads/2009/05/foviance-office-building.jpg\">', {maxWidth: 220} );
		});

		map.addOverlay(marker);

		marker.openInfoWindowHtml('<p style=\"float:right;margin-right:5px;width:120px;height:110px\">Foviance\'s London office is located at 14 Bonhill Street, London.<br/><a href=\"http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&q=14+Bonhill+St,+Islington,+Greater+London+EC2A+4,+United+Kingdom&sll=53.800651,-4.064941&sspn=19.248626,57.084961&ie=UTF8&cd=2&geocode=FZssEgMdJrL-_w&split=0&hq=&hnear=14+Bonhill+St,+London+EC2A+4BX,+United+Kingdom&ll=51.522673,-0.084787&spn=0.001198,0.003484&z=19&layer=c&cbll=51.522666,-0.084649&panoid=OuapaOzC0N-eS84gyfBuWQ&cbp=12,316.63,,0,-9.83\">Google street view</a></p><img style=\"margin-right:8px\" src=\"http://www.foviance.com/wp-content/uploads/2009/05/foviance-office-building.jpg\">', {maxWidth:220} );
	
		
		
		
		
		
		
		
		
		
		//$('#contact_map').addClass('contact_map');
		//var map = new GMap2(document.getElementById("contact_map"));
		//map.setCenter(new GLatLng(51.52257, -0.08547), 15);
		//map.setCenter(new GLatLng(51.522723,-0.085402), 15);
		//map.addControl(new GLargeMapControl());
		//map.addControl(new GMapTypeControl());


		// Create Foviance 'disc' marker icon
		//var icon = new GIcon();
		//icon.image = "http://www.foviance.com/wp-content/uploads/2009/05/foviance-disc-small.jpg";
		//icon.iconSize = new GSize(40, 41);
		//icon.iconAnchor = new GPoint(30, -10);
		//icon.infoWindowAnchor = new GPoint(5, 1);
		
		
		
		//var windowContent = "map.getCenter(),'<img src=\"http://www.foviance.com/wp-content/uploads/2009/05/foviance-office-building.jpg\" alt=\"Foviance is located at 14 Bonhill Street, London.\">';
		
		
		
		//var marker = new GMarker(point, icon);
		//GEvent.addListener(marker, "click", function() {
		//marker.openInfoWindowTabsHtml(infoTabs, {maxWidth: 400} );
		//});

				
		
		//var marker = new GMarker(point, icon);
		//GEvent.addListener(marker, "click", function() {
		//marker.openInfoWindowTabsHtml(, {maxWidth: 220} );
		//});

				
		
		}
}


function contact_map_zh_init()
{
	if ($('#contact_map_zh').length == 0)
		return false;
		
	if (typeof(window['GBrowserIsCompatible']) == 'undefined')
		return false;
		
	if (GBrowserIsCompatible()) 
	{
		
		$('#contact_map_zh').addClass('contact_map');
		var map = new GMap2(document.getElementById("contact_map_zh"));
		
		
		var point = new GLatLng(22.2793277146398, 114.16148900985718);
		map.setCenter(new GLatLng(22.2793277146398, 114.16148900985718), 15);

		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());

		
		
		// Create Foviance 'disc' marker icon
		var icon = new GIcon();
		icon.image = "http://www.foviance.com/wp-content/uploads/2009/05/foviance-disc-small.jpg";
		icon.iconSize = new GSize(20, 20);
		icon.iconAnchor = new GPoint(5, 19);
		icon.infoWindowAnchor = new GPoint(5, 1);
		
		var marker = new GMarker(point, icon);
		GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml('<p style=\"float:right;margin-right:5px;width:120px;height:110px\">[zh-translation-required]Foviance\'s China office is located at XXXX</p><img style=\"margin-right:8px\" src=\"http://www.foviance.com/wp-content/uploads/2009/05/foviance-office-building.jpg\">', {maxWidth: 220} );
		});

		map.addOverlay(marker);

		marker.openInfoWindowHtml('<p style=\"float:right;margin-right:5px;width:120px;height:110px\">[zh-translation-required]Foviance\'s China office is located at XXXX</p><img style=\"margin-right:8px\" src=\"http://www.foviance.com/wp-content/uploads/2009/05/foviance-office-building.jpg\">', {maxWidth:220} );
	
		}
}

function client_list_init()
{
	if ($('#client_list').length == 0) 
		return false;
	
	// Create paging div
	$('#client_list').parent().children('h1')
		.after(
			'<div id="case_studies_paging_t" class="clearfix"><div class="paging"><span>Sector</span><ul><li class="current"><a href="#">All</a></ul></div></div>'
		);
	
	// Get categories and items
	var categories_count = $('#client_list h2').length;
	var client_list_items = [];
	
	$('#client_list h2').each(
		function(i)
		{
			var category = $(this).text();
			var style = (i == (categories_count - 1)) ? ' class="last"' : '';
			var id = $(this).attr('id');
			
			$('#case_studies_paging_t ul')
				.append('<li id="category_' + id + '"' + style + '><a href="#">' + category + '</a></li>');
				
			$(this).next().children().each(
				function(i)
				{
					client_list_items.push([$(this).html(), id]);
					$(this).remove();
				}
			)
				
			$(this).remove();
		}
	);
	
	// Sort items
	client_list_items.sort(client_list_sort);
	
	// Remove all except first row
	$('.row:gt(0)').remove();
	
	// Add columns if less than 4
	if ($('.row div').length < 4)
	{
		var div_class = $('.row div:first').attr('class');
		var d = 4 - $('.row div').length;
		for (var i = 1; i <= d; i++)
		{
			$('.row').append('<div class="'+div_class+'"><ul></ul></div>');
		}
	}
	
	// Put items back into columns
	var column_count = Math.ceil(client_list_items.length/4);
	var item_count = 0;
	var column = 0;
	for (var i in client_list_items)
	{
		if (item_count >= column_count)
		{
			item_count = 0;
			column++;
		}
		
		client_list_items[i][0] = jQuery.trim(client_list_items[i][0]);
		$('.row div:eq(' + column + ') ul')
			.append('<li class="category_' + client_list_items[i][1] + '">' + client_list_items[i][0] + '</li>');
	
		item_count++;
	}
	
	// Attach click actions
	$('#case_studies_paging_t li')
		.bind('click',
			function()
			{
				$(this).siblings().removeClass('current');
				$(this).addClass('current');
				client_list_filter($(this).attr('id'));
				return false;
			}
		);
	
}

function client_list_sort(a, b)
{
	a = a[0];
	b = b[0];
	
	var a_temp = a.split('>');
	var b_temp = b.split('>');
	
	if (a_temp.length > 1)
		a = a_temp[1];
		
	if (b_temp.length > 1)
		b = b_temp[1];
		
	if (a > b)
		return 1;
	else if (a == b)
		return 0;
	else if (a < b)
		return -1;
}

function client_list_filter(category)
{
	if (category != '')
	{
		$('#client_list li.'+category).removeClass('client_list_faded');
		$('#client_list li:not(.'+category+')').addClass('client_list_faded');
	}
	else
	{
		$('#client_list li').removeClass('client_list_faded');
	}
}

function thumbnail_borders_init()
{
	$('.crop').each(
		function(i)
		{
			var width = parseInt($(this).parent().css('width').replace('px', '')) - 2;
			var height = $(this).find('img').attr('height') - 2;
			var a_margin_bottom = ($(this).children('a').length > 0) ? $(this).children('a').css('margin-bottom').replace('px', '') : 0;
			var margin_bottom = parseInt(a_margin_bottom);
			
			$(this).css('width', width);
			$(this).css('height', height);
			$(this).css('margin-bottom', margin_bottom+'px');
			$(this).css('border', '1px solid #d2d2c8');
		}
	);
}

function timeline_init()
{
	if ($('#timeline_nojs').length == 0) 
		return false;
		
	var item_count = Math.round($('#timeline_nojs .span_in3x4_1x3').length / 2);
	
	$('#timeline_nojs').before('<div id="timeline"><div id="timeline_wrapper"></div></div>');
	
	$('#timeline_nojs .span_in3x4_1x3').each(
		function(i)
		{	
			var item = $(this).clone().appendTo('#timeline_wrapper');
		
			item
				.removeClass('span_in3x4_1x3')
				.addClass('span_in4x4_1x4')
				.addClass('timeline_item');
			
			/*
			item.find('.timeline_nojs_item_date')
				.removeClass('timeline_nojs_item_date')
				.addClass('timeline_item_date')
				.addClass('span_in4x4_1x4');
			*/
			
			//var date_txt = item.find('.timeline_nojs_item_date').text();
			//alert(date_html);
			
			//item.find('.timeline_nojs_item_date')
			//	.remove();
				
			item.find('.timeline_nojs_item_content')
				.removeClass('timeline_nojs_item_content')
				.addClass('timeline_item_content');
				//.find('div p').hide();
				
			item.find('.timeline_item_content')
				.find('h3');
				//.text(date_txt);
				
			var x = (item.width() + parseInt(item.css('margin-right').replace('px', ''))) * i;
			x = (x/10) + 'em';
			//item.css('position', 'absolute').css('left', x)
			item.css('left', x);

			/*
			item.hover(
				function() {
					$(this).find('.timeline_item_content div p').slideDown('fast');
				},
				function() {
					$(this).find('.timeline_item_content div p').slideUp('fast');
				}
			);
			*/
			
		}
	)
	$('#timeline_nojs').remove();
	
	// Create controls
	//if ($('#timeline_nojs .span_in3x4_1x3').length > 2)
	//{
		$('#timeline')
			.append('<a id="timeline_left" class="timeline_scroll" href="#"></a>')
			.append('<a id="timeline_right" class="timeline_scroll" href="#"></a>');
	//}
		
	$('#timeline_left')
		.click(function() {
			timeline_scroll(1);
			return false;
		})
		.css('cursor', 'pointer')
		.hide();
	
	$('#timeline_right')
		.click(function() {
			timeline_scroll(-1);
			return false;
		})
		.css('cursor', 'pointer');

	// Create timeline ticks
	$('#timeline').before('<div class="timeline_ticks"></div>').after('<div class="timeline_ticks"></div>');
	
	for (var i = 0; i < item_count; i++)
	{
		var width = 100/item_count + '%';
		$('.timeline_ticks').append('<div class="timeline_tick" style="width:' + width + '"><a></a></div>');			
		$('.timeline_ticks:first .timeline_tick:last a').data('i', i);
		$('.timeline_ticks:last .timeline_tick:last a').data('i', i);
	}
	
	$('.timeline_tick a')
		.click(function() {
			var i = $(this).data('i');
			var d = (i - $('.timeline_tick a.current').data('i'))*-1;
			timeline_scroll(d, true);
			
			$('.timeline_tick a.current').removeClass('current');
			$('.timeline_ticks:first .timeline_tick:eq('+i+') a').addClass('current');
			$('.timeline_ticks:last .timeline_tick:eq('+i+') a').addClass('current');
		})
		.css('cursor', 'pointer');
	
	$('.timeline_ticks:first .timeline_tick:first a').addClass('current');
	$('.timeline_ticks:last .timeline_tick:first a').addClass('current');

	// Animate in
	var width = $('#timeline_wrapper .timeline_item:first').width() + parseInt($('#timeline_wrapper .timeline_item:first').css('margin-right').replace('px', ''));
	$('#timeline_wrapper').css('left', -(width/2));
	$('#timeline_wrapper').animate({'left': '+='+width}, 'slow');
	$('#timeline_wrapper').data('x_target', (width/2));
	
}

function timeline_scroll(d, clicked)
{
	//var x = parseInt($('#timeline_wrapper').css('left').replace('px', ''));
	var x = $('#timeline_wrapper').data('x_target');
	var increment = $('#timeline_wrapper .timeline_item:first').width() + parseInt($('#timeline_wrapper .timeline_item:first').css('margin-right').replace('px', ''));
	var offset = increment/2;
	
	var rounded_item_count = (Math.round($('#timeline_wrapper .timeline_item').length / 2))*2;
	var total_width = (rounded_item_count * increment) - parseInt( $('#timeline_wrapper .timeline_item:first').css('margin-right').replace('px', '') );
	
	var move = (increment * Math.abs(d)) * 2;
	
	$('#timeline_left').show();
	$('#timeline_right').show();
	
	if (d > 0 && x < 0)
	{
		if ((x + move) == offset) 
			$('#timeline_left').hide();	
			
		$('#timeline_wrapper').animate({'left': '+='+move}, 'slow');
		$('#timeline_wrapper').data('x_target', (x + move));
		
		if (!clicked)
		{
			var current_item = $('.timeline_ticks .timeline_tick:has(a.current)');
			current_item.children('a').removeClass('current');
			current_item.prev().children('a').addClass('current');
		}
	}
	else if (d < 0 && x > -(total_width - $('#timeline').width()))
	{
		if ((x - move) == -(total_width - $('#timeline').width() + offset)) 
			$('#timeline_right').hide();
			
		$('#timeline_wrapper').animate({'left': '-='+move}, 'slow');
		$('#timeline_wrapper').data('x_target', (x - move));
		
		if (!clicked)
		{
			var current_item = $('.timeline_ticks .timeline_tick:has(a.current)');
			current_item.children('a').removeClass('current');
			current_item.next().children('a').addClass('current');
		}
	}
}

function focus_fix(selector, className) 
{
	$(selector)
		.focus(function() {
			$(this).addClass(className);
		})
		.blur(function() {
			$(this).removeClass(className);
		});
}

function init()
{
	home_carousel_init();
	what_we_do_carousel_init();
	hide_backup_nav();
	dropdowns_init();
	ie_headline_init();
	timeline_init(); 
	//client_list_init();
	contact_map_init();
	contact_map_zh_init();
	//search_init();
	//newsletter_init();
	if (!$.browser.safari) {
		thumbnail_borders_init();
		$('.tab_box:not(#glossary)').each(tabs_init);
		footer_init();
	}
	if ($.browser.msie) {
		focus_fix('#skip', 'focus');
	}
}

function init_dimension_sensitive()
{
	thumbnail_borders_init();
	$('.tab_box:not(#glossary)').each(tabs_init);
	footer_init();
}


function dropdowns_init(){

	$(".showHover").append("<span></span>"); 	//Only shows drop down trigger when js is enabled - Adds empty span tag with hover anchor
	$(".showHover").attr( { href : "#?"});  	//if javascript is enabled the sub nav item itself shouldn't link anywhere (question mark is used to prevent jump to top (#)
	$("ul.we_do_subnavi li a").click( function() { 	//When sub nav item is is clicked...

		//Following events are applied to the drop_nav itself (moving drop_nav up and down)
		$(this).parent().find("ul.drop_nav").slideDown('fast').show(); //Drop down the drop_nav on click

		$(this).parent().hover (function() {
		}, function(){
			$(this).parent().find("ul.drop_nav").slideUp('fast');	//When the mouse hovers out of the drop_nav, move it back up
			$("ul.we_do_subnavi li a").blur(); 			// Also remove the focus from the sub nav element
			}); 			

		//Following events are applied to the trigger (Hover events for the trigger)
	});
};


function hide_backup_nav(){
	$('#backup-nav-if-no-dropdown').hide();
}


function ie_headline_init(){
	if ( $.browser.msie ) {
	  if( parseInt($.browser.version, 10) < 8){	//disable cufon rendering of headline (as it appears above the dropdown - stupid ie, fixed from ie8 onwards)
	  $(".headline").addClass("ieHeadline");
	  $(".headline").removeClass("headline");
	  }
	}
}


$(document).ready(init);



if ($.browser.safari)
	$(window).load(init_dimension_sensitive);
	


/*
 * Panelise
 */
$.fn.panelise = function(options) {
	// Initialise panelised layout
  var hash = document.location.hash;
  var currentLink = hash.length ?
                      $('a[rel='+hash+']')
                    : $('a[rel]:first');
  currentLink
    .parent().addClass('active-tool').end()
    .addClass('tool-active-link');

	$('#tools-container').addClass('tools-container-panel');
	$('#tools-alllinks').addClass('tools-alllinks-panel');
	$('#tools-section').addClass('tools-section-panel');
	$('#tools-content').addClass('tools-content-panel');
	$('.tool-detail').addClass('tool-detail-panel');
  // eof: Initialise panelised layout
	

	var container = $(this).children().css('position', 'relative');

  $.each(container.children(), function(i) {
    $('a[rel=#'+$(this).attr('id')+']').click(function(e) {
      e.preventDefault();

			$('.active-tool').removeClass('active-tool');
			$('.tool-active-link').removeClass('tool-active-link');
			$(this)
        .parent().addClass('active-tool').end()
        .addClass('tool-active-link');

      var initialLeft = 0;
      if (hash.length && !jQuery.browser.msie) {
        var hashPanel = container.children(hash);
        if (hashPanel.length) {
          initialLeft = $(hash).position().left;
        }
      }
      var panel = $($(this).attr('rel'));
      container.animate({ 'left' : (initialLeft-panel.position().left).toString()+'px' });
    });
  });


  // IE fix (the only browser that doesn't automatically scroll to display
  // the currently anchored element)
  if (hash.length && jQuery.browser.msie) {
    var hashPanel = container.children(hash);
    container.css('left', (-hashPanel.position().left).toString()+'px');
  }
}

