/**
 * jQuery Scheduling Plugin
 * Author: Craig Nagy craig.nagy AT vancouverradio.rogers.com
 * Version: 2007.11.12
 * Dependencies: jQuery.js, jQuery.metadata.js
 *
 * <div class="schedule {dow: 'dow', stime:'1100', etime:'1400'}">...</div>
 *
 *
 */
(function($) {
					
  // google analytics initialization
	$.fn.schedule = function(options)
	{	
		return this.each(function() {
				new $.schedule(this, options);
		});
	};
	
	$.schedule = function(src, options)
	{
		var self = this; // persistent self reference
		this.source = src; // element to apply scheduling to
		
		this.options = $.extend({
			trackAnchors : true,
			trackFiles : true,
			trackForms : true,
			gmtOffset: -5,
			debug : false,
			fxSpeed : 'slow',
			dowSeparator: ','
		}, options);		
		
		this.schedule();
	};
	
	$.extend($.schedule.prototype, {
			schedule : function() {
						
				var self = this, o = this.options;
				
				// get schedule information stored in the class name
				// using the metadata plugin.
				var meta = $.metadata ? $.metadata.get(self.source) : {};
				
				// get days of the week, convert to integer 0-6 (sun-sat)
				var dow = (meta.dow != null) ? meta.dow.split(o.dowSeparator) : '';
				for(var i=0; i<dow.length; i++) { dow[i] = dayStringToInt(dow[i]); }
				
				var stime = cleanTime(meta.stime);
				var etime = cleanTime(meta.etime);
									
				this.log('[schedule] dow:'+dow+' '+stime+'-'+etime);
				
				if( isDue(dow,stime,etime) ) {
					this.log( 'show this' );
					$(self.source).show(o.fxSpeed);
				}
				
				function isDue(dow,stime,etime)
				{
					var now = new Date();
					var nowDay = now.getDay();
					var nowMin = now.getMinutes();
					if(nowMin < 10) nowMin = '0'+nowMin;
					var nowHrs = now.getHours();
					var nowTime = parseInt(nowHrs+''+nowMin);
					var due = jQuery.inArray(nowDay, dow) > -1 && stime <= nowTime && etime > nowTime;
					self.log(nowDay, nowTime, dow, stime, etime, due);
					return due;
				}
				
				function cleanTime(time)
				{
					if(time.indexOf('0') == 0) {
						time = time.substr(1); // remove leading 0 eg: 0500->500
					}
					return parseInt(time); // convert to integer
				}
				
				function dayStringToInt(day)
				{
					var dow = new Array(7);
					dow['sun']=0;
					dow['mon']=1;
					dow['tue']=2;
					dow['wed']=3;
					dow['thu']=4;
					dow['fri']=5;
					dow['sat']=6;
					return dow[day.substr(0,3).toLowerCase()];
				}
			
			},
			log : function() {
				if(!this.options.debug) return;
				if( window.console )
					console.debug.apply( console, arguments );
				else
					alert( [].join.apply( arguments, [' '] ) );
			}
			
	});
		
})(jQuery);
