<!doctype html>
<?php 

use Jackiedo\DotenvEditor\Facades\DotenvEditor;
$MAIL_HOST = DotenvEditor::load(base_path('.env'))->getValue('MAIL_HOST');
$editor = DotenvEditor::load(storage_path('app/settings.env'));

$cs = 'primary';


?>
<html lang="en" class="h-100">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{$model->descriptor}}@if($model->job_number) {{$model->job_number}}@endif - {{$editor->getKey('APP_TITLE')['value']}}</title>
    <link rel="icon" type="image/vnd.microsoft.icon" href="/images/bürozeit.ico">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@7.4.47/css/materialdesignicons.min.css">
    
    <!-- JQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    
    <!-- Latest compiled and minified CSS -->
    <!--link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.21.1/dist/bootstrap-table.min.css"-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/bootstrap-table.min.css">

    <!-- Latest compiled and minified JavaScript -->
    <!--script src="https://unpkg.com/bootstrap-table@1.21.1/dist/bootstrap-table.min.js"></script-->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/bootstrap-table.min.js"></script>
    <!-- Latest compiled and minified Locales -->
    <!--script src="https://unpkg.com/bootstrap-table@1.21.1/dist/locale/bootstrap-table-de-DE.min.js"></script-->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/locale/bootstrap-table-de-DE.js"></script>
    <!--link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.21.1/dist/extensions/reorder-rows/bootstrap-table-reorder-rows.css"-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/extensions/reorder-rows/bootstrap-table-reorder-rows.css">
    <!--script src="https://cdnjs.cloudflare.com/ajax/libs/TableDnD/1.0.5/jquery.tablednd.js"></script-->
    <script src="https://cdn.jsdelivr.net/gh/isocra/TableDnD@1.0.5/dist/jquery.tablednd.1.0.5.js"></script>
    <!--script src="https://unpkg.com/bootstrap-table@1.21.1/dist/extensions/reorder-rows/bootstrap-table-reorder-rows.js"></script-->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/extensions/reorder-rows/bootstrap-table-reorder-rows.js"></script>

    <!-- Bootstrap -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
    
    <!-- Bootstrap editable -->
    <link rel="stylesheet" href="{{url('/css/xeditable.css')}}">
     <script src="{{url('/js/bootstrap.editable.js')}}"></script>
    <script src="{{url('/js/x-editable.js')}}"></script>
    <script src="{{url('/js/bootstrap-table.editable.js')}}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.0.0/moment.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <!-- Bootstrap Dialogs -->
    <link rel="stylesheet" href="{{url('/css/bootstrap/bootstrap.dialogs.css')}}">
    <script src="{{url('/js/bootstrap.dialogs.js')}}"></script>
    
    <!-- Tabulator -->
    <!--link href="https://unpkg.com/tabulator-tables@5.4.3/dist/css/tabulator.min.css" rel="stylesheet"-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tabulator-tables@5.4.3/dist/css/tabulator.min.css">
    <!--script type="text/javascript" src="https://unpkg.com/tabulator-tables@5.4.3/dist/js/tabulator.min.js"></script-->
    <script src="https://cdn.jsdelivr.net/npm/tabulator-tables@5.4.3/dist/js/tabulator.min.js"></script>
    <!--link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tabulator/5.4.3/css/tabulator_bootstrap5.min.css" integrity="sha512-ReR0xAw/cxBF3WctjOmEo8fwOfnjS2x63iyaIoe/Bn3zjBQM9PYSh/Exbj4vcgnAOiqrGMNUKxaXWJeFJrZZQA==" crossorigin="anonymous" referrerpolicy="no-referrer" /-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tabulator-tables@5.4.3/dist/css/tabulator_bootstrap5.min.css">
    <!--script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.2.1/luxon.min.js" integrity="sha512-pyR2hpC7bLig9Ub4eUIOC/BAO4anpdt7jhpF4dfrPv+qIg+KWztdVjFPCRCsRaWVfUylUCvrrxqMFNrJBdQIjQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script-->
    <script src="https://cdn.jsdelivr.net/npm/luxon@3.2.1/build/global/luxon.min.js"></script>
    
    <script src="https://cdn.jsdelivr.net/npm/jquery.fancytree@2.38.2/dist/jquery.fancytree-all-deps.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/jquery.fancytree@2.38.2/dist/skin-win8/ui.fancytree.min.css" rel="stylesheet">
    
    <!-- JSignatrue -->
    <!--script src="https://cdnjs.cloudflare.com/ajax/libs/jSignature/2.1.3/jSignature.min.js" integrity="sha512-lZ7GJNAmaXw7L4bCR5ZgLFu12zSkuxHZGPJdIoAqP6lG+4eoSvwbmKvkyfauz8QyyzHGUGVHyoq/W+3gFHCLjA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script-->
    <script src="https://cdn.jsdelivr.net/npm/jsignature@2.1.3/libs/jSignature.min.js"></script>
    
    <script src=" https://cdn.jsdelivr.net/npm/numeral@2.0.6/numeral.min.js "></script>
    
    <!-- Datepicker -->
    <link rel="stylesheet" href="{{url('/css/air-datepicker.css')}}">
    <script src="{{url('/js/air-datepicker.js')}}"></script>
    <script src="{{url('/js/air-datepicker-de.js')}}"></script>
    
    <script src="{{url('js/hwplus.js?1')}}"></script>
    <link rel="stylesheet" href="{{url('css/hwplus.css?1')}}">
    
    <style type="text/css">
            
        textarea {
            resize:both;
        }
        
        .textarea {
        
            width:75vw !important;
        
        }

        ul.fancytree-container, span.fancytree-title {
            font-size: inherit;
            font-family:inherit;
        }

        ul.fancytree-container {
            border: none;
        }

        .card-header {
            padding: .375rem .75rem;
        }

    </style>
    
    <script>
    
    let listVat = @json(\Runtime::make('hwplus_vat_rates')->get()->keyBy('ID'));

    let fareRate = '{{$model->fare_rate}}';
        fareRate = fareRate ? fareRate : "0,00";

    var editAble = function(cell){
        return {{$model->job_number ? "false" : "true"}}
    }
    
    var netCalc = function(values, data, calcParams) {
        //values - array of column values
        //data - all table data
        //calcParams - params passed from the column definition object

        var calc = 0;

        values.forEach(function(value){
            value = parseFloat(value.replace(',','.'));
            calc = calc + value;
        });

        return calc.toFixed(2) + '€';
    }
    
    var sumCalc = function(values, data, calcParams) {
        //values - array of column values
        //data - all table data
        //calcParams - params passed from the column definition object

        var calc = 0;

        values.forEach(function(value){
            value = parseFloat(value);
            calc = calc + value;
        });

        return calc.toFixed(2) + '€';
    }
    

    $(function() {
    
        setInterval(function() {


            // Zwischensumme 1

            let sum1 = 0;
            let b_sum1 = 0;

            let manhours = 0;
            let fare = 0;
            let services = 0;
            let fareCharges = 0;

            let b_manhours = 0;
            let b_fare = 0;
            let b_services = 0;
            let b_fareCharges = 0;

            if($('#manhourTable div.tabulator-footer [tabulator-field="sum"]').length ) {
                manhours = $('#manhourTable div.tabulator-footer [tabulator-field="sum"]').html();
                manhours = parseFloat(manhours.slice(0, -1));
                b_manhours = $('#manhourTable div.tabulator-footer [tabulator-field="brutto"]').html();
                b_manhours = parseFloat(b_manhours.slice(0, -1));

            }

            if($('#fareTable div.tabulator-footer [tabulator-field="sum"]').length ) {
                fare = $('#fareTable div.tabulator-footer [tabulator-field="sum"]').html();
                fare = parseFloat(fare.slice(0, -1));
                b_fare = $('#fareTable div.tabulator-footer [tabulator-field="brutto"]').html();
                b_fare = parseFloat(b_fare.slice(0, -1));
            }

            if($('#serviceTable div.tabulator-footer [tabulator-field="sum"]').length ) {
                services = $('#serviceTable div.tabulator-footer [tabulator-field="sum"]').html();
                services = parseFloat(services.slice(0, -1));
                b_services = $('#serviceTable div.tabulator-footer [tabulator-field="brutto"]').html();
                b_services = parseFloat(b_services.slice(0, -1));
            }

            if($('#fareChargeTable div.tabulator-footer [tabulator-field="sum"]').length ) {
                fareCharges = $('#fareChargeTable div.tabulator-footer [tabulator-field="sum"]').html();
                fareCharges = parseFloat(fareCharges.slice(0, -1));
                b_fareCharges = $('#fareChargeTable div.tabulator-footer [tabulator-field="brutto"]').html();
                b_fareCharges = parseFloat(b_fareCharges.slice(0, -1));
            }

            sum1 = manhours + fare + services + fareCharges;
            b_sum1 = b_manhours + b_fare + b_services + b_fareCharges;

            $('.sum1').html('Zwischensumme netto: ' + sum1.toFixed(2) + '€');
            $('.sum1').data('sum1', sum1);
            $('.sum1').data('b_sum1', b_sum1);

            // Zwischensumme 2

            let sum2 = sum1;
            let b_sum2 = b_sum1;
            let selection = {};
            let row = {};

            if(typeof premiumChargeTable !== 'undefined' && premiumChargeTable.getSelectedData().length) {

                selection = premiumChargeTable.getSelectedData()[0];
                row = premiumChargeTable.getSelectedRows()[0];

                if(selection.unit == "%") {

                    let im = sum2 / 100 * parseFloat(selection.value);
                    row.update({sum:sum2})
                    sum2 = sum2 + im;
                    b_sum2 = b_sum2 + parseFloat(selection.brutto);
                }
                else {
                    row.update({sum:parseFloat(selection.value)});
                    sum2 = sum2 + parseFloat(selection.value);
                    b_sum2 = b_sum2 + parseFloat(selection.brutto);
                }

            }

            $('.sum2').html('Zwischensumme netto: ' + sum2.toFixed(2) + '€');
            $('.sum2').data('sum2', sum2);
            $('.sum2').data('b_sum2', sum2);

            // Gesamtsumme inkl. Material
            
            let material = $('#materialTable div.tabulator-footer [tabulator-field="sum"]').html();
            let b_material = $('#materialTable div.tabulator-footer [tabulator-field="brutto"]').html();

            material = parseFloat(material.slice(0, -1));
            b_material = parseFloat(b_material.slice(0, -1));

            let netto = sum2 + material;
            let brutto = b_sum2 + b_material;

            $('.netto').html('Gesamt netto: ' + netto.toFixed(2) + '€');
            $('.brutto').html('Gesamt brutto: ' + (brutto.toFixed(2)) + '€');
            
            }, 500);
               

        @if('material_offer' == $model->_meta->_doctype->identifier)

        fareTable = new Tabulator("#fareTable", {
            movableRows:true,
            layout:"fitColumns",
            selectable: false,
            rowHeight:100,
            data: [{descriptor:'Lieferpauschale', fare_rate:"{{$model->fare_rate}}", fare:"{{$model->fare}}", fare_rate_vat:"{{$model->fare_rate_vat}}"}],
            initialSort:[{column:'date', dir:'asc'}],
            columns:[
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {__formatter:"rowSelection", headerSort:false, width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"input", editable:false},
                {title:'Menge', field:'fare', visible:true, editor:'input', editable:editAble, width:120, mutateLink:"sum", editorParams:{
                    selectContents:true,
                } },
                {title:'Einzel-<br>preis', field:'fare_rate', visible:true, width:100, editor:'input', editable:editAble,
                    formatter: function(cell) { return cell.getValue() + '€'},
                    mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }},
                {title:'MwSt.', field:'fare_rate_vat', visible:true, width:90, editor:'list', editable:editAble, formatter: function(cell) { return cell.getValue() + '%'}, mutateLink:"brutto", editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },
                {title:'Gesamt', field:'sum', visible:true, width:120, bottomCalc:sumCalc, mutateLink:"brutto",
                    mutator: function(value, row) {
                        let sum = parseFloat(row.fare_rate.replace(',','.')) * parseFloat(row.fare.replace(',','.'));
                        return sum.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'; }
                },
                {title:'Brutto', field:'brutto', visible:false, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto = parseFloat(row.sum) + parseFloat(row.fare_rate_vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},
            ],
        });

        fareTable.on("cellEdited", function(cell){


            if('fare' != cell.getField() && 'fare_rate' != cell.getField() && 'fare_rate_vat' != cell.getField()) return;

            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }


            postData.data[cell.getField()] = cell.getValue();

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)

                .done(function() {

                    $('#spinner').addClass('d-none');

                })

                .fail(function(xhr, status, error) {

                    $('#spinner').addClass('d-none');
                    cell.restoreOldValue();

                    alertException(xhr);



                });
            });




        @elseif(\Runtime::make('hwplus_manhours_units')->count())

        let manhourTableData = @json(\App\Models\PHPXPress\HwplusManhours::where('_manhours_at_tickets', $model->getKey())->orderBy('date')->get())

        manhourTable = new Tabulator("#manhourTable", {
            movableRows:true,
            layout:"fitColumns",
            selectable: 1,
            //ajaxURL:"http://www.getmydata.com/now", //ajax URL
            data:manhourTableData,
            rowHeight:100,
            initialSort:[{column:'date', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"input", editable:editAble},
                {title:'Stunden', field:'workinghours', visible:true, editor:'input', editable:editAble, width:120, mutateLink:"sum", formatter:function(cell, formatterParams, onRendered) {
                    return formatAmount(cell.getValue());

                },editorParams:{
                    elementAttributes:{
                        oninput:"validateAmount(event, this)",
                    }
                } },
                {title:'Mitarbeiter', field:'_staff', visible:true, editor:'input', editable:false, width:120, editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusStaff::get() AS $row) {value:'{{$row->getKey()}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusStaff::get() AS $row) '{{$row->getKey()}}':'{{$row->descriptor}}',@endforeach
                    }

                },
                {title:"Fahrt-<br>kosten", field:'fare', visible:true, editor:'list', editable:editAble, width:100, mutateLink: "sum",
                    cellEdited:function() {

                        let fares = 0;
                        var rows = manhourTable.getRows().forEach((row)=>{ row.getData().fare == 1 ? fares++ : "" });

                        var rows = fareTable.getRows();

                        rows.forEach((row)=>{
                            row.update({amount:fares + ""});
                        });

                    },
                    editorParams: {
                        values:[{value:1, label:"Ja"},{value:0, label:"Nein"}],
                        clearable:true,
                    },
                    formatter:'lookup',
                    formatterParams:{
                        1:'Ja',0:'Nein'
                    }
                
                },
                {title:'Einzel-<br>preis', field:'netprice', visible:true, width:100, editor:'input', editable:editAble, formatter:function(cell, formatterParams, onRendered) {
                    return formatPrice(cell.getValue());

                },editorParams:{
                    elementAttributes:{
                        oninput:"validatePrice(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }},
                {title:'MwSt.', field:'vat', visible:true, width:90, editor:'list', editable:editAble, formatter: function(cell) { return cell.getValue() + '%'}, mutateLink:"brutto", editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },
                {title:'Gesamt', field:'sum', visible:true, width:120, bottomCalc:sumCalc, mutateLink:"brutto",
                    mutator: function(value, row) {
                        let sum = parseFloat(row.netprice.replace(',','.')) * parseFloat(row.workinghours.replace(',','.'));
                        return sum.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'; }
                },
                {title:'Brutto', field:'brutto', visible:false, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto = parseFloat(row.sum) + parseFloat(row.vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},
            ],
        });
        
        manhourTable.on("rowSelected", function(row){
            $('.manhour_menu_button').prop("disabled",false);
        });
        
        manhourTable.on("rowDeselected", function(row){
            $('.manhour_menu_button').prop("disabled",true);
        });
            
        manhourTable.on("cellEdited", function(cell) {
                        
            $('#spinner').removeClass('d-none');
            
            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            

            let row = cell.getRow().getData();
        
            postData.data[cell.getField()] = cell.getValue();
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/672de507342c544245caa62bd33fb2978778b3a4/" + row.ID, postData)
                
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr, status, error) {
                        
                    $('#spinner').addClass('d-none');
                    cell.restoreOldValue();
                                
                    alertException(xhr);
                    
                    
        
                });
        });
            
        manhourTable.on("dataChanged", function() {

            let fares = 0;
            var rows = manhourTable.getRows().forEach((row)=>{ row.getData().fare == 1 ? fares++ : "" });

            var rows = fareTable.getRows();

            rows.forEach((row)=>{
                row.update({amount:fares + ""});
            });

        })
            
        $('.add_manhour').click(function() {
        
            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../create/672de507342c544245caa62bd33fb2978778b3a4/bdf23694c97afce98ac9fbe9788ad82b8bf5719f?data[_manhours_at_tickets]={{$model->getKey()}}&offer=1'),
                title:'Leistung erfassen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Speichern',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        let postData = $('#new_manhour').serialize();
                        
                        $.post("../../../api/{{$repository->getConfig()->_service->url}}/672de507342c544245caa62bd33fb2978778b3a4/bdf23694c97afce98ac9fbe9788ad82b8bf5719f", postData)
                            
                            .done(function(data) { 

                                $('#spinner').addClass('d-none');
                                manhourTable.addData(data);
                                dialogItself.close(); 
                                
                            })
                            
                            .fail(function(xhr) {
                            
                                $('#spinner').addClass('d-none');
                            
                            
                                if(422 == xhr.status) {
                                
                                    $('#new_manhour').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_manhour').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                    });
                                
                                    return;
                                
                                }
                            
                                alertException(xhr); 
                            
                            });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        
        });
        
        
        
        $('.drop_manhour_button').click(function() {
        
                      
            dialog = BootstrapDialog.confirm('Sollen die aktuell gewählten Arbeitsstunden wirklich gelöscht werden?', function(result){
                if(result) {
                
                    $('#spinner').removeClass('d-none');
                    
                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }
                    
                    let selectedRowID = manhourTable.getSelectedData()[0].ID;
                                            
                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/672de507342c544245caa62bd33fb2978778b3a4/" + selectedRowID, postData)
                    
                        .done(function() {
                                                
                            $('#spinner').addClass('d-none');
                            
                            manhourTable.getSelectedRows()[0].delete();
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            alertException(xhr);
                        });
                    
                    $('.manhour_menu_button').prop('disabled', true);
                }
            });
        
        
        })

        fareTable = new Tabulator("#fareTable", {
            movableRows:true,
            layout:"fitColumns",
            selectable: false,
            rowHeight:100,
            data: [{descriptor:'Fahrtkostenpauschale', fare_rate:fareRate, amount:"0", fare_rate_vat:"{{$model->fare_rate_vat}}"}],
            initialSort:[{column:'date', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {__formatter:"rowSelection", headerSort:false, width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"input", editable:false},
                {title:'Menge', field:'amount', visible:true, editor:'input', editable:false, width:120, mutateLink:"sum", formatter:function(cell, formatterParams, onRendered) {
                    return formatAmount(cell.getValue());

                },editorParams:{
                    elementAttributes:{
                        oninput:"validateAmount(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'Einzel-<br>preis', field:'fare_rate', visible:true, width:100, editor:'input', editable:editAble, formatter:function(cell, formatterParams, onRendered) {
                    return formatPrice(cell.getValue());

                }, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                    elementAttributes:{
                        oninput:"validatePrice(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'MwSt.', field:'fare_rate_vat', visible:true, width:90, editor:'list', editable:editAble, formatter: function(cell) { return cell.getValue() + '%'}, mutateLink:"brutto", editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },
                {title:'Gesamt', field:'sum', visible:true, width:120, bottomCalc:sumCalc, mutateLink:"brutto",
                    mutator: function(value, row) {
                        let sum = parseFloat(row.fare_rate.replace(',','.')) * parseFloat(row.amount.replace(',','.'));
                        return sum.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'; }
                },
                {title:'Brutto', field:'brutto', visible:false, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto = parseFloat(row.sum) + parseFloat(row.fare_rate_vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);
                    }, formatter: function(cell) { return cell.getValue() + '€'}},
            ],
        });

        fareTable.on("cellEdited", function(cell){


            if('fare_rate' != cell.getField() && 'fare_rate_vat' != cell.getField()) return;

            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }


            postData.data[cell.getField()] = cell.getValue();

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)

                .done(function() {

                    $('#spinner').addClass('d-none');

                })

                .fail(function(xhr, status, error) {

                    $('#spinner').addClass('d-none');
                    cell.restoreOldValue();

                    alertException(xhr);



                });
            });


        fareTable.on("tableBuilt", function() {

            let fares = 0;
            var rows = manhourTable.getRows().forEach((row)=>{ row.getData().fare == 1 ? fares++ : "" });

            var rows = fareTable.getRows();

            rows.forEach((row)=>{
                row.update({amount:fares + ""}); //update the name of each row to steve;
            });

        })




        @endif

        @if('material_offer' == $model->_meta->_doctype->identifier)
        @elseif(\Runtime::make('hwplus_services_master')->count())

        let serviceTableData = @json(\App\Models\PHPXPress\HwplusServices::where('_services_at_hwplus_tickets', $model->getKey())->get())

        serviceTable = new Tabulator("#serviceTable", {
            movableRows:true,
            layout:"fitColumns",
            selectable: 1,
            //ajaxURL:"http://www.getmydata.com/now", //ajax URL
            data:serviceTableData,
            rowHeight:100,
            initialSort:[{column:'date', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"input", editable:editAble},
                {title:'Einheit', field:'_unit', visible:true, editor:'list', editable:editAble, width:100,
                    editorParams: {
                        values:[@foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) {value:'{{$row->getKey()}}', label:"{{$row->descriptor}}"},@endforeach],
                        clearable:true,
                    },
                    formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) '{{$row->getKey()}}':'{{$row->descriptor}}',@endforeach
                    }

                },
                {title:'Menge', field:'amount', visible:true, editor:'input', width:100, editable:editAble, mutateLink:"sum"},
                {title:'Einzel-<br>preis', field:'netprice', visible:true, width:100, editor:'input', editable:editAble, formatter: function(cell) { return cell.getValue() + '€'}, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }},
                {title:'MwSt.', field:'vat', visible:true, width:90, editor:'list', editable:editAble, formatter: function(cell) { return cell.getValue() + '%'}, mutateLink:"brutto", editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },
                {title:'Gesamt', field:'sum', visible:true, width:120, bottomCalc:sumCalc, mutateLink:"brutto",
                    mutator: function(value, row) {
                        let sum = parseFloat(row.netprice.replace(',','.')) * parseFloat(row.amount.replace(',','.'));
                        return sum.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}

                },
                {title:'Brutto', field:'brutto', visible:true, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto = parseFloat(row.sum) + parseFloat(row.vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},
            ],
        });

        serviceTable.on("rowSelected", function(row){
            $('.service_menu_button').prop("disabled",false);
        });

        serviceTable.on("rowDeselected", function(row){
            $('.service_menu_button').prop("disabled",true);
        });

        serviceTable.on("cellEdited", function(cell){

            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }


            let row = cell.getRow().getData();

            postData.data[cell.getField()] = cell.getValue();

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/d9f7caca5cd46e1ca131a2b9535670012239ac96/" + row.ID, postData)

                .done(function() {

                    $('#spinner').addClass('d-none');

                })

                .fail(function(xhr, status, error) {

                    $('#spinner').addClass('d-none');
                    cell.restoreOldValue();

                    alertException(xhr);



                });
        });


        $('.add_service').click(function() {

            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../1866d911c19cfc6a7edd7933a9ac1b71f160c171/d88b5f160ec4cb110473cda17917466cd2b9d352?data[_services_at_hwplus_tickets]={{$model->getKey()}}'),
                title:'Dienstleistung erfassen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [ {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });


        });

        $('.drop_service_button').click(function() {


            dialog = BootstrapDialog.confirm('Soll die aktuell selektierte Dienstleistung wirklich gelöscht werden?', function(result){
                if(result) {

                    $('#spinner').removeClass('d-none');

                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }

                    let selectedRowID = serviceTable.getSelectedData()[0].ID;

                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/d9f7caca5cd46e1ca131a2b9535670012239ac96/" + selectedRowID, postData)

                        .done(function() {

                            $('#spinner').addClass('d-none');

                            serviceTable.getSelectedRows()[0].delete();

                        })

                        .fail(function(xhr) {

                            $('#spinner').addClass('d-none');

                            alertException(xhr);
                        });

                    $('.service_menu_button').prop('disabled', true);
                }
            });


        })

        @endif


        @if('material_offer' == $model->_meta->_doctype->identifier)
        @elseif(\Runtime::make('hwplus_fare_charges_master')->count())

        let fareChargeTableData = @json(\App\Models\PHPXPress\HwplusFareCharges::where('_fare_charges_at_hwplus_tickets', $model->getKey())->get())

        fareChargeTable = new Tabulator("#fareChargeTable", {
            movableRows:true,
            layout:"fitColumns",
            selectable: 1,
            data:fareChargeTableData,
            rowHeight:100,
            initialSort:[{column:'date', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"input", editable:editAble},
                {title:'Einheit', field:'_unit', visible:true, editor:'list', editable:editAble, width:100,
                    editorParams: {
                        values:[@foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) {value:'{{$row->getKey()}}', label:"{{$row->descriptor}}"},@endforeach],
                        clearable:true,
                    },
                    formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) '{{$row->getKey()}}':'{{$row->descriptor}}',@endforeach
                    }

                },
                {title:'Menge', field:'amount', visible:true, editor:'input', width:100, editable:editAble, mutateLink:"sum"},
                {title:'Einzel-<br>preis', field:'netprice', visible:true, width:100, editor:'input', editable:editAble, formatter: function(cell) { return cell.getValue() + '€'}, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }},
                {title:'MwSt.', field:'vat', visible:true, width:90, editor:'list', editable:editAble, formatter: function(cell) { return cell.getValue() + '%'}, mutateLink:"brutto", editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },
                {title:'Gesamt', field:'sum', visible:true, width:120, bottomCalc:sumCalc, mutateLink:'brutto',
                    mutator: function(value, row) {
                        let sum = parseFloat(row.netprice.replace(',','.')) * parseFloat(row.amount.replace(',','.'));
                        return sum.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},
                {title:'Brutto', field:'brutto', visible:true, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto = parseFloat(row.sum) + parseFloat(row.vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},
            ],
        });

        fareChargeTable.on("rowSelected", function(row){
            $('.fare_charge_menu_button').prop("disabled",false);
        });

        fareChargeTable.on("rowDeselected", function(row){
            $('.fare_charge_menu_button').prop("disabled",true);
        });

        fareChargeTable.on("cellEdited", function(cell){

            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }


            let row = cell.getRow().getData();

            postData.data[cell.getField()] = cell.getValue();

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/eac7536bc4b7bedde668cb12fcb160d655037a03/" + row.ID, postData)

                .done(function() {

                    $('#spinner').addClass('d-none');

                })

                .fail(function(xhr, status, error) {

                    $('#spinner').addClass('d-none');
                    cell.restoreOldValue();

                    alertException(xhr);



                });
        });


        $('#add_fare_charge').click(function() {

            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../70fbe0cc6e52b3bfeda1e392c5f03b09d7634e10/baab2d50701592cb784913b0e3d4deb7e9d57ab7?data[_fare_charges_at_hwplus_tickets]={{$model->getKey()}}'),
                title:'Dienstleistung erfassen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });


        });

        $('.drop_fare_charge_button').click(function() {


            dialog = BootstrapDialog.confirm('Soll die aktuell gewählten Fahrtkosten wirklich gelöscht werden?', function(result){
                if(result) {

                    $('#spinner').removeClass('d-none');

                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }

                    let selectedRowID = fareChargeTable.getSelectedData()[0].ID;

                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/eac7536bc4b7bedde668cb12fcb160d655037a03/" + selectedRowID, postData)

                        .done(function() {

                            $('#spinner').addClass('d-none');

                            fareChargeTable.getSelectedRows()[0].delete();

                        })

                        .fail(function(xhr) {

                            $('#spinner').addClass('d-none');

                            alertException(xhr);
                        });

                    $('.service_menu_button').prop('disabled', true);
                }
            });


        })

        @endif

        @if('material_offer' == $model->_meta->_doctype->identifier)
        @elseif(\Runtime::make('hwplus_premium_charges')->count())

        let premiumChargeTableData = @json(\App\Models\PHPXPress\HwplusPremiumCharges::get());

        premiumChargeTable = new Tabulator("#premiumChargeTable", {
            movableRows:editAble(),
            layout:"fitColumns",
            selectable: editAble() ? 1 : 0 ,
            selectableRows:1,
            rowHeight:100,
            data:premiumChargeTableData,
            index: "ID",
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:60 },
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"textarea", editable:editAble, formatter:"textarea", editorParams:             {
                    selectContents:true,
                }},
                {title:'Wert', field:'value', visible:true, editor:'input', width:100, editable:false, editorParams:             {
                    selectContents:true,
                }},
                {title:'Einheit', field:'unit', visible:true, width:100, editable:false, editorParams:             {
                    selectContents:true,
                }},
                 {title:'MwSt.', field:'_vat', visible:true, width:90, editor:'list', editable:false, formatter: function(cell) { return cell.getValue() + '%'}, mutateLink:"brutto", editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->getKey()}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->getKey()}}':'{{$row->descriptor}}',@endforeach
                    }


                },
                {title:'Gesamt', field:'sum', visible:true, width:120, mutateLink:"brutto",
                    formatter: function(cell) { return cell.getValue() > 0 ? cell.getValue().toFixed(2) + '€' : ''; }
                },
                {title:'Brutto', field:'brutto', visible:true, width:120,
                    mutator: function(cell, row) {

                        let brutto = row.sum + row.sum / 100 * listVat[row._vat].rate;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() > 0 ? cell.getValue() + '€' : ''; }},
            ],
        });


        @if($model->_premium_charge)

            premiumChargeTable.on("dataProcessed", function() {
                premiumChargeTable.selectRow('{{$model->_premium_charge->getKey()}}');
            });

        @endif

        premiumChargeTable.on("rowSelected", function(row){

            let selectedRow = premiumChargeTable.getSelectedRows()[0];
            let rowData = selectedRow.getData();

            let postData = {};
                postData._token = '{{csrf_token()}}';
                postData._method = "PUT";
                postData.data = {};
                postData.data._premium_charge = rowData.ID;

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)

                        .done(function() {

                            $('#spinner').addClass('d-none');


                        })

                        .fail(function(xhr) {

                            $('#spinner').addClass('d-none');
                            premiumChargeTable.deselectRow();

                            alertException(xhr);
                        });



        });

        premiumChargeTable.on("rowDeselected", function(row) {

            let selectedRow = premiumChargeTable.getSelectedRows()[0];
            let rowData = row.getData();


            let postData = {};
                postData._token = '{{csrf_token()}}';
                postData._method = "PUT";
                postData.data = {};
                postData.data._premium_charge = rowData.ID;

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)

                        .done(function() {

                            $('#spinner').addClass('d-none');
                            row.update({sum:0, brutto:0});

                        })

                        .fail(function(xhr) {

                            $('#spinner').addClass('d-none');
                            premiumChargeTable.selectRow();

                            alertException(xhr);
                        });

        });
        
        @endif
       
        let materialTableData = @json(\App\Models\PHPXPress\HwplusMaterial::where('_material_at_tickets', $model->getKey())->orderBy('_material_at_tickets_order')->get())

        materialTable = new Tabulator("#materialTable", {
            movableRows:editAble,
            //rowHeader:{headerSort:false, resizable: false, minWidth:30, width:30, rowHandle:true, formatter:"handle"},
            layout:"fitColumns",
            rowHeight:100,
            data:materialTableData,            
            initialSort:[{column:'_material_at_tickets_order', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:10},
                {rowHandle:true, formatter:"handle", headerSort:false, width:10, vertAlign:'top'},
                {title:"", field:'_material_at_tickets_order', visible:true, sorter:'number', width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"textarea", formatter:"textarea", editable:editAble, editorParams:             {
                    selectContents:true,
                }},
                {title:'VPE', field:'unit', visible:true, editor:'list', editable:editAble, width:100,
                    editorParams: {
                        values:[@foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) {value:'{{$row->xunitcode}}', label:"{{$row->descriptor}}"},@endforeach],
                        clearable:true,
                    },
                    formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) '{{$row->xunitcode}}':'{{$row->descriptor}}',@endforeach
                    }
                
                },
                {title:'Menge', field:'amount', visible:true, editor:'input', width:100, editable:editAble, mutateLink:"sum", formatter:function(cell, formatterParams, onRendered) {
                    return formatAmount(cell.getValue());

                },editorParams:{
                    elementAttributes:{
                        oninput:"validateAmount(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'Einzel-<br>preis', field:'netprice', visible:true, width:100, editor:'input', editable:editAble, mutateLink:"sum", formatter:function(cell, formatterParams, onRendered) {
                    return formatPrice(cell.getValue());

                }, editorParams:             {
                    selectContents:true,
                    elementAttributes:{
                        oninput:"validatePrice(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'MwSt.', field:'vat', visible:true, width:90, editor:'list', editable:editAble, formatter: function(cell) { return cell.getValue() + '%'}, mutateLink:'sum', editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },
                {title:'Gesamt', field:'sum', visible:true, width:120, bottomCalc:sumCalc, mutateLink:'brutto',
                    mutator: function(value, row) {
                        let sum = parseFloat(row.netprice.replace(',','.')) * parseFloat(row.amount.replace(',','.'));
                        return sum.toFixed(2);

                    }, formatter:function(cell, formatterParams, onRendered) {
                    return formatPrice(cell.getValue());

                }, editorParams:             {
                    selectContents:true,
                    elementAttributes:{
                        oninput:"validatePrice(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},,
                {title:'Brutto', field:'brutto', visible:false, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto = parseFloat(row.sum) + parseFloat(row.vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);

                    },
                    formatter: function(cell) { return cell.getValue() + '€'; }
                },
            ],
        });
    
    
        materialTable.on("rowSelected", function(row){
            $('.material_menu_button').prop("disabled",false);
        });
        
        materialTable.on("rowDeselected", function(row){
            $('.material_menu_button').prop("disabled",true);
        });
        
        materialTable.on("rowMoved", function(row) {
        
                $('#spinner').removeClass('d-none');
        
                let postData = {
                    _token:'{{csrf_token()}}',
                    _method: 'PUT',
                    data: {}
                }
                
                postData.data['_material_at_tickets_order'] = row.getPosition();        
                
                $.post("../../../api/{{$repository->getConfig()->_service->url}}/c5b93c44c6aa831b9f9b39580a9efeed7470c8bc/" + row.getData().ID, postData)
                    
                    .done(function(data) {
                                
                        materialTable.setData("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}/_material");

                        $('#spinner').addClass('d-none');
                        
                    })
                    
                    .fail(function(xhr) {
                    
                        $('#spinner').addClass('d-none');
                    
                        alertException(xhr);      
                    });
            
        
        });
    
    
        materialTable.on("cellEdited", function(cell){
                        
                $('#spinner').removeClass('d-none');
                
                let postData = {
                    _token:'{{csrf_token()}}',
                    _method: 'PUT',
                    data: {}
                }
                
    
                let row = cell.getRow().getData();
            
                postData.data[cell.getField()] = cell.getValue();
                
                $.post("../../../api/{{$repository->getConfig()->_service->url}}/c5b93c44c6aa831b9f9b39580a9efeed7470c8bc/" + row.ID, postData)
                    
                    .done(function() {
                    
                        $('#spinner').addClass('d-none');
                    
                    })
                    
                    .fail(function(xhr, status, error) {
                            
                        $('#spinner').addClass('d-none');
                        cell.restoreOldValue();
                                    
                        alertException(xhr);
                        
                        
            
                    });
        });
        
        $('.add_material').on('click', function() {
    
            BootstrapDialog.show({
                message: $('<div></div>').load('../../create/c5b93c44c6aa831b9f9b39580a9efeed7470c8bc/f7978012a68047ec09fcafe66f8e7fff51be91fa?data[_material_at_tickets]={{$model->getKey()}}&offer=1'),
                title:'Material erfassen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Speichern',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        let postData = $('#new_material').serialize();
                                        
                        $.post("../../../api/{{$repository->getConfig()->_service->url}}/c5b93c44c6aa831b9f9b39580a9efeed7470c8bc/f7978012a68047ec09fcafe66f8e7fff51be91fa", postData)
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            materialTable.addData(data);
                            dialogItself.close(); 
                        
                        })
                            
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            if(422 == xhr.status) {
                                
                                    $('#new_material').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_material').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                    });
                                
                                    return;
                                
                            }
                        
                            alertException(xhr);
                        
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
    
        });

        window.add_material_from_master = function(postData) {

            postData.data._material_at_tickets = postData.data.object;

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/c5b93c44c6aa831b9f9b39580a9efeed7470c8bc/f7978012a68047ec09fcafe66f8e7fff51be91fa", postData)
                        .done(function(data) {

                        $('#spinner').addClass('d-none');
                            materialTable.addData(data);
                            $('#liveToast').toast('show');

                        })

                        .fail(function(xhr) {

                            $('#spinner').addClass('d-none');

                            alertException(xhr);


                        });

        }
        
        $(document).on('click', 'btn.copy_material_show_ticket', function() {
        
            dialog.close();
            
            let ids = $.map($('#subtable').bootstrapTable('getSelections'), function (row) {
                return row.ID
            })
        
            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../85694dee442cf8c09c5787974e68950420024783/afe4f16263308b092d15e04719f202efe1326813/' + ids[0], function() {
                    $('.btn.btn-block').removeClass('btn-block');
                }),
                size:BootstrapDialog.SIZE_WIDE,
                type:BootstrapDialog.TYPE_LIGHT,
                title:"Postenauswahl",
                buttons: [{
                    label: 'Übernehmen',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                        
                        
                         let postData = {
                            _token:'{{csrf_token()}}',
                            data: {}
                        }
                        
                        let ids = $.map($('#subtable').bootstrapTable('getSelections'), function (row) {
                            return row.ID
                        })
                        
                        
                        if(!ids[0]) {
                            BootstrapDialog.alert('Keine Auswahl getroffen');
                            $('#spinner').addClass('d-none');
                            return;
                        }
                        
                        postData.data['copyItems'] = ids;
                             
                        $.post("../../copyMaterial/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                        
                        .done(function(data) { 
                            $('#spinner').addClass('d-none');
                            dialogItself.close(); 
                            window.location.reload(); 
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                            
                            alertException(xhr);
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        });
        
        $('#make_ticket_copy').click(function() {
               
            let postData = {
                _token:'{{csrf_token()}}',
                data: {}
            }
            
            $('#spinner').removeClass('d-none');
                                      
                             
            $.post("../../copyTicket/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function(data) { 
                    $('#spinner').addClass('d-none');
                    BootstrapDialog.confirm({
                        title: 'Vorgang erfolgreich',
                        message: 'Das Ticket wurde erfolgreich kopiert. Sie finden die Kopie unter "Offene Aufträge und Lieferscheine',
                        closable: true, // <-- Default value is false
                        draggable: true, // <-- Default value is false
                        btnCancelLabel: 'Schließen', // <-- Default value is 'Cancel',
                        btnOKLabel: 'Kopie öffnen', // <-- Default value is 'OK',
                        btnOKClass: 'btn-success', // <-- If you didn't specify it, dialog type will be used,
                        callback: function(result) {
                            // result will be true if button was click, while it will be false if users close the dialog directly.
                            if(result) {
                                //window.location = "./" + data.ID;
                            }
                        }
                    });
                })
                
                .fail(function(xhr, status, error) {
                
                    $('#spinner').addClass('d-none');
                    
                    alertException(xhr);
                
                })
        
        })
        
        $('.copy_material_from_open_button').click(function() {
               
            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../eb705ce470640e244888405f1fa821eda8518981/afe4f16263308b092d15e04719f202efe1326813?filter[printed]=0', function(el) { $('.btn.btn-block').removeClass('btn-block'); }),
                size:BootstrapDialog.SIZE_WIDE,
                type:BootstrapDialog.TYPE_LIGHT,
                title:"Auswahl",
                buttons: [{
                    label: 'Übernehmen',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                        
                        let ids = $.map($('#subtable').bootstrapTable('getSelections'), function (row) {
                            return row.ID
                        })
                        
                         let postData = {
                            _token:'{{csrf_token()}}',
                            data: {}
                        }
                        
                        if(!ids[0]) {
                            BootstrapDialog.alert('Keine Auswahl getroffen');
                            $('#spinner').addClass('d-none');
                            return;
                        }
                        
                        postData.data['copyFrom'] = ids[0];
                        
                             
                        $.post("../../copyMaterial/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                        
                        .done(function(data) { 
                            $('#spinner').addClass('d-none');
                            dialogItself.close(); 
                            window.location.reload(); 
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                            
                            alertException(xhr);
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        });
        
        
        
        $('.copy_material_from_closed_button').click(function() {
               
            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../eb705ce470640e244888405f1fa821eda8518981/afe4f16263308b092d15e04719f202efe1326813?filter[printed]=1'),
                size:BootstrapDialog.SIZE_WIDE,
                title:"Auswahl",
                buttons: [{
                    label: 'Übernehmen',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                        
                        
                         let postData = {
                            _token:'{{csrf_token()}}',
                            data: {}
                        }
                        
                        let ids = $.map($('#subtable').bootstrapTable('getSelections'), function (row) {
                            return row.ID
                        })
                        
                        
                        if(!ids[0]) {
                            BootstrapDialog.alert('Keine Auswahl getroffen');
                            $('#spinner').addClass('d-none');
                            return;
                        }
                        
                        postData.data['copyFrom'] = ids[0];
                             
                        $.post("../../copyMaterial/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                        
                        .done(function(data) { 
                            $('#spinner').addClass('d-none');
                            dialogItself.close(); 
                            window.location.reload(); 
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                            
                            alertException(xhr);
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        });
        
        
        $('.drop_material_button').click(function() {
        
            BootstrapDialog.confirm('Möchten Sie die selektierte Materialposition wirklich löschen?', function(result){
                if(result) {
                
                    $('#spinner').removeClass('d-none');
                    
                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }
                    
                    let selectedRowID = materialTable.getSelectedData()[0].ID;
                                            
                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/c5b93c44c6aa831b9f9b39580a9efeed7470c8bc/" + selectedRowID, postData)
                    
                        .done(function() {
                                        
                            $('#spinner').addClass('d-none');            
                            
                            materialTable.setData("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}/_material");
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            alertException(xhr);
                        });
                    $('.material_menu_button').prop('disabled', true);
                }
            });
        
        
        })
        
        $(document).on('click', '#open_manhourunits_button', function() {
        
       
            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../9ffce4444107ee0f282fbffa210a9f36f157aeaa/d596f5dc798b83d3bca3ad7d68d7ccb2ad6e5029'),
                title:'Arbeitsleistung erfassen',
                type:BootstrapDialog.TYPE_LIGHT
            });
        
        })
        
        
        $(document).on('click', '#open_materialmaster_button', function() {
        
            $.each(BootstrapDialog.dialogs, function(id, dialog){
                dialog.close();
            });
        
            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../bdd9815c6685a7ea6a567b141e2919969717c80b/5a7dfc613be971ac442fff63b73ecd1b2ebd9594'),
                size:BootstrapDialog.SIZE_EXTRAWIDE,
                title:"Materialstamm",
                //cssClass:'modal-fullscreen',
                data:{
                    ticket: '{{$model->getKey()}}'
                }
                
            });
        
        })
        
        
        $(document).on('click', '#open_unitselection_button', function() {
        
            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../ba0cfd2e18e37e3b20f8d121a5a01d05951dd232/5ddb8c9ee285433c6034c2e62b3590242eb2f82c'),
                type:BootstrapDialog.TYPE_LIGHT,
                title:'Verpackungseinheit auswählen'
            });
        
        });
        
        $('#drop_ticket').click(function() {
        
           BootstrapDialog.confirm({
                message:'Soll das aktuell gewählte Angebot wirklich gelöscht werden ?',
                type:BootstrapDialog.TYPE_DANGER, 
                title:'Angebot löschen', 
                btnCancelLabel:'Abbrechen', 
                btnOKLabel:'Löschen', 
                callback: function(result){
           
                    if(!result) return;
                   
                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }
                    
                          
                    $.post("/api/hwplus/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                    
                        .done(function() {
                        
                            window.location = "/hwplus/7596f11cd8b4f79e81ac81fae42f45e5281c8b2c/afe4f16263308b092d15e04719f202efe1326813";
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            alertException(xhr);
                        });
                    
                } 
            });
        
        });
        
        $(document).on('click', '.preview_ticket', function() {
           
            if(!download('../../preview_offer/1/{{$model->getKey()}}')) {
                getPDFTicket('../../preview_offer/1/{{$model->getKey()}}');
            }
        
        });
        
        $(document).on('click', '.preview_confirmation', function() {
           
             if(!download('../../preview_confirmation/{{$model->getKey()}}')) {
                getPDFTicket('../../preview_confirmation/{{$model->getKey()}}');
            }
        
        });
        
        
        $('.pdf_print').click(function() {
        
            if(!download('../../print/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}')) {
                getPDFTicket('../../print/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}');
            }
        
        });
        
        $('.send_email').click(function() {
             
            BootstrapDialog.show({
                message: $('<div></div>').load('../../340beb9bb920081568658f76e5fa0afdc0c87ed8/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}'),
                title:'Email-Versand',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Senden',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        let postData = $('#new_email').serialize();
                    
                        postData._token = '{{csrf_token()}}';
                        
                        $.post("../../mail/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            dialogItself.close();
                            window.location.reload();
                            
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                        
                            
                             if(422 == xhr.status) {
                                $('#new_email').find('.is-invalid').removeClass('is-invalid');
                                $.each(xhr.responseJSON.errors, function(index, item) {
                                    let array = index.split('.');
                                    $('#new_email').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                });
                            
                            
                            }

                            else { 
                            
                                alertException(xhr);
                            }
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        })
        
        $('#images').click(function() {
        
      
            BootstrapDialog.show({
                message: $('<div></div>').load('../../ea947bc4ff6ae49ce07977b9418fd26c819aa0de/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}'),
                title:'Baustellendokumentation',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Foto hinzufügen',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                                  
                        $.ajax( {
                            url: "../../../api/{{$repository->getConfig()->_service->url}}/044437d236597965414e994e7fbe67c84824a6ff/19963a1fc51e95ff83d11ea55a3c83858f5dd0d2",
                            type: 'POST',
                            data: new FormData($('#capture')[0]),
                            processData: false,
                            contentType: false
                        })
                        
                        .done(function(data) { 
                            add_image(data[0].ID, data[0].descriptor, data[0].image);
                            $('#spinner').addClass('d-none');
                            
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                            
                             if(422 == xhr.status) {
                                $('#capture').find('.is-invalid').removeClass('is-invalid');
                                $.each(xhr.responseJSON.errors, function(index, item) {
                                    let array = index.split('.');
                                    $('#capture').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                });
                            
                            
                            }

                            else { 
                            
                                alertException(xhr);
                            }
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        })
        
       
        $('.close_ticket').click(function() {
        
        
            dialog = BootstrapDialog.confirm({
                title: 'Angebot schließen bestätigen',
                type: BootstrapDialog.TYPE_LIGHT, // <-- Default value is BootstrapDialog.TYPE_PRIMARY
                message: 'Möchten Sie das aktuelle Angebot abschließen und eine Angebotsnummer generieren. Achtung: das Dokument kann nach diesem Vorgang nicht mehr verändert werden!',
                closable: true, // <-- Default value is false
                draggable: true, // <-- Default value is false
                btnCancelLabel: 'Abbrechen', // <-- Default value is 'Cancel',
                btnOKLabel: 'Jetzt abschließen', // <-- Default value is 'OK',
                btnOKClass: 'btn-success', // <-- If you didn't specify it, dialog type will be used,
                callback: function(result) {
                    if(!result) return;
                    $.get('../../close_offer/1/{{$model->getKey()}}')
                     .done(function(data) { 
                        window.location.reload(); 
                      })
                     .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                            
                            alertException(xhr);
                        
                        });
                }
            });
        
            return;
      
            BootstrapDialog.show({
                message: $('<div></div>').load('../../0653b64aa076b01f10299c2b363151edf6a9648c/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}'),
                title:'Unterschrift einholen',
                type:BootstrapDialog.TYPE_LIGHT,
                closable:false,
                buttons: [{
                    label: 'Senden',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        // Get the signature pad data -
                        let sigData =  $('#signaturePad').jSignature('getData', 'default');

                        // Set the hidden field value with the value from the sigData variable.
                        $('#sigData').val(sigData);
                 
                        let postData = $('#sigForm').serialize();
                        
                        $.post("../../subscribe/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                        
                        .done(function(data) { 
                            $('#spinner').addClass('d-none');
                            dialogItself.close(); 
                            window.location.reload(); 
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                            
                            if(422 == xhr.status) {
                                $('#new_email').find('.is-invalid').removeClass('is-invalid');
                                $.each(xhr.responseJSON.errors, function(index, item) {
                                    let array = index.split('.');
                                    $('#new_email').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                });
                            
                            
                            }

                            else alertException(xhr);
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        })
    
        @if($model->flag_signed)
        @else
        $('#fare,#location,#assignment,#commission_number,#note,#order_number,#date,#date_valid_to, #header,#footer').editable({ onblur:"ignore", emptytext:'Klicken zum ändern'});
        @endif
        
        $('#note').on('save', function(e, params) {

            $('#spinner').removeClass('d-none');
            
            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['note'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);    
                });
        });
        
        $('#print_note').change(function() {
        
            $('#spinner').removeClass('d-none');
            
            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['print_note'] = $('#print_note').prop('checked') ? 1 : 0;
                        
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);           
                });
            
        });
        
        $('#title').on('save', function(e, params) {
        
            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['title'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);   
                });
        });
        
        $('#fare').on('save', function(e, params) {
        
            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['fare'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);     
                });
        });
        
        
        $('#location').on('save', function(e, params) {
        
            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['location'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);    
                });
        });
        
        $('#assignment').on('save', function(e, params) {
        
            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['assignment'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
            
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);    
                });
        });
        
        $('#commission_number').on('save', function(e, params) {
        
            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['commission_number'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);      
                });
        });
        
        $('#order_number').on('save', function(e, params) {
        
        
            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['order_number'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
            
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);   
                });
        });
             
        $('#date').on('save', function(e, params) {
        
            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['date'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function(data) {
                    $('#spinner').addClass('d-none');
                    $('#date').html(moment(data[0].date).format('DD.MM.YYYY'));
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                    
                    alertException(xhr);
                });
        });
        
        $('#date_valid_to').on('save', function(e, params) {
        
            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['date_valid_to'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function(data) {
                    $('#spinner').addClass('d-none');
                    $('#date_valid_to').html(moment(data[0].date_valid_to).format('DD.MM.YYYY'));
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                    
                    alertException(xhr);       
                });
        });
        
        $('#header').on('save', function(e, params) {
        
            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['header'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function(data) {
                    $('#spinner').addClass('d-none');
                    $('#date').html(moment(data[0].date).format('DD.MM.YYYY'));
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                    
                    alertException(xhr);    
                });
        });
        
        $('#footer').on('save', function(e, params) {
        
            $('#spinner').removeClass('d-none');

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['footer'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                
                .done(function(data) {
                    $('#spinner').addClass('d-none');
                    $('#date').html(moment(data[0].date).format('DD.MM.YYYY'));
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                    
                    alertException(xhr);   
                });
        });
        
        $('.offer2ticket').on('click', function() {
        
                
            $('#spinner').removeClass('d-none');

    
            let postData = {};
                postData._token = '{{csrf_token()}}';
            
            $.post("../../offer2ticket/{{$model->getKey()}}", postData)
            
            .done(function(data) { 
            
                $('#spinner').addClass('d-none');
                //window.location.reload();
                window.parent.load_frame('open_tickets', '0ff1bb77a9de65eac6621c9c5a983da7a37ed3bf/afe4f16263308b092d15e04719f202efe1326813/' + data[0].ID, true)
                
            })
            
            .fail(function(xhr, status, error) {
            
                $('#spinner').addClass('d-none');
            
                alertException(xhr);
            
            });
        
        });

        $('#make_ticket_copy').click(function() {

            let postData = {
                _token:'{{csrf_token()}}',
                data: {}
            }

            $('#spinner').removeClass('d-none');


            $.post("../../copy_offer/{{$model->getKey()}}", postData)

                .done(function(data) {
                    $('#spinner').addClass('d-none');
                    BootstrapDialog.confirm({
                        title: 'Vorgang erfolgreich',
                        message: 'Das Angebot wurde erfolgreich kopiert.',
                        closable: true, // <-- Default value is false
                        draggable: true, // <-- Default value is false
                        btnCancelLabel: 'Schließen', // <-- Default value is 'Cancel',
                        btnOKLabel: 'Kopie öffnen', // <-- Default value is 'OK',
                        btnOKClass: 'btn-success', // <-- If you didn't specify it, dialog type will be used,
                        callback: function(result) {
                            // result will be true if button was click, while it will be false if users close the dialog directly.
                            if(result) {
                                window.location = "./" + data.ID;
                            }
                        }
                    });
                })

                .fail(function(xhr, status, error) {

                    $('#spinner').addClass('d-none');

                    alertException(xhr);

                })

        })
        
        $('.adjust_offer').on('click', function() {


            $('#spinner').removeClass('d-none');


            let postData = {};
                postData._token = '{{csrf_token()}}';

            $.post("../../adjust_offer/{{$model->getKey()}}", postData)

            .done(function(data) {

                $('#spinner').addClass('d-none');
                //window.location.reload();
                window.parent.load_frame('offers', 'd774d83528528c1bb8aa3f8a18d6bd66a9c76e66/afe4f16263308b092d15e04719f202efe1326813/' + data.ID, true)

            })

            .fail(function(xhr, status, error) {

                $('#spinner').addClass('d-none');

                alertException(xhr);

            });

        });

        $('#to_invoice').on('click', function() {
        
            BootstrapDialog.show({
                message: $('<div></div>').load('../../b8395fb122146f77bec7389c1b4a0430d3d65236/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}'),
                title:'Rechnungsadresse auswählen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Weiter',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                    
                        var option = $('#new_invoice [name="recipient"]:checked').val();
                        
                        switch(option) {
                        
                            case "new": 
                            
                                dialogItself.close();
                            
                                BootstrapDialog.show({
                                    message: $('<div></div>').load('../../bee81541cb1e85aa6f48a7ec8f590b5e2a4b0c28/86343e16c8551a46bdd6560814444580b3833a53/{{$model->_client->getKey()}}'),
                                    title:'Neue Rechnungsadresse erfassen',
                                    type:BootstrapDialog.TYPE_LIGHT,
                                    buttons: [{
                                        label: 'Speichern',
                                        cssClass:'btn-success',
                                        action: function(dialogItself) {
                                        
                                            $('#spinner').removeClass('d-none');
                                        
                                            let postData = $('#new_recipient').serialize();
                                            postData._token = '{{csrf_token()}}';
                                            
                                            $.post("../../../api/{{$repository->getConfig()->_service->url}}/86343e16c8551a46bdd6560814444580b3833a53/bee81541cb1e85aa6f48a7ec8f590b5e2a4b0c28", postData)
                        
                                                .done(function(data) { 
                                                                                                    
                                                    let postData = {};
                                                        postData.recipient = data[0].ID;
                                                        postData._token = '{{csrf_token()}}';
                                                    
                                                    $.post("../../create_invoice/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                                                    
                                                    .done(function(data) { 
                                                    
                                                        $('#spinner').addClass('d-none');
                                                        dialogItself.close();
                                                        window.parent.load_frame('invoices', '2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/' + data.ID, true);





                                                        
                                                    })
                                                    
                                                    .fail(function(xhr, status, error) {
                                                    
                                                        $('#spinner').addClass('d-none');
                                                        alertException(xhr);
                                                    
                                                    });
                                                    
                                                    
                                                })
                                                
                                                .fail(function(xhr, status, error) {
                                                
                                                    $('#spinner').addClass('d-none');
                                        
                                                    if(422 == xhr.status) {
                                                        
                                                            $('#new_recipient').find('.is-invalid').removeClass('is-invalid');
                                                            $.each(xhr.responseJSON, function(index, item) {
                                                                let array = index.split('.');
                                                                $('#new_recipient').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                                            });
                                                        
                                                            return;
                                                        
                                                    }
                                                
                                                    
                                                    else alertException(xhr);
                                                
                                                });
                                        }
                                    }]
                                });
                            
                            
                                break;
                                
                                
                            case "": alert('Fehler! Keine Auswahl getroffen'); 
                                break;
                                
                                
                                
                            default:
                            
                               $('#spinner').removeClass('d-none');
                    
                       
                                let postData = $('#new_invoice').serialize();
                            
                                postData._token = '{{csrf_token()}}';
                                
                                $.post("../../create_invoice/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                                
                                .done(function(data) { 
                                
                                    $('#spinner').addClass('d-none');
                                    dialogItself.close();
                                    window.parent.load_frame('invoices', '2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/' + data.ID, true);
                                    
                                })
                                
                                .fail(function(xhr, status, error) {
                                
                                    $('#spinner').addClass('d-none');
                                    alertException(xhr);
                                
                                });
                                break;
                        
                        }
                    
                        return;
                    
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
            
        
        });
        
        
        $('#to_standing_order').on('click', function() {
        
            let recipient = "";
            
            let subDialog = function() {
            
                BootstrapDialog.show({
                    message: $('<div></div>').load('../../3f5ddc28f04120d70a58dfa16fd9d4e727a7b298/eb6d39ca7f5625f42000457be649fb949284eca3?ticket={{$model->getKey()}}&recipient=' + recipient),
                    title:'Neuen Dauerauftrag erstellen',
                    type:BootstrapDialog.TYPE_LIGHT,
                    onshown: function() {
                    
                    
                    },
                    buttons: [{
                        label: 'Speichern',
                        cssClass:'btn-success',
                        action: function(dialogItself) { 
                        
                            $('#spinner').removeClass('d-none');
                            
                            
                            let postData = $('#new_standing_order').serialize();
                        
                            postData._token = '{{csrf_token()}}';
                            
                            $.post("/api/hwplus/eb6d39ca7f5625f42000457be649fb949284eca3/3f5ddc28f04120d70a58dfa16fd9d4e727a7b298", postData)
                            
                            .done(function(data) { 
                            
                                $('#spinner').addClass('d-none');
                                window.location.reload();
                                
                            })
                            
                            .fail(function(xhr, status, error) {
                            
                                $('#spinner').addClass('d-none');
                            
                                if(422 == xhr.status) {
                                    $('#new_standing_order').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON.errors, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_standing_order').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                    });    
                                
                                }

                                else { 
                                
                                    alertException(xhr);
                                }
                            
                            });
                        
                        }
                    }, {
                        label: 'Abbrechen',
                        action: function(dialogItself){
                            dialogItself.close();
                        }
                    }]
                });
            
            }
        
            BootstrapDialog.show({
                message: $('<div></div>').load('../../b8395fb122146f77bec7389c1b4a0430d3d65236/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}'),
                title:'Rechnungsadresse auswählen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Weiter',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                    
                        var option = $('#new_invoice [name="recipient"]:checked').val();
                        
                        switch(option) {
                        
                            case "new": 
                            
                                dialogItself.close();
                            
                                BootstrapDialog.show({
                                    message: $('<div></div>').load('../../bee81541cb1e85aa6f48a7ec8f590b5e2a4b0c28/86343e16c8551a46bdd6560814444580b3833a53/{{$model->_client->getKey()}}'),
                                    title:'Neue Rechnungsadresse erfassen',
                                    type:BootstrapDialog.TYPE_LIGHT,
                                    buttons: [{
                                        label: 'Speichern',
                                        cssClass:'btn-success',
                                        action: function(dialogItself) {
                                        
                                            $('#spinner').removeClass('d-none');
                                        
                                            let postData = $('#new_recipient').serialize();
                                            postData._token = '{{csrf_token()}}';
                                            
                                            $.post("../../../api/{{$repository->getConfig()->_service->url}}/86343e16c8551a46bdd6560814444580b3833a53/bee81541cb1e85aa6f48a7ec8f590b5e2a4b0c28", postData)
                        
                                                .done(function(data) { 
                                                
                                                    $('#spinner').addClass('d-none');
                                                    recipient = data[0].ID;
                                                    dialogItself.close();
                                                    subDialog();
                       
                                                    
                                                })
                                                
                                                .fail(function(xhr, status, error) {
                                                
                                                    $('#spinner').addClass('d-none');
                                        
                                                    if(422 == xhr.status) {
                                                        
                                                            $('#new_recipient').find('.is-invalid').removeClass('is-invalid');
                                                            $.each(xhr.responseJSON, function(index, item) {
                                                                let array = index.split('.');
                                                                $('#new_recipient').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                                            });
                                                        
                                                            return;
                                                        
                                                    }
                                                
                                                    
                                                    else alertException(xhr);
                                                
                                                });
                                        }
                                    }]
                                });
                            
                            
                                break;
                                
                                
                            case "": alert('Fehler! Keine Auswahl getroffen'); 
                                break;
                                
                                
                                
                            default:
                            
                                $('#spinner').addClass('d-none');
                                
                                recipient = option;
                                dialogItself.close();
                                subDialog();
                       
                                
                                break;
                        
                        }
                    
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
            
            
            
            
        
        });
        
        $('#change_client').on('click', function() {
        
            BootstrapDialog.show({
                message: $('<div></div>').load('../../2fffe827a87ec53b4b1c575e6f58dda5a2093c46/86343e16c8551a46bdd6560814444580b3833a53'),
                title:'Kunde ändern',
                size:BootstrapDialog.SIZE_WIDE,
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Auswahl übernehmen',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        let ids = $.map($('#client_select_table').bootstrapTable('getSelections'), function (row) {
                            return row.ID
                        })
                        
                        let postData = {};
                            postData._method = "PUT";
                            postData.data = {};
                            postData.data['_client'] = ids[0];
                                            
                        $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                        
                        .done(function(data) { 
                            $('#spinner').addClass('d-none');
                            dialogItself.close(); 
                            window.location.reload(); 
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                            
                            alertException(xhr);
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        });
        
        $('.confirmation_accept').on('click', function() {
        
            BootstrapDialog.show({
                message: $('<div></div>').load('../../85da55a20ef00d2ac317c1b293672d5a719d24bd/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}'),
                title:'Auftrag annehmen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Senden',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');

                        let postData = $('#accept_order').serialize();
                    
                        postData._token = '{{csrf_token()}}';
                        
                        $.post("/api/hwplus/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}/85da55a20ef00d2ac317c1b293672d5a719d24bd", postData)
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            dialogItself.close();
                            window.location.reload();
                            
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                        
                             if(422 == xhr.status) {
                                $('#accept_order').find('.is-invalid').removeClass('is-invalid');
                                $.each(xhr.responseJSON.errors, function(index, item) {
                                    let array = index.split('.');
                                    $('#accept_order').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                });    
                            
                            }

                            else { 
                            
                                alertException(xhr);
                            }
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        });
        
        $('.confirmation_print').on('click', function() {
            if(!download('../../print_confirmation/{{$model->getKey()}}')) {
                getPDFTicket('../../print_confirmation/{{$model->getKey()}}');
            }
            window.location.reload();
        });
        
        
        $('.confirmation_mail').on('click', function() {
        
            BootstrapDialog.show({
                message: $('<div></div>').load('../../4b56fcceb37080cc3121aa673e4a08dfa64dbde4/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}'),
                title:'Auftragsbestätigung versenden',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Senden',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        let postData = $('#new_email').serialize();
                    
                        postData._token = '{{csrf_token()}}';
                        
                        $.post("../../mail_confirmation/{{$model->getKey()}}", postData)
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            dialogItself.close();
                            
                            BootstrapDialog.alert({
                                title: 'Bestätigung',
                                type: BootstrapDialog.TYPE_SUCCESS,
                                message: 'Email-Erfolgreich versendet'
                            });
                            
                            window.location.reload();
                            
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                        
                            
                             if(422 == xhr.status) {
                                $('#new_email').find('.is-invalid').removeClass('is-invalid');
                                $.each(xhr.responseJSON.errors, function(index, item) {
                                    let array = index.split('.');
                                    $('#new_email').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                });
                            
                            
                            }

                            else { 
                            
                                alertException(xhr);
                            }
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        });
    
    });
    
    show_image = function(image) {
        BootstrapDialog.show({
            message: '<img src="{{url('Models/PHPXPress/HwplusImages/image')}}/'+image+'" style="width:100%;">',
            size:BootstrapDialog.SIZE_WIDE,
            type:BootstrapDialog.TYPE_LIGHT
        });

    
    }
    
    
    delete_image = function(id) {
    
        BootstrapDialog.confirm('Bild löschen bestätigen?', function(result){
                if(result) {
                
                    $('#spinner').removeClass('d-none');
                    
                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }
                    
                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/044437d236597965414e994e7fbe67c84824a6ff/" + id, postData)
                    
                        .done(function() {
                        
                            $('#spinner').addClass('d-none');
                            $('#image_' + id).remove();
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            alertException(xhr);
                        });
                    
                }
            });
    
    }

    function preview_header() {

            BootstrapDialog.show({
                message: $('<div></div>').load('../../9fb3ac0f42ad029cc63c17d32680fe58ef781b80/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}?display=header'),
                title:'Vorschau Kopfzeile',
                buttons: [{
                    label: 'Schließen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });

        }

    function preview_footer() {

            BootstrapDialog.show({
                message: $('<div></div>').load('../../9fb3ac0f42ad029cc63c17d32680fe58ef781b80/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}?display=footer'),
                title:'Vorschau Kopfzeile',
                buttons: [{
                    label: 'Schließen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });

        }
    
    </script>
    
    </head> 

    <body class="bg-transparent">
    
        <div id="spinner" class="spinner spinner-border d-none" role="status">
            <span class="sr-only">Loading...</span>
        </div>
    
        <div class="container pt-3 bg-white border-left border-right border-{{$cs}}">

        <nav class="navbar navbar-expand-lg navbar-light bg-{{$cs}} text-white">
            <a class="navbar-brand text-white" href="#"><i class="mdi mdi-offer"></i> Angebotswesen</a>
        </nav>
          
        <div class="btn-group mt-2 mb-2" role="group">
        
            <button type="button" class="btn btn-{{$cs}}" style="color:white !important; background-color:var(--{{$cs}}); opacity:1" disabled><i class="mdi mdi-menu"></i></button>
        
            <button type="button" class="btn btn-{{$cs}}" onclick="window.location='../../2077b82edbd2ffc1c8dc27880d101b975bd444b8/afe4f16263308b092d15e04719f202efe1326813'"><i class="mdi mdi-home-circle"></i> zurück zur Übersicht</button>
                       
            <div class="dropdown">
                <button class="btn btn-{{$cs}} dropdown-toggle rounded-0" type="button" data-toggle="dropdown">
                  <i class="mdi mdi-file-sign"></i> Angebot
                </button>
                <div class="dropdown-menu">
                    <a class="dropdown-item" href="#" id="images">Baustellendokumentation</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="#" id="make_ticket_copy">Kopie erstellen</a>
                    
                    
                        
                    @if($model->_invoice OR !$model->flag_signed)
                    @elseif($model->_offer_at_hwplus_tickets->first())
                    @elseif(!$model->mailed AND !$model->printed)
                    @else
                        <!--a class="dropdown-item" href="#" id="to_invoice">Rechnung erstellen</a -->
                        @if($model->_manhours->count() OR $model->_services->count() OR $model->_fare_charges->count())
                        <a class="dropdown-item offer2ticket" href="#">Auftrag erstellen</a>
                        @elseif($model->_material->count() AND !$model->_manhours->count() AND !$model->_services->count() AND !$model->_fare_charges->count())
                        <a class="dropdown-item offer2ticket" href="#">Lieferschein erstellen</a>
                        @endif
                    @endif
                        
                    
                    
                    @if(!$model->flag_signed)
                    @elseif($model->_invoice)
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="../../2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->_invoice->getKey()}}">Rechnung anzeigen</a>
                    @elseif($model->_offer_at_hwplus_tickets->first())
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="../../0ff1bb77a9de65eac6621c9c5a983da7a37ed3bf/afe4f16263308b092d15e04719f202efe1326813/{{$model->_offer_at_hwplus_tickets->first()->getKey()}}">{{$model->_offer_at_hwplus_tickets->first()->descriptor}} anzeigen</a>
                    @elseif(!$model->date_accept_order AND ($model->printed OR $model->mailed))
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item confirmation_accept @if(!$model->job_number) disabled @endif" href="#">Auftrag annehmen</a>
                    <a class="dropdown-item adjust_offer @if(!$model->job_number) disabled @endif" href="#">Angebot korrigieren</a>
                    @elseif($model->date_accept_order)
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item preview_confirmation @if(!$model->flag_signed) disabled @endif" href="#">Vorschau Auftragsbestätigung</a>
                    @endif
                    @if(!$model->_invoice AND $model->date_accept_order)
                    <a class="dropdown-item confirmation_print @if(!$model->flag_signed) disabled @endif" href="#">Auftragsbestätigung @if($model->printed_confirmation) erneut @endif drucken</a>
                    <a class="dropdown-item confirmation_mail @if(!$model->flag_signed) disabled @endif" href="#">Auftragsbestätigung @if($model->mailed_confirmation) erneut @endif per Email senden</a>
                    @endif
                
                    @if(!$model->flag_signed)
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item close_ticket" href="#">Angebot abschließen</a>
                    @elseif($model->flag_signed AND !$model->date_accept_order)
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item pdf_print" href="#">Angebot @if($model->printed) erneut @endif drucken</a>
                    <a class="dropdown-item send_email" href="#" >Angebot @if($model->mailed) erneut @endif per Email senden</a>
                    @endif
                    
                    @if(!$model->flag_signed)
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item preview_ticket" href="#">Vorschau</a>
                    @endif
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item @if($model->flag_signed) disabled @endif" href="#" id="drop_ticket" >Löschen</a>
                </div>
            </div>
        </div>
          
          
          
            <div class="row">
            
                <div class="col col-xs-12 col-md-4">
                
                    <div class="card">
                            <ul class="list-group list-group-flush">
                            <li class="list-group-item"><b>{{$model->descriptor}}</b> @if(!$model->flag_signed) <button class="btn btn-{{$cs}} btn-sm float-right" id="change_client" >Adresse ändern</button> @endif</li>
                            <li class="list-group-item">
                                <b>{{$model->_client->descriptor}}</b>
                                @if($model->_client->firstname) <br> {{$model->_client->firstname}} {{$model->_client->surname}} @endif
                                <br>{{$model->_client->streetadress}} {{$model->_client->housenumber}}
                                <br>{{$model->_client->postcode}} {{$model->_client->location}}
                                <br>Geschäftlich: {{$model->_client->phone_business}}
                                <br>Mobil: {{$model->_client->phone_mobile}}
                            </li>
                        </ul>
                    </div>
                </div>
            
            
                <div class="col col-xs-12 col-md-4">
                    <div class="card">
                            <ul class="list-group list-group-flush">
                            <li class="list-group-item"><b>Notizen:</b> <small>(auf PDF drucken: <input type="checkbox" name="data[print_note]" id="print_note" {{$model->print_note ? 'checked="checked"' : ''}}>)</small></li>
                            <li class="list-group-item"><a href="#" id="note" data-type="textarea" data-mode="inline">{{$model->note}}</a></li>
                        </ul>
                    </div>
                
                </div>
                <div class="col col-xs-12 col-md-4">
                    <div class="card">
                            <ul class="list-group list-group-flush">
                            <li class="list-group-item" style="font-size:x-large"><b>{{$model->short_name}}-{{$model->job_number ? : "[" . $model->createJobNumber() . "]"}}</b></li>

                            @if($model->_offer_at_hwplus_tickets->first())
                            <li class="list-group-item"><b>{{$model->_offer_at_hwplus_tickets->first()->descriptor}}:</b>
                                @if($model->_offer_at_hwplus_tickets->first()->_meta->_doctype->identifier == "lot")
                                <a class="editable-click" href="#" onclick="window.parent.load_frame('lot', '0ff1bb77a9de65eac6621c9c5a983da7a37ed3bf/afe4f16263308b092d15e04719f202efe1326813/{{$model->_offer_at_hwplus_tickets->first()->getKey()}}')', true)">
                                @elseif($model->_offer_at_hwplus_tickets->first()->flag_signed)
                                <a class="editable-click text-success" href="#" onclick="window.parent.load_frame('closed_tickets', '0ff1bb77a9de65eac6621c9c5a983da7a37ed3bf/afe4f16263308b092d15e04719f202efe1326813/{{$model->_offer_at_hwplus_tickets->first()->getKey()}}', true)">
                                @else
                                <a class="editable-click text-info" href="#" onclick="window.parent.load_frame('open_tickets', '0ff1bb77a9de65eac6621c9c5a983da7a37ed3bf/afe4f16263308b092d15e04719f202efe1326813/{{$model->_offer_at_hwplus_tickets->first()->getKey()}}', true)">
                                @endif

                                @if($model->_offer_at_hwplus_tickets->first()->flag_signed) {{$model->_offer_at_hwplus_tickets->first()->job_number}}
                                @else [{{$model->_offer_at_hwplus_tickets->first()->createJobNumber()}}]
                            @endif</b></a></li>

                            @elseif($model->_invoice)
                            <li class="list-group-item"><b>{{$model->_invoice->descriptor}}</b>: <a style="color:var(--cyan)" href="#" onclick="window.parent.load_frame('invoices', '2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->_invoice->getKey()}}', true)"><b>
                            @if($model->_invoice->invoice_number) {{$model->_invoice->invoice_number}}
                            @else [{{$model->_invoice->createInvoiceNumber()}}]
                            @endif</b></a></li>

                            @elseif($model->_ticket_at_hwplus_standing_orders)
                            <li class="list-group-item"><b>Dauerauftrag</b>: <a style="color:var(--cyan)" href="../../c793c74059479a1b43400430343e5f0849222492/eb6d39ca7f5625f42000457be649fb949284eca3/{{$model->_ticket_at_hwplus_standing_orders->getKey()}}"><b>Anzeigen</b></a></li>

                            @endif

                            @if($model->_adjusted_offer_at_hwplus_tickets)
                            <li class="list-group-item"><b>Korrigiertes Angebot:</b> <a href="../../d774d83528528c1bb8aa3f8a18d6bd66a9c76e66/afe4f16263308b092d15e04719f202efe1326813/{{$model->_adjusted_offer_at_hwplus_tickets->getKey()}}">{{$model->_adjusted_offer_at_hwplus_tickets->job_number}}</a></li>
                            @endif

                            <li class="list-group-item"><b>Kundenreferenz:</b> <a href="#" id="order_number" data-type="text" data-mode="inline">{{$model->order_number}}</a></li>
                            <li class="list-group-item"><b>Einsatzstelle:</b> <a href="#" id="location" data-type="text" data-mode="inline">{{$model->location}}</a></li>
                            <li class="list-group-item"><b>Kommission:</b> <a href="#" id="commission_number" data-type="text" data-mode="inline">{{$model->commission_number}}</a></li>
                            @if($model->flag_signed)
                                @if($model->date_accept_order)
                                <li class="list-group-item"><b>Angenommen zum:</b> @if($model->date_accept_order) {{(new \Carbon\Carbon($model->date_accept_order))->format('d.m.Y')}} @endif</li>
                                @endif
                            <li class="list-group-item"><b>per Mail gesendet:</b> @if($model->mailed) {{(new \Carbon\Carbon($model->mailed))->format('d.m.Y')}} @endif</li>
                            <li class="list-group-item"><b>Gedruckt:</b> @if($model->printed) {{(new \Carbon\Carbon($model->printed))->format('d.m.Y')}} @endif</li>
                            @endif
                            <li class="list-group-item"><b>Gültig bis:</b> <a href="#" id="date_valid_to" data-tpl="<input type='date'>" data-mode="inline" data-value="{{$model->date_valid_to}}">@if($model->date_valid_to) {{(new \Carbon\Carbon($model->date_valid_to))->format('d.m.Y')}} @endif</a></li>
                            <li class="list-group-item"><b>Angebotsdatum:</b> <a href="#" id="date" data-tpl="<input type='date'>" data-mode="inline" data-value="{{$model->date}}" data-emptytext="Heute">@if($model->date) {{(new \Carbon\Carbon($model->date))->format('d.m.Y')}} @endif</a></li>
                        </ul>
                    </div>
                </div>
            </div>
            

            <hr>

            @if($model->_adjusted_offer)
            <div class="card mt-2">
                <div class="card-header bg-danger text-white">Hinweis</div>
                <div class="card-body bg-danger text-white">

                    Dieses Angebot wurde korrigiert. Das korrigierte Angebot finden Sie <a class="text-dark" href="../../d774d83528528c1bb8aa3f8a18d6bd66a9c76e66/afe4f16263308b092d15e04719f202efe1326813/{{$model->_adjusted_offer->getKey()}}">&gt; hier &lt;</a>.

                </div>
            </div>
            @endif
          

            <!--div class="card mt-2">
                <div class="card-header bg-secondary text-white">Titel</div>
                <div class="card-body">
                    <table style="width:100%" border=0>
                    <tr>
                        <td><a href="#" id="title" data-mode="inline" data-type="text" data-showbuttons="bottom" data-inputclass="textarea">{{$model->title}}</a></td>
                    </tr>
                    </table>
                </div>
            </div-->

            @if('material_offer' == $model->_meta->_doctype->identifier)
            @else
            <div class="card mt-2">
                <div class="card-header bg-secondary text-white">Durchzuführende Arbeiten</div>
                <div class="card-body">
                    <table style="width:100%" border=0>
                    <tr>
                        <td><a href="#" id="assignment" data-mode="inline" data-type="textarea" data-inputclass="textarea">{{$model->assignment}}</a></td>
                    </tr>
                </table>
            </div>
            </div>
            @endif

            
            <div class="card mt-2">
                <div class="card-header bg-secondary text-white">Kopfzeile</div>
                <div class="card-header ">
                    <div class="btn-group float-right" role="group">
                        <button class="btn btn-primary" type="button" data-toggle="collapse">
                            Platzhalter
                        </button>
                        <button class="btn btn-primary" onclick="preview_header()">
                            Vorschau
                        </button>
                    </div>
                </div>
                <x-placeholder_tickets :model="$model"/>
                <div class="card-body">

                    <table style="width:100%">
                    @if(!$model->flag_signed)
                    <tr>
                        <td><a href="#" id="header" data-mode="inline" data-type="textarea" data-showbuttons="bottom" data-inputclass="textarea">{!!$model->header!!}</a></td>
                    </tr>
                    @else
                    <tr>
                        <td>@foreach(explode("\n", $model->header) as $line){{ $line }}<br>@endforeach</td>
                    </tr>
                    @endif

                    </table>
                </div>
            </div> 
            


            @if('material_offer' == $model->_meta->_doctype->identifier)
            <div class="card mt-2">
                <div class="card-header bg-secondary text-white">Fahrt- und Nebenkosten</div>
                <div class="card-body">
                    <div id="fareTable" class="mt-3"></div>
                </div>
            </div>
            @elseif(\Runtime::make('hwplus_manhours_units')->count())
            <div class="card mt-2">
                <div class="card-header bg-secondary text-white">Arbeitsstunden</div>
                <div class="card-body">
                    
                    @if(!$model->flag_signed)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-{{$cs}} add_manhour"><i class="mdi mdi-plus-circle"></i> Zeit hinzufügen</button>
                        <button class="btn btn-{{$cs}} dropdown-toggle manhour_menu_button" type="button" data-toggle="dropdown" aria-expanded="false" disabled>
                         gewählte Position
                        </button>
                        <div class="dropdown-menu">
                            <button class="dropdown-item drop_manhour_button">Löschen</button>
                        </div>
                    </div>
                    @endif

                    <div id="manhourTable" class="mt-3"></div>

                    @if(!$model->flag_signed)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-{{$cs}} add_manhour"><i class="mdi mdi-plus-circle"></i> Zeit hinzufügen</button>
                        <button class="btn btn-{{$cs}} dropdown-toggle manhour_menu_button" type="button" data-toggle="dropdown" aria-expanded="false" disabled>
                         gewählte Position
                        </button>
                        <div class="dropdown-menu">
                            <button class="dropdown-item drop_manhour_button">Löschen</button>
                        </div>
                    </div>
                    @endif

                </div>
            </div>
            <div class="card mt-2">
                <div class="card-header bg-secondary text-white">Automatisch berechnete Fahrtkostentabelle</div>
                <div class="card-body">
                    <div id="fareTable" class="mt-3"></div>
                </div>
            </div>
            @endif

            @if('material_offer' == $model->_meta->_doctype->identifier)
            @elseif(\Runtime::make('hwplus_services_master')->count())
            <div class="card mt-2">
                <div class="card-header bg-secondary text-white">Dienstleistungen</div>
                <div class="card-body">

                    @if(!$model->flag_signed)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-{{$cs}} add_service"><i class="mdi mdi-plus-circle"></i> Dienstleistung hinzufügen</button>
                        <button class="btn btn-{{$cs}} dropdown-toggle service_menu_button" type="button" data-toggle="dropdown" aria-expanded="false" disabled>
                         gewählte Position
                        </button>
                        <div class="dropdown-menu">
                            <button class="dropdown-item drop_service_button">Löschen</button>
                        </div>
                    </div>
                    @endif

                    <div id="serviceTable" class="mt-3"></div>

                    @if(!$model->flag_signed)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-{{$cs}} add_service"><i class="mdi mdi-plus-circle"></i> Dienstleistung hinzufügen</button>
                        <button class="btn btn-{{$cs}} dropdown-toggle service_menu_button" type="button" data-toggle="dropdown" aria-expanded="false" disabled>
                         gewählte Position
                        </button>
                        <div class="dropdown-menu">
                            <button class="dropdown-item drop_service_button">Löschen</button>
                        </div>
                    </div>
                    @endif
                </div>
            </div>
            @endif

            @if('material_offer' == $model->_meta->_doctype->identifier)
            @elseif(\Runtime::make('hwplus_fare_charges_master')->count())
            <div class="card mt-2">
                <div class="card-header bg-secondary text-white">Nebenkosten (Fahrtkosten etc)</div>
                <div class="card-body">

                    @if(!$model->flag_signed)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-{{$cs}} add_fare_charge"><i class="mdi mdi-plus-circle"></i> Fahrtkosten hinzufügen</button>
                        <button class="btn btn-{{$cs}} dropdown-toggle fare_charge_menu_button" type="button" data-toggle="dropdown" aria-expanded="false" disabled>
                         gewählte Position
                        </button>
                        <div class="dropdown-menu">
                            <button class="dropdown-item drop_fare_charge_button">Löschen</button>
                        </div>
                    </div>
                    @endif

                    <div id="fareChargeTable" class="mt-3"></div>

                    @if(!$model->flag_signed)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-{{$cs}} add_fare_charge"><i class="mdi mdi-plus-circle"></i> Fahrtkosten hinzufügen</button>
                        <button class="btn btn-{{$cs}} dropdown-toggle fare_charge_menu_button" type="button" data-toggle="dropdown" aria-expanded="false" disabled>
                         gewählte Position
                        </button>
                        <div class="dropdown-menu">
                            <button class="dropdown-item drop_fare_charge_button">Löschen</button>
                        </div>
                    </div>
                    @endif
                </div>
            </div>
            @endif

            @if(\Runtime::make('hwplus_fare_charges_master')->count() OR \Runtime::make('hwplus_services_master')->count() OR \Runtime::make('hwplus_manhours_units')->count())
            <div class="card mt-2">
                <div class="card-header bg-secondary font-weight-bold text-white">
                    Zwischensumme
                </div>
                <div class="card-body text-right pr-5">
                    <div class="sum1">0.00€</div>
                </div>
            </div>


            @else
            <div class="sum1 d-none"></div>
            @endif


            @if('material_offer' == $model->_meta->_doctype->identifier)
            @elseif(\App\Models\PHPXPress\HwplusPremiumCharges::count())

            <div class="card mt-2">
                <div class="card-header  bg-secondary text-white">Sonderzuschlag</div>
                <div class="card-body">
                    <div id="premiumChargeTable" class="mt-3"></div>
                </div>
            </div>

             <div class="card mt-2">
                <div class="card-header bg-secondary font-weight-bold text-white">
                    Zwischensumme
                </div>
                <div class="card-body text-right pr-5">
                    <div class="sum2">0.00€</div>
                </div>
            </div>

            @else

            <div class="sum2 d-none"></div>

            @endif
            
            <div class="card mt-2">
                <div class="card-header bg-secondary text-white">Material</div>
                <div class="card-body">
                    @if(!$model->flag_signed)
                    <div class="btn-group mt-2" role="group">

                        <button type="button" class="btn btn-{{$cs}} add_material"><i class="mdi mdi-plus-circle"></i> Material hinzufügen</button>
                        
                        <div class="btn-group" role="group">
                            <button class="btn btn-{{$cs}} dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false">
                                Material übernehmen
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item copy_material_from_open_button" >.. aus offenem Auftrag</button>
                                <button class="dropdown-item copy_material_from_closed_button" >.. aus abgeschlossener Auftrag</button>
                            </div>
                        </div>
                        
                        <div class="btn-group" role="group">
                            <button class="btn btn-{{$cs}} dropdown-toggle material_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_material_button" >Löschen</button>
                            </div>
                       </div>
                    </div>
                    @endif

                    <div id="materialTable" class="mt-3"></div>

                    @if(!$model->flag_signed)
                    <div class="btn-group mt-2" role="group">

                        <button type="button" class="btn btn-{{$cs}} add_material"><i class="mdi mdi-plus-circle"></i> Material hinzufügen</button>

                        <div class="btn-group" role="group">
                            <button class="btn btn-{{$cs}} dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false">
                                Material übernehmen
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item copy_material_from_open_button" >.. aus offenem Auftrag</button>
                                <button class="dropdown-item copy_material_from_closed_button" >.. aus abgeschlossener Auftrag</button>
                            </div>
                        </div>

                        <div class="btn-group" role="group">
                            <button class="btn btn-{{$cs}} dropdown-toggle material_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_material_button" >Löschen</button>
                            </div>
                       </div>
                    </div>
                    @endif
            </div>
                
        </div>

        <div class="card mt-2">
        <div class="card-header bg-secondary font-weight-bold text-white">
            Endbetrag
        </div>
        <div class="card-body text-right pr-5">
            <div class="netto">0.00€</div>
                @if(!$editor->getValue('COMPANY_SBLAW'))<div class="brutto">0.00€</div>@endif
        </div>
    </div>
                
        <div class="card mt-2">
            <div class="card-header  bg-secondary text-white">Fußzeile</div>
            <div class="card-header ">
                    <div class="btn-group float-right" role="group">
                        <button class="btn btn-primary" type="button" data-toggle="collapse">
                            Platzhalter
                        </button>
                        <button class="btn btn-primary" onclick="preview_footer()">
                            Vorschau
                        </button>
                    </div>
                </div>
                <x-placeholder_tickets :model="$model"/>
            <div class="card-body">
                <table style="width:100%" border=0>
                @if(!$model->flag_signed)
                <tr>
                    <td><a href="#" id="footer" data-mode="inline" data-type="textarea" data-showbuttons="bottom" data-inputclass="textarea">{!!$model->footer!!}</a></td>
                </tr>
                @else
                <tr>
                    <td>@foreach(explode("\n", $model->footer) as $line){{ $line }}<br>@endforeach</td>
                </tr>
                @endif
                </table>
            </div>
        </div> 
           
        <div class="card mt-2">
                <div class="card-header bg-secondary text-white">Aktionen</div>
                <div class="card-body text-right">
                    
                    @if($model->_offer_at_hwplus_tickets->first())
                    <button type="button" class="btn btn-{{$cs}}"><a href="../../0ff1bb77a9de65eac6621c9c5a983da7a37ed3bf/afe4f16263308b092d15e04719f202efe1326813/{{$model->_offer_at_hwplus_tickets->first()->getKey()}}" class="mdi mdi-draw text-white">{{$model->_offer_at_hwplus_tickets->first()->descriptor}} anzeigen</i></button>
                    @elseif($model->_invoice)
                    <button type="button" class="btn btn-{{$cs}}"><a href="../../2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->_invoice->getKey()}}" class="mdi mdi-draw text-white">{{$model->_invoice->descriptor}} anzeigen</a></button>
                    @elseif($model->mailed_confirmation OR $model->printed_confirmation)
                    <button type="button" class="btn btn-{{$cs}} to_invoice"><i class="mdi mdi-draw"></i>Rechnung erstellen</button>
                        @if($model->_manhours->count())
                        <button type="button" class="btn btn-{{$cs}} offer2ticket"><i class="mdi mdi-draw"></i>Auftrag erstellen</button>
                        @elseif($model->_material->count() AND !$model->_manhours->count())
                        <button type="button" class="btn btn-{{$cs}} offer2ticket"><i class="mdi mdi-draw"></i>In Lieferschein umwandeln</button>
                        @endif
                    @elseif($model->date_accept_order AND !$model->mailed_confirmation AND !$model->printed_confirmation)
                    <button type="button" class="btn btn-{{$cs}} confirmation_mail"><i class="mdi mdi-draw"></i>Auftragsbestätigung mailen</button>
                    <button type="button" class="btn btn-{{$cs}} confirmation_print"><i class="mdi mdi-draw"></i> Auftragsbestätigung drucken</button>
                    @elseif($model->flag_signed AND !$model->mailed AND !$model->printed)
                    <button type="button" class="btn btn-{{$cs}} pdf_print"><i class="mdi mdi-printer"></i>{{$model->descriptor}} @if($model->printed) erneut @endif drucken</button>
                    <button type="button" class="btn btn-{{$cs}} send_email"><i class="mdi mdi-mail"></i>{{$model->descriptor}} @if($model->mailed) erneut @endif per Email senden</button>
                    @elseif($model->flag_signed)
                    <button type="button" class="btn btn-{{$cs}} confirmation_accept"><i class="mdi mdi-draw"></i>Auftrag annehmen</button>
                    @elseif(!$model->flag_signed)
                    <button type="button" class="btn btn-{{$cs}} close_ticket"><i class="mdi mdi-draw"></i>Angebot abschließen</button>                   
                    @endif
            </div>
            </div>
           
            
        </div>
        
        
        
    </div>   

    
    </body>
</html>
