$(function() {
	navigation();
	addInputPlaceholders();
	selectMagazines();
	loadingMessage();
	articleTabs();
	autocomplete();
	changeDeliveryRegion();
	createSocialJS();
	colorbox();
});


/**
 * On hovered tab/selected tab find previous sibling and remove the border
 */
function navigation() {
	var $navigation = $('#navigation'),
		$selectedNav = $('#navigation .selected');
		
	$selectedNav.prev().addClass('no-border');
	
	$navigation.delegate('.tab','hover',
		function(event) {
			var $tab = $(this);
			
			if ($tab.prev().hasClass('selected') === false) {
				if (event.type === 'mouseenter') {
					$tab.prev().addClass('no-border');
				} else {
					$tab.prev().removeClass('no-border');
					$selectedNav.prev().addClass('no-border');
				}
			}
		}
	);
	
	// fix ie6 z-index over selects
	if (typeof document.body.style.maxHeight === 'undefined') {
		$('.subnav ul').bgiframe();
	}
}


/**
 * If input doesn't support placeholder attribute mimic it
 */
function addInputPlaceholders() {	
	if (!('placeholder' in document.createElement('input'))) {
		var $searchInput = $('#search-form input');
		$searchInput.attr('value', 'Search for your favourite magazine');
		
		$searchInput.focus(
			function() {
				var $input = $(this);			
				if ($input.val() === 'Search for your favourite magazine') {
					$input.attr('value', '');
				}
			}
		).blur(
			function() {
				var $input = $(this);			
				if ($input.val() === '') {
					$input.attr('value', 'Search for your favourite magazine');
				}
			}
		);
	}
}


/**
 * Find all selects and when option is selected change the location
 */
function selectMagazines() {
	var $selectMagazines = $('#select-magazines');
	$selectMagazines.delegate('select','change',
		function() {
			var selectedOption = $(this).find('option:selected').attr('value');
			if (selectedOption !== 'ignore') {
				window.location = selectedOption;
			}
		}
	);
}

/**
 * Find all button elements and check for data-message attribute
 * If present hide the button and replace with message and loader gif
 */
function loadingMessage() {	
	$('form').delegate('button','click',
		function(event) {
			//event.preventDefault();
			var $button = $(this),
				buttonMessage = $button.attr('data-message'),
				buttonItemDescrip = $button.attr('data-item-descrip');
			
			// remove button on your basket page
			if (typeof buttonItemDescrip !== 'undefined') {
				if (!confirm('Are you sure you wish to remove ' + buttonItemDescrip + ' from your basket?')) {
					return false;
				}
			}
			
			if (typeof buttonMessage !== 'undefined') {
				$button.hide().after('<p class="loading"><img src="/images/loader.gif" width="16" height="16">' + buttonMessage + '</p>');
			}
		}
	);
}


/**
 * If article has tabs hide/show relevant ones
 */
function articleTabs() {
	var $tabs = $('#tabs');
	
	$tabs.find('.active').siblings().addClass('hidden');
	$tabs.delegate('.tabs a','click',
		function(event) {
			event.preventDefault();
			
			var $tab = $(this); 
			var divToShow = $tab.attr('href');
			
			if (!$tab.parent().hasClass('on')) {
				var $divToShow = $(divToShow);
				
				if (typeof document.body.style.maxHeight !== 'undefined') {
					// jQuery can't calculate the height of hidden elements			
					var divToShowHeight = $divToShow.removeClass('hidden').addClass('active').outerHeight();					
					
					$divToShow.removeClass('active').addClass('hidden').parent().animate({
						'height' : divToShowHeight
					}).end().removeClass('hidden').addClass('active').siblings().removeClass('active').addClass('hidden');
				} else {
					$divToShow.removeClass('hidden').addClass('active').siblings().removeClass('active').addClass('hidden');
				}
				
				$tab.parent().addClass('on').siblings().removeClass('on');
			}
		}
	);
}


/**
 * Autocomplete for search in header
 */
function autocomplete() {
	if (typeof searchTerms !== 'undefined') {
		// replace &amp; with &
		for(var i=0; i < searchTerms.length; i++) {
			searchTerms[i] = searchTerms[i].replace(/&amp;/g, '&');
		}
		
		var timer = null,
			$searchForm = $('#search-form');
			$search = $('#search-form input');
			
		if ($search.length) {
			$search.autocomplete({
				minLength: 2,
				source: searchTerms,
				select: function(event, ui) {
					$search.attr('value',ui.item.value);
					$searchForm.submit();
				}
			}).live('keydown',
				function(e) {
					var keyCode = e.keyCode || e.which;
					//if TAB or RETURN is pressed set the value of the textbox to the text of the first suggestion
					if ((keyCode == 9 || keyCode == 13) && $('.ui-autocomplete').is(':visible')) {
						$(this).val($('.ui-autocomplete li:visible:first').text());
						$searchForm.submit();
					}
				}
			);
		}
	}
}


/**
 * Functions below handle social media
 * Create async twitter and google scripts if in article page
 * Handle GA tracking for google plus one and twitter tweet
 */
function createSocialJS() {
	var isArticleRegex = /(?:\d+\.)?(\d+)/;
	if (isArticleRegex.test(document.location.pathname)) {
		// google plus one
		var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
		po.src = 'https://apis.google.com/js/plusone.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
		
		// twitter
		var tw = document.createElement('script'); tw.type = 'text/javascript'; tw.async = true;
		tw.src = 'http://platform.twitter.com/widgets.js';
		document.getElementsByTagName('head')[0].appendChild(tw);
	}
}

function plusone_vote(obj){
	_gaq.push(['_md._trackEvent','Social Networking','Google Plus One','"' + document.title + '"']);
}

function twitter() {
	twttr.events.bind('tweet', function(event) {
		if (event) {
			var targetUrl;
			if (event.target && event.target.nodeName == 'IFRAME') {
				targetUrl = extractParamFromUri(event.target.src, 'url');
			}
			_gaq.push(['_md._trackEvent', 'Social Networking', 'Tweet', targetUrl]);
		}
	});
}

function extractParamFromUri(uri, paramName) {
	if (!uri) {
		return;
	}
	var uri = uri.split('#')[0];  // Remove anchor.
	var parts = uri.split('?');  // Check for query params.
	if (parts.length == 1) {
		return;
	}
	var query = decodeURI(parts[1]);
	
	// Find url param.
	paramName += '=';
	var params = query.split('&');
	for (var i = 0, param; param = params[i]; ++i) {
		if (param.indexOf(paramName) === 0) {
			return unescape(param.split('=')[1]);
		}
	}
}


/**
 * Change country in article
 */
function changeDeliveryRegion() {
	$deliveryRegion = $('#delivery-region');
	$deliveryRegion.change(
		function() {
			var optionSelected = $(this).find('option:selected');
			setCookie('country',optionSelected.val());
			setCookie('countryName',optionSelected.text());
			window.location = window.location;
		}
	);
}

function setCookie(cookieName,cookieValue) {
	document.cookie=cookieName+"="+escape(cookieValue)+";path=/";
}


/**
 * Launch colorbox for fullsize image
 */
function colorbox() {
	var $fullsizeImage = $('.lbox');
	if ($fullsizeImage.length) {
		$fullsizeImage.colorbox({
			opacity: '0.7'
		});
	}
}
