var Gratisrecept = {
	start: function(){		
		var add_ingridient_button = $$('button.add-ingredient');

		if(add_ingridient_button) {
			add_ingridient_button.addEvent('click', function(event) {
				event.stop();
				Gratisrecept.add_ingredient(this);
				Gratisrecept.addsort();
			});
		}
		
		$$('input, textarea').addEvent('focus', function(event) {
			this.addClass('focus');
		});
		
		$$('input, textarea').each(function(el,index){
			el.addEvent('blur', function(event) {
				el.removeClass('focus');
			});
		});
		
		if($('inpIngredient')) {
			var ac = new Autocompleter.Request.JSON('inpIngredient', '/ajax/ingredients', {
	        	'postVar': 'ingredient'
	    	});
	    }
	    
	    $$('ul.ingredients a').each(function(el,index){
			el.addEvent('click', function(event) {
				el.getParent().destroy();
				return false;
			});
		});
		
		if($$('#recipe-form ul.ingredients')) {
			Gratisrecept.addsort();
		}
	    
	    if($('recipe-form')) {
	    	$$('#recipe-form input').each(function(el,index){
	    		el.addEvent('keypress', function(e) {
	    			var event = new Event(e);
					if (event.key == 'enter') {
						return false;
					}
				});
			});	
	    }
	    
	    if($('inpIngredient')) {
	    	$('inpIngredient').addEvent('keyup', function(e) {
	    		var event = new Event(e);
				if (event.key == 'enter') {
					Gratisrecept.add_ingredient(this);
				}
			});
	    }
	    
	   	$$('a.confirm').each(function(el,index){
			el.addEvent('click', function(event) {
				return confirm('Are your sure?');
			});
		});
	},
	
	add_ingredient: function(el){
		if(el.getProperty('type') == 'button') {
			var inpFields = el.getParent().getParent().getElements('input');
		}
		else {
			var inpFields = el.getParent().getElements('input');
		}
			
		if( ! inpFields[0].value=="" && ! inpFields[1].value=="" ){
			var myLI = new Element('li',{});
			
			var myINPUT1 = new Element('input', {
				'type': 'hidden',
				'name': 'recipe[ingredients][ingredient][]',
				'value': $('inpIngredient').value
			});
			
			var myINPUT2 = new Element('input', {
				'type': 'hidden',
				'name': 'recipe[ingredients][amount][]',
				'value': $('inpAmount').value
			});
			
			var mySpan = new Element('span', {
				'html': $('inpAmount').value + ' ' + $('inpIngredient').value
			});
			
			var myA = new Element('a', {
				'href': '#',
				'class': 'remove',
				'html': '',
				'events': {
			        'click': function(event){ event.stop();this.getParent().destroy(); }
			    }
			});
			
			myLI.adopt(myA, mySpan, myINPUT1, myINPUT2);
			var sort = Gratisrecept.addsort();
			sort.addItems(myLI);
			
			$$('ul.ingredients').adopt(myLI);		
			
			inpFields[0].setProperty('value','');
			inpFields[1].setProperty('value','');
			inpFields[0].focus();
		}
	},
	
	addsort: function(){
		var sort = new Sortables('#recipe-form ul.ingredients', {
			constrain: true,
			clone: true,
			opacity: 0.6
		});
		
		return sort;
	}
};

window.addEvent('domready', Gratisrecept.start);
