/*
 * MapMyFitness Timepicker
 */
$(function(){
	/*********************** 
	** 
	************************/
	$.fn.timepicker = function( options ) {
		
		//Set Defaults
		
		var opts = $.extend({}, $.fn.timepicker.defaults, options);
		
		if($.isFunction($._)) {
            H = $._('H');
			_H = $._('H');
            M = $._('M');
			_M = $._('M');
            S = $._('S');
			_S = $._('S');
        } else {
            H = 'H';
			_H = 'H';
            M = 'M';
			_M = 'M';
            S = 'S';
			_S = 'S';
        }
        
        var hours_name = "";
        var minutes_name = "";
        var seconds_name = "";
        var ampm_name = "";
        
		var current_time = "";
		
        var duration = opts.duration === true ? true : false;
        var locale = opts.is24hr === true ? 24 : 12;
		var show_hours = opts.show_hours === true ? true : false;
		
		var hidden_field = $(this);
		
		hours_name  = hidden_field.attr('name')+'_hours';
        hours_field = '<input id="id_' + hours_name + '" name="' + hours_name + '" type="text" maxlength="2" class="timepicker_time hours" autocomplete="off"/> ';//+': '
        
        minutes_name  = hidden_field.attr('name')+'_minutes';
        minutes_field = '<input id="id_' + minutes_name + '" name="' + minutes_name + '" type="text" maxlength="2" class="timepicker_time minutes" autocomplete="off"/> ';// + ': '
        
        seconds_name  = hidden_field.attr('name')+'_seconds';
        seconds_field = '<input id="id_' + seconds_name + '" name="' + seconds_name + '" type="text" maxlength="2" class="timepicker_time seconds" autocomplete="off"/>'; 
        
        ampm_name  = hidden_field.attr('name')+'_ampm';
        ampm_field = '<select id="id_' + ampm_name + '" name="' + ampm_name + '" class="timepicker_time" autocomplete="off"><option value="1">AM</option><option value="2">PM</option></select>  ';
   		
		if( show_hours === true ){
        	hidden_field.before(hours_field);
		}
        
        hidden_field.before(minutes_field);
        
		if( duration === true ){
        	hidden_field.before(seconds_field);
		}
		
        // Selectively Show AM/PM Dropdown
        // If a Duration Time + 12 Hour Mode
        if(!duration && locale == 12) {
        	hidden_field.before(ampm_field);
        }
        
		
        // Set Time
		if(hidden_field.val()) {
			if( duration === true ){
				
				current_time = hidden_field.val().split(' ');
				
				if( (current_time instanceof Array)===true && current_time.length == 2  && current_time[0] != "0.0" && current_time[0] != "0" ){
					H = Math.floor(current_time[0] / (60*60));
					M = Math.floor((current_time[0] - (H*60*60) ) / 60);
					S = (current_time[0] - (H*60*60) - (M*60));
					
					if( show_hours === true ){
						$('#id_' + hours_name).val(H);
					}
					
					$('#id_' + minutes_name).val(M);
					$('#id_' + seconds_name).val(S);
				}
			} else {
				
				current_time = hidden_field.val().split(':');
				
				if((current_time instanceof Array)===true && current_time.length >= 2 && current_time.length <= 3 ) {
					H = current_time[0];
					M = current_time[1];
					if( locale == 12) {
						// Handle 2400 Hours
						if(H == 0) {
							H = 12;
							$('#id_' + ampm_name).val(1);
						}
						// Handle PM
						else if(H > 12) {
							H -= 12;
							$('#id_' + ampm_name).val(2);
						} else if(H == 12){
							$('#id_' + ampm_name).val(2);
						}
					}
					
					$('#id_' + hours_name).val(H);
					$('#id_' + minutes_name).val(M);
				}
			}
		}
		
		// Set Validation Rules
		if( show_hours === true ){
			$('#id_' + hours_name).rules('add', {
				required: false,
				//min: 0,
				digits: true
			});
			
			$('#id_' + hours_name).keyup(function(){
				forceNumber($(this));
			});
		}
        
        $('#id_' + minutes_name).rules('add', {
        	required: false,
        	digits: true
        });
		
		$('#id_' + minutes_name).keyup(function(){
			forceNumber($(this));
		});
        
		if( duration === true ){
			$('#id_' + seconds_name).rules('add', {
				required: false,
				digits: true
			});
			
			$('#id_' + seconds_name).keyup(function(){
				forceNumber($(this));
			});
		}
        
        // Bind to Update
		if( show_hours === true ){
        	$('#id_' + hours_name).bind('blur', function(){updateTime(duration, show_hours, locale, hidden_field);});
		}
		
        $('#id_' + minutes_name).bind('blur', function(){updateTime(duration, show_hours, locale, hidden_field);});
        
		if( duration === true ){
			$('#id_' + seconds_name).bind('blur', function(){updateTime(duration, show_hours, locale, hidden_field);});
		}
        
        // Bind to Form Submits (if never blurred)
        $('form').bind('submit', function(){updateTime(duration, show_hours, locale, hidden_field);});
		
        // Bind to AM/PM
        if(!duration && locale == 12) {
        	$('#id_' + ampm_name).bind('change', function(){updateTime(duration, show_hours, locale, hidden_field);});
        }
                	
        
        // Politely Add Watermarking if Possible
        // Watermarking Available, No Times Provided...
        if($.isFunction($.fn.watermark)) {
        	if( show_hours === true ){
				$('#id_'+hours_name).watermark(_H+_H);
			}
			
        	$('#id_'+minutes_name).watermark(_M+_M);
        	
			if( duration === true ){
				$('#id_'+seconds_name).watermark(_S+_S);
			}
        }
        
        // Hide Original this
        hidden_field.addClass('hidden')
        //hidden_field.attr('disabled','disabled')
	};
	
    $.fn.timepicker.defaults = {
		duration: false,
		is24hr:	true,
		show_hours: true
	};
	
});


// Update
function updateTime(is_duration, show_hours, locale, element) {
	var hours_name  = $(element).attr('name')+'_hours';
	
	var minutes_name  = $(element).attr('name')+'_minutes';
	
	var seconds_name  = $(element).attr('name')+'_seconds';
	
	var ampm_name  = $(element).attr('name')+'_ampm';
	
	var time = "";
	
	if( is_duration === true ){
		if( show_hours === true ){
			H = $('#id_' + hours_name).val() || 0; 
			H = parseInt(H,10) == H ? H : 0;
			H = H*1;
		} else {
			H = 0;
		}
		
		M = $('#id_' + minutes_name).val() || 0;
		S = $('#id_' + seconds_name).val() || 0;
		
		M = parseInt(M, 10) == M ? M : 0;
		S = parseInt(S, 10) == S ? S : 0;
		
		//Make sure they get converted to numbers
		
		M = M*1;
		S = S*1;
		
		time = (H * 60 * 60) + (M * 60) + (S);
		
		$(element).val(time);
		
	} else {
		H = $('#id_' + hours_name).val();     	
		M = $('#id_' + minutes_name).val();
		
		if( H != "" || M != "" ){
			H = parseInt(H, 10) == H ? H : "00";
			M = parseInt(M, 10) == M ? M : "00";
		
			if( locale == 12 && $('#id_' + ampm_name).val() == 2) {
				H = parseInt(H, 10)+12;
				// Set 12:00 pm back to 12.
				if(H == 24) {
					H = 12;
				}
			} else if( locale == 12 && $('#id_' + ampm_name).val() == 1 && H == 12 ){
				// Set 12:00 am back to 00:00:00.
				H = "00";
			}
			
			time = H + ':' + M ;
		}
		
		$(element).val(time);
	}
}

function forceNumber(element) {
	if( typeof element != 'object' )
		element = $( '#' + element )
	var y = element.val();
	y = y.replace(/\s+/g, "");
	y = y.replace(/[A-z]/g, "");
	y = y.replace(/[\,\?!\s]/g, "");
	element.val(y);
}
