﻿$(function()
{
    if (typeof($quoteChangeInterval) == 'undefined')
    {
        var $quoteChangeInterval = 7000;
    }

 	// Get a handle on all the relevant elements
 	var $list = $('#quotesPaneWrapper ul');
 	var $items = $('#quotesPaneWrapper li');
 
 	// Work out how many list items there are
 	var $itemCount = $items.size();
 	
 	// Apply the IE6 clearType fix to prevent horrible text rendering
 	clearTypeFix($items);
 	
 	// Hide all but the first list item initially
 	$items.animate(
	{
		opacity: 0
	}, 0);
	$($items[0]).animate(
	{
		opacity: 1
	}, 0);
 	
 	// Set up an iterator with starting value 1 to represent the second
 	// element in a zero-based array
    var $i = 1;
    
    // This uses the jQuery Timers plugin to fire off a function every 7 seconds
	$list.everyTime($quoteChangeInterval, function()
	{
	 	// If iterator is zero...
	 	if ($i == 0)
	 	{
	 	 	// Fade out the last list item
			$($items[$itemCount]).animate(
			{
				opacity: 0
			}, 1000);
			
			// Fade in the first list item
			$($items[0]).animate(
			{
				opacity: 1
			}, 1000);
			
			// Increment the iterator
			$i++;
		}
		// If iterator is not zero and is less than total number of
		// list items
	 	else if ($i < $itemCount)
	 	{
	 	 	// Fade out previous list item
			$($items[$i - 1]).animate(
			{ 
				opacity: 0
			}, 1000);
			
			// Fade in current list item
			$($items[$i]).animate(
			{ 
				opacity: 1
			}, 1000);
			
			// Increment the iterator
			$i++;
		}
		// If iterator is equal to total number of list items
		else
		{
		 	// Fade out previous list item
			$($items[$i - 1]).animate(
			{ 
				opacity: 0
			}, 1000);
			
			// Fade in first list item
			$($items[0]).animate(
			{ 
				opacity: 1
			}, 1000);
			
			// Reset the iterator
			$i = 1;
		}
	}, 0); // The 0 here tells the ongoing timer to loop indefinitely

    // fix clearType problems in ie6 by setting an explicit bg color
    // (otherwise text looks horrible during a fade transition)
    function clearTypeFix($textElement)
    {
	    function hex(s)
	    {
		    s = parseInt(s).toString(16);
		    return s.length < 2 ? '0'+s : s;
	    };
	    function getBg(e)
	    {
		    for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode)
		    {
			    var v = $.css(e,'background-color');
			    if (v.indexOf('rgb') >= 0 )
			    {
				    var rgb = v.match(/\d+/g);
				    return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
			    }
			    if (v && v != 'transparent')
				    return v;
		    }
		    return '#ffffff';
	    };
	    $textElement.each(function()
	    {
	        $(this).css('background-color', getBg(this));
	    });
    };

});