package SGN::View::Mason::Commands;
use strict;
use vars qw($m $c);
HTML::Mason::Component::FileBased->new(
'code' => sub {
use utf8; local $SGN::View::Mason::Commands::m = $HTML::Mason::Commands::m;
HTML::Mason::Exception::Params->throw
    ( error =>
      "Odd number of parameters passed to component expecting name/value pairs"
    ) if @_ % 2;
my ( $trial_id, $trial_name, $trial_stock_type );
{
    my %pos;
    for ( my $x = 0; $x < @_; $x += 2 )
    {
        $pos{ $_[$x] } = $x + 1;
    }

    foreach my $arg ( qw( trial_id trial_name ) )
    {
        HTML::Mason::Exception::Params->throw
            ( error => "no value sent for required parameter '$arg'" )
                unless exists $pos{$arg};
    }
#line 2 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
    $trial_id = $_[ $pos{'trial_id'} ];
#line 3 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
    $trial_name = $_[ $pos{'trial_name'} ];
#line 4 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
     $trial_stock_type = exists $pos{'trial_stock_type'} ? $_[ $pos{'trial_stock_type'} ] :  undef;
}
$m->debug_hook( $m->current_comp->path ) if ( HTML::Mason::Compiler::IN_PERL_DB() );

#line 6 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print( '

' );
#line 8 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->comp(   '/util/import_javascript.mas', classes => [ 'jqueryui.js', 'jquery.js' ]   
); #line 8 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print( '


<!-- Load DataTables CSS and JS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>

<!-- Load Buttons CSS and JS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.0.1/css/buttons.dataTables.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.0.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.0.1/js/buttons.html5.min.js"></script>

' );
#line 20 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->comp(   '/analyses/store_new_analysis_values_and_model.mas'  
); #line 20 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print( '

<div class="modal  fade" id="edit_field_map_dialog" name="edit_field_map_dialog" tabindex="-1" role="dialog" aria-labelledby="EditFieldMapDialog">
    <div class="modal-dialog " role="document">
        <div class="modal-content">
            <div class="modal-header" style="text-align: center">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="EditFieldMapDialog">Edit Field Map For ' );
#line 27 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print(  $trial_name  );
#line 27 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print( '</h4>
            </div>
            <div class="modal-body">
                <div class="container-fluid">

                    <form class="form-horizontal" role="form" method="post" enctype="multipart/form-data" encoding="multipart/form-data" id="edit_field_map_form" name="edit_field_map_form">
                        <p id = "edit_field_map_title"></p>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button id="close_edit_field_map_dialog" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" name="replace_trial_stock_submit" id="replace_trial_stock_submit"></button>
                <!-- <button type="button" class="btn btn-primary" name="substitute_stock_submit" id="substitute_stock_submit"></button> -->
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="replace_trial_stocks_dialog" name="replace_trial_stocks_dialog" tabindex="-1" role="dialog" aria-labelledby="replace_stocks_dialog">
    <div class="modal-dialog " role="document">
        <div class="modal-content">
            <div class="modal-header" style="text-align: center">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="replace_stocks_dialog"></h4>
            </div>
            <div class="modal-body">
                <div class="container-fluid">

                    <form class="form-horizontal" role="form" method="post" enctype="multipart/form-data" encoding="multipart/form-data" id="replace_trial_accession_form" name="replace_trial_accession_form">

	                    <div class="form-group">
	                      <label id = "replace_stock_label1" class="col-sm-3 control-label"></label>
	                      <div class="col-sm-9" id="stocks_in_trial">
	                        <!--<select class="form-control" id="stocks_in_trial" name="stocks_in_trial"></select>-->
	                      </div>
	                    </div>

	                      <div class="form-group">
	                        <label id = "replace_stock_label2" class="col-sm-3 control-label"></label>
	                        <div class="col-sm-9" >
	                          <input class="form-control" id="replace_database_stock" name="replace_database_stock"></input>
	                        </div>
	                      </div>

                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button id="close_replace_trial_accession_dialog" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" name="replace_stock_submit" id="replace_stock_submit"></button>
            </div>
        </div>
    </div>
</div>

<!--
<div class="modal fade" id="substitute_plot_stocks_dialog" name="substitute_plot_stocks_dialog" tabindex="-1" role="dialog" aria-labelledby="substitute_plot_dialog">
    <div class="modal-dialog " role="document">
        <div class="modal-content">
            <div class="modal-header" style="text-align: center">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="substitute_plot_dialog"></h4>
            </div>
            <div class="modal-body">
                <div class="container-fluid">

                    <form class="form-horizontal" role="form" method="post" enctype="multipart/form-data" encoding="multipart/form-data" id="substitute_plot_accession_form" name="substitute_plot_accession_form">

											<div class="form-group">
												<label class="col-sm-3 control-label">Select Plot 1: </label>
												<div class="col-sm-9" id="plot_name_in_trial">

												</div>
											</div>

											<div class="form-group">
												<label class="col-sm-3 control-label">Select Plot 2: </label>
												<div class="col-sm-9" id="sub_plot_accession_in_trial">
												</div>
											</div>

                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button id="close_substitute_plot_accession_dialog" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" name="substitute_plot_stock_submit" id="substitute_plot_stock_submit"></button>
            </div>
        </div>
    </div>
</div>
-->

<div class="modal  fade" id="replace_stock_dialog_success_message" name="replace_stock_dialog_success_message" tabindex="-1" role="dialog" aria-labelledby="replace_stock_message_title">
    <div class="modal-dialog " role="document">
        <div class="modal-content">
            <div class="modal-header" style="text-align: center">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="replace_stock_message_title"></h4>
            </div>
            <div class="modal-body">
                <div class="container-fluid">

                    <p3 id="replace_stock_success_message"></p3>

                </div>
            </div>
            <div class="modal-footer">
                <button id="close_replace_field_map_dialog" type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            </div>
        </div>
    </div>
</div>

<div class="modal  fade" id="sub_success_message" name="sub_success_message" tabindex="-1" role="dialog" aria-labelledby="subs_stock_message_title">
    <div class="modal-dialog " role="document">
        <div class="modal-content">
            <div class="modal-header" style="text-align: center">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="subs_stock_message_title"></h4>
            </div>
            <div class="modal-body">
                <div class="container-fluid">

                    <p3 id="subs_stock_success_message"></p3>

                </div>
            </div>
            <div class="modal-footer">
                <button id="close_subs_field_map_dialog" type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            </div>
        </div>
    </div>
</div>


<div class="modal  fade" id="fieldmap_usage_modal" name="fieldmap_usage_modal" tabindex="-1" role="dialog" aria-labelledby="UsageFieldMapDialog">
    <div class="modal-dialog modal-lg " role="document">
        <div class="modal-content">
            <div class="modal-header" style="text-align: center">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="UsageFieldMapDialog">How to Use and Edit Field Map </h4>
            </div>
            <div class="modal-body">
                <div class="container-fluid">

                <h4>
                  Background:
                </h4>
                  <center><p>Field map is a tool that enable users to view the physical layout of plots in a trial. Maps can be generated on the fly while adding a trial or uploading a trial. Field map coordinates can also be uploaded independently after trials have been added or uploaded. It is a very intuitive, flexible and user friendly tool for manipulation/making changes to field trial layouts before phenotypes are uploaded. </p></center>

                <h4>
                  Editing Options:
                </h4>
                <dl>
                  <dt>Replace Plot Accession</dt>
                  <dd>A plot accession can be replaced by an accession within or outside of the trial. To do this, <b>click on the plot</b> and <b>provide the name of the new accession</b> (must already exist in the database).</dd>
                  <dt>Replace Trial Accession</dt>
                  <dd>An accession used in a trial can be replaced by a new accession or another accession from the trial. When this replace option is used, it replaces every instances (plots and plants) of that accession in the trial. To do this, <b>click on the Edit Field Map link</b> by the top right of the physical trial layout section; <b>click on Replace Accession button</b>; <b>select accession</b> to replace from the trial and <b>provide a new accession</b> (must already exit in the database); <b>click on Replace Trial Accession button</b> to complete the operation.</dd>
                  <dt>Change dimensions</dt>
                  <dd>Click on the change dimensions button to alter the dimensions of the field map, and the respective row and column attributes of the plots in your trial. Clicking on this button will open a dialogue that prompts you to enter an accession name if the change you are making will result in dimensions that are larger than the amount of plots in your trial. The result is that the map will fill in the extra space with filler plots, and the filler plots will have the accession entered in input in the dialogue.</dd>
                  <dt>Invert rows</dt>
                  <dd>Check invert rows to observe your trial from the top down instead of the bottom up. This change is only present on your visualization, and the trial data will not be changed.</dd>
                  <dt>Plot Layout</dt>
                  <dd>You can select how you want your map to be ordered. The options include serpentine and zigzag.</dd>
                  <dt>Download Harvesting Order</dt>
                  <dd>This button allows you to download an excel file which has an incrementally ordered list of the harvesting order for your trial based on the current layout of the field map. You can play around with the four options given to experiment with the different traversal patterns available. The harvesting order file will omit border plots, but it will include filler plots.</dd>
                  <dt>Download Planting Order</dt>
                  <dd>This button allows you to download an excel file which has an incrementally ordered list of the planting order for your trial. It is very similar to the harvesting order, but since you will need to plant the borders too, it includes the border plots in the traversal of your map.</dd>
                  <dt>Add Borders</dt>
                  <dd>These checkboxes allow you to add borders around your field map on any sides you would like. These plots are purely visual and have no real data associated with them. They will not be included in the database, but you can see them in your harvesting order if they are present.</dd>
                  <dt>Submit Field Layout</dt>
                  <dd>This button allows you to update the databases with the changes you have made to your trial. You can continuously change your trial data, just remember to submit the changes when you are satisfied so that it is saved.</dd>
                  <dt>HeatMap</dt>
                  <dd>If your trial has trait data uploaded, you can view a heatmap of that data by selecting a trait from the dropdown menu. You will see a color weighting on the plots that corresponds with the value of each plot for a given trait.</dd>
                  <dt>Transpose Fieldmap</dt>
                  <dd>This button transposes the x and y coordinates of each plot in your map. Borders will adjust accordingly.</dd>
                  <!--
                  <dt>Substitute Plot Accessions<dt>
                  <dd>This feature allows you to switch plot accessions between any two plots. To switch the accessions of two plots, <b>click on the Edit Field Map link</b>; <b>click on Substitute Accession button</b>; <b>select the plots to switch there accessions</b>; <b>click on Substitute Plot Accession</b> to switch the accession in those plots.</dd>
                  -->
                </dl>

                <h4>
                  Features:
                </h4>
                <dt>Mouse Over<dt>
                <dd>Displays plot field information.</dd>
                <dt>Double Click</dt>
                <dd>Double clicking on a plot, opens the stock page for that plot.</dd>
                <dt>Download Map<dt>
                <dd>Field Map can be downloaded as image using the download button below the map.</dd>
                <dt>Delete Map</dt>
                <dd>Field Map can be deleted if the user have the right privilege.</dd>

                <h4>
                  Note:
                </h4>
                <dd>- You have to be a <b>curator</b> or a <b>submitter and associated to the breeding program</b> of the trial to use the features of this tool.</dd>
                <dd>- <b>Input boxes</b> used within the field map tool will automatically (<b>autocomplete</b>) give accession name options from the database when you start typing the accession name.</dd>
                <dd>- <b>Changes can only be made to the physical layout when phenotypes are not yet upload for the trial.</b></dd>

                </div>
            </div>
            <div class="modal-footer">
                <button id="close_usage_field_map_dialog" type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            </div>
        </div>
    </div>
</div>



<script>

jQuery(document).ready(function () {

    var trial_stock_type = "' );
#line 248 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print(  $trial_stock_type  );
#line 248 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print( '";

    if (trial_stock_type == \'family_name\') {
        jQuery(\'input[id*="replace_database_stock"]\').autocomplete({
            appendTo: "#replace_trial_stocks_dialog",
            source: \'/ajax/stock/family_name_autocomplete\'
        });
    } else if (trial_stock_type == \'cross\') {
        jQuery(\'input[id*="replace_database_stock"]\').autocomplete({
            appendTo: "#replace_trial_stocks_dialog",
            source: \'/ajax/stock/cross_autocomplete\'
        });
    } else {
        jQuery(\'input[id*="replace_database_stock"]\').autocomplete({
            appendTo: "#replace_trial_stocks_dialog",
            source: \'/ajax/stock/accession_autocomplete\'
        });
    }

	jQuery.ajax ( {
        url : \'/ajax/breeders/trial/\'+' );
#line 268 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print(  $trial_id  );
#line 268 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print( '+\'/accessions\',

	    success: function(response){
	         //console.log(response);

            var trial_stocks_html = "<select class=\'form-control\' id=\'trial_stock_table\'>";
            for (i=0; i<response.accessions[0].length; i++) {
                trial_stocks_html = trial_stocks_html + "<option value=" + response.accessions[0][i].stock_id + ">" + response.accessions[0][i].accession_name + "</option>";
            }
            trial_stocks_html = trial_stocks_html + "</select>";
            jQuery(\'#stocks_in_trial\').empty();
            jQuery(\'#stocks_in_trial\').html(trial_stocks_html);
        },
	    error: function(response){
            alert("Error retrieving stocks.");
	    }
	});

jQuery(\'#calculate_spatial_correction\').click(function() {
    jQuery("#spatial_correction_results_buttons button").hide(); //hide the buttons
    jQuery(\'#trait_spatial_selector\').hide();
   var trial_id = get_trial_id();
   jQuery(\'#calculate_spatial_correction_dialog\').modal({
       backdrop: \'static\',
       keyboard: false,
   }).find(\'.modal-dialog\').css({
       width: \'60%\',
       maxWidth: \'95%\',
       
   });
});
var pheno_filepath;
var headers;
var phenotype_file;
var dataTableToPass;
jQuery("#confirm_calculating_spatial_correction").click(async function() {
  try { //try is a block of code that will run and if it encounters an error it will run the catch block
    jQuery("#calculate_spatial_correction_status_message").html("starting analysis");

    const response = await new Promise((resolve, reject) => {
      jQuery.ajax({
        beforeSend: function(xhr, settings) {
          jQuery("#calculate_spatial_correction_status_message").html("starting analysis");
          jQuery(\'#working_modal\').modal("show");
        },
        url: \'/ajax/spatial_model/generate_results/\' + trial_id,
        success: function(response) {
          resolve(response);
        },
        error: function(xhr, status, error) {
          reject(new Error(error));
        }
      });
    });

    jQuery(\'#working_modal\').modal("hide");
    jQuery("#calculate_spatial_correction_status_message").html("Analysis complete. Click below to correct spatial correlation on necessary traits.");

    if (response.error) {
      alert(response.error);
      alert("Error calculating spatial correction");
    } else {
      //jQuery("#confirm_store_spatial_correction").prop("disabled", false);
      jQuery("#spatial_correction_results_buttons button").show();
      headers = response.headers;
      pheno_filepath = response.pheno_filepath;
      phenotype_file = response.phenotype_file;
      dataTableToPass = response.data;
      
      jQuery("#spatial_correction_needed_results_table").show();
      jQuery("#spatial_correction_needed_results_table_wrapper").show();

      var dataTable = jQuery("#spatial_correction_needed_results_table").DataTable({
        \'destroy\': true,
        \'timeout\': 6000000,
        \'searching\':false,
        \'info\':false,
        \'paging\':false,
        \'data\': response.data,
        \'columns\': [
          { \'title\': \'Trait\' },
          { \'title\': \'Data Quality\' },
          { \'title\': \'Moran P Value\' },
          { \'title\': \'Spatial Correction Needed\' },
        ],
        \'dom\': \'Bfrtip\',
        \'buttons\': [
          \'csv\', \'excel\'
        ]
      });

      dataTable.on(\'init\', function() {
        var columnValues = dataTable.column(1).data().unique().toArray();
        console.log(columnValues);
        var dropdown = jQuery(\'#dropdown\');
        dropdown.empty();
        jQuery.each(columnValues, function(i, value) {
          dropdown.append(jQuery(\'<option>\').text(value).attr(\'value\', value));
        });
        jQuery(\'#trait_spatial_selector\').show();
      });

      jQuery(\'#dropdown\').on(\'change\', function() {
        var selectedValue = jQuery(this).val();
        dataTable.column(1).search(selectedValue).draw();
      });

      
    }
  } catch (error) {
    console.error(\'Error:\', error);
    jQuery(\'#calculate_spatial_correction_status_message\').text("Error calculating spatial correction.");
  }
});

var projectprop_data;
var input_file;
var fitted_data;
var nested_data;
var traits;
var accessionNamesArray;
var model_properties;
var analysis_design;
var model_string;

jQuery("#correct_spatial").click(function() {
  //var dataTableData = jQuery("#spatial_correction_needed_results_table").DataTable().data();
  //alert(JSON.stringify(dataTableData));
  //console.log(dataTableData);
  let include_rc_random = 0;
  if (jQuery(\'#include_rc_random_effects\').is(":checked")) {
    include_rc_random = 1;
  }
  let genotype_as_random = 0;
  if (jQuery(\'#genotype_as_random\').is(":checked")) {
    genotype_as_random = 1;
  }
  let nseg_degree = (100 - jQuery(\'#nseg_ratio_select\').val()) / 100;
  jQuery(\'#working_modal\').modal(\'show\');
  jQuery.ajax({
    url: \'/ajax/spatial_model/correct_spatial/\' + trial_id,
    data: {
      dataTableData: dataTableToPass,
      pheno_filepath: pheno_filepath,
      headers: headers,
      phenotype_file: phenotype_file,
      include_rc_random : include_rc_random,
      genotype_as_random : genotype_as_random,
      nseg_degree : nseg_degree
    },
    success: function(response) {
      jQuery(\'#working_modal\').modal(\'hide\');
      if (response.error) {
        alert(response.error);
        alert("Error calculating spatial correction");
      } else {
        jQuery(\'#confirm_store_spatial_correction\').prop(\'disabled\', false);
        jQuery("#spatial_correction_blue_results_table").DataTable({
          \'destroy\': true,
          \'timeout\': 6000000,
          \'data\': response.result,
          \'scrollX\': true,
          \'columns\': [
            { \'title\': \'Plot\' },
            { \'title\': \'Accession\' },
            { \'title\': \'Trait\' },
            { \'title\': \'Original\' },
            { \'title\': \'Corrected\' },
            { \'title\': \'Adjustment\'}
          ],
          \'dom\': \'Bfrtip\',
          \'buttons\': [
          \'csv\', \'excel\'
        ]
        });
        jQuery("#spatial_correction_new_moran_table").DataTable({
          \'destroy\': true,
          \'timeout\': 6000000,
          \'searching\': false,
          \'lengthChange\': false,
          \'info\':false,
          \'paging\':false,
          \'data\': response.moran_p_values,
          \'scrollX\': true,
          \'columns\': [
            { \'title\': \'Trait\' },
            { \'title\': \'Moran P-value after spatial corrections\' },
          ]
        });
      }

      input_file = response.phenotype_file;
      fitted_data = response.result;
      nested_data = response.nested_data;
      traits = response.traits;
      accessionNamesArray = response.accession_names;
      console.log(traits);
      console.log(JSON.stringify({ "properties": { "traits": traits } }));
      model_properties = JSON.stringify({ "properties": { "traits": traits } });
      analysis_design = response.analysis_design;
      projectprop_data = response.projectprop_data;
      model_string = response.model_string;
    }, 
    error: function(error) {
      jQuery(\'#working_modal\').modal(\'hide\');
      alert("Error calculating spatial corrections: "+error);
    }
  });
});

jQuery(document).on(\'click\', \'#confirm_store_spatial_correction\', async function(e) {

    //save data as projectprop
    jQuery.ajax({
        \'url\': \'/ajax/spatial_model/store_spatial_adjustments/\' + trial_id,
        \'data\' : {
        \'spatial_adjustments\': projectprop_data
        },
        \'success\' : function(response) {
        if (response.error) {
            alert(response.error);
        } else {
            alert("Spatial corrections have been stored in association with this trial. You may also wish to save them as a standalone analysis for use in downstream analyses.\\n");
        }
        },
        \'error\' : function(error) {
        alert("An error occurred: " + error);
        }
    });

    jQuery(\'#generic_save_analysis_dialog\').modal("show");
    jQuery(\'#generic_save_analysis_model_properties\').val(model_properties);
    jQuery(\'#generic_save_analysis_protocol\').val(model_string);
    //jQuery(\'#generic_save_analysis_dataset_id\').val("dataset_id");
    jQuery(\'#generic_save_analysis_accession_names\').val(JSON.stringify(accessionNamesArray));
    jQuery(\'#generic_save_analysis_trial_id\').val(trial_id);
    jQuery(\'#generic_save_analysis_trait_names\').val(JSON.stringify(traits));
    jQuery(\'#generic_save_analysis_statistical_ontology_term\').val(\'Adjusted Means from Spatial Correction using SpATS R|SGNSTAT:0000054\');
    jQuery(\'#generic_save_analysis_design\').val(analysis_design);
    jQuery(\'#generic_save_analysis_model_language\').val(\'R\');
    jQuery(\'#generic_save_analysis_model_application_name\').val(\'Breedbase Spatial Correction Tool\');
    jQuery(\'#generic_save_analysis_model_application_version\').val(\'0.01\');
    jQuery(\'#generic_save_analysis_model_type\').val(\'spatial_model_SpATS\');
    jQuery(\'#generic_save_analysis_result_values\').val(nested_data);
    jQuery(\'#generic_save_analysis_result_values_type\').val(\'analysis_result_values_match_precomputed_design\');
    jQuery(\'#generic_save_analysis_result_summary_values\').val(\'{ "method" : "Breedbase spatial correction tool" }\');
    jQuery(\'#generic_save_analysis_model_training_data_file\').val(input_file);
    jQuery(\'#generic_save_analysis_model_archived_training_data_file_type\').val(\'mixed_model_input_data\');
});


  jQuery(\'#edit_field_map_link\').click(function () {

  	jQuery.ajax( {
  			 url: \'/ajax/breeders/trial/\'+trial_id+\'/coords\',

  				 success: function(response) {

  				 var trial_plot_name_html = "<select class=\'form-control\' id=\'trial_plot_1_name_table\'>";
  				 var trial_plot_number_html = "<select class=\'form-control\' id=\'trial_plot_2_name_table\'>";
  				 //var trial_plot_accession_html = "<select class=\'form-control\' id=\'trial_plot_accession_table\'>";

  				  for (n=0; n<response.plot_name.length; n++){
  			 			for (i=0; i<response.plot_name[n].length; i++) {
  			 		    trial_plot_name_html = trial_plot_name_html + "<option value=" + response.plot_id[n][i] + "," + response.acc[n][i] + ">" + "Plot:" + response.plot_name[n][i] + "," + " Number:" + response.plot_number[n][i] + "," +" Accession:"+ response.acc[n][i] +"</option>";
  							trial_plot_number_html = trial_plot_number_html + "<option value=" + response.plot_id[n][i] + "," + response.acc[n][i] + ">" + "Plot:" + response.plot_name[n][i] + "," + " Number:" + response.plot_number[n][i] + "," +" Accession:"+ response.acc[n][i] + "</option>";
  				 		}
  					}
  					trial_plot_name_html = trial_plot_name_html + "</select>";
  					jQuery(\'#plot_name_in_trial\').empty();
  					jQuery(\'#plot_name_in_trial\').html(trial_plot_name_html);

  					trial_plot_number_html = trial_plot_number_html + "</select>";
  					jQuery(\'#sub_plot_accession_in_trial\').empty();
  					jQuery(\'#sub_plot_accession_in_trial\').html(trial_plot_number_html);

  			 }
  	});

    open_edit_field_map_dialog();
  });

  function open_edit_field_map_dialog() {
    jQuery(\'#edit_field_map_dialog\').modal(\'show\');
  }

    jQuery(\'#replace_stock_submit\').click(function() {
        replace_stock_in_trial(trial_stock_type)
    });

    function replace_stock_in_trial() {
        jQuery(\'#replace_trial_stocks_dialog\').modal("hide");
        var old_stock_id = jQuery(\'#trial_stock_table\').val();
        var new_stock = jQuery(\'#replace_database_stock\').val();

        new jQuery.ajax({
            type: \'POST\',
            url: \'/ajax/breeders/trial/' );
#line 565 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print(  $trial_id  );
#line 565 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print( '/replace_stock\',
            dataType: "json",
            data: {
                \'old_stock_id\': old_stock_id,
                \'new_stock\': new_stock,
                \'trial_stock_type\': trial_stock_type,
            },
            beforeSend: function(){
                jQuery(\'#working_modal\').modal("show");
            },
            success: function (response) {
                jQuery(\'#working_modal\').modal("hide");

                if (response.error) {
                    alert("Error Replacing Stock: "+response.error);
                } else {
                    jQuery(\'#replace_stock_dialog_success_message\').modal("show");
                }
            },
            error: function() {
                jQuery(\'#working_modal\').modal("hide");
                alert(\'An error occurred replacing stock\');
            }
        });
    }

  jQuery(\'#close_replace_field_map_dialog\').click( function() {
    location.reload();
  });

//   jQuery(\'#close_subs_field_map_dialog\').click( function() {
//     location.reload();
//   });

//   jQuery(\'#substitute_plot_stock_submit\').click( function() {
//     substitute_plot_stock();
//   });

//   function substitute_plot_stock() {

//     var plot_1_info = jQuery(\'#trial_plot_1_name_table\').val();
//     var plot_2_info = jQuery(\'#trial_plot_2_name_table\').val();

//     new jQuery.ajax({
//       type: \'POST\',
//       url: \'/ajax/breeders/trial/' );
#line 610 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print(  $trial_id  );
#line 610 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print( '/substitute_stock\',
//       dataType: "json",
//       data: {
//               \'plot_1_info\': plot_1_info,
//               \'plot_2_info\': plot_2_info,
//       },
//       beforeSend: function(){
//         jQuery(\'#working_modal\').modal("show");
//       },
//       success: function (response) {
//         jQuery(\'#working_modal\').modal("hide");

//         if (response.error){
//           alert("Error Substituting Stock: "+response.error);
//         } else {
//           jQuery(\'#sub_success_message\').modal("show");
//         }
//       },
//       error: function(){
//         jQuery(\'#working_modal\').modal("hide");
//         alert(\'An error occurred substituting plot stock. Please try again or contact us.\');
//       }
//     });
//   }

    var trial_name = "' );
#line 635 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print(  $trial_name  );
#line 635 "/home/production/cxgn/sgn/mason/breeders_toolbox/trial/edit_fieldMap.mas"
$m->print( '";
    var edit_dialog_title = \'\';
    var replace_button_label = \'\';
    var substitute_button_label = \'\';
    var replace_dialog_title = \'\';
    var replace_stock_text1 = \'\';
    var replace_stock_text2 = \'\';
    var replace_button_submit = \'\';
    var substitute_dialog_title = \'\';
    var substitute_button_submit = \'\';
    var replace_message_title = \'\';
    var replace_success_message = \'\';
    var subs_message_title = \'\';
    var subs_success_message = \'\';

    if (trial_stock_type == \'family_name\') {
        edit_dialog_title = \'Replace Trial Family Names Or Substitute Family Names Within A Trial Plots\';
        replace_button_label = \'Replace Family Name\';
        substitute_button_label = \'Substitute Family Name\';
        replace_dialog_title = \'Replace Trial Family Name in \'.concat(trial_name);
        replace_stock_text1 = \'Select Family Name: \';
        replace_stock_text2 = \'Enter New Family Name: \';
        replace_button_submit = \'Replace Trial Family Name\';
        substitute_dialog_title = \'Substitute Plot Family Name in \'.concat(trial_name);
        substitute_button_submit = \'Substitute Plot Family Name\';
        replace_message_title = \'Replace Trial Family Name\';
        replace_success_message = \'Family Name was replaced successfully.\';
        subs_message_title = \'Substitute Plot Family Name\';
        subs_success_message = \'Family Name was substituted successfully.\';
    } else if (trial_stock_type == \'cross\') {
        edit_dialog_title = \'Replace Trial Cross Unique IDs Or Substitute Cross Unique IDs Within A Trial Plots\';
        replace_button_label = \'Replace Cross Unique ID\';
        substitute_button_label = \'Substitute Cross Unique ID\';
        replace_dialog_title = \'Replace Trial Cross Unique ID in \'.concat(trial_name);
        replace_stock_text1 = \'Select Cross Unique ID: \';
        replace_stock_text2 = \'Enter New Cross Unique ID: \';
        replace_button_submit = \'Replace Trial Cross Unique ID\';
        substitute_dialog_title = \'Substitute Plot Cross Unique ID in \'.concat(trial_name);
        substitute_button_submit = \'Substitute Plot Cross Unique ID\';
        replace_message_title = \'Replace Cross Unique ID\';
        replace_success_message = \'Cross Unique ID was replaced successfully.\';
        subs_message_title = \'Substitute Cross Unique ID\';
        subs_success_message = \'Crosss Unique ID was substituted successfully.\';
    } else {
        edit_dialog_title = \'Replace Trial Accessions Within A Trial Plots\';
        replace_button_label = \'Replace Accession\';
        // substitute_button_label = \'Substitute Accession\';
        replace_dialog_title = \'Replace Trial Accession in \'.concat(trial_name);
        replace_stock_text1 = \'Select Accession: \';
        replace_stock_text2 = \'Enter New Accession: \';
        replace_button_submit = \'Replace Trial Accession\';
        // substitute_dialog_title = \'Substitute Plot Accession in \'.concat(trial_name);
        // substitute_button_submit = \'Substitute Plot Accession\';
        replace_message_title = \'Replace Trial Accession\';
        replace_success_message = \'Accession was replaced successfully.\';
        // subs_message_title = \'Substitute Plot Accession\';
        // subs_success_message = \'Accession was substituted successfully.\';
    }

    jQuery(\'#edit_field_map_title\').text(edit_dialog_title);
    jQuery(\'#replace_trial_stock_submit\').text(replace_button_label);
    // jQuery(\'#substitute_stock_submit\').text(substitute_button_label);
    jQuery(\'#replace_stocks_dialog\').text(replace_dialog_title);
    jQuery(\'#replace_stock_label1\').text(replace_stock_text1);
    jQuery(\'#replace_stock_label2\').text(replace_stock_text2);
    jQuery(\'#replace_stock_submit\').text(replace_button_submit);
    // jQuery(\'#substitute_plot_dialog\').text(substitute_dialog_title);
    // jQuery(\'#substitute_plot_stock_submit\').text(substitute_button_submit);
    jQuery(\'#replace_stock_message_title\').text(replace_message_title);
    jQuery(\'#replace_stock_success_message\').text(replace_success_message);
    // jQuery(\'#subs_stock_message_title\').text(subs_message_title);
    // jQuery(\'#subs_stock_success_message\').text(subs_success_message);

});


</script>
' );
;return;
},
'declared_args' => {
  '$trial_id' => { default => undef },
  '$trial_name' => { default => undef },
  '$trial_stock_type' => { default => ' undef' }
},
'load_time' => 1763102299,

)
;