var addRowIndex = 0;
$(document).ready(function() {
	
	$('body').on('focus',".datepicker", function(){
		if( $(this).hasClass('hasDatepicker') === false )  {
			$(this).datepicker({
				autoclose: true,	
				format: "dd-mm-yyyy",
				todayHighlight: true
			});
		}	
	});
	
    /* Add row functionality for material */
    $(document).on('click', '.item .add-row', function() {    
        addRowIndex ++ ;
        var formType = $(this).parents('form').hasClass('edit_form') ? 'edit' : 'add';
        var itemObj = $(this).parents('.item').clone();
        itemObj.find('.label').remove();
        itemObj.find('.uom').html('');
        itemObj.find('em.invalid').remove();
        itemObj.find('.state-success').removeClass('state-success');
        itemObj.find('.state-error').removeClass('state-error');
        itemObj.find('.invalid').removeClass('invalid');
        itemObj.find('input, select, textarea').each(function(index, element) {
            /* if ($(element).hasClass('item_hidden_ids')) {
                $(element).remove();
            } */
            
            if ($(element).prop('name') != '') {
                var name = $(element).prop('name').split('[')[0];
                name = ((formType == 'edit') && (name.indexOf('new') == -1)) ? 'new_' + name : name;
                $(element).prop('name', name + '[' + addRowIndex + ']');
            }
            
            $(element).val('');
            if ($(element).prop('tagName').toLowerCase() == 'select') {
                if ($(element).prev().hasClass('select2')) {
                    $(element).prev().remove();
                    $(element).select2({width: '100%'});
                }
            }
            
        });
        
        var itemContainer = $(this).parents('.item_container');
       
        if ($(this).parent().find('.remove-row').length) {
            $(this).remove();
        } else { 
           $(this).removeClass('add-row fa-plus-circle').addClass('remove-row fa-minus-circle');
        }
        
        if ($(itemObj).find('.remove-row').length == 0) { 
            $(itemObj).find('.add-row').after(' <i class="fa fa-2x fa-minus-circle remove-row addRow_color"></i>');
        }
      
        $(itemContainer).find('.item:last').after(itemObj);
       
    });
	
	$(document).on('keyup', '.item_container .receive_qty', function(){
		var $row    	= $(this).parent().closest('.item_details')
		,	qty  		= $row.find('.qty').val() || 0
		,	r_qty  		= $row.find('.received_qty').val() || 0
		,	enter_qty	= $(this).val()
		, 	tot_receive	= parseInt(enter_qty) + parseInt(r_qty)
		, 	balance_qty	= parseInt(qty) - parseInt(r_qty);
		
		console.log(tot_receive);
		if (tot_receive > 0) {
            if (parseInt(tot_receive) > parseInt(qty)) {
                msgBox('Entered quantity can not be exceeded than purchased quantity!');
                $(this).val(parseInt(balance_qty));
                return false;
            }
            
        }
       /* var total = 0
        ,   $row    = $(this).parent().closest('.item_details')
        ,   qty   = $row.find('.pr-qty').val() || 0
        ,   price   = $row.find('.pr-price').val() || 0
        ,   $stotal = $row.find('.stotal')
        ,   pstotal  = $stotal.val() || 0
        ,   nstotal = (qty * price).toFixed(2);
        
        $stotal.val( nstotal );
        
        $('[name="amount"]').attr('data-add-amt', ( pstotal > 0 ? nstotal - pstotal : nstotal ));
        
        setTotal();*/
    });
	
	$(document).on("click", '#purchase_details', function () {
		
        var purchase_ref_no 	= $('#purchase_ref_no').val();
		//$('.purchase_ref_div').remove()	
		
		if(purchase_ref_no == ''){
			msgBox('Please enter Purchase Ref No!');
            return false;
		}else{			
			$.ajax({
				url: base_url + 'inventory_purchase_receive/edit',
				//dataType: 'JSON',
				data: {ref_no: purchase_ref_no},
				type: 'post',
				cache: false,
				success: function (html) {
					console.log(html);								
					if(html == ''){		
						$('.purchase_ref_div').html('');				
						msgBox('Entered Purchase Ref No not exsits. Please enter valid data!!!');
            			return false;
					}else{												
						$('.purchase_ref_div').html(html);						
					}
				}
			});
		}
		return false;
    });	
    
    /* Remove row functionality for material */
    $(document).on('click', '.item .remove-row', function() {
        var itemContainer = $(this).parents('.item_container');
        $(this).parents('.item').remove();
        if (itemContainer.find('.item:last').find('.add-row').length == 0) {
           itemContainer.find('.item:last').find('.remove-row').before('<i class="fa fa-2x fa-plus-circle add-row addRow_color"></i> ');
        }
        
        if ((itemContainer.find('.item').length == 1) && (itemContainer.find('.item:last').find('.add-row').length)) {
            itemContainer.find('.item:last').find('.remove-row').remove();
        }
        get_total_amount();
    });
    
    $.validator.addMethod('category_required', function(value, element) {
        return (value != '') ? true : false;
    }, 'Please select Category Name!');
    
    $.validator.addMethod('item_required', function(value, element) {
        var return_val = true;
        var category = $(element).parents('.item').find('.category_id').val();
        
        if(category != '') {
            if(value != '') 
               return_val = true; 
            else 
               return_val = false; 
            
        } else 
           return_val = true;
        
        return return_val;
    }, 'Please select Item Name!');
    
    $.validator.addMethod('item_already_exist', function(value, element) {
        var prevItems = $(element).parents('.item').prevAll('.item');
        var category = $(element).parents('.item').find('.category_id').val();
        return ((value != '') && prevItems.find('select.category_id option[value="' + category + '"]:selected').length && prevItems.find('select.item_id option[value="' + value + '"]:selected').length) ? false : true;
    }, 'Item Name is already Exists!');
    
    $.validator.addMethod('qty_required', function(value, element) {
        var return_val = true;
        var item = $(element).parents('.item').find('.item_id').val();
        if(item != '') {
            if(value != '') 
               return_val = true; 
            else 
               return_val = false; 
            
        } else 
           return_val = true;
       
        return return_val;
    }, 'Please enter Quantity!');
    
    $.validator.addMethod('price_required', function(value, element) {
        var return_val = true;
        var item = $(element).parents('.item').find('.item_id').val();
        if(item != '') {
            if(value != '') 
               return_val = true; 
            else 
               return_val = false; 
            
        } else 
           return_val = true;
       
        return return_val;
    }, 'Please enter Price!');
    
    $.validator.addMethod('valid_qty', function(value, element) {
        var return_val = true;
        var po_item_id = $(element).parents('.item').find('.poi_id').val();
        $.ajax({
            async: false,
            url: base_url + 'inventory_purchase_receive/check_valid_qty',
            type: 'POST',
            data: {
                po_item_id: po_item_id
            },
            dataType: "json"
        })
        .done(function(data) {
            var old_poi_qty = data.poi_qty;
            var item_inv_qty = data.quantity;
            var quantity = parseFloat(old_poi_qty) - parseFloat(value);
            if(parseFloat(value) > parseFloat(old_poi_qty)){
                return_val = true;
            } else if(parseFloat(item_inv_qty) >= 0 && parseFloat(quantity) > parseFloat(item_inv_qty)) {
                return_val = false;
            }
        })
        .fail(function(XHR, status_code, error_thrown) {
            console.log(error_thrown);
        });
        return return_val;
        
    }, 'Insufficient Quantity!');
    
    $.validator.addClassRules({
        category_id: {
            category_required: true
        },
        item_id: {
            item_required: true,
            item_already_exist: true
        },
        qty: {
            qty_required: true,
            valid_qty: true
        },
        price: {
            price_required: true            
        }
    });
    
    $('form[name="purchase_form"]').validate({
        errorElement: "li",
        errorLabelContainer:'.error_container',
        validClass: 'valid',
        focusInvalid: true,
        rules: {
            supplier_id: {
                required: true
            },
            invoice_no: {
                required: true
            },
            invoice_date: {
                required: true
            },
            payment: {
                required: true
            }
        },
        messages: {
            supplier_id: {
                required: 'Please select Supplier Name!'
            },
            invoice_no: {
                required: 'Please enter Invoice No!'
            },
            invoice_date: {
                required: 'Please select Invoice Date!'
            },
            payment: {
                required: 'Please select Payment Status!'
            }
        }
    });
});

function get_item_by_cat_id(_this){
    var cat_id = $(_this).val();
    if(cat_id != '') {
        $.ajax({
            async: false,
            url: base_url + 'inventory_purchase_receive/get_items_by_cat_id',
            type: 'POST',
            data: {
                category_id: cat_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>';
            }
            $(_this).parents('.item').find('.item_id').html(item_name);
        })
        .fail(function(XHR, status_code, error_thrown) {
            console.log(error_thrown);
        });
    } else {
        $(_this).parents('.item').find('.item_id').val('');
        $(_this).parents('.item').find('.uom').html('');
        $(_this).parents('.item').find('.hidden_uom').val('');
    }
}

function get_unit_by_item_id(_this) {
    var item_id 		= $(_this).val();
    var category_id 	= $(_this).parents('.item').find('.category_id').val();
	
	var prevItems 		= $(_this).parents('.item').prevAll('.item');
    var category 		= $(_this).parents('.item').find('.category_id').val();
    if((item_id != '') && prevItems.find('select.category_id option[value="' + category + '"]:selected').length && prevItems.find('select.item_id option[value="' + item_id + '"]:selected').length){
		$(_this).val('');
		msgBox('Item Name is already Exists!!!');
       	return false;
	}
	
    if(item_id != '') {
        $.ajax({
            async: false,
            url: base_url + 'inventory_purchase_receive/get_unit_by_item_id',
            type: 'POST',
            data: {
                item_id: item_id,
                category_id: category_id
            },
            dataType: "JSON"
        })
        .done(function(data) {
            var uom = data.item.unit_name || "";
            if( uom != '' ) {
                $(_this).parents('.item').find('.uom').html('<b>UOM:' + data.item.unit_name +'</b>');
            }
            $(_this).parents('.item').find('.hidden_uom').val(data.item.id);
            
        })
        .fail(function(XHR, status_code, error_thrown) {
            console.log(error_thrown);
        });
    } else {
        $(_this).parents('.item').find('.uom').html('');
        $(_this).parents('.item').find('.hidden_uom').val('');
    }
}

function calculate_amount_by_price(_this){
    var price = ($(_this).val() != '') ? $(_this).val() : 0;
    var qty = ($(_this).parents('.item').find('.qty').val() != '') ? $(_this).parents('.item').find('.qty').val() : 0;
    var amount = parseFloat(qty) * parseFloat(price);
    $(_this).parents('.item').find('.sub_total').val((parseFloat(amount)).toFixed(2));
    get_total_amount();
}

function calculate_amount_by_qty(_this){
    var qty = ($(_this).val() != '') ? $(_this).val() : 0;
    var price = ($(_this).parents('.item').find('.price').val() != '') ? $(_this).parents('.item').find('.price').val() : 0;
    var amount = parseFloat(qty) * parseFloat(price);
    $(_this).parents('.item').find('.sub_total').val((parseFloat(amount)).toFixed(2));
    get_total_amount();
}

function get_total_amount(){
    var total_amt = 0;
    $('.sub_total').each(function() {
       total_amt = parseFloat(total_amt) + parseFloat($(this).val());
    });
    $('input[name="total"]').val((parseFloat(total_amt)).toFixed(2));
}