﻿/* Class Description
 *
 * CountDown class represents a counter that counts the
 * Days, Hours, Minutes and Seconds to an event. The constructor creates
 * object that will support the count down
 */
 
/* Consructor 
 * Parametes:
 *      - a_sDaysCtlId - Id for the HTML control that would display Days
 *      - a_sHoursCtlId - Id for the HTML control that would display Hours
 *      - a_sMinutesCtlId - Id for the HTML control that would display Minutes
 *      - a_sSecondsCtlId - Id for the HTML control that would display Seconds
 *      - a_sDeadlineDate - Deadline (or target) date. The format should be as follows: 'March 01. 2010 00:00:00'
 */
CountDown = function(a_sDaysCtlId, a_sHoursCtlId, a_sMinutesCtlId, a_sSecondsCtlId, a_sDeadlineDate)
{
    this.DaysControl = document.getElementById(a_sDaysCtlId);
    this.HoursControl = document.getElementById(a_sHoursCtlId);
    this.MinutesControl = document.getElementById(a_sMinutesCtlId);
    this.SecondsControl = document.getElementById(a_sSecondsCtlId);
    try
    {
        this.DeadLineDate = new Date(a_sDeadlineDate);                              
    }
    catch(e)
    {
        alert('Invalid date format. Date should beformatted like this: \'March 01, 2010 00:00:00\'');
    }
}

/* Method Description:
 * Starts the count down process. When this method is called the counter
 * should start to count down the remaining time to Deadline (or target) date. 
 */
CountDown.prototype.StartCountDown = function()
{    
    this.Time = Math.floor((this.DeadLineDate - new Date()) / 1000);
    this.TimerLoop();
}

/* Method Description
 * This method runs the loop used to update the timer
 * each second.
 */
CountDown.prototype.TimerLoop = function()
{
    this.VisualiseDateDiff(this.Time);
    if (this.Time >= -1)          
    {
        this.Time--;
        var oThis = this;
        setTimeout(function() {oThis.TimerLoop()}, 1000);
    }
}

/* Method Description
 * This method is used to calculate and visualise the
 * different components: Days, Hours, Minutes, Seconds
 * Paramters:
 *      - a_nDateDiff - calculated difference between dates in miliseconds
 */
CountDown.prototype.VisualiseDateDiff = function(a_nDateDiff)
{
    if (a_nDateDiff < 0)
        a_nDateDiff = 0;
        
    var nDays = Math.floor(a_nDateDiff / (60 * 60 * 24));
    var nHours = Math.floor(a_nDateDiff / (60 * 60) - (nDays * 24));
    var nMinutes = Math.floor(a_nDateDiff / 60 - ((nDays * 24 + nHours) * 60));
    var nSeconds = Math.floor(a_nDateDiff - (((nDays * 24 + nHours) * 60 + nMinutes) * 60) );
    
    this.DaysControl.innerHTML = nDays;
    this.HoursControl.innerHTML = nHours;
    this.MinutesControl.innerHTML = nMinutes;
    this.SecondsControl.innerHTML = nSeconds;
} 