// JavaScript Document
var formatResult;
$(document).ready(function (e) {


//###########################################################################################################################################################
//######################################### Bills Return  controller   ##############################################################################################
//###########################################################################################################################################################

    formatResult = function (data) {
        return  data.id;
    };




    $("#billno").select2({
        placeholder: "اختر فاتورة",
        minimumInputLength: 0,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "billsajax.php?do=getbillsno",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: formatResult,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });


    $("#billno").live('change', function (e) {
        var bilNo = $(this).val();
        if (bilNo == '')
        {
            $('#billDetails').html('');
        }
        else
        {
            $.post('billsajax.php?do=getbillDetail', {bilNo: bilNo}, function (rslt) {
                $('#billDetails').html('');
                $('#billDetails').html(rslt);
                $(".positiveNo").forcepositiveNum();
                $(".positivefloat").forcepositivefloat();
            });
        }

    });

    $("#discValue").live('keyup', function (e) {
        var discValue = $(this).val();
        var oldNet = $('#oldNet').val();

        var netValue = Number(oldNet) - Number(discValue);

        $('#netValue').val(netValue);
        $('#netValueP').html(netValue);

        checkClientReceiveValue();
    });

    $("#clientReceiveValue").live('keyup', function (e) {
        checkClientReceiveValue();
    });



    function checkClientReceiveValue()
    {
        var clientReceiveValue = Number($("#clientReceiveValue").val());
        var clientReceiveValueOld = Number($("#clientReceiveValueOld").val());
        var discValue = Number($("#discValue").val());

        if (clientReceiveValue == "")
        {
            clientReceiveValue = 0;
        }

        if (clientReceiveValue > discValue)
        {
            alert('المبلغ المرتجع للعميل  أكبر من قيمة القطع المرتجعة ');
            $("#clientReceiveValue").val(clientReceiveValueOld);
            return 1;
        }
        else
        {
            return 2;
        }
    }

    $(".changeNum").live('keyup', function (e) {
        var itr = $(this).attr('data-itr');
        var retNumber = $('#retnum' + itr).val();
        var billProNumber = $('#pronum' + itr).val();
        var dis_val = Number( $('#dis_val').html());
        var oldNet = $('#oldNet').val();

        if (Number(retNumber) > Number(billProNumber))
        {
            alert('عدد القطع المراد ارجاعها أكبر من عدد الصافى للمنتج فى الفاتورة ');
            $('#retnum' + itr).val(0);
            $('#rettotal' + itr).html(0);
            $('#totalRetPrice' + itr).val(0);
        }
        else
        {
            var productPrice = $('#proprice' + itr).val();
            var productRetTotalPrice = Number(retNumber) * Number(productPrice);
            
            //# if total return more than total bill .. sub discount .
            if( productRetTotalPrice > oldNet ){
                productRetTotalPrice -= dis_val;
            }
            
            $('#rettotal' + itr).html(Number(productRetTotalPrice));
            $('#totalRetPrice' + itr).val(Number(productRetTotalPrice));
        }
        calcTotal();


    });

    function calcTotal()
    {
        var itr = $('#hidden_itr').val();
        var oldNet = $('#oldNet').val();
        var dis_val = Number( $('#dis_val').html());
        
        var totalRetNum = 0;
        var totalRetPrice = 0;
        var netValue = 0;
        for (var i = 1; i <= itr; i++)
        {
            if ($('#retnum' + i).length > 0)
            {
                var productNumber = $('#retnum' + i).val();
                var productPrice = $('#proprice' + i).val();
                var productTotalPrice = Number(productNumber) * Number(productPrice);
                totalRetPrice = totalRetPrice + productTotalPrice;
                totalRetNum = totalRetNum + Number(productNumber);

            }
        }
        netValue = Number(oldNet) - totalRetPrice;

        //# if total return more than total bill .. sub discount .
        if( totalRetPrice > oldNet ){
            totalRetPrice -= dis_val;
        }

        $('#totalRetNumP').html(Number(totalRetNum));
        $('#discValue').val(Number(totalRetPrice));

        //# add discount from profit if netValue < 0 ;
        if( netValue < 0){
            netValue += dis_val;
        }
        $('#netValue').val(netValue);
        $('#netValueP').html(netValue);

        checkClientReceiveValue();

    }

    $(".saveBillReturn").live('click', function (e) {
        var btn = $(this);
        btn.attr('disabled', true);


        var discValue = $("#discValue").val();
        var oldNet = $('#oldNet').val();
        var netValue = Number(oldNet) - Number(discValue);
        var edit = $('#edit').val();

        if ($('#netValue').val() != netValue)
        {
            alert('صافى قيمة الفاتورة  لا يساوى اجمالى الفاتورة مطروح منه قيمة القطع المرتجعة ');
            btn.attr('disabled', false);
        }
        else
        {
            if (checkClientReceiveValue() == 1)
            {
                alert('المبلغ المرتجع للعميل  أكبر من قيمة القطع المرتجعة ');
                btn.attr('disabled', false);
            }
            else
            {
                $('#billForm').submit();
            }
        }



    });


//######################################### search in bills  #########################################

    $(".searchBills").live('change', function (e) {
        var clientId = $('#client').val();
        var billNo = $('#billNo').val();
        var fromDate = $('#fromDate').val();
        var toDate = $('#toDate').val();
        $.post('billsajax.php?do=billsreturnsearch', {clientId: clientId, billNo: billNo, fromDate: fromDate, toDate: toDate}, function (rslt) {
            // alert(rslt);
            $('#searchResult').html('');
            $('#searchResult').html(rslt);
        });
    });



});