$(document).ready(function () {




    formatResult = function (data) {
        return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">';
    };


    $("#client_2").select2({
        placeholder: "اختر عميل ",
        minimumInputLength: 0,
        //  minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "billsajax.php?do=getclients&noadd=1", //# to prevent add new client noadd = 1.
            dataType: 'json',
            data: function (term, page) {
                //  alert(term);
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                };
            },
            results: function (data) {

                // alert(term);
                return {results: data};
            }
        },
        formatResult: formatResult,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //# to prevent add client .

            var data = {id: item[0], text: item[1]};
            callback(data);


        }
    }).on('change', function () {
    });

    $("#bill_no").select2({
        placeholder: "اختر رقم الفاتورة ",
        minimumInputLength: 0,
        //  minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "billsajax.php?do=getBills",
            dataType: 'json',
            data: function (term, page) {
                //  alert(term);
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                };
            },
            results: function (data) {

                // alert(term);
                return {results: data};
            }
        },
        formatResult: formatResult,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //# to prevent add client .

            var data = {id: item[0], text: item[1]};
            callback(data);


        }
    }).on('change', function () {
    });

    function paymentnetworks(paymentnetworks) {
        $(paymentnetworks).select2({
            placeholder: "اختر نوع شبكة ",
            minimumInputLength: 0,
            //  minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "billsajax.php?do=getpaymentnetworks",
                dataType: 'json',
                data: function (term, page) {
                    //  alert(term);
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                    };
                },
                results: function (data) {

                    // alert(term);
                    return {results: data};
                }
            },
            formatResult: formatResult,
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                //# to prevent add client .

                var data = {id: item[0], text: item[1]};
                callback(data);


            }
        }).on('change', function () {
        });

    }

    paymentnetworks(".paymentnetworks");
    $('body').on('change', '.paytype', function () {
        var ths_val = $(this).val();
        var id = $(this).attr('data-id');
        paymentnetworks('#paymentnetworks_' + id + '');

        if (ths_val == 'shbka') {
            //$('.paymentnetworks').css("display","none");
            $('#s2id_paymentnetworks_' + id + '').css("display", "block");
        } else {
            $('#s2id_paymentnetworks_' + id + '').css("display", "none");
        }

    });

    $('body').on('keyup', '.bill_pay', function () {
        var bill_id = $(this).attr('data-id');
        var pay = Number($(this).val());

        var waitvalue = Number($('#waitvalue_' + bill_id + '').text());
        //# check if pay larger than wait value of not .
        if (pay > waitvalue) {
            alert('خطأ ... فيمة السداد اكبر من قيمة الدين .');
            $(this).val('0');
        } else {
            var total = 0;
            $('.bill_pay').each(function () {

                var ths_val = Number($(this).val());
                total += ths_val;
            });
            $('#total_value').text(total);
            $('#total_value_h').val(total);

            console.log('total = ' + total);
        }

    });


    $('body').on('click', '.save_payment', function () {

        var total_value_h = $('#total_value_h').val();
        if (total_value_h > 0) {

            var id_pay = [];
            var check_paymentnetwork = '';
            $('.bill_pay').each(function () {
                var bill_id = $(this).attr('data-id');


                var bill_tr = $('#bill_tr_' + bill_id + '');
                var ths_val = Number($(this).val());
                var paymentnetworks_id = 0;
                if (ths_val > 0) {
                    //# remove hidden print class if exist to show tr in print .
                    if (bill_tr.hasClass('hidden-print')) {
                        bill_tr.removeClass('hidden-print');
                    }

                    var paytype = $('#paytype_' + bill_id + ':checked').val();
                    console.log('paytype = ' + paytype);
                    var paytype_txt = '';
                    if (paytype == 'cashe') {
                        paytype_txt = 'كاش'
                    } else {
                        var paymentnetworks_data = $('#s2id_paymentnetworks_' + bill_id + '').select2('data');
                        var paymentnetworks = paymentnetworks_data.text
                        paymentnetworks_id = paymentnetworks_data.id;
                        paytype_txt = 'شبكة - ' + paymentnetworks;
                        if (typeof (paymentnetworks_id) == 'undefined') {
                            check_paymentnetwork = 'يجب اختيار نوع الشبكة';
                        }
                    }
                    //console.log('paytype_txt = '+paytype_txt);
                    //# allow this span to show pay type text .
                    // $('#paytype_text_'+bill_id+'').removeClass('hide');
                    $('#paytype_text_' + bill_id + ' span').html(paytype_txt);
                    $('.paytype_radio').addClass('hidden-print');

                    //# change total dept value .
                    var values = [bill_id, ths_val, paytype_txt, paymentnetworks_id];
                    var lbl_dept = Number($('#lbl_dept').html());
                    lbl_dept = lbl_dept - ths_val;
                    $('#lbl_dept').html(lbl_dept);
                    var total_dept = Number($('#waitValue').val()) + Number($('#lbl_dept').html());
                    $('#total_dept').html(Number(total_dept));


                    id_pay.push(values);
                } else {
                    //# add hidden print class to prevent empty payment from showing on print .
                    if (!bill_tr.hasClass('hidden-print')) {
                        bill_tr.addClass('hidden-print');
                    }
                }

            });
            //console.log(id_pay);
            var client_id = $('#client_id').val();
            //console.log('client_id = '+client_id);

            var payment_print = $(this).attr('data-print');

            $.post('billsajax.php?do=addclientDeptChange', {id_pay: id_pay, client_id: client_id}, function (data) {

                var bills = $('#bills').val();
                if (check_paymentnetwork == '') {
                    if (bills == 'yes') {

                        if (payment_print == 'yes') {

                            var contents = data;
                            var frame1 = $('<iframe />');
                            frame1[0].name = "frame1";
                            // frame1.css({ "position": "absolute", "top": "-1000000px" });
                            $("body").append(frame1);
                            var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;

                            frameDoc.document.open();
                            //Create a new HTML document.
                            frameDoc.document.write('<html><head><title>DIV Contents</title>');
                            //Append the external CSS file.


                            frameDoc.document.write('</head><body>');

                            //Append the DIV contents.
                            frameDoc.document.write(contents);

                            frameDoc.document.write('</body></html>');
                            frameDoc.document.close();
                            setTimeout(function () {
                                window.frames["frame1"].focus();
                                window.frames["frame1"].print();
                                frame1.remove();
                            }, 500);

                            $('#table_container').html('');
                            $('#clientdept-modal').modal('hide');

                        } else {

                            $('#table_container').html('');
                            $('#clientdept-modal').modal('hide');
                        }

//

//                console.log(client_dept_bills);
//                $('#client_dept_bills').css('border-collapse','collapse');
//                $('#client_dept_bills').css('border','1px solid black');
//                $('#client_dept_bills th').css('border','1px solid black');
//                $('#client_dept_bills td').css('border','1px solid black');
//                $('.print_div').html(client_dept_bills);
// $('#date_1').remove();
//  $('#date_2').remove();
//
// $('.form_datetime').addClass('hide');
//                $('body .container').addClass('hidden-print');
//                setTimeout(function(){  print_Custom('mycustomheader'); }, 3000);

                    } else {

                        $('.save_payment').prop('disabled', true);
                        if (payment_print == 'yes') {
                            print_Custom('mycustomheader');
                        }
                        // $('.paytype_text').addClass('hide');
                        $('.paytype_text span').html('');
                        $('.paytype_radio').removeClass('hidden-print');
                        //console.log(client_dept_bills);
                        //alert('تم السداد بنجاح .');

                        window.location.href = "clientPayedDeptBillsController.php?do=show";
                    }
                } else {
                    alert(check_paymentnetwork);
                }
            });
        } else {
            alert(' يجب ادخال القيم المراد سدادها فى الفواتير');
        }

    });


    //Initialize the validation object which will be called on form submit.
    var validobj = $("#search_form").validate({
        ignore: [],
        onkeyup: false,
        errorClass: "myErrorClass",
        //put error message behind each form element
        errorPlacement: function (error, element) {
            var elem = $(element);

            error.insertAfter(element);
        },
        //When there is an error normally you just add the class to the element.
        // But in the case of select2s you must add it to a UL to make it visible.
        // The select element, which would otherwise get the class, is hidden from
        // view.
        highlight: function (element, errorClass, validClass) {
            var elem = $(element);
            if (elem.prev().hasClass("select2-container")) {
                $parent = elem.prev();
                $parent.find('a.select2-choice').addClass(errorClass);
            } else {
                elem.addClass(errorClass);
                //$('a.select2-choice').addClass(errorClass);
            }
        },
        //When removing make the same adjustments as when adding
        unhighlight: function (element, errorClass, validClass) {
            var elem = $(element);
            if (elem.prev().hasClass("select2-container")) {
                $parent = elem.prev();
                $parent.find('a.select2-choice').removeClass(errorClass);
            } else {
                elem.removeClass(errorClass);
                //$('a.select2-choice').removeClass(errorClass);
            }
        }
    });

    $('body').on('click', '.print_show', function () {
        $('.show_billno').removeClass('hide');
        print_Custom('mycustomheader');
        setTimeout(function () {
            $('.show_billno').addClass('hide');
        }, 3000);

    });

});


