(function($) {
	$(document).ready (function () {
		// Don't submit upon enter keypress when in textarea
		var textareaHasFocus = false;
		
		$('textarea')
			.focus (function () { textareaHasFocus = true; })
			.blur (function () { textareaHasFocus = false; });
					
		$(document).keydown (function (event) {
			if (event.keyCode == 13 && !textareaHasFocus) {
				$('div.save input').click ();
			}
		});
		
		// Change product sizes when a different product is selected
		var product_box = $('select#product');
		var size_box = $('select#size');
		
		
		product_box.change (function () {
			var product_name = product_box.val ();

			// Now we have the name of the product selected, AJAX the related sizes
			updateSizes (product_name, size_box);
		});
		
		var updateSizes = function (product_name, size_box) {
			// Disable the boxes until request is complete
			size_box.attr ('disabled', 'disabled');
			
			$.getJSON (
				'/upload/ajx-get-options',
				{
					name: product_name
				},
				function (json) {
					// Save the current selection
					var cur_size_val = size_box.val ();
					
					// Empty the current values
					size_box.empty ();

					// Add the new ones
					$.each (json['sizes'], function (i, size) {
						$('<option value="' + size.replace ('"', '&quot;') + '">' + size + '</option>').appendTo (size_box);
					});
					
					// Reselect the item if it still exists
					$('option[value="' + cur_size_val + '"]', size_box).attr ('selected', 'selected');
					
					// Re-enable boxes
					size_box.attr ('disabled', '');
				}
			);
		};
		
		// It's a bit dodgy, but to make this AJAX stuff and Zend work together, call the change event on document load
		// This is because Zend wants all items loaded at init for validation purposes, but we just want to show the
		// appropriate ones
		
		product_box.change ();
	});
})(jQuery);