$(document).ready(function() {
    $.validator.addMethod("already_exist_item_name", function(value, element) {
        var return_val = true;
        var category_id = $('select[name="category_id"]').val();
        var id = $('input[name="hidden_id"]').val();
        var item_name = ($('select[name="category_id"]').val() == "0") ? $('select[name="item_id"]').val() : $('input[name="item_name"]').val();
        $.ajax({
            async: false,
            url: base_url + 'inventory_item_master/item_name_exists',
            type: 'POST',
            data: {
                category_id: category_id,
                id: id,
                item_name: item_name
            },
            dataType: "json"
        })
        .done(function(data) {
            if(data == 1) {
                return_val = false;
            }
        })
        .fail(function(jqXHR, status_code, error_thrown) {
            console.log(jqXHR.responseText);
        });
        
        return return_val;
    });
    
    $('form[name="inventory_item_form"]').validate({
        errorElement: "li",
        errorLabelContainer:'.error_container',
        validClass: 'valid',
        focusInvalid: true,
        rules: {
            code: {
                required: true
            },
            category_id: {
                required: true
            },
            item_name: {
                required: true,
                already_exist_item_name: true
            },
            item_id: {
                required: true,
                already_exist_item_name: true
            },
            unit_id: {
                required: true
            },
            quantity: {
                required: true
            },
            
        },
        messages: {
            code: {
                required: 'Please enter Item Code!'
            },
            category_id: {
                required: 'Please select Category Name!'
            },
            item_name: {
                required: 'Please enter Item Name!',
                already_exist_item_name: 'Item name already Exists!'
            },
            item_id: {
                required: 'Please select Item Name!',
                already_exist_item_name: 'Item name already Exists!'
            },
            unit_id: {
                required: 'Please select UOM!'
            },
            quantity: {
                required: 'Please enter Quantity'
            },
            
        }
    });
});

function goBack() {
    window.history.back();
}