/*! jQuery Countdown Plugin
* Copyright 2011 Tom Ellis http://www.webmuse.co.uk
* Licensed under MIT License
* See http://www.webmuse.co.uk/license/
*/
(function($) {
   
	jQuery.fn.countdown = function( options ) {  
	
		var defaults = {
				date: (new Date()),
				updateTime: 1000,
				htmlTemplate: "%{d} <span class=\"small\">days</span> %{h} <span class=\"small\">hours</span> %{m} <span class=\"small\">mins</span> %{s} <span class=\"small\">sec</span><b>event countdown</b>",
				minus: false
			},
			opts = {},
			rDate = /(%{d}|%{h}|%{m}|%{s})/g,
			rDays = /%{d}/,
			rHours = /%{h}/,
			rMins = /%{m}/,
			rSecs = /%{s}/,
			rDays = /%{d}/,
			cancel = false,
			template;
		   
		$.extend( opts, defaults, options );
		
		template = opts.htmlTemplate;
	   
		return this.each(function() {
		
			var $this = $(this),
				intval;
				
			intval = window.setInterval(function(){
				
				var TodaysDate = new Date(),
					CountdownDate = new Date( opts.date ),
					msPerDay = 24 * 60 * 60 * 1000,
					timeLeft = (CountdownDate.getTime() - TodaysDate.getTime()),
					e_daysLeft = timeLeft / msPerDay,
					daysLeft = Math.floor(e_daysLeft),
					e_hrsLeft = (e_daysLeft - daysLeft)*24, //Gets remainder and * 24
					hrsLeft = Math.floor(e_hrsLeft),
					minsLeft = Math.floor((e_hrsLeft - hrsLeft)*60),					
					e_minsleft = (e_hrsLeft - hrsLeft)*60, //Gets remainder and * 60
					secLeft = Math.floor((e_minsleft - minsLeft)*60),
					time = "";

				if ( TodaysDate <= CountdownDate || opts.minus ) {
					time = template.replace( rDays, daysLeft ).replace( rHours, hrsLeft ).replace( rMins, minsLeft ).replace( rSecs, secLeft );
				} else {
					time = template.replace( rDate, "00");
					cancel = true;
				}
			   
				$this.html( time );
			   
				if ( cancel ){
					cancel = false;
					clearInterval( intval );
				}       		
			
			}, opts.updateTime);

		});
	};
       
})(jQuery);
