Merge pull request #2864 from solgenomics/topic/fixing_h2_detail_page
[sgn.git] / mason / breeders_toolbox / manage_drone_imagery.mas
blob3921b6baf384e8c81a9e826773a4874710ddd48d
2 <%args>
3 </%args>
5 <& /util/import_javascript.mas, classes => [ 'jquery.iframe-post-form', 'CXGN.BreederSearch', 'd3.d3v4Min.js', "opencv.opencv" ] &>
7 <style>
8 .ui-autocomplete { z-index:2147483647; }
10 .straightLine, .hrLine{
11   position: absolute;
12   background-color: red;
13   transition: transform .05s ease-in-out;
15 </style>
17 <div id="manage_drone_imagery_top_div">
19     <& /page/page_title.mas, title=>"Manage Drone Imagery" &>
21 <%perl>
22 my $buttons_html = "<button class='btn btn-primary' style='margin:3px' id='upload_drone_imagery_link'>Upload Imagery</button><button class='btn btn-default' style='margin:3px' id='download_phenotypes_drone_imagery_link'>Download Image-Phenotypes</button><button class='btn btn-success' style='margin:3px' id='keras_cnn_drone_imagery_link'>Keras CNN Models</button><button class='btn btn-success' style='margin:3px' id='drone_imagery_calculate_statistics_link'>Calculate Statistics</button><button class='btn btn-default' style='margin:3px' id='drone_imagery_compare_field_images_link'>Compare Aerial Field Images</button>";
23 </%perl>
25     <& /page/detail_page_2_col_section.mas, info_section_collapsed => 0, info_section_title => "<h4 style='display:inline'>Drone Imagery</h4>", info_section_subtitle => 'Upload and view field drone imagery', buttons_html => $buttons_html, icon_class => undef, col1_width_class => "col-sm-0", col2_width_class => "col-sm-12", info_section_id => "manage_drone_imagery_main" &>
27 </div>
29 <div id="manage_drone_imagery_standard_process_div" style="display:none">
31     <& /page/page_title.mas, title=>"Manage Drone Imagery: Run A Standard Process On Orthophotomosaics" &>
33     <&| /util/workflow.mas, id=> "manage_drone_imagery_standard_process_workflow" &>
34         <&| /util/workflow.mas:step, title=> "Intro" &>
35             <& /page/page_title.mas, title=>"This workflow will guide you through applying a standard process to your aerial imaging bands" &>
36             <p>Here you can take one of the drone run bands you uploaded all the way through the process to plot image saving. This will require manual steps such as image rotation, cropping, and plot polygon templating. After you have completed this process for one drone run band, you can apply it to all other drone run bands and other calculated vegetative indices.</p>
37             <br/><br/>
38             <center>
39             <button class="btn btn-primary" onclick="Workflow.complete(this); return false;">Go to Next Step</button>
40             </center>
41         </&>
42         <&| /util/workflow.mas:step, title=> "Drone Run Band" &>
43             <& /page/page_title.mas, title=>"Select a drone run band" &>
45             <div class="well well-sm">
46                 <p>Please select one drone run band to take through the process. It is recommended to select a band that has high contrast, such as a NIR band.</p>
47             </div>
49             <div class="well well-sm">
50                 <div class="panel panel-default">
51                     <div class="panel-body">
52                         <table class="table table-bordered table-hover" id="manage_drone_imagery_standard_process_drone_run_bands_table">
53                             <thead>
54                                 <tr>
55                                     <th>Select</th>
56                                     <th>Drone Run Band Name</th>
57                                     <th>Drone Run Band Description</th>
58                                     <th>Drone Run Band Type</th>
59                                     <th>Drone Run Name</th>
60                                     <th>Drone Run Description</th>
61                                     <th>Drone Run Date</th>
62                                     <th>Field Trial Name</th>
63                                     <th>Field Trial Description</th>
64                                 </tr>
65                             </thead>
66                         </table>
68                         <br/>
70                         <center>
71                         <button class="btn btn-primary" id="manage_drone_imagery_standard_process_drone_run_band_step">Go to Next Step</button>
72                         </center>
73                     </div>
74                 </div>
75             </div>
77         </&>
78         <&| /util/workflow.mas:step, title=> "Rotate" &>
79             <& /page/page_title.mas, title=>"Rotate your selected drone run band" &>
81             <div class="well well-sm">
82                 <ul>
83                     <li>Here you can do a rotation of your drone run image.</li>
84                     <li>Your image should have precise row-to-row parallel alignment.</li>
85                 </ul>
86             </div>
88             <div class="well well-sm">
90                 <form class="form-horizontal">
91                     <div class="form-group form-group-sm">
92                         <label class="col-sm-6 control-label">Rotate Counter-Clockwise Degrees: </label>
93                         <div class="col-sm-6">
94                             <input class="form-control" id="drone_imagery_standard_process_rotate_degrees_input" name="drone_imagery_standard_process_rotate_degrees_input" type="text" placeholder="Number of degrees to rotate" value="0.00"/>
95                         </div>
96                     </div>
97                 </form>
99                 <button class="btn btn-primary" id="drone_imagery_standard_process_rotate_stitched_view">Rotate Image (Does Not Save)</button>
100                 <button class="btn btn-default" id="drone_imagery_standard_process_rotate_stitched_crosshairs">Draw Crosshairs Assist</button>
101                 <button class="btn btn-default" id="drone_imagery_standard_process_rotate_stitched_restart">Restart</button>
102                 <button class="btn btn-primary" id="manage_drone_imagery_standard_process_rotate_step">Save Rotated Image And Go To Next Step</button>
103             </div>
105             <div id="manage_drone_imagery_standard_process_rotate_load_div">
106                 <img src="/img/wheel.gif" />
107             </div>
109             <canvas id="drone_imagery_standard_process_rotate_original_stitched_div">
110             </canvas>
112         </&>
113         <&| /util/workflow.mas:step, title=> "Cropping" &>
114             <& /page/page_title.mas, title=>"Crop your drone run band to specific area" &>
116             <div class="well well-sm">
117                 <ul>
118                     <li>Here you can do a rough cropping of the stitched ortho image to focus only on the actual field experiment.</li>
119                     <li>Click on four points in the image to make a four-sided polygon.</li>
120                     <li>Only the last polygon that you draw will be used for the cropping.</li>
121                 </ul>
122                 <br/>
123                 <button class="btn btn-primary" id="manage_drone_imagery_standard_process_cropping_step">Save and Go to Next Step</button>
124             </div>
126             <div id="manage_drone_imagery_standard_process_crop_load_div">
127                 <img src="/img/wheel.gif" />
128             </div>
130             <canvas id="drone_imagery_standard_process_crop_original_stitched_div"></canvas>
132             <hr>
133             <div class="well well-sm">
134                 <form class="form-horizontal">
135                     <div class="row">
136                         <div class="col-sm-12">
137                             <div class="form-group form-group-sm">
138                                 <label class="col-sm-6 control-label">Previously Used Image Cropping For This Field Trial: </label>
139                                 <div class="col-sm-6">
140                                     <div id="plot_polygons_standard_process_previously_saved_image_cropping_templates">
141                                     </div>
142                                 </div>
143                             </div>
144                         </div>
145                     </div>
146                 </form>
147                 <button class="btn btn-primary" id="drone_imagery_standard_process_cropping_use_previous_cropping">Use Image Cropping</button>
148             </div>
150         </&>
151         <&| /util/workflow.mas:step, title=> "Thresholding" &>
152             <& /page/page_title.mas, title=>"Threshold your drone run band to remove background" &>
154             <div class="well">
155                 <&| /page/info_section.mas, title => 'Remove Background Using Percentage Threshold', collapsible=>1, collapsed => 0, subtitle=> 'Remove the background by specifying percentage threshold value' &>
156                     <div class="panel panel-default">
157                         <div class="panel-body">
158                             <div class="row">
159                                 <div class="col-sm-6">
160                                     <div class="form-group form-group-sm">
161                                         <label class="col-sm-6 control-label">Discard Lowest Percent of Pixel Values: </label>
162                                         <div class="col-sm-6">
163                                             <input class="form-control" id="drone_imagery_standard_process_remove_background_lower_threshold_percentage" name="drone_imagery_standard_process_remove_background_lower_threshold_percentage" type="number" max="99" min="0" placeholder="e.g. 10% of lowest pixel values (Min 0, Max 100)" value=25 disabled/>
164                                         </div>
165                                     </div>
166                                 </div>
167                                 <div class="col-sm-6">
168                                     <div class="form-group form-group-sm">
169                                         <label class="col-sm-6 control-label">Discard Highest Percent of Pixel Values: </label>
170                                         <div class="col-sm-6">
171                                             <input class="form-control" id="drone_imagery_standard_process_remove_background_upper_threshold_percentage" name="drone_imagery_standard_process_remove_background_upper_threshold_percentage" type="number" max="99" min="0" placeholder="e.g. 10% of highest pixel values (Min 0, Max 100)" value=25 disabled/>
172                                         </div>
173                                     </div>
174                                 </div>
175                             </div>
176                         </div>
177                     </div>
178                 </&>
179             </div>
181             <center>
182                 <button id="drone_imagery_standard_process_remove_background_defined_percentage_submit" class="btn btn-primary">Apply Threshold</button>
183             </center>
185             <hr>
187             <div id="manage_drone_imagery_standard_process_remove_background_load_div">
188                 <img src="/img/wheel.gif" />
189             </div>
191             <div class="well well-sm">
192                 <&| /page/info_section.mas, title => 'Histogram of pixel values', collapsible=>1, collapsed => 0, subtitle=> 'Histogram of Pixel Values' &>
193                     <center>
194                         <canvas id="drone_imagery_standard_process_remove_background_histogram_div"></canvas>
195                     </center>
196                 </&>
197             </div>
199             <div class="well well-sm">
200                 <&| /page/info_section.mas, title => 'Denoised Original Image', collapsible=>1, collapsed => 0, subtitle=> 'Denoised Original Image' &>
201                     <center>
202                         <canvas id="drone_imagery_standard_process_remove_background_original"></canvas>
203                     </center>
204                 </&>
205             </div>
207         </&>
208         <&| /util/workflow.mas:step, title=> "Plot Polygons" &>
209             <& /page/page_title.mas, title=>"Define plot polygons relative to the field layout" &>
211             <& /page/detail_page_2_col_section.mas, info_section_collapsible=>1, info_section_collapsed=>0, info_section_title => "<h4 style='display:inline'>Generate Polygon Template Tool</h4>", info_section_subtitle => 'Overlay a uniform grid over the image.', icon_class => "glyphicon glyphicon-th-large", info_section_id => "manage_drone_imagery_standard_process_generate_plot_polygons_section" &>
213             <div class="well well-sm">
214                 <div id="drone_imagery_standard_process_plot_polygons_top_section"></div>
216                 <button id="drone_imagery_standard_process_plot_polygons_clear" class="btn btn-danger">Clear All Polygons</button>
217                 <button id="drone_imagery_standard_process_plot_polygons_clear_one" class="btn btn-danger">Clear One Polygon</button>
218                 <button id="drone_imagery_standard_process_plot_polygons_get_distance" class="btn btn-default">Find Distance Between Points</button>
219             </div>
221             <div id="manage_drone_imagery_standard_process_plot_polygons_load_div">
222                 <img src="/img/wheel.gif" />
223             </div>
225             <canvas id="drone_imagery_standard_process_plot_polygons_original_stitched_div"></canvas>
227             <div id="drone_imagery_standard_process_generated_polygons_div"></div>
229             <hr>
230             <div class="well well-sm">
231                 <div id="drone_imagery_standard_process_trial_layout_div"></div>
232             </div>
234         </&>
235         <&| /util/workflow.mas:step, title=> "Apply" &>
236             <& /page/page_title.mas, title=>"Apply these same steps to other drone run bands in the current drone run" &>
238             <div class="well well-sm">
239                 <ul>
240                     <li>Here you can apply the same actions you did for the previous steps 1 to 6, to additional drone run bands in this drone run.</li>
241                     <li>Thresholding will be done dynamically, by removing the top and bottom 20% of pixel values.</li>
242                 </ul>
243             </div>
245             <div class="well well-sm">
246                 <div class="panel panel-default">
247                     <div class="panel-body">
248                         <table class="table table-bordered table-hover" id="manage_drone_imagery_standard_process_drone_run_bands_apply_table">
249                             <thead>
250                                 <tr>
251                                     <th>Select</th>
252                                     <th>Drone Run Band Name</th>
253                                     <th>Drone Run Band Description</th>
254                                     <th>Drone Run Band Type</th>
255                                     <th>Drone Run Name</th>
256                                     <th>Drone Run Description</th>
257                                     <th>Drone Run Date</th>
258                                     <th>Field Trial Name</th>
259                                     <th>Field Trial Description</th>
260                                 </tr>
261                             </thead>
262                         </table>
264                         <br/>
266                         <center>
267                         <button class="btn btn-primary" id="manage_drone_imagery_standard_process_drone_run_band_apply_step">Go to Next Step</button>
268                         </center>
269                     </div>
270                 </div>
271             </div>
272         </&>
273         <&| /util/workflow.mas:step, title=> "Indices" &>
274             <& /page/page_title.mas, title=>"Create and apply these same steps to vegetative indices" &>
276             <form class="form-horizontal">
277                 <div class="form-group form-group-sm">
278                     <label class="col-sm-6 control-label">Vegetative Indices To Apply: </label>
279                     <div class="col-sm-6">
280                         <input name="drone_imagery_standard_process_apply_indices_select" value="TGI" type="checkbox" checked> Triangular Greenness Index (TGI) <br/>
281                         <input name="drone_imagery_standard_process_apply_indices_select" value="VARI" type="checkbox" checked> Visible Atmospheric Resistant Index (VARI) <br/>
282                         <input name="drone_imagery_standard_process_apply_indices_select" value="NDVI" type="checkbox" checked> Normalized Difference Vegetative Index (NDVI) <br/>
283                         <input name="drone_imagery_standard_process_apply_indices_select" value="NDRE" type="checkbox" checked> Normalized Difference Red Edge Vegetative Index (NDRE) <br/>
284                     </div>
285                 </div>
286             </form>
288             <br/>
290             <center>
291             <button type="button" class="btn btn-primary" id="manage_drone_imagery_standard_process_indices_step">Go to Next Step</button>
292             </center>
293         </&>
294         <&| /util/workflow.mas:step, title=> "Phenotypes" &>
295             <& /page/page_title.mas, title=>"Calculate phenotypes for all plot polygon images" &>
297             <form class="form-horizontal">
298                 <div class="form-group form-group-sm">
299                     <label class="col-sm-6 control-label">Zonal Statistics to Calculate and Save in Database: </label>
300                     <div class="col-sm-6">
301                         <input name="drone_imagery_standard_process_phenotypes_select" value="zonal" type="checkbox" checked disabled> Zonal Statistics: nonzero_pixel_count, total_pixel_sum, mean_pixel_value, harmonic_mean_value, median_pixel_value, variance_pixel_value, stdev_pixel_value, pstdev_pixel_value, min_pixel_value, max_pixel_value, minority_pixel_value, minority_pixel_count, majority_pixel_value, majority_pixel_count, pixel_variety_count <br/>
302                     </div>
303                 </div>
304             </form>
305             <br/>
307             <div id="drone_imagery_standard_process_week_term_div"></div>
309             <center>
310             <button type="button" class="btn btn-info" id="manage_drone_imagery_standard_process_phenotypes_step">Finish</button>
311             </center>
312         </&>
313     </&>
315 </div>
317 <div id="manage_drone_imagery_standard_process_raw_images_div" style="display:none">
319     <& /page/page_title.mas, title=>"Manage Drone Imagery: Run A Standard Process On Raw Images" &>
321     <&| /util/workflow.mas, id=> "manage_drone_imagery_standard_process_raw_images_workflow" &>
322         <&| /util/workflow.mas:step, title=> "Intro" &>
323             <& /page/page_title.mas, title=>"This workflow will guide you through applying a standard process to your aerial imaging bands" &>
325             <div class="well well-sm">
326                 <p>This process will allow you to manually assign plot-polygons to the raw images.</p>
327             </div>
329             <br/><br/>
330             <center>
331             <button class="btn btn-primary" onclick="Workflow.complete(this); return false;">Go to Next Step</button>
332             </center>
333         </&>
334         <&| /util/workflow.mas:step, title=> "Plot Polygons" &>
335             <& /page/page_title.mas, title=>"Manually assign plot-polygons to raw images" &>
337             <div class="well well-sm">
338                 <ul>
339                     <li>(1) Select an image from the grid below and adjust the rotation.</li>
340                     <li>(2) Click the four corners encompassing a group of plots of interest. Alternatively, paste a previously used template.</li>
341                     <li>(3) Type the plot numbers corresponding to the drawn plot-polygons in the drawn table.</li>
342                     <li>(4) Click assign plot-polygons to save. Repeat steps 1 to 4 until all plots have been assigned an image.</li>
343                 </ul>
344             </div>
346             <div class="form-horizontal">
347                 <div class="form-group form-group-sm">
348                     <label class="col-sm-2 control-label">Click Raw Image Stack: </label>
349                     <div class="col-sm-10">
350                         <div id="drone_imagery_standard_process_raw_images_image_id_select_div"></div>
351                     </div>
352                 </div>
353             </div>
354             <hr>
356             <canvas id="drone_imagery_standard_process_raw_images_show"></canvas>
358             <hr>
359             <form class="form-horizontal">
360                 <div class="form-group form-group-sm">
361                     <label class="col-sm-6 control-label">Rotate Counter-Clockwise Degrees: </label>
362                     <div class="col-sm-6">
363                         <input class="form-control" id="drone_imagery_standard_process_raw_images_rotate_degrees_input" name="drone_imagery_standard_process_raw_images_rotate_degrees_input" type="text" placeholder="Number of degrees to rotate" value="0.00"/>
364                     </div>
365                 </div>
366             </form>
367             <button class="btn btn-primary btn-sm" id="drone_imagery_standard_process_raw_images_rotate_image" onclick="return false;">Rotate Image</button>
368             <hr>
370             <hr>
371             <button class="btn btn-primary btn-sm" id="drone_imagery_standard_process_raw_images_save_polygon" onclick="return false;">Save Plot-Polygon</button>
372             <button class="btn btn-primary btn-sm" id="drone_imagery_standard_process_raw_images_paste_polygon" onclick="return false;">Paste Plot-Polygon</button>
373             <button class="btn btn-danger btn-sm" id="drone_imagery_standard_process_raw_images_clear_polygon" onclick="return false;">Start Over</button>
374             <hr>
376             <hr>
377             <form class="form-horizontal">
378                 <div class="form-group form-group-sm">
379                     <label class="col-sm-6 control-label">Previously used plot-polygons: </label>
380                     <div class="col-sm-6">
381                         <div id="drone_imagery_standard_process_raw_images_previous_polygons_div"></div>
382                     </div>
383                 </div>
384             </form>
385             <button class="btn btn-primary btn-sm" id="drone_imagery_standard_process_raw_images_paste_previous_polygon" onclick="return false;">Paste Previously Used Plot-Polygon</button>
386             <hr>
388             <div class="form-horizontal">
389                 <div class="form-group form-group-sm">
390                     <label class="col-sm-3 control-label">Number of Rows: </label>
391                     <div class="col-sm-9">
392                         <input type="number" class="form-control" id="drone_imagery_standard_process_raw_images_number_rows" name="drone_imagery_standard_process_raw_images_number_rows" placeholder="0"/>
393                     </div>
394                 </div>
395                 <div class="form-group form-group-sm">
396                     <label class="col-sm-3 control-label">Number of Columns: </label>
397                     <div class="col-sm-9">
398                         <input type="number" class="form-control" id="drone_imagery_standard_process_raw_images_number_columns" name="drone_imagery_standard_process_raw_images_number_columns" placeholder="0"/>
399                     </div>
400                 </div>
401                 <div class="form-group form-group-sm">
402                     <label class="col-sm-3 control-label">Template Name: </label>
403                     <div class="col-sm-9">
404                         <input type="text" class="form-control" id="drone_imagery_standard_process_raw_images_partial_template_name" name="drone_imagery_standard_process_raw_images_partial_template_name" placeholder="e.g. 3rd Range 2x4"/>
405                     </div>
406                 </div>
407             </div>
408             <button class="btn btn-primary btn-sm" id="drone_imagery_standard_process_raw_images_draw_polygons" onclick="return false;">Draw Plot-Polygon (Does Not Save)</button>
409             <hr>
411             <div id="drone_imagery_standard_process_raw_images_polygon_assign_table" name="drone_imagery_standard_process_raw_images_polygon_assign_table"></div>
413             <br/><br/>
414             <center>
415             <button class="btn btn-primary" id="drone_imagery_standard_process_raw_images_assign_plot" onclick="return false;">Assign Plot Images (Saves)</button>
416             </center>
418             <hr>
419             <div id="drone_imagery_standard_process_raw_images_assigned_plot_images" name="drone_imagery_standard_process_raw_images_assigned_plot_images"></div>
420         </&>
421     </&>
423 </div>
425 <div id="manage_drone_imagery_rotate_div" style="display:none">
427     <& /page/page_title.mas, title=>"Manage Drone Imagery: Rotate Stitched Image" &>
429     <div class="well well-sm">
430         <ul>
431             <li>Here you can rotate the stitched image so that the rows and columns align exactly vertically and horizontally.</li>
432             <li>The rotation can be done on decimals of degrees.</li>
433             <li>Negative values mean clock-wise and positive values mean counter-clockwise.</li>
434             <li>Crosshairs are only for assisting in alignment and they will not be saved.</li>
435         </ul>
436     </div>
437     <div class="well well-sm">
439         <form class="form-horizontal">
440             <div class="form-group form-group-sm">
441                 <label class="col-sm-6 control-label">Rotate Counter-Clockwise Degrees: </label>
442                 <div class="col-sm-6">
443                     <input class="form-control" id="drone_imagery_rotate_degrees_input" name="drone_imagery_rotate_degrees_input" type="text" placeholder="Number of degrees to rotate" value="0.00"/>
444                 </div>
445             </div>
446         </form>
448         <button class="btn btn-primary" id="drone_imagery_rotate_stitched_view">Rotate Image (Does Not Save)</button>
449         <button class="btn btn-default" id="drone_imagery_rotate_stitched_crosshairs">Draw Crosshairs Assist</button>
450         <button class="btn btn-default" id="drone_imagery_rotate_stitched_restart">Restart</button>
451         <button class="btn btn-primary" id="drone_imagery_rotate_stitched_submit">Save Rotated Image</button>
452     </div>
454     <div id="manage_drone_imagery_rotate_load_div">
455         <img src="/img/wheel.gif" />
456     </div>
458     <canvas id="drone_imagery_rotate_original_stitched_div">
459     </canvas>
460 </div>
462 <div id="manage_drone_imagery_crop_div" style="display:none">
464     <& /page/page_title.mas, title=>"Manage Drone Imagery: Crop Stitched Image To Field Experiment" &>
466     <div class="well well-sm">
467         <ul>
468             <li>Here you can do a rough cropping of the stitched ortho image to focus only on the actual field experiment.</li>
469             <li>Click on four points in the image to make a four-sided polygon.</li>
470             <li>Only the last polygon that you draw will be used for the cropping.</li>
471         </ul>
472         <br/>
473         <button class="btn btn-primary" id="drone_imagery_crop_stitched_submit">Crop Image To Selected Polygon</button>
474     </div>
476     <div class="well well-sm">
477         <form class="form-horizontal">
478             <div class="row">
479                 <div class="col-sm-12">
480                     <div class="form-group form-group-sm">
481                         <label class="col-sm-6 control-label">Previously Used Image Cropping For This Field Trial: </label>
482                         <div class="col-sm-6">
483                             <div id="plot_polygons_previously_saved_image_cropping_templates">
484                             </div>
485                         </div>
486                     </div>
487                 </div>
488             </div>
489         </form>
490         <button class="btn btn-primary" id="drone_imagery_cropping_use_previous_cropping">Use Image Cropping</button>
491     </div>
493     <div id="manage_drone_imagery_crop_load_div">
494         <img src="/img/wheel.gif" />
495     </div>
497     <canvas id="drone_imagery_crop_original_stitched_div"></canvas>
498 </div>
500 <div id="manage_drone_imagery_vegetative_index_div" style="display:none">
502     <& /page/page_title.mas, title=>"Manage Drone Imagery: Convert to Vegetative Index" &>
504     <div class="well well-sm">
505         <ul>
506             <li>Here you can convert to a vegetative index.</li>
507             <li>If you have a NIR band, you can calculate "Normalized difference vegetative index", NDVI.</li>
508             <li>If you have an RGB image, you can calculate "Visible atmospheric resistant index", VARI, or "Triangular greenness index", TGI.</li>
509             <li>If you have red or blue or green, or images from any spectral band, you can calculate ratios to use as your vegetative index.</li>
510         </ul>
511     </div>
513     <hr>
514     <div id="manage_drone_imagery_vegetative_index_tgi_bgr_div" style="display:none">
515         <button class="btn btn-primary" id="drone_imagery_vegetative_index_TGI_bgr">Calculate "Triangular Greenness Index" TGI. TGI = {Green band2} - 0.39*{Red band3} - 0.61*{Blue band1}</button>
516         <hr>
517     </div>
518     <div id="manage_drone_imagery_vegetative_index_vari_bgr_div" style="display:none">
519         <button class="btn btn-primary" id="drone_imagery_vegetative_index_VARI_bgr">Calculate "Visible Atmospheric Resistant Index" VARI. VARI = ({Green band2} - {Red band3}) / ({Green band2} + {Red band3} - {Blue band1})</button>
520         <hr>
521     </div>
522     <div id="manage_drone_imagery_vegetative_index_tgi_rgb_div" style="display:none">
523         <button class="btn btn-primary" id="drone_imagery_vegetative_index_TGI_rgb">Calculate "Triangular Greenness Index" TGI. TGI = {Green band2} - 0.39*{Red band1} - 0.61*{Blue band3}</button>
524         <hr>
525     </div>
526     <div id="manage_drone_imagery_vegetative_index_vari_rgb_div" style="display:none">
527         <button class="btn btn-primary" id="drone_imagery_vegetative_index_VARI_rgb">Calculate "Visible Atmospheric Resistant Index" VARI. VARI = ({Green band2} - {Red band1}) / ({Green band2} + {Red band1} - {Blue band3})</button>
528         <hr>
529     </div>
530     <div id="manage_drone_imagery_vegetative_index_ndvi_div" style="display:none">
531         <button class="btn btn-primary" id="drone_imagery_vegetative_index_NDVI">Calculate "Normalized Difference Vegetative Index" NDVI. NDVI = ({NIR band1} - {Red band2}) / ({NIR band1} + {Red band2})</button>
532         <hr>
533     </div>
534     <div id="manage_drone_imagery_vegetative_index_ndre_div" style="display:none">
535         <button class="btn btn-primary" id="drone_imagery_vegetative_index_NDRE">Calculate "Normalized Difference Red Edge" NDRE. NDRE = ({NIR band1} - {Red Edge band2}) / ({NIR band1} + {Red Edge band2})</button>
536         <hr>
537     </div>
539     <button class="btn btn-success" id="drone_imagery_rgb_vegetative_index_submit">Finish and Save Vegetative Index</button>
540     <hr>
542     <canvas id="drone_imagery_vegetative_index_original_stitched_div"></canvas>
543 </div>
545 <div id="manage_drone_imagery_remove_background_div" style="display:none">
547     <& /page/page_title.mas, title=>"Manage Drone Imagery: Remove Background" &>
549     <div class="well">
550         <&| /page/info_section.mas, title => 'Remove Background Using Graphical Threshold', collapsible=>1, collapsed => 1, subtitle=> 'Remove the background using a simple threshold value' &>
552             <div class="panel panel-default">
553                 <div class="panel-body">
554                     <div class="well well-sm">
555                         <h5>The background can be removed by placing a threshold on pixel values</h5>
556                         <ul>
557                             <li><b>1.</b> Click on the two right-most, highest peaks in the histogram. The right most peak represents the pixels we are interested in, while the peak immediately to the left of that peak represents the soil background.</li>
558                             <li><b>2.</b> Click on the "Find Minimum" button.</li>
559                             <li><b>3.</b> If the image looks good with the applied threshold, click Save. Otherwise, you can start over.</li>
560                         </ul>
561                     </div>
563                     <div class="well well-sm">
564                         <div name="drone_imagery_remove_background_threshold_current"></div>
565                         <div name="drone_imagery_remove_background_threshold"></div>
566                     </div>
568                     <canvas id="drone_imagery_remove_background_histogram_div"></canvas>
569                     <hr>
570                     <button class="btn btn-primary" id="drone_imagery_remove_background_find_minimum">Find Minimum (Does Not Save)</button>
571                     <button class="btn btn-default" id="drone_imagery_remove_background_start_over">Start Over</button>
572                     <button class="btn btn-primary" id="drone_imagery_remove_background_submit">Save</button>
573                     <hr>
574                 </div>
575             </div>
576         </&>
577     </div>
578     <div class="well">
579         <&| /page/info_section.mas, title => 'Remove Background Using User Defined Threshold', collapsible=>1, collapsed => 1, subtitle=> 'Remove the background using a simple threshold value' &>
580             <div class="panel panel-default">
581                 <div class="panel-body">
582                     <div class="row">
583                         <div class="col-sm-6">
584                             <div class="form-group form-group-sm">
585                                 <label class="col-sm-6 control-label">Discard Pixels with Value Lower Than: </label>
586                                 <div class="col-sm-6">
587                                     <input class="form-control" id="drone_imagery_remove_background_lower_threshold" name="drone_imagery_remove_background_lower_threshold" type="number" max="255" min="0" placeholder="e.g. 10 (Min 0)" />
588                                 </div>
589                             </div>
590                         </div>
591                         <div class="col-sm-6">
592                             <div class="form-group form-group-sm">
593                                 <label class="col-sm-6 control-label">Discard Pixels with Value Higher Than: </label>
594                                 <div class="col-sm-6">
595                                     <input class="form-control" id="drone_imagery_remove_background_upper_threshold" name="drone_imagery_remove_background_upper_threshold" type="number" max="255" min="0" placeholder="e.g. 200 (Max 255)"/>
596                                 </div>
597                             </div>
598                         </div>
599                     </div>
600                     <button id="drone_imagery_remove_background_defined_submit" class="btn btn-primary">Apply Threshold</button>
601                 </div>
602             </div>
603         </&>
604     </div>
605     <div class="well">
606         <&| /page/info_section.mas, title => 'Remove Background Using Percentage Threshold', collapsible=>1, collapsed => 1, subtitle=> 'Remove the background by specifying percentage threshold value' &>
607             <div class="panel panel-default">
608                 <div class="panel-body">
609                     <div class="row">
610                         <div class="col-sm-6">
611                             <div class="form-group form-group-sm">
612                                 <label class="col-sm-6 control-label">Discard Lowest Percent of Pixel Values: </label>
613                                 <div class="col-sm-6">
614                                     <input class="form-control" id="drone_imagery_remove_background_lower_threshold_percentage" name="drone_imagery_remove_background_lower_threshold_percentage" type="number" max="99" min="0" placeholder="e.g. 10% of lowest pixel values (Min 0, Max 100)" />
615                                 </div>
616                             </div>
617                         </div>
618                         <div class="col-sm-6">
619                             <div class="form-group form-group-sm">
620                                 <label class="col-sm-6 control-label">Discard Highest Percent of Pixel Values: </label>
621                                 <div class="col-sm-6">
622                                     <input class="form-control" id="drone_imagery_remove_background_upper_threshold_percentage" name="drone_imagery_remove_background_upper_threshold_percentage" type="number" max="99" min="0" placeholder="e.g. 10% of highest pixel values (Min 0, Max 100)"/>
623                                 </div>
624                             </div>
625                         </div>
626                     </div>
627                     <button id="drone_imagery_remove_background_defined_percentage_submit" class="btn btn-primary">Apply Threshold</button>
628                 </div>
629             </div>
630         </&>
631     </div>
633     <hr>
635     <div id="manage_drone_imagery_remove_background_load_div">
636         <img src="/img/wheel.gif" />
637     </div>
639     <canvas id="drone_imagery_remove_background_original"></canvas>
640 </div>
642 <div id="manage_drone_imagery_plot_polygons_div" style="display:none">
644     <& /page/page_title.mas, title=>"Manage Drone Imagery: Define Plot Polygons" &>
646     <& /page/detail_page_2_col_section.mas, info_section_collapsible=>1, info_section_collapsed=>0, info_section_title => "<h4 style='display:inline'>Generate Polygon Template Tool</h4>", info_section_subtitle => 'Overlay a uniform grid over the image.', icon_class => "glyphicon glyphicon-th-large", info_section_id => "manage_drone_imagery_generate_plot_polygons_section" &>
648     <div class="well well-sm">
649         <div id="drone_imagery_plot_polygons_top_section"></div>
651         <button id="drone_imagery_plot_polygons_clear" class="btn btn-danger">Clear All Polygons</button>
652         <button id="drone_imagery_plot_polygons_clear_one" class="btn btn-danger">Remove One Polygon</button>
653         <button id="drone_imagery_plot_polygons_get_distance" class="btn btn-default">Find Distance Between Points</button>
654     </div>
656     <div id="manage_drone_imagery_plot_polygons_load_div">
657         <img src="/img/wheel.gif" />
658     </div>
660     <canvas id="drone_imagery_plot_polygons_original_stitched_div"></canvas>
662     <div id="drone_imagery_generated_polygons_div"></div>
664     <hr>
665     <div class="well well-sm">
666         <div id="drone_imagery_trial_layout_div"></div>
667     </div>
668 </div>
670 <div id="manage_drone_imagery_calculate_phenotypes_div" style="display:none">
672     <& /page/page_title.mas, title=>"Manage Drone Imagery: Calculate Phenotypes" &>
674     <div class="well well-sm">
675         <ul>
676             <li>Here you can calculate phenotypes for all plot polygons at once.</li>
677         </ul>
678     </div>
680     <hr>
681     <button class="btn btn-primary" id="drone_imagery_calculate_phenotypes_zonal_stats">Zonal Statistics</button>
682     <button class="btn btn-primary" id="drone_imagery_calculate_phenotypes_sift">Calculate SIFT Features</button>
683     <button class="btn btn-primary" id="drone_imagery_calculate_phenotypes_surf">Calculate SURF Features</button>
684     <button class="btn btn-primary" id="drone_imagery_calculate_phenotypes_orb">Calculate ORB Features</button>
685     <hr>
687     <div id="manage_drone_imagery_calculate_phenotypes_show_zonal_stats" style="overflow:scroll"></div>
688     <div id="manage_drone_imagery_calculate_phenotypes_show_fourier_transform" style="overflow:scroll"></div>
689     <div id="manage_drone_imagery_calculate_phenotypes_show_sift"></div>
690     <div id="manage_drone_imagery_calculate_phenotypes_show_surf"></div>
691     <div id="manage_drone_imagery_calculate_phenotypes_show_orb"></div>
693 </div>
695 <div id="manage_drone_imagery_loading_div" style="display:none">
696     <& /page/page_title.mas, title=>"Loading..." &>
697     <div class="well well-sm">
698         <center>
699         <h3>Please wait...</h3>
700         <hr>
701         <img src="/img/wheel.gif" />
702         </center>
703     </div>
704 </div>
706 <div class="modal fade" id="drone_imagery_assign_plot_dialog" name="drone_imagery_assign_plot_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryAssignPlotDialog" data-backdrop="static">
707   <div class="modal-dialog modal-sm" role="document">
708     <div class="modal-content">
709       <div class="modal-header">
710         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
711         <h4 class="modal-title" id="droneImageryAssignPlotDialog">Assign Plot</h4>
712       </div>
713       <div class="modal-body">
714         <div class="container-fluid">
715             <form class="form-horizontal" id="drone_imagery_assign_plot_form">
716                 <div class="form-group">
717                     <label class="col-sm-5 control-label">Plot Name:</label>
718                     <div class="col-sm-7">
719                         <input class="form-control" id="drone_imagery_plot_polygon_assign_plot_name" name="drone_imagery_plot_polygons_autocomplete" type="text" placeholder="Auto-completes plot name..." />
720                     </div>
721                 </div>
722             </form>
723         </div>
724       </div>
725       <div class="modal-footer">
726         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
727         <button type="button" class="btn btn-primary" id="drone_imagery_plot_polygon_assign_add">Assign Plot</button>
728       </div>
729     </div>
730   </div>
731 </div>
733 <div class="modal fade" id="drone_imagery_plot_polygon_remove_polygon" name="drone_imagery_plot_polygon_remove_polygon" tabindex="-1" role="dialog" aria-labelledby="droneImageryRemovePlotPolygonDialog" data-backdrop="static">
734   <div class="modal-dialog modal-sm" role="document">
735     <div class="modal-content">
736       <div class="modal-header">
737         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
738         <h4 class="modal-title" id="droneImageryRemovePlotPolygonDialog">Remove Plot Polygon</h4>
739       </div>
740       <div class="modal-body">
741         <div class="container-fluid">
742             <form class="form-horizontal">
743                 <div class="form-group">
744                     <label class="col-sm-5 control-label">Polygon Identifier:</label>
745                     <div class="col-sm-7">
746                         <input class="form-control" id="drone_imagery_plot_polygon_remove_polygon_number" name="drone_imagery_plot_polygon_remove_polygon_number" type="number" placeholder="e.g. 3" />
747                     </div>
748                 </div>
749             </form>
750         </div>
751       </div>
752       <div class="modal-footer">
753         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
754         <button type="button" class="btn btn-primary" id="drone_imagery_plot_polygon_remove_polygon_submit">Remove Plot Polygon</button>
755       </div>
756     </div>
757   </div>
758 </div>
760 <div class="modal fade" id="drone_imagery_merge_channels_dialog" name="drone_imagery_merge_channels_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryMergeChannelsDialog" data-backdrop="static">
761   <div class="modal-dialog modal-xl" role="document">
762     <div class="modal-content">
763       <div class="modal-header">
764         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
765         <h4 class="modal-title" id="droneImageryMergeChannelsDialog">Merge Drone Run Bands Into Single 3-channel image</h4>
766       </div>
767       <div class="modal-body">
768         <div class="container-fluid">
769             <form class="form-horizontal" id="drone_imagery_merge_bands_form">
770                 <div class="form-group">
771                     <label class="col-sm-5 control-label">First Band:</label>
772                     <div class="col-sm-7">
773                         <div id="drone_imagery_merge_bands_band1_select"></div>
774                     </div>
775                 </div>
776                 <div class="form-group">
777                     <label class="col-sm-5 control-label">Second Band:</label>
778                     <div class="col-sm-7">
779                         <div id="drone_imagery_merge_bands_band2_select"></div>
780                     </div>
781                 </div>
782                 <div class="form-group">
783                     <label class="col-sm-5 control-label">Third Band:</label>
784                     <div class="col-sm-7">
785                         <div id="drone_imagery_merge_bands_band3_select"></div>
786                     </div>
787                 </div>
788                 <div class="form-group">
789                     <label class="col-sm-5 control-label">Merge Image Type:</label>
790                     <div class="col-sm-7">
791                         <select class="form-control" id="drone_run_merge_image_type" name="drone_run_merge_image_type">
792                             <option value="">Select One</option>
793                             <option value="BGR">BGR (Band 1 = Blue, Band 2 = Green, Band 3 = Red)</option>
794                             <option value="NRN">NRN (Band 1 = NIR, Band 2 = Red, Band 3 = NIR)</option>
795                             <option value="NReN">NReN (Band 1 = NIR, Band 2 = Red Edge, Band 3 = NIR)</option>
796                         </select>
797                     </div>
798                 </div>
799             </form>
800         </div>
802         <ul>
803             <li>TGI = {GREEN band2} - 0.39*{RED band3} - 0.61*{BLUE band1}</li>
804             <li>VARI = ( {GREEN band2} - {RED band3} ) / ( {GREEN band2} + {RED band3} - {BLUE band1} )</li>
805             <li>NDVI = ( {NIR band1} - {RED band 2} ) / ( {NIR band1} + {RED band2} )</li>
806             <li>NDRE = ( {NIR band1} - {RED EDGE band 2} ) / ( {NIR band1} + {RED EDGE band2} )</li>
807         </ul>
809       </div>
810       <div class="modal-footer">
811         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
812         <button type="button" class="btn btn-primary" id="drone_imagery_merge_bands_submit">Merge Bands</button>
813       </div>
814     </div>
815   </div>
816 </div>
818 <div class="modal fade" id="drone_imagery_calc_phenotypes_zonal_channel_dialog" name="drone_imagery_calc_phenotypes_zonal_channel_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryCalcPhenotypesZonalChannelDialog" data-backdrop="static">
819   <div class="modal-dialog modal-xl" role="document">
820     <div class="modal-content">
821       <div class="modal-header">
822         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
823         <h4 class="modal-title" id="droneImageryCalcPhenotypesZonalChannelDialog">Select the Channel to Calculate Zonal Statistics On</h4>
824       </div>
825       <div class="modal-body">
826           <div class="container-fluid">
827               <div id="drone_imagery_calculate_phenotypes_zonal_stats_week_term_div"></div>
828           </div>
830       </div>
831       <div class="modal-footer">
832         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
833         <button type="button" class="btn btn-primary" id="drone_imagery_calculate_phenotypes_zonal_stats_channel_select">Calculate Zonal Statistics</button>
834       </div>
835     </div>
836   </div>
837 </div>
839 <div class="modal fade" id="drone_imagery_delete_drone_run_dialog" name="drone_imagery_delete_drone_run_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryDeleteDroneRunDialog" data-backdrop="static">
840   <div class="modal-dialog modal-xl" role="document">
841     <div class="modal-content">
842       <div class="modal-header">
843         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
844         <h4 class="modal-title" id="droneImageryDeleteDroneRunDialog">Delete a Drone Run</h4>
845       </div>
846       <div class="modal-body">
847         <div class="container-fluid">
848             <div class="well">
849                 <ul>
850                     <li>Deleting a drone run will remove the drone run and all drone run bands permanently.</li>
851                     <li>All images in the drone run will be deleted (obsoleted).</li>
852                     <li>Phenotypes that were generated for plots in this drone run will be deleted permanently.</li>
853                 </ul>
854             </div>
855         </div>
856       </div>
857       <div class="modal-footer">
858         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
859         <button type="button" class="btn btn-primary" id="drone_imagery_delete_drone_run_confirm">Delete Drone Run</button>
860       </div>
861     </div>
862   </div>
863 </div>
865 <div class="modal fade" id="drone_imagery_calc_phenotypes_trial_dialog" name="drone_imagery_calc_phenotypes_trial_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryCalcPhenotypesZonalChannelTrialDialog" data-backdrop="static">
866   <div class="modal-dialog modal-xl" role="document">
867     <div class="modal-content">
868       <div class="modal-header">
869         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
870         <h4 class="modal-title" id="droneImageryCalcPhenotypesZonalChannelTrialDialog">Calculate Zonal Statistics</h4>
871       </div>
872       <div class="modal-body">
873         <div class="container-fluid">
874             <div id="drone_imagery_week_term_div"></div>
875         </div>
877         <div class="form-group">
878             <label class="col-sm-5 control-label">Phenotype Process:</label>
879             <div class="col-sm-7">
880                 <select class="form-control" id="drone_imagery_generate_phenotypes_process_type" name="drone_imagery_generate_phenotypes_process_type">
881                     <option value="minimal,minimal_vi">Minimal</option>
882                     <option value="extended">Extended</option>
883                 </select>
884             </div>
885         </div>
887       </div>
888       <div class="modal-footer">
889         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
890         <button type="button" class="btn btn-primary" id="drone_imagery_calculate_phenotypes_zonal_stats_trial_select">Calculate Zonal Statistics</button>
891       </div>
892     </div>
893   </div>
894 </div>
896 <div class="modal fade" id="drone_imagery_minimal_vi_standard_process_dialog" name="drone_imagery_minimal_vi_standard_process_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryMinimalVIStandardProcessDialog" data-backdrop="static">
897   <div class="modal-dialog modal-xl" role="document">
898     <div class="modal-content">
899       <div class="modal-header">
900         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
901         <h4 class="modal-title" id="droneImageryMinimalVIStandardProcessDialog">Run Minimal Vegetative Index Standard Process</h4>
902       </div>
903       <div class="modal-body">
904         <div class="container-fluid">
905             <div id="drone_imagery_minimal_vi_standard_process_week_term_div"></div>
906         </div>
908       </div>
909       <div class="modal-footer">
910         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
911         <button type="button" class="btn btn-primary" id="drone_imagery_minimal_vi_standard_process_select">Run Minimal Vegetative Index Standard Process</button>
912       </div>
913     </div>
914   </div>
915 </div>
917 <div class="modal fade" id="drone_imagery_extended_standard_process_dialog" name="drone_imagery_extended_standard_process_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryExtenededStandardProcessDialog" data-backdrop="static">
918   <div class="modal-dialog modal-xl" role="document">
919     <div class="modal-content">
920       <div class="modal-header">
921         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
922         <h4 class="modal-title" id="droneImageryExtenededStandardProcessDialog">Run Extended Standard Process</h4>
923       </div>
924       <div class="modal-body">
925         <div class="container-fluid">
926             <div id="drone_imagery_extended_standard_process_week_term_div"></div>
927         </div>
929       </div>
930       <div class="modal-footer">
931         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
932         <button type="button" class="btn btn-primary" id="drone_imagery_extended_standard_process_select">Run Extended Standard Process</button>
933       </div>
934     </div>
935   </div>
936 </div>
938 <div class="modal fade" id="drone_imagery_download_phenotypes_dialog" name="drone_imagery_download_phenotypes_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryDownloadPhenotypesDialog" data-backdrop="static">
939   <div class="modal-dialog modal-xl" role="document">
940     <div class="modal-content">
941       <div class="modal-header">
942         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
943         <h4 class="modal-title" id="droneImageryDownloadPhenotypesDialog">Download drone image phenotypes and plot images</h4>
944       </div>
945       <div class="modal-body">
946         <div class="container-fluid">
948             <&| /util/workflow.mas, id=> "drone_imagery_download_phenotypes_workflow" &>
949                 <&| /util/workflow.mas:step, title=> "Field Trial" &>
950                     <& /page/page_title.mas, title=>"Select the field trial you are interested in" &>
951                     <br/><br/>
952                     <form class="form-horizontal">
953                         <div class="form-group">
954                             <label class="col-sm-3 control-label">Field Trial: </label>
955                             <div class="col-sm-9" >
956                                 <div id="drone_imagery_download_phenotypes_trial_select_div"></div>
957                             </div>
958                         </div>
959                     </form>
960                     <center>
961                     <button class="btn btn-primary" id="drone_imagery_download_phenotypes_field_trial_select_step">Go to Next Step</button>
962                     </center>
963                 </&>
964                 <&| /util/workflow.mas:step, title=> "Trait Selection" &>
965                     <& /page/page_title.mas, title=>"Select the observation variable(s) you are interested in downloading" &>
966                     <br/><br/>
967                     <form class="form-horizontal">
968                         <div class="form-group">
969                             <label class="col-sm-3 control-label">Observation Variables Phenotyped in the Selected Field Trial: </label>
970                             <div class="col-sm-9" >
971                                 <div id="drone_imagery_download_phenotypes_trait_select_div"></div>
972                             </div>
973                         </div>
974                     </form>
975                     <center>
976                     <button class="btn btn-primary" id="drone_imagery_download_phenotypes_trait_select_step">Go to Next Step</button>
977                     </center>
978                 </&>
979                 <&| /util/workflow.mas:step, title=> "Download" &>
980                     <& /page/page_title.mas, title=>"Download!" &>
982                     <div id ="drone_imagery_download_phenotypes_file_div">
983                     </div>
985                     <br/><br/>
986                     <center>
987                     <button class="btn btn-primary" id="drone_imagery_download_phenotypes_confirm_step">Submit</button>
988                     </center>
989                 </&>
990             </&>
992         </div>
994       </div>
995       <div class="modal-footer">
996         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
997       </div>
998     </div>
999   </div>
1000 </div>
1002 <div class="modal fade" id="drone_imagery_calculate_statistics_dialog" name="drone_imagery_calculate_statistics_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryCalculateStatisticsDialog" data-backdrop="static">
1003   <div class="modal-dialog modal-xl" role="document">
1004     <div class="modal-content">
1005       <div class="modal-header">
1006         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
1007         <h4 class="modal-title" id="droneImageryCalculateStatisticsDialog">Calculate statistics on drone phenotypes</h4>
1008       </div>
1009       <div class="modal-body">
1010         <div class="container-fluid">
1012             <&| /util/workflow.mas, id=> "drone_imagery_calculate_statistics_workflow" &>
1013                 <&| /util/workflow.mas:step, title=> "Field Trial" &>
1014                     <& /page/page_title.mas, title=>"Select the field trial(s) you are interested in. Selected field trials should have some common accessions between them." &>
1015                     <br/><br/>
1016                     <form class="form-horizontal">
1017                         <div class="form-group">
1018                             <label class="col-sm-3 control-label">Field Trial(s): </label>
1019                             <div class="col-sm-9" >
1020                                 <div id="drone_imagery_calculate_statistics_trial_select_div"></div>
1021                             </div>
1022                         </div>
1023                     </form>
1024                     <center>
1025                     <button class="btn btn-primary" id="drone_imagery_calculate_statistics_field_trial_select_step">Go to Next Step</button>
1026                     </center>
1027                 </&>
1028                 <&| /util/workflow.mas:step, title=> "Trait Selection" &>
1029                     <& /page/page_title.mas, title=>"Select the observation variable(s) you are interested in downloading" &>
1030                     <br/><br/>
1031                     <form class="form-horizontal">
1032                         <div class="form-group">
1033                             <label class="col-sm-3 control-label">Observation Variable Type: </label>
1034                             <div class="col-sm-9" >
1035                                 <select class="form-control" id="drone_imagery_calculate_statistics_select_observation_variable_type">
1036                                     <option value="time_ontology">Time Series</option>
1037                                     <option value="">Single Trait</option>
1038                                 </select>
1039                             </div>
1040                         </div>
1041                         <div class="form-group">
1042                             <label class="col-sm-3 control-label">Observation Variables Phenotyped in the Selected Field Trial: </label>
1043                             <div class="col-sm-9" >
1044                                 <div id="drone_imagery_calculate_statistics_trait_select_div"></div>
1045                             </div>
1046                         </div>
1047                     </form>
1048                     <center>
1049                     <button class="btn btn-primary" id="drone_imagery_calculate_statistics_trait_select_step">Go to Next Step</button>
1050                     </center>
1051                 </&>
1052                 <&| /util/workflow.mas:step, title=> "Statistics" &>
1053                     <& /page/page_title.mas, title=>"Select statistics to calculate" &>
1055                     <select class="form-control" id="drone_imagery_calculate_statistics_select_input">
1056                         <option value="lmer_germplasmname">LMER y~replicate+1|GermplasmName. Percent Variance Explained by GermplasmName</option>
1057                         <option value="lmer_germplasmname_block">LMER y~blockNumber+1|GermplasmName. Percent Variance Explained by GermplasmName</option>
1058                         <option value="marss_germplasmname_block">MARSS prediction for each germplasmName</option>
1059                     </select>
1061                     <div id="drone_imagery_calculate_statistics_marss_div" style="display:none">
1062                         $$x_t = Bx_{t-1} + u + w_t\\ w_t \sim MVN(0,Q)\\ y_t = Zx_t + a + v_t\\ v_t \sim MVN(0,R)\\ x_0 \sim MVN(\pi, \Lambda)$$
1063                         <hr>
1064                         <select class="form-control" id="drone_imagery_calculate_statistics_select_marss" name="drone_imagery_calculate_statistics_select_marss">
1065                             <option value="marss_predict_last_time_point">Predict Last Time Point</option>
1066                             <option value="marss_predict_last_two_time_points">Predict Last Two Time Point</option>
1067                         </select>
1068                     </div>
1070                     <br/><br/>
1071                     <center>
1072                     <button class="btn btn-primary" id="drone_imagery_calculate_statistics_select_step">Submit</button>
1073                     </center>
1074                 </&>
1075                 <&| /util/workflow.mas:step, title=> "Results" &>
1076                     <& /page/page_title.mas, title=>"Statistics results" &>
1078                     <div id ="drone_imagery_calculate_statistics_result_div">
1079                     </div>
1080                 </&>
1081             </&>
1083         </div>
1085       </div>
1086       <div class="modal-footer">
1087         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
1088       </div>
1089     </div>
1090   </div>
1091 </div>
1093 <div class="modal fade" id="drone_imagery_keras_cnn_dialog" name="drone_imagery_keras_cnn_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryKerasCNNDialog" data-backdrop="static">
1094   <div class="modal-dialog" role="document">
1095     <div class="modal-content">
1096       <div class="modal-header">
1097         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
1098         <h4 class="modal-title" id="droneImageryKerasCNNDialog">Train and Predict Using Keras CNN Model</h4>
1099       </div>
1100       <div class="modal-body">
1101         <div class="container-fluid">
1102             <button class="btn btn-primary" id="drone_imagery_keras_cnn_train_link">Train Keras CNN Model Using Images and Phenotypes In Database</button>
1103             <br/><br/>
1104             <button class="btn btn-primary" id="drone_imagery_keras_cnn_predict_link">Predict Phenotypes Using Images and Trained Keras Model CNN</button>
1105         </div>
1106       </div>
1107       <div class="modal-footer">
1108         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
1109       </div>
1110     </div>
1111   </div>
1112 </div>
1114 <div class="modal fade" id="drone_imagery_train_keras_cnn_dialog" name="drone_imagery_train_keras_cnn_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryTrainKerasCNNDialog" data-backdrop="static">
1115   <div class="modal-dialog modal-xl" role="document">
1116     <div class="modal-content">
1117       <div class="modal-header">
1118         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
1119         <h4 class="modal-title" id="droneImageryTrainKerasCNNDialog">Train Keras CNN Model</h4>
1120       </div>
1121       <div class="modal-body">
1122         <div class="container-fluid">
1124             <&| /util/workflow.mas, id=> "drone_imagery_train_keras_model_workflow" &>
1125                 <&| /util/workflow.mas:step, title=> "Intro" &>
1126                     <& /page/page_title.mas, title=>"This workflow will guide you through training a keras model using images and phenotypes in the database." &>
1127                     <br/><br/>
1128                     <center>
1129                     <button class="btn btn-primary" onclick="Workflow.complete(this); return false;">Go to Next Step</button>
1130                     </center>
1131                 </&>
1132                 <&| /util/workflow.mas:step, title=> "Field Trial(s)" &>
1133                     <& /page/page_title.mas, title=>"Select the field trial(s) you are interested in" &>
1134                     <br/><br/>
1135                     <form class="form-horizontal">
1136                         <div class="form-group">
1137                             <label class="col-sm-3 control-label">Field Trial(s): </label>
1138                             <div class="col-sm-9" >
1139                                 <div id="drone_imagery_train_keras_cnn_trial_select_div"></div>
1140                             </div>
1141                         </div>
1142                     </form>
1143                     <br/><br/>
1144                     <center>
1145                     <button class="btn btn-primary" id="drone_imagery_train_keras_model_field_trial_select_step">Go to Next Step</button>
1146                     </center>
1147                 </&>
1148                 <&| /util/workflow.mas:step, title=> "Trait Selection" &>
1149                     <& /page/page_title.mas, title=>"Select the trait you are interested in predicting" &>
1150                     <br/><br/>
1151                     <form class="form-horizontal">
1152                         <div class="form-group">
1153                             <label class="col-sm-3 control-label">Trait Phenotyped in the Selected Field Trial(s) To Predict: </label>
1154                             <div class="col-sm-9" >
1155                                 <div id="drone_imagery_train_keras_cnn_trait_select_div"></div>
1156                             </div>
1157                         </div>
1158                         <div class="form-group">
1159                             <label class="col-sm-3 control-label">Traits Phenotyped in the Selected Field Trial(s) As Auxiliary Trait(s): </label>
1160                             <div class="col-sm-9" >
1161                                 <div id="drone_imagery_train_keras_cnn_aux_trait_select_div"></div>
1162                             </div>
1163                         </div>
1164                     </form>
1165                     <br/><br/><br/>
1166                     <center>
1167                     <button class="btn btn-primary" id="drone_imagery_train_keras_model_trait_select_step">Go to Next Step</button>
1168                     </center>
1169                 </&>
1170                 <&| /util/workflow.mas:step, title=> "Population Selection" &>
1171                     <& /page/page_title.mas, title=>"Select the population(s) you are specifically interested in predicting. Leave blank if you want to train on images from all germplasm in the selected field trial(s)." &>
1172                     <br/><br/>
1173                     <form class="form-horizontal">
1174                         <div class="form-group">
1175                             <label class="col-sm-5 control-label">Population(s) to include in training (Leave blank to include images from all germplasm in the selected field trials): </label>
1176                             <div class="col-sm-7" >
1177                                 <div id="drone_imagery_train_keras_cnn_population_select_div"></div>
1178                             </div>
1179                         </div>
1180                     </form>
1181                     <br/><br/><br/>
1182                     <center>
1183                     <button class="btn btn-primary" id="drone_imagery_train_keras_model_population_select_step">Go to Next Step</button>
1184                     </center>
1185                 </&>
1186                 <&| /util/workflow.mas:step, title=> "Drone Run Selection" &>
1187                     <& /page/page_title.mas, title=>"Select the drone runs you are interested in using in the model" &>
1189                     <table class="table table-bordered table-hover" id="drone_image_train_keras_drone_runs_table">
1190                         <thead>
1191                             <tr>
1192                                 <th>Select <br/><input type="checkbox" id="drone_image_train_keras_drone_runs_table_select_all" checked>Select All</th>
1193                                 <th>Drone Run Name</th>
1194                                 <th>Drone Run Type</th>
1195                                 <th>Drone Run Description</th>
1196                                 <th>Drone Run Date</th>
1197                                 <th>Drone Run GDD</th>
1198                                 <th>Camera Type</th>
1199                                 <th>Field Trial Name</th>
1200                                 <th>Field Trial Description</th>
1201                             </tr>
1202                         </thead>
1203                     </table>
1205                     <br/><br/>
1206                     <center>
1207                     <button class="btn btn-primary" id="drone_imagery_train_keras_model_drone_run_select_step">Go to Next Step</button>
1208                     </center>
1209                 </&>
1210                 <&| /util/workflow.mas:step, title=> "Images Selection" &>
1211                     <& /page/page_title.mas, title=>"Select the types of images you are interested in using in the model" &>
1213                     <table class="table table-bordered table-hover" id="drone_image_train_keras_plot_polygon_image_type_table">
1214                         <thead>
1215                             <tr>
1216                                 <!--th>Select <br/><input type="checkbox" id="drone_image_train_keras_plot_polygon_image_type_table_select_all" checked>Select All</th-->
1217                                 <th>Select</th>
1218                                 <th>Field Trial</th>
1219                                 <th>Drone Run Name</th>
1220                                 <th>Drone Run Band Name</th>
1221                                 <th>Drone Run Band Type</th>
1222                                 <th>Plot Polygon Type</th>
1223                                 <th>Number of Images</th>
1224                             </tr>
1225                         </thead>
1226                     </table>
1228                     <br/><br/>
1229                     <center>
1230                     <button class="btn btn-primary" id="drone_imagery_train_keras_model_plot_polygon_type_select_step">Go to Next Step</button>
1231                     </center>
1232                 </&>
1233                 <&| /util/workflow.mas:step, title=> "Confirm" &>
1234                     <& /page/page_title.mas, title=>"Train the model!" &>
1236                     <br/><br/>
1237                     <div class="form-horizontal">
1238                         <div class="form-group">
1239                             <label class="col-sm-4 control-label">Model Type: </label>
1240                             <div class="col-sm-8" >
1241                                 <select class="form-control" id="drone_image_train_keras_model_type" name="drone_image_train_keras_model_type" >
1242                                     <option value="KerasCNNSequentialSoftmaxCategorical">Keras CNN Sequential 16-32-64-128-512 Linear Regression</option>
1243                                     <option value="KerasCNNMLPExample">Keras CNN and MLP Example</option>
1244                                     <option value="SimpleKerasTunerCNNSequentialSoftmaxCategorical">Simple Keras Tuner CNN Sequential 16-32-64-128-512 Linear Regression</option>
1245                                     <option value="KerasTunerCNNSequentialSoftmaxCategorical">Keras Tuner CNN Sequential 16-32-64-128-512 Linear Regression</option>
1246                                     <option value="KerasCNNInceptionResNetV2">Keras CNN InceptionResNetV2 Linear Regression</option>
1247                                     <option value="KerasCNNLSTMDenseNet121ImageNetWeights">Keras LSTM DenseNet121 ImageNet Weights Linear Regression</option>
1248                                     <option value="KerasCNNInceptionResNetV2ImageNetWeights">Keras CNN Pre-Trained InceptionResNetV2 ImageNet Weights Linear Regression</option>
1249                                     <option value="KerasCNNDenseNet121ImageNetWeights">Keras DenseNet121 ImageNet Weights Linear Regression</option>
1250                                 </select>
1251                             </div>
1252                         </div>
1253                         <div class="form-group">
1254                             <label class="col-sm-4 control-label">Model Name: </label>
1255                             <div class="col-sm-8" >
1256                                 <input class="form-control" type="text" id="drone_image_train_keras_model_name" name="drone_image_train_keras_model_name" />
1257                             </div>
1258                         </div>
1259                         <div class="form-group">
1260                             <label class="col-sm-4 control-label">Model Description: </label>
1261                             <div class="col-sm-8" >
1262                                 <input class="form-control" type="text" id="drone_image_train_keras_model_desc" name="drone_image_train_keras_model_desc" />
1263                             </div>
1264                         </div>
1265                         <div class="form-group">
1266                             <label class="col-sm-4 control-label">Genotyping Protocol for GRM: </label>
1267                             <div class="col-sm-8" >
1268                                 <div id="drone_image_train_keras_model_genotyping_protocol_div"></div>
1269                             </div>
1270                         </div>
1271                         <div class="form-group">
1272                             <label class="col-sm-4 control-label">Use Parents of Accessions For In-silico Hybrid: </label>
1273                             <div class="col-sm-8" >
1274                                 <select class="form-control" id="drone_image_train_keras_model_use_parents_grm" name="drone_image_train_keras_model_use_parents_grm" >
1275                                     <option value="yes">Yes, GRM for parents of accessions if genotyped</option>
1276                                     <option value="no">No, GRM for accessions if genotyped</option>
1277                                 </select>
1278                             </div>
1279                         </div>
1280                     </div>
1282                     <br/><br/>
1283                     <center>
1284                     <button class="btn btn-primary" id="drone_imagery_train_keras_model_confirm_step">Train and Save Keras CNN Model</button>
1285                     </center>
1287                     <div id="drone_imagery_train_keras_model_results_div">
1288                     </div>
1289                 </&>
1290             </&>
1292         </div>
1294       </div>
1295       <div class="modal-footer">
1296         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
1297       </div>
1298     </div>
1299   </div>
1300 </div>
1302 <div class="modal fade" id="drone_imagery_predict_keras_cnn_dialog" name="drone_imagery_predict_keras_cnn_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryPredictKerasCNNDialog" data-backdrop="static">
1303   <div class="modal-dialog modal-xl" role="document">
1304     <div class="modal-content">
1305       <div class="modal-header">
1306         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
1307         <h4 class="modal-title" id="droneImageryPredictKerasCNNDialog">Predict Phenotypes Using Trained Keras CNN Model</h4>
1308       </div>
1309       <div class="modal-body">
1310         <div class="container-fluid">
1312             <&| /util/workflow.mas, id=> "drone_imagery_predict_keras_model_workflow" &>
1313                 <&| /util/workflow.mas:step, title=> "Intro" &>
1314                     <& /page/page_title.mas, title=>"This workflow will guide you through predicting phenotypes from trained Kera CNN Models and images in the database." &>
1315                     <br/><br/>
1316                     <center>
1317                     <button class="btn btn-primary" onclick="Workflow.complete(this); return false;">Go to Next Step</button>
1318                     </center>
1319                 </&>
1320                 <&| /util/workflow.mas:step, title=> "Field Trial" &>
1321                     <& /page/page_title.mas, title=>"Select the field trial(s) you are interested in sourcing images from for prediction" &>
1322                     <br/><br/>
1323                     <form class="form-horizontal">
1324                         <div class="form-group">
1325                             <label class="col-sm-3 control-label">Field Trial: </label>
1326                             <div class="col-sm-9" >
1327                                 <div id="drone_imagery_predict_keras_cnn_trial_select_div"></div>
1328                             </div>
1329                         </div>
1330                     </form>
1331                     <br/><br/>
1332                     <center>
1333                     <button class="btn btn-primary" id="drone_imagery_predict_keras_model_field_trial_select_step">Go to Next Step</button>
1334                     </center>
1335                 </&>
1336                 <&| /util/workflow.mas:step, title=> "Keras CNN Model Selection" &>
1337                     <& /page/page_title.mas, title=>"Select the Keras CNN Model for prediction" &>
1339                     <br/><br/>
1340                     <form class="form-horizontal">
1341                         <div class="form-group">
1342                             <label class="col-sm-3 control-label">Trained Keras CNN Model: </label>
1343                             <div class="col-sm-9" >
1344                                 <div id="drone_imagery_predict_keras_cnn_model_select_div"></div>
1345                             </div>
1346                         </div>
1347                     </form>
1348                     <br/><br/>
1350                     <center>
1351                     <button class="btn btn-primary" id="drone_imagery_predict_keras_model_select_step">Go to Next Step</button>
1352                     </center>
1353                 </&>
1354                 <&| /util/workflow.mas:step, title=> "Population Selection" &>
1355                     <& /page/page_title.mas, title=>"Select the population(s) you are specifically interested in predicting. Leave blank if you want to train on images from all germplasm in the selected field trial(s)." &>
1356                     <br/><br/>
1357                     <form class="form-horizontal">
1358                         <div class="form-group">
1359                             <label class="col-sm-5 control-label">Population(s) to include in training (Leave blank to include images from all germplasm in the selected field trials): </label>
1360                             <div class="col-sm-7" >
1361                                 <div id="drone_imagery_predict_keras_cnn_population_select_div"></div>
1362                             </div>
1363                         </div>
1364                     </form>
1365                     <br/><br/><br/>
1366                     <center>
1367                     <button class="btn btn-primary" id="drone_imagery_predict_keras_model_population_select_step">Go to Next Step</button>
1368                     </center>
1369                 </&>
1370                 <&| /util/workflow.mas:step, title=> "Drone Run Selection" &>
1371                     <& /page/page_title.mas, title=>"Select the drone runs you are interested in sourcing images from for prediction" &>
1373                     <table class="table table-bordered table-hover" id="drone_image_predict_keras_drone_runs_table">
1374                         <thead>
1375                             <tr>
1376                                 <th>Select <br/><input type="checkbox" id="drone_image_predict_keras_drone_runs_table_select_all" checked>Select All</th>
1377                                 <th>Drone Run Name</th>
1378                                 <th>Drone Run Type</th>
1379                                 <th>Drone Run Description</th>
1380                                 <th>Drone Run Date</th>
1381                                 <th>Drone Run GDD</th>
1382                                 <th>Camera Type</th>
1383                                 <th>Field Trial Name</th>
1384                                 <th>Field Trial Description</th>
1385                             </tr>
1386                         </thead>
1387                     </table>
1389                     <br/><br/>
1390                     <center>
1391                     <button class="btn btn-primary" id="drone_imagery_predict_keras_model_drone_run_select_step">Go to Next Step</button>
1392                     </center>
1393                 </&>
1394                 <&| /util/workflow.mas:step, title=> "Images Selection" &>
1395                     <& /page/page_title.mas, title=>"Select the types of images you are interested sourcing images from for prediction" &>
1397                     <table class="table table-bordered table-hover" id="drone_image_predict_keras_plot_polygon_image_type_table">
1398                         <thead>
1399                             <tr>
1400                                 <!--th>Select <br/><input type="checkbox" id="drone_image_predict_keras_plot_polygon_image_type_table_select_all" checked>Select All</th-->
1401                                 <th>Select</th>
1402                                 <th>Field Trial</th>
1403                                 <th>Drone Run Name</th>
1404                                 <th>Drone Run Band Name</th>
1405                                 <th>Drone Run Band Type</th>
1406                                 <th>Plot Polygon Type</th>
1407                                 <th>Number of Images</th>
1408                             </tr>
1409                         </thead>
1410                     </table>
1412                     <br/><br/>
1413                     <center>
1414                     <button class="btn btn-primary" id="drone_imagery_predict_keras_model_plot_polygon_type_select_step">Go to Next Step</button>
1415                     </center>
1416                 </&>
1417                 <&| /util/workflow.mas:step, title=> "Confirm" &>
1418                     <& /page/page_title.mas, title=>"Predict Phenotypes!" &>
1419                     <br/><br/>
1420                     <form class="form-horizontal">
1421                         <div class="form-group">
1422                             <label class="col-sm-3 control-label">Prediction Model: </label>
1423                             <div class="col-sm-9" >
1424                                 <select class="form-control" id="drone_imagery_keras_model_prediction_select">
1425                                     <option value="standard_cnn">Standard CNN Prediction</option>
1426                                     <option value="cnn_prediction_mixed_model">CNN Prediction For Mixed Model Prediction</option>
1427                                 </select>
1428                             </div>
1429                         </div>
1430                     </form>
1432                     <div id="drone_imagery_keras_model_prediction_cnn_prediction_mixed_model_div" style="display:none">
1433                         $$y_t = \beta_{CNN,pred} + rep + 1|\mbox{GermplasmName}$$
1434                     </div>
1435                     <br/><br/>
1437                     <center>
1438                     <button class="btn btn-primary" id="drone_imagery_predict_keras_model_confirm_step">Submit</button>
1439                     </center>
1441                     <div id="drone_imagery_predict_keras_model_results_div">
1442                     </div>
1443                 </&>
1444             </&>
1446         </div>
1448       </div>
1449       <div class="modal-footer">
1450         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
1451       </div>
1452     </div>
1453   </div>
1454 </div>
1456 <div class="modal fade" id="drone_imagery_standard_process_complete_dialog" name="drone_imagery_standard_process_complete_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryStandardProcessCompleteDialog" data-backdrop="static">
1457   <div class="modal-dialog modal-xl" role="document">
1458     <div class="modal-content">
1459       <div class="modal-header">
1460         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
1461         <h4 class="modal-title" id="droneImageryStandardProcessCompleteDialog">Standard Process Complete</h4>
1462       </div>
1463       <div class="modal-body">
1464         <div class="container-fluid">
1465             <p>
1466                 <span class="ui-icon ui-icon-circle-check" style="float: left; margin: 0 7px 50px 0;"></span>
1467                 It will take time to finish processing your drone run and calculating phenotypes for all plot polygon images, vegetative indices, and processing combinations. Once it is complete, the "Processing Icon" on the Manage->Drone Imagery page will disappear from the drone run.
1468             </p>
1469         </div>
1470       </div>
1471       <div class="modal-footer">
1472         <button type="button" class="btn btn-primary" data-dismiss="modal">Finish</button>
1473       </div>
1474     </div>
1475   </div>
1476 </div>
1478 <div class="modal fade" id="drone_imagery_plot_polygon_template_options_dialog" name="drone_imagery_plot_polygon_template_options_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryPlotPolygonTemplateDialog" data-backdrop="static">
1479   <div class="modal-dialog modal-xl" role="document">
1480     <div class="modal-content">
1481       <div class="modal-header">
1482         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
1483         <h4 class="modal-title" id="droneImageryPlotPolygonTemplateDialog">Plot Template Options</h4>
1484       </div>
1485       <div class="modal-body">
1486         <div class="container-fluid">
1487             <&| /page/info_section.mas, title => 'Copy/Paste Template', collapsible=>1, collapsed => 0, subtitle=> 'Copy/Paste this template onto the image.' &>
1488                 <button class="btn btn-primary" id="drone_imagery_plot_polygon_template_options_paste_click">Click To Paste</button>
1489             </&>
1490         </div>
1491       </div>
1492       <div class="modal-footer">
1493         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
1494       </div>
1495     </div>
1496   </div>
1497 </div>
1499 <div class="modal fade" id="drone_imagery_calculate_gdd_dialog" name="drone_imagery_calculate_gdd_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryCalculateGDDDialog" data-backdrop="static">
1500   <div class="modal-dialog modal-lg" role="document">
1501     <div class="modal-content">
1502       <div class="modal-header">
1503         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
1504         <h4 class="modal-title" id="droneImageryCalculateGDDDialog">Calculate Growing Degree Days</h4>
1505       </div>
1506       <div class="modal-body">
1507         <div class="container-fluid">
1508             <div class="well well-sm">
1509                 Growing Degree Days (GDD) are calculated using the average high and low temperature for each day from planting date to the date of the imaging event. <a href="https://www.canr.msu.edu/news/understanding_growing_degree_days" target=_blank >More Information on GDD</a>. The average daily high and low temperature is fetched from the <a href="https://www.ncdc.noaa.gov/cdo-web/webservices/v2" target=_blank>NOAA NCDC</a>.
1510             </div>
1512             <div id="drone_imagery_calculate_gdd_time_div"></div>
1514             <div class="form-horizontal">
1515                 <div class="form-group">
1516                     <label class="col-sm-3 control-label">Base Temperature:</label>
1517                     <div class="col-sm-9" >
1518                         <select class="form-control" id="drone_imagery_calculate_gdd_base_temperature_input">
1519                             <option value="50">50F</option>
1520                         </select>
1521                     </div>
1522                 </div>
1523                 <div class="form-group">
1524                     <label class="col-sm-3 control-label">Formula:</label>
1525                     <div class="col-sm-9" >
1526                         <select class="form-control" id="drone_imagery_calculate_gdd_formula_input">
1527                             <option value="average_daily_temp_sum">GDD = sum_over_days ( ( (Max Temp + Min Temp)/2 ) - Base Temp)</option>
1528                         </select>
1529                     </div>
1530                 </div>
1531             </div>
1533         </div>
1534       </div>
1535       <div class="modal-footer">
1536         <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
1537         <button type="button" class="btn btn-primary" id="drone_imagery_upload_gdd_submit">Calculate</button>
1538       </div>
1539     </div>
1540   </div>
1541 </div>
1543 <div class="modal fade" id="drone_imagery_compare_images_dialog" name="drone_imagery_compare_images_dialog" tabindex="-1" role="dialog" aria-labelledby="droneImageryCompareImagesDialog" data-backdrop="static">
1544   <div class="modal-dialog modal-xl" role="document">
1545     <div class="modal-content">
1546       <div class="modal-header">
1547         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
1548         <h4 class="modal-title" id="droneImageryCompareImagesDialog">Compare Images</h4>
1549       </div>
1550       <div class="modal-body">
1551         <div class="container-fluid">
1553             <&| /util/workflow.mas, id=> "drone_imagery_compare_images_workflow" &>
1554                 <&| /util/workflow.mas:step, title=> "Comparison" &>
1555                     <& /page/page_title.mas, title=>"Select the comparison you are interested in" &>
1556                     <form class="form-horizontal">
1557                         <div class="form-group">
1558                             <label class="col-sm-3 control-label">Comparison: </label>
1559                             <div class="col-sm-9" >
1560                                 <select id="drone_imagery_compare_images_comparison_select" class="form-control">
1561                                     <option value="compare_pixel_values_two_images">Compare pixel values for two different aerial field images</option>
1562                                 </select>
1563                             </div>
1564                         </div>
1565                     </form>
1566                     <center>
1567                     <button class="btn btn-primary" id="drone_imagery_compare_images_comparison_select_step">Go to Next Step</button>
1568                     </center>
1569                 </&>
1570                 <&| /util/workflow.mas:step, title=> "Field Trial(s)" &>
1571                     <& /page/page_title.mas, title=>"Select the field trials you are interested in comparing" &>
1573                     <form class="form-horizontal">
1574                         <div class="form-group">
1575                             <label class="col-sm-3 control-label">Field Trial(s): </label>
1576                             <div class="col-sm-9" >
1577                                 <div id="drone_imagery_compare_images_trial_select_div"></div>
1578                             </div>
1579                         </div>
1580                     </form>
1582                     <br/><br/>
1584                     <center>
1585                     <button class="btn btn-primary" id="drone_imagery_compare_images_field_trial_select_step">Go to Next Step</button>
1586                     </center>
1587                 </&>
1588                 <&| /util/workflow.mas:step, title=> "Imaging Event(s)" &>
1589                     <& /page/page_title.mas, title=>"Select the imaging events you are interested in comparing" &>
1591                     <table class="table table-bordered table-hover" id="drone_image_compare_images_drone_runs_table">
1592                         <thead>
1593                             <tr>
1594                                 <th>Select</th>
1595                                 <th>Drone Run Name</th>
1596                                 <th>Drone Run Type</th>
1597                                 <th>Drone Run Description</th>
1598                                 <th>Drone Run Date</th>
1599                                 <th>Drone Run GDD</th>
1600                                 <th>Camera Type</th>
1601                                 <th>Field Trial Name</th>
1602                                 <th>Field Trial Description</th>
1603                             </tr>
1604                         </thead>
1605                     </table>
1607                     <br/><br/>
1609                     <center>
1610                     <button class="btn btn-primary" id="drone_imagery_compare_images_drone_runs_select_step">Go to Next Step</button>
1611                     </center>
1612                 </&>
1613                 <&| /util/workflow.mas:step, title=> "Imaging Event Band(s)" &>
1614                     <& /page/page_title.mas, title=>"Select the imaging event bands you are interested in comparing" &>
1616                     <table class="table table-bordered table-hover" id="drone_image_compare_images_drone_run_bands_table">
1617                         <thead>
1618                             <tr>
1619                                 <th>Select</th>
1620                                 <th>Drone Run Name</th>
1621                                 <th>Drone Run Type</th>
1622                                 <th>Drone Run Description</th>
1623                                 <th>Drone Run Date</th>
1624                                 <th>Drone Run GDD</th>
1625                                 <th>Camera Type</th>
1626                                 <th>Field Trial Name</th>
1627                                 <th>Field Trial Description</th>
1628                             </tr>
1629                         </thead>
1630                     </table>
1632                     <br/><br/>
1634                     <center>
1635                     <button class="btn btn-primary" id="drone_imagery_compare_images_drone_run_bands_select_step">Go to Next Step</button>
1636                     </center>
1637                 </&>
1638                 <&| /util/workflow.mas:step, title=> "Image Selection" &>
1639                     <& /page/page_title.mas, title=>"Select the images you are interested in comparing" &>
1641                     <table class="table table-bordered table-hover" id="drone_imagery_compare_images_images_type_table">
1642                         <thead>
1643                             <tr>
1644                                 <th>Select</th>
1645                                 <th>Field Trial</th>
1646                                 <th>Drone Run Name</th>
1647                                 <th>Drone Run Band Name</th>
1648                                 <th>Drone Run Band Type</th>
1649                                 <th>Plot Polygon Type</th>
1650                                 <th>Number of Images</th>
1651                             </tr>
1652                         </thead>
1653                     </table>
1655                     <br/><br/>
1657                     <center>
1658                     <button class="btn btn-primary" id="drone_imagery_compare_images_images_select_step">Go to Next Step</button>
1659                     </center>
1660                 </&>
1661                 <&| /util/workflow.mas:step, title=> "Result" &>
1662                     <& /page/page_title.mas, title=>"Image comparison results" &>
1664                     <div id="drone_imagery_compare_images_result_div"></div>
1665                 </&>
1666             </&>
1668         </div>
1670       </div>
1671       <div class="modal-footer">
1672         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
1673       </div>
1674     </div>
1675   </div>
1676 </div>
1678 <div class="modal fade" id="upload_drone_imagery_standard_process_additional_raw_images_dialog" name="upload_drone_imagery_standard_process_additional_raw_images_dialog" tabindex="-1" role="dialog" aria-labelledby="uploadDroneImageryStandardProcessAdditionalRawImagesDialog">
1679     <div class="modal-dialog modal-xl" role="document">
1680         <div class="modal-content">
1681             <div class="modal-header">
1682                 <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
1683                 <h4 class="modal-title" id="uploadDroneImageryStandardProcessAdditionalRawImagesDialog">Upload Additional Raw Image Captures</h4>
1684             </div>
1685             <div class="modal-body">
1686                 <div class="container-fluid">
1688                     <form class="form-horizontal" role="form" method="post" enctype="multipart/form-data" encoding="multipart/form-data" id="upload_drone_imagery_additional_raw_images_form" name="upload_drone_imagery_additional_raw_images_form">
1689                         <div class="form-group">
1690                             <label class="col-sm-3 control-label">Drone Images ZipFile (.zip) (2GB Maximum): </label>
1691                             <div class="col-sm-9" >
1692                                 <input type="file" id="upload_drone_imagery_additional_raw_images_zipfile" name="upload_drone_imagery_additional_raw_images_zipfile" encoding="multipart/form-data" />
1693                             </div>
1694                         </div>
1695                         <div class="form-group">
1696                             <label class="col-sm-3 control-label">Micasense Radiometric Calibration Images ZipFile (.zip with 5 images in it): </label>
1697                             <div class="col-sm-9" >
1698                                 <input type="file" id="upload_drone_imagery_additional_raw_images_calibration_zipfile" name="upload_drone_imagery_additional_raw_images_calibration_zipfile" encoding="multipart/form-data" />
1699                             </div>
1700                         </div>
1702                         <input type="hidden" id="upload_drone_imagery_additional_raw_images_drone_run_id" name="upload_drone_imagery_additional_raw_images_drone_run_id" value="" />
1703                         <input type="hidden" id="upload_drone_imagery_additional_raw_images_field_trial_id" name="upload_drone_imagery_additional_raw_images_field_trial_id" value="" />
1704                     </form><br/>
1706                     <center>
1707                         <button type="button" class="btn btn-info" name="upload_drone_imagery_additional_raw_images_submit" id="upload_drone_imagery_additional_raw_images_submit">Submit</button>
1708                     </center>
1710                 </div>
1711             </div>
1712             <div class="modal-footer">
1713                 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
1714             </div>
1715         </div>
1716     </div>
1717 </div>
1719 <& /breeders_toolbox/drone_imagery/upload_drone_imagery_dialogs.mas &>
1721 <script>
1723 jQuery(document).ready(function() {
1725     //
1726     // Standard Process for Drone Runs
1727     //
1729     var manage_drone_imagery_standard_process_field_trial_id;
1730     var manage_drone_imagery_standard_process_drone_run_project_id;
1731     var manage_drone_imagery_standard_process_drone_run_band_project_id;
1732     var manage_drone_imagery_standard_process_rotate_stitched_image_id;
1733     var manage_drone_imagery_standard_process_rotate_drone_run_band_project_id;
1734     var manage_drone_imagery_standard_process_rotate_stitched_image_degrees;
1735     var manage_drone_imagery_standard_process_rotated_stitched_image_id;
1736     var manage_drone_imagery_standard_process_cropped_image_id;
1737     var manage_drone_imagery_standard_process_denoised_image_id;
1738     var manage_drone_imagery_standard_process_removed_background_image_id;
1739     var manage_drone_imagery_standard_process_current_threshold_background_removed_type;
1740     var manage_drone_imagery_standard_process_apply_drone_run_band_project_ids = [];
1741     var manage_drone_imagery_standard_process_apply_drone_run_band_vegetative_indices = [];
1742     var manage_drone_imagery_standard_process_phenotype_time = '';
1744     jQuery(document).on('click', 'button[name="project_drone_imagery_standard_process"]', function(){
1745         showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1747         manage_drone_imagery_standard_process_drone_run_project_id = jQuery(this).data('drone_run_project_id');
1748         manage_drone_imagery_standard_process_field_trial_id = jQuery(this).data('field_trial_id');
1750         jQuery('#manage_drone_imagery_standard_process_drone_run_bands_table').DataTable({
1751             destroy : true,
1752             ajax : '/api/drone_imagery/drone_run_bands?select_checkbox_name=drone_run_standard_process_band_select&drone_run_project_id='+manage_drone_imagery_standard_process_drone_run_project_id
1753         });
1754     });
1756     jQuery('#manage_drone_imagery_standard_process_drone_run_band_step').click(function(){
1757         var selected = [];
1758         jQuery('input[name="drone_run_standard_process_band_select"]:checked').each(function() {
1759             selected.push([jQuery(this).val(), jQuery(this).data('background_removed_threshold_type')]);
1760         });
1761         if (selected.length < 1){
1762             alert('Please select at least one drone run band! Preferably one with high contrast such as NIR.');
1763             return false;
1764         } else if (selected.length > 1){
1765             alert('Please select only one drone run band! Preferably one with high contrast such as NIR.');
1766             return false;
1767         } else {
1768             manage_drone_imagery_standard_process_drone_run_band_project_id = selected[0][0];
1769             manage_drone_imagery_standard_process_current_threshold_background_removed_type = selected[0][1];
1770             jQuery.ajax({
1771                 url : '/api/drone_imagery/get_project_md_image?drone_run_band_project_id='+manage_drone_imagery_standard_process_drone_run_band_project_id+'&project_image_type_name=stitched_drone_imagery',
1772                 beforeSend: function(){
1773                     showManageDroneImagerySection('manage_drone_imagery_loading_div');
1774                 },
1775                 success: function(response){
1776                     console.log(response);
1777                     manage_drone_imagery_standard_process_rotate_stitched_image_id = response.data[0]['image_id'];
1778                     manage_drone_imagery_standard_process_rotate_stitched_image_degrees = 0.00;
1780                     showRotateImage(manage_drone_imagery_standard_process_rotate_stitched_image_id, 'drone_imagery_standard_process_rotate_original_stitched_div', 'manage_drone_imagery_standard_process_rotate_load_div');
1782                     showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1783                 },
1784                 error: function(response){
1785                     alert('Error getting standard process image rotation step!');
1786                     showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1787                 }
1788             });
1790             Workflow.complete("#manage_drone_imagery_standard_process_drone_run_band_step");
1791             Workflow.focus('#manage_drone_imagery_standard_process_workflow', 2);
1792         }
1793     });
1795     jQuery('#drone_imagery_standard_process_rotate_stitched_view').click(function(){
1796         manage_drone_imagery_standard_process_rotate_stitched_image_degrees = parseFloat(jQuery('#drone_imagery_standard_process_rotate_degrees_input').val());
1797         applyShowRotateImage(manage_drone_imagery_standard_process_rotate_stitched_image_id, manage_drone_imagery_standard_process_drone_run_band_project_id, manage_drone_imagery_standard_process_rotate_stitched_image_degrees, 'drone_imagery_standard_process_rotate_original_stitched_div');
1798     });
1800     jQuery('#drone_imagery_standard_process_rotate_stitched_crosshairs').click(function(){
1801         drawRotateCrosshairs(getRandomColor(), 'drone_imagery_standard_process_rotate_original_stitched_div');
1802     });
1804     jQuery('#drone_imagery_standard_process_rotate_stitched_restart').click(function(){
1805         showRotateImage(manage_drone_imagery_standard_process_rotate_stitched_image_id, 'drone_imagery_standard_process_rotate_original_stitched_div', 'manage_drone_imagery_standard_process_rotate_load_div');
1806         manage_drone_imagery_standard_process_rotate_stitched_image_degrees = 0.00;
1807     });
1809     jQuery('#manage_drone_imagery_standard_process_rotate_step').click(function() {
1810         var rotate_stitched_image_degrees_text = jQuery('#drone_imagery_standard_process_rotate_degrees_input').val();
1811         if (rotate_stitched_image_degrees_text == '') {
1812             alert('Please give a number of degrees first! Can be a decimal amount.');
1813             return;
1814         }
1815         if (isNaN(rotate_stitched_image_degrees_text)) {
1816             alert('Please give a number of degrees first! Can be a decimal amount.');
1817             return;
1818         }
1819         manage_drone_imagery_standard_process_rotate_stitched_image_degrees = parseFloat(rotate_stitched_image_degrees_text);
1820         jQuery.ajax({
1821             url : '/api/drone_imagery/rotate_image?image_id='+manage_drone_imagery_standard_process_rotate_stitched_image_id+'&drone_run_band_project_id='+manage_drone_imagery_standard_process_drone_run_band_project_id+'&angle='+manage_drone_imagery_standard_process_rotate_stitched_image_degrees,
1822             beforeSend: function() {
1823                 showManageDroneImagerySection('manage_drone_imagery_loading_div');
1824             },
1825             success: function(response){
1826                 console.log(response);
1827                 manage_drone_imagery_standard_process_rotated_stitched_image_id = response.rotated_image_id;
1828                 showCropImageStart(manage_drone_imagery_standard_process_rotated_stitched_image_id, 'drone_imagery_standard_process_crop_original_stitched_div', 'manage_drone_imagery_standard_process_crop_load_div');
1830                 get_select_box('drone_imagery_parameter_select','plot_polygons_standard_process_previously_saved_image_cropping_templates', {'name':'drone_imagery_standard_process_previously_saved_image_cropping_select', 'id':'drone_imagery_standard_process_previously_saved_image_cropping_select', 'empty':1, 'field_trial_id':manage_drone_imagery_standard_process_field_trial_id, 'parameter':'image_cropping' });
1832                 Workflow.complete("#manage_drone_imagery_standard_process_rotate_step");
1833                 Workflow.focus('#manage_drone_imagery_standard_process_workflow', 3);
1835                 showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1836             },
1837             error: function(response){
1838                 //alert('Error saving standard process rotated image image!');
1839                 showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1840             }
1841         });
1842     });
1844     jQuery(document).on('click', '#manage_drone_imagery_standard_process_cropping_step', function(){
1845         console.log(crop_points);
1846         if (crop_points.length != 4) {
1847             alert('Please click 4 points on the image to draw a rectangle first!');
1848             return false;
1849         }
1850         jQuery.ajax({
1851             url : '/api/drone_imagery/crop_image?image_id='+manage_drone_imagery_standard_process_rotated_stitched_image_id+'&polygon='+JSON.stringify(crop_points)+'&drone_run_band_project_id='+manage_drone_imagery_standard_process_drone_run_band_project_id,
1852             beforeSend: function() {
1853                 showManageDroneImagerySection('manage_drone_imagery_loading_div');
1854             },
1855             success: function(response){
1856                 console.log(response);
1857                 manage_drone_imagery_standard_process_cropped_image_id = response.cropped_image_id;
1858                 if (response.error) {
1859                     alert(response.error);
1860                     return false;
1861                 } else {
1862                     jQuery.ajax({
1863                         url : '/api/drone_imagery/denoise?image_id='+manage_drone_imagery_standard_process_cropped_image_id+'&drone_run_band_project_id='+manage_drone_imagery_standard_process_drone_run_band_project_id,
1864                         success: function(response){
1865                             console.log(response);
1866                             manage_drone_imagery_standard_process_denoised_image_id = response.denoised_image_id;
1867                             remove_background_current_image_id = manage_drone_imagery_standard_process_denoised_image_id;
1868                             remove_background_drone_run_band_project_id = manage_drone_imagery_standard_process_drone_run_band_project_id;
1870                             showRemoveBackgroundHistogramStart(manage_drone_imagery_standard_process_denoised_image_id, 'drone_imagery_standard_process_remove_background_original', 'drone_imagery_standard_process_remove_background_histogram_div', 'manage_drone_imagery_standard_process_remove_background_load_div');
1872                             Workflow.complete("#manage_drone_imagery_standard_process_cropping_step");
1873                             Workflow.focus('#manage_drone_imagery_standard_process_workflow', 4);
1875                             showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1876                         },
1877                         error: function(response){
1878                             alert('Error standard process denoising image!');
1879                             showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1880                         }
1881                     });
1882                 }
1883             },
1884             error: function(response){
1885                 alert('Error standard process cropping image!');
1886                 showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1887             }
1888         });
1889     });
1891     jQuery(document).on('click', '#drone_imagery_standard_process_cropping_use_previous_cropping', function() {
1892         var plot_polygons_use_previously_saved_cropping = jQuery('#drone_imagery_standard_process_previously_saved_image_cropping_select').val();
1893         jQuery.ajax({
1894             url : '/api/drone_imagery/retrieve_parameter_template?plot_polygons_template_projectprop_id='+plot_polygons_use_previously_saved_cropping,
1895             success: function(response){
1896                 console.log(response);
1897                 jQuery.ajax({
1898                     url : '/api/drone_imagery/crop_image?image_id='+manage_drone_imagery_standard_process_rotated_stitched_image_id+'&polygon='+JSON.stringify(response.parameter[0])+'&drone_run_band_project_id='+manage_drone_imagery_standard_process_drone_run_band_project_id,
1899                     beforeSend: function() {
1900                         showManageDroneImagerySection('manage_drone_imagery_loading_div');
1901                     },
1902                     success: function(response){
1903                         console.log(response);
1904                         manage_drone_imagery_standard_process_cropped_image_id = response.cropped_image_id;
1905                         if (response.error) {
1906                             alert(response.error);
1907                             return false;
1908                         } else {
1909                             jQuery.ajax({
1910                                 url : '/api/drone_imagery/denoise?image_id='+manage_drone_imagery_standard_process_cropped_image_id+'&drone_run_band_project_id='+manage_drone_imagery_standard_process_drone_run_band_project_id,
1911                                 success: function(response){
1912                                     console.log(response);
1913                                     manage_drone_imagery_standard_process_denoised_image_id = response.denoised_image_id;
1914                                     remove_background_current_image_id = manage_drone_imagery_standard_process_denoised_image_id;
1915                                     remove_background_drone_run_band_project_id = manage_drone_imagery_standard_process_drone_run_band_project_id;
1917                                     showRemoveBackgroundHistogramStart(manage_drone_imagery_standard_process_denoised_image_id, 'drone_imagery_standard_process_remove_background_original', 'drone_imagery_standard_process_remove_background_histogram_div', 'manage_drone_imagery_standard_process_remove_background_load_div');
1919                                     Workflow.complete("#manage_drone_imagery_standard_process_cropping_step");
1920                                     Workflow.focus('#manage_drone_imagery_standard_process_workflow', 4);
1922                                     showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1923                                 },
1924                                 error: function(response){
1925                                     alert('Error standard process denoising image!');
1926                                     showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1927                                 }
1928                             });
1929                         }
1930                     },
1931                     error: function(response){
1932                         showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1933                         alert('Error cropping image!');
1934                     }
1935                 });
1936             },
1937             error: function(response){
1938                 alert('Error retrieving saved cropping template in standard process!');
1939                 showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1940             }
1941         });
1942         return;
1943     });
1945     jQuery('#drone_imagery_standard_process_remove_background_defined_percentage_submit').click(function(){
1946         var drone_imagery_remove_background_lower_percentage = Number(jQuery('#drone_imagery_standard_process_remove_background_lower_threshold_percentage').val());
1947         var drone_imagery_remove_background_upper_percentage = Number(jQuery('#drone_imagery_standard_process_remove_background_upper_threshold_percentage').val());
1949         //var threshold_value_return = calculateThresholdPercentageValues('drone_imagery_remove_background_original', drone_imagery_remove_background_lower_percentage, drone_imagery_remove_background_upper_percentage);
1951         manage_drone_imagery_standard_process_remove_background_threshold_percentage_save(manage_drone_imagery_standard_process_denoised_image_id, manage_drone_imagery_standard_process_current_threshold_background_removed_type, manage_drone_imagery_standard_process_drone_run_band_project_id, drone_imagery_remove_background_lower_percentage, drone_imagery_remove_background_upper_percentage);
1952     });
1954     function manage_drone_imagery_standard_process_remove_background_threshold_percentage_save(image_id, image_type, drone_run_band_project_id, lower_threshold_percentage, upper_threshold_percentage){
1955         jQuery.ajax({
1956             type: 'POST',
1957             url: '/api/drone_imagery/remove_background_percentage_save',
1958             dataType: "json",
1959             beforeSend: function() {
1960                 showManageDroneImagerySection('manage_drone_imagery_loading_div');
1961             },
1962             data: {
1963                 'image_id': image_id,
1964                 'image_type_list': image_type,
1965                 'drone_run_band_project_id': drone_run_band_project_id,
1966                 'lower_threshold_percentage': lower_threshold_percentage,
1967                 'upper_threshold_percentage': upper_threshold_percentage
1968             },
1969             success: function(response){
1970                 console.log(response);
1971                 if(response.error) {
1972                     alert(response.error);
1973                 }
1974                 manage_drone_imagery_standard_process_removed_background_image_id = response[0]['removed_background_image_id'];
1976                 showPlotPolygonStart(manage_drone_imagery_standard_process_removed_background_image_id, drone_run_band_project_id, 'drone_imagery_standard_process_plot_polygons_original_stitched_div', 'drone_imagery_standard_process_plot_polygons_top_section', 'manage_drone_imagery_standard_process_plot_polygons_load_div');
1978                 showPlotPolygonTableStart(manage_drone_imagery_standard_process_field_trial_id, 'drone_imagery_standard_process_trial_layout_div', 'drone_imagery_standard_process_layout_table')
1980                 get_select_box('drone_imagery_parameter_select','plot_polygons_standard_process_previously_saved_plot_polygon_templates', {'name': 'plot_polygons_standard_process_template_select', 'id': 'plot_polygons_standard_process_template_select', 'empty':1, 'field_trial_id':manage_drone_imagery_standard_process_field_trial_id, 'parameter':'plot_polygons' });
1982                 Workflow.complete("#drone_imagery_standard_process_remove_background_defined_percentage_submit");
1983                 Workflow.focus('#manage_drone_imagery_standard_process_workflow', 5);
1985                 showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1986             },
1987             error: function(response){
1988                 //alert('Error saving standard process removed background image!');
1989                 showManageDroneImagerySection('manage_drone_imagery_standard_process_div');
1990             }
1991         });
1992     }
1994     jQuery('#plot_polygons_standard_process_use_previously_saved_template').click(function() {
1995         var plot_polygons_use_previously_saved_template = jQuery('#plot_polygons_standard_process_template_select').val();
1996         if (plot_polygons_use_previously_saved_template == '') {
1997             alert('Please select a previously saved template before trying to apply it. If there is not a template listed, then you can create one using the templating tool above.');
1998             return;
1999         }
2001         jQuery.ajax({
2002             url : '/api/drone_imagery/retrieve_parameter_template?plot_polygons_template_projectprop_id='+plot_polygons_use_previously_saved_template,
2003             success: function(response){
2004                 console.log(response);
2006                 drone_imagery_plot_polygons_display = response.parameter;
2007                 drone_imagery_plot_polygons = response.parameter;
2009                 draw_canvas_image(background_image_url, 0);
2010                 droneImageryDrawLayoutTable(field_trial_layout_response, drone_imagery_plot_polygons, 'drone_imagery_standard_process_trial_layout_div', 'drone_imagery_standard_process_layout_table');
2011                 droneImageryRectangleLayoutTable(drone_imagery_plot_polygons, 'drone_imagery_standard_process_generated_polygons_div', 'drone_imagery_standard_process_generated_polygons_table', 'drone_imagery_standard_process_plot_polygons_generated_assign', 'drone_imagery_standard_process_plot_polygons_submit_bottom');
2012             },
2013             error: function(response){
2014                 alert('Error retrieving plot polygons template in standard process!');
2015             }
2016         });
2017         return;
2018     });
2020     jQuery('#drone_imagery_standard_process_plot_polygons_rectangles_apply').click(function() {
2021         plot_polygons_display_points = [];
2022         plot_polygons_ind_points = [];
2023         plot_polygons_ind_4_points = [];
2025         var num_rows_val = jQuery('#drone_imagery_standard_process_plot_polygons_num_rows').val();
2026         var num_cols_val = jQuery('#drone_imagery_standard_process_plot_polygons_num_cols').val();
2027         var section_top_row_left_offset_val = jQuery('#drone_imagery_standard_process_plot_polygons_top_row_left_offset').val();
2028         var section_top_row_right_offset_val = jQuery('#drone_imagery_standard_process_plot_polygons_top_row_right_offset').val();
2029         var section_bottom_row_left_offset_val = jQuery('#drone_imagery_standard_process_plot_polygons_bottom_row_left_offset').val();
2030         var section_left_column_top_offset_val = jQuery('#drone_imagery_standard_process_plot_polygons_left_column_top_offset').val();
2031         var section_left_column_bottom_offset_val = jQuery('#drone_imagery_standard_process_plot_polygons_left_column_bottom_offset').val();
2032         var section_right_column_bottom_offset_val = jQuery('#drone_imagery_standard_process_plot_polygons_right_col_bottom_offset').val();
2034         plotPolygonsRectanglesApply(num_rows_val, num_cols_val, section_top_row_left_offset_val, section_bottom_row_left_offset_val, section_left_column_top_offset_val, section_left_column_bottom_offset_val, section_top_row_right_offset_val, section_right_column_bottom_offset_val, 'drone_imagery_standard_process_generated_polygons_div', 'drone_imagery_standard_process_generated_polygons_table', 'drone_imagery_standard_process_plot_polygons_generated_assign', 'drone_imagery_standard_process_plot_polygons_submit_bottom', 'drone_imagery_standard_process_plot_polygons_active_templates');
2035     });
2037     var drone_imagery_standard_process_plot_polygon_click_type = '';
2038     jQuery('#drone_imagery_standard_process_plot_polygons_top_left_click').click(function(){
2039         alert('Now click the top left corner of your field on the image below.');
2040         drone_imagery_standard_process_plot_polygon_click_type = 'top_left';
2041     });
2042     jQuery('#drone_imagery_standard_process_plot_polygons_top_right_click').click(function(){
2043         alert('Now click the top right corner of your field on the image below.');
2044         drone_imagery_standard_process_plot_polygon_click_type = 'top_right';
2045     });
2046     jQuery('#drone_imagery_standard_process_plot_polygons_bottom_left_click').click(function(){
2047         alert('Now click the bottom left corner of your field on the image below.');
2048         drone_imagery_standard_process_plot_polygon_click_type = 'bottom_left';
2049     });
2050     jQuery('#drone_imagery_standard_process_plot_polygons_bottom_right_click').click(function(){
2051         alert('Now click the bottom right corner of your field on the image below.');
2052         drone_imagery_standard_process_plot_polygon_click_type = 'bottom_right';
2053     });
2054     jQuery(document).on('click', '#drone_imagery_standard_process_plot_polygons_get_distance', function(){
2055         alert('Click on two points in image. The distance will be returned.');
2056         drone_imagery_standard_process_plot_polygon_click_type = 'get_distance';
2057         return false;
2058     });
2060     jQuery(document).on('click', '#drone_imagery_standard_process_plot_polygons_clear', function(){
2061         plot_polygons_display_points = [];
2062         plot_polygons_ind_points = [];
2063         plot_polygons_ind_4_points = [];
2064         drone_imagery_plot_polygons = {};
2065         drone_imagery_plot_generated_polygons = {};
2066         drone_imagery_plot_polygons_display = {};
2067         plot_polygons_generated_polygons = [];
2068         drone_imagery_plot_polygons_removed_numbers = [];
2069         plot_polygons_template_dimensions = [];
2070         ctx.clearRect(0, 0, canvas.width, canvas.height);
2071         draw_canvas_image(background_image_url, 0);
2072         jQuery('#drone_imagery_standard_process_generated_polygons_div').html('');
2073         droneImageryDrawLayoutTable(field_trial_layout_response, drone_imagery_plot_polygons, 'drone_imagery_standard_process_trial_layout_div', 'drone_imagery_standard_process_layout_table');
2074         droneImageryDrawPlotPolygonActiveTemplatesTable("drone_imagery_standard_process_plot_polygons_active_templates", plot_polygons_template_dimensions);
2075     });
2077     jQuery(document).on('click', '#drone_imagery_standard_process_plot_polygons_clear_one', function(){
2078         jQuery('#drone_imagery_plot_polygon_remove_polygon').modal('show');
2079         return false;
2080     });
2082     jQuery(document).on('click', '#drone_imagery_standard_process_plot_polygons_generated_assign', function() {
2083         generatePlotPolygonAssignments('drone_imagery_standard_process_trial_layout_div', 'drone_imagery_standard_process_layout_table');
2085         jQuery('input[name="drone_imagery_plot_polygons_autocomplete"]').each(function() {
2086             var stock_name = this.value;
2087             if (stock_name != '') {
2088                 var polygon = drone_imagery_plot_generated_polygons[jQuery(this).data('generated_polygon_key')];
2089                 drone_imagery_plot_polygons[stock_name] = polygon;
2090             }
2091         });
2092     });
2094     jQuery(document).on('click', 'button[name=drone_imagery_standard_process_plot_polygons_submit_bottom]', function(){
2095         jQuery.ajax({
2096             type: 'POST',
2097             url: '/api/drone_imagery/save_plot_polygons_template',
2098             dataType: "json",
2099             data: {
2100                 'drone_run_band_project_id': manage_drone_imagery_standard_process_drone_run_band_project_id,
2101                 'stock_polygons': JSON.stringify(drone_imagery_plot_polygons)
2102             },
2103             success: function(response){
2104                 console.log(response);
2105                 if(response.error) {
2106                     alert(response.error);
2107                 } else {
2108                     Workflow.complete("#drone_imagery_standard_process_generated_polygons_div");
2109                     Workflow.focus('#manage_drone_imagery_standard_process_workflow', 6);
2110                 }
2111             },
2112             error: function(response){
2113                 //alert('Error saving standard process assigned plot polygons!')
2114             }
2115         });
2117         jQuery('#manage_drone_imagery_standard_process_drone_run_bands_apply_table').DataTable({
2118             destroy : true,
2119             ajax : '/api/drone_imagery/drone_run_bands?select_checkbox_name=drone_run_standard_process_band_apply_select&drone_run_project_id='+manage_drone_imagery_standard_process_drone_run_project_id+'&select_all=1&disable=1'
2120         });
2121     });
2123     jQuery('#manage_drone_imagery_standard_process_drone_run_band_apply_step').click(function(){
2124         manage_drone_imagery_standard_process_apply_drone_run_band_project_ids = [];
2125         jQuery('input[name="drone_run_standard_process_band_apply_select"]:checked').each(function() {
2126             manage_drone_imagery_standard_process_apply_drone_run_band_project_ids.push(jQuery(this).val());
2127         });
2128         if (manage_drone_imagery_standard_process_apply_drone_run_band_project_ids.length < 1){
2129             alert('Please select at least one other drone run band!');
2130             return false;
2131         } else {
2132             Workflow.complete("#manage_drone_imagery_standard_process_drone_run_band_apply_step");
2133             Workflow.focus('#manage_drone_imagery_standard_process_workflow', 7);
2134         }
2135     });
2137     jQuery('#manage_drone_imagery_standard_process_indices_step').click(function(){
2138         manage_drone_imagery_standard_process_apply_drone_run_band_vegetative_indices = [];
2139         jQuery('input[name="drone_imagery_standard_process_apply_indices_select"]:checked').each(function() {
2140             manage_drone_imagery_standard_process_apply_drone_run_band_vegetative_indices.push(jQuery(this).val());
2141         });
2142         if (manage_drone_imagery_standard_process_apply_drone_run_band_vegetative_indices.length < 1){
2143             alert('Please select at least one vegetative index!');
2144             return false;
2145         } else {
2146             jQuery.ajax({
2147                 type: 'GET',
2148                 url: '/api/drone_imagery/get_weeks_after_planting_date?drone_run_project_id='+manage_drone_imagery_standard_process_drone_run_project_id,
2149                 dataType: "json",
2150                 beforeSend: function (){
2151                     jQuery('#working_modal').modal('show');
2152                 },
2153                 success: function(response){
2154                     jQuery('#working_modal').modal('hide');
2155                     console.log(response);
2156                     if (response.error) {
2157                         alert(response.error);
2158                     }
2160                     var html = "<center><b>Field Trial Planting Date</b>: "+response.planting_date+"<br/><b>Drone Run Date</b>: "+response.drone_run_date+"<br/><b>Number of Weeks</b>: "+response.rounded_time_difference_weeks+"<br/><b>Number of Weeks Ontology Term</b>: "+response.time_ontology_week_term+"<br/><b>Number of Days</b>:"+response.time_difference_days+"<br/><b>Number of Days Ontology Term</b>: "+response.time_ontology_day_term+"<br/><br/></center>";
2161                     jQuery('#drone_imagery_standard_process_week_term_div').html(html);
2163                     manage_drone_imagery_standard_process_phenotype_time = response.time_ontology_day_cvterm_id;
2164                 },
2165                 error: function(response){
2166                     alert('Error getting time terms!');
2167                     jQuery('#working_modal').modal('hide');
2168                 }
2169             });
2171             Workflow.complete("#manage_drone_imagery_standard_process_indices_step");
2172             Workflow.focus('#manage_drone_imagery_standard_process_workflow', 8);
2173         }
2174     });
2176     jQuery('#manage_drone_imagery_standard_process_phenotypes_step').click(function(){
2177         var selected = [];
2179         if (manage_drone_imagery_standard_process_phenotype_time == '') {
2180             alert('Time of phenotype not set! This should not happen! Please contact us.');
2181             return false;
2182         }
2184         jQuery('input[name="drone_imagery_standard_process_phenotypes_select"]:checked').each(function() {
2185             selected.push(jQuery(this).val());
2186         });
2187         if (selected.length < 1){
2188             alert('Please select at least one phenotype!');
2189             return false;
2190         } else {
2191             jQuery.ajax({
2192                 type: 'POST',
2193                 url: '/api/drone_imagery/standard_process_apply',
2194                 dataType: "json",
2195                 data: {
2196                     'drone_run_project_id': manage_drone_imagery_standard_process_drone_run_project_id,
2197                     'drone_run_band_project_id': manage_drone_imagery_standard_process_drone_run_band_project_id,
2198                     'apply_drone_run_band_project_ids': JSON.stringify(manage_drone_imagery_standard_process_apply_drone_run_band_project_ids),
2199                     'vegetative_indices': JSON.stringify(manage_drone_imagery_standard_process_apply_drone_run_band_vegetative_indices),
2200                     'phenotype_types': JSON.stringify(selected),
2201                     'time_cvterm_id': manage_drone_imagery_standard_process_phenotype_time,
2202                     'standard_process_type': 'minimal'
2203                 },
2204                 success: function(response){
2205                     console.log(response);
2206                     if(response.error) {
2207                         alert(response.error);
2208                     }
2209                 },
2210                 error: function(response){
2211                     //alert('Error saving standard process assigned plot polygons!')
2212                 }
2213             });
2215             Workflow.complete("#manage_drone_imagery_standard_process_phenotypes_step");
2216             jQuery('#drone_imagery_standard_process_complete_dialog').modal('show');
2217         }
2218     });
2220     jQuery('#drone_imagery_standard_process_complete_dialog').on('hidden.bs.modal', function () {
2221         location.reload();
2222     })
2224     //
2225     // Standard process on raw images
2226     //
2228     var manage_drone_imagery_standard_process_raw_images_field_trial_id;
2229     var manage_drone_imagery_standard_process_raw_images_drone_run_id;
2230     var manage_drone_imagery_standard_process_raw_images_drone_run_band_id;
2231     var manage_drone_imagery_standard_process_raw_images_image_id;
2232     var manage_drone_imagery_standard_process_raw_images_stack_image_ids;
2233     var manage_drone_imagery_standard_process_raw_images_rotated_image_id;
2234     var manage_drone_imagery_standard_process_raw_images_polygon = [];
2235     var manage_drone_imagery_standard_process_raw_images_previous_polygon;
2236     var manage_drone_imagery_standard_process_raw_images_rotate_angle = 0.00;
2237     var manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new = {}; 
2238     var ctx;
2239     var dronecroppingImg;
2241     jQuery(document).on('click', 'button[name="project_drone_imagery_stadard_process_raw_images_add_images"]', function(){
2242         manage_drone_imagery_standard_process_raw_images_field_trial_id = jQuery(this).data('field_trial_id');
2243         manage_drone_imagery_standard_process_raw_images_drone_run_id = jQuery(this).data('drone_run_project_id');
2244         jQuery('#upload_drone_imagery_additional_raw_images_drone_run_id').val(manage_drone_imagery_standard_process_raw_images_drone_run_id);
2245         jQuery('#upload_drone_imagery_additional_raw_images_field_trial_id').val(manage_drone_imagery_standard_process_raw_images_field_trial_id);
2246         jQuery('#upload_drone_imagery_standard_process_additional_raw_images_dialog').modal('show');
2247     });
2249     jQuery('#upload_drone_imagery_additional_raw_images_submit').click(function(){
2250         standard_process_upload_additional_raw_images();
2251     });
2253     function standard_process_upload_additional_raw_images() {
2254         jQuery('#upload_drone_imagery_additional_raw_images_form').attr("action", "/api/drone_imagery/upload_drone_imagery_additional_raw_images");
2255         jQuery("#upload_drone_imagery_additional_raw_images_form").submit();
2256     }
2258     jQuery('#upload_drone_imagery_additional_raw_images_form').iframePostForm({
2259         json: true,
2260         post: function () {
2261             jQuery('#working_modal').modal("show");
2262         },
2263         complete: function (response) {
2264             console.log(response);
2265             jQuery('#working_modal').modal("hide");
2266             if (response.error) {
2267                 alert(response.error);
2268             }
2269             else {
2270                 location.reload;
2271             }
2272         }
2273     });
2275     jQuery(document).on('click', 'button[name="project_drone_imagery_standard_process_raw_images"]', function() {
2276         showManageDroneImagerySection('manage_drone_imagery_standard_process_raw_images_div');
2278         manage_drone_imagery_standard_process_raw_images_field_trial_id = jQuery(this).data('field_trial_id');
2279         manage_drone_imagery_standard_process_raw_images_drone_run_id = jQuery(this).data('drone_run_project_id');
2281         get_select_box('micasense_aligned_raw_images_grid','drone_imagery_standard_process_raw_images_image_id_select_div', {'name': 'drone_imagery_standard_process_raw_images_image_id_select', 'id': 'drone_imagery_standard_process_raw_images_image_id_select', 'empty':1, 'drone_run_project_id':manage_drone_imagery_standard_process_raw_images_drone_run_id });
2283         get_select_box('plot_polygon_templates_partial','drone_imagery_standard_process_raw_images_previous_polygons_div', {'name': 'drone_imagery_standard_process_raw_images_plot_sizes_select', 'id':'drone_imagery_standard_process_raw_images_plot_sizes_select', 'drone_run_project_id':manage_drone_imagery_standard_process_raw_images_drone_run_id, 'empty':1});
2285         jQuery.ajax({
2286             url : '/api/drone_imagery/get_drone_run_image_counts?drone_run_id='+manage_drone_imagery_standard_process_raw_images_drone_run_id,
2287             success: function(response){
2288                 console.log(response);
2289                 var html = '<table class="table table-bordered table-hover" id="manage_drone_imagery_standard_process_assigned_plot_images"><thead><tr><th>Plot Name</th><th>Plot Number</th><th>Image Counts</th></thead><tbody>';
2290                 for (var i=0; i<response.data.length; i++) {
2291                     html = html + '<tr><td>'+response.data[i]['plot_name'] + '</td><td>' + response.data[i]['plot_number'] + '</td><td>' + response.data[i]['image_counts'] + '</td></tr>';
2292                 }
2293                 html = html +'</tbody></table>';
2294                 jQuery('#drone_imagery_standard_process_raw_images_assigned_plot_images').html(html);
2295                 jQuery('#manage_drone_imagery_standard_process_assigned_plot_images').DataTable();
2296             },
2297             error: function(response){
2298                 alert('Error retrieving drone run image counts!')
2299             }
2300         });
2301     });
2303     jQuery(document).on('click', 'span[name="drone_imagery_standard_process_raw_images_image_id_select"]', function() {
2304         manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new = {};
2305         crop_points = [];
2306         plot_polygons_generated_polygons = [];
2308         manage_drone_imagery_standard_process_raw_images_image_id = jQuery(this).data('image_id');
2309         manage_drone_imagery_standard_process_raw_images_rotated_image_id = jQuery(this).data('image_id');
2310         manage_drone_imagery_standard_process_raw_images_stack_image_ids = jQuery(this).data('image_ids');
2312         jQuery.ajax({
2313             url : '/api/drone_imagery/get_image?size=original_converted&image_id='+manage_drone_imagery_standard_process_raw_images_image_id,
2314             success: function(response){
2315                 console.log(response);
2317                 background_image_width = response.image_width;
2318                 background_image_height = response.image_height;
2320                 var canvas = document.getElementById('drone_imagery_standard_process_raw_images_show');
2321                 ctx = canvas.getContext('2d');
2322                 var image = new Image();
2323                 image.onload = function () {
2324                     canvas.width = this.naturalWidth;
2325                     canvas.height = this.naturalHeight;
2326                     ctx.drawImage(this, 0, 0);
2327                 };
2328                 image.src = response.image_url;
2329                 dronecroppingImg = canvas;
2330                 dronecroppingImg.onmousedown = GetCoordinatesCroppedImage;
2332                 manage_drone_imagery_standard_process_raw_images_drone_run_band_id = response.drone_run_band_project_id;
2333             },
2334             error: function(response){
2335                 alert('Error retrieving image!')
2336             }
2337         });
2338     });
2340     jQuery('#drone_imagery_standard_process_raw_images_draw_polygons').click(function(){
2341         var manage_drone_imagery_standard_process_raw_images_num_rows = jQuery('#drone_imagery_standard_process_raw_images_number_rows').val();
2342         var manage_drone_imagery_standard_process_raw_images_num_columns = jQuery('#drone_imagery_standard_process_raw_images_number_columns').val();
2343     
2344         if (manage_drone_imagery_standard_process_raw_images_num_rows == '') {
2345             alert('Please give the number of rows in the area of interest!');
2346             return false;
2347         }
2348         if (manage_drone_imagery_standard_process_raw_images_num_columns == '') {
2349             alert('Please give the number of columns in the area of interest!');
2350             return false;
2351         }
2353         if (crop_points.length < 4) {
2354             alert('Please select an area of interest on the image first by clicking the four corner points.');
2355             return false;
2356         }
2358         plot_polygons_num_rows_generated = parseInt(manage_drone_imagery_standard_process_raw_images_num_rows);
2359         plot_polygons_num_cols_generated = parseInt(manage_drone_imagery_standard_process_raw_images_num_columns);
2361         var section_width = background_image_width;
2362         var section_height = background_image_height;
2363         var section_top_row_left_offset = parseInt(crop_points[0]['x']);
2364         var section_bottom_row_left_offset = parseInt(crop_points[3]['x']);
2365         var section_left_column_top_offset = parseInt(crop_points[0]['y']);
2366         var section_left_column_bottom_offset = parseInt(background_image_height - crop_points[3]['y']);
2367         var section_top_row_right_offset = parseInt(background_image_width - crop_points[1]['x']);
2368         var section_right_column_bottom_offset = parseInt(background_image_height - crop_points[2]['y']);
2370         var total_gradual_left_shift = section_bottom_row_left_offset - section_top_row_left_offset;
2371         var col_left_shift_increment = total_gradual_left_shift / plot_polygons_num_rows_generated;
2373         var total_gradual_vertical_shift = section_right_column_bottom_offset - section_left_column_bottom_offset;
2374         var col_vertical_shift_increment = total_gradual_vertical_shift / plot_polygons_num_cols_generated;
2376         var col_width = (section_width - section_top_row_left_offset - section_top_row_right_offset) / plot_polygons_num_cols_generated;
2377         var row_height = (section_height - section_left_column_top_offset - section_left_column_bottom_offset) / plot_polygons_num_rows_generated;
2379         var x_pos = section_top_row_left_offset;
2380         var y_pos = section_left_column_top_offset;
2382         var row_num = 1;
2383         for (var i=0; i<plot_polygons_num_rows_generated; i++) {
2384             for (var j=0; j<plot_polygons_num_cols_generated; j++) {
2385                 var x_pos_val = x_pos;
2386                 var y_pos_val = y_pos;
2387                 plot_polygons_generated_polygons.push([
2388                     {x:x_pos_val, y:y_pos_val},
2389                     {x:x_pos_val + col_width, y:y_pos_val},
2390                     {x:x_pos_val + col_width, y:y_pos_val + row_height},
2391                     {x:x_pos_val, y:y_pos_val + row_height}
2392                 ]);
2393                 x_pos = x_pos + col_width;
2394                 y_pos = y_pos - col_vertical_shift_increment;
2395             }
2396             x_pos = section_top_row_left_offset + (row_num * col_left_shift_increment);
2397             y_pos = y_pos + row_height + total_gradual_vertical_shift;
2398             row_num = row_num + 1;
2399         }
2400         console.log(plot_polygons_generated_polygons);
2402         plot_polygons_total_height_generated = row_height * plot_polygons_num_rows_generated;
2403         plot_polygons_number_generated = plot_polygons_generated_polygons.length;
2405         manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new = {}; 
2406         var drone_imagery_plot_polygons_display_new = {};
2408         for (var i=0; i<plot_polygons_generated_polygons.length; i++) {
2409             plot_polygons_ind_4_points = plot_polygons_generated_polygons[i];
2410             plot_polygons_display_points = plot_polygons_ind_4_points;
2411             if (plot_polygons_display_points.length == 4) {
2412                 plot_polygons_display_points.push(plot_polygons_ind_4_points[0]);
2413             }
2414             drawPolyline(plot_polygons_display_points);
2415             drawWaypoints(plot_polygons_display_points, i, 0);
2416             drone_imagery_plot_generated_polygons[i] = plot_polygons_ind_4_points;
2417             manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new[i] = plot_polygons_ind_4_points;
2418             drone_imagery_plot_polygons_display[i] = plot_polygons_display_points;
2419             drone_imagery_plot_polygons_display_new[i] = plot_polygons_display_points;
2420         }
2422         plot_polygons_template_dimensions.push({
2423             'num_rows':plot_polygons_num_rows_generated,
2424             'num_cols':plot_polygons_num_cols_generated,
2425             'total_plot_polygons':plot_polygons_num_rows_generated*plot_polygons_num_cols_generated,
2426             'plot_polygons':manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new,
2427             'plot_polygons_display':drone_imagery_plot_polygons_display_new
2428         });
2429         console.log(plot_polygons_template_dimensions);
2431         var table_html = '<table class="table table-bordered table-hover"><thead><tr><th>Generated Index</th><th>Plot Number</th></tr></thead><tbody>';
2432         for (var gen_index in manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new) {
2433             if (manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new.hasOwnProperty(gen_index)) {
2434                 table_html = table_html + '<tr><td>'+gen_index+'</td><td><input type="text" class="form-control" placeholder="e.g. 1001" name="manage_drone_imagery_standard_process_raw_images_given_plot_number" data-generated_index="'+gen_index+'"></td></tr>';
2435             }
2436         }
2437         table_html = table_html + '</tbody></table>';
2439         jQuery('#drone_imagery_standard_process_raw_images_polygon_assign_table').html(table_html);
2440     });
2442     jQuery('#drone_imagery_standard_process_raw_images_assign_plot').click(function(){
2444         var manage_drone_imagery_standard_process_raw_images_partial_template_name = jQuery('#drone_imagery_standard_process_raw_images_partial_template_name').val();
2445         if (manage_drone_imagery_standard_process_raw_images_partial_template_name == '') {
2446             alert('Please give a partial template name');
2447             return false;
2448         }
2449         var manage_drone_imagery_standard_process_raw_images_given_plot_numbers = {};
2450         jQuery('input[name="manage_drone_imagery_standard_process_raw_images_given_plot_number"]').each(function() {
2451             if (jQuery(this).val() != '') {
2452                 manage_drone_imagery_standard_process_raw_images_given_plot_numbers[jQuery(this).data('generated_index')] = jQuery(this).val();
2453             }
2454         });
2455         if (Object.keys(manage_drone_imagery_standard_process_raw_images_given_plot_numbers).length < 1) {
2456             alert('Please give the plot numbers corresponding to the generated index numbers of the plot polygons!');
2457             return false;
2458         }
2460         jQuery.ajax({
2461             url : '/api/drone_imagery/manual_assign_plot_polygon',
2462             type : 'POST',
2463             data : {
2464                 'field_trial_id':manage_drone_imagery_standard_process_raw_images_field_trial_id,
2465                 'drone_run_project_id':manage_drone_imagery_standard_process_raw_images_drone_run_id,
2466                 'image_ids':manage_drone_imagery_standard_process_raw_images_stack_image_ids,
2467                 'polygon':JSON.stringify(manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new),
2468                 'polygon_plot_numbers':JSON.stringify(manage_drone_imagery_standard_process_raw_images_given_plot_numbers),
2469                 'angle_rotated':manage_drone_imagery_standard_process_raw_images_rotate_angle,
2470                 'partial_template_name':manage_drone_imagery_standard_process_raw_images_partial_template_name
2471             },
2472             success: function(response){
2473                 console.log(response);
2474                 if (response.error) {
2475                     alert(response.error);
2476                 } else if (response.warning) {
2477                     alert(response.warning);
2478                 } else {
2479                     get_select_box('plot_polygon_templates_partial','drone_imagery_standard_process_raw_images_previous_polygons_div', {'name': 'drone_imagery_standard_process_raw_images_plot_sizes_select', 'id':'drone_imagery_standard_process_raw_images_plot_sizes_select', 'drone_run_project_id':manage_drone_imagery_standard_process_raw_images_drone_run_id, 'empty':1});
2481                     jQuery.ajax({
2482                         url : '/api/drone_imagery/get_drone_run_image_counts?drone_run_id='+manage_drone_imagery_standard_process_raw_images_drone_run_id,
2483                         success: function(response){
2484                             console.log(response);
2485                             var html = '<table class="table table-bordered table-hover" id="manage_drone_imagery_standard_process_assigned_plot_images"><thead><tr><th>Plot Name</th><th>Plot Number</th><th>Image Counts</th></thead><tbody>';
2486                             for (var i=0; i<response.data.length; i++) {
2487                                 html = html + '<tr><td>'+response.data[i]['plot_name'] + '</td><td>' + response.data[i]['plot_number'] + '</td><td>' + response.data[i]['image_counts'] + '</td></tr>';
2488                             }
2489                             html = html +'</tbody></table>';
2490                             jQuery('#drone_imagery_standard_process_raw_images_assigned_plot_images').html(html);
2491                             jQuery('#manage_drone_imagery_standard_process_assigned_plot_images').DataTable();
2492                         },
2493                         error: function(response){
2494                             alert('Error retrieving drone run image counts!')
2495                         }
2496                     });
2498                     //alert('Plot-images saved!');
2499                 }
2500             },
2501             error: function(response){
2502                 alert('Error cropping and saving plot images!')
2503             }
2504         });
2505         return false;
2506     });
2508     jQuery('#drone_imagery_standard_process_raw_images_rotate_image').click(function(){
2509         var rotate_stitched_image_degrees = parseFloat(jQuery('#drone_imagery_standard_process_raw_images_rotate_degrees_input').val());
2510         applyShowRotateImage(manage_drone_imagery_standard_process_raw_images_image_id, manage_drone_imagery_standard_process_raw_images_drone_run_band_id, rotate_stitched_image_degrees, 'drone_imagery_standard_process_raw_images_show');
2511         manage_drone_imagery_standard_process_raw_images_rotate_angle = rotate_stitched_image_degrees;
2512     });
2514     jQuery('#drone_imagery_standard_process_raw_images_clear_polygon').click(function(){
2515         crop_points = [];
2516         manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new = {};
2517         plot_polygons_generated_polygons = [];
2519         jQuery.ajax({
2520             url : '/api/drone_imagery/get_image?size=original_converted&image_id='+manage_drone_imagery_standard_process_raw_images_image_id,
2521             success: function(response){
2522                 console.log(response);
2524                 var canvas = document.getElementById('drone_imagery_standard_process_raw_images_show');
2525                 ctx = canvas.getContext('2d');
2526                 var image = new Image();
2527                 image.onload = function () {
2528                     canvas.width = this.naturalWidth;
2529                     canvas.height = this.naturalHeight;
2530                     ctx.drawImage(this, 0, 0);
2531                 };
2532                 image.src = response.image_url;
2533                 dronecroppingImg = canvas;
2534                 dronecroppingImg.onmousedown = GetCoordinatesCroppedImage;
2535             },
2536             error: function(response){
2537                 alert('Error retrieving image!')
2538             }
2539         });
2540     });
2542     jQuery('#drone_imagery_standard_process_raw_images_save_polygon').click(function() {
2543         if (crop_points.length != 4) {
2544             alert('Click the four corners of the plot in the image first!');
2545             return false;
2546         }
2547         else {
2548             manage_drone_imagery_standard_process_raw_images_polygon = crop_points;
2549         }
2550     });
2552     jQuery('#drone_imagery_standard_process_raw_images_paste_polygon').click(function(){
2553         if (manage_drone_imagery_standard_process_raw_images_polygon.length != 4) {
2554             alert('First save a plot-polygon!');
2555             return false;
2556         }
2557         else {
2558             drone_imagery_standard_process_plot_polygon_click_type = 'standard_process_raw_images_paste_polygon';
2559             alert('Now click a point on the image where to paste the top-left corner of the saved polygon.');
2560         }
2561     });
2563     jQuery('#drone_imagery_standard_process_raw_images_paste_previous_polygon').click(function(){
2564         manage_drone_imagery_standard_process_raw_images_previous_polygon = jQuery('#drone_imagery_standard_process_raw_images_plot_sizes_select').val();
2565         console.log(manage_drone_imagery_standard_process_raw_images_previous_polygon);
2566         if (manage_drone_imagery_standard_process_raw_images_previous_polygon == '') {
2567             alert('To do this first select a previously used polygon, if there exists one!');
2568             return false;
2569         }
2570         drone_imagery_standard_process_plot_polygon_click_type = 'standard_process_raw_images_paste_previous_polygon';
2571         alert('Now click a point on the image where to paste the top-left corner of the saved polygon.');
2572     });
2574     //
2575     // Phenotype calc buttons
2576     //
2578     jQuery(document).on('click', 'button[name="project_drone_imagery_phenotype_run"]', function(){
2579         manage_drone_imagery_standard_process_drone_run_project_id = jQuery(this).data('drone_run_project_id');
2581         jQuery.ajax({
2582             type: 'GET',
2583             url: '/api/drone_imagery/get_weeks_after_planting_date?drone_run_project_id='+manage_drone_imagery_standard_process_drone_run_project_id,
2584             dataType: "json",
2585             beforeSend: function (){
2586                 jQuery('#working_modal').modal('show');
2587             },
2588             success: function(response){
2589                 jQuery('#working_modal').modal('hide');
2590                 console.log(response);
2591                 if (response.error) {
2592                     alert(response.error);
2593                 }
2595                 var html = "<center><b>Field Trial Planting Date</b>: "+response.planting_date+"<br/><b>Drone Run Date</b>: "+response.drone_run_date+"<br/><b>Number of Weeks</b>: "+response.rounded_time_difference_weeks+"<br/><b>Number of Weeks Ontology Term</b>: "+response.time_ontology_week_term+"<br/><b>Number of Days</b>:"+response.time_difference_days+"<br/><b>Number of Days Ontology Term</b>: "+response.time_ontology_day_term+"<br/><br/></center>";
2596                 jQuery('#drone_imagery_week_term_div').html(html);
2598                 manage_drone_imagery_standard_process_phenotype_time = response.time_ontology_day_cvterm_id;
2599             },
2600             error: function(response){
2601                 alert('Error getting time terms!');
2602                 jQuery('#working_modal').modal('hide');
2603             }
2604         });
2606         jQuery('#drone_imagery_calc_phenotypes_trial_dialog').modal('show');
2607     });
2609     jQuery('#drone_imagery_calculate_phenotypes_zonal_stats_trial_select').click(function(){
2610         if (manage_drone_imagery_standard_process_phenotype_time == '') {
2611             alert('Time of phenotype not set! This should not happen so please contact us!');
2612             return false;
2613         }
2615         alert("Phenotype generation will occur in the background. You can check the indicator on this page by refreshing the page.");
2617         jQuery.ajax({
2618             type: 'GET',
2619             url: '/api/drone_imagery/generate_phenotypes?drone_run_project_id='+manage_drone_imagery_standard_process_drone_run_project_id+'&time_cvterm_id='+manage_drone_imagery_standard_process_phenotype_time+'&standard_process_type='+jQuery('#drone_imagery_generate_phenotypes_process_type').val(),
2620             dataType: "json",
2621             success: function(response){
2622                 console.log(response);
2623                 if (response.error) {
2624                     alert(response.error);
2625                 }
2626                 if (response.success) {
2627                     alert('Drone image phenotypes stored!');
2628                 }
2629             },
2630             error: function(response){
2631                 alert('Error generating drone image phenotypes!');
2632             }
2633         });
2635         location.reload();
2636     });
2638     //
2639     // Minimal VI Standard Process ()
2640     //
2642     var manage_drone_imagery_standard_process_minimal_vi_drone_run_project_id;
2643     var manage_drone_imagery_standard_process_minimal_vi_phenotype_time = '';
2645     jQuery(document).on('click', 'button[name=project_drone_imagery_standard_process_minimal_vi]', function(){
2646         manage_drone_imagery_standard_process_minimal_vi_drone_run_project_id = jQuery(this).data('drone_run_project_id');
2648         jQuery.ajax({
2649             type: 'GET',
2650             url: '/api/drone_imagery/get_weeks_after_planting_date?drone_run_project_id='+manage_drone_imagery_standard_process_minimal_vi_drone_run_project_id,
2651             dataType: "json",
2652             beforeSend: function (){
2653                 jQuery('#working_modal').modal('show');
2654             },
2655             success: function(response){
2656                 jQuery('#working_modal').modal('hide');
2657                 console.log(response);
2658                 if (response.error) {
2659                     alert(response.error);
2660                 }
2662                 var html = "<center><b>Field Trial Planting Date</b>: "+response.planting_date+"<br/><b>Drone Run Date</b>: "+response.drone_run_date+"<br/><b>Number of Weeks</b>: "+response.rounded_time_difference_weeks+"<br/><b>Number of Weeks Ontology Term</b>: "+response.time_ontology_week_term+"<br/><b>Number of Days</b>:"+response.time_difference_days+"<br/><b>Number of Days Ontology Term</b>: "+response.time_ontology_day_term+"<br/><br/></center>";
2663                 jQuery('#drone_imagery_minimal_vi_standard_process_week_term_div').html(html);
2664                 manage_drone_imagery_standard_process_minimal_vi_phenotype_time = response.time_ontology_day_cvterm_id;
2665             },
2666             error: function(response){
2667                 alert('Error getting time terms!');
2668                 jQuery('#working_modal').modal('hide');
2669             }
2670         });
2672         jQuery('#drone_imagery_minimal_vi_standard_process_dialog').modal('show');
2673     });
2675     jQuery('#drone_imagery_minimal_vi_standard_process_select').click(function() {
2676         if (manage_drone_imagery_standard_process_minimal_vi_phenotype_time == '') {
2677             alert('Time of phenotype not set for minimal vi process! This should not happen so please contact us');
2678             return false;
2679         }
2681         alert("Minimal vegetative index standard process will occur in the background. You can check the indicator on this page by refreshing the page.");
2683         jQuery.ajax({
2684             type: 'POST',
2685             url: '/api/drone_imagery/standard_process_minimal_vi_apply?drone_run_project_id='+manage_drone_imagery_standard_process_minimal_vi_drone_run_project_id,
2686             dataType: "json",
2687             success: function(response){
2688                 console.log(response);
2689                 if (response.error) {
2690                     alert(response.error);
2691                 } else {
2692                     alert('Minimal vegetative index standard process complete! Phenotype generation may still be occurring.');
2693                     location.reload();
2694                 }
2695             },
2696             error: function(response){
2697                 alert('Error running minimal vegetative index standard process!');
2698             }
2699         });
2701         jQuery.ajax({
2702             type: 'GET',
2703             url: '/api/drone_imagery/generate_phenotypes?drone_run_project_id='+manage_drone_imagery_standard_process_minimal_vi_drone_run_project_id+'&time_cvterm_id='+manage_drone_imagery_standard_process_minimal_vi_phenotype_time+'&standard_process_type=minimal_vi',
2704             dataType: "json",
2705             success: function(response){
2706                 console.log(response);
2707                 if (response.error) {
2708                     alert(response.error);
2709                 }
2710                 if (response.success) {
2711                     alert('Drone image phenotypes stored for minimal vegetative index standard process!');
2712                 }
2713             },
2714             error: function(response){
2715                 alert('Error generating drone image phenotypes for minial vegetative index standard process!');
2716             }
2717         });
2719         location.reload();
2720     });
2722     //
2723     // Extended Standard Process
2724     //
2726     var manage_drone_imagery_standard_process_extended_drone_run_project_id;
2727     var manage_drone_imagery_standard_process_extended_phenotype_time = '';
2729     jQuery(document).on('click', 'button[name="project_drone_imagery_standard_process_extended"]', function() {
2730         manage_drone_imagery_standard_process_extended_drone_run_project_id = jQuery(this).data('drone_run_project_id');
2731         jQuery.ajax({
2732             type: 'GET',
2733             url: '/api/drone_imagery/get_weeks_after_planting_date?drone_run_project_id='+manage_drone_imagery_standard_process_extended_drone_run_project_id,
2734             dataType: "json",
2735             beforeSend: function (){
2736                 jQuery('#working_modal').modal('show');
2737             },
2738             success: function(response){
2739                 jQuery('#working_modal').modal('hide');
2740                 console.log(response);
2741                 if (response.error) {
2742                     alert(response.error);
2743                 }
2745                 var html = "<center><b>Field Trial Planting Date</b>: "+response.planting_date+"<br/><b>Drone Run Date</b>: "+response.drone_run_date+"<br/><b>Number of Weeks</b>: "+response.rounded_time_difference_weeks+"<br/><b>Number of Weeks Ontology Term</b>: "+response.time_ontology_week_term+"<br/><b>Number of Days</b>:"+response.time_difference_days+"<br/><b>Number of Days Ontology Term</b>: "+response.time_ontology_day_term+"<br/><br/></center>";
2746                 jQuery('#drone_imagery_extended_standard_process_week_term_div').html(html);
2747                 manage_drone_imagery_standard_process_extended_phenotype_time = response.time_ontology_day_cvterm_id;
2748             },
2749             error: function(response){
2750                 alert('Error getting time terms!');
2751                 jQuery('#working_modal').modal('hide');
2752             }
2753         });
2754         jQuery('#drone_imagery_extended_standard_process_dialog').modal('show');
2755     });
2757     jQuery('#drone_imagery_extended_standard_process_select').click(function(){
2758         if (manage_drone_imagery_standard_process_extended_phenotype_time == '') {
2759             alert('Time of phenotype not set for extended standard process! This should not happen so please contact us!');
2760             return false;
2761         }
2763         alert("Extended standard process will occur in the background. You can check the indicator on this page by refreshing the page.");
2765         jQuery.ajax({
2766             type: 'GET',
2767             url: '/api/drone_imagery/standard_process_extended_apply?drone_run_project_id='+manage_drone_imagery_standard_process_extended_drone_run_project_id+'&time_days_cvterm_id='+manage_drone_imagery_standard_process_extended_phenotype_time+'&standard_process_type=extended',
2768             dataType: "json",
2769             success: function(response){
2770                 console.log(response);
2771                 if (response.error) {
2772                     alert(response.error);
2773                 }
2774             },
2775             error: function(response){
2776                 alert('Error running extended standard process!');
2777             }
2778         });
2780         location.reload();
2781     });
2783     //
2784     // Download Phenotypes
2785     //
2787     var manage_drone_imagery_download_phenotypes_field_trial_id = undefined;
2788     var manage_drone_imagery_download_phenotypes_trait_ids = [];
2790     jQuery('#download_phenotypes_drone_imagery_link').click(function(){
2791         jQuery('#drone_imagery_download_phenotypes_dialog').modal('show');
2792         get_select_box('trials', 'drone_imagery_download_phenotypes_trial_select_div', { 'name' : 'drone_imagery_download_phenotypes_field_trial_id', 'id' : 'drone_imagery_download_phenotypes_field_trial_id', 'empty':1, 'multiple':0 });
2794         manage_drone_imagery_download_phenotypes_field_trial_id = undefined;
2795         manage_drone_imagery_download_phenotypes_trait_ids = [];
2796     });
2798     jQuery('#drone_imagery_download_phenotypes_field_trial_select_step').click(function(){
2799         manage_drone_imagery_download_phenotypes_field_trial_id = jQuery('#drone_imagery_download_phenotypes_field_trial_id').val();
2800         if (manage_drone_imagery_download_phenotypes_field_trial_id == '') {
2801             alert('Please select a field trial first!');
2802         } else {
2803             get_select_box('traits', 'drone_imagery_download_phenotypes_trait_select_div', { 'name' : 'drone_imagery_download_phenotypes_trait_id_select', 'id' : 'drone_imagery_download_phenotypes_trait_id_select', 'empty':1, 'multiple':1, 'size': 20, 'trial_ids':manage_drone_imagery_download_phenotypes_field_trial_id, 'stock_type':'plot' });
2805             Workflow.complete("#drone_imagery_download_phenotypes_field_trial_select_step");
2806             Workflow.focus('#drone_imagery_download_phenotypes_workflow', 1);
2807         }
2808         return false;
2809     });
2811     jQuery('#drone_imagery_download_phenotypes_trait_select_step').click(function(){
2812         manage_drone_imagery_download_phenotypes_trait_ids = jQuery('#drone_imagery_download_phenotypes_trait_id_select').val();
2813         if (manage_drone_imagery_download_phenotypes_trait_ids == null || manage_drone_imagery_download_phenotypes_trait_ids == undefined) {
2814             alert('Please select at least one observation variable!');
2815             return false;
2816         }
2817         if (manage_drone_imagery_download_phenotypes_trait_ids.length < 1){
2818             alert('Please select at least one observation variable!');
2819         } else {
2820             Workflow.complete("#drone_imagery_download_phenotypes_trait_select_step");
2821             Workflow.focus('#drone_imagery_download_phenotypes_workflow', 2);
2822         }
2823         return false;
2824     });
2826     jQuery('#drone_imagery_download_phenotypes_confirm_step').click(function() {
2827         jQuery.ajax({
2828             type: 'POST',
2829             url: '/api/drone_imagery/analysis_query',
2830             dataType: "json",
2831             data: {
2832                 'observation_variable_id_list':JSON.stringify(manage_drone_imagery_download_phenotypes_trait_ids),
2833                 'field_trial_id_list':JSON.stringify([manage_drone_imagery_download_phenotypes_field_trial_id]),
2834                 'format':'csv'
2835             },
2836             beforeSend: function (){
2837                 jQuery('#working_modal').modal('show');
2838             },
2839             success: function(response){
2840                 jQuery('#working_modal').modal('hide');
2841                 console.log(response);
2842                 if(response.error) {
2843                     alert(response.error);
2844                 }
2845                 jQuery('#drone_imagery_download_phenotypes_file_div').html('Download File: <a href="'+response.file+'">'+response.file+'</a>');
2846             },
2847             error: function(response){
2848                 alert('Error downloading drone image phenotypes!');
2849                 jQuery('#working_modal').modal('hide');
2850             }
2851         });
2852     });
2854     //
2855     // Calculate statistics
2856     //
2858     var manage_drone_imagery_calculate_statistics_field_trial_id_array = undefined;
2859     var manage_drone_imagery_calculate_statistics_field_trial_id_string = "";
2860     var manage_drone_imagery_calculate_statistics_observation_variable_type;
2861     var manage_drone_imagery_calculate_statistics_trait_ids = [];
2862     var manage_drone_imagery_calculate_statistics_select = '';
2864     jQuery('#drone_imagery_calculate_statistics_link').click(function(){
2865         get_select_box('trials', 'drone_imagery_calculate_statistics_trial_select_div', { 'name' : 'drone_imagery_calculate_statistics_field_trial_id', 'id' : 'drone_imagery_calculate_statistics_field_trial_id', 'empty':1, 'multiple':1 });
2867         jQuery('#drone_imagery_calculate_statistics_dialog').modal('show');
2868     });
2870     jQuery('#drone_imagery_calculate_statistics_select_observation_variable_type').change(function(){
2871         manage_drone_imagery_calculate_statistics_observation_variable_type = jQuery('#drone_imagery_calculate_statistics_select_observation_variable_type').val();
2872         if (manage_drone_imagery_calculate_statistics_observation_variable_type == 'time_ontology') {
2873             get_select_box('traits', 'drone_imagery_calculate_statistics_trait_select_div', { 'name' : 'drone_imagery_calculate_statistics_trait_id_select', 'id' : 'drone_imagery_calculate_statistics_trait_id_select', 'empty':1, 'multiple':1, 'size': 20, 'trial_ids':manage_drone_imagery_calculate_statistics_field_trial_id_string, 'stock_type':'plot', 'contains_composable_cv_type':manage_drone_imagery_calculate_statistics_observation_variable_type, 'select_format':'component_table_select' });
2874         }
2875         else {
2876             get_select_box('traits', 'drone_imagery_calculate_statistics_trait_select_div', { 'name' : 'drone_imagery_calculate_statistics_trait_id_select', 'id' : 'drone_imagery_calculate_statistics_trait_id_select', 'empty':1, 'multiple':1, 'size': 20, 'trial_ids':manage_drone_imagery_calculate_statistics_field_trial_id_string, 'stock_type':'plot', 'contains_composable_cv_type':manage_drone_imagery_calculate_statistics_observation_variable_type });
2877         }
2878     });
2880     jQuery('#drone_imagery_calculate_statistics_field_trial_select_step').click(function(){
2881         manage_drone_imagery_calculate_statistics_field_trial_id_array = undefined;
2882         manage_drone_imagery_calculate_statistics_field_trial_id_string = "";
2883         manage_drone_imagery_calculate_statistics_field_trial_id_array = jQuery('#drone_imagery_calculate_statistics_field_trial_id').val();
2884         manage_drone_imagery_calculate_statistics_field_trial_id_string = manage_drone_imagery_calculate_statistics_field_trial_id_array.join(",");
2885         manage_drone_imagery_calculate_statistics_observation_variable_type = jQuery('#drone_imagery_calculate_statistics_select_observation_variable_type').val();
2886         if (manage_drone_imagery_calculate_statistics_field_trial_id_string == '') {
2887             alert('Please select a field trial first!');
2888         } else {
2889             if (manage_drone_imagery_calculate_statistics_observation_variable_type == 'time_ontology') {
2890                 get_select_box('traits', 'drone_imagery_calculate_statistics_trait_select_div', { 'name' : 'drone_imagery_calculate_statistics_trait_id_select', 'id' : 'drone_imagery_calculate_statistics_trait_id_select', 'empty':1, 'multiple':1, 'size': 20, 'trial_ids':manage_drone_imagery_calculate_statistics_field_trial_id_string, 'stock_type':'plot', 'contains_composable_cv_type':manage_drone_imagery_calculate_statistics_observation_variable_type, 'select_format':'component_table_select' });
2891             }
2892             else {
2893                 get_select_box('traits', 'drone_imagery_calculate_statistics_trait_select_div', { 'name' : 'drone_imagery_calculate_statistics_trait_id_select', 'id' : 'drone_imagery_calculate_statistics_trait_id_select', 'empty':1, 'multiple':1, 'size': 20, 'trial_ids':manage_drone_imagery_calculate_statistics_field_trial_id_string, 'stock_type':'plot', 'contains_composable_cv_type':manage_drone_imagery_calculate_statistics_observation_variable_type });
2894             }
2896             Workflow.complete("#drone_imagery_calculate_statistics_field_trial_select_step");
2897             Workflow.focus('#drone_imagery_calculate_statistics_workflow', 1);
2898         }
2899         return false;
2900     });
2902     jQuery('#drone_imagery_calculate_statistics_trait_select_step').click(function(){
2903         manage_drone_imagery_calculate_statistics_trait_ids = [];
2905         if (manage_drone_imagery_calculate_statistics_observation_variable_type == 'time_ontology') {
2906             jQuery('input[name="drone_imagery_calculate_statistics_trait_id_select"]').each(function() {
2907                 if (this.checked){
2908                     manage_drone_imagery_calculate_statistics_trait_ids.push(jQuery(this).val());
2909                 }
2910             });
2911         }
2912         else {
2913             manage_drone_imagery_calculate_statistics_trait_ids = jQuery('#drone_imagery_calculate_statistics_trait_id_select').val();
2914             if (manage_drone_imagery_calculate_statistics_trait_ids == null || manage_drone_imagery_calculate_statistics_trait_ids == undefined) {
2915                 alert('Please select at least one observation variable!');
2916                 return false;
2917             }
2918         }
2920         if (manage_drone_imagery_calculate_statistics_trait_ids.length < 1){
2921             alert('Please select at least one observation variable!');
2922         } else {
2923             Workflow.complete("#drone_imagery_calculate_statistics_trait_select_step");
2924             Workflow.focus('#drone_imagery_calculate_statistics_workflow', 2);
2925         }
2926         return false;
2927     });
2929     jQuery('#drone_imagery_calculate_statistics_select_input').change(function(){
2930         manage_drone_imagery_calculate_statistics_select = jQuery('#drone_imagery_calculate_statistics_select_input').val();
2931         if (manage_drone_imagery_calculate_statistics_select == 'marss_germplasmname_block') {
2932             jQuery('#drone_imagery_calculate_statistics_marss_div').show();
2933         }
2934         else {
2935             jQuery('#drone_imagery_calculate_statistics_marss_div').hide();
2936         }
2937     });
2939     jQuery('#drone_imagery_calculate_statistics_select_step').click(function(){
2940         manage_drone_imagery_calculate_statistics_select = jQuery('#drone_imagery_calculate_statistics_select_input').val();
2942         if (manage_drone_imagery_calculate_statistics_select == 'marss_germplasmname_block' && manage_drone_imagery_calculate_statistics_observation_variable_type != 'time_ontology') {
2943             alert('The MARSS model fit and prediction only works for Time Series traits! Please go to Trait Selection and select time series traits.');
2944             return false;
2945         }
2947         jQuery.ajax({
2948             url : '/api/drone_imagery/calculate_statistics',
2949             type : 'POST',
2950             data : {
2951                 'observation_variable_id_list':JSON.stringify(manage_drone_imagery_calculate_statistics_trait_ids),
2952                 'field_trial_id_list':JSON.stringify(manage_drone_imagery_calculate_statistics_field_trial_id_array),
2953                 'statistics_select':manage_drone_imagery_calculate_statistics_select,
2954                 'statistics_select_marss_options':jQuery('#drone_imagery_calculate_statistics_select_marss').val()
2955             },
2956             beforeSend: function() {
2957                 jQuery("#working_modal").modal("show");
2958             },
2959             success: function(response){
2960                 console.log(response);
2961                 jQuery("#working_modal").modal("hide");
2962                 
2963                 if (response.error) {
2964                     alert(response.error);
2965                 }
2966                 else {
2967                     var html = '<table class="table table-bordered table-hover"><thead><tr><th>Observation Variable</th><th>Statistics</th><th>Plot</th></tr></thead><tbody>';
2968                     for (var i=0; i<response.length; i++) {
2969                         html = html + '<tr><td>'+response[i][0]+'</td><td>'+response[i][1]+'</td><td><img src="'+response[i][2]+'"></td></tr>';
2970                     }
2971                     html = html + '</tbody></table>';
2972                     jQuery('#drone_imagery_calculate_statistics_result_div').html(html);
2974                     Workflow.complete("#drone_imagery_calculate_statistics_select_step");
2975                     Workflow.focus('#drone_imagery_calculate_statistics_workflow', 3);
2976                 }
2977             },
2978             error: function(response){
2979                 jQuery("#working_modal").modal("hide");
2980                 alert('Error calculating statistics!')
2981             }
2982         });
2983     });
2985     //
2986     // Growing Degree Days Calculation
2987     //
2989     var manage_drone_imagery_calculate_gdd_field_trial_id;
2990     var manage_drone_imagery_calculate_gdd_drone_run_project_id;
2991     var manage_drone_imagery_calculate_gdd_phenotype_time;
2993     jQuery(document).on('click', 'button[name=drone_imagery_drone_run_calculate_gdd]', function() {
2994         manage_drone_imagery_calculate_gdd_field_trial_id = jQuery(this).data('field_trial_id');
2995         manage_drone_imagery_calculate_gdd_drone_run_project_id = jQuery(this).data('drone_run_project_id');
2997         jQuery.ajax({
2998             url : '/api/drone_imagery/get_weeks_after_planting_date?drone_run_project_id='+manage_drone_imagery_calculate_gdd_drone_run_project_id,
2999             success: function(response){
3000                 console.log(response);
3001                 var html = "<center><b>Field Trial Planting Date</b>: "+response.planting_date+"<br/><b>Drone Run Date</b>: "+response.drone_run_date+"<br/><b>Number of Weeks</b>: "+response.rounded_time_difference_weeks+"<br/><b>Number of Weeks Ontology Term</b>: "+response.time_ontology_week_term+"<br/><b>Number of Days</b>:"+response.time_difference_days+"<br/><b>Number of Days Ontology Term</b>: "+response.time_ontology_day_term+"<br/><br/></center>";
3002                 jQuery('#drone_imagery_calculate_gdd_time_div').html(html);
3003                 manage_drone_imagery_calculate_gdd_phenotype_time = response.time_ontology_day_cvterm_id;
3005                 jQuery('#drone_imagery_calculate_gdd_dialog').modal('show');
3006             },
3007             error: function(response){
3008                 alert('Error getting gdd!')
3009             }
3010         });
3011     });
3013     jQuery('#drone_imagery_upload_gdd_submit').click(function(){
3014         var manage_drone_imagery_calculate_gdd_base_temp = jQuery('#drone_imagery_calculate_gdd_base_temperature_input').val();
3015         var manage_drone_imagery_calculate_gdd_formula = jQuery('#drone_imagery_calculate_gdd_formula_input').val();
3016         jQuery.ajax({
3017             url : '/api/drone_imagery/growing_degree_days?drone_run_project_id='+manage_drone_imagery_calculate_gdd_drone_run_project_id+'&formula='+manage_drone_imagery_calculate_gdd_formula+'&gdd_base_temperature='+manage_drone_imagery_calculate_gdd_base_temp+'&field_trial_id='+manage_drone_imagery_calculate_gdd_field_trial_id,
3018             beforeSend: function(){
3019                 jQuery('#working_modal').modal('show');
3020             },
3021             success: function(response){
3022                 console.log(response);
3023                 jQuery('#working_modal').modal('hide');
3024                 location.reload();
3025             },
3026             error: function(response){
3027                 jQuery('#working_modal').modal('hide');
3028                 alert('Error calculating growing degree days!');
3029             }
3030         });
3031     });
3033     //
3034     // Keras CNN Training JS
3035     //
3037     var manage_drone_imagery_train_keras_drone_run_ids = [];
3038     var manage_drone_imagery_train_keras_field_trial_id_array = [];
3039     var manage_drone_imagery_train_keras_field_trial_id_string = '';
3040     var manage_drone_imagery_train_keras_trait_id;
3041     var manage_drone_imagery_train_keras_aux_trait_ids;
3042     var manage_drone_imagery_train_keras_plot_polygon_type_ids = [];
3043     var manage_drone_imagery_train_keras_temporary_model_file = '';
3044     var manage_drone_imagery_train_keras_temporary_model_input_file = '';
3045     var manage_drone_imagery_train_keras_temporary_model_input_aux_file = '';
3046     var manage_drone_imagery_train_keras_class_map = '';
3048     var manage_drone_imagery_predict_keras_drone_run_ids = [];
3049     var manage_drone_imagery_predict_keras_field_trial_id_array = [];
3050     var manage_drone_imagery_predict_keras_field_trial_id_string = '';
3051     var manage_drone_imagery_predict_keras_plot_polygon_type_ids = [];
3052     var manage_drone_imagery_predict_keras_model_id = '';
3054     jQuery('#keras_cnn_drone_imagery_link').click(function(){
3055         jQuery('#drone_imagery_keras_cnn_dialog').modal('show');
3056     });
3058     jQuery('#drone_imagery_keras_cnn_train_link').click(function(){
3059         get_select_box('trials', 'drone_imagery_train_keras_cnn_trial_select_div', { 'name' : 'drone_imagery_train_keras_cnn_field_trial_id', 'id' : 'drone_imagery_train_keras_cnn_field_trial_id', 'empty':1, 'multiple':1 });
3061         jQuery('#drone_imagery_train_keras_cnn_dialog').modal('show');
3062     });
3064     jQuery('#drone_imagery_train_keras_model_field_trial_select_step').click(function(){
3065         manage_drone_imagery_train_keras_field_trial_id_array = [];
3066         manage_drone_imagery_train_keras_field_trial_id_string = '';
3067         manage_drone_imagery_train_keras_field_trial_id_array = jQuery('#drone_imagery_train_keras_cnn_field_trial_id').val();
3068         manage_drone_imagery_train_keras_field_trial_id_string = manage_drone_imagery_train_keras_field_trial_id_array.join(",");
3069         if (manage_drone_imagery_train_keras_field_trial_id_string == '') {
3070             alert('Please select a field trial first!');
3071         } else {
3072             get_select_box('traits', 'drone_imagery_train_keras_cnn_trait_select_div', { 'name' : 'drone_imagery_train_keras_cnn_trait_id', 'id' : 'drone_imagery_train_keras_cnn_trait_id', 'empty':1, 'trial_ids':manage_drone_imagery_train_keras_field_trial_id_string, 'stock_type':'plot' });
3074             get_select_box('traits', 'drone_imagery_train_keras_cnn_aux_trait_select_div', { 'name' : 'drone_imagery_train_keras_cnn_aux_trait_ids', 'id' : 'drone_imagery_train_keras_cnn_aux_trait_ids', 'empty':1, 'multiple':1, 'trial_ids':manage_drone_imagery_train_keras_field_trial_id_string, 'stock_type':'plot' });
3076             jQuery('#drone_image_train_keras_drone_runs_table').DataTable({
3077                 paging : false,
3078                 destroy : true,
3079                 ajax : '/api/drone_imagery/drone_runs?select_checkbox_name=train_keras_drone_imagery_drone_run_select&checkbox_select_all=1&field_trial_ids='+manage_drone_imagery_train_keras_field_trial_id_string
3080             });
3082             Workflow.complete("#drone_imagery_train_keras_model_field_trial_select_step");
3083             Workflow.focus('#drone_imagery_train_keras_model_workflow', 2);
3084         }
3085         return false;
3086     });
3088     jQuery('#drone_imagery_train_keras_model_trait_select_step').click(function(){
3089         manage_drone_imagery_train_keras_trait_id = undefined;
3090         manage_drone_imagery_train_keras_aux_trait_ids = undefined;
3091         manage_drone_imagery_train_keras_trait_id = jQuery('#drone_imagery_train_keras_cnn_trait_id').val();
3092         manage_drone_imagery_train_keras_aux_trait_ids = jQuery('#drone_imagery_train_keras_cnn_aux_trait_ids').val();
3093         if (manage_drone_imagery_train_keras_trait_id == undefined || manage_drone_imagery_train_keras_trait_id == 'null' || manage_drone_imagery_train_keras_trait_id == '') {
3094             alert('Please select a phenotyped trait first!');
3095         } else {
3097             get_select_box('stocks', 'drone_imagery_train_keras_cnn_population_select_div', { 'name' : 'drone_imagery_train_keras_cnn_population_id', 'id' : 'drone_imagery_train_keras_cnn_population_id', 'empty':1, 'multiple':1, 'stock_type_name':'population' });
3099             Workflow.complete("#drone_imagery_train_keras_model_trait_select_step");
3100             Workflow.focus('#drone_imagery_train_keras_model_workflow', 3);
3101         }
3102         return false;
3103     });
3105     jQuery('#drone_imagery_train_keras_model_population_select_step').click(function(){
3106         Workflow.complete("#drone_imagery_train_keras_model_population_select_step");
3107         Workflow.focus('#drone_imagery_train_keras_model_workflow', 4);
3108     });
3110     jQuery('#drone_imagery_train_keras_model_drone_run_select_step').click(function(){
3111         manage_drone_imagery_train_keras_drone_run_ids = [];
3112         jQuery('input[name="train_keras_drone_imagery_drone_run_select"]:checked').each(function() {
3113             manage_drone_imagery_train_keras_drone_run_ids.push(jQuery(this).val());
3114         });
3115         if (manage_drone_imagery_train_keras_drone_run_ids.length < 1){
3116             alert('Please select at least one drone run!');
3117         } else {
3119             jQuery('#drone_image_train_keras_plot_polygon_image_type_table').DataTable({
3120                 destroy : true,
3121                 paging : false,
3122                 ajax : '/api/drone_imagery/plot_polygon_types?checkbox_select_standard_4=1&select_checkbox_name=train_keras_drone_imagery_plot_polygon_type_select&field_trial_ids='+manage_drone_imagery_train_keras_field_trial_id_string+'&drone_run_ids='+JSON.stringify(manage_drone_imagery_train_keras_drone_run_ids)
3123             });
3125             Workflow.complete("#drone_imagery_train_keras_model_drone_run_select_step");
3126             Workflow.focus('#drone_imagery_train_keras_model_workflow', 5);
3127         }
3128         return false;
3129     });
3131     jQuery('#drone_image_train_keras_drone_runs_table_select_all').change(function(){
3132         jQuery('input[name="train_keras_drone_imagery_drone_run_select"]').each(function() {
3133             jQuery(this).prop('checked', jQuery('#drone_image_train_keras_drone_runs_table_select_all').prop("checked"));
3134         });
3135     });
3137     jQuery('#drone_image_train_keras_plot_polygon_image_type_table_select_all').change(function() {
3138         jQuery('input[name="train_keras_drone_imagery_plot_polygon_type_select"]').each(function() {
3139             jQuery(this).prop('checked', jQuery('#drone_image_train_keras_plot_polygon_image_type_table_select_all').prop("checked"));
3140         });
3141     });
3143     jQuery('#drone_imagery_train_keras_model_plot_polygon_type_select_step').click(function(){
3144         manage_drone_imagery_train_keras_plot_polygon_type_ids = [];
3145         jQuery('input[name="train_keras_drone_imagery_plot_polygon_type_select"]:checked').each(function() {
3146             manage_drone_imagery_train_keras_plot_polygon_type_ids.push(jQuery(this).val());
3147         });
3148         if (manage_drone_imagery_train_keras_plot_polygon_type_ids.length < 1){
3149             alert('Please select at least one plot polygon type!');
3150         } else {
3151             Workflow.complete("#drone_imagery_train_keras_model_plot_polygon_type_select_step");
3152             Workflow.focus('#drone_imagery_train_keras_model_workflow', 6);
3153         }
3155         get_select_box('genotyping_protocol', 'drone_image_train_keras_model_genotyping_protocol_div', { 'name' : 'drone_image_train_keras_model_genotyping_protocol_select', 'id' : 'drone_image_train_keras_model_genotyping_protocol_select', 'empty':1 });
3157         return false;
3158     });
3160     jQuery('#drone_imagery_train_keras_model_confirm_step').click(function(){
3161         manage_drone_imagery_train_keras_temporary_model_file = '';
3162         manage_drone_imagery_train_keras_temporary_model_input_file = '';
3163         manage_drone_imagery_train_keras_temporary_model_input_aux_file = '';
3164         manage_drone_imagery_train_keras_class_map = '';
3166         var drone_imagery_keras_model_name = jQuery('#drone_image_train_keras_model_name').val();
3167         var drone_imagery_keras_model_desc = jQuery('#drone_image_train_keras_model_desc').val();
3168         var drone_imagery_keras_model_type = jQuery('#drone_image_train_keras_model_type').val();
3169         if (drone_imagery_keras_model_type =='' || drone_imagery_keras_model_name == '' || drone_imagery_keras_model_desc == '') {
3170             alert('Please give a model type, name, and description!');
3171             return false;
3172         }
3173         else {
3174             jQuery.ajax({
3175                 url : '/api/drone_imagery/train_keras_model',
3176                 type: "POST",
3177                 data : {
3178                     'field_trial_ids' : manage_drone_imagery_train_keras_field_trial_id_string,
3179                     'trait_id' : manage_drone_imagery_train_keras_trait_id,
3180                     'aux_trait_id' : manage_drone_imagery_train_keras_aux_trait_ids,
3181                     'drone_run_ids' : JSON.stringify(manage_drone_imagery_train_keras_drone_run_ids),
3182                     'plot_polygon_type_ids' : JSON.stringify(manage_drone_imagery_train_keras_plot_polygon_type_ids),
3183                     'save_model' : 1,
3184                     'model_name' : drone_imagery_keras_model_name,
3185                     'model_description' : drone_imagery_keras_model_desc,
3186                     'model_type' : drone_imagery_keras_model_type,
3187                     'population_id' : jQuery('#drone_imagery_train_keras_cnn_population_id').val(),
3188                     'nd_protocol_id' : jQuery('#drone_image_train_keras_model_genotyping_protocol_select').val(),
3189                     'use_parents_grm' : jQuery('#drone_image_train_keras_model_use_parents_grm').val()
3190                 },
3191                 beforeSend: function() {
3192                     jQuery("#working_modal").modal("show");
3193                 },
3194                 success: function(response){
3195                     console.log(response);
3196                     jQuery("#working_modal").modal("hide");
3198                     if (response.error) {
3199                         alert(response.error);
3200                     }
3201                     else {
3202                         alert("Trained Keras CNN Model saved!");
3203                     }
3205                     var html = "<hr><a href='"+response.loss_history_file+"' target=_blank>Loss History</a><hr><h4>Results</h4><br/><br/>";
3206                     html = html + "<table class='table table-bordered table-hover'><thead><tr><th>Results</th></tr></thead><tbody>";
3207                     for (var i=0; i<response.results.length; i++) {
3208                         html = html + "<tr><td>"+response.results[i]+"</td></tr>";
3209                     }
3210                     html = html + "</tbody></table>";
3212                     //html = html + '<hr><h3>Save Model for Predictions</h3><div class="form-horizontal"><div class="form-group"><label class="col-sm-6 control-label">Model Name: </label><div class="col-sm-6"><input class="form-control" id="drone_imagery_save_keras_model_name" name="drone_imagery_save_keras_model_name" type="text" /></div></div><div class="form-group"><label class="col-sm-6 control-label">Model Description: </label><div class="col-sm-6"><input class="form-control" id="drone_imagery_save_keras_model_desc" name="drone_imagery_save_keras_model_desc" type="text" /></div></div></div><button class="btn btn-primary" id="drone_imagery_keras_model_save">Save Model (Required For Using For Prediction)</button>';
3214                     manage_drone_imagery_train_keras_temporary_model_input_file = response.model_input_file;
3215                     manage_drone_imagery_train_keras_temporary_model_input_aux_file = response.model_input_aux_file;
3216                     manage_drone_imagery_train_keras_temporary_model_file = response.model_temp_file;
3217                     manage_drone_imagery_train_keras_class_map = response.class_map;
3219                     jQuery('#drone_imagery_train_keras_model_results_div').html(html);
3220                 },
3221                 error: function(response){
3222                     jQuery("#working_modal").modal("hide");
3223                     alert('Error training keras model!')
3224                 }
3225             });
3226         }
3227     });
3229     jQuery(document).on('click', '#drone_imagery_keras_model_save', function() {
3230         var manage_drone_imagery_train_keras_model_save_name = jQuery('#drone_imagery_save_keras_model_name').val();
3231         var manage_drone_imagery_train_keras_model_save_desc = jQuery('#drone_imagery_save_keras_model_desc').val();
3232         if (manage_drone_imagery_train_keras_model_save_name == '' || manage_drone_imagery_train_keras_model_save_desc == '') {
3233             alert('A model name and description are required for saving!');
3234             return false;
3235         }
3236         else {
3237             jQuery.ajax({
3238                 url : '/api/drone_imagery/save_keras_model?field_trial_ids='+manage_drone_imagery_train_keras_field_trial_id_string+'&drone_run_ids='+JSON.stringify(manage_drone_imagery_train_keras_drone_run_ids)+'&plot_polygon_type_ids='+JSON.stringify(manage_drone_imagery_train_keras_plot_polygon_type_ids)+'&model_file='+manage_drone_imagery_train_keras_temporary_model_file+'&model_input_file='+manage_drone_imagery_train_keras_temporary_model_input_file+'&model_input_aux_file='+manage_dromanage_drone_imagery_train_keras_temporary_model_input_aux_file+'&model_name='+manage_drone_imagery_train_keras_model_save_name+'&model_description='+manage_drone_imagery_train_keras_model_save_desc+'&class_map='+JSON.stringify(manage_drone_imagery_train_keras_class_map)+'&trait_id='+manage_drone_imagery_train_keras_trait_id,
3239                 beforeSend: function() {
3240                     jQuery("#working_modal").modal("show");
3241                 },
3242                 success: function(response){
3243                     console.log(response);
3244                     jQuery("#working_modal").modal("hide");
3245                     if (response.error) {
3246                         alert(response.error);
3247                     }
3248                     else {
3249                         alert('Trained Keras CNN Model Saved! You can now use it for prediction!');
3250                     }
3251                 },
3252                 error: function(response){
3253                     jQuery("#working_modal").modal("hide");
3254                     alert('Error saving keras model!')
3255                 }
3256             });
3257         }
3258     });
3260     jQuery('#drone_imagery_keras_cnn_predict_link').click(function(){
3261         get_select_box('trials', 'drone_imagery_predict_keras_cnn_trial_select_div', { 'name' : 'drone_imagery_predict_keras_cnn_field_trial_id', 'id' : 'drone_imagery_predict_keras_cnn_field_trial_id', 'empty':1, 'multiple':0 });
3262         get_select_box('trained_keras_cnn_models', 'drone_imagery_predict_keras_cnn_model_select_div', { 'name' : 'drone_imagery_predict_keras_cnn_model_id', 'id' : 'drone_imagery_predict_keras_cnn_model_id', 'empty':1 });
3264         jQuery('#drone_imagery_predict_keras_cnn_dialog').modal('show');
3265     });
3267     jQuery('#drone_imagery_predict_keras_model_field_trial_select_step').click(function(){
3268         manage_drone_imagery_predict_keras_field_trial_id_array = [];
3269         manage_drone_imagery_predict_keras_field_trial_id_string = '';
3270         manage_drone_imagery_predict_keras_field_trial_id_string = jQuery('#drone_imagery_predict_keras_cnn_field_trial_id').val();
3271         //manage_drone_imagery_predict_keras_field_trial_id_array = jQuery('#drone_imagery_predict_keras_cnn_field_trial_id').val();
3272         //manage_drone_imagery_predict_keras_field_trial_id_string = manage_drone_imagery_predict_keras_field_trial_id_array.join(",");
3273         if (manage_drone_imagery_predict_keras_field_trial_id_string == '') {
3274             alert('Please select a field trial first!');
3275         } else {
3277             jQuery('#drone_image_predict_keras_drone_runs_table').DataTable({
3278                 destroy : true,
3279                 paging : false,
3280                 ajax : '/api/drone_imagery/drone_runs?select_checkbox_name=predict_keras_drone_imagery_drone_run_select&checkbox_select_all=1&field_trial_ids='+manage_drone_imagery_predict_keras_field_trial_id_string
3281             });
3283             Workflow.complete("#drone_imagery_predict_keras_model_field_trial_select_step");
3284             Workflow.focus('#drone_imagery_predict_keras_model_workflow', 2);
3285         }
3286         return false;
3287     });
3289     jQuery('#drone_image_predict_keras_drone_runs_table_select_all').change(function(){
3290         jQuery('input[name="predict_keras_drone_imagery_drone_run_select"]').each(function() {
3291             jQuery(this).prop('checked', jQuery('#drone_image_predict_keras_drone_runs_table_select_all').prop("checked"));
3292         });
3293     });
3295     jQuery('#drone_imagery_predict_keras_model_select_step').click(function(){
3296         manage_drone_imagery_predict_keras_model_id = '';
3297         manage_drone_imagery_predict_keras_model_id = jQuery('#drone_imagery_predict_keras_cnn_model_id').val();
3298         if (manage_drone_imagery_predict_keras_model_id == '') {
3299             alert('Please select a trained Keras CNN model before proceeding!');
3300         }
3301         else {
3302             get_select_box('stocks', 'drone_imagery_predict_keras_cnn_population_select_div', { 'name' : 'drone_imagery_predict_keras_cnn_population_id', 'id' : 'drone_imagery_predict_keras_cnn_population_id', 'empty':1, 'multiple':1, 'stock_type_name':'population' });
3304             Workflow.complete("#drone_imagery_predict_keras_model_select_step");
3305             Workflow.focus('#drone_imagery_predict_keras_model_workflow', 3);
3306         }
3307         return false;
3308     });
3310     jQuery('#drone_imagery_predict_keras_model_population_select_step').click(function(){
3311         Workflow.complete("#drone_imagery_predict_keras_model_population_select_step");
3312         Workflow.focus('#drone_imagery_predict_keras_model_workflow', 4);
3313     });
3315     jQuery('#drone_imagery_predict_keras_model_drone_run_select_step').click(function(){
3316         manage_drone_imagery_predict_keras_drone_run_ids = [];
3317         jQuery('input[name="predict_keras_drone_imagery_drone_run_select"]:checked').each(function() {
3318             manage_drone_imagery_predict_keras_drone_run_ids.push(jQuery(this).val());
3319         });
3320         if (manage_drone_imagery_predict_keras_drone_run_ids.length < 1){
3321             alert('Please select at least one drone run!');
3322         } else {
3324             jQuery('#drone_image_predict_keras_plot_polygon_image_type_table').DataTable({
3325                 destroy : true,
3326                 paging : false,
3327                 ajax : '/api/drone_imagery/plot_polygon_types?checkbox_select_standard_4=1&select_checkbox_name=predict_keras_drone_imagery_plot_polygon_type_select&field_trial_ids='+manage_drone_imagery_predict_keras_field_trial_id_string+'&drone_run_ids='+JSON.stringify(manage_drone_imagery_predict_keras_drone_run_ids)
3328             });
3330             Workflow.complete("#drone_imagery_predict_keras_model_drone_run_select_step");
3331             Workflow.focus('#drone_imagery_predict_keras_model_workflow', 5);
3332         }
3333         return false;
3334     });
3336     jQuery('#drone_image_predict_keras_plot_polygon_image_type_table_select_all').change(function() {
3337         jQuery('input[name="predict_keras_drone_imagery_plot_polygon_type_select"]').each(function() {
3338             jQuery(this).prop('checked', jQuery('#drone_image_predict_keras_plot_polygon_image_type_table_select_all').prop("checked"));
3339         });
3340     });
3342     jQuery('#drone_imagery_predict_keras_model_plot_polygon_type_select_step').click(function(){
3343         manage_drone_imagery_predict_keras_plot_polygon_type_ids = [];
3344         jQuery('input[name="predict_keras_drone_imagery_plot_polygon_type_select"]:checked').each(function() {
3345             manage_drone_imagery_predict_keras_plot_polygon_type_ids.push(jQuery(this).val());
3346         });
3347         if (manage_drone_imagery_predict_keras_plot_polygon_type_ids.length < 1){
3348             alert('Please select at least one plot polygon type!');
3349         } else {
3350             Workflow.complete("#drone_imagery_predict_keras_model_plot_polygon_type_select_step");
3351             Workflow.focus('#drone_imagery_predict_keras_model_workflow', 6);
3352         }
3353         return false;
3354     });
3356     jQuery('#drone_imagery_keras_model_prediction_select').change(function(){
3357         if (jQuery(this).val() == 'cnn_prediction_mixed_model') {
3358             jQuery('#drone_imagery_keras_model_prediction_cnn_prediction_mixed_model_div').show();
3359         }
3360         else {
3361             jQuery('#drone_imagery_keras_model_prediction_cnn_prediction_mixed_model_div').hide();
3362         }
3363     });
3365     jQuery('#drone_imagery_predict_keras_model_confirm_step').click(function(){
3366         jQuery.ajax({
3367             url : '/api/drone_imagery/predict_keras_model',
3368             type: "POST",
3369             data: {
3370                 'field_trial_ids' : manage_drone_imagery_predict_keras_field_trial_id_string,
3371                 'drone_run_ids' : JSON.stringify(manage_drone_imagery_predict_keras_drone_run_ids),
3372                 'plot_polygon_type_ids' : JSON.stringify(manage_drone_imagery_predict_keras_plot_polygon_type_ids),
3373                 'model_id' : manage_drone_imagery_predict_keras_model_id,
3374                 'model_prediction_type' : jQuery('#drone_imagery_keras_model_prediction_select').val(),
3375                 'population_id' : jQuery('#drone_imagery_predict_keras_cnn_population_id').val()
3376             },
3377             beforeSend: function() {
3378                 jQuery("#working_modal").modal("show");
3379             },
3380             success: function(response){
3381                 console.log(response);
3382                 jQuery("#working_modal").modal("hide");
3383                 if (response.error) {
3384                     alert(response.error);
3385                 }
3387                 var html = "<hr><h4>Prediction Results: "+response.trained_trait_name+"</h4>";
3388                 html = html + "<table class='table table-bordered table-hover'><thead><tr><th>Stock</th><th>Prediction</th><th>True Phenotype Value</th></tr></thead><tbody>";
3389                 for (var i=0; i<response.results.length; i++) {
3390                     html = html + "<tr><td><a href='/stock/"+response.results[i][1]+"/view' target=_blank>"+response.results[i][0]+"</a></td><td>"+response.results[i][2]+"</td><td>"+response.results[i][3]+"</td></tr>";
3391                 }
3392                 html = html + "</tbody></table>";
3394                 html = html + "<a href='"+response.activation_output+"' target=_blank>Download Activation Result</a><a href='"+response.corr_plot+"' target=_blank>Download Correlation</a>";
3396                 if (response.evaluation_results.length > 0) {
3397                     html = html + "<hr><h4>Model Evaluation Results</h4><br/><br/>";
3398                     html = html + "<table class='table table-bordered table-hover'><thead><tr><th>Results</th></tr></thead><tbody>";
3399                     for (var i=0; i<response.evaluation_results.length; i++) {
3400                         html = html + "<tr><td>"+response.evaluation_results[i]+"</td></tr>";
3401                     }
3402                     html = html + "</tbody></table>";
3403                 }
3405                 jQuery('#drone_imagery_predict_keras_model_results_div').html(html);
3406             },
3407             error: function(response){
3408                 jQuery("#working_modal").modal("hide");
3409                 alert('Error predicting keras model!')
3410             }
3411         });
3412     });
3414     //
3415     // Image Rotating JS
3416     //
3418     var rotate_stitched_image_id;
3419     var rotate_drone_run_band_project_id;
3420     var rotate_stitched_image_degrees;
3422     jQuery(document).on('click', 'button[name="project_drone_imagery_rotate_image"]', function() {
3423         showManageDroneImagerySection('manage_drone_imagery_rotate_div');
3425         rotate_stitched_image_id = jQuery(this).data('stitched_image_id');
3426         rotate_drone_run_band_project_id = jQuery(this).data('drone_run_band_project_id');
3427         rotate_stitched_image_degrees = 0.00;
3429         showRotateImage(rotate_stitched_image_id, 'drone_imagery_rotate_original_stitched_div', 'manage_drone_imagery_rotate_load_div');
3430     });
3432     jQuery('#drone_imagery_rotate_stitched_view').click(function(){
3433         rotate_stitched_image_degrees = parseFloat(jQuery('#drone_imagery_rotate_degrees_input').val());
3434         applyShowRotateImage(rotate_stitched_image_id, rotate_drone_run_band_project_id, rotate_stitched_image_degrees, 'drone_imagery_rotate_original_stitched_div');
3435     });
3437     jQuery('#drone_imagery_rotate_stitched_restart').click(function(){
3438         showRotateImage(rotate_stitched_image_id, 'drone_imagery_rotate_original_stitched_div', 'manage_drone_imagery_rotate_load_div');
3439         rotate_stitched_image_degrees = 0.00;
3440     });
3442     function applyShowRotateImage(rotate_stitched_image_id, rotate_drone_run_band_project_id, rotate_stitched_image_degrees, canvas_div_id) {
3443         jQuery.ajax({
3444             url : '/api/drone_imagery/rotate_image?image_id='+rotate_stitched_image_id+'&drone_run_band_project_id='+rotate_drone_run_band_project_id+'&angle='+rotate_stitched_image_degrees+'&view_only=1',
3445             beforeSend: function() {
3446                 jQuery("#working_modal").modal("show");
3447             },
3448             success: function(response){
3449                 console.log(response);
3450                 jQuery("#working_modal").modal("hide");
3452                 var canvas = document.getElementById(canvas_div_id);
3453                 ctx = canvas.getContext('2d');
3454                 var image = new Image();
3455                 image.onload = function () {
3456                     canvas.width = this.naturalWidth;
3457                     canvas.height = this.naturalHeight;
3458                     ctx.drawImage(this, 0, 0);
3459                 };
3460                 image.src = response.rotated_image_url;
3462                 manage_drone_imagery_standard_process_raw_images_rotated_image_id = response.rotated_image_id;
3463             },
3464             error: function(response){
3465                 jQuery("#working_modal").modal("hide");
3466                 alert('Error getting rotated image!')
3467             }
3468         });
3469     }
3471     function showRotateImage(rotate_stitched_image_id, canvas_div_id, load_div_id) {
3472         jQuery.ajax({
3473             url : '/api/drone_imagery/get_image?image_id='+rotate_stitched_image_id,
3474             beforeSend: function() {
3475                 jQuery("#working_modal").modal("show");
3476             },
3477             success: function(response){
3478                 console.log(response);
3479                 jQuery("#working_modal").modal("hide");
3481                 var canvas = document.getElementById(canvas_div_id);
3482                 ctx = canvas.getContext('2d');
3483                 var image = new Image();
3484                 image.onload = function () {
3485                     canvas.width = this.naturalWidth;
3486                     canvas.height = this.naturalHeight;
3487                     ctx.drawImage(this, 0, 0);
3488                     jQuery('#'+load_div_id).hide();
3489                 };
3490                 image.src = response.image_url;
3492             },
3493             error: function(response){
3494                 jQuery("#working_modal").modal("hide");
3495                 alert('Error retrieving image!')
3496             }
3497         });
3498     }
3500     function getRandomColor() {
3501         var letters = '0123456789ABCDEF';
3502         var color = '#';
3503         for (var i = 0; i < 6; i++) {
3504             color += letters[Math.floor(Math.random() * 16)];
3505         }
3506         return color;
3507     }
3509     jQuery('#drone_imagery_rotate_stitched_crosshairs').click(function(){
3510         drawRotateCrosshairs(getRandomColor(), 'drone_imagery_rotate_original_stitched_div');
3511     });
3513     function drawRotateCrosshairs(color, canvas_div_id) {
3514         var canvas = document.getElementById(canvas_div_id);
3515         var rotate_image_width = canvas.width;
3516         var rotate_image_height = canvas.height;
3517         var ctx = canvas.getContext("2d");
3519         ctx.beginPath();
3520         ctx.moveTo(rotate_image_width/2,0);
3521         ctx.lineTo(rotate_image_width/2, rotate_image_height);
3522         ctx.strokeStyle = color;
3523         ctx.lineWidth=5;
3524         ctx.stroke();
3526         ctx.beginPath();
3527         ctx.moveTo(rotate_image_width*1/4,0);
3528         ctx.lineTo(rotate_image_width*1/4, rotate_image_height);
3529         ctx.strokeStyle = color;
3530         ctx.lineWidth=5;
3531         ctx.stroke();
3533         ctx.beginPath();
3534         ctx.moveTo(rotate_image_width*3/4,0);
3535         ctx.lineTo(rotate_image_width*3/4, rotate_image_height);
3536         ctx.strokeStyle = color;
3537         ctx.lineWidth=5;
3538         ctx.stroke();
3540         ctx.beginPath();
3541         ctx.moveTo(0,rotate_image_height/2);
3542         ctx.lineTo(rotate_image_width, rotate_image_height/2);
3543         ctx.strokeStyle = color;
3544         ctx.lineWidth=5;
3545         ctx.stroke();
3547         ctx.beginPath();
3548         ctx.moveTo(0,rotate_image_height*1/4);
3549         ctx.lineTo(rotate_image_width, rotate_image_height*1/4);
3550         ctx.strokeStyle = color;
3551         ctx.lineWidth=5;
3552         ctx.stroke();
3554         ctx.beginPath();
3555         ctx.moveTo(0,rotate_image_height*3/4);
3556         ctx.lineTo(rotate_image_width, rotate_image_height*3/4);
3557         ctx.strokeStyle = color;
3558         ctx.lineWidth=5;
3559         ctx.stroke();
3560     }
3562     jQuery('#drone_imagery_rotate_stitched_submit').click(function() {
3563         var rotate_stitched_image_degrees_text = jQuery('#drone_imagery_rotate_degrees_input').val();
3564         if (rotate_stitched_image_degrees_text == '') {
3565             alert('Please give a number of degrees first! Can be a decimal amount.');
3566             return;
3567         }
3568         if (isNaN(rotate_stitched_image_degrees_text)) {
3569             alert('Please give a number of degrees first! Can be a decimal amount.');
3570             return;
3571         }
3572         rotate_stitched_image_degrees = parseFloat(rotate_stitched_image_degrees_text);
3573         jQuery.ajax({
3574             url : '/api/drone_imagery/rotate_image?image_id='+rotate_stitched_image_id+'&drone_run_band_project_id='+rotate_drone_run_band_project_id+'&angle='+rotate_stitched_image_degrees,
3575             beforeSend: function() {
3576                 jQuery("#working_modal").modal("show");
3577             },
3578             success: function(response){
3579                 console.log(response);
3580                 jQuery("#working_modal").modal("hide");
3581                 location.reload();
3582             },
3583             error: function(response){
3584                 jQuery("#working_modal").modal("hide");
3585                 alert('Error saving rotated image image!')
3586             }
3587         });
3588     });
3590     //
3591     // Image Cropping JS
3592     //
3594     var trial_id;
3595     var stitched_image_id;
3596     var rotated_stitched_image_id;
3597     var stitched_image;
3598     var drone_run_project_id;
3599     var drone_run_band_project_id;
3600     var crop_points = [];
3601     var crop_display_points = [];
3602     var dronecroppingImg;
3604     jQuery(document).on('click', 'button[name="project_drone_imagery_crop_image"]', function() {
3605         trial_id = jQuery(this).data('field_trial_id');
3606         stitched_image_id = jQuery(this).data('stitched_image_id');
3607         stitched_image = jQuery(this).data('stitched_image');
3608         drone_run_project_id = jQuery(this).data('drone_run_project_id');
3609         drone_run_band_project_id = jQuery(this).data('drone_run_band_project_id');
3610         rotated_stitched_image_id = jQuery(this).data('rotated_stitched_image_id');
3612         get_select_box('drone_imagery_parameter_select','plot_polygons_previously_saved_image_cropping_templates', {'name':'drone_imagery_previously_saved_image_cropping_select', 'id':'drone_imagery_previously_saved_image_cropping_select', 'empty':1, 'field_trial_id':trial_id, 'parameter':'image_cropping' });
3614         showManageDroneImagerySection('manage_drone_imagery_crop_div');
3616         showCropImageStart(rotated_stitched_image_id, 'drone_imagery_crop_original_stitched_div', 'manage_drone_imagery_crop_load_div');
3617     });
3619     function showCropImageStart(rotated_stitched_image_id, canvas_div_id, load_div_id) {
3620         crop_points = [];
3621         crop_display_points = [];
3622         jQuery.ajax({
3623             url : '/api/drone_imagery/get_image?image_id='+rotated_stitched_image_id,
3624             beforeSend: function() {
3625                 jQuery("#working_modal").modal("show");
3626             },
3627             success: function(response){
3628                 console.log(response);
3629                 jQuery("#working_modal").modal("hide");
3631                 var canvas = document.getElementById(canvas_div_id);
3632                 ctx = canvas.getContext('2d');
3633                 var image = new Image();
3634                 image.onload = function () {
3635                     canvas.width = this.naturalWidth;
3636                     canvas.height = this.naturalHeight;
3637                     ctx.drawImage(this, 0, 0);
3638                     jQuery('#'+load_div_id).hide();
3639                 };
3640                 image.src = response.image_url;
3641                 dronecroppingImg = canvas;
3642                 dronecroppingImg.onmousedown = GetCoordinatesCroppedImage;
3643             },
3644             error: function(response){
3645                 jQuery("#working_modal").modal("hide");
3646                 alert('Error retrieving image!')
3647             }
3648         });
3649     }
3651     function FindPosition(oElement) {
3652         if(typeof( oElement.offsetParent ) != "undefined") {
3653             for(var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) {
3654                 posX += oElement.offsetLeft;
3655                 posY += oElement.offsetTop;
3656             }
3657             return [ posX, posY ];
3658         } else {
3659             return [ oElement.x, oElement.y ];
3660         }
3661     }
3663     function GetCoordinatesCroppedImage(e) {
3664         var PosX = 0;
3665         var PosY = 0;
3666         var ImgPos;
3667         ImgPos = FindPosition(dronecroppingImg);
3668         if (!e) var e = window.event;
3669         if (e.pageX || e.pageY) {
3670             PosX = e.pageX;
3671             PosY = e.pageY;
3672         }
3673         else if (e.clientX || e.clientY) {
3674             PosX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
3675             PosY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
3676         }
3677         PosX = PosX - ImgPos[0];
3678         PosY = PosY - ImgPos[1];
3680         if (drone_imagery_standard_process_plot_polygon_click_type == 'standard_process_raw_images_paste_polygon') {
3681             plotPolygonsTemplatePasteRawImage(PosX, PosY, manage_drone_imagery_standard_process_raw_images_polygon);
3682             drone_imagery_standard_process_plot_polygon_click_type = '';
3683         }
3684         else if (drone_imagery_standard_process_plot_polygon_click_type == 'standard_process_raw_images_paste_previous_polygon') {
3685             manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new = {};
3686             var manage_drone_imagery_standard_process_raw_images_previous_polygon_template = JSON.parse(decodeURI(manage_drone_imagery_standard_process_raw_images_previous_polygon));
3688             manage_drone_imagery_standard_process_raw_images_previous_polygon = [];
3689             for (var index in manage_drone_imagery_standard_process_raw_images_previous_polygon_template) {
3690                 if (manage_drone_imagery_standard_process_raw_images_previous_polygon_template.hasOwnProperty(index)) {
3691                     manage_drone_imagery_standard_process_raw_images_previous_polygon.push(manage_drone_imagery_standard_process_raw_images_previous_polygon_template[index]);
3692                 }
3693             }
3694             console.log(manage_drone_imagery_standard_process_raw_images_previous_polygon);
3696             var PosX_shift = manage_drone_imagery_standard_process_raw_images_previous_polygon[0][0]['x']-PosX;
3697             var PosY_shift = manage_drone_imagery_standard_process_raw_images_previous_polygon[0][0]['y']-PosY;
3699             for (var i=0; i<manage_drone_imagery_standard_process_raw_images_previous_polygon.length; i++) {
3700                 plot_polygons_ind_4_points = manage_drone_imagery_standard_process_raw_images_previous_polygon[i];
3701                 plot_polygons_display_points = plot_polygons_ind_4_points;
3702                 if (plot_polygons_display_points.length == 4) {
3703                     plot_polygons_display_points.push(plot_polygons_ind_4_points[0]);
3704                 }
3705                 console.log(plot_polygons_display_points);
3706                 var plot_polygons_display_points_shifted = [];
3707                 for (var j=0; j<plot_polygons_display_points.length; j++) {
3708                     plot_polygons_display_points_shifted.push({'x':plot_polygons_display_points[j]['x']-PosX_shift, 'y':plot_polygons_display_points[j]['y']-PosY_shift});
3709                 }
3710                 plot_polygons_display_points = plot_polygons_display_points_shifted;
3711                 drawPolyline(plot_polygons_display_points);
3712                 drawWaypoints(plot_polygons_display_points, i, 0);
3713                 drone_imagery_plot_generated_polygons[i] = plot_polygons_display_points;
3714                 manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new[i] = plot_polygons_display_points;
3715                 drone_imagery_plot_polygons_display[i] = plot_polygons_display_points;
3716             }
3718             crop_points = manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new;
3719             
3720             var table_html = '<table class="table table-bordered table-hover"><thead><tr><th>Generated Index</th><th>Plot Number</th></tr></thead><tbody>';
3721             for (var gen_index in manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new) {
3722                 if (manage_drone_imagery_standard_process_raw_images_drone_imagery_plot_polygons_new.hasOwnProperty(gen_index)) {
3723                     table_html = table_html + '<tr><td>'+gen_index+'</td><td><input type="text" class="form-control" placeholder="e.g. 1001" name="manage_drone_imagery_standard_process_raw_images_given_plot_number" data-generated_index="'+gen_index+'"></td></tr>';
3724                 }
3725             }
3726             table_html = table_html + '</tbody></table>';
3728             jQuery('#drone_imagery_standard_process_raw_images_polygon_assign_table').html(table_html);
3729             
3730             drone_imagery_standard_process_plot_polygon_click_type = '';
3731         }
3732         else {
3733             if (crop_points.length < 4){
3734                 crop_points.push({x:PosX, y:PosY});
3735                 crop_display_points.push({x:PosX, y:PosY});
3736             } else {
3737                 crop_display_points.push({x:PosX, y:PosY});
3738                 console.log(crop_points);
3739             }
3740             if (crop_display_points.length > 5){
3741                 crop_points = [];
3742                 crop_display_points = [];
3743             }
3744             drawPolyline(crop_display_points);
3745             drawWaypoints(crop_display_points, undefined, 0);
3746         }
3747     }
3749     function drawPolyline(points){
3750         if (points.length == 4) {
3751             points.push(points[0]);
3752         }
3753         for(var i=0;i<points.length;i++){
3754             ctx.beginPath();
3755             ctx.moveTo(points[0].x,points[0].y);
3756             for(var i=1;i<points.length;i++){
3757                 ctx.lineTo(points[i].x,points[i].y);
3758             }
3759             ctx.strokeStyle='blue';
3760             ctx.lineWidth=5;
3761             ctx.stroke();
3762         }
3763     }
3765     function drawWaypoints(points, label, random_factor){
3766         var plot_polygon_random_number = Math.random() * random_factor;
3767         if (points.length > 0 && label != undefined) {
3768             if (drone_imagery_plot_polygons_removed_numbers.includes(label)) {
3769                 ctx.font = "bold 18px Arial";
3770                 ctx.fillStyle = 'blue';
3771                 ctx.fillText('NA', points[0].x + 3, points[0].y + 14 + plot_polygon_random_number);
3772             } else {
3773                 ctx.font = "bold 18px Arial";
3774                 ctx.fillStyle = 'red';
3775                 ctx.fillText(label, points[0].x + 3, points[0].y + 14 + plot_polygon_random_number);
3776                 //ctx.fillText(label.toString().substring(label.length - 3), points[0].x + 3, points[0].y + 14 + plot_polygon_random_number);
3777             }
3778         }
3779         for(var i=0;i<points.length;i++){
3780             ctx.beginPath();
3781             ctx.arc(points[i].x,points[i].y,4,0,Math.PI*2);
3782             ctx.closePath();
3783             ctx.strokeStyle='black';
3784             ctx.lineWidth=1;
3785             ctx.stroke();
3786             ctx.fillStyle='white';
3787             ctx.fill();
3788         }
3789     }
3791     jQuery(document).on('click', '#drone_imagery_crop_stitched_submit', function(){
3792         jQuery.ajax({
3793             url : '/api/drone_imagery/crop_image?image_id='+rotated_stitched_image_id+'&polygon='+JSON.stringify(crop_points)+'&drone_run_band_project_id='+drone_run_band_project_id,
3794             beforeSend: function() {
3795                 jQuery("#working_modal").modal("show");
3796             },
3797             success: function(response){
3798                 console.log(response);
3799                 jQuery("#working_modal").modal("hide");
3800                 location.reload();
3801             },
3802             error: function(response){
3803                 jQuery("#working_modal").modal("hide");
3804                 alert('Error cropping image!')
3805             }
3806         });
3807     });
3809     jQuery(document).on('click', '#drone_imagery_cropping_use_previous_cropping', function() {
3810         var plot_polygons_use_previously_saved_cropping = jQuery('#drone_imagery_previously_saved_image_cropping_select').val();
3811         jQuery.ajax({
3812             url : '/api/drone_imagery/retrieve_parameter_template?plot_polygons_template_projectprop_id='+plot_polygons_use_previously_saved_cropping,
3813             success: function(response){
3814                 console.log(response);
3815                 jQuery.ajax({
3816                     url : '/api/drone_imagery/crop_image?image_id='+rotated_stitched_image_id+'&polygon='+JSON.stringify(response.parameter[0])+'&drone_run_band_project_id='+drone_run_band_project_id,
3817                     beforeSend: function() {
3818                         jQuery("#working_modal").modal("show");
3819                     },
3820                     success: function(response){
3821                         console.log(response);
3822                         jQuery("#working_modal").modal("hide");
3823                         location.reload();
3824                     },
3825                     error: function(response){
3826                         jQuery("#working_modal").modal("hide");
3827                         alert('Error cropping image!')
3828                     }
3829                 });
3830             },
3831             error: function(response){
3832                 alert('Error retrieving saved cropping template!');
3833             }
3834         });
3835         return;
3836     });
3838     //
3839     // Denoising JS
3840     //
3842     var gridData = new Array();
3844     jQuery(document).on('click', 'button[name="project_drone_imagery_denoise"]', function() {
3845         var trial_id = jQuery(this).data('field_trial_id');
3846         var drone_run_project_id = jQuery(this).data('drone_run_project_id');
3847         var drone_run_band_project_id = jQuery(this).data('drone_run_band_project_id');
3848         var cropped_stitched_image_id = jQuery(this).data('cropped_stitched_image_id');
3849         var stitched_image = jQuery(this).data('stitched_image');
3850         var cropped_stitched_image = jQuery(this).data('cropped_stitched_image');
3852         jQuery.ajax({
3853             url : '/api/drone_imagery/denoise?image_id='+cropped_stitched_image_id+'&drone_run_band_project_id='+drone_run_band_project_id,
3854             beforeSend: function() {
3855                 jQuery("#working_modal").modal("show");
3856             },
3857             success: function(response){
3858                 console.log(response);
3859                 jQuery("#working_modal").modal("hide");
3860                 location.reload();
3861             },
3862             error: function(response){
3863                 jQuery("#working_modal").modal("hide");
3864                 alert('Error denoising image!')
3865             }
3866         });
3868     });
3870     //
3871     //Define Plot Polygons JS
3872     //
3874     var canvas;
3875     var background_image_url;
3876     var background_image_width;
3877     var background_image_height;
3878     var plot_polygons_display_points = [];
3879     var plot_polygons_ind_points = [];
3880     var plot_polygons_ind_4_points = [];
3881     var drone_imagery_plot_polygons = {};
3882     var drone_imagery_plot_generated_polygons = {};
3883     var drone_imagery_plot_polygons_display = {};
3884     var plot_polygons_generated_polygons = [];
3885     var drone_imagery_plot_polygons_removed_numbers = [];
3886     var field_trial_layout_response = {};
3887     var plot_polygon_name;
3888     var plotpolygonsImg;
3889     var drone_imagery_plot_polygons_available_stock_names = [];
3890     var trial_id;
3891     var cropped_stitched_image_id;
3892     var denoised_stitched_image_id;
3893     var background_removed_stitched_image_id;
3894     var drone_run_project_id;
3895     var drone_run_band_project_id;
3896     var assign_plot_polygons_type;
3898     jQuery(document).on('click', 'button[name="project_drone_imagery_plot_polygons"]', function(){
3899         trial_id = jQuery(this).data('field_trial_id');
3900         cropped_stitched_image_id = jQuery(this).data('cropped_stitched_image_id');
3901         denoised_stitched_image_id = jQuery(this).data('denoised_stitched_image_id');
3902         background_removed_stitched_image_id = jQuery(this).data('background_removed_stitched_image_id');
3903         drone_run_project_id = jQuery(this).data('drone_run_project_id');
3904         drone_run_band_project_id = jQuery(this).data('drone_run_band_project_id');
3905         assign_plot_polygons_type = jQuery(this).data('assign_plot_polygons_type');
3907         get_select_box('drone_imagery_parameter_select','plot_polygons_previously_saved_plot_polygon_templates', {'empty':1, 'field_trial_id':trial_id, 'parameter':'plot_polygons' });
3909         plot_polygons_display_points = [];
3910         plot_polygons_ind_points = [];
3911         plot_polygons_ind_4_points = [];
3912         drone_imagery_plot_polygons = {};
3913         drone_imagery_plot_generated_polygons = {};
3914         drone_imagery_plot_polygons_display = {};
3915         field_trial_layout_response = {};
3917         showManageDroneImagerySection('manage_drone_imagery_plot_polygons_div');
3919         showPlotPolygonStart(background_removed_stitched_image_id, drone_run_band_project_id, 'drone_imagery_plot_polygons_original_stitched_div', 'drone_imagery_plot_polygons_top_section', 'manage_drone_imagery_plot_polygons_load_div');
3921         showPlotPolygonTableStart(trial_id, 'drone_imagery_trial_layout_div', 'drone_imagery_layout_table');
3922     });
3924     function showPlotPolygonTableStart(trial_id, layout_div, layout_table){
3925         jQuery.ajax({
3926             url : '/ajax/breeders/trial/'+trial_id+'/layout_table',
3927             beforeSend: function() {
3928                 jQuery("#working_modal").modal("show");
3929             },
3930             success: function(response){
3931                 console.log(response);
3932                 field_trial_layout_response = response;
3933                 var layout = field_trial_layout_response.output;
3934                 for (var i=1; i<layout.length; i++) {
3935                     drone_imagery_plot_polygons_available_stock_names.push(layout[i][0]);
3936                 }
3937                 droneImageryDrawLayoutTable(response, {}, layout_div, layout_table);
3938                 jQuery("#working_modal").modal("hide");
3939             },
3940             error: function(response){
3941                 jQuery("#working_modal").modal("hide");
3942                 alert('Error retrieving trial layout and design!')
3943             }
3944         });
3945     }
3947     function showPlotPolygonStart(background_removed_stitched_image_id, drone_run_band_project_id, canvas_div_id, info_div_id, load_div_id){
3948         //jQuery.ajax({
3949         //    url : '/api/drone_imagery/get_contours?image_id='+background_removed_stitched_image_id+'&drone_run_band_project_id='+drone_run_band_project_id,
3950         //    beforeSend: function() {
3951         //        jQuery("#working_modal").modal("show");
3952         //    },
3953         //    success: function(response){
3954         //        console.log(response);
3955         //        jQuery("#working_modal").modal("hide");
3956         //        background_image_url = response.image_url;
3958         //        background_image_width = response.image_width;
3959         //        background_image_height = response.image_height;
3961         //        var top_section_html = '<h4>Total Image Width: '+response.image_width+'px. Total Image Height: '+response.image_height+'px.</h4>';
3962         //        top_section_html = top_section_html + '<button class="btn btn-default btn-sm" id="drone_imagery_plot_polygons_switch" data-image_url="'+response.image_url+'" data-image_fullpath="'+response.image_fullpath+'" data-contours_image_url="'+response.contours_image_url+'" data-contours_image_fullpath="'+response.contours_image_fullpath+'">Switch Image View</button><br/><br/>';
3963         //        jQuery('#'+info_div_id).html(top_section_html);
3965         //        canvas = document.getElementById(canvas_div_id);
3966         //        ctx = canvas.getContext('2d');
3967         //        draw_canvas_image(background_image_url, 0);
3969         //        plotpolygonsImg = document.getElementById(canvas_div_id);
3970                 //plotpolygonsImg.onmousedown = GetCoordinatesPlotPolygons;
3971         //        plotpolygonsImg.onmousedown = GetCoordinatesPlotPolygonsPoint;
3973         //        jQuery('#'+load_div_id).hide();
3975         //    },
3976         //    error: function(response){
3977         //        jQuery("#working_modal").modal("hide");
3978         //        alert('Error retrieving contours for image!')
3979         //    }
3980         //});
3982         jQuery.ajax({
3983             url : '/api/drone_imagery/get_image?image_id='+background_removed_stitched_image_id,
3984             beforeSend: function() {
3985                 jQuery("#working_modal").modal("show");
3986             },
3987             success: function(response){
3988                 console.log(response);
3989                 background_image_url = response.image_url;
3991                 background_image_width = response.image_width;
3992                 background_image_height = response.image_height;
3994                 var top_section_html = '<h4>Total Image Width: '+response.image_width+'px. Total Image Height: '+response.image_height+'px.</h4>';
3996                 jQuery('#'+info_div_id).html(top_section_html);
3998                 canvas = document.getElementById(canvas_div_id);
3999                 ctx = canvas.getContext('2d');
4000                 draw_canvas_image(background_image_url, 0);
4002                 plotpolygonsImg = document.getElementById(canvas_div_id);
4003                 //plotpolygonsImg.onmousedown = GetCoordinatesPlotPolygons;
4004                 plotpolygonsImg.onmousedown = GetCoordinatesPlotPolygonsPoint;
4006                 jQuery('#'+load_div_id).hide();
4007             },
4008             error: function(response){
4009                 jQuery("#working_modal").modal("hide");
4010                 alert('Error retrieving plot polygon image!')
4011             }
4012         });
4013     }
4015     var drone_imagery_plot_polygon_click_type = '';
4016     jQuery('#drone_imagery_plot_polygons_top_left_click').click(function(){
4017         alert('Now click the top left corner of your field on the image below.');
4018         drone_imagery_plot_polygon_click_type = 'top_left';
4019     });
4020     jQuery('#drone_imagery_plot_polygons_top_right_click').click(function(){
4021         alert('Now click the top right corner of your field on the image below.');
4022         drone_imagery_plot_polygon_click_type = 'top_right';
4023     });
4024     jQuery('#drone_imagery_plot_polygons_bottom_left_click').click(function(){
4025         alert('Now click the bottom left corner of your field on the image below.');
4026         drone_imagery_plot_polygon_click_type = 'bottom_left';
4027     });
4028     jQuery('#drone_imagery_plot_polygons_bottom_right_click').click(function(){
4029         alert('Now click the bottom right corner of your field on the image below.');
4030         drone_imagery_plot_polygon_click_type = 'bottom_right';
4031     });
4032     jQuery(document).on('click', '#drone_imagery_plot_polygons_get_distance', function(){
4033         alert('Click on two points in image. The distance will be returned.');
4034         drone_imagery_plot_polygon_click_type = 'get_distance';
4035         return false;
4036     });
4038     var drone_imagery_plot_polygon_current_background_toggle = 1;
4039     jQuery(document).on('click', '#drone_imagery_plot_polygons_switch', function(){
4040         var image_url;
4041         if (drone_imagery_plot_polygon_current_background_toggle == 0) {
4042             drone_imagery_plot_polygon_current_background_toggle = 1;
4043             image_url = jQuery(this).data('contours_image_url');
4044         } else if (drone_imagery_plot_polygon_current_background_toggle == 1) {
4045             drone_imagery_plot_polygon_current_background_toggle = 0;
4046             image_url = jQuery(this).data('image_url');
4047         }
4048         draw_canvas_image(image_url, plot_polygons_total_height_generated/plot_polygons_num_rows_generated);
4050         return;
4051     });
4053     jQuery('#plot_polygons_use_previously_saved_template').click(function() {
4054         var plot_polygons_use_previously_saved_template = jQuery('#drone_imagery_plot_polygon_select').val();
4055         if (plot_polygons_use_previously_saved_template == '') {
4056             alert('Please select a previously saved template before trying to apply it. If there is not a template listed, then you can create one using the templating tool above.');
4057             return;
4058         }
4060         jQuery.ajax({
4061             url : '/api/drone_imagery/retrieve_parameter_template?plot_polygons_template_projectprop_id='+plot_polygons_use_previously_saved_template,
4062             success: function(response){
4063                 console.log(response);
4065                 drone_imagery_plot_polygons_display = response.parameter;
4066                 drone_imagery_plot_polygons = response.parameter;
4068                 draw_canvas_image(background_image_url, 0);
4069                 droneImageryDrawLayoutTable(field_trial_layout_response, drone_imagery_plot_polygons, 'drone_imagery_trial_layout_div', 'drone_imagery_layout_table');
4070                 droneImageryRectangleLayoutTable(drone_imagery_plot_polygons, 'drone_imagery_generated_polygons_div', 'drone_imagery_generated_polygons_table', 'drone_imagery_plot_polygons_generated_assign', 'drone_imagery_plot_polygons_submit_bottom');
4071             },
4072             error: function(response){
4073                 alert('Error retrieving plot polygons template!');
4074             }
4075         });
4076         return;
4077     });
4079     var plot_polygons_num_rows_generated;
4080     var plot_polygons_num_cols_generated;
4081     var plot_polygons_number_generated;
4082     var plot_polygons_total_height_generated;
4083     var plot_polygons_template_dimensions = [];
4085     jQuery('#drone_imagery_plot_polygons_rectangles_apply').click(function() {
4086         plot_polygons_display_points = [];
4087         plot_polygons_ind_points = [];
4088         plot_polygons_ind_4_points = [];
4090         var num_rows_val = jQuery('#drone_imagery_plot_polygons_num_rows').val();
4091         var num_cols_val = jQuery('#drone_imagery_plot_polygons_num_cols').val();
4092         var section_top_row_left_offset_val = jQuery('#drone_imagery_plot_polygons_top_row_left_offset').val();
4093         var section_bottom_row_left_offset_val = jQuery('#drone_imagery_plot_polygons_bottom_row_left_offset').val();
4094         var section_left_column_top_offset_val = jQuery('#drone_imagery_plot_polygons_left_column_top_offset').val();
4095         var section_left_column_bottom_offset_val = jQuery('#drone_imagery_plot_polygons_left_column_bottom_offset').val();
4096         var section_top_row_right_offset_val = jQuery('#drone_imagery_plot_polygons_top_row_right_offset').val();
4097         var section_right_column_bottom_offset_val = jQuery('#drone_imagery_plot_polygons_right_col_bottom_offset').val();
4099         plotPolygonsRectanglesApply(num_rows_val, num_cols_val, section_top_row_left_offset_val, section_bottom_row_left_offset_val, section_left_column_top_offset_val, section_left_column_bottom_offset_val, section_top_row_right_offset_val, section_right_column_bottom_offset_val, 'drone_imagery_generated_polygons_div', 'drone_imagery_generated_polygons_table', 'drone_imagery_plot_polygons_generated_assign', 'drone_imagery_plot_polygons_submit_bottom', 'drone_imagery_plot_polygons_active_templates');
4100     });
4102     function plotPolygonsRectanglesApply(num_rows_val, num_cols_val, section_top_row_left_offset_val, section_bottom_row_left_offset_val, section_left_column_top_offset_val, section_left_column_bottom_offset_val, section_top_row_right_offset_val, section_right_column_bottom_offset_val, plot_polygons_assignment_info, plot_polygons_assignment_table, plot_polygons_generate_assignment_button, plot_polygon_assignment_submit_button, drone_imagery_plot_polygons_active_templates) {
4103         if (num_rows_val == ''){
4104             alert('Please give the number of rows!');
4105             return;
4106         }
4107         if (num_cols_val == ''){
4108             alert('Please give the number of columns!');
4109             return;
4110         }
4111         if (section_top_row_left_offset_val == ''){
4112             alert('Please give the top-most rows left margin! This can be 0 if there is no offset.');
4113             return;
4114         }
4115         if (section_bottom_row_left_offset_val == ''){
4116             alert('Please give the bottom-most rows left margin! This can be 0 if there is no offset.');
4117             return;
4118         }
4119         if (section_left_column_top_offset_val == ''){
4120             alert('Please give the left-most columns top margin! This can be 0 if there is no offset.');
4121             return;
4122         }
4123         if (section_left_column_bottom_offset_val == ''){
4124             alert('Please give the left-most columns bottom margin! This can be 0 if there is no offset.');
4125             return;
4126         }
4127         if (section_top_row_right_offset_val == ''){
4128             alert('Please give the top-most rows right margin! This can be 0 if there is no offset.');
4129             return;
4130         }
4131         if (section_right_column_bottom_offset_val == ''){
4132             alert('Please give the right-most columns bottom margin! This can be 0 if there is no offset.');
4133             return;
4134         }
4136         plot_polygons_num_rows_generated = parseInt(num_rows_val);
4137         plot_polygons_num_cols_generated = parseInt(num_cols_val);
4139         var section_width = background_image_width;
4140         var section_height = background_image_height;
4141         var section_top_row_left_offset = parseInt(section_top_row_left_offset_val);
4142         var section_bottom_row_left_offset = parseInt(section_bottom_row_left_offset_val);
4143         var section_left_column_top_offset = parseInt(section_left_column_top_offset_val);
4144         var section_left_column_bottom_offset = parseInt(section_left_column_bottom_offset_val);
4145         var section_top_row_right_offset = parseInt(section_top_row_right_offset_val);
4146         var section_right_column_bottom_offset = parseInt(section_right_column_bottom_offset_val);
4148         var total_gradual_left_shift = section_bottom_row_left_offset - section_top_row_left_offset;
4149         var col_left_shift_increment = total_gradual_left_shift / plot_polygons_num_rows_generated;
4151         var total_gradual_vertical_shift = section_right_column_bottom_offset - section_left_column_bottom_offset;
4152         var col_vertical_shift_increment = total_gradual_vertical_shift / plot_polygons_num_cols_generated;
4154         var col_width = (section_width - section_top_row_left_offset - section_top_row_right_offset) / plot_polygons_num_cols_generated;
4155         var row_height = (section_height - section_left_column_top_offset - section_left_column_bottom_offset) / plot_polygons_num_rows_generated;
4157         var x_pos = section_top_row_left_offset;
4158         var y_pos = section_left_column_top_offset;
4160         var row_num = 1;
4161         for (var i=0; i<plot_polygons_num_rows_generated; i++) {
4162             for (var j=0; j<plot_polygons_num_cols_generated; j++) {
4163                 var x_pos_val = x_pos;
4164                 var y_pos_val = y_pos;
4165                 plot_polygons_generated_polygons.push([
4166                     {x:x_pos_val, y:y_pos_val},
4167                     {x:x_pos_val + col_width, y:y_pos_val},
4168                     {x:x_pos_val + col_width, y:y_pos_val + row_height},
4169                     {x:x_pos_val, y:y_pos_val + row_height}
4170                 ]);
4171                 x_pos = x_pos + col_width;
4172                 y_pos = y_pos - col_vertical_shift_increment;
4173             }
4174             x_pos = section_top_row_left_offset + (row_num * col_left_shift_increment);
4175             y_pos = y_pos + row_height + total_gradual_vertical_shift;
4176             row_num = row_num + 1;
4177         }
4178         //console.log(plot_polygons_generated_polygons);
4180         plot_polygons_total_height_generated = row_height * plot_polygons_num_rows_generated;
4181         plot_polygons_number_generated = plot_polygons_generated_polygons.length;
4183         var drone_imagery_plot_polygons_new = {};
4184         var drone_imagery_plot_polygons_display_new = {};
4186         for (var i=0; i<plot_polygons_generated_polygons.length; i++) {
4187             plot_polygons_ind_4_points = plot_polygons_generated_polygons[i];
4188             plot_polygons_display_points = plot_polygons_ind_4_points;
4189             if (plot_polygons_display_points.length == 4) {
4190                 plot_polygons_display_points.push(plot_polygons_ind_4_points[0]);
4191             }
4192             drawPolyline(plot_polygons_display_points);
4193             drawWaypoints(plot_polygons_display_points, i, 0);
4194             drone_imagery_plot_generated_polygons[i] = plot_polygons_ind_4_points;
4195             drone_imagery_plot_polygons_new[i] = plot_polygons_ind_4_points;
4196             drone_imagery_plot_polygons_display[i] = plot_polygons_display_points;
4197             drone_imagery_plot_polygons_display_new[i] = plot_polygons_display_points;
4198         }
4200         plot_polygons_template_dimensions.push({
4201             'num_rows':plot_polygons_num_rows_generated,
4202             'num_cols':plot_polygons_num_cols_generated,
4203             'total_plot_polygons':plot_polygons_num_rows_generated*plot_polygons_num_cols_generated,
4204             'plot_polygons':drone_imagery_plot_polygons_new,
4205             'plot_polygons_display':drone_imagery_plot_polygons_display_new
4206         });
4208         droneImageryDrawPlotPolygonActiveTemplatesTable(drone_imagery_plot_polygons_active_templates, plot_polygons_template_dimensions, drone_imagery_plot_generated_polygons, drone_imagery_plot_polygons_display);
4210         droneImageryRectangleLayoutTable(drone_imagery_plot_generated_polygons, plot_polygons_assignment_info, plot_polygons_assignment_table, plot_polygons_generate_assignment_button, plot_polygon_assignment_submit_button);
4211     }
4213     function plotPolygonsTemplatePaste(posx, posy, plot_polygon_template_id, plot_polygons_assignment_info, plot_polygons_assignment_table, plot_polygons_generate_assignment_button, plot_polygon_assignment_submit_button, drone_imagery_plot_polygons_active_templates) {
4214         var plot_polygon_template_to_paste = plot_polygons_template_dimensions[plot_polygon_template_id];
4216         var plot_polygons_previous_plot_polygons = plot_polygon_template_to_paste['plot_polygons'];
4217         plot_polygons_num_rows_generated = plot_polygon_template_to_paste['num_rows'];
4218         plot_polygons_num_cols_generated = plot_polygon_template_to_paste['num_cols'];
4220         var section_width = background_image_width;
4221         var section_height = background_image_height;
4223         var plot_polygon_top_left_position = plot_polygons_previous_plot_polygons[0][0];
4224         var plot_polygon_template_paste_x_diff = plot_polygon_top_left_position['x'] - posx;
4225         var plot_polygon_template_paste_y_diff = plot_polygon_top_left_position['y'] - posy;
4227         for (var i in plot_polygons_previous_plot_polygons) {
4228             plot_polygons_generated_polygons.push([
4229                 {x:plot_polygons_previous_plot_polygons[i][0]['x'] - plot_polygon_template_paste_x_diff, y:plot_polygons_previous_plot_polygons[i][0]['y']- plot_polygon_template_paste_y_diff},
4230                 {x:plot_polygons_previous_plot_polygons[i][1]['x'] - plot_polygon_template_paste_x_diff, y:plot_polygons_previous_plot_polygons[i][1]['y'] - plot_polygon_template_paste_y_diff},
4231                 {x:plot_polygons_previous_plot_polygons[i][2]['x'] - plot_polygon_template_paste_x_diff, y:plot_polygons_previous_plot_polygons[i][2]['y'] - plot_polygon_template_paste_y_diff},
4232                 {x:plot_polygons_previous_plot_polygons[i][3]['x'] - plot_polygon_template_paste_x_diff, y:plot_polygons_previous_plot_polygons[i][3]['y'] - plot_polygon_template_paste_y_diff}
4233             ]);
4234         }
4236         plot_polygons_number_generated = plot_polygons_generated_polygons.length;
4237         console.log(plot_polygons_generated_polygons);
4239         var drone_imagery_plot_polygons_new = {};
4240         var drone_imagery_plot_polygons_display_new = {};
4242         for (var i=0; i<plot_polygons_generated_polygons.length; i++) {
4243             plot_polygons_ind_4_points = plot_polygons_generated_polygons[i];
4244             plot_polygons_display_points = plot_polygons_ind_4_points;
4245             if (plot_polygons_display_points.length == 4) {
4246                 plot_polygons_display_points.push(plot_polygons_ind_4_points[0]);
4247             }
4248             drawPolyline(plot_polygons_display_points);
4249             drawWaypoints(plot_polygons_display_points, i, 0);
4250             drone_imagery_plot_generated_polygons[i] = plot_polygons_ind_4_points;
4251             drone_imagery_plot_polygons_new[i] = plot_polygons_ind_4_points;
4252             drone_imagery_plot_polygons_display[i] = plot_polygons_display_points;
4253             drone_imagery_plot_polygons_display_new[i] = plot_polygons_display_points;
4254         }
4256         plot_polygons_template_dimensions.push({
4257             'num_rows':plot_polygons_num_rows_generated,
4258             'num_cols':plot_polygons_num_cols_generated,
4259             'total_plot_polygons':plot_polygons_num_rows_generated*plot_polygons_num_cols_generated,
4260             'plot_polygons':drone_imagery_plot_polygons_new,
4261             'plot_polygons_display':drone_imagery_plot_polygons_display_new
4262         });
4264         droneImageryDrawPlotPolygonActiveTemplatesTable(drone_imagery_plot_polygons_active_templates, plot_polygons_template_dimensions);
4266         droneImageryRectangleLayoutTable(drone_imagery_plot_generated_polygons, plot_polygons_assignment_info, plot_polygons_assignment_table, plot_polygons_generate_assignment_button, plot_polygon_assignment_submit_button);
4267     }
4269     function plotPolygonsTemplatePasteRawImage(posx, posy, polygon) {
4270         var plot_polygon_top_left_position = polygon[0];
4271         var plot_polygon_template_paste_x_diff = plot_polygon_top_left_position['x'] - posx;
4272         var plot_polygon_template_paste_y_diff = plot_polygon_top_left_position['y'] - posy;
4274         crop_points = [
4275             {x:polygon[0]['x'] - plot_polygon_template_paste_x_diff, y:polygon[0]['y'] - plot_polygon_template_paste_y_diff},
4276             {x:polygon[1]['x'] - plot_polygon_template_paste_x_diff, y:polygon[1]['y'] - plot_polygon_template_paste_y_diff},
4277             {x:polygon[2]['x'] - plot_polygon_template_paste_x_diff, y:polygon[2]['y'] - plot_polygon_template_paste_y_diff},
4278             {x:polygon[3]['x'] - plot_polygon_template_paste_x_diff, y:polygon[3]['y'] - plot_polygon_template_paste_y_diff}
4279         ];
4281         plot_polygons_ind_4_points = JSON.parse(JSON.stringify(crop_points));
4282         plot_polygons_display_points = plot_polygons_ind_4_points;
4283         if (plot_polygons_display_points.length == 4) {
4284             plot_polygons_display_points.push(plot_polygons_ind_4_points[0]);
4285         }
4286         drawPolyline(plot_polygons_display_points);
4287         drawWaypoints(plot_polygons_display_points, 1, 0);
4288     }
4290     function droneImageryDrawPlotPolygonActiveTemplatesTable(div_id, plot_polygons_template_dimensions){
4291         var html = '<table class="table table-bordered table-hover"><thead><tr><th>Template Number</th><th>Rows</th><th>Columns</th><th>Total Polygons</th><th>Options</th></tr></thead><tbody>';
4292         for (var i=0; i<plot_polygons_template_dimensions.length; i++) {
4293             html = html + '<tr><td>'+i+'</td><td>'+plot_polygons_template_dimensions[i]['num_rows']+'</td><td>'+plot_polygons_template_dimensions[i]['num_cols']+'</td><td>'+plot_polygons_template_dimensions[i]['total_plot_polygons']+'</td><td><button class="btn btn-sm btn-primary" name="drone_imagery_plot_polygon_template_options" data-plot_polygon_template_id="'+i+'" >Options</button></td></tr>';
4294         }
4295         html = html + '</tbody></table>';
4296         jQuery('#'+div_id).html(html);
4297     }
4299     var drone_imagery_current_plot_polygon_index_options_id = '';
4300     jQuery(document).on('click', 'button[name="drone_imagery_plot_polygon_template_options"]', function(){
4301         jQuery('#drone_imagery_plot_polygon_template_options_dialog').modal('show');
4302         drone_imagery_current_plot_polygon_index_options_id = jQuery(this).data('plot_polygon_template_id');
4303     });
4305     jQuery('#drone_imagery_plot_polygon_template_options_paste_click').click(function(){
4306         jQuery('#drone_imagery_plot_polygon_template_options_dialog').modal('hide');
4307         alert('Click on where the top left corner of the template will be pasted.');
4308         drone_imagery_plot_polygon_click_type = 'plot_polygon_template_paste';
4309     });
4311     jQuery('input[name=drone_imagery_plot_polygons_autocomplete]').autocomplete({
4312         source: drone_imagery_plot_polygons_available_stock_names
4313     });
4315     jQuery(document).on('click', '#drone_imagery_plot_polygons_clear', function(){
4316         plot_polygons_display_points = [];
4317         plot_polygons_ind_points = [];
4318         plot_polygons_ind_4_points = [];
4319         drone_imagery_plot_polygons = {};
4320         drone_imagery_plot_generated_polygons = {};
4321         drone_imagery_plot_polygons_display = {};
4322         plot_polygons_generated_polygons = [];
4323         plot_polygons_template_dimensions = [];
4324         drone_imagery_plot_polygons_removed_numbers = [];
4325         ctx.clearRect(0, 0, canvas.width, canvas.height);
4326         draw_canvas_image(background_image_url, 0);
4327         jQuery('#drone_imagery_generated_polygons_div').html('');
4328         droneImageryDrawLayoutTable(field_trial_layout_response, drone_imagery_plot_polygons, 'drone_imagery_trial_layout_div', 'drone_imagery_layout_table');
4329         droneImageryDrawPlotPolygonActiveTemplatesTable("drone_imagery_plot_polygons_active_templates", plot_polygons_template_dimensions);
4330     });
4332     jQuery(document).on('click', '#drone_imagery_plot_polygons_clear_one', function(){
4333         jQuery('#drone_imagery_plot_polygon_remove_polygon').modal('show');
4334         return false;
4335     });
4337     jQuery('#drone_imagery_plot_polygon_remove_polygon_submit').click(function(){
4338         var polygon_number = jQuery('#drone_imagery_plot_polygon_remove_polygon_number').val();
4339         drone_imagery_plot_polygons_removed_numbers.push(polygon_number);
4340         draw_canvas_image(background_image_url, plot_polygons_total_height_generated/plot_polygons_num_rows_generated);
4341         return false;
4342     });
4344     function draw_canvas_image(image_url, random_scaling) {
4345         var image = new Image();
4346         image.onload = function () {
4347             canvas.width = this.naturalWidth;
4348             canvas.height = this.naturalHeight;
4349             ctx.drawImage(this, 0, 0);
4351             for (key in drone_imagery_plot_polygons_display) {
4352                 var plot_polygons_display_points_again = drone_imagery_plot_polygons_display[key];
4353                 drawPolyline(plot_polygons_display_points_again);
4354                 drawWaypoints(plot_polygons_display_points_again, key, random_scaling);
4355             }
4356         };
4357         image.src = image_url;
4358     }
4360     function GetCoordinatesPlotPolygons(e) {
4361         var PosX = 0;
4362         var PosY = 0;
4363         var ImgPos;
4364         ImgPos = FindPosition(plotpolygonsImg);
4365         if (!e) var e = window.event;
4366         if (e.pageX || e.pageY) {
4367             PosX = e.pageX;
4368             PosY = e.pageY;
4369         }
4370         else if (e.clientX || e.clientY) {
4371             PosX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
4372             PosY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
4373         }
4374         PosX = PosX - ImgPos[0];
4375         PosY = PosY - ImgPos[1];
4376         if (plot_polygons_ind_points.length <= 4){
4377             plot_polygons_ind_points.push({x:PosX, y:PosY});
4378             plot_polygons_display_points.push({x:PosX, y:PosY});
4380             if (plot_polygons_ind_points.length == 4) {
4381                 plot_polygons_ind_4_points = plot_polygons_ind_points;
4382             }
4383         } else if (plot_polygons_ind_points.length > 4) {
4384             if (plot_polygons_display_points.length == 5) {
4385                 jQuery('#drone_imagery_assign_plot_dialog').modal('show');
4386             }
4387             plot_polygons_ind_points = [];
4388         }
4389         drawPolyline(plot_polygons_display_points);
4390         drawWaypoints(plot_polygons_display_points, undefined, 0);
4391     }
4393     var plot_polygons_get_distance_point_1x = '';
4394     var plot_polygons_get_distance_point_1y = '';
4396     function GetCoordinatesPlotPolygonsPoint(e) {
4397         var PosX = 0;
4398         var PosY = 0;
4399         var ImgPos;
4400         ImgPos = FindPosition(plotpolygonsImg);
4401         if (!e) var e = window.event;
4402         if (e.pageX || e.pageY) {
4403             PosX = e.pageX;
4404             PosY = e.pageY;
4405         }
4406         else if (e.clientX || e.clientY) {
4407             PosX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
4408             PosY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
4409         }
4410         PosX = PosX - ImgPos[0];
4411         PosY = PosY - ImgPos[1];
4413         if (drone_imagery_plot_polygon_click_type == '' && drone_imagery_standard_process_plot_polygon_click_type == '') {
4414             alert('X Coordinate: '+PosX+'. Y Coordinate: '+PosY+'.');
4415         }
4416         else if (drone_imagery_plot_polygon_click_type == 'top_left') {
4417             drone_imagery_plot_polygon_click_type = '';
4418             jQuery('#drone_imagery_plot_polygons_left_column_top_offset').val(PosY);
4419             jQuery('#drone_imagery_plot_polygons_top_row_left_offset').val(PosX);
4420         }
4421         else if (drone_imagery_plot_polygon_click_type == 'top_right') {
4422             drone_imagery_plot_polygon_click_type = '';
4423             jQuery('#drone_imagery_plot_polygons_top_row_right_offset').val(background_image_width-PosX);
4424         }
4425         else if (drone_imagery_plot_polygon_click_type == 'bottom_left') {
4426             drone_imagery_plot_polygon_click_type = '';
4427             jQuery('#drone_imagery_plot_polygons_bottom_row_left_offset').val(PosX);
4428             jQuery('#drone_imagery_plot_polygons_left_column_bottom_offset').val(background_image_height-PosY);
4429         }
4430         else if (drone_imagery_plot_polygon_click_type == 'bottom_right') {
4431             drone_imagery_plot_polygon_click_type = '';
4432             jQuery('#drone_imagery_plot_polygons_right_col_bottom_offset').val(background_image_height-PosY);
4433         }
4434         else if (drone_imagery_plot_polygon_click_type == 'get_distance') {
4435             if (plot_polygons_get_distance_point_1x != '') {
4436                 var distance = Math.round(Math.sqrt(Math.pow(plot_polygons_get_distance_point_1x - PosX, 2) + Math.pow(plot_polygons_get_distance_point_1y - PosY, 2)));
4437                 alert('Distance='+distance+'. X1='+plot_polygons_get_distance_point_1x+'. Y1='+plot_polygons_get_distance_point_1y+'. X2='+PosX+'. Y2='+PosY);
4438                 plot_polygons_get_distance_point_1x = '';
4439                 plot_polygons_get_distance_point_1y = '';
4440                 drone_imagery_plot_polygon_click_type = '';
4441             } else {
4442                 plot_polygons_get_distance_point_1x = PosX;
4443                 plot_polygons_get_distance_point_1y = PosY;
4444             }
4445         }
4446         else if (drone_imagery_plot_polygon_click_type == 'plot_polygon_template_paste') {
4447             drone_imagery_plot_polygon_click_type = '';
4449             if (manage_drone_imagery_standard_process_field_trial_id == undefined) {
4450                 plotPolygonsTemplatePaste(PosX, PosY, parseInt(drone_imagery_current_plot_polygon_index_options_id), 'drone_imagery_generated_polygons_div', 'drone_imagery_generated_polygons_table', 'drone_imagery_plot_polygons_generated_assign', 'drone_imagery_plot_polygons_submit_bottom');
4451             }
4452             else {
4453                 plotPolygonsTemplatePaste(PosX, PosY, parseInt(drone_imagery_current_plot_polygon_index_options_id), 'drone_imagery_standard_process_generated_polygons_div', 'drone_imagery_standard_process_generated_polygons_table', 'drone_imagery_standard_process_plot_polygons_generated_assign', 'drone_imagery_standard_process_plot_polygons_submit_bottom');
4454             }
4455         }
4456         else if (drone_imagery_standard_process_plot_polygon_click_type == 'top_left') {
4457             drone_imagery_standard_process_plot_polygon_click_type = '';
4458             jQuery('#drone_imagery_standard_process_plot_polygons_left_column_top_offset').val(PosY);
4459             jQuery('#drone_imagery_standard_process_plot_polygons_top_row_left_offset').val(PosX);
4460         }
4461         else if (drone_imagery_standard_process_plot_polygon_click_type == 'top_right') {
4462             drone_imagery_standard_process_plot_polygon_click_type = '';
4463             jQuery('#drone_imagery_standard_process_plot_polygons_top_row_right_offset').val(background_image_width-PosX);
4464         }
4465         else if (drone_imagery_standard_process_plot_polygon_click_type == 'bottom_left') {
4466             drone_imagery_standard_process_plot_polygon_click_type = '';
4467             jQuery('#drone_imagery_standard_process_plot_polygons_bottom_row_left_offset').val(PosX);
4468             jQuery('#drone_imagery_standard_process_plot_polygons_left_column_bottom_offset').val(background_image_height-PosY);
4469         }
4470         else if (drone_imagery_standard_process_plot_polygon_click_type == 'bottom_right') {
4471             drone_imagery_standard_process_plot_polygon_click_type = '';
4472             jQuery('#drone_imagery_standard_process_plot_polygons_right_col_bottom_offset').val(background_image_height-PosY);
4473         }
4474         else if (drone_imagery_standard_process_plot_polygon_click_type == 'get_distance') {
4475             if (plot_polygons_get_distance_point_1x != '') {
4476                 var distance = Math.round(Math.sqrt(Math.pow(plot_polygons_get_distance_point_1x - PosX, 2) + Math.pow(plot_polygons_get_distance_point_1y - PosY, 2)));
4477                 alert('Distance='+distance+'. X1='+plot_polygons_get_distance_point_1x+'. Y1='+plot_polygons_get_distance_point_1y+'. X2='+PosX+'. Y2='+PosY);
4478                 plot_polygons_get_distance_point_1x = '';
4479                 plot_polygons_get_distance_point_1y = '';
4480                 drone_imagery_plot_polygon_click_type = '';
4481             } else {
4482                 plot_polygons_get_distance_point_1x = PosX;
4483                 plot_polygons_get_distance_point_1y = PosY;
4484             }
4485         }
4486     }
4488     jQuery('#drone_imagery_assign_plot_dialog').on('shown.bs.modal', function (e) {
4489         jQuery("#drone_imagery_plot_polygon_assign_plot_name").focus();
4490     });
4492     jQuery('#drone_imagery_assign_plot_dialog').on('hide.bs.modal', function (e) {
4493         drawPolyline(plot_polygons_display_points);
4494         drawWaypoints(plot_polygons_display_points, plot_polygon_name, 0);
4495         drone_imagery_plot_polygons_display[plot_polygon_name] = plot_polygons_display_points;
4496         plot_polygons_display_points = [];
4497     });
4499     jQuery('#drone_imagery_plot_polygon_assign_add').click(function(){
4500         plot_polygon_name = jQuery('#drone_imagery_plot_polygon_assign_plot_name').val();
4501         if (plot_polygon_name == ''){
4502             alert('Please give a name name (plot name, plant name, etc)');
4503         }
4504         drone_imagery_plot_polygons[plot_polygon_name] = plot_polygons_ind_4_points;
4505         jQuery('#drone_imagery_assign_plot_dialog').modal('hide');
4506         console.log(drone_imagery_plot_polygons);
4507         droneImageryDrawLayoutTable(field_trial_layout_response, drone_imagery_plot_polygons, 'drone_imagery_trial_layout_div', 'drone_imagery_layout_table');
4508     });
4510     jQuery('#drone_imagery_assign_plot_form').on('keyup keypress', function(e) {
4511         var keyCode = e.keyCode || e.which;
4512         if (keyCode === 13) {
4513             e.preventDefault();
4514             jQuery("#drone_imagery_plot_polygon_assign_add").trigger( "click" );
4515             return false;
4516         }
4517     });
4519     jQuery(document).on('click', 'button[name=drone_imagery_plot_polygons_submit_bottom]', function(){
4521         jQuery('input[name="drone_imagery_plot_polygons_autocomplete"]').each(function() {
4522             var stock_name = this.value;
4523             if (stock_name != '') {
4524                 var polygon = drone_imagery_plot_generated_polygons[jQuery(this).data('generated_polygon_key')];
4525                 drone_imagery_plot_polygons[stock_name] = polygon;
4526             }
4527         });
4529         submit_assignment_plot_polygons();
4530     });
4532     function submit_assignment_plot_polygons() {
4533         jQuery.ajax({
4534             type: 'POST',
4535             url: '/api/drone_imagery/assign_plot_polygons',
4536             dataType: "json",
4537             data: {
4538                 'image_id': background_removed_stitched_image_id,
4539                 'drone_run_band_project_id': drone_run_band_project_id,
4540                 'stock_polygons': JSON.stringify(drone_imagery_plot_polygons),
4541                 'assign_plot_polygons_type': assign_plot_polygons_type
4542             },
4543             beforeSend: function() {
4544                 jQuery("#working_modal").modal("show");
4545             },
4546             success: function(response){
4547                 console.log(response);
4548                 if(response.error) {
4549                     alert(response.error);
4550                 }
4552                 jQuery("#working_modal").modal("hide");
4553                 location.reload();
4554             },
4555             error: function(response){
4556                 jQuery("#working_modal").modal("hide");
4557                 alert('Error saving assigned plot polygons!')
4558             }
4559         });
4560     }
4562     jQuery(document).on('click', '#drone_imagery_plot_polygons_generated_assign', function() {
4563         generatePlotPolygonAssignments('drone_imagery_trial_layout_div', 'drone_imagery_layout_table');
4565         jQuery('input[name="drone_imagery_plot_polygons_autocomplete"]').each(function() {
4566             var stock_name = this.value;
4567             if (stock_name != '') {
4568                 var polygon = drone_imagery_plot_generated_polygons[jQuery(this).data('generated_polygon_key')];
4569                 drone_imagery_plot_polygons[stock_name] = polygon;
4570             }
4571         });
4572     });
4574     function generatePlotPolygonAssignments(trial_layout_div, trial_layout_table) {
4575         var plot_polygons_first_plot_start = jQuery('#drone_imagery_plot_polygons_first_plot_start').val();
4576         var plot_polygons_second_plot_follows = jQuery('#drone_imagery_plot_polygons_second_plot_follows').val();
4577         var plot_polygons_plot_orientation = jQuery('#drone_imagery_plot_polygons_plot_orientation').val();
4579         var plot_polygons_layout = field_trial_layout_response.output;
4580         var plot_polygons_plot_numbers = [];
4581         var plot_polygons_plot_numbers_plot_names = {};
4582         for (var i=1; i<plot_polygons_layout.length; i++) {
4583             var plot_polygons_plot_number = parseInt(plot_polygons_layout[i][2]);
4584             plot_polygons_plot_numbers.push(plot_polygons_plot_number);
4585             plot_polygons_plot_numbers_plot_names[plot_polygons_plot_number] = plot_polygons_layout[i][0];
4586         }
4587         plot_polygons_plot_numbers = plot_polygons_plot_numbers.sort(function (a, b) {  return a - b;  });
4588         var plot_polygons_current_plot_number_index = 0;
4590         var plot_polygons_template_index = 0;
4591         var plot_polygons_template_current = plot_polygons_template_dimensions[plot_polygons_template_index];
4592         var plot_polygons_template_current_num_cols = plot_polygons_template_current.num_cols;
4593         var plot_polygons_template_current_num_rows = plot_polygons_template_current.num_rows;
4594         var plot_polygons_template_current_total_plot_polygons = plot_polygons_template_current.total_plot_polygons;
4595         var plot_polygons_template_current_plot_polygon_index = 0;
4597         var plot_polygon_new_display = {};
4598         if (plot_polygons_first_plot_start == 'top_left') {
4599             var generated_polygon_key_first_plot_number = 0;
4600             if (plot_polygons_second_plot_follows == 'left' || plot_polygons_second_plot_follows == 'up') {
4601                 alert('Second plot cannot follow left or up from first plot if the first plot starts at the top left, because that is physically impossible.');
4602                 return;
4603             }
4604             if (plot_polygons_second_plot_follows == 'right') {
4605                 if (plot_polygons_plot_orientation == 'zigzag') {
4606                     var plot_polygon_current_polygon_index = generated_polygon_key_first_plot_number;
4607                     for (var j=generated_polygon_key_first_plot_number; j<plot_polygons_plot_numbers.length + drone_imagery_plot_polygons_removed_numbers.length; j++){
4608                         if (drone_imagery_plot_polygons_removed_numbers.includes(plot_polygon_current_polygon_index.toString())) {
4609                             console.log("Skipping "+plot_polygon_current_polygon_index);
4610                             plot_polygon_new_display[plot_polygon_current_polygon_index] = drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4611                         } else {
4612                             plot_polygon_new_display[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4613                             drone_imagery_plot_polygons[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_generated_polygons[plot_polygon_current_polygon_index];
4614                             plot_polygons_current_plot_number_index = plot_polygons_current_plot_number_index + 1;
4615                             plot_polygons_template_current_plot_polygon_index = plot_polygons_template_current_plot_polygon_index + 1;
4616                         }
4617                         plot_polygon_current_polygon_index = plot_polygon_current_polygon_index + 1;
4619                         if (plot_polygons_template_current_plot_polygon_index == plot_polygons_template_current_total_plot_polygons) {
4620                             plot_polygons_template_index = plot_polygons_template_index + 1;
4621                             plot_polygons_template_current = plot_polygons_template_dimensions[plot_polygons_template_index];
4622                             if (plot_polygons_template_current != undefined) {
4623                                 plot_polygons_template_current_num_cols = plot_polygons_template_current.num_cols;
4624                                 plot_polygons_template_current_num_rows = plot_polygons_template_current.num_rows;
4625                                 plot_polygons_template_current_total_plot_polygons = plot_polygons_template_current.total_plot_polygons;
4626                                 plot_polygons_template_current_plot_polygon_index = 0;
4627                             }
4628                         }
4629                     }
4630                 }
4631                 if (plot_polygons_plot_orientation == 'serpentine') {
4632                     var plot_polygon_current_polygon_index = generated_polygon_key_first_plot_number;
4633                     var plot_polygon_column_count = 0;
4634                     var plot_polygon_zigzig_polygon_index = generated_polygon_key_first_plot_number;
4635                     var going_right = 1;
4636                     var plot_polygon_previous_template_plot_count = 0;
4637                     for (var j=generated_polygon_key_first_plot_number; j<plot_polygons_plot_numbers.length + drone_imagery_plot_polygons_removed_numbers.length; j++){
4639                         if (going_right == 1) {
4640                             plot_polygon_current_polygon_index = plot_polygon_zigzig_polygon_index;
4641                         }
4642                         if (going_right == 0) {
4643                             plot_polygon_current_polygon_index = plot_polygon_previous_template_plot_count + plot_polygons_template_current_num_cols - plot_polygon_column_count - 1;
4644                         }
4646                         if (drone_imagery_plot_polygons_removed_numbers.includes(plot_polygon_current_polygon_index.toString())) {
4647                             console.log("Skipping "+plot_polygon_current_polygon_index);
4648                             plot_polygon_new_display[plot_polygon_current_polygon_index] = drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4649                         } else {
4650                             plot_polygon_new_display[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] =  drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4651                             drone_imagery_plot_polygons[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_generated_polygons[plot_polygon_current_polygon_index];
4652                             plot_polygons_current_plot_number_index = plot_polygons_current_plot_number_index + 1;
4653                             plot_polygons_template_current_plot_polygon_index = plot_polygons_template_current_plot_polygon_index + 1;
4654                         }
4656                         plot_polygon_zigzig_polygon_index = plot_polygon_zigzig_polygon_index + 1;
4657                         plot_polygon_column_count = plot_polygon_column_count + 1;
4659                         if (plot_polygon_column_count == plot_polygons_template_current_num_cols) {
4660                             plot_polygon_column_count = 0;
4661                             if (going_right == 1) {
4662                                 going_right = 0;
4663                             } else {
4664                                 going_right = 1;
4665                             }
4666                             plot_polygon_previous_template_plot_count = plot_polygon_previous_template_plot_count + plot_polygons_template_current_num_cols;
4667                         }
4669                         if (plot_polygons_template_current_plot_polygon_index == plot_polygons_template_current_total_plot_polygons) {
4670                             plot_polygons_template_index = plot_polygons_template_index + 1;
4671                             plot_polygons_template_current = plot_polygons_template_dimensions[plot_polygons_template_index];
4672                             if (plot_polygons_template_current != undefined) {
4673                                 plot_polygons_template_current_num_cols = plot_polygons_template_current.num_cols;
4674                                 plot_polygons_template_current_num_rows = plot_polygons_template_current.num_rows;
4675                                 plot_polygons_template_current_total_plot_polygons = plot_polygons_template_current.total_plot_polygons;
4676                                 plot_polygons_template_current_plot_polygon_index = 0;
4677                             }
4678                         }
4679                     }
4680                 }
4681             }
4682             if (plot_polygons_second_plot_follows == 'down') {
4683                 alert('Down not implemented if first plot starts in top left. Please contact us or try rotating your image differently before assigning plot polygons (e.g. rotate image 90 degrees clock-wise, then first plot starts in top right and you can go left for plot assignment).');
4684                 return;
4685             }
4686         }
4687         if (plot_polygons_first_plot_start == 'top_right') {
4688             var generated_polygon_key_first_plot_number = plot_polygons_template_current_num_cols - 1;
4689             if (plot_polygons_second_plot_follows == 'right' || plot_polygons_second_plot_follows == 'up') {
4690                 alert('Second plot cannot follow right or up from first plot if the first plot starts at the top right, because that is physically impossible.');
4691                 return;
4692             }
4693             if (plot_polygons_second_plot_follows == 'left') {
4694                 if (plot_polygons_plot_orientation == 'zigzag') {
4695                     console.log(generated_polygon_key_first_plot_number);
4696                     var plot_polygon_current_polygon_index = generated_polygon_key_first_plot_number;
4697                     var plot_polygon_column_count = 0;
4698                     var plot_polygon_previous_template_plot_count = 0;
4699                     for (var j=generated_polygon_key_first_plot_number; j<generated_polygon_key_first_plot_number + plot_polygons_plot_numbers.length + drone_imagery_plot_polygons_removed_numbers.length; j++){
4701                         plot_polygon_current_polygon_index = plot_polygon_previous_template_plot_count + plot_polygons_template_current_num_cols - plot_polygon_column_count - 1;
4703                         if (drone_imagery_plot_polygons_removed_numbers.includes(plot_polygon_current_polygon_index.toString())) {
4704                             console.log("Skipping "+plot_polygon_current_polygon_index);
4705                             plot_polygon_new_display[plot_polygon_current_polygon_index] =  drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4706                         } else {
4707                             plot_polygon_new_display[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] =  drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4708                             drone_imagery_plot_polygons[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_generated_polygons[plot_polygon_current_polygon_index];
4709                             plot_polygons_current_plot_number_index = plot_polygons_current_plot_number_index + 1;
4710                             plot_polygons_template_current_plot_polygon_index = plot_polygons_template_current_plot_polygon_index + 1;
4711                         }
4713                         plot_polygon_column_count = plot_polygon_column_count + 1;
4715                         if (plot_polygon_column_count == plot_polygons_template_current_num_cols) {
4716                             plot_polygon_column_count = 0;
4717                             plot_polygon_previous_template_plot_count = plot_polygon_previous_template_plot_count + plot_polygons_template_current_num_cols;
4718                         }
4720                         if (plot_polygons_template_current_plot_polygon_index == plot_polygons_template_current_total_plot_polygons) {
4721                             plot_polygons_template_index = plot_polygons_template_index + 1;
4722                             plot_polygons_template_current = plot_polygons_template_dimensions[plot_polygons_template_index];
4723                             if (plot_polygons_template_current != undefined) {
4724                                 plot_polygons_template_current_num_cols = plot_polygons_template_current.num_cols;
4725                                 plot_polygons_template_current_num_rows = plot_polygons_template_current.num_rows;
4726                                 plot_polygons_template_current_total_plot_polygons = plot_polygons_template_current.total_plot_polygons;
4727                                 plot_polygons_template_current_plot_polygon_index = 0;
4728                             }
4729                         }
4730                     }
4731                 }
4732                 if (plot_polygons_plot_orientation == 'serpentine') {
4733                     var plot_polygon_current_polygon_index = generated_polygon_key_first_plot_number;
4734                     var plot_polygon_column_count = 0;
4735                     var plot_polygon_zigzig_polygon_index = generated_polygon_key_first_plot_number;
4736                     var going_left = 1;
4737                     var plot_polygon_previous_template_plot_count = 0;
4738                     for (var j=generated_polygon_key_first_plot_number; j<generated_polygon_key_first_plot_number + plot_polygons_plot_numbers.length + drone_imagery_plot_polygons_removed_numbers.length; j++){
4740                         if (going_left == 0) {
4741                             plot_polygon_current_polygon_index = plot_polygon_previous_template_plot_count + plot_polygon_column_count;
4742                         }
4743                         if (going_left == 1) {
4744                             plot_polygon_current_polygon_index = plot_polygon_previous_template_plot_count + plot_polygons_template_current_num_cols - plot_polygon_column_count - 1;
4745                         }
4747                         if (drone_imagery_plot_polygons_removed_numbers.includes(plot_polygon_current_polygon_index.toString())) {
4748                             console.log("Skipping "+plot_polygon_current_polygon_index);
4749                             plot_polygon_new_display[plot_polygon_current_polygon_index] = drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4750                         } else {
4751                             plot_polygon_new_display[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] =  drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4752                             drone_imagery_plot_polygons[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_generated_polygons[plot_polygon_current_polygon_index];
4753                             plot_polygons_current_plot_number_index = plot_polygons_current_plot_number_index + 1;
4754                             plot_polygons_template_current_plot_polygon_index = plot_polygons_template_current_plot_polygon_index + 1;
4755                         }
4757                         plot_polygon_zigzig_polygon_index = plot_polygon_zigzig_polygon_index + 1;
4758                         plot_polygon_column_count = plot_polygon_column_count + 1;
4760                         if (plot_polygon_column_count == plot_polygons_template_current_num_cols) {
4761                             plot_polygon_column_count = 0;
4762                             if (going_left == 1) {
4763                                 going_left = 0;
4764                             } else {
4765                                 going_left = 1;
4766                             }
4767                             plot_polygon_previous_template_plot_count = plot_polygon_previous_template_plot_count + plot_polygons_template_current_num_cols;
4768                         }
4770                         if (plot_polygons_template_current_plot_polygon_index == plot_polygons_template_current_total_plot_polygons) {
4771                             plot_polygons_template_index = plot_polygons_template_index + 1;
4772                             plot_polygons_template_current = plot_polygons_template_dimensions[plot_polygons_template_index];
4773                             if (plot_polygons_template_current != undefined) {
4774                                 plot_polygons_template_current_num_cols = plot_polygons_template_current.num_cols;
4775                                 plot_polygons_template_current_num_rows = plot_polygons_template_current.num_rows;
4776                                 plot_polygons_template_current_total_plot_polygons = plot_polygons_template_current.total_plot_polygons;
4777                                 plot_polygons_template_current_plot_polygon_index = 0;
4778                             }
4779                         }
4780                     }
4781                 }
4782             }
4783             if (plot_polygons_second_plot_follows == 'down') {
4784                 alert('Down not implemented if your first plot starts in top right. Please contact us or try rotating your image differently before assigning plot polygons (e.g. rotate image 90 degrees clockwise, then first plot starts in bottom right corner and plot assignment can follow going left).');
4785                 return;
4786             }
4787         }
4788         if (plot_polygons_first_plot_start == 'bottom_left') {
4789             var generated_polygon_key_first_plot_number = plot_polygons_number_generated - (plot_polygons_num_border_rows_bottom * plot_polygons_num_cols_generated) - plot_polygons_num_border_rows_right;
4790             if (plot_polygons_second_plot_follows == 'left' || plot_polygons_second_plot_follows == 'down') {
4791                 alert('Second plot cannot follow left or down from the first plot if the first plot starts at the bottom left, because that is physically impossible.');
4792                 return;
4793             }
4794             if (plot_polygons_second_plot_follows == 'right') {
4795                 if (plot_polygons_plot_orientation == 'serpentine') {
4796                     var plot_polygon_current_polygon_index = generated_polygon_key_first_plot_number;
4797                     var plot_polygon_column_count = 0;
4798                     var going_right = 1;
4799                     var plot_polygon_row_count = 0;
4800                     for (var j=0; j<plot_polygons_plot_numbers.length; j++){
4802                         if (going_right == 0) {
4803                             plot_polygon_current_polygon_index = plot_polygons_number_generated - (plot_polygons_num_border_rows_bottom * plot_polygons_num_cols_generated) - (plot_polygon_row_count * plot_polygons_num_cols_generated) - plot_polygons_num_border_rows_right - plot_polygon_column_count - 1;
4804                         }
4805                         if (going_right == 1) {
4806                             plot_polygon_current_polygon_index = plot_polygons_number_generated - (plot_polygons_num_border_rows_bottom * plot_polygons_num_cols_generated) - (plot_polygon_row_count * plot_polygons_num_cols_generated) - plot_polygons_num_cols_generated + plot_polygons_num_border_rows_left + plot_polygon_column_count;
4807                         }
4809                         if (drone_imagery_plot_polygons_removed_numbers.includes(plot_polygon_current_polygon_index.toString())) {
4810                             console.log("Skipping "+plot_polygon_current_polygon_index);
4811                             plot_polygon_new_display[plot_polygon_current_polygon_index] = drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4812                         } else {
4813                             plot_polygon_new_display[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] =  drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4814                             drone_imagery_plot_polygons[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_generated_polygons[plot_polygon_current_polygon_index];
4815                             plot_polygons_current_plot_number_index = plot_polygons_current_plot_number_index + 1;
4816                         }
4818                         plot_polygon_column_count = plot_polygon_column_count + 1;
4820                         if (plot_polygon_column_count == (plot_polygons_num_cols_generated - plot_polygons_num_border_rows_left - plot_polygons_num_border_rows_right)) {
4821                             plot_polygon_column_count = 0;
4822                             plot_polygon_row_count = plot_polygon_row_count + 1;
4823                             if (going_right == 1) {
4824                                 going_right = 0;
4825                             } else {
4826                                 going_right = 1;
4827                             }
4828                         }
4829                     }
4830                 }
4831                 if (plot_polygons_plot_orientation == 'zigzag') {
4832                     var plot_polygon_current_polygon_index = generated_polygon_key_first_plot_number;
4833                     var plot_polygon_column_count = 0;
4834                     var plot_polygon_row_count = 0;
4835                     for (var j=0; j<plot_polygons_plot_numbers.length; j++){
4837                         plot_polygon_current_polygon_index = plot_polygons_number_generated - (plot_polygons_num_border_rows_bottom * plot_polygons_num_cols_generated) - (plot_polygon_row_count * plot_polygons_num_cols_generated) - plot_polygons_num_cols_generated + plot_polygons_num_border_rows_left + plot_polygon_column_count;
4839                         if (drone_imagery_plot_polygons_removed_numbers.includes(plot_polygon_current_polygon_index.toString())) {
4840                             console.log("Skipping "+plot_polygon_current_polygon_index);
4841                             plot_polygon_new_display[plot_polygon_current_polygon_index] = drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4842                         } else {
4843                             plot_polygon_new_display[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] =  drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4844                             drone_imagery_plot_polygons[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_generated_polygons[plot_polygon_current_polygon_index];
4845                             plot_polygons_current_plot_number_index = plot_polygons_current_plot_number_index + 1;
4846                         }
4848                         plot_polygon_column_count = plot_polygon_column_count + 1;
4850                         if (plot_polygon_column_count == (plot_polygons_num_cols_generated - plot_polygons_num_border_rows_left - plot_polygons_num_border_rows_right)) {
4851                             plot_polygon_column_count = 0;
4852                             plot_polygon_row_count = plot_polygon_row_count + 1;
4853                         }
4854                     }
4855                 }
4856             }
4857             if (plot_polygons_second_plot_follows == 'up') {
4858                 alert('Up not implemented if your first plot starts in bottom left. Please contact us or try rotating your image differently before assigning plot polygons (e.g. rotate image clockwise 90 degrees, then first plot starts in top-left corner and plot assignment can follow going right).');
4859                 return;
4860             }
4861         }
4862         if (plot_polygons_first_plot_start == 'bottom_right') {
4863             var generated_polygon_key_first_plot_number = plot_polygons_number_generated - (plot_polygons_num_border_rows_bottom * plot_polygons_num_cols_generated) - plot_polygons_num_border_rows_right - 1;
4864             if (plot_polygons_second_plot_follows == 'right' || plot_polygons_second_plot_follows == 'down') {
4865                 alert('Second plot cannot follow right or down from the first plot if the first plot starts at the bottom right, because that is physically impossible.');
4866                 return;
4867             }
4868             if (plot_polygons_second_plot_follows == 'left') {
4869                 if (plot_polygons_plot_orientation == 'zigzag') {
4870                     var plot_polygon_current_polygon_index = generated_polygon_key_first_plot_number;
4871                     var plot_polygon_column_count = 0;
4872                     for (var j=0; j<plot_polygons_plot_numbers.length; j++){
4874                         if (drone_imagery_plot_polygons_removed_numbers.includes(plot_polygon_current_polygon_index.toString())) {
4875                             console.log("Skipping "+plot_polygon_current_polygon_index);
4876                             plot_polygon_new_display[plot_polygon_current_polygon_index] = drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4877                         } else {
4878                             plot_polygon_new_display[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4879                             drone_imagery_plot_polygons[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_generated_polygons[plot_polygon_current_polygon_index];
4880                             plot_polygons_current_plot_number_index = plot_polygons_current_plot_number_index + 1;
4881                         }
4883                         plot_polygon_current_polygon_index = plot_polygon_current_polygon_index - 1;
4884                         plot_polygon_column_count = plot_polygon_column_count + 1;
4886                         if (plot_polygon_column_count == (plot_polygons_num_cols_generated - plot_polygons_num_border_rows_left - plot_polygons_num_border_rows_right)) {
4887                             plot_polygon_current_polygon_index = plot_polygon_current_polygon_index - plot_polygons_num_border_rows_left - plot_polygons_num_border_rows_right;
4888                             plot_polygon_column_count = 0;
4889                         }
4890                     }
4891                 }
4892                 if (plot_polygons_plot_orientation == 'serpentine') {
4893                     var plot_polygon_current_polygon_index = generated_polygon_key_first_plot_number;
4894                     var plot_polygon_column_count = 0;
4895                     var plot_polygon_zigzig_polygon_index = generated_polygon_key_first_plot_number;
4896                     var going_left = 1;
4897                     var plot_polygon_row_count = 0;
4898                     for (var j=0; j<plot_polygons_plot_numbers.length; j++){
4900                         if (going_left == 1) {
4901                             plot_polygon_current_polygon_index = plot_polygon_zigzig_polygon_index;
4902                         }
4903                         if (going_left == 0) {
4904                             plot_polygon_current_polygon_index = plot_polygons_number_generated - (plot_polygons_num_border_rows_bottom * plot_polygons_num_cols_generated) - (plot_polygon_row_count * plot_polygons_num_cols_generated) - plot_polygons_num_cols_generated + plot_polygons_num_border_rows_left + plot_polygon_column_count;
4905                         }
4907                         if (drone_imagery_plot_polygons_removed_numbers.includes(plot_polygon_current_polygon_index.toString())) {
4908                             console.log("Skipping "+plot_polygon_current_polygon_index);
4909                             plot_polygon_new_display[plot_polygon_current_polygon_index] = drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4910                         } else {
4911                             plot_polygon_new_display[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_polygons_display[plot_polygon_current_polygon_index];
4912                             drone_imagery_plot_polygons[plot_polygons_plot_numbers_plot_names[plot_polygons_plot_numbers[plot_polygons_current_plot_number_index]]] = drone_imagery_plot_generated_polygons[plot_polygon_current_polygon_index];
4913                             plot_polygons_current_plot_number_index = plot_polygons_current_plot_number_index + 1;
4914                         }
4916                         plot_polygon_zigzig_polygon_index = plot_polygon_zigzig_polygon_index - 1;
4917                         plot_polygon_column_count = plot_polygon_column_count + 1;
4919                         if (plot_polygon_column_count == (plot_polygons_num_cols_generated - plot_polygons_num_border_rows_left - plot_polygons_num_border_rows_right)) {
4920                             plot_polygon_zigzig_polygon_index = plot_polygon_zigzig_polygon_index - plot_polygons_num_border_rows_left - plot_polygons_num_border_rows_right;
4921                             plot_polygon_column_count = 0;
4922                             plot_polygon_row_count = plot_polygon_row_count + 1;
4923                             if (going_left == 1) {
4924                                 going_left = 0;
4925                             } else {
4926                                 going_left = 1;
4927                             }
4928                         }
4929                     }
4930                 }
4931             }
4932             if (plot_polygons_second_plot_follows == 'up') {
4933                 alert('Up not implemented if your first plot starts in bottom right. Please contact us or try rotating your image differently before assigning plot polygons (e.g. rotate image 90 degrees clockwise, then first plot starts in bottom left corner and plot assignment can follow going right).');
4934                 return;
4935             }
4936         }
4938         console.log(drone_imagery_plot_polygons);
4939         droneImageryDrawLayoutTable(field_trial_layout_response, drone_imagery_plot_polygons, trial_layout_div, trial_layout_table);
4941         drone_imagery_plot_polygons_display = plot_polygon_new_display;
4942         draw_canvas_image(background_image_url, plot_polygons_total_height_generated/plot_polygons_num_rows_generated);
4943     }
4945     function droneImageryRectangleLayoutTable(generated_polygons, plot_polygons_layout_assignment_info, plot_polygons_layout_assignment_table, plot_polygons_generate_assignment_button, plot_polygon_assignment_submit_button) {
4946         var html = '<hr><div class="well well-sm"><h2>Assign Plot Polygons to Field Trial Entities</h2>';
4947         html = html + '<div class="panel panel-default"><div class="panel-body"><div class="form form-horizontal">';
4948         html = html + '<div class="row"><div class="col-sm-6"><div class="form-group form-group-sm"><label class="col-sm-6 control-label">Location of First Plot (e.g. plot number 1): </label><div class="col-sm-6"><select class="form-control" id="drone_imagery_plot_polygons_first_plot_start" name="drone_imagery_plot_polygons_first_plot_start"><option value="top_left">Top Left</option><option value="top_right">Top Right</option><option value="bottom_left" disabled>Bottom Left</option><option value="bottom_right" disabled>Bottom Right</option></select></div></div></div><div class="col-sm-6"><div class="form-group form-group-sm"><label class="col-sm-6 control-label">Second Plot Follows First Plot Going: </label><div class="col-sm-6"><select class="form-control" id="drone_imagery_plot_polygons_second_plot_follows" name="drone_imagery_plot_polygons_second_plot_follows"><option value="right">Right</option><option value="up">Up</option><option value="down">Down</option><option value="left">Left</option></select></div></div></div></div>';
4949         html = html + '<div class="row"><div class="col-sm-6"><div class="form-group form-group-sm"><label class="col-sm-6 control-label">Plot Number Orientation: </label><div class="col-sm-6"><select class="form-control" id="drone_imagery_plot_polygons_plot_orientation" name="drone_imagery_plot_polygons_plot_orientation"><option value="serpentine">Serpentine</option><option value="zigzag">Zigzag (Not Serpentine)</option></select></div></div></div></div>';
4950         html = html + '</div></div></div></div>';
4951         //html = html + '<table class="table table-borders table-hover" id="'+plot_polygons_layout_assignment_table+'"><thead><tr><th>Generated Number</th><th>Field Trial Observation Unit</th></tr></thead><tbody>';
4952         //for (key in generated_polygons) {
4953         //    html = html + '<tr><td>' + key + '</td><td><input class="form-control" type="text" name="drone_imagery_plot_polygons_autocomplete" data-generated_polygon_key="'+key+'"/></td></tr>';
4954         //}
4955         //html = html + '</tbody></table>';
4956         html = html + '<button class="btn btn-primary" id="'+plot_polygons_generate_assignment_button+'">Generate Assignments (Does Not Save)</button>&nbsp;&nbsp;&nbsp;<button class="btn btn-primary" name="'+plot_polygon_assignment_submit_button+'">Finish and Save Polygons To Plots</button></div>';
4957         jQuery('#'+plot_polygons_layout_assignment_info).html(html);
4958         jQuery('#'+plot_polygons_layout_assignment_table).DataTable({'paging':false});
4960         jQuery('input[name=drone_imagery_plot_polygons_autocomplete]').autocomplete({
4961             source: drone_imagery_plot_polygons_available_stock_names
4962         });
4963     }
4965     function droneImageryDrawLayoutTable(response, plot_polygons, layout_div_id, layout_table_div_id) {
4966         var output = response.output;
4967         var header = output[0];
4968         var html = '<table class="table table-borders table-hover" id="'+layout_table_div_id+'"><thead><tr>';
4969         for (var i=0; i<header.length; i++){
4970             html = html + '<td>'+header[i]+'</td>';
4971         }
4972         html = html + '<td>Polygon Assigned</td>';
4973         html = html + '</tr></thead><tbody>';
4974         for (var i=1; i<output.length; i++){
4975             html = html + '<tr>';
4976             for (var j=0; j<output[i].length; j++){
4977                 html = html + '<td>'+output[i][j]+'</td>';
4978             }
4979             if (output[i][0] in plot_polygons && plot_polygons[output[i][0]] != undefined){
4980                 html = html + '<td>Yes</td>';
4981             } else {
4982                 html = html + '<td></td>';
4983             }
4984             html = html + '</tr>';
4985         }
4986         html = html + '</tbody></table>';
4987         jQuery('#'+layout_div_id).html(html);
4988         jQuery('#'+layout_table_div_id).DataTable();
4989     }
4991     //
4992     //Remove Background Histogram
4993     //
4995     var removeBackgroundHistogramImg;
4996     var removeBackgroundDisplayImg;
4997     var removeBackgroundThresholdPeak1;
4998     var removeBackgroundThresholdPeak1pixels;
4999     var removeBackgroundThresholdPeak2;
5000     var removeBackgroundThresholdPeak2pixels;
5001     var removeBackgroundThresholdValue;
5002     var remove_background_denoised_stitched_image_id;
5003     var remove_background_current_image_id;
5004     var remove_background_current_image_type;
5005     var remove_background_drone_run_band_project_id;
5007     jQuery(document).on('click', 'button[name=project_drone_imagery_remove_background]', function(){
5008         showManageDroneImagerySection('manage_drone_imagery_remove_background_div');
5010         remove_background_denoised_stitched_image_id = jQuery(this).data('denoised_stitched_image_id');
5011         remove_background_drone_run_band_project_id = jQuery(this).data('drone_run_band_project_id');
5012         remove_background_current_image_id = jQuery(this).data('remove_background_current_image_id');
5013         remove_background_current_image_type = jQuery(this).data('remove_background_current_image_type');
5015         showRemoveBackgroundHistogramStart(remove_background_current_image_id, 'drone_imagery_remove_background_original', 'drone_imagery_remove_background_histogram_div', 'manage_drone_imagery_remove_background_load_div');
5016     });
5018     function showRemoveBackgroundHistogramStart(remove_background_current_image_id, canvas_div_id, histogram_canvas_div_id, load_div_id) {
5019         jQuery.ajax({
5020             url : '/api/drone_imagery/get_image?image_id='+remove_background_current_image_id,
5021             beforeSend: function() {
5022                 jQuery("#working_modal").modal("show");
5023             },
5024             success: function(response){
5025                 console.log(response);
5026                 jQuery("#working_modal").modal("hide");
5028                 var canvas = document.getElementById(canvas_div_id);
5029                 removeBackgroundDisplayImg = canvas;
5030                 ctx = canvas.getContext('2d');
5031                 var image = new Image();
5032                 image.onload = function () {
5033                     canvas.width = this.naturalWidth;
5034                     canvas.height = this.naturalHeight;
5035                     ctx.drawImage(this, 0, 0);
5037                     var src = cv.imread(canvas_div_id);
5038                     cv.cvtColor(src, src, cv.COLOR_RGBA2GRAY, 0);
5039                     var srcVec = new cv.MatVector();
5040                     srcVec.push_back(src);
5041                     var accumulate = false;
5042                     var channels = [0];
5043                     var histSize = [256];
5044                     var ranges = [0, 255];
5045                     var hist = new cv.Mat();
5046                     var mask = new cv.Mat();
5047                     var color = new cv.Scalar(255, 255, 255);
5048                     var scale = 3;
5049                     var hist_height = src.rows/2;
5051                     cv.calcHist(srcVec, channels, mask, hist, histSize, ranges, accumulate);
5052                     var result = cv.minMaxLoc(hist, mask);
5053                     var max = result.maxVal;
5054                     var dst = new cv.Mat.zeros(hist_height, histSize[0] * scale, cv.CV_8UC3);
5055                     // draw histogram
5056                     for (let i = 0; i < histSize[0]; i++) {
5057                         var binVal = hist.data32F[i] * hist_height / max;
5058                         var point1 = new cv.Point(i * scale, hist_height - 1);
5059                         var point2 = new cv.Point((i + 1) * scale - 1, hist_height - binVal);
5060                         cv.rectangle(dst, point1, point2, color, cv.FILLED);
5061                     }
5062                     cv.imshow(histogram_canvas_div_id, dst);
5063                     src.delete(); dst.delete(); srcVec.delete(); mask.delete(); hist.delete();
5065                     removeBackgroundHistogramImg = document.getElementById(histogram_canvas_div_id);
5066                     removeBackgroundHistogramImg.onmousemove = GetCoordinatesRemoveBackgrounHistogram;
5067                     removeBackgroundHistogramImg.onmousedown = GetCoordinatesRemoveBackgrounHistogramDrawLine;
5069                     jQuery('#'+load_div_id).hide();
5071                 };
5072                 image.src = response.image_url;
5074             },
5075             error: function(response){
5076                 jQuery("#working_modal").modal("hide");
5077                 alert('Error retrieving image!')
5078             }
5079         });
5080     }
5082     jQuery('#drone_imagery_remove_background_find_minimum').click(function(){
5083         if (!removeBackgroundThresholdPeak1 || !removeBackgroundThresholdPeak2) {
5084             alert('Please click on the two right-most peaks in the histogram first!');
5085         } else {
5086             showRemoveBackgroundHistogramMinimum(remove_background_current_image_id, 'drone_imagery_remove_background_original', 'drone_imagery_remove_background_histogram_div');
5087         }
5088     });
5090     function showRemoveBackgroundHistogramMinimum(remove_background_current_image_id, canvas_div_id, histogram_canvas_div_id) {
5091         jQuery.ajax({
5092             url : '/api/drone_imagery/get_image?image_id='+remove_background_current_image_id,
5093             beforeSend: function() {
5094                 jQuery("#working_modal").modal("show");
5095             },
5096             success: function(response){
5097                 console.log(response);
5098                 jQuery("#working_modal").modal("hide");
5100                 var canvas = document.getElementById(canvas_div_id);
5101                 ctx = canvas.getContext('2d');
5102                 var image = new Image();
5103                 image.onload = function () {
5104                     canvas.width = this.naturalWidth;
5105                     canvas.height = this.naturalHeight;
5106                     ctx.drawImage(this, 0, 0);
5108                     var src = cv.imread(canvas_div_id);
5109                     cv.cvtColor(src, src, cv.COLOR_RGBA2GRAY, 0);
5110                     var srcVec = new cv.MatVector();
5111                     srcVec.push_back(src);
5112                     var accumulate = false;
5113                     var channels = [0];
5114                     var histSize = [256];
5115                     var ranges = [0, 255];
5116                     var hist = new cv.Mat();
5117                     var mask = new cv.Mat();
5118                     var color = new cv.Scalar(255, 255, 255);
5119                     var scale = 3;
5120                     var hist_height = src.rows/2;
5122                     cv.calcHist(srcVec, channels, mask, hist, histSize, ranges, accumulate);
5123                     var result = cv.minMaxLoc(hist, mask);
5124                     var max = result.maxVal;
5125                     var dst = new cv.Mat.zeros(hist_height, histSize[0] * scale, cv.CV_8UC3);
5126                     // draw histogram
5127                     var minimum_x_val = 0;
5128                     var minimum_x_val_pix = 0;
5129                     var minimum_y_val = 1000000000000000000000000000;
5131                     if (removeBackgroundThresholdPeak1pixels > removeBackgroundThresholdPeak2pixels) {
5132                         var removeBackgroundThresholdPeak1pixels_original = removeBackgroundThresholdPeak1pixels;
5133                         removeBackgroundThresholdPeak1pixels = removeBackgroundThresholdPeak2pixels;
5134                         removeBackgroundThresholdPeak2pixels = removeBackgroundThresholdPeak1pixels_original;
5135                     }
5137                     for (let i = 0; i < histSize[0]; i++) {
5138                         var binVal = hist.data32F[i] * hist_height / max;
5140                         var x_start = i * scale;
5141                         if (x_start >= removeBackgroundThresholdPeak1pixels && x_start <= removeBackgroundThresholdPeak2pixels){
5142                             //console.log('x: '+i.toString()+' y: '+binVal.toString());
5143                             if (binVal < minimum_y_val) {
5144                                 minimum_y_val = binVal;
5145                                 minimum_x_val = i;
5146                                 minimum_x_val_pix = x_start;
5147                             }
5148                         }
5150                         var point1 = new cv.Point(x_start, hist_height - 1);
5151                         var point2 = new cv.Point((i + 1) * scale - 1, hist_height - binVal);
5152                         cv.rectangle(dst, point1, point2, color, cv.FILLED);
5153                     }
5154                     cv.imshow('drone_imagery_remove_background_histogram_div', dst);
5155                     src.delete(); dst.delete(); srcVec.delete(); mask.delete(); hist.delete();
5157                     removeBackgroundHistogramImg = document.getElementById(histogram_canvas_div_id);
5158                     removeBackgroundHistogramImg.onmousemove = GetCoordinatesRemoveBackgrounHistogram;
5159                     removeBackgroundHistogramImg.onmousedown = GetCoordinatesRemoveBackgrounHistogramDrawLine;
5161                     jQuery('div[name="drone_imagery_remove_background_threshold"]').html('<h5>Selected Threshold Value: '+ minimum_x_val );
5163                     removeBackgroundHistogramImgDrawLine(removeBackgroundHistogramImg, removeBackgroundThresholdPeak1pixels, removeBackgroundHistogramImg.height, '#ff0000');
5164                     removeBackgroundHistogramImgDrawLine(removeBackgroundHistogramImg, removeBackgroundThresholdPeak2pixels, removeBackgroundHistogramImg.height, '#ff0000');
5165                     removeBackgroundHistogramImgDrawLine(removeBackgroundHistogramImg, minimum_x_val_pix, removeBackgroundHistogramImg.height, '#0000ff');
5167                     removeBackgroundThresholdValue = minimum_x_val;
5169                     removeBackgroundHistogramImgReDraw();
5170                 };
5171                 image.src = response.image_url;
5172             },
5173             error: function(response){
5174                 jQuery("#working_modal").modal("hide");
5175                 alert('Error retrieving image!')
5176             }
5177         });
5178     }
5180     jQuery('#drone_imagery_remove_background_start_over').click(function(){
5181         removeBackgroundThresholdPeak1 = undefined;
5182         removeBackgroundThresholdPeak2 = undefined;
5183         removeBackgroundThresholdPeak1pixels = undefined;
5184         removeBackgroundThresholdPeak2pixels = undefined;
5186         showRemoveBackgroundHistogramStart(remove_background_current_image_id, 'drone_imagery_remove_background_original', 'drone_imagery_remove_background_histogram_div', 'manage_drone_imagery_remove_background_load_div');
5187     });
5189     function removeBackgroundHistogramImgDrawLine(removeBackgroundHistogramImg, position, image_height, color) {
5190         var ctx = removeBackgroundHistogramImg.getContext("2d");
5191         ctx.beginPath();
5192         ctx.moveTo(position,0);
5193         ctx.lineTo(position, image_height);
5194         ctx.strokeStyle = color;
5195         ctx.stroke();
5196     }
5198     function removeBackgroundHistogramImgReDraw() {
5199         jQuery.ajax({
5200             type: 'POST',
5201             url: '/api/drone_imagery/remove_background_display',
5202             dataType: "json",
5203             data: {
5204                 'image_id': remove_background_current_image_id,
5205                 'drone_run_band_project_id': remove_background_drone_run_band_project_id,
5206                 'lower_threshold': removeBackgroundThresholdValue,
5207                 'upper_threshold': '255',
5208             },
5209             success: function(response){
5210                 console.log(response);
5211                 if(response.error) {
5212                     alert(response.error);
5213                 }
5215                 var canvas = removeBackgroundDisplayImg;
5216                 ctx = canvas.getContext('2d');
5217                 var image = new Image();
5218                 image.onload = function () {
5219                     canvas.width = this.naturalWidth;
5220                     canvas.height = this.naturalHeight;
5221                     ctx.drawImage(this, 0, 0);
5222                 };
5223                 image.src = response.removed_background_image_url;
5224             },
5225             error: function(response){
5226                 alert('Error saving removed background display image!')
5227             }
5228         });
5229     }
5231     function GetCoordinatesRemoveBackgrounHistogram(e) {
5232         var PosX = 0;
5233         var PosY = 0;
5234         var ImgPos;
5235         ImgPos = FindPosition(removeBackgroundHistogramImg);
5236         if (!e) var e = window.event;
5237         if (e.pageX || e.pageY) {
5238             PosX = e.pageX;
5239             PosY = e.pageY;
5240         }
5241         else if (e.clientX || e.clientY) {
5242             PosX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
5243             PosY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
5244         }
5245         PosX = PosX - ImgPos[0];
5246         PosY = PosY - ImgPos[1];
5248         jQuery('div[name="drone_imagery_remove_background_threshold_current"]').html('<h5>Current Mouse Value: '+ (((PosX+1)/3)-1) );
5249     }
5251     function GetCoordinatesRemoveBackgrounHistogramDrawLine(e) {
5252         var PosX = 0;
5253         var PosY = 0;
5254         var image_width = removeBackgroundHistogramImg.width;
5255         var image_height = removeBackgroundHistogramImg.height;
5257         var ImgPos;
5258         ImgPos = FindPosition(removeBackgroundHistogramImg);
5259         if (!e) var e = window.event;
5260         if (e.pageX || e.pageY) {
5261             PosX = e.pageX;
5262             PosY = e.pageY;
5263         }
5264         else if (e.clientX || e.clientY) {
5265             PosX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
5266             PosY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
5267         }
5268         PosX = PosX - ImgPos[0];
5269         PosY = PosY - ImgPos[1];
5271         if (!removeBackgroundThresholdPeak1 || !removeBackgroundThresholdPeak2) {
5272             removeBackgroundHistogramImgDrawLine(removeBackgroundHistogramImg, PosX, image_height, '#ff0000');
5274             var threshold_value = Math.round( (((PosX+1)/3)-1) );
5275             if (removeBackgroundThresholdPeak1) {
5276                 removeBackgroundThresholdPeak2 = threshold_value;
5277                 removeBackgroundThresholdPeak2pixels = PosX;
5278             } else {
5279                 removeBackgroundThresholdPeak1 = threshold_value;
5280                 removeBackgroundThresholdPeak1pixels = PosX;
5281             }
5282         }
5283     }
5285     jQuery('#drone_imagery_remove_background_submit').click(function(){
5286         manage_drone_imagery_remove_background_threshold_save(remove_background_current_image_id, remove_background_current_image_type, remove_background_drone_run_band_project_id, removeBackgroundThresholdValue, '255');
5287     });
5289     jQuery('#drone_imagery_remove_background_defined_submit').click(function(){
5290         var remove_background_drone_run_band_lower_threshold = jQuery('#drone_imagery_remove_background_lower_threshold').val();
5291         var remove_background_drone_run_band_upper_threshold = jQuery('#drone_imagery_remove_background_upper_threshold').val();
5292         manage_drone_imagery_remove_background_threshold_save(remove_background_current_image_id, remove_background_current_image_type, remove_background_drone_run_band_project_id, remove_background_drone_run_band_lower_threshold, remove_background_drone_run_band_upper_threshold);
5293     });
5295     function calculateThresholdPercentageValues(canvas_div_id, drone_imagery_remove_background_lower_percentage, drone_imagery_remove_background_upper_percentage) {
5296         var src = cv.imread(canvas_div_id);
5297         cv.cvtColor(src, src, cv.COLOR_RGBA2GRAY, 0);
5298         var srcVec = new cv.MatVector();
5299         srcVec.push_back(src);
5300         var total_pixels = src.cols * src.rows;
5301         var accumulate = false;
5302         var channels = [0];
5303         var histSize = [256];
5304         var ranges = [0, 255];
5305         var hist = new cv.Mat();
5306         var mask = new cv.Mat();
5308         cv.calcHist(srcVec, channels, mask, hist, histSize, ranges, accumulate);
5309         var summing = 0;
5310         var drone_imagery_remove_background_lower_percentage_threshold;
5311         var drone_imagery_remove_background_upper_percentage_threshold;
5312         for (let i = 0; i < histSize[0]; i++) {
5313             var binVal = hist.data32F[i];
5314             summing = summing + binVal;
5315             var percentage = summing / total_pixels;
5316             if (percentage >= drone_imagery_remove_background_lower_percentage) {
5317                 drone_imagery_remove_background_lower_percentage_threshold = i;
5318                 break;
5319             }
5320         }
5321         summing = 0;
5322         for (let i = 0; i < histSize[0]; i++) {
5323             var binVal = hist.data32F[i];
5324             summing = summing + binVal;
5325             var percentage = summing / total_pixels;
5326             if (percentage >= 1-drone_imagery_remove_background_upper_percentage) {
5327                 drone_imagery_remove_background_upper_percentage_threshold = i;
5328                 break;
5329             }
5330         }
5331         return [drone_imagery_remove_background_lower_percentage_threshold*100, drone_imagery_remove_background_upper_percentage_threshold*100];
5332     }
5334     jQuery('#drone_imagery_remove_background_defined_percentage_submit').click(function(){
5335         var drone_imagery_remove_background_lower_percentage = Number(jQuery('#drone_imagery_remove_background_lower_threshold_percentage').val())/100;
5336         var drone_imagery_remove_background_upper_percentage = Number(jQuery('#drone_imagery_remove_background_upper_threshold_percentage').val())/100;
5338         var threshold_value_return = calculateThresholdPercentageValues('drone_imagery_remove_background_original', drone_imagery_remove_background_lower_percentage, drone_imagery_remove_background_upper_percentage);
5340         manage_drone_imagery_remove_background_threshold_save(remove_background_current_image_id, remove_background_current_image_type, remove_background_drone_run_band_project_id, threshold_value_return[0], threshold_value_return[1]);
5341     });
5343     function manage_drone_imagery_remove_background_threshold_save(image_id, image_type, drone_run_band_project_id, lower_threshold, upper_threshold){
5344         jQuery.ajax({
5345             type: 'POST',
5346             url: '/api/drone_imagery/remove_background_save',
5347             dataType: "json",
5348             data: {
5349                 'image_id': image_id,
5350                 'image_type': image_type,
5351                 'drone_run_band_project_id': drone_run_band_project_id,
5352                 'lower_threshold': lower_threshold,
5353                 'upper_threshold': upper_threshold
5354             },
5355             beforeSend: function() {
5356                 jQuery("#working_modal").modal("show");
5357             },
5358             success: function(response){
5359                 console.log(response);
5360                 if(response.error) {
5361                     alert(response.error);
5362                 }
5364                 jQuery("#working_modal").modal("hide");
5365                 location.reload();
5366             },
5367             error: function(response){
5368                 jQuery("#working_modal").modal("hide");
5369                 alert('Error saving removed background image!')
5370             }
5371         });
5372     }
5374     //
5375     //Calculate Phenotypes JS
5376     //
5378     var manage_drone_imagery_calculate_phenotypes_drone_run_id;
5379     var manage_drone_imagery_calculate_phenotypes_drone_run_band_id;
5380     var manage_drone_imagery_calculate_phenotypes_drone_run_band_type;
5381     var manage_drone_imagery_calculate_phenotypes_plot_polygons_type;
5382     var manage_drone_image_calculate_phenotypes_zonal_time_cvterm_id = '';
5384     jQuery(document).on('click', 'button[name=project_drone_imagery_get_phenotypes]', function() {
5385         showManageDroneImagerySection('manage_drone_imagery_calculate_phenotypes_div');
5387         manage_drone_imagery_calculate_phenotypes_drone_run_id = jQuery(this).data('drone_run_project_id');
5388         manage_drone_imagery_calculate_phenotypes_drone_run_band_id = jQuery(this).data('drone_run_band_project_id');
5389         manage_drone_imagery_calculate_phenotypes_drone_run_band_type = jQuery(this).data('drone_run_band_project_type');
5390         manage_drone_imagery_calculate_phenotypes_plot_polygons_type = jQuery(this).data('plot_polygons_type');
5391     });
5393     jQuery('#drone_imagery_calculate_phenotypes_sift').click(function(){
5395         jQuery.ajax({
5396             type: 'POST',
5397             url: '/api/drone_imagery/calculate_phenotypes?method=sift',
5398             dataType: "json",
5399             data: {
5400                 'drone_run_band_project_id': manage_drone_imagery_calculate_phenotypes_drone_run_band_id,
5401                 'drone_run_band_project_type': manage_drone_imagery_calculate_phenotypes_drone_run_band_type,
5402                 'plot_polygons_type': manage_drone_imagery_calculate_phenotypes_plot_polygons_type
5403             },
5404             beforeSend: function() {
5405                 jQuery("#working_modal").modal("show");
5406             },
5407             success: function(response){
5408                 console.log(response);
5409                 if(response.error) {
5410                     alert(response.error);
5411                     return;
5412                 }
5414                 var html = '<table class="table table-bordered table-hover"><thead><tr><th>Observation Unit</th><th>SIFT Features Image</th></tr></thead><tbody>';
5415                 for (var i=0; i<response.results.length; i++) {
5416                     html = html + '<tr><td><a target="_blank" href="/stock/' + response.results[i].stock_id + '/view" >' + response.results[i].stock_uniquename + '</a></td><td>' + response.results[i].image + '</td></tr>';
5417                 }
5418                 jQuery('#manage_drone_imagery_calculate_phenotypes_show_sift').html(html);
5420                 jQuery("#working_modal").modal("hide");
5421             },
5422             error: function(response){
5423                 jQuery("#working_modal").modal("hide");
5424                 alert('Error calculating sift features!')
5425             }
5426         });
5428     });
5430     jQuery('#drone_imagery_calculate_phenotypes_orb').click(function(){
5432         jQuery.ajax({
5433             type: 'POST',
5434             url: '/api/drone_imagery/calculate_phenotypes?method=orb',
5435             dataType: "json",
5436             data: {
5437                 'drone_run_band_project_id': manage_drone_imagery_calculate_phenotypes_drone_run_band_id,
5438                 'drone_run_band_project_type': manage_drone_imagery_calculate_phenotypes_drone_run_band_type,
5439                 'plot_polygons_type': manage_drone_imagery_calculate_phenotypes_plot_polygons_type
5440             },
5441             beforeSend: function() {
5442                 jQuery("#working_modal").modal("show");
5443             },
5444             success: function(response){
5445                 console.log(response);
5446                 if(response.error) {
5447                     alert(response.error);
5448                     return;
5449                 }
5451                 var html = '<table class="table table-bordered table-hover"><thead><tr><th>Observation Unit</th><th>ORB Features Image</th></tr></thead><tbody>';
5452                 for (var i=0; i<response.results.length; i++) {
5453                     html = html + '<tr><td><a target="_blank" href="/stock/' + response.results[i].stock_id + '/view" >' + response.results[i].stock_uniquename + '</a></td><td>' + response.results[i].image + '</td></tr>';
5454                 }
5455                 jQuery('#manage_drone_imagery_calculate_phenotypes_show_orb').html(html);
5457                 jQuery("#working_modal").modal("hide");
5458             },
5459             error: function(response){
5460                 jQuery("#working_modal").modal("hide");
5461                 alert('Error calculating ORB features!')
5462             }
5463         });
5465     });
5467     jQuery('#drone_imagery_calculate_phenotypes_surf').click(function(){
5469         jQuery.ajax({
5470             type: 'POST',
5471             url: '/api/drone_imagery/calculate_phenotypes?method=surf',
5472             dataType: "json",
5473             data: {
5474                 'drone_run_band_project_id': manage_drone_imagery_calculate_phenotypes_drone_run_band_id,
5475                 'drone_run_band_project_type': manage_drone_imagery_calculate_phenotypes_drone_run_band_type,
5476                 'plot_polygons_type': manage_drone_imagery_calculate_phenotypes_plot_polygons_type
5477             },
5478             beforeSend: function() {
5479                 jQuery("#working_modal").modal("show");
5480             },
5481             success: function(response){
5482                 console.log(response);
5483                 if(response.error) {
5484                     alert(response.error);
5485                     return;
5486                 }
5488                 var html = '<table class="table table-bordered table-hover"><thead><tr><th>Observation Unit</th><th>SURF Features Image</th></tr></thead><tbody>';
5489                 for (var i=0; i<response.results.length; i++) {
5490                     html = html + '<tr><td><a target="_blank" href="/stock/' + response.results[i].stock_id + '/view" >' + response.results[i].stock_uniquename + '</a></td><td>' + response.results[i].image + '</td></tr>';
5491                 }
5492                 jQuery('#manage_drone_imagery_calculate_phenotypes_show_surf').html(html);
5494                 jQuery("#working_modal").modal("hide");
5495             },
5496             error: function(response){
5497                 jQuery("#working_modal").modal("hide");
5498                 alert('Error calculating surf features!')
5499             }
5500         });
5502     });
5504     jQuery('#drone_imagery_calculate_phenotypes_zonal_stats').click(function(){
5506         jQuery.ajax({
5507             type: 'GET',
5508             url: '/api/drone_imagery/get_weeks_after_planting_date?drone_run_project_id='+manage_drone_imagery_calculate_phenotypes_drone_run_id,
5509             dataType: "json",
5510             beforeSend: function (){
5511                 jQuery('#working_modal').modal('show');
5512             },
5513             success: function(response){
5514                 jQuery('#working_modal').modal('hide');
5515                 console.log(response);
5516                 if (response.error) {
5517                     alert(response.error);
5518                 }
5520                 var html = "<center><b>Field Trial Planting Date</b>: "+response.planting_date+"<br/><b>Drone Run Date</b>: "+response.drone_run_date+"<br/><b>Number of Weeks</b>: "+response.rounded_time_difference_weeks+"<br/><b>Number of Weeks Ontology Term</b>: "+response.time_ontology_week_term+"<br/><b>Number of Days</b>:"+response.time_difference_days+"<br/><b>Number of Days Ontology Term</b>: "+response.time_ontology_day_term+"<br/><br/></center>";
5521                 jQuery('#drone_imagery_calculate_phenotypes_zonal_stats_week_term_div').html(html);
5522                 manage_drone_image_calculate_phenotypes_zonal_time_cvterm_id = response.time_ontology_day_cvterm_id;
5523             },
5524             error: function(response){
5525                 alert('Error getting time terms!');
5526                 jQuery('#working_modal').modal('hide');
5527             }
5528         });
5529         
5530         jQuery('#drone_imagery_calc_phenotypes_zonal_channel_dialog').modal('show');
5531     });
5533     jQuery('#drone_imagery_calculate_phenotypes_zonal_stats_channel_select').click(function(){
5534         if (manage_drone_image_calculate_phenotypes_zonal_time_cvterm_id == '') {
5535             alert('Time of phenotype not set for calculate zonal stats. This should not happen so please contact us!');
5536             return false;
5537         }
5539         jQuery.ajax({
5540             type: 'POST',
5541             url: '/api/drone_imagery/calculate_phenotypes?method=zonal',
5542             dataType: "json",
5543             data: {
5544                 'drone_run_band_project_id': manage_drone_imagery_calculate_phenotypes_drone_run_band_id,
5545                 'drone_run_band_project_type': manage_drone_imagery_calculate_phenotypes_drone_run_band_type,
5546                 'time_cvterm_id': manage_drone_image_calculate_phenotypes_zonal_time_cvterm_id,
5547                 'plot_polygons_type': manage_drone_imagery_calculate_phenotypes_plot_polygons_type,
5548             },
5549             beforeSend: function() {
5550                 jQuery("#working_modal").modal("show");
5551             },
5552             success: function(response){
5553                 console.log(response);
5554                 jQuery("#working_modal").modal("hide");
5556                 if(response.error) {
5557                     alert(response.error);
5558                     return false;
5559                 }
5561                 var html = '<table class="table table-bordered table-hover" id="manage_drone_imagery_zonal_stats_table"><thead><tr><th>Observation Unit</th><th>Image</th>';
5562                 for (var i=0; i<response.result_header.length; i++) {
5563                     html = html + '<th>'+response.result_header[i]+'</th>';
5564                 }
5565                 html = html + '</tr></thead><tbody>';
5566                 for (var i=0; i<response.results.length; i++) {
5567                     html = html + '<tr><td><a target="_blank" href="/stock/' + response.results[i].stock_id + '/view" >' + response.results[i].stock_uniquename + '</a></td><td>' + response.results[i].image + '</td>';
5568                     for (var j=0; j<response.results[i].result.length; j++){
5569                         html = html + '<td>'+response.results[i].result[j]+'</td>';
5570                     }
5571                     html = html + '</tr>';
5572                 }
5573                 jQuery('#manage_drone_imagery_calculate_phenotypes_show_zonal_stats').html(html);
5574                 jQuery('#manage_drone_imagery_zonal_stats_table').DataTable();
5576                 jQuery('#drone_imagery_calc_phenotypes_zonal_channel_dialog').modal('hide');
5577                 return false;
5578             },
5579             error: function(response){
5580                 jQuery("#working_modal").modal("hide");
5581                 alert('Error calculating zonal stats!')
5582             }
5583         });
5584     });
5586     //
5587     //RGB/3band Image Vegetative Index
5588     //
5590     var manage_drone_imagery_vi_rgb_drone_run_band_project_id;
5591     var manage_drone_imagery_vi_rgb_denoised_stitched_image_id;
5592     var manage_drone_imagery_vi_drone_run_band_type;
5593     var manage_drone_imagery_vi_selected_index;
5594     var manage_drone_imagery_vi_selected_image_type;
5596     jQuery(document).on('click', 'button[name="project_drone_imagery_rgb_vegetative"]', function(){
5597         manage_drone_imagery_vi_rgb_drone_run_band_project_id = jQuery(this).data('drone_run_band_project_id');
5598         manage_drone_imagery_vi_rgb_denoised_stitched_image_id = jQuery(this).data('denoised_stitched_image_id');
5599         manage_drone_imagery_vi_drone_run_band_type = jQuery(this).data('drone_run_band_project_type');
5601         showManageDroneImagerySection('manage_drone_imagery_vegetative_index_div');
5603         jQuery('#manage_drone_imagery_vegetative_index_tgi_rgb_div').show();
5604         jQuery('#manage_drone_imagery_vegetative_index_tgi_bgr_div').hide();
5605         jQuery('#manage_drone_imagery_vegetative_index_vari_rgb_div').show();
5606         jQuery('#manage_drone_imagery_vegetative_index_vari_bgr_div').hide();
5607         jQuery('#manage_drone_imagery_vegetative_index_ndvi_div').hide();
5608         jQuery('#manage_drone_imagery_vegetative_index_ndre_div').hide();
5609     });
5611     jQuery(document).on('click', 'button[name="project_drone_imagery_3_band_bgr_vegetative"]', function(){
5612         manage_drone_imagery_vi_rgb_drone_run_band_project_id = jQuery(this).data('drone_run_band_project_id');
5613         manage_drone_imagery_vi_rgb_denoised_stitched_image_id = jQuery(this).data('denoised_stitched_image_id');
5614         manage_drone_imagery_vi_drone_run_band_type = jQuery(this).data('drone_run_band_project_type');
5616         showManageDroneImagerySection('manage_drone_imagery_vegetative_index_div');
5618         jQuery('#manage_drone_imagery_vegetative_index_tgi_rgb_div').hide();
5619         jQuery('#manage_drone_imagery_vegetative_index_tgi_bgr_div').show();
5620         jQuery('#manage_drone_imagery_vegetative_index_vari_rgb_div').hide();
5621         jQuery('#manage_drone_imagery_vegetative_index_vari_bgr_div').show();
5622         jQuery('#manage_drone_imagery_vegetative_index_ndvi_div').hide();
5623         jQuery('#manage_drone_imagery_vegetative_index_ndre_div').hide();
5624     });
5626     jQuery(document).on('click', 'button[name="project_drone_imagery_3_band_nrn_vegetative"]', function(){
5627         manage_drone_imagery_vi_rgb_drone_run_band_project_id = jQuery(this).data('drone_run_band_project_id');
5628         manage_drone_imagery_vi_rgb_denoised_stitched_image_id = jQuery(this).data('denoised_stitched_image_id');
5629         manage_drone_imagery_vi_drone_run_band_type = jQuery(this).data('drone_run_band_project_type');
5631         showManageDroneImagerySection('manage_drone_imagery_vegetative_index_div');
5633         jQuery('#manage_drone_imagery_vegetative_index_tgi_rgb_div').hide();
5634         jQuery('#manage_drone_imagery_vegetative_index_tgi_bgr_div').hide();
5635         jQuery('#manage_drone_imagery_vegetative_index_vari_rgb_div').hide();
5636         jQuery('#manage_drone_imagery_vegetative_index_vari_bgr_div').hide();
5637         jQuery('#manage_drone_imagery_vegetative_index_ndvi_div').show();
5638         jQuery('#manage_drone_imagery_vegetative_index_ndre_div').hide();
5639     });
5641     jQuery(document).on('click', 'button[name="project_drone_imagery_3_band_nren_vegetative"]', function(){
5642         manage_drone_imagery_vi_rgb_drone_run_band_project_id = jQuery(this).data('drone_run_band_project_id');
5643         manage_drone_imagery_vi_rgb_denoised_stitched_image_id = jQuery(this).data('denoised_stitched_image_id');
5644         manage_drone_imagery_vi_drone_run_band_type = jQuery(this).data('drone_run_band_project_type');
5646         showManageDroneImagerySection('manage_drone_imagery_vegetative_index_div');
5648         jQuery('#manage_drone_imagery_vegetative_index_tgi_rgb_div').hide();
5649         jQuery('#manage_drone_imagery_vegetative_index_tgi_bgr_div').hide();
5650         jQuery('#manage_drone_imagery_vegetative_index_vari_rgb_div').hide();
5651         jQuery('#manage_drone_imagery_vegetative_index_vari_bgr_div').hide();
5652         jQuery('#manage_drone_imagery_vegetative_index_ndvi_div').hide();
5653         jQuery('#manage_drone_imagery_vegetative_index_ndre_div').show();
5654     });
5656     jQuery('#drone_imagery_vegetative_index_TGI_bgr').click(function(){
5657         manage_drone_imagery_vi_selected_index = 'TGI';
5658         manage_drone_imagery_vi_selected_image_type = 'BGR';
5659         getVegetativeIndex('calculate_vegetative_index', manage_drone_imagery_vi_rgb_denoised_stitched_image_id, manage_drone_imagery_vi_rgb_drone_run_band_project_id, manage_drone_imagery_vi_drone_run_band_type, manage_drone_imagery_vi_selected_index, 1, manage_drone_imagery_vi_selected_image_type);
5660     });
5662     jQuery('#drone_imagery_vegetative_index_TGI_rgb').click(function(){
5663         manage_drone_imagery_vi_selected_index = 'TGI';
5664         manage_drone_imagery_vi_selected_image_type = 'BGR';
5665         getVegetativeIndex('calculate_vegetative_index', manage_drone_imagery_vi_rgb_denoised_stitched_image_id, manage_drone_imagery_vi_rgb_drone_run_band_project_id, manage_drone_imagery_vi_drone_run_band_type, manage_drone_imagery_vi_selected_index, 1, manage_drone_imagery_vi_selected_image_type);
5666     });
5668     jQuery('#drone_imagery_vegetative_index_VARI_bgr').click(function(){
5669         manage_drone_imagery_vi_selected_index = 'VARI';
5670         manage_drone_imagery_vi_selected_image_type = 'BGR';
5671         getVegetativeIndex('calculate_vegetative_index', manage_drone_imagery_vi_rgb_denoised_stitched_image_id, manage_drone_imagery_vi_rgb_drone_run_band_project_id, manage_drone_imagery_vi_drone_run_band_type, manage_drone_imagery_vi_selected_index, 1, manage_drone_imagery_vi_selected_image_type);
5672     });
5674     jQuery('#drone_imagery_vegetative_index_VARI_rgb').click(function(){
5675         manage_drone_imagery_vi_selected_index = 'VARI';
5676         manage_drone_imagery_vi_selected_image_type = 'BGR';
5677         getVegetativeIndex('calculate_vegetative_index', manage_drone_imagery_vi_rgb_denoised_stitched_image_id, manage_drone_imagery_vi_rgb_drone_run_band_project_id, manage_drone_imagery_vi_drone_run_band_type, manage_drone_imagery_vi_selected_index, 1, manage_drone_imagery_vi_selected_image_type);
5678     });
5680     jQuery('#drone_imagery_vegetative_index_NDVI').click(function(){
5681         manage_drone_imagery_vi_selected_index = 'NDVI';
5682         manage_drone_imagery_vi_selected_image_type = 'NRN';
5683         getVegetativeIndex('calculate_vegetative_index', manage_drone_imagery_vi_rgb_denoised_stitched_image_id, manage_drone_imagery_vi_rgb_drone_run_band_project_id, manage_drone_imagery_vi_drone_run_band_type, manage_drone_imagery_vi_selected_index, 1, manage_drone_imagery_vi_selected_image_type);
5684     });
5686     jQuery('#drone_imagery_vegetative_index_NDRE').click(function(){
5687         manage_drone_imagery_vi_selected_index = 'NDRE';
5688         manage_drone_imagery_vi_selected_image_type = 'NReN';
5689         getVegetativeIndex('calculate_vegetative_index', manage_drone_imagery_vi_rgb_denoised_stitched_image_id, manage_drone_imagery_vi_rgb_drone_run_band_project_id, manage_drone_imagery_vi_drone_run_band_type, manage_drone_imagery_vi_selected_index, 1, manage_drone_imagery_vi_selected_image_type);
5690     });
5692     jQuery('#drone_imagery_rgb_vegetative_index_submit').click(function(){
5693         getVegetativeIndex('calculate_vegetative_index', manage_drone_imagery_vi_rgb_denoised_stitched_image_id, manage_drone_imagery_vi_rgb_drone_run_band_project_id, manage_drone_imagery_vi_drone_run_band_type, manage_drone_imagery_vi_selected_index, 0, manage_drone_imagery_vi_selected_image_type);
5694     });
5696     function getVegetativeIndex(url_part, image_id, drone_run_band_project_id, drone_run_band_project_type, index, view_only, manage_drone_imagery_vi_selected_image_type) {
5697         jQuery.ajax({
5698             type: 'POST',
5699             url: '/api/drone_imagery/'+url_part,
5700             dataType: "json",
5701             data: {
5702                 'image_id': image_id,
5703                 'drone_run_band_project_id': drone_run_band_project_id,
5704                 'vegetative_index': index,
5705                 'drone_run_band_project_type': drone_run_band_project_type,
5706                 'view_only': view_only,
5707                 'image_type': manage_drone_imagery_vi_selected_image_type
5708             },
5709             beforeSend: function() {
5710                 jQuery("#working_modal").modal("show");
5711             },
5712             success: function(response){
5713                 console.log(response);
5714                 jQuery("#working_modal").modal("hide");
5716                 if(response.error) {
5717                     alert(response.error);
5718                 }
5720                 if (view_only == 1) {
5721                     var canvas = document.getElementById('drone_imagery_vegetative_index_original_stitched_div');
5722                     ctx = canvas.getContext('2d');
5723                     var image = new Image();
5724                     image.onload = function () {
5725                         canvas.width = this.naturalWidth;
5726                         canvas.height = this.naturalHeight;
5727                         ctx.drawImage(this, 0, 0);
5728                     };
5729                     image.src = response.index_image_url;
5730                 } else {
5731                     location.reload();
5732                 }
5733             },
5734             error: function(response){
5735                 alert('Error getting vegetative index!')
5736             }
5737         });
5738     }
5740     //
5741     // Apply Masks From Background Removed Vegetative Index to Denoised Image
5742     //
5744     jQuery(document).on('click', 'button[name="project_drone_imagery_apply_tgi_removed_background_mask_to_denoised_image"]', function(){
5745         drone_imagery_mask_remove_background(jQuery(this).data('denoised_stitched_image_id'), jQuery(this).data('background_removed_tgi_stitched_image_id'), jQuery(this).data('drone_run_band_project_id'), 'denoised_background_removed_thresholded_tgi_mask_original');
5746     });
5748     jQuery(document).on('click', 'button[name="project_drone_imagery_apply_vari_removed_background_mask_to_denoised_image"]', function(){
5749         drone_imagery_mask_remove_background(jQuery(this).data('denoised_stitched_image_id'), jQuery(this).data('background_removed_vari_stitched_image_id'), jQuery(this).data('drone_run_band_project_id'), 'denoised_background_removed_thresholded_vari_mask_original');
5750     });
5752     jQuery(document).on('click', 'button[name="project_drone_imagery_apply_ndvi_removed_background_mask_to_denoised_image"]', function(){
5753         drone_imagery_mask_remove_background(jQuery(this).data('denoised_stitched_image_id'), jQuery(this).data('background_removed_ndvi_stitched_image_id'), jQuery(this).data('drone_run_band_project_id'), 'denoised_background_removed_thresholded_ndvi_mask_original');
5754     });
5756     jQuery(document).on('click', 'button[name="project_drone_imagery_apply_ndre_removed_background_mask_to_denoised_image"]', function(){
5757         drone_imagery_mask_remove_background(jQuery(this).data('denoised_stitched_image_id'), jQuery(this).data('background_removed_ndre_stitched_image_id'), jQuery(this).data('drone_run_band_project_id'), 'denoised_background_removed_thresholded_ndre_mask_original');
5758     });
5760     jQuery(document).on('click', 'button[name="project_drone_imagery_apply_tgi_mask_to_denoised_image"]', function(){
5761         drone_imagery_mask_remove_background(jQuery(this).data('denoised_stitched_image_id'), jQuery(this).data('tgi_stitched_image_id'), jQuery(this).data('drone_run_band_project_id'), 'denoised_background_removed_tgi_mask_original');
5762     });
5764     jQuery(document).on('click', 'button[name="project_drone_imagery_apply_vari_mask_to_denoised_image"]', function(){
5765         drone_imagery_mask_remove_background(jQuery(this).data('denoised_stitched_image_id'), jQuery(this).data('vari_stitched_image_id'), jQuery(this).data('drone_run_band_project_id'), 'denoised_background_removed_vari_mask_original');
5766     });
5768     jQuery(document).on('click', 'button[name="project_drone_imagery_apply_ndvi_mask_to_denoised_image"]', function(){
5769         drone_imagery_mask_remove_background(jQuery(this).data('denoised_stitched_image_id'), jQuery(this).data('ndvi_stitched_image_id'), jQuery(this).data('drone_run_band_project_id'), 'denoised_background_removed_ndvi_mask_original');
5770     });
5772     jQuery(document).on('click', 'button[name="project_drone_imagery_apply_ndre_mask_to_denoised_image"]', function(){
5773         drone_imagery_mask_remove_background(jQuery(this).data('denoised_stitched_image_id'), jQuery(this).data('ndre_stitched_image_id'), jQuery(this).data('drone_run_band_project_id'), 'denoised_background_removed_ndre_mask_original');
5774     });
5776     function drone_imagery_mask_remove_background(image_id, mask_image_id, drone_run_band_project_id, mask_type) {
5777         jQuery.ajax({
5778             type: 'POST',
5779             url: '/api/drone_imagery/mask_remove_background',
5780             dataType: "json",
5781             data: {
5782                 'image_id': image_id,
5783                 'mask_image_id': mask_image_id,
5784                 'drone_run_band_project_id': drone_run_band_project_id,
5785                 'mask_type': mask_type
5786             },
5787             beforeSend: function() {
5788                 jQuery("#working_modal").modal("show");
5789             },
5790             success: function(response){
5791                 console.log(response);
5792                 jQuery("#working_modal").modal("hide");
5794                 if(response.error) {
5795                     alert(response.error);
5796                 }
5798                 location.reload();
5799             },
5800             error: function(response){
5801                 alert('Error removing background using mask of vegetative index!' + mask_type);
5802             }
5803         });
5804     }
5806     //
5807     // Run and save Fourier Transform HPF30
5808     //
5810     var manage_drone_imagery_ft_hpf30_drone_run_band_project_id = '';
5811     var manage_drone_imagery_ft_hpf30_image_id = '';
5812     var manage_drone_imagery_ft_hpf30_drone_run_band_type = '';
5813     var manage_drone_imagery_ft_hpf30_selected_image_type = '';
5815     jQuery(document).on('click', 'button[name="project_drone_imagery_fourier_transform_hpf30"]', function(){
5816         manage_drone_imagery_ft_hpf30_drone_run_band_project_id = jQuery(this).data('drone_run_band_project_id');
5817         manage_drone_imagery_ft_hpf30_image_id = jQuery(this).data('image_id');
5818         manage_drone_imagery_ft_hpf30_drone_run_band_type = jQuery(this).data('drone_run_band_project_type');
5819         manage_drone_imagery_ft_hpf30_selected_image_type = jQuery(this).data('selected_image_type');
5820         getFourierTransform(30, manage_drone_imagery_ft_hpf30_image_id, manage_drone_imagery_ft_hpf30_drone_run_band_project_id, manage_drone_imagery_ft_hpf30_drone_run_band_type, manage_drone_imagery_ft_hpf30_selected_image_type, 'frequency');
5821     });
5823     function getFourierTransform(high_pass_filter, image_id, drone_run_band_project_id, drone_run_band_project_type, selected_image_type, high_pass_filter_type) {
5824         jQuery.ajax({
5825             type: 'POST',
5826             url: '/api/drone_imagery/calculate_fourier_transform',
5827             dataType: "json",
5828             data: {
5829                 'image_id': image_id,
5830                 'drone_run_band_project_id': drone_run_band_project_id,
5831                 'drone_run_band_project_type': drone_run_band_project_type,
5832                 'high_pass_filter': high_pass_filter,
5833                 'high_pass_filter_type': high_pass_filter_type,
5834                 'image_type': selected_image_type
5835             },
5836             beforeSend: function() {
5837                 jQuery("#working_modal").modal("show");
5838             },
5839             success: function(response){
5840                 console.log(response);
5841                 jQuery("#working_modal").modal("hide");
5843                 if(response.error) {
5844                     alert(response.error);
5845                 }
5847                 location.reload();
5848             },
5849             error: function(response){
5850                 jQuery("#working_modal").modal("hide");
5851                 alert('Error getting fourier transform!')
5852             }
5853         });
5854     }
5856     //
5857     // Merge bands into single image
5858     //
5860     var drone_imagery_merge_channels_drone_run_project_id;
5861     var drone_imagery_merge_channels_drone_run_project_name;
5862     jQuery(document).on('click', 'button[name="project_drone_imagery_merge_channels"]', function() {
5863         drone_imagery_merge_channels_drone_run_project_id = jQuery(this).data('drone_run_project_id');
5864         drone_imagery_merge_channels_drone_run_project_name = jQuery(this).data('drone_run_project_name');
5866         jQuery('#drone_imagery_merge_channels_dialog').modal('show');
5868         get_select_box('drone_imagery_drone_run_band','drone_imagery_merge_bands_band1_select', {'id':'drone_run_merge_band_select_1', 'name':'drone_run_merge_band_select_1', 'empty':1, 'drone_run_project_id':drone_imagery_merge_channels_drone_run_project_id });
5869         get_select_box('drone_imagery_drone_run_band','drone_imagery_merge_bands_band2_select', {'id':'drone_run_merge_band_select_2', 'name':'drone_run_merge_band_select_2', 'empty':1, 'drone_run_project_id':drone_imagery_merge_channels_drone_run_project_id });
5870         get_select_box('drone_imagery_drone_run_band','drone_imagery_merge_bands_band3_select', {'id':'drone_run_merge_band_select_3', 'name':'drone_run_merge_band_select_3', 'empty':1, 'drone_run_project_id':drone_imagery_merge_channels_drone_run_project_id });
5871     });
5873     jQuery('#drone_imagery_merge_bands_submit').click(function(){
5874         var band_1_drone_run_band_project_id = jQuery('#drone_run_merge_band_select_1').val();
5875         var band_2_drone_run_band_project_id = jQuery('#drone_run_merge_band_select_2').val();
5876         var band_3_drone_run_band_project_id = jQuery('#drone_run_merge_band_select_3').val();
5877         var merged_image_type = jQuery('#drone_run_merge_image_type').val();
5878         if (merged_image_type == '') {
5879             alert('Please select a merged image type first!');
5880             return false;
5881         }
5883         jQuery.ajax({
5884             type: 'POST',
5885             url: '/api/drone_imagery/merge_bands',
5886             dataType: "json",
5887             data: {
5888                 'band_1_drone_run_band_project_id': band_1_drone_run_band_project_id,
5889                 'band_2_drone_run_band_project_id': band_2_drone_run_band_project_id,
5890                 'band_3_drone_run_band_project_id': band_3_drone_run_band_project_id,
5891                 'drone_run_project_id': drone_imagery_merge_channels_drone_run_project_id,
5892                 'drone_run_project_name': drone_imagery_merge_channels_drone_run_project_name,
5893                 'merged_image_type' : merged_image_type
5894             },
5895             beforeSend: function() {
5896                 jQuery("#working_modal").modal("show");
5897             },
5898             success: function(response){
5899                 console.log(response);
5900                 jQuery("#working_modal").modal("hide");
5902                 if(response.error) {
5903                     alert(response.error);
5904                 }
5906                 location.reload();
5907             },
5908             error: function(response){
5909                 jQuery("#working_modal").modal("hide");
5910                 alert('Error merging bands!')
5911             }
5912         });
5913     });
5915     //
5916     // Compare Aerial Field Images
5917     //
5919     var drone_imagery_compare_images_comparison_type = '';
5920     var drone_imagery_compare_images_field_trial_ids = [];
5921     var drone_imagery_compare_images_field_trial_id_string = '';
5922     var drone_imagery_compare_images_drone_run_ids = [];
5923     var drone_imagery_compare_images_drone_run_band_ids = [];
5924     var drone_imagery_compare_images_image_types = [];
5926     jQuery('#drone_imagery_compare_field_images_link').click(function(){
5927         jQuery('#drone_imagery_compare_images_dialog').modal('show');
5929         drone_imagery_compare_images_comparison_type =   '';
5930         drone_imagery_compare_images_field_trial_ids = [];
5931         drone_imagery_compare_images_field_trial_id_string = '';
5932         drone_imagery_compare_images_drone_run_ids = [];
5933         drone_imagery_compare_images_image_types = [];
5934     });
5936     jQuery('#drone_imagery_compare_images_comparison_select_step').click(function(){
5937         get_select_box('trials', 'drone_imagery_compare_images_trial_select_div', { 'name' : 'drone_imagery_compare_images_field_trial_id', 'id' : 'drone_imagery_compare_images_field_trial_id', 'empty':1, 'multiple':1 });
5938     
5939         Workflow.complete("#drone_imagery_compare_images_comparison_select_step");
5940         Workflow.focus('#drone_imagery_compare_images_workflow', 1);
5941         return false;
5942     });
5944     jQuery('#drone_imagery_compare_images_field_trial_select_step').click(function(){
5945         drone_imagery_compare_images_field_trial_ids = [];
5946         drone_imagery_compare_images_field_trial_id_string = '';
5947         drone_imagery_compare_images_field_trial_ids = jQuery('#drone_imagery_compare_images_field_trial_id').val();
5948         drone_imagery_compare_images_field_trial_id_string = drone_imagery_compare_images_field_trial_ids.join(",");
5949         if (drone_imagery_compare_images_field_trial_id_string == '') {
5950             alert('Please select a field trial first!');
5951         } else {
5952             jQuery('#drone_image_compare_images_drone_runs_table').DataTable({
5953                 destroy : true,
5954                 ajax : '/api/drone_imagery/drone_runs?select_checkbox_name=drone_imagery_compare_images_drone_run_select&field_trial_ids='+drone_imagery_compare_images_field_trial_id_string
5955             });
5956         
5957             Workflow.complete("#drone_imagery_compare_images_field_trial_select_step");
5958             Workflow.focus('#drone_imagery_compare_images_workflow', 2);
5959         }
5960         return false;
5961     });
5963     jQuery('#drone_imagery_compare_images_drone_runs_select_step').click(function(){
5964         drone_imagery_compare_images_drone_run_ids = [];
5965         jQuery('input[name="drone_imagery_compare_images_drone_run_select"]:checked').each(function() {
5966             drone_imagery_compare_images_drone_run_ids.push(jQuery(this).val());
5967         });
5968         if (drone_imagery_compare_images_drone_run_ids.length < 1){
5969             alert('Please select at least one drone run!');
5970         } else if (drone_imagery_compare_images_drone_run_ids.length > 2){
5971             alert('Please select a maximum of two drone runs, given that we can only compare two images at a time here.');
5972         } else {
5973             jQuery('#drone_image_compare_images_drone_run_bands_table').DataTable({
5974                 destroy : true,
5975                 ajax : '/api/drone_imagery/drone_run_bands?select_checkbox_name=drone_run_compare_images_band_select&drone_run_project_ids='+JSON.stringify(drone_imagery_compare_images_drone_run_ids)
5976             });
5978             Workflow.complete("#drone_imagery_compare_images_drone_runs_select_step");
5979             Workflow.focus('#drone_imagery_compare_images_workflow', 3);
5980         }
5981         return false;
5982     });
5984     jQuery('#drone_imagery_compare_images_drone_run_bands_select_step').click(function(){
5985         drone_imagery_compare_images_drone_run_band_ids = [];
5986         jQuery('input[name="drone_run_compare_images_band_select"]:checked').each(function() {
5987             drone_imagery_compare_images_drone_run_band_ids.push(jQuery(this).val());
5988         });
5989         if (drone_imagery_compare_images_drone_run_band_ids.length < 1){
5990             alert('Please select at least one drone run band!');
5991         } else if (drone_imagery_compare_images_drone_run_band_ids.length > 2){
5992             alert('Please select a maximum of two drone run bands, given that we can only compare two images at a time here.');
5993         } else {
5994             jQuery('#drone_imagery_compare_images_images_type_table').DataTable({
5995                 destroy : true,
5996                 paging : false,
5997                 ajax : '/api/drone_imagery/plot_polygon_types?select_checkbox_name=drone_imagery_compare_images_plot_polygon_type_select&field_trial_ids='+drone_imagery_compare_images_field_trial_id_string+'&drone_run_ids='+JSON.stringify(drone_imagery_compare_images_drone_run_ids)+'&field_trial_images_only=1+&drone_run_band_ids='+JSON.stringify(drone_imagery_compare_images_drone_run_band_ids)
5998             });
6000             Workflow.complete("#drone_imagery_compare_images_drone_run_bands_select_step");
6001             Workflow.focus('#drone_imagery_compare_images_workflow', 4);
6002         }
6003         return false;
6004     });
6006     jQuery('#drone_imagery_compare_images_images_select_step').click(function(){
6007         drone_imagery_compare_images_image_types = [];
6008         jQuery('input[name="drone_imagery_compare_images_plot_polygon_type_select"]:checked').each(function() {
6009             drone_imagery_compare_images_image_types.push(jQuery(this).val());
6010         });
6011         if (drone_imagery_compare_images_image_types.length < 1){
6012             alert('Please select at least one image type!');
6013         } else if (drone_imagery_compare_images_image_types.length > 2){
6014             alert('Please select a maximum of two image types, given that we can only compare two images at a time here.');
6015         } else {
6016             jQuery.ajax({
6017                 url : '/api/drone_imagery/compare_images?drone_run_ids='+JSON.stringify(drone_imagery_compare_images_drone_run_ids)+'&drone_run_band_ids='+JSON.stringify(drone_imagery_compare_images_drone_run_band_ids)+'&image_type_ids='+JSON.stringify(drone_imagery_compare_images_image_types)+'&comparison_type='+jQuery('#drone_imagery_compare_images_comparison_select').val(),
6018                 beforeSend: function() {
6019                     jQuery("#working_modal").modal("show");
6020                 },
6021                 success: function(response){
6022                     console.log(response);
6023                     jQuery("#working_modal").modal("hide");
6025                     var html = '<a target=_blank href="'+response.result+'">File</a>';
6026                     jQuery('#drone_imagery_compare_images_result_div').html(html);
6028                     Workflow.complete("#drone_imagery_compare_images_images_select_step");
6029                     Workflow.focus('#drone_imagery_compare_images_workflow', 5);
6030                 },
6031                 error: function(response){
6032                     jQuery("#working_modal").modal("hide");
6033                     alert('Error comparing images!')
6034                 }
6035             });
6036         }
6037         return false;
6038     });
6040     //
6041     // Delete drone run
6042     //
6044     var manage_drone_imagery_delete_drone_run_project_id;
6045     jQuery(document).on('click', 'button[name="project_drone_imagery_delete_drone_run"]', function(){
6046         manage_drone_imagery_delete_drone_run_project_id = jQuery(this).data('drone_run_project_id');
6047         jQuery('#drone_imagery_delete_drone_run_dialog').modal('show');
6048     });
6050     jQuery('#drone_imagery_delete_drone_run_confirm').click(function(){
6051         jQuery.ajax({
6052             type: 'GET',
6053             url: '/api/drone_imagery/delete_drone_run?drone_run_project_id='+manage_drone_imagery_delete_drone_run_project_id,
6054             beforeSend: function() {
6055                 jQuery("#working_modal").modal("show");
6056             },
6057             success: function(response){
6058                 console.log(response);
6059                 jQuery("#working_modal").modal("hide");
6061                 if(response.error) {
6062                     alert(response.error);
6063                 }
6064                 if(response.success) {
6065                     alert('Drone run deleted successfully!');
6066                 }
6067                 location.reload();
6068             },
6069             error: function(response){
6070                 jQuery("#working_modal").modal("hide");
6071                 alert('Error deleting drone run!')
6072             }
6073         });
6074     });
6076     function showManageDroneImagerySection(section_div_id) {
6077         console.log(section_div_id);
6078         if (section_div_id == 'manage_drone_imagery_crop_div') {
6079             jQuery('#manage_drone_imagery_crop_div').show();
6080             jQuery('#manage_drone_imagery_top_div').hide();
6081             jQuery('#manage_drone_imagery_plot_polygons_div').hide();
6082             jQuery('#manage_drone_imagery_calculate_phenotypes_div').hide();
6083             jQuery('#manage_drone_imagery_remove_background_div').hide();
6084             jQuery('#manage_drone_imagery_rotate_div').hide();
6085             jQuery('#manage_drone_imagery_vegetative_index_div').hide();
6086             jQuery('#manage_drone_imagery_standard_process_div').hide();
6087             jQuery('#manage_drone_imagery_standard_process_raw_images_div').hide();
6088             jQuery('#manage_drone_imagery_loading_div').hide();
6089         } else if (section_div_id == 'manage_drone_imagery_top_div'){
6090             jQuery('#manage_drone_imagery_crop_div').hide();
6091             jQuery('#manage_drone_imagery_top_div').show();
6092             jQuery('#manage_drone_imagery_plot_polygons_div').hide();
6093             jQuery('#manage_drone_imagery_calculate_phenotypes_div').hide();
6094             jQuery('#manage_drone_imagery_remove_background_div').hide();
6095             jQuery('#manage_drone_imagery_rotate_div').hide();
6096             jQuery('#manage_drone_imagery_vegetative_index_div').hide();
6097             jQuery('#manage_drone_imagery_standard_process_div').hide();
6098             jQuery('#manage_drone_imagery_standard_process_raw_images_div').hide();
6099             jQuery('#manage_drone_imagery_loading_div').hide();
6100         } else if (section_div_id == 'manage_drone_imagery_plot_polygons_div'){
6101             jQuery('#manage_drone_imagery_crop_div').hide();
6102             jQuery('#manage_drone_imagery_top_div').hide();
6103             jQuery('#manage_drone_imagery_plot_polygons_div').show();
6104             jQuery('#manage_drone_imagery_calculate_phenotypes_div').hide();
6105             jQuery('#manage_drone_imagery_remove_background_div').hide();
6106             jQuery('#manage_drone_imagery_rotate_div').hide();
6107             jQuery('#manage_drone_imagery_vegetative_index_div').hide();
6108             jQuery('#manage_drone_imagery_standard_process_div').hide();
6109             jQuery('#manage_drone_imagery_standard_process_raw_images_div').hide();
6110             jQuery('#manage_drone_imagery_loading_div').hide();
6111         } else if (section_div_id == 'manage_drone_imagery_calculate_phenotypes_div'){
6112             jQuery('#manage_drone_imagery_crop_div').hide();
6113             jQuery('#manage_drone_imagery_top_div').hide();
6114             jQuery('#manage_drone_imagery_plot_polygons_div').hide();
6115             jQuery('#manage_drone_imagery_calculate_phenotypes_div').show();
6116             jQuery('#manage_drone_imagery_remove_background_div').hide();
6117             jQuery('#manage_drone_imagery_rotate_div').hide();
6118             jQuery('#manage_drone_imagery_vegetative_index_div').hide();
6119             jQuery('#manage_drone_imagery_standard_process_div').hide();
6120             jQuery('#manage_drone_imagery_standard_process_raw_images_div').hide();
6121             jQuery('#manage_drone_imagery_loading_div').hide();
6122         } else if (section_div_id == 'manage_drone_imagery_remove_background_div'){
6123             jQuery('#manage_drone_imagery_crop_div').hide();
6124             jQuery('#manage_drone_imagery_top_div').hide();
6125             jQuery('#manage_drone_imagery_plot_polygons_div').hide();
6126             jQuery('#manage_drone_imagery_calculate_phenotypes_div').hide();
6127             jQuery('#manage_drone_imagery_remove_background_div').show();
6128             jQuery('#manage_drone_imagery_rotate_div').hide();
6129             jQuery('#manage_drone_imagery_vegetative_index_div').hide();
6130             jQuery('#manage_drone_imagery_standard_process_div').hide();
6131             jQuery('#manage_drone_imagery_standard_process_raw_images_div').hide();
6132             jQuery('#manage_drone_imagery_loading_div').hide();
6133         } else if (section_div_id == 'manage_drone_imagery_rotate_div'){
6134             jQuery('#manage_drone_imagery_crop_div').hide();
6135             jQuery('#manage_drone_imagery_top_div').hide();
6136             jQuery('#manage_drone_imagery_plot_polygons_div').hide();
6137             jQuery('#manage_drone_imagery_calculate_phenotypes_div').hide();
6138             jQuery('#manage_drone_imagery_remove_background_div').hide();
6139             jQuery('#manage_drone_imagery_rotate_div').show();
6140             jQuery('#manage_drone_imagery_vegetative_index_div').hide();
6141             jQuery('#manage_drone_imagery_standard_process_div').hide();
6142             jQuery('#manage_drone_imagery_standard_process_raw_images_div').hide();
6143             jQuery('#manage_drone_imagery_loading_div').hide();
6144         } else if (section_div_id == 'manage_drone_imagery_vegetative_index_div'){
6145             jQuery('#manage_drone_imagery_crop_div').hide();
6146             jQuery('#manage_drone_imagery_top_div').hide();
6147             jQuery('#manage_drone_imagery_plot_polygons_div').hide();
6148             jQuery('#manage_drone_imagery_calculate_phenotypes_div').hide();
6149             jQuery('#manage_drone_imagery_remove_background_div').hide();
6150             jQuery('#manage_drone_imagery_rotate_div').hide();
6151             jQuery('#manage_drone_imagery_vegetative_index_div').show();
6152             jQuery('#manage_drone_imagery_standard_process_div').hide();
6153             jQuery('#manage_drone_imagery_standard_process_raw_images_div').hide();
6154             jQuery('#manage_drone_imagery_loading_div').hide();
6155         } else if (section_div_id == 'manage_drone_imagery_standard_process_div'){
6156             jQuery('#manage_drone_imagery_crop_div').hide();
6157             jQuery('#manage_drone_imagery_top_div').hide();
6158             jQuery('#manage_drone_imagery_plot_polygons_div').hide();
6159             jQuery('#manage_drone_imagery_calculate_phenotypes_div').hide();
6160             jQuery('#manage_drone_imagery_remove_background_div').hide();
6161             jQuery('#manage_drone_imagery_rotate_div').hide();
6162             jQuery('#manage_drone_imagery_vegetative_index_div').hide();
6163             jQuery('#manage_drone_imagery_standard_process_div').show();
6164             jQuery('#manage_drone_imagery_standard_process_raw_images_div').hide();
6165             jQuery('#manage_drone_imagery_loading_div').hide();
6166         } else if (section_div_id == 'manage_drone_imagery_standard_process_raw_images_div'){
6167             jQuery('#manage_drone_imagery_crop_div').hide();
6168             jQuery('#manage_drone_imagery_top_div').hide();
6169             jQuery('#manage_drone_imagery_plot_polygons_div').hide();
6170             jQuery('#manage_drone_imagery_calculate_phenotypes_div').hide();
6171             jQuery('#manage_drone_imagery_remove_background_div').hide();
6172             jQuery('#manage_drone_imagery_rotate_div').hide();
6173             jQuery('#manage_drone_imagery_vegetative_index_div').hide();
6174             jQuery('#manage_drone_imagery_standard_process_div').hide();
6175             jQuery('#manage_drone_imagery_standard_process_raw_images_div').show();
6176             jQuery('#manage_drone_imagery_loading_div').hide();
6177         } else if (section_div_id == 'manage_drone_imagery_loading_div'){
6178             jQuery('#manage_drone_imagery_crop_div').hide();
6179             jQuery('#manage_drone_imagery_top_div').hide();
6180             jQuery('#manage_drone_imagery_plot_polygons_div').hide();
6181             jQuery('#manage_drone_imagery_calculate_phenotypes_div').hide();
6182             jQuery('#manage_drone_imagery_remove_background_div').hide();
6183             jQuery('#manage_drone_imagery_rotate_div').hide();
6184             jQuery('#manage_drone_imagery_vegetative_index_div').hide();
6185             jQuery('#manage_drone_imagery_standard_process_div').hide();
6186             jQuery('#manage_drone_imagery_standard_process_raw_images_div').hide();
6187             jQuery('#manage_drone_imagery_loading_div').show();
6188         }
6189         window.scrollTo(0,0);
6190     }
6194 </script>