$(document).ready(function() {
    integer_value();
    $("#img_hide").on('ifChanged', function(event){
        $(".toggle").slideToggle();
    });
    
    $.validator.addMethod("already_exist_category_name", function(value, element) {
        var return_val = true;
        var category_name = $('input[name="category_name"]').val();
        var id = $('input[name="hidden_category_id"]').val();
        $.ajax({
            async: false,
            url: base_url + 'category/category_name_exists',
            type: 'POST',
            data: {
                category_name: category_name,
                category_id: id
            },
            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;
    });
    
    $.validator.addMethod("empty_image", function(value, element) {
        var return_val = true;
        //alert($('input[type="file"]').width());
        if($('input[name="hidden_category_id"]').val() != '' && $('input[type="file"]').attr('data-value') != '') {
            var upload_image = $('input[type="file"]').attr('data-value');
        } else if($('input[name="hidden_category_id"]').val() != '' && $('input[type="file"]').attr('data-value') == '') {
            upload_image = $('input[type="file"]').val();
        } else {
            var upload_image = $('input[type="file"]').val();
        }
        //alert(upload_image);
        if(upload_image == '') {
            return_val = false;
        }
        return return_val;
    });
  
    $('form[name="category_form"]').validate({
        errorElement: "li",
        errorLabelContainer:'.error_container',
        validClass: 'valid',
        focusInvalid: true,
        rules: {
            category_name: {
                required: true,
                already_exist_category_name: true
            },
            category_order: {
                required: true
            },
            grouping: {
                required: true
            },
            /*image: {
                empty_image: true
            }*/
        },
        messages: {
            category_name: {
                required: 'Please enter Category Name!',
                already_exist_category_name: 'Category Name already exists!'
            },
            category_order: {
                required: 'Please enter Category Order Number!'
            },
            grouping: {
                required: 'Please enter Category Grouping!'
            },
            /*image: {
                empty_image: 'Please Upload Image!'
            }*/
        }
      });
});

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