var millisPerDay = 24 * 60 * 60 * 1000;
var PRACTICES = 6;
var headings = new Array(
	'Practice', 'Start Date*','Repetitions','Total Repetitions','Days so far','Percent','Reps per day',
	'Total days','End date','Days left', '',
	'Future reps per day', 'Total days', 'End date', 'Days left');
var ids = new Array(
	'practice','start','reps','totalReps','days','pct','repsPerDay',
	'totalDays','endDate','daysLeft', 'progress',
	'fReps','fTotalDays','fEndDate','fDaysLeft');

function init() {
	initCurrent();
	if (readCookie())
		updateCurrent();			
}
	
function initProgress(j) {
	var progressTable = document.createElement('table');
	progressTable.width = '100%';
	var progressRow = document.createElement('tr');
	var progressCell1 = document.createElement('td');
	progressCell1.id = 'filled' + j;
	progressCell1.width = '1%';
	progressCell1.className = 'empty';
	var progressCell2 = document.createElement('td');
	progressCell2.className = 'empty';
	progressRow.appendChild(progressCell1);
	progressRow.appendChild(progressCell2);
	progressTable.appendChild(progressRow);    
	return progressTable;  
}

function initRow(i, tblBody, row, cell, text) {
	cell.appendChild(text);
	row.appendChild(cell);

	(PRACTICES).times(function(j) {
		var newCell = document.createElement("td");
		var element;						
		if (ids[i] == 'progress')
			element = initProgress(j);                     
		else {
			element = document.createElement('input');
			element.size = 15;
			element.maxLength = 15;
		}
		newCell.appendChild(element);
		element.id = ids[i] + j;

		row.appendChild(newCell);
	});

	tblBody.appendChild(row);
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
	
function initCurrent() {
	var tbl = $('currentTable');
	var tblBody = document.createElement("tbody");

	(headings.length).times(function(i) {	
		var row = document.createElement("tr");
		var cell = document.createElement("th");
		var text = document.createTextNode(headings[i]);
		initRow(i, tblBody, row, cell, text);
	});
	
	var row = document.createElement("tr");
	var cell = document.createElement("th");

	cell.colSpan = 2;
	cell.id = 'total';
	row.appendChild(cell);
	tblBody.appendChild(row);		
	
	tbl.appendChild(tblBody);

	cell.colSpan = 2;
	cell.id = 'total';
	row.appendChild(cell);
	tblBody.appendChild(row);		
	
	tbl.appendChild(tblBody);
}

function update() {
	updateCurrent();
	writeCookie();
}

function fixNumber(x) {
	if (isNaN(x) || x == "")
		return 0;
	return x;
}
	
function formatCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function formatDate(date) {
	return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear();
}

function setText(id, i, value) {
	$(id + i).value = value;
}

function updateForecast(i, repetitionsLeft, totalRepetitions, startDate) {
    var projectedRepsPerDay = $('fReps'+i).value;

	var currentDateInMillis = new Date().getTime();
    var endDateInMillis = startDate.getTime() + (totalRepetitions / projectedRepsPerDay) * millisPerDay;
	var daysLeft = (endDateInMillis - currentDateInMillis) / millisPerDay;
    setText('fTotalDays', i, Math.round((endDateInMillis - startDate.getTime()) / millisPerDay));
    setText('fEndDate', i, formatDate(new Date(endDateInMillis)));
	setText('fDaysLeft', i, Math.floor(daysLeft));   
}

function updateStats(i, repetitions) {
    var startDate = new Date($('start' + i).value);
    var totalRepetitions = fixNumber(parseInt($('totalReps' + i).value));               

    var now = new Date();
    var daysSoFar = 0;

    var pct = (repetitions / totalRepetitions * 100.0).toFixed(2);
    var daysSoFar = Math.round((now - startDate) / millisPerDay, 0);
    var repsPerDay = repetitions / daysSoFar;
    var totalDays = totalRepetitions / repsPerDay;
    var daysLeft = totalDays - daysSoFar;
           
    setText('days',i,daysSoFar);
    setText('pct',i,pct + '%');
    setText('repsPerDay', i, repsPerDay.toFixed(1));
    setText('totalDays', i, Math.round(totalDays));   
    setText('endDate', i,
        (daysLeft >= 0)
        ? formatDate(new Date(startDate.getTime() + totalDays * millisPerDay))
        : '');
    setText('daysLeft', i, (daysLeft >= 0) ? Math.round(daysLeft) : '');

    $('filled'+i).className = 'filled';
    if (pct < 100)
        $('filled'+i).width = ((pct < 1) ? 1 : pct) + '%';
    else
        $('filled'+i).width = '100%';

    if ($('fReps'+i).value != '')
        if (pct < 100.0)
            updateForecast(i, totalRepetitions - repetitions, totalRepetitions , startDate);
        else
            $('fReps'+i).value = '';
}


function updateCurrent() {
	var total = 0;
	(PRACTICES).times(function(i) {
		var repetitions = fixNumber(parseInt($('reps' + i).value));
		if (repetitions > 0) {
			updateStats(i, repetitions);
			total += repetitions;
		}
		else
			$('filled'+i).className = 'empty';
	});
	$('total').innerHTML = 'Total: ' + formatCommas(total);
}

function addCookieElement(id, expires) {
	var list = '';
	(PRACTICES).times(function(i) {
		list += $(id + i).value + ',';
	});
	document.cookie = 
		id + '=' + list +
		";expires=" + expires;
}

function initCell(cookie) {
	var pair = cookie.split('=');
	var id = pair[0];
	var list = pair[1].split(',');
	(Math.min(list.length,PRACTICES)).times(function(i) {
		$(id + i).value = list[i];
	});
}

function calc(cookies) {
	cookies.each(function(cookie) {
		while (cookie.charAt(0) == ' ')
			cookie = cookie.substring(1,cookie.length);		
		initCell(cookie);
	});
}

function readCookie() {
	var cookies = document.cookie.split(';');
	if (cookies == '') return false;
	calc(cookies);
	return true;
}

function writeCookie() {
	var expires = (new Date(2030,11,31)).toGMTString();		

	addCookieElement('practice', expires);	
	addCookieElement('start', expires);
	addCookieElement('reps', expires);	
	addCookieElement('totalReps', expires);
	addCookieElement('fReps', expires);
}

function importCookies(importFlag) {
	$('cookiesImport').style.visibility='hidden';
	if (importFlag) {
		calc(cookies = $('cookiesImportTextArea').value.split(';'));
		update();
	}
}

function exportCookies() {
	$('cookiesExportTextArea').value = document.cookie;
	$('cookiesExport').style.visibility = 'visible';
}
