(function ($) {
    $.fn.countdown = function (options) {
        var defaults = {
            targetDate: new Date(new Date().getFullYear(), 11, 25),
            month: 0,
            day: 0,
            year: 0,
            hour: 0,
            minutes: 0,
            GMTOffset: -5,
            arrivedMessage: "<h2>Christmas Day!</h2>"
        }
        var options = $.extend(defaults, options);
        var timer = $(this)[0];
        var totalSeconds;
        var localOffset = 0;
        var clientOffsetSeconds = -(new Date().getTimezoneOffset() * 60);
        function ConfigureDate() {
            if (options.month != 0 && options.day != 0 && options.year != 0) {
                options.targetDate = new Date(options.year, (options.month - 1), options.day, options.hour, options.minutes);
            }
        }
        function CalculateLocalOffset() {
            if (options.GMTOffset * 60 * 60 > clientOffsetSeconds) {
                localOffset = clientOffsetSeconds - options.GMTOffset * 60 * 60;
            } else if (options.GMTOffset * 60 * 60 < clientOffsetSeconds) {
                localOffset = clientOffsetSeconds + options.GMTOffset * 60 * 60;
            } else if (options.GMTOffset * 60 * 60 == clientOffsetSeconds) {
                localOffset = 0;
            }
        }
        function CreateTimer() {
            totalSeconds = SecondsTillDate(options.targetDate);
            UpdateTimer();
            setTimeout(function () { Tick(); }, 1000);
        }
        function SecondsTillDate(tDate) {
            var seconds = 0;
            var today = new Date();
            seconds = Math.floor((tDate.getTime() - today.getTime()) / 1000);
            return seconds + localOffset;
        }

        function Tick() {
            if (totalSeconds <= 0) {
                timer.innerHTML = options.arrivedMessage;
                return;
            }
            totalSeconds -= 1;
            UpdateTimer();
            setTimeout(function () { Tick(); }, 1000);
        }

        function UpdateTimer() {
            var seconds = totalSeconds;

            var days = Math.floor(seconds / 86400);
            seconds -= days * 86400;

            var hours = Math.floor(seconds / 3600);
            seconds -= hours * (3600);

            var minutes = Math.floor(seconds / 60);
            seconds -= minutes * (60);


            var timeStr = '<span class="cdTitle">'+ options.countingTo + '</span> <span class="cdDays">' + ((days > 0) ? days + ' days ' : '')+'</span><span class="cdTime">'+ LeadingZero(hours) + ':' + LeadingZero(minutes) + ':' + LeadingZero(seconds)+'</span>';


            timer.innerHTML = timeStr;
        }
        function LeadingZero(time) {

            return (time < 10) ? "0" + time : +time;

        }

        //init
        ConfigureDate();
        CalculateLocalOffset();
        CreateTimer();
    }
})(jQuery);
