var addIngredientPopup = null;

function handleChangeIgnoreWarnings(checkbox) {
	var newVal = 'false';
	if ( checkbox.checked ) {
		newVal = 'true';
	}
	checkbox.form.elements['ignoreWarnings'].value = newVal;
}

function getRecipeIngredientIdField(nameField) {
	var fieldId = nameField.id;
	var idFieldId = fieldId.replace(/\.([^.]+)\.name$/, '.$1.$1Id');
	return document.getElementById(idFieldId);
}

function toggleIngredientType() {
	var currentlyRecipe = $(this).hasClass('recipe');
	if ( currentlyRecipe ) {
		$(this).removeClass('recipe').addClass('ingredient');
	} else {
		$(this).addClass('recipe').removeClass('ingredient');
	}
	$(this).nextAll('div').each(function() {
		$(this).toggle();
		var div = this;
		$(this).find('input').each(function() {
			// clear out current value, and focus if this is the visible field
			$(this).val('');
			if ( $(div).is(':visible') ) {
				$(this).get(0).disabled = false;
				if ( $(this).is(':text') ) {
					$(this).focus().select();
				}
			} else {
				$(this).get(0).disabled = true;
			}
		});
	});
	return false;
}

function handleIngredientFocus(event) {
	$(this).data('startingValue',$(this).val());
}

function handleIngredientBlur(event) {
	console.log("blur: ", this, event, $(this).data('startingValue'), $(this).val());
	if ( $(this).parent().get(0).id.match('ingredient$') 
			&& $(this).data('startingValue') != $(this).val() ) {
		var idField = $(getRecipeIngredientIdField(this));
		idField.val('');
		// pop-up new ingredient now
		console.log("unknown ingredient " +$(this).val());
		addRecipeIngredient(this);
	}
}

function handleIngredientSearchResult(event, data, formatted) {
	console.log("chose ingredient result: ", data, "; ", formatted);
	$(getRecipeIngredientIdField(this)).val(data[1]);
	$(this).data('startingValue', $(this).val());
}

function addRecipeIngredient(input) {
	var rowIndex = input.id.match(/\[(\d+)\]/);
	if ( rowIndex ) {
		rowIndex = rowIndex[1];
	} else {
		return;
	}
	
	var url = webContext +'/addRecipeIngredient.do?mode=recipe.ingredient['
		+rowIndex +'].ingredient.name' 
		+'&ingredient.name=' +$(input).val();
	
	var width = 500;
	var height = 300;
	var top = (screen.height - height ) / 2;
	var left = (screen.width - width ) / 2;
	
	var windowOpts = "titlebar,toolbar=no,resizable,scrollbars,left=" +left 
		+",top=" +top +",width=" +width +",height=" +height;
	if ( addIngredientPopup != null && !addIngredientPopup.closed ) {
		addIngredientPopup.close();
	}
	addIngredientPopup = window.open(url, "add_ingredient", windowOpts);
	addIngredientPopup.focus();
}

function addedNewIngredient(elementId, ingredientId, ingredientName) {
	console.log("New ingredient added at [%s]: %s (%s)", elementId, ingredientId, ingredientName);
	var field = document.getElementById(elementId);
	$(field).val(ingredientName);
	$(getRecipeIngredientIdField(field)).val(ingredientId);
	$(field).data('startingValue', ingredientName);
}

function addIngredientRow() {
	var newRow = $('#ingredient_table > tbody > tr:first').clone().insertBefore('#ingredient_add_row');
	
	// remove 'id' attribute
	newRow.removeAttr('id');
	
	// clear out quantity, qualifier, ingredient/recipe name
	newRow.find('input:text,input:hidden').val('');
	
	// set new unit and ingredient to selected index 0
	newRow.find('input:select').each(function() {
		this.selectedIndex = 0;
	});
	
	// make the 'minus' button appear
	newRow.find('a.minus').show();
	
	updateIngredientRowIndexValues(newRow.get(0));

	applyIngredientRowBehaviors(newRow.get(0));
	
	if ( newRow.tableDnDUpdate ) {
		$('#ingredient_table').tableDnDUpdate();
	}
	
	newRow.find('input:text[name*=quantity]').focus();
	
	return false;
}

function addStepRow() {
	var newRow = $('#step_table > tbody > tr:first').clone().insertBefore('#step_add_row');
	
	// remove 'id' attribute
	newRow.removeAttr('id');
	
	// clear out contents
	newRow.find('textarea').val('').focus();
	
	// make the 'minus' button appear
	newRow.find('a.minus').show();
	
	updateStepRowIndexValues(newRow.get(0));
	
	applyStepRowBehaviors(newRow.get(0));
	
	if ( newRow.tableDnDUpdate ) {
		$('#step_table').tableDnDUpdate();
	}
	
	return false;
}


function updateIngredientRowIndexValues(row) {	
	var myIndex = $(row).prevAll('tr.recipe-ingredient').size();
	
	// find all 'name' attributes, and increment index values
	replaceAttribute(row,'name','ingredient\\[\\d+\\]',
		'ingredient[' +myIndex +']');

	// find all 'id' attributes, and increment index values
	replaceAttribute(row,'id','ingredient\\[\\d+\\]',
		'ingredient[' +myIndex +']');
}

function updateStepRowIndexValues(row) {	
	var myIndex = $(row).prevAll('tr.recipe-step').size();
	
	// find all 'name' attributes, and increment index values
	replaceAttribute(row,'name','step\\[\\d+\\]', 'step[' +myIndex +']');
}

function applyAutocomplete(el) {
	if ( !$(el).autocomplete ) {
		return;
	}
	$(el).find(".ingredient-autocomplete")
	.focus(handleIngredientFocus)
	.blur(handleIngredientBlur)
	.autocomplete("/ieat/ingredientSearch.json", {
		extraParams: {
			approximateSearch: 'true',
			recipeSearch: 'false'
		},
		dataType: 'json',
		autoFill: false,
		parse: function (data) {
			var searchResults = data[ 'magoffin.matt.xweb.MODEL'];
			console.log("Got ingredient searchResults: ", searchResults);
			var results =[];
			for (var i = 0; i < searchResults.ingredient.length; i++) {
				var ing = searchResults.ingredient[i];
				results[results.length] = {
					data:[ing.name, ing.ingredientId],
					value: ing.name,
					result: ing.name
				};
			}
			return results;
		}
	}).result(handleIngredientSearchResult);
	
	$(el).find(".recipe-autocomplete")
	.focus(handleIngredientFocus)
	.blur(handleIngredientBlur)
	.autocomplete("/ieat/ingredientSearch.json", {
		extraParams: {
			approximateSearch: 'false',
			recipeSearch: 'true'
		},
		dataType: 'json',
		autoFill: false,
		parse: function (data) {
			var searchResults = data[ 'magoffin.matt.xweb.MODEL'];
			console.log("Got recipe searchResults: ", searchResults);
			var results =[];
			for (var i = 0; i < searchResults.recipe.length; i++) {
				var ing = searchResults.recipe[i];
				results[results.length] = {
					data:[ing.name, ing.recipeId],
					value: ing.name,
					result: ing.name
				};
			}
			return results;
		}
	}).result(handleIngredientSearchResult);
}

function applyRecipeTypeChooser(el) {
	$(el).find('a.ingredient-type-chooser').click(toggleIngredientType);
}

function removeIngredientRow() {
	var ingredientIndex = $(this).parents('tr.recipe-ingredient').prevAll('tr.recipe-ingredient').size();
	console.log("remove ingredient row %d: ", ingredientIndex);
	
	if ( ingredientIndex < 1 ) {
		alert(XwebLocale.i18n('noDeleteFirstIngredient'));
		return;
	}
	
	// remove selected ingredient from table
	$(this).parents('tr.recipe-ingredient').remove();
	
	// update form field index values for ingredients *after* the removed one
	console.log("update index values >%d: ", ingredientIndex-1);
	$('#ingredient_table tr.recipe-ingredient:gt(' +(ingredientIndex-1) +')').each(function() {
		updateIngredientRowIndexValues(this);
	});
	
	return false;
}

function removeStepRow() {
	var stepIndex = $(this).parents('tr.recipe-step').prevAll('tr.recipe-step').size();
	console.log("remove step row %d: ", stepIndex);
	
	if ( stepIndex < 1 ) {
		alert(XwebLocale.i18n('noDeleteFirstStep'));
		return;
	}
	
	// remove selected ingredient from table
	$(this).parents('tr.recipe-step').remove();
	
	// update form field index values for ingredients *after* the removed one
	console.log("update index values >%d: ", stepIndex-1);
	$('#step_table tr.recipe-step:gt(' +(stepIndex-1) +')').each(function() {
		updateStepRowIndexValues(this);
	});
	
	return false;
}

function applyRecipeIngredientRemove(el) {
	$(el).find('a.minus').click(removeIngredientRow);
}

function applyRecipeStepRemove(el) {
	$(el).find('a.minus').click(removeStepRow);
}

function applyIngredientRowBehaviors(el) {
	applyAutocomplete(el);
	applyRecipeTypeChooser(el);
	applyRecipeIngredientRemove(el);
}

function applyStepRowBehaviors(el) {
	applyRecipeStepRemove(el);
}

$(document).ready(function () {
	$('#ingredient_add_link').click(addIngredientRow);
	$('#step_add_link').click(addStepRow);
	applyIngredientRowBehaviors($('#ingredient_table').get(0));
	applyStepRowBehaviors($('#step_table').get(0));
	if ( $(this).tableDnD ) {
		$("#ingredient_table").tableDnD({
			onDragClass: 'in-drag',
			onDrop: function(table, row) {
				$(table).find('tr.recipe-ingredient').each(function(i) {
					updateIngredientRowIndexValues(this);
					if ( i > 0 ) {
						$(this).find('a.minus').show();
					} else {
						$(this).find('a.minus').hide();
					}
				});
			}
		});
		$("#step_table").tableDnD({
			onDragClass: 'in-drag',
			onDrop: function(table, row) {
				$(table).find('tr.recipe-step').each(function(i) {
					updateStepRowIndexValues(this);
					if ( i > 0 ) {
						$(this).find('a.minus').show();
					} else {
						$(this).find('a.minus').hide();
					}
				});
			}
		});
	}
	installTextAreaFocusHandler();
});
