function navSpace(selector, align){
	$(selector).children().children('li:last').css('border-right', 'none');
	totalWidth = $(selector).width();
	total = $(selector).children().children().size();
	$(selector).children().children().find('a:first').css('padding-left', 0).css('padding-right', 0);
	currentWidth=0;
	$(selector).children().children().each(function(){
		currentWidth+=$(this).width();
	});
	if(currentWidth < totalWidth){
		newWidth = Math.floor((totalWidth-currentWidth)/total);
		remainder = (totalWidth-currentWidth-(newWidth*total));
		$(selector).children().children().find('a:first').css('padding-left', Math.floor(newWidth/2)+'px').css('padding-right', Math.ceil(newWidth/2)+'px');
		$(selector).children().children('li:last').find('a:first').css('padding-right', Math.ceil(newWidth/2)+remainder+'px');
		if(align == true){
			$(selector).children().children().find('a').css('padding-left', Math.floor(newWidth/2)+'px');
		}
	}
	else{
		$(selector).children().children().find('a:first').css('padding-left', '7px').css('padding-right', '7px');
	}
	$(selector).children().children().hover(function(){
		$(this).find('ul:first').show();
		$(this).addClass('navon');
	},function(){
		$(this).find('ul:first').hide();
		$(this).removeClass('navon');
	});
}


/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function theRotator() {
	//Set the opacity of all images to 0
	$('div.rotator ul li').css({opacity: 0.0});
	
	//Get the first image and display it (gets set to full opacity)
	$('div.rotator ul li:first').css({opacity: 1.0});
		
	//Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds
	
	setInterval('rotate()',12000);
	
}

function rotate() {	
	//Get the first image
	var current = ($('div.rotator ul li.show')?  $('div.rotator ul li.show') : $('div.rotator ul li:first'));

    if ( current.length == 0 ) current = $('div.rotator ul li:first');

	//Get next image, when it reaches the end, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator ul li:first') :current.next()) : $('div.rotator ul li:first'));
	
	//Un-comment the 3 lines below to get the images in random order
	
	var sibs = current.siblings();
    var rndNum = Math.floor(Math.random() * sibs.length );
    var next = $( sibs[ rndNum ] );
			

	//Set the fade in effect for the next image, the show class has higher z-index
	next.css({opacity: 0.0})
	.addClass('show')
	.animate({opacity: 1.0}, 1000);

	//Hide the current image
	current.animate({opacity: 0.0}, 1000)
	.removeClass('show');
	
};

// show/hide content tabs used on Barrister profile pages
function tabbedContent(){
	$('body').append('<div id="debug" style="display:none"/>')
	if ($('.tabContent').length>0) {
		var tabContent = $('.tabContent'),
			tabs = $('#tabNav a'),
			maxHeight = $('#tabNav ul').height() - 5;

		// hide links for empty tabs
		tabContent.each(function(){
			var context = $(this),
				contextHref = context.attr('id');
			
			if (context.children().length ==0){
				$('#tabNav a[href="#' + contextHref + '"]').hide();
			}			
		});
		
		// on initial load hide all but the first block of content and tag the first tab with a class of active
		tabs.first().addClass('active');
		tabContent.hide();
		tabContent.first().show();
		
		tabs.each(function(){
			//setTabHeight($(this),maxHeight);
			var tab = $(this).find('span');
			var tabOuterHeight = tab.outerHeight(),
				tabHeight = tab.height(),
				padding = (maxHeight - tabHeight)/2;
			
			if (maxHeight > tabOuterHeight){
				//if( $(this).is('.active')){
				//	tab.css({ 'padding-top':padding, 'padding-bottom':paddingActive, 'margin':'0' });
				//} else {
					tab.css({ 'padding-top':padding, 'padding-bottom':padding });
				//}
			}
		});
		
		tabs.click(function(e){
			e.preventDefault();
			var context = $(this),
				newTab = context.attr('href');
			
			if(!context.hasClass('active')){
				tabs.removeAttr('class');
				context.addClass('active');
				tabContent.hide();
				$(newTab).show();
			}

		});
	}
}

function setTabHeight(tab,maxHeight) {
	var tabOuterHeight = tab.outerHeight(),
		tabHeight = tab.height(),
		padding = (maxHeight - tabHeight)/2,
		paddingActive = padding+5;
	
	if (maxHeight > tabOuterHeight){
		if( $(this).is('.active')){
			tab.css({ 'padding-top':padding, 'padding-bottom':paddingActive, 'margin':'0' });
		} else {
			tab.css({ 'padding-top':padding, 'padding-bottom':padding });
		}
	}
	//$('#debug').append( + ', ');
	//alert(maxHeight + ', ' + tabOuterHeight)
}

$(document).ready(function() {		

	theRotator();
		$('div.rotator').fadeIn(1000);
		$('div.rotator ul li').fadeIn(1000); // tweek for IE
	
	
	
	navSpace('#mainnav', true);
	$('#mainnav ul ul').each(function(){
		$(this).find('li:first').remove();
	});
	if($('#barristerul').children().size() < 1 && $('#qcul').children().size() < 1){
    	$('#barrister').remove();
	}
	else{
		var liNo = $('#barristerul li').size();
		var liNo1 = $('#qcul li').size();
		$('#barristerul').after('<ul id="barristerul2" class="barristerul"></ul>');
		$('#qcul').after('<ul id="qcul2" class="qcul"></ul>');
		if($('#barristerul li').size() > 1){
			$('#barristerul li').each(function(e){
				if(e >= Math.floor(liNo/2)){
					$(this).appendTo($('#barristerul2'));
				}
			});
		}
		if($('#qcul li').size() > 1){
			$('#qcul li').each(function(e){
				if(e >= Math.floor(liNo1/2)){
					$(this).appendTo($('#qcul2'));
				}
			});
		}
	}
	$('#rightcol h2').each(function(){
		if($(this).next().not('h2').size() < 1){
			$(this).remove();
		}
	});
		$('#rightcol h3').each(function(){
		if($(this).next().not('h3').size() < 1){
			$(this).remove();
		}
	});
	$('#mainnav ul li').not($('#mainnav ul ul li')).hover(function(){
		ddWidth = $('#mainnav').children(':last').children(':last').width();
		if(ddWidth > 210){
			$('#mainnav ul ul').width(ddWidth + 'px');
		}
	});
	
	
	///// TEXT RESIZER /////
	
	//testURL = document.location.href;
	//testURL = testURL.split('#');
	//testURL = testURL[testURL.length-1]
	//if(testURL == 'tester'){
		$('#search').css('width' ,'255px');
		$('<div id="textResizer"><a href="Reset" id="resizeA">A</a><a href="Medium" id="resizeAA">A</a><a href="Large" id="resizeAAA">A</a></div>').prependTo('#search');
	//}
	$('#resizeA').click(function(){
		$('#textResizer a').removeClass('on');
		$('#midcol, #midcol2, #midcolsite, #rightcol, .homequote, #midcolwide').removeClass('mediumText').removeClass('largeText');
		$(this).addClass('on');
		$.cookie('textSize', '0', {expires:30, path: '/', domain: 'hardwicke.co.uk'});
		return false;
	});
	$('#resizeAA').click(function(){
		$('#textResizer a').removeClass('on');
		$('#midcol, #midcol2, #midcolsite, #rightcol, .homequote, #midcolwide').addClass('mediumText').removeClass('largeText');
		$(this).addClass('on');
		$.cookie('textSize', '1', {expires:30, path: '/', domain: 'hardwicke.co.uk'});
		return false;
	});
	$('#resizeAAA').click(function(){
		$('#textResizer a').removeClass('on');
		$('#midcol, #midcol2, #midcolsite, #rightcol, .homequote, #midcolwide').removeClass('mediumText').addClass('largeText');
		$(this).addClass('on');
		$.cookie('textSize', '2', {expires:30, path: '/', domain: 'hardwicke.co.uk'});
		return false;
	});
	if($.cookie('textSize') == '1'){
		$('#resizeAA').click();
	}
	else if($.cookie('textSize') == '2'){
		$('#resizeAAA').click();
	}
	else{
		$('#resizeA').click();
	}


	//  Code to do the read more link

	var $paragraphs 	= $('#readmore p').not(':first');
	var $firstParagraph = $('#readmore p:first');

	if ( $paragraphs.length > 0 ) {
		
		$firstParagraph.append( '&nbsp; <a href="#" id="btnReadMore">Read more\u2026</a>' );

   		$paragraphs.wrapAll('<div></div>');

		$showMoreWrapper = $( $paragraphs[0] ).parent();

		$showMoreWrapper.hide();

		$('#btnReadMore').click( function ( ev ) {
		    ev.preventDefault();
	     $showMoreWrapper.slideDown( 'slow' );
	     $( this ).remove();
	  });

	}
	
	// Barrister tabs
	tabbedContent();
	
});
