// JavaScript Document

$('#specialDiscount').on('change', function () {
    if ($(this).is(':checked')) {
        $('#specialDiscountVal_div').show();
    } else {
        $('#specialDiscountVal_div').hide();
    }
});
$('#specialDiscountVal').on('keyup', function () {
    if (Number($(this).val()) > 100) {
        $(this).val(100);
    }
});
$('.savemodel1').on('click', function () {

    var clientPhoneReq = $('#clientPhoneReq').val();
    if (clientPhoneReq == 1) {
        if ($('#clientmobile').val().length != 11) {
            alert('تاكد من ادخال رقم الموبايل و ان يكون 11 رقم');
            return false;
        }
    }
    $.ajax({
        type: 'POST',
        url: 'clientControllerAjax.php?do=addclient',
        data: new FormData($("#clientInfo")[0]), //$("#clientInfo").serialize(),
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
//alert(data);
            if (data == '2')//اسم العميل مكرر
            {
                $("#newclientName").val("");
                $("#nameError").css("display", "block");
                $('#debt').html("0");
                document.getElementById("hidden_debt").value = 0;
                $("#tempclientName").val("نقدى");
                therestofdebt();
                $('#genpay').attr('readonly', true);
            } else
            {


                if (data == "3") //كود العميل مكرر
                {
                    alert('كود العميل مكرر');
                } else if (data == "1") //ادخل اسم العميل
                {
                    alert('ادخل اسم العميل');
                } else//success
                {
                    data = data.split(',');
                    $('#myModal1').modal('hide');
                    //empty modal box's inputs' values
                    emptyClientModalForm();
                    $('#supplier').val(data[0]).change();
                    $('#supplier').select2('data', {id: data[0], text: data[1]});
                }
            }
        }
    });

});




$('.savemodel2').on('click', function () {


    $('#myModal1').modal('hide');

    //$("#supplier").val("1");
    //to get old supplier
    //$('#supplier').select2('data', {id: $('#oldsupplierid').val(), text: $('#oldsuppliername').val()});
    if ($('#supplieridBeforeChange').length > 0 && $('#suppliernameBeforeChange').length > 0) {
        var supplieridBeforeChange = Number($('#supplieridBeforeChange').val());
        var suppliernameBeforeChange = $('#suppliernameBeforeChange').val();
        if (supplieridBeforeChange > 0 && suppliernameBeforeChange != "") {
            $('#supplier').select2('data', {id: supplieridBeforeChange, text: suppliernameBeforeChange});
        }
    } else {
        $('#supplier').select2('data', {id: 1, text: 'نقدى'});
        $('#debt').html("0");
        document.getElementById("hidden_debt").value = 0;


        $("#tempclientName").val("نقدى");

        $('#genpay').attr('readonly', true);
    }


    $('select').select2();
    //pricetype
    var hiddenpritype = $("#hiddenpritype").val();
    $.post('sellbillAjaxController.php?do=getPricType', {supplier_id: 1}, function (data) {
        // alert(data);
        // $('#pricetype').html(data);
        if (data == -1) {
            $("#pricetype").val(hiddenpritype).change();
        } else {
            $("#pricetype").val(data).change();
        }
    });
    //store
    $.ajax({
        type: 'GET',
        url: 'sellbillAjaxController.php?do=clientstore&id=1',
        success: function (data) {
            var current_store = Number($('#storeid option:selected').val());
            //alert(data)
            data = data.split(',,,,,');
            $(".clientstore").not('[id^="s2id_"]').find('option').remove().end().append(data[0]);
            // ## now we are in document ready if ther is store selected choose it or choose first choice
            if (current_store > 0) {
                $(".clientstore").val(current_store).trigger('change');
            } else {
                $(".clientstore").val($(".clientstore option:first").val()).trigger('change');
            }

            $('.clientstoretxt').html(data[1]);
            $('#userstoreidForClient').val(data[2]);
//            userstoreidForUser = data[3];
        }
    });



    therestofdebt();

    emptyClientModalForm();
});





function emptyClientModalForm()
{

    $('#clientInfo').find(':input').each(function () {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.value = '-1';
    });
}

function getclientdebtSuccess(data, theselectedvalue) {
//    data = getValueInTermsOfSelectedCurrency2(data);
    //data is client debt
    //theselectedvalue is supplierid
    $('#divclientdata').html(data)
    setTimeout(function () {
        data = getValueInTermsOfSelectedCurrency($('#hidden_debt_main_curr').val());
        $('#debt').html(data);
        document.getElementById("hidden_debt").value = $('#debt').html();
        //$("#tempclientName").val($("#supplier option[value='" + theselectedvalue + "']").text());
        ;
        $("#tempclientName").val($('#supplier').select2('data').text);
        ////////////add by sara//////////////////
        //get the total price of sell
        //selltotalprice(noitr);

        // get the total price of sell and return sell
        totalprice();
        //get the general discount
        thegeneraldiscount();
        checkthepayed();
        //get the general payed
        thegeneralpayed();
        therestofdebt();
        if (theselectedvalue == "1")
        {
            $('#genpay').attr('readonly', true);
            $('#genpayvisa').attr('readonly', true);
        } else
        {
            $('#genpay').attr('readonly', false);
            $('#genpayvisa').attr('readonly', false);
        }
    }, 0);
}