/**counter-protect_seals.js
 * 
 * JavaScript Counter Code
 * by Khan Klatt (khan@khan.org)
 * Last updated by Thomas Giordano
 * Revision History
 *
 * Copyright 2005, 2006, 2007
 * Donordigital, LLC
 *
 * Revision History:
 * Khan Klatt      - 3/10/2005: First Release
 * Oksana Timonina - 4/16/2006: Support for multiple death rates and start/stop dates
 * Thomas Giordano - 3/14/2007: Support for multiple death rate start and stop times, 
 *                              countdowns to multiple hunt dates, initial count values, 
 *                              and a stop counter setting (counter will stop automatically 
 *                              after death rate date or hunt dates end).
 * 
 * Usage: Refer to this javascript file via a src call, such as:
 * <script language="javascript" src="/path/to/this/script/counter.js">
 * 
 * Note about Date formats: According to the ECMAScript spec, the Date() format 
 * uses the full (actual) four digit year, but zero-indexed month indicator
 * (i.e. January = 00, December = 11), yet 1-indexed (actual) date, actual 24h
 * hour, and actual minute/second values. January 1, 2006 at 12:00:00 midnight is:
 * Date(2006, 00, 01, 00, 00, 00)
 * 
 * 
 */

// Do not change these 3 lines:
var sealDeathRate      = new Array();
var sealDeathRateStart = new Array();
var sealDeathRateEnd   = new Array();

// Stops all dead seal counting if changed to stopSealCounting = true;
// If this is true, only the number in currentDeadSeals is shown, and it will not increase
// This has no effect on the countdown of time to the hunt start date.
var stopSealCounting = false; 

// The number the dead seal count will start with.
var deadSealsCount = 0;

// Below are the seal death rates and the start/end times for each death rate.
// Note that the death rate start/end times are NOT related to the Hunt start/end times.
// This can be modified to be 1/1 (one every second), 1/60 (one every minute), or 2/1 (two every second), etc.
// The start and end dates CAN OVERLAP, during the time where they overlap, the rates will be added together.
sealDeathRate[0]      = 2 / 3; // Two every 3 seconds
sealDeathRateStart[0] = new Date(2007, 02, 28, 06, 00, 00); // March 28, 2007 at 06:00:00am EST
sealDeathRateEnd[0]   = new Date(2007, 03, 28, 23, 59, 59); // May 15, 2007 at 11:59:59pm EST

sealDeathRate[1]      = 0; // No seals killed
sealDeathRateStart[1] = new Date(2007, 02, 28, 06, 00, 00); // March 28, 2007 at 06:00:00am EST
sealDeathRateEnd[1]   = new Date(2007, 04, 15, 23, 59, 59); // May 15, 2007 at 11:59:59pm EST

sealDeathRate[2]      = 0; // No seals killed
sealDeathRateStart[2] = new Date(2007, 02, 28, 06, 00, 00); // March 28, 2007 at 06:00:00am EST
sealDeathRateEnd[2]   = new Date(2007, 04, 15, 23, 59, 59); // May 15, 2007 at 11:59:59pm EST

sealDeathRate[3]      = 0; // No seals killed
sealDeathRateStart[3] = new Date(2007, 02, 28, 06, 00, 00); // March 28, 2007 at 06:00:00am EST
sealDeathRateEnd[3]   = new Date(2007, 04, 15, 23, 59, 59); // May 15, 2007 at 11:59:59pm EST

sealDeathRate[4]      = 2 / 3; // Two every 3 seconds
sealDeathRateStart[4] = new Date(2008, 02, 28, 06, 00, 00); // March 28, 2008 at 06:00:00am EST
sealDeathRateEnd[4]   = new Date(2008, 04, 15, 23, 59, 59); // May 15, 2008 at 11:59:59pm EST

sealDeathRate[5]      = 2 / 3; // Two every 3 seconds
sealDeathRateStart[5] = new Date(2009, 02, 28, 06, 00, 00); // March 28, 2009 at 06:00:00am EST
sealDeathRateEnd[5]   = new Date(2009, 04, 15, 23, 59, 59); // May 15, 2009 at 11:59:59pm EST

// Do not change the 2 lines below
var dateHuntStart = new Array();
var dateHuntEnd = new Array();

// Please note that hunts MUST NOT OVERLAP!
dateHuntStart[0] = new Date(2007, 02, 28, 06, 00, 00); // March 28, 2007 at 06:00:00am EST
dateHuntEnd[0]   = new Date(2007, 04, 15, 23, 59, 59); // May 15, 2007 at 11:59:59pm EST

dateHuntStart[1] = new Date(2008, 02, 28, 06, 00, 00); // March 28, 2008 at 6:00:00am EST
dateHuntEnd[1]   = new Date(2008, 04, 15, 23, 59, 59); // May 15, 2008 at 11:59:59pm EST

dateHuntStart[2] = new Date(2009, 02, 28, 06, 00, 00); // March 28, 2009 at 6:00:00am EST
dateHuntEnd[2]   = new Date(2009, 04, 15, 23, 59, 59); // May 15, 2009 at 11:59:59pm EST

/*
 *
 * *** FOR THE MOST PART, NO USER SERVICEABLE PARTS BELOW ***
 * *** THAR BE DRAGONS HERE ***
 * *** PROCEED WITH CAUTION ***
 * *** DANGER WILL ROBINSON, DANGER ***
 *
 */

/*
 * This function generates a string of digits, with commas if needed.
 * 
 * The old function generated digit-oriented img tags for display
 * It takes as an argument any length of integers.
 * It returns HTML to images that are expected to be in a relative
 * path called "js/[x].gif, where [x] is [0-9] for the appropriate
 * GIF that depicts that number.
 */
function displayDigits(num)
{
	/*
	var string = num.toString();
	var result = '';
	for (var i = 0; i < string.length; i++)
	{
		var c = string.substring(i, i + 1);
		result += '<img src="js/' + c + '.gif" alt="' + c + '">'; 
	}
	return result;
	*/
	var rgx = /(\d+)(\d{3})/;
	num = num + '';  // Convert num to string
	
	while (rgx.test(num))
		num = num.replace(rgx, '$1' + ',' + '$2');

	return '<span class="counterdigit">' + num + '</span>';
}

/*
 * This function displays the content on the page.
 * First it calculates the current date. For debugging purposes, you 
 * could temporarily override the defaults.
 */
function showCounter()
{
	var dateNow = new Date();
	var sealsKilled = 0;
	var sealHuntsArrayLen = dateHuntStart.length;

	// Do countdown calculations:
	var dateToUseInt = -1;
	var mostRecentHuntInt    = -1;
	var nearestFutureHuntInt = -1;

	for (var hd = 0; hd < sealHuntsArrayLen; hd++)
	{
		// If there is an active hunt
		if (dateHuntStart[hd] <= dateNow && dateHuntEnd[hd] > dateNow)
		{
			dateToUseInt = hd;
			break;
		}
		
		// Find the most recently ended hunt, else Find the nearest upcoming hunt
		if (dateHuntStart[hd] <= dateNow && (dateHuntStart[hd] < dateHuntStart[mostRecentHuntInt] || mostRecentHuntInt == -1))
			mostRecentHuntInt = hd;
		else if (dateHuntStart[hd] > dateNow && (dateHuntStart[hd] < dateHuntStart[nearestFutureHuntInt] || nearestFutureHuntInt == -1))
			nearestFutureHuntInt = hd;
	}

	var date90DaysAway = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate() + 90);

	// If there is no active hunt to use
	if (dateToUseInt == -1)
	{
		// If there is a hunt starting within 90 days, use it, otherwise use the most recently ended hunt
		if (nearestFutureHuntInt > -1 && dateHuntStart[nearestFutureHuntInt] <= date90DaysAway)
			dateToUseInt = nearestFutureHuntInt;
		else
			dateToUseInt = mostRecentHuntInt;
	}

	// These variables calculate and store our absolute, relative, and countdown values
	var msTimeToStart = dateNow.getTime() - dateHuntStart[dateToUseInt].getTime();

	var daysTimeToStart       = msTimeToStart / (1000 * 60 * 60 * 24);
	var daysIntTimeToStart    = Math.abs(parseInt(daysTimeToStart));
	var hoursTimeToStart      = (daysTimeToStart - parseInt(daysTimeToStart)) * 24;
	var hoursIntTimeToStart   = Math.abs(parseInt(hoursTimeToStart));
	var minutesTimeToStart    = (hoursTimeToStart - parseInt(hoursTimeToStart)) * 60;
	var minutesIntTimeToStart = Math.abs(parseInt(minutesTimeToStart));
	var secondsTimeToStart    = (minutesTimeToStart - parseInt(minutesTimeToStart)) * 60;
	var secondsIntTimeToStart = Math.abs(parseInt(secondsTimeToStart));

	// If the date is in the past
	if (dateHuntStart[dateToUseInt] <= dateNow)
	{
		// Count how many days ago hunt started
		//var header = '<img src="js/huntbegan.gif"><br>';
		//var footer = '<img src="js/ago.gif">';
		var header = 'The Hunt Began<br>';
		var footer = 'Ago';
		var countingDown = false;
	}
	else
	{
		// Count down to hunt start
		//var header = '<img src="js/countdown.gif"><br>';
		//var footer = '';
		var header = '';
		var footer = '<br><span class="subcounter">COUNTDOWN TO THE HUNT</span>';
		var countingDown = true;
	}
	
	// Check if we should be counting seals
	if (!stopSealCounting)
	{
		// Begin dead seal calculations:
		var sealDeathArrayLen = sealDeathRate.length;
	
		for (var dr = 0; dr < sealDeathArrayLen; dr++)
		{
			// If the death rate start date is not in the future
			if (sealDeathRateStart[dr] < dateNow)
			{
				for (var sh = 0; sh < sealHuntsArrayLen; sh++)
				{
					// If (the death rate start date is after the seal hunt start date or
					// the death rate end date is after the seal hunt start date) and the hunt has started
					if (((sealDeathRateStart[dr] >= dateHuntStart[sh]) || (sealDeathRateEnd[dr] >= dateHuntStart[sh])) && dateHuntStart[sh] <= dateNow)
					{
						var startDate = new Date();
						var endDate = new Date();
	
						// If the death rate end date is before seal hunt end date, use that for our end date
						if (sealDeathRateEnd[dr] <= dateHuntEnd[sh])
							endDate = sealDeathRateEnd[dr];
						else 
							endDate = dateHuntEnd[sh];

						// If our end date is in the future, use now instead
						if (endDate > dateNow)
							endDate = dateNow;

						// If death rate start date is before the hunt start date, use the time since the hunt started
						if (sealDeathRateStart[dr] < dateHuntStart[sh])
							startDate = dateHuntStart[sh];
						else
							startDate = sealDeathRateStart[dr];

						// Subtract StartDate from EndDate to get the elapsed time at this death rate
						var sealDeathRateDuration = (endDate.getTime() - startDate.getTime()) / 1000;

						// Convert death rate duration to a number of seconds, and multiply it by the death rate ratio
						sealsKilled += parseInt(sealDeathRateDuration * sealDeathRate[dr]);
					}
				}
			}
		}
	}

	// Generate output by getting a handle to the div tag, then write into it.
	myDiv = document.getElementById("displayCounter");
	//myDiv.innerHTML = header + displayDigits(daysIntTimeToStart) + '<img src="js/days.gif" alt="days">' + displayDigits(hoursIntTimeToStart) + '<img src="js/hours.gif" alt="hours">' + displayDigits(minutesIntTimeToStart) + '<img src="js/min.gif" alt="minutes">' + displayDigits(secondsIntTimeToStart) + '<img src="js/sec.gif" alt="seconds">' + footer + '<br><br><img src="js/sealskilled.gif" alt="seals killed">' + displayDigits(deadSealsCount + sealsKilled);
	if (stopSealCounting || !countingDown)
		myDiv.innerHTML = displayDigits(deadSealsCount + sealsKilled) + '<br><span class="subcounter">SEALS KILLED</span>';
	else
		myDiv.innerHTML = header + displayDigits(daysIntTimeToStart) + ' <span class="counterunit">DAYS</span> ' + displayDigits(hoursIntTimeToStart) + ' <span class="counterunit">HOURS</span> ' + displayDigits(minutesIntTimeToStart) + ' <span class="counterunit">MIN</span> ' + displayDigits(secondsIntTimeToStart) + ' <span class="counterunit">SEC</span>' + footer;
	
	// Recurse to get updated date values, and redisplay updated info.
	setTimeout("showCounter();", 1000);
}

