summaryrefslogtreecommitdiff
path: root/js/garden.js
blob: 8077260977e62d8d4b48f353396ca84b1623d16d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
const WEEKS_BEFORE_LAST_FROST = 10;
const FALL_FACTOR = 2;

function range(start, end) {
  const size = end - start;
  const array = new Array(size);
  for(let i = start; i < end; i++) {
    array[i - start] = i;
  }
  return array;
}

function daysLater(date, n) {
  return new Date(date.getTime() + n * 24 * 60 * 60 * 1000);
}

function weeksLater(date, n) {
  return daysLater(date, n * 7);
}

function seasonLengthInWeeks(lastFrostDate, firstFrostDate) {
  const oneWeek = 7 * 24 * 60 * 60 * 1000;
  const dt = firstFrostDate.getTime() - lastFrostDate.getTime();
  return Math.floor(dt / oneWeek);
}

function seasonWeeks(lastFrostDate, seasonLength) {
  return range(-WEEKS_BEFORE_LAST_FROST, seasonLength + 3).map(offset => {
    return {
      date: weeksLater(lastFrostDate, offset),
      offset: offset
    };
  });
}

class Season {
  constructor(lastFrostDate, firstFrostDate) {
    this.lastFrostDate = lastFrostDate;
    this.firstFrostDate = firstFrostDate;
    this.length = seasonLengthInWeeks(lastFrostDate, firstFrostDate);
    this.weeks = seasonWeeks(lastFrostDate, this.length);
  }
}

class Crop {
  constructor(name, {depth, fallCrop, family, headStart, interval, maturity, multisow,
                     overwinterPlant, pause, references, spacing, springPlant, resume,
                     species, transplant, trellis}) {
    // Seed planting depth in inches.
    this.depth = depth || .25;
    // Plant again in the fall?
    this.fallCrop = fallCrop;
    // Broad category (brassica, cucurbit, nightshade, etc.)
    this.family = family;
    // Weeks spent indoors before transplanting.
    this.headStart = headStart || 0;
    // Succession planting interval (weeks)
    this.interval = interval || 0;
    // Average time to maturity from transplanting or sowing (weeks)
    this.maturity = maturity;
    // Seeds per module
    this.multisow = multisow || 1;
    // Human readable name
    this.name = name;
    // Overwintered crops are fall crops but they are not subject to
    // the same rules as plants that are harvested the same year.
    // Instead of planting them relative to their time to maturity,
    // they are planted relative to the first frost date so they can
    // be harvested in the spring/summer of the following year.
    this.overwinterPlant = overwinterPlant;
    // When to pause succession planting (weeks after last frost)
    this.pause = pause || 99;
    // External links to helpful information about the crop.
    this.references = references || [];
    // When to resume succession planting (weeks before first frost)
    this.resume = resume || 99;
    // Plants per square foot, or, in the case of multisowing, clumps
    // per square foot.
    this.spacing = spacing || 1;
    // Latin names.
    this.species = species || [];
    // Earliest sowing/transplanting week (offset relative to last
    // frost date.) Null if the crop should not be planted in the
    // spring.
    this.springPlant = springPlant;
    // Transplanted or direct sown?
    this.transplant = transplant || false;
    // Needs a trellis?
    this.trellis = trellis || false;
  }
}

const CROPS = [
  new Crop("Amaranth", {
    depth: 0.125,
    family: "Amaranth",
    headStart: 4,
    maturity: 5,
    spacing: 4,
    springPlant: 0,
    species: ["amaranth tricolor"],
    transplant: true
  }),
  new Crop("Arugula", {
    family: "Brassica",
    fallCrop: true,
    headStart: 4,
    maturity: 6,
    multisow: 3,
    pause: 3,
    resume: 11,
    spacing: 4,
    species: ["eruca sativa"],
    springPlant: -4,
    transplant: true
  }),
  new Crop("Basil", {
    family: "Mint",
    headStart: 5,
    maturity: 6,
    species: ["ocimum basilicum"],
    springPlant: 2,
    transplant: true
  }),
  new Crop("Bean (Bush)", {
    depth: 1,
    family: "Legume",
    headStart: 3,
    interval: 3,
    maturity: 8,
    spacing: 9,
    species: ["phaseolus vulgaris"],
    springPlant: 1,
    transplant: true,
    transplantIterations: 1
  }),
  new Crop("Bean (Pole)", {
    depth: 1,
    family: "Legume",
    headStart: 2,
    maturity: 9,
    spacing: 8,
    species: ["phaseolus vulgaris"],
    springPlant: 1,
    transplant: true,
    trellis: true
  }),
  new Crop("Beet", {
    depth: .5,
    family: "Amaranth",
    headStart: 4,
    interval: 3,
    maturity: 8,
    multisow: 3,
    pause: 1,
    resume: 12,
    spacing: 4,
    species: ["beta vulgaris"],
    springPlant: -3,
    transplant: true
  }),
  new Crop("Bok Choy", {
    fallCrop: true,
    family: "Brassica",
    headStart: 2,
    maturity: 7,
    spacing: 4,
    species: ["brassica rapa"],
    springPlant: -2,
    transplant: true
  }),
  new Crop("Broccoli", {
    fallCrop: true,
    family: "Brassica",
    headStart: 4,
    maturity: 12,
    species: ["brassica oleracea"],
    springPlant: -3,
    transplant: true
  }),
  new Crop("Brussels Sprouts", {
    fallCrop: true,
    family: "Brassica",
    headStart: 6,
    maturity: 16,
    species: ["brassica oleracea"],
    transplant: true
  }),
  new Crop("Cabbage (Early)", {
    family: "Brassica",
    fallCrop: true,
    headStart: 4,
    maturity: 8,
    species: ["brassica oleracea"],
    springPlant: -3,
    transplant: true
  }),
  new Crop("Cabbage (Late)", {
    family: "Brassica",
    fallCrop: true,
    headStart: 4,
    maturity: 14,
    species: ["brassica oleracea"],
    transplant: true
  }),
  new Crop("Cabbage (Asian)", {
    family: "Brassica",
    fallCrop: true,
    headStart: 2,
    maturity: 8,
    species: ["brassica rapa"],
    springPlant: -3,
    transplant: true
  }),
  new Crop("Cauliflower", {
    family: "Brassica",
    fallCrop: true,
    headStart: 4,
    maturity: 10,
    species: ["brassica oleracea"],
    springPlant: -3,
    transplant: true
  }),
  new Crop("Carrot", {
    family: "Umbellifer",
    interval: 4,
    maturity: 10,
    spacing: 16,
    species: ["daucus carota"],
    springPlant: -4
  }),
  new Crop("Cilantro", {
    family: "Umbellifer",
    interval: 3,
    maturity: 7,
    species: ["coriandrum sativum"],
    springPlant: 0
  }),
  new Crop("Claytonia", {
    fallCrop: true,
    family: "Montiaceae",
    headStart: 4,
    maturity: 6,
    spacing: 9,
    species: ["montia perfoliata"],
    springPlant: -5,
    transplant: true
  }),
  new Crop("Cucumber", {
    depth: .5,
    family: "Cucurbit",
    headStart: 4,
    maturity: 9,
    spacing: 2,
    species: ["cucumis sativus"],
    springPlant: 1,
    transplant: true,
    trellis: true
  }),
  new Crop("Dill", {
    family: "Umbellifer",
    fallCrop: true,
    headStart: 3,
    maturity: 8,
    spacing: 4,
    species: ["anethum graveolens"],
    springPlant: -2,
    transplant: true
  }),
  new Crop("Eggplant", {
    family: "Nightshade",
    headStart: 8,
    maturity: 11,
    species: ["solanum melongena"],
    springPlant: 3,
    transplant: true
  }),
  new Crop("Endive", {
    depth: .125,
    family: "Aster",
    headStart: 4,
    maturity: 4,
    species: ["cichorium endivia"],
    springPlant: -3,
    transplant: true
  }),
  new Crop("Fennel", {
    fallCrop: true,
    family: "Umbellifer",
    headStart: 4,
    maturity: 10,
    spacing: 4,
    species: ["foeniculum vulgare"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Garlic", {
    depth: 3,
    family: "Allium",
    fallCrop: true,
    overwinterPlant: 2,
    maturity: 28,
    spacing: 4,
    species: ["allium sativum"]
  }),
  new Crop("Kale", {
    fallCrop: true,
    family: "Brassica",
    headStart: 4,
    maturity: 4,
    species: ["brassica napus", "brassica oleracea"],
    springPlant: -4,
    transplant: true
  }),
  new Crop("Leek (Summer)", {
    depth: 0.5,
    family: "Allium",
    headStart: 6,
    maturity: 10,
    multisow: 4,
    spacing: 1,
    species: ["allium ampeloprasum"],
    springPlant: -2,
    transplant: true
  }),
  new Crop("Lettuce (Leaf)", {
    depth: .125,
    family: "Aster",
    headStart: 4,
    interval: 2,
    maturity: 7,
    pause: 3,
    resume: 11,
    spacing: 4,
    species: ["latuca sativa"],
    springPlant: -4,
    transplant: true
  }),
  new Crop("Mache (Corn Salad)", {
    family: "Honeysuckle",
    interval: 2,
    maturity: 7,
    pause: 1,
    resume: 11,
    spacing: 16,
    species: ["valerianella locusta"],
    springPlant: -4
  }),
  new Crop("Mustard Greens", {
    family: "Brassica",
    headStart: 3,
    interval: 3,
    maturity: 6,
    pause: 1,
    resume: 10,
    spacing: 4,
    species: ["brassica juncea", "brassica rapa"],
    springPlant: -4,
    transplant: true
  }),
  new Crop("Onion", {
    depth: 0.5,
    family: "Allium",
    headStart: 6,
    maturity: 14,
    multisow: 4,
    references: [
      {
        title: "Charles Dowding - Grow onions and spring onions from seed",
        url: "https://www.youtube.com/watch?v=1k0f4GoC6Zw"
      }
    ],
    spacing: 1,
    species: ["allium cepa"],
    springPlant: -4,
    transplant: true
  }),
  new Crop("Parsley", {
    family: "Umbellifer",
    headStart: 6,
    maturity: 7,
    spacing: 4,
    species: ["petroselinum crispum"],
    springPlant: -4,
    transplant: true
  }),
  new Crop("Parsnip", {
    depth: .5,
    family: "Umbellifer",
    maturity: 14,
    spacing: 4,
    species: ["pastinaca sativa"],
    springPlant: -2
  }),
  new Crop("Pea", {
    fallCrop: 'sow',
    family: "Legume",
    headStart: 2,
    maturity: 12,
    multisow: 4,
    spacing: 4,
    species: ["pisum sativum"],
    springPlant: -3,
    transplant: true,
    trellis: true
  }),
  new Crop("Pepper", {
    family: "Nightshade",
    headStart: 8,
    maturity: 10,
    species: ["capsicum annuum"],
    springPlant: 3,
    transplant: true
  }),
  new Crop("Potato", {
    depth: 3,
    family: "Nightshade",
    maturity: 12,
    spacing: 4,
    species: ["solanum tuberosum"],
    springPlant: -3
  }),
  new Crop("Radish (Spring)", {
    depth: .5,
    family: "Brassica",
    headStart: 3,
    interval: 3,
    maturity: 4,
    multisow: 5,
    pause: 4,
    resume: 10,
    spacing: 4,
    species: ["raphanus raphanistrum"],
    springPlant: -3,
    transplant: true
  }),
  new Crop("Radish (Winter)", {
    depth: .5,
    family: "Brassica",
    fallCrop: true,
    headStart: 3,
    maturity: 9,
    spacing: 4,
    species: ["raphanus raphanistrum"],
    transplant: true
  }),
  new Crop("Shallot", {
    family: "Allium",
    headStart: 6,
    maturity: 9,
    multisow: 3,
    spacing: 4,
    species: ["allium cepa"],
    springPlant: -4,
    transplant: true
  }),
  new Crop("Spinach", {
    depth: .5,
    family: "Amaranth",
    fallCrop: true,
    headStart: 3,
    maturity: 6,
    multisow: 3,
    pause: -1,
    resume: 11,
    spacing: 4,
    species: ["spinacia olerace"],
    springPlant: -5,
    transplant: true
  }),
  new Crop("Squash (Summer)", {
    depth: 1,
    family: "Cucurbit",
    headStart: 4,
    maturity: 8,
    spacing: 1.0 / 9,
    species: ["cucurbita pepo"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Squash (Winter)", {
    depth: 1,
    family: "Cucurbit",
    headStart: 4,
    maturity: 12,
    spacing: 0.5,
    species: ["cucurbita maxima", "cucurbita moschata", "cucurbita pepo"],
    springPlant: 1,
    transplant: true
  }),
  new Crop("Swiss Chard", {
    depth: .5,
    family: "Amaranth",
    headStart: 4,
    maturity: 4,
    spacing: 4,
    species: ["beta vulgaris"],
    springPlant: 2,
    transplant: true
  }),
  new Crop("Tomato (Indeterminate)", {
    family: "Nightshade",
    headStart: 7,
    maturity: 11,
    species: ["lycopersicon esculentum"],
    springPlant: 3,
    transplant: true,
    trellis: true
  }),
  new Crop("Turnip", {
    family: "Brassica",
    fallCrop: true,
    headStart: 3,
    maturity: 5,
    multisow: 5,
    pause: 6,
    resume: 10,
    spacing: 4,
    species: ["brassica rapa"],
    springPlant: -3,
    transplant: true
  }),
  new Crop("Alyssum", {
    family: "Brassica",
    headStart: 4,
    maturity: 8,
    species: ["lobularia maritima"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Amaranth (Flower)", {
    family: "Amaranth",
    headStart: 4,
    maturity: 12,
    species: ["amaranthus caudatus"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Borage", {
    family: "Borage",
    maturity: 7,
    species: ["borago officinalis"],
    springPlant: 0
  }),
  new Crop("Calendula", {
    family: "Aster",
    headStart: 4,
    maturity: 11,
    species: ["calendula officinalis"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Cornflower", {
    family: "Aster",
    headStart: 4,
    maturity: 12,
    spacing: 4,
    species: ["centaurea cyanus"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Cosmos", {
    family: "Aster",
    headStart: 4,
    maturity: 12,
    species: ["cosmos bipinnatus"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Larkspur", {
    family: "Buttercup",
    headStart: 4,
    maturity: 11,
    spacing: 3,
    species: ["consolida ajacis"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Marigold", {
    family: "Aster",
    headStart: 4,
    maturity: 11,
    species: ["Tagetes erecta", "tagetes patula"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Mexican Sunflower", {
    family: "Aster",
    headStart: 4,
    maturity: 12,
    species: ["tithonia rotundifolia"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Nasturtium", {
    depth: 0.5,
    family: "Tropaeolum",
    headStart: 2,
    maturity: 8,
    species: ["tropaeolum majus"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Nigella", {
    family: "Buttercup",
    headStart: 4,
    maturity: 10,
    species: ["nigella hispanica"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Strawflower", {
    family: "Aster",
    headStart: 8,
    maturity: 10,
    species: ["xerochrysum bracteatum"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Sunflower", {
    family: "Helianthus",
    headStart: 2,
    maturity: 11,
    species: ["helianthus annuus"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Sweet Pea", {
    depth: 0.5,
    family: "Legume",
    headStart: 8,
    maturity: 10,
    species: ["lathyrus odoratus"],
    springPlant: 0,
    transplant: true
  }),
  new Crop("Zinnia", {
    family: "Aster",
    headStart: 4,
    maturity: 7,
    species: ["zinnia elegans"],
    springPlant: 0,
    transplant: true
  })
];

function makeCropSchedule(crop, season) {
  function isSuccession(offset) {
    const start = offset <= crop.pause ? crop.springPlant : crop.resume;
    return crop.interval > 0 &&
      offset != crop.springPlant &&
      offset >= crop.springPlant &&
      offset <= fallPlant &&
      (offset <= crop.pause || offset >= resume) &&
      (offset - start) % crop.interval == 0;
  }

  function isSuccessionStart(offset) {
    offset += crop.headStart;
    const start = offset <= crop.pause ? crop.springPlant : crop.resume;
    return crop.interval > 0 &&
      crop.transplant &&
      offset != crop.springPlant &&
      offset >= crop.springPlant &&
      offset <= fallPlant &&
      (offset <= crop.pause || offset >= resume) &&
      (offset - start) % crop.interval == 0;
  }

  const springStart = crop.springPlant - crop.headStart;
  const fallPlant = season.length - crop.maturity - FALL_FACTOR;
  const fallStart = fallPlant - crop.headStart;
  const resume = season.length - crop.resume;

  return season.weeks.map(week => {
    const actions = [];

    if(crop.transplant && week.offset == springStart) {
      actions.push("start");
    } else if(crop.transplant && week.offset == crop.springPlant) {
      actions.push("transplant");
    } else if(week.offset == crop.springPlant) {
      actions.push("sow");
    }

    if(isSuccession(week.offset)) {
      actions.push(crop.transplant ? "transplant" : "sow");
    }
    if(isSuccessionStart(week.offset)) {
      actions.push("start");
    }

    if(crop.fallCrop) {
      if(crop.overwinterPlant) {
        if(week.offset == season.length + crop.overwinterPlant) {
          actions.push("sow");
        }
      } else if(crop.transplant && week.offset == fallStart) {
        actions.push("start");
      } else if(crop.transplant && week.offset == fallPlant) {
        actions.push("transplant");
      } else if(week.offset == fallPlant) {
        actions.push("sow");
      }
    }

    return {
      date: weeksLater(season.lastFrostDate, week.offset),
      actions: actions
    };
  });
}

function clearElement(element) {
  while (element.firstChild) {
    element.removeChild(element.firstChild);
  }
}

function makeSchedule(crops, season) {
  const schedule = {};
  crops.forEach(crop => {
    schedule[crop.name] = makeCropSchedule(crop, season);
  });
  return schedule;
}

function monthAndDay(date) {
  return (date.getUTCMonth() + 1) + "/" + date.getUTCDate();
}

function viewCropDetails(crop) {
  function close() {
    container.removeChild(overlay);
  }

  function addDetail(name, detail) {
    const p = document.createElement("p");
    p.appendChild(document.createTextNode(`${name}: ${detail}`));
    modal.appendChild(p);
  }

  function addReferences() {
    if(crop.references.length > 0) {
      const div = document.createElement("div");
      const title = document.createElement("span");
      const list = document.createElement("ul");
      title.appendChild(document.createTextNode("References"));
      div.appendChild(title);
      crop.references.forEach(ref => {
        const li = document.createElement("li");
        const link = document.createElement("a");
        link.appendChild(document.createTextNode(ref.title));
        link.href = ref.url;
        link.target = "_blank"; // open in new tab.
        li.appendChild(link);
        list.appendChild(li);
      });
      div.appendChild(list);
      modal.appendChild(div);
    }
  }

  const container = document.getElementById("container");
  const overlay = document.createElement("div");
  const modal = document.createElement("div");
  const heading = document.createElement("h2");
  const subheading = document.createElement("span");
  const speciesDetail = `(${crop.species.join(", ")}) - ${crop.family} family`;
  heading.appendChild(document.createTextNode(crop.name));
  subheading.appendChild(document.createTextNode(speciesDetail));
  subheading.classList.add("detail-subheading");
  heading.appendChild(subheading);
  modal.classList.add("modal");
  modal.appendChild(heading);
  addDetail("Average time to maturity",
            `${crop.maturity} weeks from ${crop.transplant ? "transplant" : "seed"}`);
  if(crop.springPlant == -1) {
    addDetail("Spring planting time", `1 week before last frost`);
  } else if(crop.springPlant < 0) {
    addDetail("Spring planting time",
              `${Math.abs(crop.springPlant)} weeks before last frost`);
  } else if(crop.springPlant == 1) {
    addDetail("Spring planting time", `1 week after last frost`);
  } else if(crop.springPlant > 0) {
    addDetail("Spring planting time",
              `${crop.springPlant} weeks after last frost`);
  } else if(crop.springPlant == 0) {
    addDetail("Spring planting time", "On the last frost date");
  } else {
    addDetail("Spring planting time", "Not a spring crop");
  }
  if(crop.fallCrop) {
    addDetail("Fall planting time", `${crop.maturity + FALL_FACTOR} weeks before first frost`);
  } else if(crop.resume != 99) {
    addDetail("Fall planting time", `Succession planted ${crop.resume} weeks before first frost`);
  } else if(crop.interval > 0) {
    addDetail("Fall planting time", `Succession planted until ${crop.maturity + FALL_FACTOR} weeks before first frost`);
  } else {
    addDetail("Fall planting time", "Not a fall crop");
  }
  addDetail("Planting method", crop.transplant ? "Transplant" : "Direct sow");
  if(crop.transplant) {
    addDetail("Start indoors", `${crop.headStart} weeks before planting`);
  }
  if(crop.interval > 0) {
    addDetail("Succession planting interval", `Every ${crop.interval} weeks`);
  }
  if(crop.multisow > 1) {
    addDetail("Multisow", `${crop.multisow} plants per hole (after thinning)`);
  } else {
    addDetail("Multisow", "No");
  }
  if(crop.spacing >= 1) {
    addDetail("Spacing", `${crop.spacing} ${crop.multisow > 1 ? "clump(s)" : "plant(s)"} per square foot`);
  } else {
    addDetail("Spacing", `1 per ${Math.floor(1 / crop.spacing)} square feet`);
  }
  addDetail("Seed planting depth", `${crop.depth}"`);
  addDetail("Needs a trellis", crop.trellis ? "Yes" : "No");
  addReferences();
  overlay.classList.add("overlay");
  overlay.appendChild(modal);
  container.appendChild(overlay);
  overlay.addEventListener("click", event => close());
}

function makeDetailLink(crop) {
  const span = document.createElement("span");
  span.classList.add("crop");
  span.appendChild(document.createTextNode(crop.name));
  span.addEventListener("click", event => {
    viewCropDetails(crop);
  });
  return span;
}

function refreshTable(crops, season, schedule) {
  function createWeeksRow(season) {
    const row = document.createElement("tr");
    row.appendChild(document.createElement("th"));
    season.weeks.forEach(week => {
      const td = document.createElement("th", {scope: "col"});
      const firstFrost = week.offset == 0;
      const lastFrost = week.offset == season.length;
      const dateString = monthAndDay(week.date);
      const label = firstFrost || lastFrost ?  `${dateString}❄`: dateString;
      const text = document.createTextNode(label);
      td.appendChild(text);
      row.appendChild(td);
    });
    return row;
  }

  function createHeader(season) {
    const thead = document.createElement("thead");
    const row = document.createElement("tr");
    ["Crop", "Week"].forEach(column => {
      const th = document.createElement("th", {scope: "col"});
      const text = document.createTextNode(column);
      th.appendChild(text);
      row.appendChild(th);
    });
    thead.appendChild(row);
    thead.appendChild(createWeeksRow(season));
    return thead;
  }

  function createCropRow(crop, schedule) {
    function icon(name) {
      const icon = document.createElement("span");
      icon.classList.add("icon");
      icon.classList.add(`icon-${name}`);
      return icon;
    }

    const row = document.createElement("tr");
    const th = document.createElement("td");
    th.appendChild(makeDetailLink(crop));
    row.appendChild(th);
    schedule.forEach(week => {
      const td = document.createElement("td");
      td.title = monthAndDay(week.date);
      week.actions.forEach(action => {
        const iconName = {
          start: "start-indoors",
          sow: "direct-sow",
          transplant: "transplant"
        }[action];
        td.appendChild(icon(iconName));
      });
      row.appendChild(td);
    });
    return row;
  }

  const scheduleTable = document.getElementById("schedule");
  const tbody = document.createElement("tbody");
  clearElement(scheduleTable);
  scheduleTable.appendChild(createHeader(season));
  crops.forEach(crop => {
    tbody.appendChild(createCropRow(crop, schedule[crop.name]));
  });
  scheduleTable.appendChild(tbody);
}

function refreshInstructions(crops, season, schedule) {
  const instructionsDiv = document.getElementById("instructions");
  season.weeks.forEach(week => {
    const actions = crops.flatMap(crop => {
      const i = week.offset + WEEKS_BEFORE_LAST_FROST;
      return schedule[crop.name][i].actions.map(action => {
        return {
          crop: crop,
          type: action
        };
      });
    }).sort((a, b) => {
      if(a.type < b.type) {
        return -1;
      } else if(a.type > b.type) {
        return 1;
      }

      return 0;
    });;

    if(actions.length > 0) {
      const weekDiv = document.createElement("div");
      const heading = document.createElement("h3");
      heading.appendChild(document.createTextNode(monthAndDay(week.date)));
      weekDiv.appendChild(heading);
      actions.forEach(action => {
        const p = document.createElement("p");
        let prefix;
        let suffix;
        if(action.type == "start") {
          prefix = "Start ";
          suffix = " indoors.";
        } else if(action.type == "sow") {
          prefix = "Sow ";
          suffix = " outdoors.";
        } else if(action.type == "transplant") {
          prefix = "Transplant ";
          suffix = " outdoors.";
        }
        p.appendChild(document.createTextNode(prefix));
        p.appendChild(makeDetailLink(action.crop));
        p.appendChild(document.createTextNode(suffix));
        weekDiv.appendChild(p);
      });
      instructionsDiv.appendChild(weekDiv);
    }
  });
}

function refreshView() {
  function loadDate(name) {
    const dateString = window.localStorage.getItem(name);
    return dateString && new Date(Date.parse(dateString));
  }

  const lastFrostDate = loadDate("lastFrostDate");
  const firstFrostDate = loadDate("firstFrostDate");

  if(firstFrostDate && lastFrostDate) {
    const season = new Season(lastFrostDate, firstFrostDate);
    const schedule = makeSchedule(CROPS, season);
    refreshTable(CROPS, season, schedule);
    refreshInstructions(CROPS, season, schedule);
  }
}

function getLastFrostDateInput() {
  return document.querySelector("input[name='last-frost-date']");
}

function getFirstFrostDateInput() {
  return document.querySelector("input[name='first-frost-date']");
}

function loadConfiguration() {
  const lastFrostDate = window.localStorage.getItem("lastFrostDate");
  const firstFrostDate = window.localStorage.getItem("firstFrostDate");
  if(lastFrostDate) {
    getLastFrostDateInput().value = lastFrostDate;
  }
  if(firstFrostDate) {
    getFirstFrostDateInput().value = firstFrostDate;
  }
}

function loadIntensiveGarden() {
  loadConfiguration();
  getLastFrostDateInput().addEventListener("input", event => {
    window.localStorage.setItem("lastFrostDate", event.target.value);
    refreshView();
  });
  getFirstFrostDateInput().addEventListener("input", event => {
    window.localStorage.setItem("firstFrostDate", event.target.value);
    refreshView();
  });
  refreshView();
  // Open/close sections of page.
  document.querySelectorAll("section").forEach(section => {
    const container = section.querySelector(".section-container");
    const header = section.querySelector("h2");
    header.classList.add("open");
    header.addEventListener("click", event => {
      header.classList.remove(container.hidden ? "closed" : "open");
      container.hidden = !container.hidden;
      header.classList.add(container.hidden ? "closed" : "open");
    });
  });
}

window.addEventListener("load", loadIntensiveGarden);