/* Initialization */
$(function ()
{
	setupAjaxLinks();
	if ($('#splash-intro').length)
	{
		setTimeout("fadeInRandomGridPiece()", 1000); // start the slideshow after 1 second delay
	}
	dtr();
	setupSlideshow();
	setupPartyBuilder();
	setupScrollPane();
});

function setupScrollPane()
{
	if ($('.jscrollpane-off').length) // check for disabled scroll[pane (i.e. party builder)
	{
		return;	
	}
	if ($('#content_area .main').length)
	{
		$('#content_area .main').jScrollPane();
	}
}

function setupPartyBuilder()
{
	$('#questions').data('curIndex', 0);
	
	$('.question .nextQuestion').live('click', function ()
	{
		var lastQuestion = 7;
		var curQ = $(this).parents('.question:first');
		var curIndex = $('#questions').data('curIndex') ? $('#questions').data('curIndex') : 0;
		var nextIndex = curIndex + 1;
		var nextQ = $('#questions .question:eq(' + nextIndex + ')');
		if (nextQ.length)
		{
			curQ.fadeOut().removeClass('curQuestion');
			nextQ.fadeIn().addClass('curQuestion');
			$('#questions').data('curIndex', nextIndex);

			if (nextIndex == lastQuestion)
			{
				$.post('/wp-content/themes/garelick_herbs/party-form.php', $('#party-form').serialize());
			}
		}
		return false;
	});
}

function setupSlideshow()
{
	if($('#menu-slideshow .slide').length > 1)
	{
		$('#menu-slideshow').slideshow({'interval' : 5000});
	}
}

function dtr()
{
	// dynamic text replacement
	$('.main h2').each(function ()
	{
		if ($(this).hasClass('dtr-replaced'))
		{
			return true; // continue	
		}
		var myTitle = $(this).html();
		
		var imgUrl = '/wp-content/themes/garelick_herbs/dtr/dtr.php?text=' + encodeURIComponent(myTitle);
		$(this).addClass('dtr-replaced').html('<img src="' + imgUrl + '" alt="' + myTitle + '" />');
	});
}

/*
 * AJAX Links functionality
 */

/* Captures click events on links with the ajaxLink CSS class, making them use AJAX instead of a normal page load */
function setupAjaxLinks()
{
	// use jQuery's live events to ensure operability with content loaded via AJAX
	$('a.ajaxLink').live('click', function ()
	{
		// prevent reloading of the current page
		if ($(this).parents('li:first').hasClass('current'))
		{
			return false; 
		}
		
		// add the current class to this <li>, and remove it from the old one
		$(this).parents('ul:first').find('li.current').removeClass('current'); // remove current class from old link
		$(this).parents('li:first').addClass('current'); // add current class to this link

		var srcUrl = $(this).attr('href'); // original URL
		var trgUrl = false;
		var isSidebarLink = $(this).parents('#nav:first').length > 0;
		
		// make sure URL is valid, if so continue loading the page via AJAX
		if (srcUrl && srcUrl.length > 3)
		{
			trgUrl = convertUrlToAjax(srcUrl); // "ajaxify" the URL
			loadPageWithAjax(trgUrl, isSidebarLink);
		}
		// prevent normal link behavior (i.e., changing pages)
		return false;
	});
}

/* Load the URL from the headless server and replace the old page content with the new content (with fading transition) */
function loadPageWithAjax(url, isSidebarLink)
{
	// show the loading graphic and fade out the current page content
	ajaxLoader('show');
	var ajaxTarget = $('#ajax-target'); // contains the content area and nav (new content area and nav will be loaded from server)

	// abort any outstanding AJAX requests
	var ajaxHook = ajaxTarget.data('ajaxHook');
	if (ajaxHook)
	{
		ajaxHook.abort();	
	}
	
	// if its a sidebar link only fade the content_area in/out
	if (isSidebarLink)
	{
    ajaxTarget.find('#content_area').animate({'opacity' : 0}, 1500); // fade out
	}
	else
	{
		ajaxTarget.animate({'opacity' : 0}, 1500); // fade out
	}

	// load the new data from the server via AJAX. When its loaded, add it to the page and fade it in
	ajaxHook = $.get(url, function (data) 
	{
		// clear the AJAX hook reference
		ajaxTarget.data('ajaxHook', false);

		// load the content into the ajax-target div
		if (data && data.indexOf('content_area')) // basic check to ensure content is of the right form
		{
			if (ajaxTarget.is(':animated'))
			{
				ajaxTarget.stop();	
			}

			// swap in the new HTML, and fade in
			if (isSidebarLink) // if its a sidebar link, only fade in the content_area (nav is already visible)
			{
				$('#testing').html(data);
        ajaxTarget.html(data).find('#content_area').animate({'opacity' : 1}, 1500); // fade in
			}
			else // fade in both the nav and the content_area
			{
				ajaxTarget.html(data).animate({'opacity' : 1}, 1500); // fade in
			}
			// redo any fancy text replacement
			dtr();
//			$('#menu-slideshow').killInterval();
			setupSlideshow();
			setupScrollPane();
			// clear the loading screen
			ajaxLoader('hide'); 
		}
	});
	// store a hook to this request so we can abort it if the user clicks another link before it finishes loading
	ajaxTarget.data('ajaxHook', ajaxHook);
}

/* Adds the ajax=1 parameter to the URL. Sensitive to URLs with preexisting query string parameters, e.g., ;http://example.com/?page=3332' */
function convertUrlToAjax(srcUrl)
{
	var trgUrl = srcUrl;
	// add '?' if the URL has no query string params, or '&' if there are already query string params and we need to add ours to the end
	trgUrl += (trgUrl.indexOf('?') == -1) ? '?' : '&';
	// add ajax flag
	trgUrl += 'ajax=1';
	return trgUrl;
}

/* Show or hide the 'loading' graphic (usage: pass 'show' or 'hide' as the only parameter) */
function ajaxLoader(showHide)
{
	var loadingDiv = $('#ajaxLoader');
	// create the div if it does not yet exist
	if (showHide == 'show' && !loadingDiv.length)
	{
		loadingDiv = $('<div id="ajaxLoader" style="position:absolute;display:none;"></div>');
		$('#wrapper').append(loadingDiv);
	}
		
	if (showHide == 'show')
	{
		loadingDiv.css({'display' : 'block' })
				  .animate({'opacity' : 1}, 'fast');
	}
	else // hide
	{
		loadingDiv.css({'display' : 'none' })
				  .animate({'opacity' : 0}, 'fast');
	}
}

/*
 * Intro movie
 */

/* Fades in the remaining hidden grid pieces, 1 by 1. When all pieces have been faded in, calls onGridComplete() */
function fadeInRandomGridPiece()
{
	// first, get a random piece
	var myPiece = randomGridPiece();
	if (myPiece && myPiece.length)
	{
		callback = function ()
		{
			if (morePiecesToFade())
			{
				fadeInRandomGridPiece();
			}
			else
			{
				setTimeout( function () { onGridComplete(); }, 3000);
			}
		};
		fadeInGridPiece(myPiece, callback);
	}
}

/* Callback function called when the last grid piece has been faded in */
function onGridComplete()
{
	$('#splash-intro h1').animate({'top': '25px'}, function ()
	{
//		$('#wrapper').addClass('show-bg');
		
		$('#splash-grid').animate({'opacity' : 0}, 'medium', function () // fade out
		{
			$(this).remove();
			$('#splash-content').css({'display' : 'block'}).animate({'opacity' : 1}, 'medium');	// fade in
		});
	});
}

/* Fades in the supplied grid piece, nothing special. Optional callback. */
function fadeInGridPiece(gridPiece, callback)
{
	if (gridPiece)
	{
		gridPiece.addClass('visible');
		gridPiece.css({'opacity' : 0});
		gridPiece.css({'visibility' : 'visible'});
		if (typeof(callback) == 'function')
		{
			gridPiece.animate({'opacity' : 1}, 'medium', callback); // fade in, fire callback when done
		}
		else
		{
			gridPiece.animate({'opacity' : 1}, 'medium'); // fade in, no callback
		}
	}
}

/* Bool: are there any hidden gid pieces? */
function morePiecesToFade()
{
	var hiddenPieces = getHiddenPieces();
	return hiddenPieces.length > 0;
}

/* Returns the jQuery set of hidden grid pieces */
function getHiddenPieces()
{
	var hiddenPieces = false;
	var randPiece = false;
	var randInt = 0;	
	// select a random grid item and fade it in
	hiddenPieces = $('#splash-grid li').filter(function () // remove elements that are already visible
	{
		return !$(this).hasClass('visible');
	});
	return hiddenPieces;
}

/* Select a random gid piece from the set of hidden pieces */
function randomGridPiece()
{
	var hiddenPieces = false;
	var randPiece = false;
	var randInt = 0;	
	// select a random grid item and fade it in
	hiddenPieces = getHiddenPieces();

	if (hiddenPieces.length == 0)
	{
		return false;	
	}
	randInt = 0;
	if (hiddenPieces.length > 1)
	{
		randInt = Math.round(Math.random() * hiddenPieces.length) - 1;
	}
	randPiece = $(hiddenPieces.get(randInt));
	return randPiece;
}

