
var tableTemplate = jQuery.template('<div id="tablecontainer"><table><thead><tr><td colspan="4" class="titlerow"><img src="/assets/deliveryboard/i/staff.gif" width="37" height="45" alt=""><h1>Your donations at work:</h1><h2>Medical and Humanitarian Aid Shipments</h2></td></tr><tr class="headingrow"><th scope="col">Date</th><th scope="col">Destination</th><th scope="col">Transport</th><th scope="col">Value</th></tr></thead><tbody></tbody></table></div><div id="footer"><ul class="selector"><li><a href="#" class="current">1</a></li><li><a href="#">2</a></li><li><a href="#">3</a></li></ul>Click on the country or state for more information about the shipment.</div><br clear="all" />');
var rowTemplate = jQuery.template('<tr id="${num}" class="${even_or_odd}"><td>${date}</td><td><a href="${link}">${country}</a></td><td>${transport}</td><td>${amount}</td></tr>');

currentPage = -1;
shipAnimate = true;

jQuery(document).ready(function(){
	if(jQuery('#shipments')){
		jQuery('#shipments').hide();
		jQuery.get("/shippingdata/shippingdata.csv", function(data){
			csvData = jQuery.csv()(data);
			makeTable(csvData);
			registerPages();
			changePage();
			jQuery('#shipments').slideDown();
			}); 
	}
});

function changePage(){
	if(shipAnimate){
		currentPage++;
		if(!jQuery('#shipments #footer li a').eq(currentPage).length){
			currentPage = 0;
		}
		jQuery('#shipments #footer li a').eq(currentPage).click()
	}
	setTimeout('changePage()',5500);
}

function even_or_odd(num){
	if(!(num % 2)){
		return 'even';
	}else{
		return 'odd';
	}
}

function makeTable(data){
	jQuery('#shipments').append(tableTemplate,{});
	for(var i=0;i<data.length;i++){
		row=data[i];
		jQuery('#shipments table tbody').append(rowTemplate,{
			num:i,
			even_or_odd:even_or_odd(i+1),
			country:row[0],
			date:row[1],
			transport:row[2],
			amount:row[3],
			link:row[4]
			});
	}
	jQuery('#shipments').mouseenter(function(){
		shipAnimate=false;
	});
	jQuery('#shipments').mouseleave(function(){
		shipAnimate=true;
	});
}

function registerPages(){
	jQuery('#shipments #footer li a').each(function(i){
		jQuery(this).click(function(){
			num = i*5;
			showRows(num+1,num+5);
			jQuery('#shipments #footer li a').removeClass("current")
			jQuery(this).addClass('current');
			currentPage = i;
			return false;
		});
	});
}

function showRows(start,end){
	rows = jQuery('#shipments tbody tr');
	for(var i=0;i<rows.length;i++){
		if((start<=i+1)&&(i+1<=end)){
			jQuery(rows[i]).fadeIn();
		}else{
			jQuery(rows[i]).hide();
		}
	}
}