// -------------------------------------
// ------ jquery.timer -----------------
// -------------------------------------
// Controls a timer placed on the page.
// -------------------------------------

; (function ($, window, document, undefined) {

	var pluginName = "timer";

    function timer(element, options) {
        this.element = element;
        this._name = pluginName;
        this._defaults = $.fn.timer.defaults;
        this.options = $.extend({}, this._defaults, options);

        this.init();

        this.setMessages();
        this.setTime();
    }

	$.extend(timer.prototype, {

		init: function () {
			this.buildCache();

			this.bindEvents();
		},

		destroy: function () {
			this.unbindEvents();
		},

		buildCache: function () {

            this.$element = $(this.element);

            this.totalSeconds = parseInt(this.$element.data("total"));
            this.remainingSeconds = parseInt(this.$element.data("remaining"));

            if (isNaN(this.totalSeconds)) {
                this.totalSeconds = 0;
            }

            if (isNaN(this.remainingSeconds)) {
                this.remainingSeconds = 0;
            }

            if (this.totalSeconds < this.remainingSeconds) {
                this.remainingSeconds = this.totalSeconds;
            }

            this.elapsedSeconds = this.totalSeconds - this.remainingSeconds;

            this.$timerMessageContainer = $(this.options.timerMessageContainerId);
            this.$timerAnnounce = $(this.options.timerAnnounceId);
            this.$mainCell = $(this.options.mainCellId);
            this.$secondaryCell = $(this.options.secondaryCellId);
            this.$progressBar = $(this.options.progressBarId);

            this.refreshIntervalId = null;
        },

		bindEvents: function () {
			var plugin = this;

            if (plugin.options.timerRunning === false) {
                return;
            }

            plugin.refreshIntervalId = setInterval(function() {
                plugin.tick();
            }, 1000);
        },

		unbindEvents: function () {
			var plugin = this;

            clearInterval(plugin.refreshIntervalId);
        },

        setTime: function() {
            var plugin = this;

            var minutesLeft = "00";
            var secondsLeft = "00";

            if (plugin.remainingSeconds > 0) {

                var date = new Date(null);
                date.setSeconds(plugin.remainingSeconds);

                plugin.$element.html(date.toISOString().substr(11, 8));
                plugin.$element.html("Time left to complete this form: " + date.toISOString().substr(11, 8));

                // calculate split units
                minutesLeft = Math.floor(plugin.remainingSeconds / 60);
                secondsLeft = Math.floor(plugin.remainingSeconds % 60);

                if (minutesLeft < 10) {
                    minutesLeft = "0" + minutesLeft;
                }
                if (secondsLeft < 10) {
                    secondsLeft = "0" + secondsLeft;
                }
            }

            plugin.$mainCell.text(minutesLeft);
            plugin.$secondaryCell.text(secondsLeft);

        },

        setMessages: function() {
            var plugin = this;

            if (plugin.elapsedSeconds === 0) {
                plugin.$timerAnnounce.html(plugin.options.startAnnouncement);
                plugin.$timerMessageContainer.html(plugin.options.startMessage);

                return;
            }

            if (plugin.remainingSeconds <= 0) {
                plugin.$timerAnnounce.html(plugin.options.overrunAnnouncement);
                plugin.$timerMessageContainer.html(plugin.options.overrunMessage);
                plugin.$timerMessageContainer.parent().addClass("alert");
                plugin.$progressBar.addClass("alert");

                return;
            }

            plugin.$timerAnnounce.html(plugin.options.inProgressAnnouncement);

            var message = plugin.options.inProgressMessage;

            var remainingTimeDescription = "";

            if (plugin.remainingSeconds < 61) {
                remainingTimeDescription = "Under a minute";
            } else if (plugin.remainingSeconds < 121) {
                remainingTimeDescription = "1 minute";
            } else {
                var minutesLeft = Math.floor(plugin.remainingSeconds / 60);
                remainingTimeDescription = minutesLeft + " minutes";
            }

            message = message.replace("[TimeRemaining]", remainingTimeDescription);

            plugin.$timerMessageContainer.html(message);

        },

        tick: function () {
            var plugin = this;

            plugin.remainingSeconds = plugin.remainingSeconds - 1;
            plugin.elapsedSeconds = plugin.totalSeconds - plugin.remainingSeconds;

            plugin.setMessages();
            plugin.setTime();

            //console.log(plugin.remainingSeconds + " seconds total set with total elapsed count of");

            if (plugin.remainingSeconds <= 0) {
                plugin.$element.html(plugin.options.timerEndedText);

                plugin.$progressBar.attr("aria-valuenow", 0).attr("aria-valuetext", 0 + " percent");
                plugin.$progressBar.find(".progress-meter").css("width", 0 + "%");

                if (plugin.options.overrunAllowed === false) {

                    clearInterval(plugin.refreshIntervalId);

                    setInterval(function () {
                        plugin.options.onTimerReached();
                    }, 3000);

                    return;
                }

                // Now can do something on counting forward

                return;
            }

            // sync progress bar
            var progressLeft = Math.floor((plugin.elapsedSeconds / plugin.totalSeconds) * 100);

            plugin.$progressBar.attr("aria-valuenow", progressLeft).attr("aria-valuetext", progressLeft + " percent");
            plugin.$progressBar.find(".progress-meter").css("width", progressLeft + "%");
        }

	});

    $.fn.timer = function (options) {
        this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new timer(this, options));
            }
        });

        return this;
    };

    $.fn.timer.defaults = {
        timerContainerId: "#timerProgress",
        timerMessageContainerId: "#tpMessage",
        timerAnnounceId: "#tpAnnounce",
        mainCellId: "#minutes_text",
        secondaryCellId: "#seconds_text",
        progressBarId: "#tpProgress",
        hoursText: "hours",
        minutesText: "minutes",
        secondsText: "seconds",
        startAnnouncement: "Time allowed",
        inProgressAnnouncement: "Time remaining",
        overrunAnnouncement: "No time remaining",
        timerEndedText: "Timer ended",
        startMessage: "",
        inProgressMessage: "",
        overrunMessage: "",
        timerRunning: false,
        overrunAllowed: false,
        hideTimerWhenTimedOut: false,
        countTimeAfterTimedOut: false,
        onTimerReached: function() {

        }
    };

})(jQuery, window, document);
