/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

function accordion() {

	// Use for debugging
	function log(s) {
	 if (typeof console != "undefined" && typeof console.debug != "undefined") {
	  console.log(s);
	 } else {
	  // alert(s);
	 }
	}

	// hides all the non-active sections
	$('.heading:not(.active) ~ .section').hide();

	randomiseList();
	
	// Get page, open section
	var hash = self.document.location.hash;
	if (hash != '') {

		$('.section').slideUp('fast');
		$('.heading').removeClass('active');
		
		// we need to split the hash up by slashes - and navigate accordingly
		var parts = hash.split('/');
		var url = hash.replace('#', '/')
		var $panel = $(parts[0] + '.panel'); // TODO: [LK] Need to fix this so that it can load content for the #home and #footer links
		
		// special condition for #home
		if (parts[0] == '#home') {
			url = '';
			$panel = $('#content');
		}

		// populates the panel/section
		populatePanel($panel, url, false);

		// sets the .active class on the appropriate sub-nav link
		if (parts.length > 1) {
			$panel.find(".section .nav a[href*='" + hash.substring(1) + "']").addClass('active');
		}
		else {
			$panel.find('.section .nav a:first').addClass('active');
		}

	}

	$('#home.panel .heading').click(function(e) {
		
		e.preventDefault();
	
		// remove the .active class from the previously selected (and slideUp/hide the sections)
		$('.heading').not(this).removeClass('active').children('.close').remove();
		$('#footer a, .panel .section .nav a').removeClass('active');
		$('.panel .section, #search-results, #footer .additional').slideUp('fast');

		var $panel = $(this).parent('.panel');
		var $link = $(this).find('.title a');
		var url = $link.attr('href');

		// set the hash location
		self.document.location.hash = $panel.attr('id');
		track('Section', $(this).find('.title a').text(), 'open');

		// set the document's title (level 1)
		document.title = $link.text() + ' - ' + $('#logo').text();

		// set the breadcrumbs (level 1)
		$('#breadcrumb > ul').html('<ul><li><a href="' + url + '">' + $link.text() + '</a></li></ul>');

		// }

	});

	// click event for all the headings - apart from #home, as the content is loaded into a different section/location
	$('.panel:not(#home) .heading').click(function(e) {

		e.preventDefault();
		var $link = $(this).find('.title a');
		// remove the .active class from the previously selected (and slideUp/hide the sections)
		$('.heading').not(this).removeClass('active').children('.close').remove();
		$('#footer a, .panel .section .nav a').removeClass('active');

		$('.section, #search-results, #footer .additional').slideUp('fast', function(){});

		// if the .heading is currently .active, then collapse it
		if ($(this).hasClass('active')) {

			// reset the hash location
			self.document.location.hash = '#';

			// remove the .active class and slideUp/hide the .section)
			$(this).removeClass('active').next('.section').slideUp();

			// remove the .close button [SC]
			// $(this).children('.close').remove();

			// set the document's title (level 1 - the root site title)
			document.title = $('#logo').text();
			track('Section', $link.text(), 'close' );
			// set the breadcrumbs (level 1 - just show the home crumb)
			$('#breadcrumb > ul').html('<ul><li><a href="/">Home</a></li></ul>');

		}
		// otherwise open/expand/populate the .section
		else {

			var $panel = $(this).parent('.panel');
			var $link = $(this).find('.title a');
			var url = $link.attr('href');

			// add the .close button [SC]
			// $(this).append('<a href="#" class="close">Close</a>');

			// set the hash location
			self.document.location.hash = $panel.attr('id');

			// populates the panel/section
			populatePanel($panel, url, false);

			// sets the .active class on the first sub-nav link
			$panel.find('.section .nav a:first').addClass('active');
			track('Section', $link.text(), 'open');
			// set the document's title (level 2)
			document.title = $link.text() + ' - ' + $('#logo').text();

			// set the breadcrumbs (level 2)
			$('#breadcrumb > ul').html('<ul><li><a href="/">Home</a><ul><li><a href="' + url + '">' + $link.text() + '</a></li></ul></li></ul>');
		}
	});
	
	// click event for the sub-nav links
	$('.panel .section .nav a').click(function(e) {

		e.preventDefault();

		if (!$(this).hasClass('active') || $(this).hasClass('active') || $(this).attr('href', '/what-we-do/latest-projects.aspx').hasClass('active') || $(this).attr('href', '/media-centre/press-releases.aspx').hasClass('active')) {

			var $panel = $(this).parents('.panel');
			var url = $(this).attr('href');
			var $parentLink = $panel.find('.heading .title a');

			$('.panel .section .nav a').removeClass('active');
			$(this).addClass('active');

			// set the hash location
			self.document.location.hash = url.substring(1).replace('.aspx', '');

			populatePanel($panel, url, true);
			track('Subsection ('+$parentLink.text()+')', $(this).text(), 'loaded');
			// set the document's title (level 3)
			document.title = $(this).text() + ' - ' + $parentLink.text() + ' - ' + $('#logo').text();

			// set the breadcrumbs (level 3)
			$('#breadcrumb > ul').html('<ul><li><a href="/">Home</a><ul><li><a href="' + $parentLink.attr('href') + '">' + $parentLink.text() + '</a><ul><li><a href="' + url + '">' + $(this).text() + '</a></li></ul></li></ul></li></ul>');

		} 

		return false;

	});
	
	// $('.panel .section .nav a').hover(function(e){
	// 	log($(this).attr('href'))
	// })

	// click event for the footer nav links
	$('#footer a:not([rel=external])').click(function(e) {

		e.preventDefault();

		// remove the .active class from the previously selected (and slideUp/hide the sections)
		$('.heading').removeClass('active').children('.close').remove();
		$('#footer a').not(this).removeClass('active');
		$('.section, #search-results').slideUp('fast');

		// if the .heading is currently not .active, then open/expand/populate it
		if (!$(this).hasClass('active')) {

			var url = $(this).attr('href');

			//$('#footer a').removeClass('active');

			// add the .active class
			$(this).addClass('active');

			// set the hash location
			self.document.location.hash = url.substring(1).replace('.aspx', '');
			track('Footer', $(this).text(), 'opened');
			// remove the .aspx from the URL and append the '/html.aspx' for the AJAX get.
			url = url.replace('.aspx', '') + '/html.aspx';
			
			// populates the panel/section
			$('#footer .additional').load(url, function(data) {
				$(this).slideDown(function(){
					$.scrollTo('#vTwitter', 'fast');
				}).append('<a href="#" class="close">Close</a>');
			});

			// set the document's title (level 2)
			document.title = $(this).text() + ' - ' + $('#logo').text();

			// set the breadcrumbs (level 2)
			$('#breadcrumb > ul').html('<ul><li><a href="/">Home</a><ul><li><a href="' + url + '">' + $(this).text() + '</a></li></ul></li></ul>');

		}

		return false;

	});

	function populatePanel($currentPanel, url, clearContent) {
		// get jQuery object for the .article container
		var $article = $currentPanel.find('> .section .article');
		// remove the .aspx from the URL and append the '/html.aspx' for the AJAX get.
		url = url.replace('.aspx', '') + '/html.aspx';
		if (clearContent) {
			$article.html('');
		}
		// check if the .article is empty
		if ($article.text() == '') {
			// if it's empty, then get the HTML content via AJAX
			$article.load(url, function(data) {
				$(this).parent('.section')
					.slideDown()
					.prev('.heading')
					.addClass('active');
				randomiseList();
			});
		}
		else {			
			// otherwise just add the .active class and slide open the .section
			$currentPanel.children('.heading').addClass('active');
			$currentPanel.children('.section').slideDown();
		}
	}

	function randomiseList() {
		// define the letters and sort randomly
		var letters = ['a', 'b', 'c', 'd', 'e'];
		letters.sort(function() { return 0.5 - Math.random(); })
		// apply the style to each bullet-point
		$("ul.list-random li:not(> span.bullet)").each(function(i) {
			$(this).append('<span class="bullet ' + (i < letters.length ? letters[i] : letters[0]) + '"></span>');
		});
	}
	
	function track(category, action, label, value ){
		_gaq.push(['_trackEvent', category, action, label, value]);
		//pageTracker._trackEvent(category, action, label, value );
	}

}
