// JavaScript Document

var allItems = new Array();
var displayItems = new Array();
var title = "";
var description = "";

var buzzFeedsBaseXmlUrl = "/eng/buzz_feeds/";

var numDisplay = 6;

function parseText(text){
	// Find all URLs and convert them
	var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
	text = text.replace(exp,"<a href='$1' target='_blank'>$1</a>"); 
	
	// Find all # tags and convert them
	var exp = /(#[-A-Z0-9+&%?!]*)/gi;
	text = text.replace(exp,"<a href='http://twitter.com/search?q=$1' target='_blank'>$1</a>"); 

	// replace the # in the URL with %23, twitter doesn't like the hash tag. How ironic...
	var exp = /(\?q=#)/gi;
	text = text.replace(exp,"?q=%23");
	
	return text;
}

function parseXML(xmlfile,container,headerContainer){
	i = 0;

	$.ajax({
		type: "GET", url: buzzFeedsBaseXmlUrl + xmlfile, dataType: "xml",
		success: function(xml) {
			title = $(xml).find('title').text();
			description = $(xml).find('description').text();

			$(xml).find('item').each(function(){
				i++;
				var newRow = $("<li>");
				var newSpan = $("<p>");
				/*Get profile information */
				var type = $(this).attr('type');
				var content = parseText($(this).text());
				
				newSpan.addClass(type);
				newSpan.append(content);
				newRow.append(newSpan)
				allItems.push(newRow);
			});
			
			/* Add new contact to table */
			selectItems();
			showItems(container, headerContainer);
		}
	});

}

/* Generates a random set of unique numbers */
function selectItems(){
	if(numDisplay > allItems.length) //Check if numDisplay is less than total number of items
		numDisplay = allItems.length-2
	if(numDisplay%2 == 0)	//Check if numDisplay is odd
		numDisplay++;
	var r;
	
	if (numDisplay < allItems.length && numDisplay < 6) {
		numDisplay = allItems.length;
	}
	
	while( displayItems.length < numDisplay ) {
		r = Math.round(Math.random()*(allItems.length-1));
		if($.inArray(r,displayItems) == -1) //Make sure it is unique
			displayItems.push(r);
	}
}

/* Based on the random set it displays those items */
function showItems(container, headerContainer){
	newList = $("<ul>");
	var nextRow;
	
	for(i=0; i<displayItems.length; i++){
	  nextRow = allItems[displayItems[i]];
	  
	  if(i % 2 != 0) // Make even rows display with a grey background
		 nextRow.addClass('grey');
	  
	  newList.append(nextRow);
	}
	  
	container.html(newList);
	
	if (headerContainer) {
		headerContainer.html("<div class='subtitle replace'>" + title + "</div><div class='description'>" + description + "</div>");
	}
}
