//google.setOnLoadCallback(function() {
$(function() {
	tabs();
	captionText();
	clickEvents();
	cycleBox();
	navDropdown();
	forms();
	footerScroll();
	signupForm();
	twitterLink();
	relatedSlide();
	clickableArticles();
	dataAccordion();
	quotesTools();
	basketTotal();
	gallery();
	related();
	blogDirectory();
	leaderboardImage();
});
/**
 * 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);
			var 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');
	var 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);
			var anchorHref = $anchor.attr('href');
			var $anchorParent = $anchor.parent();
			
			// Open external links in new tab/window
			if ((this.hostname !== window.location.hostname || $anchorParent.hasClass('icon-print')) && anchorHref.substring(0,6) !== 'mailto' && $anchor.closest('div').attr('id') !== 'module-submit-a-blog') {
				
				if ($anchor.closest('div').hasClass('story-blog')) {
					window.open(anchorHref);
					return false;
				} else {
					event.preventDefault();
					
					if (!$anchor.parent().hasClass('icon-facebook')) {
						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);
						
						var fontSize = parseFloat($element.css('font-size'));
						var 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');
				var $emailAFriend = $('#email-a-friend');
				
				$emailAFriend.slideDown();
				
				$('html,body').animate({
					scrollTop: $('#column-content').offset().top 
				},'slow');
			}
			// 	Data Browse-Search Panesl
			if ($anchor.parent().parent().is('#data-tabs')) {
				event.preventDefault();
				
				var $currentTab = $('#related').find('.active');
				var $currentDisplay = $('#related').find('.selected');
				
				var $dataTab = $(this);
				var $dataTabToShow = $dataTab.attr('href');
				
				if (!$dataTab.hasClass('active')) {
				
					$currentTab.removeClass('active');
					$dataTab.addClass('active');
					
					$currentDisplay.fadeOut('normal', function(){
						$dataTabShow = $($dataTabToShow);
						$(this).removeClass('selected');
						$dataTabShow.fadeIn().addClass('selected');
					});
				}
			}		
			
			if ($anchor.closest('div').attr('id') === 'module-submit-a-blog') {
				event.preventDefault();
				$anchor.colorbox({
					iframe: true,
					height: '600px',
					width: '610px',
					opacity: 0.8
				});
			}
			
			// colorbox
			if ($anchorParent.attr('id') == 'view-gallery') {
				event.preventDefault();
				var $firstImage = $('#gallery a:eq(0)')
				$firstImage.colorbox({
					open: true
				});
			}
		}
	);
	
	$('#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, #content-by > .story, #bloggers > .story, #shop-article, #related-article-slide,#random-speech','click',
		function() {
			var $storyBlog = $(this).closest('div');
			var $anchorLink = $(this).find('a:eq(0)').attr('href');
			if (typeof $anchorLink !== 'undefined' && ($storyBlog.hasClass('story-blog') === false)) {
				window.location = $anchorLink;
			} else if (typeof $anchorLink !== 'undefined' && ($storyBlog.hasClass('story-blog') === true)) {
				window.open($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');
	var $navDropdowns = $('.nav-dropdown');
	
	if ($navDropdowns.length) {
		$navigation.delegate('a','mouseover',
			function() {
				var $tab = $(this);
				
				if ($tab.parent().is('#nav-home') && $navDropdowns.is(':visible')) {
					$navDropdowns.slideUp();	
					$navigation.find('.hover').removeClass('hover');
				} else if ($tab.parent().is('li')) {
					var $navDropdown = $tab.next();
					if ($navDropdown.length) {
						
						if (!$navDropdowns.is(':visible')) {
							$navDropdown.stop(true,true).slideDown();
						} else {
							$navDropdowns.hide();
							$navDropdown.show();
						}
						
						$tab.addClass('hover').parent().siblings().children().removeClass('hover');
					}
				}
			}
		).mouseleave(
			function() {
				$navigation.find('.nav-dropdown:visible').delay(500).slideUp('normal',
					function() {
						$navigation.find('a').removeClass('hover');
					}
				);
			}
		);
	
		// Calculate spacer height so image is always positioned bottom (can't position absolutely as text will then not wrap)
		var $images = $('.positioned');
		$images.each(
			function() {
				var $image = $(this);
				
				/*var imageHeight = $image.height();
				var containerHeight = $image.closest('div.column-main').height();
				var spacerHeight = containerHeight - imageHeight - 5;
				
				$image.parent().prev().css({ 'height' : spacerHeight + 'px' });*/
			}
		);
	}
	
	// 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');
	$form.delegate('button','click',
		function() {
			var $button = $(this);
			var sectionID = $('body').attr('id');
			
			if (sectionID !== 'shop' && ($button.attr('type') !== 'button') && $form.attr('id') !== 'custom') {
				$button.hide().parent().addClass('no-bg').end().before('<p class="loading"><img src="/images/loader.gif" width="16" height="16" />Submitted, please wait...</p>');
			}
		
		}
	);	
}
/**
 * Scroll the quotes div in the footer
 * As jQuery can't calculate the position of hidden elements, we need to show it and then invoke the scroller
 * And then hide it again
 */
function footerScroll() {
	var $quotesScroll = $('.quotes-scroll');
	$quotesScroll.each(
		function() {
			var $quotesScrollElement = $(this);
			var $quotesScrollParent = $quotesScrollElement.closest('.container');
			
			if ($quotesScrollParent.is(':hidden')) {
				$quotesScrollParent.show().addClass('hidden');
			}
			
			$quotesScrollElement.scroller({
				direction: 'horizontal',
				horizontalOffset: 0
			});
			
			if ($quotesScrollParent.hasClass('hidden')) {
				$quotesScrollParent.removeClass('hidden').hide();
			}
		}
	);
	
	$quotesScroll.delegate('.story','click',
		function() {
			var id = $(this).attr('id');
			window.location = '/quotes/#' + id;
		}
	);
	
	var quoteStories = $quotesScroll.find('.story');
	quoteStories.each(
		function() {
			var $para = $(this).find('p:eq(0)');
			var wordLength = $para.text().split(' ').length;
			if (wordLength == '20') {
				$para.append('...');
			}
		}
	);
	
}
/* 
 *  Third party newsletter signup, hide form on submittal and show a subscription upsell message in its place
 */
function signupForm() {	
	var $signupInput = $('#newsletter-signup');
	$signupInput.delegate('input:text','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');
				}
			}
		}
	);
}

function twitterLink() {
	$('.twtr-hd > h4').click(function() {
		window.open('http://www.twitter.com/totalpolitics');
	});			
}

/**
 * This scrolls in the related article div when the comments div
 * is scrolled into view and the scrolls back out when it is out of view
 */ 
function relatedSlide() {	
	var $slide = $('#related-article-slide');
	if($slide.length) {
		var $window = $(window);
		var $comments = $('#comments');
		var commentsOffsetTop = $comments.offset().top;
		
		var sliderPositionToSet = (($window.width() - 960) / 2) + 960 - 332;
		
		$window.scroll(
			function() {				
				var commentsOffset = $comments.offset().top - 100;
				var viewportPosition =  $window.height() + $window.scrollTop();
				
				if (viewportPosition > commentsOffset) {
					$slide.show().addClass('showing').animate({
						left: sliderPositionToSet
					}, 'slow');
				} else {
					if ($slide.hasClass('showing')) {
						$slide.stop(true).animate({
							left: '2000px'
						}, 'slow',
							function() {
								$(this).removeClass('showing').hide();
							}
						);
					}
				}
			}
		);	
		
	}
} 


// Data RHS Accordion functionality
function dataAccordion() { 
	var dataList = $('.open');
	dataList.click(function() {
		var subList =$(this).parent('li').find('.sub-list');
		if(subList.is(':visible')) {
			$(this).removeClass('browse-list');
			subList.slideUp(function() {
				if(subList.hasClass('display-list')) {
					subList.removeClass('display-list');
				}
			});
		} else {
			$(this).removeClass('open').addClass('browse-list');
			subList.slideDown();			
		}
	});
}
function quotesTools(){
	var $quotes = $('#article > .story');
	$quotes.hover(function(){
		$(this).find('.quotes-tools').delay(500).fadeIn();	
	}, function(){
		$(this).find('.quotes-tools').fadeOut();
	});
	var queryString = window.location.search.substring(1);
	var getQuery = queryString.split('?');	
	if (window.location.search !== '') {
		var $rhsSearch = $('#rhs-search');
		if ($rhsSearch.length) {
			$rhsSearch.addClass('selected').show();
			$rhsSearch.siblings('div').removeClass('selected').hide();
			
			var $tabs = $('#data-tabs');
			var $tabToShow = $tabs.find('li:eq(1)').find('a');
			$tabToShow.addClass('active').parent().prev().find('a').removeClass('active');
		}
	}
}
/*********
*	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'
		});
	}
	
	$basketTotal.click(
		function() {
			var $anchor = $(this).find('a');
			window.location = $anchor.attr('href');
		}
	);
}

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


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

function related() {
	var $related = $('#related-documents, #related-articles');
	var $story = $related.find('.story');
	if ($story.length == 0) {
		$related.hide();
	}
}


function blogDirectory() {
	var $categories = $('#categories');
	if ($categories.length) {
		$categories.delegate('select','change',
			function() {
				var $select = $(this);
				
				var section = $select.attr('id');			
				var optionValue = $select.find('option:selected').attr('value');
				
				if (optionValue !== '') {
					window.location = '/blog/directory/' + section + '/' + optionValue + '/';
				}
			}
		);
	}
	
	$('#blog-close').click(
		function() {
			parent.$.fn.colorbox.close();
		}
	);
	
	var $submitABlog = $('#module-submit-a-blog a');
	if ($submitABlog.length) {
		$submitABlog.attr('href','/blog/directory/submit-a-blog/');
	}
}


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