/**
 * @author	Jonathan Cochran <jono.cochran@gmail.com>
 * --------------------------------------------------------- */

// Load jQuery
//google.load("jquery", "1.4");

//Load Complete...
//google.setOnLoadCallback(function() {
$(document).ready(function() {
	/**
	 * ADDITIONAL PLGUINS
	 * --------------------------------------------------------- */	
	/*
	$.getScript(hostname +'js/jquery.backgroundPosition.1.1.js');
	$.getScript(hostname +'js/jquery.easing.1.3.js');
	$.getScript(hostname +'js/jquery.timers-1.1.3.js', function() {
		$.getScript(hostname +'js/jquery.fabric.banners.js', initHomepage);
	});
	$.getScript(hostname +'js/jquery.scrollTo-1.4.2-min.js');
	*/
	
	/**
	 * BROWSER / DOC LOCATION
	 * --------------------------------------------------------- */
	var docLoc = window.location.href;	
	var isPage = docLoc.indexOf('/') != "-1" ? true : false;
	var arSlash= docLoc.split('/');
	var bSingle= arSlash[(arSlash.length-2)] == 'p';
	var pageId = arSlash[(arSlash.length-1)];
	var badBrowser = (/MSIE ((5\.5)|6|7)/.test(navigator.userAgent) && navigator.platform == "Win32");
	
	/**
	 * NAVIGATION
	 * --------------------------------------------------------- */
	var $parentNavLinks = $('.parent-nav a');
	var $parentNavDivs  = $('[class^="subnav-"]');
	
	// Remove empty sub navs
	$parentNavDivs.each(function() {
		if ( $('a', $(this)).length == 0 )
			$(this).remove();
	});
	
	$parentNavLinks.mouseover(function(event, subnavid) {
		
		var id = this.id;
		if ( subnavid != undefined )
		{
			id = subnavid;
		}
		
		var $subNav = $('div.subnav-'+ id);
		var $docW   = $(document).width()	
		//var $iNavPos= event.pageX - (($docW-980)/2);	
		//$parentNavLinks.removeAttr('style');
		//$(this).css('color', 'black');
		
		if ($subNav.css('margin-top') == "0px")
			return false;
			
		//var $iWidth = $subNav.width();
		//var $iPos	= ($iNavPos-60); //parseInt((980-$iWidth) / 2)
		//$subNav.css('padding-left', $iPos);
		
		$parentNavDivs.stop().animate( {
				'margin-top' 	: -30
				//'position' 		: 'absolute', // Buggy in IE
			}, 100, 'easeOutExpo', function() {
				$subNav.stop().animate( { 'margin-top' : 0 }, 200, 'easeOutExpo', function(){
					var $this = $(this);
					$('.sub-nav-inner').mouseout(function(event) { 
						if (($('#page-wrap').length > 0 && event.pageY > 390) || ($('#homepage-banner').length > 0 && event.pageY > 510))
						{
							$this.stop().animate( { 'margin-top' : -30 }, 500, 'easeOutExpo');
						}
					});
				});
			});
		
	});
	
	// Page is loaded, load & select nav
	if ( !isNaN(pageId) && !bSingle )
	{
		$childLink = $('#child-'+ pageId);
		// Third level nav...
		if ( $childLink.length == 0 )
		{
			$('#thirdnav-'+ pageId).addClass('thirdnav-current');
			pageId = $('#parent_id').val();
			$childLink = $('#child-'+ pageId);
		}
		// Second level nav...
		if ( $childLink.length > 0 )
		{
			id = $childLink.parent().attr('class').replace('subnav-', ''); //subnav container
			$('#child-'+ pageId).addClass('subnav-current');
			$parentNavLinks.trigger('mouseover', [id]);
		}
	}
	
	/**
	 * REPLACE FONTS
	 * --------------------------------------------------------- */
	Cufon.replace('#header-navigation a, .copyright', { fontFamily: 'Gotham Medium', hover: true });
	Cufon.replace('#navigation a, #navigation span', { fontFamily: 'Gotham Medium', hover: true });
	Cufon.replace('#footer-widgets a', { fontFamily: 'Gotham Bold', hover: true });
	
	if ( $('h1').length > 0 ) {
		Cufon.replace('h1', { fontFamily: 'Gotham Medium' });
	}
	if ( $('.widget h2').length > 0 ) {
		Cufon.replace('.widget h2', { fontFamily: 'Gotham Bold' });
	}
	
	/**
	 * BOTTOM CAROUSEL
	 * --------------------------------------------------------- */
	var $objBottomCarousel = $('#footer-banners-img');
	if ( $objBottomCarousel.length > 0 )
	{
		
		var iCurrent = 0;
		var $objBanners = $('a', $objBottomCarousel);
		var iCount = $objBanners.length;
		$objBottomCarousel.width( parseInt(iCount * 740) );
		$('#footer-banners-inner').scrollTo( $('#footer-banners-img li:eq(0)'), 1); //fix a initial padding issue
		$('#footer-banners-img li:eq('+ parseInt(iCount-1) +')').css('border-right', 'none'); //remove last img border
		
		//Buttons
		$('.footer-next').click(function() {
			$(document).stopTime();
			resumeTime();
			
			if ( parseInt(iCurrent+1) == iCount ){
				//$('.footer-prev').addClass('footer-prev-current');
				//return false;
				iCurrent = -1;
			}
			iCurrent++;			
			$('#footer-banners-inner').scrollTo( $('#footer-banners-img li:eq('+ iCurrent +')'), 500, { easing: 'easeOutExpo'  });
			
			
		});
		$('.footer-prev').click(function() {
			$(document).stopTime();
			resumeTime();
			
			if ( iCurrent == 0 ) {
				return false;
			} 
			iCurrent--;
			$('#footer-banners-inner').scrollTo( $('#footer-banners-img li:eq('+ iCurrent +')'), 500,  { easing: 'easeOutExpo'  } );
		});
		
		//Timer
		function resumeTime()
		{
			$(document).everyTime(5000, function(i) { 
				//$('.footer-next').trigger('click');
			});
		}
		resumeTime();
	}
	
	/**
	 * PAGES
	 * --------------------------------------------------------- */
	if ( $('#homepage-banner').length > 0 )
	{
		var iImg = $('#banner-img img').length;
		if (iImg < 1) return false;
		$('#banner-img').cycle({ fx: 'fade', speed: '5000' });
		//$('#banner-img').slideImages('horizontal', 980, 370, 200, 'easeInOutExpo', 'timer=10000');  
		
	}
	
	if ( $('#page').length > 0 )
	{
		$('#footer').css('padding', '25px 0 40px 0');
	}
	
	if (isPage) initPage();
	function initPage()
	{
		var $objPageContent = $('#page-content');
		var $objJumpTo = $('#jump-to ul');
		var $objH2s = $('h2', $objPageContent);
		
		if ($objPageContent.length < 1) return false;
		
		//Object positioning..
		$('#page-content img, object').each(function() {
			if ( $(this).css('float') == "left" )
			{
				$(this).addClass('content-item-left');
			}
			if ( $(this).css('float') == "right" )
			{
				$(this).addClass('content-item-right');
			}
		});
		
	}
	
	// Media Centre
	if ( $('.media-centre').length > 0 )
	{
		// Series Overview...
		$('.media-item').hover(function() {
			$(this).stop().animate({
				backgroundColor : '#000'
			}, 200);
		}, function() {
			$(this).stop().animate({
				backgroundColor : '#F9F8F1'
			}, 500);
		});
		
		// Sidebar Navigation
		$('a.series-year').addClass('series-closed');
		$('a.series-link').hide();
		$('a.series-year').click(function() {
			var $parentDiv = $(this).parent();
			if ($(this).hasClass('series-closed'))
			{
				$(this).removeClass('series-closed');
			}
			else 
			{
				$(this).addClass('series-closed');
			}
			$('a.series-link', $parentDiv).toggle();
		});
		
		if ( $('.series-current').length > 0 )
		{
			var $parentDiv = $('a.series-current').parent();
			var $parentA   = $('a.series-year', $parentDiv);
			
			if ($parentA.hasClass('series-closed'))
			{
				$parentA.removeClass('series-closed');
			}
			else 
			{
				$parentA.addClass('series-closed');
			}
			$('a.series-link', $parentDiv).toggle();
		}
		
		// Media description..
		$('.media-description').click(function() {
			var $id = this.id;
			$('#desc-full-'+ $id).toggle();
		});
	}

	
	if ( $('.video').length > 0 )
	{
		
		//Fullscreen video.
		$('.video').click(function() {
			vUrl = $(this).attr('rel');
			videoDesc = $(this).parents().parents().children('span').html(); 
			if (videoDesc == null) videoDesc = "";
			$.getJSON(
				hostname +'?c=site&m=getVideoCode',
				{ vurl : vUrl },
				function(data) 
				{
					html = '<div class="fullscreen-video-desc"><a href="'+ data.video_url +'">'+ videoDesc +'</a></div>';
					$('#fullscreen-content').addClass('fullscreen-video');
					$('#fullscreen-close').addClass('fullscreen-video-close');
					loadFullScreen('<div id="fullscreen-video">'+ data.embed_code + html +'</div>');
				}
			);
		});
	}
	
	var Url = {

		// public method for url encoding
		encode : function (string) {
			return escape(this._utf8_encode(string));
		},

		// public method for url decoding
		decode : function (string) {
			return this._utf8_decode(unescape(string));
		},

		// private method for UTF-8 encoding
		_utf8_encode : function (string) {
			string = string.replace(/\r\n/g,"\n");
			var utftext = "";

			for (var n = 0; n < string.length; n++) {

				var c = string.charCodeAt(n);

				if (c < 128) {
					utftext += String.fromCharCode(c);
				}
				else if((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				}
				else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}

			}

			return utftext;
		},

		// private method for UTF-8 decoding
		_utf8_decode : function (utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;

			while ( i < utftext.length ) {

				c = utftext.charCodeAt(i);

				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				}
				else if((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				}
				else {
					c2 = utftext.charCodeAt(i+1);
					c3 = utftext.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}

			}

			return string;
		}

	}

	

	
	/**
	 * FULL SCREEN, IMAGES & VIDEOS
	 * --------------------------------------------------------- */
		var objImagesParent = ""; //Parent div holding images (prev / next)
		function loadFullScreen(html)
		{
			//Check if loaded already...
			if ($('#fullscreen-bg').is(':visible'))
			{
				$('#fullscreen-content').html(html);
				initFullScreenEvents();
			}
			//Load'r in...
			else {
				$('#fullscreen-bg').height($(document).height());
				$('#fullscreen-bg').css('display','block').fadeTo(300, .75, function() {
					$('#fullscreen-content').css('display', 'block').html(html).fadeTo(500, 1, function() {
						$('.tour-info', $(this)).css('display', 'block');
						$('#fullscreen-close').css('display', 'block');
						initFullScreenEvents();
						if ( $('h1', $(html)).length > 0 )
							Cufon.replace('h1');
						
						if ( $('.calendar-event-inner').innerHeight() > 240 )
						{
							$('#fullscreen-close').css('left', '162px');
						}	
						
					});
				});
			}
		}
		function initFullScreenEvents()
		{
			initFullScreenNext();

			//Remove fullscreen
			$('#fullscreen-close, #fullscreen-bg').click(function() {
				removeFullScreen();
			});
			//Escape, or backspace key is press
			$(document).keypress(function (e) {
				if (e.which == 0 || e.which == 8)
				{
					removeFullScreen();
				}
			});
		}
		function removeFullScreen()
		{
			//Remove previously added classes...
			$('#fullscreen-content').removeClass('fullscreen-video');
			$('#fullscreen-close').removeClass('fullscreen-video-close');

			//Remove inline styles...
			$('#fullscreen-content').attr('style', '');
			$('#fullscreen-close').attr('style', '');

			$('#fullscreen-bg, #fullscreen-close, #fullscreen-content').css('display', 'none');
			$('#fullscreen-content').html('');
		}
		function loadFullScreenImage(objImg)
		{
			var imgSrc  = $('img', objImg).attr('src').replace('_thumb', '');
			var imgDesc = $(objImg).next('span').html();
			var imgDim  = $(objImg).attr('rel').split('x');
			var imgW    = Number(imgDim[0]);
			var imgH    = Number(imgDim[1]);

			html  = '<img src="'+ imgSrc +'" />'; 
			html += '<div class="fullscreen-video-desc" style="margin-top: 6px">'+ imgDesc +'</div>';
			$('#fullscreen-content')
			.animate({
				'width'  	 : imgW +'px',
				'height' 	 : (imgH+40) +'px',
				'left' 		 : (imgW/2)*-1,
				'marginTop'  : ((imgH+40)/2)*-1
			},200); 
			$('#fullscreen-close')
			.animate( {
				'left' 		 : (imgW/2)-100,
				'marginTop'  : ((imgH-40)/2)+13
			},200);

			loadFullScreen(html);
		}
		function initFullScreenNext()
		{
			//Parent is the holder of thumbnails
			if (objImagesParent)
			{
				$('#fullscreen-content img').click(function() {			
					thisImageSrc = $(this).attr('src'); 		 //Get the current fullscreen image
					objChildImages  = $('img', objImagesParent); //Get children images (thumbnails)

					//Loop thumbnails...
					objChildImages.each(function() {

						//Check if the current image is the loop item
						var strChildSrc = $(this).attr('src').replace('_thumb', '');
						if (strChildSrc == thisImageSrc)
						{
							//Replace current image with the next image
							var objNext = $(this).parent('a').parent('div').next('div');
							var refA	= $('a', objNext);
							if ($(refA).length == 0) {
								refA = $('a:first', objImagesParent);													
							}

							//Load in image
							loadFullScreenImage(refA);
						}
					})
				});
			}
		}
	
	
});
