$(document).ready( function() {

	var check_agent = function() {
	
		if( $('#agent_check').is(':checked') ) {
		
			$('#agent_info').show();
			$('#visitor_info').hide();
		} else {
		
			$('#agent_info').hide();
			$('#visitor_info').show();
		}
	};

	check_agent();
	$('#agent_check').click( check_agent );	
	
	//AUTOSAVE COMMENTS
	$('#comments').blur( function() {
		$.get( 'requests.php5', { 'ajax_save_comments' : $(this).val() });
	});
	
	//AUTOSAVE DATES
	$('input.date_in,input.date_out').blur( function() {
		var row = $(this).closest('tr');
		$.get( 'requests.php5', { 
			'ajax_save_date' : true,
			'id' : row.find('input.product_id').val(),
			'type' : row.find('input.product_type').val(),
			'date_in' : row.find('input.date_in').val(),
			'date_out' : row.find('input.date_out').val()
		});
	});
	
	var date_cal_opts = { 
		changeMonth: false,
		showAnim: 'fadeIn',
		dateFormat: 'mm/dd/yy',
		onSelect: function() { 
			
			// CALCULATE PRODUCT DATE OUT
			var row = $(this).closest('tr');	
			if( row.find('input.product_type').val() == 'tour' ) {
			
				var days = row.find('input.product_days').val();
				
				var dt = new Date($(this).val());				
				dt.setDate(dt.getDate()+parseInt(days) );
			
				var m = zeroPad( dt.getMonth()+1, 2 );
				var d = zeroPad( dt.getDate(), 2 );
				var y = zeroPad( dt.getYear(), 2 );
				
				row.find('input.date_out').val( m+"/"+d+"/"+y );
			}
			
			$(this).blur();
		}
	};
	
	// DISABLE DATE OUTS FOR PRODUCTS
	$('input.date_out').each( function() {
	
		var row = $(this).closest('tr');
		if( row.find('input.product_type').val() == 'tour' ) {
		
			$(this).attr('readonly', true );
			$(this).addClass('disabled');
		} else {
		
			$(this).datepick( date_cal_opts );
		}
	});
	
	$('input.date_in').datepick( date_cal_opts );
});

// n = number you want padded
// digits = length you want the final output
function zeroPad(n, digits) {
	n = n.toString();
	while (n.length < digits) {
		n = '0' + n;
	}
	return n;
}