jQuery(document).ready(function () {
    var id = 0;
    // $('#SenderName').live('change', function () {
    //     if ($('#SenderName option:selected').data('id')) {
    //         var id = $('#SenderName option:selected').data('id');
    //     }
    //     $('#SenderId').val(id);
    // });

    $('body').on('change', '.sender', function () {
        let data = $(this).select2('data');
        // $('#SenderName').append($('<option>', {
        //     value: data.text,
        //     text: data.text
        // }));
        $('#SenderName').val(data.text);
        $('#SenderId').val(data.id);
    });


    $('#cusType').on('click', function () {
        // $.post('policyAjaxController.php?do=getCustomers', function (res) {
        //     $('#SenderName').val('');
        //     $('#SenderName').html(res);
        //     $('#SenderName').val('-1').change();
        // });
        $('#SenderNameDiv').addClass('hidden');
        $('#sDiv').addClass('hidden');
        $('#cDiv').removeClass('hidden');
        clientSelect();
        $('#SenderName').val();
        $('#SenderId').val();
    });

    $('#supType').on('click', function () {

        // $.post('policyAjaxController.php?do=getSuppliers', function (res) {
        //     $('#SenderName').val('');
        //     $('#SenderName').html(res);
        //     $('#SenderName').val('-1').change();
        // });
        $('#SenderNameDiv').addClass('hidden');
        $('#cDiv').addClass('hidden');
        $('#sDiv').removeClass('hidden');
        supplierSelect();
        $('#SenderName').val();
        $('#SenderId').val();
    });

    function clientSelect() {
        $(".select2Client").select2({
            placeholder: "العميل",
            minimumInputLength: document.getElementById("clientsearchvalue").value,
            inimumInputLength: 0,
            multiple: false,
            quietMillis: 100,
            formatInputTooShort: function (input, min) {
                var n = min - input.length;
                $lenMsg = '<ul class="select2-results">';
                // if (supplierWithAddOption == 1)
                // $lenMsg += '<li class="select2-results-dept-0 select2-result select2-result-selectable" onclick="newOptionAtInputTooShort();"><div class="select2-result-label newoption"><span class="newoption">اضافة عميل جديد</span></div></li>';
                $lenMsg += '</ul><div class="select2-result-label"><span>من فضلك أدخل ' + n + ' حروف أكثر</span></div>';
                // Append it to the select
                return $lenMsg;
            },
            ajax: {
                url: "clientControllerAjax.php?do=select2ClientsAjax",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 7, // page size
                        withAddOption: 0,
                        withNakdi: 1,
                        //jsonRowRet: 1,
                    };
                },
                results: function (data) {
                    return { results: data };
                }
            },
            formatResult: function (data) {
                if (Number(data.id) == -2) {
                    return '<span class="newoption">' + data.text + '</span >';
                } else {
                    return '<span>' + data.text + '</span >';
                }
            },
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                var data = { id: item[0], text: item[1], mobile: item[6] };
                callback(data);
            },
            //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
        }).on('select2-loaded', function (e) {// not "select2-open" nor "select2-opening" //http://mkurz.github.io/select2/index.html
            $('.newoption').parent().addClass('newoption');
        }).on("select2-selecting", function (e) {
            // the class to make diffrence of change from select2 itself "choose another option" ,it wont exist for triggering change
            $('#clientid').addClass('selectingClass');
        })
        //this is needed for ajax =>to obtain id from it  and use in ajax
        $('#clientid').select2('data', { id: $('#oldclientid').val(), text: $('#oldclientname').val() });
        setTimeout(function () {
            //this is needed as we need html to end drawing then put value => without it text will be undefined
            $('#clientid').select2('data', { id: $('#oldclientid').val(), text: $('#oldclientname').val() });
        }, 0)
    }

    function supplierSelect() {
        $(".select2Supp").select2({
            placeholder: "المورد",
            minimumInputLength: document.getElementById("clientsearchvalue").value,
            inimumInputLength: 0,
            multiple: false,
            quietMillis: 100,
            formatInputTooShort: function (input, min) {
                var n = min - input.length;
                $lenMsg = '<ul class="select2-results">';
                // if (supplierWithAddOption == 1)
                // $lenMsg += '<li class="select2-results-dept-0 select2-result select2-result-selectable" onclick="newOptionAtInputTooShort();"><div class="select2-result-label newoption"><span class="newoption">اضافة عميل جديد</span></div></li>';
                $lenMsg += '</ul><div class="select2-result-label"><span>من فضلك أدخل ' + n + ' حروف أكثر</span></div>';
                // Append it to the select
                return $lenMsg;
            },
            ajax: {
                url: "supplierAjaxController.php?do=select2supplier",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 7, // page size
                        withAddOption: 0,
                        withNakdi: 1,
                        //jsonRowRet: 1,
                    };
                },
                results: function (data) {
                    return { results: data };
                }
            },
            formatResult: function (data) {
                if (Number(data.id) == -2) {
                    return '<span class="newoption">' + data.text + '</span >';
                } else {
                    return '<span>' + data.text + '</span >';
                }
            },
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                var data = { id: item[0], text: item[1], mobile: item[6] };
                callback(data);
            },
            //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
        }).on('select2-loaded', function (e) {// not "select2-open" nor "select2-opening" //http://mkurz.github.io/select2/index.html
            $('.newoption').parent().addClass('newoption');
        }).on("select2-selecting", function (e) {
            // the class to make diffrence of change from select2 itself "choose another option" ,it wont exist for triggering change
            $('#suppid').addClass('selectingClass');
        })
        //this is needed for ajax =>to obtain id from it  and use in ajax
        $('#suppid').select2('data', { id: $('#oldsuppid').val(), text: $('#oldsuppname').val() });
        setTimeout(function () {
            //this is needed as we need html to end drawing then put value => without it text will be undefined
            $('#suppid').select2('data', { id: $('#oldsuppid').val(), text: $('#oldsuppname').val() });
        }, 0)
    }

    let type = $('input[name="type"]:checked').val();
    if (type == 1) {
        clientSelect();
    }
    if (type == 2)
        supplierSelect();

    $('#submtBtn').on('click', function (e) {
        var type = $('input[name="type"]:checked').val();
        if (type == 1) {
            if ($('#clientid').val() <= 0 && $('#oldclientid').val() <= 0) {
                e.preventDefault();
                alert('اختر الاسم');
            }
        }
        if (type == 2) {
            let oldid = $('#oldsuppid').val();
            if ($('#suppid').val() <= 0 && oldid <= 0) {
                e.preventDefault();
                alert('اختر الاسم');
            }
        }
    });
});


