/* jQuery timepicker
 * replaces a single text input with a set of pulldowns to select hour, minute, and am/pm
 *
 * Copyright (c) 2007 Jason Huck/Core Five Creative (http://www.corefive.com/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 1.0.1
 * Изменил Иван Чурюмов 16:15 17 ноября 2009 г.
 */

(function($){
	jQuery.fn.timepicker = function( customOptions ){
	
		var options = {
		
				containerClass: 'timepicker_input_container'				// Class for container that wraps this widget			
			};

		$.extend(options, customOptions); 
	
		this.each(function(){
			// get the ID and value of the current element
			var i = this.id;
			var v = $(this).val();
	
			// the options we need to generate
			var hrs = new Array('00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23');
			var mins = new Array('00','15','30','45');
						
			// default to the current time
			var d = new Date;
			var h = d.getHours();
			var m = d.getMinutes();
			
			// override with current values if applicable
			if(v.length > 3){
				h = parseInt(v.substr(0,2));
				m = parseInt(v.substr(3,2));			
			}
				
			// round minutes to nearest quarter hour
			for(mn in mins){
				if(m <= parseInt(mins[mn])){
					m = parseInt(mins[mn]);
					break;
				}
			}			
			
			// build the new DOM objects
			var output = '';
			
			output += '<select id="h_' + i + '" class="h timepicker">';				
			for(hr in hrs){
				output += '<option value="' + hrs[hr] + '"';
				if(parseInt(hrs[hr]) == h) output += ' selected';
				output += '>' + hrs[hr] + '</option>';
			}
			output += '</select>';
	
			output += '<select id="m_' + i + '" class="m timepicker">';				
			for(mn in mins){
				output += '<option value="' + mins[mn] + '"';
				if(parseInt(mins[mn]) == m) output += ' selected';
				output += '>' + mins[mn] + '</option>';
			}
			output += '</select>';			

			output += '<div class="'+options['containerClass']+'"></div>';	
	
			// hide original input and append new replacement inputs
			$(this).after(output);
			
			$(this).prependTo('div.'+options['containerClass']);
		});
		
		$('select.timepicker').change(function(){
			var i = this.id.substr(2);
			var h = $('#h_' + i).val();
			var m = $('#m_' + i).val();
			var v = h + ':' + m ;//+ p;
			$('#' + i).val(v);
		});
		
		return this;
	};
})(jQuery);


