﻿__CountDownElements = new Array();
__CountDownIsCreated = false;

var javascript_countdown = function () {
    //var time_left = 10; //number of seconds for countdown
    //var output_element_id = 'javascript_countdown_time';
    var keep_counting = 1;
    
    function countdown() {
        var time_left = 0;
        for (var counter = 0; counter < __CountDownElements.length; counter++) {
            if (time_left <= __CountDownElements[counter]['time_left']) {
                time_left = __CountDownElements[counter]['time_left'];
                if (__CountDownElements[counter]['time_left'] > 0) {
                    __CountDownElements[counter]['time_left'] = __CountDownElements[counter]['time_left'] - 1;
                }
            }
        }
        if (time_left == 0) {
            keep_counting = 0;
        }

        //time_left = time_left - 1;
    }

    function add_leading_zero(n) {
        if (n.toString().length < 2) {
            return '0' + n;
        } else {
            return n;
        }
    }

    function format_output(time_left) {
        var hours, minutes, seconds;
        seconds = time_left % 60;
        minutes = Math.floor(time_left / 60) % 60;
        hours = Math.floor(time_left / 3600);

        seconds = add_leading_zero(seconds);
        minutes = add_leading_zero(minutes);
        hours = add_leading_zero(hours);

        return hours + ':' + minutes + ':' + seconds;
    }

    function show_time_left() {
        for (var counter = 0; counter < __CountDownElements.length; counter++) {
            if (__CountDownElements[counter]['time_left'] > 0) {
                document.getElementById(__CountDownElements[counter]['output_element_id']).innerHTML = format_output(__CountDownElements[counter]['time_left']);
            }
        }
        //document.getElementById(output_element_id).innerHTML = format_output(); //time_left;
    }

    return {
        count: function () {
            countdown();
            show_time_left();
        },
        timer: function () {
            __CountDownIsCreated = true;
            javascript_countdown.count();

            if (keep_counting) {
                setTimeout("javascript_countdown.timer();", 1000);
            } else {
                //no_time_left();
                location.reload();
            }
        },
        init: function (t, element_id) {
            __CountDownElements[__CountDownElements.length] = {
                'time_left': t,
                'output_element_id': element_id
            };
            if (__CountDownIsCreated == false) {
                javascript_countdown.timer();
            }
            else {
                show_time_left();
            }
        }
    };
} ();


