/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);

;(function(window, document, undefined) {
    /* taken from base.js - frontend-common */
    // get an element's auto-height
    $.fn.fullHeight = function() {
        var height = this.height(),
            autoHeight = this.height('auto').height();
            
        this.height(height);
        return autoHeight;
    };
})(window, document);

var branded = {};
branded.isIpad = navigator.userAgent.match(/iPad/i) != null;

branded.init = function() {	
	if (branded.isIpad) branded.fixIpad();
	
	if (window.location.pathname == '/') {
        if ($('body').hasClass('index')) { 
            $('body').addClass('splash');
        }
    } else {
        var path = window.location.pathname.split('.html')[0];
        window.location = '/#' + path;
	}
	
    // Poor naming, this does more than initialising
    // navigation, it also provides the fragment loading.
	branded.initNavigation();
};

branded.fixIpad = function() {
	$('header nav ul, footer div').css({'width':700, 'position':'relative', 'left':10});
};

branded.initNavigation = function() {
	$(window).bind('hashchange', function(e) {
		if ($.param.fragment() !== "") branded.loadPage($.param.fragment().substr(1)+".html");
	});
	$(window).trigger('hashchange');
	
	$('nav a').click(function(e) {
        branded.hideHeader();
		var link = $(this),
			url = link.attr('href'),
			page = url.split('.html')[0],
			li = link.parent().addClass('active').siblings().removeClass('active');
		
		if (window.location.hash !== "#"+page) {
			// Hide any stupid bubbles..
			window.clientTooltips && clientTooltips.hide();
			
			$('article').animate({height:1}, 600, function() {
				window.location.hash = page;
			});
		}

		return false;
	});
	
	$('a.inline').live('click', function(e) {
		var link = $(this),
			url = link.attr('href'),
			page = url.split('.html')[0];
		
		// Hide any stupid bubbles..
		window.clientTooltips && clientTooltips.hide();
		
		$('html,body').animate({
			scrollTop: 0
		}, 600);
		$('article').animate({height:1}, 600, function() {
			window.location.hash = page;
		});
		return false;
	});
};

branded.loadPage = function(url) {
    
	var hasSplash = $('body').hasClass('splash') ? " splash" : "";
    var hash = url.split('.html')[0];
    // The hash gets used as the body class for styling purposes; but we want
    // to have one set of styles for a whole bunch of pages (the news detail
    // pages) and therefore to keep these seperated we put them in a seperate
    // folder and only use the folder name as the class to attach to the body.
    if (hash.indexOf("/") > 0){
        hash = hash.split('/')[0];
    }
	
	$('body').attr('class', hash == "" ? "index" + hasSplash : hash + hasSplash);
    var body_class = $('body').attr('class');
	$('nav a.' + body_class).parent().addClass('active').siblings().removeClass('active');
	$('article').load(url + ' article div.wrap', function() {

        if (hasSplash !== "") {
            branded.hideSplash();
        }
		
		if (hash == 'whoweworkwith') {
			branded.initClientsList();
		}

        var wrap_height = $('article').fullHeight(), animate_height;
        var min_height = 570;
        if (wrap_height < min_height) {
            animate_height = min_height;
        } else {
            animate_height = wrap_height;
        }
        $('article').animate({height:animate_height}, {
			duration: 500,
			complete: function() {
			}
		});
	});
};

branded.hideSplash = function() {
	$('div#splash, footer').fadeOut(500, function() {
		$('footer').addClass('toothed').fadeIn(500);
	});
    $('body').removeClass('splash');
};

branded.hideHeader = function() {
    $('header').animate({marginTop: -185}, 500);
    $('#branded-logo-small').animate({top: 178}, 500);
};

branded.showSplash = function() {
	$('footer').fadeOut(300, function() {
		$(this).removeClass('toothed');
		$('article').animate({height:1}, 600, function() {
			$('footer, div#splash').fadeIn(500);
			$('body').addClass('splash');
		});
	});
};

branded.initClientsList = function() {
	var $container = $('#clients-list'),
		sectorRows = [], // in format [ [ {$node, $img, position}, {$node, $img, position}, ... ], ... ] array per row
		alphaRows = [], // same format as sector
		$clients = $('#clients-list section.sector li'),
		$sectorHeadings = $('#clients-list section.sector h1'),
		$clientImgs = $('#clients-list section.sector img'),
		currentLayout = 'sector',
		busy;
	
	function populateSectorRows() {
		var lastTop,
			currentRow;
		
		$clients.each(function() {
			var $client = $(this),
				position = $client.position(),
				$img = $client.children(),
				data;
				
			if ( lastTop != position.top ) {
				// new row time!
				currentRow = [];
				sectorRows.push(currentRow);
				lastTop = position.top;
			}
			
			data = {
				$node: $client,
				$img: $img,
				position: position
			};
			
			currentRow.push(data);
			$client.data('sector', data).css(position);
		});
		
		$container.height( $container.height() );
		$container.addClass('clients-positioned');
		$('#clients-list section.sector ul').css('overflow', 'visible');
	}
	
	function fixSectorHeadings() {
		// fix their position
		$sectorHeadings.each(function() {
			var $heading = $(this);
			$heading.css( $heading.position() );
		});
	}
	
	function populateAlphaRows() {
		var rowLen = 5,
			currentRow,
			imgsAlpha,
			initialLeft = sectorRows[0][0].position.left,
			rowHeight = 73,
			colWidth = 133,
			currentLeft,
			currentTop = sectorRows[0][0].position.top - rowHeight,
			i = 0,
			owedToPreviousRow = 0;
		
		// sort our images into alpha order
		imgsAlpha = $clientImgs.toArray().sort(function(a, b) {
			return a.alt > b.alt ? 1 : -1;
		});
		
		$.each(sectorRows, function(row, clientsRow) {
			// reorder the row so we fill up the previous row with items from the END of this row
			clientsRow = clientsRow.slice(-owedToPreviousRow).concat( clientsRow.slice(0, -owedToPreviousRow) );
			
			$.each(clientsRow, function(col, clientData) {
				var $client = clientData.$node,
					$img = $( imgsAlpha[i] );
					
				currentLeft += colWidth;
				if ( !(i % rowLen) ) {
					// new row time!
					currentRow = [];
					alphaRows.push(currentRow);
					currentTop += rowHeight;
					currentLeft = initialLeft;
				}
				
				data = {
					$node: $client,
					$img: $img.parent(),
					position: {top: currentTop, left: currentLeft}
				};
				
				currentRow.push(data);
				$client.data('alpha', data);
				
				i++;
			});
			
			owedToPreviousRow = (rowLen + owedToPreviousRow - clientsRow.length) % rowLen;
		});
	}
	
	function setInitialDisplay(sort_by) {
        if (sort_by == 'alpha') {
            $sectorHeadings.hide();
        } else {
            $sectorHeadings.show();
        }
		$clientImgs.parent().detach();
		$clients.each(function() {
			var $client = $(this),
				data = $client.data(sort_by);
			$client.css( data.position ).append( data.$img );
		});
		currentLayout = sort_by;
	}
	
	var controls = (function() {
		var $aToZ = $('<span role="button" class="alpha-btn">A to Z </span>'),
			$sector = $('<span role="button" class="active">Sector</span>'),
			$controls = $('<div class="controls">Sort by: </div>').append($aToZ).append($sector);
			
		return {
			add: function() {
				$container.before( $controls );
		
				$aToZ.click(function(event) {
					alphaLayout();
					event.preventDefault();
				});
				
				$sector.click(function(event) {
					sectorLayout();
					event.preventDefault();
				});
			},
			activateSector: function() {
				$sector.addClass('active');
				$aToZ.removeClass('active');
			},
			activateAlpha: function() {
				$aToZ.addClass('active');
				$sector.removeClass('active');
			}
		}
	})();
	
	function imgsFadeOut(callback) {
		var complete;
		$clientImgs.parent().animate({
			opacity: 0
		}, {
			duration: 300,
			complete: function() {
				$(this).detach();
				!complete && callback();
				complete = true;
			}
		});
	}
	
	function sectorHeadingsFadeOut() {
		$sectorHeadings.fadeOut(300);
	}
	
	function sectorHeadingsFadeIn() {
		$sectorHeadings.fadeIn(300);
	}
	
	function imgsFadeIn(callback) {
		var complete;
		
		$clients.each(function() {
			var $client = $(this);
			$client.append( $client.data(currentLayout).$img );
		});
		
		$clientImgs.parent().animate({
			opacity: 1
		}, {
			duration: 300,
			complete: function() {
				!complete && callback();
				complete = true;
			}
		});
	}
	
	function sectorLayout() {
		if (currentLayout == 'sector' || busy) { return; }
		
		busy = true;
		
		controls.activateSector();
		
		imgsFadeOut(function() {
			var completeCount = 0;
			
			// set up animations
			$clients.each(function(i) {
				var $client = $(this),
					sectorData = $client.data('sector'),
					alphaData = $client.data('alpha');
				
				$client.delay( 25 * ($clients.length - i) );
				
				$client.animate({
					top: sectorData.position.top
				}, {
					duration: 300
				});

				$client.animate({
					left: sectorData.position.left
				}, {
					duration: 300,
					complete: function() {
						completeCount++;
						if (completeCount === $clients.length) {
							sectorHeadingsFadeIn();
							imgsFadeIn(function() {
								busy = false;
							});
						}
					}
				});
			});
		});
		
		currentLayout = 'sector';
	}
	
	function alphaLayout() {
		if (currentLayout == 'alpha' || busy) { return; }
		
		busy = true;
		
		controls.activateAlpha();
		
		sectorHeadingsFadeOut();
		imgsFadeOut(function() {
			var completeCount = 0;
			
			// set up animations
			$clients.each(function(i) {
				var $client = $(this),
					sectorData = $client.data('sector'),
					alphaData = $client.data('alpha');
				
				$client.delay( 25 * i );
				
				$client.animate({
					left: alphaData.position.left
				}, {
					duration: 300
				});

				$client.animate({
					top: alphaData.position.top
				}, {
					duration: 300,
					complete: function() {
						completeCount++;
						if (completeCount === $clients.length) {
							imgsFadeIn(function() {
								busy = false;
							});
						}
					}
				});
			});
		});
		
		currentLayout = 'alpha';
	}
	
	
	var tooltips = (function() {
		var bubbles = [],
			lastBubbleIndex = 1,
			$header = $( document.body ).children('header'),
			$lastHovered;
		
		function showForImg($img) {
			var $bubble = getNextBubbleToShow(),
				imgPos = $img.data('active-bubble', $bubble).offset();
			
			$bubble.addClass('client-tooltip-active').css({
				top: imgPos.top - 92 - parseInt( $header.css('margin-top') ),
				left: imgPos.left - 131
			}).children().text( $img.data('tooltip') );
		}
		
		function hideForImg($img) {
			var $bubble = $img.data('active-bubble');
			$bubble && $bubble.removeClass('client-tooltip-active');
			$img.removeData('active-bubble');
		}
		
		function createBubble() {
			return $('<div class="client-tooltip"><div class="tooltip-inner"></div></div>').appendTo(document.body);
		}
		
		function getNextBubbleToShow() {
			lastBubbleIndex = (lastBubbleIndex + 1) % 2;
			return bubbles[lastBubbleIndex];
		}
		
		return {
			init: function() {
				bubbles[0] = createBubble();
				bubbles[1] = createBubble();
				$('#clients-list img').hoverIntent({
					over: function() {
						$lastHovered = $(this);
						showForImg( $lastHovered );
					},
					out: function() {
						hideForImg( $(this) );
					},
					interval: 200
				}).each(function() {
					var $img = $(this),
						text = $img.attr('title');
					
					$img.attr('title', '').data('tooltip', text);
				});
			},
			hide: function() {
				$lastHovered && hideForImg( $lastHovered );
			}
		}
	})();
	
	fixSectorHeadings();
	populateSectorRows();
	populateAlphaRows();
    // Set this to alpha/sector depending on 
    // which you want on initial page load.
	setInitialDisplay('sector');
	controls.add();
	tooltips.init();
	$container.css('visibility', 'visible');
	
	window.clientTooltips = tooltips;
};

$(document).ready(function() {
	
	if ($.support.scriptEval) {
		$('article div.wrap').hide();
		branded.init(); // non-ie
	}
	else{
		$('article div.wrap').show();
		$('html').removeClass('js');
	}
});

