jQuery.fn.rainbowText = function(colors) {
	$(this).each(function() {
		var text = $(this).text();
		var output = '';
		for(i=0; i < text.length; i++)
		{
			var color_div = (colors.length / text.length);
			var color_index = Math.ceil(color_div * (i + 1)) - 1;
			if(color_index >= colors.length && color_index > 0)
			{
				color_index = colors.length -1;
			}
			output += "<font color='#" + colors[color_index] + "'>" + text.substring(i,i+1) + "</font>";
		}
		$(this).html(output, colors);
	});
};


jQuery.fn.rainbow = function(colors) {
	$(this).each(function() {
		var text_i = 0;
		var text_length = $(this).text().length;
		$(this).rainbowChildren(colors, text_i, text_length);
	});
}


jQuery.fn.rainbowChildren = function(colors, text_i, text_length) {
	var color_div = (colors.length / text_length);
	$(this).contents().each(function() {
		if($(this).attr('nodeType') != undefined && this.nodeType !== 1)
		{
			// 'this' is not a text node
			text_i += $(this).text().length;
			$(this).rainbowChildren(colors, text_i, text_length);
		}
		else
		//else if($(this).attr('nodeType') == undefined || $(this).attr('nodeType') == 3)
		{
			// 'this' is assumed to be a text node
			var text;
			var container;
			if($(this).attr('nodeType') != undefined)
			{
				// nodeType is valid, so we'll process 'this' directly
				text = $(this).text();
				container = $(this);
			}
			else
			{
				// nodeType is undefined
				// text must be contained in order to be changed, so wrap a SPAN around 'this'
				// the contents of the SPAN may then be changed
				container = $(this).wrap("<span></span>").parent();
				text = $(container).text();
			}

			var new_text = '';
			for(i=0; i < text.length; i++)
			{
				var color_index = Math.ceil(color_div * (text_i + 1)) - 1;
				if(color_index >= colors.length && color_index > 0)
				{
					color_index = colors.length -1;
				}
				new_text += "<font color='#" + colors[color_index] + "'>" + text.substring(i,i+1) + "</font>";
				//new_text += "<font style='background-color: #" + colors[color_index] + "'>" + text.substring(i,i+1) + "</font>"; // change background, rather than text color
				text_i++;
			}
			container.html(new_text);
		}
	});
}


