(function() {
    var updateQuote, scheduleUpdate, changeQuote, updateDelay=0;

    if(typeof String.prototype.supplant !== 'function') {
	String.prototype.supplant = function(o) {
	    return this.replace (/{([^{}]*)}/g, function(a, b) {
		var v = o[b];
		return typeof v === 'string' ? v : a;
	    });
	};
    }
    
    updateQuote = function() {
	$('#randomquote').fadeOut(500, changeQuote);
    };

    scheduleUpdate = function() {
	window.setTimeout(updateQuote, updateDelay);
    };

    changeQuote = function() {
	var template = '<a class="nolinkstyle" href="/quotes.html"><span id="randomquotetext">{text}</span> <span id="randomquotesource">{source}<span></a>';
	var quote = FREEDOMLETTER.quotes.atRandom();
	this.innerHTML = template.supplant(quote);
	updateDelay = 5000 + quote.text.split(' ').length*500;
	$(this).fadeIn(500, scheduleUpdate);
    };

    $(document).ready(function() {
	var element;
	FREEDOMLETTER.quotes.atRandom = function() {
	    return this[Math.floor(Math.random() * this.length)];
	};

	element = $('#randomquote');
	if(element) {
	    element.hide(0, changeQuote);
	}
    });
	
}())
