<select  class="form-control" name="labInvests[]"  id="labInvests"
         multiple="multiple"   size="20" >
    <option value="" disabled
            style="background-color: cadetblue;color: black;text-align: center;">
        Offers
    </option>


    {foreach $invoffers as $offer}
    {if !empty($offer->name)}
    <optgroup label="{$offer->name} {if $offer->price > 0 }  ({$offer->price})  =>  ({$offer->hold})   {else }  ( 0 )    {/if}"  class="txtl" >

        {foreach $offer->offerInvests as $offerInv}
        {if !empty($offerInv.name)}
        <option class="txtl" value="offer_{$offerInv.id}" id="offer_{$offerInv.id}"
                data-price="{$offerInv.price}"  data-id="{$offerInv.id}" data-originalPrice="{$offerInv.originalPrice}"
                data-discount="{$offerInv.discount}" data-hold="{$offerInv.hold}"
                data-external="{$offerInv.external}" data-name="{$offerInv.name}" >
            {$offerInv.name}
            {if $offerInv.price > 0 }  ({$offerInv.price}) =>  ({$offerInv.hold})  {else }  ( 0 )    {/if}
        </option>
        {/if}
        {/foreach}

    </optgroup>
    {/if}
    {/foreach}
    <option value="" disabled
            style="background-color: cadetblue;color: black;text-align: center;">
        Investigations
    </option>

    {foreach $invests as $row}
    {if !empty($row.name)}
    <option class="txtl" value="{$row.id}" id="{$row.id}" data-price="{$row.price}"
            data-discount="{$row.discount}" data-hold="{$row.hold}" data-originalPrice="{$row.originalPrice}"
            data-id="{$row.id}" data-external="{$row.external}"  data-name="{$row.name}" >
        {$row.name}
        {if $row.price > 0 }  ({$row.price}) =>  ({$row.hold})  {else }  ( 0 )    {/if}
    </option>
    {/if}
    {/foreach}
</select>


{literal}
<script>
    if ($("#labInvests").length > 0) {

        $('#labInvests').multiSelect({
            selectableHeader: "<div style='background-color: #4b8df8;;height: 10px;'></div>"
                    + "<input type='search' id='searchIn' class='search-input' style='text-align: center; width: -webkit-fill-available;' autocomplete='off' placeholder=''>",
            selectionHeader: "<div style='background-color: #4b8df8;;height: 10px;'></div>"
                    + "<input type='search' id='searchOut' class='search-input' style='text-align: center; width: -webkit-fill-available;'  autocomplete='off' placeholder=''>",
            selectableFooter: "<div style='background-color: #4b8df8;;height: 10px;'> </div>",
            selectionFooter: "<div style='background-color: #4b8df8;;height: 10px;'> </div>",
            afterInit: function (ms) {
                var that = this,
                        $selectableSearch = that.$selectableUl.prev(),
                        $selectionSearch = that.$selectionUl.prev(),
                        selectableSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selectable:not(.ms-selected)',
                        selectionSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selection.ms-selected';
                that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
                        .on('keydown', function (e) {
                            if (e.which === 40) {
                                that.$selectableUl.focus();
                                return false;
                            }
                        });
                that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
                        .on('keydown', function (e) {
                            if (e.which == 40) {
                                that.$selectionUl.focus();
                                return false;
                            }
                        });
            },
            afterSelect: function (e) {
                //    alert(e);
                this.qs1.cache();
                this.qs2.cache();
                $('#searchIn').focus();
                visitInvestsPrice();
                externalVisitsSelect(e);
                //   vcalc();
            },
            afterDeselect: function (d) {
                this.qs1.cache();
                this.qs2.cache();
                visitInvestsPrice();
                externalVisitsDSelect(d);
                //  vcalc();
            },
            selectableOptgroup: true
        });
        $('#ms-labInvests').css("width", "100%");
    }


    $("#discountType_0").prop("checked", true);
    $('#discountType_0').parent().addClass('checked');
    $("#discountType_1").removeAttr('checked');
    $("#discountType_1").parent().removeClass('checked');
    $(document).ready(function (e) {
        visitInvestsPrice();
    });

    function visitInvestsPrice() {
        var totalPrice = 0;
        var totalOrgDiscount = 0;
        var totalOrgContract = 0;
        var totalOrgHold = 0;
        var totalOriginalPrice = 0;
        var labDetectionPrice = 0;
        if (Number($('#labDetectionPrice').val()) > 0) {
            labDetectionPrice = Number($('#labDetectionPrice').val());
        }

        totalPrice = totalPrice + labDetectionPrice;

        var orgTotalDiscount = 0;
        $("#labInvests option:selected").each(function () {
//                var value = $(this).val();
            var price = Number($(this).attr('data-price'));
            var orgDiscount = Number($(this).attr('data-discount'));
            var orgHold = Number($(this).attr('data-hold'));
            var originalPrice = Number($(this).attr('data-originalPrice'));
            if (price > 0) {
                totalPrice = totalPrice + price;
            }

            if (orgDiscount > 0) {
                orgTotalDiscount = orgTotalDiscount + orgDiscount;
            }

            totalOrgDiscount += orgDiscount;
            totalOrgContract += price;
            totalOrgHold += orgHold;
            totalOriginalPrice += originalPrice;
        });

        $('#contractPrice').val(totalOrgContract);
        $('#discountRatio').val(totalOrgDiscount);
        $('#patient_hold').val(totalOrgHold);
        $('#originalPrice').val(totalOriginalPrice);


        $("#totaldetectionvalue").val(totalPrice);
        //  $('#discount').val(discount);
        var x = vcalc();

        var vatValue = Number($('#vatCalc').val());
        if (vatValue > 0) {
            totalPrice = totalPrice + vatValue;
        }

        var price_in = $('#price_in').val();


        if ($('#editView').val() == 1) {

            var rest = totalPrice - $("#detectionvalue_cash").val() - $("#detectionvalue_visa").val();
            $("#restdetectionvalue").val(rest);
        } else {
            $("#restdetectionvalue").val(0);
            $("#detectionvalue_cash").val(0);
            $("#detectionvalue_visa").val(0);
            $("#" + price_in).val(totalPrice);


        }

        $("#totaldetectionvalue").trigger('change');

    }

    function externalVisitsDSelect(deSelectedArray) {
        $.each(deSelectedArray, function (index, id) {
            if ($('#exLabsTr' + id).length > 0) {
                $('#exLabsTr' + id).remove();
            }
        });
    }

    function externalVisitsSelect(selectedArray) {

        $.post(hosturl + '/controllers/visits.php?ac=get_externals', function (external_labs) {
            $.each(selectedArray, function (index, id) {
                var external = Number($('#' + id).attr('data-external'));
                var name = $('#' + id).attr('data-name');
                if (external > 0) {
                    $('#externalContainer').append(' <tr  id="exLabsTr' + id + '" > '
                            + '<td class="txtl" >   '
                            + name
                            + '  </td> '
                            + ' <td > '
                            + ' <select class="form-control select2 external_labs"   id="exLabs' + id + '"   name="exLabs' + id + '"> '
                            + external_labs
                            + ' </select> '
                            + ' </td> '
                            + ' </tr> ');
                    $("#exLabs" + id).select2({
                        placeholder: "Select",
                        width: '240px',
                        allowClear: true,
                        formatNoMatches: function (term) {
                            /* customize the no matches output */
                            return "<input class='form-control' id='newTerm_" + id + "' value='" + term + "'><a href='#' data-id='" + id + "'  data-text='newTerm_" + id + "'  class='btn blue custombtnstyle addNew_ex'>إضافة جديد</a>"
                        }
                    }).parent().find('.select2-with-searchbox').on('click', '.addNew_ex', function () {
                        /* add the new term */
                        var text_id = $(this).attr('data-text');
                        var id = $(this).attr('data-id');
                        var new_name = $('#' + text_id).val();
                        $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {
                            selectId: 'external_labs', new_name: new_name
                        }, function (data) {
                            //   alert($('#exLabs' + id).html());

                            $('#exLabs' + id + ' > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + new_name + '</option>');
                            $('#exLabs' + id).select2('val', Number(data)); // select the new term
                            $("#exLabs" + id).select2('close'); // close the dropdown

                        });
                    });
                    $("#exLabs" + id).on('change', function () {
                        var select = $(this);
                        var colName = 'name';
                        var delColName = 'deleted';
                        var tableName = 'external_labs';
                        var value = select.val();
                        if (value == '-2') {
                            $.post(hosturl + '/controllers/invsdept.php?ac=editModal', {
                                tableName: tableName, delColName: delColName, selectClass: tableName
                                , colName: colName}, function (data) {
                                select.select2("val", "");
                                $("#editModalDiv").html(data);
                                $("#edit_model").modal('show');
                            });
                        }

                    });
                    $('#externalTable').show();
                    if ($('#editView').val() == 1) {
                        $.each(externalsArray, function (index, entry) {
                            if (entry.id == "exLabs" + id) {
                                $("#exLabs" + id).select2("val", entry.val);
                                //        console.log(entry.val);
                                return false; // Ends the "loop"
                            }
                        });
                    }
                }
            });
//                var externals = $('#externalsss').html();
//                $.each(externals, function (i, e) {
//                    $('#' + e.id).select2("val", e.val);
//                    //            console.log(e.id);
//                });
        });
    }


    function vcalc() {
        var saudi = $('input[name="saudi"]:checked').val();
        var patientid = $("#patientvisitid").val();
        var patientName = $("#wifename").val();

        if ((patientid > 0 || patientName != "") && saudi == 1) {
            var total = Number($('#totaldetectionvalue').val());
            var discount = 0;
            var discountType = $('input[name="discountType"]:checked').val();
            if (discountType == 1) {
                var discountRatio = Number($('#discount').val());
                discount = total * (discountRatio / 100);
            } else {
                discount = Number($('#discount').val());
            }
            total = total - discount;
            var vat = Number($('#vat').val());
            var vatAmount = (total * vat) / 100;
            $('#vatCalc').val(vatAmount);
        } else {
            $('#vatCalc').val(0);
        }

    }
</script>
{/literal}
