(function($) {
	$.fn.timetable = function(o) {
		o = $.extend({
			min: '10:00',
			max: '3:00',
			slider: true
		}, o || {});
	
		return this.each(function(){
			var table = $(this).find('table:first');
			table.find('tr:last').addClass('last');
			
			var k1 = 3600000;
			var k2 = 60000;
			
			o.min = timeStringToMilliseconds(o.min);
			o.max = timeStringToMilliseconds(o.max);

			if(o.slider) {
				var spans = table.find('td span');
				spans.each(function(index){
					var cTime = timeStringToMilliseconds($(this).text());
					if (cTime < o.min) cTime += (24*k1);
					$(this).attr('time', cTime);
				});
				
				if (o.max < o.min) o.max+=(24*k1);
				if ($.fn.slider != undefined) {
					$(this).append('<div id="slider"></div>');
					$(this).find( "#slider" ).slider({
						value: getTimeInMilliseconds(),
						min: o.min,
						max: o.max,
						step: k2,
						create: function (event, ui) {
							var h = 0;
							table.find('tbody tr').each(function(){
								h += $(this).outerHeight(true);
							});
							var handle = $(this).find('.ui-slider-handle');
							handle.css('height', parseInt(h)-15+Math.abs(parseInt($(this).css('top')))+'px')
								.html(getTimeToString());
							func(getTimeInMilliseconds());
						},
						slide: function(event, ui) {
							getTimeToString(ui.value);
							$(ui.handle).html(getTimeToString(ui.value));
							func(ui.value);
						}
					});
				}
			}
			
			function getTimeInMilliseconds() {
				var time = new Date();
				return ((time.getHours() * 60 + time.getMinutes())*k2);
			}
			function getTimeToString(time) {
				if (time === undefined) {
					var time = new Date();
					var hours = time.getHours();
					var minutes = time.getMinutes();
				} else {
					var hours = Math.floor(time/k1);
					var minutes = Math.ceil((time - hours * k1)/k2);
				}
				if (hours > 23) hours -=24;
				if (minutes < 10) minutes = '0'+minutes; 
				return (hours+':'+minutes);
			}
			function timeStringToMilliseconds(time) {
				time = time.split(':', 2);
				return time[0]*k1 + time[1]*k2;
			}
			
			function func(time) {
				spans.each(function(index){
					if ($(this).attr('time') <= time) {
						$(this).addClass('disable');
					} else {
						$(this).removeClass('disable');
					}
				});
			}
				
			var row = table.find('tbody tr');
			var col = new Array(4);
			for(i=0; i<4; i++) {
				col[i] = row.find('td:eq('+i+')');
			}

			table.find('thead th a').each(function(index){
				$(this).attr('rel', index);
				$(this).toggle(
					function(){
						col[index].addClass('selected');
					},
					function(){
						col[index].removeClass('selected');
					}
				);
			});

			row.hover(
				function(){
					$(this).addClass('hover');
				},
				function(){
					$(this).removeClass('hover');
				}
			);
			
		});
	}
})(jQuery);
