$(document).ready(function() {
	var CACHED_NEWS = "cached_news";
	//localStorage.clear();
	var items = localStorage.getItem(CACHED_NEWS);
	//show the loading spinner
	$("#newsLoader").show();
	//if news are not cached (cache disabled by user or first visit)
	if(items == null) {
		//get json data asynchronously from webservice via GET REST method
		items = [];
		$.getJSON('server/api/news.php', function(data) {	 
			//Construct the li collection
			for(var i=0;i<data.length;i++) {
				items += '<li id="' + data[i].ID + '">' + data[i].Title + '<br /><small>' + data[i].AddedDate  + '</small></li>';
			}
			console.log(items);
			localStorage.setItem(CACHED_NEWS, items);
			//render the list
			renderList(items);
		});
	} else {
		//render the list
		renderList(items);
	}
});

function renderList(data) {
	//Make sure the news listing doesn't show at the bottom before spinner disappear
	$('#newsBoxScrollable').hide();
	
	//Create the ul tag, shove the li collection in it, then put it in the scrollable box
	$('<ul/>', {
		html : data
	}).appendTo('#newsBoxScrollable');
	
	//transition between spinner and loaded ul
	$("#newsLoader").fadeOut(500, function() { $(this).hide(); });
	$('#newsBoxScrollable').fadeIn(500);
	
	//Show a iOS-style scroller
	$('#newsBoxScrollable').innerscroll({
		destination: $('#newsBox'),
		draggable: true
	});
}
