﻿(function ($) {                                          // Compliant with jquery.noConflict()
    $.fn.jDealTimer = function (o) {
        o = $.extend({
            endDate: new Date(),                //Creates a date
            container: '#timer',                    //Timer container, hides this element if the timer reaches 0
            refreshInterval: 1,                 //Interval in seconds
            buyButton: '#buy_now_button_div',   //The selector for the buy button
            overButton: '#deal_over',           //The selector for the deal over button
            fadeInterval: 500                   //Interval in which the fade occures
        }, o || {});

        return this.each(function () {
            var timer = null;
            var label = $(this);

            refresh();


            function refresh() {
                _dateNow = new Date();
                _amount = o.endDate.getTime() - _dateNow.getTime();
                delete dateNow;


                if (_amount > 0) {
                    var _display = "";
                    _amount = Math.floor(_amount / 1000); //kill the "milliseconds" so just secs
                    var _days = Math.floor(_amount / 86400); //days
                    _amount = _amount % 86400;
                    var _hours = Math.floor(_amount / 3600); //hours
                    _amount = _amount % 3600;
                    var _mins = Math.floor(_amount / 60); //minutes
                    _amount = _amount % 60;
                    var _secs = Math.floor(_amount); //seconds

                    if (_days != 0) { _display += _days + " " + ((_days == 1) ? "day" : "days") + " "; }
                    _display += ((_hours <= 9) ? "0" : "") + _hours + ":";
                    _display += ((_mins <= 9) ? "0" : "") + _mins + ":";
                    _display += ((_secs <= 9) ? "0" : "") + _secs;


                    $(label).html(_display);

                    //Cleanup variables
                    delete _days;
                    delete _hours;
                    delete _mins;
                    delete _secs;
                    delete _display;

                    if (o.refreshInterval && o.refreshInterval > 0) {
                        timer = setTimeout(function () { refresh(); }, o.refreshInterval ? o.refreshInterval * 1000 : 1000);
                    }
                }
                else {

                    //Change the deal over button
                    $(o.buyButton).fadeOut(o.fadeInterval, function () { $(o.overButton).fadeIn(o.fadeInterval); });

                    if (o.container) {
                        $(o.container).hide();
                    }
                }



            }
        });
    };
})(jQuery);
