// contador.jquery.js
(function ($) {
    var Contador = function (element, options) {
        var elem = $(element);
        var obj = this;

        // mescla as opcoes com os padroes
        var config = $.extend({
            dias: 0,
            horas: 0,
            minutos: 5,
            segundos: 0,
            intervalo: 1000, // milisegundos
            tempoExpirou: function (elem) { // 
                alert('tempo esgotado!');
                elem.hide();
                return;
            }
        }, options || {});

        var dd = config.dias;
        var hh = config.horas;
        var mm = config.minutos;
        var ss = config.segundos;

        this.timer = null;

        this.initTimer = function () {
            var obj = this;

            this.timer = setInterval(function () {
                init();
            }, config.intervalo);

            return this.timer;
        };

        var stopTimer = function () {
            clearInterval(this.timer);
        };

        var init = function () {
            ss--;
            if (ss < 0) {
                ss = 59;
                mm--;
                if (mm < 0) {
                    mm = 59;
                    hh--;
                    if (hh < 0) {
                        hh = 23;
                        dd--;
                        if (dd < 0) {
                            stopTimer();
                            config.tempoExpirou(elem);
                            return;
                        }
                    }
                }
            }

            if (dd <= 9) {
                xdd = "0" + dd;
            }
            else {
                xdd = dd;
            }
            if (hh <= 9) {
                xhh = "0" + hh;
            }
            else {
                xhh = hh;
            }
            if (mm <= 9) {
                xmm = "0" + mm;
            }
            else {
                xmm = mm;
            }
            if (ss <= 9) {
                xss = "0" + ss;
            }
            else {
                xss = ss;
            }

            elem.html(xdd + '&nbsp;&nbsp;&nbsp;' + xhh + "&nbsp;&nbsp;&nbsp;" + xmm + "&nbsp;&nbsp;&nbsp;" + xss);
        };
    };

    $.fn.contador = function (options) {
        var count = 0;

        return this.each(function () {
            var element = $(this);

            // retorn antes se o elemento ja tem uma instancia do plugin
            if (element.data('contador' + count)) return;

            var contador = new Contador(this, options);
            contador.initTimer();
            count++;

            element.data('contador' + count, contador);
        });
    };
})(jQuery);

