/**
 * @author	Jonathan Cochran <jono.cochran@gmail.com>
 * --------------------------------------------------------- */
$(document).ready(function() {
	
	
	var $objContentWrap = $('#content-wrapper');
	var $objContent		= $('.content'); 	// main content nest
	var $objNav			= $('#navigation a');
	
	/**
	 * BROWSER / DOC LOCATION
	 * --------------------------------------------------------- */
	var docLoc = window.location.href;	
	var isPage = docLoc != hostname ? 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|8)/.test(navigator.userAgent) && navigator.platform == "Win32"); 
	
	var getHash = docLoc.indexOf('#') != "-1" ? true : false; // hash # present in uri
	var split = docLoc.split('#');
	var $hashPage = split[1];

	/**
	 * REPLACE FONTS
	 * --------------------------------------------------------- */
	Cufon.replace('.navigation-links a', { hover: true });
	Cufon.replace('h1');
	
	/**
	 * NAVIGATION
	 * --------------------------------------------------------- */		
	// Replace nav links to ajax...
	// $objNav.each(function() { 
	// 	var id  = this.id;
	// 	var url = $(this).attr('href');
	// 	var rel = $(this).attr('rel')
	// 	
	// 	if ( rel != "missions" && id != "logo" )
	// 	{
	// 		if ( docLoc.indexOf(hostname) != "-1" && !$(this).hasClass('external') )
	// 		{
	// 			var page = url.replace(hostname, '');
	// 			if ( page != "javascript:;" )
	// 			{
	// 				$(this).attr('href', hostname +'#'+ page);
	// 			}
	// 		}
	// 	}
	// 	
	// 	//eval(url)(name);
	// });
	
	// Scrollable nav
	$('.nav-scrollUp, .nav-scrollDown').hide();
	function navResize()
	{
		$objNav = $('.navigation-inner');
		
		var docH = $('#navigation').height();
		var navH = $objNav.height() + 50;

		//$('.nav-scrollUp, .nav-scrollDown').show();		
		if ( docH < navH )
		{
			if ( badBrowser) {
				$('.nav-scrollUp, .nav-scrollDown').show();
			} else {
				$('.nav-scrollUp, .nav-scrollDown').stop().fadeTo(300, 1);			
			}
			$('.navigation-inner').stop().animate({ 'marginTop' : 0 }, 1000, 'easeInOutExpo');
			iNavMarginTop = 0;
		}
		else
		{
			if (badBrowser) {
				$('.nav-scrollUp, .nav-scrollDown').hide();
			} else {
				$('.nav-scrollUp, .nav-scrollDown').stop().fadeTo(300, 0);
			}			
		}
	}
	$(window).resize(function() {		
		navResize();		
	});	
	
	var iNavMarginTop = 0;
	var iScrollAmt = 3;
	function toggleNavScroll()
	{		
		$('.nav-scrollDown, .nav-scrollUp').mouseup(function(){
			$('.navigation-inner').stopTime('controlled');
	    }).mousedown(function(){
			var $objScroll = $(this);
			
	    	$('.navigation-inner').everyTime(5, 'controlled', function(i) {
				if ( $objScroll.hasClass('nav-scrollDown') )
				{
					iNavMarginTop -= iScrollAmt;
				}
				else
				{
					iNavMarginTop += iScrollAmt;
				}
				$('.navigation-inner').css('marginTop', iNavMarginTop);
			});
		});		
	}
	
	toggleNavScroll();
	
	
	
	// Top level nav clicked...
	$objNav.bind('click', function() {			
		var strPageToLoad = $(this).attr('href').split('#')[1];
		
		
		if ( $(this).parent('div').length > 0 )
		{			
			return true;
		}
		
		// Add 'current' Class
		$('.navigation-links a').removeClass('navigation-current');
		$(this).addClass('navigation-current');
		Cufon.replace('.navigation-links a', { hover: true });
		Cufon.replace('h1');
		
		// Hide any other sub nav menus
		$('.navigation-links div').hide();		
		
		// Load content if it's not a sublink
		if ( $(this).hasClass('main-link') )
		{
			loadContent(strPageToLoad);
			//return false;
		}
		
		// Remove & add navigation classes
		$(this).parent('li').children('div').toggle();
		navResize();
		
	});
	
	// Subnav links clicked...
	$('.subnav-links a').click(function() {
		
		var strPageToLoad = $(this).attr('href').split('#')[1];
		
		// Add 'current' Class
		$('.subnav-links a').removeClass('subnav-current');
		$(this).addClass('subnav-current');
		Cufon.replace('.navigation-links a', { hover: true });
		
		// Add arrow
		$('.navigation-arrow').remove();
		loadContent(strPageToLoad);
		if ( badBrowser ) 
		{
			$(this).after('<img class="navigation-arrow" src="'+ hostname +'images/nav-arrow.gif" />');
		} 
		else
		{
			$(this).after('<img class="navigation-arrow" src="'+ hostname +'images/nav-arrow.png" />');
		}
		
	});
	
	function randNum(min, max)
	{
	  var argc = arguments.length;
	    if (argc === 0) {
	        min = 0;
	        max = 2147483647;    } else if (argc === 1) {
	        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
	    }
	    return Math.floor(Math.random() * (max - min + 1)) + min;
	}
	function loadContent(strPageToLoad)
	{	
		var rand = randNum(1, 7);
		
		// Do the animation
		if ( $objContentWrap.css('marginLeft') == '0px' )
		{
			$objContentWrap.stop().animate({ 'marginLeft' : '-860', 'opacity' : .5 }, 800, 'easeOutExpo', function() {
				$(document).oneTime(100, function() { loadContent(strPageToLoad) }); // Timer to fix a lag animation issue	
			});
		}
		else
		{	
			$.post(
				hostname + strPageToLoad,
				{ 
					bHideView : false
				},
				function(data)
				{				
					// Replace the background
					$('.content').html(data);
						Cufon.replace('.content-header h1');
						$objContentWrap.stop().animate({ 'marginLeft' : '0', 'opacity' : 1 }, 1500, 'easeOutExpo', function() { ieFix(); });
						initPage();
						initCalendar();
						initNews();	
						ieFix();
				}
			);
			
		}
	}
	
	// Load the next page...
	$('.hide-page').click(function() {
		$objContentWrap.stop().animate({ 'marginLeft' : '-860', 'opacity' : .5 }, 800, 'easeOutExpo');
	});
	
	/**
	 * Auto expand the navigation & show content if a user is brought to 
	 * a page from a search engine (rather than ajax)
	 */
	if (isPage)
	{
		if ( $hashPage != "media" )
		{
			$objContentWrap.stop().animate({ 'marginLeft' : '0', 'opacity' : 1 }, 500, 'easeOutExpo');
			Cufon.replace('.content-header h1');
		}
		
		$('#navigation a').each(function() {
			var href = $(this).attr('href').replace(hostname, '');
			var rel  = $(this).attr('rel');
			
			if ( href == "#"+$hashPage && $hashPage != "media" )
			{
				$(this).trigger('click');
			}
			
			/*
			if ( rel !="" && href.indexOf(rel) != "-1" )
			{
				if ( $(this).parent().hasClass('subnav-links') )
				{
					$(this).parent().prev('a').trigger('click');
					$(this).addClass('subnav-current');					
				}
				else
				{
					$(this).addClass('navigation-current');
					
				}
				Cufon.replace('.navigation-links a', { hover: true });
			}
			*/
		});
	}
	
	// Fix IE Height issues
	if (badBrowser) ieFix();
	function ieFix()
	{
		// Scrolling
		if ( badBrowser )
		{
			docH  = $(document).height();
			pageH = $('.content').height();
			
			//alert(pageH);
			
			// IE 8
			if ( pageH != null )
			{
				//alert(pageH);
				pageH += 50;
				$('body').css({ 'overflow' : 'auto', 'height' : pageH });
				//$('#page-wrapper').css({ 'height' : pageH +'px' });
				$('#navigation-wrapper, #page-wrapper').css({ 'height' : pageH +'px' });
				//$('.content').css({ 'height' : pageH +'px' });
				
				if ( docH > pageH )
				{
					$('body').css({ 'overflow' : 'hidden', 'height' : '100%' });
					$('#navigation-wrapper, #page-wrapper').css('height', '100%');
				}
			}
			
		}
	}
	
	
	// Media centre
	$('.media-centre').click(function(ev) {
		
		window.open(hostname +'media',
		'CLA_Media_Centre','width=840,height=550');
		ev.preventDefault();
		return false;
		
		// $.post(
		// 	hostname +'media',
		// 	{
		// 		bHideView : false
		// 	},
		// 	function(html)
		// 	{
		// 		loadMediaCentre(html);
		// 	}
		// );
		
	});
	
	/**
	 * PAGES
	 * --------------------------------------------------------- */
	initPage();
	function initPage()
	{	
		Cufon.replace ('.entry h1');
		// Object positioning..
		$('#page img, object').each(function() {
			if ( $(this).css('float') == "left" )
			{
				$(this).addClass('content-item-left');
			}
			if ( $(this).css('float') == "right" )
			{
				$(this).addClass('content-item-right');
			}
		});
		
		// Campus page
		$objEvents = $('.upcoming-events');
		$objImg = $('#page .campus-content img:first');
		if ( $objEvents.length > 0 )
		{
			if ( $objImg.width() > 500 )
			{
				$objEvents.clone(true).insertAfter($objImg);
				$objEvents.remove();
			}
		}
		
		$('.view-map').click(function() {
			$.get(
					hostname +'site/getMap/'+ this.id,
					function(data)
					{
						loadMap(data);
					}
				);
		});
		
		// Contact page
		if ( $('#contact-form').length > 0 )
		{
			initContact();
		}
		
		// Ministries page
		// if ( $('.ministries').length > 0 )
		// {
		// 	initJumpTo();
		// }
		
	}
	
	function initContact()
	{
		$('.contact-submit').click(function() {
			$.post(
				hostname +'site/contactSubmit',
				{
					name 	: $('input[name="name"]').val(),
					email 	: $('input[name="email"]').val(),
					message : $('textarea[name="message"]').val()
				},
				function(data) {
					$('#contact-response').show().html(data);
					if ( data == "Message Sent!" )
					{
						$('#contact-form input, #contact-form textarea').val('');
					}
				}
			);
		});
	}
	if ( $('#contact-form').length > 0 ) initContact();
	
	
	if ( $('.calendar').length > 0 ) initCalendar();
	function initCalendar()
	{	
		
		//Hide special events..
		toggleCal('special');
		
		//Toggle cal links...
		$('a.special-events').click(function()
		{
			$('.upcoming-events').removeClass('upcoming-events-current');
			$(this).addClass('special-events-current');
			toggleCal('upcoming');
		});
		$('a.upcoming-events').click(function()
		{
			$('.special-events').removeClass('special-events-current');
			$(this).addClass('upcoming-events-current');
			toggleCal('special');
		});
		
		//TD cells
		removeBorders();
		function removeBorders()
		{
			$('tr.cal-days td:last-child').css('border-right', 'none');
			$('tr.cal-days:last-child td').css('border-bottom', 'none');
		}
		
		//Ajax load months
		$('.next-month').click(function() {
			loadCalendar('next');
		})
		$('.prev-month').click(function() {
			loadCalendar('prev');
		});
		
		//Ajax load event info
		loadEventContent();
		function loadEventContent()
		{
			$('.upcoming-events a, .cal-days td a').click(function() {
				$.get(
					hostname +'site/getEvent/'+ $(this).attr('id'),
					{ },
					function(html)
					{
						loadFullScreen(html);
					}
				);
			});
		}
		
		//Hide / show cal event items <a
		function toggleCal(cal)
		{
			$objCalLinks = $('tr.cal-days a');
			$('tr.cal-days td').removeClass('td-event')
			$objCalLinks.each(function() {
				$(this).removeClass('cal-current');
				if ($(this).attr('rel') == cal)
				{	
					$(this).removeClass('cal-current'); //.hide()
				}
				else
				{
					$(this).parent('td').addClass('td-event');
					$(this).addClass('cal-current'); //.show()
				}
			});
		}
		
		//Ajax load next / prev months...
		function loadCalendar(nextPrev)
		{
			$('#cal-load').show();
			
			var strMonth = $('span.cal-month').html();
			var strYear  = parseInt($('span.cal-year').html());
			
			var arMonths = Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
			if (nextPrev == "next")
			{
				for ( i = 0; i < arMonths.length; i++ )
				{
					if (arMonths[i] == strMonth && i < 12)
					{
						strMonth = arMonths[i+1];
						iMonth = i+2;
						break;
					}
					else if (i+2 == arMonths.length)
					{
						strMonth = arMonths[0];
						iMonth = 1;
						strYear++;
					}
				}
			}
			if (nextPrev == "prev")
			{
				for ( i = arMonths.length-1; i > -1; i-- )
				{
					if (arMonths[i] == strMonth && i > 0)
					{
						strMonth = arMonths[i-1];
						iMonth = i;
						break;
					}
					else if (arMonths[i] == strMonth && i == 0)
					{
						strMonth = arMonths[11];
						iMonth = 12;
						strYear--;
					}
				}
			}
			
			$('span.cal-month').html(strMonth);
			$('span.cal-year').html(strYear);
			
			$.post(
				hostname +'site/getCalendar',
				{
					year  : strYear,
					month : iMonth
				},
				function(data) {
					$('.cal-table').fadeTo(500, 0, function() {
						$('.cal-table').before(data).remove();	
						
						$('#cal-load').hide();
							
						removeBorders();
						loadEventContent();
						Cufon.replace('.cal-weekdays td');
						
						if ( $('.special-events-current').length > 0 )
							toggleCal('upcoming');
						else
							toggleCal('special');
					});
				}
			);
		}
	}
	
	if ( $('.news').length > 0 ) initNews();
	function initNews()
	{
		Cufon.replace('.entry h2', { hover: true });
		if ( $('.entry').length > 0 )
		{			
			$(document).oneTime(1000, function() { ieFix(); });
		}
		
		// Next & Prev
		$('.news-prev, .news-next').click(function() {
			$('#page-wrapper').scrollTo(0,0); // scroll to the top of the page...
			var uri = $(this).attr('href').replace(hostname, '');
			loadContent(uri);
			return false;
		});
	}
	
	if ( $('.page-videos').length > 0 ) initVideos();
	function initVideos()
	{
		var $objVideos = $('.video-item');
		
		//Remove 3rd column margin
		i = 1;
		$objVideos.each(function() {
			
			if (i == 3)
			{
				$(this).css('margin-right', 0);
				i = 0;
			}			
			i++;
		});
		
		
		//Fullscreen video.
		$('.video-item a').click(function() {
			videoUrl  = $(this).attr('rel');
			videoDesc = $(this).next('div').children().children().html(); 
			if (videoDesc == null) videoDesc = "";
			$.get(
				hostname +'site/getVideoCode/'+ videoUrl,
				{ },
				function(html) 
				{
					html += '<div class="fullscreen-video-desc"><a href="http://www.youtube.com/watch?v='+ videoUrl +'">'+ videoDesc +'</a></div>';
					$('#fullscreen-content').addClass('fullscreen-video');
					$('#fullscreen-close').addClass('fullscreen-video-close');
					loadFullScreen('<div id="fullscreen-video">'+ html +'</div>');
				}
			);
		});
	}

	
	/**
	 * MAILING LIST
	 * --------------------------------------------------------- */
	$('.nav-mailing-list').attr('href', 'javascript:;');
	$('.mailing-list-link, .nav-mailing-list').click(function() {
		
		//already shown...
		if ( $('#top-mailing-list').length > 0 && ( $('#wrap').css('marginTop') == "130px" || $('#wrap').css('top') == "130px") ) return false;
		
		$.get(
			hostname +'site/getMailingListSignup',
			{ },
			function(data) {
				$(window).scrollTo( 'div#body-wrap', 200, { easing:'easeInOutExpo' } );
				if (badBrowser)
				{
					$('#wrap').animate({ top : 130 }, 1000, 'easeInOutExpo', function() {
						$('#wrap').before(data);
						$('#top-mailing-list').css('margin-top', 0);
						initMailingList();
					});
					
				}
				else
				{
					$('#wrap').before(data).animate({ marginTop : 130 }, 1000, 'easeInOutExpo', function() {
						$('body').css({ backgroundPosition : '0px 130px' });
					});
					initMailingList();
				}
			}
		);
		
		function initMailingList()
		{
			//Close top bar
			$('.mailing-list-close').click(function() {
				closeMailingList();
			});
			
			//New Sign Up...
			$('.mailing-list-submit').click(function() {
				$.post(
					hostname +'site/saveMailingList',
					{
						name  : $('#mailing-list-name').val(),
						email : $('#mailing-list-email').val()
					},
					function(response)
					{
						if (response == "success")
						{
							$('#top-mailing-list-inner').fadeTo(500, 0, function() {
								$(this).css('background', 'url('+ hostname +'/images/mailing-list-complete.gif) no-repeat center 10px').html('&nbsp;').fadeTo(1500, 1, function() {
									closeMailingList();
								});
							});
						}
						else
						{
							alert(response);
						}
					}
				);
			});

		}
		
		function closeMailingList()
		{
			if (badBrowser)
			{
				$('#top-mailing-list').remove();
				$('#wrap').animate({ top : 0 }, 1000, 'easeOutExpo');
			}
			else
			{
				$('body').css({ backgroundPosition : '0px 0px' });
				$('#wrap').animate({ marginTop : 0 }, 1000, 'easeOutExpo', function() { $('#top-mailing-list').remove(); });
			}
		}

	});
	
	/**
	 * 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');							
						}	
						initMediaCentre();
												
					});
				});
			}
		}
		function loadMap(html)
		{
			var imgW    = 720; 
			var imgH    = 350; 

			$('#fullscreen-content')
			.animate({
				'width'  	 : imgW +'px',
				'height' 	 : imgH +'px',
				'left' 		 : (imgW/2)*-1,
				'marginTop'  : ((imgH)/2)*-1
			},200); 
			$('#fullscreen-close').css({ marginTop : -190, left : 350 });
			loadFullScreen(html);
		}
		
		function loadMediaCentre(html)
		{
			//var imgSrc  = $('img', objImg).attr('src').replace('_thumb', '');
			//var imgDesc = $(objImg).next('span').html();
			//var imgDim  = $(objImg).attr('rel').split('x');
			var imgW    = 750; //Number(imgDim[0]);
			var imgH    = 405; //Number(imgDim[1]);

			$('#fullscreen-content')
			.animate({
				'width'  	 : imgW +'px',
				'height' 	 : (imgH+40) +'px',
				'left' 		 : (imgW/2)*-1,
				'marginTop'  : ((imgH+40)/2)*-1
			},200); 
			$('#fullscreen-close').css({ marginTop : -235, left : 365 });
			/*
			$('#fullscreen-close')
			.animate( {
				'left' 		 : (imgW/2)-100,
				'marginTop'  : ((imgH-40)/2)+13
			},200); */

			loadFullScreen(html);
		}
		
		if ( $('#media-centre').length > 0 ) initMediaCentre();
		function initMediaCentre()
		{
			$('.media-items-table tr:first').addClass('media-item-current');
			
			$('.media-items-table tr').click(function() {
				$('.media-items-table tr.media-item-current').removeClass('media-item-current');
				$(this).addClass('media-item-current');
				
				$.get(
					hostname +'mediaItem/'+ this.id,
					function(data)
					{
						var $json = $.evalJSON(data);
						
						// Toggle file download
						if ( $json.objMediaItem.file == "" )
						{
							$('#media-file-download').hide();
						}
						else
						{
							$('#media-file-download').show();
						}	
						
						// Toggle media url download
						if ( $json.media_url == "" || $json.media_url.indexOf('vimeo')  != "-1")
						{
							$('#media-url-download').hide();
						}
						else
						{
							$('#media-url-download').show();
						}
						
						// Toggle video
						if ( $json.objMediaItem.video == "" && $json.audio == "")
						{
							$('.no-video').show();
							$('#media-video').hide();
						}
						else
						{
							$('.no-video').hide();
							$('#media-video').show();
						}			
						
						// Toggle buy link...
						if ( $json.objMediaItem.url == "" )
						{
							$('#media-url').hide();
						}
						else
						{
							$('#media-url').show();
						}	
						
						if ( $json.audio != "" )
						{
							$('#media-video').html($json.audio);
						}
						else
						{
							$('#media-video').html($json.video);
						}
						$('#media-share').attr('share_url', hostname +'media/'+ $json.objMediaItem.id);
						//http://www.facebook.com/sharer.php?u=http%3A%2F%2Fjdesktop.com%2Fclient%2Fcla%2Fdev%2Fmedia%2F6&src=sp
						$('#media-share').attr('href', 'http://www.facebook.com/sharer.php?u='+ encodeURI(hostname +'media/'+ $json.objMediaItem.id) +'&t='+ encodeURI($json.objMediaItem.title));
						
						$('#media-file-download').attr('href', hostname +'download/'+ $json.objMediaItem.id);
						//console.log($json.media_url);
						$('#media-url-download').attr('href', $json.media_url);
						$('#media-description-scroll').html($json.objMediaItem.description);
						
					}					
				);
			});
			
		}
		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 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);
						}
					})
				});
			}
		}
	
	
});
