function flightTime(a,b){
	var days = Math.round((b-a)/86400 * 100) / 100
	var months = Math.round(days/30)
	var years = Math.round(months/12)
	if (days < 30){
		return ""+days+" "+dictionnary.jours
	}
	else if (days >= 30 && days < 365){
		if(months>1){
			return ""+months+" "+dictionnary.mois_pluriel
		}
		else{
			return ""+months+" "+dictionnary.mois
		}
	}
	else if (days >= 365){
		if(years>1){
			return ""+years+" "+dictionnary.ans
		}
		else{
			return ""+years+" "+dictionnary.an
		}
	}
}

//load
var nPages;
var nPagesLoaded = 1
$.post( "getAnthology.php", function(pages) {
	pages = $.parseJSON(pages)
	nPages = Number(pages.nPages)
})

function displayAnthology(){ // clean and display first page
	$("#anthologyItems").html('')
	nPagesLoaded = 1
	$.post( "getAnthology.php?page=1", function(result) {
		results = $.parseJSON(result)
		var momentLocale = lang;
		if (momentLocale == 'zh'){momentLocale = 'zh-cn'} //troubleshot for chinese
		moment.locale(momentLocale)
		for (var i in results){
			addAnthologyLine(results[i])
		}
	})
}

$( "#anthology" ).scroll(function() {
   if($("#anthology").scrollTop() + 700 > $("#anthologyItems").height()){
	   if (nPagesLoaded < nPages){
		   nPagesLoaded++
		    console.log('Loading anthology page '+nPagesLoaded+'/'+nPages)
		   $.post( "getAnthology.php?page="+nPagesLoaded+"", function(result) {
			results = $.parseJSON(result)
			var momentLocale = lang;
			if (momentLocale == 'zh'){momentLocale = 'zh-cn'} //troubleshot for chinese
			moment.locale(momentLocale)
			for (var i in results){
				addAnthologyLine(results[i])
			}
		})
	   }
   }
});

function addAnthologyLine(results){
	if (lang == 'ar'){ // arabic : rtl + add <br>
		$("#anthologyItems").append(
		'<small style="float:right">'+dictionnary.origine+': <b>'+results.startName+'</b> &bull; '+dictionnary.destination+': <b>'+results.destName+'</b> &bull; '+dictionnary.date_arrivee+': <b>'+moment(Number(results.deliveryTime)*1000).format('LL')+'</b> &bull; '+dictionnary.temps_de_vol+': <b>'+flightTime(Number(results.startTime),Number(results.deliveryTime))+'</b></small><br><br>'+results.message+'<br><hr><br>'
		)
	}
	else{
		$("#anthologyItems").append(
		'<small>'+dictionnary.origine+': <b>'+results.startName+'</b> &bull; '+dictionnary.destination+': <b>'+results.destName+'</b> &bull; '+dictionnary.date_arrivee+': <b>'+moment(Number(results.deliveryTime)*1000).format('LL')+'</b> &bull; '+dictionnary.temps_de_vol+': <b>'+flightTime(Number(results.startTime),Number(results.deliveryTime))+'</b></small><br><br>'+results.message+'<br><hr><br>'
		)
	}
}


