// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

/* Refactoring Javascript */
/* Requirements: jQuery */
function modalDialogAjax(url) {
	TINY.box.show(url, 1, 0, 0, 1);
}

function modalDialog(id) {
	TINY.box.show($('#'+id).html(), 0, 0, 0, 1);
}

function modalClose() {
	try { TINY.box.hide(); } catch (e) {}
}

function remoteFormActivity(dom_id) {
	$('#'+dom_id+' .form_activity').css('visibility', 'visible');
	var current_word = $('#'+dom_id+' input[type=submit]').val();
	$('#'+dom_id+' input[type=submit]').val(current_word.indexOf('Send') != -1 ? 'Sending...' : 'Saving...');
}
/* Requirements: jQuery */
function selectTab(handles, container, tab) {
  $(handles + " li").removeClass('selected');
  $(handles + " " + tab.replace('#','.')).addClass('selected');
  $(container + " .tab").hide();
  $(container + " " + tab).show();
}

/* Requirements: jQuery */
function slideMenu(id) {
  /* Hide all submenus */
  $(id + " ul ul").hide();
  /* Create the mouseover actions */
  $(id + " li").mouseover(function() {
    $(this).find("ul").show();
  }).mouseout(function() {
    $(this).find("ul").hide();
  });
}

function toggleCategorizations(elem) {
	elem.closest('div').find('.categorize').toggleClass('hidden');
}

function addOrRemoveItem(elem) {
	var old_parent = elem.closest('div');
	var have_already = !old_parent.hasClass('have_already');
	var clipped = elem.closest('tr').remove();
	showOrHideShoppingListCategory(old_parent);
	if (clipped.hasClass('ingredient')) {
		var destination = have_already ? 'have_already' : clipped.find('option:selected').val();
		destination = (typeof destination == 'undefined') ? 'need_to_purchase' : destination;
		destination = (destination == '') ? 'uncategorized' : destination;
		clipped.find('a').text(have_already ? 'Add' : 'Remove');
		var new_parent = $('.'+destination);
		new_parent.find('table').append(clipped);
		showOrHideShoppingListCategory(new_parent);
	}
	addPageBreaks();
	return false;
}

function showOrHideShoppingListCategory(elem) {
	var num_rows = elem.find('tbody').children().length;
	if (elem.hasClass('empty') && num_rows > 0) {
		elem.removeClass('empty');
	} else if (num_rows == 0) {
		elem.addClass('empty');
	}
}

function addPageBreaks() {
	var page_break_count = 6;
	$('.page_break').removeClass('page_break');
	$('.ingredients_list:visible:not(.have_already)').each(function(i, elem) {
		page_break_count += $(elem).find('tbody').children().length + 2;
		if (page_break_count > 50) {
			$(elem).addClass('page_break');
			page_break_count = $(elem).find('tbody').children().length + 3;
		}
	});
}
/* End Refactoring Javascript */