$(document).ready(function()
{

	var quotes = new Array();

	if(typeof(window.quotes_file) == "undefined")
		window.quotes_file = "quotes.xml";

	// Get the quotes xml file
	$.ajax({
		type: "get",
		url: "/Websites/luz/templates/LightCMS/"+quotes_file,
		dataType: "xml",
		success: function(xml) {

			var quotesArray = new Array();

			$(xml).find("Quote").each(function(i) {
				quoteObject = new Object();
				quoteObject.contents = $(this).find("Contents").text();
				quoteObject.author = $(this).find("Author").text();
				quoteObject.title = $(this).find("Title").text();
				quotesArray.push(quoteObject);
			});

			quotes = quotesArray;
			injectQuotes();

		}
	});

	function injectQuotes() {

		// Trim leading/trailing whitespace from quotes
		for(var i = 0, length=quotes.length; i < length; ++i) {
			quotes[i].contents = quotes[i].contents.replace(/^\s*/, "").replace(/\s*$/, "");
			quotes[i].author = quotes[i].author.replace(/^\s*/, "").replace(/\s*$/, "");
			quotes[i].title = quotes[i].title.replace(/^\s*/, "").replace(/\s*$/, "");
		}

		// Randomize order of quotes
		quotes = $.shuffle(quotes);

		// If there is a #quotes_rotator on the page, run the rotator function
		if($("#quotes_rotator").length)
			quoteRotator();

		// If there is a #quotes_grid on the page, call the grid function
		if($("#quotes_grid").length)
			quoteGrid();
	}

	function quoteRotator() {

		// Quotes Rotator Preferences
		var rotatorTimeout = 7500;	// Rotator interval
		var rotatorAnimationSpeed = 500;		// Rotator animation speed

		// index
		var i = 0;

		// Insert Back/Forward Buttons and attach click handlers
		$("#quotes_rotator")
			.before("<button class=\"quotes_rotator-button\" id=\"quotes_rotator-next\">Next Quote</button>")
			.before("<button class=\"quotes_rotator-button\" id=\"quotes_rotator-previous\">Previous Quote</button>");
		$("#quotes_rotator-previous").click(previousQuote);
		$("#quotes_rotator-next").click(nextQuote);
		$("#quotes_rotator-next").before("<a href=\"/buzz\" class=\"quotes_rotator-button\" id=\"quotes_rotator-more\">More</a>");

		// Show the first quote
		replaceQuote();

		// Start cycling quotes
		activeRotator = startCycleQuotes();

		// Inserts content of the cued quote (determined by i) into the rotator div
		function replaceQuote() {

			// Set quote content variables
			var quoteContents = quotes[i].contents;
			var quoteAuthor = quotes[i].author;
			var quoteTitle = quotes[i].title;

			// Fade out quote rotator
			$("#quotes_rotator").fadeOut(rotatorAnimationSpeed, function() {

				// Replace the rotator container's content with the new quote
				$("#quotes_rotator").html(""
				+ "<blockquote class=\"quote_content\"><p>&#8220;"+quoteContents+"&#8221;</p></blockquote>"
				+ "<span class=\"quote_author\">"+quoteAuthor+"</span>"
				);
				// If the author has a title, append it to the author name
				if(quoteTitle != "") {
					$("#quotes_rotator .quote_author").append("<br />"+quoteTitle);
				}

				// Fade in quote rotator
				$("#quotes_rotator").fadeIn(rotatorAnimationSpeed);

			});

		}

		// Replaces current quote with the previous quote in the array
		function previousQuote() {

			// Decrement quote index
			i--;

			// If index is less than 0, set index to last quote in the array
			if(i < 0)
				i = quotes.length-1;

			// Stop quotes from cycling - we're going to start again in a few lines
			stopCycleQuotes(activeRotator);

			// Switch out quote content
			replaceQuote();

			// Start cycling quotes again
			activeRotator = startCycleQuotes();

			// Return false so the button doesn't submit the .NET form
			return false;
		}

		// Replaces current quote with the next quote in the array
		function nextQuote() {

			// Increment quote index
			i++;

			// If index is greater than the number of quotes in our array, set index to 0
			if(i > quotes.length-1)
				i = 0;

			// Stop quotes from cycling - we're going to start again in a few lines
			stopCycleQuotes(activeRotator);

			// Switch out quote content
			replaceQuote();

			// Start cycling quotes again
			activeRotator = startCycleQuotes();

			// Return false so the button doesn't submit the .NET form
			return false;
		}

		// Cycles quotes at a rate set in rotatorTimeout preference variable
		function startCycleQuotes() {

			// Returns the interval so it can be passed to a clearInterval() to stop the cycle
			return setInterval(function() {
				// If index is equal to or greater than the number of quotes in our array, reset to 0...
				if(i >= quotes.length-1)
					i = 0;
				// ...otherwise, increment
				else
					i++;
				// Switch out quote content
				replaceQuote();
			}, rotatorTimeout);

		}

		// Stops the quote cycling
		function stopCycleQuotes(rotatorInterval) {
			// Clear the quote cycle interval
			clearInterval(rotatorInterval);
		}

	}

	function quoteGrid() {

		// Quote Grid Preferences
		var gridNumberOfQuotes = 12;	// Max number of quotes to show
		var gridNumberOfColumns = 12;	// Max number of grid columns to show
		var doubleWidthCount = 4;		// Max number of doubleWidth quote boxes
		var doubleHeightCount = 0;		// Max number of doubleHeight quote boxes

		// Delete placeholder text
		$("#quotes_grid").html("");

		// Make sure we aren't trying to use more quotes than are in the array
		if(quotes.length < gridNumberOfQuotes) {
			gridNumberOfQuotes = quotes.length-1;
		}

		// Fill the grid with the specified number of boxes
		var columnsInRow = 0;
		var addedColumns = 0;
		var i = 0;
		while(addedColumns < gridNumberOfColumns) {
			i++;
			gridNumberOfQuotes = i;

			var blockStyle = randomFromTo(0, 10);
			if(blockStyle <= 5) {
				if(randomFromTo(0, 5) == 1) {
					//blockStyle += " spacer ";
				}
				columnsInRow++;
				addedColumns++;
			}
			else if(blockStyle <= 10 && doubleWidthCount > 0 && columnsInRow < 3) {
				blockStyle = "doubleWidth";
				doubleWidthCount--;
				columnsInRow = columnsInRow + 2;
				addedColumns = addedColumns + 2;
			}
			else if(blockStyle <= 10 && doubleHeightCount > 0) {
				blockStyle = "doubleHeight";
				doubleHeightCount--;
				columnsInRow++;
				addedColumns++;
			} else {
				columnsInRow++;
				addedColumns++;
			}

			$("#quotes_grid").append(""
			+ "<div class=\"grid_3 quotes_grid-quote block"+i+" "+blockStyle+"\">"
			+ "	<blockquote>"//+i+"/"+columnsInRow+"/"+addedColumns
			+ "		<p></p>"
			+ "		<p class=\"cite\"></p>"
			+ "	</blockquote>"
			+ "</div>"
			);
			if(columnsInRow > 3) { columnsInRow = 0; }

			insertQuote(0, i, true);
			$("body.buzz div.quotes_grid-quote.block"+i+" blockquote").hide();
		}

		setTimeout(function() {
			$("body.buzz div.quotes_grid-quote blockquote").fadeIn(500);
			insertQuote();
		}, 300);

//		$("div.quotes_grid-quote:nth-child(4n+5)").addClass("every5th");

		function insertQuote(i, quoteBox, noAnimation, quote) {

		    //Default Values
			while(typeof(quotes[quote]) == "undefined") {
		    	quote = getRandomQuote();
			}
		    quoteBox = typeof(quoteBox) == "undefined" ? getRandomBox() : quoteBox;
			var quoteBoxOb = $("div.block"+quoteBox);

			// Set quote content
			var quoteContents = quotes[quote].contents;
			var quoteAuthor = quotes[quote].author;
			var quoteTitle = quotes[quote].title;

			// Set a class for the quote based on its length. This allows us to style short quotes differently from longer ones.
			var nextTimeout = 0;
			if(quoteContents.length <= 100) {
				nextTimeout = 4000;
				quoteBoxOb.removeClass("medium_quote");
				quoteBoxOb.removeClass("long_quote");
				quoteBoxOb.addClass("short_quote");
			}
			else if(quoteContents.length >= 100 && quoteContents.length < 150) {
				nextTimeout = 6000;
				quoteBoxOb.removeClass("short_quote");
				quoteBoxOb.removeClass("long_quote");
				quoteBoxOb.addClass("medium_quote");
			}
			else if(quoteContents.length >= 150) {
				nextTimeout = 8000;
				quoteBoxOb.removeClass("short_quote");
				quoteBoxOb.removeClass("medium_quote");
				quoteBoxOb.addClass("long_quote");
			}
			nextTimeout = 2500;

			// Change the box's id attr
			quoteBoxOb.attr("id", "quote_"+quote);

			if(noAnimation) {
				quoteBoxOb.find("blockquote p:first-child").html("&ldquo;"+quoteContents+"&rdquo;");
				quoteBoxOb.find("blockquote p:last-child").html("&ndash; "+quoteAuthor+"<br />"+quoteTitle);
				quoteBoxOb.addClass("filled");
				quoteBoxOb.addClass("faded");
			}
			else {
				quoteBoxOb.find("blockquote").fadeOut(500, function() {
/*					var goToBlank = randomFromTo(1,10);
					if(goToBlank < 8 && $("div.filled").length > 7) {
						quoteBoxOb.removeClass("filled");
						quoteBoxOb.find("p:first-child").html("");
						quoteBoxOb.find("p:last-child").html("");
						clearTimeout(window.quotesRotatorTimeout);
						insertQuote();
					} else {*/
						quoteBoxOb.addClass("filled");
						quoteBoxOb.find("p:first-child").html("&ldquo;"+quoteContents+"&rdquo;");
						quoteBoxOb.find("p:last-child").html("&ndash; "+quoteAuthor+"<br />"+quoteTitle);
						window.quotesRotatorTimeout = setTimeout(insertQuote, nextTimeout);
					//}
					quoteBoxOb.removeClass("faded").addClass("latest");
					setTimeout(function() {
							quoteBoxOb.find("blockquote").fadeIn(500);
						}, 400);
					setTimeout(function() {
							quoteBoxOb.removeClass("latest").addClass("faded");
						}, nextTimeout*3);
				});
			}

			function getRandomQuote() {
				do {
					var quote = randomFromTo(0,quotes.length);
				}
				while($("div#quote_"+quote).length > 0);
				return quote;
			}
			function getRandomBox() {
				do {
					var quoteBox = randomFromTo(1,gridNumberOfQuotes);
				}
				while($("div.block"+quoteBox+".filled").length > 0 && ($("div.filled").length < gridNumberOfQuotes || $("div.block"+quoteBox+".latest").length > 0));
				return quoteBox;
			}

		}

		function randomFromTo(from, to){
			return Math.floor(Math.random() * (to - from + 1) + from);
		}

	}

});

/*
 * jQuery shuffle
 *
 * Copyright (c) 2008 Ca-Phun Ung <caphun at yelotofu dot com>
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://yelotofu.com/labs/jquery/snippets/shuffle/
 *
 * Shuffles an array or the children of a element container.
 * This uses the Fisher-Yates shuffle algorithm <http://jsfromhell.com/array/shuffle [v1.0]>
 */
 
(function($){

	$.fn.shuffle = function() {
		return this.each(function(){
			var items = $(this).children().clone(true);
			return (items.length) ? $(this).html($.shuffle(items)) : this;
		});
	}
	
	$.shuffle = function(arr) {
		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	}
	
})(jQuery);

// FadeInSequence Plugin
(function($) {
$.fn.fadeInSequence = function(fadeInTime, timeBetween)
{
    //Default Values
    timeBetween = typeof(timeBetween) == 'undefined' ? 0 : timeBetween;
     fadeInTime = typeof(fadeInTime) == 'undefined' ? 500 : fadeInTime;
 
    //The amount of remaining time until the animation is complete.
    //Initially set to the value of the entire animation duration.
    var remainingTime = $(this).size() * (fadeInTime+timeBetween);
 
    var i=0; //Counter
    return $(this).each(function()
    {
        //Wait until previous element has finished fading and timeBetween has elapsed
        $(this).delay(i++*(fadeInTime+timeBetween));
 
        //Decrement remainingTime
        remainingTime -= (fadeInTime+timeBetween);
 
        if($(this).css('display') == 'none')
        {
            $(this).fadeIn(fadeInTime);
        }
        else //If hidden by other means such as opacity: 0
        {
            $(this).animate({'opacity' : 1}, fadeInTime);
        }
 
        //Delay until the animation is over to fill up the queue.
        $(this).delay(remainingTime+timeBetween);
 
    });
 
};
 
})(jQuery);


