
function addIngredient(){

	// Get number of ingredients
	var iNumber =  $('numberOfIngredients').get('value');
	
	// Increment number of ingredients
	var newNumber = parseInt(iNumber) + 1 ;
	
	// Declare all new cells
	var tableCells = '<tr id="trIngredient' + newNumber + '"><td class="ingredientNumber">' + newNumber +'</td><td class="quantity"><input type="text" value="" id="quantity' + iNumber + '" name="quantity' + iNumber + '" size="6"><span class="response" id="quantityStatus' + iNumber + '" style="display: none;"></span></td><td class="unit"><input name="unitId' + iNumber + '" id="unitId'+iNumber+'" size="7"><span class="response" id="unitIdStatus'+iNumber+'" style="display: none;"></span></td><td class="ingredient"><input type="text" value="" id="ingredient'+iNumber+'" name="ingredient'+iNumber+'" size="14"><span class="response" id="ingredientStatus' + iNumber + '" style="display: none;"></span></td><td class="comment"><input type="text" value="" id="comment' + iNumber + '" name="comment' + iNumber + '" size="6"><span class="response" id="commentStatus' + iNumber + '" style="display: none;"></span></td></tr>' ;

	// Hack to get all td:s as elements
	var newRow = new Element('div', {html: '<table><tbody>' + tableCells + '</tbody></table>'}).getElement('tr');  
	newRow.inject($('tbodyIngredientContainer'));
	
	// Highlight ingredient container
	$('ingredientContainerLegend').highlight('#d8f2d0');

	// Update number of ingredient hidden value
	$('numberOfIngredients').set('value',newNumber);
	$$('.unit input').removeEvents();
	$$('.ingredient input').removeEvents();
	addIngredientListener();
	addUnitListener();
}

function addUnitListener(){
	// Add listener for all unit-inputs
	$$('.unit input').addEvent('focus', function(e){
		new Autocompleter.Request.JSON(this, '/getUnit.php', {
			'indicatorClass': 'autocompleter-loading',
			'postVar': 'criteria',
			'width' : '100'
		});
	});
}

function addIngredientListener(){
	// Add listener for all ingredients-inputs
	$$('.ingredient input').addEvent('focus', function(e){
		new Autocompleter.Request.JSON(this, '/getIngredient.php', {
			'indicatorClass': 'autocompleter-loading',
			'postVar': 'criteria',
			'width' : '100'
		});
	});
}

//Ändra till befintlig
function connectIngredientListener(){
	//If any object with the class updateIngredient is clicked on it starts the function
	$$('.connectIngredient').addEvent('click', function(){
		// Sets the objects rel-value to the variable
		var iIngredientId = this.get('rel');
		// Now we have the id of the row. 
		// Search for  an object with id ingredientSing(and *plur)45 and sets this objects value to the variable
		var sIngredientSing = $('ingredient'+iIngredientId).get('value');
		// Builds a new request and store it in variable reqUpdate
		var reqUpdate = new Request({
			url : '/?service=recipeAdmin&action=ingredientUpdater',
			onSuccess: function(responseText){
				if(responseText == 'no'){
					alert("Ändringen misslyckades.\nDu måste ange en befintlig ingrediens som ska ersätta den gamla.\nAlternativt skapar du en ny ingrediens i kolumnen till höger.")
				}else{				
					$('hideLeft'+iIngredientId).set('html', '&nbsp;&nbsp;&nbsp;&nbsp;Ändrad till '+sIngredientSing+' &nbsp; <img src="admin/media/gfx/all-ok.gif">');
					$('hideRight'+iIngredientId).set('html','&nbsp;');
				}
			},
			onFailure: function(){
				alert("neh funkar inte");
			}
		});
		// Sends the variable
		reqUpdate.send('type=connect&id='+iIngredientId+'&sing='+sIngredientSing);
		//Update
		
		//$(sElementId).set('src','admin/media/gfx/ajax-loader.gif');
	});
}

//Skapa ingrediens.
function updateIngredientListener(){
	//If any object with the class updateIngredient is clicked on it starts the function
	$$('.updateIngredient').addEvent('click', function(){
		
		// Sets the objects rel-value to the variable
		var iIngredientId = this.get('rel');
		// Now we have the id of the row. 
		// Search for  an object with id ingredientSing(and *plur)45 and sets this objects value to the variable
		var sIngredientSing = $('ingredientSing'+iIngredientId).get('value');
		var sIngredientPlur = $('ingredientPlur'+iIngredientId).get('value');
		// Builds a new request and store it in variable reqUpdate
		var reqUpdate = new Request({
			url : '/?service=recipeAdmin&action=ingredientUpdater',
			onSuccess: function(responseText){
				if(responseText == 'no'){
					alert("Skapandet misslyckades.\nDu måste ange både singular- och pluralnamnet och singularnamnet får inte redan finnas.\nAlternativt kopplar du denna ingrediens till en befintlig i kolumnen till vänster.")
				}else{				
					$('hideRight'+iIngredientId).set('html', '&nbsp;&nbsp;&nbsp;&nbsp;'+sIngredientSing+' är skapad &nbsp; <img src="admin/media/gfx/all-ok.gif">');
					$('hideLeft'+iIngredientId).set('html','&nbsp;');
				}
			},
			onFailure: function(){
				alert("neh funkar inte");
			}
		});
		// Sends the variable
		reqUpdate.send('type=update&id='+iIngredientId+'&sing='+sIngredientSing+'&plur='+sIngredientPlur);
		//Update
		
		//$(sElementId).set('src','admin/media/gfx/ajax-loader.gif');
	});
}

function closeDeleteNotify(){
	
	if($('deleteNotify')){
	
		
		var myFx = new Fx.Tween($('deleteNotify'),{
			link: 'chain',

			onComplete: function(e) {
				$('deleteNotify').destroy();
				
			}
		});
		//Transitions the background color of the Element from black to red:
		myFx.start('opacity', '1', '0');

	}
}



window.addEvent('domready', function() {
	
	
	var params = location.pathname.split('/');

	//alert(params[1]);
	
	if(params[1] == 'recept'){
		$('topMenu').getElement('.item23').addClass('activeTopMenu');
	}
	if(params[1] == 'klotterplank'){
		$('topMenu').getElement('.item54').addClass('activeTopMenu');
	}
	if(params[1] == 'forum'){
		$('topMenu').getElement('.item24').addClass('activeTopMenu');
	}
	if(params[1] == 'blogg'){
		$('topMenu').getElement('.item55').addClass('activeTopMenu');
	}
	if(params[1] == 'om_kokboken'){
		$('topMenu').getElement('.item178').addClass('activeTopMenu');
	}
	if(params[1] == 'kokshjalpen'){
		$('topMenu').getElement('.item191').addClass('activeTopMenu');
	}
	
	if(params[1] == ''){
		$('topMenu').getElement('.item162').addClass('activeTopMenu');
	}
		
		

	
	/**
	 * Delete recipe
	 */
	
	if($$('.buttonDelete')){
		$$('.buttonDelete').addEvent('click', function(e){
			var objectId = this.get("rel") ;

			var sRecipeName = "recipeNameId" + objectId  ;

			var position = this.getPosition() ;
			
			var size = this.getParent().getParent().getParent().getSize();
			
			//myDivText = '<div class="deleteNotifyContainer"><div class="deleteNotifyClose" onclick="javascript:closeDeleteNotify();"><span>x</span></div><h4>Vill du verkligen ta bort ditt recept:<br /> <em>'+ $(sRecipeName).get('text') +'</em>?</h4><a href="/?service=recipes&action=deleteRecipe&recipeId=' + objectId + '" class="actionDeleteRecipe">Ja tack!</a></div>';
			myDivText = '<div class="deleteNotifyContainer" style="padding-top: '+(size.y/2-30)+'px"><a class="button buttonLarge" onclick="javascript:closeDeleteNotify();">Nej förlåt!</a>&nbsp;<a href="/?service=recipes&action=deleteRecipe&recipeId=' + objectId + '" class="button buttonSmall actionDeleteRecipe">Ja snälla</a></div>';
			
			if(!$('deleteNotify')){

				var alertDiv = new Element('div',{'id':'deleteNotify','class':'deleteNotify'}); 

				alertDiv.inject('recipeContainerList','before');
			
				$('deleteNotify').set('style','opacity: 0;position: absolute; float: left; z-index: 10000; height: '+ (size.y)+'px; top: '+ (position.y)+'px;left: '+ (position.x+100) +'px; background-color: white;');

				$('deleteNotify').set('html',myDivText);
			
				var myFx = new Fx.Tween($('deleteNotify'),{
				});
				//Transitions the background color of the Element from black to red:
				myFx.start('opacity', '0', '1');

			}
		});
	}

	
	/**
	 * Recept hjälp bubblor
	 */
	
	if($$('.recipeHelp')){
		$$('.recipeHelp').addEvents({
			'mouseover': function(e){
				this.getElement('div').set({style :'display:block'});
			},
			'mouseout':function(e){
				this.getElement('div').set({style :'display:none'});
			}
		});
	}

	/**
	 * Taggningsfunktion för receptskapande
	 */
	
	if($('recipeTagInput')){
		var recipeTagInput = $('recipeTagInput').get('value') ;
		
		if(recipeTagInput != ''){
			var arrayTags = recipeTagInput.split(",");

			arrayTags.each(function(item, index){
				if(item != ''){
					$('tag'+item).addClass('selected');
				}
			});
			
		}
	}

	var clickedTags = new Array() ;

	if($$('div.tagList span.tag')){
		
		if($('recipeTagInput')){
			var recipeTagInput = $('recipeTagInput').get('value') ;
			clickedTags = recipeTagInput.split(",");
		}
		
		$$('div.tagList span.tag').addEvents({
			'click': function(e){
				if(this.hasClass("selected")){
					// Remove class
					this.removeClass("selected")
					
					// Remove value from array
					for (x in clickedTags){
						if(this.get("rel") == clickedTags[x]){
							clickedTags[x] = '' ;
						}
					}
					
				}else{
					this.addClass('selected');
					clickedTags.push(this.get("rel")) ;
				}
				
				$('recipeTagInput').set('value',clickedTags.toString());

			}
		});
	}
	
	
	if($$('div.formStepButton a')){
		$$('div.formStepButton a').addEvents({
			'click': function(e){
			
				$$('div.formStepButton a').each(function(item, index){
					if(item.hasClass("selected")){
						item.removeClass("selected");
					}
				});
				
				$$('div.serviceRecipes fieldset.formTabs').each(function(item, index){
					item.setStyle("display","none") ;
				});
				
				$(this.get('rel')).setStyle("display","block") ;
				this.addClass("selected") ;
			}
		});
	}
	
	/**
	 * Form selection function, createRecipe
	 */
	
	if($$('.serviceRecipes form .stepHelp table td a')){
		$$('.serviceRecipes form .stepHelp table td a').addEvents({
			'click': function(e){
				var nextStep = this.get('rel') ;
				
				$$('.serviceRecipes form fieldset.formTabs').each(function(item, index){
					item.setStyle("display","none") ;
				});
				
				$$('div.formStepButton a').each(function(item, index){
					
					if(item.hasClass("selected")){
						item.removeClass("selected");
					}
					
					if(item.get('rel') == nextStep){
						item.addClass("selected") ;
						
					}
					
				});
				
				$(this.get('rel')).setStyle("display","block") ;
			}
		});
	}
		
	if($('addIngredientItem')){
		$('addIngredientItem').addEvents({
			'click': function(e){
				addIngredient();
			}
		});
	}

	connectIngredientListener();
	updateIngredientListener();
	addUnitListener();

	// Add listener for all ingredient-inputs
	$$('.ingredient input, .oldIngredient input').addEvent('focus', function(e){
		new Autocompleter.Request.JSON(this, '/getIngredient.php', {
			'indicatorClass': 'autocompleter-loading',
			'postVar': 'criteria',
			'width' : '250'
		});
	});



	
});

