(function($) {

$(function() {
	$.ajax({
		type: 'GET',
		url: 'http://kirtasbooks.com/categorize/categorize_form.php',
		cache: false,
		data: 'product_id=' + $('#product_id').val(),
		success: function(data) {
			$('#categorize').hide();
			$('#categorize_frame').prepend(data);
			$('#ajax_categorize_form').hide();

			// add onclick action to help button
			$('#helpbutton').fancybox({
				'hideOnContentClick': false,
				'frameWidth': 640,
				'frameHeight': 260
			});

			// add onclick action to help button
			$('.fakeraido').live('click', function(e) {
				var src = $(this).attr('src').replace('http://kirtasbooks.com/categorize/', '');

				if(src == 'unchecked.gif') {
					$(this).attr('src', 'http://kirtasbooks.com/categorize/checked.gif');
					$(this).attr('alt', 'checked');

					// update select
					$('#categories option[value='+$(this).attr('title')+']').attr("selected", "selected");
				} else {
					$(this).attr('src', 'http://kirtasbooks.com/categorize/unchecked.gif');
					$(this).attr('alt', 'unchecked');

					// update select
					$('#categories option[value='+$(this).attr('title')+']').removeAttr('selected');
				}

				e.preventDefault();
			});

			// submit suggested categories
			$('#ajax_submit_button').live('click', function(e) {
				// close the fancybox. Wow, Fancy!
				$.fn.fancybox.close();

				// TODO: only submit if they set something

				var data = $('#categorize').serialize();
				//console.debug(data);
				$.ajax({
					type: 'POST',
					url: 'http://kirtasbooks.com/categorize/categorize.php',
					cache: false,
					data: data,
					success: function(data) {
						var product_id = $('#product_id').val();
						$('#helpbutton').remove();
						$('#ajax_categorize_form').remove();

						// deselect all values | this is a must, the following line does not reset the values
						$('#categories').val('');

						$('#categorize').remove();

						// almost like an infinite loop...but not (hopefully)
						$.ajax({
							type: 'GET',
							url: 'http://kirtasbooks.com/categorize/categorize_done.php',
							cache: false,
							data: 'product_id=' + product_id,
							success: function(data) {
								$('#categorize_frame').html(data);
							}
						});
					}
				});

				e.preventDefault();
			});
		}
	});
});

})(jQuery);