(function($) {
	var Wacountdown = function(element, options) {

		var defaults = {
			time: 20, // Timer amount in seconds
			lang: {
				text_syntax: "You have !minutes_left minutes left until you will be logged out",
				warning_text: " (<strong>Warning!</strong> You only have !minutes_left minutes left and then you will be logged out!)",
				time_up: "You are out of time"
			},
			update_interval: 1, // In seconds
			warning_text_show: true,
			warning_time: 120, // When to issue an warningtext
			warning_callback: null,
			time_up_callback: null
		};
		var options = $.extend(defaults, options);
		var host = $(element);
		var start_date = null;
		var timer_id = null;
		var warning_callback_called = false;
		var time_up_callback_called = false;

		/**
		 * Methods
		 */
		this.init = function() {
			options.update_interval  = options.update_interval * 1000;
			this.startCountDown();
		}

		this.resetCountDown = function() {
			date = new Date();
			start_date = date.getTime()/1000;
		}

		this.startCountDown = function() {
			timer_id = setInterval(this.updateText, options.update_interval);
			date = new Date();
			start_date = date.getTime()/1000;
			this.updateText();
		}

		this.updateText = function() {
			date = new Date();
			seconds_left = Math.round(options.time+start_date - (date.getTime()/1000));
			minutes_left = Math.ceil(seconds_left/60);
			hours_left = Math.ceil(seconds_left/60/60);
			

			if(seconds_left <= 0) {
				text = options.lang.time_up;
				if(typeof options.time_up_callback == 'function' && !time_up_callback_called) {
					options.time_up_callback();
					time_up_callback_called = true;
				}
			} else {
				text = options.lang.text_syntax;
				if(seconds_left <= options.warning_time && options.warning_time != 0) {
					if(options.warning_text_show) {text += options.lang.warning_text;}
					if(typeof options.warning_callback == 'function' && !warning_callback_called) {
						options.warning_callback();
						warning_callback_called = true;
					}
				}
			}

			text = text.replace(/!hours_left/g, hours_left);
			text = text.replace(/!minutes_left/g, minutes_left);
			text = text.replace(/!seconds_left/g, seconds_left);

			host.html(text);
		}

		this.init();

	}
	/* Wrapper */
	$.fn.wacountdown = function(options) {
		return this.each(function() {
			var element = $(this);

			// Return early if this element already has a plugin instance
			if (element.data('wacountdown')) return;

			// pass options to plugin constructor
			var wacountdown = new Wacountdown(this, options);

			// Store plugin object in this element's data
			element.data('wacountdown', wacountdown);
		});
	};


})(jQuery);
