$(document).ready(function(){
	var _urlEnding = '.co.uk';

	if ($('.home').size()>0) {
	// FIND OR CREATE A HASH SHORTLINK
	function makeHash(_section,_post){
	
		//FILTER OUT ABSOLUTE LINKS
		if(_post.split(_urlEnding + '/')[1]){
		
			_post = _post.split(_urlEnding + '/')[1]
		
		}
	
		var _queryString = '';
	
		_queryString += 'section=' + _section + '&page=' + _post;
		
		location.hash = '#!/' + _queryString;
	
	} // END MAKEHASH function

	var _currentSection = '';
	var _currentPost = '';
	var _loadAnimating = false;
	var _animateSpeed = 600; 

	// Homepage featured image slider
	$('#featured').anythingSlider({
		resizeContents      : true,
		buildNavigation     : false,      
		enableNavigation    : false,
		hashTags            : false,
		delay               : 5000,     
		resumeDelay         : 5000,
		animationTime       : 600 
	});


	function goToSection(section, callBack) {

		$(window).scrollTo($('#'+section+'').offset().top - 100, 500, { onAfter: function() { if (typeof callBack == 'function') callBack(); } });
	}
	
	function showBackButton(section) {
		$('.backbutton', section).stop(true, true).fadeIn();	
	}
	
	function loadContent(section, url) {
		if(!_loadAnimating){
		loadAnimating = true;
		section = $('#' + section);
		var loadArea = $('.loadarea', section);
		
		if (loadArea.data('original-height') == undefined) loadArea.data('original-height', section.height());

		var slide = $('div[rel = "' + url + '"]', section);

		// slideOut what's already there
		$('.current', loadArea).animate({left: '-1000px'}, 800).removeClass('current');

		// if content not already loaded then load it.
		if (slide.length == 0) {

			slide = $('<div class="wrapper"></div>').attr('rel', url);

			slide.load(url + ' .single', function() {

				slide
					.appendTo(loadArea)
					.css('left', '1000px');
				
				var slideshow = $('#slideshow ul', slide);
				if (slideshow.length) 
				slideshow.anythingSlider({
						autoPlay			: false,
						resizeContents      : false,
						buildNavigation     : true,      
						enableNavigation    : true,
						hashTags            : false,
						buildArrows			: false,
						delay               : 5000,     
						resumeDelay         : 5000,
						animationTime       : 600 
					});
				
				
				loadArea.animate({ height: slide.height() }, 300, function() {
					slide.animate({left: 0}, 800, function() { showBackButton(section) });
					loadAnimating = false;
				});

			});
		} 
		else {
			// slide already loaded, just animate it
			
			loadArea.animate({ height: slide.height() }, 300, function() {
			
				slide
					.css('left', '1000px')
					.delay(800)
					.animate({left: 0}, 800, function() { showBackButton(section) });
					loadAnimating = false;
			});
		}
		slide.addClass('current');
		}
	}
	
	
	$('#header .navigation a').click(function(e) {

		e.preventDefault();
		makeHash($(this).attr('rel'),''); //MB
		//goToSection($(this).attr('rel'));
	});
	
	$('.loadarea a[rel = "permalink"]').live('click', function(e) {
		e.preventDefault();
		makeHash($(this).closest('.scrollable').attr('id'),$(this).attr('href')); //MB
		//loadContent($(this).closest('.loadarea').parent().attr('id'), $(this).attr('href'));
	});
	
	$('.backbutton').click(function(e) {
	
		e.preventDefault();
		
		if ($(this).data('clicked')) return false;
		
		$(this).data('clicked', true);
		
		var that = this;
		var parent = $(this).closest('.scrollable');

		parent.find('.current').animate({ left: '1000px' }, _animateSpeed, function() {
			
			$(this).removeClass('current');
			
			var loadArea = $('.loadarea', parent);
			loadArea.animate({ height: loadArea.data('original-height') }, _animateSpeed, function() {
			
				$('.default', parent).css('left', '-1000px').animate({ left: 0 }).addClass('current');
				$(that).hide();
				$(that).data('clicked', false);
								
				if(parent.attr('id') == _currentSection){
					makeHash(_currentSection,'');
				}
				_animateSpeed = 600;
			});
		});
	});
	
	$('#banner .panel a').each(function() {
	
		theLink = $('h2 a[href = "' + $(this).attr('href') + '"]:not(#banner a)');
		
		$(this).data('data', {
			 parent: theLink.closest('.loadarea').parent().attr('id'),
			 url: theLink.attr('href')
		 });
			
	}).click(function(e) {
		
		e.preventDefault();
		makeHash($(this).data('data').parent,$(this).attr('href'));
		/*goToSection($(this).data('data').parent);
		loadContent($(this).data('data').parent, $(this).data('data').url);*/
	});
	
	//Make the previous and next buttons of the news articles anchor to the section
	$('.navigation .alignright a,.navigation .alignleft a').each(function(){
	
	
		var linkURL = $(this).attr('href');
		var anchorURL = '#!/section=' + $(this).closest('.scrollable').attr('id');
		$(this).attr('href',linkURL + anchorURL)
		
	
	})

	// MB - HASH SHORTLINKING
	
	function runHash(){
	
		if(_currentPost.length > 1){
			
			goToSection(_currentSection);
			loadContent(_currentSection, _currentPost);
			
		
		} else if (_currentSection.length > 1){
			
			goToSection(_currentSection);
									
		}
	
	}
	
	function findHash(){
	
		// Bind the event.

		try {
		
			_currentPost = location.hash.split('page=')[1].split('&')[0];
			
		} catch(err) {
		
			_currentPost = '';
		
		}
		
		try {
		
			_currentSection = location.hash.split('section=')[1].split('&')[0];
		
		} catch(err){
		
			_currentSection = '';
		
		}
				
		if($('.backbutton:visible').size()){
			//make back button animate instantaneously
			_animateSpeed = 0;
			$('.backbutton:visible').trigger('click');
			
			runHash();
				
		} else {
		
			runHash();
		
		}
							
	}
	
	
	// Bind the event.
  $(window).hashchange( function(){
    // Alerts every time the hash changes!
    findHash();
  })

  // Trigger the event (useful on page load).
  $.doTimeout(500,function(){$(window).hashchange()});

		

	} else {// END HOME IF STATEMENT
		//CHANGE MAIN NAVS TO DYNAMICS on ALL OTHER pages - do this with JS instead of PHP to ensure non JS compat
		$('.navigation a').each(function(){
		
			var splitURL = $(this).attr('href').split(_urlEnding + '/');
			
			var siteURL =  splitURL[0] + _urlEnding + '/';
			var linkPath = splitURL[1];
			
			$(this).attr('href',siteURL+'#!/section='+linkPath)
		
		});
	
	}
	
});
