<script>

	$.fn.serializeObject = function(){
		var obj = {};
		$.each( this.serializeArray(), function(i,o){
			var n = o.name, v = o.value;
			obj[n] = obj[n] === undefined ? v
			: $.isArray( obj[n] ) ? obj[n].concat( v )
			: [ obj[n], v ];
		});
		
		return obj;
	};

	// Validates and submits the asset add form for cycle count
    $("#varience-create-form").validate({
		ignore: ":hidden:not(select)",
		onfocusout: false,  // Disable validation on field value changes (focus out)
    	onkeyup: false,     // Disable validation on keyup events
        rules: {
            location: {
                required: true,
            },
            asset_type_id: {
                required: true,
            },
            serial_no: {
                required: true,
                checkScannedAssetType:true,
                checkIfAlreadyScanned:true
            },
        },
		submitHandler: function (form) {
			var count = $('#count_add').val();
			count++;
			$('#count_add').val(count);
			$('#asset_count').html(count);
			$('#submit_add').attr('disabled',true);
			// var formData = $(this).serialize();
			var formData = $("#varience-create-form").serializeObject();
	
			$.ajax({  
				type: "POST",  
				url: '{{route($route_name)}}',  
				data: formData,  
				success: function(value) { 
					if (value == 'type_mismatch') {
						$('#errorText').html('Asset type mismatch');
						decrementAssetCountByOne();
					} else if (value=='asset_error') { 
						$('#errorText').html("Can't add this asset");
						decrementAssetCountByOne();
					} else if (value=='serial_exist') { 
						$('#errorText').html("Already scanned asset");
						decrementAssetCountByOne();
					} else {
						$('#asset-table').append(value);
					}
					$("#serial_no").val('');
					    	
					$('#submit_add').attr('disabled',false);
				},
				error: function(jqXHR, textStatus, errorThrown) {
					decrementAssetCountByOne();
				},
			});
		}
    });
	
	

	function decrementAssetCountByOne() {
		var count = $('#count_add').val();
		count--;
		$('#count_add').val(count);
		$('#asset_count').html(count);
	}
	</script>