<script src="/js/plugins/jquery-validation/additional-methods.min.js"></script>
<script src="/js/plugins/mask/jquery.mask.min.js"></script>
<script>
	$(document).ready(function () {
		$(".phone_number_div").hide();
		$(".no_phone_number_div").show();
		$(".mobilephone").hide();

		$(".upload_phone_number_div").hide();
	});
	$("#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"]
			},
			serial_no: {
				required: true,
				unique: true,
				minlength: 2,
				serialunique: 5,
				unique_fields: [6, 'serial_no'],
				no_whitespaces: ["Mobile Phone Number"]
			},
			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 true;
				}
			},
			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,
			// }
		},
		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);

			if (count > 0) {
				$("#createAssetBtn").prop('disabled', false);
			} else {
				$("#createAssetBtn").prop('disabled', true);
			}
			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);
				}
			});
		}
	});

	$("#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);
					$('#asset_count').text(count);
					$('#upload-asset-form')[0].reset();
				},
				cache: false,
				contentType: false,
				processData: false
			});
		}

	});


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

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

	$("#asset_type_id").change(function () {
		if ($(this).val() != '' && $(this).val() != '--Select--' && $(this).val() != '0') {
			try {
				if ($("#asset_type_id option:selected").text() == "Mobile Phone") {
					$(".phone_number_div").show();
					$(".no_phone_number_div").show();
					$('#serial_no').unmask('(000) 000-0000');
					$(".lblserial_and_phone").html('Serial #<span class="text-danger">*</span>');
					// $(".assetTagLabel").html('IMEI #');
					$(".mobilephone").show();
					getCarrier($(this).val());
					$(".lease-fields").show('slow');

				}
				else if ($("#asset_type_id option:selected").text() == "Mobile Phone Number") {
					$(".phone_number_div").show();
					$(".no_phone_number_div").hide();
					$(".lblserial_and_phone").html('Mobile Phone Number<span class="text-danger">*</span>');
					$('#serial_no').mask('(000) 000-0000');
					$(".mobilephone").hide();
					getCarrier($(this).val());
					$(".lease-fields").hide();
				}
				else if ($("#asset_type_id option:selected").text() == "Printer") {
					$(".lease-fields").show('slow');
					$('#serial_no').unmask('(000) 000-0000');
				}
				else {
					$(".assetTagLabel").html('Asset Tag #<span class="text-danger">*</span>');
					$(".phone_number_div").hide();
					$(".no_phone_number_div").show();
					$(".lblserial_and_phone").html('Serial #<span class="text-danger">*</span>');
					$(".mobilephone").hide();
					$(".lease-fields").hide();
					$('#serial_no').unmask('(000) 000-0000');
				}

				$.ajax({
					type: "POST",
					data: { id: $(this).val(), type: $('#category').val() },
					url: "/assets-create/listHardware",
					success: function (data) {
						$('#make_and_model_id').empty();
						$('#make_and_model_id').append($('<option>', {
							value: null,
							text: "--Select--"
						}));
						$("#make_and_model_id").select2();
						$('#technical_spec_id').empty();
						$('#technical_spec_id').append($('<option>', {
							value: null,
							text: "--Select--"
						}));
						$("#technical_spec_id").select2();
						$.each(data, function (key, value) {
							$('#make_and_model_id').append($('<option>', {
								value: value.id,
								text: value.hardware
							}));
						});
					},
					error: function (value) {
					}
				});

				$.ajax({
					type: "POST",
					data: { id: $(this).val() },
					url: "{{ route('assets-create.checkAttribute') }}",
					success: function (data) {
						$("#extra_fields").html(data);
					},
					error: function (data) {
					}
				});
			} catch (err) {

			}
		}
	});

	function getCarrier(id) {
		$.ajax({
			type: "POST",
			data: { id: id },
			url: "{{ route('list-carrier') }}",
			success: function (data) {
				$('#carriers').empty();
				$('#carriers').append(data);
			},
			error: function (value) {

			}
		});
	}

	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;
	}

	$("#make_and_model_id").change(function () {
		if ($(this).val() != '' && $(this).val() != '--Select--' && $(this).val() != '0') {
			try {
				$.ajax({
					type: "POST",
					data: { id: $(this).val() },
					url: "/assets-create/listtechnics",
					success: function (data) {
						$('#technical_spec_id').empty();
						$('#technical_spec_id').append($('<option>', {
							value: 0,
							text: "--Select--"
						}));
						$("#technical_spec_id").select2();
						$.each(data, function (key, value) {
							$('#technical_spec_id').append($('<option>', {
								value: value.id,
								text: value.details
							}));
						});
					},
					error: function (value) {

					}
				});
			} catch (err) {

			}
		}
	});

	$('.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>