
//run an update when the page loads
$(function(){
	$('#stop-fetching-new-companies').hide();
	$.getJSON("?action=last-update&format=json", function(result){
		var msg = '';
		if (result.lastUpdate){
			msg = result.lastUpdate;
		}
		else {
			msg = "Never";
		}
		$("#cdb-last-update").html(msg);
	});
	$('input.date').datepicker({
		dateFormat: 'dd-M-yy'
	});
})

var stopFetchingCompanies = false;

$('#fetch-new-companies').live("click", function(){
	var $btn = $(this);
	var c = 0;
	$btn.hide();
	$('#stop-fetching-new-companies').show();
	$('#fetch-companies-status').text("fetching new companies...");
	stopFetchingCompanies = false;
	var startIncDate = null;
	var startTime = (new Date()).getTime() / 1000;
	var fetchNewCompanies = function(){
		if (!stopFetchingCompanies){
			$.getJSON("?action=fetch-new-companies&format=json&limit=3", function(result){
				//TODO show results
				if (result && !result.error){
					if (!startIncDate && result.startIncorporationDate){
						startIncDate = result.startIncorporationDate;
					}
					
					var progress = (result.endIncorporationDate - startIncDate) / (result.maxIncorporationDate - startIncDate)
					var msg = "Total Companies: "+ result.totalCompanies +' : '+ parseInt(progress * 100) +"% ("+ c++ +")";
					
					//estimate the time remaining
					var currTime = (new Date()).getTime() / 1000;
					var remaining = (100 / progress) * (currTime - startTime);
					//if (isFinite(remaining)){
						//msg += "\nApproximately "+ parseInt(remaining / 60) +" minutes remaining";
					//}
					
					$('#fetch-companies-status').text(msg);
					//and then fetch some more
					if (result.endIncorporationDate < result.maxIncorporationDate){
						fetchNewCompanies();
					}
				}
				else {
					//something screwed up, try again?
					fetchNewCompanies();
				}
			});
		}
		else {
			//
			stopFetchingCompanies = false;
			$('#stop-fetching-new-companies').hide().val("Stop Fetching New Companies");
			$btn.show();
		}
	}
	fetchNewCompanies();
})

$('#stop-fetching-new-companies').live("click", function(result){
	//send a stop signal to the backend
	stopFetchingCompanies = true;
	$(this).val("stopping...");
})
