Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Global Variables
- var pageLoaded = false;
- var advFermSteps = [];
- var advFermHeaders = [];
- var beerStylesJSON;
- var styleGuides = [];
- var fermentableIngredients;
- var hopIngredients;
- var maxFermentableCount = 12;
- var maxHopCount = 12;
- var maxFermStepCount = 5;
- var recipeGrains = [];
- var recipeGrainHeaders = [];
- var recipeHops = [];
- var recipeHopsHeaders = [];
- var recipeAdjType = new Array();
- var recipeAdjAmt = new Array();
- var recipeAdjTime = new Array();
- var recipeFermType = new Array();
- var recipeFermTemp = new Array();
- var recipeFermTime = new Array();
- var grainSum = 0;
- var gravitySum = 0;
- var colorSum = 0;
- //constant
- var maxGrainTypes = 8;
- //added efficiency var for scope
- var eff = 0;
- //get variable values
- var origBit;
- var recipeName;
- var recipeAuth;
- var type;
- var H2O;
- var origName;
- var origAuth;
- var mashTemp;
- var mashTime;
- var mashType;
- var boilTime;
- var boilTemp;
- var boilType;
- var ABV;
- var OG;
- var FG;
- var IBU;
- var SRM;
- var fermentorWort = $("[name = beerWort]").val();
- //var fermentorWort = finBeer + 0.2;
- var yeastAA;
- var yeastPitch;
- var mashType;
- var custText;
- var guid;
- var notes;
- var cookTemp;
- var cookTime;
- var waterType;
- var amend1;
- var amend2;
- var amend3;
- var amend4;
- var amendAmt1;
- var amendAmt2;
- var amendAmt3;
- var amendAmt4;
- var adj1;
- var adjAmt1;
- var adjTime1;
- var adjUse1;
- var adj2;
- var adjAmt2;
- var adjTime2;
- var adjUse2;
- var beerText;
- //String Outputs for US and Metric
- var grainLimitUS = 9.0;
- var grainLimitMetric = ConvertLBsToKG(grainLimitUS).toFixed(2);
- var grainLimitUSString = grainLimitUS.toString() + " lbs";
- var grainLimitMetricString = grainLimitMetric.toString() + " kgs";
- var finBeerMaxUS = 3.5;
- var finBeerMaxMetric = 13.25;
- var hopLimitUS = 1.5;
- var hopLimitMetric = 43;
- var hopLimitUSString = "1.5 oz."
- var hopLimitMetricString = "43 grams"
- var mashTempMaxUS = 207;
- var mashTempMaxMetric = ConvertCelciusToFahrenheit(207);
- //Yeast Data
- var yeast;
- var yeastName = new Array();
- var yeastMfg = new Array(); //array
- var yeastNumber = new Array(); //array
- var yeastMinAtten = new Array(); //array
- var yeastMaxAtten = new Array(); //array
- var yeastMinTemp = new Array(); //array
- var yeastMaxTemp = new Array(); //array
- var yeastFloculation = new Array(); //array
- var yeastID = new Array();
- //Global Functions
- function ConverGToLiters(gallons)
- {
- return 3.78541178 * gallons;
- }
- function ConvertLBsToKG(pounds)
- {
- return 0.45359237 * pounds;
- }
- function ConvertOZtoKG(oz)
- {
- return 0.0283495231 * oz;
- }
- function ConvertCelciusToFahrenheit(celcius)
- {
- return parseFloat((celcius * 1.8) + 32.0);
- }
- function RoundedConvertFahrenheitToCelcius(fahrenheit)
- {
- return parseFloat(((fahrenheit - 32) / 1.8).toFixed(1));
- }
- function RoundedConvertLitersToGallons(liters)
- {
- return parseFloat((liters * 0.26417205).toFixed(2));
- }
- function RoundedConvertKgToLbs(kg)
- {
- return parseFloat((kg * 2.20462262).toFixed(2));
- }
- function RoundedConvertGallonToLiters(gallon)
- {
- return parseFloat((gallon * 3.78541178).toFixed(2));
- }
- function ConvertOunceToGram(ounces)
- {
- return ounces * 28.3495231;
- }
- function ConvertGramToOunce(grams)
- {
- return grams * 0.03527396;
- }
- $(document).ready(function ()
- {
- //page load modal
- $('#loadModal').modal('show');
- var grainLoad = false;
- var hopLoad = false;
- var yeastLoad = false;
- var styleLoad = false;
- //Load variables when document is loaded
- custText = parseInt($("[name = custText]").val());
- amend1 = $("#waterAmend1").val();
- amend2 = $("#waterAmend2").val();
- amend3 = $("#waterAmend3").val();
- amend4 = $("#waterAmend4").val();
- H2O = $("#H2O").text();
- origBit = $("[name = origBit]").val();
- recipeName = $("[name = recipe_name]").val();
- recipeAuth = $("[name = recAuth]").val();
- type = $("[name = recipe_type]").val();
- origName = $("#origName").val();
- origAuth = $("#origAuth").val();
- mashTemp = $("[name = mashTemp]").val();
- mashTime = $("[name = mashTime]").val();
- mashType = $("[name = mash_type]").val();
- boilTime = parseInt($("#boilTime").val());
- boilTemp = $("[name = boilTemp]").val();
- boilType = $("#boilType").val();
- ABV = $("#ABV").text();
- OG = $("#OG").val();
- FG = $("#FG").text();
- IBU = $("#IBU").val();
- SRM = $("#SRM").text();
- //var fermentorWort = $("[name = beerWort]").val();
- fermentorWort = finBeer + 0.2;
- yeastAA = $("[name = yeastExp]").val();
- yeastPitch = $("[name = yeastPitch]").val();
- mashType = $("#mashType").val();
- guid = $("[name = previous]").val();
- notes = $("[name = recipe_Notes]").val();
- cookTemp = unitInUS ? $("[name = cookTemp]").val() : ConvertCelciusToFahrenheit($("[name = cookTemp]").val());
- cookTime = $("[name = cookTime]").val();
- waterType = $("[name=water]").val();
- amendAmt1 = $("#amendAmt1").val();
- amendAmt2 = $("#amendAmt2").val();
- amendAmt3 = $("#amendAmt3").val();
- amendAmt4 = $("#amendAmt4").val();
- adj1 = $("[name=adj1]").val();
- adjAmt1 = $("[name=adjAmt1]").val();
- adjTime1 = $("[name=adjTime1]").val();
- adjUse1 = $("[name=adjUse1]").val();
- adj2 = $("[name=adj2]").val();
- adjAmt2 = $("[name=adjAmt2]").val();
- adjTime2 = $("[name=adjTime2]").val();
- adjUse2 = $("[name=adjUse2]").val();
- beerText = $("#beer-text").val();
- if (!!fermentablesList && fermentablesList.length > 0) {
- }
- //Document Ready Helper Function
- function loadLogic(type)
- {
- //Set the loaded variable to true whenthe AJAX call has completed
- switch (type)
- {
- case 0:
- grainLoad = true;
- break;
- case 1:
- hopLoad = true;
- break;
- case 2:
- yeastLoad = true;
- break;
- case 3:
- styleLoad = true;
- break;
- default:
- break;
- }
- //When all AJAX calls have been completed, return access of crafter to user
- if (grainLoad && hopLoad && yeastLoad && styleLoad)
- {
- //Populate the dynamic data
- populateFermentationSteps();
- checkAdvancedFermSchedule();
- init();
- //Set the excessive boil time and don't allow any value less than 0
- $("#excessBoil").val(Math.max(0, $("#boilTime").val() - parseInt($("#hopBoil").html())));
- //hide loading modal
- $('#loadModal').modal('hide');
- loaded();
- }
- }
- $("#saveButtonOther").hide();
- //Get BeerStyles and save into JSON interpreted variable;
- $.ajax({
- url: "/Json/BeerJson.cshtml",
- dataType: "json",
- success: function (data)
- {
- beerStylesJSON = data;
- populateBeverageStyles();
- loadLogic(3);
- }
- });
- //Get Fermentables\Grains
- $.ajax({
- url: "/Json/grainsJson.cshtml",
- dataType: "json",
- success: function (data)
- {
- fermentableIngredients = data;
- populateFermentablesIngredients();
- if (!!fermentablesList && fermentablesList.length > 0) {
- recipeGrains = fermentablesList;
- for (var i = 0; i < recipeGrains.length; i++) {
- recipeGrains[i].Ingredient = fermentableIngredients[recipeGrains[i].FermentableID];
- }
- }
- organizeGrains();
- loadLogic(0);
- }
- });
- //hops
- $.ajax({
- url: "/Json/hopsJson.cshtml",
- dataType: "json",
- success: function (data)
- {
- hopIngredients = data;
- populateHopIngredients();
- if (!!hopList && hopList.length > 0) {
- recipeHops = hopList;
- for (var i = 0; i < recipeHops.length; i++) {
- recipeHops[i].Ingredient = hopIngredients[recipeHops[i].HopID];
- }
- }
- organizeHops();
- loadLogic(1);
- }
- });
- //var recipeYeastType = 0;
- $.ajax({
- url: "/Json/yeastJson.cshtml",
- dataType: "json",
- success: function (data)
- {
- yeast = data;
- for (var i = 0; i < yeast.length; i++)
- {
- var yID = yeast[i].YeastID
- yeastName[yID] = yeast[i].Name;
- yeastMfg[yID] = yeast[i].Laboratory; //array
- yeastNumber[yID] = yeast[i].ProductID; //array
- yeastMinAtten[yID] = yeast[i].MinAtten; //array
- yeastMaxAtten[yID] = yeast[i].MaxAtten; //array
- yeastMinTemp[yID] = yeast[i].MinTemp; //array
- yeastMaxTemp[yID] = yeast[i].MaxTemp; //array
- yeastFloculation[yID] = yeast[i].FlocculationCode; //array
- yeastID[yID] = yeast[i].YeastID;
- }
- loadLogic(2);
- }
- });
- //updates bounds for default style
- function loaded()
- {
- //?? Why run twice?
- vitaStatsChangeBounds();
- textRecipeDescription();
- pageLoaded = true;
- if (!unitInUS)
- {
- //Change Units and re-run validations
- unitchange();
- }
- recalcForm();
- vitaStatsChangeBounds();
- textRecipeDescription();
- //recalculate the form
- recalcForm();
- }
- function validHopTime()
- {
- var isValid = false;
- var count = 0;
- var hopTimes = new Array();
- for (var i = 1; i < 8; i++)
- {
- var time = parseInt($('[name=hopTime' + i + ']').val());
- if (time != 0)
- {
- var index = hopTimes.indexOf(time);
- if (index < 0)
- {
- hopTimes[count] = time;
- count++;
- }
- }
- }
- if (count > 4)
- {
- return false;
- }
- return true;
- }
- $("[name = yeast]").change(function ()
- {
- var temp = this.value;
- $('[name=yeast]').removeClass("error");
- if (temp == 0)
- {
- $("#yeastAtten").html("0 - 0");
- $("#yeastTemp").html("0 - 0");
- $("[name=yeastExp]").val(70);
- $("[name=yeastPitch]").val(unitInUS ? 75 : RoundedConvertFahrenheitToCelcius(75));
- $("[name = yeast]").addClass("error");
- var warning = "Yeast is a required field";
- $('#warnings-yeasts').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- else
- {
- $("[name = yeast]").removeClass("error");
- $('#warnings-yeasts').empty();
- $("#yeastAtten").html(yeastMinAtten[temp] + " - " + yeastMaxAtten[temp]);
- $("#yeastTemp").html((unitInUS ? yeastMinTemp[temp] : RoundedConvertFahrenheitToCelcius(yeastMinTemp[temp])) + " - " + (unitInUS ? yeastMaxTemp[temp] : RoundedConvertFahrenheitToCelcius(yeastMaxTemp[temp])));
- $("[name=yeastExp]").val(parseInt((yeastMinAtten[temp] + yeastMaxAtten[temp]) / 2));
- yeastPitch = parseInt((yeastMinTemp[temp] + yeastMaxTemp[temp]) / 2);
- $("[name=yeastPitch]").val(unitInUS ? yeastPitch : RoundedConvertFahrenheitToCelcius(yeastPitch));
- $('[name=yeastPitch]').removeClass("error");
- $('[name=yeastExp]').removeClass("error");
- }
- fermScheduleChange($("#fermTypeSelection")[0]);
- recalcForm();
- });
- $("[name=finBeer]").change(function ()
- {
- if (unitInUS)
- {
- finBeer = parseFloat($("[name=finBeer]").val());
- } else
- {
- finBeer = RoundedConvertLitersToGallons(parseFloat($("[name=finBeer]").val()));
- }
- recalcForm();
- });
- function validateAmendment(target) {
- var index = target.dataset.index;
- if (!!index) {
- var input = $("#amendAmt" + index)[0];
- var amount = parseInt(input.value);
- if (amount < 0) {
- $(input).val(0);
- var warning = "Water amendment amount " + index + " is not a number. Reset to 0.";
- $('#warnings-water').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- }
- }
- $(document).on("change", ".water-amend-amount", function () {
- validateAmendment(this);
- });
- function validYeast()
- {
- var validExp = false;
- var validPitch = false;
- var maximum = 100;
- if (!unitInUS)
- {
- maximum = RoundedConvertFahrenheitToCelcius(maximum);
- }
- $('#all').wrap('<form id="temp_form_id" />');
- $('#temp_form_id').validate({
- rules: {
- yeastPitch: {
- required: true,
- number: true,
- max: maximum,
- min: 0
- },
- yeastExp: {
- required: true,
- number: true,
- max: 100,
- min: 0
- }
- },
- errorPlacement: function ()
- {
- return false;
- }
- });
- $('#warnings-yeasts').empty();
- validPitch = $('[name=yeastPitch]').valid();
- validExp = $('[name=yeastExp]').valid();
- $('#all').unwrap();
- count = 0;
- if (!validPitch)
- {
- if (unitInUS)
- {
- $('[name=yeastPitch]').val(70);
- } else
- {
- $('[name=yeastPitch]').val(RoundedConvertFahrenheitToCelcius(70));
- }
- count++;
- var warning = "Yeast pitch temp is out of range, must be between 0 and " + (unitInUS ? "100 F" : RoundedConvertFahrenheitToCelcius(100) + "C") + ". Reset.";
- $('#warnings-yeasts').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- } else
- {
- yeastPitch = unitInUS ? $('[name=yeastPitch]').val() : ConvertCelciusToFahrenheit($('[name=yeastPitch]').val());
- }
- if (!validExp)
- {
- $('[name=yeastExp]').val(75);
- count++;
- var warning = "Yeast expected AA is out of range, must be between 0 and 100. Reset.";
- $('#warnings-yeasts').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (count > 0)
- {
- return false;
- }
- return true;
- }
- $('[name=yeastExp]').change(function ()
- {
- var valid = validYeast();
- if (valid)
- {
- recalcForm();
- }
- });
- $('[name=yeastPitch]').change(function ()
- {
- validYeast();
- fermScheduleChange($("#fermTypeSelection")[0]);
- });
- function validMash()
- {
- var maximum = 207;
- if (!unitInUS)
- {
- maximum = RoundedConvertFahrenheitToCelcius(maximum);
- }
- var validTemp = false;
- var validTime = false;
- $('#all').wrap('<form id="temp_form_id" />');
- $('#temp_form_id').validate({
- rules: {
- mashTemp: {
- required: true,
- max: maximum,
- min: 0
- },
- mashTime: {
- required: true,
- digits: true,
- max: 360,
- min: 0
- }
- },
- errorPlacement: function ()
- {
- return false;
- }
- });
- $('#warnings-mash').empty();
- validTemp = $('[name=mashTemp]').valid();
- validTime = $('[name=mashTime]').valid();
- $('#all').unwrap();
- count = 0;
- if (!validTemp)
- {
- if (unitInUS)
- {
- $('[name=mashTemp]').val(152);
- } else
- {
- $('[name=mashTemp]').val(RoundedConvertFahrenheitToCelcius(152));
- }
- count++;
- var warning = "Mash Temp out of range (" + (unitInUS ? "0-207 F" : "0 - 97 C") + "). Reset to default.";
- $('#warnings-mash').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (!validTime)
- {
- $('[name=mashTime]').val(90);
- count++;
- var warning = "Mash time out of range (max 360). Reset to default.";
- $('#warnings-mash').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (count > 0)
- {
- return;
- }
- recalcForm();
- }
- $('[name=mashTemp]').change(function ()
- {
- validMash();
- });
- $('[name=mashTime]').change(function ()
- {
- validMash();
- });
- function validBoil()
- {
- var maximum = 207;
- if (!unitInUS)
- {
- maximum = RoundedConvertFahrenheitToCelcius(maximum);
- }
- var validTemp = false;
- var validTime = false;
- $('#all').wrap('<form id="temp_form_id" />');
- $('#temp_form_id').validate({
- rules: {
- boilTemp: {
- required: true,
- max: maximum,
- min: 0
- },
- boilTime: {
- required: true,
- digits: true,
- max: 360,
- min: 0
- }
- },
- errorPlacement: function ()
- {
- return false;
- }
- });
- $('#warnings-boil').empty();
- validTemp = $('[name=boilTemp]').valid();
- validTime = $('#boilTime').valid();
- $('#all').unwrap();
- count = 0;
- if (!validTemp)
- {
- if (unitInUS)
- {
- $('[name=boilTemp]').val(207);
- } else
- {
- $('[name=boilTemp]').val(RoundedConvertFahrenheitToCelcius(207));
- }
- count++;
- var warning = "Boil Temp out of range (" + (unitInUS ? "0-207 F" : "0 - 97 C") + "). Reset to default.";
- $('#warnings-boil').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (!validTime)
- {
- $('#boilTime').val(90);
- count++;
- var warning = "Boil time out of range (max 360). Reset to default.";
- $('#warnings-boil').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (count > 0)
- {
- return;
- }
- recalcForm();
- }
- $('[name=boilTemp]').change(function ()
- {
- validBoil();
- });
- $('#boilTime').change(function ()
- {
- validBoil();
- });
- function validFerm()
- {
- var validTemp1 = false;
- var validTime1 = false;
- var validTemp2 = false;
- var validTime2 = false;
- var maximum = 100;
- if (!unitInUS)
- {
- maximum = RoundedConvertFahrenheitToCelcius(maximum);
- }
- $('#all').wrap('<form id="temp_form_id" />');
- $('#temp_form_id').validate({
- rules: {
- fermTemp1: {
- required: true,
- max: maximum,
- min: 0
- },
- fermTemp2: {
- required: true,
- max: maximum,
- min: 0
- },
- fermTime1: {
- required: true,
- digits: true,
- min: 0
- },
- fermTime2: {
- required: true,
- digits: true,
- min: 0
- }
- },
- errorPlacement: function ()
- {
- return false;
- }
- });
- $('#warnings-ferm').empty();
- validTemp1 = $('[name=fermTemp1]').valid();
- validTime1 = $('[name=fermTime1]').valid();
- validTemp2 = $('[name=fermTemp2]').valid();
- validTime2 = $('[name=fermTime2]').valid();
- $('#all').unwrap();
- count = 0;
- if (!validTemp1)
- {
- $('[name=fermTemp1]').val(0);
- count++;
- var warning = "Ferm temp out of range, reset to 0.";
- $('#warnings-ferm').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (!validTime1)
- {
- $('[name=fermTime1]').val(0);
- count++;
- var warning = "Ferm time out of range, reset to 0.";
- $('#warnings-ferm').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (!validTemp2)
- {
- $('[name=fermTemp2]').val(0);
- count++;
- var warning = "Ferm temp out of range, reset to 0.";
- $('#warnings-ferm').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (!validTime2)
- {
- $('[name=fermTime2]').val(0);
- count++;
- var warning = "Ferm time out of range, must be rounded to the nearest minute greater than zero, reset to 0.";
- $('#warnings-ferm').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- }
- function validAdj()
- {
- var validAmt1 = false;
- var validTime1 = false;
- var validAmt2 = false;
- var validTime2 = false;
- $('#all').wrap('<form id="temp_form_id" />');
- $('#temp_form_id').validate({
- rules: {
- adjAmt1: {
- required: true,
- number: true,
- min: 0
- },
- adjTime1: {
- required: true,
- digits: true,
- min: 0
- },
- adjAmt2: {
- required: true,
- number: true,
- min: 0
- },
- adjTime2: {
- required: true,
- digits: true,
- min: 0
- }
- },
- errorPlacement: function ()
- {
- return false;
- }
- });
- $('#warnings-adj').empty();
- validAmt1 = $('[name=adjAmt1]').valid();
- validTime1 = $('[name=adjTime1]').valid();
- validAmt2 = $('[name=adjAmt2]').valid();
- validTime2 = $('[name=adjTime2]').valid();
- $('#all').unwrap();
- count = 0;
- if (!validAmt1)
- {
- $('[name=adjAmt1]').val(0);
- count++;
- var warning = "Adjunct quantity out of range, reset to 0.";
- $('#warnings-adj').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- } else
- {
- adjAmt1 = unitInUS ? $("[name=adjAmt1]").val() : ConvertOunceToGram($("[name=adjAmt1]").val()).toFixed(2);
- }
- if (!validTime1)
- {
- $('[name=adjTime1]').val(0);
- count++;
- var warning = "Adjunct time out of range, reset to 0.";
- $('#warnings-adj').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (!validAmt2)
- {
- $('[name=adjAmt2]').val(0);
- count++;
- var warning = "Adjunct quantity out of range, reset to 0.";
- $('#warnings-adj').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- } else
- {
- adjAmt2 = unitInUS ? $("[name=adjAmt2]").val() : ConvertOunceToGram($("[name=adjAmt2]").val()).toFixed(2);
- }
- if (!validTime2)
- {
- $('[name=adjTime2]').val(0);
- count++;
- var warning = "Adjunct time out of range, must be rounded to the nearest minute greater than zero, reset to 0.";
- $('#warnings-adj').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- recalcForm();
- }
- $('[name=adj1]').change(function ()
- {
- if ($('[name=adj1]').val() == 0)
- {
- $('[name=adjAmt1]').val(0);
- $('[name=adjAmt1]').removeClass("error");
- $('[name=adjTime1]').val(0);
- $('[name=adjTime1]').removeClass("error");
- $('[name=adj1]').removeClass("error");
- }
- });
- $('[name=adj2]').change(function ()
- {
- if ($('[name=adj2]').val() == 0)
- {
- $('[name=adjAmt2]').val(0);
- $('[name=adjAmt2]').removeClass("error");
- $('[name=adjTime2]').val(0);
- $('[name=adjTime2]').removeClass("error");
- $('[name=adj2]').removeClass("error");
- }
- });
- $('[name=adjAmt1]').change(function ()
- {
- validAdj();
- });
- $('[name=adjAmt2]').change(function ()
- {
- validAdj();
- });
- $('[name=adjTime1]').change(function ()
- {
- validAdj();
- });
- $('[name=adjTime2]').change(function ()
- {
- validAdj();
- });
- $("#OG").change(function ()
- {
- $("#warning-vitalstats").empty();
- var temp = parseFloat($("#OG").val());
- solveOG();
- checkBetweenBounds();
- $("[name=OG]").val(Math.round(OG * 1000) / 1000);
- recalcForm();
- });
- $("#IBU").change(function ()
- {
- var temp = parseFloat($("#IBU").val());
- if (IBU != 0 && temp != 0)
- {
- var iter = 0;
- var errorThresh = 0.5;
- while (Math.abs(temp - IBU) > errorThresh && iter < 10)
- {
- var scaleFactor = temp / IBU;
- solveIBU(scaleFactor);
- iter = iter + 1;
- }
- $("#IBU").html(Math.round(IBU));
- recalcForm();
- }
- });
- $("#BeerStyle").change(function ()
- {
- vitaStatsChangeBounds();
- textRecipeDescription();
- });
- function clearErrors()
- {
- $('#warnings-general').empty();
- $('#warnings-all').empty();
- $('#warnings-grains').empty();
- $('#warnings-hops').empty();
- $('#warnings-adj').empty();
- $('#warnings-water').empty();
- $('#warnings-mash').empty();
- $('#warnings-boil').empty();
- $('#warnings-yeasts').empty();
- $('#warnings-ferm').empty();
- $('#warnings-notes').empty();
- }
- function beerVis()
- {
- $("#beerRec1").show();
- $("#beerRec2").show();
- $("#beerRec3").show();
- $("#beerRec4").show();
- $("#beerRec5").show();
- $("#beerRec6").show();
- $("#otherRec1").hide();
- $("#otherRec2").hide();
- $("#saveButtonOther").hide();
- $("#saveButton").show();
- }
- function otherVis()
- {
- $("#beerRec1").hide();
- $("#beerRec2").hide();
- $("#beerRec3").hide();
- $("#beerRec4").hide();
- $("#beerRec5").hide();
- $("#beerRec6").hide();
- $("#otherRec1").show();
- $("#otherRec2").show();
- $("#saveButtonOther").show();
- $("#saveButton").hide();
- }
- $("#type").change(function ()
- {
- clearErrors();
- var val = $("#type").val();
- if (val == 0)
- {
- beerVis();
- }
- else if (val == 1)
- {
- otherVis();
- }
- });
- $('[name=recipe_name]').change(function ()
- {
- origBit = $("[name = origBit]").val();
- if (origBit == 0)
- {
- $('#origName').val($('[name=recipe_name]').val());
- }
- });
- //Function to send post data to the recipe saver
- $("#saveButton").click(function ()
- {
- $('#warnings-general').empty();
- var isValid = validAll();
- $(document).scrollTop(0);
- if (!isValid)
- {
- return;
- }
- $("#buttonHide").hide();
- $('#msgBod2').html("<p>Saving Recipe</p>");
- $('#loadModal').modal('show');
- var numSes = $("#numSes").val();
- //Fix the arrays to ensure post data is complete
- recalcForm();
- gatherNonCalc();
- var serializedFermSteps = JSON.stringify(advFermSteps);
- var serializedIngredients = JSON.stringify(recipeGrains);
- var serializedHops = JSON.stringify(recipeHops);
- $.ajax({
- type: "POST",
- url: "saverecipe.cshtml",
- //first one is the variable the other file will get. second one is the variable i send over
- data: {
- Name: recipeName,
- User: recipeAuth,
- Notes: notes,
- wort: finBeer,
- boil: boilTime,
- originalGravity: OG,
- finalGravity: FG,
- bitternes: IBU,
- color: SRM,
- alcohol: ABV,
- MashTemp: mashTemp,
- MashTime: mashTime,
- boilTemp: boilTemp,
- WaterAmount: H2O,
- Eff: eff,
- beerNumber: $("#BeerStyle").val(),
- Type: type,
- origGUID: guid,
- origName: origName,
- origAuth: origAuth,
- boilType: boilType,
- mashType: mashType,
- yeastAA: yeastAA,
- yeastPitch: yeastPitch,
- waterType: waterType,
- numSes: numSes,
- yeast: recipeYeastType,
- adj1: adj1,
- adj2: adj2,
- adjAmt1: adjAmt1,
- adjAmt2: adjAmt2,
- adjTime1: adjTime1,
- adjTime2: adjTime2,
- adjUse1: adjUse1,
- adjUse2: adjUse2,
- uGUID: uGUID,
- beerText: beerText,
- amend1: amend1,
- amend2: amend2,
- amend3: amend3,
- amend4: amend4,
- amendAmt1: amendAmt1,
- amendAmt2: amendAmt2,
- amendAmt3: amendAmt3,
- amendAmt4: amendAmt4,
- mashType: mashType,
- fermentationSteps: serializedFermSteps,
- grainIngredients: serializedIngredients,
- hopIngredients: serializedHops,
- fileGuid: fileGuid,
- importBit: fileImport
- },
- success: function (stuff)
- {
- if (stuff.indexOf("!!!") != -1)
- {
- var returned = stuff.toString();
- var startI = returned.indexOf("!!!") + 3;
- var endI = returned.indexOf("???");
- var newGUID = returned.substr(startI, endI - startI);
- $("#loadModal").hide();
- clearErrors();
- window.location.replace('/Members/Recipes/ParseRecipe.cshtml?id=' + newGUID);
- }
- else if (stuff.indexOf("###") != -1)
- {
- $('#loadModal').modal('hide');
- $('#msgHead').css('background-color', 'red');
- $('#myModalLabel').text("Error");
- stuff = stuff.replace("###", "");
- $('#msgBod').html(stuff);
- $("#buttonHide").show();
- $("#savingMsg").hide();
- window.setTimeout($('#myModal').modal('show'), 500);
- }
- else
- {
- window.location.replace('/');
- }
- }
- });
- });
- $("#cancel").click(function ()
- {
- window.location.replace('/Members/User/Brewhouse.cshtml');
- });
- function validAllOther()
- {
- var validName = false;
- var validNotes = false;
- var validTemp = false;
- var validTime = false;
- $('#all').wrap('<form id="temp_form_id" />');
- $('#temp_form_id').validate({
- rules: {
- recipe_name: {
- required: true,
- maxlength: 20
- },
- cookTime: {
- required: true,
- digits: true,
- max: 3570,
- min: 1
- },
- cookTemp: {
- required: true,
- max: unitInUS ? 207 : RoundedConvertFahrenheitToCelcius(207),
- min: unitInUS ? 33 : RoundedConvertFahrenheitToCelcius(33)
- },
- recipe_Notes: {
- required: false,
- maxlength: 4000
- }
- },
- errorPlacement: function ()
- {
- return false;
- }
- });
- clearErrors();
- validName = $('[name=recipe_name]').valid();
- validNotes = $('[name=recipe_Notes]').valid();
- validTemp = $('[name=cookTemp]').valid();
- validTime = $('[name=cookTime]').valid();
- $('#all').unwrap();
- if (recipeName.indexOf('#') > 0)
- {
- validName = false;
- }
- else if (recipeName.indexOf('/') > 0)
- {
- validName = false;
- }
- else if (recipeName.indexOf('|') > 0)
- {
- validName = false;
- }
- count = 0;
- if (!validName)
- {
- count++;
- var warning = "Recipe name is invalid (mandatory, 20 characters or less). Non-English characters and special characters except ' . _ - are not allowed.";
- $('#warnings-all').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (!validNotes)
- {
- count++;
- var warning = "Recipe notes are invalid (max length 4000).";
- $('#warnings-notes').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (!validTemp)
- {
- $('[name=cookTemp]').val(unitInUS ? 207 : RoundedConvertFahrenheitToCelcius(207));
- count++;
- var warning = "Cook temp out of bounds " + (unitInUS ? "(33-207 F)." : "(0.5-97 C).") + " Reset to max.";
- $('#warnings-all').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (!validTime)
- {
- $('[name=cookTime]').val(60);
- count++;
- var warning = "Cook time out of bounds (1-3570). Reset to 60.";
- $('#warnings-all').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- if (count > 0)
- {
- return false;
- }
- return true;
- }
- $("#saveButtonOther").click(function ()
- {
- var isValid = validAllOther();
- if (!isValid)
- {
- var warning = "The recipe is not valid. Please review error messages and try again.";
- $('#warnings-general').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- return;
- }
- gatherNonCalc();
- type = parseInt($("[name = recipe_type]").val());
- notes = $("[name = recipe_Notes]").val();
- cookTemp = unitInUS ? $("[name = cookTemp]").val() : ConvertCelciusToFahrenheit($("[name = cookTemp]").val());
- cookTime = $("[name = cookTime]").val();
- $("#buttonHide").hide();
- $("#savingMsg").show();
- $.ajax({
- type: "POST",
- url: "saveother.cshtml",
- data: {
- Name: recipeName, User: recipeAuth, Notes: notes, Time: cookTime, Temp: cookTemp, uGUID: uGUID, origName: origName, origAuth: origAuth, Type: type
- },
- success: function (stuff)
- {
- if (stuff.indexOf("!!!") != -1)
- {
- var returned = stuff.toString();
- var startI = returned.indexOf("!!!") + 3;
- var endI = returned.indexOf("???");
- var newGUID = returned.substr(startI, endI - startI);
- $("#loadModal").hide();
- clearErrors();
- window.location.replace('/Members/Recipes/ParseRecipe.cshtml?id=' + newGUID);
- }
- else if (stuff.indexOf("###") != -1)
- {
- $('#loadModal').modal('hide');
- $('#msgHead').css('background-color', 'red');
- $('#myModalLabel').text("Error");
- stuff = stuff.replace("###", "");
- $('#msgBod').html(stuff);
- $("#buttonHide").show();
- $("#savingMsg").hide();
- window.setTimeout($('#myModal').modal('show'), 500);
- }
- else
- {
- window.location.replace('/');
- }
- }
- });
- });
- //TODO?? DELETE?
- $("#beer-text").change(function ()
- {
- $('#warnings-all').empty();
- if ($("#beer-text").val() == "")
- {
- custText = 0;
- $("[name = custText]").val(0);
- textRecipeDescription();
- }
- else
- {
- $("[name = custText]").val(1);
- custText = 1;
- }
- var recReg = /^\s*[a-zA-Z0-9\'!&(,)?\/._\-\s]+\s*$/; ;
- beerText = $("#beer-text").val();
- if (beerText.match(recReg) == null)
- {
- custText = 0;
- $("[name = custText]").val(0);
- textRecipeDescription();
- var warning = "Tasting notes are invalid, only alphanumeric input and the characters , ( ) ? ! ' . - and _ are permitted. ";
- $('#warnings-all').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- });
- $("#mashType").change(function ()
- {
- mashType = $("#mashType").val();
- if (mashType == 0)
- {
- $('[name = mashTemp]').prop('disabled', false);
- $('[name = mashTime]').prop('disabled', false);
- }
- else if (mashType == 1)
- {
- $('[name = mashTemp]').prop('disabled', true);
- $('[name = mashTime]').prop('disabled', true);
- }
- recalcForm();
- });
- $("#recipe_name").change(function ()
- {
- var recReg = /^\s*[a-zA-Z0-9\'._\-\s]+\s*$/;
- recipeName = $("[name = recipe_name]").val();
- if (recipeName.match(recReg) == null)
- {
- var warning = "Recipe name is invalid, only alphanumeric input and the characters ' . - and _ are permitted. Max length is 20 characters.";
- $('#warnings-all').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- $("[name = recipe_name]").val("New Recipe");
- }
- });
- $(document).on("focus", "div.search > input", function(){
- var results = $(this.parentNode).children(".results");
- for(var i = 0; i < results.length; i++) {
- $(results[i]).show();
- }
- });
- $(document).on("mouseenter", ".results", function () {
- $(this).data("user-focus", true);
- })
- $(document).on("mouseleave", ".results", function () {
- $(this).data("user-focus", false);
- })
- $(document).on("blur", "div.search > input", function(){
- var results = $(this.parentNode).children(".results");
- for (var i = 0; i < results.length; i++) {
- if (!$(results[i]).data("user-focus")) {
- $(results[i]).hide();
- }
- }
- });
- $("#cookTemp").change(function () {
- cookTemp = unitInUS ? this.valueAsNumber : ConvertCelciusToFahrenheit(this.valueAsNumber);
- });
- function delayHide(target, delay) {
- setTimeout(function(){
- $(target).hide();
- }, delay);
- }
- function init() {
- var maxHopTime = 0;
- for (var i = 0; i < recipeHops.length; i++) {
- if (recipeHops[i].Time > maxHopTime) {
- maxHopTime = recipeHops[i].Time;
- }
- }
- $("#hopBoil").html(maxHopTime);
- }
- });
- //Fermentation Standard Temperatures
- var aleFermTemp = 66;
- var aleFermTimeDays = 10;
- var lagerFermTemp = 55;
- var lagerTemp = 35;
- //=====================CHANGE EVENT HANDLERS=====================
- //Function that executes when unit changes are made
- function unitchange()
- {
- var unitSelected = document.getElementById("unit");
- if (unitSelected.options[unitSelected.selectedIndex].value == 0)
- //US Unit Changes
- {
- unitInUS = true;
- //Change all temp labels to show F for symbol instead of C
- $(".temperature").each(function ()
- {
- $(this).html($(this).html().replace("(C)", "(F)"));
- });
- //Change all liquid to show G symbol instead of L
- $(".liquid").each(function ()
- {
- $(this).html($(this).html().replace("(L)", "(G)"));
- });
- //Change all liquid to show G symbol instead of L
- $(".poundKilo").each(function ()
- {
- $(this).html($(this).html().replace("(kg)", "(lb)"));
- });
- $(".ounceGram").each(function ()
- {
- $(this).html($(this).html().replace("(g)", "(oz)"));
- });
- $(".tspGram").each(function ()
- {
- $(this).html($(this).html().replace("(g)", "(tsp)"));
- });
- //Sous Vide Changes
- $("#cookTemp").val(cookTemp);
- //Remove Metric Warning
- var metricWarning = document.getElementById("metricWarning");
- metricWarning.style.visibility = 'hidden';
- metricWarning.style.display = 'none';
- //Beer Volume in US units
- $("#finBeer").val(parseFloat(finBeer).toFixed(2));
- for (var i = 0; i < recipeGrains.length; i++)
- {
- var grainPositionName = "grain" + (i + 1);
- var grainPositionAmount = "grainsamt" + (i + 1);
- var tempNum = parseFloat(isNaN(recipeGrains[i]["Amount"]) ? 0 : recipeGrains[i]["Amount"]).toFixed(2);
- //If whole number, don't show decimal
- if (tempNum % 1 == 0)
- {
- tempNum = Math.round(tempNum);
- }
- $("#" + grainPositionAmount).val(tempNum);
- }
- //Change properties of each hop amount field
- $(".hop-amount").each(function ()
- {
- $(this).prop(
- {
- 'min': 0,
- 'max': 1.5,
- 'step': 0.1
- });
- })
- //Populate any existing values
- for (var i = 0; i < recipeHops.length; i++)
- {
- var hopPositionAmount = "hopAmt" + (i + 1);
- var tempNum = parseFloat(isNaN(recipeHops[i]["Amount"]) ? 0 : recipeHops[i]["Amount"]).toFixed(2);
- if (tempNum % 1 == 0)
- {
- tempNum = Math.round(tempNum);
- }
- $("#" + hopPositionAmount).val(tempNum);
- }
- $('#mashTemp').val(mashTemp);
- $('#mashTemp').prop(
- {
- 'max': 207,
- 'step': 1
- });
- $('#boilTemp').val(boilTemp);
- $('#boilTemp').prop(
- {
- 'max': 207,
- 'step': 1
- });
- var yeastType = $("[name=yeast]").val();
- if (yeastType == 0)
- {
- $("#yeastTemp").html("0 - 0");
- $("[name=yeastPitch]").val(0);
- } else
- {
- $("#yeastTemp").html(yeastMinTemp[yeastType] + " - " + yeastMaxTemp[yeastType]);
- $("[name=yeastPitch]").val(yeastPitch);
- }
- $('#yeastPitchTemp').prop(
- {
- 'max': 100,
- 'step': 1
- });
- var fermCount = 0;
- //Change temp values to F values
- $('#advFermSched tr').has('td').each(function ()
- {
- $('td', $(this)).each(function (index, item)
- {
- $('input', $(this)).each(function (index, item)
- {
- if ($(this).data("name") == "Temp")
- {
- if (!!$(this).val())
- {
- if (advFermSteps.length > fermCount)
- {
- $(this).val(advFermSteps[fermCount]["Temp"]);
- }
- }
- $(this).prop("max", 85);
- $(this).prop("min", 32);
- $(this).prop("step", 1);
- }
- })
- })
- fermCount += 1;
- });
- //adjunct amount changes
- $('[name=adjAmt1]').val(adjAmt1);
- $('[name=adjAmt2]').val(adjAmt2);
- //Change properties of each hop amount field
- $(".adjunctAmount").each(function ()
- {
- $(this).prop(
- {
- 'min': 0,
- 'max': 1.5,
- 'step': 0.1
- });
- })
- } else if (unitSelected.options[unitSelected.selectedIndex].value == 1)
- //Metric Unit Changes
- {
- unitInUS = false;
- //Replace all temperature F symbols with C
- $(".temperature").each(function ()
- {
- $(this).html($(this).html().replace("F", "C"));
- });
- //Change all liquid to show G symbol instead of L
- $(".liquid").each(function ()
- {
- $(this).html($(this).html().replace("(G)", "(L)"));
- });
- $(".poundKilo").each(function ()
- {
- $(this).html($(this).html().replace("(lb)", "(kg)"));
- });
- $(".ounceGram").each(function ()
- {
- $(this).html($(this).html().replace("(oz)", "(g)"));
- });
- $(".tspGram").each(function ()
- {
- $(this).html($(this).html().replace("(tsp)", "(g)"));
- });
- //Sous Vide Changes
- //Convert temperature to Celcius
- $("#cookTemp").val(RoundedConvertFahrenheitToCelcius(cookTemp));
- //Warn user of Metric Conversion
- var metricWarning = document.getElementById("metricWarning");
- metricWarning.style.visibility = 'visible';
- metricWarning.style.display = 'block';
- //Change Finished Beer to Liter Measurement
- $("#finBeer").val(RoundedConvertGallonToLiters(finBeer));
- //Populate all grain values with converted metric values
- for (var i = 0; i < recipeGrains.length; i++)
- {
- var grainPositionName = "grain" + (i + 1);
- var grainPositionAmount = "grainsamt" + (i + 1);
- var tempNum = parseFloat(isNaN(recipeGrains[i]["Amount"]) ? 0 : ConvertLBsToKG(recipeGrains[i]["Amount"])).toFixed(2);
- if (tempNum % 1 == 0)
- {
- tempNum = Math.round(tempNum);
- }
- if (recipeGrains[i]["Amount"] != 0)
- {
- $("#" + grainPositionAmount).val(tempNum);
- }
- }
- //Change properties for gram units for min and max
- $(".hop-amount").each(function ()
- {
- $(this).prop(
- {
- 'min': 0,
- 'max': 43,
- 'step': 1
- });
- });
- //Populate any preexisting hop amounts
- for (var i = 0; i < recipeHops.length; i++)
- {
- var hopPositionAmount = "hopAmt" + (i + 1);
- $("#" + hopPositionAmount).val(Math.round(parseFloat(isNaN(recipeHops[i]["Amount"]) ? 0 : ConvertOunceToGram(recipeHops[i]["Amount"]))));
- }
- //Change Mash Temperature
- $('#mashTemp').val(RoundedConvertFahrenheitToCelcius(mashTemp));
- $('#mashTemp').prop(
- {
- 'max': 97.2,
- 'step': 0.1
- });
- //Change Boil temperature
- $('#boilTemp').val(RoundedConvertFahrenheitToCelcius(boilTemp));
- $('#boilTemp').prop(
- {
- 'max': 97.2,
- 'step': 0.1
- });
- //Change yeast temperatures
- $('#yeastRangeTemp').val(RoundedConvertFahrenheitToCelcius(mashTemp));
- var yeastType = $("[name=yeast]").val();
- if (yeastType == 0)
- {
- $("#yeastTemp").html("0 - 0");
- $("[name=yeastPitch]").val(0);
- } else
- {
- $("#yeastTemp").html(RoundedConvertFahrenheitToCelcius(yeastMinTemp[yeastType]) + " - " + RoundedConvertFahrenheitToCelcius(yeastMaxTemp[yeastType]));
- $("[name=yeastPitch]").val(parseFloat(RoundedConvertFahrenheitToCelcius(yeastPitch)).toFixed(1));
- }
- $('#yeastPitchTemp').prop(
- {
- 'max': 37.8,
- 'step': 0.1
- });
- var fermCount = 0;
- //Change temp values to Celcius values
- $('#advFermSched tr').has('td').each(function ()
- {
- $('td', $(this)).each(function (index, item)
- {
- $('input', $(this)).each(function (index, item)
- {
- if ($(this).data("name") == "Temp")
- {
- if (!!$(this).val())
- {
- if (advFermSteps.length > fermCount)
- {
- $(this).val(RoundedConvertFahrenheitToCelcius(advFermSteps[fermCount]["Temp"]));
- }
- }
- $(this).prop("max", RoundedConvertFahrenheitToCelcius(85));
- $(this).prop("min", RoundedConvertFahrenheitToCelcius(32));
- $(this).prop("step", 0.1);
- }
- })
- })
- fermCount += 1;
- });
- //adjunct amount changes
- $('[name=adjAmt1]').val(ConvertOunceToGram(adjAmt1).toFixed(0));
- $('[name=adjAmt2]').val(ConvertOunceToGram(adjAmt2).toFixed(0));
- //Change properties of each hop amount field
- $(".adjunctAmount").each(function ()
- {
- $(this).prop(
- {
- 'min': 0,
- 'max': 43,
- 'step': 1
- });
- })
- }
- storeAdvancedFermentation();
- changeNormalScheduleDescription();
- recalcForm();
- }
- //Executes when the selection box for the fermentation schedule is changed
- function fermScheduleChange(select)
- {
- var value = parseInt(select.value);
- switch (value)
- {
- default:
- case 0:
- //Hide Other Tables
- hideAdvFermSchedTable();
- //Show Normal Table
- normalFermentation(document.getElementById("normalFermSelection"));
- showNormalTable();
- break;
- case 1:
- //Hide Other Tables
- hideNormalTable();
- //Show Advanaced Table
- showAdvFermSchedTable();
- break;
- }
- changeNormalScheduleDescription();
- //Fermentation Schedule Change Helper Functions
- //Shows the Table for the Normal Options
- function showNormalTable()
- {
- //Show normal schedule
- var table = document.getElementById("normalFermSched");
- table.style.visibility = 'visible';
- table.style.display = 'block';
- }
- //Hides the Table for the Normal Options
- function hideNormalTable()
- {
- //Hide the normal schedule
- var table = document.getElementById("normalFermSched");
- table.style.visibility = 'hidden';
- table.style.display = 'none';
- }
- //Show advanced table
- function showAdvFermSchedTable()
- {
- var table = document.getElementById("advFermSched");
- table.style.visibility = 'visible';
- table.style.display = 'block';
- var notes = document.getElementById("advanceNotifications");
- notes.style.visibility = 'visible';
- notes.style.display = 'block';
- }
- //Hide advanaced table
- function hideAdvFermSchedTable()
- {
- var table = document.getElementById("advFermSched");
- table.style.visibility = 'hidden';
- table.style.display = 'none';
- var notes = document.getElementById("advanceNotifications");
- notes.style.visibility = 'hidden';
- notes.style.display = 'none';
- }
- }
- //Normal schedule option has changed, this will change the description to the proper description
- function changeNormalScheduleDescription()
- {
- var aleFermDescription = "Cool to " + (unitInUS ? $("#advFermTemp1").val() + " F" : parseFloat($("#advFermTemp1").val()) + " C") + " and keep temperature consistent for " + $("#advFermDay1").val() + " Days";
- var lagerFermDescription = "Cool to " + (unitInUS ? $("#advFermTemp1").val() + " F" : parseFloat($("#advFermTemp1").val()) + " C") + " and keep temperature consistent for 3 weeks. Rack to a lagering container and keep at " + (unitInUS ? $("#advFermTemp2").val() + " F" : parseFloat($("#advFermTemp2").val()) + " C") + " for another 4 weeks.";
- if ($("#fermTypeSelection").val() == 0)
- {
- if (document.getElementById("normalFermSelection").value == 0)
- {
- $("#fermDescription").html(aleFermDescription);
- }
- else if (document.getElementById("normalFermSelection").value == 1)
- {
- $("#fermDescription").html(lagerFermDescription);
- }
- }
- else
- {
- $("#fermDescription").html("");
- }
- }
- //After a grain is selected, this function will execute.
- function changeFermentable(target)
- {
- var search = target.parentNode;
- while(search.className !== "search") {
- search = search.parentNode;
- }
- var grainIndex = search.dataset.index;
- var searchInput = $(search).children("input")[0];
- var grainAmtID = "grainsamt" + grainIndex;
- $('#warnings-grains').empty();
- $(searchInput).removeClass("error");
- //if the selection is 0, this is the blank selection
- var ingredientID = parseInt(target.dataset.value);
- if (ingredientID !== 0)
- {
- //Set both values as required
- $(searchInput).prop("required", true);
- $(searchInput).data("ingredientID", ingredientID.toString());
- $(searchInput).val(target.innerText);
- $("#" + grainAmtID).prop("required", true);
- }
- $(searchInput).removeClass("error");
- //hide the results if they are open
- $(target.parentNode).hide();
- storeFermentables();
- recalcForm();
- }
- function removeFermentable(target) {
- var search = target.parentNode;
- while (search.className !== "search") {
- search = search.parentNode;
- }
- var searchInput = $(search).children("input")[0];
- $(searchInput).removeData("ingredientID");
- storeFermentables();
- recalcForm();
- }
- function grainAmountChange(input)
- {
- $('#warnings-grains').empty();
- $('#warnings-grains2').empty();
- $(input).removeClass("error");
- //If input is empty, set to 0 instead
- if (input.value == "")
- {
- input.value = 0;
- }
- //Store values and then recalculate form
- storeFermentables();
- recalcForm();
- }
- function hopAmountChange(input)
- {
- if (!input.value)
- {
- input.value = 0;
- }
- storeHops();
- recalcForm();
- }
- //Beer Style Change Function
- function BeerStyleChange()
- {
- vitaStatsChangeBounds();
- textRecipeDescription();
- }
- function LoadBeverageStyles(styleGuide) {
- if(!styleGuide) {
- styleGuide = 'BJCP 2015';
- }
- $("#BeerStyle").empty();
- for (var styleID in beerStylesJSON)
- {
- //Add all the different style guides to a list to filter
- if(beerStylesJSON[styleID].StyleGuide === styleGuide) {
- $("#BeerStyle").append('<option class="bjcp-style-list" value="' + beerStylesJSON[styleID].StyleID + '" data-styleCode="' + styleID + '" data-guide="' + beerStylesJSON[styleID].StyleGuide + '">' + beerStylesJSON[styleID].CatNumCode + beerStylesJSON[styleID].CatLettCode + '. ' + beerStylesJSON[styleID].StyleNameCode + '</option>');
- }
- }
- }
- function BeerStyleGuideChange(){
- var selectedStyle = $("#BeerStyleGuide").val()
- LoadBeverageStyles(selectedStyle);
- $("#BeerStyle").val($("#BeerStyle option[data-guide='" + selectedStyle +"']")[0].value)
- }
- function changeHop(target)
- {
- var search = target.parentNode;
- while (search.className !== "search") {
- search = search.parentNode;
- }
- var hopIndex = search.dataset.index;
- var searchInput = $(search).children("input")[0];
- $(searchInput).removeClass("error");
- var ingredientID = parseInt(target.dataset.value);
- //if the selection is 0, this is the blank selection
- if (ingredientID !== 0)
- {
- $(searchInput).data("ingredientID", ingredientID.toString());
- $(searchInput).val(target.innerText);
- $("#hopAA" + hopIndex).val(hopIngredients[ingredientID].Alpha);
- validateHop(hopIndex);
- }
- $(target.parentNode).hide();
- storeHops();
- recalcForm();
- }
- function removeHop(target) {
- var search = target.parentNode;
- while (search.className !== "search") {
- search = search.parentNode;
- }
- var searchInput = $(search).children("input")[0];
- $(searchInput).removeData("ingredientID");
- storeHops();
- recalcForm();
- }
- function hopInputChange(input)
- {
- $(input).removeClass("error");
- if (!input.value)
- {
- input.value = 0;
- }
- storeHops();
- recalcForm();
- }
- //=====================GENERAL FUNCTIONS=====================
- //Uses information in the crafter to recalculate the values for the beer
- function recalcForm()
- {
- //Get the total amount of water
- //H2O = parseFloat($("#H2O").text());
- //If in metric, convert to gallons
- //if (!unitInUS)
- //{
- // H2O = RoundedConvertLitersToGallons(H2O);
- //}
- //get the recipe\beverage style value
- recipeStyle = parseInt($("[name = recipe_style]").val());
- //Finished Beer volume
- fermentorWort = finBeer + 0.2;
- //Recipe type, Beer or Souse Vide
- type = parseInt($("[name = recipe_type]").val());
- mashTemp = unitInUS ? parseInt($("[name = mashTemp]").val()) : parseInt(ConvertCelciusToFahrenheit(parseFloat($("[name = mashTemp]").val())));
- mashTime = parseInt($("[name = mashTime]").val());
- mashType = parseInt($("[name = mash_type]").val());
- boilTime = parseInt($("#boilTime").val());
- boilTemp = unitInUS ? parseInt($("[name = boilTemp]").val()) : parseInt(ConvertCelciusToFahrenheit(parseFloat($("[name = boilTemp]").val())));
- boilType = parseInt($("#boilType").val());
- yeastAA = parseInt($("[name = yeastExp]").val());
- recipeYeastType = parseInt($("[name = yeast]").val());
- yeastPitch = unitInUS ? parseInt($("[name = yeastPitch]").val()) : parseInt(ConvertCelciusToFahrenheit(parseFloat($("[name = yeastPitch]").val())));
- recipeName = $("[name = recipe_name]").val();
- notes = $("[name = recipe_Notes]").val();
- beerText = $("#beer-text").val();
- //DISABLED RESET
- //reset boilTime for loop 1/31
- //boilTime = 0;
- //Sum all hop amounts
- var hopAmt = 0.0;
- for (var i = 0; i < recipeHops.length; i++)
- {
- hopAmt += parseFloat(recipeHops[i]["Amount"]);
- }
- //Check summation of grains
- grainSumCheck();
- //get total of grains in lbs from the array
- grainSum = grainSumLbs();
- //Get the total and reflect in the HTML for either US or metric
- $(".grainSum").html(Math.round((unitInUS ? grainSum : ConvertLBsToKG(grainSum)) * 100) / 100);
- var mashThickness;
- var efficiency;
- if (mashType == 0)
- {
- //calc water amount
- var grainLossPerLb = 0.104;
- //calculate efficiency based on mash thickness
- if (grainSum > 0)
- {
- H2O = parseFloat(fermentorWort) + parseFloat((grainSum * grainLossPerLb)) + 0.030 + (0.046 * hopAmt);
- mashThickness = (H2O * 4) / grainSum;
- efficiency = 0.55;
- }
- else
- {
- H2O = 0;
- mashThickness = 0;
- efficiency = 0;
- }
- }
- else if (mashType == 1)
- {
- var grainLossPerLb = 0.06;
- //calculate efficiency based on mash thickness
- if (grainSum > 0)
- {
- H2O = parseFloat(fermentorWort) + parseFloat((grainSum * grainLossPerLb)) + 0.030 + (0.046 * hopAmt);
- mashThickness = (H2O * 4) / grainSum;
- efficiency = -(0.0087 * Math.pow(mashThickness, 4)) + (0.1245 * Math.pow(mashThickness, 3)) - (0.6438 * Math.pow(mashThickness, 2)) + (1.4384 * mashThickness) - 0.3769;
- } else
- {
- H2O = 0;
- mashThickness = 0;
- efficiency = 0;
- }
- }
- eff = efficiency;
- //calculate gravity point contributions for each row of grain
- gravitySum = 0;
- colorSum = 0;
- for (var i = 0; i < recipeGrains.length; i++)
- {
- //Only calculate if FermentableID is non Zero
- if (recipeGrains[i]["FermentableID"])
- {
- recipeGrains[i]["Gravity"] = efficiency * (fermentableIngredients[recipeGrains[i]["FermentableID"]].Yield * recipeGrains[i]["Amount"] / fermentorWort);
- $("#gravityPts" + (i + 1)).html(Math.round(recipeGrains[i]["Gravity"] * 100) / 100);
- gravitySum += recipeGrains[i]["Gravity"];
- }
- else
- {
- $("#gravityPts" + (i + 1)).html(0);
- }
- }
- $(".gravitySum").html(Math.round(gravitySum * 100) / 100);
- //calculate the percentage of grains
- for (var i = 0; i < recipeGrains.length; i++)
- {
- if (recipeGrains[i]["FermentableID"])
- {
- if (parseFloat(grainSum) > 0)
- {
- recipeGrains[i]["Percent"] = Math.round((recipeGrains[i]["Amount"] / grainSum) * 100);
- $("#percent" + (i + 1)).html(recipeGrains[i]["Percent"]);
- }
- else
- {
- $("#percent" + (i + 1)).html(0);
- }
- }
- else
- {
- $("#percent" + (i + 1)).html(0);
- }
- }
- //Calculate the color point contributino for each row of grain
- for (var i = 0; i < recipeGrains.length; i++)
- {
- //Check if Fermentable ID is not zero
- if (recipeGrains[i]["FermentableID"])
- {
- recipeGrains[i]["Color"] = (fermentableIngredients[recipeGrains[i]["FermentableID"]].Color * recipeGrains[i]["Amount"]) / fermentorWort;
- $("#colorPts" + (i + 1)).html(Math.round(recipeGrains[i]["Color"] * 10) / 10);
- colorSum += recipeGrains[i]["Color"];
- }
- else
- {
- $("#colorPts" + (i + 1)).html(0);
- }
- }
- //Solve for OG if needed... only allow this if og not 0;
- if (gravitySum == 0)
- {
- OG = 0;
- } else
- {
- OG = 1.000 + (gravitySum / 1000);
- }
- //read in the hops stats and populate the fields
- //(have to do this last because we need to know some of the Vital Stats like OG and Volume
- var bignessFactor = 1.65 * Math.pow(0.000125, (OG - 1));
- var kettleUtilization = 4.25; // This number is 4.15 in classic Tinseth, ours is larger because of our lower utilization
- IBU = 0;
- hopAmt = 0.0;
- var maxHopTime = 0
- for (var i = 0; i < recipeHops.length; i++)
- {
- var hopAlphaVal = $("#hopAA" + (i + 1)).val();
- var hopTimeVal = $("#hopTime" + (i + 1)).val();
- var boilTimeFactor = (1 - Math.pow(2.72, (-0.04 * hopTimeVal))) / kettleUtilization;
- var hopsUtilizationRate = bignessFactor * boilTimeFactor;
- hopAmt += parseFloat(recipeHops[i]["Amount"]);
- recipeHops[i]["IBU"] = hopsUtilizationRate * (recipeHops[i]["Amount"] * (recipeHops[i]["Alpha"] / 100) * 7490) / fermentorWort;
- var temp = "#ibuAMT" + i;
- $("#ibuAMT" + (i + 1)).html(Math.round(recipeHops[i]["IBU"] * 10) / 10);
- IBU += recipeHops[i]["IBU"];
- //add to boilTime
- if (hopTimeVal > 0 && hopTimeVal > maxHopTime)
- {
- maxHopTime = parseInt(hopTimeVal);
- }
- }
- boilTime = maxHopTime;
- boilTime += parseInt($("#excessBoil").val());
- var TI = $("[name=IBU]").val();
- /*
- if (IBU != 0 && TI != 0) { //if form submit type = solve for ibu
- //scale the grain in the recipe up
- var iter = 0;
- var errorThresh = 0.5;
- while (Math.abs(TI - IBU > errorThresh) && iter < 10) {
- var scaleFactor = TI / IBU;
- solveIBU(scaleFactor);
- iter = iter + 1;
- }
- }
- */
- //calculate OG from grains and water amount
- if (OG == 0)
- {
- FG = 0;
- SRM = 0;
- ABV = 0;
- } else
- {
- FG = 1.0 + ((OG - 1.000) * (100.0 - yeastAA) / 100);
- SRM = 1.4922 * Math.pow(colorSum, 0.6859);
- ABV = (OG - FG) * 130.0;
- }
- $("#hopBoil").html(maxHopTime);
- $("#boilTime").val(boilTime);
- $("#H2O").html(unitInUS ? Math.round(H2O * 100) / 100 : RoundedConvertGallonToLiters(H2O));
- $("#OG").val(Math.round(OG * 1000) / 1000);
- $("#FG").html(Math.round(FG * 1000) / 1000);
- $("#IBU").val(Math.round(IBU));
- $("#SRM").html(Math.round(SRM));
- $("#ABV").html(Math.round(ABV * 10) / 10);
- checkBetweenBounds();
- changePicture();
- textRecipeDescription();
- }
- function changePicture()
- {
- var SrmValue = $("#SRM").html();
- var approxColor = parseInt(SrmValue);
- if (approxColor == 0)
- {
- approxColor = 1;
- } else if (approxColor > 40)
- {
- approxColor = 40;
- }
- approxColor = Math.round(approxColor);
- var image = imageContainer + "/images/SRM_Small/" + approxColor + ".png";
- $("#beer-pic").attr("src", image);
- }
- function textRecipeDescription()
- {
- if (custText == 0)
- {
- var desc = ""
- if (SRM == 0)
- {
- desc = desc + "A clear"
- }
- else if (SRM < 4)
- {
- desc = desc + "A very pale"
- }
- else if (SRM < 7)
- {
- desc = desc + "A pale"
- }
- else if (SRM < 11)
- {
- desc = desc + "A golden"
- }
- else if (SRM < 20)
- {
- desc = desc + "An amber"
- }
- else if (SRM < 29)
- {
- desc = desc + "A brown"
- }
- else if (SRM < 39)
- {
- desc = desc + "A dark"
- }
- else
- {
- desc = desc + "A black"
- }
- var buguRatio = IBU / (1000 * (OG - 1))
- if (OG < 0.2 && buguRatio < 0.35)
- {
- desc = desc + ", watery,"
- }
- else if (buguRatio < 0.35)
- {
- desc = desc + ", very sweet,"
- }
- else if (buguRatio < 0.45)
- {
- desc = desc + ", malty,"
- }
- else if (buguRatio < 0.65)
- {
- desc = desc + ", balanced,"
- }
- else if (buguRatio < 0.85)
- {
- desc = desc + ", hoppy,"
- }
- else if (buguRatio < 0.99)
- {
- desc = desc + ", bitter,"
- }
- else
- {
- desc = desc + ", intensely bitter,"
- }
- if (OG < 1.030)
- {
- desc = desc + " very light-bodied"
- }
- else if (OG < 1.040)
- {
- desc = desc + " light bodied"
- }
- else if (OG < 1.060)
- {
- desc = desc + " medium-bodied"
- }
- else if (OG < 1.070)
- {
- desc = desc + " full-bodied"
- }
- if (recipeStyle == 0)
- {
- desc = desc + " custom beer."
- }
- else
- {
- desc = desc + " " + beerStylesJSON[$("#BeerStyle option:selected").data("stylecode")].StyleNameCode + ".";
- }
- $("#beer-text").val(desc);
- }
- }
- //TODO May not longer be needed
- function validateGrains(select)
- {
- var grainIndex = select.id.slice(-1);
- var arrayIndex = parseInt(grainIndex) - 1;
- var grainAmtID = "grainsamt" + grainIndex;
- $('#warnings-grains').empty();
- //Store the current textbox value in the respective array location
- recipeGrains[arrayIndex]["FermentableID"] = select.value;
- if (unitInUS)
- {
- recipeGrains[arrayIndex]["Amount"] = parseFloat($("#" + grainAmtID).val());
- }
- else
- {
- recipeGrains[arrayIndex]["Amount"] = RoundedConvertKgToLbs(parseFloat($("#" + grainAmtID).val()));
- }
- storeFermentables();
- recalcForm();
- }
- function validateHop(index)
- {
- var hopRowID = "hopRowNum" + (parseInt(index) - 1);
- var valid = true;
- //Wrap the current row into a temp form
- $("#" + hopRowID).wrap('<form id="temp_form_id" />');
- //Run validation on fields.
- $('#temp_form_id').validate();
- //Empty Warnings Field
- $('#warnings-hops').empty();
- //If hop values are valid
- if (!$("#hopAmt" + index).valid())
- {
- var warning = "Recipe hop amount is required and must be a number no greater than " + (unitInUS ? hopLimitUSString : hopLimitMetricString) + ". Hop amount in excess of " + (unitInUS ? hopLimitUSString : hopLimitMetricString) + " can be split into multiple cages.";
- $('#warnings-hops').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- valid = false;
- }
- if (!$("#hopAA" + index).valid())
- {
- var warning = "Recipe hop alpha is required and must be a number no greater than 20.0.";
- $('#warnings-hops').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- valid = false;
- }
- if (!$("#hopTime" + index).valid())
- {
- var warning = "Recipe hop time is required and must be a number greater than 300, rounded to the nearest minute.";
- $('#warnings-hops').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- valid = false;
- }
- //Unwrap from temp form
- $("#" + hopRowID).unwrap();
- }
- function gatherNonCalc()
- {
- recipeName = $("[name = recipe_name]").val();
- recipeAuth = $("[name = recAuth]").val();
- origName = $("#origName").val();
- origAuth = $("#origAuth").val();
- recipeStyle = $("[name = recipe_style]").val();
- type = $("[name = recipe_type]").val();
- mashTemp = unitInUS ? $("[name = mashTemp]").val() : Math.round(ConvertCelciusToFahrenheit($("[name = mashTemp]").val()));
- mashTime = $("[name = mashTime]").val();
- mashType = $("[name = mash_type]").val();
- boilTime = $("#boilTime").val();
- boilTemp = unitInUS ? $("[name = boilTemp]").val() : Math.round(ConvertCelciusToFahrenheit($("[name = boilTemp]").val()));
- boilType = $("#boilType").val();
- yeastAA = $("[name = yeastExp]").val();
- yeastPitch = unitInUS ? $("[name = yeastPitch]").val() : Math.round(ConvertCelciusToFahrenheit(parseFloat($("[name = yeastPitch]").val())));
- recipeYeastType = $("[name = yeast]").val();
- notes = $("[name = recipe_Notes]").val();
- waterType = $("[name=water]").val();
- amend1 = $("#waterAmend1").val();
- amend2 = $("#waterAmend2").val();
- amend3 = $("#waterAmend3").val();
- amend4 = $("#waterAmend4").val();
- amendAmt1 = $("#amendAmt1").val();
- amendAmt2 = $("#amendAmt2").val();
- amendAmt3 = $("#amendAmt3").val();
- amendAmt4 = $("#amendAmt4").val();
- adj1 = $("[name=adj1]").val();
- adjAmt1 = unitInUS ? $("[name=adjAmt1]").val() : ConvertGramToOunce($("[name=adjAmt1]").val());
- adjTime1 = $("[name=adjTime1]").val();
- adjUse1 = $("[name=adjUse1]").val();
- adj2 = $("[name=adj2]").val();
- adjAmt2 = unitInUS ? $("[name=adjAmt2]").val() : ConvertGramToOunce($("[name=adjAmt2]").val());
- adjTime2 = $("[name=adjTime2]").val();
- adjUse2 = $("[name=adjUse2]").val();
- }
- //once the beer type is changed, the bounds for min and max are changed.
- function vitaStatsChangeBounds()
- {
- var selectedStyle = $("#BeerStyle option:selected").data("stylecode");
- $("#minOG").html(beerStylesJSON[selectedStyle].MinOG);
- $("#maxOG").html(beerStylesJSON[selectedStyle].MaxOG);
- $("#minFG").html(beerStylesJSON[selectedStyle].MinFG);
- $("#maxFG").html(beerStylesJSON[selectedStyle].MaxFG);
- $("#minIBU").html(beerStylesJSON[selectedStyle].MinIBU);
- $("#maxIBU").html(beerStylesJSON[selectedStyle].MaxIBU);
- $("#minSRM").html(beerStylesJSON[selectedStyle].MinSRM);
- $("#maxSRM").html(beerStylesJSON[selectedStyle].MaxSRM);
- $("#minABV").html(beerStylesJSON[selectedStyle].MinABV);
- $("#maxABV").html(beerStylesJSON[selectedStyle].MaxABV);
- checkBetweenBounds();
- }
- //Return summation of grain amounts in US units
- function grainSumLbs()
- {
- totalSum = 0.0;
- for (var i = 0; i < recipeGrains.length; i++)
- {
- if (recipeGrains[i]["FermentableID"])
- {
- totalSum += parseFloat(recipeGrains[i]["Amount"]);
- }
- }
- return totalSum;
- }
- function validGrainFinal()
- {
- for (var i = 0; i < recipeGrains.length; i++)
- {
- if (recipeGrains[i]["Amount"] < 0)
- {
- var warning = "Recipe Fermentable has a value less than 0.";
- $('#warnings-grains').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- return false;
- }
- //If recipe amount is less than minimum amount of 1lb
- if (recipeGrains[i]["FermentableID"] && grainSumLbs() < 1)
- {
- var warning = "Recipe fermentable is invalid due to minimum Fermentable amount of " + (unitInUS ? "1lb." : ConvertLBsToKG(1).toFixed(2) + "kg.");
- $('#warnings-grains').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- return false;
- }
- }
- return true;
- }
- function validHopsFinal()
- {
- var isValid = true;
- $('#warnings-hops').empty();
- for (var i = 0; isValid && i < recipeHops.length; i++)
- {
- if (recipeHops[i]["HopID"])
- {
- if (recipeHops[i]["Amount"] <= 0 || recipeHops[i]["Amount"] > 1.5)
- {
- var warning = "\nHop amount must be greater than 0 and less than " + (unitInUS ? "1.5 oz." : "42 grams.");
- $('#warnings-hops').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }
- if (recipeHops[i]["Alpha"] <= 0 || recipeHops[i]["Alpha"] > 20)
- {
- var warning = "\nHop Alpha Acid must be greater than 0 and less than 20 percent";
- $('#warnings-hops').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }
- if (recipeHops[i]["Time"] <= 0 || recipeHops[i]["Time"] > 360)
- {
- var warning = "Hop time is required and must be less than 360, rounded to the nearest minute.";
- $('#warnings-hops').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }
- }
- }
- return isValid;
- }
- //Helper Function
- function validAdjFinal()
- {
- var isNameValid = false;
- var count = 0;
- $('#warnings-adj').empty();
- if ($("[name=adjAmt1]").val() != "0" || $("[name=adjTime1]").val() != "0")
- {
- $('#all').wrap('<form id="temp_form_id" />');
- $('#temp_form_id').validate({
- rules: {
- adj1: {
- required: true,
- min: 1
- }
- },
- errorPlacement: function ()
- {
- return false;
- }
- });
- isNameValid = $('[name=adj1]').valid();
- $('#all').unwrap();
- if (!isNameValid && count == 0)
- {
- var warning = "Adjunct name is missing (mandatory).";
- $('#warnings-adj').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- count++;
- } else
- {
- adjAmt1 = unitInUS ? $("[name=adjAmt1]").val() : ConvertOunceToGram($("[name=adjAmt1]").val()).toFixed(2);
- }
- }
- if ($("[name=adjAmt2]").val() != "0" || $("[name=adjTime2]").val() != "0")
- {
- $('#all').wrap('<form id="temp_form_id" />');
- $('#temp_form_id').validate({
- rules: {
- adj2: {
- required: true,
- min: 1
- }
- },
- errorPlacement: function ()
- {
- return false;
- }
- });
- isNameValid = $('[name=adj2]').valid();
- $('#all').unwrap();
- if (!isNameValid && count == 0)
- {
- var warning = "Adjunct name is missing (mandatory).";
- $('#warnings-adj').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- count++;
- } else
- {
- adjAmt2 = unitInUS ? $("[name=adjAmt2]").val() : ConvertOunceToGram($("[name=adjAmt2]").val()).toFixed(2);
- }
- }
- if (count > 0)
- {
- return false;
- }
- return true;
- }
- //Helper Function
- function validAll()
- {
- //Check for any instances of the error class
- var errorInstances = $(".error");
- //Empty all errors
- $('#warnings-all').empty();
- $('#warnings-yeasts').empty();
- $('#warnings-notes').empty();
- $('#warnings-hops').empty();
- $('#warnings-grains').empty();
- //Run validation on grains hops and adjuncts
- var isValid = errorInstances.length == 0 && validGrainFinal() && validHopsFinal() && validAdjFinal();
- //Wrap all inputs into a temp form and run validation
- $('#all').wrap('<form id="temp_form_id" />');
- $('#temp_form_id').validate();
- var isNameValid = $('#recipe_name').valid();
- var isStyleValid = $('#BeerStyle').valid();
- var isYeastValid = $('[name=yeast]').valid();
- var isNoteValid = $('#notes-text-area').valid();
- var isQuantValid = $('[name=finBeer]').valid();
- //Unwrap form
- $('#all').unwrap();
- //TODO Change to Regex
- if (recipeName.indexOf('#') > 0)
- {
- isNameValid = false;
- }
- else if (recipeName.indexOf('/') > 0)
- {
- isNameValid = false;
- }
- else if (recipeName.indexOf('|') > 0)
- {
- isNameValid = false;
- }
- if (!isNameValid)
- {
- var warning = "Recipe name is invalid (mandatory, 20 characters or less). Non-English characters and special characters except ' . _ - are not allowed.";
- $('#warnings-all').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }
- if (!isQuantValid)
- {
- var warning = "Finished beer quantity is out of range.";
- $('#warnings-all').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }
- if (recipeGrains.length == 0 || recipeGrains[0]["FermentableID"] == 0)
- {
- $("#selectgrain1").addClass("error");
- var warning = "At least one grain in the first row is required";
- $('#warnings-grains').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }
- /*if (recipeHops.length == 0 || recipeHops[0]["HopID"] == 0)
- {
- $("#selecthop1").addClass("error");
- var warning = "At least one hop in the first row is required.";
- $('#warnings-hops').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }*/
- if (!isStyleValid)
- {
- var warning = "Recipe style is required.";
- $('#warnings-all').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }
- if (!isYeastValid || $('[name=yeast]').val() == 0)
- {
- $('[name=yeast]').addClass("error");
- var warning = "Recipe yeast is required.";
- $('#warnings-yeasts').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }
- if ($("#excessBoil").val() < 0)
- {
- var warning = "Pre-Hop Boil is less than 0";
- $('#warnings-boil').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }
- if (!isNoteValid)
- {
- var warning = "Recipe notes are invalid, 4000 character limit.";
- $('#warnings-notes').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- isValid = false;
- }
- if (!isValid)
- {
- var warning = "Errors on page preventing submission, please make appropriate corrections and try again.";
- $('#warnings-general').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- return false;
- }
- return isValid;
- }
- //see if the calculated values are within bounds, then adds red or green border to show if they are
- function checkBetweenBounds()
- {
- var min = parseFloat($("#minOG").text());
- var max = parseFloat($("#maxOG").text());
- var value = parseFloat($("#OG").val());
- if (value < min || value > max)
- {
- $("#OG").attr("class", "vital-stat-element-bad");
- $("#OGTable").attr("class", "vital-stat-element-bad");
- }
- else
- {
- $("#OG").attr("class", "vital-stat-element-good");
- $("#OGTable").attr("class", "vital-stat-element-good");
- }
- min = parseFloat($("#minFG").text());
- max = parseFloat($("#maxFG").text());
- value = parseFloat($("#FG").text());
- if (value < min || value > max)
- {
- $("#FG").attr("class", "vital-stat-element-bad");
- }
- else
- {
- $("#FG").attr("class", "vital-stat-element-good");
- }
- min = parseFloat($("#minIBU").text());
- max = parseFloat($("#maxIBU").text());
- value = parseFloat($("#IBU").val());
- if (value < min || value > max)
- {
- $("#IBU").attr("class", "vital-stat-element-bad");
- $("#IBUTable").attr("class", "vital-stat-element-bad");
- }
- else
- {
- $("#IBU").attr("class", "vital-stat-element-good");
- $("#IBUTable").attr("class", "vital-stat-element-good");
- }
- min = parseFloat($("#minSRM").text());
- max = parseFloat($("#maxSRM").text());
- value = parseFloat($("#SRM").text());
- if (value < min || value > max)
- {
- $("#SRM").attr("class", "vital-stat-element-bad");
- }
- else
- {
- $("#SRM").attr("class", "vital-stat-element-good");
- }
- }
- function calcVitalStats(scaleFactor)
- {
- fermentorWort = finBeer + 0.2;
- var hopAmt = 0.0;
- for (var i = 0; i < recipeHops.length; i++)
- {
- hopAmt += parseFloat(recipeHops[i]["Amount"]);
- }
- //get the total grain amount from the array that contains lbs values
- grainSum = grainSumLbs();
- //Change HTML total to the sum of the input textboxes
- $(".grainSum").html(Math.round((unitInUS ? grainSum : ConvertLBsToKG(grainSum)) * 100) / 100);
- var mashThickness;
- var efficiency;
- if (mashType == 0)
- {
- //calc water amount
- var grainLossPerLb = 0.104;
- //calculate efficiency based on mash thickness
- if (grainSum > 0)
- {
- H2O = parseFloat(fermentorWort) + parseFloat((grainSum * grainLossPerLb)) + 0.030 + (0.046 * hopAmt);
- mashThickness = (H2O * 4) / grainSum;
- efficiency = 0.55;
- } else
- {
- H2O = 0;
- mashThickness = 0;
- efficiency = 0;
- }
- }
- else if (mashType == 1)
- {
- var grainLossPerLb = 0.06;
- //calculate efficiency based on mash thickness
- if (grainSum > 0)
- {
- H2O = parseFloat(fermentorWort) + parseFloat((grainSum * grainLossPerLb)) + 0.030 + (0.046 * hopAmt);
- mashThickness = (H2O * 4) / grainSum;
- efficiency = -(0.0087 * Math.pow(mashThickness, 4)) + (0.1245 * Math.pow(mashThickness, 3)) - (0.6438 * Math.pow(mashThickness, 2)) + (1.4384 * mashThickness) - 0.3769;
- } else
- {
- H2O = 0;
- mashThickness = 0;
- efficiency = 0;
- }
- }
- eff = efficiency;
- //calculate gravity point contributions for each row of grain
- gravitySum = 0;
- colorSum = 0;
- for (var i = 0; i < recipeGrains.length; i++)
- {
- //Calculate gravity
- recipeGrains[i]["Gravity"] = efficiency * (fermentableIngredients[recipeGrains[i]["FermentableID"]].Yield * recipeGrains[i]["Amount"] / fermentorWort);
- //Change HTML value of Gravity to calculated and rounded value
- $("#gravityPts" + (i + 1)).html(Math.round(recipeGrains[i]["Gravity"] * 100) / 100);
- //Sum all gravity values
- gravitySum += recipeGrains[i]["Gravity"];
- }
- $(".gravitySum").html(Math.round(gravitySum * 100) / 100);
- for (var i = 0; i < recipeGrains.length; i++)
- {
- if (parseFloat(grainSum) > 0)
- {
- var grainAmount = $("#grainsamt" + (i + 1)).val()
- recipeGrains[i]["Percent"] = Math.round((grainAmount / grainSum) * 100);
- $("#percent" + (i + 1)).html(recipeGrains[i]["Percent"]);
- }
- }
- //Calculate the color point contributino for each row of grain
- for (var i = 0; i < recipeGrains.length; i++)
- {
- recipeGrains[i]["Color"] = (fermentableIngredients[recipeGrains[i]["FermentableID"]].Color * recipeGrains[i]["Amount"]) / fermentorWort;
- var temp = "#colorPts" + i;
- $("#colorPts" + (i + 1)).html(Math.round(recipeGrains[i]["Color"] * 10) / 10);
- colorSum += recipeGrains[i]["Color"];
- }
- //Solve for OG if needed... only allow this if og not 0;
- if (gravitySum == 0)
- {
- OG = 0;
- } else
- {
- OG = 1.000 + (gravitySum / 1000);
- }
- }
- function solveIBU(scaleFactor)
- {
- IBU = 0;
- var kettleUtilization = 4.25;
- var bignessFactor = 1.65 * Math.pow(0.000125, (OG - 1));
- for (var i = 0; i < recipeHops.length; i++)
- {
- var boilTimeFactor = (1 - Math.pow(2.72, (-0.04 * recipeHops[i]["Time"]))) / kettleUtilization;
- var hopsUtilizationRate = bignessFactor * boilTimeFactor;
- if (recipeHops[i]["Amount"] > 0)
- {
- recipeHops[i]["Amount"] *= scaleFactor;
- recipeHops[i]["IBU"] = hopsUtilizationRate * (recipeHops[i]["Amount"] * (recipeHops[i]["Alpha"] / 100) * 7490) / fermentorWort;
- $("#ibuAMT" + (i + 1)).html(Math.round(parseFloat(recipeHops[i]["IBU"] * 100)) / 100);
- $("#hopAmt" + (i + 1)).val(unitInUS ? Math.round(parseFloat(recipeHops[i]["Amount"] * 100)) / 100 : ConvertOunceToGram(parseFloat(recipeHops[i]["Amount"])).toFixed(0));
- IBU += recipeHops[i]["IBU"];
- }
- }
- }
- function solveOG()
- {
- //solve for OG if needed.. only allow this if OG not 0!
- if (gravitySum == 0)
- {
- OG = 0;
- } else
- {
- OG = 1.00 + (gravitySum / 1000)
- }
- var TG = parseFloat($("#OG").val());
- if (OG != 0 && TG != 0 && OG)
- {
- //scale the grain in the recipe up
- var iter = 0;
- var errorThresh = 0.0009;
- while (Math.abs(TG - OG) > errorThresh && iter < 10)
- {
- var scaleFactor = (TG - 1) / (OG - 1);
- //calcVitalStats(scaleFactor);
- for (var i = 0; i < recipeGrains.length; i++)
- {
- recipeGrains[i]["Amount"] = Math.max(scaleFactor * recipeGrains[i]["Amount"], 0.01)
- $("#grainsamt" + (i + 1)).val(unitInUS ? recipeGrains[i]["Amount"].toFixed(2) : ConvertLBsToKG(recipeGrains[i]["Amount"]).toFixed(1));
- }
- calcVitalStats(scaleFactor);
- iter = iter + 1;
- }
- }
- $("#H2O").html(Math.round(H2O * 100) / 100);
- $("#OG").html(Math.round(OG * 1000) / 1000);
- $("#FG").html(Math.round(FG * 1000) / 1000);
- $("#IBU").html(Math.round(IBU));
- $("#SRM").html(Math.round(SRM));
- $("#ABV").html(Math.round(ABV * 10) / 10);
- checkBetweenBounds();
- changePicture();
- textRecipeDescription();
- recalcForm();
- }
- //calculates vital stats
- //Get sum of all grain inputs and return total weight
- function grainSumCheck()
- {
- var grainTotal = 0.0;
- for (var grain in recipeGrains)
- {
- grainTotal += parseFloat(recipeGrains[grain]["Amount"]);
- }
- if (grainTotal > grainLimitUS)
- {
- $('#warnings-grains2').empty();
- var warning = "Grain limit of compartment estimated to be " + (unitInUS ? grainLimitUSString : grainLimitMetricString) + " (excluding sugars which can be added to keg). Be advised that exceeding this limit reduces calculation accuracy and may not fit in the machine.";
- $('#warnings-grains2').append("<div class=\"alert alert-info alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- else
- {
- $('#warnings-grains2').empty();
- }
- return grainTotal;
- }
- //Executes when the beer type in the Normal Fermentation Schedule is Selected
- //Fermentation Steps
- function normalFermentation(select)
- {
- var value = parseInt(select.value);
- switch (value)
- {
- default:
- case 0:
- //Change step table to the normal ale schedule
- normalAleSchedule();
- break;
- case 1:
- normalLagerSchedule();
- break;
- }
- changeNormalScheduleDescription();
- }
- //Executes on any text input change for the advanced editor
- //table to pull information from is id advFermSched
- //Fermentation Steps
- function storeAdvancedFermentation()
- {
- $('#warnings-ferm').empty();
- //Clear the current array
- while (advFermSteps.length > 0)
- {
- advFermSteps.pop();
- }
- //get title headers as strings
- $('#advFermSched th').each(function (index, item)
- {
- advFermHeaders[index] = $(item).data("name");
- });
- $('#advFermSched tr').has('td').each(function ()
- {
- var fermStep = {};
- var store = true;
- $('td', $(this)).each(function (index, item)
- {
- //Check if step is still intended to be stored
- if (advFermHeaders[index] == "Step")
- {
- fermStep[advFermHeaders[index]] = $(item).html();
- } else
- {
- fermStep[advFermHeaders[index]] = $('input', $(this)).val().trim();
- //Check if this field is populated with a value
- if (!!fermStep[advFermHeaders[index]])
- {
- $('input', $(this)).removeClass("error");
- //Check value if this is not a name field
- if (advFermHeaders[index] != "Name")
- {
- var value = parseFloat($('input', $(this)).val());
- var max = parseFloat($('input', $(this)).prop("max"));
- var min = parseFloat($('input', $(this)).prop("min"));
- if (value > max || value < min)
- {
- $('input', $(this)).addClass("error");
- var warning = "Step " + fermStep["Step"] + ": " + advFermHeaders[index] + " value is out of acceptable ranges (" + $('input', $(this)).prop("min") + " - " + $('input', $(this)).prop("max") + ")";
- $('#warnings-ferm').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- }
- //Check if the name field is empty
- if (!fermStep["Name"])
- {
- $("#advFermName" + $('input', $(this))[0].id.slice(-1)).addClass("error");
- }
- else
- {
- $("#advFermName" + $('input', $(this))[0].id.slice(-1)).removeClass("error");
- }
- } else
- {
- //If name is populated, add error class to other values
- if (!!fermStep["Name"])
- {
- $('input', $(this)).addClass("error");
- }
- else
- {
- $('input', $(this)).removeClass("error");
- }
- //Don't store any incomplete entries
- store = false;
- }
- }
- })
- //If any of the fields are populated and name is empty, throw a warning
- if (!fermStep["Name"] && (!!fermStep["Temp"] || !!fermStep["Days"] || !!fermStep["Hours"]))
- {
- var warning = "Step " + fermStep["Step"] + ": Empty Name";
- $('#warnings-ferm').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- else
- {
- $("#advFermName" + fermStep["Step"]).removeClass("error");
- }
- //If the current unit is in celcius, convert to F as a whole number
- if (!unitInUS && pageLoaded)
- {
- fermStep["Temp"] = ConvertCelciusToFahrenheit(fermStep["Temp"]).toFixed(0);
- }
- //If all values were populated, store the ferm step
- if (store)
- {
- advFermSteps.push(fermStep);
- }
- });
- }
- //Calculate number of characters remaining on the Notes Input
- //Recipe Notes
- function noteCharRemaining()
- {
- var limit = 4000;
- var notes = document.getElementById("notes-text-area");
- var remaining = limit - notes.value.length;
- var charsRemainRow = document.getElementById("noteCharRemainRow");
- if (remaining < limit)
- {
- charsRemainRow.style.visibility = 'visible';
- charsRemainRow.style.display = 'block';
- $("#notesRemaining").html(remaining + " characters remaining.");
- } else
- {
- charsRemainRow.style.visibility = 'hidden';
- charsRemainRow.style.display = 'none';
- }
- }
- //Populate the advanced steps with normal ale
- //Fermentation Steps
- function normalAleSchedule()
- {
- //clear all current values in the schedule
- clearAdvanacedSchedule();
- //Populate step table with normal ale steps
- //Step 1 is fermentation at 66F
- document.getElementById("advFermName1").value = "Fermentation";
- if ($("[name=yeast]").val() != 0)
- {
- document.getElementById("advFermTemp1").value = yeastPitch;
- changeNormalScheduleDescription();
- }
- else
- {
- document.getElementById("advFermTemp1").value = aleFermTemp;
- changeNormalScheduleDescription();
- }
- document.getElementById("advFermDay1").value = aleFermTimeDays;
- document.getElementById("advFermHour1").value = 0;
- //Step 2 is chilling to slow fermentation
- document.getElementById("advFermName2").value = "Crash Chill";
- document.getElementById("advFermTemp2").value = 44;
- document.getElementById("advFermDay2").value = 0;
- document.getElementById("advFermHour2").value = 0;
- //Check if page is loaded to determine if the value needs to be displayed in metric if necessary
- if (!unitInUS && pageLoaded)
- {
- document.getElementById("advFermTemp1").value = RoundedConvertFahrenheitToCelcius(document.getElementById("advFermTemp1").value);
- document.getElementById("advFermTemp2").value = RoundedConvertFahrenheitToCelcius(document.getElementById("advFermTemp2").value);
- }
- storeAdvancedFermentation();
- }
- //Populate advanced steps with normal lager shcedule
- //Fermentation Steps
- function normalLagerSchedule()
- {
- //clear all current values in the schedule
- clearAdvanacedSchedule();
- //Populate step table with normal ale steps
- //Step 1 is fermentation at 66F
- document.getElementById("advFermName1").value = "Primary Fermentation";
- if ($("[name=yeast]").val() != 0)
- {
- document.getElementById("advFermTemp1").value = yeastPitch;
- changeNormalScheduleDescription();
- }
- else
- {
- document.getElementById("advFermTemp1").value = lagerFermTemp;
- changeNormalScheduleDescription();
- }
- document.getElementById("advFermDay1").value = 21;
- document.getElementById("advFermHour1").value = 0;
- //Step 2 is chilling to stop fermentation
- document.getElementById("advFermName2").value = "Lagering";
- document.getElementById("advFermTemp2").value = 35;
- document.getElementById("advFermDay2").value = 28;
- document.getElementById("advFermHour2").value = 0;
- //Check if page is loaded to determine if the value needs to be displayed in metric if necessary
- if (!unitInUS && pageLoaded)
- {
- document.getElementById("advFermTemp1").value = RoundedConvertFahrenheitToCelcius(document.getElementById("advFermTemp1").value);
- document.getElementById("advFermTemp2").value = RoundedConvertFahrenheitToCelcius(document.getElementById("advFermTemp2").value);
- }
- storeAdvancedFermentation();
- }
- //Clear contents of the advanced schedule
- //Fermentation Steps
- function clearAdvanacedSchedule()
- {
- $('#advFermSched tr').has('td').each(function ()
- {
- //If there is input clear the values
- if (!!$('input', $(this)).val())
- {
- $('input', $(this)).val("");
- }
- });
- }
- //Store Fermentables\Grains
- //re-orders all selections to the top
- function storeFermentables()
- {
- //Clear the current array
- recipeGrains = [];
- //get title headers as strings
- $('#mash-table th').each(function (index, item)
- {
- recipeGrainHeaders[index] = $(item).data("name");
- });
- $('#mash-table tr').has('td').each(function ()
- {
- if (this.id != "fermentablesTotal")
- {
- var ingredient = {};
- var store = true;
- $('td', $(this)).each(function (index, item)
- {
- if (recipeGrainHeaders[index] == "FermentableID")
- {
- ingredient[recipeGrainHeaders[index]] = parseInt($('input', $(this)).data("ingredientID"));
- if (!!ingredient[recipeGrainHeaders[index]])
- {
- ingredient.Ingredient = fermentableIngredients[ingredient[recipeGrainHeaders[index]]];
- }
- else
- {
- return true;
- }
- }
- else if (recipeGrainHeaders[index] == "Amount")
- {
- $('input', $(this)).removeClass("error");
- ingredient[recipeGrainHeaders[index]] = parseFloat($('input', $(this)).val());
- if (ingredient[recipeGrainHeaders[index]] < 0)
- {
- $('input', $(this)).addClass("error");
- var warning = "Grain Amount can't be less than 0.";
- $('#warnings-grains').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- }
- else
- {
- ingredient[recipeGrainHeaders[index]] = parseFloat($(item).html());
- $(item).html("0");
- }
- })
- //If the current unit is in celcius, convert to F as a whole number
- if (!unitInUS && pageLoaded)
- {
- ingredient["Amount"] = RoundedConvertKgToLbs(ingredient["Amount"]);
- }
- //Store if there are no null values and both the ID and Amount are populated.
- if (ingredient["FermentableID"])
- {
- recipeGrains.push(ingredient);
- }
- }
- });
- organizeGrains();
- }
- function organizeGrains(){
- //clear all current fields
- $("tr.recipegrain").each(function (index)
- {
- if (index < recipeGrains.length)
- {
- $('input.fermentable-search', $(this)).val(recipeGrains[index].Ingredient.Name);
- $('input.fermentable-search', $(this)).data("ingredientID", recipeGrains[index].FermentableID);
- $('input.fermentable-search', $(this)).prop('disabled', true);
- $('span.ingredient-remove', $(this)).show();
- if (unitInUS) {
- $('input.fermentable-amount', $(this)).val(recipeGrains[index].Amount);
- } else {
- $('input.fermentable-amount', $(this)).val(Math.round(ConvertLBsToKG(recipeGrains[index].Amount) * 100) / 100);
- }
- }
- else
- {
- $('input.fermentable-search', $(this)).prop('disabled', false);
- $('input.fermentable-search', $(this)).val("");
- $('input.fermentable-search', $(this)).removeData("ingredientID");
- $('span.ingredient-remove', $(this)).hide();
- $('input.fermentable-amount', $(this)).val(0);
- $('td.fermentable-gravity', $(this)).html(0);
- $('td.fermentable-color', $(this)).html(0);
- $('td.fermentable-percent', $(this)).html(0);
- }
- });
- }
- function storeHops()
- {
- //Clear any warnings
- $('#warnings-hops').empty();
- //Clear the current array
- while (recipeHops.length > 0)
- {
- recipeHops.pop();
- }
- //get title headers as strings
- $('#hops-table th').each(function (index, item)
- {
- recipeHopsHeaders[index] = $(item).data("name");
- });
- $('#hops-table tr').has('td').each(function ()
- {
- var hop = {};
- var store = true;
- $('td', $(this)).each(function (index, item)
- {
- //Check if step is still intended to be stored
- if (recipeHopsHeaders[index] == "HopID")
- {
- hop[recipeHopsHeaders[index]] = parseInt($('input', $(this)).data("ingredientID"));
- if (!!hop[recipeHopsHeaders[index]]) {
- hop.Ingredient = hopIngredients[hop[recipeHopsHeaders[index]]];
- }
- else
- {
- return true;
- }
- }
- else if (recipeHopsHeaders[index] == "Amount" || recipeHopsHeaders[index] == "Time" || recipeHopsHeaders[index] == "Alpha")
- {
- $('input', $(this)).removeClass("error");
- hop[recipeHopsHeaders[index]] = parseFloat($('input', $(this)).val());
- var min = parseFloat($('input', $(this)).attr("min"));
- var max = parseFloat($('input', $(this)).attr("max"));
- if (hop[recipeHopsHeaders[index]] < min || hop[recipeHopsHeaders[index]] > max)
- {
- $('input', $(this)).addClass("error");
- var warning = "";
- if ($('input', $(this))[0].id.indexOf("hopAmt") != -1)
- {
- warning = "Recipe hop amount is required and must be a number no greater than " + (unitInUS ? hopLimitUSString : hopLimitMetricString) + ". Hop amount in excess of " + (unitInUS ? hopLimitUSString : hopLimitMetricString) + " can be split into multiple cages.";
- } else if ($('input', $(this))[0].id.indexOf("hopTime") != -1)
- {
- warning = "Recipe hop time is required and must be a number greater than 300, rounded to the nearest minute.";
- } else if ($('input', $(this))[0].id.indexOf("hopAA") != -1)
- {
- warning = "Hop Alpha Acid must be greater than 0 and less than 20 percent.";
- }
- $('#warnings-hops').append("<div class=\"alert alert-warning alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×\;</button>" + warning + "</div>");
- }
- }
- else if (recipeHopsHeaders[index] == "Use")
- {
- hop[recipeHopsHeaders[index]] = $('select', $(this)).val();
- }
- else
- {
- hop[recipeHopsHeaders[index]] = parseFloat($(item).html());
- }
- });
- //If the current unit is in celcius, convert to F as a whole number
- if (!unitInUS && pageLoaded)
- {
- hop["Amount"] = Math.min(ConvertGramToOunce(hop["Amount"]), 1.5);
- }
- //If all values were populated, store the ferm step
- if (hop["HopID"])
- {
- recipeHops.push(hop);
- }
- });
- organizeHops();
- }
- function organizeHops() {
- //clear all current fields
- $("tr.recipehop").each(function (index) {
- if (index < recipeHops.length) {
- $('input.hop-search', $(this)).val(recipeHops[index].Ingredient.Name);
- $('input.hop-search', $(this)).data("ingredientID", recipeHops[index].HopID);
- $('input.hop-search', $(this)).prop('disabled', true);
- $('span.ingredient-remove', $(this)).show();
- if (unitInUS) {
- $('input.hop-amount', $(this)).val(recipeHops[index].Amount);
- } else {
- $('input.hop-amount', $(this)).val(Math.round(ConvertOunceToGram(recipeHops[index].Amount)));
- }
- $('input.hop-alphaacid', $(this)).val(recipeHops[index].Alpha);
- $('input.hop-time', $(this)).val(recipeHops[index].Time);
- }
- else
- {
- $('input.hop-search', $(this)).prop('disabled', false);
- $('input.hop-search', $(this)).val("");
- $('input.hop-search', $(this)).removeData("ingredientID");
- $('span.ingredient-remove', $(this)).hide();
- $('input.hop-amount', $(this)).val(0);
- $('input.hop-alphaacid', $(this)).val(0);
- $('input.hop-time', $(this)).val(0);
- $('td.hop-ibu', $(this)).html("0")
- }
- });
- }
- function checkAdvancedFermSchedule()
- {
- //Determine if the standard Fermentation Options should be shown or the advanced steps
- if (!!fermSteps)
- {
- if (JSON.stringify(fermSteps) == normalAleFermSteps)
- {
- //Change to Ale
- document.getElementById("normalFermSelection").getElementsByTagName('option')[0].selected = 'selected';
- //Change the schedule to Normal Ale
- fermScheduleChange(document.getElementById("fermTypeSelection"))
- }
- else if (JSON.stringify(fermSteps) == normalLagerFermSteps)
- {
- //Change to Lager
- document.getElementById("normalFermSelection").getElementsByTagName('option')[1].selected = 'selected';
- //Change the schedule to Normal Lager
- fermScheduleChange(document.getElementById("fermTypeSelection"))
- }
- //Empty, show NONE option
- else if (fermSteps.length == 0)
- {
- normalAleSchedule();
- }
- //If neither of the above, it's advanaced Steps
- else
- {
- document.getElementById("fermTypeSelection").getElementsByTagName('option')[1].selected = 'selected';
- }
- fermScheduleChange(document.getElementById("fermTypeSelection"));
- }
- else
- {
- normalAleSchedule();
- }
- }
- //=====================POPULATE FUNCTIONS=====================
- //Populate Options for BJCP Styles
- function populateBeverageStyles()
- {
- //Populate the Select Dropdown with all beverage style options
- //Find all the styles based on expected ordering by style
- var styleGuide = "";
- for (var styleID in beerStylesJSON)
- {
- //Add all the different style guides to a list to filter
- if(beerStylesJSON[styleID].StyleGuide != styleGuide) {
- styleGuides.push(beerStylesJSON[styleID].StyleGuide);
- styleGuide = beerStylesJSON[styleID].StyleGuide;
- }
- }
- //Add the style guide option for each guide
- for(var i = 0; i < styleGuides.length; i++) {
- $("#BeerStyleGuide").append('<option value="' + styleGuides[i] + '">' + styleGuides[i] +'</option>');
- }
- if (recipeStyle > 0)
- {
- LoadBeverageStyles(beerStylesJSON[recipeStyle].StyleGuide);
- $("#BeerStyle").val(recipeStyle);
- }
- else
- {
- LoadBeverageStyles();
- }
- //Set the style guide to the guide used for the beer style
- $("#BeerStyleGuide").val($("#BeerStyle option:selected").data("guide"));
- }
- //Populate Fermentation\Grain Input Table
- function populateFermentablesIngredients()
- {
- //Create as many rows as needed
- for (i = 0; i < maxFermentableCount; i++)
- {
- //Create starting row tag and beginning column
- var rowNumberID = "fermentableRowNum" + i;
- $("#mash-table").append('<tr class="recipegrain" id="' + rowNumberID + '"></tr>');
- var colNumberID = "fermentableRow" + i + "Col0";
- $("#" + rowNumberID).append('<td id="' + colNumberID + '"></td>')
- //Create Selection Box with name grain(i) in new Row
- var grainResultID = "grainResults" + (i + 1);
- var grainSelectID = "grainSelect" + (i + 1);
- $("#" + colNumberID).append('<div class="search" id="' + grainSelectID + '" data-index="' + (i + 1) + '"><input class="fermentable-search" type="text" oninput="filterResults(this)" onfocus="filterResults(this)" " /><div class="remove-container"><span class="ingredient-remove glyphicon glyphicon-remove" onclick="removeFermentable(this)"></div></span><dl class="results" id="' + grainResultID + '"></dl></div>')
- //First element generates the HTML while all additional elements can copy the HTML generated
- if (i == 0)
- {
- //Populate with options for selection
- for (var ingredient in fermentableIngredients)
- {
- //Get the Type from FermTypeCode
- var type = fermentableIngredients[ingredient].FermTypeCode.replace(/\s+/g, '').toLowerCase();
- //Check if type exists, if not create it
- if (document.getElementById("gp-" + type) === null)
- {
- $("#" + grainResultID).append('<dt class="no-select" id="gp-' + type + '" data-type="' + type + '" data-filter="" onclick="hideResults(this)">' + fermentableIngredients[ingredient].FermTypeCode + '</dt>');
- }
- $("#" + grainResultID).append('<dd data-value="' + fermentableIngredients[ingredient].FermentableID + '" data-type="' + type + '" data-filter="' + fermentableIngredients[ingredient].Name + '" onclick="changeFermentable(this)">' + fermentableIngredients[ingredient].Name + '</dd>');
- }
- //Sort the list
- var $grainResult = $("#" + grainResultID);
- var $grainOptions = $grainResult.children();
- $grainOptions.sort(function (a, b) {
- var at = a.getAttribute("data-type").toLowerCase(),
- bt = b.getAttribute("data-type").toLowerCase();
- if (at === bt)
- {
- var an = a.getAttribute("data-filter").toLowerCase(),
- bn = b.getAttribute("data-filter").toLowerCase();
- if (an > bn) {
- return 1;
- }
- if (an < bn) {
- return -1;
- }
- return 0;
- }
- else
- {
- if (at > bt) {
- return 1;
- }
- if (at < bt) {
- return -1;
- }
- return 0;
- }
- });
- $grainOptions.detach().appendTo($grainResult);
- }
- else
- {
- $("#" + grainResultID).html($("#grainResults1").html());
- }
- //Create column for Number Input
- var mashAmountID = "mash-table-amount" + i
- $("#" + rowNumberID).append('<td id="' + mashAmountID + '"></td>');
- //Create Input Form
- $("#" + mashAmountID).append('<input class="fermentable-amount recipe-numeric-input" id="grainsamt' + (i + 1) + '" type="number" min="0" step="0.01" value="0" onChange="grainAmountChange(this)">');
- //Column for Gravity Points
- $("#" + rowNumberID).append('<td class="fermentable-gravity" id="gravityPts' + (i + 1) + '">' + 0 + '</td>');
- //Column for Color Points
- $("#" + rowNumberID).append('<td class="fermentable-color" id="colorPts' + (i + 1) + '">' + 0 + '</td>');
- //Column for Ingredient Percentage Total
- $("#" + rowNumberID).append('<td class="fermentable-percent" id="percent' + (i + 1) + '">' + 0 + '</td>');
- }
- //Append total row after
- $("#mash-table").append('<tr class="reciperow" id="fermentablesTotal">\n\t<td style="font-weight: bold">Total</td>\n\t\t<td style="font-weight: bold" class="grainSum"></td>\n\t\t<td style="font-weight: bold" class="gravitySum"></td>\n\t\t<td style="font-weight: bold"></td>\n\t\t<td style="font-weight: bold"></td>\n\t</tr>');
- }
- function populateHopIngredients()
- {
- for (var i = 0; i < maxHopCount; i++)
- {
- //Create starting Row
- var rowNumberID = "hopRowNum" + i;
- $("#hops-table").append('<tr class="recipehop" id="' + rowNumberID + '"></tr>');
- //Create starting column that will contain selection
- var colNumberID = "hopRow" + i + "Col0";
- $("#" + rowNumberID).append('<td id="' + colNumberID + '"></td>')
- //Create Selection Box with name grain(i) in new Row
- var hopResultID = "hopResults" + (i + 1);
- var hopSelectID = "hopSelect" + (i + 1);
- $("#" + colNumberID).append('<div class="search" id="' + hopSelectID + '" data-index="' + (i + 1) + '"><input class="hop-search" type="text" oninput="filterResults(this)" onfocus="filterResults(this)" " /><div class="remove-container"><span class="ingredient-remove glyphicon glyphicon-remove" onclick="removeHop(this)"></div></span><dl class="results" id="' + hopResultID + '"></dl></div>')
- //First element generates the HTML while all additional elements can copy the HTML generated
- if (i == 0) {
- //Populate with options for selection
- for (var ingredient in hopIngredients)
- {
- $("#" + hopResultID).append('<dd data-value="' + hopIngredients[ingredient].HopID + '" data-filter="' + hopIngredients[ingredient].Name + '" onclick="changeHop(this)">' + hopIngredients[ingredient].Name + '</dd>');
- }
- //Sort the list
- var $hopResult = $("#" + hopResultID);
- var $hopOptions = $hopResult.children("dd");
- $hopOptions.sort(function (a, b) {
- var an = a.getAttribute("data-filter").toLowerCase(),
- bn = b.getAttribute("data-filter").toLowerCase();
- if (an > bn) {
- return 1;
- }
- if (an < bn) {
- return -1;
- }
- return 0;
- });
- $hopOptions.detach().appendTo($hopResult);
- }
- else {
- $("#" + hopResultID).html($("#hopResults1").html());
- }
- //Add the column for amount and the input
- $("#" + rowNumberID).append('<td><input class="recipe-numeric-input valid hop-amount" id="hopAmt' + (i + 1) + '" type="number" step="0.01" min="0" max="1.5" value="0" onChange="hopInputChange(this)"></td>');
- //Add the column for AA and the input
- $("#" + rowNumberID).append('<td><input class="recipe-numeric-input valid hop-alphaacid" id="hopAA' + (i + 1) + '" type="number" step="0.1" min="0" max="20" value="0" onChange="hopInputChange(this)"></td>');
- //Add the column for Hop Use and the Select
- var hopUseID = "hopUse" + (i + 1);
- $("#" + rowNumberID).append('<td><select class="selectS valid hop-use" id="' + hopUseID + '"></select></td>');
- //Add boil option
- $("#" + hopUseID).append('<option value="Boil">Boil</option>')
- //Add the column for Time and the input
- $("#" + rowNumberID).append('<td><input class="recipe-numeric-input valid hop-time" id="hopTime' + (i + 1) + '" type="number" step="1" min="0" max="300" value="0" onChange="hopInputChange(this)"></td>')
- //Add text HTML for IBU
- $("#" + rowNumberID).append('<td class="recipe-ibu-amt hop-ibu" id="ibuAMT' + (i + 1) + '">0</td>');
- }
- }
- function populateFermentationSteps()
- {
- for (var i = 0; i < maxFermStepCount; i++)
- {
- var rowNumberID = "fermStepRow" + i;
- $("#advFermSched").append('<tr class="reciperow" id="' + rowNumberID + '"></tr>');
- //Step Number Column
- $("#" + rowNumberID).append('<td class="advRecipeFirstCol" id="advFermStep' + (i + 1) + '">' + (i + 1) + '</td>');
- $("#" + rowNumberID).append('<td><input class="recipe-numeric-input" id="advFermName' + (i + 1) + '" style="width: 95%; text-align: left" onchange="storeAdvancedFermentation()" maxlength="20"></td>');
- $("#" + rowNumberID).append('<td><input class="recipe-numeric-input fermTemp" type="number" min="32" max="85" step="1" data-name="Temp" id="advFermTemp' + (i + 1) + '" onchange="storeAdvancedFermentation()"></td>');
- $("#" + rowNumberID).append('<td><input class="recipe-numeric-input" type="number" min="0" max="45" step="1" id="advFermDay' + (i + 1) + '" onchange="storeAdvancedFermentation()"></td>');
- $("#" + rowNumberID).append('<td><input class="recipe-numeric-input" type="number" min="0" max="24" step="0.1" id="advFermHour' + (i + 1) + '" onchange="storeAdvancedFermentation()"></td>');
- if (fermSteps.length > i)
- {
- $("#advFermName" + (i + 1)).val(fermSteps[i].Name);
- $("#advFermTemp" + (i + 1)).val(fermSteps[i].Temp);
- //Get total time in minutes
- var minuteSum = 0;
- minuteSum += fermSteps[i].Days * 1440;
- minuteSum += fermSteps[i].Hours * 60;
- minuteSum += fermSteps[i].Minutes;
- //Make sure the number is always positive
- minuteSum = Math.max(0, minuteSum);
- $("#advFermDay" + (i + 1)).val(Math.floor(minuteSum / 1440));
- $("#advFermHour" + (i + 1)).val(minuteSum % 1440 / 60);
- }
- }
- storeAdvancedFermentation();
- }
- function filterResults(target) {
- var filterText = target.value.toLowerCase();
- var results = $(target.parentNode).children(".results");
- if(results.length > 0) {
- for(var i = 0; i < results.length; i++) {
- var items = $(results[i]).children("dd");
- for(var j = 0; j < items.length; j++) {
- var itemFilter = $(items[j]).data("filter");
- if(!!itemFilter) {
- if(itemFilter.toLowerCase().indexOf(filterText) > -1) {
- $(items[j]).show();
- } else {
- $(items[j]).hide();
- }
- }
- }
- }
- }
- }
- function hideResults(target) {
- $(target.parentNode).hide();
- }
Advertisement
Add Comment
Please, Sign In to add comment