Event.observe(window, 'load', function() {

	if ($$('input.autofocus').length)
		$$('input.autofocus').first().focus();

	initInputs();
	
});

var defaultValues = $H();

function initInputs() {

	var inputs = arguments.length ? arguments[0].select('input.inactive') : $$('input.inactive');
	
	// Handle text inputs with default values
	inputs.each(function(input) {

		// The default values of the text inputs, used for comparison
//		var defaultValues = $H();

		defaultValues.set(input.identify(), input.value);

		// Check if the default text is still there, and if it is, remove it
		input.observe('focus', function(e) {

			var obj = e.element();

			if ($F(obj) == defaultValues.get(input.identify())) {
				obj.value = '';
				obj.removeClassName('inactive');
			}
			
		});
		
		// Check if the text input is empty, and if so, put the default text back in
		input.observe('blur', function(e) {
		
			var obj = e.element();
			
			if ($F(obj) == '') {
				obj.value = defaultValues.get(input.identify().replace('MB_', ''));
				obj.addClassName('inactive');
			}
		
		});
		
	});
	
	// Initialize the phone number auto-tabbing
	var inputs = arguments.length ? arguments[0].select('input.phoneArea') : $$('input.phoneArea');
	
	inputs.each(function(input) {

		// Check to see if the user just typed the 3rd letter of an area code
		input.observe('keyup', function(e) {
			
			// If the area code field is full
			if (this.value.length == 3) {
			
				// Check if the key pressed was a number from the numbers across the top of the keyboard (keycode 48 - 57) and the keypad both (keycode 96 - 105)
				if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105))
					Event.element(e).next().focus();
			
			}
			
		});
		
		// Check to see if the user is trying to type in an area code field that already has 3 digits
		input.observe('keydown', function(e) {
		
			// If the area code field is full
			if (this.value.length == 3) {
					
				// Check to see if any text is currently selected, and if so, let the browser handle the input
				var start = getSelectionStart(this);
				var end = getSelectionEnd(this);
				var selection = start != end;
			
				// Check if the key pressed was a number from the numbers across the top of the keyboard (keycode 48 - 57) and the keypad both (keycode 96 - 105)
				if (!selection && ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105))) {
					Event.stop(e);
					return;
				}
					
			}
		
		});
	
	});

	// Initialize the date picker inputs
	var inputs = arguments.length ? arguments[0].select('input.datepicker') : $$('input.datepicker');

	inputs.each(function(input) {

		input.setAttribute('autocomplete', 'off');
	
		new Control.DatePicker(input, {
			dateFormat: 'MM/dd/yyyy',
			icon: '/_images/icons/calendar.png',
			onDateSelect: function(input) {
				input.removeClassName('inactive');
			}
		});
		
		input.observe('blur', datePickerBlur);
		input.observe('keydown', datePickerKeyDown);
		
	});
	
	
	// Initialize the time picker inputs
	var inputs = arguments.length ? arguments[0].select('input.timepicker') : $$('input.timepicker');

	inputs.each(function(input) {

		input.setAttribute('autocomplete', 'off');
	
		new Control.DatePicker(input, {
			datePicker: false, 
			timePicker: true, 
			timeFormat: 'h:mm a', 
			icon: '/wide_images/icons/time.png',
			onDateSelect: function(input) {
				input.removeClassName('inactive');
			}
		});
		
	});
	
}

function datePickerBlur(e) {
		
	var obj = Event.element(e);

	// If the date only has a 2-digit year, add '19' or '20' in front of it to make it 4-digit
	if (/^\d{2}\/\d{2}\/\d{2}$/.match(obj.value)) {
		
		var regs = /(\d{2}\/\d{2}\/)(\d{2})/.exec(obj.value);
		
		var today = new Date();
		var year = parseInt(regs[2]);

		obj.value = regs[1] + (year < today.getYear() - 90 ? '20' : '19') + regs[2];
		
		alert('All dates require a 4-digit year. This field has been automatically corrected for you.');
		
	}
	

}
		
function datePickerKeyDown(e) {

	// Make sure Control, Alt, and Windows/Command aren't being pressed or held down to allow Select All, Refresh, and other
	// commands to still be ran while this field has focus
	if (!(e.keyCode == 91 && e.keyCode == 17 && e.keyCode == 18) && !(e.altKey || e.ctrlKey || e.metaKey)) {
			
		var obj = Event.element(e);
			
		// Check to see if any text is currently selected, and if so, let the browser handle the input
		var start = getSelectionStart(obj);
		var end = getSelectionEnd(obj);
		var selection = start != end;

		if (!(selection && ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)))) {

			// If '/' is pressed and there is a single digit by itself (ie: '1/' or '11/3/'), add a '0' in front of it (ie: '01/' and '11/03/')
			if (e.keyCode == 191 || e.keyCode == 111) {

				var value = obj.value;

				// Skip an empty string, string lengths where a slash occurs naturally, and the end a completed date string
				if (value.length == 1 || value.length == 4) {
					obj.value = value.substring(0, value.length - 1) + '0' + value[value.length - 1] + '/';
				} else if (value.length == 2 || value.length == 5)
					obj.value += '/';

				Event.stop(e);
				return;

			// If any key other than a number (on the keyboard and keypad both) or specialty keys (home, end, page down, shift, etc), ignore it
			} else if (((e.keyCode > 57 && e.keyCode < 91) || e.keyCode > 105)) {
				Event.stop(e);
				return;
			}

			// If a number key is pressed, reformat the input
			if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
								
				if (obj.value.length == 10) {
					
					Event.stop(e);
					return;
				}
			
				// If the numbers on the number pad are used, give them the same key values as the normal number buttons
				var keyCode = e.keyCode >= 96 ? e.keyCode - 48 : e.keyCode;
				
				// Remove any non-numeric values from the string
				var tmpValue = obj.value.replace(/\D/g, '');// + String.fromCharCode(keyCode);

				var finalValue = '';
				
				// Cycle through max number of digits (8) to a date, and auto-insert slashes
				for (var i = 0; i < 8; i++) {
					if (tmpValue[i])
						finalValue += tmpValue[i] + (i == 1 || i == 3 ? '/' : '');
					else
						break;
				}

				// Set the formatted string to the object
				obj.value = finalValue;
				
			}
			
		}
		
	}
	
}



/***************************************
	Debugger
 ***************************************/
 
Event.observe(window, 'load', function() {

	if ($('debug')) {
	
		$('debugClosebox').observe('click', hideDebugger);
		
		// Bind Command+Shift+D to show the debugger
		Hotkeys.bind('left-win+alt+shift+d', showDebugger);
		
		// If debug was called from inside of a hidden element, show it
		var obj = $('debug').up();
		
		while (obj && obj.tagName != 'BODY') {
			if (obj.visible && !obj.visible()) obj.show();
			obj = obj.up();
		}
		
	}

});

function showDebugger() {
	if ($('debug') && !$('debug').visible()) {
		new Effect.Appear('debug', { duration: 0.5 });
		Hotkeys.bind('esc', hideDebugger);
	}
}

function hideDebugger() {
	new Effect.Fade('debug', { duration: 0.5 });
	Hotkeys.release();
	Hotkeys.bind('left-win+shift+d', showDebugger);
}

