function checkAdjust(){
    
    var adjQty = parseInt($('[name="issued_qty"]').val()) || 0
    ,   availQty = parseInt($('[name="avail_qty"]').val()) || 0
    ,   isPositive = $('[name="adj_type"]:checked').val() == 1 ? true : false;
    
    msgBox();
    if( adjQty > 0 ) {
        
        if( !isPositive ){
            
           if( adjQty > availQty ){ 
                // Overflow
                $('[name="issued_qty"]').val(availQty);
                msgBox("Unable to reduce than actual available quanity!");
                return false;
            }/*else{
                var totIssuedQty = parseInt( $('[name="avail_qty"]').attr('data-issued-qty') ) || 0;
                if( adjQty < totIssuedQty && totIssuedQty > 0 ){
                    // Reduce more than already issued qty
                    $('[name="issued_qty"]').val(totIssuedQty);
                    msgBox("Sorry, Unable to reduce than "+ totIssuedQty+" Quantity! <div> Because of those items are already issued.</div>");
                    return false;
                }
            }*/
        }
    }
    
    return true;
    
}

$(document).ready(function() {
    
    $('[name="issued_qty"]').on('keyup', function(){		
        checkAdjust();
    });
    
	$('[name="issued_qty"]').on('blur', function(){
		var adjQty 		= parseInt($('[name="issued_qty"]').val()) || 0
    	,   availQty 	= parseInt($('[name="avail_qty"]').val()) || 0;
		
		var balanceQty = availQty - adjQty;
		$('[name="balance_qty"]').val(balanceQty);
	});
	
    $('[name="adj_type"]').on('ifClicked', function(){
        setTimeout(function(){
            checkAdjust();
        }, 400);
    });
    
    $('select[name="category_id"]').change(function(){
        var category_id = $(this).val();
        if(category_id != '') {
            $.ajax({
                async: false,
                url: base_url + 'inventory_stock_issue/get_items_by_cat_id',
                type: 'POST',
                data: {
                    category_id: category_id
                },
                dataType: "json"
            })
            .done(function(data) {                
                var item_name ='';
                item_name += '<option value="">Select Item Name</option>';
                for(var i in data.items) {
                    var item = data.items[i];
                    item_name += '<option value="'+ item.id +'">'+ item.item_name+'</option>';
                }
                $('select[name="item_id"]').html(item_name);
                $('input[name="avail_qty"]').val('');
            })
            .fail(function(XHR, status_code, error_thrown) {
                console.log(error_thrown);
            });
        } else {
            $('select[name="item_id"]').val('');
            $('input[name="avail_qty"]').val('');
        }
    });
    
    $('select[name="item_id"]').change(function(){
        var item_id = $(this).val();
        var category_id = $('select[name="category_id"]').val();
        if(item_id != '') {
            $.ajax({
                async: false,
                url: base_url + 'inventory_stock_issue/get_unit_by_item_id',
                type: 'POST',
                data: {
                    item_id: item_id,
                    category_id: category_id
                },
                dataType: "JSON"
            })
            .done(function(data) {
                var availQty = data.item.now_avail_qty || 0;
                $('input[name="avail_qty"]').val(availQty);
            })
            .fail(function(XHR, status_code, error_thrown) {
                console.log(error_thrown);
            });
        } else {           
            $('input[name="avail_qty"]').val('');
        }
    });
    
    
    $.validator.addMethod("valid_issued_qty", function(value, element) {
        var return_val = true;
        var avail_qty = $('input[name="avail_qty"]').val();
        var issue_qty = $('input[name="issued_qty"]').val();
        if(parseFloat(avail_qty) < parseFloat(issue_qty)) {
            return_val = false;
            return false;
        }
        return return_val;
    });
    
    $('form[name="inv_stock_issue_form"]').validate({
        errorElement: "li",
        errorLabelContainer:'.error_container',
        validClass: 'valid',
        focusInvalid: true,
        rules: {
			stock_issue: {
				required: true
			},
            category_id: {
                required: true
            },
            item_id: {
                required: true
            },
            issued_qty: {
                required: true,
                valid_issued_qty: true
            },
			issue_date: {
                required: true
            }
        },
        messages: {
			stock_issue: {
				required: "Please enter stock issue to!"
			},
            category_id: {
                required: 'Please select Category Name!'
            },
            item_id: {
                required: 'Please select Item Name!'
            },
            issued_qty: {
                required: 'Please enter Issued Quantity!',
                valid_issued_qty: 'Issued Quantity should not be greater than Available Quantity!'
            },
            issue_date: {
                required: 'Please select Issue Date!'
            }
        }
    });

});

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