var inter = '';
$(document).ready(function() {
    integer_value();
    $("#img_hide").on('ifChanged', function(event){
        $(".toggle").slideToggle();
    });
    
    $.validator.addMethod("already_exist_item_name", function(value, element) {
        var return_val = true;
        var category_name = ($('select[name="category_id"]').val() != '') ? $('select[name="category_id"]').val() : '';
        var id = $('input[name="hidden_item_id"]').val();
        var item_name = $('input[name="item_name"]').val();
        $.ajax({
            async: false,
            url: base_url + 'item/item_name_exists',
            type: 'POST',
            data: {
                category_name: category_name,
                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;
    });
    
    $.validator.addMethod("empty_image", function(value, element) {
        var return_val = true;
        if($('input[name="hidden_item_id"]').val() != '' && $('input[type="file"]').attr('data-value')) {
            var upload_image = $('input[type="file"]').attr('data-value');
        } else if($('input[name="hidden_item_id"]').val() != '' && $('input[type="file"]').attr('data-value') == '') {
            upload_image = $('input[type="file"]').val();
        }else {
            var upload_image = $('input[type="file"]').val();
        }
        
        if(upload_image == '') {
            return_val = false;
        }
        return return_val;
    });
  
    $('form[name="item_form"]').validate({
        errorElement: "li",
        errorLabelContainer:'.error_container',
        validClass: 'valid',
        focusInvalid: true,
        rules: {
            category_id: {
                required: true
            },
            item_name: {
                required: true,
                already_exist_item_name: true
            },
            price: {
                required: true
            },
            /*image: {
                empty_image: true
            }*/
        },
        messages: {
            category_id: {
                required: 'Please select Category Name!'
            },
            item_name: {
                required: 'Please enter Item Name!',
                already_exist_item_name: 'Item Name already exists!'
            },
            price: {
                required: 'Please enter Price!'
            },
            /*image: {
                empty_image: 'Please Upload Image!'
            }*/
        }
      });
     
    $('[name="item_name"]').on('keyup', function(){
        window.clearInterval(inter);
        if( $(this).val() != '' ) {
            inter = window.setInterval(function(){
                window.clearInterval(inter);
                showInvCat();
            }, 700);
        }else {
            $('[name="inv_cat"]').val('').removeAttr('readonly').find('option').show();
        }
        
    });
      
    $('[name="is_inventory"]').on('ifClicked', function(){
        setTimeout(function(){
            showInvCat();
        }, 100);
        
    });
    
    $('[name="inv_cat"]').on('change', function(){
        if( $(this).val() != '' ) {
            $('[type="submit"]').removeAttr('disabled');
        }else {
            $('[type="submit"]').attr('disabled', 'disabled');
        }
        
    });
    
    if( method == 'view' && $('#inv-cat-id').length > 0 ) {
        var invCatId = $('#inv-cat-id').val() || "";
        if( invCatId != '' ) {
            var data = {
                type    : 'get_inv_cat',
                value   : invCatId,
            };

            $.post( baseURL + controller + '/ajax/', data, function(results){
                results = JSON.parse(results);

                if( results != '' ) {
                    $('#inv-cat-wrap .second-coln').html(results['name']);
                }
            });
            
        }
        
    }else if( method == 'edit' ) {
        showInvCat();
    }
});

function showInvCat(){
    if( !$('[name="is_inventory"]').is(':checked') ) {
        // Unchecked
        $('[name="inv_cat"]').removeClass('req');
        $('#inv-cat-wrap').slideUp('slow', function(){
            $('[type="submit"]').removeAttr('disabled');
        });

    }else {
        // Checked
        $('[name="inv_item"]').val('');
        var itemName = $('[name="item_name"]').val();

        if( itemName == '' ) {
            msgBox('Please enter the Item name first!');
            setTimeout(function(){
                $('[name="is_inventory"]').prop('checked', false).parent().removeClass('checked').attr('aria-checked', false); //;
            }, 400);

            $('[name="item_name"]').focus();
            return false;
        }

        $('[type="submit"]').attr('disabled', 'disabled');

        var data = {
            type    : 'check',
            value   : itemName,
        };

        $.post( baseURL + controller + '/ajax/', data, function(results){
            results = JSON.parse(results);

            if( results != '' ) {
                // Already Inv. Category exists
                $('[name="inv_item"]').val(results['item_id']);
                $('[name="inv_cat"]').val(results['category_id']).attr('readonly', 'readonly').find('option').hide();//.attr('onclick', 'javascript: return false;');
                $('[type="submit"]').removeAttr('disabled');

            }else {
                $('[name="inv_cat"]').val('').removeAttr('readonly').find('option').show();//.removeAttr('onclick');
            }

            $('[name="inv_cat"]').addClass('req');
            $('#inv-cat-wrap').slideDown('slow');
        });


    }
}
    

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