· 5 years ago · Mar 04, 2020, 08:28 AM
1var fld_crp_color_obj = {};
2var fld_crp_color = [];
3var fld_addFieldPoint;
4var fld_addFieldsinglePointMarker;
5var fld_fieldPtLabels = [];
6var fld_fieldPts = [];
7
8/*
9 gen_mode_sub = 2; - vra
10 gen_mode_sub = 3; - field point
11*/
12
13function deselectEditedField() {
14
15 for (var i = 0; i < polygonsArray.length; i++) {
16 resetPolyObj(polygonsArray[i]);
17 }
18}
19
20
21//farm list filter
22$(document).on("keyup", "#ui_fieldSearch", function () {
23
24 //first hide any field detail panels.
25 $(".fieldInfo").each(function () {
26 if ($(this).is(":visible")) {
27 $(this).empty().hide();
28 }
29 })
30
31 $(".field_item_selected").addClass("field_item").removeClass("field_item_selected");
32
33 $(".field_item").each(function () {
34
35 if ($(this).text().toUpperCase().indexOf($("#ui_fieldSearch").val().toUpperCase()) > -1) {
36 $(this).removeAttr("style");
37 } else {
38 $(this).attr("style", "display:none");
39 }
40 });
41
42});
43
44
45$(document).on("click", "#submitNewCropToField", function () {
46 var fld_newFieldError = "";
47 $("#fldCropModalMessages").empty();
48 var selectedCrop = $("#wo_crop_newFieldCropLayerFarmersCropList").find(":selected").val();
49 var isCurrentSeason = false;
50 var isNewSeason = false;
51 var seasonFromDate = "";
52 var seasonFromTo = "";
53 var prevSeasonId = 0;
54 var newSeasonName = "";
55 var selectedCropName = $("#wo_crop_newFieldCropLayerFarmersCropList").find(":selected").text();
56
57 //is this a new season?
58 if ($("#wo_crop_fld_NewCropSeason").is(":checked")) {
59 isNewSeason = true;
60
61 if (fld_newFieldError == "") {
62 //date validation.
63 var temp_arr_0 = $("#wo_crop_addNewFieldSeasonFromDate").val().split('-');
64 var temp_arr_1 = $("#wo_crop_addNewFieldSeasonToDate").val().split('-');
65
66 var fld_crop_season_frm_dte = new Date(temp_arr_0[1] + '/' + temp_arr_0[0] + '/' + temp_arr_0[2]).toISOString();
67 var fld_crop_season_to_dte = new Date(temp_arr_1[1] + '/' + temp_arr_1[0] + '/' + temp_arr_1[2]).toISOString();
68
69 if (fld_crop_season_to_dte <= fld_crop_season_frm_dte) {
70 fld_newFieldError = "'From date' must be after the 'To date'.";
71 }
72 }
73
74 if (($("#wo_crop_newSeasonFieldCropLayerFarmersCropList").find(":selected").val() == "") && (fld_newFieldError == "")) {
75 fld_newFieldError = "Select a crop the list.";
76 }
77 }
78 else {
79 if (($("#wo_crop_newFieldCropLayerFarmersCropList").find(":selected").val() == "") && (fld_newFieldError == "")) {
80 fld_newFieldError = "Select a crop the list.";
81 }
82 }
83
84 if (fld_newFieldError != "") {
85 $("#fldCropModalMessages").show().empty().html("<p class=\"error\">" + fld_newFieldError + "</p>");
86 }
87 else {
88
89 //form values
90 if ($("#wo_crop_fld_NewCropSeason").is(":checked")) {
91 if ($(".wo_crop_add_new_field_crop_right_chk_current_season").is(":checked")) {
92 isCurrentSeason = true;
93 }
94 seasonFromDate = $("#wo_crop_addNewFieldSeasonFromDate").val();
95 seasonFromTo = $("#wo_crop_addNewFieldSeasonToDate").val();
96
97 //generate season name from years
98 newSeasonName = seasonFromDate.split('-')[2] + "-" + seasonFromTo.split('-')[2];
99 selectedCrop = $("#wo_crop_newSeasonFieldCropLayerFarmersCropList").find(":selected").val();
100 selectedCropName = $("#wo_crop_newSeasonFieldCropLayerFarmersCropList").find(":selected").text();
101 }
102
103 else {
104 prevSeasonId = $("#wo_crop_newFieldCropLayerSeasonList").find(":selected").val();
105 }
106
107 $("#FieldWithoutCropModal").modal('hide');
108 loadStatus("Adding Crop To Field");
109
110
111 $("#fldCropModalMessages").empty().hide();
112 $.ajax({
113 type: "POST",
114 url: urlPrepend + "/fielddata/addcrop-" + getFieldId(),
115 data: { tradingId: getTradingId(), farmId: getFarmId(), fieldId: getFieldId(), seasonName: newSeasonName, strFarmersCrop: selectedCrop, prevSeason: prevSeasonId, newSeason: isNewSeason, currentSeason: isCurrentSeason, frmDate: seasonFromDate, toDate: seasonFromTo }
116 }).done(function (data) {
117
118 if (data.length > 0) {
119
120
121 $(".wo_crop_add_new_field_crop").show();
122
123
124 var cropDDLArr = data.split('|');
125 //insert new season into ddl
126 for (var i = 0; i < cropDDLArr.length; i++) {
127 if (cropDDLArr[i] != "") {
128 $('#wo_crop_newFieldCropLayerSeasonList')
129 .append($("<option></option>")
130 .attr("value", cropDDLArr[i].split('_')[1])
131 .text(cropDDLArr[i].split('_')[0]));
132 }
133 }
134
135 removeStatus();
136 }
137 else {
138 //display err message;
139 displayErrMsg(txtFd24);
140 }
141 })
142 .fail(function () {
143 //display err message;
144 displayErrMsg(txtFd24);
145 });
146
147
148 }
149});
150
151/// <summary>Chemical Records</summary>
152//#####Global
153
154let fld_allFiles2D = new Array(); //an array on arrays of objects ([fileObj, fileInfoObj])
155let fld_exceededMaxSize = false;
156function UploadClick(){document.getElementById("invisibleFileInputter").click();};
157
158function MakeNameSafe(nameWithExt){
159 var ext = nameWithExt.substr(nameWithExt.lastIndexOf('.') + 1);
160 var nameNoExt = nameWithExt.substr(0, nameWithExt.lastIndexOf('.'));
161 nameNoExt = nameNoExt.replace(/[^A-Z0-9]+/ig, "_");
162 var nameWithExtSafe = nameNoExt.concat(".",ext);
163 return(nameWithExtSafe);
164}
165
166function makeLengthFitDatabase(nameWithExt)
167{
168 //server route + date modified is about 62 characters, (plus extension) we all 250 so to be safe limiting the name to 150 characters
169 let ext = nameWithExt.substr(nameWithExt.lastIndexOf('.') + 1);
170 let nameNoExt = nameWithExt.substr(0, nameWithExt.lastIndexOf('.'));
171 nameNoExt = nameNoExt.substring(0,140);
172 let nameWithExtSafe = nameNoExt.concat(".",ext);
173 return(nameWithExtSafe);
174}
175
176function fileGroupExceedsLimit(){
177
178 let currentGroupSize = 0;
179 let maxGroupSize = 141557760;
180
181 for (let i = 0; i < fld_allFiles2D.length; i++)
182 {
183 currentGroupSize += fld_allFiles2D[i][0].size;
184 }
185
186 if(currentGroupSize>maxGroupSize){
187 fld_exceededMaxSize = true;
188 displayErrMsg("Your files currently exceed the maximum allowed MB. Please remove some files.");
189 }else{ fld_exceededMaxSize = false;}
190}
191
192/// <summary>Chemical Records</summary>
193$(document).on("click", "#chemRecordsBtn", function () {
194 $("#chemicalRecordModal").modal("show");
195
196 //############ Code for uploading
197
198 let smallerMaxSizeShownToUserMB = "40MB"; //Smaller amount to show to user
199 let upload = document.getElementById("invisibleFileInputter");
200
201
202 upload.onchange = function(e) {
203
204 let fileName ="";
205
206 for(let i = 0 ; i < this.files.length; i++){
207 fileName = this.files[i].name;
208
209 //Included//gif, jpg, jpeg, (missing anyway??), png, bmp, doc, docx, rtf, xls, xlsx, pdf, txt
210 //Not included //"pjp","pjpeg" "jfif","tif","tiff","ppt","pptx", "pub", "text",
211 let acceptibleFileTypeAr = ["gif","jpg","jpeg","png","bmp","doc","docx","xls", "xlsx", "rtf", "txt","pdf"];
212 let maxSize = 45000000;/*12MP smart phone photo so I have rounded up to future proof*//*36000000*/
213
214 /*Check files acceptible*/
215 if(!fileTypeAllowed(this.files[i],acceptibleFileTypeAr))
216 {
217 displayErrMsg("File " + fileName + " not of a permissable type and will not be uploaded when the form is submitted. Files must be one of the following types: " + acceptibleFileTypeAr.join(" "))
218 continue;
219 }
220
221 if(!fileSizeAllowed(this.files[i].size,maxSize))
222 {
223 displayErrMsg("File " + fileName + " is too large and will not be uploaded when the form is submitted. Please attach files smaller then "+ smallerMaxSizeShownToUserMB);
224 continue;
225 }
226
227 if(isAlreadyInArray(this.files[i]))
228 {
229 displayErrMsg("File " + fileName + " has already added, a duplicate will not be added");
230 continue;
231 }
232
233 fld_allFiles2D.push([this.files[i],makeFileInfoArObj(this.files[i])])
234
235 //Dynamically make element
236 $("#fileDeleteArea").append( '<div class="input-group input-file "><input type="text" class="form-control showText" value="'+ fld_allFiles2D[i][1].fileNameModifiedPrepend + '" disabled /><span class="input-group-btn"><button class="btn btn-danger removeButton" type="button">X</button></span></div></div>' );
237
238
239 }
240 //Add del functionality to elements
241 $(".removeButton").one("click", removeFile);
242 //Reset the upload html element so that if files deleted can read them
243
244 upload.value= null;
245 //Send an error message if limit exceeded
246 fileGroupExceedsLimit();
247
248 }
249
250
251 function removeFile()
252 {
253
254 var buttonsElement =$(event.target).closest('div');
255 fileToRemoveName = buttonsElement.find(":input").val();
256
257 //now we have removed datemodified prepend and because removing special characters more risk of identical names
258 indexInFileInfoAr = -1;
259 for (let i = 0; i < fld_allFiles2D.length; i++)
260 {
261 if (fld_allFiles2D[i][1].fileNameModifiedPrepend === fileToRemoveName) { indexInFileInfoAr = i; break;}
262 }
263
264 if (indexInFileInfoAr !== -1)
265 {
266 fld_allFiles2D.splice(indexInFileInfoAr, 1);
267 }
268
269 fileGroupExceedsLimit();
270 buttonsElement.remove();
271
272
273 }
274
275
276 function makeFileInfoArObj(file)
277 {
278 //Create object with file data for table
279 let fileInfoObj =
280 {
281 fileNameOriginal :makeLengthFitDatabase(file.name),
282 fileNameModifiedPrepend:fld_GetDateTime()+"_"+makeLengthFitDatabase(MakeNameSafe(file.name)),
283 fileLastModified : file.lastModified,
284 fileLastModifiedDate : file.lastModifiedDate,
285 fileSize : file.size,
286 fileType : file.type,
287 fieldId : parseInt(getFieldId()),
288 customerId:parseInt($('#sessionCustomerId').val()),
289 farmId:parseInt(getFarmId())
290 };
291
292 return fileInfoObj;
293
294 }
295
296 function fileTypeAllowed(file,acceptibleFileTypeAr)
297 {
298 let fileExt = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
299 return acceptibleFileTypeAr.includes(fileExt);
300 }
301
302
303 function fileSizeAllowed(fileSize,maxSize) { return (fileSize < maxSize);}
304
305 function isAlreadyInArray(file)
306 {
307
308 for (let i = 0; i < fld_allFiles2D.length; i++)
309 {
310 if ((makeLengthFitDatabase(file.name) === fld_allFiles2D[i][1].fileNameOriginal) && (file.lastModified === fld_allFiles2D[i][1].fileLastModified))
311 {
312 return true;
313 }
314 }
315 return false;
316 }
317
318});
319
320function fld_GetDateTime()
321{
322 var nowDateTime = new Date();
323 var dateString =
324 nowDateTime.getFullYear().toString() +
325 ( ( (nowDateTime.getMonth() + 1) < 10 ? '0' : '') + (nowDateTime.getMonth() + 1) ).toString() +
326 ( ( (nowDateTime.getDate() < 10 ? '0' : '') + nowDateTime.getDate()) ).toString() +
327 ( ( (nowDateTime.getHours() < 10 ? '0' : '') + nowDateTime.getHours()) ).toString() +
328 ( ( (nowDateTime.getMinutes() < 10 ? '0' : '') + nowDateTime.getMinutes()) ).toString() +
329 ( ( (nowDateTime.getSeconds() < 10 ? '0' : '') + nowDateTime.getSeconds()) ).toString();
330 return dateString;
331}
332
333function fld_GetDateTimeForDB()
334{
335 var nowDateTime = new Date();
336 var dateString =
337 nowDateTime.getFullYear().toString() +"-"+
338 ( ( (nowDateTime.getMonth() + 1) < 10 ? '0' : '') + (nowDateTime.getMonth() + 1) ).toString() +"-"+
339 ( ( (nowDateTime.getDate() < 10 ? '0' : '') + nowDateTime.getDate()) ).toString() +" "+
340 ( ( (nowDateTime.getHours() < 10 ? '0' : '') + nowDateTime.getHours()) ).toString() +":"+
341 ( ( (nowDateTime.getMinutes() < 10 ? '0' : '') + nowDateTime.getMinutes()) ).toString() +":"+
342 ( ( (nowDateTime.getSeconds() < 10 ? '0' : '') + nowDateTime.getSeconds()) ).toString();
343 return dateString;
344}
345
346//There are two click for add application
347$(document).on("click", "#addApplicationBtn", function () {
348 RetrieveAllProducts();
349 disableInputProductFields();
350});
351
352$(document).on("click", "#addApplicationBtn", function () {
353
354 let fieldId = parseInt(getFieldId());
355 let seasonId = $('#customerSeason option:selected').val();
356
357 $.ajax({
358 url: urlPrepend + "/FieldData/IsFieldSeasonSignedOffGetStartEnd",
359 type: "POST",
360 contentType: "application/json",
361 data: JSON.stringify({fieldId:fieldId,seasonId:seasonId})
362 })
363 .done(function (dataCanAddApplication) {
364
365 if (dataCanAddApplication.didFail === true) {
366 displayErrMsg("Failed to check if field signed off for the season");
367 return false;
368 }else{
369 if(dataCanAddApplication.signedOff==false)
370 {
371 //datepicker is inclusive
372 let seasonStartDate = new Date(parseInt(dataCanAddApplication.seasonStart.substr(6)));
373 let today = new Date();
374
375 if(today<seasonStartDate){ displayErrMsg("Cannot add applications to seasons that have not yet started");return;
376 }else{
377
378 let seasonEndDate = new Date(parseInt(dataCanAddApplication.seasonEnd.substr(6)));
379 let maxDate = ((today<seasonEndDate) ? today : seasonEndDate);
380 $("#chemicalRecordModal").modal("hide");
381 $("#addChemicalRecordModal").modal("show");
382
383 $('#recordDatePicker').datepicker({defaultDate: seasonStartDate, dateFormat: 'dd/mm/yy', minDate: seasonStartDate, maxDate:maxDate,
384 onClose: function (dateText) {
385 if ($('#recordDatePicker').val().length === 0) {
386 $("#applyDateRow").addClass("has-error");
387 $("#errorDateNotSelected").show();
388 return;
389 } else {
390 $("#applyDateRow").removeClass("has-error");
391 $("#errorDateNotSelected").hide();
392 $('#productDisableField').removeAttr('disabled');
393 }
394 }
395 });
396 $('#recordDatePicker').datepicker('option',{defaultDate: seasonStartDate, minDate: seasonStartDate, maxDate:maxDate});
397 }
398 }else
399 {
400 displayErrMsg("This field's applications have been signed off for this season. No further applications can be added");
401 }
402 }})
403 .fail(function (errDataTable) {
404 displayErrMsg("Failed to check if field signed off for the season");
405 return false;
406 })
407});
408
409function disableInputProductFields() {
410 $("#addChemRecordBtn, #cropGrowthStage, #reasonForApp, #hectarsSprayed, #ratesPerHa, #cropGrowthStage").addClass("disabled");
411}
412
413
414function enableInputProductFields() {
415 $('#firstAppearFieldset').removeAttr("disabled");
416
417 $("#addChemRecordBtn, #cropGrowthStage, #reasonForApp, #hectarsSprayed, #ratesPerHa, #cropGrowthStage").removeClass("disabled");
418}
419
420
421
422
423
424$('#hectarsSprayed').on('focusout', function () {
425 var desiredHectresToBeSprayed = parseFloat($('#hectarsSprayed').val());
426 var fieldHectars = parseFloat($('.current_field_area').text());
427
428 if (desiredHectresToBeSprayed > fieldHectars) {
429 $("#addChemRecordBtn").addClass("disabled");
430
431 $("#hectaresDiv").addClass("has-error");
432 $("#errorHectaresLabel").show();
433 } else {
434 $("#addChemRecordBtn").removeClass("disabled");
435
436 $("#hectaresDiv").removeClass("has-error");
437 $("#errorHectaresLabel").hide();
438 }
439});
440
441$("#addChemicalRecordModal").on("hidden.bs.modal", function () {
442 $('#recordDatePicker').val('');
443 $('#hectarsSprayed').val('');
444 $('#ratesPerHa').val('');
445 $('#harvestInterval').val('');
446 $('#earliestHarvestDate').val('');
447 $('#measuredInEle').val('');
448
449 $('#productsList').empty();
450 $('#cropGrowthStage').empty();
451 $('#reasonForApp').empty();
452 $('#eamuRow').hide();
453
454 $('#errorRatesLabel').hide();
455 $('#ratesDiv').removeClass("has-error");
456 $('#productDisableField').prop('disabled', true); // done to prevent selecting a product before selecting a date;
457 $('#firstAppearFieldset').prop('disabled', true);
458
459 $("#applyDateRow").removeClass("has-error");
460 $("#errorDateNotSelected").hide();
461
462 //Reset the uploads
463 fld_allFiles2D = [];
464 $("#fileDeleteArea").empty();
465});
466
467// make the modal scrollable;
468$('#addChemicalRecordModal').css('overflow-y', 'auto');
469
470$('#ratesPerHa').on('focusout', function () {
471 var inputRates = parseFloat($('#ratesPerHa').val());
472 var selectedProductId = $('#productsList').val();
473
474 getProductDetails(selectedProductId)
475 .then(function (product) {
476 product = JSON.parse(product);
477
478 var productMaxAppRate = parseFloat(product.max_app_rate)
479 var productMinRate = parseFloat(product.min_app_rate)
480
481 if (inputRates > productMaxAppRate) {
482 $("#addChemRecordBtn").addClass("disabled");
483
484 $("#ratesDiv").addClass("has-error");
485 $("#errorRatesLabel").text("Rates entered are greater than the maximum allowed rate for this product.");
486 $("#errorRatesLabel").show();
487 } else if (inputRates < productMinRate) {
488 $("#addChemRecordBtn").addClass("disabled");
489
490 $("#ratesDiv").addClass("has-error");
491 $("#errorRatesLabel").text("Rates entered are less than the minimum allowed rate for this product.");
492 $("#errorRatesLabel").show();
493 } else {
494 $("#addChemRecordBtn").removeClass("disabled");
495
496 $("#ratesDiv").removeClass("has-error");
497 $("#errorRatesLabel").hide();
498 }
499 });
500});
501
502$(document).on("click", "#addChemRecordBtn", function () {
503 if ($('#eamuRow:visible').length && $('#eamuCheckBtn').is(':checked') == false) {
504 $("#eamuDiv").addClass("has-error");
505 $("#errorEamuNotClicked").show();
506 return;
507 }
508
509 if ($('#recordDatePicker').val().length === 0) {
510 $("#applyDateRow").addClass("has-error");
511 $("#errorDateNotSelected").show();
512 return;
513 }
514
515 if ($('#hectarsSprayed').val().length === 0) {
516 $("#hectaresDiv").addClass("has-error");
517 $("#errorHectaresLabel").show();
518 return;
519 }
520
521 if ($('#ratesPerHa').val().length === 0) {
522 $("#ratesDiv").addClass("has-error");
523 $("#errorRatesLabel").text("Please fill the rates input field before proceeding!");
524 $("#errorRatesLabel").show();
525 return;
526 }
527
528 fileGroupExceedsLimit();
529 if(fld_exceededMaxSize){return false;}
530
531 $("#cover-spin").show();
532
533 // input fieldsfld_allFiles2D
534 var dateApplied = $('#recordDatePicker').val();
535 var selectedProduct = $('#productsList').val();
536 var cropGrowthStage = $('#cropGrowthStage').val();
537 var reasonForApp = $('#reasonForApp').val();
538 var hectaresSprayed = $('#hectarsSprayed').val();
539 var ratesPerHa = $('#ratesPerHa').val();
540 var harvestInterval = $('#harvestInterval').val();
541 var earliestHarvestDate = $('#earliestHarvestDate').val();
542
543 var fieldId = parseInt(getFieldId());
544 let customerId= parseInt($('#sessionCustomerId').val());
545 let farmId = parseInt(getFarmId());
546
547 let currUrlSubs = "MiFarm/" + getTradingId() + "/" + getFarmId() + "/";
548
549 let seasonId = $('#customerSeason option:selected').val();
550 var formAndFileDataObjArAsObj = {
551 product: selectedProduct,
552 applied: dateApplied,
553 groStage: cropGrowthStage,
554 reason: reasonForApp,
555 hectaresSprayed: hectaresSprayed,
556 rates: ratesPerHa,
557 earliestHarDate: earliestHarvestDate,
558 fieldId: fieldId,
559 customerId: customerId,
560 farmId:farmId,
561 seasonId: seasonId,
562 tradingId: getTradingId(),
563 link: currUrlSubs
564 }
565
566 //3 Ajax calls that run in order within each others done method
567 //First AJAX call adds the data from the form fields into the table and returns the id of the row of that table and a route to save the files in
568 //Second AJAX call uses the the route and creates or save to a folder at this path
569 //Third AJAX call runs if the files have been saved and creates or saves to a table the table holds the id from the first ajax and using
570 //the file name records each files info and the location it will have saved itself to
571
572 let formDataFiles = new FormData();
573 //###############First AJAX Call sending the form fields data
574 $.ajax({
575 url: urlPrepend + "/FieldData/CreateApplication",
576 type: "POST",
577 contentType: "application/json",
578 data: JSON.stringify({ singleApplicationData:formAndFileDataObjArAsObj }),
579 })
580 .done(function (dataResponseCreateApplication) {
581
582 if (dataResponseCreateApplication.didFail === true) {
583 $("#cover-spin").hide();
584 displayErrMsg("Form input upload failed no form information has been saved")
585
586 }
587 if (fld_allFiles2D.length > 0) {
588 for (let i = 0; i < fld_allFiles2D.length; i++)
589 {
590
591 formDataFiles.append("filesToUpload", fld_allFiles2D[i][0], fld_allFiles2D[i][1].fileNameModifiedPrepend);
592 }
593
594 formDataFiles.append("partSaveFolderPath", dataResponseCreateApplication.partSaveFolderPath);
595
596 //###############Second AJAX Call Saving the files
597
598 $.ajax({
599 type: 'POST',
600 url: urlPrepend + "/FieldData/UploadApplicationRecordAttachedFiles",
601 cache: false,
602 contentType: false,
603 processData: false,
604 data : formDataFiles
605 })
606
607 .done(function (dataResponseSaveFiles) {
608
609 if (dataResponseSaveFiles.didFail === true) {
610 DeleteRecordData(dataResponseCreateApplication.id);
611 $("#cover-spin").hide();
612 displayErrMsg("File upload failed no form information has been saved")
613 return;
614 }
615
616 //Turn 2d array into 1D array
617 let fileInfoAr = new Array();//empty incase ajax failed and adding again
618 for (let i = 0; i < fld_allFiles2D.length; i++) {
619 fileInfoAr.push(fld_allFiles2D[i][1]);
620 }
621
622 //######## Third AJAX call saving the files data
623 $.ajax({
624 url: urlPrepend + "/FieldData/UploadApplicationRecordAttachedFilesData",
625 type: "POST",
626 contentType: "application/json",
627 data: JSON.stringify({id:dataResponseCreateApplication.id,partSaveFolderPath:dataResponseCreateApplication.partSaveFolderPath,fileInfoAr:fileInfoAr}),
628 })
629 .done(function (dataResponseForFilesDataTable) {
630
631 if (dataResponseForFilesDataTable.didFail === true) {
632 DeleteRecordData(dataResponseCreateApplication.id);
633 DeleteFilesUploaded(dataResponseSaveFiles.savedFiles);
634 $("#cover-spin").hide();
635 displayErrMsg("File data upload failed no form information has been saved" )
636 return;
637 }else{
638 $("#cover-spin").hide();
639 $("#addChemicalRecordModal").modal("hide");
640 displaySuccessMsg("You have successfully submitted the application data and files.")}
641
642
643 })
644 .fail(function (errDataTable) {
645 DeleteRecordData(dataResponseCreateApplication.id);
646 DeleteFilesUploaded(dataResponseSaveFiles.savedFiles);
647 $("#cover-spin").hide();
648 displayErrMsg("File data upload failed no form information has been saved" )
649 return;
650 })
651 })
652 .fail(function (errFileDownload) {
653 DeleteRecordData(dataResponseCreateApplication.id);
654 $("#cover-spin").hide();
655 displayErrMsg("File upload failed no form information has been saved")
656 return;
657 })
658 }else
659 {
660 $("#cover-spin").hide();
661 $("#addChemicalRecordModal").modal("hide");
662 displaySuccessMsg("You have successfully submitted the application data and files.")
663 return;
664
665
666
667 }
668 }).fail(function (errFormFieldsSave) {
669 $("#cover-spin").hide();
670 displayErrMsg("Form input upload failed no form information has been saved")
671 return;
672 });
673
674})
675
676function DeleteFilesUploaded(filesRoutes){
677
678 let fieldIdPermission = getFieldId();
679 let customerIdPermission= $('#sessionCustomerId').val();
680 let farmIdPermission= getFarmId();
681 let tradingIdPermission= getTradingId();
682
683 // var permissionModelObj = {fieldId :fieldIdPermission , customerId:customerIdPermission, farmId:farmIdPermission, tradingId:tradingIdPermission};
684
685 $.ajax({
686 url: urlPrepend + "/FieldData/DeleteFilesUploaded",
687 type: "POST",
688 dataType:'json',
689 contentType: "application/json",
690 data: JSON.stringify({locations: filesRoutes, customerId:customerIdPermission, farmId:farmIdPermission, fieldId :fieldIdPermission,farmId:farmIdPermission, tradingId:tradingIdPermission })
691 })
692}
693
694
695function DeleteRecordData(recordID){
696
697 $.ajax({
698 url: urlPrepend + "/FieldData/DeleteRecordData",
699 type: "POST",
700 contentType: "application/json",
701 data: JSON.stringify({id:recordID })
702 })
703}
704
705function RetrieveAllProducts() {
706 $.getJSON(urlPrepend + '/FieldData/GetProducts', function (products) {
707 var productsSelect = $('#productsList');
708 products = JSON.parse(products);
709 var productElements = products.map(function (product) {
710 return $('<option>', { value: product.id, text: product.name })
711 });
712
713 productsSelect.append('<option value="" selected disabled hidden>Select...</option>');
714 productsSelect.append(productElements);
715 });
716};
717
718function updateProductReasons(selectedProductId) {
719 $.getJSON(urlPrepend + '/FieldData/GetProductReasons', { productId: selectedProductId }, function (reasons) {
720 reasons = JSON.parse(reasons);
721 var reasonsSelect = $('#reasonForApp');
722 var reasonElements = reasons.map(function (reason) {
723 return $('<option>', { value: reason.id, text: reason.name })
724 });
725
726 reasonsSelect.html(reasonElements);
727 });
728}
729
730
731
732
733
734function updateGrowthStages(selectedProductId) {
735 $.getJSON(urlPrepend + '/FieldData/GetProductGrowthStages', { productId: selectedProductId }, function (stages) {
736 var stageSelect = $('#cropGrowthStage');
737 var stageElements = stages.map(function (stage) {
738 return $('<option>', { value: stage.id, text: stage.name })
739 });
740
741 stageSelect.html(stageElements);
742 });
743}
744
745function updateHarvestDatesAndEAMU(selectedProductId) {
746 $.getJSON(urlPrepend + '/FieldData/GetProductDetails', { productId: selectedProductId }, function (product) {
747 product = JSON.parse(product);
748
749 $('#harvestInterval').val(product.harvest_interval)
750 var harvestInterval = $('#harvestInterval').val();
751
752 if (isInputNumbersOnly(harvestInterval)) {
753 var dateApplied = $.datepicker.parseDate('dd/mm/yy', $('#recordDatePicker').val());
754 var earliestHarvestDate = new Date(dateApplied);
755
756 harvestInterval = parseInt(harvestInterval);
757 earliestHarvestDate.setDate(earliestHarvestDate.getDate() + harvestInterval);
758 var earliestHarvestProperlyParsed = $.datepicker.formatDate('dd/mm/yy', earliestHarvestDate);
759
760 $('#earliestHarvestDate').val(earliestHarvestProperlyParsed);
761 } else {
762 $('#earliestHarvestDate').removeAttr('placeholder').val('');
763 }
764
765 $('#measuredInEle').val(product.rates_unit)
766
767 let hectSprayedDefaultVal = Number($('.current_field_area').text().replace(/[^0-9\.]+/g, ""));
768
769 $('#hectarsSprayed').val(hectSprayedDefaultVal)
770
771 if (product.is_eamu === true) {
772 $('#eamuRow').show();
773 } else {
774 $('#eamuRow').hide();
775 }
776 });
777}
778
779function getProductDetails(selectedProductId) {
780 return $.getJSON(urlPrepend + '/FieldData/GetProductDetails', { productId: selectedProductId });
781};
782
783function parseAndReturn(product) {
784 product = JSON.parse(product);
785 return product;
786}
787
788function isInputNumbersOnly(harvestInterval) {
789 return /^\d+$/.test(harvestInterval);
790}
791
792function doesStringContainLetters(harvestInterval) {
793 return /[a-zA-Z]/.test(harvestInterval);
794}
795
796
797$('#productsList').on('change', function () {
798 var selectedProductId = $(this).val();
799 updateProductReasons(selectedProductId);
800 updateGrowthStages(selectedProductId);
801 updateHarvestDatesAndEAMU(selectedProductId);
802 enableInputProductFields();
803})
804
805/// <summary>Chemical Records</summary>
806
807/// <summary>View Applications List</summary>
808$('#viewChemApplicationsBtn').on('click', function () {
809 $("#applicationBodyModal").html("");
810 $("#chemicalRecordModal").modal("hide");
811
812 //check user access level decide how to display
813
814 $("#applicationListModal").modal({ backdrop: 'static', keyboard: false });
815 $("#applicationListModal .modal-dialog").attr("style", "width:90%;");
816 $("#applicationListModal .modal-body").attr("style", "min-height:" + gen_screen_height + "px;");
817
818 //$(".modal-productList-content").attr("style", "height:" + gen_screen_height * 0.4 + "px;")
819 ShowChemApplicationRecord();
820
821});
822
823
824
825
826
827//RefreshApplicationFormWithNewPermission is just for testing delete later
828function fld_deleteMeTempRefreshModal(){
829 $("#chemicalRecordModal").modal("hide");
830 $("#applicationListModal").modal({ backdrop: 'static', keyboard: false });
831 $("#applicationListModal .modal-dialog").attr("style", "width:90%;");
832 $("#applicationListModal .modal-body").attr("style", "min-height:" + gen_screen_height + "px;");
833 $("#applicationListModal").modal("show"); return true;
834}
835
836
837
838var fld_temporaryGlobalSignOffPermission = true;
839var fld_signedOffWillBeStoredInDataBasePerSeasonFieldSetOfRecords = false;
840function RefreshApplicationFormWithNewPermission(checkBox) //del later onnce have permissions check function
841{
842 if(fld_deleteMeTempRefreshModal()){
843 fld_temporaryGlobalSignOffPermission = checkBox.checked;
844 ShowChemApplicationRecord();
845 }
846}
847//useful function hides closest parent modal
848function fld_HideThisModal(getMyModal)
849{
850 $(getMyModal).closest('.modal').modal('hide');
851}
852
853//this function should be anonymous within the click once we check permission
854//it isnt now so the checkbox can simulate changing between permissions
855function ShowChemApplicationRecord() {
856 //In future change signOffPermission to be based on their permission level
857
858 let signOffPermission = fld_temporaryGlobalSignOffPermission;//replace this with the function that will handle the permissions
859 let seasonCurr = $('#customerSeason option:selected').val();
860 var request = $.ajax({
861 url: urlPrepend + "/FieldData/GetFieldApplications",
862 type: "POST",
863 data: { fieldId: getFieldId(), seasonId: seasonCurr, signOffPermission:signOffPermission},
864
865 })
866 .done( function (recordFieldSeasonData) {
867
868 $('#applicationBodyModal').html(recordFieldSeasonData);
869 $("#applicationListModal").modal("show");
870 });
871}
872
873$(".recordAppTableCheckbox").prop("checked",true);
874function fld_selectAllCheckBox(){
875 $(".recordAppTableCheckbox").prop("checked",true);}
876function fld_deselectAllCheckBox(){
877 $(".recordAppTableCheckbox").prop("checked",false);}
878
879function fld_CheckSignNameInput(){
880
881
882 let inputSignName = $("#inputSignName");
883 if (!fld_NameValid(inputSignName) ) {
884
885 $("#inputSignName").focus;
886 $("#signOffBtn").prop('disabled', true);
887 $("#signNameFormGroup").addClass("has-error");
888 $("#invalidNameSignedValidationLbl").show();
889
890 } else {
891
892 $("#signOffBtn").prop('disabled', false);
893 $("#signNameFormGroup").removeClass("has-error");
894 $("#invalidNameSignedValidationLbl").hide();
895 }
896}
897
898$(document).on('input', "#inputSignName", fld_CheckSignNameInput ) ;
899
900
901function fld_NameValid(inputNameObj)
902{
903 let regexTestPattern = new RegExp(inputNameObj.attr("pattern"));
904 return regexTestPattern.test(inputNameObj.val());
905}
906$(document).on("click", "#signOffBtn", function () {
907
908 let noCheckboxesChecked = true;
909 let inputSignName = $("#inputSignName");
910
911 $(".recordAppTableCheckbox").each(function()
912 {
913 if($(this).is(':checked')){noCheckboxesChecked = false;}
914 });
915 //They should not be able to access button without permission but if they do
916 //will need to be replaced with the method for checking permission
917
918 if($("#userIsSigner").is(':checked')==false){
919 displayErrMsg("Application sign off submission failed");
920 return true;
921 }
922 else if(noCheckboxesChecked)
923 {
924 displayErrMsg("No applications agreed");
925 return true;
926 }
927 else if (!fld_NameValid(inputSignName) ){
928
929 {
930 $("#inputSignName").focus;
931 $("#signOffBtn").prop('disabled', true);
932 $("#signNameFormGroup").addClass("has-error");
933 $("#invalidNameSignedValidationLbl").show();
934
935 }
936 return true;
937 }
938 else {
939
940 $("#confirmSignOffSeasonChemicals").modal("show");
941 return true;
942 }
943 });
944
945
946$(document).on("click", "#confirmedSubmissionBtn", fld_SignOffFieldSeason);
947function fld_SignOffFieldSeason ()
948
949{
950
951
952 let agreedApplicationsInRecord = new Array();
953 $(".recordAppTableCheckbox").each(function()
954 {
955 if($(this).is(':checked')){
956 agreedApplicationsInRecord.push($(this).attr("name"));}
957 })
958
959 //allApplicationsInRecord = JSON.stringify({'allApplicationsInRecord':allApplicationsInRecord});
960 let submissionDateTime = $("#submitAppRecordsDateTime").val();
961 let submittersName = $("#inputSignName").val();
962
963 $.ajax({
964 url: urlPrepend + "/FieldData/FieldSeasonAppRecordsSignOff",
965 type: "POST",
966 contentType: "application/json",
967 data: JSON.stringify({submissionDateTime :submissionDateTime, submittersName:submittersName, agreedApplicationsInRecord: agreedApplicationsInRecord}),
968 traditional: true
969 }).done(function(dataFromDbSignOff)
970 {
971 if(dataFromDbSignOff.didFail == true)
972 {
973 displayErrMsg("Application sign off submission failed");
974 $("#confirmSignOffSeasonChemicals").modal("hide");
975 }
976 else
977 {
978 displaySuccessMsg("Application records were signed off");
979 $("#applicationListModal").modal('hide');
980 $("#applicationBodyModal").html("");
981 $("#confirmSignOffSeasonChemicals").modal("hide");
982 }
983
984 })
985
986}
987
988
989// button to close the modal
990$(document).on("click", ".product_list_close_modal", function () {
991 $("#applicationListModal").modal('hide');
992 $("#applicationBodyModal").html("");
993});
994
995$(document).on("click", ".app_details_close_modal", function () {
996 $('.modal').modal('hide');
997
998});
999
1000$(document).on("click", "#recordDetailsBackBtn", function () {
1001
1002 $('#applicationDetailsModal').modal('hide');
1003 $('#applicationListModal').modal('show');
1004
1005});
1006
1007
1008
1009$(document).on("click", ".viewAppDate", function () {
1010 $("#uploadedDocumentsArea").empty(); //Moved from hidden.bs.modal to deal with execution order issues
1011 $('#applicationListModal').modal('hide');
1012 $('#applicationDetailsModal').modal('show');
1013 var appClickedId = this.id;
1014
1015 $.ajax({
1016 url: urlPrepend + "/FieldData/GetApplicationDetails",
1017 type: "POST",
1018 data: { applicationId: appClickedId },
1019 })
1020 .done(
1021 function (dataDetails) {
1022
1023 fld_GetApplyDetailsForApplicationFromUserDetails(dataDetails);
1024 fld_ApplyDetailsToApplicationRecordFromApplication(dataDetails);
1025 fld_DynamicallyCreateDownloadElements(dataDetails);
1026 })
1027
1028});
1029
1030function fld_DynamicallyCreateDownloadElements(dataDetails){
1031
1032 if(dataDetails.fileInfoForApp.length < 1){
1033 $("#uploadedDocumentsArea").append( '<span>There are no files associated with this record</span>');
1034 }else{
1035 for(let i=0; i< dataDetails.fileInfoForApp.length; i++)
1036 {
1037 $("#uploadedDocumentsArea").append('<form action="'+urlPrepend+'/FieldData/DownloadFile" method="post"><input type="text" name="nameModifiedPrepend" value="'+dataDetails.fileInfoForApp[i].nameModifiedPrepended+'" hidden><input type="text" name="partPath" value="'+dataDetails.fileInfoForApp[i].partPath+'" hidden><input type="text" name="fileType" value="'+dataDetails.fileInfoForApp[i].fileType+'" hidden><div class="input-group input-file" style="display:flex;"><input type="text" class="form-control showText" value="'+dataDetails.fileInfoForApp[i].nameModifiedPrepended+'" disabled /><span class="input-group-btn"><button class="btn btn-success downloadDocumentBtn" type="submit"> Download</button></span></div></form>');
1038 //$("#uploadedDocumentsArea").append('<form ><div class="input-group input-file" style="display:flex;"><input type="text" class="form-control showText" value="'+dataDetails.fileInfoForApp[i].nameModifiedPrepended+'" disabled /><span class="input-group-btn"><button class="btn btn-success downloadDocumentBtn" type="button" rel="https://portal.precisiondecisions.co.uk/MiFarm/beAgChem' + dataDetails.fileInfoForApp[i].fullPath + '" onclick="fld_ClickDownload(this)"> Download</button></span></div></form>');
1039 }
1040 }
1041}
1042
1043
1044function fld_ApplyDetailsToApplicationRecordFromApplication(dataDetails){
1045
1046 var getNumbersFromCreatedOn = dataDetails.application_date.match(/\d+/g).map(Number)[0];
1047 var createdOntString = new Date(getNumbersFromCreatedOn);
1048 var createdDateParsed = $.datepicker.formatDate('dd/mm/yy', createdOntString);
1049 $('#appDetailsAppCreatedDate').val(createdDateParsed);
1050 $('#appDetailsProdName').val(dataDetails.product_name);
1051 $('#appDetailsReason').val(dataDetails.reason_name);
1052 $('#appDetailsGrowthStage').val(dataDetails.growth_stage_name);
1053 $('#appDetailsHectaresSprayed').val(dataDetails.hectares_sprayed);
1054 $('#appDetailsRatesPerHectare').val(dataDetails.rates_per_hectare);
1055 if (dataDetails.earliest_harvest_date === "") {
1056 dataDetails.earliest_harvest_date = "N/A";
1057 };
1058 if (dataDetails.earliest_harvest_date === null) {
1059 $('#appDetailsEarliestHarDate').val("N/A");
1060 }
1061 else {
1062 var getNumbersFromEarliestHarvestDate = dataDetails.earliest_harvest_date.match(/\d+/g).map(Number)[0];
1063 var earliestHarvestString = new Date(getNumbersFromEarliestHarvestDate);
1064 var earliestHarvestDateParsed = $.datepicker.formatDate('dd/mm/yy', earliestHarvestString);
1065 $('#appDetailsEarliestHarDate').val(earliestHarvestDateParsed);
1066 }
1067
1068 var getNumbersFromDateOnly = dataDetails.added_on.match(/\d+/g).map(Number)[0];
1069 var addedDateString = new Date(getNumbersFromDateOnly);
1070 var addedOnDateParsed = $.datepicker.formatDate('dd/mm/yy', addedDateString);
1071 $('#appDetailsAppAddedOn').val(addedOnDateParsed);
1072 $('#appDetailsFieldName').val($('.field_item_selected').text());
1073}
1074
1075function fld_GetApplyDetailsForApplicationFromUserDetails(dataDetails){
1076
1077 $.ajax({
1078 url: urlPrepend + "/FieldData/GetUserDetails",
1079 type: "POST",
1080 data: { staffId: dataDetails.staffId },
1081 })
1082 .done( function (dataApp) {
1083 dataApp = JSON.parse(dataApp);
1084 $('#appDetailsCreator').val(dataApp.sname);
1085
1086
1087 }
1088 )
1089}
1090// make the modal scrollable;
1091$('#applicationListModal').css('overflow-y', 'auto');
1092$('#applicationDetailsModal').css('overflow-y', 'auto');
1093
1094$(document).ready(function () {
1095 $('[data-toggle="tooltip"]').tooltip();
1096});
1097/// <summary>View Applications List</summary>
1098
1099/// <summary>View Admin Products</summary>
1100$('#admin_manage_products').on('click', function () {
1101 $('#adminModal').modal('hide');
1102
1103 $('#adminManageProducts').modal('show');
1104})
1105
1106// make the modal scrollable;
1107$('#productsListViewModal').css('overflow-y', 'auto');
1108$('#productAdminPreviewModal').css('overflow-y', 'auto');
1109
1110
1111$('#adminViewProductsBtn').on('click', function () {
1112 $("#adminManageProducts").modal("hide");
1113
1114 $("#productsListViewModal").modal("show");
1115});
1116
1117$(document).on("click", "#adminViewProductsBtn", function () {
1118 var request = $.ajax({
1119 url: urlPrepend + "/FieldData/GetAllProductsAsModel",
1120 type: "POST",
1121 //data: { fieldId: getFieldId() },
1122 success: function (data) {
1123 //$('#viewAppFieldName').text($('.field_item_selected').text());
1124 $('#productListBodyModal').html(data);
1125 }
1126 });
1127});
1128
1129// button to close the modal
1130$(document).on("click", ".product_listView_close_modal", function () {
1131 $("#productsListViewModal").modal('hide');
1132});
1133
1134function getProdAdminGrowthStages(selectedProductId) {
1135 $.getJSON(urlPrepend + '/FieldData/GetProductGrowthStages', { productId: selectedProductId }, function (stages) {
1136 var stageSelect = $('#adminProdGrowthStages');
1137 var stageElements = stages.map(function (stage) {
1138 //return $('<option>', { value: stage.id, text: stage.name })
1139 return $('<li><a id="' + stage.id + '">' + stage.name + '<span class="close glyphicon glyphicon-remove removeProdGrowthStBtn"></span></a></li>')
1140 });
1141
1142 stageSelect.html(stageElements);
1143 let inputOptionEl = "<li class='adminProdCustGrowthInputDiv'><input type='text' class='adminProductAddInputFd' id='adminProductGrStageInputFd'/><span class='adminProductAddBtn' id='adminProdAddGrStage'>+</span></li>";
1144 stageSelect.append(inputOptionEl)
1145 });
1146}
1147
1148function getProdAdminReasons(selectedProductId) {
1149 $.getJSON(urlPrepend + '/FieldData/GetProductReasons', { productId: selectedProductId }, function (reasons) {
1150 reasons = JSON.parse(reasons);
1151 var reasonsSelect = $('#adminProdReasons');
1152 var reasonElements = reasons.map(function (reason) {
1153 return $('<li><a id="' + reason.id + '">' + reason.name + '<span class="close glyphicon glyphicon-remove removeProdReasonsBtn"></span></a></li>')
1154 //return $('<option>', { value: reason.id, text: reason.name })
1155 });
1156
1157 reasonsSelect.html(reasonElements);
1158 let inputOptionEl = "<li class='adminProdCustReasonInputDiv'><input type='text' class='adminProductAddInputFd' id='adminProductReasonInputFd'/><span class='adminProductAddBtn' id='adminProdAddReason'>+</span></li>";
1159 reasonsSelect.append(inputOptionEl)
1160 });
1161}
1162
1163$(document).on("click", ".viewListProductName", function () {
1164 $('#productsListViewModal').modal('hide');
1165 $('#productAdminPreviewModal').modal('show');
1166
1167 $('#productDetailsAdminPADateDiv').show();
1168
1169 var productId = this.id;
1170
1171 getProdAdminGrowthStages(productId);
1172 getProdAdminReasons(productId);
1173 var request = $.ajax({
1174 url: urlPrepend + "/FieldData/GetProductDetails",
1175 type: "POST",
1176 data: { productId: productId },
1177 success: function (data) {
1178 data = JSON.parse(data);
1179 $('#productDetailsAdminPName').val(data.name);
1180 $('#productDetailsAdminPId').val(data.id);
1181 $('#productDetailsAdminPHI').val(data.harvest_interval);
1182
1183 $('#productDetailsAdminPIsEAMU').remove();
1184 $('#prodPreviewEAMUBtnValue').remove();
1185
1186 if (data.is_eamu ? $('#prodPreviewEamuBoxText').text('Required') : $('#prodPreviewEamuBoxText').text('Not Required'));
1187 if (data.is_eamu) {
1188 $('.prodPreviewEAMURB').append('<input type="checkbox" checked="checked" id="productDetailsAdminPIsEAMU">');
1189 $('.prodPreviewEAMURB').append('<span class="customRadioButton" id="prodPreviewEAMUBtnValue"></span>');
1190 } else {
1191 $('.prodPreviewEAMURB').append('<input type="checkbox" id="productDetailsAdminPIsEAMU">');
1192 $('.prodPreviewEAMURB').append('<span class="customRadioButton" id="prodPreviewEAMUBtnValue"></span>');
1193 }
1194
1195 $('#productDetailsAdminPMinAR').val(data.min_app_rate);
1196 $('#productDetailsAdminPMaxAR').val(data.max_app_rate);
1197 $('#productDetailsAdminPAI').val(data.active_ingredient);
1198 $('#productDetailsAdminPMNA').val(data.max_number_applications);
1199 $('#productDetailsAdminPRU').val(data.rates_unit);
1200
1201 var addedDateString = new Date(data.added_on);
1202 var addedDateStringParsed = $.datepicker.formatDate('dd/mm/yy', addedDateString);
1203 $('#productDetailsAdminPADate').val(addedDateStringParsed);
1204 //$.ajax({
1205 // url: urlPrepend + "/FieldData/GetUserDetails",
1206 // type: "POST",
1207 // data: { staffId: data.staffId },
1208 // success: function (data) {
1209 // data = JSON.parse(data);
1210 // $('#productDetailsAdminPCreator').val(data.sname);
1211 // }
1212 //});
1213 }
1214 });
1215});
1216
1217
1218
1219$(document).on("click", "#adminProdAddGrStage", function () {
1220 let productId = $('#productDetailsAdminPId').val();
1221 let growthStageName = $('#adminProductGrStageInputFd').val()
1222 $.post(urlPrepend + "/FieldData/AddGrowthStageToProduct", {
1223 productId: productId,
1224 growthStageName: growthStageName
1225 }, function () { })
1226 .done(function (dataResponse) {
1227 if (dataResponse.didFail === true) {
1228 displayErrMsg(dataResponse.message);
1229 return;
1230 }
1231
1232 var stageId = dataResponse.id;
1233 var stageDropDown = $('#adminProdGrowthStages');
1234 var element = $('<li><a id="' + stageId + '">' + growthStageName + '<span class="close glyphicon glyphicon-remove removeProdGrowthStBtn"></span></a></li>')
1235
1236 $('.adminProdCustGrowthInputDiv').before(element);
1237
1238 $('#adminProductGrStageInputFd').val('');
1239 })
1240})
1241
1242$(document).on("click", "#adminProdAddReason", function () {
1243 let productId = $('#productDetailsAdminPId').val();
1244 let reasonName = $('#adminProductReasonInputFd').val()
1245 $.post(urlPrepend + "/FieldData/AddReasonToProduct", {
1246 productId: productId,
1247 reasonName: reasonName
1248 }, function () { })
1249 .done(function (dataResponse) {
1250 if (dataResponse.didFail === true) {
1251 displayErrMsg(dataResponse.message);
1252 return;
1253 }
1254
1255 var reasonId = dataResponse.id;
1256 var reasonsDropdown = $('#adminProdReasons');
1257 var element = $('<li><a id="' + reasonId + '">' + reasonName + '<span class="close glyphicon glyphicon-remove removeProdReasonsBtn"></span></a></li>');
1258
1259 $('.adminProdCustReasonInputDiv').before(element);
1260
1261 $('#adminProductReasonInputFd').val('');
1262 })
1263})
1264
1265$(document).on("click", "#product_admin_edit_btn", function () { // edit product modal
1266 $('#adminProductDisableField').removeAttr('disabled'); // removes the disabled field so you can write new values of input elements
1267 $('#product_admin_edit_btn').attr('id', 'product_admin_save_btn'); // changing the id of the edit button to save button id;
1268 $('#product_admin_save_btn').text('Save Changes'); // changing the inner text of the button to Save Changes;
1269 $('#adminProdGrowReasonsField').removeAttr('disabled');
1270
1271 $('#productDetailsAdminPADateDiv').hide(); // we hide the date created element input because its not supposed to be edited
1272});
1273
1274function productCloseEditModalPreview() {
1275 $('#productAdminPreviewModal').modal('hide');
1276
1277 $('#adminProductDisableField').prop('disabled', true);
1278 $('#product_admin_save_btn').attr('id', 'product_admin_edit_btn');
1279 $('#product_admin_edit_btn').text('Edit Product');
1280 $('#adminProdGrowReasonsField').prop('disabled', true);
1281
1282 $('#productDetailsAdminPADateDiv').show();
1283}
1284
1285//$(document).on('click', '#productDetailsAdminPIsEAMU', function () {
1286// $('#productDetailsAdminPIsEAMU').attr('checked', true)
1287//});
1288
1289$(document).on("click", "#product_admin_save_btn", function () {
1290 let productName = $('#productDetailsAdminPName').val();
1291 let productHarvestInterval = $('#productDetailsAdminPHI').val();
1292 let productIsEAMU;
1293 if ($('#prodPreviewEAMUBtnValue').css("background-color") == "rgb(32, 178, 170)" ? productIsEAMU = "true" : productIsEAMU = "false"); // this checks if the radio button when editing is clicked or not.
1294
1295 let productMinAR = $('#productDetailsAdminPMinAR').val();
1296 let productMaxAR = $('#productDetailsAdminPMaxAR').val();
1297 let productActiveIngredient = $('#productDetailsAdminPAI').val();
1298 let productMaxNumApp = $('#productDetailsAdminPMNA').val();
1299 let productRatesUnit = $('#productDetailsAdminPRU').val();
1300 let productId = $('#productDetailsAdminPId').val();
1301
1302 $.post(urlPrepend + "/FieldData/EditProduct", {
1303 productId: productId,
1304 productName: productName,
1305 productHarvestInterval: productHarvestInterval,
1306 productIsEAMU: productIsEAMU,
1307 productMinAR: productMinAR,
1308 productMaxAR: productMaxAR,
1309 productActiveIngredient: productActiveIngredient,
1310 productMaxNumApp: productMaxNumApp,
1311 productRatesUnit: productRatesUnit
1312 }, function () { })
1313 .done(function (dataResponse) {
1314 if (dataResponse.didFail === true) {
1315 //productCloseEditModalPreview();
1316 displayErrMsg(dataResponse.message);
1317 return;
1318 }
1319
1320 productCloseEditModalPreview();
1321 displaySuccessMsg("You have successfully updated this product.")
1322 })
1323 .fail(function (dataResponse, httpStatusMessage, customErrorMessage) {
1324 productCloseEditModalPreview();
1325 displayErrMsg(customErrorMessage);
1326 })
1327 //$("#productAdminPreviewModal").modal('hide');
1328});
1329
1330/// <summary>View Admin Products</summary>
1331
1332/// <summary>Create Admin Products</summary>
1333$(document).on("click", "#adminAddProductBtn", function () {
1334 $('#adminManageProducts').modal('hide');
1335 $('#productAdminCreate').modal('show');
1336
1337 $('#prodCreateGrowthStagesUl li:not(:last-child)').remove();
1338 $('#prodCreateReasonsUl li:not(:last-child)').remove();
1339});
1340
1341$('#productAdminCreate').css('overflow-y', 'auto');
1342
1343
1344$('#productAdminPreviewModal').on('hidden.bs.modal', function () {
1345 //$(document).on("click", "#prodPreviewCloseBtn", function () {
1346 $('#productAdminPreviewModal').modal('hide');
1347
1348 $('#adminProductDisableField').prop('disabled', true);
1349 $('#product_admin_save_btn').attr('id', 'product_admin_edit_btn');
1350 $('#product_admin_edit_btn').text('Edit Product');
1351
1352 $('#adminProdGrowReasonsField').prop('disabled', true);
1353
1354 $('#prodPreviewEAMUBtnValue').attr('checked', false);
1355
1356 $('#adminProdGrowthStages li:not(:last-child)').remove();
1357 $('#adminProdReasons li:not(:last-child)').remove();
1358});
1359
1360$(document).on('click', '#productCreateAddGrStage', function () {
1361 let growthStageName = $('#productCreateGrStageInputFd').val()
1362
1363 var element = $('<li><a>' + growthStageName + '<span class="close glyphicon glyphicon-remove removeProdGrowthStBtn"></span></a></li>')
1364
1365 var liInputElementId = $('#inputLiFieldProdCreateGS').index();
1366
1367 $('#prodCreateGrowthStagesUl li:eq(' + liInputElementId + ')').before(element);
1368
1369 $('#productCreateGrStageInputFd').val('');
1370});
1371
1372$(document).on('click', '#productCreateAddReason', function () {
1373 let growthStageName = $('#productCreateReasonInputFd').val()
1374
1375 var element = $('<li><a>' + growthStageName + '<span class="close glyphicon glyphicon-remove removeProdReasonsBtn"></span></a></li>')
1376
1377 var liInputElementId = $('#inputLiFieldProdCreateReason').index();
1378
1379 $('#prodCreateReasonsUl li:eq(' + liInputElementId + ')').before(element);
1380
1381 $('#productCreateReasonInputFd').val('');
1382});
1383
1384$(document).on('click', '.removeProdGrowthStBtn', function () {
1385 var element = $(this).parents("li:first");
1386 let productId = $('#productDetailsAdminPId').val();
1387 var elementId = $(this).parents("a:first").attr('id');
1388 if (elementId === undefined) {
1389 $(this).parents("li:first").remove();
1390 } else {
1391 $.post(urlPrepend + "/FieldData/RemoveProductGrowthStage", {
1392 productId: productId,
1393 elementId: elementId
1394 }, function () { })
1395 .done(function (dataResponse) {
1396 if (dataResponse.didFail === true) {
1397 displayErrMsg(dataResponse.message);
1398 return;
1399 }
1400
1401 $('#adminProdGrowthStages > li').find('a[id=' + elementId + ']').remove();
1402 displaySuccessMsg("The selected growth stage has been successfully removed from the product.")
1403 })
1404 };
1405});
1406
1407$(document).on('click', '.removeProdReasonsBtn', function () {
1408 var element = $(this).parents("li:first");
1409 let productId = $('#productDetailsAdminPId').val();
1410 var elementId = $(this).parents("a:first").attr('id');
1411 if (elementId === undefined) {
1412 $(this).parents("li:first").remove();
1413 } else {
1414 $.post(urlPrepend + "/FieldData/RemoveProductReason", {
1415 productId: productId,
1416 elementId: elementId
1417 }, function () { })
1418 .done(function (dataResponse) {
1419 if (dataResponse.didFail === true) {
1420 displayErrMsg(dataResponse.message);
1421 return;
1422 }
1423
1424 $('#adminProdReasons > li').find('a[id=' + elementId + ']').remove();
1425 displaySuccessMsg("The selected reason has been successfully removed from the product.")
1426 })
1427 };
1428});
1429
1430/// <summary>Create Product Modal Validations</summary>
1431$('#productCreateAdminPHI').on('focusout', function () {
1432 var isInputValid = doesStringContainLetters($('#productCreateAdminPHI').val());
1433
1434 ManageValidationCreateProduct(isInputValid, 'product_admin_create_btn', 'prodCreateHIDiv', 'errorProdCreateAdminPHI');
1435});
1436
1437$('#productCreateAdminPMinAR').on('focusout', function () {
1438 var isInputValid = doesStringContainLetters($('#productCreateAdminPMinAR').val());
1439
1440 ManageValidationCreateProduct(isInputValid, 'product_admin_create_btn', 'prodCreateMinARDiv', 'errorProdCreateAdminMinAR');
1441});
1442
1443$('#productCreateAdminPMaxAR').on('focusout', function () {
1444 var isInputValid = doesStringContainLetters($('#productCreateAdminPMaxAR').val());
1445
1446 ManageValidationCreateProduct(isInputValid, 'product_admin_create_btn', 'prodCreateMaxARDiv', 'errorProdCreateAdminMaxAR');
1447});
1448
1449$('#productCreateAdminPMNA').on('focusout', function () {
1450 var isInputValid = doesStringContainLetters($('#productCreateAdminPMNA').val());
1451
1452 ManageValidationCreateProduct(isInputValid, 'product_admin_create_btn', 'prodCreateMaxAppDiv', 'errorProdCreateAdminMNA');
1453});
1454
1455$('#productCreateAdminPRU').on('focusout', function () {
1456 var isInputValid = ($('#productCreateAdminPRU').val() === "");
1457 ManageValidationCreateProduct(isInputValid, 'product_admin_create_btn', 'prodCreateRatesDiv', 'errorProdCreateAdminPRU');
1458});
1459
1460$('#productCreateAdminPAI').on('focusout', function () {
1461 var isInputValid = ($('#productCreateAdminPAI').val() === "");
1462 ManageValidationCreateProduct(isInputValid, 'product_admin_create_btn', 'prodCreateAIDiv', 'errorProdCreateAdminAI');
1463});
1464
1465function ManageValidationCreateProduct(isValid, mainBtnName, div, errorLb) {
1466 if (isValid) {
1467 $('#' + mainBtnName).addClass("disabled");
1468
1469 $('#' + div).addClass("has-error");
1470 $('#' + errorLb).show();
1471 } else {
1472 $('#' + mainBtnName).removeClass("disabled");
1473
1474 $('#' + div).removeClass("has-error");
1475 $('#' + errorLb).hide();
1476 }
1477}
1478
1479function CheckIfInputIsFilled(inputFieldName, divError, errorLabel) {
1480 if ($('#' + inputFieldName).val().length === 0) {
1481 $('#' + divError).addClass("has-error");
1482 $('#' + errorLabel).show();
1483 return false;
1484 }
1485 return true;
1486}
1487
1488/// <summary>Create Product Modal Validations</summary>
1489
1490
1491$(document).on('click', '#product_admin_create_btn', function () {
1492 let productName = $('#productCreateAdminPName').val();
1493 let productHarvestInterval = $('#productCreateAdminPHI').val();
1494 let productMinAR = $('#productCreateAdminPMinAR').val();
1495 let productMaxAR = $('#productCreateAdminPMaxAR').val();
1496 let productActiveIngredient = $('#productCreateAdminPAI').val();
1497 let productMaxNumApp = $('#productCreateAdminPMNA').val();
1498 let productRatesUnit = $('#productCreateAdminPRU').val();
1499
1500 let productIsEAMU = $('#productCreateIsEAMU').is(':checked');
1501
1502 let isProductCreateAdminPHIFilled = CheckIfInputIsFilled('productCreateAdminPHI', 'prodCreateHIDiv', 'errorProdCreateAdminPHI');
1503 if (!isProductCreateAdminPHIFilled) return;
1504
1505 let isproductCreateAdminPMinARFilled = CheckIfInputIsFilled('productCreateAdminPMinAR', 'prodCreateMinARDiv', 'errorProdCreateAdminMinAR');
1506 if (!isproductCreateAdminPMinARFilled) return;
1507
1508 let isproductCreateAdminPMaxARFilled = CheckIfInputIsFilled('productCreateAdminPMaxAR', 'prodCreateMaxARDiv', 'errorProdCreateAdminMaxAR');
1509 if (!isproductCreateAdminPMaxARFilled) return;
1510
1511 let isproductCreateAdminPAIFilled = CheckIfInputIsFilled('productCreateAdminPAI', 'prodCreateAIDiv', 'errorProdCreateAdminAI');
1512 if (!isproductCreateAdminPAIFilled) return;
1513
1514 let isproductCreateAdminPMNAFilled = CheckIfInputIsFilled('productCreateAdminPMNA', 'prodCreateMaxAppDiv', 'errorProdCreateAdminMNA');
1515 if (!isproductCreateAdminPMNAFilled) return;
1516
1517 let isproductCreateAdminPRUFilled = CheckIfInputIsFilled('productCreateAdminPRU', 'prodCreateRatesDiv', 'errorProdCreateAdminPRU');
1518 if (!isproductCreateAdminPRUFilled) return;
1519
1520 $.post(urlPrepend + "/FieldData/CreateProduct", {
1521 productName: productName,
1522 productHarvestInterval: productHarvestInterval,
1523 productIsEAMU: productIsEAMU,
1524 productMinAR: productMinAR,
1525 productMaxAR: productMaxAR,
1526 productActiveIngredient: productActiveIngredient,
1527 productMaxNumApp: productMaxNumApp,
1528 productRatesUnit: productRatesUnit
1529 }, function () { })
1530 .done(function (dataResponse) {
1531 if (dataResponse.didFail === true) {
1532 //$('#productAdminCreate').modal('hide');
1533 displayErrMsg(dataResponse.message);
1534 return;
1535 }
1536
1537 let productId = dataResponse.id;
1538
1539 let growthStagesArr = [];
1540 let growthStagesCount = $('#prodCreateGrowthStagesUl li').length;
1541 for (var i = 0; i < growthStagesCount - 1; i++) {
1542 var currStage = $("#prodCreateGrowthStagesUl li").get(i).innerText
1543 growthStagesArr.push(currStage);
1544 };
1545
1546 let reasonArr = [];
1547 let reasonsCount = $('#prodCreateReasonsUl li').length;
1548 for (var i = 0; i < reasonsCount - 1; i++) {
1549 var currReason = $("#prodCreateReasonsUl li").get(i).innerText
1550 reasonArr.push(currReason);
1551 };
1552
1553 let growthStagesArrToStr = JSON.stringify(growthStagesArr);
1554 let reasonsArrToStr = JSON.stringify(reasonArr);
1555
1556 $.post(urlPrepend + "/FieldData/AddListOfGrowthStagesToProduct", {
1557 productId: productId,
1558 stages: growthStagesArrToStr,
1559 }, function () { })
1560 .done(function (dataResponse) {
1561 })
1562
1563 $.post(urlPrepend + "/FieldData/AddListOfReasonsToProduct", {
1564 productId: productId,
1565 reasons: reasonsArrToStr,
1566 }, function () { })
1567 .done(function (dataResponse) {
1568 })
1569
1570 $('#productAdminCreate').modal('hide');
1571
1572 emptyCreateProductInputAndUlFields();
1573
1574 displaySuccessMsg("You have successfully updated this product.")
1575 })
1576 .fail(function (dataResponse, httpStatusMessage, customErrorMessage) {
1577 $('#productAdminCreate').modal('hide');
1578 displayErrMsg(customErrorMessage);
1579 })
1580 .always(productCloseEditModalPreview);
1581});
1582
1583function emptyCreateProductInputAndUlFields() {
1584 $('#productCreateAdminPName').val('');
1585 $('#productCreateAdminPHI').val('');
1586 $('#productCreateAdminPMinAR').val('');
1587 $('#productCreateAdminPMaxAR').val('');
1588 $('#productCreateAdminPAI').val('');
1589 $('#productCreateAdminPMNA').val('');
1590 $('#productCreateAdminPRU').val('');
1591
1592 $('#prodCreateGrowthStagesUl li:not(:last-child)').remove();
1593 $('#prodCreateReasonsUl li:not(:last-child)').remove();
1594}
1595
1596/// <summary>Create Admin Products</summary>
1597
1598/// <summary>Export AgChem Records of specific Field</summary>
1599$(document).on('click', '#exportFieldAppsBtn', function () {
1600 $('#adminManageProducts').modal('hide');
1601 $('#exportRecordsModal').modal('show');
1602});
1603
1604//$('#exportRecordsModal').on('hidden.bs.modal', function () {
1605// $('#cover-spin').hide();
1606//});
1607
1608//$(document).on('click', '#beginExportConfirmBtn', function () {
1609// $('#cover-spin').fadeIn('slow').fadeOut('slow');
1610//});
1611
1612$("#beginExportForm").submit(function (e) {
1613 let seasonCurr = $('#customerSeason option:selected').val();
1614 let farmIdCurr = getFarmId();
1615 let seasonName = $('#customerSeason option:selected').text();
1616 let exportFarmName = $('.farm_item_selected').text();
1617 $('#exportSeasonId').val(seasonCurr);
1618 $('#exportFarmId').val(farmIdCurr);
1619 $('#exportSeasonName').val(seasonName);
1620 $('#exportFarmName').val(exportFarmName);
1621
1622 $('#exportRecordsModal').modal('hide')
1623});
1624
1625
1626/// <summary>Export AgChem Records of specific Field</summary>
1627
1628$(document).on("click", "#editField", function () {
1629
1630 if (gen_mode_sub == 2) {
1631 removeSingleFieldSampleData();
1632 $("#leftDetailsPanel").hide();
1633 //hide nutrients
1634 $(".fld_recent_sample_nutrients").hide();
1635 }
1636 //edit mode
1637 gen_mode_sub = 3;
1638
1639
1640 //display save button
1641 showSaveButton();
1642
1643 //make field name editable
1644 $(".field_item_selected").attr("contenteditable", "true");
1645 $(".field_item_selected").addClass("field_name_edit_mode")
1646
1647 var id = $(this).attr("rel");
1648 var obj;
1649 for (var i = 0; i < polygonsArray.length; i++) {
1650 if (polygonsArray[i].get("id") == id) {
1651 obj = polygonsArray[i];
1652
1653
1654 polygonsArray[i].setOptions({
1655 editable: true,
1656 fillColor: '#000000'
1657 })
1658 }
1659 }
1660
1661 if ($(this).hasClass("editmode")) {
1662 //user has clicked this to get out of edit mode
1663 if (obj.getPaths().getLength() > 1) {
1664 resetMultiPathPolyObj(obj);
1665 }
1666 else {
1667 resetPolyObj(obj);
1668 }
1669
1670 $(this).removeClass("editmode");
1671 //remove editable attribute
1672 $(".field_item_selected").removeAttr("contenteditable");
1673 hideSaveFieldButton();
1674 }
1675 else {
1676 $(this).addClass("editmode");
1677
1678 var str = "";
1679 //set centre point and set label.
1680 var tempBounds = new google.maps.LatLngBounds();
1681 for (var i = 0; i < obj.getPath().getLength() ; i++) {
1682 var xy = obj.getPath().getAt(i);
1683 str += xy.lat() + ',' + xy.lng() + "|";
1684 }
1685
1686 ogObjCoords = str;
1687
1688 editField(obj);
1689
1690 }
1691});
1692
1693// UI 2
1694
1695
1696
1697
1698$(document).on("click", ".download_fd_boundary", function () {
1699
1700 if (gen_mode_sub == 2) {
1701 removeSingleFieldSampleData();
1702 $("#leftDetailsPanel").hide();
1703 //hide nutrients
1704 $(".fld_recent_sample_nutrients").hide();
1705 }
1706
1707 location.href = siteUrl + "Administration/MiFarm/DownloadFieldBoundary.aspx?id=" + getFieldId();
1708});
1709
1710//extend polyline class to inlice getBounds
1711google.maps.Polyline.prototype.getBounds = function () {
1712 var bounds = new google.maps.LatLngBounds();
1713 this.getPath().forEach(function (e) {
1714 bounds.extend(e);
1715 });
1716 return bounds;
1717};
1718
1719// Polygon containsLatLng - method to determine if a latLng is within a polygon
1720google.maps.Polygon.prototype.containsLatLng = function (latLng) {
1721 // Exclude points outside of bounds as there is no way they are in the poly
1722
1723 var inPoly = false,
1724 bounds, lat, lng,
1725 numPaths, p, path, numPoints,
1726 i, j, vertex1, vertex2;
1727
1728 // Arguments are a pair of lat, lng variables
1729 if (arguments.length == 2) {
1730 if (
1731 typeof arguments[0] == "number" &&
1732 typeof arguments[1] == "number"
1733 ) {
1734 lat = arguments[0];
1735 lng = arguments[1];
1736 }
1737 } else if (arguments.length == 1) {
1738 bounds = this.getBounds();
1739
1740 if (!bounds && !bounds.contains(latLng)) {
1741 return false;
1742 }
1743 lat = latLng.lat();
1744 lng = latLng.lng();
1745 } else {
1746 // console.log("Wrong number of inputs in google.maps.Polygon.prototype.contains.LatLng");
1747 }
1748
1749 // Raycast point in polygon method
1750
1751 numPaths = this.getPaths().getLength();
1752 for (p = 0; p < numPaths; p++) {
1753 path = this.getPaths().getAt(p);
1754 numPoints = path.getLength();
1755 j = numPoints - 1;
1756
1757 for (i = 0; i < numPoints; i++) {
1758 vertex1 = path.getAt(i);
1759 vertex2 = path.getAt(j);
1760
1761 if (
1762 vertex1.lng() < lng &&
1763 vertex2.lng() >= lng ||
1764 vertex2.lng() < lng &&
1765 vertex1.lng() >= lng
1766 ) {
1767 if (
1768 vertex1.lat() +
1769 (lng - vertex1.lng()) /
1770 (vertex2.lng() - vertex1.lng()) *
1771 (vertex2.lat() - vertex1.lat()) <
1772 lat
1773 ) {
1774 inPoly = !inPoly;
1775 }
1776 }
1777
1778 j = i;
1779 }
1780 }
1781
1782 return inPoly;
1783};
1784
1785var fieldLabels = [];
1786var icon = urlPrepend + "/Content/images/dots/red_dot.png";
1787var polygonsArray = [];
1788var markers = [];
1789var serviceOrderPolygons = [];
1790
1791function saveFieldname() {
1792
1793 loadStatus(txtFd1);
1794 var newTxt = $(".current_field_name").text();
1795 var currentId = $(".current_field_name").attr("rel");
1796
1797 $.ajax({
1798 type: "POST",
1799 url: urlPrepend + "/fielddata/editname-" + currentId,
1800 data: { fieldName: newTxt }
1801 })
1802 .done(function () {
1803 //loop through polygon and get id, if it matches with current id then
1804 for (var i = 0; i < polygonsArray.length; i++) {
1805 //match the out current field id
1806 if ((polygonsArray[i].id) == currentId) {
1807 //update label content
1808 fieldLabels[i].setContent(newTxt);
1809 }
1810 }
1811
1812 //update field drop list
1813 updateFieldNameListing(newTxt, currentId);
1814 removeStatus();
1815 });
1816}
1817function updateFieldNameListing(newTxt, id) {
1818 $(".field_item").each(function () {
1819 if ($(this).attr("id").split("_")[1] == id) {
1820 $(this).empty().html(newTxt);
1821 }
1822 })
1823}
1824
1825function showSaveButton() {
1826 $("#saveEditedField").show(200);
1827}
1828
1829function hideSaveFieldButton() {
1830 $("#saveEditedField").hide();
1831}
1832
1833var fld_fieldBoundaryInsertsect = function (googlePolygonPath) {
1834 var coordinates = googleMaps2JTS(googlePolygonPath);
1835 var geometryFactory = new jsts.geom.GeometryFactory();
1836 var shell = geometryFactory.createLinearRing(coordinates);
1837 var jstsPolygon = geometryFactory.createPolygon(shell);
1838
1839 // if the geometry is aleady a simple linear ring, do not
1840 // try to find self intersection points.
1841 var validator = new jsts.operation.IsSimpleOp(jstsPolygon);
1842 if (validator.isSimpleLinearGeometry(jstsPolygon)) {
1843 return;
1844 }
1845
1846 var res = [];
1847 var graph = new jsts.geomgraph.GeometryGraph(0, jstsPolygon);
1848 var cat = new jsts.operation.valid.ConsistentAreaTester(graph);
1849 var r = cat.isNodeConsistentArea();
1850 if (!r) {
1851 var pt = cat.getInvalidPoint();
1852 res.push([pt.x, pt.y]);
1853 }
1854 return res;
1855};
1856
1857
1858var googleMaps2JTS = function (boundaries) {
1859 var coordinates = [];
1860 for (var i = 0; i < boundaries.getLength() ; i++) {
1861 coordinates.push(new jsts.geom.Coordinate(
1862 boundaries.getAt(i).lat(), boundaries.getAt(i).lng()));
1863 }
1864 coordinates.push(coordinates[0]);
1865 return coordinates;
1866};
1867
1868
1869var selectedShape;
1870var fld_drawingManager;
1871function setDrawPolygon(hasField) {
1872 selectedShape = "";
1873 if (gen_mode_sub == 1) {
1874 $("#saveNewFieldBoundary").show(200);
1875 }
1876 else {
1877 if (gen_mode_sub == 3) {
1878 //field point
1879 $("#saveFieldBoundaryFieldPt").show(200);
1880 } else {
1881 $("#saveFieldBoundary").show(200);
1882 }
1883 }
1884
1885 fld_drawingManager = new google.maps.drawing.DrawingManager({
1886
1887 drawingMode: google.maps.drawing.OverlayType.POLYGON,
1888 drawingControl: false,
1889 drawingControlOptions: {
1890 position: google.maps.ControlPosition.TOP_CENTER,
1891 drawingModes: [
1892 google.maps.drawing.OverlayType.POLYGON
1893 ]
1894 },
1895 polygonOptions: newPolyOptions
1896 });
1897
1898 fld_drawingManager.setMap(map);
1899
1900 google.maps.event.addListener(fld_drawingManager, 'polygoncomplete', function (e) {
1901
1902
1903 //check for intersects here
1904 var intersects = fld_fieldBoundaryInsertsect(e.getPath());
1905
1906 if (intersects && intersects.length) {
1907 //alert user and remove current polygon
1908
1909 displayErrMsg(txtFd21)
1910 e.setMap(null);
1911 } else {
1912
1913 fld_drawingManager.setDrawingMode(null);
1914 selectedShape = e;
1915
1916 addDeleteButton(e);
1917
1918 //add event to all points to allow for deletion of selected point.
1919 google.maps.event.addListener(selectedShape, 'rightclick', function (event) {
1920 if (event.vertex == undefined) {
1921 return;
1922 } else {
1923 var path = selectedShape.getPath();
1924 path.removeAt(event.vertex);
1925 }
1926 });
1927
1928 google.maps.event.addListener(selectedShape, 'dragend', function () {
1929 mousestatus = false;
1930 });
1931
1932 google.maps.event.addListener(selectedShape, 'dragstart', function () {
1933 mousestatus = true;
1934 });
1935
1936
1937 if (gen_mode_sub == 1) {
1938 $("#saveNewFieldBoundary").removeAttr("disabled");
1939 //polygon has been completed so hide 'add field link' in left panel fuield list
1940
1941 }
1942 else {
1943 if (gen_mode_sub == 3) {
1944 //field point
1945 $("#saveFieldBoundaryFieldPt").removeAttr("disabled");
1946 } else {
1947 $("#saveFieldBoundary").removeAttr("disabled");
1948 }
1949 }
1950
1951 $("#saveFieldBoundary").attr("title", "Save Boundary");
1952 if (hasField) {
1953 $("#saveFieldBoundary").addClass("has-field");
1954 }
1955
1956
1957
1958 selectedShape.getPaths().forEach(function (path, index) {
1959
1960 google.maps.event.addListener(path, 'insert_at', function () {
1961 // New point
1962 var intersects = fld_fieldBoundaryInsertsect(selectedShape.getPath());
1963 if (intersects && intersects.length) {
1964 //alert user and remove current polygon
1965
1966 displayErrMsg(txtFd21)
1967 //selectedShape.setMap(null);
1968 //selectedShape = "";
1969 //setDrawPolygon(false);
1970 }
1971 });
1972
1973 google.maps.event.addListener(path, 'remove_at', function () {
1974 // Point was removed
1975 var intersects = fld_fieldBoundaryInsertsect(selectedShape.getPath());
1976 if (intersects && intersects.length) {
1977 //alert user and remove current polygon
1978
1979 displayErrMsg(txtFd21)
1980 //selectedShape.setMap(null);
1981 //selectedShape = "";
1982 //setDrawPolygon(false);
1983 }
1984 });
1985
1986 google.maps.event.addListener(path, 'set_at', function () {
1987 // Point was moved
1988 var intersects = fld_fieldBoundaryInsertsect(selectedShape.getPath());
1989 if (intersects && intersects.length) {
1990 //alert user and remove current polygon
1991
1992 displayErrMsg(txtFd21)
1993 //selectedShape.setMap(null);
1994 //selectedShape = "";
1995 //setDrawPolygon(false);
1996 }
1997 });
1998
1999 });
2000 }
2001 });
2002}
2003
2004function polygonDirection(path) {
2005 //false - anti clockwise : true - clockwise
2006 return (google.maps.geometry.spherical.computeSignedArea(path) < 0);
2007}
2008
2009
2010
2011function addNewField() {
2012
2013 loadStatus("Save new field.....");
2014
2015 var newFieldId = 0;
2016 var seasonId = 0;
2017 var newFieldName = $("#newFieldNametxt").val();
2018 var selectedCrop = $("#newFieldCropLayerFarmersCropList").find(":selected").val();
2019 var selectedCropVar = "";
2020 if ($(".add_new_field_crop_ele_2").is(":visible")) {
2021 selectedCropVar = $("#newFieldCropVarietyLayerSeasonList").find(":selected").val();
2022 }
2023
2024 seasonId = $("#customerSeason").find(":selected").val();
2025
2026 $('#newFieldModal').modal('hide');
2027 var str = "";
2028 //set centre point and set label.
2029 var tempBounds = new google.maps.LatLngBounds();
2030 for (var i = 0; i < selectedShape.getPath().getLength() ; i++) {
2031 var xy = selectedShape.getPath().getAt(i);
2032 str += xy.lat() + ',' + xy.lng() + "|";
2033 tempBounds.extend(xy);
2034 }
2035 //calculate new area of polygon
2036 var area = google.maps.geometry.spherical.computeArea(selectedShape.getPath(), 6371);
2037 area = area * 100;
2038 //find put if user has entered points in a clockwise or anti-clockwise fashion.
2039
2040 var ptsDirection = polygonDirection(selectedShape.getPath());
2041
2042 $.ajax({
2043 type: "POST",
2044 url: urlPrepend + "/fielddata/newfield-" + newFieldName.replace(/\W/g, ''),
2045 data: { name: newFieldName, area: area, tradingId: getTradingId(), farmid: getFarmId(), points: str, crop: selectedCrop, applicationId:13, variety: $("#newFieldCropVarietyLayerSeasonList").find(":selected").val(), seasonId: seasonId, clockwisePts: ptsDirection }
2046 })
2047 .done(function (data) {
2048
2049 newFieldId = data;
2050
2051 resetPolyObj(selectedShape)
2052 selectedShape.setOptions({
2053 id: data,
2054 clickable: true
2055 });
2056 insertNewFieldItem(data, newFieldName);
2057 fld_addfieldToCroppingFieldList(data, newFieldName);
2058 addPolygonClickEvent(selectedShape);
2059 addPolygonMouseCoordsData(selectedShape);
2060
2061 setFieldMarker(selectedShape, tempBounds.getCenter().lat(), tempBounds.getCenter().lng(), newFieldName);
2062
2063 //add new polygon to the array
2064 polygonsArray.push(selectedShape);
2065
2066 $("#alertWrapper").append("<div class=\"alert-overlay modal-backdrop fade in\"></div>");
2067
2068 displaySuccessMsg2(txtFd3);
2069 removeStatus();
2070 field_resetNewFieldCropElements();
2071
2072 //refresh cropping season list in new field model
2073 crp_cropSeasonByFarm(getFarmId()); //lives in crop.js
2074 crp_addCropColoringToFields();//lives in crop.js
2075
2076 })
2077 .fail(function () {
2078 field_resetNewFieldCropElements();
2079 //display failure message.
2080 if (selectedShape) {
2081 selectedShape.setMap(null);
2082 setDrawPolygon(false);
2083 }
2084 })
2085}
2086
2087function field_resetNewFieldCropElements() {
2088 $("#newFieldCropLayerSeason").val('');
2089 $("#newFieldCropLayerSeasonList").val('');
2090 $("#newFieldCropLayerFarmersCropList").val('');
2091}
2092
2093var fld_fieldArrayItemNumber = 0;
2094
2095function deleteSelectedFieldBoundary() {
2096 var id = $("#deleteBoundary").attr("rel");
2097 //search and remove field from map
2098 for (var i = 0; i < polygonsArray.length; i++) {
2099 if (polygonsArray[i].get("id") == id) {
2100 polygonsArray[i].setMap(null);
2101 fieldLabels[i].setMap(null);
2102 markers[i].setMap(null);
2103 fld_fieldArrayItemNumber = i;
2104 }
2105 }
2106
2107
2108 $("#confirm-delete-boundary").modal('hide');
2109 loadStatus("Deleting Field Boundary.");
2110 $.ajax({
2111 type: "POST",
2112 url: urlPrepend + "/fielddata/delboundary",
2113 data: { id: id }
2114 })
2115 .done(function (data) {
2116 if (data) {
2117 removeStatus();
2118 displaySuccessMsg2(txtFd4);
2119 getFieldNoCacheUpdate(id);
2120
2121 //remove field items from all arrays
2122 polygonsArray.splice(fld_fieldArrayItemNumber, 1);
2123 fieldLabels.splice(fld_fieldArrayItemNumber, 1);
2124 markers.splice(fld_fieldArrayItemNumber, 1);
2125 //reset variable
2126 fld_fieldArrayItemNumber = 0;
2127
2128 //V2 - Ui addition
2129 //add italics to field name
2130 $(".field_item_selected").addClass("no-field");
2131
2132 }
2133 else {
2134 removeStatus();
2135 $("#alertWrapper").append("<div class=\"alert-overlay modal-backdrop fade in\"></div>");
2136 $("#genDangerAlert").show().find("span").first().empty().html(txtFd5);
2137 }
2138 })
2139 .fail(function () {
2140 removeStatus();
2141 // displayErrStatusMessage("There Was An Error Deleting A Field.");
2142 $("#alertWrapper").append("<div class=\"alert-overlay modal-backdrop fade in\"></div>");
2143 $("#genDangerAlert").show().find("span").first().empty().html(txtFd5);
2144 });
2145
2146 //close panel
2147 $("#panelField").removeClass("visible panel-behind").animate({ "margin-left": "-300px" });
2148 //reset variable
2149 fld_fieldRemoveId = 0;
2150}
2151
2152var fld_fieldArrayItemNumber_2 = 0;
2153
2154
2155function deleteSelectedField() {
2156
2157 //is this a field point we are deleting or field?
2158
2159 if ($("#deleteNoBoundaryFieldPt").length > 0) {
2160 //deleting a field point.
2161
2162 var fieldId = $("#deleteNoBoundaryFieldPt").attr("rel");
2163
2164
2165
2166 $("#confirm-delete").modal('hide');
2167 loadStatus(txtFd31);
2168 $.ajax({
2169 type: "POST",
2170 url: urlPrepend + "/fielddata/del",
2171 data: { id: fieldId }
2172 }).done(function (data) {
2173
2174
2175 if (data) {
2176 removeStatus();
2177 displaySuccessMsg(txtFd33);
2178 for (var i = 0; i < fld_fieldPts.length; i++) {
2179 if (fieldId === fld_fieldPts[i].id) {
2180
2181 fld_fieldPts[i].setMap(null);
2182 fld_fieldPtLabels[i].setMap(null);
2183 fld_fieldPts.splice(0, 1)
2184 fld_fieldPtLabels.splice(0, 1)
2185 //remove item from field list
2186 $(".field_item_selected").remove();
2187 $(".fieldInfo").each(function () {
2188 if ($(this).is(":visible")) {
2189 $(this).remove();
2190 }
2191 });
2192 }
2193 }
2194 }
2195 else {
2196 removeStatus();
2197 displayErrMsg(txtFd18);
2198 }
2199
2200 });
2201 }
2202 else {
2203 var id = $("#deleteField").attr("rel");
2204 //search and remove field from map
2205 for (var i = 0; i < polygonsArray.length; i++) {
2206 if (polygonsArray[i].get("id") == id) {
2207 polygonsArray[i].setMap(null);
2208 fieldLabels[i].setMap(null);
2209 markers[i].setMap(null);
2210 fld_fieldArrayItemNumber_2 = i;
2211 }
2212 }
2213
2214 $("#confirm-delete").modal('hide');
2215 loadStatus(txtFd32);
2216 $.ajax({
2217 type: "POST",
2218 url: urlPrepend + "/fielddata/del",
2219 data: { id: id }
2220 })
2221 .done(function (data) {
2222
2223
2224 //remove field items from all arrays
2225 polygonsArray.splice(fld_fieldArrayItemNumber_2, 1);
2226 fieldLabels.splice(fld_fieldArrayItemNumber_2, 1);
2227 markers.splice(fld_fieldArrayItemNumber_2, 1);
2228 //reset variable
2229 fld_fieldArrayItemNumber_2 = 0;
2230
2231 if (data) {
2232 removeStatus();
2233 displaySuccessMsg(txtFd19);
2234 $("#fieldInfo").empty();
2235 //closetab($("#fieldInfo")); v2 - ui
2236 removeFieldItem(id);
2237 }
2238 else {
2239 removeStatus();
2240 displayErrMsg(txtFd18);
2241 }
2242 })
2243 .fail(function () {
2244 removeStatus();
2245 displayErrMsg(txtFd18);
2246 });
2247 }
2248}
2249
2250function insertNewFieldItem(fieldId, fieldName) {
2251 if ($(".no_field_for_farm").length > 0) {
2252 $(".no_field_for_farm").remove();
2253 }
2254
2255 var newOption = "<li id=\"f_" + fieldId + "\" class=\"field_item\">" + fieldName + "</li><li class=\"fieldInfo\" rel=\"" + fieldId + "\"></li>";
2256
2257 $(".field_list_items").append(newOption);
2258
2259 displayLeftDetailsPanel(false);
2260 $('.add_new_field_item').removeClass("disabledLikeAButton");
2261}
2262
2263function removeFieldItem(fieldId) {
2264
2265 //this is fallback code fromm mf2 v1 - ui
2266 $(".field_item").each(function () {
2267 if ($(this).attr("id").split("_")[1] == fieldId) {
2268 $(this).remove()
2269 }
2270 })
2271
2272 $(".field_item_selected").remove();
2273
2274 $(".fieldInfo").each(function () {
2275 if ($(this).attr("rel") == fieldId) {
2276 $(this).remove()
2277 }
2278 })
2279
2280 ////v2 - ui
2281 ////if ($(".field_item").length == 0) {
2282 //// $(".dropdown_field_menu").prepend("<li class=\"no-field no_field_for_farm\">" + txtFd17 + "</li>");
2283 ////}
2284}
2285
2286function resetPolyObj(obj) {
2287
2288 var color = crp_getFieldFillColor(obj.get("id"));
2289
2290 obj.setOptions({
2291 editable: false,
2292 strokeColor: '#4fde47',
2293 strokeOpacity: 1,
2294 strokeWeight: 2,
2295 fillColor: color,
2296 fillOpacity: 0.45
2297 });
2298}
2299
2300function isJson(str) {
2301 try {
2302 JSON.parse(str);
2303 } catch (e) {
2304 return false;
2305 }
2306 return true;
2307}
2308
2309
2310var fld_fieldIdArr = [];
2311var fld_disableClick = false;
2312
2313
2314function fld_loadFieldBoundary() {
2315 if (fld_fieldIdArr.length > 0) {
2316 $.ajax({
2317 type: "POST",
2318 url: urlPrepend + "/fielddata/boundary",
2319 data: { id: fld_fieldIdArr.pop() },
2320 }).done(function (data) {
2321 if (data.length > 0) {
2322
2323 var t = JSON.parse(data);
2324 if (t.length == 1) {
2325 //field point no boundary.
2326 fld_displayFieldPoints(t[0].lat, t[0].lng, t[0].fieldName, t[0].fieldId);
2327 }
2328 else {
2329 fld_drawField(data);
2330 }
2331
2332 fld_loadFieldBoundary();
2333
2334 if (data.length > 2) {
2335 //user has field if in url
2336 if (JSON.parse(data)[0].fieldId == getFieldId()) {
2337 $(".field_item ").each(function () {
2338 if ($(this).attr("id").split('_')[1] == getFieldId()) {
2339 $(this).addClass("field_item_selected");
2340 getFieldNoCache($(this).attr("id").split("_")[1]);
2341
2342
2343 for (var i = 0; i < polygonsArray.length; i++) {
2344 if (polygonsArray[i].get("id") == getFieldId()) {
2345 polygonsArray[i].setOptions({
2346 highlight: true,
2347 fillColor: '#3c2668',
2348 strokeColor: '#0000ff',
2349 strokeOpacity: 0.8,
2350 strokeWeight: 1.5
2351 });
2352 }
2353 }
2354
2355 var container = $(".left_panel_content"),
2356 scrollTo = $("#f_" + getFieldId());
2357 container.animate({
2358 scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
2359 });
2360
2361 }
2362 });
2363
2364 $(".fieldInfo").each(function () {
2365 if ($(this).attr("rel") == getFieldId()) {
2366 $(this).show();
2367 }
2368 });
2369 }
2370 }
2371 }
2372 });
2373 }
2374 else {
2375 setSeasonDDLStyle();
2376 removeStatus();
2377 crp_addCropColoringToFields();
2378
2379 }
2380}
2381
2382function fld_displayFieldPoints(lat, lng, name, fieldId) {
2383
2384 //add label to point
2385 var label = new InfoBox({
2386 content: name,
2387 boxStyle: {
2388 border: "1px solid black",
2389 textAlign: "center",
2390 backgroundColor: "white",
2391 fontSize: "8pt",
2392 padding: "0",
2393 whiteSpace: "nowrap",
2394 width: calcNameLength(name) + "px",
2395 overflow: "hidden",
2396 textOverflow: "ellipsis"
2397 },
2398 disableAutoPan: true,
2399 position: new google.maps.LatLng(lat, lng),
2400 closeBoxURL: "",
2401 enableEventPropagation: true,
2402 pixelOffset: new google.maps.Size(-18, -3)
2403 });
2404 label.open(map)
2405 fld_fieldPtLabels.push(label);
2406
2407
2408 var marker = new google.maps.Marker({
2409 position: new google.maps.LatLng(lat, lng),
2410 map: map,
2411 draggable: false,
2412 id: fieldId,
2413 icon: new google.maps.MarkerImage("//maps.google.com/mapfiles/ms/icons/yellow.png")
2414 });
2415
2416 google.maps.event.addListener(marker, 'click', function () {
2417
2418 //open up field panel if its not open
2419 if ($(".field_list_title").find('span').hasClass("glyphicon-menu-down")) {
2420 setFieldPanelList();
2421 }
2422
2423
2424 //remove any previous selected
2425 $(".field_item_selected").removeClass("field_item_selected").addClass("field_item");
2426
2427
2428 //find field item.
2429 $(".field_item").each(function () {
2430
2431 if ($(this).attr("id") == "f_" + fieldId) {
2432 $(this).addClass("field_item_selected").removeClass("field_item");
2433
2434 var container = $(".left_panel_content"),
2435 scrollTo = $("#f_" + fieldId);
2436 container.animate({
2437 scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
2438 });
2439 }
2440 else {
2441 $(this).removeClass("field_item_selected");
2442 }
2443 });
2444
2445
2446 //if not field item has been found, the this marker has been added in this session to use field-name.
2447 str = "<span class=\"current_field_area\">Size : 0 Ha</span><span class=\"glyphicon glyphicon-plus-sign\" title=\"" + txtFd8 + "\" id=\"addBoundaryToFieldPt\"></span>";
2448 str += "<p><button id=\"deleteNoBoundaryFieldPt\" class=\"btn-ok btn-danger\" title=\"" + txtFd37 + "\" rel=\"" + fieldId + "\">Delete</button>";
2449 str += "<button id=\"saveFieldBoundaryFieldPt\" class=\"btn-ok btn-success\" rel=\"" + fieldId + "\" disabled=\"disabled\" title=\"" + txtFd7 + "\">" + txtGen15 + "</button></p>";
2450 $(".fieldInfo").each(function () {
2451 if ($(this).attr("rel") == fieldId) {
2452 $(this).empty().html(str).show();
2453 }
2454 else {
2455 $(this).empty().hide();
2456 }
2457 })
2458
2459 $("#f_" + fieldId + " .fieldInfo").empty().html(str).show();
2460 gen_mode_sub = 3;
2461
2462 });
2463
2464 fld_fieldPts.push(marker);
2465
2466}
2467
2468function fld_drawField(data) {
2469
2470
2471 if (data != "") {
2472 var t = JSON.parse(data);
2473 //show legend toogle
2474 $(".legends_toggle_wrapper").show();
2475 $(".field_names_toggle_wrapper").show();
2476
2477
2478 var fieldboundary = new google.maps.MVCArray();
2479 var polygon1stPt = "";
2480 var bStartNewPolygon = false;
2481 var arrHolesMVCArray = []; //this array will contain an array of hole_fieldboundary
2482 var hole_fieldboundary = new google.maps.MVCArray();
2483 var hole_bStartNewPolygon = false;
2484 var fieldId = 0;
2485 var fieldNme = "";
2486 var hole_fieldboundary4directionChk = [];
2487
2488 for (var i = 0; i < t.length; i++) {
2489
2490 if (i == 0) {
2491 fieldId = t[i].fieldId;
2492 fieldNme = t[i].fieldName;
2493 }
2494
2495 if (t[i].ishole == "False") {
2496 //this is a field
2497 fieldboundary.push(new google.maps.LatLng(t[i].lat, t[i].lng));
2498 bStartNewPolygon = true;
2499
2500 }
2501 else {
2502
2503 hole_fieldboundary.push(new google.maps.LatLng(t[i].lat, t[i].lng));
2504 hole_fieldboundary4directionChk.push(new google.maps.LatLng(t[i].lat, t[i].lng));
2505 if (!hole_bStartNewPolygon) {
2506 polygon1stPt = new google.maps.LatLng(t[i].lat, t[i].lng);
2507 hole_bStartNewPolygon = true;
2508 }
2509 else {
2510 if (polygon1stPt.equals(new google.maps.LatLng(t[i].lat, t[i].lng))) {
2511
2512 arrHolesMVCArray.push(hole_fieldboundary);
2513
2514 ////////check direction, do we need to reverse.
2515 //////if (!polygonDirection(hole_fieldboundary4directionChk)) {
2516
2517 ////// //poly is anitclockwise - change direction.
2518 ////// hole_fieldboundary4directionChk.reverse();
2519 ////// arrHolesMVCArray.push(hole_fieldboundary4directionChk);
2520 ////// hole_fieldboundary4directionChk = [];
2521 //////}
2522 //////else {
2523 ////// arrHolesMVCArray.push(hole_fieldboundary);
2524 //////}
2525
2526 //reset
2527 hole_fieldboundary = new google.maps.MVCArray();
2528 hole_bStartNewPolygon = false; //get first point of hole
2529 }
2530 }
2531
2532
2533 if (i == (t[i].length - 1)) {
2534 hole_drawHolePoly(fieldboundary, arrHolesMVCArray, fieldId, fieldNme, fld_disableClick);
2535 }
2536 }
2537
2538 }
2539
2540 if (t.length > 3) {
2541
2542 if ((!hole_bStartNewPolygon) && (arrHolesMVCArray.length == 0)) {
2543 drawPoly(fieldboundary, fieldId, fieldNme, fld_disableClick);
2544 }
2545 if ((arrHolesMVCArray.length > 0) && (i == t.length)) {
2546 hole_drawHolePoly(fieldboundary, arrHolesMVCArray, fieldId, fieldNme, fld_disableClick);
2547 }
2548 }
2549
2550
2551 }
2552}
2553
2554
2555function loadFields(disableClick) {
2556
2557 if ($("#fb1").val() != "") {
2558
2559 fld_fieldIdArr = $("#fb1").val().split('|');
2560 fld_disableClick = disableClick
2561 fld_loadFieldBoundary();
2562 loadStatus("Loading Fields.....");
2563 }
2564
2565
2566
2567 google.maps.event.addListener(map, 'zoom_changed', function () {
2568
2569 var zoomLevel = 16;
2570 if (fieldLabels.length < 5) {
2571 zoomLevel = 14;
2572 }
2573
2574 });
2575}
2576
2577function hole_drawSingleHolePoly(arr, hole, fieldId, fieldName, disableClick) {
2578
2579 var polygon = new google.maps.Polygon({
2580 id: fieldId,
2581 paths: [arr, hole],
2582 class: 'withhole',
2583 map: map,
2584 strokeColor: '#4fde47',
2585 strokeOpacity: 1,
2586 strokeWeight: 2,
2587 fillColor: '#c2c2c2',
2588 fillOpacity: 0.55,
2589 suppressUndo: true
2590 });
2591
2592 if (!disableClick) {
2593 polygon.setOptions({
2594 clickable: true
2595 })
2596 }
2597 else {
2598 polygon.setOptions({
2599 clickable: false
2600 })
2601 }
2602
2603 addPolygonClickEvent(polygon);
2604 addPolygonMouseCoordsData(polygon);
2605 //store polygon in an array
2606 polygonsArray.push(polygon);
2607 setMapBounds(arr);
2608
2609 var tempBounds = new google.maps.LatLngBounds();
2610 for (var i = 0; i < arr.getLength() ; i++) {
2611 tempBounds.extend(arr.getAt(i));
2612 }
2613
2614 setFieldMarker(polygon, tempBounds.getCenter().lat(), tempBounds.getCenter().lng(), fieldName);
2615
2616
2617}
2618
2619function hole_drawHolePoly(arr, hole_arr, fieldId, fieldName, disableClick) {
2620
2621 var polypath = [];
2622 polypath.push(arr);
2623
2624 //are we drawing field in the holes modal?
2625
2626 for (var i = 0; i < hole_arr.length; i++) {
2627 polypath.push(hole_arr[i]);
2628 }
2629
2630 var polygon = new google.maps.Polygon({
2631 id: fieldId,
2632 paths: polypath,
2633 map: map,
2634 class: 'withhole',
2635 strokeColor: '#4fde47',
2636 strokeOpacity: 1,
2637 strokeWeight: 2,
2638 fillColor: '#c2c2c2',
2639 fillOpacity: 0.55,
2640 suppressUndo: true
2641 });
2642
2643
2644 if (!disableClick) {
2645 polygon.setOptions({
2646 clickable: true
2647 })
2648 }
2649 else {
2650 polygon.setOptions({
2651 clickable: false
2652 })
2653 }
2654
2655
2656 addPolygonClickEvent(polygon);
2657 addPolygonMouseCoordsData(polygon);
2658
2659 //store polygon in an array
2660 polygonsArray.push(polygon);
2661 setMapBounds(arr);
2662
2663 var tempBounds = new google.maps.LatLngBounds();
2664 for (var i = 0; i < arr.getLength() ; i++) {
2665 tempBounds.extend(arr.getAt(i));
2666 }
2667
2668 setFieldMarker(polygon, tempBounds.getCenter().lat(), tempBounds.getCenter().lng(), fieldName);
2669
2670
2671}
2672
2673function hole_drawMultiHolePoly(arr, hole_arr, fieldId, fieldName, disableClick) {
2674
2675 var polypath = [];
2676 polypath.push(arr);
2677
2678 //are we drawing field in the holes modal?
2679
2680 for (var i = 0; i < hole_arr.length; i++) {
2681 polypath.push(hole_arr[i]);
2682 }
2683
2684 var polygon = new google.maps.Polygon({
2685 id: fieldId,
2686 paths: polypath,
2687 map: map,
2688 class: 'withhole',
2689 strokeColor: '#0000ff',
2690 strokeOpacity: 0.6,
2691 strokeWeight: 1,
2692 fillColor: '#FF0400',
2693 fillOpacity: 0.35,
2694 suppressUndo: true
2695 });
2696
2697
2698 if (!disableClick) {
2699 polygon.setOptions({
2700 clickable: true
2701 })
2702 }
2703 else {
2704 polygon.setOptions({
2705 clickable: false
2706 })
2707 }
2708
2709
2710 addPolygonClickEvent(polygon);
2711 addPolygonMouseCoordsData(polygon);
2712 //store polygon in an array
2713 polygonsArray.push(polygon);
2714 setMapBounds(arr);
2715
2716 var tempBounds = new google.maps.LatLngBounds();
2717 for (var i = 0; i < arr.getLength() ; i++) {
2718 tempBounds.extend(arr.getAt(i));
2719 }
2720
2721 setFieldMarker(polygon, tempBounds.getCenter().lat(), tempBounds.getCenter().lng(), fieldName);
2722
2723
2724}
2725
2726function toggleLegendNameLabels(label, toggle, isField) {
2727 if (!toggle) {
2728 // if (map.getZoom() <= 14)
2729 // {
2730 if (isField) {
2731 gen_fieldName_toggle = false;
2732 }
2733 else {
2734 gen_layerName_toggle = false;
2735 }
2736
2737 // changeLabelSize(label, "44px");
2738 // }
2739 }
2740 else {
2741 if (isField) {
2742 gen_fieldName_toggle = true;
2743 }
2744 else {
2745 gen_layerName_toggle = true;
2746 }
2747
2748 //changeLabelSize(label, calcNameLength(label.content_) + "px");
2749 //label.setOptions({
2750 // boxStyle: {
2751 // border: "1px solid black",
2752 // textAlign: "center",
2753 // backgroundColor: "white",
2754 // fontSize: "8pt",
2755 // padding: "0 2px 0 2px",
2756 // whiteSpace: "nowrap",
2757 // overflow: "hidden",
2758 // textOverflow: "ellipsis"
2759 // },
2760 //})
2761 }
2762
2763}
2764
2765function calcNameLength(str) {
2766 var chars = str.split('');
2767 var score = 0;
2768 if (chars.length > 3) {
2769 for (var i = 0; i < chars.length; i++) {
2770 switch (chars[i]) {
2771
2772 case "A":
2773 case "B":
2774 case "C":
2775 case "D":
2776 case "E":
2777 case "F":
2778 case "G":
2779 case "H":
2780 case "I":
2781 case "J":
2782 case "K":
2783 case "L":
2784 case "M":
2785 case "N":
2786 case "O":
2787 case "P":
2788 case "Q":
2789 case "R":
2790 case "S":
2791 case "T":
2792 case "U":
2793 case "V":
2794 case "X":
2795 case "Y":
2796 case "Z":
2797 score += 20;
2798 break;
2799 case "0":
2800 case "2":
2801 case "3":
2802 case "4":
2803 case "5":
2804 case "6":
2805 case "7":
2806 case "8":
2807 case "9":
2808 case "0":
2809 score += 9;
2810 break;
2811 case "a":
2812 case "b":
2813 case "c":
2814 case "d":
2815 case "e":
2816 case "f":
2817 case "g":
2818 case "h":
2819 case "k":
2820 case "n":
2821 case "o":
2822 case "p":
2823 case "q":
2824 case "r":
2825 case "s":
2826 case "t":
2827 case "u":
2828 case "v":
2829 case "x":
2830 case "y":
2831 case "z":
2832
2833 score += 7;
2834 break;
2835 case "i":
2836 case "j":
2837 case "l":
2838 case "1":
2839 score += 5;
2840 break;
2841 case "m":
2842 case "w":
2843 score += 10;
2844 break;
2845 case " ":
2846 case "/":
2847 score += 11;
2848 break;
2849 default:
2850 score += 5;
2851 break;
2852
2853 }
2854 }
2855 }
2856 else {
2857 if (chars.length < 2) {
2858 score = 34;
2859 }
2860 if (chars.length <= 3) {
2861 score = 44;
2862 }
2863 }
2864
2865
2866 return score;
2867}
2868
2869//function changeLabelSize(label, wdth) {
2870
2871// label.setOptions({
2872// boxStyle: {
2873// border: "1px solid black",
2874// textAlign: "center",
2875// backgroundColor: "white",
2876// fontSize: "8pt",
2877// padding: "0",
2878// whiteSpace: "nowrap",
2879// width: wdth,
2880// overflow: "hidden",
2881// textOverflow: "ellipsis"
2882// },
2883// })
2884//}
2885
2886function drawPoly(arr, fieldId, fieldName, disableClick) {
2887 var polygon = new google.maps.Polygon({
2888 id: fieldId,
2889 paths: arr,
2890 map: map,
2891 strokeColor: '#4fde47',
2892 strokeOpacity: 1,
2893 strokeWeight: 2,
2894 fillColor: '#c2c2c2',
2895 fillOpacity: 0.45
2896 });
2897
2898 if (!disableClick) {
2899 polygon.setOptions({
2900 clickable: true
2901 })
2902 }
2903 else {
2904 polygon.setOptions({
2905 clickable: false
2906 })
2907 }
2908
2909 addPolygonClickEvent(polygon);
2910 addPolygonMouseCoordsData(polygon);
2911 ////onclick zoom into field
2912
2913
2914
2915 //store polygon in an array
2916 polygonsArray.push(polygon);
2917 setMapBounds(arr);
2918
2919 var tempBounds = new google.maps.LatLngBounds();
2920 for (var i = 0; i < arr.getLength() ; i++) {
2921 tempBounds.extend(arr.getAt(i));
2922 }
2923
2924 setFieldMarker(polygon, tempBounds.getCenter().lat(), tempBounds.getCenter().lng(), fieldName);
2925 //setFieldMarker(arr)
2926}
2927
2928function setFieldMarker(polygon, lat, lng, fieldName) {
2929
2930 var realPosition = setMarkerPositionWithinPolygon(lat, lng, polygon);
2931
2932 infowindow = new google.maps.InfoWindow();
2933 var marker = new google.maps.Marker({
2934 position: realPosition,
2935 map: map,
2936 title: fieldName,
2937 icon: new google.maps.MarkerImage(icon)
2938 });
2939 marker.setMap(null);
2940
2941 markers.push(marker);
2942
2943 fieldLabels.push(new InfoBox({
2944 content: fieldName,
2945 boxStyle: {
2946 border: "1px solid black",
2947 textAlign: "center",
2948 backgroundColor: "white",
2949 fontSize: "8pt",
2950 padding: "1px",
2951 whiteSpace: "nowrap",
2952 overflow: "hidden",
2953 textOverflow: "ellipsis",
2954 width: calcNameLength(fieldName) + "px"
2955 },
2956 disableAutoPan: true,
2957 pixelOffset: new google.maps.Size(-10, 0),
2958 position: realPosition,
2959 closeBoxURL: "",
2960 isHidden: false,
2961 enableEventPropagation: true
2962 }));
2963
2964 // do not display labels anymore
2965 // fieldLabels[fieldLabels.length - 1].open(map);
2966}
2967
2968function returnRandomPolygonPoint(thisPoly) {
2969 var p = thisPoly.getPath();
2970 var max = p.length - 1;
2971 var random = Math.floor(Math.random() * (max - 1) + 1);
2972 var pt = p.getAt(random);
2973 return pt;
2974}
2975
2976function GetCentroid(paths) {
2977 var f;
2978 var x = 0;
2979 var y = 0;
2980 var nPts = paths.length - 1;
2981 var j = nPts - 1;
2982 var area = 0;
2983
2984
2985 for (var i = 0; i < nPts; j = i++) {
2986
2987 var pt1 = paths.getAt(i);
2988 var pt2 = paths.getAt(j);
2989
2990 f = pt1.lat() * pt2.lng() - pt2.lat() * pt1.lng();
2991
2992 x += (pt1.lat() + pt2.lat()) * f;
2993 y += (pt1.lng() + pt2.lng()) * f;
2994
2995 area += pt1.lat() * pt2.lng();
2996 area -= pt1.lng() * pt2.lat();
2997 }
2998 area /= 2;
2999 f = area * 6;
3000 return new google.maps.LatLng(x / f, y / f);
3001}
3002
3003//********** poly with holes code START ********////
3004
3005var holes_undoIcon = urlPrepend + '/content/images/map-undo-icon-active.png';
3006var holes_undoIconOver = urlPrepend + '/content/images/map-undo-icon-over.png';
3007
3008var holes_deleteIcon = urlPrepend + '/content/images/map-delete-icon-active.png';
3009var holes_deleteIconOver = urlPrepend + '/content/images/map-delete-icon-over.png';
3010var holes_markers = [];
3011
3012function MVCArrayBinder(mvcArray) {
3013 this.array_ = mvcArray;
3014}
3015MVCArrayBinder.prototype = new google.maps.MVCObject();
3016MVCArrayBinder.prototype.get = function (key) {
3017 if (!isNaN(parseInt(key))) {
3018 return this.array_.getAt(parseInt(key));
3019 } else {
3020 this.array_.get(key);
3021 }
3022}
3023
3024MVCArrayBinder.prototype.set = function (key, val) {
3025 if (!isNaN(parseInt(key))) {
3026 this.array_.setAt(parseInt(key), val);
3027 } else {
3028 this.array_.set(key, val);
3029 }
3030}
3031
3032function deleteMark(evt) {
3033 var minDist = Number.MAX_VALUE;
3034 var minPathIdx = -1;
3035 var minIdx = -1;
3036 var i, j;
3037 for (i = 0; i < editedObj.getPaths().getLength() ; i++) {
3038 for (j = 0; j < editedObj.getPaths().getAt(i).getLength() ; j++) {
3039 var distance = google.maps.geometry.spherical.computeDistanceBetween(evt.latLng, editedObj.getPaths().getAt(i).getAt(j));
3040 if (distance < minDist) {
3041 minDist = distance;
3042 minPathIdx = i;
3043 minIdx = j;
3044 }
3045 if (distance < 10) {
3046 //document.getElementById('info').innerHTML = "deleted path=" + i + " idx=" + j + " dist<10 minDist=" + minDist + " meters";
3047 editedObj.getPaths().getAt(i).removeAt(j);
3048 break;
3049 }
3050 }
3051 }
3052 if ((i == editedObj.getPaths().getLength()) && (j == editedObj.getPaths(i - 1).getLength())) {
3053 editedObj.getPaths().getAt(minPathIdx).removeAt(minIdx);
3054 // document.getElementById('info').innerHTML = "deleted path=" + minPathIdx + " idx=" + minIdx + " dist=" + minDist + " meters";
3055 }
3056 this.setMap(null);
3057}
3058
3059var hole_previousMarker;
3060
3061function hole_markerDragStart(mark) {
3062
3063 google.maps.event.addListener(mark, "dragstart", function () {
3064 //grab this point to remember it incase we need to do an undo for this marker.
3065 hole_previousMarker = new google.maps.LatLng(this.getPosition().lat(), this.getPosition().lng());
3066 });
3067}
3068
3069function hole_markerMouseDwn(mark) {
3070 google.maps.event.addListener(mark, "mousedown", function () {
3071 hole_previousMarker = new google.maps.LatLng(this.getPosition().lat(), this.getPosition().lng());
3072 });
3073}
3074
3075function hole_markerDragEnd(mark, obj, i) {
3076
3077 google.maps.event.addListener(mark, "dragend", function () {
3078
3079 //showSaveButton();
3080 hideNewPtMarkers();
3081
3082 var undoMarker = holes_undoMarkerIcon(this.get("id"), this.getPosition(), holes_undoIcon);
3083 holes_markers.push(undoMarker);
3084 var deleteMarker = holes_deleteMarkerIcon(this.get("id"), this.getPosition(), holes_deleteIcon);
3085 holes_markers.push(deleteMarker);
3086
3087 google.maps.event.addListener(undoMarker, 'mouseover', function () {
3088 undoMarker.setOptions({
3089 icon: {
3090 url: holes_undoIconOver,
3091 size: new google.maps.Size(36, 27),
3092 origin: new google.maps.Point(0, 0),
3093 anchor: new google.maps.Point(-4, 12)
3094 }
3095 })
3096 });
3097
3098 google.maps.event.addListener(undoMarker, 'mouseout', function () {
3099 undoMarker.setOptions({
3100 icon: {
3101 url: holes_undoIcon,
3102 size: new google.maps.Size(36, 27),
3103 origin: new google.maps.Point(0, 0),
3104 anchor: new google.maps.Point(-4, 12)
3105 }
3106 })
3107 setInterval(function () { undoMarker.setMap(null) }, 10000);
3108 });
3109
3110 google.maps.event.addListener(undoMarker, 'click', function () {
3111
3112 deleteMarker.setMap(null);
3113 undoMarker.setMap(null);
3114
3115 for (var j = 0; j < obj.getPaths().getAt(i).getLength() ; j++) {
3116 //go through markers and find the one we need to move.
3117 if (obj.markers[i][j].id === this.get("id")) {
3118
3119 obj.markers[i][j].setPosition(hole_previousMarker);
3120 mark.bindTo('position', obj["binder" + i], (j).toString());
3121 }
3122 }
3123 });
3124
3125 google.maps.event.addListener(deleteMarker, 'mouseover', function () {
3126 deleteMarker.setOptions({
3127 icon: {
3128 url: holes_deleteIconOver,
3129 size: new google.maps.Size(36, 27),
3130 origin: new google.maps.Point(0, 0),
3131 anchor: new google.maps.Point(-4, -12)
3132 }
3133 })
3134 });
3135
3136 google.maps.event.addListener(deleteMarker, 'mouseout', function () {
3137 deleteMarker.setOptions({
3138 icon: {
3139 url: holes_deleteIcon,
3140 size: new google.maps.Size(36, 27),
3141 origin: new google.maps.Point(0, 0),
3142 anchor: new google.maps.Point(-4, -12)
3143 }
3144 })
3145 });
3146
3147 google.maps.event.addListener(deleteMarker, 'click', function () {
3148
3149 deleteMarker.setMap(null);
3150 undoMarker.setMap(null);
3151 for (var j = 0; j < obj.getPaths().getAt(i).getLength() ; j++) {
3152 //go through markers and find the one we need to move.
3153 if (obj.markers[i][j].id === this.get("id")) {
3154 obj.getPaths().getAt(i).removeAt(j);
3155 obj.markers[i][j].setMap(null);
3156 }
3157 }
3158 });
3159 });
3160}
3161
3162function holes_deleteMarkerIcon(id, position, icon) {
3163
3164 return (new google.maps.Marker({
3165 map: map,
3166 position: position,
3167 icon: {
3168 url: icon,
3169 size: new google.maps.Size(36, 27),
3170 origin: new google.maps.Point(0, 0),
3171 anchor: new google.maps.Point(-4, -12)
3172 },
3173 id: id
3174 }));
3175}
3176
3177function holes_undoMarkerIcon(id, position, icon) {
3178
3179 return (new google.maps.Marker({
3180 map: map,
3181 position: position,
3182 icon: {
3183 url: icon,
3184 size: new google.maps.Size(36, 27),
3185 origin: new google.maps.Point(0, 0),
3186 anchor: new google.maps.Point(-4, 12)
3187 },
3188 id: id
3189 }));
3190}
3191
3192function resetEditField(obj, i) {
3193
3194 obj["binder" + i] = new MVCArrayBinder(obj.getPaths().getAt(i));
3195 obj.markers[i] = [];
3196
3197
3198 for (var j = 0; j < obj.getPaths().getAt(i).getLength() ; j++) {
3199
3200 var mark = new google.maps.Marker({
3201 map: map,
3202 icon: {
3203 path: google.maps.SymbolPath.CIRCLE,
3204 scale: 5,
3205 strokeWeight: 5,
3206 strokeColor: 'red',
3207 fillColor: 'yellow',
3208 fillOpacity: 0.9
3209 },
3210 draggable: true,
3211 position: obj.getPaths().getAt(i).getAt(j),
3212 id: j
3213 });
3214
3215 obj.markers[i][j] = mark;
3216 mark.bindTo('position', obj["binder" + i], (j).toString());
3217 google.maps.event.addListener(mark, "rightclick", deleteMark);
3218 // mark.bindTo("position", poly.getPaths().getAt(i).getAt(j));
3219
3220 hole_markerDragStart(mark);
3221 hole_markerMouseDwn(mark);
3222 hole_markerDragEnd(mark, obj, i);
3223
3224
3225 }
3226
3227 google.maps.event.addListener(obj.getPaths().getAt(i), 'insert_at', function (index) {
3228
3229 //showSaveButton();
3230 //hide any markers
3231 hideNewPtMarkers();
3232
3233 //unbind all elements
3234 for (var j = 0; j < obj.getPaths().getAt(i).getLength() - 1 ; j++) {
3235 obj["binder" + i].unbind((j).toString());
3236 obj.markers[i][j].setMap(null);
3237 obj.markers[i][j] = [];
3238 }
3239
3240 obj.markers[i] = [];
3241
3242 for (var j = 0; j < obj.getPaths().getAt(i).getLength() ; j++) {
3243 var mark = new google.maps.Marker({
3244 map: map,
3245 icon: {
3246 path: google.maps.SymbolPath.CIRCLE,
3247 scale: 5,
3248 strokeWeight: 5,
3249 strokeColor: 'red',
3250 fillColor: 'yellow',
3251 fillOpacity: 0.9
3252 },
3253 draggable: true,
3254 position: obj.getPaths().getAt(i).getAt(j),
3255 id: j
3256 });
3257
3258 mark.bindTo('position', obj["binder" + i], (j).toString());
3259 obj.markers[i][j] = mark;
3260
3261 hole_markerDragStart(mark);
3262 hole_markerMouseDwn(mark);
3263 google.maps.event.addListener(mark, "rightclick", deleteMark);
3264
3265 google.maps.event.addListener(mark, "dragend", function () {
3266
3267 //hide any markers
3268 hideNewPtMarkers();
3269
3270 var undoMarker = holes_undoMarkerIcon(this.get("id"), this.getPosition(), holes_undoIcon);
3271 holes_markers.push(undoMarker);
3272 var deleteMarker = holes_deleteMarkerIcon(this.get("id"), this.getPosition(), holes_deleteIcon);
3273 holes_markers.push(deleteMarker);
3274
3275 google.maps.event.addListener(deleteMarker, 'click', function () {
3276 deleteMarker.setMap(null);
3277 undoMarker.setMap(null);
3278 for (var j = 0; j < obj.getPaths().getAt(i).getLength() ; j++) {
3279 //go through markers and find the one we need to move.
3280 if (obj.markers[i][j].id === this.get("id")) {
3281 obj.getPaths().getAt(i).removeAt(j);
3282 obj.markers[i][j].setMap(null);
3283 }
3284
3285 }
3286 });
3287
3288 google.maps.event.addListener(undoMarker, 'click', function () {
3289 undoMarker.setMap(null);
3290 deleteMarker.setMap(null);
3291 for (var j = 0; j < obj.getPaths().getAt(i).getLength() ; j++) {
3292 //go through markers and find the one we need to move.
3293 if (obj.markers[i][j].id === this.get("id")) {
3294 obj.markers[i][j].setPosition(hole_previousMarker);
3295 }
3296 editedObj.markers[i][j].setMap(null);
3297 }
3298 resetEditField(obj, i);
3299 });
3300
3301 google.maps.event.addListener(deleteMarker, 'mouseover', function () {
3302 deleteMarker.setOptions({
3303 icon: {
3304 url: holes_deleteIconOver,
3305 size: new google.maps.Size(36, 27),
3306 origin: new google.maps.Point(0, 0),
3307 anchor: new google.maps.Point(-4, -12)
3308 }
3309 })
3310 });
3311
3312 google.maps.event.addListener(deleteMarker, 'mouseout', function () {
3313 deleteMarker.setOptions({
3314 icon: {
3315 url: holes_deleteIcon,
3316 size: new google.maps.Size(36, 27),
3317 origin: new google.maps.Point(0, 0),
3318 anchor: new google.maps.Point(-4, -12)
3319 }
3320 })
3321 });
3322
3323 google.maps.event.addListener(undoMarker, 'mouseover', function () {
3324 undoMarker.setOptions({
3325 icon: {
3326 url: holes_undoIconOver,
3327 size: new google.maps.Size(36, 27),
3328 origin: new google.maps.Point(0, 0),
3329 anchor: new google.maps.Point(-4, 12)
3330 }
3331 })
3332 });
3333
3334 google.maps.event.addListener(undoMarker, 'mouseout', function () {
3335 undoMarker.setOptions({
3336 icon: {
3337 url: holes_undoIcon,
3338 size: new google.maps.Size(36, 27),
3339 origin: new google.maps.Point(0, 0),
3340 anchor: new google.maps.Point(-4, 12)
3341 }
3342 })
3343 //// setInterval(function () { marker.setMap(null) }, 3000);
3344 });
3345
3346 });
3347 }
3348 });
3349}
3350
3351function resetMultiPathPolyObj(obj) {
3352
3353 for (var i = 0; i < obj.getPaths().getLength() ; i++) {
3354 for (var j = 0; j < obj.getPaths().getAt(i).getLength() ; j++) {
3355 obj.markers[i][j].setMap(null);
3356 }
3357 }
3358
3359 obj.setOptions({
3360 editable: false,
3361 fillColor: '#FF0400',
3362 strokeColor: '#0000ff',
3363 strokeOpacity: 0.6,
3364 strokeWeight: 1,
3365 fillOpacity: 0.35
3366 });
3367}
3368
3369
3370function hole_saveBoundaryChanges() {
3371 var jsonStart = "";
3372 var json = ""
3373 var obj = editedObj;
3374 var mainpolyArea = 0;
3375 var is_hole = false;
3376
3377 loadStatus("Saving Boundary Data");
3378
3379 for (var i = 0; i < editedObj.getPaths().getLength() ; i++) {
3380 //calculate new area of polygon
3381 var area = google.maps.geometry.spherical.computeArea(obj.getPaths().getAt(i), 6371);
3382 area = area * 100;
3383 //update area size in field tab (on left side)
3384 if (i == 0) {
3385 mainpolyArea = area;
3386 }
3387 else {
3388 mainpolyArea = mainpolyArea - area;
3389 }
3390
3391 if (i > 0) { is_hole = true; }
3392
3393 json += "{\"points\":[";
3394
3395 var hole_firstPolyPt = new google.maps.MVCArray();
3396
3397 for (var j = 0; j < obj.getPaths().getAt(i).getLength() ; j++) {
3398
3399 json += "{\"lat\":\"" + obj.getPaths().getAt(i).getAt(j).lat() + "\",\"lng\":\"" + obj.getPaths().getAt(i).getAt(j).lng() + "\",\"ishole\":\"" + is_hole + "\"}";
3400
3401 if (is_hole && j == 0) {
3402 //get first coords incase we need to close off polygon
3403 hole_firstPolyPt = new google.maps.LatLng(obj.getPaths().getAt(i).getAt(j).lat(), obj.getPaths().getAt(i).getAt(j).lng());
3404 }
3405 else {
3406 if (j == obj.getPaths().getAt(i).getLength() - 1 && is_hole) {
3407 hole_lastPolyPt = new google.maps.LatLng(obj.getPaths().getAt(i).getAt(j).lat(), obj.getPaths().getAt(i).getAt(j).lng());
3408 if (hole_lastPolyPt.equals(hole_firstPolyPt)) {
3409 //add last point in to close off polygon.
3410 }
3411 else {
3412 //the first and last point do not match so add the first point as a final one to close the polygon
3413 json += ",{\"lat\":\"" + hole_firstPolyPt.lat() + "\",\"lng\":\"" + hole_firstPolyPt.lng() + "\",\"ishole\":\"" + is_hole + "\"}";
3414 }
3415 }
3416 }
3417 if (j < obj.getPaths().getAt(i).getLength() - 1) {
3418 json += ",";
3419 }
3420 }
3421
3422 json += "]}";
3423
3424 if (i < editedObj.getPaths().getLength() - 1) {
3425 json += ",";
3426 }
3427 }
3428
3429 if (json != "") {
3430
3431 json += "]";
3432
3433 jsonStart = "[{\"size\": \"" + mainpolyArea.toFixed(2) + "\"},";
3434
3435 $.ajax({
3436 type: "POST",
3437 url: urlPrepend + "/fielddata/edit-multi-" + editedObj.get("id"),
3438 data: { strJson: jsonStart + json }
3439 })
3440 .done(function (data) {
3441 if (data) {
3442 resetPolyObj(editedObj);
3443 removeNewPtMarkers(editedObj);
3444 //lets loop through polygon array and update path
3445 for (var i = 0; i < polygonsArray.length; i++) {
3446 if (polygonsArray[i].get("id") == editedObj.get("id")) {
3447 polygonsArray[i].setPaths(editedObj.getPath());
3448 }
3449 }
3450
3451 editedObj = null;
3452 removeStatus();
3453 hideSaveFieldButton();
3454 hideCancel();
3455 $("#editField").removeClass("editmode");
3456
3457 VRA_linkCheck(area.toFixed(2));
3458 }
3459 else {
3460 $("#alertWrapper").append("<div class=\"alert-overlay modal-backdrop fade in\"></div>");
3461 $("#genDangerAlert").show().find("span").first().empty().html("There was an error saving data. Refresh the page and try again.");
3462 }
3463 });
3464 //update area size in field tab (on left side)
3465 $(".current_field_area").empty().text(mainpolyArea.toFixed(2) + " Ha");
3466 }
3467}
3468
3469function removeNewPtMarkers(obj) {
3470
3471 if (holes_markers.length > 0) {
3472 //hide all markers
3473 for (var k = 0; k < holes_markers.length; k++) {
3474 holes_markers[k].setMap(null);
3475 }
3476 }
3477
3478 for (var i = 0; i < obj.getPaths().getLength() ; i++) {
3479 for (var j = 0; j < obj.getPaths().getAt(i).getLength() ; j++) {
3480 //remove all markers.
3481 obj.markers[i][j].setMap(null);
3482 }
3483 }
3484}
3485
3486function hideNewPtMarkers() {
3487 if (holes_markers.length > 0) {
3488 //hide all markers
3489 for (var k = 0; k < holes_markers.length; k++) {
3490 holes_markers[k].setMap(null);
3491 }
3492 }
3493}
3494
3495function generateCicleHole(clickpt) {
3496 //get centre point of circle
3497 var drawingManager = new google.maps.drawing.DrawingManager({
3498 drawingMode: google.maps.drawing.OverlayType.CIRCLE,
3499 drawingControl: false,
3500 drawingControlOptions: {
3501 drawingModes: ['circle']
3502 },
3503
3504 circleOptions: {
3505 fillColor: '#ffff00',
3506 fillOpacity: 1,
3507 strokeWeight: 5,
3508 clickable: false,
3509 editable: true,
3510 zIndex: 1
3511 }
3512 });
3513 drawingManager.setMap(map);
3514}
3515
3516//********** poly with holes code END ********////
3517
3518var editedObj;
3519
3520function editField_v2(obj) {
3521 editedObj = obj;
3522 if (obj.getPaths().getLength() > 1) {
3523
3524 } else {
3525 // console.log("1");
3526 }
3527}
3528
3529
3530function editField(obj) {
3531
3532 editedObj = obj;
3533
3534 //if this field has holes then add listeners to points of holes.
3535 if (obj.getPaths().getLength() > 1) {
3536
3537 obj.markers = [];
3538
3539 for (var i = 0; i < obj.getPaths().getLength() ; i++) {
3540 //add own points and bind them to path so that we have control of the point to allow it to be edited.
3541 resetEditField(obj, i);
3542 }
3543
3544 // set properties of polygon
3545 obj.setOptions({
3546 editable: true,
3547 fillColor: '#000000'
3548 })
3549 }
3550 else {
3551
3552 addDeleteButton(obj);
3553 //add event to all points to allow for deletion of selected point.
3554 google.maps.event.addListener(obj, 'rightclick', function (event) {
3555 if (event.vertex == undefined) {
3556 return;
3557 } else {
3558 var path = obj.getPath();
3559 path.removeAt(event.vertex);
3560 }
3561 });
3562
3563 //New point
3564 google.maps.event.addListener(obj.getPath(), 'insert_at', function (index) {
3565 if (!mousestatus) {
3566 pointUpdated(index, path)
3567
3568 //var intersects = fld_fieldBoundaryInsertsect(obj.getPath());
3569 //if (intersects && intersects.length) {
3570 // //alert user and remove current polygon
3571
3572 // displayErrMsg(txtFd21)
3573 //}
3574 //else {
3575 if (!$("#saveEditedField").is(":visible")) {
3576 //showSaveButton();
3577 displayCancel();
3578 }
3579 //}
3580 }
3581 });
3582
3583 //Point was removed
3584 google.maps.event.addListener(obj.getPath(), 'remove_at', function (index) {
3585 pointUpdated(index, path);
3586 //var intersects = fld_fieldBoundaryInsertsect(obj.getPath());
3587 //if (intersects && intersects.length) {
3588 // //alert user and remove current polygon
3589
3590 // displayErrMsg(txtFd21)
3591 //}
3592 //else {
3593 if (!$("#saveEditedField").is(":visible")) {
3594 // showSaveButton();
3595 displayCancel();
3596 }
3597 //}
3598 });
3599
3600 //Point was moved
3601 google.maps.event.addListener(obj.getPath(), 'set_at', function () {
3602
3603 //var intersects = fld_fieldBoundaryInsertsect(obj.getPath());
3604 //if (intersects && intersects.length) {
3605 // //alert user and remove current polygon
3606
3607 // displayErrMsg(txtFd21)
3608 //}
3609 //else {
3610 if (!$("#saveEditedField").is(":visible")) {
3611 // showSaveButton();
3612 displayCancel();
3613 }
3614 //}
3615 });
3616
3617
3618 // set properties of polygon
3619 obj.setOptions({
3620 editable: true,
3621 fillColor: '#000000'
3622 })
3623 //get lat lng corrds of all points
3624 var vertices = obj.getPath();
3625 var latlngbounds = new google.maps.LatLngBounds();
3626 //loop through points and add to latlngbounds
3627 for (var i = 0; i < vertices.getLength() ; i++) {
3628 var xy = vertices.getAt(i);
3629 var coords = vertices.getAt(i);
3630 latlngbounds.extend(coords);
3631 }
3632 //add lat/lng so that the map can zoom into polygon.
3633 map.fitBounds(latlngbounds);
3634 }
3635}
3636
3637function displayCancel() {
3638 if (!$("#cancelChanges").is(":visible")) {
3639 $("#cancelChanges").show();
3640 }
3641}
3642
3643function hideCancel() {
3644 if ($("#cancelChanges").is(":visible")) {
3645 $("#cancelChanges").hide();
3646 }
3647}
3648
3649function checkInPolygon(marker, polygon) {
3650 var infowindow = new google.maps.InfoWindow();
3651 var html = "";
3652 if (google.maps.geometry.poly.containsLocation(marker.getPosition(), polygon)) {
3653 html = "inside polygon";
3654 } else {
3655 html = "outside polygon";
3656 }
3657
3658}
3659
3660function checkInPolygon2(marker, polygon) {
3661
3662 var mainpoly = new google.maps.Polygon({
3663 paths: polygon,
3664 });
3665
3666 if (google.maps.geometry.poly.containsLocation(marker, mainpoly)) {
3667 return true;
3668 } else {
3669 return false;
3670 }
3671}
3672
3673function saveBoundaryChanges() {
3674
3675 loadStatus("Saving Boundary Data");
3676
3677 var str = "";
3678 //get path of polygon to get lat lng coords, pass lat/lng data to ajax post.
3679 //polygon with no holes.
3680 for (var i = 0; i < editedObj.getPath().getLength() ; i++) {
3681 var xy = editedObj.getPath().getAt(i);
3682 str += xy.lat() + ',' + xy.lng() + "|";
3683 }
3684
3685 //calculate new area of polygon
3686 var area = google.maps.geometry.spherical.computeArea(editedObj.getPath(), 6371);
3687 area = area * 100;
3688 //update area size in field tab (on left side)
3689 $(".current_field_area").empty().text(area.toFixed(2) + " Ha");
3690
3691 $.ajax({
3692 type: "POST",
3693 url: urlPrepend + "/fielddata/edit-" + editedObj.get("id"),
3694 data: { coords: str, a: area }
3695 })
3696 .done(function () {
3697
3698 //lets loop through polygon array and update path
3699 for (var i = 0; i < polygonsArray.length; i++) {
3700 if (polygonsArray[i].get("id") == editedObj.get("id")) {
3701 polygonsArray[i].setPaths(editedObj.getPath());
3702 }
3703 }
3704
3705 resetPolyObj(editedObj);
3706 editedObj = null;
3707 removeStatus();
3708 hideSaveFieldButton();
3709 hideCancel();
3710 $("#editField").removeClass("editmode");
3711
3712 VRA_linkCheck(area.toFixed(2));
3713
3714 });
3715
3716}
3717
3718
3719
3720//v2 - ui -- might need to remove this.
3721function highlightSelectedField(fieldId, pan, fieldSize) {
3722
3723
3724 var iMarker = 0;
3725
3726 for (var i = 0; i < polygonsArray.length; i++) {
3727 if (polygonsArray[i].get("id") == fieldId) {
3728 polygonsArray[i].setOptions({
3729 highlight: true,
3730 strokeColor: '#FF0000',
3731 strokeOpacity: 0.8,
3732 strokeWeight: 5
3733 });
3734 if (pan) {
3735 panToField(polygonsArray[i]);
3736 }
3737
3738 if ((fieldSize != null) || (fieldSize == 0)) {
3739 //field size in db is null, but we have polygon points.
3740 //update size on screen and add field icons in panel.
3741 var area = google.maps.geometry.spherical.computeArea(polygonsArray[i].getPath(), 6371);
3742 area = area * 100;
3743 $(".current_field_area").empty().text(area.toFixed(2) + " Ha");
3744 $("#addBoundary").remove();
3745 str = fieldPanelIconContent(fieldId, fieldSize)
3746 //$("#fieldInfo").empty().html(str + $("#fieldInfo").html());
3747 $(".current_field_area").after(str);
3748 //then send an ajax request to update field size in database.
3749 }
3750 }
3751 else {
3752 polygonsArray[i].setOptions({
3753 strokeColor: '#4fde47',
3754 strokeOpacity: 1,
3755 strokeWeight: 2
3756 });
3757 //resetPolyObj(polygonsArray[i]);
3758 }
3759 $("#fieldInfo").addClass("field-has-holes");
3760 }
3761}
3762
3763function unSelectedField(fieldId) {
3764 for (var i = 0; i < polygonsArray.length; i++) {
3765 if (polygonsArray[i].get("id") == fieldId) {
3766 resetPolyObj(polygonsArray[i]);
3767 }
3768 }
3769}
3770
3771function panToField(obj) {
3772 var vertices = obj.getPath();
3773 var latlngbounds = new google.maps.LatLngBounds();
3774 //loop through points and add to latlngbounds
3775 for (var i = 0; i < vertices.getLength() ; i++) {
3776 var xy = vertices.getAt(i);
3777 var coords = vertices.getAt(i);
3778 latlngbounds.extend(coords);
3779 }
3780 //add lat/lng so that the map can zoom into polygon.
3781 map.fitBounds(latlngbounds);
3782}
3783var ogObjCoords;
3784
3785
3786
3787
3788
3789
3790$(document).on("mouseover", ".holes-polygon-g-poly", function () {
3791 $(this).attr("src", urlPrepend + "/Content/images/drawing-polygon-over.png");
3792});
3793
3794$(document).on("mouseout", ".holes-polygon-g-poly", function () {
3795 $(this).attr("src", urlPrepend + "/Content/images/drawing-polygon.png");
3796});
3797
3798$(document).on("mouseover", ".holes-polygon-g-circle", function () {
3799 $(this).attr("src", urlPrepend + "/Content/images/drawing-circle-over.png");
3800});
3801
3802$(document).on("mouseout", ".holes-polygon-g-circle", function () {
3803 $(this).attr("src", urlPrepend + "/Content/images/drawing-circle.png");
3804});
3805
3806$(document).on("click", "#admin_holes_closeModal", function () {
3807 $("#holes_Modal").hide();
3808 removeOverlay();
3809 removeCutouts = [];
3810});
3811
3812$(document).on("click", ".holes-polygon-g-circle", function () {
3813
3814
3815 if (gen_mode_sub == 2) {
3816 removeSingleFieldSampleData();
3817 $("#leftDetailsPanel").hide();
3818 //hide nutrients
3819 $(".fld_recent_sample_nutrients").hide();
3820 }
3821
3822 $("#holes_Modal").show();
3823 $(".google-drawing-tool-wrapper").attr("mode", "genCircle");
3824 $("#holes_Modal .modal-dialog").attr("style", "width:98%;");
3825
3826 if (window.innerHeight < 700) {
3827 $("#holes_ModalMap").attr("style", "height:400px; width:100%; position: relative; overflow: hidden;");
3828 }
3829 if (window.innerHeight > 900) {
3830 $("#holes_ModalMap").attr("style", "height:" + (parseFloat(window.innerHeight) * 0.6) + "px; width:100%; position: relative; overflow: hidden;");
3831 }
3832
3833 displayHoleModalField()
3834});
3835
3836$(document).on("click", ".holes-polygon-g-sq", function () {
3837 $("#holes_Modal").show();
3838 $(".google-drawing-tool-wrapper").attr("mode", "genSq");
3839 displayHoleModalField()
3840});
3841
3842$(document).on("click", ".holes-polygon-g-poly", function () {
3843
3844 if (gen_mode_sub == 2) {
3845 removeSingleFieldSampleData();
3846 $("#leftDetailsPanel").hide();
3847 //hide nutrients
3848 $(".fld_recent_sample_nutrients").hide();
3849 }
3850
3851 $("#holes_Modal").show();
3852 $(".google-drawing-tool-wrapper").attr("mode", "genPoly");
3853 $("#holes_Modal .modal-dialog").attr("style", "width:98%;");
3854
3855 if (window.innerHeight < 700) {
3856 $("#holes_ModalMap").attr("style", "height:400px; width:100%; position: relative; overflow: hidden;");
3857 }
3858 if (window.innerHeight > 900) {
3859 $("#holes_ModalMap").attr("style", "height:" + (parseFloat(window.innerHeight) * 0.6) + "px; width:100%; position: relative; overflow: hidden;");
3860 }
3861
3862 displayHoleModalField()
3863});
3864
3865$(document).on("click", ".layer-item-name", function () {
3866
3867 getLayerItemData($(this).parent(), false);
3868});
3869
3870$(document).on("click", ".layer-item-name-icon", function () {
3871 getLayerItemData($(this).parent(), false);
3872});
3873
3874$(document).on("click", "#deleteField", function () {
3875 $("#confirm-delete").modal('show');
3876 if (gen_mode_sub == 2) {
3877 removeSingleFieldSampleData();
3878 $("#leftDetailsPanel").hide();
3879 //hide nutrients
3880 $(".fld_recent_sample_nutrients").hide();
3881 }
3882
3883});
3884
3885$(document).on("click", "#vraModal", function () {
3886
3887 if (gen_mode_sub == 2) {
3888 removeSingleFieldSampleData();
3889 $("#leftDetailsPanel").hide();
3890 //hide nutrients
3891 $(".fld_recent_sample_nutrients").hide();
3892 }
3893 //edit mode
3894 gen_mode_sub = 4;
3895
3896 vra_populateModal();
3897});
3898
3899$(document).on("click", "#deleteBoundary", function () {
3900 if (gen_mode_sub == 2) {
3901 removeSingleFieldSampleData();
3902 $("#leftDetailsPanel").hide();
3903 //hide nutrients
3904 $(".fld_recent_sample_nutrients").hide();
3905 }
3906 $("#confirm-delete-boundary").modal('show');
3907
3908});
3909
3910$(document).on("click", "#saveChangesToBoundaryModal", function () {
3911 if (editedObj.getPaths().getLength() > 1) {
3912 hole_saveBoundaryChanges();
3913 }
3914 else {
3915 //check for intersects here
3916 var intersects = fld_fieldBoundaryInsertsect(editedObj.getPath());
3917
3918 if (intersects && intersects.length) {
3919 //alert user and remove current polygon
3920 displayErrMsg(txtFd21)
3921 } else {
3922 saveBoundaryChanges();
3923 }
3924 }
3925});
3926
3927$(document).on("click", "#NoChangesToBoundaryModal", function () {
3928
3929 var thisId = editedObj.id;
3930 editedObj.setMap(null)
3931 editedObj = null;
3932
3933 $.ajax({
3934 type: "POST",
3935 url: urlPrepend + "/fielddata/boundary",
3936 data: { id: getFieldId() }
3937 }).done(function (data) {
3938
3939 var t = JSON.parse(data);
3940 var fieldboundary = new google.maps.MVCArray();
3941 for (var j = 0; j < t.length; j++) {
3942 fieldboundary.push(new google.maps.LatLng(t[j].lat, t[j].lng));
3943 }
3944
3945 for (var i = 0; i < polygonsArray.length; i++) {
3946 if (polygonsArray[i].get("id") == thisId) {
3947
3948 if (fieldboundary.length > 0) {
3949
3950 var polygon = new google.maps.Polygon({
3951 id: thisId,
3952 paths: fieldboundary,
3953 map: map,
3954 strokeColor: '#0000ff',
3955 strokeOpacity: 0.6,
3956 strokeWeight: 1,
3957 fillColor: '#FF0400',
3958 fillOpacity: 0.35
3959 });
3960
3961 polygonsArray[i] = polygon;
3962 }
3963
3964 $(".fieldInfo").each(function () {
3965 if ($(this).attr("rel") == thisId) {
3966 $(this).prev().removeClass("field_item_selected").addClass("field_item");
3967 $(this).hide();
3968 }
3969 });
3970
3971 $("#confirm-boundary-changes").modal('hide');
3972 }
3973 }
3974 });
3975})
3976
3977$(document).on("click", "#fieldSendToNsensor_closeModal", function () {
3978 $("#field-send-to-n-sensor").modal('hide');
3979});
3980
3981$(document).on("click", "#sendToNsensor", function () {
3982 $("#field-send-to-n-sensor").modal('show');
3983 $("#field-send-to-n-sensor .modal-dialog").attr("style", "width:90%;");
3984 $("#field-send-to-n-sensor .modal-body").attr("style", "min-height:320px;");
3985});
3986
3987$(document).on("click", "#fieldSendToNsensorSubmit", function () {
3988
3989 $(".send_to_NSensor_error_msg").hide();
3990 if ($("#FieldMachineDeviceList").find(":selected").val() != "") {
3991 $.ajax({
3992 url: genericGetEnvironmentURL() + "Administration/MiFarm/SendFieldBoundariesToPDXFER.aspx?userid=" + $("#MF2Id").val() + "&farmid=" + getFarmId() + "&deviceid=" + $("#FieldMachineDeviceList").find(":selected").val() + "&seasonid=" + $('#customerSeason option:selected').val()
3993 }).done(function (data) {
3994
3995 $("#field-send-to-n-sensor").modal('hide');
3996
3997 if (data.length > 0) {
3998 var t = JSON.parse(data);
3999 if (t.result.toString().search("ERROR") > 0) {
4000 displayErrMsg(t.result);
4001 }
4002 else {
4003 displaySuccessMsg(t.result);
4004 }
4005 }
4006 else {
4007 //error
4008 displayErrMsg("There was an error with your request");
4009 }
4010
4011 });
4012 }
4013 else {
4014 $(".send_to_NSensor_error_msg").show();
4015 }
4016
4017});
4018
4019$(document).on("click", "#moveToField", function () {
4020
4021
4022 //loop through polygon and get id, if it matches with current id then
4023 var fieldboundary = new google.maps.MVCArray();
4024
4025 for (var i = 0; i < polygonsArray.length; i++) {
4026 //match the out current field id
4027 if ((polygonsArray[i].id) == getFieldId()) {
4028 for (var p = 0; p < polygonsArray[i].getPath().getLength() ; p++) {
4029 fieldboundary.push(new google.maps.LatLng(polygonsArray[i].getPath().getAt(p).lat(), polygonsArray[i].getPath().getAt(p).lng()));
4030 }
4031
4032 }
4033 }
4034
4035
4036 field_MapBounds = new google.maps.LatLngBounds();
4037 for (var i = 0; i < fieldboundary.getLength() ; i++) {
4038 field_MapBounds.extend(fieldboundary.getAt(i));
4039 }
4040 map.fitBounds(field_MapBounds);
4041
4042})
4043
4044$(document).on("click", "#downloadShapeFile", function () {
4045
4046 if (gen_mode_sub == 2) {
4047 removeSingleFieldSampleData();
4048 $("#leftDetailsPanel").hide();
4049 //hide nutrients
4050 $(".fld_recent_sample_nutrients").hide();
4051 }
4052
4053 location.href = siteUrl + "Administration/MiFarm/DownloadShapefile.aspx?id=" + getFieldId();
4054});
4055
4056$(document).on("click", "#cancelChanges", function () {
4057
4058
4059 vertices = editedObj.getPath();
4060 // Iterate over the vertices.
4061 for (var i = vertices.length - 1; i > -1; i--) {
4062 vertices.removeAt(i);
4063 }
4064
4065
4066 var arrTemp = ogObjCoords.split("|");
4067 for (var j = 0; j < arrTemp.length; j++) {
4068
4069 latlng = new google.maps.LatLng(arrTemp[j].split(",")[0], arrTemp[j].split(",")[1]);
4070 editedObj.getPath().insertAt(editedObj.getPath().getLength(), latlng);
4071 }
4072
4073 hideSaveFieldButton();
4074 hideCancel();
4075});
4076
4077
4078$(document).on("click", "#delButton", function () {
4079 //taken from the field elements code to remove any fields already drawn
4080 displayLeftDetailsPanel(false); // maybe should use setFieldPanelList instead of the below
4081 chkUserAddingField();
4082 //remove any previous single field sample results
4083 removeSingleFieldSampleData();
4084
4085 ////v2 ui
4086 $(".field_item_selected").removeClass("field_item_selected").addClass("field_item");
4087
4088 ////make sure any previous field detail elements are emptied and closed.
4089 ////remove any highlighting of panels.
4090 $(".field_item").each(function () {
4091 $(this).removeClass("field_item_selected");
4092 $(this).children(0).empty().hide();
4093 });
4094 ///Above taken from field_item click event
4095 deleteSelectedField();
4096
4097});
4098
4099$(document).on("click", "#delBoundaryButton", function () {
4100 deleteSelectedFieldBoundary();
4101});
4102
4103$(document).on("blur", ".current_field_name", function () {
4104 saveFieldname();
4105});
4106
4107$(document).on("click", "#saveEditedField", function () {
4108 if (editedObj.getPaths().getLength() > 1) {
4109 hole_saveBoundaryChanges();
4110 }
4111 else {
4112 //check for intersects here
4113 var intersects = fld_fieldBoundaryInsertsect(editedObj.getPath());
4114
4115 if (intersects && intersects.length) {
4116 //alert user and remove current polygon
4117 displayErrMsg(txtFd21)
4118 } else {
4119 saveBoundaryChanges();
4120 }
4121
4122 }
4123
4124 //update field name
4125 if ($(".field_item_selected").hasClass("field_name_edit_mode")) {
4126 var editedName = $(".field_item_selected").text();
4127 var fieldId = $(".field_item_selected").attr("id").split('_')[1];
4128 if (editedName != "") {
4129 $.ajax({
4130 type: "POST",
4131 url: urlPrepend + "/fielddata/editname-" + fieldId,
4132 data: { fieldName: editedName }
4133 })
4134 //update label name
4135
4136 //loop through polygon and get id, if it matches with current id then
4137 for (var i = 0; i < polygonsArray.length; i++) {
4138 //match the out current field id
4139 if ((polygonsArray[i].id) == fieldId) {
4140 //update label content
4141 fieldLabels[i].setContent(editedName);
4142 fieldLabels[i].setOptions({
4143 boxStyle: {
4144 border: "1px solid black",
4145 textAlign: "center",
4146 backgroundColor: "white",
4147 fontSize: "8pt",
4148 padding: "1px",
4149 whiteSpace: "nowrap",
4150 overflow: "hidden",
4151 textOverflow: "ellipsis",
4152 width: calcNameLength(editedName) + "px"
4153 },
4154 });
4155 }
4156 }
4157 //remove editable attribute
4158 $(".field_item_selected").removeAttr("contenteditable");
4159 }
4160 else {
4161 //display alert
4162 displayErrMsg(txtFd23);
4163 }
4164 }
4165
4166});
4167
4168$(document).on("click", "#newfield", function () {
4169 //Below taken from pin and field functionality for closing pin and previous drawings
4170 //taken from the field elements code to remove any fields already drawn
4171
4172 chkUserAddingField();
4173 //remove any previous single field sample results
4174 removeSingleFieldSampleData();
4175 $('.add_new_field_item').addClass("disabledLikeAButton");
4176 ////v2 ui
4177 $(".field_item_selected").removeClass("field_item_selected").addClass("field_item");
4178
4179 ////make sure any previous field detail elements are emptied and closed.
4180 ////remove any highlighting of panels.
4181 $(".field_item").each(function () {
4182 $(this).removeClass("field_item_selected");
4183 $(this).children(0).empty().hide();
4184 });
4185 ///Above taken from field_item click event
4186
4187 $(".fld_newfield_wo_boundary_field_name").val('');
4188 if ($("#fld_noBoundaryPt_wrapper").is(":visible")) {
4189 $("#fld_noBoundaryPt_wrapper").hide();
4190 gen_mode_sub = 0;
4191 google.maps.event.removeListener(fld_addFieldPoint);
4192 //need to remove added marker as its not been saved.
4193 if (fld_addFieldsinglePointMarker != null) {
4194 fld_addFieldsinglePointMarker.setMap(null);
4195 fld_addFieldsinglePointMarker = null;
4196 }
4197
4198
4199 }
4200
4201 //above taken from pin drop
4202
4203 displayLeftDetailsPanel(true);
4204 $(".left_details_panel_content").html("<p>Please draw your field on the map</p><button id=\"saveNewFieldBoundary\" value=\"Save Boundary\" class=\"save_new_field_boundary btn\" disabled=\"\">Save Field Boundary</button>");
4205 if (!$("#saveFieldBoundary").is(":disabled")) {
4206 $("#saveFieldBoundary").prop("disabled", true);
4207 }
4208 gen_setGlobalSubMode(1);
4209 setDrawPolygon(false);
4210});
4211
4212//No field boundary ///
4213
4214$(document).on("click", "#deleteNoBoundaryFieldPt", function () {
4215 $("#confirm-delete").modal('show');
4216});
4217
4218
4219$(document).on("click", "#fld_noBoundaryPt_activeWrapper", function () {
4220
4221 //taken from the field elements code to remove any fields already drawn
4222 displayLeftDetailsPanel(false); // maybe should use setFieldPanelList instead of the below
4223 chkUserAddingField();
4224 //remove any previous single field sample results
4225 removeSingleFieldSampleData();
4226
4227 ////v2 ui
4228 $(".field_item_selected").removeClass("field_item_selected").addClass("field_item");
4229
4230 ////make sure any previous field detail elements are emptied and closed.
4231 ////remove any highlighting of panels.
4232 $(".field_item").each(function () {
4233 $(this).removeClass("field_item_selected");
4234 $(this).children(0).empty().hide();
4235 });
4236///Above taken from field_item click event
4237
4238 $(".fld_newfield_wo_boundary_field_name").val('');
4239 if ($("#fld_noBoundaryPt_wrapper").is(":visible")) {
4240 $("#fld_noBoundaryPt_wrapper").hide();
4241 gen_mode_sub = 0;
4242 google.maps.event.removeListener(fld_addFieldPoint);
4243 //need to remove added marker as its not been saved.
4244 if (fld_addFieldsinglePointMarker != null) {
4245 fld_addFieldsinglePointMarker.setMap(null);
4246 fld_addFieldsinglePointMarker = null;
4247 }
4248
4249
4250 }
4251 else {
4252 $("#fld_noBoundaryPt_wrapper").show();
4253 gen_setGlobalSubMode(3);
4254 setAddFieldPoint();
4255 }
4256});
4257
4258$(document).on("click", ".fld_newfield_wo_boundary_delete", function () {
4259 //remove point and clear txt box//hide wrapper.
4260 if (fld_addFieldsinglePointMarker != null) {
4261 fld_addFieldsinglePointMarker.setMap(null);
4262 fld_addFieldsinglePointMarker = null;
4263 }
4264
4265 $(".fld_newfield_wo_boundary_field_name").val('');
4266});
4267
4268$(document).on("click", ".fld_newfield_wo_boundary_save", function () {
4269
4270 //validate
4271 var err = false;
4272 //does point exist
4273 if ($(".fld_newfield_wo_boundary_field_name").val() == "") {
4274 err = true;
4275 }
4276 //does name exist
4277 if (!(err) && fld_addFieldsinglePointMarker == null) {
4278 err = true;
4279 }
4280
4281 if (!err) {
4282
4283 //add label to point
4284 var label = new InfoBox({
4285 content: $(".fld_newfield_wo_boundary_field_name").val(),
4286 boxStyle: {
4287 border: "1px solid black",
4288 textAlign: "center",
4289 backgroundColor: "white",
4290 fontSize: "8pt",
4291 padding: "0",
4292 whiteSpace: "nowrap",
4293 width: calcNameLength($(".fld_newfield_wo_boundary_field_name").val()) + "px",
4294 overflow: "hidden",
4295 textOverflow: "ellipsis"
4296 },
4297 disableAutoPan: true,
4298 position: new google.maps.LatLng(fld_addFieldsinglePointMarker.getPosition().lat(), fld_addFieldsinglePointMarker.getPosition().lng()),
4299 closeBoxURL: "",
4300 enableEventPropagation: true,
4301 pixelOffset: new google.maps.Size(-18, -3)
4302 });
4303 label.open(map)
4304
4305 // notes additions
4306 let currUrlSubs = "MiFarm/" + getTradingId() + "/" + getFarmId() + "/";
4307
4308 $.ajax({
4309 type: "POST",
4310 url: urlPrepend + "/fielddata/newfieldwo-" + $(".fld_newfield_wo_boundary_field_name").val().replace(/\W/g, ''),
4311 data: { name: $(".fld_newfield_wo_boundary_field_name").val(), lat: fld_addFieldsinglePointMarker.getPosition().lat(), lng: fld_addFieldsinglePointMarker.getPosition().lng(), farmId: getFarmId(), applicationId:13,
4312 tradingId: getTradingId(), link: currUrlSubs}
4313
4314 }).done(function (data) {
4315
4316 displaySuccessMsg(txtFd36);
4317
4318 insertNewFieldItem(data, $(".fld_newfield_wo_boundary_field_name").val());
4319 fld_fieldPtLabels.push(label);
4320 //add if to marker
4321 fld_addFieldsinglePointMarker.setOptions({
4322 id: data
4323 });
4324
4325 $("#fld_noBoundaryPt_wrapper").hide();
4326
4327 google.maps.event.addListener(fld_addFieldsinglePointMarker, 'click', function () {
4328
4329 //open up field panel if its not open
4330 if ($(".field_list_title").find('span').hasClass("glyphicon-menu-down")) {
4331 setFieldPanelList();
4332 }
4333
4334
4335 //remove any previous selected
4336 $(".field_item_selected").removeClass("field_item_selected").addClass("field_item");
4337
4338
4339 //find field item.
4340 $(".field_item").each(function () {
4341
4342 if ($(this).attr("id") == "f_" + data) {
4343 $(this).addClass("field_item_selected").removeClass("field_item");
4344
4345 var container = $(".left_panel_content"),
4346 scrollTo = $("#f_" + data);
4347 container.animate({
4348 scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
4349 });
4350 }
4351 else {
4352 $(this).removeClass("field_item_selected");
4353 }
4354 });
4355
4356 var fieldId = $(".field_item_selected").attr("id").split('_')[1];
4357 //if not field item has been found, the this marker has been added in this session to use field-name.
4358 str = "<span class=\"current_field_area\">Size : 0 Ha</span> <span class=\"glyphicon glyphicon-plus-sign\" title=\"" + txtFd8 + "\" id=\"addBoundaryToFieldPt\"></span>";
4359 str += "<p><button id=\"deleteNoBoundaryFieldPt\" class=\"btn-ok btn-danger\" title=\"" + txtFd37 + "\" rel=\"" + data + "\">" + txtGen18 + "</button>";
4360 str += "<button id=\"saveFieldBoundaryFieldPt\" class=\"btn-ok btn-success\" rel=\"" + fieldId + "\" disabled=\"disabled\" title=\"" + txtFd7 + "\">" + txtGen15 + "</button></p>";
4361 $(".fieldInfo").each(function () {
4362 if ($(this).attr("rel") == data) {
4363 $(this).empty().html(str).show();
4364 }
4365 else {
4366 $(this).empty().hide();
4367 }
4368 })
4369
4370 $("#f_" + data + " .fieldInfo").empty().html(str).show();
4371 gen_mode_sub = 3;
4372 });
4373
4374
4375 fld_fieldPts.push(fld_addFieldsinglePointMarker);
4376 });
4377 } else {
4378 displayErrMsg(txtFd35)
4379 }
4380});
4381
4382
4383$(document).on("click", ".fld_newfield_wo_boundary_delete", function () {
4384 fld_addFieldsinglePointMarker.setMap(null);
4385 fld_addFieldsinglePointMarker = null;
4386 $(".fld_newfield_wo_boundary_field_name").val('');
4387 $("#fld_noBoundaryPt_wrapper").hide();
4388});
4389
4390
4391
4392function setAddFieldPoint() {
4393
4394 fld_addFieldPoint = google.maps.event.addListener(map, "click", function (event) {
4395
4396 if (fld_addFieldsinglePointMarker != null) {
4397 google.maps.event.removeListener(fld_addFieldPoint);
4398 } else {
4399 fld_addFieldsinglePointMarker = new google.maps.Marker({
4400 position: event.latLng,
4401 map: map,
4402 draggable: true,
4403 icon: {
4404 url: urlPrepend + "/content/images/mapicons/red-flag.png"
4405 }
4406 });
4407 }
4408 });
4409}
4410
4411
4412$(document).on("click", "#addBoundaryToFieldPt", function () {
4413
4414 setDrawPolygon(false);
4415});
4416
4417$(document).on("click", "#saveFieldBoundaryFieldPt", function () {
4418
4419
4420 if ($("#fieldPtCropLayerFarmersCropList option").length > 0) {
4421 //destroy select 2
4422 $("#fieldPtCropLayerFarmersCropList").select2("destroy");
4423 }
4424 $("#fieldPtCropLayerFarmersCropList").select2({
4425 width: '100%',
4426 theme: 'classic'
4427 });
4428
4429 if ($("#fieldPtCropVarietyLayerSeasonList option").length > 0) {
4430 //destroy select 2
4431 $("#fieldPtCropVarietyLayerSeasonList").select2("destroy");
4432 }
4433 $("#fieldPtCropVarietyLayerSeasonList").select2({
4434 width: '100%',
4435 theme: 'classic'
4436 });
4437
4438
4439 $('#fieldPtBoundaryModal').modal('show');
4440 $("#fieldPtBoundaryModal .modal-dialog").attr("style", "width:90%;");
4441 $("#fieldPtBoundaryModal .modal-body").attr("style", "min-height:320px;");
4442 $("#newFieldCropLayerSeason").val('');
4443 $("#fieldPtCropLayerFarmersCropList").val('');
4444 $("#fld_fieldPointNewBoundaryFieldId").val($(this).attr("rel"));
4445 $(".new-field-point-modal-error").empty()
4446});
4447
4448$("#fieldPtCropLayerFarmersCropList").change(function () {
4449 //go and get variety data for the select crop.
4450 getCrpVarietyForNewFieldModal(this.value, false)
4451 $("#fieldPtCropVarietyLayerSeasonList").parent().show();
4452})
4453
4454
4455$(document).on("click", "#fld_addNewField_closeModal", function () {
4456 $('#fieldPtBoundaryModal').modal('hide');
4457});
4458
4459
4460$('#submitNewFieldNameForFieldPt').click(function (e) {
4461
4462 e.preventDefault();
4463
4464 var fld_newFieldError = "";
4465
4466 if (($("#fieldPtCropLayerFarmersCropList").find(":selected").val() == "") && (fld_newFieldError == "")) {
4467 fld_newFieldError = "Select a crop from the list.";
4468 }
4469
4470
4471 if (fld_newFieldError != "") {
4472 $("#new_field_pt_validation").removeClass("fade out");
4473 $("#new_field_pt_validation").show().addClass("fade in");
4474 $(".new-field-point-modal-error").empty().text(fld_newFieldError);
4475 }
4476 else {
4477 $("#new_field_validation").removeClass("fade in");
4478 $("#new_field_validation").addClass("fade out").hide();
4479
4480 loadStatus("Save field boundary.....");
4481
4482 var fieldId = $("#fld_fieldPointNewBoundaryFieldId").val();
4483 var seasonId = 0;
4484 var selectedCrop = $("#fieldPtCropLayerFarmersCropList").find(":selected").val();
4485
4486
4487 seasonId = $("#customerSeason").find(":selected").val();
4488
4489
4490 $('#fieldPtBoundaryModal').modal('hide');
4491
4492 var str = "";
4493 //set centre point and set label.
4494 var tempBounds = new google.maps.LatLngBounds();
4495 for (var i = 0; i < selectedShape.getPath().getLength() ; i++) {
4496 var xy = selectedShape.getPath().getAt(i);
4497 str += xy.lat() + ',' + xy.lng() + "|";
4498 tempBounds.extend(xy);
4499 }
4500 //calculate new area of polygon
4501 var area = google.maps.geometry.spherical.computeArea(selectedShape.getPath(), 6371);
4502 area = area * 100;
4503 //find put if user has entered points in a clockwise or anti-clockwise fashion.
4504 var ptsDirection = polygonDirection(selectedShape.getPath());
4505
4506 $.ajax({
4507 type: "POST",
4508 url: urlPrepend + "/fielddata/addfieldboundarytofldpt",
4509 data: { fieldId: fieldId, farmId: getFarmId(), tradingId: getTradingId(), area: area, points: str, crop: selectedCrop, variety: $("#fieldPtCropVarietyLayerSeasonList").find(":selected").val(), seasonId: seasonId, clockwisePts: ptsDirection }
4510 })
4511 .done(function (data) {
4512
4513 resetPolyObj(selectedShape)
4514 selectedShape.setOptions({
4515 id: fieldId,
4516 clickable: true
4517 });
4518
4519 fld_addfieldToCroppingFieldList(fieldId, data);
4520 addPolygonClickEvent(selectedShape);
4521 addPolygonMouseCoordsData(selectedShape);
4522
4523 setFieldMarker(selectedShape, tempBounds.getCenter().lat(), tempBounds.getCenter().lng(), data);
4524
4525 //add new polygon to the array
4526 polygonsArray.push(selectedShape);
4527
4528 $("#alertWrapper").append("<div class=\"alert-overlay modal-backdrop fade in\"></div>");
4529
4530 displaySuccessMsg2(txtFd3);
4531 removeStatus();
4532 field_resetNewFieldCropElements();
4533
4534 //refresh cropping season list in new field model
4535 crp_cropSeasonByFarm(getFarmId()); //lives in crop.js
4536 crp_addCropColoringToFields();//lives in crop.js
4537
4538 //remove field point and refresh field panel.
4539 $(".fieldInfo").each(function () {
4540 if ($(this).attr("rel") == fieldId) {
4541 //clear panel and reload.
4542
4543
4544 $(this).empty();
4545 $.getJSON(urlPrepend + "/fielddata/l-" + fieldId + "_" + $("#customerSeason").find(":selected").val())
4546 .done(function (data) {
4547 highlightSelectedField(data.fieldId, true, data.fieldArea);
4548 setMasterFieldVar(data.fieldId);
4549 populateFieldDetailsPlaceHoler(data);
4550 })
4551 .fail(function () {
4552 displayErrMsg(txtFd16);
4553 });
4554 }
4555 });
4556
4557
4558 for (var i = 0; i < fld_fieldPts.length; i++) {
4559 if (fieldId === fld_fieldPts[i].id) {
4560 fld_fieldPts[i].setMap(null);
4561 fld_fieldPtLabels[i].setMap(null);
4562 fld_fieldPts.splice(0, 1)
4563 fld_fieldPtLabels.splice(0, 1)
4564 }
4565 }
4566
4567 })
4568 .fail(function () {
4569 field_resetNewFieldCropElements();
4570 //display failure message.
4571 if (selectedShape) {
4572 selectedShape.setMap(null);
4573 setDrawPolygon(false);
4574 }
4575 })
4576
4577
4578 }
4579});
4580//No field boundary end ///
4581
4582$(document).on("click", '#saveNewFieldBoundary', function () {
4583
4584 if ($(this).hasClass("has-field")) {
4585 addBoundaryToField();
4586 }
4587 else {
4588
4589
4590 if ($("#newFieldCropLayerFarmersCropList option").length > 0) {
4591 //destroy select 2
4592 $("#newFieldCropLayerFarmersCropList").select2("destroy");
4593 }
4594 $("#newFieldCropLayerFarmersCropList").select2({
4595 width: '100%',
4596 theme: 'classic'
4597 });
4598
4599 if ($("#newFieldCropVarietyLayerSeasonList option").length > 0) {
4600 //destroy select 2
4601 $("#newFieldCropVarietyLayerSeasonList").select2("destroy");
4602 }
4603 $("#newFieldCropVarietyLayerSeasonList").select2({
4604 width: '100%',
4605 theme: 'classic'
4606 });
4607
4608 $(".add_new_field_crop_ele_2").hide();
4609
4610 $('#newFieldModal').modal('show');
4611 $("#newFieldModal .modal-dialog").attr("style", "width:90%;");
4612 $("#newFieldModal .modal-body").attr("style", "min-height:320px;");
4613
4614
4615 $('#newFieldModal').on('shown.bs.modal', function () {
4616 $('#newFieldNametxt').focus();
4617 });
4618 $("#newFieldNametxt").val('');
4619 $("#newFieldCropLayerSeason").val('');
4620 $("#newFieldCropLayerFarmersCropList").val('');
4621
4622
4623
4624 }
4625});
4626
4627
4628$(document).on("click", '#saveFieldBoundary', function () {
4629 if ($(this).hasClass("has-field")) {
4630 addBoundaryToField();
4631 }
4632 else {
4633 $('#newFieldModal').modal('show');
4634 $('#newFieldModal').on('shown.bs.modal', function () {
4635 $('#newFieldNametxt').focus();
4636 });
4637 $("#newFieldNametxt").val('');
4638 $("#newFieldCropLayerSeason").val('');
4639 $("#newFieldCropLayerFarmersCropList").val('');
4640
4641 }
4642});
4643
4644$("#newFieldModal").on("hidden.bs.modal", function () {
4645 $("#new_field_validation").fadeOut(0);
4646});
4647
4648$('#submitNewFieldName').click(function (e) {
4649
4650 e.preventDefault();
4651
4652 var fld_newFieldError = "";
4653
4654 if ($("#newFieldNametxt").val() == "") {
4655 fld_newFieldError = "Enter a valid field name.";
4656 }
4657
4658 if (($("#newFieldCropLayerFarmersCropList").find(":selected").val() == "") && (fld_newFieldError == "")) {
4659 fld_newFieldError = "Select a crop from the list.";
4660 }
4661
4662 let doesFieldNameAlreadyExist = false;
4663
4664 $('.field_list_items > li').each(function( index ) {
4665 if($(this).hasClass("field_item")){
4666 let currentFieldName = $(this).text().trim().toLowerCase();
4667 let inputFieldName = $("#newFieldNametxt").val().trim().toLowerCase();
4668
4669 if(currentFieldName == inputFieldName){
4670 doesFieldNameAlreadyExist = true;
4671 fld_newFieldError = "This name is already used for another field in this farm.";
4672 }else if(currentFieldName.replace(' ', '') == inputFieldName.replace(' ', '')){
4673 doesFieldNameAlreadyExist = true;
4674 fld_newFieldError = "This name is already used for another field in this farm.";
4675 }
4676
4677 }
4678 });
4679
4680 if (fld_newFieldError != "") {
4681 $("#new_field_validation").removeClass("fade out");
4682 $("#new_field_validation").show().addClass("fade in");
4683 $(".new-field-modal-error").empty().text(fld_newFieldError);
4684 }
4685 else {
4686 $("#new_field_validation").removeClass("fade in");
4687 $("#new_field_validation").addClass("fade out").hide();
4688 addNewField();
4689 }
4690});
4691
4692
4693$("#fld_addNewField_closeModal").click(function () {
4694 $("#newFieldModal").modal("hide");
4695});
4696
4697
4698//bind farm textbox to allow users to press enter to save
4699$("#newFieldNametxt").keypress(function (event) {
4700 if (event.keyCode == 13) {
4701
4702 var fld_newFieldError = "";
4703
4704
4705 if ($("#newFieldNametxt").val() == "") {
4706 fld_newFieldError = "Enter a valid field name.";
4707 }
4708
4709 if (($("#newFieldCropLayerFarmersCropList").find(":selected").val() == "") && (fld_newFieldError == "")) {
4710 fld_newFieldError = "Select a crop the list.";
4711 }
4712
4713
4714 if (fld_newFieldError != "") {
4715 $("#new_email_validation").removeClass("fade out");
4716 $("#new_email_validation").addClass("fade in");
4717 $(".new-field-modal-error").empty().text(fld_newFieldError);
4718 }
4719 else {
4720 $("#new_email_validation").removeClass("fade in");
4721 $("#new_email_validation").addClass("fade out");
4722 addNewField();
4723 }
4724 }
4725});
4726
4727$("#newFieldCropLayerSeason").keypress(function (event) {
4728 if (event.keyCode == 13) {
4729
4730 var fld_newFieldError = "";
4731
4732 if ($("#newFieldNametxt").val() == "") {
4733 fld_newFieldError = "Enter a valid field name.";
4734 }
4735
4736 if (($("#newFieldCropLayerSeason").val() == "" && $("#newFieldCropLayerSeasonList").find(":selected").val() == "") && (fld_newFieldError == "")) {
4737 fld_newFieldError = "Add a new season, or select one from the list.";
4738 }
4739
4740
4741
4742 if (($("#newFieldCropLayerFarmersCropList").find(":selected").val() == "") && (fld_newFieldError == "")) {
4743 fld_newFieldError = "Select a crop the list.";
4744 }
4745
4746
4747 if (fld_newFieldError != "") {
4748 $("#new_email_validation").removeClass("fade out");
4749 $("#new_email_validation").addClass("fade in");
4750 $(".new-field-modal-error").empty().text(fld_newFieldError);
4751 }
4752 else {
4753 $("#new_email_validation").removeClass("fade in");
4754 $("#new_email_validation").addClass("fade out");
4755 addNewField();
4756 }
4757 }
4758
4759
4760});
4761
4762
4763$("#newFieldCropLayerSeasonList").keypress(function (event) {
4764 if (event.keyCode == 13) {
4765
4766 var fld_newFieldError = "";
4767
4768 if ($("#newFieldNametxt").val() == "") {
4769 fld_newFieldError = "Enter a valid field name.";
4770 }
4771
4772 if (($("#newFieldCropLayerSeason").val() == "" && $("#newFieldCropLayerSeasonList").find(":selected").val() == "") && (fld_newFieldError == "")) {
4773 fld_newFieldError = "Add a new season, or select one from the list.";
4774 }
4775
4776
4777
4778 if (($("#newFieldCropLayerFarmersCropList").find(":selected").val() == "") && (fld_newFieldError == "")) {
4779 fld_newFieldError = "Select a crop the list.";
4780 }
4781
4782
4783 if (fld_newFieldError != "") {
4784 $("#new_email_validation").removeClass("fade out");
4785 $("#new_email_validation").addClass("fade in");
4786 $(".new-field-modal-error").empty().text(fld_newFieldError);
4787 }
4788 else {
4789 $("#new_email_validation").removeClass("fade in");
4790 $("#new_email_validation").addClass("fade out");
4791 // addNewField();
4792 }
4793 }
4794
4795
4796});
4797
4798$("#newFieldCropLayerFarmersCropList").keypress(function (event) {
4799 if (event.keyCode == 13) {
4800 var fld_newFieldError = "";
4801
4802 if ($("#newFieldNametxt").val() == "") {
4803 fld_newFieldError = "Enter a valid field name.";
4804 }
4805
4806 if (($("#newFieldCropLayerSeason").val() == "" && $("#newFieldCropLayerSeasonList").find(":selected").val() == "") && (fld_newFieldError == "")) {
4807 fld_newFieldError = "Add a new season, or select one from the list.";
4808 }
4809
4810
4811
4812 if (($("#newFieldCropLayerFarmersCropList").find(":selected").val() == "") && (fld_newFieldError == "")) {
4813 fld_newFieldError = "Select a crop the list.";
4814 }
4815
4816
4817 if (fld_newFieldError != "") {
4818 $("#new_email_validation").removeClass("fade out");
4819 $("#new_email_validation").addClass("fade in");
4820 $(".new-field-modal-error").empty().text(fld_newFieldError);
4821 }
4822 else {
4823 $("#new_email_validation").removeClass("fade in");
4824 $("#new_email_validation").addClass("fade out");
4825 // addNewField();
4826 }
4827 }
4828
4829
4830});
4831
4832
4833$(document).on("click", "#addBoundary", function () {
4834
4835 setDrawPolygon(true);
4836});
4837
4838//display farmname in left panel
4839if ($("#selecteFarmName").length > 0) {
4840 $("#fieldInfo").empty().html("Farm : " + $("#selecteFarmName").val());
4841}
4842
4843
4844$(document).on("mouseleave", ".field_item", function () {
4845
4846 //have any fields been selected and displaying field details.
4847 var intSelectedFieldDetailsId = 0;
4848 $(".fieldInfo").each(function () {
4849 if ($(this).is(":visible")) {
4850 intSelectedFieldDetailsId = $(this).attr("rel");
4851 }
4852 });
4853
4854 for (var i = 0; i < polygonsArray.length; i++) {
4855 if (polygonsArray[i].get("id") == $(this).attr("id").split("_")[1] && polygonsArray[i].get("id") != intSelectedFieldDetailsId) {
4856 resetPolyObj(polygonsArray[i]);
4857 }
4858 }
4859});
4860
4861
4862$(document).on("mouseenter", ".field_item", function () {
4863
4864 //have any fields been selected and displaying field details.
4865 var intSelectedFieldDetailsId = 0;
4866 $(".fieldInfo").each(function () {
4867 if ($(this).is(":visible")) {
4868 intSelectedFieldDetailsId = $(this).attr("rel");
4869 }
4870 });
4871
4872
4873 var iMarker = 0;
4874
4875 for (var i = 0; i < polygonsArray.length; i++) {
4876 if (polygonsArray[i].get("id") == $(this).attr("id").split("_")[1] && polygonsArray[i].get("id") != intSelectedFieldDetailsId) {
4877 polygonsArray[i].setOptions({
4878 highlight: true,
4879 strokeColor: '#083508',
4880 strokeOpacity: 0.8,
4881 strokeWeight: 2
4882 });
4883 }
4884 }
4885
4886});
4887
4888
4889$(document).on("click", ".field_item", function () {
4890
4891 //Below taken from pin functionality for closing pin and previous drawings
4892 displayLeftDetailsPanel(false); // maybe should use setFieldPanelList instead of the below
4893 $(".fld_newfield_wo_boundary_field_name").val('');
4894 if ($("#fld_noBoundaryPt_wrapper").is(":visible")) {
4895 $("#fld_noBoundaryPt_wrapper").hide();
4896 gen_mode_sub = 0;
4897 google.maps.event.removeListener(fld_addFieldPoint);
4898 //need to remove added marker as its not been saved.
4899 if (fld_addFieldsinglePointMarker != null) {
4900 fld_addFieldsinglePointMarker.setMap(null);
4901 fld_addFieldsinglePointMarker = null;
4902 }
4903 }
4904
4905 //above taken from pin drop
4906
4907
4908
4909 chkUserAddingField();
4910 //remove any previous single field sample results
4911 removeSingleFieldSampleData();
4912
4913 ////v2 ui
4914 $(".field_item_selected").removeClass("field_item_selected").addClass("field_item");
4915
4916 ////make sure any previous field detail elements are emptied and closed.
4917 ////remove any highlighting of panels.
4918 $(".field_item").each(function () {
4919 $(this).removeClass("field_item_selected");
4920 $(this).children(0).empty().hide();
4921 });
4922
4923 //change this class name
4924 $(this).removeClass("field_item").addClass("field_item_selected");
4925
4926
4927 //is this a field point?
4928 var fieldId = $(this).attr("id").split("_")[1];
4929 var isFieldPt = false;
4930 for (var i = 0; i < fld_fieldPts.length; i++) {
4931 if (fieldId === fld_fieldPts[i].id) {
4932 //we have a field point
4933 isFieldPt = true;
4934 }
4935 }
4936
4937 if (!isFieldPt) {
4938 getFieldNoCache($(this).attr("id").split("_")[1]);
4939 }
4940 else {
4941
4942 str = "<span class=\"current_field_area\">Size : 0 Ha</span><span class=\"glyphicon glyphicon-plus-sign\" title=\"" + txtFd8 + "\" id=\"addBoundaryToFieldPt\"></span>";
4943 str += "<p><button id=\"deleteNoBoundaryFieldPt\" class=\"btn-ok btn-danger\" title=\"" + txtFd37 + "\" rel=\"" + fieldId + "\">Delete</button>";
4944 str += "<button id=\"saveFieldBoundaryFieldPt\" class=\"btn-ok btn-success\" rel=\"" + fieldId + "\" disabled=\"disabled\" title=\"" + txtFd7 + "\">" + txtGen15 + "</button></p>";
4945 $(".fieldInfo").each(function () {
4946 if ($(this).attr("rel") == fieldId) {
4947 $(this).empty().html(str).show();
4948 }
4949 else {
4950 $(this).empty().hide();
4951 }
4952 })
4953
4954 $("#f_" + fieldId + " .fieldInfo").empty().html(str).show();
4955 gen_mode_sub = 3;
4956 }
4957
4958
4959});
4960
4961$(document).on("click", ".field_sample_service_link", function () {
4962
4963 var temp_OrderId = $(this).find('span').attr("id");
4964 var ele = $(this);
4965
4966 if (!$(this).hasClass("active")) {
4967 $(this).addClass("active");
4968 $(".fld_recent_sample_nutrients").each(function () {
4969 //loop through elements to find container for nutrients
4970 if ($(this).attr("rel") == temp_OrderId) {
4971 //if container already has nutrients, then display otherwise go and get nutrients.
4972 if ($(this).children().length > 0) {
4973 $(this).show();
4974 }
4975 else {
4976
4977
4978 $.ajax({
4979 url: urlPrepend + "/fielddata/ui_field_sample_results_" + temp_OrderId
4980 }).done(function (data) {
4981
4982 var temp_str = "";
4983 for (var i = 0; i < data.length; i++) {
4984 temp_str += "<li class=\"lyr_single_field_sample_service_nutrient\" rel=\"" + data[i].Id + "\">" + data[i].nutrientName + "</li>";
4985 }
4986
4987 if (temp_str != "") {
4988 //add checkbox to load sample points
4989 temp_str += "<li class=\"lyr_sample_points_display_wrapper\"><label for=\"fld_load_sample_pt_" + temp_OrderId + "\">Load Sample Points</label><input id=\"fld_load_sample_pt_" + temp_OrderId + "\" type=\"checkbox\" value=\"" + temp_OrderId + "\" class=\"lyr_sample_points_display\" title=\"View Sample Points\"/></li>";
4990 $(".fld_recent_sample_nutrients").each(function () {
4991
4992 if ($(this).attr("rel") == temp_OrderId) {
4993 $(this).empty().html(temp_str);
4994 }
4995 });
4996 };
4997
4998 });
4999 }
5000 }
5001 });
5002 }
5003 else {
5004 $(this).removeClass("active");
5005 $(".fld_recent_sample_nutrients").each(function () {
5006 if ($(this).attr("rel") == temp_OrderId) {
5007 $(this).hide();
5008 }
5009 });
5010 }
5011
5012
5013
5014});
5015
5016
5017$(document).on("click", ".lyr_single_field_sample_service_nutrient", function () {
5018
5019 //uncheck any other load sample checkboxes (could be historical)
5020 if ($(".lyr_sample_points_display").length > 1) {
5021
5022 var tmp_checkbox_val = $(this).parent().attr("rel");
5023 $(".lyr_sample_points_display").each(function () {
5024 if ($(this).is(":checked") && $(this).val() != tmp_checkbox_val) {
5025 $(this).prop("checked", false);
5026 }
5027 });
5028
5029 if (lyr_sample_points_overlay.length > 1) {
5030 for (var j = 0; j < lyr_sample_points_overlay.length; j++) {
5031 lyr_sample_points_overlay[j].setMap(null);
5032 }
5033 }
5034 }
5035
5036
5037
5038 //check if user is editing field boundary
5039 if ($("#saveEditedField").is(":visible")) {
5040
5041 editedObj.setMap(null);
5042
5043 // resetPolyObj(editedObj);
5044 editedObj = null;
5045 removeStatus();
5046 hideSaveFieldButton();
5047 hideCancel();
5048 $("#editField").removeClass("editmode");
5049 }
5050
5051 //has this item been selected, if so remove
5052 if ($(this).hasClass("lyr_single_field_sample_service_nutrient_selected")) {
5053 if (gen_mode_sub == 2) {
5054 removeSingleFieldSampleData();
5055 $("#leftDetailsPanel").hide();
5056 }
5057 $(this).removeClass("lyr_single_field_sample_service_nutrient_selected");
5058 $(".lyr_sample_points_display_wrapper").hide();
5059 }
5060 else {
5061
5062 $(".lyr_sample_points_display_wrapper").show();
5063
5064 $(".lyr_single_field_sample_service_nutrient").each(function () {
5065 if ($(this).hasClass("lyr_single_field_sample_service_nutrient_selected")) {
5066 $(this).removeClass("lyr_single_field_sample_service_nutrient_selected");
5067 }
5068 })
5069
5070 //highlight item
5071 $(this).addClass("lyr_single_field_sample_service_nutrient_selected");
5072
5073 var temp_fieldId = getFieldId();
5074 var temp_nutId = $(this).attr("rel");
5075 var temp_orderId = $(this).parent().attr("rel");
5076
5077 loadStatus("Loading " + $(this).text() + " Sample Results Data");
5078
5079 $.ajax({
5080 url: urlPrepend + "/layerdata/ui_data-layers_sample_results_" + temp_orderId + "_" + temp_nutId + "_" + temp_fieldId
5081 }).done(function (data) {
5082
5083 //set local submode
5084 gen_mode_sub = 2;
5085
5086 lyr_field_sample_results_getZoneResultValues(temp_orderId, temp_nutId, temp_fieldId);
5087 displayLeftDetailsPanel(true);
5088 $(".left_details_panel_content").empty().html("<div class=\"imagery_layer_legend\"><p>" + data.displayName + "</p><img src=\"https://portal.precisiondecisions.co.uk/MiFarm/Content/images/nutrient-scale/" + data.legend + "\" /></div>");
5089
5090
5091 //ajax call to get lat lng for bounding box.
5092 var thisImagePath = data.imagePath;
5093 var thisFieldId = data.fieldId;
5094 var thisLegend = data.legend;
5095
5096
5097 //reset and hide any previous field sample data
5098 if (lyr_sample_results_polygon_field_boundary_overlay.length > 0) {
5099 lyr_sample_results_polygon_field_boundary_overlay[0].setMap(null);
5100 }
5101
5102 lyr_sample_results_polygon_field_boundary_overlay = [];
5103 lyr_sample_service_zone_data(data.fieldId, temp_orderId, thisImagePath, 1, 1);
5104 sr_sampleResultsOverlaysLoaded = true;
5105 checkSampleDataHasLoaded();
5106
5107 }).fail(function () {
5108 sr_sampleResultsOverlaysLoaded = true;
5109 displayErrMsg("There are no results for this nutrient at this time.");
5110 checkSampleDataHasLoaded();
5111 removeSingleFieldSampleData();
5112 $("#leftDetailsPanel").hide();
5113 removeStatus();
5114 })
5115 }
5116});
5117
5118
5119function removeSingleFieldSampleData() {
5120 //user viewing field sample results.
5121 //hide results
5122 if (lyr_sample_results_polygon_field_boundary_overlay.length > 0) {
5123 for (var j = 0; j < lyr_sample_results_polygon_field_boundary_overlay.length; j++) {
5124 lyr_sample_results_polygon_field_boundary_overlay[j].setMap(null);
5125 }
5126 lyr_sample_results_polygon_field_boundary_overlay = [];
5127 }
5128
5129 //remove sample points
5130 fld_clearSamplePts();
5131
5132 if (lyr_sample_results_zone_values_overlay.length > 0) {
5133 for (var k = 0; k < lyr_sample_results_zone_values_overlay.length; k++) {
5134 lyr_sample_results_zone_values_overlay[k].setMap(null);
5135 }
5136 lyr_sample_results_zone_values_overlay = [];
5137 }
5138
5139 if (lyr_sample_results_im_polygon_overlay.length > 0) {
5140 for (var m = 0; m < lyr_sample_results_im_polygon_overlay.length; m++) {
5141
5142 lyr_sample_results_im_polygon_overlay[m].overlay.setMap(null);
5143 }
5144 lyr_sample_results_im_polygon_overlay = [];
5145 }
5146 //display field polys again
5147 for (var i = 0; i < polygonsArray.length; i++) {
5148 if (polygonsArray[i].getMap() == null) {
5149 polygonsArray[i].setMap(map);
5150 }
5151 }
5152}
5153
5154function lyr_field_sample_results_getZoneResultValues(orderId, nutrientId, fieldId) {
5155
5156 //reset and hide any previous field sample data
5157 if (lyr_sample_results_zone_values_overlay.length > 0) {
5158 for (var k = 0; k < lyr_sample_results_zone_values_overlay.length; k++) {
5159 lyr_sample_results_zone_values_overlay[k].setMap(null);
5160 }
5161 lyr_sample_results_zone_values_overlay = [];
5162 }
5163
5164 $.ajax({
5165 url: urlPrepend + "/layerdata/ui_data-layers_sample_result_zones_" + orderId + "_" + nutrientId + "_" + fieldId
5166 }).done(function (data) {
5167
5168 for (var i = 0; i < data.length; i++) {
5169
5170 infowindow = new google.maps.InfoWindow();
5171
5172 var label = new InfoBox({
5173 content: data[i].result,
5174 boxStyle: {
5175 border: "1px solid black",
5176 textAlign: "center",
5177 backgroundColor: "white",
5178 fontSize: "8pt",
5179 padding: "0",
5180 whiteSpace: "nowrap",
5181 width: "35px",
5182 overflow: "hidden",
5183 textOverflow: "ellipsis"
5184 },
5185 disableAutoPan: true,
5186 position: new google.maps.LatLng(data[i].lat, data[i].lng),
5187 closeBoxURL: "",
5188 enableEventPropagation: true,
5189 });
5190 label.open(map)
5191 lyr_sample_results_zone_values_overlay.push(label);
5192
5193 if (i == data.length - 1) {
5194 sr_sampleResultsZoneValuesLoaded = true;
5195 }
5196
5197 }
5198
5199 });
5200
5201}
5202
5203var lyr_sample_points_overlay = [];
5204var lyr_sample_points_marker = urlPrepend + "/Content/images/dots/black_dot.png";
5205
5206$(document).on("change", ".lyr_sample_points_display", function () {
5207 //get sample points
5208
5209 //do we have more than one checkbox from historical sample sets?
5210 if ($(".lyr_sample_points_display").length > 1) {
5211 if (lyr_sample_points_overlay.length > 1) {
5212 for (var j = 0; j < lyr_sample_points_overlay.length; j++) {
5213 lyr_sample_points_overlay[j].setMap(null);
5214 }
5215 }
5216
5217 var tmp_checkbox_val = $(this).val();
5218 $(".lyr_sample_points_display").each(function () {
5219 if ($(this).is(":checked") && $(this).val() != tmp_checkbox_val) {
5220 $(this).prop("checked", false);
5221 }
5222 });
5223 }
5224
5225
5226 if ($(this).is(":checked")) {
5227 $.getJSON(urlPrepend + "/sampledata/sample-points-" + getFieldId() + "-" + $(this).val())
5228 .done(function (data) {
5229 for (var i = 0; i < data.length; i++) {
5230
5231 lyr_sample_points_overlay.push(new google.maps.Marker({
5232 position: new google.maps.LatLng(data[i].lat, data[i].lng),
5233 map: map,
5234 draggable: false,
5235 icon: new google.maps.MarkerImage(lyr_sample_points_marker)
5236 }));
5237
5238 }
5239 });
5240 }
5241 else {
5242 for (var j = 0; j < lyr_sample_points_overlay.length; j++) {
5243 lyr_sample_points_overlay[j].setMap(null);
5244 }
5245 }
5246
5247
5248});
5249
5250function fld_clearSamplePts() {
5251 for (var j = 0; j < lyr_sample_points_overlay.length; j++) {
5252 lyr_sample_points_overlay[j].setMap(null);
5253 }
5254 lyr_sample_points_overlay = [];
5255
5256 $(".lyr_sample_points_display").each(function () {
5257 if ($(this).is(":checked")) {
5258 $(this).prop("checked", false);
5259 }
5260 });
5261}
5262
5263function getField(id) {
5264
5265 $.getJSON(urlPrepend + "/fielddata/" + id + "_" + $("#customerSeason").find(":selected").val())
5266 .done(function (data) {
5267
5268 highlightSelectedField(data.fieldId, true, data.fieldArea);
5269 setMasterFieldVar(data.fieldId);
5270 closeAllLayerLists(true);
5271 //open left panel field list only if its closed.
5272 if ($(".field_list_title").find('span').hasClass("glyphicon-menu-down")) {
5273 setFieldPanelList();
5274 }
5275
5276 populateFieldDetailsPlaceHoler(data);
5277 $(".field_item").each(function () {
5278 if ($(this).attr("id") == "f_" + data.fieldId) {
5279 $(this).addClass("field_item_selected").removeClass("field_item");
5280
5281 var container = $(".left_panel_content"),
5282 scrollTo = $("#f_" + data.fieldId);
5283
5284 container.animate({
5285 scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
5286 });
5287
5288
5289 }
5290 else {
5291 $(this).removeClass("field_item_selected");
5292 }
5293 });
5294 })
5295 .fail(function () {
5296 displayErrMsg(txtFd16);
5297 })
5298}
5299
5300function getFieldNoCacheUpdate(id) {
5301 $("#fieldInfo").empty();
5302
5303
5304 $.getJSON(urlPrepend + "/fielddata/l-" + id + "_" + $("#customerSeason").find(":selected").val())
5305 .done(function (data) {
5306 highlightSelectedField(data.fieldId, true, data.fieldArea);
5307 setMasterFieldVar(data.fieldId);
5308
5309 closeAllLayerLists(true);
5310 //open left panel field list
5311 setFieldPanelList();
5312 populateFieldDetailsPlaceHoler(data);
5313 $(".field_item").each(function () {
5314 if ($(this).attr("id") == "f_" + data.fieldId) {
5315 $(this).addClass("field_item_selected");
5316
5317
5318 var container = $(".left_panel_content"),
5319 scrollTo = $("#f_" + data.fieldId);
5320
5321 container.animate({
5322 scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
5323 });
5324
5325
5326 }
5327 else {
5328 $(this).removeClass("field_item_selected");
5329 }
5330 });
5331 })
5332 .fail(function () {
5333 displayErrMsg(txtFd16);
5334 });
5335}
5336
5337function getFieldNoCache(id) {
5338 $.getJSON(urlPrepend + "/fielddata/l-" + id + "_" + $("#customerSeason").find(":selected").val())
5339 .done(function (data) {
5340 populateFieldDetailsPlaceHoler(data);
5341 setMasterFieldVar(data.fieldId);
5342
5343 for (var i = 0; i < polygonsArray.length; i++) {
5344 if (polygonsArray[i].get("id") == id) {
5345 polygonsArray[i].setOptions({
5346 highlight: true,
5347 strokeColor: '#FF0000',
5348 strokeOpacity: 0.8,
5349 strokeWeight: 5
5350 });
5351
5352 panToField(polygonsArray[i]);
5353
5354
5355 }
5356 else {
5357 polygonsArray[i].setOptions({
5358 strokeColor: '#4fde47',
5359 strokeOpacity: 1,
5360 strokeWeight: 2
5361 });
5362 //resetPolyObj(polygonsArray[i]);
5363 }
5364 $("#fieldInfo").addClass("field-has-holes");
5365 }
5366
5367
5368
5369 })
5370 .fail(function () {
5371 displayErrMsg(txtFd16);
5372 });
5373}
5374
5375function addBoundaryToField() {
5376 var newFieldName = $(".field_item_selected").text();
5377
5378 var str = "";
5379 //set centre point and set label.
5380 var tempBounds = new google.maps.LatLngBounds();
5381 for (var i = 0; i < selectedShape.getPath().getLength() ; i++) {
5382 var xy = selectedShape.getPath().getAt(i);
5383 str += xy.lat() + ',' + xy.lng() + "|";
5384 tempBounds.extend(xy);
5385 }
5386 //calculate new area of polygon
5387 var area = google.maps.geometry.spherical.computeArea(selectedShape.getPath(), 6371);
5388 area = area * 100;
5389 var ptsDirection = (google.maps.geometry.spherical.computeSignedArea(selectedShape.getPath()) < 0);
5390
5391 loadStatus(txtFd15);
5392 $.ajax({
5393 type: "POST",
5394 url: urlPrepend + "/fielddata/newboundary-" + encodeURI(newFieldName),
5395 data: { name: newFieldName, area: area, fieldId: getFieldId(), points: str, clockwisePts: ptsDirection }
5396 //data: { name: newFieldName, area: area, farmid: $("#fieldsList").attr("rel"), points: str }
5397 })
5398 .done(function (data) {
5399 resetPolyObj(selectedShape)
5400 selectedShape.setOptions({
5401 id: getFieldId()
5402 });
5403
5404
5405 //20182607 - AT - disabled code as it is not needed. Database insert already switches polygon direction when inserting data.
5406 // When user is inserting a hole, the field is redrawn from db points into the modal map
5407 //////if (!ptsDirection) {
5408
5409 ////// //if this polygon has been drawn anticlock then reverse it.
5410 ////// var antiClockWisePtsArray = [];
5411 ////// for (var k = 0; k < selectedShape.getPath().getLength() ; k++) {
5412 ////// antiClockWisePtsArray.push(new google.maps.LatLng(selectedShape.getPath().getAt(k).lat(), selectedShape.getPath().getAt(k).lng()));
5413 ////// }
5414 ////// //add extra point to close polygon loop
5415 ////// if (antiClockWisePtsArray.length > 0) {
5416 ////// antiClockWisePtsArray.push(new google.maps.LatLng(selectedShape.getPath().getAt(0).lat(), selectedShape.getPath().getAt(0).lng()));
5417 ////// }
5418
5419
5420 ////// //reverse points so that the direction of pts is cw
5421 ////// antiClockWisePtsArray.reverse();
5422
5423 ////// for (var m = 0; m < antiClockWisePtsArray.length; m++) {
5424 ////// //remove old coordinate
5425 ////// selectedShape.getPath().removeAt(m);
5426 ////// //insert new coordinate
5427 ////// selectedShape.getPath().insertAt(m, antiClockWisePtsArray[m]);
5428 ////// }
5429
5430 //////}
5431
5432
5433 setFieldMarker(selectedShape, tempBounds.getCenter().lat(), tempBounds.getCenter().lng(), newFieldName);
5434 //add new polygon to the array
5435 polygonsArray.push(selectedShape);
5436 $("#alertWrapper").append("<div class=\"alert-overlay modal-backdrop fade in\"></div>");
5437 displaySuccessMsg2(txtFd14);
5438 //$("#genSuccessAlert").show().find("span").first().empty().html(txtFd14);
5439 //displayStatusMessage("New boundary has been added successfully.");
5440 getFieldNoCache(getFieldId());
5441 $("#saveFieldBoundary").removeClass("has-field").hide();
5442 removeStatus();
5443 //update area status
5444 $(".current_field_area").text(area.toFixed(5));
5445
5446 $("#addBoundary").remove();
5447 //remove add boundary button
5448 str = fieldPanelIconContent(selectedShape.fieldId, area.toFixed(5));
5449 $(".current_field_area").prepend(str);
5450
5451 //if adding a new boundary to existing field, remove styling.
5452 removeItalicField(getFieldId());
5453 })
5454 .fail(function () {
5455 //display failure message.
5456 if (selectedShape) {
5457 selectedShape.setMap(null);
5458 setDrawPolygon(false);
5459 }
5460 removeStatus();
5461 })
5462}
5463
5464function populateFieldDetailsPlaceHoler(obj) {
5465
5466 var str = "Size : <span class=\"current_field_area\">" + obj.fieldArea + " Ha</span>";
5467
5468 if (obj.fieldCrop != "") {
5469 str += "<br/><span class=\"fld_crop_name\">Crop : " + obj.fieldCrop + "</span>";
5470 if (obj.fieldCropVar != "") {
5471 str += "<br/><span class=\"fld_crop_name_variety\">Variety : " + obj.fieldCropVar + "</span>";
5472 }
5473 }
5474
5475 if (obj.noBoundary == 0) {
5476 // str += "<span title=\"" + txtSmp1 + "\" class=\"download_fd_boundary glyphicon glyphicon-save-file\" id=\"downloadFieldBoundary\" rel=\"" + obj.fieldId + "\"></span>";
5477 str += fieldPanelIconContent(obj.fieldId, obj.fieldArea)
5478 str += "<input type=\"button\" id=\"saveEditedField\" value=\"Save changes\" class=\"edit_field_save_bt btn\" />";
5479 }
5480 else {
5481 str += "<span class=\"glyphicon glyphicon-plus-sign\" title=\"" + txtFd8 + "\" id=\"addBoundary\" rel=\"" + obj.fieldId + "\"></span>";
5482 str += "<button id=\"saveFieldBoundary\" disabled=\"disabled\" title=\"" + txtFd7 + "\">" + txtGen15 + "</button>";
5483 }
5484
5485 $(".fieldInfo").each(function () {
5486 if ($(this).attr("rel") == obj.fieldId) {
5487 $(this).empty().html(str).show();
5488 }
5489 else {
5490 $(this).empty().hide();
5491 }
5492 })
5493
5494 $("#f_" + obj.fieldId + " .fieldInfo").empty().html(str).show();
5495
5496 //get most recent field sample data
5497
5498
5499 $.ajax({
5500 url: urlPrepend + "/fielddata/ui_field_sample_" + obj.fieldId
5501 }).done(function (data) {
5502 if (data != null) {
5503 fld_sampleServiceLink(data.service, data.dateSampled, data.Id);
5504 fld_getMoreFieldSampleCount(obj.fieldId, data.Id);
5505 }
5506 }).fail(function () {
5507 $(".field_sample_service_link_wrapper").empty().html("<div class=\"fld_no_sample_results\">This field has no sample data</div>");
5508 });
5509}
5510
5511function fld_getMoreFieldSampleCount(fieldId, sampleId) {
5512 $.ajax({
5513 url: urlPrepend + "/fielddata/ui_field_sample_count_" + fieldId + "_" + sampleId
5514 }).done(function (data) {
5515 if (data != "0") {
5516 $(".fld_more_sample_results_lnk").show();
5517 }
5518 });
5519}
5520
5521
5522
5523
5524$(document).on("click", ".download_probelogger", function () {
5525 location.href = siteUrl + "Administration/MiFarm/DownloadProbeLogger.aspx?id=" + ($(this).parent().children(0).children(0).attr("id"));
5526 // window.open(siteUrl + "/Administration/MiFarm/DownloadFieldBoundary.aspx?id=" + getFieldId());
5527});
5528
5529var fld_more_sample_results_txt = "";
5530
5531$(document).on("click", ".fld_more_sample_results_lnk", function () {
5532
5533 var tmp_span = $(".fld_more_sample_results_lnk").find('span');
5534 if ($(".fld_sample_more_sample_results_icon").hasClass("glyphicon-chevron-down")) {
5535
5536
5537
5538
5539 if ($(".fld_more_sample_results_wrapper").children().children().length == 0) {
5540
5541 $(".fld_sample_more_sample_results_icon").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-left");
5542
5543 //populate sample results
5544 $(".fld_more_sample_results_lnk").text(txtFd29);
5545 $(".fld_more_sample_results_lnk").append(tmp_span);
5546 $(".fld_more_sample_results_wrapper").show();
5547
5548 $.ajax({
5549 url: urlPrepend + "/fielddata/ui_field_sample_" + getFieldId() + "_" + $(this).attr("rel")
5550 }).done(function (data) {
5551 if (data != null) {
5552
5553 $(".fld_more_sample_results_lnk").text(txtFd28);
5554 $(".fld_more_sample_results_lnk").append(tmp_span);
5555 $(".fld_sample_more_sample_results_icon").removeClass("glyphicon-chevron-left").addClass("glyphicon-chevron-up");
5556
5557 for (var i = 0; i < data.length; i++) {
5558 fld_more_sample_results_txt += "<div class=\"fld_more_sample_results_wrapper_item\"><div class=\"field_sample_service_link\"><span id=\"" + data[i].Id + "\">" + data[i].service + "</br>" + data[i].dateSampled.split(' ')[0] + "</span></div><div title=\"Download Probelogger File\" class=\"download_probelogger glyphicon glyphicon-save-file\"></div><div style=\"clear:both\"></div><ul rel=\"" + data[i].Id + "\" class=\"fld_recent_sample_nutrients\"></ul></div>";
5559 }
5560 $(".fld_more_sample_results_wrapper").empty().html(fld_more_sample_results_txt);
5561 }
5562 }).fail(function () {
5563 $(".field_sample_service_link_wrapper").empty().html("<div class=\"fld_no_sample_results\">This field has no sample data</div>");
5564 });
5565 }
5566 else {
5567 $(".fld_sample_more_sample_results_icon").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
5568 $(".fld_more_sample_results_lnk").text(txtFd28);
5569 $(".fld_more_sample_results_wrapper").show();
5570 $(".fld_more_sample_results_lnk").append(tmp_span);
5571 }
5572 }
5573 else {
5574 //show less
5575 $(".fld_more_sample_results_lnk").text(txtFd27);
5576 $(".fld_more_sample_results_lnk").append(tmp_span);
5577 $(".fld_sample_more_sample_results_icon").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
5578 $(".fld_more_sample_results_wrapper").hide();
5579 }
5580
5581
5582
5583});
5584
5585
5586
5587
5588function fld_sampleServiceLink(service, date, id) {
5589
5590 $(".field_sample_service_link_wrapper").empty().html("<div class=\"field_sample_service_link\"><span id=\"" + id + "\">" + service + "</br>" + date.split(' ')[0] + "</span></div><div title=\"Download Probelogger File\" class=\"download_probelogger glyphicon glyphicon-save-file\"></div><div style=\"clear:both\"></div><ul rel=\"" + id + "\" class=\"fld_recent_sample_nutrients\"></ul><p class=\"fld_more_sample_results_lnk\" rel=\"" + id + "\">" + txtFd27 + "<span class=\"fld_sample_more_sample_results_icon glyphicon glyphicon-chevron-down\"></span></p><div class=\"fld_more_sample_results_wrapper\"><img src=\"" + urlPrepend + "/Content/images/ajax-loader.gif\" /></div>");
5591
5592}
5593
5594function VRA_linkCheck(area) {
5595
5596
5597 if (area > 0.5) {
5598 $(".field_vra_link").empty().text("Create VRA Prescription Map").removeAttr("id").removeAttr("title");
5599 $(".field_vra_link").attr("id", "vraModal");
5600 $(".field_vra_link").attr("title", "Create a variable rate assessment application file");
5601 }
5602 else {
5603 $(".field_vra_link").empty().text("Field too small to create VRA map").removeAttr("id").removeAttr("title");
5604 $(".field_vra_link").attr("id", "no_vraModal");
5605 $(".field_vra_link").attr("title", "We're unable to create a variable rate assessment application for fields smaller than 0.5 Ha");
5606 }
5607}
5608
5609function fieldPanelIconContent(fieldId, fieldSize) {
5610 var str = "";
5611 str = "<div class=\"field-icons-wrapper\">";
5612 str += "<ul>";
5613 str += "<li>";
5614 str += "<span class=\"glyphicon glyphicon-pencil\" title=\"" + txtFd13 + "\" id=\"editField\" rel=\"" + fieldId + "\"></span>";
5615 str += "<span class=\"glyphicon glyphicon-remove\" title=\"" + txtFd12 + "\" id=\"deleteField\" rel=\"" + fieldId + "\"></span>";
5616 str += "<span class=\"glyphicon glyphicon-remove-circle\" title=\"" + txtFd11 + "\" id=\"deleteBoundary\" rel=\"" + fieldId + "\"></span>";
5617 str += "<span class=\"glyphicon glyphicon-repeat\" title=\"" + txtGen16 + "\" id=\"cancelChanges\" rel=\"" + fieldId + "\"></span>";
5618 str += "<span title=\"" + txtFd10 + "\" class=\"download_fd_boundary glyphicon glyphicon-save-file\" id=\"downloadFieldBoundary\" rel=\"" + fieldId + "\"></span>";
5619 str += "<span class=\"glyphicon icon-noun_413076_cc\" title=\"" + txtFd9 + "\" id=\"downloadShapeFile\" rel=\"" + fieldId + "\"></span>";
5620 str += "<span class=\"glyphicon glyphicon-phone send_boundary_to_nsensor\" title=\"" + txtFd22 + "\" id=\"sendToNsensor\" rel=\"" + fieldId + "\"></span>";
5621 str += "<span class=\"glyphicon glyphicon-move send_move_to_field\" title=\"" + txtFd26 + "\" id=\"moveToField\" rel=\"" + fieldId + "\"></span>";
5622 str += "<div class=\"field_notes_wrapper\"><span class=\"glyphicon icon-noun_notes_1353560\ field_notes\" title=\"" + txtFd38 + "\" rel=\"" + fieldId + "\"></div>";
5623 str += "</li>";
5624 //checking to see if user is using an ipad
5625 if (!gen_isiPad) {
5626 str += "<li style=\"float:left\">";
5627 str += "<div class=\"google-drawing-tool-wrapper\"><img class=\"holes-polygon-g-circle\" title=\"" + txtHoles11 + "\" src=\"" + urlPrepend + "/Content/images/drawing-circle.png\" rel=\"" + fieldId + "\"/>"
5628 str += "<img title=\"" + txtHoles10 + "\" class=\"holes-polygon-g-poly\" src=\"" + urlPrepend + "/Content/images/drawing-polygon.png\" rel=\"" + fieldId + "\"/></div>";
5629 str += "</li>";
5630 str += "<li>";
5631 str += "<span style=\"cursor:pointer\" class=\"glyphicon glyphicon-map-marker fld_icon_poi_icon\" title=\"" + txtFd25 + "\" id=\"dropPOI\" rel=\"" + fieldId + "\"></span>"
5632 if (getTradingId() == 2215) {
5633 str += "<span class=\"glyphicon glyphicon-leaf fld_icon_plant_recording_icon\" title=\"record plant flowering\" id=\"BE_Flowering\" rel=\"" + fieldId + "\"></span>";
5634 }
5635 if($('#sessionCustomerId').val() === "218"){
5636 str += "<span class=\"glyphicon glyphicon-fire fld_icon_poi_icon\" title=\"" + txtFd30 + "\" id=\"chemRecordsBtn\" rel=\"" + fieldId + "\"></span>";
5637 }
5638 str += "</li>";
5639 }
5640 else {
5641 str += "<li>";
5642 str += "<div class=\"google-drawing-tool-wrapper\"><img class=\"holes-polygon-g-circle\" title=\"" + txtHoles11 + "\" src=\"" + urlPrepend + "/Content/images/drawing-circle.png\" rel=\"" + fieldId + "\"/>"
5643 str += "<img title=\"" + txtHoles10 + "\" class=\"holes-polygon-g-poly\" src=\"" + urlPrepend + "/Content/images/drawing-polygon.png\" rel=\"" + fieldId + "\"/></div>";
5644 str += "</li>";
5645 str += "<li>";
5646 str += "<span style=\"cursor:pointer\" class=\"glyphicon glyphicon-map-marker fld_icon_poi_icon_ipad\" title=\"" + txtFd25 + "\" id=\"dropPOI\" rel=\"" + fieldId + "\"></span>"
5647 if (getTradingId() == 2215) {
5648 str += "<span class=\"glyphicon glyphicon-leaf fld_icon_plant_recording_icon_ipad\" title=\"record plant flowering\" id=\"BE_Flowering\" rel=\"" + fieldId + "\"></span>";
5649 }
5650 if ($('#sessionCustomerId').val() === "218") {
5651 str += "<span class=\"glyphicon glyphicon-fire fld_icon_poi_icon_ipad\" title=\"" + txtFd30 + "\" id=\"chemRecordsBtn\" rel=\"" + fieldId + "\"></span>";
5652 }
5653 str += "</li>";
5654 }
5655
5656
5657
5658 str += "</ul>";
5659 if (fieldSize > 0.5) {
5660 str += "<span class=\"field_vra_link\" id=\"vraModal\" title=\"Create a variable rate assessment application file\">Create VRA Prescription Map</span>";
5661 }
5662 else {
5663 str += "<span class=\"field_vra_link\" id=\"no_vraModal\" title=\"We're unable to create a variable rate assessment application for fields smaller than 0.5 Ha\">Field too small to create VRA map</span>"
5664 }
5665
5666
5667 if (getTradingId() == 2215) {
5668 //viewing birdseye so add link to harvest polygon modal.
5669 str += "<span class=\"field_harvest_shape_link\" id=\"harvestShapeModal\" title=\"Create harvest shape\">Create Harvest Shape Areas</span>";
5670 }
5671 str += "<div class=\"field_sample_service_link_wrapper\"><div class=\"fld_get_recent_sample_results\">Checking recent sample results</div></div>";
5672 str += "</div>";
5673 return str;
5674}
5675
5676function removeItalicField(id) {
5677
5678 $(".field_item_selected").removeClass("no-field");
5679
5680 ////v2 - UI
5681 ////$(".field_item").each(function () {
5682 //// if ($(this).attr("id").split("_")[1] == id) {
5683 //// $(this).removeClass("no-field");
5684 //// }
5685 ////})
5686}
5687
5688function addPolygonClickEvent(polygon) {
5689
5690 //onclick zoom into field
5691 google.maps.event.addListener(polygon, 'click', function (event) {
5692
5693 if (!checkServiceFormIsVisible()) {
5694 closeAllLayerLists(true);
5695
5696
5697 //get mode of what user is doing to the field
5698 var mode = $(".google-drawing-tool-wrapper").attr("mode");
5699 switch (mode) {
5700 case "genCircle":
5701 //disabled as it was generating circles on the field after creating circle-holes on the modal-hole-map.
5702 // generateCicleHole(event.latLng);
5703 break;
5704 default:
5705 getField(this.id);
5706 }
5707 }
5708 else {
5709 addServiceToField(this.id);
5710 //change colour of polygon
5711 this.setOptions({
5712 fillColor: '#1EDBFC'
5713 })
5714 serviceOrderPolygons.push(this.id);
5715 }
5716 chkUserAddingField();
5717 });
5718
5719}
5720
5721function addPolygonMouseCoordsData(polygon) {
5722 polygon.addListener('mousemove', function (event) {
5723 var lat = event.latLng.lat();
5724 var lng = event.latLng.lng();
5725 var OSNE = new LLtoNE(lat, lng);
5726
5727 $(".mapCursor_Info1").html((lat.toFixed(5) + "," + lng.toFixed(5)))
5728 $(".mapCursor_Info2").html("N/E : " + OSNE.north + "," + OSNE.east);
5729 $(".mapCursor_Info3").html("OS : " + NE2NGR(OSNE.north, OSNE.east));
5730
5731 });
5732}
5733
5734function panAllFields() {
5735
5736 var tempBounds = new google.maps.LatLngBounds();
5737 for (var i = 0; i < polygonsArray.length; i++) {
5738 for (var j = 0; j < polygonsArray[i].getPath().getLength() ; j++) {
5739 var xy = polygonsArray[i].getPath().getAt(j);
5740 tempBounds.extend(xy);
5741 }
5742 }
5743 map.fitBounds(tempBounds);
5744}
5745
5746//function resetFieldPanelContent() {
5747// $("#fieldInfo").empty().html("Farm : " + $("#selecteFarmName").val());
5748//}
5749
5750/******************************* holes field modal stuff ***********************/
5751
5752var holesModal_Map;
5753
5754window.closeHolesModal = function () {
5755 $('#holes_Modal').hide();
5756};
5757
5758
5759var hole_circle = null;
5760var hole_rectangle = null;
5761var hole_field_polygon = null;
5762var holes_Map;
5763var hole_polygons = [];
5764var hole_setPoly;
5765var arrHolesMVCArray = [];
5766var holes_circleCentrePt;
5767var holes_bNewPolyCW = false;
5768var holes_drawingManager;
5769
5770var removeCutouts = [];
5771
5772function closestDistanceToSegment(center, segment, poly) {
5773 var firstPoint, lastPoint, A, B, C, D, E, distanceAB, t, projection = holes_Map.getProjection();
5774
5775 // The other extreme of the path
5776 lastPoint = segment[0];
5777
5778 // One extreme of the path
5779 firstPoint = segment[1];
5780
5781 // C
5782 // |\
5783 // | \
5784 // | \
5785 // |_ _\
5786 // A B
5787 //
5788 // Transform to points
5789 A = projection.fromLatLngToPoint(lastPoint);
5790 B = projection.fromLatLngToPoint(firstPoint);
5791 C = projection.fromLatLngToPoint(center);
5792
5793 // Calculte distance between A and B
5794 distanceAB = Math.sqrt(Math.pow(A.x - B.x, 2) + Math.pow(A.y - B.y, 2));
5795
5796 // Compute the direction vector D from A to B
5797 D = { x: (B.x - A.x) / distanceAB, y: (B.y - A.y) / distanceAB };
5798
5799 t = D.x * (C.x - A.x) + D.y * (C.y - A.y);
5800
5801 // LatLng of the point
5802 E = projection.fromPointToLatLng({ x: t * D.x + A.x, y: t * D.y + A.y });
5803
5804 // hole_polygons[i].setPath(segment);
5805
5806 // En la docuemntacion poly.containsLocation sirve para Polygonos.
5807 // poly.isLocationOnEdge no es muy preciso
5808
5809 if (google.maps.geometry.poly.containsLocation(E, poly)) {
5810 return google.maps.geometry.spherical.computeDistanceBetween(E, center);
5811 }
5812
5813 return Number.POSITIVE_INFINITY;
5814}
5815
5816$("#holes_Modal .close").click(function () {
5817 $("#holes_Modal").hide();
5818 removeOverlay();
5819 holes_drawingManager.setDrawingMode(null);
5820 holes_drawingManager.setMap(map)
5821 removeCutouts = [];
5822});
5823
5824//$("#holes_Modal").on("hidden.bs.modal", function () {
5825// removeCutouts = [];
5826//});
5827
5828$(document).on("click", "#redrawHoles", function () {
5829 $(this).hide();
5830 $("#holes_Modal").find(".alert-danger").hide().find("p").empty();
5831
5832 if (hole_status == "genSq") {
5833
5834 }
5835 if (hole_status == "genCircle") {
5836 //hide circle polygon
5837 hole_setPoly.setMap(null);
5838
5839 holes_drawingManager = new google.maps.drawing.DrawingManager({
5840 drawingMode: google.maps.drawing.OverlayType.CIRCLE,
5841 drawingControl: false,
5842 drawingControlOptions: {
5843 drawingModes: ['circle']
5844 },
5845
5846 circleOptions: {
5847 fillColor: '#ffff00',
5848 fillOpacity: 0.5,
5849 strokeWeight: 1,
5850 clickable: false,
5851 editable: true,
5852 zIndex: 1
5853 }
5854 });
5855 holes_drawingManager.setMap(holes_Map);
5856
5857 google.maps.event.addListener(holes_drawingManager, 'circlecomplete', function (circle) {
5858 holes_drawingManager.setMap(null);
5859 hole_fn_passCircle(circle, hole_field_polygon);
5860 holes_fn_chkPointInPolygonCircle(circle, hole_field_polygon);
5861
5862 google.maps.event.addListener(circle, 'center_changed', function () {
5863 holes_fn_chkPointInPolygonCircle(circle, hole_field_polygon);
5864 });
5865
5866 google.maps.event.addListener(circle, 'radius_changed', function () {
5867 holes_fn_chkPointInPolygonCircle(circle, hole_field_polygon);
5868 });
5869 });
5870 }
5871 if (hole_status == "genPoly") {
5872 //hide polygon
5873 hole_setPoly.setMap(null);
5874 holes_fn_drawPoly(holes_Map, hole_field_polygon);
5875 }
5876});
5877
5878function reversePath(path, direction) {
5879 var hole_fieldboundary = [];
5880 //if polygon is clockwise, we need to revert this to anti-clockwise as its a hole.
5881 //clockwise = true; anti-clockwise = false;
5882 if (direction) {
5883 for (var i = (path.getLength() - 1) ; i >= 0; i--) {
5884 hole_fieldboundary.push(new google.maps.LatLng(path.getAt(i).lat(), path.getAt(i).lng()));
5885 }
5886 }
5887 else {
5888 for (var j = 0; j < path.getLength() ; j++) {
5889 hole_fieldboundary.push(new google.maps.LatLng(path.getAt(j).lat(), path.getAt(j).lng()));
5890 }
5891 }
5892 return hole_fieldboundary;
5893}
5894
5895$(document).on("click", "#submitHolesModal", function () {
5896 window.parent.closeHolesModal();
5897 var hole_boundary = [];
5898 var bPassed = true;
5899 holes_bNewPolyCW = false;
5900 //if (hole_status == "genSq") {
5901
5902 //}
5903 if (hole_status == "genPoly") {
5904 //make polygon uneditable
5905 hole_setPoly.setOptions({
5906 fillColor: 'red',
5907 fillOpacity: 0.5,
5908 strokeColor: 'red',
5909 editable: false
5910 });
5911
5912 //if polygon is clockwise, we need to revert this to anti-clockwise as its a hole.
5913 hole_boundary = reversePath(hole_setPoly.getPath(), polygonDirection(hole_setPoly.getPath()));
5914
5915 //check points are still in polygon field
5916 for (var i = 0; i < hole_setPoly.getPath().getLength() ; i++) {
5917
5918 if (!hole_field_polygon.containsLatLng(hole_setPoly.getPath().getAt(i).lat(), hole_setPoly.getPath().getAt(i).lng())) {
5919 $("#holes_Modal").find(".alert-danger").show().find("p").empty().text(txtHoles9);
5920 $("#submitHolesModal").hide();
5921 $("#redrawHoles").show();
5922 $('#removeCutouts').hide();
5923 bPassed = false;
5924 break;
5925 }
5926 }
5927
5928 //make sure path is the correct direction.
5929 if (polygonDirection(hole_setPoly.getPath())) {
5930 holes_bNewPolyCW = true;
5931 }
5932 }
5933
5934 if (hole_status == "genCircle") {
5935
5936 //hide drawn circle
5937 hole_circle.setMap(null);
5938 hole_field_polygon.setMap(null);
5939
5940 //create a new poly with coords from drawn circle.
5941 hole_setPoly = new google.maps.Polygon({
5942 map: holes_Map,
5943 paths: [hole_fn_circlePath(hole_circle)],
5944 fillColor: 'red',
5945 fillOpacity: 0.5,
5946 strokeColor: 'red',
5947 editable: false
5948 });
5949 hole_boundary = reversePath(hole_setPoly.getPath(), polygonDirection(hole_setPoly.getPath()));
5950 }
5951
5952 var fieldArea = $(".current_field_area").text().replace(" Ha", "");
5953
5954 //redraw field boundary
5955 holes_fn_drawFieldPoly();
5956
5957 //calculate new fieldsize
5958 var mainpolyArea = fieldArea - hole_calcPolyArea(hole_setPoly.getPath());
5959 $(".current_field_area").text(mainpolyArea.toFixed(2) + " Ha");
5960 ////does our shape intercept any boundary
5961 if (bPassed) {
5962
5963 loadStatus(txtHoles8);
5964
5965 //save new shape.
5966 var jsonClosingShape;
5967 var json = "{\"points\":[";
5968 //create json of coordinates
5969 for (var j = 0; j < hole_boundary.length ; j++) {
5970 json += "{\"lat\":\"" + hole_boundary[j].lat() + "\",\"lng\":\"" + hole_boundary[j].lng() + "\",\"ishole\":\"true\"}";
5971
5972 if (j == 0) {
5973 jsonClosingShape = "{\"lat\":\"" + hole_boundary[j].lat() + "\",\"lng\":\"" + hole_boundary[j].lng() + "\",\"ishole\":\"true\"}";
5974 }
5975 json += ",";
5976 }
5977 json += jsonClosingShape + "]}]";
5978
5979 jsonStart = "[{\"size\": \"" + mainpolyArea.toFixed(2) + "\"},";
5980
5981 $.ajax({
5982 type: "POST",
5983 url: urlPrepend + "/fielddata/newhole-" + getFieldId(),
5984 data: { strJson: jsonStart + json },
5985 success: function (data) {
5986 //hide modal
5987 $('#holes_Modal').modal('hide');
5988 if (data) {
5989 //focus back on field
5990 hole_fn_redrawHoleToField();
5991 window.parent.closeHolesModal();
5992 }
5993 else {
5994 $("#genDangerAlert").show().find("span").first().empty().html(txtHoles7);
5995 }
5996 removeLoader();
5997 },
5998 error: function () {
5999 $("#genDangerAlert").show().find("span").first().empty().html(txtHoles6);
6000 removeLoader();
6001 }
6002 });
6003 }
6004});
6005
6006function hole_fn_redrawHoleToField() {
6007
6008 //we need to redraw the fieldboundary with the new hole on the main map.
6009 for (var i = 0; i < polygonsArray.length; i++) {
6010 //get the field from polygon array
6011 if (polygonsArray[i].get("id") == getFieldId()) {
6012
6013 var newHolePolyPath = new google.maps.MVCArray();
6014 var arrHolesMVCArray = [];
6015
6016 //new field may have been drawn in an anti cw direction. We will have to reverse the points order.
6017 if (!polygonDirection(polygonsArray[i].getPath())) {
6018 //new field drawn anti clockwise, so we need to turn the direction to clockwise!
6019 //get points of polygon, add them to array and reverse the array. Delete polygon points and add them back in the correct way
6020 var antiClockWisePtsArray = [];
6021 for (var k = 0; k < polygonsArray[i].getPath().getLength() ; k++) {
6022 antiClockWisePtsArray.push(new google.maps.LatLng(polygonsArray[i].getPath().getAt(k).lat(), polygonsArray[i].getPath().getAt(k).lng()));
6023 }
6024 //add extra point to close polygon loop
6025 if (antiClockWisePtsArray.length > 0) {
6026 antiClockWisePtsArray.push(new google.maps.LatLng(polygonsArray[i].getPath().getAt(0).lat(), polygonsArray[i].getPath().getAt(0).lng()));
6027 }
6028
6029 //reverse points so that the direction of pts is cw
6030 antiClockWisePtsArray.reverse();
6031
6032 //loop through new order of points
6033 for (var m = 0; m < antiClockWisePtsArray.length; m++) {
6034 //remove old coordinate
6035 polygonsArray[i].getPath().removeAt(m);
6036 //insert new coordinate
6037 polygonsArray[i].getPath().insertAt(m, antiClockWisePtsArray[m]);
6038 }
6039
6040 highlightSelectedField(polygonsArray[i].get("id"), true, null);
6041
6042 for (var j = hole_setPoly.getPath().getLength() - 1; j >= 0; j--) {
6043 newHolePolyPath.push(new google.maps.LatLng(hole_setPoly.getPath().getAt(j).lat(), hole_setPoly.getPath().getAt(j).lng()));
6044 if (j == 0) {
6045 //add last point to close the polygon
6046 newHolePolyPath.push(new google.maps.LatLng(hole_setPoly.getPath().getAt(hole_setPoly.getPath().getLength() - 1).lat(), hole_setPoly.getPath().getAt(hole_setPoly.getPath().getLength() - 1).lng()));
6047 }
6048 }
6049 }
6050 else {
6051 //we are because the polygon was drawn in a clockwise direction
6052
6053 //holes_bNewPolyCW tells us which direction the polygon was drawn
6054
6055 if (!holes_bNewPolyCW && (hole_status != "genCircle")) {
6056 for (var j = 0; j < hole_setPoly.getPath().getLength() ; j++) {
6057 newHolePolyPath.push(new google.maps.LatLng(hole_setPoly.getPath().getAt(j).lat(), hole_setPoly.getPath().getAt(j).lng()));
6058 }
6059 newHolePolyPath.push(new google.maps.LatLng(hole_setPoly.getPath().getAt(0).lat(), hole_setPoly.getPath().getAt(0).lng()));
6060 }
6061 else {
6062 for (var j = hole_setPoly.getPath().getLength() - 1; j >= 0; j--) {
6063 newHolePolyPath.push(new google.maps.LatLng(hole_setPoly.getPath().getAt(j).lat(), hole_setPoly.getPath().getAt(j).lng()));
6064 if (j == 0) {
6065 //add last point to close the polygon
6066 newHolePolyPath.push(new google.maps.LatLng(hole_setPoly.getPath().getAt(hole_setPoly.getPath().getLength() - 1).lat(), hole_setPoly.getPath().getAt(hole_setPoly.getPath().getLength() - 1).lng()));
6067 }
6068 }
6069 }
6070 }
6071
6072
6073 //get exisitng field boundary and any existing holes
6074 polygonsArray[i].getPaths().forEach(function (path, index) {
6075 arrHolesMVCArray.push(path);
6076 });
6077
6078 //add new hole to array
6079 if (newHolePolyPath.length > 0) {
6080 arrHolesMVCArray.push(newHolePolyPath);
6081 }
6082 //add field boundary, existing holes and new hole to polygon path
6083 polygonsArray[i].setPaths(arrHolesMVCArray);
6084 removeOverlay();
6085 }
6086 }
6087}
6088
6089function hole_calcPolyArea(path) {
6090 var area = google.maps.geometry.spherical.computeArea(path, 6371);
6091 return (area * 100);
6092}
6093
6094function hole_fn_intersectCircleChk(poly) {
6095
6096 var path = poly.getPath(),
6097 totalPoints = path.getLength(),
6098 center = hole_circle.getCenter(),
6099 radius = hole_circle.getRadius(),
6100 intersect = false,
6101 indice = 0;
6102
6103 while (indice < totalPoints && intersect === false) {
6104 var point = path.getAt(indice++);
6105 if (google.maps.geometry.spherical.computeDistanceBetween(center, point) <= radius || (indice < totalPoints && closestDistanceToSegment(center, [point, path.getAt(indice)], poly) <= radius)) {
6106 return true;
6107 }
6108 }
6109 return false;
6110}
6111
6112function hole_fn_circlePath(circle) {
6113 var numPts = 45;
6114 var path = [];
6115 for (var i = 0; i < numPts; i++) {
6116 path.push(google.maps.geometry.spherical.computeOffset(circle.getCenter(), circle.getRadius(), i * 360 / numPts));
6117 }
6118 return path;
6119}
6120
6121function hole_fn_passCircle(obj, poly) {
6122 hole_circle = obj;
6123 hole_field_polygon = poly;
6124}
6125
6126function hole_fn_passRectangle(obj, poly) {
6127 hole_rectangle = obj;
6128 hole_field_polygon = poly;
6129}
6130
6131function displayHoleModalField() {
6132 //clear global vars
6133 hole_polygons = [];
6134 hole_circle = null;
6135 hole_field_polygon = null;
6136 hole_setPoly = null;
6137 hole_status = $(".google-drawing-tool-wrapper").attr("mode");
6138 removeCutouts = [];
6139
6140 //make sure all consle elements have been reset
6141 $("#submitHolesModal").hide();
6142 $("#redrawHoles").hide();
6143 $('#removeCutouts').show();
6144 $('#allowCuttingAgain').hide();
6145 $('#saveRemovedCutouts').hide();
6146 $("#holes_Modal").find(".alert-danger").hide().find("p").empty();
6147
6148 $.ajax({
6149 type: "POST",
6150 url: urlPrepend + "/fielddata/boundary",
6151 data: { id: getFieldId() }
6152 })
6153 .done(function (data) {
6154 if (data != "") {
6155 //addOverlay(); // Tihomir
6156 holes_Map = new google.maps.Map(document.getElementById('holes_ModalMap'),
6157 {
6158 streetViewControl: false,
6159 mapTypeId: google.maps.MapTypeId.SATELLITE
6160 });
6161
6162 google.maps.event.addListener(holes_Map, 'click', function( event ){ // Tihomir
6163
6164 /// <summary>We start the loop from index 1 because the 1 index is the whole field, the biggest polygon that contains the rest of the cutouts.</summary>
6165 for (var j = 1; j < hole_polygons.length; j++) {
6166 if (hole_polygons[j].containsLatLng(event.latLng.lat(), event.latLng.lng())) {
6167 let fieldId = hole_polygons[j].get("id");
6168 let fieldHoleIndex = j;
6169
6170 // we use this two variable to update the new area of the field, we get size of the cutout we just removed and add it to the whole area size
6171
6172
6173 let points = [];
6174 for (var o = 0; o < hole_polygons[j].getPath().getLength(); o++) {
6175 let latStr = hole_polygons[j].getPath().getAt(o).lat().toString();
6176 let lngStr = hole_polygons[j].getPath().getAt(o).lng().toString();
6177
6178 // lat
6179 let indexOfDot = latStr.indexOf('.') + 1; // Get the decimal dot
6180
6181 let latAfterDotFull = latStr.substring(indexOfDot, latStr.length); // Get the decimal numbers after the decimal dot
6182
6183 // Check if the numbers after the dec dot are with length > 10, if yes, cut the rest of the numbers.
6184 // We do that because when looked up in the database, some numbers are rounded up to 15/16 digits, some are not.
6185 // And by cutting it at the 10th digit, we make sure we can find the number.
6186 if(latAfterDotFull.length > 10){
6187 let latShortenTo10Symb = latStr.substring(indexOfDot, indexOfDot + 10);
6188 latStr = latStr.substring(0, indexOfDot) + latShortenTo10Symb;
6189 }
6190
6191
6192 // lng
6193 let lngIndexOfDot = lngStr.indexOf('.') + 1; // Get the decimal dot
6194
6195 let lngAfterDotFull = lngStr.substring(lngIndexOfDot, lngStr.length); // Get the decimal numbers after the decimal dot
6196
6197 //// Check if the numbers after the dec dot are with length > 10, if yes, cut the rest of the numbers.
6198 //// We do that because when looked up in the database, some numbers are rounded up to 15/16 digits, some are not.
6199 //// And by cutting it at the 10th digit, we make sure we can find the number.
6200 if(lngAfterDotFull.length > 10){
6201 let lngShortenTo10Symb = lngStr.substring(lngIndexOfDot, lngIndexOfDot + 10);
6202 lngStr = lngStr.substring(0, lngIndexOfDot) + lngShortenTo10Symb;
6203 }
6204
6205
6206 let currentPoint = {
6207 lat: latStr,
6208 lng: lngStr,
6209 fieldId: fieldId
6210 };
6211 points.push(currentPoint);
6212 }
6213
6214 let innerHolePointsCount = hole_polygons[j].getPath().length;
6215
6216 let areaOfCurrentHole = hole_calcPolyArea(hole_polygons[j].getPath());
6217 let cutoutPointsInfo = {holeIndex: fieldHoleIndex, points: points, areaOfCurrentHole: areaOfCurrentHole};
6218 removeCutouts.push(cutoutPointsInfo);
6219
6220 ///// <summary>Used to remove polygon's inner hole's points.</summary>
6221 for (var t = 0; t < innerHolePointsCount; t++) {
6222 hole_polygons[j].getPath().removeAt(0);
6223 }
6224
6225 break; // we break here because we dont need to loop through the rest of the holes.
6226 }
6227 }
6228 });
6229 var t = JSON.parse(data);
6230 var fieldboundary = new google.maps.MVCArray();
6231 var fieldboundary4directionChk = [];
6232 var polygon1stPt = "";
6233 arrHolesMVCArray = []; //this array will contain an array of hole_fieldboundary
6234 var hole_fieldboundary = new google.maps.MVCArray();
6235 var hole_bStartNewPolygon = false;
6236 var bStartNewPolygon = false;
6237
6238 for (var j = 0; j < t.length; j++) {
6239
6240 if (t[j].ishole == "False") {
6241 //this is a field
6242 fieldboundary.push(new google.maps.LatLng(t[j].lat, t[j].lng));
6243
6244 fieldboundary4directionChk.push(new google.maps.LatLng(t[j].lat, t[j].lng));
6245 // bStartNewPolygon = true;
6246 }
6247 else {
6248 //this is a hole
6249 hole_fieldboundary.push(new google.maps.LatLng(t[j].lat, t[j].lng));
6250 if (!hole_bStartNewPolygon) {
6251 polygon1stPt = new google.maps.LatLng(t[j].lat, t[j].lng);
6252 hole_bStartNewPolygon = true;
6253 }
6254 else {
6255 if (polygon1stPt.equals(new google.maps.LatLng(t[j].lat, t[j].lng))) {
6256 arrHolesMVCArray.push(hole_fieldboundary);
6257 //reset
6258 if ((t.length - 1) != j) {
6259 hole_fieldboundary = new google.maps.MVCArray();
6260 }
6261
6262 hole_bStartNewPolygon = false; //get first point of hole
6263 }
6264 }
6265
6266 if (j == t.length - 1) {
6267 //*map bounds
6268 target_MapBounds = new google.maps.LatLngBounds();
6269 for (var i = 0; i < fieldboundary.getLength() ; i++) {
6270 target_MapBounds.extend(fieldboundary.getAt(i));
6271 }
6272 holes_Map.fitBounds(target_MapBounds);
6273 //***end :: map bounds
6274
6275 ////for global work - add polygon to array
6276 hole_polygons.push(holes_fn_singlePoly(fieldboundary));
6277
6278 //use for local array in this function
6279 var polypath = [];
6280
6281 //check direction, do we need to reverse.
6282 if (!polygonDirection(fieldboundary4directionChk)) {
6283 //poly is anitclockwise - change direction.
6284 fieldboundary4directionChk.reverse();
6285 }
6286
6287 polypath.push(fieldboundary4directionChk);
6288 for (var i = 0; i < arrHolesMVCArray.length; i++) {
6289 polypath.push(arrHolesMVCArray[i]);
6290 ////for global work - add polygon to array
6291 hole_polygons.push(holes_fn_singlePoly(arrHolesMVCArray[i]));
6292 }
6293 //***end :: use for local array in this function
6294
6295 var polygon = new google.maps.Polygon({
6296 id: getFieldId(),
6297 paths: polypath,
6298 map: holes_Map,
6299 highlight: true,
6300 fillColor: '#3DD62F',
6301 strokeColor: '#083508',
6302 strokeOpacity: 0.8,
6303 strokeWeight: 5,
6304 fillOpacity: 0.35
6305 });
6306
6307 polygon.setMap(holes_Map);
6308
6309 if (hole_status == "genSq") {
6310 holes_fn_drawSq(holes_Map, polygon);
6311 }
6312 if (hole_status == "genPoly") {
6313 holes_fn_drawPoly(holes_Map, polygon);
6314 }
6315 if (hole_status == "genCircle") {
6316 holes_fn_drawCircle(holes_Map, polygon);
6317 }
6318 }
6319 }
6320 }
6321
6322 if ((hole_fieldboundary.length == 0 && fieldboundary.length > 0)) {
6323
6324 //draw normal no holes field.
6325 target_MapBounds = new google.maps.LatLngBounds();
6326
6327 for (var i = 0; i < fieldboundary.getLength() ; i++) {
6328 target_MapBounds.extend(fieldboundary.getAt(i));
6329 }
6330
6331 holes_Map.fitBounds(target_MapBounds);
6332
6333 var polygon = new google.maps.Polygon({
6334 id: getFieldId(),
6335 paths: fieldboundary4directionChk,
6336 map: holes_Map,
6337 highlight: true,
6338 fillColor: '#3DD62F',
6339 strokeColor: '#083508',
6340 strokeOpacity: 0.8,
6341 strokeWeight: 5,
6342 fillOpacity: 0.35
6343 });
6344
6345 hole_polygons.push(polygon);
6346 polygon.setMap(holes_Map);
6347 if (hole_status == "genSq") {
6348 holes_fn_drawSq(holes_Map, polygon);
6349 }
6350 if (hole_status == "genPoly") {
6351 holes_fn_drawPoly(holes_Map, polygon);
6352 }
6353 if (hole_status == "genCircle") {
6354 holes_fn_drawCircle(holes_Map, polygon);
6355 }
6356 }
6357 }
6358 else {
6359 //$("#targetServiceStage2").modal("hide");
6360 //displayErrMsg("This field does not have a boundary to map.");
6361 }
6362 });
6363}
6364
6365var fld_tempPoly = null;
6366
6367$(document).on('click', '#saveRemovedCutouts', function(){
6368
6369 let currentCutoutsCount = hole_polygons.length - 1;
6370
6371 if(removeCutouts.length === 0){
6372 //displayErrMsg("Please select a cutout first.");
6373 $("#holes_Modal").find(".alert-danger").show().find("p").empty().text("You have " + currentCutoutsCount + " cutouts within this field. Please select a cutout before proceeding.");
6374 return;
6375 }
6376 let fieldArea = parseFloat($(".current_field_area").text().replace(" Ha", ""));
6377
6378 for (var i = 0; i < removeCutouts.length; i++) {
6379 fieldArea = fieldArea + removeCutouts[i].areaOfCurrentHole;
6380 }
6381
6382 //calculate new fieldsize
6383 $(".current_field_area").text(fieldArea.toFixed(2) + " Ha");
6384
6385 //addOverlay();
6386 loadStatus("Removing cutout....");
6387 debugger;
6388 $.ajax({
6389 type: "POST",
6390 url: urlPrepend + "/fielddata/RemoveFieldHole",
6391 contentType: 'application/json',
6392 data: JSON.stringify(
6393 {
6394 holesToRemove: removeCutouts,
6395 newArea: fieldArea,
6396 fieldId: getFieldId()
6397 })
6398 })
6399 .done(function (data) {
6400 debugger;
6401 if(data.pointsDeleted == true){
6402
6403 hole_removed_redrawField();
6404 removeOverlay();
6405 removeLoader();
6406 //fld_loadFieldBoundary();
6407 }else if(data.pointsDeleted == false){
6408 removeOverlay();
6409 removeLoader();
6410 displayErrMsg("An error occured and no cutouts were removed.");
6411 }
6412 });
6413
6414 window.parent.closeHolesModal();
6415})
6416
6417function holes_fn_drawCircle(map, polygon) {
6418 holes_drawingManager = new google.maps.drawing.DrawingManager({
6419 drawingMode: google.maps.drawing.OverlayType.CIRCLE,
6420 drawingControl: false,
6421 drawingControlOptions: {
6422 drawingModes: ['circle']
6423 },
6424
6425 circleOptions: {
6426 fillColor: '#ffff00',
6427 fillOpacity: 0.5,
6428 strokeWeight: 1,
6429 clickable: false,
6430 editable: true,
6431 zIndex: 1
6432 }
6433 });
6434 holes_drawingManager.setMap(map);
6435
6436 fld_tempPoly = polygon;
6437
6438 google.maps.event.addListener(holes_drawingManager, 'circlecomplete', function (circle, polygon) {
6439 holes_drawingManager.setMap(null);
6440 hole_fn_passCircle(circle, fld_tempPoly);
6441 holes_fn_chkPointInPolygonCircle(circle, fld_tempPoly);
6442
6443 google.maps.event.addListener(circle, 'center_changed', function () {
6444
6445 holes_fn_chkPointInPolygonCircle(circle, fld_tempPoly);
6446 });
6447
6448 google.maps.event.addListener(circle, 'radius_changed', function () {
6449
6450
6451 holes_fn_chkPointInPolygonCircle(circle, fld_tempPoly);
6452 });
6453 });
6454}
6455
6456function holes_fn_drawPoly(map, fieldPolygon) {
6457 hole_field_polygon = fieldPolygon;
6458
6459 holes_drawingManager = new google.maps.drawing.DrawingManager({
6460 drawingMode: google.maps.drawing.OverlayType.POLYGON,
6461 drawingControl: false,
6462 drawingControlOptions: {
6463 drawingModes: ['polygon']
6464 },
6465
6466 polygonOptions: {
6467 fillColor: '#ffff00',
6468 fillOpacity: 0.5,
6469 strokeWeight: 1,
6470 clickable: false,
6471 editable: true,
6472 zIndex: 1
6473 }
6474 });
6475 holes_drawingManager.setMap(map);
6476
6477 google.maps.event.addListener(holes_drawingManager, 'polygoncomplete', function (polygon) {
6478 holes_drawingManager.setMap(null);
6479 holes_fn_chkPointinPolygonPoly(polygon, fieldPolygon);
6480
6481
6482 //check hole foe interescts
6483 var intersects = fld_fieldBoundaryInsertsect(polygon.getPath());
6484
6485 if (intersects && intersects.length) {
6486 $("#holes_Modal").find(".alert-danger").show().find("p").show().empty().text(txtHoles12)
6487 $("#submitHolesModal").hide();
6488 $("#redrawHoles").show();
6489 $('#removeCutouts').hide();
6490 polygon.setMap(null);
6491 }
6492
6493 polygon.getPaths().forEach(function (path, index) {
6494 google.maps.event.addListener(path, 'set_at', function () {
6495 //point moved - recheck polygon is valid.
6496 holes_fn_chkPointinPolygonPoly(polygon, fieldPolygon);
6497 });
6498
6499 google.maps.event.addListener(path, 'insert_at', function () {
6500 //new point - recheck polygon is valid.
6501 holes_fn_chkPointinPolygonPoly(polygon, fieldPolygon);
6502 });
6503
6504 google.maps.event.addListener(path, 'remove_at', function () {
6505 // Point was removed
6506 holes_fn_chkPointinPolygonPoly(polygon, fieldPolygon);
6507 });
6508 });
6509 });
6510}
6511
6512function holes_fn_drawSq(map, polygon) {
6513 holes_drawingManager = new google.maps.drawing.DrawingManager({
6514 drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
6515 drawingControl: false,
6516 drawingControlOptions: {
6517 drawingModes: ['rectangle']
6518 },
6519
6520 rectangleOptions: {
6521 fillColor: '#ffff00',
6522 fillOpacity: 0.5,
6523 strokeWeight: 1,
6524 clickable: false,
6525 editable: true,
6526 zIndex: 1
6527 }
6528 });
6529 holes_drawingManager.setMap(map);
6530
6531 google.maps.event.addListener(holes_drawingManager, 'click', function (rectangle) {
6532
6533 });
6534
6535 google.maps.event.addListener(holes_drawingManager, 'rectanglecomplete', function (rectangle) {
6536
6537 //holes_drawingManager.setMap(null);
6538 //hole_fn_passRectangle(rectangle, polygon);
6539 //holes_fn_chkPointInPolygonRect(rectangle, polygon);
6540 });
6541}
6542
6543function hole_removed_redrawField() { // Tihomir
6544 //we need to redraw the fieldboundary with the removed hole on the main map.
6545 for (var i = 0; i < polygonsArray.length; i++) {
6546 //get the field from the polygon array
6547 if (polygonsArray[i].get("id") == getFieldId()) {
6548 var arrHolesMVCArray = [];
6549
6550 // add all existing field boundaries and holes of the polygon, except the one that has been removed.\
6551 // indexOfRemovedHole is provided by the remove function, taken from hole_polygons.
6552 let polygonHolesIndexesToRemove = [];
6553 for (var j = 0; j < removeCutouts.length; j++) {
6554 polygonHolesIndexesToRemove.push(removeCutouts[j].holeIndex);
6555 }
6556
6557 polygonsArray[i].getPaths().forEach(function (path, index) {
6558 if(polygonHolesIndexesToRemove.includes(index) === false){
6559 arrHolesMVCArray.push(path);
6560 }
6561 //if(index != indexOfRemovedHole){
6562 //arrHolesMVCArray.push(path);
6563 //}
6564 });
6565
6566 //add field boundary, existing holes without the removed hole to polygon path
6567 polygonsArray[i].setPaths(arrHolesMVCArray);
6568 removeCutouts = []; // We reset the currently selected to remove fields.
6569 }
6570 }
6571}
6572
6573function holes_fn_chkPointinPolygonPoly(polygon, field) {
6574 hole_setPoly = polygon;
6575 var bPassed = true;
6576 for (var i = 0; i < polygon.getPath().getLength() ; i++) {
6577
6578 if (!field.containsLatLng(polygon.getPath().getAt(i).lat(), polygon.getPath().getAt(i).lng())) {
6579 $("#holes_Modal").find(".alert-danger").show().find("p").empty().text(txtHoles4)
6580 $("#submitHolesModal").hide();
6581 $("#redrawHoles").show();
6582 $('#removeCutouts').hide();
6583 bPassed = false;
6584 hole_setPoly.setOptions({
6585 fillColor: 'red',
6586 fillOpacity: 0.5,
6587 strokeColor: 'red',
6588 editable: false
6589 });
6590
6591 break;
6592 }
6593 }
6594
6595 if (hole_polygons.length > 1) {
6596 //need to carry out next test to see if the hole goes over any existing holes.
6597 var linepoints = [];
6598 var arrLinePts = [];
6599
6600 for (var i = 0; i < polygon.getPath().getLength() ; i++) {
6601 arrLinePts[0] = new google.maps.LatLng(polygon.getPath().getAt(i).lat(), polygon.getPath().getAt(i).lng());
6602
6603
6604 if (i == (polygon.getPath().getLength() - 1)) {
6605 arrLinePts[8] = new google.maps.LatLng(polygon.getPath().getAt(i - (polygon.getPath().getLength() - 1)).lat(), polygon.getPath().getAt(i - (polygon.getPath().getLength() - 1)).lng());
6606 }
6607 else {
6608 arrLinePts[8] = new google.maps.LatLng(polygon.getPath().getAt(i + 1).lat(), polygon.getPath().getAt(i + 1).lng());
6609 }
6610
6611 linepoints.push(arrLinePts[0]);
6612 linepoints.push(arrLinePts[8]);
6613 if (holes_fn_getPolygonPolyLineSegments(linepoints, arrLinePts)) {
6614 $("#holes_Modal").find(".alert-danger").show().find("p").show().empty().text(txtHoles5)
6615 $("#submitHolesModal").hide();
6616 $("#redrawHoles").show();
6617 $('#removeCutouts').hide();
6618 bPassed = false;
6619 hole_setPoly.setOptions({
6620 fillColor: 'red',
6621 fillOpacity: 0.5,
6622 strokeColor: 'red',
6623 editable: false
6624 });
6625 break;
6626 }
6627 linepoints = [];
6628 }
6629 }
6630
6631 if (bPassed) {
6632 $("#submitHolesModal").show();
6633 $('#removeCutouts').hide();
6634 $("#redrawHoles").hide();
6635 $('#saveRemovedCutouts').hide();
6636 $("#holes_Modal").find(".alert-danger").hide().find("p").empty();
6637 }
6638}
6639
6640function holes_fn_getPolygonPolyLineSegments(linepoints, arrLinePts) {
6641 //first and last point line
6642 var firstLine = new google.maps.Polyline({
6643 path: linepoints
6644 });
6645
6646 //use this point
6647 linepoints = [];
6648 arrLinePts[4] = new google.maps.LatLng(firstLine.getBounds().getCenter().lat(), firstLine.getBounds().getCenter().lng());
6649
6650
6651 linepoints.push(arrLinePts[0]);
6652 linepoints.push(arrLinePts[4]);
6653 var temp = new google.maps.Polyline({
6654 path: linepoints,
6655 });
6656
6657 arrLinePts[2] = new google.maps.LatLng(temp.getBounds().getCenter().lat(), temp.getBounds().getCenter().lng());;
6658 linepoints = [];
6659
6660 linepoints.push(arrLinePts[4]);
6661 linepoints.push(arrLinePts[8]);
6662 var temp = new google.maps.Polyline({
6663 path: linepoints,
6664 });
6665
6666 arrLinePts[6] = new google.maps.LatLng(temp.getBounds().getCenter().lat(), temp.getBounds().getCenter().lng());;
6667 linepoints = [];
6668
6669
6670 //final set
6671 linepoints.push(arrLinePts[0]);
6672 linepoints.push(arrLinePts[2]);
6673 var temp = new google.maps.Polyline({
6674 path: linepoints,
6675 });
6676 arrLinePts[1] = new google.maps.LatLng(temp.getBounds().getCenter().lat(), temp.getBounds().getCenter().lng());;
6677 linepoints = [];
6678
6679 linepoints.push(arrLinePts[2]);
6680 linepoints.push(arrLinePts[4]);
6681 var temp = new google.maps.Polyline({
6682 path: linepoints,
6683 });
6684 arrLinePts[3] = new google.maps.LatLng(temp.getBounds().getCenter().lat(), temp.getBounds().getCenter().lng());;
6685 linepoints = [];
6686
6687 linepoints.push(arrLinePts[4]);
6688 linepoints.push(arrLinePts[6]);
6689 var temp = new google.maps.Polyline({
6690 path: linepoints,
6691 });
6692 arrLinePts[5] = new google.maps.LatLng(temp.getBounds().getCenter().lat(), temp.getBounds().getCenter().lng());;
6693 linepoints = [];
6694
6695 linepoints.push(arrLinePts[6]);
6696 linepoints.push(arrLinePts[8]);
6697 var temp = new google.maps.Polyline({
6698 path: linepoints,
6699 });
6700 arrLinePts[7] = new google.maps.LatLng(temp.getBounds().getCenter().lat(), temp.getBounds().getCenter().lng());;
6701 linepoints = [];
6702
6703 var bIntersect = false;
6704 //check if these point appear in any hole-polygon
6705 for (var i = 0; i < arrLinePts.length; i++) {
6706 //loop throguh the polygon holes
6707 for (var j = 1; j < hole_polygons.length; j++) {
6708 if (hole_polygons[j].containsLatLng(arrLinePts[i].lat(), arrLinePts[i].lng())) {
6709 bIntersect = true;
6710 break;
6711 }
6712 }
6713 if (bIntersect) { break; }
6714 }
6715 return bIntersect;
6716}
6717
6718function holes_fn_chkPointInPolygonRect(rectangle, polygon) {
6719 //check if centre pt of circle is in polygon
6720
6721 var bounds = rectangle.getBounds(); // works fine
6722 var ne = rectangle.getBounds().getNorthEast();
6723 var sw = rectangle.getBounds().getSouthWest();
6724
6725 if (polygon.containsLatLng(ne.lat(), ne.lng())) {
6726
6727 }
6728 else {
6729 $("#holes_Modal").find(".alert-danger").show().find("p").empty().text(txtHoles3);
6730 $("#submitHolesModal").hide();
6731 $("#redrawHoles").show();
6732 $('#removeCutouts').hide();
6733 }
6734}
6735
6736function holes_fn_chkPointInPolygonCircle(circle, polygon) {
6737 //check if centre pt of circle is in polygon
6738
6739 if (polygon.containsLatLng(circle.getCenter().lat(), circle.getCenter().lng())) {
6740
6741 var holes_bIntersect = false;
6742 //need to check if circle intersects polygon border
6743 for (var i = 0; i < hole_fn_circlePath(circle).length; i++) {
6744 if (!hole_field_polygon.containsLatLng(hole_fn_circlePath(circle)[i].lat(), hole_fn_circlePath(circle)[i].lng())) {
6745 $("#holes_Modal").find(".alert-danger").show().find("p").empty().text(txtHoles2);
6746 $("#submitHolesModal").hide();
6747 $("#redrawHoles").show();
6748 $('#removeCutouts').hide();
6749 holes_bIntersect = true;
6750 break;
6751 }
6752 }
6753 if (holes_bIntersect) {
6754 holes_fn_replaceHideCircle(circle);
6755 }
6756 else {
6757 //so now we need to allow user to edit.
6758 $("#submitHolesModal").show();
6759 $('#removeCutouts').hide();
6760 }
6761 }
6762 else {
6763 //circle is not inside the polygon.
6764 holes_fn_replaceHideCircle(circle);
6765 $("#holes_Modal").find(".alert-danger").show().find("p").empty().text(txtHoles1);
6766 $("#submitHolesModal").hide();
6767 $("#redrawHoles").show();
6768 $('#removeCutouts').hide();
6769 $('#saveRemovedCutouts').hide();
6770 }
6771
6772}
6773
6774/// <summary>Removal of existing cutouts functionality</summary>
6775$(document).on('click', '#removeCutouts', function(){
6776 $('#allowCuttingAgain').show();
6777 $('#saveRemovedCutouts').show();
6778 holes_drawingManager.setDrawingMode(null); // Removes drawing mode v2
6779
6780});
6781
6782$(document).on('click', '#allowCuttingAgain', function(){
6783 displayHoleModalField();
6784 $('#saveRemovedCutouts').hide();
6785});
6786
6787/// <summary>Removal of existing cutouts functionality</summary>
6788
6789
6790function holes_fn_replaceHideCircle(circle) {
6791 //hide drawn circle
6792 circle.setMap(null);
6793
6794 //create a new poly with coords from drawn circle.
6795 hole_setPoly = new google.maps.Polygon({
6796 map: holes_Map,
6797 paths: [hole_fn_circlePath(circle)],
6798 fillColor: 'red',
6799 fillOpacity: 0.5,
6800 strokeColor: 'red',
6801 editable: false
6802 });
6803}
6804
6805function holes_fn_drawFieldPoly() {
6806 hole_field_polygon.setMap(holes_Map);
6807}
6808
6809function holes_fn_singlePoly(path) {
6810 var polygon = new google.maps.Polygon({
6811 id: getFieldId(),
6812 paths: path,
6813 highlight: true,
6814 fillColor: '#3DD62F',
6815 strokeColor: '#083508',
6816 strokeOpacity: 0.8,
6817 strokeWeight: 5,
6818 fillOpacity: 0.1
6819 });
6820 return polygon;
6821}
6822
6823function fld_AgrinetFieldmImport() {
6824 //check to see if we already have the login details.
6825 $.ajax({
6826 type: "POST",
6827 url: urlPrepend + "/fielddata/agrinetchk",
6828 data: { t: getTradingId() }
6829 }).done(function (data) {
6830
6831 $('#adminModal').modal('hide');
6832
6833 if (data == "False") {
6834 //no user exists
6835 $("#fieldAgrinetImportUserLogin").modal('show');
6836 $("#fieldAgrinetImportUserLogin .modal-dialog").attr("style", "width:90%;");
6837 $("#fieldAgrinetImportUserLogin .modal-body").attr("style", "min-height:320px;");
6838
6839
6840 } else {
6841
6842 $("#fieldAgrinetImportFarmList").modal('show');
6843 //display ajax loader on new modal then display list of farms
6844 $("#fieldAgrinetImportFarmList .modal-dialog").attr("style", "width:90%;");
6845 $("#fieldAgrinetImportFarmList .modal-body").attr("style", "min-height:320px;");
6846
6847 }
6848
6849 });
6850}
6851
6852$(document).on("click", "#fld_agrinetImport_save_login", function () {
6853
6854
6855 //save agrinet light data
6856 var name = $("#agriNetImportForm input[name=username]").val();
6857 var pw = $("#agriNetImportForm input[name=password]").val();
6858
6859
6860
6861 if (name != "" && pw != "") {
6862 $.ajax({
6863 type: "POST",
6864 url: urlPrepend + "/fielddata/agrinetlogin",
6865 data: { username: name, password: pw, t: getTradingId(), u: false }
6866 }).done(function (data) {
6867 if (data == false) {
6868 //something went wrong, reset form and ask user to try again.
6869 $("#fieldAgrinetImportUserLogin_2 .modal-footer span").text(txtAgrImp6).show();
6870 }
6871 else {
6872 //close modal and open up agrinet farm to field import.
6873 $("#fieldAgrinetImportUserLogin").modal('hide');
6874 $("#fieldAgrinetImportFarmList").modal('show');
6875 }
6876
6877 });
6878 }
6879 else {
6880 $("#fieldAgrinetImportUserLogin .modal-footer span").text(txtAgrImp5).show();
6881 }
6882
6883
6884
6885
6886});
6887
6888function fld_AgrinetLoader(showbutton) {
6889
6890 $(".fld_agrinet_import_loading_data").hide();
6891 $("#fieldAgrinetImportFields .agrinet_status").empty().text(txtAgrImp3);
6892 if (showbutton) {
6893 $("#fld_agrinetImport_import_field").show();
6894 }
6895 else {
6896 $("#fld_agrinetImport_import_field").hide();
6897 }
6898
6899
6900}
6901
6902$(document).on("click", "#fld_agrinetImport_import_field", function () {
6903
6904 var bNotChecked = true;
6905 var arrSelectedFields = [];
6906 $("#fieldAgrinetImportFields .modal-footer span").empty().hide();
6907
6908 $(".fld_agrinet_imported_fieldname").each(function () {
6909
6910 if (this.checked) {
6911 bNotChecked = false;
6912 var thisObj = {};
6913 thisObj.id = this.id;
6914 thisObj.area = $(this).attr("rel");
6915 thisObj.farmId = $("#fieldAgrinetImportFieldsFarm").val();
6916 thisObj.name = $(this).next().text();
6917 thisObj.tradingId = getTradingId();
6918 arrSelectedFields.push(thisObj);
6919 }
6920 })
6921
6922 if (bNotChecked) {
6923 //display alert.
6924 $("#fieldAgrinetImportFields .modal-footer span").text(txtGrnImp4).show();
6925 if ($(".fld_greenlight_save_fields_loader").is(":visible")) {
6926 $(".fld_greenlight_save_fields_loader").hide();
6927 }
6928 }
6929 else {
6930 $("#fieldAgrinetImportFields .modal-footer span").empty().hide();
6931 $(".fld_agrinet_save_fields_loader").show();
6932 }
6933
6934 if (arrSelectedFields.length > 0) {
6935 //user has selected fields to import.
6936 fld_AgrinetSaveImportedFields(arrSelectedFields);
6937 }
6938
6939});
6940
6941function fld_AgrinetFieldImportSavedStatus(agrinetCode, success) {
6942
6943 $(".fld_agrinet_imported_fieldname").each(function () {
6944 if (this.id == agrinetCode) {
6945 if (success) {
6946 $(this).parent().append("<span title=\"Field imported successfully\" class=\"fld_agrinet_imp_success glyphicon glyphicon-ok\"></span>");
6947 }
6948 else {
6949 $(this).parent().append("<span class=\"fld_agrinet_imp_fail glyphicon glyphicon-exclamation-sign\"></span>");
6950 }
6951 }
6952 $(this).attr("disabled", true);
6953 });
6954}
6955
6956function fld_AgrinetSaveImportedFields(arrFields) {
6957
6958 for (var j = 0; j < arrFields.length; j++) {
6959 $.ajax({
6960 type: "POST",
6961 dataType: "json",
6962 contentType: 'application/json; charset=utf-8',
6963 url: urlPrepend + "/fielddata/agrinetfieldupload",
6964 data: JSON.stringify(arrFields[j])
6965 }).done(function (data) {
6966
6967 var t = JSON.parse(data);
6968 if (!t.status) {
6969 //something went wrong so display red cross to indicate this.
6970 fld_AgrinetFieldImportSavedStatus(t.id, false);
6971 }
6972 else {
6973 //saved succesfully.
6974 fld_AgrinetFieldImportSavedStatus(t.id, true);
6975 //add to field list if we are on the same farm.
6976
6977 fld_appendAgrinetFieldToFieldList(t.fieldId, t.fieldName);
6978 }
6979
6980 if ($(".fld_agrinet_save_fields_loader").is(":visible")) {
6981 $(".fld_agrinet_save_fields_loader").hide();
6982 $("#fld_agrinetImport_import_field").hide();
6983 }
6984 });
6985 }
6986}
6987
6988function fld_appendAgrinetFieldToFieldList(id, name) {
6989 var newOption = "<li id=\"f_" + id + "\" class=\"field_item field_is_agrinet\">" + name + "</li><li class=\"fieldInfo\" rel=\"" + id + "\"></li>";
6990
6991 $(".field_list_items").append(newOption);
6992}
6993
6994$('#agrinetPW2 + .glyphicon').on('click', function () {
6995 $(this).toggleClass('glyphicon-eye-close').toggleClass('glyphicon-eye-open');
6996
6997 var x = $("#agrinetPW2");
6998 if ($("#agrinetPW2").attr("type") == "password") {
6999 $("#agrinetPW2").attr("type", "text");
7000 } else {
7001 $("#agrinetPW2").attr("type", "password");
7002 }
7003});
7004
7005$(document).on("click", "#fld_agrinetImport_save_login2", function () {
7006
7007 //validate form fisrt.
7008 //save agrinet light data
7009 var name = $("#agriNetImportForm2 input[name=username]").val();
7010 var pw = $("#agriNetImportForm2 input[name=password]").val();
7011
7012 if (name != "" && pw != "") {
7013 $.ajax({
7014 type: "POST",
7015 url: urlPrepend + "/fielddata/agrinetlogin",
7016 data: { username: name, password: pw, u: true, t: getTradingId() }
7017 }).done(function (data) {
7018 if (data == false) {
7019 //something went wrong, reset form and ask user to try again.
7020 $("#fieldAgrinetImportUserLogin_2 .modal-footer span").text(txtAgrImp6).show();
7021 }
7022 else {
7023 //close modal and open up agrinet farm to field import.
7024 $("#fieldAgrinetImportUserLogin_2").modal('hide');
7025 $("#fieldAgrinetImportFarmList").modal('show');
7026 }
7027
7028 });
7029 }
7030 else {
7031 $("#fieldAgrinetImportUserLogin_2 .modal-footer span").text(txtAgrImp5).show();
7032 }
7033
7034})
7035
7036$(document).on("click", "#fld_agrinetImport_remove_login", function () {
7037 $("#fieldAgrinetImportFarmList").modal('hide');
7038 $("#remove-confirm").modal('show');
7039});
7040
7041$(document).on("click", "#confirmRemoveBtn", function () {
7042 $.ajax({
7043 type: "POST",
7044 url: urlPrepend + "/fielddata/agrinetremoveaccount",
7045 data: { tradingId: getTradingId() }
7046 }).done(function (data) {
7047 if (data == "True") {
7048 displaySuccessMsg("You have successfully removed your Agrinet account!");
7049 } else {
7050 displayErrMsg("An unexpected error occured!");
7051 }
7052 $("#remove-confirm").modal('hide');
7053 });
7054});
7055
7056$(document).on("click", "#fld_agrinetImport_edit_login", function () {
7057 $("#fieldAgrinetImportFields").modal('hide');
7058
7059
7060 $("#fieldAgrinetImportUserLogin_2").modal('show');
7061 $("#fieldAgrinetImportUserLogin_2 .modal-dialog").attr("style", "width:90%;");
7062 $("#fieldAgrinetImportUserLogin_2 .modal-body").attr("style", "min-height:320px;");
7063
7064 $("#fieldAgrinetImportUserLogin_2 .modal-footer span").empty().hide();
7065 //get login details
7066 $.ajax({
7067 type: "POST",
7068 url: urlPrepend + "/fielddata/agrinetlgn",
7069 data: { t: getTradingId() }
7070 }).done(function (data) {
7071 if (data != "") {
7072 var jsonObj = $.parseJSON(data); // Parse the JSON String
7073
7074
7075 $("#agriNetImportForm2 input[name=username]").val(jsonObj.user);
7076 $("#agriNetImportForm2 input[name=password]").val(jsonObj.pw);
7077 }
7078 });
7079});
7080
7081$(document).on("click", "#fld_agrinet_displayLoginAgain", function () {
7082
7083 $("#fieldAgrinetImportUserLogin_2 .modal-footer span").empty().hide();
7084 $("#fieldAgrinetImportFields").modal('hide');
7085 $("#fieldAgrinetImportUserLogin_2").modal('show');
7086 //get login details
7087 $.ajax({
7088 type: "POST",
7089 url: urlPrepend + "/fielddata/agrinetlgn",
7090 data: { t: getTradingId() }
7091 }).done(function (data) {
7092
7093 if (data != "") {
7094 var jsonObj = $.parseJSON(data); // Parse the JSON String
7095
7096
7097 $("#agriNetImportForm2 input[name=username]").val(jsonObj.user);
7098 $("#agriNetImportForm2 input[name=password]").val(jsonObj.pw);
7099 }
7100 });
7101
7102});
7103
7104$(document).on("click", "#fld_agrinetImport_edit_login", function () {
7105 $("#fieldAgrinetImportFarmList").modal('hide');
7106
7107});
7108
7109$(document).on("click", "#fld_agrinetImport_map_farm", function () {
7110 $("#fieldAgrinetImportFarmList").modal('hide');
7111 $(".fld_agrinet_save_fields_loader").hide();
7112 //need to make sure any previous field imports have been removed.
7113
7114 $("#fieldAgrinetImportFields .agrinet_status ul").remove();
7115 $("#fieldAgrinetImportFields .agrinet_status p").remove();
7116 $("#fieldAgrinetImportFields .modal-footer span").empty().hide();
7117
7118
7119 $("#fieldAgrinetImportFields").modal('show');
7120
7121 $("#fieldAgrinetImportFields .modal-dialog").attr("style", "width:90%;");
7122 $("#fieldAgrinetImportFields .modal-body").attr("style", "min-height:320px;");
7123
7124
7125 $("#fieldAgrinetImportFields .modal-footer").show();
7126 $(".fld_agrinet_import_loading_data").show();
7127
7128 $("#fieldAgrinetImportFieldsFarm").val($("#agrinetFarmsList").find(":selected").val());
7129
7130 $.ajax({
7131 type: "POST",
7132 url: urlPrepend + "/fielddata/agrinetfieldimport",
7133 data: { t: getTradingId() }
7134 }).done(function (data) {
7135
7136 var xml = $($.parseXML(data)), // Parse the XML String to a Document, and Wrap jQuery
7137 json = xml.find("string").text(), // Get the text of the XML
7138 jsonObj = $.parseJSON(json); // Parse the JSON String
7139
7140 var agrinet_content = "";
7141
7142 var arrTempField = [];
7143
7144 if (jsonObj.Paddocks.length > 0) {
7145
7146 var showModalButton = true;
7147 //we need to see if user has agrinet fields in current farm.
7148 var arrExistingAgrinetfields = [];
7149 $.ajax({
7150 type: "POST",
7151 url: urlPrepend + "/fielddata/agrinetfieldsbyfarm",
7152 data: { farmId: $("#agrinetFarmsList").find(":selected").val() }
7153 }).done(function (data) {
7154 if (data.length > 1) {
7155 var existingAgrinetfields = data;
7156
7157 arrExistingAgrinetfields = data.split('|');
7158 }
7159
7160
7161 var iCount = 0;
7162 for (var i = 0; i < jsonObj.Paddocks.length; i++) {
7163
7164 if (!fld_arginetFieldCheck(jsonObj.Paddocks[i].Code, arrExistingAgrinetfields)) {
7165 agrinet_content += "<li><input type=\"checkbox\" class=\"fld_agrinet_imported_fieldname\"id=\"" + jsonObj.Paddocks[i].Code + "\" rel=\"" + jsonObj.Paddocks[i].Area + "\" checked=\"true\" /><label for=\"" + jsonObj.Paddocks[i].Code + "\" >" + jsonObj.Paddocks[i].Name + "</label></li>"
7166 iCount++;
7167 }
7168
7169 }
7170
7171 if (iCount > 15) {
7172 agrinet_content = "<ul class=\"fld_agri_field_wrapper\">" + agrinet_content + "</ul>";
7173 $("#fld_agrinetImport_import_field").show();
7174 }
7175 else {
7176 if (iCount > 0) {
7177 agrinet_content = "<ul>" + agrinet_content + "</ul>";
7178 }
7179 else {
7180 agrinet_content = "<p>Your fields have already been imported for this farm</p>";
7181 showModalButton = false;
7182 }
7183
7184 }
7185
7186 setTimeout(function () { fld_AgrinetLoader(showModalButton); $("#fieldAgrinetImportFields .agrinet_status").append(agrinet_content); }, 3000)
7187 });
7188 }
7189 else {
7190 //no data returned//maybe because of incorrect credentials
7191 agrinet_content = "<p>No fields were receieved from Agrinet. Your login credentials maybe incorrect. <a class=\"btn btn-success btn-ok\" id=\"fld_agrinet_displayLoginAgain\">View login details</a></p>";
7192 setTimeout(function () { fld_AgrinetLoader(showModalButton); $("#fieldAgrinetImportFields .agrinet_status").html(agrinet_content); }, 3000)
7193 showModalButton = false;
7194
7195 }
7196 });
7197});
7198
7199function fld_arginetFieldCheck(value, arr) {
7200
7201 for (var k = 0; k < arr.length; k++) {
7202 if (value == arr[k]) {
7203 return true;
7204 break;
7205 }
7206 }
7207 return false;
7208}
7209
7210
7211$('#greenlightPW2 + .glyphicon').on('click', function () {
7212 $('.greenlight_pw_login_icon').toggleClass('glyphicon-eye-close');
7213
7214 if ($("#greenlightPW2").attr("type") == "password") {
7215 $("#greenlightPW2").attr("type", "text");
7216 } else {
7217 $("#greenlightPW2").attr("type", "password");
7218 }
7219});
7220
7221$(document).on("click", "#fld_fieldGreenlightImportPT2_close_modal", function () {
7222 $("#fieldGreenlightImportPT2").modal('hide');
7223});
7224
7225function fld_GreenlightImportPT1a() {
7226
7227 //check to see if we already have the login details.
7228 $.ajax({
7229 type: "GET",
7230 url: urlPrepend + "/import/greenlightchk"
7231 }).done(function (data) {
7232 if (data == "False") {
7233 $('#adminModal').modal('hide');
7234 //no user exists
7235 $("#fieldGreenlightImportPT1a").modal('show');
7236 $("#fieldGreenlightImportPT1a .modal-dialog").attr("style", "width:90%;");
7237 $("#fieldGreenlightImportPT1a .modal-body").attr("style", "min-height:320px;");
7238
7239 } else {
7240 $('#adminModal').modal('hide');
7241 $("#fieldGreenlightImportPT2").modal('show');
7242 $("#fieldGreenlightImportPT2 .modal-dialog").attr("style", "width:90%;");
7243 $("#fieldGreenlightImportPT2 .modal-body").attr("style", "min-height:320px;");
7244 }
7245
7246 });
7247
7248}
7249
7250$(document).on("click", "#fld_greenlightImport_save_login", function () {
7251
7252 $("#greenlightImportFormPt1 input[name=username]").removeClass("error_bdr");
7253 $("#greenlightImportFormPt1 input[name=password]").removeClass("error_bdr");
7254
7255 //save green light data
7256 var name = $("#greenlightImportFormPt1 input[name=username]").val();
7257 var pw = $("#greenlightImportFormPt1 input[name=password]").val();
7258 var err = false;
7259 //validate form.
7260
7261 if (name == "") {
7262 err = true;
7263 $("#greenlightImportFormPt1 input[name=username]").addClass("error_bdr");
7264 }
7265 if (pw == "") {
7266 err = true;
7267 $("#greenlightImportFormPt1 input[name=password]").addClass("error_bdr");
7268 }
7269 if (err) {
7270 $(".greenlight_login-error").empty().text(txtGrnLtImp1).show();
7271 }
7272 else {
7273 $.ajax({
7274 type: "POST",
7275 url: urlPrepend + "/import/greenlightlogin",
7276 data: { username: name, password: pw }
7277 }).done(function (data) {
7278 if (data == "False") {
7279 //something went wrong, reset form and ask user to try again.
7280 }
7281 else {
7282 //close modal and open up greenlight farm to field import.
7283 $("#fieldGreenlightImportPT1a").modal('hide');
7284 $("#fieldGreenlightImportPT2").modal('show');
7285 }
7286 });
7287 }
7288
7289
7290
7291 return false;
7292});
7293
7294var fld_greenlightFields = [];
7295var fld_greenlight_itemObj = {};
7296
7297$(document).on("click", "#fld_greenlightImport_map_farm", function () {
7298 $("#fieldGreenlightImportPT2").modal('hide');
7299
7300 //reset fieldGreenlightImportPT3
7301 //need to make sure any previous field imports have been removed.
7302
7303 $("#fieldGreenlightImportPT3 .greenlight_field_list ul").remove();
7304 $("#fieldGreenlightImportPT3 .modal-footer span").empty().hide();
7305 //reset fieldGreenlightImportPT3
7306 $("#fieldGreenlightImportPT3").modal('show');
7307 $("#fieldGreenlightImportPT3 .modal-dialog").attr("style", "width:90%;");
7308 $("#fieldGreenlightImportPT3 .modal-body").attr("style", "min-height:320px;");
7309 $("#fieldGreenlightImportPT3 .greenlight_field_list").empty()
7310 $(".greenlight_imp_checkall_fields").hide();
7311 $(".greenlight_field_count").empty();
7312 $("#fieldGreenlightImportPT3 .modal-footer").show();
7313 $(".fld_greenlight_import_loading_data").show();
7314 $.ajax({
7315 type: "POST",
7316 url: urlPrepend + "/import/greenlightfieldimport"
7317 }).done(function (data) {
7318 var t = JSON.parse(data);
7319 if (typeof t.status != "undefined" && t.status.length > 0) {
7320
7321 if (t.status != "401") {
7322 $("#fieldGreenlightImportPT3 .greenlight_field_list").empty().html(txtGrnImp1);
7323 }
7324 else {
7325 $("#fieldGreenlightImportPT3 .greenlight_field_list").empty().html(txtGrnImp2);
7326 }
7327 $(".fld_greenlight_import_loading_data").hide();
7328 }
7329 else {
7330 //we have some data from greenlight
7331 var greenlight_content = "";
7332 fld_greenlightFields = [];
7333
7334 for (var i = 0; i < t.length; i++) {
7335
7336 fld_greenlight_itemObj = {};
7337
7338 //create object to save data on the fly.
7339 fld_greenlight_itemObj.key = t[i].key;
7340 fld_greenlight_itemObj.site = t[i].site;
7341 fld_greenlight_itemObj.name = gen_CapitaliseEachWord(t[i].name.trim());
7342 fld_greenlight_itemObj.area = t[i].area;
7343 fld_greenlight_itemObj.workingArea = t[i].workingArea;
7344 fld_greenlight_itemObj.soil = t[i].soil;
7345 fld_greenlight_itemObj.block = t[i].block;
7346 fld_greenlight_itemObj.reference = t[i].reference;
7347 fld_greenlight_itemObj.ditches = t[i].ditches;
7348 fld_greenlight_itemObj.notes = t[i].notes;
7349 fld_greenlight_itemObj.fieldCoordsWkt = t[i].fieldCoordsWkt;
7350 fld_greenlight_itemObj.workingAreaUnitKey = t[i].workingAreaUnitKey;
7351 fld_greenlight_itemObj.areaUnitKey = t[i].areaUnitKey;
7352 fld_greenlight_itemObj.version = t[i].version;
7353 fld_greenlight_itemObj.state = t[i].state;
7354 fld_greenlight_itemObj.farmId = $("#greenlightFarmsList").find(":selected").val();
7355 fld_greenlight_itemObj.mappedFieldId = "";
7356 var coords = [];
7357
7358 if (t[i].fieldCoords != null) {
7359 for (var j = 0; j < t[i].fieldCoords.coordinates[0].length; j++) {
7360 coords.push(t[i].fieldCoords.coordinates[0][j][1] + "|" + t[i].fieldCoords.coordinates[0][j][0]);
7361 }
7362 }
7363
7364 fld_greenlight_itemObj.coords = coords;
7365 fld_greenlightFields.push(fld_greenlight_itemObj);
7366 }
7367
7368 fld_greenlightFields.sort(function (a, b) {
7369 var nameA = a.name.toLowerCase(), nameB = b.name.toLowerCase();
7370 if (nameA < nameB) //sort string ascending
7371 return -1;
7372 if (nameA > nameB)
7373 return 1;
7374 return 0; //default return value (no sorting)
7375 });
7376
7377 fld_GreenlightFieldListing(fld_greenlightFields);
7378 }
7379 });
7380});
7381
7382function fld_GreenlightFieldListing(fld_greenlightFields) {
7383
7384 var greenlight_content = "";
7385 for (var i = 0; i < fld_greenlightFields.length; i++) {
7386 greenlight_content += "<div class=\"row greenlight_imp_field_rows\"><div class=\"col-md-3\"><input type=\"checkbox\" class=\"fld_greenlight_imported_fieldname\"id=\"" + fld_greenlightFields[i].key + "\" checked=\"true\" /><label for=\"" + fld_greenlightFields[i].key + "\" >" + fld_greenlightFields[i].name + "</label>";
7387 greenlight_content += "<img src=\"" + urlPrepend + "/Content/images/ajax-loader-sm-wbg.gif\" class=\"fld_greenlight_field_loader\" rel=\"" + fld_greenlightFields[i].key + "\" /></div><div class=\"col-md-3\"><select class=\"greenlight_map_fields\" rel=\"" + fld_greenlightFields[i].key + "\">" + fld_GreenlightSetMF2FieldsDDL(fld_greenlightFields[i].name) + "</select></div></div>";
7388 }
7389 greenlight_content = "<div style=\"overflow-y: scroll;height: " + gen_modal_map_height + "px;overflow-x: hidden; \">" + greenlight_content + "</div>";
7390 setTimeout(function () { fld_GreenlightLoader(); $("#fieldGreenlightImportPT3 .greenlight_field_list").append(greenlight_content); $(".modal_greenlight_imp_top_button_wrapper_1").show(); $(".greenlight_imp_checkall_fields").show(); }, 3000);
7391 $("#fld_greenlightImport_import_field").attr("disabled", false);
7392}
7393
7394function fld_GreenlightSetMF2FieldsDDL(greenlightField) {
7395
7396 var s = $('<select class=\"greenlight_map_fields\"></select>');
7397 $('<option />', { value: "", text: "Map to current Mifarm field."}).appendTo(s);
7398 $(".field_item").each(function () {
7399 if (greenlightField.toLowerCase().trim() == $(this).text().toLowerCase().trim()) {
7400 $('<option />', { value: $(this).attr("id").split("_")[1], text: $(this).text() }).attr('selected', 'selected').appendTo(s);
7401 }
7402 else {
7403 $('<option />', { value: $(this).attr("id").split("_")[1], text: $(this).text() }).appendTo(s);
7404 }
7405 });
7406
7407 return s.html();
7408}
7409
7410function fld_GreenlightLoader() {
7411
7412 $(".fld_greenlight_import_loading_data").hide();
7413 $("#fieldGreenlightImportPT3 .greenlight_status").empty().text(txtGrnImp3);
7414 $("#fld_greenlightImport_import_field").show();
7415}
7416
7417$(document).on("click", ".greenlight_imp_checkall_fields", function () {
7418
7419
7420 if ($(this).attr("rel") == "check") {
7421 //check all
7422 $(".fld_greenlight_imported_fieldname").each(function () {
7423 $(this).prop("checked", false);
7424 //disable submit button
7425 $("#fld_greenlightImport_import_field").attr("disabled", true);
7426 });
7427 $(this).removeAttr("rel").attr("rel", "uncheck");
7428 }
7429 else{
7430 $(".fld_greenlight_imported_fieldname").each(function () {
7431 $(this).prop("checked", true);
7432 $("#fld_greenlightImport_import_field").attr("disabled", false);
7433 });
7434 $(this).removeAttr("rel").attr("rel", "check");
7435 }
7436
7437});
7438
7439
7440$(document).on("click", "#fld_greenlightImport_import_field", function () {
7441
7442 var bNotChecked = true;
7443 var arrSelectedFields = [];
7444 $("#fieldGreenlightImportPT3 .modal-footer span").empty().hide();
7445
7446 //disable ddl
7447 $(".greenlight_map_fields").each(function () {
7448 $(this).attr("disabled", true);
7449 console.log("fff")
7450 })
7451
7452
7453 $(".fld_greenlight_imported_fieldname").each(function () {
7454 if (this.checked) {
7455 bNotChecked = false;
7456 arrSelectedFields.push(this.id);
7457 }
7458 })
7459
7460 if (bNotChecked) {
7461 //check this
7462 //display alert.
7463 $("#fieldGreenlightImportPT3 .modal-footer span").text(txtGrnImp4).show();
7464
7465 }
7466 else {
7467 $("#fieldGreenlightImportPT3 .modal-footer span").empty().hide();
7468 }
7469
7470 if (arrSelectedFields.length > 0) {
7471 //user has selected fields to import.
7472 fld_GreenlightSaveImportedFields(arrSelectedFields);
7473 }
7474});
7475
7476$(document).on( "click",".fld_greenlight_imported_fieldname", function () {
7477
7478 var thisChecked = false;
7479
7480 $(".fld_greenlight_imported_fieldname").each(function () {
7481 if ($(this).is(":checked")) {
7482 thisChecked = true;
7483 }
7484
7485 });
7486
7487 if (thisChecked) {
7488 //disable submit button
7489 $("#fld_greenlightImport_import_field").attr("disabled", false);
7490 }
7491 else {
7492 $("#fld_greenlightImport_import_field").attr("disabled", true);
7493 }
7494})
7495
7496$(document).on("change", ".greenlight_pd_crops ", function () {
7497 if ($(this).find(":selected").val() != "") {
7498 $(this).removeClass("error_bdr");
7499 }
7500})
7501
7502
7503var fld_greenlight_tempObjectArr = [];
7504
7505function fld_greenlight_saveAjax(arrFields) {
7506
7507 if (arrFields.length > 0) {
7508 for (var k = 0; k < fld_greenlightFields.length; k++) {
7509 if (arrFields[0] == fld_greenlightFields[k].key) {
7510
7511 $.ajax({
7512 type: "POST",
7513 dataType: "json",
7514 async : false,
7515 contentType: 'application/json; charset=utf-8',
7516 url: urlPrepend + "/import/greenlightfieldupload",
7517 data: JSON.stringify(fld_greenlightFields[k])
7518 }).done(function (data) {
7519 var t = JSON.parse(data);
7520
7521 if (!t.status) {
7522 //something went wrong so display red cross to indicate this.
7523 fld_GreenlightFieldImportSavedStatus(t.key, false);
7524 }
7525 else {
7526 //saved succesfully.
7527 fld_GreenlightFieldImportSavedStatus(t.key, true);
7528
7529 if (getFarmId() == t.farmId) {
7530 fld_appendGreenlightFieldToFieldList(t.fieldId, t.name);
7531 }
7532
7533 let temp_fieldObj = {};
7534 temp_fieldObj.fieldId = t.fieldId;
7535 temp_fieldObj.name =t.name;
7536 temp_fieldObj.key = t.key;
7537 fld_greenlight_tempObjectArr.push(temp_fieldObj);
7538
7539 }
7540
7541 if ($(".fld_greenlight_save_fields_loader").is(":visible")) {
7542 $(".fld_greenlight_save_fields_loader").hide();
7543 $("#fld_agrinetImport_import_field").hide();
7544 }
7545
7546 arrFields.splice(0, 1);
7547 $(".greenlight_field_count").empty().html(txtGrnLtImp6 + " <b>" + arrFields.length + "</b><img src=\"" + urlPrepend + "/Content/images/ajax-loader.gif\"/>");
7548
7549 setTimeout(function () { fld_greenlight_saveAjax(arrFields); }, 500);
7550 });
7551
7552 //we have match escape loop
7553 k = fld_greenlightFields.length + 1;
7554 }
7555 }
7556 }
7557 else {
7558 fld_greenlightImportCrops(fld_greenlight_tempObjectArr);
7559 }
7560
7561
7562}
7563
7564
7565function fld_GreenlightSaveImportedFields(arrFields) {
7566 var fieldCount = arrFields.length;
7567 //adding count down u/i
7568 $(".greenlight_field_count").empty().html("Fields left to import <b>" + fieldCount + "</b><img src=\"" + urlPrepend + "/Content/images/ajax-loader.gif\"/>");
7569
7570 let temp_fieldArr = [];
7571 $(".greenlight_imp_checkall_fields").hide();
7572
7573 //loop through obj array of greenlight data
7574 for (var k = 0; k < fld_greenlightFields.length; k++) {
7575
7576 for (var j = 0; j < arrFields.length; j++) {
7577
7578 if (arrFields[j] == fld_greenlightFields[k].key) {
7579
7580
7581 $(".fld_greenlight_field_loader").each(function () {
7582 if ($(this).attr("rel") == fld_greenlightFields[k].key) {
7583 $(this).show();
7584 }
7585 })
7586
7587 $(".greenlight_map_fields").each(function () {
7588 if ($(this).attr("rel") == fld_greenlightFields[k].key) {
7589 fld_greenlightFields[k].mappedFieldId = $(this).find(":selected").val();
7590 }
7591 });
7592
7593 }
7594
7595 }
7596
7597 if (k == (fld_greenlightFields.length - 1)) {
7598 setTimeout(function () { fld_greenlight_saveAjax(arrFields); }, 3000);
7599 }
7600 }
7601}
7602
7603
7604
7605function fld_greenlightImportCrops(arr) {
7606 //need to first pass ajax all data to get it back again along with the crop for the field.
7607 var json = "";
7608 for (var i = 0; i < arr.length; i++) {
7609 json += JSON.stringify(arr[i]) + ",";
7610 }
7611 json = "[" + json.slice(0, -1) + "]";;
7612 //pass json object to ajax call.
7613
7614 //json = "[{\"fieldId\":\"140782\",\"name\":\"PADFIELD 2019\",\"key\":\"a5f54c2a-39e0-4532-8839-635330ec154f\"},{\"fieldId\":\"140783\",\"name\":\"GRANGE STACKYARD\",\"key\":\"1b31f4f1-5cae-11d3-9aa8-dbb37a9e2e1f\"},{\"fieldId\":\"140784\",\"name\":\"Wakes\",\"key\":\"74629daa-f3f1-41c4-be5f-cb68517814ed\"}]"
7615
7616 var cropContentItem = "";
7617 var t, u;
7618 var pdCrpElement;
7619
7620 $.getJSON(urlPrepend + "/layerdata/crop/pdcrops")
7621 .done(function (data) {
7622
7623 let t = JSON.parse(data);
7624
7625 $.ajax({
7626 type: "POST",
7627 dataType: "json",
7628 contentType: 'application/json; charset=utf-8',
7629 url: urlPrepend + "/import/greenlightcropimport",
7630 data: json
7631 }).done(function (data) {
7632
7633 $("#fieldGreenlightImportPT3").modal('hide');
7634
7635 let u = JSON.parse(data);
7636 var hasData = u[0].hasData;
7637
7638 if (hasData == "false") {
7639
7640 //display success import message and no crops have been imported.
7641 displaySuccessMsg(txtGrnLtImp3);
7642
7643 //refresh page to get imported data on map
7644 setTimeout(function () { fld_greenlightSubmitForm(); }, 3000);
7645 }
7646 else {
7647 $("#fieldGreenlightImportPT4").modal('show');
7648 $("#fieldGreenlightImportPT4 .modal-dialog").attr("style", "width:90%;");
7649 $("#fieldGreenlightImportPT4 .modal-body").attr("style", "min-height:320px;");
7650 $(".greenlight_crop_count").hide();
7651 //import crops.
7652 for (var i = 0; i < u[0].data.length; i++) {
7653 let = pdCrpElement = $('<select class=\"greenlight_pd_crops form-control\"></select>');
7654 $('<option />', { value: "", text: txtGrnLtImp5 }).appendTo(pdCrpElement);
7655 for (var j = 0; j < t.length; j++) {
7656 if (u[0].data[i].crop == t[j].crop) {
7657 $('<option />', { value: t[j].id, text: t[j].crop }).attr('selected','selected').appendTo(pdCrpElement);
7658 }
7659 else {
7660 $('<option />', { value: t[j].id, text: t[j].crop }).appendTo(pdCrpElement);
7661 }
7662 }
7663 cropContentItem += ("<div class=\"row greenlight_imp_crop_rows\" alt=\"" + u[0].data[i].fieldId + "_" + u[0].data[i].key + "\"><div class=\"col-md-3\">" + u[0].data[i].fieldName + "</div><div class=\"col-md-3\">" + u[0].data[i].crop + "</div><div class=\"col-md-3\"><select class=\"greenlight_pd_crops form-control\" alt=\"" + u[0].data[i].fieldId + "_" + u[0].data[i].key + "\">" + pdCrpElement.html() + "</select></div></div>");
7664 }
7665 $(".greenlight_crop_wrapper").html("<div style=\"overflow-y: scroll;height: " + gen_modal_map_height + "px;overflow-x: hidden; \">" + cropContentItem + "</div>");
7666 }
7667 });
7668 });
7669}
7670
7671
7672function fld_greenlightSubmitForm() {
7673 $("<form action=\"/MiFarm/" + getTradingId() + "\" method=\"post\"><input type=\"hidden\" name=\"Farms\" id=\"farmsList\" value=\"" + getFarmId() + "\"> </form>").appendTo('body').submit();
7674}
7675
7676$(document).on("click", "#fld_greenlightImport_import_crop", function () {
7677
7678 let pd_drpNotSelected = false;
7679 //first validate
7680 $(".greenlight_pd_crops").each(function () {
7681 if ($(this).find(":selected").val() == "") {
7682 $(this).addClass("error_bdr");
7683 pd_drpNotSelected = true;
7684 }
7685 });
7686
7687
7688 if (!pd_drpNotSelected) {
7689 var fieldId, fieldKey, fieldCrp;
7690 var json = "";
7691 $(".greenlight_imp_crop_rows").each(function () {
7692 let fieldId = $(this).attr("alt").split("_")[0];
7693 let fieldKey = $(this).attr("alt").split("_")[1];
7694 var itemKey = $(this).attr("alt");
7695
7696 $(".greenlight_pd_crops").each(function () {
7697
7698 if ($(this).attr("alt") == itemKey) {
7699 fieldCrp = $(this).find(":selected").val();
7700 $(this).attr("disabled", true);
7701 }
7702 });
7703
7704 //generate json.
7705 json += "{\"fieldId\":\"" + fieldId + "\",\"fieldKey\":\"" + fieldKey + "\",\"fieldCrp\":\"" + fieldCrp + "\"},";
7706 });
7707
7708 $(".greenlight_crop_count").show();
7709
7710 $.ajax({
7711 type: "POST",
7712 dataType: "json",
7713 contentType: 'application/json; charset=utf-8',
7714 url: urlPrepend + "/import/greenlightinsertcropimport",
7715 data: "[" + json.slice(0, -1) + "]"
7716 }).done(function (data) {
7717
7718 var t = JSON.parse(data);
7719 $("#fieldGreenlightImportPT4").modal('hide');
7720 $(".greenlight_crop_count").hide();
7721 (t.status) ? displaySuccessMsg(txtGrnLtImp3) : displayErrMsg(txtGrnLtImp4);
7722
7723 //refresh page to get imported data on map
7724 setTimeout(function () { fld_greenlightSubmitForm(); }, 3000);
7725 });
7726 }
7727 else {
7728 $("#fieldGreenlightImportPT4 .alert-danger").text(txtGrnLtImp2).show();
7729 }
7730});
7731
7732function fld_appendGreenlightFieldToFieldList(id, name) {
7733 var newOption = "<li id=\"f_" + id + "\" class=\"field_item field_is_greenlight\">" + name + "</li><li class=\"fieldInfo\" rel=\"" + id + "\"></li>";
7734
7735 $(".field_list_items").append(newOption);
7736}
7737
7738function fld_GreenlightFieldImportSavedStatus(greenlightKey, success) {
7739
7740 $(".fld_greenlight_field_loader").each(function () {
7741 if ($(this).attr("rel") == greenlightKey) {
7742 $(this).remove();
7743 }
7744 })
7745
7746
7747 $(".fld_greenlight_imported_fieldname").each(function () {
7748 if (this.id == greenlightKey) {
7749 if (success) {
7750 $(this).parent().append("<span title=\"Field imported successfully\" class=\"fld_greenlight_imp_success glyphicon glyphicon-ok\"></span>");
7751 }
7752 else {
7753 $(this).parent().append("<span class=\"fld_greenlight_imp_fail glyphicon glyphicon-exclamation-sign\" title=\"There was an error importing this field.\"></span>");
7754 }
7755 }
7756 $(this).attr("disabled", true);
7757 });
7758}
7759
7760
7761function fld_checkGreenlightFieldExists(fieldId) {
7762
7763 var b = false;
7764 $(".dropdown_field_menu li").each(function () {
7765 if ($(this).text() != "No Fields Exist For This Farm") {
7766 if ($(this).attr("id").split("_")[1] === fieldId) {
7767 b = true;
7768 }
7769 }
7770 });
7771 return b;
7772}
7773
7774$(document).on("click", "#fld_fieldAgrinetLogin_close_modal2", function () {
7775 $("#fieldAgrinetImportUserLogin_2").modal('hide');
7776});
7777
7778$(document).on("click", "#fld_fieldGreenlightImportPT4_close_modal", function () {
7779 $("#fieldGreenlightImportPT4").modal('hide');
7780});
7781
7782$(document).on("click", "#fld_fieldGreenlightImportPT3_close_modal", function () {
7783 $("#fieldGreenlightImportPT3").modal('hide');
7784});
7785
7786$(document).on("click", "#fld_fieldGreenlightImportPT2_close_modal", function () {
7787 $("#fieldGreenlightImportPT2").modal('hide');
7788});
7789
7790$(document).on("click", "#fld_fieldGreenlightImportPT1a_close_modal", function () {
7791 $("#fieldGreenlightImportPT1a").modal('hide');
7792});
7793
7794$(document).on("click", "#fld_fieldAgrinetLogin_close_modal", function () {
7795 $("#fieldAgrinetImportUserLogin").modal('hide');
7796});
7797
7798$(document).on("click", "#fld_fieldAgrinetLogin2_close_modal", function () {
7799 $("#fieldAgrinetImportFarmList").modal('hide');
7800});
7801
7802$(document).on("click", "#fld_fieldAgrinetImportFields_close_modal", function () {
7803 $("#fieldAgrinetImportFields").modal('hide');
7804});
7805
7806function fld_clearCurrentPolygonMap() {
7807 if (polygonsArray.length > 0) {
7808 for (var i = 0; i < polygonsArray.length; i++) {
7809 polygonsArray[i].setMap(null);
7810 markers[i].setMap(null);
7811 fieldLabels[i].setMap(null);
7812 }
7813 }
7814}
7815
7816function fld_addfieldToCroppingFieldList(fieldId, fieldName) {
7817
7818 var str = "<input class=\"crop_layer_new_layer_field_list\" id=\"cropLayerFieldCheckBox_" + fieldName + "\" name=\"cropLayerFieldCheckBox_" + fieldName + "\" value=\"" + fieldId + "\" type=\"checkbox\"><label for=\"cropLayerFieldCheckBox_" + fieldName + "\">" + fieldName + "</label><input name=\"cropLayerFieldCheckBox_" + fieldName + "\" value=\"false\" type=\"hidden\"><br>";
7819 $("#cropsModal .map_layr_crp_frm_ele_3").append(str);
7820}
7821
7822$(document).on("click", ".farm_watch_summary", function () {
7823
7824 var bWatch = 0;
7825 if ($(this).children(1).hasClass("not_watching")) {
7826 //watch this farm.
7827 bWatch = 1;
7828 }
7829
7830
7831 $.ajax({
7832 url: urlPrepend + "/farmdata/farmwatch-" + getFarmId() + "-" + bWatch
7833 }).done(function (data) {
7834 if (data == "True") {
7835 if (bWatch == 1) {
7836 //change eye icon
7837 $(".watch_farm_icon").removeClass("glyphicon-eye-close").addClass("glyphicon-eye-open");
7838 $(".not_watching").empty().text("You are watching this farm").removeClass("not_watching").addClass("watching");
7839 }
7840 if (bWatch == 0) {
7841 //change eye icon
7842 $(".watch_farm_icon").removeClass("glyphicon-eye-open").addClass("glyphicon-eye-close");
7843 $(".watching").empty().text("You are not watching this farm").removeClass("watching").addClass("not_watching");
7844 }
7845
7846 }
7847
7848 });
7849
7850});
7851
7852
7853function fld_farmSummary() {
7854
7855
7856 var url = urlPrepend + "/fielddata/summary-" + getFarmId()
7857 var selectedSeason = $("#customerSeason").find(":selected").val();
7858 if ((selectedSeason != "") || (selectedSeason != "addseason")) {
7859 url = url + "_" + selectedSeason;
7860 }
7861
7862
7863
7864 $(".right_details_panel_content").empty().html(insertLoader());
7865
7866 $.ajax({
7867 url: url
7868 }).done(function (data) {
7869
7870
7871 var t = JSON.parse(data);
7872
7873 if (t.length > 0) {
7874
7875 //get farm name
7876 var strFarmName = "";
7877 $(".left_panel_farm_item").each(function () {
7878 if ($(this).hasClass("farm_item_selected")) {
7879 strFarmName = $(this).text();
7880 }
7881 })
7882
7883 var strTemp = "<p class=\"fm_sum_info1\"><b>" + strFarmName + "</b></p>";
7884 strTemp += "<p class=\"fm_sum_info1\">Field Count : <b>" + t[0].count + "</b></p>";
7885 strTemp += "<p class=\"fm_sum_info1\">Total Ha : <b>" + parseFloat(t[0].totalsize).toFixed(1) + "</b></p>";
7886
7887 //insert crop season stuff.
7888
7889
7890 var totalCropCount = 0;
7891 if (t[0].cropcount.length > 0) {
7892
7893 strTemp += "<p class=\"fm_sum_info2\">Total Crop Count (Ha)</p>";
7894
7895 for (var i = 0; i < t[0].cropcount.length; i++) {
7896 strTemp += "<p class=\"fm_sum_info3\">" + t[0].cropcount[i].crop + " : " + parseFloat(t[0].cropcount[i].size).toFixed(1) + " Ha</p>";
7897 totalCropCount = +parseFloat(totalCropCount) + +parseFloat(t[0].cropcount[i].size).toFixed(1);
7898 }
7899 }
7900
7901
7902 if (selectedSeason != "") {
7903 if (totalCropCount < parseFloat(t[0].totalsize).toFixed(1)) {
7904 //unallocated fields.
7905 if ((+parseFloat(t[0].totalsize).toFixed(1) - +parseFloat(totalCropCount).toFixed(1)).toFixed(1) > 0.1) {
7906 strTemp += "<p class=\"fm_sum_info3\">No Crops Assigned : " + (+parseFloat(t[0].totalsize).toFixed(1) - +parseFloat(totalCropCount).toFixed(1)).toFixed(1) + " Ha</p>";
7907 }
7908
7909 }
7910 strTemp += "<div class=\"right_pnl_refrsh_farm_sum\">Refresh farm summary<span class=\"glyphicon glyphicon-refresh\"></span></div>"
7911
7912 }
7913
7914 frm_watchingFarm();
7915
7916 //watching farm?
7917 strTemp += "<div class=\"farm_watch_summary\"></div>";
7918
7919 $(".right_details_panel_content").empty().html(strTemp);
7920
7921 }
7922
7923
7924 })
7925}
7926
7927/*########### harvest shape module ########################*/
7928
7929var fld_fieldHarvestShapes_Map;
7930var fld_harvest_shape_holes_drawingManager;
7931var fld_harvest_polygon;
7932var fld_harvest_shape_user_location = {};
7933var fld_harvest_shape_overlay;
7934var fld_harvest_automated_shape_overlay;
7935var fld_harvest_new_shape;
7936var fld_harvest_automated_max_form_validate_value = "";
7937var fld_harvest_automated_min_form_validate_value = "";
7938var fld_harvest_polygons = [];
7939var fld_harvest_automated_polygons = [];
7940var fld_fieldAutomatedHarvestShapes_Map;
7941var fieldboundary = new google.maps.MVCArray();
7942
7943
7944$(document).on("click", "#field_harvest_deleteAreas", function () {
7945
7946 $("#harvest_area_Modal").find(".alert-danger").hide().find("p").empty()
7947
7948 var str = "";
7949 for (var i = 0; i < fld_harvest_polygons.length; i++) {
7950 if (fld_harvest_polygons[i].get("fillColor") == "red") {
7951 str += "|" + fld_harvest_polygons[i].get("id");
7952 }
7953 }
7954
7955
7956 if (str != "") {
7957
7958 $.ajax({
7959 type: "POST",
7960 url: urlPrepend + "/fielddata/harvestshapedeletehole-" + getFieldId(),
7961 data: { strDelete: str }
7962 }).done(function () {
7963
7964 //hide polygons.
7965 for (var i = 0; i < fld_harvest_polygons.length; i++) {
7966 if (fld_harvest_polygons[i].get("fillColor") == "red") {
7967 fld_harvest_polygons[i].setMap(null);
7968 }
7969 }
7970
7971
7972 }).fail(function () {
7973 //display alert
7974 $("#harvest_area_Modal").find(".alert-danger").show().find("p").empty().text(txtLyrHarvArea6)
7975 });
7976 fld_harvest_shape_holes_drawingManager.setMap(fld_fieldHarvestShapes_Map);
7977 }
7978 else {
7979 //display alert
7980 $("#harvest_area_Modal").find(".alert-danger").show().find("p").empty().text(txtLyrHarvArea5)
7981 }
7982
7983 $("#field_harvest_deleteAreas").hide();
7984 $("#field_harvest_DeleteMode").prop("checked", false);
7985
7986
7987});
7988
7989var fld_harvest_polygons_listener = [];
7990
7991$(document).on("change", "#field_harvest_DeleteMode", function () {
7992
7993 if ($(this).is(":checked")) {
7994
7995 $("#field_harvest_deleteAreas").show();
7996 //make all harvest areas clickable.
7997 fld_harvest_shape_holes_drawingManager.setMap(null);
7998
7999 for (var i = 0; i < fld_harvest_polygons.length; i++) {
8000
8001 //onclick change colour of field
8002 fld_harvest_polygons_listener[i] = google.maps.event.addListener(fld_harvest_polygons[i], 'click', function (event) {
8003 if (this.get("fillColor") != "#0d47a3") {
8004 //change back colour of polygon
8005 this.setOptions({
8006 fillColor: '#0d47a3'
8007 });
8008 }
8009 else {
8010 //change colour of polygon
8011 this.setOptions({
8012 fillColor: 'red'
8013 });
8014 }
8015 });
8016 }
8017 }
8018 else {
8019
8020
8021 $("#field_harvest_deleteAreas").hide();
8022
8023 //make sure all polygons are normalised.
8024 for (var i = 0; i < fld_harvest_polygons.length; i++) {
8025
8026 //remove listener for onclick event
8027 google.maps.event.removeListener(fld_harvest_polygons_listener[i]);
8028
8029 if (fld_harvest_polygons[i].get("fillColor") != "#0d47a3") {
8030 fld_harvest_polygons[i].setOptions({
8031 fillColor: '#0d47a3',
8032 class: 'show'
8033 });
8034 }
8035 }
8036
8037 fld_harvest_shape_holes_drawingManager.setMap(fld_fieldHarvestShapes_Map);
8038
8039 }
8040 //change class in polygons.
8041})
8042
8043$(document).on("click", ".harvest_info_div", function(){
8044 $('.harvest_info_div').fadeOut(2000);
8045})
8046
8047$(document).on("click", ".harvest_area_reco_link", function () {
8048 $("#harvest_area_Modal").modal('hide');
8049 fld_harvest_automated_shape_overlay = "";
8050 $("#harvest_area_Modal_automated").modal({ backdrop: 'static', keyboard: false });
8051
8052 //set modal width and height;
8053 $("#harvest_area_Modal_automated .modal-dialog").attr("style", "width:" + gen_screen_width + "px!important;height:" + gen_screen_height + "px!important;")
8054 //set map height
8055
8056 $("#harvest_automated_area_ModalMap").attr("style", "height:" + (parseFloat(window.innerHeight) * 0.6) + "px!important;");
8057
8058
8059 $("#harvContrlAutVal").val('');
8060 $("#submitHarvestAutomated").attr("disabled", true);
8061 $("#submitHarvestAutomated").addClass("harvest_automated_form_buttons_disabled");
8062 $("#restHarvestAutomated").attr("disabled", true);
8063 $("#restHarvestAutomated").addClass("harvest_automated_form_buttons_disabled");
8064 $("#downloadHarvestAutomated").attr("disabled", true);
8065 $("#downloadHarvestAutomated").addClass("harvest_automated_form_buttons_disabled");
8066 $(".harvest_automated_error").empty().hide();
8067 $('.harvest_error_div').hide();
8068 $(".harvest_automated_map_layer_range").hide();
8069 $(".hrvst_automated_range_guide").hide();
8070 $(".harvest_automated_download_button_wrapper").hide();
8071 var temp_fieldId = getFieldId();
8072
8073 //get polygon to display
8074 fieldboundary = new google.maps.MVCArray();
8075 for (var i = 0; i < polygonsArray.length; i++) {
8076 if (polygonsArray[i].get("id") == temp_fieldId) {
8077 for (var p = 0; p < polygonsArray[i].getPath().getLength() ; p++) {
8078 fieldboundary.push(new google.maps.LatLng(polygonsArray[i].getPath().getAt(p).lat(), polygonsArray[i].getPath().getAt(p).lng()));
8079 }
8080 }
8081 }
8082
8083
8084 fld_fieldAutomatedHarvestShapes_Map = new google.maps.Map(document.getElementById('harvest_automated_area_ModalMap'),
8085 {
8086 streetViewControl: false,
8087 mapTypeId: google.maps.MapTypeId.SATELLITE,
8088 streetViewControl: false,
8089 rotateControl: false,
8090 tilt: 0
8091 });
8092 debugger;
8093
8094
8095
8096 target_MapBounds = new google.maps.LatLngBounds();
8097 for (var i = 0; i < fieldboundary.getLength() ; i++) {
8098 target_MapBounds.extend(fieldboundary.getAt(i));
8099 }
8100 fld_fieldAutomatedHarvestShapes_Map.fitBounds(target_MapBounds);
8101 debugger;
8102 fld_harvest_polygon = new google.maps.Polygon({
8103 paths: fieldboundary,
8104 map: fld_fieldAutomatedHarvestShapes_Map,
8105 fillColor: '#3DD62F',
8106 strokeColor: '#083508',
8107 strokeOpacity: 0.8,
8108 strokeWeight: 5,
8109 fillOpacity: 0.35,
8110 zIndex: 2
8111 });
8112
8113 //background overlay image ddl
8114 $.ajax({
8115 type: "POST",
8116 url: urlPrepend + "/fielddata/harvestshape-maplayers",
8117 data: { id: getFieldId() }
8118 }).done(function (data) {
8119
8120 if (data != "") {
8121 //clear placeholder first
8122 $(".harvest_automated_area_map_layer_ddl_wrapper").empty();
8123
8124 var arrMapTypes = data.split('|');
8125 var s = $('<select class=\"harvest_automated_area_map_layers form-control\"></select>');
8126 $('<option />', { value: '0', text: 'Select Map Type' }).appendTo(s);
8127
8128
8129 for (var i = 0; i < arrMapTypes.length; i++) {
8130 if (arrMapTypes[i] != "") {
8131 $('<option />', { value: arrMapTypes[i].split('_')[1], text: arrMapTypes[i].split('_')[0] }).appendTo(s);
8132 }
8133 }
8134 s.appendTo($(".harvest_automated_area_map_layer_ddl_wrapper").show());
8135 $(".harvest_area_modal_loader").hide();
8136 }
8137 else {
8138
8139 $(".harvest_automated_area_map_layer_ddl_wrapper").empty();
8140 }
8141 });
8142});
8143
8144
8145$(document).on("click", ".fld_automated_harvest_shape_email", function () {
8146 debugger;
8147 //harvest shape file is going to be emailed.
8148 $.ajax({
8149 type: "POST",
8150 url: urlPrepend + "/fielddata/harvestshapeemail",
8151 data: { farmId: getFarmId(), tradingId: getTradingId, groupId: $("#fld_harvestAutoMatedGrpId").val(), prediction: 1, sendEmail: true }
8152 }).done(function (data) {
8153 if (data.length > 0) {
8154 $("#harvest_area_Modal_automated").modal('hide');
8155 displaySuccessMsg2(txtLyrHarvArea1);
8156 }
8157 else {
8158 $("#harvest_area_Modal_automated").modal('hide');
8159 displayErrMsg(txtLyrHarvArea2);
8160 }
8161 }).fail(function () {
8162 $("#harvest_area_Modal_automated").modal('hide');
8163 displayErrMsg(txtLyrHarvArea2);
8164 });
8165});
8166
8167$(document).on("click", ".fld_automated_harvest_shape_download", function () {
8168 debugger;
8169
8170 //harvest shape file is going to be emailed.
8171 $.ajax({
8172 type: "POST",
8173 url: urlPrepend + "/fielddata/harvestshapeemail",
8174 data: { farmId: getFarmId(), tradingId: getTradingId, groupId: $("#fld_harvestAutoMatedGrpId").val(), prediction: 1 }
8175 }).done(function (data) {
8176 if (data.length > 0) {
8177 $("#harvest_area_Modal_automated").modal('hide');
8178 window.location.href = data;
8179 displaySuccessMsg2(txtLyrHarvArea3);
8180 }
8181 else {
8182 $("#harvest_area_Modal_automated").modal('hide');
8183 displayErrMsg(txtLyrHarvArea2);
8184 }
8185 }).fail(function () {
8186 $("#harvest_area_Modal_automated").modal('hide');
8187 displayErrMsg(txtLyrHarvArea2);
8188 });
8189});
8190
8191function fld_automated_harvest_getValue(typeId, mapLayerTypeId) {
8192 $.ajax({
8193 type: "POST",
8194 url: urlPrepend + "/fielddata/automatedharvestshapevalue",
8195 data: { layerType: typeId, mapLayerId: mapLayerTypeId }
8196 }).done(function (data) {
8197 fld_harvest_automated_max_form_validate_value = Math.round(data.max * 100) / 100;
8198 fld_harvest_automated_min_form_validate_value = Math.round(data.min * 100) / 100;;
8199
8200 $(".hrvst_automated_range_guide").show();
8201 $(".hrvst_automated_min").text(fld_harvest_automated_min_form_validate_value);
8202 $(".hrvst_automated_max").text(fld_harvest_automated_max_form_validate_value);
8203 });
8204}
8205
8206$(document).on("change", ".harvest_automated_area_map_layers", function () {
8207
8208
8209 $("#harvContrlAutMin").val('');
8210 $("#harvContrlAutMax").val('');
8211
8212 $(".harvest_automated_area_legend_wrapper").hide();
8213
8214 if (fld_harvest_automated_shape_overlay != "") {
8215 fld_harvest_automated_shape_overlay.setMap(null);
8216 }
8217 $("#harvContrlAutVal").val('');
8218 $(".harvest_automated_error").empty().hide();
8219 $('.harvest_error_div').hide();
8220
8221 for (var i = 0; i < fld_harvest_automated_polygons.length; i++) {
8222 fld_harvest_automated_polygons[i].setMap(null);
8223 }
8224 fld_harvest_automated_polygons = [];
8225
8226 var imgtype = $(this).find(":selected").val();
8227 if (imgtype != "0") {
8228
8229 $("#submitHarvestAutomated").show();
8230 $(".harvest_automated_map_layer_range").show();
8231 $("#submitHarvestAutomated").removeAttr("disabled");
8232 $("#submitHarvestAutomated").removeClass("harvest_automated_form_buttons_disabled");
8233 $.ajax({
8234 type: "POST",
8235 url: urlPrepend + "/fieldvariabilityassessmentdata/mostrecentimg",
8236 data: { mapLayerTypeId: imgtype, f: getFieldId() }
8237 }).done(function (data) {
8238
8239 if (data != "") {
8240 var fld_arrImgData = data.split('|');
8241
8242
8243 $("#harvest_automated_area_legend").attr("src", fld_arrImgData[1]).show();
8244 $(".harvest_automated_area_legend_wrapper").show();
8245
8246 $("#harvestAutomatedSelectedImgLayerMapLayerId").val(fld_arrImgData[2]);
8247
8248 if (!google.maps.Polygon.prototype.getBounds)
8249 google.maps.Polygon.prototype.getBounds = function () {
8250 var bounds = new google.maps.LatLngBounds();
8251 var paths = this.getPaths();
8252 for (var i = 0; i < paths.getLength() ; i++) {
8253 var path = paths.getAt(i);
8254 for (var j = 0; j < path.getLength() ; j++) {
8255 bounds.extend(path.getAt(j));
8256 }
8257 }
8258 return bounds;
8259 }
8260
8261 fld_harvest_automated_shape_overlay = new google.maps.GroundOverlay(fld_arrImgData[0], fld_harvest_polygon.getBounds());
8262 fld_harvest_automated_shape_overlay.setMap(fld_fieldAutomatedHarvestShapes_Map);
8263 fld_harvest_polygon.setOptions({ fillOpacity: 0.0 });
8264
8265 //get min and max validation values
8266 fld_automated_harvest_getValue(imgtype, fld_arrImgData[2]);
8267
8268 }
8269 else {
8270 displayErrMsg(txtLyrHarvArea4);
8271 }
8272 });
8273 }
8274 else {
8275 fld_harvest_automated_shape_overlay.setMap(null);
8276 fld_harvest_automated_shape_overlay = "";
8277 fld_harvest_polygon.setOptions({ fillOpacity: 0.5 });
8278 $(".harvest_automated_map_layer_range").hide();
8279 $(".harvest_automated_map_layer_range_min").val('');
8280 $(".harvest_automated_map_layer_range_max").val('');
8281 $("#submitHarvestAutomated").attr("disabled", true);
8282 $("#restHarvestAutomated").attr("disabled", true);
8283 $("#submitHarvestAutomated").addClass("harvest_automated_form_buttons_disabled");
8284 $("#restHarvestAutomated").addClass("harvest_automated_form_buttons_disabled");
8285 $("#harvContrlAutVal").val('');
8286 //clear any polygons on map
8287 fld_automated_harvest_clear_polygons();
8288 }
8289});
8290
8291$(document).on("click", "#restHarvestAutomated", function () {
8292 fld_automated_harvest_clear_polygons();
8293 $("#submitHarvestAutomated").attr("disabled", true);
8294 $("#restHarvestAutomated").attr("disabled", true);
8295 $("#downloadHarvestAutomated").attr("disabled", true);
8296 $("#submitHarvestAutomated").addClass("harvest_automated_form_buttons_disabled");
8297 $("#restHarvestAutomated").addClass("harvest_automated_form_buttons_disabled");
8298 $("#downloadHarvestAutomated").addClass("harvest_automated_form_buttons_disabled");
8299 $("#harvContrlAutVal").val('');
8300 $(".hrvst_automated_range_guide").hide();
8301 $(".harvest_automated_map_layer_range").hide();
8302 $(".harvest_automated_area_map_layers").val($(".harvest_automated_area_map_layers option:first").val());
8303
8304
8305 //clear everything and redraw polygon
8306
8307 if (fld_harvest_automated_shape_overlay != "") {
8308 fld_harvest_automated_shape_overlay.setMap(null);
8309 fld_harvest_automated_shape_overlay = "";
8310 }
8311 fld_harvest_polygon.setMap(null);
8312 fld_harvest_polygon = null;
8313 var temp_fieldId = getFieldId();
8314
8315 //get polygon to display
8316
8317 fld_harvest_polygon = new google.maps.Polygon({
8318 paths: fieldboundary,
8319 map: fld_fieldAutomatedHarvestShapes_Map,
8320 fillColor: '#3DD62F',
8321 strokeColor: '#000',
8322 strokeOpacity: 0.8,
8323 strokeWeight: 5,
8324 fillOpacity: 0.35,
8325 zIndex: 2
8326 });
8327
8328 //////clear any polygons on map
8329 ////fld_automated_harvest_clear_polygons();
8330});
8331
8332function fld_automated_harvest_clear_polygons() {
8333 if (fld_harvest_automated_polygons.length > 0) {
8334 for (var j = 0; j < fld_harvest_automated_polygons.length; j++) {
8335 fld_harvest_automated_polygons[j].setMap(null);
8336 }
8337 fld_harvest_automated_polygons = [];
8338 }
8339}
8340
8341$(document).on("click", "#admin_harvest_closeModal", function () {
8342 $("#harvest_area_Modal").modal('hide');
8343});
8344
8345$(document).on("click", "#submitHarvestAutomated", function () {
8346
8347 //make sure any previously drawn palygons are removed from map
8348
8349 if (fld_harvest_automated_polygons.length > 0) {
8350 for (var i = 0; i < fld_harvest_automated_polygons.length; i++) {
8351 fld_harvest_automated_polygons[i].setMap(null);
8352 }
8353 fld_harvest_automated_polygons = [];
8354 }
8355
8356
8357 //validate form
8358 var form_min_val = $("#harvContrlAutMin").val();
8359 var form_max_val = $("#harvContrlAutMax").val();
8360 var bHasError = false;
8361 $(".harvest_automated_error").empty().hide();
8362 $('.harvest_error_div').hide();
8363
8364 if (parseFloat(form_min_val) < parseFloat(fld_harvest_automated_min_form_validate_value)) {
8365 //display error
8366 $(".harvest_automated_error").empty().html("Your minimum value is less than the recommended limit of " + fld_harvest_automated_min_form_validate_value + ".").show();
8367 $('.harvest_error_div').show();
8368 bHasError = true;
8369 }
8370
8371 if (!bHasError) {
8372 if (form_max_val > parseFloat(fld_harvest_automated_max_form_validate_value)) {
8373 //display error
8374 $(".harvest_automated_error").empty().html("Your maximum value is greater than the recommended limit of " + fld_harvest_automated_max_form_validate_value + ".").show();
8375 $('.harvest_error_div').show();
8376 bHasError = true;
8377 }
8378 }
8379
8380 if (!bHasError) {
8381 if (form_max_val < form_min_val) {
8382 //display error
8383 $(".harvest_automated_error").empty().html("Your maximum value is less than your minimum value.").show();
8384 $('.harvest_error_div').show();
8385 bHasError = true;
8386 }
8387 }
8388
8389 if (!bHasError) {
8390 if (form_min_val > form_max_val) {
8391 //display error
8392 $(".harvest_automated_error").empty().html("Your minimum value is less than your maximum value.").show();
8393 $('.harvest_error_div').show();
8394 bHasError = true;
8395 }
8396 }
8397
8398
8399 if ($("#harvContrlAutVal").val() == "") {
8400 //display error
8401 $(".harvest_automated_error").empty().html("Please enter a value.").show();
8402 $('.harvest_error_div').show();
8403 bHasError = true;
8404 }
8405
8406
8407 if (fld_harvest_automated_polygons.length > 0) {
8408 //display error
8409 $(".harvest_automated_error").empty().html("You have already received an automated overlay.").show();
8410 $('.harvest_error_div').show();
8411 bHasError = true;
8412 }
8413
8414 if (!bHasError) {
8415
8416 //display loader
8417 $(".hrvst_automated_loader").show();
8418 $("#submitHarvestAutomated").addClass("harvest_automated_form_buttons_disabled");
8419 $("#submitHarvestAutomated").attr("disabled", true);
8420 $.ajax({
8421 type: "POST",
8422 url: urlPrepend + "/fielddata/automatedharvestshape",
8423 data: { mapLayerId: $("#harvestAutomatedSelectedImgLayerMapLayerId").val(), maxlevel: form_max_val, minlevel: form_min_val, fieldId: getFieldId(), layerType: $(".harvest_automated_area_map_layers").find(":selected").val() },
8424 }).done(function (data) {
8425
8426 $(".hrvst_automated_loader").hide();
8427 $("#submitHarvestAutomated").removeClass("harvest_automated_form_buttons_disabled");
8428 $("#submitHarvestAutomated").removeAttr("disabled");
8429
8430 if (data.length > 0) {
8431
8432 $("#restHarvestAutomated").removeAttr("disabled");
8433 $("#restHarvestAutomated").removeClass("harvest_automated_form_buttons_disabled");
8434 $("#downloadHarvestAutomated").removeAttr("disabled");
8435 $("#downloadHarvestAutomated").removeClass("harvest_automated_form_buttons_disabled");
8436
8437 var t = JSON.parse(data);
8438
8439 //parse data
8440 //////display editable polygon
8441 for (var i = 0; i < t.length; i++) {
8442 if (typeof (t[i].polygon) != 'undefined') {
8443 var pboundary = new google.maps.MVCArray();
8444 for (var j = 0; j < t[i].polygon.length; j++) {
8445 //get coords polygons
8446 pboundary.push(new google.maps.LatLng(t[i].polygon[j].lat, t[i].polygon[j].lng));
8447 }
8448
8449 fld_harvest_polygon = new google.maps.Polygon({
8450 paths: pboundary,
8451 map: fld_fieldAutomatedHarvestShapes_Map,
8452 fillColor: '#3DD62F',
8453 strokeColor: '#9303FF',
8454 strokeOpacity: 0.8,
8455 strokeWeight: 5,
8456 fillOpacity: 0.35,
8457 zIndex: 10,
8458 editable: true
8459 });
8460
8461 debugger;
8462 google.maps.event.addListener(fld_harvest_polygon, 'click', function( event ){
8463 debugger;
8464 for (var j = 0; j < fld_harvest_automated_polygons.length; j++) {
8465 if(fld_harvest_automated_polygons[j].containsLatLng(event.latLng.lat(), event.latLng.lng())){
8466 let fieldHoleIndex = j;
8467 debugger;
8468 console.log(fld_harvest_automated_polygons[j]);
8469
8470 let innerHolePointsCount = fld_harvest_automated_polygons[j].getPath().length
8471
8472 for (var t = 0; t < innerHolePointsCount; t++) {
8473 fld_harvest_automated_polygons[j].getPath().removeAt(0);
8474 }
8475
8476 //fld_harvest_automated_polygons[j].setMap(null);
8477 }
8478 }
8479 });
8480
8481 fld_harvest_automated_polygons.push(fld_harvest_polygon);
8482
8483 }
8484 }
8485 }
8486 else {
8487 $(".harvest_automated_error").empty().show().text("There was an error retrieving your automated recommendation");
8488 $('.harvest_error_div').show();
8489 }
8490 });;
8491 }
8492});
8493
8494
8495$(document).on("click", '#harvestShapeModal', function () {
8496
8497 //set modal width and height;
8498 $("#harvest_area_Modal .modal-dialog").attr("style", "width:" + gen_screen_width + "px!important;height:" + gen_screen_height + "px!important;")
8499 $("#harvest_area_ModalMap").attr("style", "height:" + (parseFloat(window.innerHeight) * 0.6) + "px!important;");
8500
8501 $("#harvest_area_Modal").modal({ backdrop: 'static', keyboard: false })
8502 $("#field_harvest_submitHolesModal").hide();
8503 $("#field_harvest_clearHolesModal").hide();
8504 $("#field_harvest_anotherHolesModal").hide();
8505 $("#field_harvest_createShapeFile").hide();
8506 $(".harvest_area_stage2").hide();
8507 $(".harvest_area_stage1").show();
8508 fld_harvest_shape_overlay = "";
8509 fld_harvest_new_shape = null;
8510 fld_displayHarvestFieldMap(true);
8511 $(".fld_harvest_area_stage_2_download_loader").hide();
8512 $(".fld_harvest_area_stage_2_email_loader").hide();
8513 $("#field_harvest_firstPolygon").val(0);
8514 $("#field_harvest_DeleteMode").prop("checked", false);
8515
8516});
8517
8518
8519$(document).on("click", "#admin_harvest_automated_closeModal", function () {
8520 $("#harvest_area_Modal_automated").modal('hide');
8521});
8522
8523$('#harvest_area_Modal_automated').on('shown.bs.modal', function () {
8524 $('.harvest_info_div').show();
8525})
8526
8527$(document).on("click", "#field_harvest_show_stage2", function () {
8528 $(".harvest_area_stage2").show();
8529 $(".harvest_area_stage1").hide();
8530});
8531
8532$(document).on("click", ".fld_harvest_shape_email", function () {
8533 //harvest shape file is going to be emailed.
8534 debugger;
8535 $(".fld_harvest_area_stage_2_email_loader").show();
8536 $.ajax({
8537 type: "POST",
8538 url: urlPrepend + "/fielddata/harvestshapeemail",
8539 data: { farmId: getFarmId(), tradingId: getTradingId, groupId: $("#fld_harvestAreaGrpId").val(), prediction: 0, sendEmail: true }
8540 }).done(function (data) {
8541 if (data.length > 0) {
8542 $("#harvest_area_Modal").modal('hide');
8543 displaySuccessMsg2(txtLyrHarvArea1);
8544 }
8545 else {
8546 $("#harvest_area_Modal").modal('hide');
8547 displayErrMsg(txtLyrHarvArea2);
8548 }
8549 }).fail(function () {
8550 $("#harvest_area_Modal").modal('hide');
8551 displayErrMsg(txtLyrHarvArea2);
8552 });
8553});
8554
8555$(document).on("click", ".fld_harvest_shape_download", function () {
8556 debugger;
8557 //harvest shape file is going to be emailed.
8558 $(".fld_harvest_area_stage_2_download_loader").show();
8559 $.ajax({
8560 type: "POST",
8561 url: urlPrepend + "/fielddata/harvestshapeemail",
8562 data: { farmId: getFarmId(), tradingId: getTradingId, groupId: $("#fld_harvestAreaGrpId").val(), prediction: 0 }
8563 }).done(function (data) {
8564 if (data.length > 0) {
8565 $("#harvest_area_Modal").modal('hide');
8566 window.location.href = data;
8567 displaySuccessMsg2(txtLyrHarvArea3);
8568 }
8569 else {
8570 $("#harvest_area_Modal").modal('hide');
8571 displayErrMsg(txtLyrHarvArea2);
8572 }
8573 }).fail(function () {
8574 $("#harvest_area_Modal").modal('hide');
8575 displayErrMsg(txtLyrHarvArea2);
8576 });
8577});
8578
8579var fld_hrvst_area_grp_id = 0;
8580var fld_hrvst_automated_json = [];
8581
8582$(document).on("click", "#downloadHarvestAutomated", function () {
8583
8584 fld_hrvst_automated_json = [];
8585
8586 //make all polygons un-editable
8587 if (fld_harvest_automated_polygons.length > 0) {
8588 for (var i = 0; i < fld_harvest_automated_polygons.length; i++) {
8589 fld_harvest_automated_polygons[i].setOptions({
8590 editable: false
8591 })
8592 }
8593 }
8594
8595
8596 //get polygons
8597 if (fld_harvest_automated_polygons.length > 0) {
8598
8599 $("#downloadHarvestAutomated").attr("disabled", true);
8600 $("#downloadHarvestAutomated").addClass("harvest_automated_form_buttons_disabled");
8601
8602 for (var i = 0; i < fld_harvest_automated_polygons.length; i++) {
8603 var shape_boundary = [];
8604 for (var j = 0; j < fld_harvest_automated_polygons[i].getPath().getLength() ; j++) {
8605 shape_boundary.push(new google.maps.LatLng(fld_harvest_automated_polygons[i].getPath().getAt(j).lat(), fld_harvest_automated_polygons[i].getPath().getAt(j).lng()));
8606 }
8607
8608 //save new shape.
8609 var jsonClosingShape;
8610 var json = "{\"points\":[";
8611 //create json of coordinates
8612 for (var j = 0; j < shape_boundary.length ; j++) {
8613 json += "{\"lat\":\"" + shape_boundary[j].lat() + "\",\"lng\":\"" + shape_boundary[j].lng() + "\",\"ishole\":\"true\"}";
8614
8615 if (j == 0) {
8616 jsonClosingShape = "{\"lat\":\"" + shape_boundary[j].lat() + "\",\"lng\":\"" + shape_boundary[j].lng() + "\",\"ishole\":\"true\"}";
8617 }
8618 json += ",";
8619 }
8620 json += jsonClosingShape + "]}]";
8621
8622 jsonStart = "[";
8623 fld_hrvst_automated_json.push(jsonStart + json);
8624 }
8625 fld_hrvst_automated_save_polygons();
8626 $(".harvest_automated_download_button_wrapper").show();
8627 }
8628
8629});
8630
8631function fld_hrvst_automated_save_polygons() {
8632
8633 if (fld_hrvst_automated_json.length > 0) {
8634 $.ajax({
8635 type: "POST",
8636 url: urlPrepend + "/fielddata/automatedharvestshapenewhole-" + getFieldId() + "_" + fld_hrvst_area_grp_id,
8637 data: { strJson: fld_hrvst_automated_json[0] },
8638 success: function (data) {
8639 fld_hrvst_area_grp_id = data;
8640 $("#fld_harvestAutoMatedGrpId").val(data);
8641 //remove from array
8642 fld_hrvst_automated_json.splice(0, 1);
8643
8644 //call again if we have items in the array
8645 fld_hrvst_automated_save_polygons();
8646 }
8647 });
8648 }
8649}
8650
8651$(document).on("click", "#field_harvest_clearHolesModal", function () {
8652 fld_harvest_new_shape.setMap(null);
8653 fld_harvest_new_shape = null;
8654 $("#field_harvest_submitHolesModal").hide();
8655 $("#field_harvest_clearHolesModal").hide();
8656 fld_harvest_shape_drawPoly(fld_fieldHarvestShapes_Map, fld_harvest_polygon);
8657});
8658
8659$(document).on("click", "#field_harvest_createShapeFile", function () {
8660 $("#field_harvest_submitHolesModal").hide();
8661 $("#field_harvest_clearHolesModal").hide();
8662 $("#field_harvest_anotherHolesModal").hide();
8663 $("#field_harvest_createShapeFile").hide();
8664 $(".harvest_area_stage2").show();
8665 $(".harvest_area_stage1").hide();
8666});
8667
8668$(document).on("click", "#field_harvest_anotherHolesModal", function () {
8669 $("#field_harvest_anotherHolesModal").hide();
8670 $("#field_harvest_createShapeFile").hide();
8671 fld_harvest_shape_drawPoly(fld_fieldHarvestShapes_Map, fld_harvest_polygon);
8672});
8673
8674$(document).on("click", "#field_harvest_submitHolesModal", function () {
8675 //submit hole to db
8676 var hole_boundary = [];
8677 var bPassed = true;
8678 var firstShape = true;
8679 if ($("#field_harvest_firstPolygon").val() > 0) {
8680 firstShape = false;
8681 }
8682
8683
8684 for (var i = 0; i < fld_harvest_new_shape.getPath().getLength() ; i++) {
8685 hole_boundary.push(new google.maps.LatLng(fld_harvest_new_shape.getPath().getAt(i).lat(), fld_harvest_new_shape.getPath().getAt(i).lng()));
8686 }
8687
8688 if (bPassed) {
8689
8690 loadStatus(txtHoles8);
8691 var temp_fieldId = getFieldId();
8692
8693 if (temp_fieldId == 0) {
8694 temp_fieldId = $(".harvest_area_link_legend_panel").attr("rel").split('|')[1];
8695 }
8696
8697 //save new shape.
8698 var jsonClosingShape;
8699 var json = "{\"points\":[";
8700 //create json of coordinates
8701 for (var j = 0; j < hole_boundary.length ; j++) {
8702 json += "{\"lat\":\"" + hole_boundary[j].lat() + "\",\"lng\":\"" + hole_boundary[j].lng() + "\",\"ishole\":\"true\"}";
8703
8704 if (j == 0) {
8705 jsonClosingShape = "{\"lat\":\"" + hole_boundary[j].lat() + "\",\"lng\":\"" + hole_boundary[j].lng() + "\",\"ishole\":\"true\"}";
8706 }
8707 json += ",";
8708 }
8709 json += jsonClosingShape + "]}]";
8710
8711 jsonStart = "[";
8712
8713 $.ajax({
8714 type: "POST",
8715 url: urlPrepend + "/fielddata/harvestshapenewhole-" + temp_fieldId + "_0",
8716 data: { strJson: jsonStart + json, isFirstShape: firstShape },
8717 success: function (data) {
8718 if (data > 1) {
8719
8720 $("#fld_harvestAreaGrpId").val(data);
8721
8722 var polygon = new google.maps.Polygon({
8723 paths: hole_boundary,
8724 map: fld_fieldHarvestShapes_Map,
8725 strokeColor: '#d9ff00',
8726 strokeOpacity: 0.6,
8727 strokeWeight: 1,
8728 fillColor: '#F70512',
8729 fillOpacity: 0.35
8730 });
8731 hole_boundary = [];
8732 fld_harvest_new_shape.setMap(null);
8733 fld_harvest_new_shape = null;
8734 // fld_harvest_shape_drawPoly(fld_fieldHarvestShapes_Map, fld_harvest_polygon);
8735
8736 // --- need to enable this when the api can handle creating shapefile for multple area cutouts --> $("#field_harvest_show_stage2").show();
8737
8738
8739 $("#field_harvest_submitHolesModal").hide();
8740 $("#field_harvest_clearHolesModal").hide();
8741 $("#field_harvest_anotherHolesModal").show();
8742 $("#field_harvest_createShapeFile").show();
8743
8744 $("#field_harvest_firstPolygon").val(1);
8745 }
8746 else {
8747 $("#genDangerAlert").show().find("span").first().empty().html(txtHoles7);
8748 }
8749 removeLoader();
8750
8751 //draw another shape?
8752
8753 },
8754 error: function () {
8755 $("#genDangerAlert").show().find("span").first().empty().html(txtHoles6);
8756 removeLoader();
8757 }
8758 });
8759 }
8760
8761})
8762
8763function fld_harvest_shape_holes_fn_chkPointinPolygonPoly(polygon, field) {
8764
8765 hole_setPoly = polygon;
8766 var bPassed = true;
8767 for (var i = 0; i < polygon.getPath().getLength() ; i++) {
8768
8769 if (!field.containsLatLng(polygon.getPath().getAt(i).lat(), polygon.getPath().getAt(i).lng())) {
8770 $("#harvest_area_Modal").find(".alert-danger").show().find("p").empty().text(txtHoles4)
8771 $("#field_harvest_submitHolesModal").hide();
8772 $("#field_harvest_show_stage2").show();
8773 bPassed = false;
8774 hole_setPoly.setOptions({
8775 fillColor: 'red',
8776 fillOpacity: 0.5,
8777 strokeColor: 'red',
8778 editable: false
8779 });
8780
8781 break;
8782 }
8783 }
8784
8785 if (hole_polygons.length > 1) {
8786 //need to carry out next test to see if the hole goes over any existing holes.
8787 var linepoints = [];
8788 var arrLinePts = [];
8789
8790 for (var i = 0; i < polygon.getPath().getLength() ; i++) {
8791 arrLinePts[0] = new google.maps.LatLng(polygon.getPath().getAt(i).lat(), polygon.getPath().getAt(i).lng());
8792
8793
8794 if (i == (polygon.getPath().getLength() - 1)) {
8795 arrLinePts[8] = new google.maps.LatLng(polygon.getPath().getAt(i - (polygon.getPath().getLength() - 1)).lat(), polygon.getPath().getAt(i - (polygon.getPath().getLength() - 1)).lng());
8796 }
8797 else {
8798 arrLinePts[8] = new google.maps.LatLng(polygon.getPath().getAt(i + 1).lat(), polygon.getPath().getAt(i + 1).lng());
8799 }
8800
8801 linepoints.push(arrLinePts[0]);
8802 linepoints.push(arrLinePts[8]);
8803 if (holes_fn_getPolygonPolyLineSegments(linepoints, arrLinePts)) {
8804 $("#harvest_area_Modal").find(".alert-danger").show().find("p").show().empty().text(txtHoles5)
8805 $("#field_harvest_submitHolesModal").hide();
8806 $("#field_harvest_show_stage2").show();
8807 bPassed = false;
8808 hole_setPoly.setOptions({
8809 fillColor: 'red',
8810 fillOpacity: 0.5,
8811 strokeColor: 'red',
8812 editable: false
8813 });
8814 break;
8815 }
8816 linepoints = [];
8817 }
8818 }
8819
8820 if (bPassed) {
8821 $("#field_harvest_submitHolesModal").show();
8822 $("#field_harvest_show_stage2").hide();
8823 $("#harvest_area_Modal").find(".alert-danger").hide().find("p").empty();
8824 }
8825
8826 return bPassed;
8827}
8828
8829function fld_harvest_shape_drawPoly(fld_fieldHarvestShapes_Map, fld_harvest_polygon) {
8830
8831 fld_harvest_shape_holes_drawingManager = new google.maps.drawing.DrawingManager({
8832 drawingMode: google.maps.drawing.OverlayType.POLYGON,
8833 drawingControl: false,
8834 drawingControlOptions: {
8835 drawingModes: ['polygon']
8836 },
8837
8838 polygonOptions: {
8839 fillColor: '#55580D',
8840 fillOpacity: 0.5,
8841 strokeWeight: 1,
8842 clickable: false,
8843 editable: true,
8844 zIndex: 1
8845 }
8846 });
8847
8848 fld_harvest_shape_holes_drawingManager.setMap(fld_fieldHarvestShapes_Map);
8849
8850
8851 google.maps.event.addListener(fld_harvest_shape_holes_drawingManager, 'polygoncomplete', function (polygon) {
8852 fld_harvest_shape_holes_drawingManager.setMap(null);
8853
8854 $("#field_harvest_submitHolesModal").show();
8855 $("#field_harvest_clearHolesModal").show();
8856 fld_harvest_new_shape = polygon;
8857
8858 });
8859}
8860
8861function fld_displayHarvestFieldMap(fieldPanelLink) {
8862 hole_setPoly = null;
8863 var harvest_shape_hole_fieldboundary = new google.maps.MVCArray();
8864 var harvest_shape_hole_bStartNewPolygon = false;
8865 var polygon1stPt = "";
8866 var arrHolesMVCArray = []; //this array will contain an array of harvest_shape_hole_fieldboundary
8867 var temp_fieldId = getFieldId();
8868
8869 $("#fld_harvestAreaGrpId").val(0);
8870
8871
8872
8873 if (!fieldPanelLink) {
8874 temp_fieldId = $(".harvest_area_link_legend_panel").attr("rel").split('|')[1];
8875 }
8876
8877 fld_fieldHarvestShapes_Map = new google.maps.Map(document.getElementById('harvest_area_ModalMap'),
8878 {
8879 streetViewControl: false,
8880 mapTypeId: google.maps.MapTypeId.SATELLITE,
8881 streetViewControl: false,
8882 rotateControl: false,
8883 tilt: 0
8884 });
8885
8886
8887 $.ajax({
8888 url: urlPrepend + "/fielddata/harvestshape-" + temp_fieldId
8889 }).done(function (data) {
8890
8891 //get polygon to display
8892 var fieldboundary = new google.maps.MVCArray();
8893 for (var i = 0; i < polygonsArray.length; i++) {
8894 if (polygonsArray[i].get("id") == temp_fieldId) {
8895 for (var p = 0; p < polygonsArray[i].getPath().getLength() ; p++) {
8896 fieldboundary.push(new google.maps.LatLng(polygonsArray[i].getPath().getAt(p).lat(), polygonsArray[i].getPath().getAt(p).lng()));
8897 }
8898 }
8899 }
8900
8901
8902 if (data.length > 0) {
8903
8904 var grp = 0;
8905 fld_harvest_polygons = [];
8906 for (var i = 0; i < data.length; i++) {
8907 if (i == 0) {
8908 $("#fld_harvestAreaGrpId").val(data[i].polyGroupId);
8909 }
8910 if (grp != data[i].groupId) {
8911
8912 if (grp > 0) {
8913
8914 var polygon = new google.maps.Polygon({
8915 paths: harvest_shape_hole_fieldboundary,
8916 map: fld_fieldHarvestShapes_Map,
8917 strokeColor: '#d9ff00',
8918 strokeOpacity: 0.8,
8919 strokeWeight: 2,
8920 fillColor: '#0d47a3',
8921 fillOpacity: 0.35,
8922 id: grp,
8923 zIndex: i + 1,
8924 class: 'show'
8925 });
8926
8927 fld_harvest_polygons.push(polygon);
8928 }
8929
8930 grp = data[i].groupId;
8931 harvest_shape_hole_fieldboundary = new google.maps.MVCArray();
8932 }
8933 harvest_shape_hole_fieldboundary.push(new google.maps.LatLng(data[i].lat, data[i].lng));
8934
8935 }
8936
8937 if (harvest_shape_hole_fieldboundary.length > 0) {
8938
8939
8940 //draw last polygon
8941 var polygon = new google.maps.Polygon({
8942 paths: harvest_shape_hole_fieldboundary,
8943 map: fld_fieldHarvestShapes_Map,
8944 strokeColor: '#d9ff00',
8945 strokeOpacity: 0.8,
8946 strokeWeight: 2,
8947 fillColor: '#0d47a3',
8948 fillOpacity: 0.35,
8949 id: grp,
8950 zIndex: 99,
8951 class: 'show'
8952 });
8953
8954 fld_harvest_polygons.push(polygon);
8955 grp = 0;
8956 }
8957
8958 }
8959
8960
8961 var polypath = [];
8962 polypath.push(fieldboundary);
8963
8964 //are we drawing field in the holes modal?
8965
8966
8967 target_MapBounds = new google.maps.LatLngBounds();
8968 for (var i = 0; i < fieldboundary.getLength() ; i++) {
8969 target_MapBounds.extend(fieldboundary.getAt(i));
8970 }
8971 fld_fieldHarvestShapes_Map.fitBounds(target_MapBounds);
8972
8973 fld_harvest_polygon = new google.maps.Polygon({
8974 paths: polypath,
8975 map: fld_fieldHarvestShapes_Map,
8976 fillColor: '#3DD62F',
8977 strokeColor: '#083508',
8978 strokeOpacity: 0.8,
8979 strokeWeight: 5,
8980 fillOpacity: 0.35,
8981 zIndex: 2
8982 });
8983
8984
8985 //we need to find the users location and see if its inside the field. If so then zoom into the field further
8986 if (navigator.geolocation) {
8987 navigator.geolocation.getCurrentPosition(function (position) {
8988
8989 //do these points exists inside the field?
8990 var temp_lat = position.coords.latitude;
8991 var temp_lng = position.coords.longitude;
8992 if (fld_harvest_polygon.containsLatLng(temp_lat, temp_lng)) {
8993 //zoom into this location.
8994 fld_fieldHarvestShapes_Map.setCenter(new google.maps.LatLng(temp_lat, temp_lng));
8995 fld_fieldHarvestShapes_Map.setZoom(20);
8996 };
8997 })
8998 }
8999
9000 fld_harvest_shape_drawPoly(fld_fieldHarvestShapes_Map, fld_harvest_polygon);
9001
9002 });
9003
9004 if ($(".harvest_area_stage1_map_layers").length > 0) {
9005 $(".harvest_area_stage1_map_layers").remove();
9006 }
9007
9008 if (fieldPanelLink) {
9009 //background overlay image ddl
9010 $.ajax({
9011 type: "POST",
9012 url: urlPrepend + "/fielddata/harvestshape-maplayers",
9013 data: { id: getFieldId() }
9014 }).done(function (data) {
9015
9016 if (data != "") {
9017 //clear placeholder first
9018 $("#harvest_area_map_layer_ddl_wrapper").empty();
9019
9020 var arrMapTypes = data.split('|');
9021 var s = $('<select class=\"harvest_area_stage1_map_layers form-control\"></select>');
9022 $('<option />', { value: '0', text: 'Select Map Type' }).appendTo(s);
9023
9024
9025 for (var i = 0; i < arrMapTypes.length; i++) {
9026 if (arrMapTypes[i] != "") {
9027 $('<option />', { value: arrMapTypes[i].split('_')[1], text: arrMapTypes[i].split('_')[0] }).appendTo(s);
9028 }
9029 }
9030 s.appendTo($(".harvest_area_map_layer_ddl_wrapper").show());
9031 $(".harvest_area_modal_loader").hide();
9032
9033 //display automated button if ddl exists
9034 $(".harvest_area_reco_link").show();
9035 }
9036 else {
9037
9038 $(".harvest_area_map_layer_ddl_wrapper").empty();
9039 }
9040 });
9041 }
9042 else {
9043 //opened from legend. So we have an overlay to use.
9044 if (!google.maps.Polygon.prototype.getBounds)
9045 google.maps.Polygon.prototype.getBounds = function () {
9046 var bounds = new google.maps.LatLngBounds();
9047 var paths = this.getPaths();
9048 for (var i = 0; i < paths.getLength() ; i++) {
9049 var path = paths.getAt(i);
9050 for (var j = 0; j < path.getLength() ; j++) {
9051 bounds.extend(path.getAt(j));
9052 }
9053 }
9054 return bounds;
9055 }
9056
9057 //waiting for map to fully load
9058 setTimeout(function () {
9059 fld_harvest_shape_overlay = new google.maps.GroundOverlay($(".harvest_area_link_legend_panel").attr("rel").split('|')[0], fld_harvest_polygon.getBounds());
9060 fld_harvest_shape_overlay.setMap(fld_fieldHarvestShapes_Map);
9061 fld_harvest_polygon.setOptions({ fillOpacity: 0.0 });
9062 }, 1000)
9063 }
9064
9065}
9066
9067$(document).on("click", ".harvest_area_link_legend_panel", function () {
9068
9069 $("#harvest_area_Modal").modal({ backdrop: 'static', keyboard: false })
9070 $(".harvest_area_stage2").hide();
9071 $(".harvest_area_stage1").show();
9072 fld_harvest_shape_overlay = "";
9073 fld_displayHarvestFieldMap(false);
9074
9075
9076});
9077
9078$(document).on("change", ".harvest_area_stage1_map_layers", function () {
9079
9080 if (fld_harvest_shape_overlay != "") {
9081 fld_harvest_shape_overlay.setMap(null);
9082 }
9083
9084 var imgtype = $(this).val();
9085 if (imgtype != "0") {
9086 $.ajax({
9087 type: "POST",
9088 url: urlPrepend + "/fieldvariabilityassessmentdata/mostrecentimg",
9089 data: { mapLayerTypeId: imgtype, f: getFieldId() }
9090 }).done(function (data) {
9091
9092 if (data != "") {
9093 var fld_arrImgData = data.split('|');
9094
9095 if (!google.maps.Polygon.prototype.getBounds)
9096 google.maps.Polygon.prototype.getBounds = function () {
9097 var bounds = new google.maps.LatLngBounds();
9098 var paths = this.getPaths();
9099 for (var i = 0; i < paths.getLength() ; i++) {
9100 var path = paths.getAt(i);
9101 for (var j = 0; j < path.getLength() ; j++) {
9102 bounds.extend(path.getAt(j));
9103 }
9104 }
9105 return bounds;
9106 }
9107
9108 fld_harvest_shape_overlay = new google.maps.GroundOverlay(fld_arrImgData[0], fld_harvest_polygon.getBounds());
9109 fld_harvest_shape_overlay.setMap(fld_fieldHarvestShapes_Map);
9110 fld_harvest_polygon.setOptions({ fillOpacity: 0.0 });
9111 }
9112 else {
9113 displayErrMsg(txtLyrHarvArea4);
9114 }
9115 });
9116 }
9117 else {
9118 fld_harvest_shape_overlay.setMap(null);
9119 fld_harvest_shape_overlay = "";
9120 fld_harvest_polygon.setOptions({ fillOpacity: 0.5 });
9121 }
9122
9123});
9124
9125
9126
9127/*########### harvest shape module END ########################*/
9128
9129/*########### poi module END ########################*/
9130var fld_poi_Map;
9131var fld_poi_polygon;
9132var fld_localisation = false;
9133var fld_poi_marker = "//maps.google.com/mapfiles/ms/icons/yellow.png";
9134var fld_poi_marker_old = "//maps.google.com/mapfiles/ms/icons/red.png";
9135var fld_poi_singlePointMarker;
9136var fld_poi_points = [];
9137var fld_poi_point_info = [];
9138var fld_poi_watchId;
9139var fld_poi_PointListener;
9140
9141$(document).on("click", "#dropPOI", function () {
9142
9143 //set modal width and height;
9144 $("#harvest_area_Modal .modal-dialog").attr("style", "width:" + gen_screen_width + "px!important;height:" + gen_screen_height + "px!important;")
9145 $("#poi_ModalMap").attr("style", "height:" + gen_modal_map_height + "px!important;");
9146
9147 //open modal.
9148 $("#poi_Modal").modal({ backdrop: 'static', keyboard: false });
9149 $(".submit_btn_wrapper").show();
9150 $(".start_again_btn_wrapper").hide();
9151 fld_displayPOIMap();
9152 fld_localisation = false;
9153 $("#poi_Modal").find(".alert-danger").hide().find("p").empty();
9154 $("#fld_poi_newPointInfo").val('');
9155});
9156
9157$(document).on("click", ".admin_poi_closeModal", function () {
9158 $("#poi_Modal").modal('hide');
9159 // fld_poi_modalClosed = true;
9160});
9161
9162
9163$(document).on("click", "#poi_togglelegends", function () {
9164 if ($(this).is(":checked")) {
9165 for (var i = 0; i < fld_poi_points.length; i++) {
9166 fld_poi_points[i].setMap(fld_poi_Map);
9167 }
9168 }
9169 else {
9170 for (var j = 0; j < fld_poi_points.length; j++) {
9171 fld_poi_points[j].setMap(null);
9172 }
9173 }
9174
9175 for (var k = 0; k < fld_poi_point_info.length; k++) {
9176 fld_poi_point_info[k].setMap(null);
9177 }
9178});
9179
9180
9181function fld_poi_plotCurrentMarker(lat, lng) {
9182
9183
9184 if (fld_poi_singlePointMarker != null) {
9185 fld_poi_singlePointMarker.setMap(null);
9186 fld_poi_singlePointMarker = null;
9187 }
9188
9189 if (fld_poi_polygon.containsLatLng(lat, lng)) {
9190
9191 //zoom into this location.
9192 fld_poi_Map.setCenter(new google.maps.LatLng(lat, lng));
9193 fld_poi_Map.setZoom(20);
9194 fld_localisation = true;
9195
9196 //drop draggable pin for current location and display text box and save button
9197 fld_poi_singlePointMarker = new google.maps.Marker({
9198 position: new google.maps.LatLng(lat, lng),
9199 map: fld_poi_Map,
9200 draggable: false,
9201 icon: new google.maps.MarkerImage(fld_poi_marker)
9202 });
9203
9204 }
9205 else {
9206 alert(txtLyrPOI5);
9207 navigator.geolocation.clearWatch(fld_poi_watchId);
9208 fld_localisation = false;
9209 }
9210}
9211
9212var fld_poi_geoError = function (error) {
9213 //console.log('Error occurred. Error code: ' + error.code);
9214 // error.code can be:
9215 // 0: unknown error
9216 // 1: permission denied
9217 // 2: position unavailable (error response from location provider)
9218 // 3: timed out
9219 if (error.code >= 0) {
9220 fld_localisation = false;
9221 //clear watch incase its on.
9222 navigator.geolocation.clearWatch(fld_poi_watchId);
9223 }
9224};
9225
9226
9227var t = 0;
9228var fld_poi_geoSuccess = function (position) {
9229 fld_poi_plotCurrentMarker(position.coords.latitude, position.coords.longitude)
9230};
9231
9232
9233var fld_poi_geoOptions = {
9234 enableHighAccuracy: true,
9235 maximumAge: 5000,
9236 timeout: 10 * 1000
9237}
9238
9239function fld_displayPOIMap() {
9240
9241 fld_poi_singlePointMarker = null;
9242 fld_poi_points = [];
9243 fld_poi_Map = new google.maps.Map(document.getElementById('poi_ModalMap'),
9244 {
9245 streetViewControl: false,
9246 mapTypeId: google.maps.MapTypeId.SATELLITE,
9247 streetViewControl: false,
9248 rotateControl: false,
9249 tilt: 0
9250 });
9251
9252
9253 //get polygon to display
9254 var fieldboundary = new google.maps.MVCArray();
9255 for (var i = 0; i < polygonsArray.length; i++) {
9256 if (polygonsArray[i].get("id") == getFieldId()) {
9257 for (var p = 0; p < polygonsArray[i].getPath().getLength() ; p++) {
9258 fieldboundary.push(new google.maps.LatLng(polygonsArray[i].getPath().getAt(p).lat(), polygonsArray[i].getPath().getAt(p).lng()));
9259 }
9260 }
9261 }
9262
9263 target_MapBounds = new google.maps.LatLngBounds();
9264 for (var i = 0; i < fieldboundary.getLength() ; i++) {
9265 target_MapBounds.extend(fieldboundary.getAt(i));
9266 }
9267 fld_poi_Map.fitBounds(target_MapBounds);
9268
9269 fld_poi_polygon = new google.maps.Polygon({
9270 paths: fieldboundary,
9271 map: fld_poi_Map,
9272 fillColor: '#3DD62F',
9273 strokeColor: '#083508',
9274 strokeOpacity: 0.8,
9275 strokeWeight: 5,
9276 fillOpacity: 0.35
9277 });
9278
9279
9280
9281 // check for Geolocation support
9282 if (navigator.geolocation) {
9283
9284 //we need to find the users location and see if its inside the field. If so then zoom into the field further
9285 if (navigator.geolocation) {
9286
9287 fld_poi_watchId = navigator.geolocation.watchPosition(fld_poi_geoSuccess, fld_poi_geoError, fld_poi_geoOptions);
9288 fld_localisation = true;
9289
9290 //navigator.geolocation.getCurrentPosition(function (position) {
9291
9292 // //do these points exists inside the field?
9293 // var temp_lat = position.coords.latitude;
9294 // var temp_lng = position.coords.longitude;
9295 // if (fld_poi_polygon.containsLatLng(temp_lat, temp_lng)) {
9296 // //zoom into this location.
9297 // fld_poi_Map.setCenter(new google.maps.LatLng(temp_lat, temp_lng));
9298 // fld_poi_Map.setZoom(20);
9299 // fld_localisation = true;
9300
9301 // //drop draggable pin for current location and display text box and save button
9302 // fld_poi_singlePointMarker = new google.maps.Marker({
9303 // position: new google.maps.LatLng(temp_lat, temp_lng),
9304 // map: fld_poi_Map,
9305 // draggable: true,
9306 // icon: new google.maps.MarkerImage(fld_poi_marker)
9307 // });
9308
9309 // //update location every 10 seconds
9310 // // fld_poi_modalClosed = false;
9311 // // fld_poi_updateLocation();
9312 // };
9313
9314
9315 //});
9316 }
9317 }
9318 else {
9319 fld_localisation = false;
9320 //clear watch incase its on.
9321 navigator.geolocation.clearWatch(fld_poi_watchId);
9322 }
9323
9324 //background overlay image ddl
9325 $.ajax({
9326 type: "POST",
9327 url: urlPrepend + "/fielddata/harvestshape-maplayers",
9328 data: { id: getFieldId() }
9329 }).done(function (data) {
9330
9331 if (data != "") {
9332 //clear placeholder first
9333 $(".poi_map_layer_ddl_wrapper").empty();
9334
9335 var arrMapTypes = data.split('|');
9336 var s = $('<select class=\"poi_map_layers form-control\"></select>');
9337 $('<option />', { value: '0', text: 'Select Map Type' }).appendTo(s);
9338
9339
9340 for (var i = 0; i < arrMapTypes.length; i++) {
9341 if (arrMapTypes[i] != "") {
9342 $('<option />', { value: arrMapTypes[i].split('_')[1], text: arrMapTypes[i].split('_')[0] }).appendTo(s);
9343 }
9344 }
9345 s.appendTo($(".poi_map_layer_ddl_wrapper").show());
9346 $(".poi_modal_loader").hide();
9347 }
9348 else {
9349 $(".poi_modal_loader").hide();
9350 $(".poi_map_layer_ddl_wrapper").empty();
9351 }
9352 });
9353
9354 //load previous poi
9355 $.ajax({
9356 type: "POST",
9357 url: urlPrepend + "/layerdata/field-poi",
9358 data: { fieldId: getFieldId() }
9359 }).done(function (data) {
9360
9361 if (data.length > 0) {
9362 for (var i = 0; i < data.length; i++) {
9363 fld_poi_setMarkers(data[i], i);
9364 }
9365 }
9366 });
9367
9368
9369 //allow click into field
9370 fld_poi_PointListener = google.maps.event.addListener(fld_poi_polygon, 'click', function (event) {
9371 if (!fld_localisation) {
9372 if (fld_poi_singlePointMarker != null) {
9373
9374 google.maps.event.removeListener(fld_poi_PointListener);
9375 } else {
9376 fld_poi_singlePointMarker = new google.maps.Marker({
9377 position: event.latLng,
9378 map: fld_poi_Map,
9379 draggable: true,
9380 icon: new google.maps.MarkerImage(fld_poi_marker)
9381 });
9382 }
9383 }
9384 });
9385}
9386
9387
9388function fld_poi_setMarkers(data, count) {
9389 var fld_poi_marker = new google.maps.Marker({
9390 position: new google.maps.LatLng(data.latitude, data.longitude),
9391 map: fld_poi_Map,
9392 title: data.info,
9393 icon: new google.maps.MarkerImage(fld_poi_marker_old),
9394 id: count
9395 });
9396
9397 var txt = data.info;
9398 google.maps.event.addListener(fld_poi_marker, 'click', function (txt) {
9399 infowindow.close(); // Close previously opened infowindow
9400 infowindow.setContent("<div class='lyr_poi_info_window'>" + data.info + "</div>");
9401 infowindow.open(fld_poi_Map, fld_poi_marker);
9402 fld_poi_point_info.push(infowindow);
9403 });
9404
9405 fld_poi_points.push(fld_poi_marker);
9406}
9407
9408function fld_poi_closeInfoBoxes() {
9409 for (var i = 0; i < fld_poi_point_info.length; i++) {
9410 fld_poi_point_info[i].setMap(null);
9411 }
9412}
9413
9414$(document).on("click", "#admin_poi_closeModal", function () {
9415 $("#poi_Modal").modal('hide');
9416 fld_localisation = false;
9417
9418 // check for Geolocation support
9419 if (navigator.geolocation) {
9420 //clear watch incase its on.
9421 navigator.geolocation.clearWatch(fld_poi_watchId);
9422 }
9423});
9424
9425$(document).on("click", "#poi_startAgainPOIModal", function () {
9426 $(".submit_btn_wrapper").show();
9427 $(".start_again_btn_wrapper").hide();
9428
9429 fld_poi_PointListener = google.maps.event.addListener(fld_poi_polygon, 'click', function (event) {
9430
9431 fld_poi_singlePointMarker = new google.maps.Marker({
9432 position: event.latLng,
9433 map: fld_poi_Map,
9434 draggable: true,
9435 icon: new google.maps.MarkerImage(fld_poi_marker)
9436 });
9437 });
9438
9439
9440
9441});
9442
9443$(document).on("click", "#poi_submitPOIModal", function () {
9444 var temp_validate = false;
9445
9446 //clear watchlist
9447 fld_localisation = false;
9448 // check for Geolocation support
9449 if (navigator.geolocation) {
9450 //clear watch incase its on.
9451 navigator.geolocation.clearWatch(fld_poi_watchId);
9452 }
9453
9454 $("#poi_Modal").find(".alert-danger").hide().find("p").empty();
9455
9456 //validate
9457 if (($("#fld_poi_newPointInfo").val() != "") && (fld_poi_singlePointMarker != null)) {
9458 $.ajax({
9459 type: "POST",
9460 url: urlPrepend + "/layerdata/poi/add",
9461 data: { fieldId: getFieldId(), farmId: getFarmId(), info: $("#fld_poi_newPointInfo").val(), lat: fld_poi_singlePointMarker.getPosition().lat(), lng: fld_poi_singlePointMarker.getPosition().lng() }
9462 }).done(function (data) {
9463
9464 //remove listen to map once point has been saved.
9465 google.maps.event.removeListener(fld_poi_PointListener);
9466
9467 if (data) {
9468 //update saved point
9469 var tempObj = {};
9470 tempObj.latitude = fld_poi_singlePointMarker.getPosition().lat();
9471 tempObj.longitude = fld_poi_singlePointMarker.getPosition().lng();
9472 tempObj.info = $("#fld_poi_newPointInfo").val();
9473 fld_poi_setMarkers(tempObj, 0);
9474
9475 fld_poi_singlePointMarker.setMap(null);
9476 fld_poi_singlePointMarker = null;
9477 $(".start_again_btn_wrapper div").empty().text(txtLyrPOI2);
9478 $(".submit_btn_wrapper").hide();
9479 $(".start_again_btn_wrapper").show();
9480 $("#fld_poi_newPointInfo").val('');
9481
9482 }
9483 else {
9484 $("#poi_Modal").modal('hide');
9485 displayErrMsg(txtLyrPOI3);
9486 }
9487 });
9488 }
9489 else {
9490 if ($("#fld_poi_newPointInfo").val() == "") {
9491 $("#poi_Modal").find(".alert-danger").show().find("p").empty().text(txtLyrPOI1);
9492 }
9493 if (fld_poi_singlePointMarker == null) {
9494 $("#poi_Modal").find(".alert-danger").show().find("p").empty().text(txtLyrPOI4);
9495 }
9496 }
9497});
9498
9499$(document).on("change", ".poi_map_layers", function () {
9500
9501 var imgtype = $(this).val();
9502 if (imgtype != "0") {
9503 $.ajax({
9504 type: "POST",
9505 url: urlPrepend + "/fieldvariabilityassessmentdata/mostrecentimg",
9506 data: { mapLayerTypeId: imgtype, f: getFieldId() }
9507 }).done(function (data) {
9508
9509 if (data != "") {
9510 var fld_arrImgData = data.split('|');
9511
9512 if (!google.maps.Polygon.prototype.getBounds)
9513 google.maps.Polygon.prototype.getBounds = function () {
9514 var bounds = new google.maps.LatLngBounds();
9515 var paths = this.getPaths();
9516 for (var i = 0; i < paths.getLength() ; i++) {
9517 var path = paths.getAt(i);
9518 for (var j = 0; j < path.getLength() ; j++) {
9519 bounds.extend(path.getAt(j));
9520 }
9521 }
9522 return bounds;
9523 }
9524
9525 fld_poi_overlay = new google.maps.GroundOverlay(fld_arrImgData[0], fld_poi_polygon.getBounds());
9526 fld_poi_overlay.setMap(fld_poi_Map);
9527 fld_poi_polygon.setOptions({ fillOpacity: 0.0 });
9528 }
9529 else {
9530 displayErrMsg(txtLyrHarvArea4);
9531 }
9532 });
9533 }
9534 else {
9535 fld_poi_overlay.setMap(null);
9536 fld_poi_overlay = "";
9537 fld_poi_polygon.setOptions({ fillOpacity: 0.5 });
9538 }
9539
9540});
9541/*########### poi module END ########################*/
9542
9543/*########### plant flowering points ########################*/
9544
9545var recordPlantFlowering_ModalMap;
9546var fld_recplant_polygon;
9547//var fld_replant_mobile_location;
9548var fld_replant_field_center_pt;
9549var fld_replant_field_singlePointMarker;
9550var fld_replant_marker_old = "//maps.google.com/mapfiles/ms/icons/red.png";
9551var fld_replant_marker_old_highlight = "//maps.google.com/mapfiles/ms/icons/yellow.png";
9552var fld_replant_map_new_position;
9553var fld_replant_localisation = false;
9554var fld_replant_current_singlePointMarker;
9555var fld_replant_singlePointMarker = null;
9556var fld_replant_plantCount = 0;
9557var fld_replant_map_markers = [];
9558var fld_replant_fieldboundary = new google.maps.MVCArray();
9559var fld_replant_historical_dates = [];
9560
9561$(document).on("click", "#recordPlantFlowering_submitScore", function () {
9562
9563 //validation. 1.is there a point, 2. score been selected?
9564 var tmp_validate_chk = false;
9565 var tmp_errmsg = "";
9566 var tmp_isChecked = false;
9567
9568 if (fld_replant_field_singlePointMarker == null) {
9569 tmp_errmsg = "Please add a point to the map";
9570 tmp_validate_chk = true;
9571 }
9572
9573
9574
9575 if (!tmp_validate_chk) {
9576 $(".fld_record_plant_scores").each(function () {
9577 if ($(this).is(":checked")) {
9578 tmp_isChecked = true;
9579 }
9580 });
9581
9582 if (!tmp_isChecked) {
9583 tmp_errmsg = "Please select plant status.";
9584 tmp_validate_chk = true;
9585 }
9586 }
9587
9588
9589 if (tmp_validate_chk) {
9590 alert(tmp_errmsg);
9591 }
9592 else {
9593 //we need to loop through the scores and add it individually.
9594
9595 var totalScore = 0;
9596 var json = "{\"scores\":[";
9597
9598
9599 $(".fld_record_plant_scores").each(function () {
9600 if ($(this).is(":checked")) {
9601 json += "{\"score\":\"" + $(this).val() + "\",\"qty\":\"" + $(this).next().next().next().val() + "\"},";
9602 totalScore = totalScore + (parseFloat($(this).val()) * (parseFloat($(this).next().next().next().val())));
9603 }
9604 });
9605
9606
9607 json = json.substring(0, json.length - 1) + "]}";
9608
9609 $.ajax({
9610 type: "POST",
9611 url: urlPrepend + "/fielddata/add-plant-flowering",
9612 data: { json: json, fieldId: getFieldId(), score: totalScore, notes: $("#recordPlantFlowering_note").val(), lat: fld_replant_field_singlePointMarker.getPosition().lat(), lng: fld_replant_field_singlePointMarker.getPosition().lng(), plntGrpId: fld_replant_plantCount, grpId: $("#recordPlantFlowering_grpId").val() }
9613 }).done(function (data) {
9614
9615 //enable
9616 $("#recordPlantFlowering_finish").attr("disabled", false);
9617
9618 if ($("#recordPlantFlowering_grpId").val() == "") {
9619 $("#recordPlantFlowering_grpId").val(data);
9620 }
9621
9622
9623 $(".record_plant_flowering_update").empty().text("Data has been saved. Go to next point or click 'Finish'").show();
9624
9625 //add marker onto map
9626 var temp_marker = new google.maps.Marker({
9627 position: new google.maps.LatLng(fld_replant_field_singlePointMarker.getPosition().lat(), fld_replant_field_singlePointMarker.getPosition().lng()),
9628 map: recordPlantFlowering_ModalMap,
9629 draggable: false,
9630 icon: new google.maps.MarkerImage(fld_replant_marker_old)
9631 });
9632
9633 temp_marker.setPosition(new google.maps.LatLng(fld_replant_field_singlePointMarker.getPosition().lat(), fld_replant_field_singlePointMarker.getPosition().lng()));
9634
9635 fld_replant_map_markers.push(temp_marker)
9636
9637 fld_replant_setMarkers(temp_marker, "Score " + totalScore);
9638
9639 //clear location for next point
9640 fld_replant_singlePointMarker = null;
9641 //hide editable marker.
9642 //fld_replant_field_singlePointMarker.setMap(null);
9643
9644 $("#fld_recordPlantFlwDpTitle3 span").show();
9645
9646 //reset form
9647 $("#fld_recordPlantFlwDp").removeAttr("disabled", true);
9648 $("#fld_recordPlantFlwDpTitle1 span").hide();
9649 $("#fld_recordPlantFlwDpTitle2 span").hide();
9650 $(".fld_record_plant_scores").each(function () {
9651 $(this).prop("checked", false);
9652 });
9653
9654 $(".fld_score_qty").each(function () {
9655 $(this).val('');
9656 });
9657
9658 //update plant count
9659 fld_replant_plantCount++;
9660
9661 });
9662 }
9663});
9664
9665
9666
9667function fld_replant_setMarkers(marker, info) {
9668
9669 google.maps.event.addListener(marker, 'click', function () {
9670 infowindow.close(); // Close previously opened infowindow
9671 infowindow.setContent("<div class='lyr_poi_info_window'>" + info + "</div>");
9672 infowindow.open(recordPlantFlowering_ModalMap, marker);
9673 });
9674}
9675
9676$(document).on("click", ".fld_record_plant_scores", function () {
9677 var isChecked = false;
9678 $(".fld_record_plant_scores").each(function () {
9679 if ($(this).is(":checked")) {
9680 isChecked = true;
9681 }
9682 });
9683
9684 isChecked ? $("#fld_recordPlantFlwDpTitle2 span").show() : $("#fld_recordPlantFlwDpTitle2 span").hide();
9685})
9686
9687$(document).on("click", ".fld_record_plant_scores", function () {
9688 if ($(this).is(":checked")) {
9689 if ($(this).attr("id") == "fld_recordPlantScore0") {
9690 $("#fld_score_qty_2").val("1");
9691 }
9692 if ($(this).attr("id") == "fld_recordPlantScore1") {
9693 $("#fld_score_qty_4").val("1");
9694 }
9695 if ($(this).attr("id") == "fld_recordPlantScore2") {
9696 $("#fld_score_qty_6").val("1");
9697 }
9698 if ($(this).attr("id") == "fld_recordPlantScore3") {
9699 $("#fld_score_qty_8").val("1");
9700 }
9701 if ($(this).attr("id") == "fld_recordPlantScore4") {
9702 $("#fld_score_qty_10").val("1");
9703 }
9704 }
9705 else {
9706 if ($(this).attr("id") == "fld_recordPlantScore0") {
9707 $("#fld_score_qty_2").val("");
9708 }
9709 if ($(this).attr("id") == "fld_recordPlantScore1") {
9710 $("#fld_score_qty_4").val("");
9711 }
9712 if ($(this).attr("id") == "fld_recordPlantScore2") {
9713 $("#fld_score_qty_6").val("");
9714 }
9715 if ($(this).attr("id") == "fld_recordPlantScore3") {
9716 $("#fld_score_qty_8").val("");
9717 }
9718 if ($(this).attr("id") == "fld_recordPlantScore4") {
9719 $("#fld_score_qty_10").val("");
9720 }
9721 }
9722});
9723
9724$(document).on("click", ".fld_plnt_score_addition", function () {
9725
9726 if ($(this).prev().prev().is(":checked")) {
9727 var currentVal = $(this).next().val();
9728 $(this).next().val(parseFloat(currentVal) + 1);
9729 }
9730});
9731
9732$(document).on("click", ".fld_plnt_score_minus", function () {
9733
9734 if ($(this).prev().prev().prev().prev().is(":checked")) {
9735 var currentVal = $(this).prev().val();
9736 if (currentVal > 1) {
9737 $(this).prev().val(parseFloat(currentVal) - 1);
9738 }
9739 }
9740});
9741
9742
9743$(document).on("click", ".record_plant_flowering_current_link", function (e) {
9744 e.preventDefault();
9745 //hide current
9746 $(".record_plant_flowering_current").show();
9747 $(".record_plant_flowering_historical").hide();
9748 $(".record_plant_flowering_stage2").empty().hide();
9749 $(".record_plant_flowering_stage1").show();
9750
9751
9752 if (fld_replant_field_singlePointMarker != null) {
9753 fld_replant_field_singlePointMarker.setMap(null);
9754 fld_replant_field_singlePointMarker = null;
9755 }
9756
9757 for (var i = 0; i < fld_replant_map_markers.length; i++) {
9758 fld_replant_map_markers[i].setMap(null);
9759 }
9760
9761});
9762
9763$(document).on("click", ".record_plant_flowering_historical_link", function (e) {
9764 e.preventDefault();
9765 //hide historical
9766 $(".record_plant_flowering_current").hide();
9767 $(".record_plant_flowering_historical").show();
9768 $(".record_plant_historical_data_loader").show();
9769 $(".record_plant_historical_date_data").empty().hide();
9770 $(".record_plant_historical_point_data").empty().hide();
9771 //set modal width and height;
9772 $(".record_plant_historical_cal_wrapper").empty().hide();
9773
9774 recordPlantFlowering_HistoricalModalMap = new google.maps.Map(document.getElementById('recordPlantFloweringHistorical_ModalMap'),
9775 {
9776 streetViewControl: false,
9777 mapTypeId: google.maps.MapTypeId.SATELLITE,
9778 streetViewControl: false,
9779 rotateControl: false,
9780 tilt: 0
9781 });
9782
9783 recordPlantFlowering_HistoricalModalMap.addListener('dragend', function () {
9784 fld_replant_map_new_position = recordPlantFlowering_HistoricalModalMap.getCenter();
9785 });
9786
9787 recordPlantFlowering_HistoricalModalMap.fitBounds(target_MapBounds);
9788
9789 fld_recplant_polygon = new google.maps.Polygon({
9790 paths: fld_replant_fieldboundary,
9791 map: recordPlantFlowering_HistoricalModalMap,
9792 fillColor: '#3DD62F',
9793 strokeColor: '#083508',
9794 strokeOpacity: 0.8,
9795 strokeWeight: 5,
9796 fillOpacity: 0.35
9797 });
9798
9799 //get dates for calendar
9800 $.ajax({
9801 type: "POST",
9802 url: urlPrepend + "/fielddata/plant-field-dates",
9803 data: { fieldId: getFieldId() }
9804 }).done(function (data) {
9805
9806 //hide loader
9807 $(".record_plant_historical_data_loader").hide();
9808
9809 //clear array
9810 fld_replant_historical_dates = [];
9811
9812 //set up calendar
9813 $(".record_plant_historical_cal_wrapper").empty().html("<div class=\"record_plant_historical_data_loader\"></div><div class=\"record_plant_historical_cal\"></div>").show();
9814 var temp_dates = [];
9815 for (var i = 0; i < data.length; i++) {
9816 temp_dates.push(data[i].genericStr.split(' ')[0]);
9817 }
9818
9819 var uniqueItems = [];
9820 //strip out dups
9821 $.each(temp_dates, function (i, el) {
9822 if ($.inArray(el, uniqueItems) === -1) uniqueItems.push(el);
9823 });
9824
9825
9826
9827 for (var j = 0; j < uniqueItems.length; j++) {
9828
9829 var d = uniqueItems[j].split('/')[0];
9830 var m = uniqueItems[j].split('/')[1];
9831 var y = uniqueItems[j].split('/')[2];
9832
9833 fld_replant_historical_dates.push((new Date(m + '/' + d + '/' + y)).toISOString());
9834 }
9835
9836 var setDefaultDate = new Date(fld_replant_historical_dates[0]);
9837 //display calendar
9838 $(".record_plant_historical_cal").datepicker({
9839 beforeShowDay: function (date) {
9840 return (fld_replant_historical_dates.indexOf(date.toISOString()) > -1) ? [true, "record_plant_flowering_calendar_date"] : [false, ""];
9841 },
9842 dateFormat: "dd-mm-yy",
9843 defaultDate: new Date(setDefaultDate),
9844 onSelect: function (data) {
9845 //add onclick function here
9846 fld_displayHistPlntPoints(data);
9847 },
9848 maxDate: '0'
9849 });
9850
9851
9852 //get dates
9853
9854
9855 });
9856
9857});
9858
9859var fld_replant_historical_markers = [];
9860function fld_clearHistoryPoints() {
9861 for (var i = 0; i < fld_replant_historical_markers.length; i++) {
9862 fld_replant_historical_markers[i].setMap(null);
9863 }
9864}
9865
9866function fld_displayHistPlntPoints(date) {
9867 $(".record_plant_historical_data_loader").show();
9868
9869 fld_clearHistoryPoints();
9870 $(".record_plant_historical_date_data").empty().hide();
9871 $(".record_plant_historical_point_data").empty().hide();
9872
9873
9874 $.ajax({
9875 type: "POST",
9876 url: urlPrepend + "/fielddata/plant-field-date-points",
9877 data: { d: date, fieldId: getFieldId() }
9878 }).done(function (data) {
9879 $(".record_plant_historical_data_loader").hide();
9880
9881 var r = JSON.parse(data);
9882 var temp_totalScore = 0;
9883 for (var i = 0; i < r.length; i++) {
9884
9885 //console.log(r[i]);
9886
9887 //add marker onto map
9888 var temp_marker = new google.maps.Marker({
9889 position: new google.maps.LatLng(r[i].lat, r[i].lng),
9890 map: recordPlantFlowering_HistoricalModalMap,
9891 draggable: false,
9892 icon: new google.maps.MarkerImage(fld_replant_marker_old)
9893 });
9894
9895 fld_replant_historical_markers.push(temp_marker)
9896
9897 var content = "<p>Total Point Score : " + r[i].totalScore + "</p>";
9898 temp_totalScore += parseFloat(r[i].totalScore);
9899
9900 for (var j = 0; j < r[i].details.length; j++) {
9901 content += "<p>" + r[i].details[j].stage + ". Count : " + r[i].details[j].count + "</p>";
9902 }
9903 if (r[i].notes != "") {
9904 content += "<p>Note : " + r[i].notes + "</p>";
9905 }
9906
9907 fld_HistPlntPointsListener(temp_marker, content);
9908
9909 }
9910 if (temp_totalScore > 0) {
9911 var contentDate = "<p><span>Date Summary</span><br/>Date : " + date + "</p><p>Total Field Score : " + temp_totalScore + "<p>";
9912 $(".record_plant_historical_date_data").empty().html(contentDate).show();
9913 temp_totalScore = 0;
9914 }
9915 });
9916}
9917
9918function fld_HistPlntPointsListener(marker, content) {
9919 google.maps.event.addListener(marker, 'click', function (event) {
9920
9921 fld_resetAllHistPlntPointsMarkers();
9922
9923 $(".record_plant_historical_point_data").empty().html(content).show();
9924 this.setOptions({
9925 icon: {
9926 url: fld_replant_marker_old_highlight,
9927 }
9928 })
9929 });
9930}
9931
9932
9933function fld_resetAllHistPlntPointsMarkers() {
9934 for (var i = 0; i < fld_replant_historical_markers.length; i++) {
9935 fld_replant_historical_markers[i].setOptions({
9936 icon: {
9937 url: fld_replant_marker_old
9938 }
9939 })
9940 }
9941}
9942
9943$(document).on("click", "#recordPlantFlowering_closeModal", function () {
9944 $("#recordPlantFlowering_Modal").modal('hide');
9945});
9946
9947$(document).on("click", "#BE_Flowering", function () {
9948
9949 $(".record_plant_flowering_stage1").show();
9950 $(".record_plant_flowering_stage2").hide();
9951 $(".record_plant_flowering_total_score").empty();
9952 $(".record_plant_flowering_historical").hide();
9953 $(".record_plant_flowering_current").show();
9954
9955 $("#recordPlantFlowering_Modal").modal({ backdrop: 'static', keyboard: false });
9956
9957 //set modal width and height;
9958 $("#recordPlantFlowering_Modal .modal-dialog").attr("style", "width:" + gen_screen_width + "px!important;height:" + gen_screen_height + "px!important;")
9959 $("#recordPlantFlowering_ModalMap").attr("style", "height:" + gen_modal_map_height + "px!important;");
9960 $("#recordPlantFloweringHistorical_ModalMap").attr("style", "position: relative; overflow: hidden;height:" + gen_modal_map_height + "px!important;");
9961
9962 $("#recordPlantFlowering_Modal").find(".alert-danger").hide().find("p").empty();
9963 $(".record_plant_flowering_update").empty().hide();
9964 $('#recordPlantFlowering_score').empty();
9965 $("#recordPlantFlowering_grpId").val('');
9966
9967 //make sure correct tab is active.
9968 $(".record_plant_modal_tabs").each(function () {
9969 $(this).removeClass("active");
9970 })
9971
9972 $(".record_plant_flowering_current_link").addClass("active");
9973
9974
9975
9976 $.ajax({
9977 url: urlPrepend + "/fielddata/get-plant-stages"
9978 }).done(function (data) {
9979
9980
9981 for (var i = 0; i < data.length; i++) {
9982 if (data[i] != "") {
9983 $('#recordPlantFlowering_score').append("<div><input type=\"checkbox\" id=\"fld_recordPlantScore" + i + "\" value=\"" + data[i].id + "\" class=\"fld_record_plant_scores\" /><label class=\"record_plant_flowering_stage1_label\" for=\"fld_recordPlantScore" + i + "\">" + data[i].name + "</label><span class=\"glyphicon glyphicon-plus fld_plnt_score_addition\" title=\"Add To Count\"></span><input type=\"text\" id=\"fld_score_qty_" + data[i].id + "\" class=\"fld_score_qty\" disabled /><span class=\"glyphicon glyphicon-minus fld_plnt_score_minus\" title=\"Remove From Count\"></span></div><br/>");
9984 }
9985 }
9986 });
9987
9988 recordPlantFlowering_ModalMap = new google.maps.Map(document.getElementById('recordPlantFlowering_ModalMap'),
9989 {
9990 streetViewControl: false,
9991 mapTypeId: google.maps.MapTypeId.SATELLITE,
9992 streetViewControl: false,
9993 rotateControl: false,
9994 tilt: 0
9995 });
9996
9997 recordPlantFlowering_ModalMap.addListener('dragend', function () {
9998 fld_replant_map_new_position = recordPlantFlowering_ModalMap.getCenter();
9999 });
10000
10001
10002 //get polygon to display
10003 fld_replant_fieldboundary = new google.maps.MVCArray();
10004 for (var i = 0; i < polygonsArray.length; i++) {
10005 if (polygonsArray[i].get("id") == getFieldId()) {
10006 for (var p = 0; p < polygonsArray[i].getPath().getLength() ; p++) {
10007 fld_replant_fieldboundary.push(new google.maps.LatLng(polygonsArray[i].getPath().getAt(p).lat(), polygonsArray[i].getPath().getAt(p).lng()));
10008 }
10009 }
10010 }
10011
10012 target_MapBounds = new google.maps.LatLngBounds();
10013
10014 for (var i = 0; i < fld_replant_fieldboundary.getLength() ; i++) {
10015 target_MapBounds.extend(fld_replant_fieldboundary.getAt(i));
10016 }
10017
10018 fld_replant_field_center_pt = new google.maps.LatLng(target_MapBounds.getCenter().lat(), target_MapBounds.getCenter().lng());
10019
10020 recordPlantFlowering_ModalMap.fitBounds(target_MapBounds);
10021
10022 fld_recplant_polygon = new google.maps.Polygon({
10023 paths: fld_replant_fieldboundary,
10024 map: recordPlantFlowering_ModalMap,
10025 fillColor: '#3DD62F',
10026 strokeColor: '#083508',
10027 strokeOpacity: 0.8,
10028 strokeWeight: 5,
10029 fillOpacity: 0.35
10030 });
10031
10032 // check for Geolocation support
10033 if (navigator.geolocation) {
10034 if (navigator.geolocation) {
10035 navigator.geolocation.getCurrentPosition(fld_replant_geoSuccess, fld_replant_geoError, fld_replant_geoOptions);
10036 }
10037 }
10038 else {
10039 fld_replant_localisation = false;
10040 }
10041
10042
10043 if (!fld_replant_localisation) {
10044 //allow click into field
10045
10046 var fld_replant_PointListener = google.maps.event.addListener(fld_recplant_polygon, 'click', function (event) {
10047 if (fld_replant_singlePointMarker != null) {
10048 google.maps.event.removeListener(fld_replant_PointListener);
10049 } else {
10050
10051
10052 fld_replant_singlePointMarker = new google.maps.Marker({
10053 position: event.latLng,
10054 map: recordPlantFlowering_ModalMap,
10055 draggable: true,
10056 icon: new google.maps.MarkerImage(fld_poi_marker)
10057 });
10058 }
10059 });
10060 }
10061});
10062
10063var fld_replant_geoOptions = {
10064 enableHighAccuracy: true,
10065 timeout: 10 * 1000
10066}
10067
10068var fld_replant_geoError = function (error) {
10069 //console.log('Error occurred. Error code: ' + error.code);
10070 // error.code can be:
10071 // 0: unknown error
10072 // 1: permission denied
10073 // 2: position unavailable (error response from location provider)
10074 // 3: timed out
10075 if (error.code >= 0) {
10076 fld_replant_localisation = false;
10077 }
10078};
10079
10080var fld_replant_geoSuccess = function (position) {
10081
10082
10083 if (fld_recplant_polygon.containsLatLng(position.coords.latitude, position.coords.longitude)) {
10084 // zoom into this location.
10085 fld_replant_singlePointMarker = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
10086 recordPlantFlowering_ModalMap.setCenter(fld_replant_singlePointMarker);
10087 recordPlantFlowering_ModalMap.setZoom(20);
10088 }
10089 else {
10090 //point is not inside the polygon
10091 alert("Your current location is not inside the field. Press the 'Drop point' button to add a point to the map.")
10092 };
10093};
10094
10095$(document).on("click", "#recordPlantFlowering_finish", function () {
10096
10097 //only submit if we have points on the map;
10098 if (fld_replant_map_markers.length > 0) {
10099 $.ajax({
10100 url: urlPrepend + "/fielddata/get-plant-scrores-" + $("#recordPlantFlowering_grpId").val()
10101 }).done(function (data) {
10102
10103 $(".record_plant_flowering_stage1").hide();
10104 $("#fld_recordPlantFlwDpTitle1 span").hide();
10105 $("#fld_recordPlantFlwDpTitle2 span").hide();
10106 $("#fld_recordPlantFlwDpTitle3 span").hide();
10107 $(".record_plant_flowering_update").hide();
10108 $(".record_plant_flowering_stage2").show().html("<p>Field Score : <span class=\"record_plant_flowering_total_score\">" + data + "</span></p>");
10109 // $(".record_plant_flowering_total_score").empty().text(data);
10110 $("#recordPlantFlowering_grpId").val('');
10111 });
10112 }
10113 else {
10114 alert("You do not have points on the map.")
10115 }
10116
10117
10118});
10119
10120$(document).on("click", "#fld_recordPlantFlwDp", function () {
10121
10122 var dropPtLocation;
10123
10124 $("#fld_recordPlantFlwDpTitle1 span").show();
10125 $("#fld_recordPlantFlwDpTitle2 span").hide();
10126 $("#fld_recordPlantFlwDpTitle3 span").hide();
10127 $(".record_plant_flowering_update").hide();
10128 $("#recordPlantFlowering_note").val('');
10129
10130 if (fld_replant_singlePointMarker != null) {
10131 //add tablet location
10132 dropPtLocation = fld_replant_singlePointMarker;
10133 }
10134 else {
10135
10136 //this is to check if we can get a tablet location after previous point has been saved.
10137 if (navigator.geolocation) {
10138 navigator.geolocation.getCurrentPosition(function (position) {
10139
10140 //do these points exists inside the field?
10141 var temp_lat = position.coords.latitude;
10142 var temp_lng = position.coords.longitude;
10143 if (fld_recplant_polygon.containsLatLng(temp_lat, temp_lng)) {
10144 //zoom into this location.
10145 fld_replant_singlePointMarker = new google.maps.LatLng(temp_lat, temp_lng);
10146 recordPlantFlowering_ModalMap.setCenter(fld_replant_singlePointMarker);
10147 recordPlantFlowering_ModalMap.setZoom(20);
10148 };
10149 })
10150 }
10151
10152 if (fld_replant_singlePointMarker != null) {
10153 //location of tablet.
10154 dropPtLocation = fld_replant_singlePointMarker;
10155 }
10156 else {
10157 //if we have no tablet location
10158 //location of centre of field.
10159 //use fld_replant_field_center_pt - this is centre of field.
10160 dropPtLocation = fld_replant_field_center_pt;
10161 }
10162 }
10163
10164
10165 //drop draggable pin
10166 fld_replant_field_singlePointMarker = new google.maps.Marker({
10167 position: dropPtLocation,
10168 map: recordPlantFlowering_ModalMap,
10169 draggable: true,
10170 icon: new google.maps.MarkerImage(fld_poi_marker)
10171 });
10172
10173 var temp_dragStart;
10174
10175 google.maps.event.addListener(fld_replant_field_singlePointMarker, 'dragend', function (event) {
10176
10177
10178 if (!fld_recplant_polygon.containsLatLng(this.getPosition().lat(), this.getPosition().lng())) {
10179 //point has been moved outside of field. Move it back in....
10180 fld_replant_field_singlePointMarker.setPosition(temp_dragStart);
10181 }
10182 });
10183
10184 google.maps.event.addListener(fld_replant_field_singlePointMarker, 'dragstart', function (event) {
10185 temp_dragStart = new google.maps.LatLng(this.getPosition().lat(), this.getPosition().lng());
10186 });
10187
10188 //disable buttons
10189 $("#fld_recordPlantFlwDp").attr("disabled", true);
10190 $("#recordPlantFlowering_finish").attr("disabled", true);
10191
10192
10193});
10194
10195
10196
10197/*########### plant flowering points END ########################*/
10198/*new search ddl on new field modal*/
10199
10200$("#newFieldCropLayerFarmersCropList").change(function () {
10201 //go and get variety data for the select crop.
10202 getCrpVarietyForNewFieldModal(this.value, true)
10203 $("#newFieldCropVarietyLayerSeasonList").parent().show();
10204})
10205
10206
10207function getCrpVarietyForNewFieldModal(id, isFieldNotPoint) {
10208
10209 if (!isFieldNotPoint) {
10210 if ($("#fieldPtCropVarietyLayerSeasonList option").length > 0) {
10211 //destroy select 2
10212 $("#fieldPtCropVarietyLayerSeasonList").select2("destroy");
10213 }
10214 }
10215 else {
10216 if ($("#newFieldCropVarietyLayerSeasonList option").length > 0) {
10217 //destroy select 2
10218 $("#newFieldCropVarietyLayerSeasonList").select2("destroy");
10219 }
10220 }
10221
10222
10223 $.getJSON({
10224 type: "POST",
10225 url: urlPrepend + "/layerdata/crop/pdcropvariety",
10226 data: { id: id }
10227 }).done(function (data) {
10228 if (!isFieldNotPoint) {
10229 var crpVarietyDDL = $("#fieldPtCropVarietyLayerSeasonList");
10230 crpVarietyDDL.empty();
10231
10232 if (data.length > 3) {
10233 //populate and display ddl
10234
10235 if (data.length > 0) {
10236 crpVarietyDDL.append($('<option>', {
10237 value: 0,
10238 text: "Crop Variety"
10239 }));
10240
10241 for (var i = 0; i < data.length; i++) {
10242 crpVarietyDDL.append($('<option>', {
10243 value: data[i].id,
10244 text: data[i].name
10245 }));
10246 }
10247
10248 crpVarietyDDL.parent().show();
10249 $("#fieldPtCropVarietyLayerSeasonList").select2({
10250 width: '100%',
10251 theme: 'classic'
10252 });
10253 }
10254 }
10255 else {
10256 crpVarietyDDL.parent().hide();
10257 }
10258 }
10259 else {
10260
10261 var crpVarietyDDL = $("#newFieldCropVarietyLayerSeasonList");
10262 crpVarietyDDL.empty();
10263
10264 if (data.length > 3) {
10265 //populate and display ddl
10266
10267 if (data.length > 0) {
10268 crpVarietyDDL.append($('<option>', {
10269 value: 0,
10270 text: "Crop Variety"
10271 }));
10272
10273 for (var i = 0; i < data.length; i++) {
10274 crpVarietyDDL.append($('<option>', {
10275 value: data[i].id,
10276 text: data[i].name
10277 }));
10278 }
10279
10280 crpVarietyDDL.parent().show();
10281 $("#newFieldCropVarietyLayerSeasonList").select2({
10282 width: '100%',
10283 theme: 'classic'
10284 });
10285 }
10286 }
10287 else {
10288 crpVarietyDDL.parent().hide();
10289 }
10290 }
10291
10292 });
10293}
10294
10295/*** Field Notes ***/
10296let fld_fieldNotes_editStatus = false;
10297
10298$(document).on("click", "#fld_fieldNotes_closeModal", function(){
10299 $("#fieldNotesModal").modal('hide');
10300});
10301
10302$(document).on("click",".field_notes", function(){
10303 fld_fieldNotes_editStatus = false;
10304 //open field notes modal.
10305 $("#fieldNotesModal").modal('show');
10306 $("#fieldNotesModal .modal-dialog").attr("style", "width:90%;");
10307 $("#fieldNotesModal .modal-body").attr("style", "min-height:320px;");
10308 $(".new_field_note").removeClass("error_bdr");
10309 $(".new_field_note_validation").hide();
10310 $(".fld_notes_wrapper").empty();
10311 $(".new_field_note").val("");
10312 //get field name
10313 $(".fld_fieldNote_fieldName").empty().text(" for " + $(".field_item_selected").text());
10314 $(".fld_note_item").remove();
10315 fld_fieldNotes_loadData();
10316});
10317
10318$(document).on("click", ".fld_add_field_notes", function(){
10319 fld_fieldNotes_editStatus = false;
10320 let fld_note = $(".new_field_note").val();
10321
10322 if ($(".new_field_note").val() != ""){
10323 $(".new_field_note").removeClass("error_bdr");
10324 $(".new_field_note_validation").hide();
10325
10326 $.getJSON({
10327 type: "POST",
10328 url: urlPrepend + "/fielddata/addnote",
10329 data: { fieldId: getFieldId(), note: $(".new_field_note").val(), seasonId : $("#customerSeason").find(":selected").val()}
10330 }).done(function(data){
10331 $(".fld_fieldNotes_stage").show();
10332 //data = note id
10333 $(".new_field_note").val("");
10334 //add note to list.
10335 $(".fld_notes_wrapper").prepend(fld_fieldNotes_addRow(data.id, fld_note.replace(/(\r\n|\n|\r)/g,"<br />"), data.name, fld_fieldNote_date()));
10336 });;
10337 }
10338 else{
10339 $(".new_field_note").addClass("error_bdr");
10340 $(".new_field_note_validation").removeClass("fade out").fadeIn();
10341 $(".new_field_note").focus();
10342 }
10343});
10344
10345$(document).on("blur", ".fld_note_textarea", function(){
10346
10347 let noteId = $(this).attr("id");
10348 if (!$(this).hasClass("error_bdr")){
10349 if ($(this).text() == ""){
10350 $(this).addClass("error_bdr");
10351 $(this).focus();
10352 $(".fld_note_name_err").each(function(){
10353 (noteId == $(this).attr("id")) ? $(this).show() : $(this).hide();
10354 });
10355 }
10356 else{
10357
10358 $(this).removeClass("error_bdr");
10359 $(".fld_note_name_err").hide();
10360 if (!fld_fieldNotes_editStatus){
10361 $(this).removeClass("fld_note_textarea");
10362 $(this).removeAttr("contenteditable");
10363 $(".fld_note_success").hide();
10364 }
10365 }
10366 }
10367 else{
10368 if ($(".fld_note_textarea").text() != ""){
10369 $(this).removeClass("error_bdr");
10370 $(".fld_note_name_err").hide();
10371 if (!fld_fieldNotes_editStatus){
10372 $(this).removeClass("fld_note_textarea");
10373 $(this).removeAttr("contenteditable");
10374 $(".fld_note_success").hide();
10375 $(".fld_note_save_edit").addClass("fld_note_edit").removeClass("fld_note_save_edit").removeClass("btn-success").text("Edit");
10376 }
10377 }
10378 else{
10379 $(this).addClass("error_bdr");
10380 $(this).focus();
10381 $(".fld_note_name_err").each(function(){
10382 (noteId == $(this).attr("id")) ? $(this).show() : $(this).hide();
10383 });
10384 }
10385 }
10386})
10387
10388$(document).on("focus",".new_field_note", function(){
10389 $(".fld_note_success").hide();
10390})
10391
10392$(document).on("keydown", ".fld_noteItem", function(){
10393 fld_fieldNotes_editStatus = true;
10394});
10395
10396$(document).on("click",".fld_note_save_edit", function(){
10397 fld_fieldNotes_editStatus = false;
10398 let noteId = $(this).attr("id");
10399 let fieldNoteObj = {};
10400 $(".fld_noteItem").each(function(){
10401
10402 if (noteId == $(this).attr("id")){
10403
10404 if ($(this).text() != ""){
10405 $(this).removeAttr("contenteditable");
10406 $(this).removeClass("error_bdr");
10407 fieldNoteObj.note = $(this).text();
10408 fieldNoteObj.id = noteId.split('_')[2];
10409
10410 $.ajax({
10411 url: urlPrepend + "/fielddata/editnote",
10412 type: "POST",
10413 contentType: "application/json",
10414 data: JSON.stringify(fieldNoteObj),
10415 }).done(function(data){
10416
10417 if (data == "True"){
10418 //display tick
10419 $(".fld_note_success").each(function(){
10420 if (noteId == $(this).attr("id")){
10421 $(this).show();
10422 }
10423 else{
10424 $(this).hide();
10425 }
10426 });
10427 //need to update timestamp
10428
10429 $(".fld_note_date_col").each(function(){
10430 if (noteId == $(this).attr("id")){
10431 $(this).text(fld_fieldNote_date());
10432 }
10433 });
10434
10435 $(".fld_noteItem").removeClass("fld_note_textarea");
10436 //move element to top of list.
10437 $(".fld_note_item").each(function(){
10438 if (noteId == $(this).attr("id")){
10439 $(".fld_notes_wrapper").prepend($(this));
10440 }
10441 });
10442 }
10443 else{
10444 displayErrMsg(txtFDN1);
10445 }
10446 //revert button back to edit.
10447 $(".fld_note_save_edit").addClass("fld_note_edit").removeClass("fld_note_save_edit").removeClass("btn-success").text("Edit");
10448 });
10449
10450 }
10451 else{
10452 $(this).addClass("error_bdr");
10453 $(".fld_note_name_err").each(function(){
10454 (noteId == $(this).attr("id")) ? $(this).show() : $(this).hide();
10455 });
10456 $(this).addClass("fld_note_textarea");
10457 $(this).attr("contenteditable", true);
10458 $(this).focus();
10459 }
10460
10461
10462 }
10463 });
10464});
10465
10466$(document).on("click", ".fld_note_edit", function(){
10467 fld_fieldNotes_editStatus = false;
10468 $(".fld_note_save_edit").addClass("fld_note_edit").removeClass("fld_note_save_edit").removeClass("btn-success").text("Edit");
10469
10470 let noteId = $(this).attr("id");
10471 $(".fld_note_success").hide();
10472 $(".fld_note_edit").each(function(){
10473 if ($(this).attr("id") == noteId){
10474 //$(this).off("click", foo );
10475 $(this).addClass("btn-success fld_note_save_edit");
10476 $(this).text("Save");
10477 $(this).removeClass("fld_note_edit");
10478 }
10479 else{
10480 $(this).removeClass("btn-success fld_note_save_edit");
10481 $(this).text("Edit");
10482 $(this).show()
10483 }
10484 });
10485
10486 $(".fld_noteItem").each(function(){
10487 if ($(this).attr("id") == noteId){
10488 $(this).addClass("fld_note_textarea");
10489 $(this).attr("contenteditable", true);
10490 $(this).focus()
10491 }
10492 else{
10493 $(this).removeClass("fld_note_textarea");
10494 $(this).removeAttr("contenteditable");
10495 }
10496 });
10497});
10498
10499function fld_fieldNote_date(){
10500 let today = new Date();
10501 let dd = today.getDate();
10502 let mm = today.getMonth()+1;
10503 let hh = today.getHours();
10504 let min = today.getMinutes();
10505 let sc = today.getSeconds();
10506 const yyyy = today.getFullYear();
10507 if(dd<10)
10508 {
10509 dd=`0${dd}`;
10510 }
10511
10512 if(mm<10)
10513 {
10514 mm=`0${mm}`;
10515 }
10516
10517 if(min<10)
10518 {
10519 min=`0${min}`;
10520 }
10521 if(sc<10)
10522 {
10523 sc=`0${sc}`;
10524 }
10525
10526 today = `${dd}/${mm}/${yyyy} ${hh}:${min}:${sc}`;
10527 return today;
10528}
10529
10530function fld_fieldNotes_addRow(id, note, name, date){
10531
10532 let htmlStr = "<div class=\"row fld_note_item\" id=\"fld_fieldNote_" + id + "\"><div class=\"col-md-8\"><div id=\"fld_fieldNote_" + id + "\" class=\"fld_noteItem\">" + note + "</div>";
10533 htmlStr += "<span class=\"fld_noteName\">" + name + "</span><span id=\"fld_fieldNote_" + id + "\" class=\"fld_note_name_err\">" + txtFd39 + "</span></div>";
10534 htmlStr += "<div id=\"fld_fieldNote_" + id + "\" class=\"col-md-2 fld_note_date_col\">" + date + "</div><div class=\"col-md-1\"><button id=\"fld_fieldNote_" + id + "\" class=\"fld_note_edit\">Edit</button>";
10535 htmlStr += "<span title=\"Field imported successfully\" id=\"fld_fieldNote_" + id + "\" class=\"fld_note_success\"><span class=\"glyphicon glyphicon-ok\"></span></span></div></div>";
10536 return htmlStr;
10537}
10538
10539function fld_fieldNotes_headerRow(){
10540 let htmlStr = "<div class=\"row fld_note_row_header\"><div class=\"col-md-8\"><div class=\"fld_note_header\">Note</div></div><div class=\"col-md-2\"><div class=\"fld_note_header_date\">Date Added/Edited</div></div><div class=\"col-md-1\"></div></div>";
10541 return htmlStr;
10542}
10543
10544function fld_fieldNotes_loadData(){
10545 $.getJSON({
10546 url: urlPrepend + "/fielddata/notes-" + getFieldId(),
10547 dataType: "json"
10548 }).done(function(data){
10549
10550 if ($(".fld_note_row_header").length === 0){
10551 $(".fld_notes_wrapper_header").append(fld_fieldNotes_headerRow());
10552 }
10553
10554 $(".fld_fieldNotes_stage").show();
10555
10556 if (data.length > 0){
10557 for(var i = 0; i<data.length; i++){
10558 $(".fld_notes_wrapper").append(fld_fieldNotes_addRow(data[i].id, data[i].note, data[i].staffName, data[i].date));
10559 }
10560 }
10561 else{
10562 $(".fld_fieldNotes_stage").hide();
10563 }
10564 $(".fld_fieldNotes_stage_loader").hide();
10565 });;
10566}