var Tui = Tui || {};
Tui.Countdown = {
    /**
     * Create is called to create a countdown timer. Currently it only allows a single instance to
     * be created and stored as Tui.Countdown.Timer
     * @param   element     The target element to be turned into a countdown timer
     * @param   options     Either a string containing a date or an object literal containing a date and other options 
     */
    Create: function(options) {
        var defaultOptions = {
            target: '.countdown',
            endDate: null,
            message: 'Sale ends in',
            days: true,
            hours: true,
            minutes: true,
            seconds: true
        }
        // Set up options and check for date entered as string
        if (typeof options === 'string') {
            var date = options,
                options = defaultOptions;
            options.endDate = date;
        }
        else {
            var options = jQuery.extend(defaultOptions, options);
        }
        
        // Create elements for countdown timer, including the elements to
        // contain the digits which will be updated by the timer.
        var container = jQuery(options.target).eq(0),
            timerDiv = jQuery('<div>').addClass('countdownContainer'),
            endDate = new Date(options.endDate),
            finalCountdownDate = options.finalCountdownDate ? new Date(options.finalCountdownDate) : null,
            days = jQuery('<span>').addClass('timerDigits'),
            hours = jQuery('<span>').addClass('timerDigits'),
            minutes = jQuery('<span>').addClass('timerDigits'),
            seconds = jQuery('<span>').addClass('timerDigits'),
            interval = null;
        
        // Check date is valid
        if(isNaN(endDate.valueOf())) {
            return;
        }
        
        /**
         * constructTimer creates most of the HTML elements required and inserts them into the DOM
         */
        function constructTimer() {
            var msgDiv = jQuery('<span>').addClass('countdownMessage').text(options.message),
                daysContainer = jQuery('<div>').addClass('timerElement'),
                hoursContainer = jQuery('<div>').addClass('timerElement'),
                minutesContainer = jQuery('<div>').addClass('timerElement'),
                secondsContainer = jQuery('<div>').addClass('timerElement');
            if(options.days) {
                daysContainer.append(days).append(jQuery('<span>').addClass('timerHeading').text('days'));
                timerDiv.append(daysContainer);
            }
            if(options.hours) {
                hoursContainer.append(hours).append(jQuery('<span>').addClass('timerHeading').text('hours'));
                timerDiv.append(hoursContainer);
            }
            if(options.minutes) {
                minutesContainer.append(minutes).append(jQuery('<span>').addClass('timerHeading').text('minutes'));
                timerDiv.append(minutesContainer);
            }
            if(options.seconds) {
                secondsContainer.append(seconds).append(jQuery('<span>').addClass('timerHeading').text('seconds'));
                timerDiv.append(secondsContainer);
            }
            // container.width(95 + 50 *(options.days + options.hours + options.minutes + options.seconds));
            container.empty().append(timerDiv).append(msgDiv);
            //container.width(container.width()); // Hack to persuade IE6 to display timer on some pages
        }
        
        /**
         * Calculates the time remaining and updates the countdown
         */
        function updateTimer() {
            var d,
                h,
                m,
                s,
                difference;
            today = new Date();
            difference = endDate - today;
            if(difference < 0) {
                clearInterval(Tui.Countdown.Interval);
                displayExpiredMessage();
                return;
            }
            d = Math.floor(difference/1000/60/60/24, 10);
            d = padLeftDigit(d);
            difference = difference - d * 24 * 60 * 60 * 1000;
            h = Math.floor(difference/1000/60/60, 10);
            h = padLeftDigit(h);
            difference = difference - h * 60 * 60 * 1000;
            m = Math.floor(difference/1000/60, 10);
            m = padLeftDigit(m);
            difference = difference - m * 60 * 1000;
            s = Math.floor(difference/1000, 10);
            s = padLeftDigit(s);
            days.text(d);
            hours.text(h);
            minutes.text(m);
            seconds.text(s);
            if(finalCountdownDate && finalCountdownDate <= today) {
                timerDiv.addClass('finalCountdown');
            }
            else {
                timerDiv.removeClass('finalCountdown');
            }
        }
        
        // Displays the message when the countdown finishes.
        function displayExpiredMessage() {
            container.empty();
            var expiredMessage = 'Ended at ' + getTimeString(endDate) + ' on ' + getDateString(endDate);
            options.expiredMessage = options.expiredMessage || expiredMessage;
            container.append(jQuery('<span>').addClass('expiredMessage').text(options.expiredMessage));
        }
        
        // Makes sure that the countdown digits are always 2 digits, even if less than 10
        function padLeftDigit(number) {
            if(number < 10) {
                number = '0' + number;
            }
            return number;
        }
        
        // Extracts the time in the format hh:mm from a date object
        function getTimeString(date) {
            return padLeftDigit(date.getHours()) + ':' + padLeftDigit(date.getMinutes());
        }
        
        // Extracts the date in the format dd/mm/yyyy from a date object
        function getDateString(date) {
            return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
        }
        
        // clearInterval(Tui.Countdown.Interval);
        constructTimer();
        Tui.Countdown.Interval = setInterval(function() {
            updateTimer();
        }, 100);
        
        
        Tui.Countdown.Timer = {
            stop: function() {
                clearInterval(Tui.Countdown.Interval);
            },
            start: function() {
                Tui.Countdown.Interval = setInterval(function() {
                    updateTimer();
                }, 400);
            },
            setDate: function(newDate) {
                endDate = new Date(newDate);
            },
            setFinalCountdownDate: function(finalDate)
            {
                finalCountdownDate = new Date(finalDate);
                if(isNaN(finalCountdownDate.valueOf())) {
                    finalCountdownDate = null;
                }
            },
            end: function() {
                clearInterval(Tui.Countdown.Interval);
                displayExpiredMessage();
            }
        }
    }
}
