<script src="/js/plugins/jquery-validation/additional-methods.min.js"></script>
<script src="/js/plugins/mask/jquery.mask.min.js"></script>
<script>
	
	$("#create-asset-form").validate({
		ignore: ":hidden:not(#location_id)",
		onkeyup: false,
		onfocusout: false,
		onclick: false,
		rules: {
			location_id: {
				required: true,
			},
			po_id: {
				required: true,
			},
			asset_type_id: "required",
			asset_tag: {
				required: true,
				minlength: 2,
				unique: true,
				clientunique: true,
				unique_fields: [5, 'asset_tag'],
				no_whitespaces: ["Mobile Phone Number"],
				pattern: /^[a-zA-Z0-9\-\_\(\)\+\/\# ]+$/,
			},
			serial_no: {
				required: true,
				unique: true,
				minlength: 2,
				serialunique: 5,
				unique_fields: [6, 'serial_no'],
				no_whitespaces: ["Mobile Phone Number"],
				pattern: /^[a-zA-Z0-9\-\_\(\)\+\/\# ]+$/,
			},
			carrier_id: {
				required: function () {
					if ($("#asset_type_id option:selected").text() == "Mobile Phone" || $("#asset_type_id option:selected").text() == "Mobile Phone Number") {
						return true;
					}
					return false;
				}
			},
			imei: {
				unique: function (element) {
					if ($("#imei").val().length == 0) {
						return false;
					}
					return true;
				},
				required: function () {
					if ($("#asset_type_id option:selected").text() == "Mobile Phone" || $("#asset_type_id option:selected").text() == "Mobile Phone Number") {
						return true;
					}
					return true;
				}
			},
			make_and_model_id: {
				required: function () {
					return true;
				},
				custome_required: true
			},
			technical_spec_id: {
				required: true,
				custome_required: true
			},
			// ticket_no: {
			// 	required: true,
			// }
		},
		messages: {
			asset_tag: {
				pattern: "The asset tag contains invalid characters."
			},
			serial_no: {
				pattern: "The serial # contains invalid characters."
			}
		},
		errorPlacement: function (error, element) {
			error.insertAfter($(element).next($('.errorText')));
		},
		submitHandler: function(form) {
			var formId = $(form).attr('id');
			$(form).find('button[type=submit]').prop('disabled', true);
			var count = $('#count_add').val();
			count++;

			if ($('#tblview tbody tr').length !== 0) {
				count = $('#tblview tbody tr').length;
				count++;
			}
			$('#count_add').val(count);
			$('#asset_count').html(count);
			$("#createAssetBtn").prop('disabled', true);

			if (count > 0) {
				$("#createAssetBtn").prop('disabled', false);
			}

			var formData = $(form).serialize();

			$.ajax({
				type: "POST",
				url: '{{ route("assets-create.updateRows") }}',
				data: formData,
				success: function (value) {
					$(form).find('button[type=submit]').prop('disabled', false);
					$('tbody').append(value);
					$('#tblview tbody tr').each(function(index) {
						$(this).find('td:first').text(index + 1);
					});
					$("select").val('').change();
					$('.filter-field-storage-location').trigger("chosen:updated");
					$('#' + formId)[0].reset();
					$(".extrasattributes").val('');
					$("#extra_fields").html('');
					$("#make_and_model_id").select2();
					setTimeout(function () {
						$('.alert-danger').fadeOut('fast');
					}, 30000);
				},error: function (value) {
					$("#create-asset-form").find('button[type=submit]').prop('disabled', false);
				}
			});
		}
	});

	$("#upload-asset-form").validate({
		rules: {
			bulk_upload_asset: {
				extension: "csv",
				required: true,
			}
		},
		messages: {
			bulk_upload_asset: {
				extension: "Please upload a csv file"
			}
		},errorPlacement: function (error, element) {
    	    error.insertAfter('.advanced-upload-error-div');
    	},submitHandler: function (form) {
			$('.advanced-upload-error-div').html('');

			if($('#bulk_upload_asset')[0].files[0]==undefined){
				// Create a new element to hold the error message
				$('.advanced-upload-error-div').html('<label for="bulk_upload_asset" class="error">This field is required.</label>');
				return;
			}
			$('.alert-danger').hide();

			var formData = new FormData();
			formData.append('file', $('#bulk_upload_asset')[0].files[0]);
			$.ajax({
				type: "POST",
				url: $("#upload-asset-form").attr('action'),
				data: formData,
				async: false,
				success: function (value) {
					var count = 0;
					if ($('#tblview tbody tr').length !== 0) {
						count = $('#tblview tbody tr').length;
					}
					count = parseInt(count) + parseInt(value.countVal)
					if (count > 0) {
						$("#createAssetBtn").prop('disabled', false);
					} else {
						$("#createAssetBtn").prop('disabled', true);
					}
					$('tbody').append(value.data);
					$('#upload-asset-form').append(value.errors);
					$('#upload-asset-form').append(value.duplicate_errors);
					$('.fileinput').fileinput('clear');
    				$('.advanced-upload-error-div').html('');
					$('#asset_count').text(count);
				},
				cache: false,
				contentType: false,
				processData: false
			});
		}

	});

	Array.prototype.getDuplicates = function () {
		var duplicates = {};
		for (var i = 0; i < this.length; i++) {
			if (duplicates.hasOwnProperty(this[i])) {
				duplicates[this[i]].push(i + 1);
			} else if (this.lastIndexOf(this[i]) !== i) {
				duplicates[this[i]] = [i + 1];
			}
		}

		return duplicates;
	};


	$('#createAssetBtn').click(function (e) {
		e.preventDefault();
		$("#createAssetBtn").prop('disabled', true);
		var html = '';
		$("#assetUploadErrorDiv").html('').hide();
		var formCheck = 0;
		var serialNoArray = $('#tblview .serial-no').map((i, e) => e.value).get();
		var assetTagArray = $('#tblview .asset-tag').map((i, e) => e.value).get();

		if (serialNoArray.length === new Set(serialNoArray).size) {
			formCheck++;
		} else {
			serialDuplicates = serialNoArray.getDuplicates();
			$.each(serialDuplicates, function (index, value) {
				html += '<p><strong>Warning!</strong> Serial No. ' + index + ' Duplicated in rows ' + value.toString() + '</p><br>';
			});
		}
		if (assetTagArray.length === new Set(assetTagArray).size) {
			formCheck++;
		} else {
			assetTagDuplicates = assetTagArray.getDuplicates();
			$.each(assetTagDuplicates, function (index, value) {
				html += '<p><strong>Warning!</strong> Asset Tag #. ' + index + ' Duplicated in rows ' + value.toString() + '</p><br>';
			});
		}
		if (formCheck == 2) {
			$('#bulk-upload-asset-table-form').submit();
		} else {

			$("#createAssetBtn").prop('disabled', false);
			$("#assetUploadErrorDiv").html(html).show();
			$('html, body').animate({
				scrollTop: $("#assetUploadErrorDiv").offset().top
			}, 2000);
		}

	});


	$("#serial_no").on("keyup blur", function () {
		if ($("#asset_type_id option:selected").text() === "Mobile Phone Number") {
			$("#asset_tag").val($(this).val());
		}
	});


	function sort(a, b) {
		a = a.text.toLowerCase();
		b = b.text.toLowerCase();
		if (a > b) {
			return 1;
		} else if (a < b) {
			return -1;
		}
		return 0;
	}


	$('.lease-date').datepicker({

		todayBtn: "linked",

		clearBtn: true,

		keyboardNavigation: false,

		forceParse: false,

		calendarWeeks: false,

		autoclose: true

	});


</script>
<style type="text/css">
	.error {
		min-height: 20px;
	}
</style>