﻿//Countdown function
jQuery(document).ready(function()
{
    //Get Collection
    var CountDownDivs = jQuery(".CountDown");

    //Loop through collection
    jQuery.each(CountDownDivs, function(index, div)
    {
       var MainElem = jQuery(div);

        //Set ID and date Attribute
        var divid = MainElem.attr("id");
        var date = new Date(MainElem.attr("datetime"));

        var seconds = GetSeconds(date)

        //Start countdown
        CountDown(date, MainElem);
    });
});

//Recursive countdown function
function CountDown(enddate, MainElem)
{
   var Time_left = GetSeconds(enddate);
    if (Time_left < 0)
    {
        //Display TEXT
    }
    else
    {
        FormatTime(Time_left, MainElem);
        setTimeout(function() { CountDown(enddate, MainElem) }, 1000);
    }
}

//Format time
function FormatTime(Time_left, MainElem)
{
    var seconds = Math.floor(Time_left % 60);
    var minutes =  Math.floor((Time_left / 60) % 60);
    var hours = Math.floor(Time_left / 3600) % 24;
    var days = Math.floor(Time_left / 86400);

    seconds = add_leading_zero(seconds);
    minutes = add_leading_zero(minutes);
    hours = add_leading_zero(hours);

    var emptySpace = " ";

   MainElem.find('.Days').find('.datepartnumber').html(days);
   MainElem.find('.Hours').find('.datepartnumber').html(hours);
   MainElem.find('.Minutes').find('.datepartnumber').html(minutes);
   MainElem.find('.Seconds').find('.datepartnumber').html(seconds);

}

//add zero if integer is 0 to 9
function add_leading_zero(n)
{
    if (n.toString().length < 2)
    {
        return '0' + n;
    }
    else
    {
        return n;
    }
}

//Get seconds difference between now and date(parameter)
function GetSeconds(date)
{
    var today = new Date();
    var seconds = date.getTime() - today.getTime();
    return seconds / 1000;
}
