$(function() {
	tabs();
	captionText();
	clickEvents();
	cycleBox();
	navDropdown();
	forms();
	signupForm();
	clickableArticles();
	gallery();
	leaderboardImage();
	basketTotal();
	login();
	lightboxEvents();
	myAccount();
});

/**
 * Enable use of console without throwing js errors in other browsers
 */
/*if (!console) {
	var console = {
		log: function() {}
	};
}*/

/**
 * This does the tabbed interface (most commented & footer quotes)
 * Finds all anchors and captures their href
 * Using that as a div id then adds class active and remove class active from any siblings
 */
function tabs() {
	var $tabs = $('.module ul.tabs');
	$tabs.delegate('a','click',
		function(event) {
			event.preventDefault();
			var $tab = $(this),
				divToShow = $tab.attr('href');
			
			if (!$tab.parent().hasClass('on')) {
				var $divToShow = $(divToShow);
				
				// ie6 doesn't handle the animation very well
				if (typeof document.body.style.maxHeight !== 'undefined') {
					// jQuery can't calculate the height of hidden elements				
					var divToShowHeight = $divToShow.addClass('active').outerHeight();
					
					$divToShow.removeClass('active').parent().animate({
						'height' : divToShowHeight
					}).end().addClass('active').siblings().removeClass('active');
				} else {
					$divToShow.addClass('active').siblings().removeClass('active');
				}
				
				$tab.parent().addClass('on').siblings().removeClass('on');
			}
		}
	);
}

/**
 * Sets the caption element's width to be the same as the article image
 */
function captionText() {
	var $caption = $('#article p.caption'),
		captionWidthToSet = $caption.prev().width();
		
	$caption.css({'width' : captionWidthToSet - 20 + 'px'});
}

/**
 * This function handles all click event on anchor tags
 * Finds all external links and opens them in a new tab/window
 * Increases/decreases text size for child elements of article body div
 */
function clickEvents() {				
	var $wrapper = $('#wrapper');
	$wrapper.delegate('a','click',
		function(event) {
			var $anchor = $(this),
				anchorHref = $anchor.attr('href'),
				$anchorParent = $anchor.parent();
			
			// Open external links in new tab/window
			if (typeof anchorHref !== 'undefined') {
				if (
					(this.hostname !== window.location.hostname || 
					$anchorParent.hasClass('icon-print') || 
					anchorHref.substr(anchorHref.length-4) === '.pdf') &&
					anchorHref.substring(0,6) !== 'mailto' &&
					$anchor.closest('table').hasClass('cke_editor') === false &&
					!$anchor.hasClass('qq-upload-cancel')) {
						event.preventDefault();
						
						if (!$anchor.parent().hasClass('icon-facebook') && !$anchor.parent().hasClass('cke_button')) {
							window.open(anchorHref);
						}				
					
				}
			}
			// Inrease/decrease text size
			var increaseTextSize = $anchorParent.hasClass('icon-text-increase');
			if (increaseTextSize === true || $anchorParent.hasClass('icon-text-decrease')) {
				event.preventDefault();
				
				var $textToResize = $('.article-body > *, #article h1, #article .date, .standfirst p');
				$textToResize.each(
					function() {
						var $element = $(this),
							fontSize = parseFloat($element.css('font-size')),
							newFontSize = (increaseTextSize === true) ? fontSize *= 1.1 : fontSize /= 1.1;
							
						$element.css({'font-size' : newFontSize + 'px'});
					}
				);
			}
			// Email a friend ajax call
			if ($anchorParent.hasClass('icon-email')) {
				event.preventDefault();
				
				var $article = $('#article'),
					$emailAFriend = $('#email-a-friend');
				
				$emailAFriend.slideDown();
				
				$('html,body').animate({
					scrollTop: $('#column-content').offset().top 
				},'slow');
			}
			
			
			// colorbox
			if ($anchorParent.attr('id') == 'view-gallery') {
				event.preventDefault();
				var $firstImage = $('#gallery a:eq(0)')
				$firstImage.colorbox({
					open: true
				});
			}
			
			if ($anchor.hasClass('close-lbox')) {
				event.preventDefault();
				 parent.$.colorbox.close();
			}
		}
	);
	
	$('#corporate-inner').delegate('a','click',
		function(event) {
			if (this.hostname !== window.location.hostname) {
				event.preventDefault();
				window.open($(this).attr('href'));
			}
		}
	);
}

function clickableArticles() {
	$('#wrapper').delegate('#column-featured > .story, .column > .story, .magazine','click',
		function() {
			var anchorLink = $(this).find('a:eq(0)').attr('href');
			if (typeof anchorLink !== 'undefined') {
				if (anchorLink.substr(anchorLink.length-4) === '.pdf') {
					window.open(anchorLink);
				} else {
					window.location = anchorLink;
				}
			}
		}
	);
}

/**
 * Cycle the homepage box using our custom paginator
 * Enables clicking on caption to go to article on homepage cycle box
 */
function cycleBox() {
	var $cycle = $('#cycle');
	
	// show the slide
	$cycle.delegate('#headlines a','mouseover',
		function(event) {
			var li = $(this).parent();
			
			li.addClass('on').siblings().removeClass('on');
			var divToShow = li.attr('id').replace('tab-','#cycle-');
			
			$(divToShow).stop(true,true).fadeIn().siblings().stop(true,true).fadeOut();
		}
	);
	
	$cycle.delegate('.caption','click',
		function() {
			var url = $(this).parent().find('a').attr('href');
			window.location = url;
		}
	);	
}

/**
 * Show the nav dropdown from the nav bar
 * If the nav dropdown is already visible and you mouseover another then don't slide it in, just show it
 * When you mouseout slide it back up
 */
function navDropdown() {
	var $navigation = $('#navigation'),
		$navDropdowns = $('.nav-dropdown'),
		hasSubNav = $('body').hasClass('subnav'),
		$selectedTab = $navigation.find('.on'),
		timer = null;

	$navigation.delegate('a','mouseover',
		function() {
			var $tab = $(this),
				$tabDropdown = $tab.next(),
				$navDropdownsContainer = $tabDropdown.find('.nav-dropdown-container');
				
			// if anchor is a tab
			if ($tab.parents('div').eq(0).attr('id') === 'navigation') {				
				clearTimeout(timer);
				
				// don't bother trying to understand the below
				if (hasSubNav === false) {
					
					if ($navDropdowns.is(':visible') === true) {
						if ($navDropdownsContainer.is(':empty') === false) {
							$navDropdowns.hide();
							$tabDropdown.show();
						} else {
							$navDropdowns.stop(true,true).slideUp('normal');
						}
					} else {
						if ($navDropdownsContainer.is(':empty') === false) {
							$navDropdowns.hide();
							$tabDropdown.stop(true,true).slideDown();
						}
					}
				} else {
					$navDropdowns.hide();
					$tabDropdown.show();
				}
				
				$tab.parent().addClass('on').siblings().removeClass('on');
								
			}
			
		}
	).mouseleave(
		function() {			
			if (hasSubNav === false) {
				$selectedTab.addClass('on').siblings().removeClass('on');
				$navDropdowns.slideUp('normal');
			} else {
				timer = setTimeout(originalSubNav, 800);
			}
		}
	);
	
	function originalSubNav() {		
		var $currentSelectedTab = $navigation.find('.on');
		
		if ($selectedTab.get(0) !== $currentSelectedTab.get(0)) {
			$navDropdowns.fadeOut(800).parent().removeClass('on');
			
			$selectedTab.find('.nav-dropdown').fadeIn(800,
				function() {
					$(this).parent().addClass('on');
				}
			);
		}
	}
	
	/*	
	// Fix IE6 z-index bug
	if (typeof document.body.style.maxHeight == 'undefined') {
		if ($navDropdowns.length && $('#rhs-search').length) {
			$navDropdowns.bgiframe();
		}
	}	*/
}
/**
 * On form submit hide the submit button and add a loading gif and message
 */
function forms() {
	var $form = $('#column-content form, .lightbox form'),
		$buttons = $('button[type="submit"]');
		
	$form.delegate('button, .button-back','click',
		function() {
			var $button = $(this);
			
			if ($button.parent().hasClass('buttons')) {
				$button.siblings().hide();
			}
			
			if ($button.hasClass('button-actions')) {
				$button.parent().siblings('form').hide();
			}
			
			if (!$button.hasClass('button-search') && !$button.hasClass('button-validate')) {
				$button.hide().parent().addClass('no-bg').end().before('<p class="loading"><img src="/images/loader.gif" width="16" height="16" />Submitted, please wait...</p>');
			}
			
			// fix ie6 button nonsense
			if (typeof document.body.style.maxHeight === 'undefined') {
				if ($button.prop('type') === 'submit') {
					$buttons.attr('disabled', true);
					$button.attr('disabled', false);
				}
			}		
		}
	);	

}


/* 
 *  Third party newsletter signup, hide form on submittal and show a subscription upsell message in its place
 */
function signupForm() {	
	var $signup = $('#newsletter-signup'),
		$form = $signup.find('form'),
		$input = $form.find('input:text'),
		$errorMsg = $('#signup-error'),
		$errorAjax = $('#signup-error-ajax');
	
	$signup.delegate('input','focusin focusout',
		function(event) {
			var $input = $(this);
			
			if (event.type == 'focusin') {
				if ($input.attr('value') == 'Email address') {
					$input.attr('value','');
				}
			} else if (event.type == 'focusout') {
				if ($input.attr('value') == '') {
					$input.attr('value','Email address');
				}
			}
		}
	);
	
	$form.submit(
		function(event) {
			event.preventDefault();
			
			var inputValue = $input.val(),
				emailRegex = /^[\w\.\-\']+\@[a-z0-9\-]{2,}(\.[a-z0-9\-]{2,})+$/,
				$button = $(this).find('button'),
				data = 'QuestionnaireID=177272&Email=' + inputValue;
			
			if (emailRegex.test(inputValue)) {
				// all good
				$errorMsg.hide();
				$button.hide().before('<img src="/images/loader.gif" width="16" height="16" />');
				
				// ajax submit
				$.ajax({
					url: '/newsletter-signup/',
					type: 'POST',
					data: data,
					cache: false,
					success: function(data) {
						$input.parent().html(data);
					},
					errors: function() {
						$errorAjax.show();
					}
				});
			} else {				
				$errorMsg.show();
			}
		}
	);	
}



function gallery() {
	var $gallery = $('#article a[rel="gallery"]');
	if ($gallery.length) {
		$gallery.colorbox({
			current: ''
		});
	}
}

function leaderboardImage() {
	var $image = $('#leaderboard img');
	if ($image.length) {
		$image.css({
			position: 'relative',
			zIndex: '60'
		});
	}
}

function getQuerystring(key, default_) {
	if (default_==null) default_="";
		key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
		var qs = regex.exec(window.location.href);
		if(qs == null)
		return default_;
	else
		return qs[1];
}

/* 
 * Handle resouces page events
 * Slide the sub categories down from parent span/anchor
 */
 
 
/*********
*	extends jQuery's $.unique() to work on strings,arrays in additon to DOM Elements - http://paulirish.com/2010/duck-punching-with-jquery/
***/
(function($){
    var _old = $.unique;
    $.unique = function(arr){
        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        } else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
            });
        }
    };
})(jQuery);


function basketTotal() {
	var $basketTotal = $('#basket-total');
	if ($basketTotal.length) {
		var positionLeft = ($(window).width() - 896) / 2;
		
		$basketTotal.css({
			right: 'auto',
			left: positionLeft + 896 - $basketTotal.width() + 'px'
		});
	}
}

// bind the window resize to update the position
$(window).resize(
	function() {
		basketTotal();
	}
);


function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function swapDivs(state) {
	var $loggedIn = $('.logged-in'),
		$loggedOut = $('.logged-out');
		
	if (state === 'logged-in') {
		$loggedIn.show();
		$loggedOut.hide();
	} else {
		$loggedIn.hide();
		$loggedOut.show();
	}
}

function login() {
	var loginCookie = readCookie('USER_COOKIE');	
	if (loginCookie !== null) {
		swapDivs('logged-in');
	} else {
		swapDivs('logged-out');
	}
}

function lightboxEvents() {
	var $closeButton = $('.lbox-close'),
		$lightboxLogin = $('.lbox-login');
		
	$closeButton.click(
		function(event) {
			event.preventDefault();
			parent.$.colorbox.close();
			parent.swapDivs('logged-in');
		}
	);
	
	if ($lightboxLogin.length) {	
		$lightboxLogin.colorbox({
			iframe: true,
			width: '540px',
			height: '365px',
			opacity: '0.7'
		});
	}
}


function myAccount() {
	// fix http problem
	var $websiteLink = $('.pp-website a');
	$websiteLink.each(
		function() {
			var $anchor = $(this),
				firstChars = $anchor.attr('href').substring(0, 7);
				
			if (firstChars !== 'http://') {
				var newHref = 'http://' + $anchor.attr('href');
				$anchor.attr('href', newHref);
			}
		}
	);
	
	// show field
	var $notEditable = $('.not-editable');
	$notEditable.find('input:checked').next().removeClass('hidden');
}
