//pre-load images


function NewsItem(quote,link,linkText,source,location){
 this.index = Math.random();
 this.quote = quote;
 this.link = link;
 this.linkText = linkText;
 this.write = writeNews;
 this.source = source;
 this.location = location;
}


function writeNews(){
	return testimonialsTemplate.applyTemplate(this);
}

var newsArray = new Array();
var nIndex = 0;
var timerID = null;

String.prototype.applyTemplate = function(o){ 
	return this.replace(/{([^{}]*)}/g,
	    function (a, b) {
	        var r = o[b];
	        return (typeof r === 'string') ? r : a; 
	    }
	);
}; 

var testimonialsTemplate = 
    '{quote}<br /><strong>{source} - {location} </strong>'
	+ '<br /><p>&bull;&bull;&bull;</p><a href="{link}">{linkText}</a>';

function getNodeValue(context,nodeName){
    var val;
    try{
	    val = context.getElementsByTagName(nodeName)[0].firstChild.nodeValue;
	}catch(e){
	    val = '';
	}
	return val; 
}

jQuery(document).ready(function(){
  jQuery.get("testimonials/testimonials.xml", function(data){
   var entries = jQuery('entry',data.documentElement).each(
       function(){
    	    newsArray.push(
    	    	new NewsItem( 
    	    		getNodeValue(this,'quote'),
    	    		getNodeValue(this,'link'),
    	    		getNodeValue(this,'linkText'),
    	    		getNodeValue(this,'source'),
    	    		getNodeValue(this,'location')
    	   		));
        });
    newsArray.sort(function(a, b){
       var ret = 0;
       if(a.index > b.index){
           ret = 1;
       }else if(a.index < b.index){
           ret = -1;
       }
       return ret;
    });
    
    jQuery('#stories').mouseenter(function(){
		pauseNews();
	}).mouseleave(function(){
		playNews();
	})
	
    playNews();
  
  });
});


function rotateNews(){
	var len = newsArray.length;
	if(nIndex >= len)
		nIndex = 0;

    jQuery('#stories').fadeOut(1000,function(){
        this.innerHTML = newsArray[nIndex].write();
        nIndex++;
        jQuery('#stories').fadeIn(1000, function(){ 
	    	timerID = setTimeout('rotateNews()',6000);
	    	state = 'started';
		}); 
    });   
}

function pauseNews() {
    if (timerID != null) {
	    clearTimeout(timerID);
		timerID = null;
	}
    jQuery('#stories').stop().show().fadeTo('fast',0.99);
}

function playNews() {
	if (timerID == null) {
		timerID = setTimeout('rotateNews()', 1000);
	}
}
//function playNews() {
//    nIndex = Math.random();
//    nIndex*=newsArray.length;
//    nIndex=Math.floor(nIndex);
// if (timerID == null) {
//  timerID = setTimeout('rotateNews()', 1000);
// }
//}
