/**
 * @author	Jonathan Cochran <jono.cochran@gmail.com>
 *			fabriccreative.com, COPYRIGHT 2009
 * --------------------------------------------------------- */

$(document).ready(function() {

  // added by shawn for wordpress blog links
  $("#blog-content a").attr('class','blog-link');

/**
 * REPLACE LINKS TO 'javascript:;'
 * won't replace attributes if:
 * 1) /site/ is present in the URI
 * 2) <a tag contains rel="external"
 * 3) <a tag contains target="_blank"
 * --------------------------------------------------------- */
	var docLoc = window.location.href;
	
	//is it a search engine? 
	var isSe = docLoc.indexOf('/site/') != "-1" ? true : false;
	function removeLinks()
	{
		$('a').each(function(){
			if (isSe) {
				resetNav();
				return false; //is not a search engine...
			}
			var url = $(this).attr('href');
			var rel = $(this).attr('rel').indexOf('external');
			var ext = $(this).attr('target').indexOf('_blank');

      // added by shawn for wordpress blog links
			var blog = $(this).attr('class').indexOf('blog-link');

			if (url != "http://www.fabriccreative.com" && url != docLoc && rel != "0" && ext != "0" && blog != "0")
			{	
				$(this).attr('href', 'javascript:;');
			}
		});
	}
//	removeLinks();
		
/**
 * BROWSER FIXES (IE5/6)
 * --------------------------------------------------------- */
	var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	
/**
 * FLASH PLAYER
 */
	params = {};
 	params.wmode = 'Transparent';
 	params.scale = 'noscale';
	swfobject.embedSWF("player.swf", "mp3player", "300", "35", "9.0.0", "expressInstall.swf", '', params);


	
/**
 * RESIZE DOCUMENT
 * --------------------------------------------------------- */	
	$(window).resize(function() {
		resizeBackground();
	});
	
		
/**
 * RESIZABLE BACKGROUND IMAGE (WHEN DOC > 1920x1200)
 * --------------------------------------------------------- */
	var objDocBg = $('#background-image img'); //Background image obj
	objDocBg.hide(); //don't need show this unless the browser is size > 1920x1200;
	function resizeBackground()
	{
		//Gather browser and current image size
		var imagewidth = objDocBg.width();
		var imageheight = objDocBg.height();
		var browserwidth = $(window).width();
		var browserheight = $(window).height();
		var offset;
		
		//Only proceed, if the dimensions are greater than the image...
		if ((browserwidth > 1920 || browserheight > 1200) && ! badBrowser ) //don't use this if IE5/6
		{
			//Show the background image
			objDocBg.show();
			
			//Define image ratio
			var ratio = 1200 / 1920;

			//Resize image to proper ratio
			if ((browserheight/browserwidth) > ratio){
			    objDocBg.height(browserheight);
			    objDocBg.width(browserheight / ratio);
			    objDocBg.children().height(browserheight);
			    objDocBg.children().width(browserheight / ratio);
			} else {
			    objDocBg.width(browserwidth);
			    objDocBg.height(browserwidth * ratio);
			    objDocBg.children().width(browserwidth);
			    objDocBg.children().height(browserwidth * ratio);
			}
	
			//vertical center
			objDocBg.children().css('left', (browserwidth - objDocBg.width())/2);
			objDocBg.children().css('top', (browserheight - objDocBg.height())/2);
		
		}
		else 
		{
			objDocBg.hide();
		}
		
	}
	resizeBackground();
	
/**
 * TOP NAVIGATION
 * @breif	The object objNavHandle is overlayen over top of 
 *			the <a> links when you mouse over which disables
 *			the ability to click the actual links, so for a
 * 			work around, I added the page class name to the 
 *			rel attribute of the objNavHandle. When the click 
 * 			event is fired, it will grab that rel attribute  
 *			and load the corresponding page. 
 * --------------------------------------------------------- */
	//objNavHandle is the mouse over div
	var objNavHandle  = $('.nav-bg');
	var strLastNav; //last clicked nav links...
	objNavHandle.hide();
		
	$('#navigation a')
		.mouseover(function() {
			var objNav = $(this);
			//Disable if the logo...
			if (objNav.hasClass('logo')) {
				return false;
			}		
			objNavHandle.show();
			
			//Page to load (basd on class)
			var strPage = objNav.attr('class').split(' ')[0];
			strLastNav  = strPage;
			strPage		= strPage.replace('nav-', '');
			
			//Figure out where to place the handle
			//based on the background image offset
			var iW     = objNav.width();
			var arBg   = objNav.backgroundPosition().split(' '); 
			var iBgX   = arBg[0].replace('px', '');
			var iMarginL  = Number(iBgX.replace('-', ''))+182;
			iBgX = Number(iBgX)+8;
			
			//Far right (store) link needs some extra width
			if (objNav.hasClass('nav-store')) iW = iW+13;

			//Animate the handle background image...
			objNavHandle
				.stop()
				.attr('rel', strPage) //updates the rel to tell page
				.css( { 'background-color' : '#fff' })
				.animate( { 'marginLeft' : iMarginL +'px', 'width' : iW, 'backgroundPosition' : '('+ iBgX +' -48px)' }, 200, 'expoinout')
		});

  // added by shawn to override activity on the blog
	objNavHandle.click(function(){
    page = objNavHandle.attr('rel');

		//remove clones..
		resetNav();
		
		var arBg   = objNavHandle.backgroundPosition().split(' '); 
		var strBgX = arBg[0];
		objNavHandle
			.css( { 'background-color' : '#cdd8a1' })
			.animate( { 'backgroundPosition' : '('+ strBgX +' -84px)' }, 100);

			if (page == "worshipper" || page == "blog" || page == "store")
			{
        var href = $('.nav-'+page).attr('href');
        window.open(href);
				return false;
			} else {
        window.location.href = "http://www.unhinderedworship.com/site/page/" + page;
      }
  });
		
	//Updates the background image to green if clicked...
//	objNavHandle
//		.click(function() {
//			
//			//remove clones..
//			resetNav();
//			
//			var arBg   = objNavHandle.backgroundPosition().split(' '); 
//			var strBgX = arBg[0];
//			objNavHandle
//				.css( { 'background-color' : '#cdd8a1' })
//				.animate( { 'backgroundPosition' : '('+ strBgX +' -84px)' }, 100);
//				
//			//clone the handle..
//			var objClone = objNavHandle.clone(); 
//			objClone
//				.addClass('nav-clone')
//				.css( { 'background-color' : '#cdd8a1', 'background-position' : strBgX +' -84px' });
//			objNavHandle.before(objClone);
//			page = objNavHandle.attr('rel');
//			if (page == "worshipper" || page == "blog" || page == "store")
//			{
//				window.location.href = $('.nav-'+page).attr('href');
//				return false;
//			}
//			loadContent(page); //ajax load page
//		})
//		.mouseout(function() {
//			objNavHandle.hide();
//		})
		
	function resetNav()
	{
		$('.nav-clone').remove();
	}		
		
/**
 * AJAX LOAD CONTENT
 * --------------------------------------------------------- */
	function loadContent(page, json)
	{
		var objContent = $('#content');
		objContent.fadeTo(200, 0, function() {
			$.post(
				hostname +'site/' + page,
				{
					json : $.toJSON(json)
				},
				function(html)
				{
					objContent
						.html(html)
						.fadeTo(500, 1, function() {
							eval(page)(name); 
							removeLinks();
						});
					
				}
			);
		});
	}		

/**
 * CALLBACKS (FROM AJAX)
 * --------------------------------------------------------- */	
	function about()	
	{ 
	}
	function blog()
	{
	}
	function campaign() 
	{ 
	}
	function contact()
	{
	}
	function fans()
	{
		//Fan Photos
		$('.photo-item a').click(function() {
			
			loadFullScreenImage(this);
			objImagesParent = $('#fan-photos');
		});
		
		//Fan Videos
		$('.video-item a').click(function() {
			videoUrl  = $(this).attr('rel');
			videoDesc = $(this).next('span').html(); 
			$.get(
				hostname +'site/getVideoCode/'+ videoUrl,
				{ },
				function(html) 
				{
					html += '<div class="fullscreen-video-desc">'+ videoDesc +'</div>';
					$('#fullscreen-content').addClass('fullscreen-video');
					$('#fullscreen-close').addClass('fullscreen-video-close');
					loadFullScreen('<div id="fullscreen-video">'+ html +'</div>');
				}
			);
		});
	}
	function home()		
	{ 
		arWidgetItems = $('.widget'); //array of widget objects
		loadWidgets(0);
		
		//Homepage banner - orient = vertical or horizontal
		$('#banner ul').slideImages('horizontal', 960, 285, 200, 'expoinout', 'timer=5000');
		
		//News links
		$('.widget-news a').click(function() {
			resetNav();
			json = { id : this.id }
			loadContent('news', json);
		});
		
		//Tour links
		$('.widget-tour a').click(function() {
			resetNav();
			json = { id : this.id  }
			loadContent('tour', json);
		});
		
		//Campaign, Blog, Fan Uploads, Album Widgets...
		$('a', '.widget-campaign, .widget-worshipper, .widget-album, .widget-fans').click(function() {
			var objParent = $(this).parent('div');
			if (objParent.hasClass('wigdet-campaign'))
			{
				loadContent('campaign', { })
			}
			//Be campaign
			if (objParent.hasClass('widget-campaign'))
			{
				loadContent('campaign', { })
			}
			//Fan uploads...
			if (objParent.hasClass('widget-fans'))
			{
				loadContent('fans', { })
			}
		});
	}	
	home(); //Default page to load
	
	function news()
	{
		//News links
		$('#news-headlines a').click(function() {
			json = { id : this.id }
			loadContent('news', json);
		});
	}
	initPage('news');
	
	function resources()
	{	
		$('.photo-item a').click(function() {
			
			loadFullScreenImage(this);
			objImagesParent = $('#resources-photos');
		});
	}
	initPage('resources');

	function tour()		
	{ 
		$('.tour-dates tr')
			.mouseover(function() {
				if ( $(this).hasClass('tour-heading') ) return false;
				$('td', $(this)).css({'backgroundColor' : '#1e1f19', 'color' : 'white', 'border-top' : ' 1px dashed white'});
			})
			.mouseout(function() {				
				$('td', $(this)).animate({ 'backgroundColor' : '#000000', 'color' : '#cdd8a1', 'border-top' : ' 1px dashed #cdd8a1'}, 500);
			})
			.click(function() {
				html = $('.tour-info', $(this)).html();
				loadFullScreen('<div class="tour-info">'+html+'</div>');
			});
	}
	initPage('tour');
	
	function videos()
	{		
		$('.video-item a').click(function() {
			videoUrl  = $(this).attr('rel');
			videoDesc = $(this).next('span').html(); 
			$.get(
				hostname +'site/getVideoCode/'+ videoUrl,
				{ },
				function(html) 
				{
					html += '<div class="fullscreen-video-desc">'+ videoDesc +'</div>';
					$('#fullscreen-content').addClass('fullscreen-video');
					$('#fullscreen-close').addClass('fullscreen-video-close');
					loadFullScreen('<div id="fullscreen-video">'+ html +'</div>');
				}
			);
		});
	}
	initPage('videos');
	function worshipper() 
	{
		
	}
	
/**
 * LOADS HOMEPAGE WIDGETS
 * --------------------------------------------------------- */
	
	//load in home items
	var iWidget = 0; //which item we are loading in
	var arWidgetItems; // = $('.widget'); //array of widget objects
	function loadWidgets(iWidget)
	{
		var objItem 	 = $(arWidgetItems[iWidget]);
		
		//exit... if all items are loaded
		if (iWidget == 6 || !objItem) 
		{
			return false;
		}
		 
		//fadeIn to white
		objItem.fadeTo(200, 1, function() { 
			
			//load in next item...
			++iWidget;
			loadWidgets(iWidget);
		});
	}
	
/**
 * RE-INITIATE CALLBACK IN CASE SE LOADS PAGE
 * --------------------------------------------------------- */
	function initPage(page)
	{
		if (isSe && docLoc.indexOf('/'+ page) != "-1")
		{
			eval(page)(name);
		}
	}
	

/**
 * 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();
				});
			});
		}
	}
	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);
					}
				})
			});
		}
	}

});
