function shuffleArray ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}

function rollProjects() {
	$("div#projectsBox div.projectBox:first").remove();
	addProject();
}

function addProject() {
	$("div#projectsBox").append("<div style=\"display: none;\" class=\"projectBox\"></div>");
	$("div#projectsBox div.projectBox:last").append("<p class=\"title\">" + data[idxProject].AcronymeEtTitle + "</p>");
	$("div#projectsBox div.projectBox:last").append("<p>Requérant: " + data[idxProject].Requerant + "</p>");
	$("div#projectsBox div.projectBox:last").append("<p class=\"download\"></p>");
	
	if (data[idxProject].SiteProjet != null) {
		$("div#projectsBox div.projectBox:last p.title").wrapInner("<a target=\"_blank\" href=\"" + data[idxProject].SiteProjet+ "\"></a>");
	}
	
	if (data[idxProject].RapportScientifique != null) {
		$("div#projectsBox div.projectBox:last p.download").append("<a target=\"_blank\" href=\"" + data[idxProject].RapportScientifique+ "\">Rapport</a>");
		if (data[idxProject].FicheProjet != null) {
			$("div#projectsBox div.projectBox:last p.download").append(", ");
		}
	}
	
	if (data[idxProject].FicheProjet != null) {
		$("div#projectsBox div.projectBox:last p.download").append("<a target=\"_blank\" href=\"" + data[idxProject].FicheProjet+ "\">Fiche</a>");
	}
	
	$("div#projectsBox div.projectBox:last").fadeIn('slow');
	
	// Update the index
	if (idxProject < data.length - 1) {
		idxProject++;
	}
	else
	{
		idxProject = 0;
	}
}

// Index of the current ad to display
var idxProject;
var data;

$(document).ready(function() {
	
	// Initialize indexes
	idxProject = 0;
	
	$.ajax({
		  url: "http://moss-services.heig-vd.ch/ExtraRcso-Publishing/sf.mvc/Projects/GetAllRcsoProjects/",
		  dataType: 'jsonp',
		  success: function(dataReceived, textstatus) {
		
			data = dataReceived;
			shuffleArray(data);
			
			// Displays the N first projects
			for (var i = 0; i < 3; i++)
			{
				addProject();
			}
			
			$.timer(10000, function (timer) {
				$("div#projectsBox div.projectBox:first").slideUp('slow', rollProjects);
			});
			
		} // end function success
	});
});
