var HideMe;
var blurauto;
var blurrow;
var scrollFix = function(event){ 
	if(!($(Event.element(event)).up('div#auto_complete'))) 
	{
		Event.stopObserving(document,'click',scrollFix);
		if(blurauto){
			blurauto.hide(blurauto.iefix);
			blurauto.active=false;
			blurauto.hasFocus=false;
			blurauto=null;
			blurrow=null;
		}
	}
};
var hidenow = function(){Event.stopObserving(document,'click',scrollFix);if(blurauto){blurauto.hide(blurauto.iefix);blurauto.active=false;blurauto.hasFocus=false;blurauto=null;blurrow=null;}};
Ajax.CoolAutoComplete = Class.create();
Object.extend(Object.extend(Ajax.CoolAutoComplete.prototype,Ajax.Autocompleter.prototype),{
onBlur: function(event) {blurauto=this;  blurrow = this.element;HideMe = setTimeout(hidenow,1000);},
show: function() {
	if(this.entryCount == 0) {this.active = false;return;}
	if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
	if(!this.iefix &&
	(navigator.appVersion.indexOf('MSIE')>0) &&
	(navigator.userAgent.indexOf('Opera')<0) &&
	(Element.getStyle(this.update, 'position')=='absolute')) {
	new Insertion.After(this.update,
	'<iframe id="' + this.update.id + '_iefix" '+
	'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
	'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
	this.iefix = $(this.update.id+'_iefix');
	}
	if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
	Event.observe(document,'click',scrollFix);
},
markPrevious: function() {
	if(this.index > 0) this.index--
	else this.index = this.entryCount-1;
	this.moveHighlight('up');
},
markNext: function() {
	if(this.index < this.entryCount-1) this.index++
	else this.index = 0;
	this.moveHighlight('down');
},
moveHighlight: function(direction) {
	var updatescroll = this.update.scrollTop;
	var updateheight = Element.getDimensions(this.update).height;
	var entryy = Position.positionedOffset(this.getEntry(this.index))[1];
	var entryheight = Element.getDimensions(this.getEntry(this.index)).height;
	if (((updatescroll + updateheight) < (entryy + entryheight)) || (entryy < updatescroll)) {
		var newy = (direction == 'up') ? entryy : entryy - updateheight + entryheight;
		this.update.scrollTop = newy;
	}
}
,
onComplete: function(request) {
	if(request.responseText == '<ul></ul>')
	{
		this.hide();
		this.active = false;
		setTimeout(hidenow,100);
		return;
	}
	else
	{
		this.active = true;
	}
	this.updateChoices(request.responseText);
	if(this.entryCount > 7){
		this.update.style.height = "200px";
	}else{
		this.update.style.height = "auto";
	}
}
});
var decimalSep =",";
var thousandSep = " ";
var no_of_text_field = 0;
var error = 0;
var errorrow = errorrow || [];
var checkEles = [];
var units = units || [];
var invalidUnitMsg = [];
var j;
var i;
var row = '';
var SubmitPressed = false;
var validating = false;
var no_incredient = false;
var stopValidation = false;
var setInvalid = true;
var msg='';
var curRow = 0;
var curEle = 0;
var lastRow = 0;
var lastEle = 0;
var valid_rows = 0;
var no_of_rows_incredients = 0;
function addRow(){
	var rows = $('incredient').rows.length;
	var new_row = $('incredient').insertRow(rows);
	var col1 = new_row.insertCell(0);
	var col2 = new_row.insertCell(1);
	var col3 = new_row.insertCell(2);
	$('no_of_incredients').value = parseInt($('no_of_incredients').value) + 1;
	no_of_rows_incredients = $('no_of_incredients').value;
	errorrow.push({id: $('no_of_incredients').value,value:0});
	col1.innerHTML = '<input type="hidden" value="" id="incredient_'+$('no_of_incredients').value+'_id" name="incredient_'+$('no_of_incredients').value+'_id"/><input type="text" class="input2" autocomplete="off" value="" id="incredient_'+$('no_of_incredients').value+'" name="incredient_'+$('no_of_incredients').value+'"/>';
	col2.innerHTML = '<input type="text" class="input3" value="" id="qty_'+$('no_of_incredients').value+'" name="qty_'+$('no_of_incredients').value+'"/>';
	col3.innerHTML = '<select id="unit_'+$('no_of_incredients').value+'" name="unit_'+$('no_of_incredients').value+'">'+optionsList+'</select>';
	var val = $('no_of_incredients').value;
	units[val] = [];
	invalidUnitMsg[val]=false;
	new Ajax.CoolAutoComplete('incredient_'+$('no_of_incredients').value, 'auto_complete', '/calculator/autoComplete/input/'+$('no_of_incredients').value, {minChars:3, tokens:'[]', afterUpdateElement: function (inputField, selectedItem) { $('incredient_'+$('no_of_incredients').value+'_id').value = selectedItem.id; afterUpdate(val,selectedItem.id);}});
	init();
}
function validate(isSubmit){
	if(isSubmit === true){
		SubmitPressed = isSubmit;
	}
	if(validating || stopValidation)
		return false;
	validating = true;
	if(errorrow.length == 0){
		for(i=1; i<=no_of_rows_incredients; i++)
			errorrow.push({id: i,value:0});
	}
	if(units.length == 0){
		for(i=1; i<=no_of_rows_incredients; i++)
			units[i]=[];
	}
	if(invalidUnitMsg.length == 0){
		for(i=1; i<=no_of_rows_incredients; i++)
			invalidUnitMsg[i]=false;
	}
	error = 0;
	no_of_text_field = 0;
	checkEles = [];
	valid_rows=0;
	for(i=1; i<=no_of_rows_incredients; i++){
		if($("incredient_"+i).value != ""){
			if(!(curEle == "incredient" && curRow == i)){
				if($("incredient_"+i).value != "" && (parseInt($('incredient_'+i+'_id').value) == 0 || $('incredient_'+i+'_id').value == "")){
					no_of_text_field++;
					new Ajax.Request("/calculator/validate",{method: "post",parameters: {pos: i,name: $("incredient_"+i).value} ,onSuccess : function(trans){check(trans);afterUpdate(trans.responseText.split('|||')[1],trans.responseText.split('|||')[0]);validate(false);},onError : function(){no_of_text_field--;} })
				}
			}
			msg='';
			row = '';
			errors = 0;
			errorrow.each(function(err){if(err.id<i){errors = err.value+errors;}});
			if($('incredient').rows.length > i+errors+1){
				row = $('incredient').rows[i+errors+1];
			}
			if(row != '' && $(row).down().hasClassName("errorDiv")){
				msg = $(row).down().innerHTML;
			}
			if(curRow == i){
				if(curRow == lastRow){
					if($('incredient_'+i).value != '' && parseInt($('incredient_'+i+'_id').value) === -1){
						msg = msg_incredient_not_valid;
					}else if(($('qty_'+i).value == "" || $('qty_'+i).value == 0) && (lastEle == 'qty' || msg==msg_qty_empty)){
						msg = msg_qty_empty;
					}else if($("qty_"+i).value != '' && (isNaN(convertNumber($("qty_"+i).value)) || convertNumber($("qty_"+i).value) < 0 )){
						msg = msg_qty_not_valid;
					}else	if((units[i].length>0 && units[i].indexOf($('unit_'+i).value) == -1) || (units[i].indexOf($('unit_'+i).value) == 0 && invalidUnitMsg[i])){
						msg = msg_unit_not_valid;
					}else if($('unit_'+i).value == 0 && (lastEle == 'unit' || msg==msg_select_unit || (arguments[0]?arguments[0].length:arguments.length)>1 )){
						msg = msg_select_unit;
					}else{
						msg='';
					}
				}else{
					if($('incredient_'+i).value != '' && parseInt($('incredient_'+i+'_id').value) === -1){
						msg = msg_incredient_not_valid;
					}else if(($('qty_'+i).value == "" || $('qty_'+i).value == 0)){
						msg = msg_qty_empty;
					}else if($("qty_"+i).value != '' && (isNaN(convertNumber($("qty_"+i).value)) || convertNumber($("qty_"+i).value) < 0 )){
						msg = msg_qty_not_valid;
					}else	if((units[i].length>0 && units[i].indexOf($('unit_'+i).value) == -1) || (units[i].indexOf($('unit_'+i).value) == 0 && invalidUnitMsg[i])){
						msg = msg_unit_not_valid;
					}else if($('unit_'+i).value == 0 && (arguments[0]?arguments[0].length:arguments.length)>1 || msg==msg_select_unit ){
						msg = msg_select_unit;
					}else{
						msg='';
					}
				}
			}else{
				if(parseInt($('incredient_'+i+'_id').value) === -1){
					msg = msg_incredient_not_valid;
				}else if($('qty_'+i).value == "" || $('qty_'+i).value == 0){
					msg = msg_qty_empty;
				}else if($("qty_"+i).value != '' && isNaN(convertNumber($("qty_"+i).value)) || convertNumber($("qty_"+i).value) < 0 ){
					msg = msg_qty_not_valid;
				}else	if((units[i].length>0 && units[i].indexOf($('unit_'+i).value) == -1) || (units[i].indexOf($('unit_'+i).value) == 0 && invalidUnitMsg[i])){
					msg = msg_unit_not_valid;
				}else if($("unit_"+i).value == "0"){
					msg = msg_select_unit;
				}else{
					msg=''
				}
			}
			if(msg != ''){
				no_of_text_field++;
				checkEles.push({id : msg,pos : i});
			}else{
				if(!isNaN(parseInt($('incredient_'+i+'_id').value)) && parseInt($('incredient_'+i+'_id').value) != 0){
					no_of_text_field++;
					checkEles.push({id : parseInt($('incredient_'+i+'_id').value),pos : i});
				}
			}
		}
		if($("incredient_"+i).value != ""){
			valid_rows++;
			no_incredient=false;
		}
	}
	if(SubmitPressed){
		if(valid_rows == 0){
			setInvalid = false;
			SubmitPressed = false;
			no_of_text_field++;
			check({responseText: msg_no_valid_incredient+'|||1'});
			setInvalid = true;
			no_incredient = true;
		}else{
			stopValidation = true;
			document.forms["recipeForm"].submit();
		}
	}else{
		for(i=1; i<=no_of_rows_incredients; i++){
			row = '';
			if($('incredient').rows.length > i+1){
				row = $('incredient').rows[i+1];
			}
			if(row != '' && $(row).down().hasClassName("errorDiv") && !(no_incredient && i==1)){
				$('incredient').deleteRow(i+1);
				errorrow.each(function(err){if(err.id==i){err.value=0;}}); 
			}
		}
		if(no_of_text_field > 0){
			if(checkEles.length > 0){
				checkEles.each(function(ele){check({responseText: ele.id+'|||'+ele.pos});});
			}
		}else{
			validating = false;
		}
	}
	init();
	return false;
}
function check(transport)
{
	row = '';
	trans = transport.responseText.split('|||');
	var errorrows = 0;
	i = (+trans[1]);
	errorrow.each(function(err){if(err.id<i){errorrows = err.value+errorrows;}});
	if(parseInt(trans[0]) > 0){
		$("incredient_"+trans[1]+"_id").value = parseInt(trans[0]);
		if($('incredient').rows.length > (+trans[1])+errorrows+1){
			row = $('incredient').rows[(+trans[1])+errorrows+1];
		}
		if(row != '' && $(row).down().hasClassName("errorDiv") && !invalidUnitMsg[i]){
			$('incredient').deleteRow((+trans[1])+errorrows+1);
			errorrow.each(function(err){if(err.id==i){err.value=0;}});
		}
	}else{
		if($('incredient').rows.length > (+trans[1])+errorrows+1){
			row = $('incredient').rows[(+trans[1])+errorrows+1];
		}
		if(row != '' && $(row).down().hasClassName("errorDiv")){
			var new_row = row;
			var col1 = row.cells[0];
		}else{
			var new_row = $('incredient').insertRow((+trans[1])+errorrows+1);
			var col1 = new_row.insertCell(0);
			col1.colSpan = "3";
			$(col1).addClassName("errorDiv");
			errorrow.each(function(err){if(err.id==i){err.value=1;}});
		}
		if(trans[0]==msg_incredient_not_valid)
			$("incredient_"+trans[1]+"_id").value = -1;
		col1.innerHTML = trans[0];
		error++;
	}
	no_of_text_field--;
	if(no_of_text_field == 0){
		if(SubmitPressed){
			if(error == 0){
				document.forms["recipeForm"].submit();
			}else{
				SubmitPressed = false;
			}
		}
		validating = false;
	}
}
function convertNumber(sn__value){
	var ss__decimalSep = decimalSep||',';
	var ss__thousandSep = thousandSep||' ';
	var as__groupSize = 3 ;
	sn__value = ''+sn__value+'';
	sn__value = sn__value.replace(String.fromCharCode(160),' ');
	if(sn__value == '')
		return sn__value;
	if(sn__value.indexOf(ss__decimalSep) != sn__value.lastIndexOf(ss__decimalSep))
		return sn__value;
	if(sn__value.indexOf(ss__decimalSep) != -1){
		ss__afterDecimal = sn__value.substr(sn__value.indexOf(ss__decimalSep)+1);
		ss__beforeDecimal = sn__value.substr(0,sn__value.indexOf(ss__decimalSep));
	}else{
		ss__afterDecimal = '';
		ss__beforeDecimal = sn__value;
	}
	sn__pos = ss__beforeDecimal.length;
	while((sn__pos = (sn__pos - as__groupSize - 1)) > 0){
		if(ss__beforeDecimal.substr(sn__pos,1) == ss__thousandSep)
			ss__beforeDecimal = ss__beforeDecimal.substr(0,sn__pos)+ss__beforeDecimal.substr(sn__pos+1);
	}
	if(ss__beforeDecimal == '')
		ss__beforeDecimal = 0;
	if(ss__afterDecimal == '')
		return ss__beforeDecimal;
	else
		return ss__beforeDecimal+'.'+ss__afterDecimal;
}
var focusEvent = function (event){
	temp = Event.element(event).id.split('_');
	curRow = (+temp[1]);
	curEle = temp[0];
	if(lastEle == 'incredient' && !(curRow == lastRow && lastEle == curEle))
		setTimeout(validate,10,[false]);
	return true;
};
var blurEvent = function (event){
	temp = Event.element(event).id.split('_');
	lastRow = (+temp[1]);
	lastEle = temp[0];
	if(lastEle != 'incredient')
		setTimeout(validate,10,[false]);
	return true;
};
var changeEvent = function (event){
	setTimeout(function(){validate(false,true);},10);
	return true;
};
var otherFocusEvent = function(event){
	if(curRow != 0){
		curRow = 0;
		curEle = 0;
		setTimeout(validate,100,[false]);
	}else{
		lastRow=0;
		lastEle=0;
	}	
	return true;
}; 
var onChangeIncredient = function(event){
	var IncreEle = Event.element(event);
	var increPos = (+IncreEle.id.split('_')[1]);
	if($('incredient_'+increPos+'_id').value != 0 )
	{
		$('incredient_'+increPos+'_id').value = 0;
		units[increPos] = [];
		for(k=0;k<units[0].length;k++)
			units[increPos].push(units[0][k].value);
		unitsManage(increPos);
	}
};
function submitClicked(event){
	validate(true);
	return true;
}
function init(){
	if(first){
		$('auto_complete').onscroll=function(){(HideMe)?clearInterval(HideMe):null;(blurrow)?(blurrow.focus()):null;};
		$('auto_complete').onclick=function(event){
		if(!(Event.element(event)).up('ul')) 
		{
			(HideMe)?clearInterval(HideMe):null;(blurrow)?(blurrow.focus()):null;
		}
		};
		no_of_rows_incredients = parseInt($('no_of_incredients').value);
		for(i=1; i<=no_of_rows_incredients; i++){
			new Ajax.CoolAutoComplete('incredient_'+i,'auto_complete', '/calculator/autoComplete/input/'+i, {minChars:3,tokens:'[]',afterUpdateElement: function (inputField, selectedItem) {$(inputField.id+'_id').value = selectedItem.id;afterUpdate((inputField.id.split('_')[1]),selectedItem.id);}});
		}
		document.forms["recipeForm"].onsubmit = function(event){return SubmitPressed;};
		try{ $('websubmit').type = "button"; }
		catch(e){ 
		submittext = $$('.button_innest').reduce().innerHTML;
		$('websubmit').parentNode.innerHTML = '<button id="websubmit" name="weblogin" type="button" value="Login" class="button button_big"><span class="button_inner"><span class="button_innest">'+submittext+'</span></span></button>'; 
		}
		Event.observe($('websubmit'),'click',submitClicked);
		Event.observe($('recipe_instruction'),'focus',otherFocusEvent);
		Event.observe($$('.addLink').reduce(),'focus',otherFocusEvent);
		Event.observe($('recipe_name'),'focus',otherFocusEvent);
		Event.observe($('portion'),'focus',otherFocusEvent);
		first = false;
	}
	for(i=1; i<=parseInt($('no_of_incredients').value); i++){
		Event.stopObserving($('qty_'+i),       'focus',focusEvent);
		Event.observe(      $('qty_'+i),       'focus',focusEvent);
		Event.stopObserving($('unit_'+i),      'focus',focusEvent);
		Event.observe(      $('unit_'+i),      'focus',focusEvent);
		Event.stopObserving($('incredient_'+i),'focus',focusEvent);
		Event.observe(      $('incredient_'+i),'focus',focusEvent);
		Event.stopObserving($('qty_'+i),       'blur',blurEvent);
		Event.observe(      $('qty_'+i),       'blur',blurEvent);
		Event.stopObserving($('unit_'+i),      'change',changeEvent);
		Event.observe(      $('unit_'+i),      'change',changeEvent);
		Event.stopObserving($('unit_'+i),      'blur',blurEvent);
		Event.observe(      $('unit_'+i),      'blur',blurEvent);
		Event.stopObserving($('incredient_'+i),'blur',blurEvent);
		Event.observe(      $('incredient_'+i),'blur',blurEvent);
		Event.stopObserving($('incredient_'+i),'change',onChangeIncredient);
		Event.observe(      $('incredient_'+i),'change',onChangeIncredient);
	}
}
function afterUpdate(pos,id){
	pos = parseInt(pos);
	id = parseInt(id);
	if(pos > 0 && id > 0){
		new Ajax.Request('/calculator/units/id/'+id+'/pos/'+pos, {onSuccess: function(transport){ if(transport.responseText != ''){main = transport.responseText.split('|||');units[main[1]] = main[0].split(',');unitsManage(main[1]);}}});
	}else if(pos > 0){
		units[pos] = [];
		for(k=0;k<units[0].length;k++)
			units[pos].push(units[0][k].value);
		unitsManage(pos);
	}
}
var changeUnit = function(event){
	Event.stopObserving($('unit_'+(+Event.element(event).id.split('_')[1])),'change',changeUnit);
	invalidUnitMsg[(+Event.element(event).id.split('_')[1])] = false;
};
function unitsManage(rowPos){
	oldValue = $('unit_'+rowPos).value;
	found=false;
	$('unit_'+rowPos).options.length = 0;
	temp = [];
	for(k=0;k<units[0].length;k++){
		temp[units[0][k].value] = units[0][k].text;
	}
	for(k=0;k<units[rowPos].length;k++){
		if(units[rowPos][k] == oldValue) found = true;
		$('unit_'+rowPos).options[$('unit_'+rowPos).options.length] = new Option(temp[units[rowPos][k]],units[rowPos][k]);
	}
	if(!found){
		$('unit_'+rowPos).value = 0;
		invalidUnitMsg[rowPos] = true;
		validate(false);
		Event.observe($('unit_'+rowPos),'change',changeUnit);
	}
	else
		$('unit_'+rowPos).value = oldValue;		
}