  
  function handleValidationResponse(response, params, fieldId) {
  
  $elements = $$('.fieldError');
  
  for($elementCount = 0; $elementCount < $elements.length; $elementCount++)
  {
    $elements[$elementCount].removeClassName('fieldError');
  }

  // display error message  
  if(response.responseText !== '')
  {
    $(fieldId).addClassName('fieldError');
  }
  else
  {
    $(fieldId).removeClassName('fieldError');
  }  
 
}

  
  
// --------------- Recipe Ingredient related functions ---------

// helper function to get nr of ingredients in a certain section
function getNrIngredientsForSection(sectionNr)
{
  return $('nrofingredients_section' + sectionNr).value;
}

// helper function return nr of ingredient sections at all
function getNrOfIngredientSections()
{
  return $('nrofingredientsections').value;
}

function removeIngredient(id, sectionNr, ingredientNr)
{
  // remove ingfredient table row
  $(id).remove();   
  
  // change ids of ingredients (because we could have deleted from middle)
  var nrIngredients =  $('nrofingredients_section' + sectionNr).value; 
  
  if(nrIngredients > ingredientNr)
  {
    var currentIngredientNr = ingredientNr+1;    
     
    while(currentIngredientNr <= nrIngredients)
    {
      setValuesForIngredient(sectionNr, currentIngredientNr, sectionNr, (currentIngredientNr-1));      
      currentIngredientNr++;
    }  
  }
  
  $('nrofingredients_section' + sectionNr).value--;// = (parseInt($('nrofingredients_section' + sectionNr).value)-1);  
  
}

function removeSubheadline(id, sectionNr)
{
  //remove observer
  Event.stopObserving($('but_addsub_'+sectionNr), 'click');
  Event.stopObserving($('but_s'+sectionNr), 'click');
  
  var nrIngredientsInSection     = $('nrofingredients_section' + sectionNr).value;
  var nrPreviousSection          = (sectionNr > 1)?sectionNr-1:1;
  var nrIngrInPreviousSection    = parseInt($('nrofingredients_section' + nrPreviousSection).value,10);
  var oldNrOfIngredientSections  = getNrOfIngredientSections();
  var nrOfMovedIngredients = 0;
  
  for(ingrCount = 1; ingrCount <= nrIngredientsInSection; ingrCount++) {

    // only move filled ingredients to parent block
//    if(($('ing' + sectionNr + '_' + ingrCount + '_quantity').value != '') || ($('ing' + sectionNr + '_' + ingrCount + '_name').value != '')) {  	

      nrOfMovedIngredients++;         
      
	    // rename id of table row, update input field ids
	    setValuesForIngredient(sectionNr, ingrCount, nrPreviousSection, nrIngrInPreviousSection + nrOfMovedIngredients);	    
			// move table row
			var targetElement = $$('#tbodyMoreingredients_section' + nrPreviousSection)[0];
			targetElement.insert({ bottom: $('ing' + nrPreviousSection + '_' + (nrIngrInPreviousSection + nrOfMovedIngredients))  });// extend table of previous section  
	  }
  //}

  //increment ingredient coutner for previous section, 
  $('nrofingredients_section' + nrPreviousSection).value = (nrIngrInPreviousSection + nrOfMovedIngredients);
  
  // decrement section count
  $('nrofingredientsections').value =   parseInt($('nrofingredientsections').value,10)-1;
  
   // delete section 
  $('section' + sectionNr).remove();

  
  // update names and ids of following section2
  for(sectionCount = parseInt(sectionNr,10) + 1;sectionCount <= oldNrOfIngredientSections; sectionCount++) {
    //replace the Observer by removing and readding 
    Event.stopObserving($('but_addsub_'+sectionCount), 'click');
    Event.stopObserving($('but_s'+sectionCount), 'click');
    setValuesForSection(sectionCount, sectionCount-1);
    var but_s = $$('a[id="but_s'+(sectionCount-1)+'"]'); 
    var but_addsub = $$('a[id="but_addsub_'+(sectionCount-1)+'"]');
    Event.observe(but_s[0], 'click', createAddIngredientsButtonEventhandler.bindAsEventListener(null, sectionCount-1, getIngredientNumber(sectionCount-1)));   
    Event.observe(but_addsub[0], 'click', createAddSubHeadLineButtonEventhandler.bindAsEventListener(null, sectionCount-1));
  }
  

}

// need because of problems in IE changing id and name attributes
// prototype element expected
function replaceAttribute(element, attributeName, attributeValue) 
{
    element.writeAttribute(attributeName, false);
    element.writeAttribute(attributeName, attributeValue);
}

// change name and ids for an ingredient
function setValuesForIngredient(oldSectionNr, oldIngrNr, newSectionNr, newIngrNr)
{
  var postFix = new Array('quantity', 'entity_id' , 'name', 'annotation');
  
  // rename ingredient input fields

  for(postfixCount = 0; postfixCount < postFix.length; postfixCount++) {
		elementToRename = $('ing' + oldSectionNr + '_' + oldIngrNr + '_' + postFix[postfixCount]);
		replaceAttribute(elementToRename, 'id', 'ing' + newSectionNr + '_' + newIngrNr + '_' + postFix[postfixCount]);
		replaceAttribute(elementToRename, 'name', 'ing' + newSectionNr + '_' + newIngrNr + '_' + postFix[postfixCount]);

		
		// remove fields error class
		elementToRename.removeClassName('fieldError');		
  }  
  
	// update ingredient removal link
	var link = $('ing' + oldSectionNr + '_' + oldIngrNr + '_href');

  replaceAttribute(link, 'id', 'ing' + newSectionNr + '_' + newIngrNr + '_href');
	replaceAttribute(link, 'href', 'javascript:removeIngredient(\'ing' + newSectionNr + '_' + newIngrNr 
                     + '\',' + newSectionNr + ',' + newIngrNr + ')');

  // rename ingredient table row
  replaceAttribute($('ing' + oldSectionNr + '_' + oldIngrNr), 'id', 'ing' + newSectionNr + '_' + newIngrNr);
  
}

// change all ids and names to a new section nr
function setValuesForSection(oldSectionId, newSectionId) 
{  
    var sectionDiv = $('section' + oldSectionId);    

    // change ids and names for ingredients
    for(ingrCount = 1; ingrCount <= getNrIngredientsForSection(oldSectionId); ingrCount++) {    
      setValuesForIngredient(oldSectionId, ingrCount, newSectionId, ingrCount);      
    }

    // rename global section div itself
    replaceAttribute(sectionDiv, 'id', 'section' + (newSectionId));
    // rename subheadline div
    replaceAttribute($('section' + oldSectionId + '_subheadline'), 'name', 'section' + newSectionId + '_subheadline');
    replaceAttribute($('section' + oldSectionId + '_subheadline'), 'id', 'section' + newSectionId + '_subheadline');
    
    // change subheadline removal link
    var newSubheadlineHref = $('remove_subheadline_' + oldSectionId + '_href').readAttribute('href').replace(new RegExp(oldSectionId,"g"), newSectionId);
    replaceAttribute($('remove_subheadline_' + oldSectionId + '_href'), 'href', newSubheadlineHref);
    replaceAttribute($('remove_subheadline_' + oldSectionId + '_href'), 'id', 'remove_subheadline_' + newSectionId + '_href');
    
    // change ingredient count input field
    replaceAttribute($('nrofingredients_section' + oldSectionId), 'name', 'nrofingredients_section' + newSectionId);
    replaceAttribute($('nrofingredients_section' + oldSectionId), 'id', 'nrofingredients_section' + newSectionId);

    // change name and id for new ingredient area of section
    replaceAttribute($('moreingredients_section' + oldSectionId), 'name' , 'moreingredients_section' + newSectionId);
    replaceAttribute($('moreingredients_section' + oldSectionId), 'id' , 'moreingredients_section' + newSectionId);

    // change id of table body in ingredient area (id needed for ajax updater)
    replaceAttribute($('tbodyMoreingredients_section' + oldSectionId), 'id', 'tbodyMoreingredients_section' + newSectionId);
    replaceAttribute($('but_s'+oldSectionId), 'id', 'but_s'+newSectionId);
    replaceAttribute($('but_addsub_'+oldSectionId), 'id', 'but_addsub_'+newSectionId);
   
  }

function insertNewSubheadline(response, parameters, predecessorNr) 
{

  // increase section nr for section behind the inserted
  var nrOfSections = getNrOfIngredientSections();  
  
  // change ids and names for all sections behind the section to insert (before insertion)
  for(sectionCount = predecessorNr + 1; sectionCount <= nrOfSections; sectionCount++) {      
    setValuesForSection(sectionCount, sectionCount+1);
  }

  // append new section
  ($$('div#section' + predecessorNr)[0]).insert({ after: new Element('div', { 'id': 'section' + (predecessorNr + 1)}).update(response.responseText) });  

  // increase ingredient section count
  $('nrofingredientsections').value = parseInt($('nrofingredientsections').value,10) + 1;  
}




// --------------- Shopping list related functions ---------

addSortability = function(remoteUrlPosUpdate) 
{
  $remoteUrlPosUpdate = remoteUrlPosUpdate;
  Position.includeScrollOffsets = true;
  Sortable.create('sortable', {onUpdate: sendPositionInfo});
};
// Div element in   /shoppinglist/templates/_layerContentEntries
// Function call in /shoppinglist/templates/_shoppinglistEntryEditNew.php
scrollToEndOfShoppingList = function()
{
  $('divShoppinglistEntries').scrollTop = $('divShoppinglistEntries').getHeight() + 500;
};

// function call in addNewEntry() + shoppinglist/templates/_layerContentEntries
toggleShoppingListButton = function()
{
  var enabledButton  = $('shoppingListButton');
  var disabledButton = $('shoppingListButtonDisabled');
  if (enabledButton.visible()) {
    enabledButton.hide();
    disabledButton.show();
  }
  else {
    enabledButton.show();
    disabledButton.hide();
  }
};


sendPositionInfo = function(droppedElement, remoteUrl)
{
  var serializedList = Sortable.serialize('sortable');
  //alert(serializedList);

  var myAjax = new Ajax.Request(
  $remoteUrlPosUpdate,
  { method: 'post', 
    asynchronous:true, 
    evalScripts:false,
    parameters: {entryOrder: serializedList}
    }
  );
};


addNewEntry = function(entryDivElement, saveUrl) 
{
  var entryQuantity = $(entryDivElement).down('.quantity_edit').value;
  
  var entryName = $(entryDivElement).down('.name_edit').value;
  if((entryQuantity.length == 0) && (entryName.length != 0)) {
    alert('Bitte geben Sie eine Menge ein');
  }
  else if((entryQuantity.length != 0) && (entryName.length == 0)) {
    alert('Bitte geben Sie dem Eintrag eine Bezeichnung');
  }
  else if((entryQuantity.length == 0) && (entryName.length == 0)) {  
    entryDivElement.remove();
    toggleShoppingListButton();
  }
  else {
  var result =  new Ajax.Updater('divShoppinglistEntries', 
                                      saveUrl, 
                                      { asynchronous:true, 
                                        evalScripts:true, 
                                        onComplete:function(request, json){addSortability(); toggleShoppingListButton();},
                                        parameters:{
                                          quantity:entryQuantity, 
                                          entity_id:entryDivElement.down('.entityId_edit').value, 
                                          name:entryName}});
  }
};

createMouseOverEffect = function(element) {

  if(element.tagName == 'INPUT') {
$(element).setStyle({backgroundImage:$(element).getStyle('backgroundImage').sub(/(\.gif|jpg|png)/, function(match) { return '_hover' + match[0] ;})});
  }
  else if(element.tagName == 'IMG') {
   $(element).setAttribute('src', $(element).getAttribute('src').sub(/(\.gif|jpg|png)/, function(match) { return '_hover' + match[0]; }) );
  }
};

createMouseOutEffect = function(element) {

  if(element.tagName == 'INPUT') {
    $(element).setStyle({backgroundImage:$(element).getStyle('backgroundImage').sub('_hover', '')});
  }
  else if(element.tagName == 'IMG') {
     $(element).setAttribute('src', $(element).getAttribute('src').sub('_hover', ''));
  }
};

createMouseOverEffectEventHandler = function(event) 
{
 var element = Event.element(event);
 createMouseOverEffect(element);
};

createMouseOutEffectEventHandler = function(event) 
{
 var element = Event.element(event);
 createMouseOutEffect(element);
};

/**
 * EventHandler to create a new ingredient onclick
 *
 *
 */
createAddIngredientsButtonEventhandler = function(event)
{
  var data = $A(arguments);
  data.shift(); //shift away event
  var section = data.shift();
  var ingredient = data.shift();
  increaseIngredientNumberForSection(section);
  var newIngredient = getIngredientNumber(section);
  createIngredientsForTable('tbodyMoreingredients_section'+section, section, newIngredient);
  return false;
};

/**
 * EventHandler to create a new subheadline onclick
 *
 *
 */
createAddSubHeadLineButtonEventhandler = function(event)
{
  var data = $A(arguments);
  data.shift(); //shift away event
  var section = data.shift();
  incrementSection();
  var newSection = getSectionNumber();
  createSubHeadLineForSection(newSection);
  Event.observe($("but_s"+newSection), 'click', createAddIngredientsButtonEventhandler.bindAsEventListener(null, newSection, getIngredientNumber(newSection)));
  Event.observe($("but_addsub_"+newSection), 'click', createAddSubHeadLineButtonEventhandler.bindAsEventListener(null, newSection));
  createAddIngredientsButtonEventhandler(null,newSection,1); 
  
  return false;
};

increaseIngredientNumberForSection = function(section) {
  var newval = getIngredientNumber(section)+1;
  $('nrofingredients_section'+section).value=newval; 
};

incrementSection = function(){
  var newval = getSectionNumber()+1;
  $('nrofingredientsections').value=newval;   
};

getIngredientNumber = function(section){
  return parseInt($('nrofingredients_section'+section).value,10);
};

getSectionNumber = function(){
  return parseInt($('nrofingredientsections').value,10); 
};

generateNewIngredientTrElement = function (section, ingredient){
  var elem = new Element('tr', { id: 'ing'+section+'_'+ingredient});
  return elem;
};

generateNewSubHeadLineElement = function(section){
  var elem = new Element('div', {id: 'section'+section});
  return elem; 
};

/**
* Generate the HTMLNodes for a new empty ingredient
*/
createIngredientsForTable = function(HTMLtarget,sectionNo,ingredientNo) {
    //build the line
  var ingredientId = "ing"+sectionNo+"_"+ingredientNo;
  var tr = new Element('tr', {id: ingredientId} );
  //var tr = new Element('tr', {id: ingredientId} );
  
  var td = tr.appendChild(new Element('td'));
  td.appendChild(new Element('input', { id: ingredientId+"_quantity", 'type': 'text', name: ingredientId+"_quantity", 'class': 'shadedInput textfieldmini', maxlength: '8'}));
  
  td = tr.appendChild(new Element('td'));
  var sel = td.appendChild(new Element('select', { id: ingredientId+"_entity_id",name: ingredientId+"_entity_id", 'class': 'shadedInput ingredientEntityId'}));
  
  entities.each(function(name,index) {
  sel.appendChild(new Element('option', {value: name[0]}).update(entities.get(name[0])));
}); 

  td = tr.appendChild(new Element('td'));
  td.appendChild(new Element('input', { id: ingredientId+"_name", 'type': 'text', name: ingredientId+"_name", 'class': 'shadedInput ingredientName', use_style: '1'}));

  td = tr.appendChild(new Element('td'));
  td.appendChild(new Element('input', { id: ingredientId+"_annotation", 'type': 'text', name: ingredientId+"_annotation", 'class': 'shadedInput ingredientAnnotation'}));

  td = tr.appendChild(new Element('td'));    
  var a = td.appendChild(new Element('a', { id: ingredientId+"_href", 'type': 'text', name: ingredientId+"_href", href: "javascript:removeIngredient('"+ingredientId+"',"+sectionNo+","+ingredientNo+")" }));
  a.appendChild(new Element('img', {'class': 'but_info', alt: 'close', src: '/images/recipe_db/but_close.gif'}));
  $(HTMLtarget).appendChild(tr);
};

/**
* Generate a new Empty Subheadline
*
*/
createSubHeadLineForSection = function(section) {
  var div = new Element('div', { id: 'section'+section});
  div.appendChild(new Element('label', {'class': 'editRecipeFieldLabel' }).update('Zwischenüberschrift:'));
  div.appendChild(new Element('input', {name: 'section'+section+'_subheadline', id: 'section'+section+'_subheadline', 'class': 'shadedInput textfieldlarge', value: ''} ));
  div.appendChild(new Element('span').update('&nbsp;'));
  var a = new Element('a', {id: 'remove_subheadline_'+section+'_href', href: 'javascript:removeSubheadline(\'section'+section+'_subheadline\',\''+section+'\');' });
  div.appendChild(a);  
  a.appendChild(new Element('img', {src: '/images/recipe_db/but_close.gif', alt:'close', 'class': 'but_info'}));
  div.appendChild(new Element('input', {type: 'hidden', name: 'nrofingredients_section'+section, id: 'nrofingredients_section'+section, value: '0' }));
  var span = new Element('span', {'class': 'info-icon'});
  var tooltip = new Element('img', {height: '20', width: '20', src: '/images/brigitte/elements/ico_autotooltip.gif', 'class': 'autotooltip', title: 'Welche Zutaten brauchen Sie für den Teig, welche für die Creme und welche für die Glasur Ihres Kuchens? Gliedern Sie die Zutatenliste mit Hilfe von Zwischenüberschriften - wer Ihr Rezept nachkocht oder -backt, wird es Ihnen danken!'  });
  span.appendChild(tooltip);
  div.appendChild(span);
  var table = new Element('table', {'class': 'ingredientsTable', cellspacing:'0', cellpadding:'0', id: 'moreingredients_section'+section});
  div.appendChild(table);
  var colgroup = new Element('colgroup');
  colgroup.appendChild(new Element('col', {width: '50'}));
  colgroup.appendChild(new Element('col', {width: '100'}));
  colgroup.appendChild(new Element('col', {width: 'auto'}));
  colgroup.appendChild(new Element('col', {width: '180'}));
  colgroup.appendChild(new Element('col', {width: '30'}));
  table.appendChild(colgroup);
  var tbody = new Element('tbody', {id: 'tbodyMoreingredients_section'+section });
  table.appendChild(tbody);
  div.appendChild(new Element('hr', { 'class':'imageDottedLine'}));
  var buttonbox = new Element('div', {style: 'margin-bottom:10px;margin-top:10px;'} );
  div.appendChild(buttonbox);
  var a_ingredient = new Element('a', {id: 'but_s'+section, 'class':'submit'});
  buttonbox.appendChild(a_ingredient);
  buttonbox.appendChild(new Element('span').update('&nbsp;'));
  a_ingredient.appendChild(new Element('img', { onmouseover: 'createMouseOverEffect(this)', onmouseout: 'createMouseOutEffect(this)', src: '/images/recipe_db/but_more_ingredients.gif', alt:'addIngredient' }));
  var a_section = new Element('a', { id: 'but_addsub_'+section, 'class':'submit'});
  buttonbox.appendChild(a_section);
  a_section.appendChild(new Element('img', { onmouseover: 'createMouseOverEffect(this)', onmouseout: 'createMouseOutEffect(this)', src: '/images/recipe_db/but_more_subheadlines.gif', alt:'addSubheadline' }));
  $('newsection').appendChild(div);
  common.initToolTip(tooltip);
};
