$().ajaxError(function(){
	$('a.loading').removeClass('loading');
	
	if (window.console && window.console.error)
		window.console.error(arguments);
}); 

$.ajaxSetup({ cache: false });

var cache = {};

function unload_result(callback) {
	$('div.result')
		.slideUp(700, function(){ 
			if (this.parentNode) $(this).remove();
			if (callback) callback();
		})
		.parent().find('a:first').click(get_result);
	return false;
}

function load_result(href) {
	var link = $('a[@href='+ href + ']'),
		container = link.parent();
	
	// don't do anything if there is already a result there
	if ($('> div.result', container)[0]) return;

	unload_result(attach_quantity_controls);
	
	$('<div class="result">')
		.append(cache[href])
		.hide()
		.appendTo(container)
		.slideDown(700);

	link.unbind('click').one('click', function(e){
		unload_result();
		return false;
	});

	init_date_picker();
	
	attach_quantity_controls();
}

function get_result(){
	var link = $(this),
		href = this.href;
	
	if (link.is('.loading')) return false;
	
	if (!cache[href]) {
		link.addClass('loading');
		
		$.get(href, function(html){
			// strip out any script tags
			html = html.replace(/<\/?script[^>]*>/ig, '');

			// take the contents of the <div id="staticnutritiondata">
			html = $('<div/>').html(html).find('#staticnutritiondata').html();
			
			// take out the update serving button
			html = html.replace('<input type="submit" value="Update Serving"/>', '');

			link.removeClass('loading');

			cache[href] = html;
			load_result(href);
		});
	} else {
		load_result(href);
	}
	
	return false;
}


$(function(){
	$('#results').paginate();
			
	$('#results a, ul.results a.resultlink').click(get_result);
});